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 really bad programmer can create a slower and sluggish application using C++ too, but I'm not considering that case.
One of my favorite Windows utility application is [Launchy](http://launchy.net/). And in the Readme.pdf file, the author of the program wrote this:
> 0.6 This is the first C++ release. As I became frustrated with C#’s large
> .NET framework requirements and users
> lack of desire to install it, I
> decided to switch back to the faster
> language.
I totally agree with the author of Launchy about the .NET framework requirement or even a JRE requirement for desktop applications. Let alone the specific version of them. And some of the best and my favorite desktop applications don't need .NET or Java to run. They just run after installing. Are they mostly built using C++? Is C++ the only option for good and fast GUI based applications?
And, I'm also very interested in hearing the other benefits of learning C++.
|
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 deployment, at the expense of difficulty going up for development. C++ can be very fast, natively compiles, has many modern language features, and wide support. The trade off is that it's likely that you'll need to write more code in certain situations, or seek out libraries like [Boost](http://www.boost.org/) that provide the functionality you're after.
As a programmer, working in C++ and especially in C is good experience for helping you understand something just a tad closer to the machine than say, .NET, Java or a scripting language like VBScript, Python, Perl etc. It won't necessarily make you a better programmer, but if you are open to learning new lessons from it you may find that it helps you gain a new perspective on software. After all, most of the frameworks and systems you depend on are written in pure C, so it will never hurt you to understand the foundations. C++ is a different animal from straight C, but if you develop in C++ for Windows you'll likely find yourself working in a mix of C and C++ to work with Windows APIs, so it will have a trickle-down effect.
|
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 when you have a great platform, the worst part is writing all the class declarations :-)
|
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 decimal is high enough).
|
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" quantities such as money tend to be more appropriate in decimal form. "Natural" quantities (mass, height) are on a more continuous scale, which means that `float`/`double` (which are [floating binary point types](http://pobox.com/~skeet/csharp/floatingpoint.html)) are often (but not always) more appropriate.
|
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 requires a machine reboot.
Any ideas for getting the SmartClient app to recognize the shutdown/restart event from Windows and gracefully kill itself?
**UPDATE:**
This is a highly threaded application with multiple gui threads. yes, multiple gui threads. Its really a consolidation of many project that in and of themselves could be standalone applications - all of which are launched and managed from a single exe that centralizes those management methods and keeps track of those threads. I don't believe using background threads is an option.
|
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 a process from terminating. Once all foreground threads belonging to a process have terminated, the common language runtime ends the process. Any remaining background threads are stopped and do not complete.
>
> <http://msdn.microsoft.com/en-us/library/system.threading.thread.isbackground.aspx>
|
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 function Instance()
{
if ($inst === null) {
$inst = new UserFactory();
}
return $inst;
}
/**
* Private ctor so nobody else can instantiate it
*
*/
private function __construct()
{
}
}
```
To use:
```
$fact = UserFactory::Instance();
$fact2 = UserFactory::Instance();
```
`$fact == $fact2;`
But:
```
$fact = new UserFactory()
```
Throws an error.
See [http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static](http://php.net/manual/en/language.variables.scope.php#language.variables.scope.static "PHP: Variable Scope : Using Static Variables") to understand static variable scopes and why setting `static $inst = null;` works.
|
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 __construct() {}
protected function __clone() {}
public function __wakeup()
{
throw new Exception("Cannot unserialize singleton");
}
public static function getInstance()
{
$cls = get_called_class(); // late-static-bound class name
if (!isset(self::$instances[$cls])) {
self::$instances[$cls] = new static;
}
return self::$instances[$cls];
}
}
```
Test code:
```
class Foo extends Singleton {}
class Bar extends Singleton {}
echo get_class(Foo::getInstance()) . "\n";
echo get_class(Bar::getInstance()) . "\n";
```
|
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 service and exposes it to Python applications as transparently as possible.
IBM provide a [good walk-through and example](http://www.ibm.com/developerworks/library/ws-pyth5/) on their site for getting started with SOAPpy.
SOAPpy's no longer under active development, but is instead being folded into Zolera SOAP Infrastructure (ZSI) at the [Python Web Services Project](http://pywebsvcs.sourceforge.net/). This project however has alos [not seen much activity](http://sourceforge.net/projects/pywebsvcs) since November last year.
|
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 must be 100% alike on each platform.
Mac, Linux, and Windows are the target platforms.
Heavy win32 API, MFC is already used for the Windows version.
The reason I'm not fully for cross platform libraries is because I feel that the end product will suffer a little in trying to generalize it for all platforms.
|
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 GUI code you're worried about then by all means separate out the GUI portion into a per-platform development effort, but you'll regret not keeping the core "business logic" type code common.
And given that keeping your GUI from your logic separate is generally considered a good idea, this would force your developers to maintain that separation when the temptation to put 'just a little bit' of business logic into the presentation layer inevitably arises.
|
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 incompatibilities between the different OS versions without noticing it.
* The maintenance cost will suffer proportionally to the amount of different code you have
So, by taking the risks in consideration, you can develop nice native behaving apps, with the largest common core possible (resisting the temptation of risk 1), a great set of integrated tests for all the platforms (minimizing risk 2) and designing to reduce the amount of code needed to get the native behavior (taking care of risk 3)
|
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=Thu, 01 Jan 1970 00:00:00 GMT";
}
}
```
Note that this code has two limitations:
* It will not delete cookies with `HttpOnly` flag set, as the `HttpOnly` flag disables Javascript's access to the cookie.
* It will not delete cookies that have been set with a `Path` value. (This is despite the fact that those cookies will appear in `document.cookie`, but you can't delete it without specifying the same `Path` value with which it was set.)
|
### 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(";").forEach(function(c) { document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); }); })();
```
|
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 natural way using correct Python indentation of 4 spaces.
For the moment I'm using:
```
if ( cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
```
But this isn't very pretty. :-)
Can you recommend an alternative way?
|
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' and
cond3 == 'val3' and cond4 == 'val4'
):
do_something
if (cond1 == 'val1' and cond2 == 'val2' and
cond3 == 'val3' and cond4 == 'val4'):
do_something
```
Both of those are fairly ugly though.
Maybe lose the brackets (the [Style Guide](https://www.python.org/dev/peps/pep-0008/#multiline-if-statements) discourages this though)?
```
if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and cond4 == 'val4':
do_something
```
This at least gives you some differentiation.
Or even:
```
if cond1 == 'val1' and cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something
```
I think I prefer:
```
if cond1 == 'val1' and \
cond2 == 'val2' and \
cond3 == 'val3' and \
cond4 == 'val4':
do_something
```
Here's the [Style Guide](https://www.python.org/dev/peps/pep-0008/#multiline-if-statements), which (since 2010) recommends using brackets.
|
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 subtlety to the condition.
|
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 can see a bit of how org charts are implemented in their product.
|
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&sort=-stars&colspec=ID%20Type%20Status%20Priority%20Milestone%20Owner%20Summary%20Stars) with it. But overall I was satisfied with it.
|
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 for the app, just some communal advise here and potential pitfalls advise. From the site I have gathered that SQL bulk copy is a prerequisite, is there anything I should think about (I think that just opening the txt file with a forms app will be a large endeavor; maybe break it into blob data?).
Thank you, and I will edit the question for clarity if anyone needs it.
|
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://weblogs.sqlteam.com/mladenp/articles/10631.aspx)
Update: If you are new to SSIS, check out some of these sites to get you on fast track. 1) [SSIS Control Flow Basics](http://www.jumpstarttv.com/ssis-control-flow-basics_201.aspx) 2) [Getting Started with SQL Server Integration Services](http://www.developer.com/db/article.php/3635316)
This is another How to: on [importing Excel file into SQL 2005](http://www.builderau.com.au/program/sqlserver/soa/How-to-import-an-Excel-file-into-SQL-Server-2005-using-Integration-Services/0,339028455,339285948,00.htm).
|
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 a lot of data in SQL Server (C# client)](https://stackoverflow.com/questions/24200/whats-the-fastest-way-to-bulk-insert-a-lot-of-data-in-sql-server-c-client)
[What are the recommended learning material for SSIS?](https://stackoverflow.com/questions/142015/ssis-gurus-links-to-great-learning-content-requested)
You can also create a package from C#. I have a C# program which reads a 3GL "master file" from a legacy system (parses into an object model using an API I have for a related project), takes a package template and modifies it to generate a package for the ETL.
|
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 there is an error, so I put the loop inside a `try...catch` block, like this:
```
try {
for (int i = 0; i < max; i++) {
String myString = ...;
float myNum = Float.parseFloat(myString);
myFloats[i] = myNum;
}
} catch (NumberFormatException ex) {
return null;
}
```
But then I also thought of putting the `try...catch` block inside the loop, like this:
```
for (int i = 0; i < max; i++) {
String myString = ...;
try {
float myNum = Float.parseFloat(myString);
} catch (NumberFormatException ex) {
return null;
}
myFloats[i] = myNum;
}
```
Is there any reason, performance or otherwise, to prefer one over the other?
---
**Edit:** The consensus seems to be that it is cleaner to put the loop inside the try/catch, possibly inside its own method. However, there is still debate on which is faster. Can someone test this and come back with a unified answer?
|
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;
private static int ITERATIONS = 1000000;
// time counters
private static long inTime = 0L;
private static long aroundTime = 0L;
public static void main(String[] args) {
for (int i = 0; i < NUM_TESTS; i++) {
test();
ITERATIONS += 1; // so the tests don't always return the same number
}
System.out.println("Inside loop: " + (inTime/1000000.0) + " ms.");
System.out.println("Around loop: " + (aroundTime/1000000.0) + " ms.");
}
public static void test() {
aroundTime += testAround();
inTime += testIn();
}
public static long testIn() {
long start = System.nanoTime();
Integer i = tryInLoop();
long ret = System.nanoTime() - start;
System.out.println(i); // don't optimize it away
return ret;
}
public static long testAround() {
long start = System.nanoTime();
Integer i = tryAroundLoop();
long ret = System.nanoTime() - start;
System.out.println(i); // don't optimize it away
return ret;
}
public static Integer tryInLoop() {
int count = 0;
for (int i = 0; i < ITERATIONS; i++) {
try {
count = Integer.parseInt(Integer.toString(count)) + 1;
} catch (NumberFormatException ex) {
return null;
}
}
return count;
}
public static Integer tryAroundLoop() {
int count = 0;
try {
for (int i = 0; i < ITERATIONS; i++) {
count = Integer.parseInt(Integer.toString(count)) + 1;
}
return count;
} catch (NumberFormatException ex) {
return null;
}
}
}
```
I checked the resulting bytecode using javap to make sure that nothing got inlined.
The results showed that, assuming insignificant JIT optimizations, **Jeffrey is correct**; there is absolutely **no performance difference on Java 6, Sun client VM** (I did not have access to other versions). The total time difference is on the order of a few milliseconds over the entire test.
Therefore, the only consideration is what looks cleanest. I find that the second way is ugly, so I will stick to either the first way or [Ray Hayes's way](https://stackoverflow.com/questions/141560/should-trycatch-go-inside-or-outside-a-loop#141589).
|
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 throw occurs, then the location of the error is compared against the table.
Here's a reference: <http://www.javaworld.com/javaworld/jw-01-1997/jw-01-hood.html>
The table is described about half-way down.
|
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 spirit of things:
```
-- Get list of columns in table
SELECT INTO #t
EXEC sp_columns @table_name = N'TargetTable'
-- Create a comma-delimited string excluding the identity column
DECLARE @cols varchar(MAX)
SELECT @cols = COALESCE(@cols+',' ,'') + COLUMN_NAME FROM #t WHERE COLUMN_NAME <> 'id'
-- Construct dynamic SQL statement
DECLARE @sql varchar(MAX)
SET @sql = 'INSERT INTO TargetTable (' + @cols + ') ' +
'SELECT ' + @cols + ' FROM TargetTable WHERE SomeCondition'
PRINT @sql -- for debugging
EXEC(@sql)
```
|
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 to cause. Also, explicitly naming columns is usually a good idea. If you're linking to outside code, it makes sure that you don't break that link when you add a new column. If you're not (and it sounds like you probably aren't in this scenario) I still prefer to have the columns listed out because it forces me to review the effects of the change/new column - even if it's just to look at the code and decide that adding the new column is not a problem.
|
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 imagine that such a large number of people would care about it.
What am I missing? What is the problem with reduce()?
|
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 argument, I need to grab pen and paper to diagram what's actually being fed into that function before I understand what the reduce() is supposed to do. So in my mind, the applicability of reduce() is pretty much limited to associative operators, and in all other cases it's better to write out the accumulation loop explicitly.
There is an excellent example of a confusing `reduce` in the [Functional Programming HOWTO](http://www.amk.ca/python/writing/functional) article:
> Quick, what's the following code doing?
>
> ```
> total = reduce(lambda a, b: (0, a[1] + b[1]), items)[1]
> ```
>
> You can figure it out, but it takes time to disentangle the expression to figure out
> what's going on. Using a short nested def statements makes things a little bit better:
>
> ```
> def combine (a, b):
> return 0, a[1] + b[1]
>
> total = reduce(combine, items)[1]
> ```
>
> But it would be best of all if I had simply used a for loop:
>
> ```
> total = 0
> for a, b in items:
> total += b
> ```
>
> Or the sum() built-in and a generator expression:
>
> ```
> total = sum(b for a,b in items)
> ```
>
> Many uses of reduce() are clearer when written as for loops.
|
`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/OverridingCriteraForIncludingDlls). However, the latter is just placed in the `dist` dir by py2exe and not into the executable, even if I specifically ask to include it.
Any idea how to cause py2exe to include both inside the .exe ?
|
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 of msvcr71.dll installed (IIRC Vista or XP SP2 users), then you could get away without including it. More usefully, perhaps, if you use Python 2.3 (or older), then Python links against msvcr.dll rather than msvcr71.dll, and any Windows user will have that installed, so you can just not worry about it.
|
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
<open file 'c:\scr.txt', mode 'w' at 0x019F88D8>
>>> file2 = open(path, "w")
>>> print file2
<open file 'c:\scr.txt', mode 'w' at 0x02332188>
>>> file1.write("111")
>>> file2.write("222")
>>> file1.close()
```
scr.txt now contains '111'.
```
>>> file2.close()
```
scr.txt was overwritten and now contains '222' (on Windows, Python 2.4).
The solution should work inside the same process (like in the example above) as well as when another process has opened the file.
It is preferred, if a crashing program will not keep the lock open.
|
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 appropriate method at the python cookbook.
To use it, open the file, and then call:
```
portalocker.lock(file, flags)
```
where flags are portalocker.LOCK\_EX for exclusive write access, or LOCK\_SH for shared, read access.
|
> 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 [mandatory locking](http://en.wikipedia.org/wiki/File_locking), and the Linux way to obtain it is a bit more involved:
Remount the partition that contains your file with the *mand* option:
```
# mount -o remount,mand /dev/hdXY
```
Set the *sgid* flag for your file:
```
# chmod g-x,g+s yourfile
```
In your Python code, obtain an exclusive lock on that file:
```
fcntl.flock(fd, fcntl.LOCK_EX)
```
Now even *cat* will not be able to read the file until you release the lock.
|
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 like this:
```
<TextBlock Text="{Binding Converter={StaticResource personNameConverter}" />
```
My converter looks like this:
```
class PersonNameConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
{
Person p = value as Person;
return p.FirstName + " " + p.LastName;
}
public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
```
If I bind the data without a converter it works great:
```
<TextBlock Text="{Binding Path=FirstName}" />
<TextBlock Text="{Binding Path=LastName}" />
```
What am I missing?
EDIT:
Just to clarify a few things, both Joel and Alan are correct regarding the INotifyPropertyChanged interface that needs to be implemented. In reality I do actually implement it but it still doesn't work.
I can't use multiple TextBlock elements because I'm trying to bind the Window Title to the full name, and the Window Title does not take a template.
Finally, it is an option to add a compound property "FullName" and bind to it, but I'm still wondering why updating does not happen when the binding uses a converter. Even when I put a break point in the converter code, the debugger just doesn't get there when an update is done to the underlying data :-(
Thanks,
Uri
|
**(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 `INotifyPropertyChanged`. (**Updated, see Edit 2**)
```
using System.ComponentModel;
class Person : INotifyPropertyChanged {
public event PropertyChangedEventHandler PropertyChanged;
string _firstname;
public string FirstName {
get {
return _firstname;
}
set {
_firstname = value;
onPropertyChanged( "FirstName", "FullName" );
}
}
string _lastname;
public string LastName {
get {
return _lastname;
}
set {
_lastname = value;
onPropertyChanged( "LastName", "FullName" );
}
}
public string FullName {
get {
return _firstname + " " + _lastname;
}
}
void onPropertyChanged( params string[] propertyNames ) {
PropertyChangedEventHandler handler = PropertyChanged;
if ( handler != null ) {
foreach ( var pn in propertyNames ) {
handler( this, new PropertyChangedEventArgs( pn ) );
}
}
}
}
```
**Edit 1**
Actually, since you're after the first name and last name updating, and `Path=FirstName` and such works just fine, I don't think you'll need the converter at all. Multiple `TextBlocks` are just as valid, and can actually work better when you're localizing to a right-to-left language.
**Edit 2**
I've figured it out. It's not being notified that the properties have updated because it is binding to the object itself, not one of those properties. Even when I made `Person` a `DependencyObject` and made `FirstName` and `LastName` `DependencyProperties`, it wouldn't update.
You *will* have to use a `FullName` property, and I've update the code of the `Person` class above to reflect that. Then you can bind the `Title`. (**Note:** I've set the `Person` object as the `Window`'s `DataContext`.)
```
Title="{Binding Path=FullName, Mode=OneWay}"
```
If you're editing the names in a `TextBox` and want the name changed reflected immediately instead of when the `TextBox` loses focus, you can do this:
```
<TextBox Name="FirstNameEdit"
Text="{Binding Path=FirstName, UpdateSourceTrigger=PropertyChanged}" />
```
I know you didn't want to use a `FullName` property, but anything that would accomplish what you want would probably be a bit of a Rube Goldberg device. Such as implementing `INotifyPropertyChanged` and a `Person` property on the `Window` class itself, having the `Window` listen on the `PropertyChanged` event in order to fire the `Window`'s `PropertyChanged` event, and using a relative binding like the following. You'd also have set the `Person` property before `InitializeComponent()` or fire `PropertyChanged` after setting the `Person` property so that it shows up, of course. (Otherwise it will be `null` during `InitializeComponent()` and needs to know when it's a `Person`.)
```
<Window.Resources>
<loc:PersonNameConverter
x:Key="conv" />
</Window.Resources>
<Window.Title>
<Binding
RelativeSource="{RelativeSource Self}"
Converter="{StaticResource conv}"
Path="Person"
Mode="OneWay" />
</Window.Title>
```
|
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 Path="LastName" />
</MultiBinding>
```
Or if you only use the FirstName and LastName, strip the Person object from the binding to something like this:
```
<MultiBinding Converter="{IMultiValueConverter goes here..}">
<Binding Path="FirstName" />
<Binding Path="LastName" />
</MultiBinding>
```
And the MultiValueConverter looks like this:
```
class PersonNameConverter : IMultiValueConverter
{
public object Convert(object[] values, Type targetType, object parameter, CultureInfo culture)
{
return values[0].ToString() + " " + values[1].ToString();
}
public object ConvertBack(object[] values, Type targetType, object parameter, CultureInfo culture)
{
throw new NotImplementedException();
}
}
```
But of course, the selected answer works as well, but a MultiBinding works more elegantly...
|
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;
}
return columnName;
}
```
|
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 While (d > 0)
m = (d - 1) Mod 26
name = Chr(65 + m) + name
d = Int((d - m) / 26)
Loop
GetColumnName = name
End Function
```
|
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 the XAML with a stream reader, like this:
```
Button x = (Button)XamlReader.Load(stream);
```
And trying to run the Storyboard with:
```
Storyboard pressedButtonStoryboard =
Storyboard)_xamlButton.Template.Resources["ButtonPressed"];
pressedButtonStoryboard.Begin(_xamlButton);
```
I think that the problem is that fields I am animating are in the template and that storyboard is accessing the button.
Here is the XAML:
```
<Button xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:customControls="clr-namespace:pk_rodoment.SkinningEngine;assembly=pk_rodoment"
Width="150" Height="55">
<Button.Resources>
<Style TargetType="Button">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate TargetType="Button">
<Grid Background="#00FFFFFF">
<Grid.BitmapEffect>
<BitmapEffectGroup>
<OuterGlowBitmapEffect x:Name="buttonGlow" GlowColor="#A0FEDF00" GlowSize="0"/>
</BitmapEffectGroup>
</Grid.BitmapEffect>
<Border x:Name="background" Margin="1,1,1,1" CornerRadius="15">
<Border.Background>
<SolidColorBrush Color="#FF0062B6"/>
</Border.Background>
</Border>
<ContentPresenter HorizontalAlignment="Center"
Margin="{TemplateBinding Control.Padding}"
VerticalAlignment="Center"
Content="{TemplateBinding ContentControl.Content}"
ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}"/>
</Grid>
<ControlTemplate.Resources>
<Storyboard x:Key="ButtonPressed">
<Storyboard.Children>
<DoubleAnimation Duration="0:0:0.4"
FillBehavior="HoldEnd"
Storyboard.TargetName="buttonGlow"
Storyboard.TargetProperty="GlowSize" To="4"/>
<ColorAnimation Duration="0:0:0.6"
FillBehavior="HoldEnd"
Storyboard.TargetName="background"
Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"
To="#FF844800"/>
</Storyboard.Children>
</Storyboard>
<Storyboard x:Key="ButtonReleased">
<Storyboard.Children>
<DoubleAnimation Duration="0:0:0.2"
FillBehavior="HoldEnd"
Storyboard.TargetName="buttonGlow"
Storyboard.TargetProperty="GlowSize" To="0"/>
<ColorAnimation Duration="0:0:0.2"
FillBehavior="Stop"
Storyboard.TargetName="background"
Storyboard.TargetProperty="(Panel.Background).(SolidColorBrush.Color)"
To="#FF0062B6"/>
</Storyboard.Children>
</Storyboard>
</ControlTemplate.Resources>
<ControlTemplate.Triggers>
<Trigger Property="ButtonBase.IsPressed" Value="True">
<Trigger.EnterActions>
<BeginStoryboard Storyboard="{StaticResource ButtonPressed}"/>
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard Storyboard="{StaticResource ButtonReleased}"/>
</Trigger.ExitActions>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Resources>
<DockPanel>
<TextBlock x:Name="TextContent" FontSize="28" Foreground="White" >Test</TextBlock>
</DockPanel>
</Button>
```
Any suggestions from anyone who understands WPF and XAML a lot better than me?
Here is the error stacktrace:
```
at System.Windows.Media.Animation.Storyboard.ResolveTargetName(String targetName, INameScope nameScope, DependencyObject element)
at System.Windows.Media.Animation.Storyboard.ClockTreeWalkRecursive(Clock currentClock, DependencyObject containingObject, INameScope nameScope, DependencyObject parentObject, String parentObjectName, PropertyPath parentPropertyPath, HandoffBehavior handoffBehavior, HybridDictionary clockMappings, Int64 layer)
at System.Windows.Media.Animation.Storyboard.ClockTreeWalkRecursive(Clock currentClock, DependencyObject containingObject, INameScope nameScope, DependencyObject parentObject, String parentObjectName, PropertyPath parentPropertyPath, HandoffBehavior handoffBehavior, HybridDictionary clockMappings, Int64 layer)
at System.Windows.Media.Animation.Storyboard.BeginCommon(DependencyObject containingObject, INameScope nameScope, HandoffBehavior handoffBehavior, Boolean isControllable, Int64 layer)
at System.Windows.Media.Animation.Storyboard.Begin(FrameworkElement containingObject)
at pk_rodoment.SkinningEngine.ButtonControlWPF._button_MouseDown(Object sender, MouseButtonEventArgs e)
at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)
at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)
at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)
at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)
at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)
at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)
at System.Windows.Input.InputManager.ProcessStagingArea()
at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)
at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)
at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)
at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)
at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.WrappedInvoke(Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
at System.Windows.Threading.Dispatcher.InvokeImpl(DispatcherPriority priority, TimeSpan timeout, Delegate method, Object args, Boolean isSingleParameter)
at System.Windows.Threading.Dispatcher.Invoke(DispatcherPriority priority, Delegate method, Object arg)
at MS.Win32.HwndSubclass.SubclassWndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam)
at MS.Win32.UnsafeNativeMethods.DispatchMessage(MSG& msg)
at System.Windows.Threading.Dispatcher.PushFrameImpl(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.PushFrame(DispatcherFrame frame)
at System.Windows.Threading.Dispatcher.Run()
at System.Windows.Application.RunDispatcher(Object ignore)
at System.Windows.Application.RunInternal(Window window)
at System.Windows.Application.Run(Window window)
at System.Windows.Application.Run()
at ControlTestbed.App.Main() in C:\svnprojects\rodomont\ControlsTestbed\obj\Debug\App.g.cs:line 0
at System.AppDomain._nExecuteAssembly(Assembly assembly, String[] args)
at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
at System.Threading.ThreadHelper.ThreadStart()
```
|
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 for the `Button`:
(Please note the keys `"buttonGlow"` and `"borderBackground"` and all `StaticResource` markup extensions referencing them.)
```
<Button
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
Width="150"
Height="55">
<Button.Resources>
<OuterGlowBitmapEffect
x:Key="buttonGlow"
GlowColor="#A0FEDF00"
GlowSize="0" />
<SolidColorBrush
x:Key="borderBackground"
Color="#FF0062B6" />
<Style
TargetType="Button">
<Setter
Property="Control.Template">
<Setter.Value>
<ControlTemplate
TargetType="Button">
<Grid
Name="outerGrid"
Background="#00FFFFFF"
BitmapEffect="{StaticResource buttonGlow}">
<Border
x:Name="background"
Margin="1,1,1,1"
CornerRadius="15"
Background="{StaticResource borderBackground}">
</Border>
<ContentPresenter
HorizontalAlignment="Center"
Margin="{TemplateBinding Control.Padding}"
VerticalAlignment="Center"
Content="{TemplateBinding ContentControl.Content}"
ContentTemplate="{TemplateBinding ContentControl.ContentTemplate}" />
</Grid>
<ControlTemplate.Resources>
<Storyboard
x:Key="ButtonPressed">
<Storyboard.Children>
<DoubleAnimation
Duration="0:0:0.4"
FillBehavior="HoldEnd"
Storyboard.Target="{StaticResource buttonGlow}"
Storyboard.TargetProperty="GlowSize"
To="4" />
<ColorAnimation
Duration="0:0:0.6"
FillBehavior="HoldEnd"
Storyboard.Target="{StaticResource borderBackground}"
Storyboard.TargetProperty="Color"
To="#FF844800" />
</Storyboard.Children>
</Storyboard>
<Storyboard
x:Key="ButtonReleased">
<Storyboard.Children>
<DoubleAnimation
Duration="0:0:0.2"
FillBehavior="HoldEnd"
Storyboard.Target="{StaticResource buttonGlow}"
Storyboard.TargetProperty="GlowSize"
To="0" />
<ColorAnimation
Duration="0:0:0.2"
FillBehavior="Stop"
Storyboard.Target="{StaticResource borderBackground}"
Storyboard.TargetProperty="Color"
To="#FF0062B6" />
</Storyboard.Children>
</Storyboard>
</ControlTemplate.Resources>
<ControlTemplate.Triggers>
<Trigger
Property="ButtonBase.IsPressed"
Value="True">
<Trigger.EnterActions>
<BeginStoryboard
Storyboard="{StaticResource ButtonPressed}" />
</Trigger.EnterActions>
<Trigger.ExitActions>
<BeginStoryboard
Storyboard="{StaticResource ButtonReleased}" />
</Trigger.ExitActions>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Button.Resources>
<DockPanel>
<TextBlock
x:Name="TextContent"
FontSize="28"
Foreground="White">Test</TextBlock>
</DockPanel>
</Button>
```
|
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")] = child.attr("checked");
if (child.is(":radio, checked"))
this[child.attr("name")] = child.val();
if (child.is(":text"))
this[child.attr("name")] = child.val();
return null;
});
```
Neither does the following (inspired by jobscry's answer):
```
function config() {
$("#frmMain").children().each(function() {
var child = $("this");
alert(child.length);
if (child.is(":checkbox")) {
this[child.attr("name")] = child.attr("checked");
}
if (child.is(":radio, checked"))
this[child.attr("name")] = child.val();
if (child.is(":text"))
this[child.attr("name")] = child.val();
});
}
```
The alert always shows that `child.length == 0`. Manually selecting the elements works:
```
>>> $("#frmMain").children()
Object length=42
>>> $("#frmMain").children().filter(":checkbox")
Object length=3
```
Any hints on how to do the loop correctly?
|
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 the sql query & execute it
}
```
So you can do things like `ModelBase.findAll(Albums.class)` to get a list of all persisted albums.
My problem is that in this static context, I need to get the appropriate sql string from the concrete class Album. I can't have a static method like
```
public class Album extends ModelBase {
public static String getSelectSQL() { return "select * from albums.....";}
}
```
because there is no polymorphism for static methods in Java. But I don't want to make `getSelectSQL()` an instance method in `Album` because then I need to create an instance of it just to get a string that is really static in behavior.
At the moment, `findAll()` uses reflection to get the appropriate sql for the class in question:
```
select_sql = (String)cast_to_class.getDeclaredMethod("getSelectSql", new Class[]{} ).invoke(null, null);
```
But that's pretty gross.
So any ideas? It's a general problem I'm having time and time again - the inability to specify abstract static methods in classes or interfaces. I know *why* static method polymorphism doesn't and can't work, but that doesn't stop me from wanting to use it time again!
Is there any pattern/construct that allows me to ensure that concrete subclasses X and Y implement a class method(or failing that, a class constant!)?
|
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 string that is really static in behaviour"
It is not completely correct. If you look well, you are not changing the behavior of your base class, just changing the parameter for a method. In other words you're changing the data, not the algorithm.
Inheritance is more useful when a new subclass wants to change the way a method works, if you just need to change the "data" the class uses to work probably an approach like this would do the trick.
```
class ModelBase {
// Initialize the queries
private static Map<String,String> selectMap = new HashMap<String,String>(); static {
selectMap.put( "Album", "select field_1, field_2 from album");
selectMap.put( "Artist", "select field_1, field_2 from artist");
selectMap.put( "Track", "select field_1, field_2 from track");
}
// Finds all the objects for the specified class...
// Note: it is better to use "List" rather than "ArrayList" I'll explain this later.
public static List findAll(Class classToFind ) {
String sql = getSelectSQL( classToFind );
results = execute( sql );
//etc...
return ....
}
// Return the correct select sql..
private static String getSelectSQL( Class classToFind ){
String statement = tableMap.get( classToFind.getSimpleName() );
if( statement == null ) {
throw new IllegalArgumentException("Class " +
classToFind.getSimpleName + " is not mapped");
}
return statement;
}
}
```
That is, map all the statements with a Map. The "obvious" next step to this is to load the map from an external resource, such as a properties file, or a xml or even ( why not ) a database table, for extra flexibility.
This way you can keep your class clients ( and your self ) happy, because you don't needed "creating an instance" to do the work.
```
// Client usage:
...
List albums = ModelBase.findAll( Album.class );
```
...
Another approach is to create the instances from behind, and keep your client interface intact while using instance methods, the methods are marked as "protected" to avoid having external invocation. In a similar fashion of the previous sample you can also do this
```
// Second option, instance used under the hood.
class ModelBase {
// Initialize the queries
private static Map<String,ModelBase> daoMap = new HashMap<String,ModelBase>(); static {
selectMap.put( "Album", new AlbumModel() );
selectMap.put( "Artist", new ArtistModel());
selectMap.put( "Track", new TrackModel());
}
// Finds all the objects for the specified class...
// Note: it is better to use "List" rather than "ArrayList" I'll explain this later.
public static List findAll(Class classToFind ) {
String sql = getSelectSQL( classToFind );
results = execute( sql );
//etc...
return ....
}
// Return the correct select sql..
private static String getSelectSQL( Class classToFind ){
ModelBase dao = tableMap.get( classToFind.getSimpleName() );
if( statement == null ) {
throw new IllegalArgumentException("Class " +
classToFind.getSimpleName + " is not mapped");
}
return dao.selectSql();
}
// Instance class to be overrided...
// this is "protected" ...
protected abstract String selectSql();
}
class AlbumModel extends ModelBase {
public String selectSql(){
return "select ... from album";
}
}
class ArtistModel extends ModelBase {
public String selectSql(){
return "select ... from artist";
}
}
class TrackModel extends ModelBase {
public String selectSql(){
return "select ... from track";
}
}
```
And you don't need to change the client code, and still have the power of polymorphism.
```
// Client usage:
...
List albums = ModelBase.findAll( Album.class ); // Does not know , behind the scenes you use instances.
```
...
I hope this helps.
A final note on using List vs. ArrayList. It is always better to program to the interface than to the implementation, this way you make your code more flexible. You can use another List implementation that is faster, or does something else, without changing your client code.
|
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 theoretical but it has actual consequences, as we'll see.
Each table is of a different class, and that's OK. Since you can only ever have one of each table, limit the number of instances of each class to one (use a flag - don't make it a Singleton). Make the program create an instance of the class before it accesses the table.
Now you have a couple of advantages. You can use the full power of inheritance and overriding since your methods are no longer static. You can use the constructor to do any initialisation, including associating SQL with the table (SQL that your methods can use later). This should make all your problems above go away, or at least get much simpler.
It seems like there is extra work in having to create the object, and extra memory, but it's really trivial compared with the advantages. A few bytes of memory for the object won't be noticed, and a handful of constructor calls will take maybe ten minutes to add. Against that is the advantage that code to initialise any tables doesn't need to be run if the table isn't used (the constructor shouldn't be called). You will find it simplifies things a lot.
|
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, the problem came to fruition when I forgot to check one of the fields for equality. Therefore, my equals method was incorrect. Then I thought to use reflection:
```
--code removed because it was too distracting--
```
The purpose of this post isn't necessarily to refactor the code (this isn't even the code I am using), but instead to get input on whether or not this is a good idea.
**Pros:**
* If a new field is added, it is automatically included
* The method is much more terse than 30 if statements
**Cons:**
* If a new field is added, it is automatically included, sometimes this is undesirable
* Performance: This has to be slower, I don't feel the need to break out a profiler
* Whitelisting certain fields to ignore in the comparison is a little ugly
Any thoughts?
|
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.P.S. I trust you already considered [HashCodeBuilder](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/HashCodeBuilder.html) and [EqualsBuilder](https://commons.apache.org/proper/commons-lang/apidocs/org/apache/commons/lang3/builder/EqualsBuilder.html).
|
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 javascript or make sure your server side code won't run twice.
|
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 method thinks I am not setting a valid parameter or not specifying a parameter.
e.g.
```
Dim dc As New SqlCommand("UPDATE Activities SET [Limit] = @Limit WHERE [Activity] = @Activity", cn)
If actLimit.ToLower() = "unlimited" Then
' It's not nulling :(
dc.Parameters.Add(New SqlParameter("Limit", Nothing))
Else
dc.Parameters.Add(New SqlParameter("Limit", ProtectAgainstXSS(actLimit)))
End If
```
Is there something I'm missing? Am I doing it wrong?
|
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,
string parameterName, T? nullable) where T : struct
{
if (nullable.HasValue)
return parms.AddWithValue(parameterName, nullable.Value);
else
return parms.AddWithValue(parameterName, DBNull.Value);
}
}
```
Usage:
```
string? optionalName = "Bozo";
cmd.Parameters.AddWithNullable("@Name", optionalName);
```
|
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 concurrency, scalability and reliability.
Does anybody have any ideas, in what direction to dig?
* Open Source Projects (don’t care about the language or platform, as long as it is not Ook)
* books
* articles
* Google keywords
* forums or newsgroups
Any help would greatly appreciated!
**Update:**
* simple paging (i.e.: rownumber in
SQL 2005) does not work, since there
are a lot of **concurrent** changes
to the database. Item, that is deleted or inserted between the page requests, automatically makes current page index invalid.
|
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-net.ashx)
* [Exception Handling Action Policies](http://rabdullin.com/journal/2008/12/1/net-exception-handling-action-policies-application-block.html)
|
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 (!strValue) {
// strValue was empty string, false, 0, null, undefined, ...
}
```
---
### Empty string (only!)
To check for exactly an empty string, compare for strict equality against `""` using the [`===` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_equality):
```
if (strValue === "") {
// strValue was empty string
}
```
To check for not an empty string strictly, use the [`!==` operator](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Strict_inequality):
```
if (strValue !== "") {
// strValue was not an empty string
}
```
|
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 `length` attribute, arrays have them as well, for example.)
Alternativaly, you can use the (not so) newly optional chaining and arrow functions to simplify:
```
const isEmpty = (str) => (!str?.length);
```
It will check the length, returning `undefined` in case of a nullish value, without throwing an error. In the case of an empty value, zero is falsy and the result is still valid.
For checking if a variable is falsey or if the string only contains whitespace or is empty, I use:
```
function isBlank(str) {
return (!str || /^\s*$/.test(str));
}
```
If you want, you can [monkey-patch](https://www.audero.it/blog/2016/12/05/monkey-patching-javascript/) the `String` prototype like this:
```
String.prototype.isEmpty = function() {
// This doesn't work the same way as the isEmpty function used
// in the first example, it will return true for strings containing only whitespace
return (this.length === 0 || !this.trim());
};
console.log("example".isEmpty());
```
Note that monkey-patching built-in types are controversial, as it can break code that depends on the existing structure of built-in types, for whatever reason.
|
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 tolerable as 'foo' as that is exactly what is being done on license expiry.
System: Fedora Distribution of Linux
Note: The commands which start JVM and program foo are placed in /etc/init.d and anyone who has a decent knowledge of rc.1/rc.2/rc.3 structure can change/add the starting parameters to these.
I hope my question is clear. If not, I can always edit it.
|
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/search?q=java+rmi "Remote Method Invocation").
|
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:transport=dt_socket,server=y,suspend=n,address=8888 your.app.Main
```
and connect the debugger with something like:
```
jdb -attach 127.0.0.1:8888
```
you can type:
```
threads
```
to get a list of the running threads, and use the kill command to kill a running thread. The bit I'm currently not sure about is the syntax of this kill command, I have tried the obvious:
```
kill 0xe2e new java.lang.IllegalArgumentException("er");
```
and I get the messages:
```
killing thread: Swank REPL Thread
Thread not suspended
Expression must evaluate to an object
```
("Swank REPL Thread" is the thread I want to kill, and yes, I've tried suspending it first ;)
Still my inability to use the java debugger aside, it looks to me like a thread can be killed at random. Maybe you can just make sure you ignore all exceptions and keep running and that will be enough, but I'm not sure about that.
|
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 is probably what the user wants. Why make them waste time and energy resizing my window to match all the others they have? I am primarily a Windows devoloper but it wouldn't upset me in the least if there was a cross platform way to do this.
|
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.'''
if not win32gui.IsWindowVisible(hWnd):
return False
if win32gui.GetParent(hWnd) != 0:
return False
hasNoOwner = win32gui.GetWindow(hWnd, win32con.GW_OWNER) == 0
lExStyle = win32gui.GetWindowLong(hWnd, win32con.GWL_EXSTYLE)
if (((lExStyle & win32con.WS_EX_TOOLWINDOW) == 0 and hasNoOwner)
or ((lExStyle & win32con.WS_EX_APPWINDOW != 0) and not hasNoOwner)):
if win32gui.GetWindowText(hWnd):
return True
return False
def getWindowSizes():
'''
Return a list of tuples (handler, (width, height)) for each real window.
'''
def callback(hWnd, windows):
if not isRealWindow(hWnd):
return
rect = win32gui.GetWindowRect(hWnd)
windows.append((hWnd, (rect[2] - rect[0], rect[3] - rect[1])))
windows = []
win32gui.EnumWindows(callback, windows)
return windows
for win in getWindowSizes():
print win
```
You need the [Win32 Extensions for Python module](http://python.net/crew/mhammond/win32/Downloads.html) for this to work.
EDIT: I discovered that `GetWindowRect` gives more correct results than `GetClientRect`. Source has been updated.
|
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 = oAutoItX.WinGetClientSizeWidth("Firefox")
height = oAutoItX.WinGetClientSizeHeight("Firefox")
print width, height
```
|
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, comments, etc. Extra features are a bonus.
I would also like it to be either open source or have an extendable framework for customization of not only the look, but the functionality; preferably written in C# if it's open source, as that is my language of choice.
Good performance, etc., the usual stuff when looking for applications.
Even if it's a [CMS](http://en.wikipedia.org/wiki/Content_management_system) with a blog in it, that would be beneficial to point out as well.
Please give the name, a link, and some of the the things you find good about it. Even if someone has posted what you were going to post, but you have other things you like about it, please add those things anyway.
---
I have garnered from the responses to check out [BlogEngine.Net](http://www.dotnetblogengine.net/), [subtext](http://subtextproject.com/), [dasBlog](http://www.dasblog.info/), and to stay away from the blog in [DotNetNuke](http://en.wikipedia.org/wiki/DotNetNuke). I will start with BlogEngine.
|
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 stay well away from the [DotNetNuke](http://en.wikipedia.org/wiki/DotNetNuke) blogging engine. It's low on features, difficult to configure and not very intuitive to use.
|
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 selected category is Processors, it will return products that is in Intel, Pentium, Core 2 Duo, Amd, etc...
I thought about creating some sort of "cache" that will store all the categories in the hierarchy for every category in the db and include the "IN" in the where clause. Is this the best solution?
|
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 different methods of storing a hierarchy in a database table.
# Executive Summary:
## Nested Sets
* Selects are easy for any depth
* Inserts and deletes are hard
## Standard parent\_id based hierarchy
* Selects are based on inner joins (so get hairy fast)
* Inserts and deletes are easy
So based on your example, if your hierarchy table was a nested set your query would look something like this:
```
SELECT * FROM products
INNER JOIN categories ON categories.id = products.category_id
WHERE categories.lft > 2 and categories.rgt < 11
```
the 2 and 11 are the left and right respectively of the `Processors` record.
|
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 catCTE
```
That should select the category whose name is 'Processors' and any of it's descendents, should be able to use that in an IN clause to pull back the products.
|
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 change between the inserts because another user could generate a new index in table A
I have had this problem with various DBMS postgreSQL, Informix, MySQL and MSSQL (thanks to lomaxx for the answer)
|
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 / PRIMARY KEY will create implicit index "foo_pkey" for table "foo"
CREATE TABLE
postgres=# create table bar(id int references foo, text varchar);
CREATE TABLE
postgres=# select nextval('foo_id_seq');
nextval
---------
1
(1 row)
postgres=# insert into foo values (1,'a'); insert into bar values(1,'b');
INSERT 0 1
INSERT 0 1
```
For [MySQL](http://dev.mysql.com/doc/refman/5.0/en/getting-unique-id.html), the transaction is important not to trip on your own feet in case you're using the same connection for more than one insert.
> For LAST\_INSERT\_ID(), the most
> recently generated ID is maintained in
> the server on a per-connection basis.
> It is not changed by another client.
> It is not even changed if you update
> another AUTO\_INCREMENT column with a
> non-magic value (that is, a value that
> is not NULL and not 0). Using
> LAST\_INSERT\_ID() and AUTO\_INCREMENT
> columns simultaneously from multiple
> clients is perfectly valid. Each
> client will receive the last inserted
> ID for the last statement that client
> executed.
```
mysql> create table foo(id int primary key auto_increment, text varchar(10)) Engine=InnoDB;
Query OK, 0 rows affected (0.06 sec)
mysql> create table bar(id int references foo, text varchar(10)) Engine=InnoDB;
Query OK, 0 rows affected (0.01 sec)
mysql> begin;
Query OK, 0 rows affected (0.00 sec)
mysql> insert into foo(text) values ('x');
Query OK, 1 row affected (0.00 sec)
mysql> insert into bar values (last_insert_id(),'y');
Query OK, 1 row affected (0.00 sec)
mysql> commit;
Query OK, 0 rows affected (0.04 sec)
```
|
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 unexpected exception occurs.
|
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, how am I supposed to know that it's wrong?
In what scenario is it assumed that I know better than my compiler on this issue?
|
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 typical set of use cases will do this. Personally, I gather this information by enabling profiling on my automated regression tests. In addition to forcing inlines, I have unrolled loops and carried out other manual optimizations on the basis of such data, to good effect. It is also imperative to profile again afterwards, as sometimes your best efforts can actually lead to decreased performance. Again, automation makes this a lot less painful.
More often than not though, in my experience, tweaking alogorithms gives much better results than straight code optimization.
|
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 comments: You can also do it this way:
```
var lastFoo = Enum.GetValues(typeof(Foo)).Cast<Foo>().Max();
```
... which will work when some of your enum values are negative.
|
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 code to exit the function and not execute the remaining code.
|
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.exit("aa! errors!")
```
Prints "aa! errors!" and exits with a status code of 1.
There is also an \_exit() function in the os module. The [sys.exit()](http://docs.python.org/2/library/sys.html#sys.exit) function raises a SystemExit exception to exit the program, so try statements and cleanup code can execute. The os.\_exit() version doesn't do this. It just ends the program without doing any cleanup or flushing output buffers, so it shouldn't normally be used.
The [Python docs](http://docs.python.org/2/library/os.html#os._exit) indicate that os.\_exit() is the normal way to end a child process created with a call to os.fork(), so it does have a use in certain circumstances.
|
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:
```
self.browser = mechanize.Browser()
self.browser.addheaders = [('User-agent', browser_header)]
self.browser.open(query_url)
self.result_page = self.browser.response().read()
```
How can I know what errors / exceptions can be thrown here and handle them ?
|
```
$ 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',
```
Or:
```
>>> import mechanize
>>> filter(lambda s: "Error" in s, dir(mechanize))
['BrowserStateError', 'ContentTooShortError', 'FormNotFoundError', 'GopherError'
, 'HTTPDefaultErrorHandler', 'HTTPError', 'HTTPErrorProcessor', 'LinkNotFoundErr
or', 'LoadError', 'ParseError', 'RobotExclusionError', 'URLError']
```
|
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 through catching this exception, eg:
```
import urllib2
try:
... br.open("http://www.example.org/invalid-page")
... except urllib2.HTTPError, e:
... print e.code
...
404
```
|
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.
EDIT: Thanks everyone, I think this is turning into a great quick reference. The more descriptive the more effective it would be, so please if you see your way open - please edit and add some descriptions of what one could find. Many thanks to those that have already done so!
|
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 [comprehensive index](http://wiki.lessthandot.com/index.php/SQL_Server_Programming_Hacks_-_100%2B_List).
Also available from the same site: [SQL Server Admin Hacks](http://wiki.lessthandot.com/index.php/SQL_Server_Admin_Hacks).
|
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
Optimization](http://blog.ola.hallengren.com/blog/_archives/2008/1/1/3440068.html)
* [SQLServerCentral Scripts](http://www.sqlservercentral.com/Scripts/) - Scripts for most most DBA tasks and more
* [Script Repository: SQL Server 2005](http://www.microsoft.com/technet/scriptcenter/scripts/sql/sql2005/default.mspx?mfr=true) - TechNet Script Center
* [Scripts and Tools for Performance Tuning and Troubleshooting SQL Server 2005](http://sqlcat.com/toolbox/archive/2008/02/21/scripts-and-tools-for-performance-tuning-and-troubleshooting-sql-server-2005.aspx)
* [SQL Server Query Processing Team](http://blogs.msdn.com/sqlqueryprocessing/default.aspx) - Hardcore advice from the MS SQL optimisation team
* [Common Solutions for T-SQL Problems](http://code.msdn.microsoft.com/SQLExamples)
* [Davide Mauri's Index Scripts](http://www.davidemauri.it/SqlScripts.aspx)
|
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.addTestSuite(MyTestCase.class);
```
I would like to be able to pass a parameter (a string) to the MyTestCase instance which is created when the test runs. As it is now, I have to have a separate class for each parameter value.
I tried passing it an anynomous subclass:
```
MyTestCase testCase = new MyTestCase() {
String getOption() {
return "some value";
}
}
suite.addTestSuite(testCase.getClass());
```
However, this fails with the assertion:
```
... MyTestSuite$1 has no public constructor TestCase(String name) or TestCase()`
```
Any ideas? Am I attacking the problem the wrong way?
|
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 void testSomething() {
API myAPI = new BlahAPI();
assertNotNull(myAPI.something());
}
```
just add an abstract method to the TestCase that returns the specific API object to use.
```
public abstract class AbstractTestCase extends TestCase {
public abstract API getAPIToTest();
public void testSomething() {
API myAPI = getAPIToTest();
assertNotNull(myAPI.something());
}
public void testSomethingElse() {
API myAPI = getAPIToTest();
assertNotNull(myAPI.somethingElse());
}
}
```
Then the TestCase for the new implementation you want to test only has to implement your AbstractTestCase and supply the concrete implementation of the API class:
```
public class ImplementationXTestCase extends AbstractTestCase{
public API getAPIToTest() {
return new ImplementationX();
}
}
```
Then all of the test methods that test the API in the abstract class are run automatically.
|
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:
1) Boost.Regex (I need to go read the Boost Software License, but this question is not about software licenses)
2) C (not C++) POSIX regex (#include <regex.h>, regcomp, regexec, etc.)
3) <http://freshmeat.net/projects/cpp_regex/> (I know nothing about this one; seems to be GPL, therefore not usable on this project)
|
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 proved to be the easiest.
|
[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 (regexes compiled at compile time).
**Update:** If you're using a C++11 compliant compiler (gcc 4.8 is NOT!), use [std::regex](http://en.cppreference.com/w/cpp/regex) unless you have good reason to use something else.
|
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 after all kids are collected.
What is the best way to work it out? Thanks.
|
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`, and cull the returned values from the list of children, instead of waiting on each one in turn (as here). If you set up an `alarm` with a `SIGALRM` handler, you can terminate the waiting after a specified delay. This is all standard UNIX stuff, not Python-specific...
|
*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
def doTheJob(job):
for i in xrange(10):
print job, i
time.sleep(0.01*ord(os.urandom(1)))
# random.random() would be the same for each process
jobs = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J"]
imTheFather = True
children = []
for job in jobs:
child = os.fork()
if child:
children.append(child)
else:
imTheFather = False
doTheJob(job)
break
# in the meanwhile
# ps aux|grep python|grep -v grep|wc -l == 11 == 10 children + the father
if imTheFather:
for child in children:
os.waitpid(child, 0)
```
|
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 trying to open the file you saved. The "yellow bar" in IE is warning that the HTML is trying to run an Active X (which it is not, there is only JavaScript doing a submit() on a form). However if you receive the exact same HTML file by email, save it, and open it, you don't have this problem. (It looks like IE is putting some more constraint on what can be done in a HTML file you saved from web site.)
My question is: where can I find documentation on this IE security mechanism, and possibly how can I get around it?
Alex
|
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 can start reading here: <http://msdn.microsoft.com/en-us/library/ms537183.aspx>
|
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 Regex( @"\\[uU]([0-9A-F]{4})" );
result = rx.Replace( result, delegate (Match match) { return ((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); } );
```
The first example shows the replacement being made using a lambda expression (C# 3.0) and the second uses a delegate which should work with C# 2.0.
To break down what's going on here, first we create a regular expression:
```
new Regex( @"\\[uU]([0-9A-F]{4})" );
```
Then we call Replace() with the string 'result' and an anonymous method (lambda expression in the first example and the delegate in the second - the delegate could also be a regular method) that converts each regular expression that is found in the string.
The Unicode escape is processed like this:
```
((char) Int32.Parse(match.Value.Substring(2), NumberStyles.HexNumber)).ToString(); });
```
Get the string representing the number part of the escape (skip the first two characters).
```
match.Value.Substring(2)
```
Parse that string using Int32.Parse() which takes the string and the number format that the Parse() function should expect which in this case is a hex number.
```
NumberStyles.HexNumber
```
Then we cast the resulting number to a Unicode character:
```
(char)
```
And finally we call ToString() on the Unicode character which gives us its string representation which is the value passed back to Replace():
```
.ToString()
```
Note: Instead of grabbing the text to be converted with a Substring call you could use the match parameter's GroupCollection, and a subexpressions in the regular expression to capture just the number ('2320'), but that's more complicated and less readable.
|
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.
Do you think it is possible for us to use the boost libraries instead of our own containers in these conditions?
Any comments and/or advice are welcomed!
Thanks a lot,
Nic
|
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 elements.)
|
**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 parts of boost that have no allocation and you might find them useful.
I would **pick and choose** based on your requirements.
Like anything that you use, you need to know the costs.
|
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 you prefer ASP:
```
<%
Dim UserIPAddress
UserIPAddress = Request.ServerVariables("REMOTE_ADDR")
%>
```
Note: I don't know ASP, but I figured it might be useful to have here so I googled.
|
<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 information of even where to start would be helpful.\
Note: We're using a lotus notes server to do this, but a generic way would be more helpful (If possible).
|
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/sun/mail/pop3/package-summary.html)/[imap](http://java.sun.com/products/javamail/javadocs/com/sun/mail/imap/package-summary.html) client
* [Maildir](http://en.wikipedia.org/wiki/Maildir)/Mailbox
|
*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 [Wiser](http://code.google.com/p/subethasmtp/wiki/Wiser).
Wiser lets you start an in-Java mailserver:
```
Wiser wiser = new Wiser();
wiser.setPort(2500);
wiser.start();
```
Then you can just poll it periodically for mail:
```
for (WiserMessage message : wiser.getMessages())
{
String envelopeSender = message.getEnvelopeSender();
String envelopeReceiver = message.getEnvelopeReceiver();
MimeMessage mess = message.getMimeMessage();
// mail processing goes here
}
```
|
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) return;
char *tail = head;
while(*tail) ++tail; // find the 0 terminator, like head+strlen
--tail; // tail points to the last real char
// head still points to the first
for( ; head < tail; ++head, --tail) {
// walk pointers inwards until they meet or cross in the middle
char h = *head, t = *tail;
*head = t; // swapping as we go
*tail = h;
}
}
```
```
// test program that reverses its args
#include <stdio.h>
int main(int argc, char **argv)
{
do {
printf("%s ", argv[argc-1]);
strrev(argv[argc-1]);
printf("%s\n", argv[argc-1]);
} while(--argc);
return 0;
}
```
The same algorithm works for integer arrays with known length, just use `tail = start + length - 1` instead of the end-finding loop.
(Editor's note: this answer originally used XOR-swap for this simple version, too. Fixed for the benefit of future readers of this popular question. [XOR-swap is *highly* not recommended](https://stackoverflow.com/questions/10549155/why-swap-dont-use-xor-operation-in-c); hard to read and making your code compile less efficiently. You can see [on the Godbolt compiler explorer](https://godbolt.org/z/pPNxJq) how much more complicated the asm loop body is when xor-swap is compiled for x86-64 with gcc -O3.)
---
## Ok, fine, let's fix the UTF-8 chars...
(This is XOR-swap thing. Take care to note that you *must avoid* swapping with self, because if `*p` and `*q` are the same location you'll zero it with a^a==0. XOR-swap depends on having two distinct locations, using them each as temporary storage.)
Editor's note: you can replace SWP with a safe inline function using a tmp variable.
```
#include <bits/types.h>
#include <stdio.h>
#define SWP(x,y) (x^=y, y^=x, x^=y)
void strrev(char *p)
{
char *q = p;
while(q && *q) ++q; /* find eos */
for(--q; p < q; ++p, --q) SWP(*p, *q);
}
void strrev_utf8(char *p)
{
char *q = p;
strrev(p); /* call base case */
/* Ok, now fix bass-ackwards UTF chars. */
while(q && *q) ++q; /* find eos */
while(p < --q)
switch( (*q & 0xF0) >> 4 ) {
case 0xF: /* U+010000-U+10FFFF: four bytes. */
SWP(*(q-0), *(q-3));
SWP(*(q-1), *(q-2));
q -= 3;
break;
case 0xE: /* U+000800-U+00FFFF: three bytes. */
SWP(*(q-0), *(q-2));
q -= 2;
break;
case 0xC: /* fall-through */
case 0xD: /* U+000080-U+0007FF: two bytes. */
SWP(*(q-0), *(q-1));
q--;
break;
}
}
int main(int argc, char **argv)
{
do {
printf("%s ", argv[argc-1]);
strrev_utf8(argv[argc-1]);
printf("%s\n", argv[argc-1]);
} while(--argc);
return 0;
}
```
* Why, yes, if the input is borked, this will cheerfully swap outside the place.
* Useful link when vandalising in the UNICODE: <http://www.macchiato.com/unicode/chart/>
* Also, UTF-8 over 0x10000 is untested (as I don't seem to have any font for it, nor the patience to use a hexeditor)
Examples:
```
$ ./strrev Räksmörgås ░▒▓○◔◑◕●
░▒▓○◔◑◕● ●◕◑◔○▓▒░
Räksmörgås sågrömskäR
./strrev verrts/.
```
|
```
#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 and update the TaskOder column when a sibling is deleted?
```
Task Table
----------
TaskId
ParentTaskId
TaskOrder
TaskName
--etc--
```
Any ideas? Thanks.
|
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
UPDATE Task
SET TaskOrder = TaskOrder - 1
WHERE ParentTaskId = deleted.ParentTaskId
AND TaskOrder > deleted.TaskOrder
```
If you don't want a trigger, you can capture the parentID and TaskOrder in a query first, delete the row, then execute that same update statement but with literals rather than the trigger.
Or if you want to minimize server round-trips, you could move the to-be-deleted task all the way to the bottom, then move the others up, then do the delete, but that seems overly complicated.
|
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.HttpResponse.set_cookie), I can't tell if this is possible. It looks like it just takes a string, so is there another way?
I've tried passing it an array (`[10, 20, 30]`) and dictionary (`{'name': 'Scott', 'id': 1}`) but they just get converted to their string format. My current solution is to just use an arbitrary separator and then parse it when reading it in, which feels icky. If multi-values aren't possible, is there a better way? I'd rather not use lots of cookies, because that would get annoying.
|
.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 multiple cookies. Keep the over-the-wire overhead down by doing what you're doing.
|
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're looking for, but it could work if you don't mind a small amount of db overhead.
|
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:
```
StreamReader reader=new StreamReader("myfile.txt");
try
{
int i = 5 / 0;
}
finally // Will execute despite any exception
{
reader.Close();
}
```
As far as I can tell, the only difference between putting cleanup code in a finally block and putting cleanup code after the try..catch blocks is if you have return statements in your try block (in that case, the cleanup code in finally will run, but code after the try..catch will not).
Otherwise, what's so special about finally?
|
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 of "I can recover from this exception". You should only recover from exceptions you really can correct - catch without arguments says "Hey, I can recover from anything!", which is nearly always untrue.
*If* it were possible to recover from every exception, then it would really be a semantic quibble, about what you're declaring your intent to be. However, it's not, and almost certainly frames above yours will be better equipped to handle certain exceptions. As such, use finally, get your cleanup code run for free, but still let more knowledgeable handlers deal with the issue.
|
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 portability for the dreaded day when someone decides I need to be able to compile my code in say, gcc or some other compiler. Is this syntax widely supported and can I use it without worrying about portability issues?
|
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-us/library/xey702bw%28VS.80%29.aspx> [/edit]
|
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 be very much appreciated.
|
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 you're correctly referencing the JNI and Win32 SDK headers, your code could thus be as simple as:
```
JNIEXPORT jboolean JNICALL Java_ClassName_MethodName
(JNIEnv *env, jstring symLinkName, jstring targetName)
{
const char *nativeSymLinkName = env->GetStringUTFChars(symLinkName, 0);
const char *nativeTargetName = env->GetStringUTFChars(targetName, 0);
jboolean success = (CreateSymbolicLink(nativeSymLinkName, nativeTargetName, 0) != 0);
env->ReleaseStringUTFChars(symLinkName, nativeSymLinkName);
env->ReleaseStringUTFChars(targetName, nativeTargetName);
return success;
}
```
Note that this is just off the top of my head, and I haven't dealt with JNI in ages, so I may have overlooked some of the finer points of making this work...
|
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/bart/archive/2006/10/24/Windows-Vista-*2D00*-Creating-symbolic-links-with-C\_2300\_.aspx](http://community.bartdesmet.net/blogs/bart/archive/2006/10/24/Windows-Vista-_2D00_-Creating-symbolic-links-with-C_2300_.aspx)
A C++ Example, this is cnp from another article I was reading. I have not tested it so use it with caution.
```
typedef BOOL (WINAPI* CreateSymbolicLinkProc) (LPCSTR, LPCSTR, DWORD);
void main(int argc, char *argv[])
{
HMODULE h;
CreateSymbolicLinkProc CreateSymbolicLink_func;
LPCSTR link = argv[1];
LPCSTR target = argv[2];
DWORD flags = 0;
h = LoadLibrary("kernel32");
CreateSymbolicLink_func =
(CreateSymbolicLinkProc)GetProcAddress(h,
if (CreateSymbolicLink_func == NULL)
{
fprintf(stderr, "CreateSymbolicLinkA not available\n");
} else
{
if ((*CreateSymbolicLink_func)(link, target, flags) == 0)
{
fprintf(stderr, "CreateSymbolicLink failed: %d\n",
GetLastError());
} else
{
printf("Symbolic link created.");
}
}
```
}
Having said this, I would not use this code :-) I would either be inclined to fork mklink or look at the native library from jruby/jpython (Sorry I cant look it up atm as my network connection is flakey). I seem to recall that jruby has written a library that wraps up various posix apis into java (thinks like chown that are required for ruby compliance but are not cross platform). This library is being used by the jpython folks who seem very pleased with it. I would be surprised if this library does not offer sym link support.
|
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 spawning extra processes on the server.
If you know of any, please post it!
|
[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
{
//Gets the icon associated with the currently executing assembly
//(or pass a different file path and name for a different executable)
Icon appIcon = Icon.ExtractAssociatedIcon(Assembly.GetExecutingAssembly().Location);
}
catch(ArgumentException ae)
{
//handle
}
}
}
}
```
|
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();
}
```
The question is, how expensive is the `new string[0]` ?
Should I just return null and make the caller accept null as a valid way of indicating "nothing was found"?
NB: This is being called in a loop which gets run hundreds and hundreds of times, so it's one of the few cases where I think this kind of optimiziation is not actually 'premature'.
PS: And even if it was premature, I'd still like to know how it works :-)
### Update:
Initially when I asked if it used any space, I was thinking of things from the 'C/C++' point of view, kind of like how in C, writing `char a[5];` will allocate 5 bytes of space on the stack, and `char b[0];` will allocate 0 bytes.
I realise this is not a good fit for the .NET world, but I was curious if this was something that the compiler or CLR would detect and optimize out, as a non-resizeable array of size zero really shouldn't (as far as I can see?) require any storage space.
|
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 know whether there's anything beyond that, but it's not entirely free. (It *is* incredibly cheap though...)
Fortunately, there's an optimization you can make without compromising the API itself: have a "constant" of an empty array. I've made another small change to make the code clearer, if you'll permit...
```
private static readonly string[] EmptyStringArray = new string[0];
string[] GetTheStuff() {
if( somePredicate() ) {
List<string> s = new List<string>();
// imagine we load some data or something
return s.ToArray();
} else {
return EmptyStringArray;
}
}
```
If you find yourself needing this frequently, you could even create a generic class with a static member to return an empty array of the right type. The way .NET generics work makes this trivial:
```
public static class Arrays<T> {
public static readonly Empty = new T[0];
}
```
(You could wrap it in a property, of course.)
Then just use: Arrays<string>.Empty;
EDIT: I've just remembered [Eric Lippert's post on arrays](http://blogs.msdn.com/ericlippert/archive/2008/09/22/arrays-considered-somewhat-harmful.aspx). Are you sure that an array is the most appropriate type to return?
|
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: contains the word "spam"
"""
data = "spam"
```
|
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 data.
#: Use with caution.
#: @type: C{str}
data = "important data"
```
Now when you generate your documentation, `data` will be described as module variable with given description and type `str`. You can omit the `@type` line.
|
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 obfuscated so that the salesmen cannot start messing with it on their own.
I can come up with something myself bouncing numbers around, dividing by pi and converting to hex and whatnot but I'd be really interested in ideas or best practices from the community.
I'm doing this in C# but I expect that methods from any language can be translated.
edit:
to clarify. I can't store this stuff ahead of time, the codes have to be built on the fly and carry all the information with them.
eg. Salesman 14 calls in about client 773 and wants to give them $500 off their order. 14, 773 and 500 must be in the coupon code and able to be extracted in the client app after the salesman keys in the code.
|
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 that was originally signed (e.g., prepend the user ID to the coupon value) and then verifying the digital signature.
|
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 xml string. Validation would be to decrypt the string and see if it is valid xml (I recommend not to deserialise the object without checking this before).
|
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.
Environment: Windows XP, Visual C++ 2005/2008, raw WinApi.
Here is what is certain about this "Heisenbug":
1) The crash happens only in the Release version.
2) The crash goes away as soon as I remove all GDI-related stuff.
3) BoundChecker has no complains.
4) Writing a log shows that the crash happens on a declaration of a local int variable! How could that be? Memory corruption?
Any ideas would be greatly appreciated!
**UPDATE: I've managed to get the app debugged on a "faulty" PC. The results:**
"Unhandled exception at 0x0044a26a in CintaNotes.exe: 0xC000001D: Illegal Instruction."
and code breaks on
0044A26A cvtsi2sd xmm1,dword ptr [esp+14h]
**So it seems that the problem was in the "Code Generation/Enable Enhanced Instruction Set" compiler option. It was set to "/arch:SSE2" and was crashing on the machines that didn't support SSE2. I've set this option to "Not Set" and the bug is gone. Phew!**
Thank you all very much for help!!
|
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 happened you should perform what is called a postmortem analysis.
## Windows Error Reporting
If you want to analyse the crash, you should get a crash dump. One option for this is to register for Windows Error Reporting - requires some money (you need a digital code signing ID) and some form filling. For more visit <https://winqual.microsoft.com/> .
## Get the crash dump intended for WER directly from the customer
Another option is to get in touch witch some user who is experiencing the crash and get a crash dump intended for WER from him directly. The user can do this when he clicks on the Technical details before sending the crash to Microsoft - the crash dump file location can be checked there.
## Your own minidump
Another option is to register your own exception handler, handle the exception and write a minidump anywhere you wish. Detailed description can be found at [Code Project Post-Mortem Debugging Your Application with Minidumps and Visual Studio .NET article](http://www.codeproject.com/KB/debug/postmortemdebug_standalone1.aspx).
|
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 locals are removed from the stack and if some temporary objects were allocated they are garbage collected anyway.
From my perspective that doesn’t differ from calling method of the same single instance by separate threads. So why cannot a container use one instance of a bean instead of pooling a number of them?
|
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 example, in EJB, you can inject several server resources in to a Session Bean. That state is private to the bean, but there's no reason you can't keep it from invocation to invocation. So, by pooling beans you reduce these lookups to only happening when the bean is created.
Three, you can use bean pool as a means to throttle traffic. If you only have 10 Beans in a pool, you're only going to get at most 10 requests working simultaneously, the rest will be queued up.
|
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 actual activity.
|
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 this just results in many failed compiles. I usually just watch for errors and hit ctrl-break to stop the build manually.
Is there a way to configure it such the build stops at the **very first compile error** (not the first failed project build) automatically?
|
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.Name = "Build") Then Exit Sub
pPane.TextDocument.Selection.SelectAll()
Dim Context As String = pPane.TextDocument.Selection.Text
pPane.TextDocument.Selection.EndOfDocument()
Dim found As Integer = Context.IndexOf(": error ")
If found > 0 Then
DTE.ExecuteCommand("Build.Cancel")
End If
End Sub
```
Hope it works out for you guys.
|
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 BuildEvents.OnBuildProjConfigDone
If Success = False Then
DTE.ExecuteCommand("Build.Cancel")
End If
End Sub
```
|
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 nSubAuthorityCount,
__in DWORD dwSubAuthority0,
__in DWORD dwSubAuthority1,
__in DWORD dwSubAuthority2,
__in DWORD dwSubAuthority3,
__in DWORD dwSubAuthority4,
__in DWORD dwSubAuthority5,
__in DWORD dwSubAuthority6,
__in DWORD dwSubAuthority7,
__out PSID *pSid
);
```
and I don't know how to construct the signature of this method - what should I do with `PSID_IDENTIFIER_AUTHORITY` and `PSID` types? How should I pass them - using `ref` or `out`?
|
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(
System.Runtime.InteropServices.UnmanagedType.ByValArray,
SizeConst = 6,
ArraySubType =
System.Runtime.InteropServices.UnmanagedType.I1)]
public byte[] Value;
}
public partial class NativeMethods {
/// Return Type: BOOL->int
///pIdentifierAuthority: PSID_IDENTIFIER_AUTHORITY->_SID_IDENTIFIER_AUTHORITY*
///nSubAuthorityCount: BYTE->unsigned char
///nSubAuthority0: DWORD->unsigned int
///nSubAuthority1: DWORD->unsigned int
///nSubAuthority2: DWORD->unsigned int
///nSubAuthority3: DWORD->unsigned int
///nSubAuthority4: DWORD->unsigned int
///nSubAuthority5: DWORD->unsigned int
///nSubAuthority6: DWORD->unsigned int
///nSubAuthority7: DWORD->unsigned int
///pSid: PSID*
[System.Runtime.InteropServices.DllImportAttribute("advapi32.dll", EntryPoint = "AllocateAndInitializeSid")]
[return: System.Runtime.InteropServices.MarshalAsAttribute(System.Runtime.InteropServices.UnmanagedType.Bool)]
public static extern bool AllocateAndInitializeSid(
[System.Runtime.InteropServices.InAttribute()]
ref SidIdentifierAuthority pIdentifierAuthority,
byte nSubAuthorityCount,
uint nSubAuthority0,
uint nSubAuthority1,
uint nSubAuthority2,
uint nSubAuthority3,
uint nSubAuthority4,
uint nSubAuthority5,
uint nSubAuthority6,
uint nSubAuthority7,
out System.IntPtr pSid);
}
```
|
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 to check a few well-known immutable types:
```
private static final Set<Class> knownImmutables = new HashSet<Class>(Arrays.asList(
String.class, Byte.class, Short.class, Integer.class, Long.class,
Float.class, Double.class, Boolean.class, BigInteger.class, BigDecimal.class
));
...
public static boolean isImmutable(Object o) {
return knownImmutables.contains(o.getClass());
}
```
This actually gets me 90% of the way, but sometimes my users will want to create simple immutable types of their own:
```
public class ImmutableRectangle {
private final int width;
private final int height;
public ImmutableRectangle(int width, int height) {
this.width = width;
this.height = height;
}
public int getWidth() { return width; }
public int getHeight() { return height; }
}
```
Is there some way (perhaps using reflection) that I could reliably detect whether a class is immutable? False positives (thinking it's immutable when it isn't) are not acceptable but false negatives (thinking it's mutable when it isn't) are.
**Edited to add:** Thanks for the insightful and helpful answers. As some of the answers pointed out, I neglected to define my security objectives. The threat here is clueless developers -- this is a piece of framework code that will be used by large numbers of people who know next-to-nothing about threading and won't be reading the documentation. I do NOT need to defend against malicious developers -- anyone clever enough to [mutate a String](http://directwebremoting.org/blog/joe/2005/05/26/1117108773674.html) or perform other shenanigans will also be smart enough to know it's not safe in this case. Static analysis of the codebase IS an option, so long as it is automated, but code reviews cannot be counted on because there is no guarantee every review will have threading-savvy reviewers.
|
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 know are immutable),
* Require the class to be final itself
* Require that they inherit from a base class you provide (which is guaranteed to be immutable)
Then you can check with the following code if the object you have is immutable:
```
static boolean isImmutable(Object obj) {
Class<?> objClass = obj.getClass();
// Class of the object must be a direct child class of the required class
Class<?> superClass = objClass.getSuperclass();
if (!Immutable.class.equals(superClass)) {
return false;
}
// Class must be final
if (!Modifier.isFinal(objClass.getModifiers())) {
return false;
}
// Check all fields defined in the class for type and if they are final
Field[] objFields = objClass.getDeclaredFields();
for (int i = 0; i < objFields.length; i++) {
if (!Modifier.isFinal(objFields[i].getModifiers())
|| !isValidFieldType(objFields[i].getType())) {
return false;
}
}
// Lets hope we didn't forget something
return true;
}
static boolean isValidFieldType(Class<?> type) {
// Check for all allowed property types...
return type.isPrimitive() || String.class.equals(type);
}
```
**Update:** As suggested in the comments, it could be extended to recurse on the superclass instead of checking for a certain class. It was also suggested to recursively use isImmutable in the isValidFieldType Method. This could probably work and I have also done some testing. But this is not trivial. You can't just check all field types with a call to isImmutable, because String already fails this test (its field `hash` is not final!). Also you are easily running into endless recursions, causing *StackOverflowErrors* ;) Other problems might be caused by generics, where you also have to check their types for immutablity.
I think with some work, these potential problems might be solved somehow. But then, you have to ask yourself first if it really is worth it (also performance wise).
|
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 updating some shared state somewhere).
Ignoring a unhandled exception can be dangerous. If you have a real un-handlable exception (OutOfMemoryException comes into mind), there's not much you can do anyway and your process is basically doomed.
Back to .Net 1.1, an unhandled exception in a backgroundthread would just be thrown to nowhere and the main thread would gladly plough on. And that could have nasty repercussions. So in .Net 2.0 this behavior has changed.
Now, an unhandled exception thrown in a thread which is not the main thread will terminate the process. You may be notified of this (by subscribing to the event on the AppDomain) but the process will die nonetheless.
Since this can be inconvenient (when you don't know what will be run in the thread and you are not absolutely sure it's properly guarded, and your main thread must be resilient), there's a workaround. It's intended as a legacy settings (meaning, it's strongly suggested you make sure you don't have stray threads) but you can force the former behavior this way :
Just add this setting to your service/application/whatever configuration file :
```
<configuration>
<runtime>
<!-- the following setting prevents the host from closing when an unhandled exception is thrown -->
<legacyUnhandledExceptionPolicy enabled="1" />
</runtime>
</configuration>
```
It doesn't seem to work with ASP.NET, though.
For more information (and a huge warning that this setting may not be supported in upcoming versions of the CLR) see <http://msdn.microsoft.com/en-us/library/ms228965.aspx>
|
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 without a
> user interface). However, while it
> offers a good last-resort mechanism
> for logging untrapped exceptions, it
> provides no means of preventing the
> application from shutting down – and
> no means to suppress the .NET
> unhandled exception dialog.
>
> In production applications, explicit
> exception handling is required on all
> thread entry methods. One can cut the
> work by using a wrapper or helper
> class to perform the job, such as
> BackgroundWorker (discussed in Part
> 3).
|
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 through the modules available but can't seem to find anything that matches.
---
Thanks, I do know how to make the relevant code myself, but since such smallish solutions are usually mine-fields waiting to happen (ie. someone writes: Name1='Value1=2';) etc. then I usually prefer some pre-tested function.
I'll do it myself then.
|
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 exact format you are looking for is (what quote chars are accepted, what escape chars etc). You may want to look at the csv module to see if it can cover your format. Here's an example: (Note that the API is a little clunky for this example, as CSV is designed to iterate through a sequence of records, hence the .next() calls I'm making to just look at the first line. Adjust to suit your needs):
```
>>> s = "Name1='Value=2';Name2=Value2;Name3=Value3"
>>> dict(csv.reader([item], delimiter='=', quotechar="'").next()
for item in csv.reader([s], delimiter=';', quotechar="'").next())
{'Name2': 'Value2', 'Name3': 'Value3', 'Name1': 'Value1=2'}
```
Depending on the exact structure of your format, you may need to write your own simple parser however.
|
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 that I run into is with queries like
```
$sql = sqlf("SELECT * FROM Users WHERE id IN (:1)",array(1,2,3) );
```
My code works, but it fails with empty arrays, e.g. the following throws a mysql error:
```
SELECT * FROM Users WHERE id IN ();
```
Does anyone have any suggestions? How should I translate and empty array into sql that can be injected into an IN clause? Substituting NULL will not work.
|
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 it to a Controller/Action. The only option I see is pointing it directly to a view.
|
[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/controllers or implement your own
[HandleErrorAttribute](http://www.codeplex.com/aspnet/SourceControl/FileView.aspx?itemId=266465&changeSetId=16503) isnt very complex. I think MS recommends you copy this code and modify to suit your requirements.
The OnException override gives you access to all that info you may need - controller, action, route data, etc - through ExceptionContext.
Remember to set the ExceptionHandled. Then you can set the filterContext.Result to a new RedirectToAction instance which redirect to your ErrorController and action - obviously you can expose the specific controller and action with properties.
|
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 errors.
```
[SuppressMessage("Microsoft.Performance", "CA1813:AvoidUnsealedAttributes",
Justification = "This attribute is AllowMultiple = true and users might want to override behavior.")]
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
public class GenericExceptionHandlerFilter : ActionFilterAttribute, IExceptionFilter
{
public Type ExceptionType { get; set;}
public string RedirectToAction { get; set;}
public string RedirectToController { get; set;}
protected bool ApplyFilter(ExceptionContext filterContext)
{
Type lExceptionType = filterContext.Exception.GetType();
return (ExceptionType == null ||
lExceptionType.Equals(ExceptionType));
}
#region IExceptionFilter Members
public void OnException(ExceptionContext filterContext)
{
if (ApplyFilter(filterContext))
{
IbfControllerLogger.Log(filterContext.Exception);
filterContext.ExceptionHandled = true;
#region Calculate Action Controller Error
RouteValueDictionary lRoutes = new RouteValueDictionary(new
{
action = RedirectToAction,
controller = String.IsNullOrEmpty(RedirectToController) ? (string)filterContext.RouteData.Values["controller"] : RedirectToController
});
UrlReWriterUtils.UrlReWriter(filterContext.Controller.ViewData, lRoutes);
#endregion
filterContext.Controller.TempData[TempDataName.C_TEMPDATA_EXCEPTIONERROR] = filterContext.Exception;
filterContext.Result = new RedirectToRouteResult(lRoutes);
}
}
#endregion
```
|
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's the case. If there's anyone from Oracle who can comment on it, that'd be fantastic!
|
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 that has never been prompted for, data where the answer exists but is not known by the user, data where there is no answer, etc. all of which constitute some sense of `NULL`).
By the time that the SQL standard came around and agreed that `NULL` and the empty string were distinct entities, there were already Oracle users that had code that assumed the two were equivalent. So Oracle was basically left with the options of breaking existing code, violating the SQL standard, or introducing some sort of initialization parameter that would change the functionality of potentially large number of queries. Violating the SQL standard (IMHO) was the least disruptive of these three options.
Oracle has left open the possibility that the `VARCHAR` data type would change in a future release to adhere to the SQL standard (which is why everyone uses `VARCHAR2` in Oracle since that data type's behavior is guaranteed to remain the same going forward).
|
[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)
> becomes '' which is a zero length
> string and a zero length string is
> NULL in Oracle (it is no long '')
|
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 someone could test ?
2. What tools are available(and used) for testing RESTful web services ?
|
[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 goal here.
Note: I'm looking for a generic tree, not a balanced tree or a map/set, the structure itself and the connectivity of the tree is important in this case, not only the data within.
So each branch needs to be able to hold arbitrary amounts of data, and each branch should be separately iterateable.
|
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 'emulate' a tree through a graph, and maybe it'll be (conceptually) closer to what you're looking for.
|
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 alternative algorithms are available.
HTH
|
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 that?
Or is there some simple algorithm to run this comparison?
> **Update:** Red gate lists "from $395". Anything free? Or more foolproof than just keeping the version number?
|
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,
so.type,
sc.name,
sc.number,
sc.colid,
sc.status,
sc.type,
sc.length,
sc.usertype ,
sc.scale
FROM sysobjects so ,
syscolumns sc
WHERE so.id = sc.id
ORDER BY so.type, so.name, sc.name
/* get definition of each stored procedure */
SELECT so.name,
so.type,
sc.number,
sc.text
FROM sysobjects so ,
syscomments sc
WHERE so.id = sc.id
ORDER BY so.type, so.name, sc.number
```
|
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 third party tool.
|
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 script when a validator is displayed. (I'm using validators with `Display="dynamic"`)
|
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 server side techniques.
|
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 and compare the cached visiblity state with the element's current state. If the states are different, update the cache and run the custom resize script.
This is ugly in lots of ways, and it's only a solution for my specific scenario, not the abstract case where we want to piggyback arbitrary code onto the showing/hiding of a validator. I'd love a better suggestion!
|
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.sun.com/j2se/1.4.2/docs/api/javax/xml/parsers/DocumentBuilder.html) in Java 1.4 specifically says that it *isn't* meant to be concurrent; so can I assume that in 1.6 it is?
The reason is that I have several million tasks running in an ExecutorService, and it seems expensive to call DocumentBuilderFactory.newDocumentBuilder() every time.
|
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>() {
@Override protected DocumentBuilder initialValue() {
try {
return
DocumentBuilderFactory
.newInstance(
"xx.MyDocumentBuilderFactory",
getClass().getClassLoader()
).newDocumentBuilder();
} catch (ParserConfigurationException exc) {
throw new IllegalArgumentException(exc);
}
}
};
```
(Disclaimer: Not so much as attempted to compile the code.)
|
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 XML output from an instance of `XmlDocument`?
|
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 XmlWriterSettings
{
Indent = true,
IndentChars = " ",
NewLineChars = "\r\n",
NewLineHandling = NewLineHandling.Replace
};
using (XmlWriter writer = XmlWriter.Create(sb, settings)) {
doc.Save(writer);
}
return sb.ToString();
}
```
It's a bit more code than I hoped for, but it works just peachy.
|
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 = new XmlTextWriter("data.xml", null)) {
writer.Formatting = Formatting.Indented;
doc.Save(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 most material I could find either targets people who are new to the language or those with a lot of experience.
Which C++ libraries are popular these days? I guess I will need to read on the STL because I didn't use it much. What else? Boost? ATL? WTL?
|
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 to you while learning C++. I would recommned Thinking in C++ for getting up fast on the syntax.
STL would be really useful yes. Thats one thing i have found commonly appreciated by all mature C++ programmers. It would be useful to know the libraries that Boost provides.
The changes to C++ world, depends on the changes your favourite compiler has decided to implement. Since you mentioned ATl/COM i assume it would be VC++. The changes to MFC would be support for Windows Forms (2005 vc++) and Vista compliant uI's and ribbon support(?) (2008 Vc++)
VC++ now supports managed C++ -i'm sure you know what that is coming from the C# world - 2008 adds supports for managed STL too.
VC++ is trying to be more standards compliant and are making some progress in that area.
They have introduced lots of secure functions that depreciate the old stds like strcpy and the compilers will also give warnings if you use the old fns.
VC++2005 also has something called function attributes, which it uses to describe the parameters so that it can do more checking on the inputs you pass in and statically flag a warning if it sees soething amiss. Usefuli would say though our shop has not progressed to using the 2005 compiler.
MSDN has the list of breaking changes for each releases. Oh & Support for Windows 95, Windows 98, Windows Millennium Edition, and Windows NT 4.0 has been removed from 2005 version of VC++. Additionally the core libraries you required till now (CRT, ATL, MFC etc) now support a new deployment model which makes them shared side sy side assemblies and requires a manifest.
This link should get you going - <http://msdn.microsoft.com/en-us/library/y8bt6w34.aspx>
2008 adds even more like Tr1 recommendations, more optimizning compiler, parallel compilation(/mp), support for new processor architectures etc. Open Mp support has also been enhanced in one of these versions is what i remember.
Again refer MSDN - thats the suthentic source for all the answers.
Good luck.
|
[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 me wrong, I liked it and still use it somewhat, but its not fashionable in the MS world anymore).
Something like QT is probably more new and cool for C++ developers, and has the advantage of getting you into all the new Linux and web development that'll be increasingly popular over the next few years.
However, once you start looking at the things you can do, I think it'll all come back quite quickly.
|
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(2000);
f.Close();
```
My idea here is to show the wait window to the user for 2 second. But when i do this the Form 2 is not completely loaded because of which the label in it is blank. Please let me know your inputs on this.
|
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;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Threading;
namespace WaitingBox
{
public class ShowWaitingBox
{
private class WaitingForm:Form
{
public WaitingForm()
{
this.tableLayoutPanel1 = new System.Windows.Forms.TableLayoutPanel();
this.label1 = new System.Windows.Forms.Label();
this.progressBar1 = new System.Windows.Forms.ProgressBar();
this.tableLayoutPanel1.SuspendLayout();
this.SuspendLayout();
//
// tableLayoutPanel1
//
this.tableLayoutPanel1.ColumnCount = 1;
this.tableLayoutPanel1.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.Controls.Add(this.progressBar1, 0, 0);
this.tableLayoutPanel1.Controls.Add(this.label1, 0, 2);
this.tableLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill;
this.tableLayoutPanel1.Location = new System.Drawing.Point(0, 0);
this.tableLayoutPanel1.Name = "tableLayoutPanel1";
this.tableLayoutPanel1.RowCount = 3;
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 29F));
this.tableLayoutPanel1.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 50F));
this.tableLayoutPanel1.Size = new System.Drawing.Size(492, 155);
this.tableLayoutPanel1.TabIndex = 0;
//
// label1
//
this.label1.Anchor = System.Windows.Forms.AnchorStyles.Top;
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(209, 92);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(73, 13);
this.label1.TabIndex = 3;
this.label1.Text = "Please Wait...";
//
// progressBar1
//
this.progressBar1.Anchor = System.Windows.Forms.AnchorStyles.Bottom;
this.progressBar1.Location = new System.Drawing.Point(22, 37);
this.progressBar1.Name = "progressBar1";
this.progressBar1.Size = new System.Drawing.Size(447, 23);
this.progressBar1.TabIndex = 2;
//
// WaitingForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(492, 155);
this.Controls.Add(this.tableLayoutPanel1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedToolWindow;
this.Name = "WaitingForm";
this.Text = "Working in the background";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.WaitingForm_FormClosing);
this.Load += new System.EventHandler(this.WaitingForm_Load);
this.tableLayoutPanel1.ResumeLayout(false);
this.tableLayoutPanel1.PerformLayout();
this.ResumeLayout(false);
}
private System.Windows.Forms.TableLayoutPanel tableLayoutPanel1;
private System.Windows.Forms.ProgressBar progressBar1;
private System.Windows.Forms.Label label1;
private void WaitingForm_Load(object sender, EventArgs e)
{
progressBar1.Style = ProgressBarStyle.Marquee;
this.BringToFront();
this.CenterToScreen();
}
private void WaitingForm_FormClosing(object sender, FormClosingEventArgs e)
{
}
internal void SetLabel(string p)
{
label1.Text = p;
}
}
private WaitingForm wf = new WaitingForm();
private string title, text;
private Thread waiting;
public bool IsAlive
{
get
{
return waiting.IsAlive;
}
set { }
}
public ShowWaitingBox(string Title, string Text)
{
this.title = string.IsNullOrEmpty(Title) ? "Working in the Background..": Title;
this.text = string.IsNullOrEmpty(Text) ? "Please wait..." : Text;
waiting = new Thread(new ThreadStart(Show));
}
public ShowWaitingBox()
{
waiting = new Thread(new ThreadStart(Show));
}
private void Show()
{
wf.Show();
wf.Text = this.title;
wf.SetLabel(this.text);
while (true) {
wf.Refresh();
System.Threading.Thread.Sleep(50);
}
}
public void Start()
{
waiting.Start();
}
public void Stop()
{
waiting.Abort();
}
}
}
```
|
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 integrating changes may hinder easily updating the software as new versions are released.
It does require that someone be very familiar with the software to modify the software directly, but this isn't necessarily a bad idea.
On a side note, I think modifying WordPress is almost a necessity, especially if you want it to have a decent architecture or to actually be secure (ok, that was a jab, sue me).
|
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 standard old version to build a patch set, then apply that patch set to the new version.) You should also be using a VCS yourself to keep yourself sane.
If you aren't up to this then you aren't up to it, there's nothing wrong with following the KISS principle and not mucking up the application code.
If you can write a plugin that does the same thing and does it just as efficiently, then you should do that so you don't have to maintain your own fork.
However, there are a lot of things WordPress is terrible at (efficiency, security) that you can ameliorate (sometimes without much work, just by disabling code you don't need) only by hacking the application code. WordPress is dirty legacy spaghetti code originally written by people with virtually zero knowledge of software or database design, and it does a lot of tremendously stupid things like querying the database *on every request* to see what it's own `siteurl` is, when this never changes -- there's nothing wrong with taking 5 minutes to change 2 lines of code so it doesn't do this any more.
I worked as tech lead on a then-top-20 Technorati-ranked blog and did a lot of work to scale WordPress on a single server and then onto a cluster (with separate servers for admin vs. public access). We had upstream reverse proxies (i.e. Varnish or Squid) acting as HTTP accelerators and an internal object/page fragment cache system that plugged into memcached with failover to filesystem caching using PEAR::Cache\_Lite. We had to modify WordPress to do things like send sane, cache-friendly HTTP headers, to disable a lot of unnecessary SQL and processing.
I modified WP to run using MySQL's memory-only NDB cluster storage engine, which meant specifying indexes in a lot of queries (in the end we opted for a replicated cluster instead, however). In modifying it to run with separate servers for admin vs. public access, we locked down the public-side version so it ran with much reduced MySQL privileges allowing only reads (a third MySQL user got commenting privileges).
If you have a serious comment spam problem (i.e. 10K/hour), then you *have* to do something beyond plugins. Spam will DOS you because WordPress just initializing its core is something like half a second on a standalone P4 with no concurrency, and since WP is a code hairball there's no way to do anything without initializing the core first.
"WP-Cron" is braindead and should be disabled if you have access to an actual crontab to perform these functions. Not hard to do.
In short, I could go on forever listing reasons why you might want to make modifications.
Throughout this it was of course a goal for maintainability reasons to keep these modifications to a minimum and document them as clearly as possible, and we implemented many as plugins when it made sense.
|
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 world a simpler place.
|
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 specify the language by passing `-x c` to the compiler:
```
gcc -x c -c test.cpp -o test.o
```
---
If you run `nm test.o` on these C-language versions, you'll notice that `___gxx_personality_v0` is not listed as a symbol.
(And if you run the same command on an object file generated with `gcc -c test.cpp -o test.o`, the `___gxx_personality_v0` symbol is present.)
|
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 backwards compatibility.
|
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 all Graphics objects
> returned by the API in Java 1.2 or
> above will be a subclass of
> Graphics2D.
Another hint [here](http://www.unidata.ucar.edu/staff/caron/java/JavaOne2003.html) with the same conclusion.
> Graphics Object can always be cast
> Graphics2D g2d = (Graphics2D)g;
|
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 `Graphics2D`.
Both of the authors worked at Sun, so I would assume that they know what they are talking about.
|
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 elements.
```
def Comment(text=None):
element = Element(Comment)
element.text = text
return element
```
Then in the `_write` function of ElementTree that actually outputs the XML, there's a special case handling for comments:
```
if tag is Comment:
file.write("<!-- %s -->" % _escape_cdata(node.text, encoding))
```
In order to support CDATA sections, I create a factory function called `CDATA`, extended the ElementTree class and changed the `_write` function to handle the CDATA elements.
This still doesn't help if you want to parse an XML with CDATA sections and then output it again with the CDATA sections, but it at least allows you to create XMLs with CDATA sections programmatically, which is what I needed to do.
The implementation seems to work with both ElementTree and cElementTree.
```
import elementtree.ElementTree as etree
#~ import cElementTree as etree
def CDATA(text=None):
element = etree.Element(CDATA)
element.text = text
return element
class ElementTreeCDATA(etree.ElementTree):
def _write(self, file, node, encoding, namespaces):
if node.tag is CDATA:
text = node.text.encode(encoding)
file.write("\n<![CDATA[%s]]>\n" % text)
else:
etree.ElementTree._write(self, file, node, encoding, namespaces)
if __name__ == "__main__":
import sys
text = """
<?xml version='1.0' encoding='utf-8'?>
<text>
This is just some sample text.
</text>
"""
e = etree.Element("data")
cdata = CDATA(text)
e.append(cdata)
et = ElementTreeCDATA(e)
et.write(sys.stdout, "utf-8")
```
|
[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 users.
We're not able to see a relationship between the crashing templates at this time, and while there *are* many ways to troubleshoot, the one that's confuddling us is related to event listeners.
The sites crash when any anchor on these templates is clicked. There isn't any inline JS, and while we firebug'ed our way through the attributes of the HTML, we couldn't find a discernable loop or issue that would cause this. (while we troubleshoot, you can experience this for yourself [here](http://dv1.gatehousemedia.com/dev/omniture/index.html) [**warning**! clicking any link in the page will cause your browser to crash!])
**How do you determine if an object has a listener or not? How do you determine what will fire when event is triggered?**
> FYI, I'd love to set breakpoints, but
> *between Omnitures miserably obfuscated code and repeated browser
> crashes*, I'd like to research more
> thoroughly how I can approach this.
|
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 guess) attaches to links:
```
function anonymous(e) {
var s = s_c_il[0], b = s.eh(this, "onclick");
s.lnk = s.co(this);
s.t();
s.lnk = 0;
if (b) {
return this[b](e);
}
return true;
}
```
Maybe in the same way you can see what it is really running after all that obfuscation.
|
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 WebAPI group at W3 on whether to add this functionality. Specialists seem to be against that. I share their arguments.
|
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 kill the entirety of Apache.
As for security, with FastCGI you could technically run the php process under a different user from the default web servers user.
On a seperate note, if you are using Apache's new worker threading support you will want to make sure that you are not using mod\_php as some of the extensions are not thread safe and will cause race conditions.
|
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 your scripts to that user you have to chmod them to 777 - world readable. This means, alas, that your server neighbour can take a look at them - think of where you store the database access password. Most shared servers have solved this using stuff like phpsuexec and such, which run scripts with the permissions of the script owner, so you can (must) have your code chmoded to 644. Phpsuexec runs only with PHP as CGI - that's more or less all, it's just a local machine thing - makes no difference to the world at large.
|
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 the end of the function call.
Example:
```
function doStuff() {
blockUI();
ajaxCall();
unblockUI();
};
```
Is there a way for doStuff to listen for ajaxCall to complete, before firing the unBlockUI? As it is, it processes the function linearly, calling each object in order, then a separate thread is spawned to complete each one. So, though my AJAX call might take 10-15 seconds to complete, I am only blocking the user for just a split-second, due to the linear execution of the function.
There are less elegant ways around this...putting a loop to end only when a return value set by the AJAX function is set to true, or something of that nature. But that seems unnecessarily complicated and inefficient.
|
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-perform-a-synchronous-rather-than-asynchronous-ajax-req) that describes what you're looking for.
|
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 offers the best performance:**
Many servlets (one for each type of data request)?
**Or:**
a single servlet that can handle all of the requests?
|
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)
{
return ViewContext.RouteData.Values["controller"].ToString().Equals(controller, StringComparison.OrdinalIgnoreCase);
}
return false;
}
public bool IsAction(string action)
{
if (ViewContext.RouteData.Values["action"] != null)
{
return ViewContext.RouteData.Values["action"].ToString().Equals(action, StringComparison.OrdinalIgnoreCase);
}
return false;
}
public bool IsAction(string action, string controller)
{
return IsController(controller) && IsAction(action);
}
```
/// Some extension methods that I added to the UrlHelper class.
```
public static class UrlHelperExtensions
{
/// <summary>
/// Determines if the current view equals the specified action
/// </summary>
/// <typeparam name="TController">The type of the controller.</typeparam>
/// <param name="helper">Url Helper</param>
/// <param name="action">The action to check.</param>
/// <returns>
/// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
/// </returns>
public static bool IsAction<TController>(this UrlHelper helper, LambdaExpression action) where TController : Controller
{
MethodCallExpression call = action.Body as MethodCallExpression;
if (call == null)
{
throw new ArgumentException("Expression must be a method call", "action");
}
return (call.Method.Name.Equals(helper.ViewContext.ViewName, StringComparison.OrdinalIgnoreCase) &&
typeof(TController) == helper.ViewContext.Controller.GetType());
}
/// <summary>
/// Determines if the current view equals the specified action
/// </summary>
/// <param name="helper">Url Helper</param>
/// <param name="actionName">Name of the action.</param>
/// <returns>
/// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
/// </returns>
public static bool IsAction(this UrlHelper helper, string actionName)
{
if (String.IsNullOrEmpty(actionName))
{
throw new ArgumentException("Please specify the name of the action", "actionName");
}
string controllerName = helper.ViewContext.RouteData.GetRequiredString("controller");
return IsAction(helper, actionName, controllerName);
}
/// <summary>
/// Determines if the current view equals the specified action
/// </summary>
/// <param name="helper">Url Helper</param>
/// <param name="actionName">Name of the action.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <returns>
/// <c>true</c> if the specified action is the current view; otherwise, <c>false</c>.
/// </returns>
public static bool IsAction(this UrlHelper helper, string actionName, string controllerName)
{
if (String.IsNullOrEmpty(actionName))
{
throw new ArgumentException("Please specify the name of the action", "actionName");
}
if (String.IsNullOrEmpty(controllerName))
{
throw new ArgumentException("Please specify the name of the controller", "controllerName");
}
if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
{
controllerName = controllerName + "Controller";
}
bool isOnView = helper.ViewContext.ViewName.SafeEquals(actionName, StringComparison.OrdinalIgnoreCase);
return isOnView && helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Determines if the current request is on the specified controller
/// </summary>
/// <param name="helper">The helper.</param>
/// <param name="controllerName">Name of the controller.</param>
/// <returns>
/// <c>true</c> if the current view is on the specified controller; otherwise, <c>false</c>.
/// </returns>
public static bool IsController(this UrlHelper helper, string controllerName)
{
if (String.IsNullOrEmpty(controllerName))
{
throw new ArgumentException("Please specify the name of the controller", "controllerName");
}
if (!controllerName.EndsWith("Controller", StringComparison.OrdinalIgnoreCase))
{
controllerName = controllerName + "Controller";
}
return helper.ViewContext.Controller.GetType().Name.Equals(controllerName, StringComparison.OrdinalIgnoreCase);
}
/// <summary>
/// Determines if the current request is on the specified controller
/// </summary>
/// <typeparam name="TController">The type of the controller.</typeparam>
/// <param name="helper">The helper.</param>
/// <returns>
/// <c>true</c> if the current view is on the specified controller; otherwise, <c>false</c>.
/// </returns>
public static bool IsController<TController>(this UrlHelper helper) where TController : Controller
{
return (typeof(TController) == helper.ViewContext.Controller.GetType());
}
}
```
|
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 member variables:
```
<?php
class X {
private $non_static_member = 1;
private static $static_member = 2;
function __construct() {
echo $this->non_static_member . ' '
. self::$static_member;
}
}
new X();
?>
```
Here is an example of **incorrect** usage of `$this` and `self` for non-static and static member variables:
```
<?php
class X {
private $non_static_member = 1;
private static $static_member = 2;
function __construct() {
echo self::$non_static_member . ' '
. $this->static_member;
}
}
new X();
?>
```
Here is an example of **polymorphism** with `$this` for member functions:
```
<?php
class X {
function foo() {
echo 'X::foo()';
}
function bar() {
$this->foo();
}
}
class Y extends X {
function foo() {
echo 'Y::foo()';
}
}
$x = new Y();
$x->bar();
?>
```
Here is an example of **suppressing polymorphic behaviour** by using `self` for member functions:
```
<?php
class X {
function foo() {
echo 'X::foo()';
}
function bar() {
self::foo();
}
}
class Y extends X {
function foo() {
echo 'Y::foo()';
}
}
$x = new Y();
$x->bar();
?>
```
> The idea is that `$this->foo()` calls the `foo()` member function of whatever is the exact type of the current object. If the object is of `type X`, it thus calls `X::foo()`. If the object is of `type Y`, it calls `Y::foo()`. But with self::foo(), `X::foo()` is always called.
From <http://www.phpbuilder.com/board/showthread.php?t=10354489>:
By <http://board.phpbuilder.com/member.php?145249-laserlight>
|
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. Just as you can use `parent::methodName()` to call the parents version of a function, so you can call `self::methodName()` to call the current classes implementation of a method.
```
class Person {
private $name;
public function __construct($name) {
$this->name = $name;
}
public function getName() {
return $this->name;
}
public function getTitle() {
return $this->getName()." the person";
}
public function sayHello() {
echo "Hello, I'm ".$this->getTitle()."<br/>";
}
public function sayGoodbye() {
echo "Goodbye from ".self::getTitle()."<br/>";
}
}
class Geek extends Person {
public function __construct($name) {
parent::__construct($name);
}
public function getTitle() {
return $this->getName()." the geek";
}
}
$geekObj = new Geek("Ludwig");
$geekObj->sayHello();
$geekObj->sayGoodbye();
```
This will output:
> Hello, I'm Ludwig the geek
> Goodbye from Ludwig the person
`sayHello()` uses the `$this` pointer, so the vtable is invoked to call `Geek::getTitle()`.
`sayGoodbye()` uses `self::getTitle()`, so the vtable is not used, and `Person::getTitle()` is called. In both cases, we are dealing with the method of an instantiated object, and have access to the `$this` pointer within the called functions.
|
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 to know how to create the effect of the red line.
|
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://geekswithblogs.net/pvidler/archive/2003/10/15/188.aspx) doing exactly what you want to do.
|
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 dCommission = request.getPremium().doubleValue() - netToCompany;
```
877.8499999999999 = 1586.6 - 708.75
The resulting expected value would be 877.85.
What should be done to ensure the correct calculation?
|
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 example, the last line would be as following using BigDecimal.
```
import java.math.BigDecimal;
BigDecimal premium = BigDecimal.valueOf("1586.6");
BigDecimal netToCompany = BigDecimal.valueOf("708.75");
BigDecimal commission = premium.subtract(netToCompany);
System.out.println(commission + " = " + premium + " - " + netToCompany);
```
This results in the following output.
```
877.85 = 1586.6 - 708.75
```
|
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 choice of using a new `BigDecimal(double)` constructor or the `BigDecimal.valueOf(double)` static factory method. Use the static factory method.
The double constructor converts the entire precision of the `double` to a `BigDecimal` while the static factory effectively converts it to a `String`, then converts that to a `BigDecimal`.
This becomes relevant when you are running into those subtle rounding errors. A number might display as .585, but internally its value is '0.58499999999999996447286321199499070644378662109375'. If you used the `BigDecimal` constructor, you would get the number that is NOT equal to 0.585, while the static method would give you a value equal to 0.585.
```
double value = 0.585;
System.out.println(new BigDecimal(value));
System.out.println(BigDecimal.valueOf(value));
```
on my system gives
```
0.58499999999999996447286321199499070644378662109375
0.585
```
|
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 directory all of my DLLs are in.
So, the problem, is that I add another call that uses a new external DLL, and suddenly when loading the library, an UnsatisfiedLinkError is thrown. The message is: 'The specified procedure could not be found'. This doesn't seem to be a problem with a missing dependent DLL, because I can remove a dependent DLL and get a different message about dependent DLL missing. From what I've been able to find online, it appears that this message means that a native Java function implementation is missing from the DLL, but it's odd that it works fine without this extra bit of code.
Does anyone know what might be causing this? What kinds of things can give a 'The specified procedure could not be found' messages for an UnsatisifedLinkError?
|
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 correctly. But this can apparently happen if a dependent DLL is loaded and that DLL is missing a function required by its parent.
By way of example, we have a library named input.dll. The DLL search order is to always look in the application directory first and the PATH directories last. In the past, we always ran executables from the same directory as input.dll. However, there is another input.dll in the windows system directory (which is in the middle of the DLL search order). So when running this from a java applet, if I include the code described above in the applet, which causes input.dll to be loaded, it loads the input.dll from the system directory. Because our code is expecting certain functions in input.dll which aren't there (because it's a different DLL) the load fails with an error message about missing procedures. Not because the JNI functions are exported wrong, but because the wrong dependent DLL was loaded and it didn't have the expected functions in it.
|
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 or properties that will generate compiler warnings that give messages that I write. Something like this
```
[MyAttribute("This code sux and should be looked at")]
public void DoEverything()
{
}
```
```
<MyAttribute("This code sux and should be looked at")>
Public Sub DoEverything()
End Sub
```
I want this to generate a compiler warning that says, "This code sux and should be looked at". I know how to create a custom attribute, the question is how do I cause it to generate compiler warnings in visual studio.
|
## 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
---
*Original outdated answer:*
I don't believe it's possible. ObsoleteAttribute is treated specially by the compiler and is defined in the C# standard. Why on earth is ObsoleteAttribute not acceptable? It seems to me like this is precisely the situation it was designed for, and achieves precisely what you require!
Also note that Visual Studio picks up the warnings generated by ObsoleteAttribute on the fly too, which is very useful.
Don't mean to be unhelpful, just wondering why you're not keen on using it...
Unfortunately ObsoleteAttribute is sealed (probably partly due to the special treatment) hence you can't subclass your own attribute from it.
From the C# standard:-
> The attribute Obsolete is used to mark
> types and members of types that should
> no longer be used.
>
> If a program uses a type or member
> that is decorated with the Obsolete
> attribute, the compiler issues a
> warning or an error. Specifically, the
> compiler issues a warning if no error
> parameter is provided, or if the error
> parameter is provided and has the
> value false. The compiler issues an
> error if the error parameter is
> specified and has the value true.
Doesn't that sum up your needs?... you're not going to do better than that I don't think.
|
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 compile warnings will show. It generates a compile time warning, but the error message looks funny, you should see it for yourself and choose. This is very close to what you wanted to achieve.
**UPDATE:
With [this code](http://pastie.org/282556) It generates a warning (not very nice, but I don't think there's something better).**
```
public class User
{
private String userName;
[TooManyArgs] // Will show warning: Try removing some arguments
public User(String userName)
{
this.userName = userName;
}
public String UserName
{
get { return userName; }
}
[MustRefactor] // will show warning: Refactor is needed Here
public override string ToString()
{
return "User: " + userName;
}
}
[Obsolete("Refactor is needed Here")]
public class MustRefactor : System.Attribute
{
}
[Obsolete("Try removing some arguments")]
public class TooManyArgs : System.Attribute
{
}
```
|
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:
void testMethod();
};
void TestClass::testMethod(){
// some code here...
}
} // end namespace test_ns
#endif
```
If inside the same project I include this header from more than one cpp file, I get an error saying "`multiple definition of test_ns::TestClass::testMethod()`", while if I put the method definition inside the class body this does not happen:
```
// example.h
#ifndef EXAMPLE_H_
#define EXAMPLE_H_
namespace test_ns{
class TestClass{
public:
void testMethod(){
// some code here...
}
};
} // end namespace test_ns
#endif
```
Since the class is defined inside a namespace, shouldn't the two forms be equivalent? Why is the method considered to be defined twice in the first case?
|
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 translation units then you will have multiple definitions and linker errors.
Also, headers should really always be guarded to prevent multiple definition errors in the same translation unit. That should convert your header to:
```
#ifndef EXAMPLE_H
#define EXAMPLE_H
//define your class here
#endif
```
|
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...
}
} // end namespace test_ns
```
**Edit**
For myself it often helps to solve these kinds of compile problems by realizing that the compiler does not see anything like a header file. Header files are preprocessed and the compiler just sees one huge file containing every line from every (recursively) included file. Normally the starting point for these recursive includes is a cpp source file that is being compiled.
In our company, even a modest looking cpp file can be presented to the compiler as a 300000 line monster.
So when a method, that is not declared inline, is implemented in a header file, the compiler could end up seeing void TestClass::testMethod() {...} dozens of times in the preprocessed file. Now you can see that this does not make sense, same effect as you'd get when copy/pasting it multiple times in one source file.
And even if you succeeded by only having it once in every compilation unit, by some form of conditional compilation ( e.g. using inclusion brackets ) the linker would still find this method's symbol to be in multiple compiled units ( object files ).
|
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 actual strategy used is that each window increments a counter when it is created and decrements one when it is closed. The default close operation is DISPOSE\_ON\_CLOSE. Wen the counter reaches zero, I stop all threadpools and release all JNI resources.
When I launched the application from a bat file (same JARs), it terminated fine when all windows were closed, so I figured that the problem has something to do with Webstart.
Now the questions:
1. Can anybody tell me what exactly is happening? Why does Webstart leave zombie JVMs?
2. Is there a way to release the Webstart resources explicitly without halting the JVM?
3. I've always had the opinion that calling System.exit() encourages the sloppy practice of not releasing your resources and relying on the OS to clean up after you (which can lead to nasty surprises if you reuse the code later)... am I missing something?
See also the [followup question](https://stackoverflow.com/questions/216315/what-is-the-best-way-to-detect-whether-an-application-is-launched-by-webstart) for detecting whether the app has been launched by Webstart.
|
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=232>
|
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 possibly want to leave it out for some testing to detect leaks).
The WebStart thread should all be daemon when there are no system windows (console, javax.jnlp services and other dialogs) showing.
|
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 is usually at a whole number of hours or half-hours.
Suggestions on how best to store this in a SQL Server 2005 database?
|
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 easier to understand value 60 = 1 hour than 3600000. I can't imagine you really needing fractions of minutes as the offset.
|
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 you'd need to store some timezone information. This is because a simple offset can't unambiguously represent the origin of a time. Please see (the somewhat confusing) MSDN documentation about [Choosing Between DateTime, DateTimeOffset, and TimeZoneInfo](http://msdn.microsoft.com/en-us/library/bb384267.aspx).
|
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 you recommend?
|
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 is better.
2. *Much* more important however, it better states your **intent**. You do generally *not* intend to create stateless/empty objects. Rather, you intend to create objects with some state or content. Do it. No need to create a useless (because empty) temporary.
|
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")
//anotherDataSet does not contain the new table
MyTypedDataSet ds2 = anotherDataSet;
//ds12 actually points to anotherDataSet
ds2.Tables.Add("test");
//anotherDataSet now contains the new table
```
---
Ok, let's assume that what you meant was:
```
MyClass o1 = new MyClass();
o1.LoadFrom( /* some data */ );
//vs
MyClass o2 = new MyClass( /* some data */ );
```
Then the latter is better, as the former creates an empty object before populating it.
However unless initialising an empty class has a high cost or is repeated a large number of times the difference is not that important.
|
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.javanature</nature>
</natures>
</projectDescription>
```
And in .classpath, reference the Java libs:
```
<classpath>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER"/>
</classpath>
```
|
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 Project -> Properties.
3. Go to "Targetted Runtimes" and add the proper runtime. Click APPLY.
4. Go to "Project Facets" and select the JAVA facet which has appeared due to step 4. Click APPLY
5. Set your build path.
6. If it's a Maven project, you might want to select the project, click Maven -> Update Project configuration...
That did it for me. And Eclipse is configured correctly. Hope it'll work for you too.
|
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.