Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I used Visual Studio's Application Wizard to create a skeleton MFC program with a multi-document interface. When I start this program, it automatically creates a child frame, which I don't want it to do - I need the main frame's client area to be empty until the user chooses to open a file.
The debugger tells me that ... | This worked for me -- change
```
if (!ProcessShellCommand(cmdInfo))
```
to
```
if (cmdInfo.m_nShellCommand != CCommandLineInfo::FileNew && !ProcessShellCommand(cmdInfo))
```
in your app's InitInstance() function. | This works, it maintains printing/opening from the shell etc.
```
// Parse command line for standard shell commands, DDE, file open
CCommandLineInfo cmdInfo;
ParseCommandLine(cmdInfo);
if ( cmdInfo.m_nShellCommand == CCommandLineInfo::FileNew )
{
cmdInfo.m_nShellCommand = CCommandLineInfo::FileNothing ;
}
// Dis... | How can I stop my MFC application from calling OnFileNew() when it starts? | [
"",
"c++",
"mfc",
""
] |
Evil or not evil?
```
public static void Raise(this EventHandler handler, object sender, EventArgs args)
{
if (handler != null)
{
handler(sender, args);
}
}
// Usage:
MyButtonClicked.Raise(this, EventArgs.Empty);
// This works too! Evil?
EventHandler handler = null;
handler.Raise(this, EVentArgs.Empty... | Not evil. I wish events worked this way by default. Can someone explain why an event with no subscribers is null? | You can always declare your events like this (not that i recommend it):
```
public event EventHandler<EventArgs> OnClicked = delegate { };
```
That way they have something assigned to them when you call them, so they don't throw a null pointer exception.
You can probably get rid of the delegate keyword in C# 3.0... | Is calling an extension method on a "null" reference (i.e. event with no subscribers) evil? | [
"",
"c#",
"events",
"extension-methods",
""
] |
I've got two collections (generic Lists), let's call them ListA and ListB.
In ListA I've got a few items of type A. In ListB I've got some items of type B that have the SAME ID (but not same type) as the items in ListA, plus many more. I want to remove all the items from ListB that have the same ID as the ones in List... | I discovered that lambda expressions was a perfect match. Instead of a long linq to objects method, I could do it in just a few lines with lambda:
```
foreach(TypeA objectA in listA){
listB.RemoveAll(objectB => objectB.Id == objectA.Id);
}
``` | Here are two options. Not sure which one is faster.
```
listB.RemoveAll(listA.Contains);
foreach (string str in listA.Intersect(listB))
listB.Remove(str);
``` | Deleting items from one collection in another collection | [
"",
"c#",
".net",
"collections",
"linq-to-objects",
""
] |
What is the most efficient way to read the last row with SQL Server?
The table is indexed on a unique key -- the "bottom" key values represent the last row. | If you're using MS SQL, you can try:
```
SELECT TOP 1 * FROM table_Name ORDER BY unique_column DESC
``` | ```
select whatever,columns,you,want from mytable
where mykey=(select max(mykey) from mytable);
``` | How to read the last row with SQL Server | [
"",
"sql",
"sql-server",
""
] |
Imagine I have these python lists:
```
keys = ['name', 'age']
values = ['Monty', 42, 'Matt', 28, 'Frank', 33]
```
Is there a direct or at least a simple way to produce the following list of dictionaries ?
```
[
{'name': 'Monty', 'age': 42},
{'name': 'Matt', 'age': 28},
{'name': 'Frank', 'age': 33}
]
``` | Here is the zip way
```
def mapper(keys, values):
n = len(keys)
return [dict(zip(keys, values[i:i + n]))
for i in range(0, len(values), n)]
``` | It's not pretty but here's a one-liner using a list comprehension, zip and stepping:
```
[dict(zip(keys, a)) for a in zip(values[::2], values[1::2])]
``` | Map two lists into one single list of dictionaries | [
"",
"python",
"dictionary",
"list",
""
] |
The documentation available on the [boost website](http://www.boost.org/doc/libs/1_36_0/doc/html/boost_asio.html) is... limited.
From what I've been able to read, the general consensus is that it is simply difficult to find good documentation on the boost::asio library.
Is this really the case? If so, why?
Notes:
*... | First, I've been using Boost.Asio for quite a while already -- and I share your concern. To address your question:
* There really is very scarce documentation about Boost.Asio aside from the introduction and tutorial. I am not the author, but this is mostly because there are just too many things to document for someth... | Some nice documentation on boost including a chapter on asio can be found in a (free) boost book at <http://en.highscore.de/cpp/boost/index.html>. The chapter on asio provides a general overview and then goes as far as how to develop your own custom asio extensions. Really fantastic effort by Boris Schäling! | Best documentation for Boost:asio? | [
"",
"c++",
"boost",
"boost-asio",
""
] |
We are introducing static analysis tools into the build system for our Java product. We are using Maven2 so [Checkstyle](http://checkstyle.sourceforge.net/) and [PMD](http://pmd.sourceforge.net/) integration come for free. However it looks like there is a large overlap in functionality between these two tools, in terms... | You should definitely use [FindBugs](http://findbugs.sourceforge.net/). In my experience, the false-positive rate is very low, and even the least-critical warnings it reports are worth addressing to some extent.
As for Checkstyle vs. PMD, I would not use Checkstyle since it is pretty much only concerned with style. In... | Both softwares are useful. Checkstyle will help you during your programming by checking your *coding style* i.e braces, naming etc. Simple things but very numerous!
PMD will help you by checking more complicate rules like during the design of your classes, or for more special problems like implementing correctly the c... | Checkstyle vs. PMD | [
"",
"java",
"static-analysis",
"findbugs",
"checkstyle",
"pmd",
""
] |
I'd like something like
```
int minIndex = list.FindMin(delegate (MyClass a, MyClass b) {returns a.CompareTo(b);});
```
Is there a builtin way to do this in .NET? | Try looking at these:
[Min](http://msdn.microsoft.com/en-us/library/bb909313.aspx)
[Max](http://msdn.microsoft.com/en-us/library/bb909073.aspx)
As long as your class implements IComparable, all you have to do is:
```
List<MyClass> list = new List();
//add whatever you need to add
MyClass min = list.Min();
MyClass ... | Well, if you can't use .NET 3.5, you could always sort the list and then return list[0]. It might not be the fastest way, but it's probably the shortest code, especially if your class already implements IComparable.
```
List<SomeClass> list = new List<SomeClass>();
// populate the list
// assume that SomeClass impleme... | Shortest code to calculate list min/max in .NET | [
"",
"c#",
".net",
"algorithm",
""
] |
I am working in Java on a fairly large project. My question is about how to best structure the set of Properties for my application.
Approach 1: Have some static Properties object that's accessible by every class. (Disadvantages: then, some classes lose their generality should they be taken out of the context of the a... | I like using Spring dependency injection for many of the properties. You can treat your application like building blocks and inject the properties directly into the component that needs them. This preserves (encourages) encapsulation. Then, you assemble your components together and create the "main class".
A nice side... | Actually, approach 2 works really well.
I tried using a Singleton properties object on a recent project. Then, when it came time to add features, I need to revise the Singleton, and regretted having to locate every place where I used `MySingleton.getInstance()`.
Approach 2 of passing a global information object throu... | Correct approach to Properties | [
"",
"java",
"oop",
"properties",
"structure",
""
] |
I am trying to run some unit tests in a C# Windows Forms application (Visual Studio 2005), and I get the following error:
> System.IO.FileLoadException: Could not load file or assembly 'Utility, Version=1.2.0.200, Culture=neutral, PublicKeyToken=764d581291d764f7' or one of its dependencies. The located assembly's mani... | The .NET Assembly loader:
* is unable to find 1.2.0.203
* but did find a 1.2.0.200
This assembly does not match what was requested and therefore you get this error.
In simple words, it can't find the assembly that was referenced. Make sure it can find the right assembly by putting it in the GAC or in the application... | You can do a couple of things to troubleshoot this issue. First, use Windows file search to search your hard drive for your assembly (.dll). Once you have a list of results, do View->Choose Details... and then check "File Version". This will display the version number in the list of results, so you can see where the ol... | The located assembly's manifest definition does not match the assembly reference | [
"",
"c#",
"reference",
"compiler-errors",
"dependencies",
"version",
""
] |
I don't use Eclipse as an IDE, and have no interest in doing so. However, I do like its source-level debugging.
Is there any way I can use it to debug a C++ Linux app without going through the ritual of creating a project? (In effect, can I just use it like a frontend to gdb?)
If not, what are the steps I need to fol... | Take a look at [this question](https://stackoverflow.com/questions/204345/how-to-setup-a-linux-c-project-in-eclipse#204353). Create a C/C++-project, use your project's source directory as project directory, select to use the external builder, and change "make" to whatever tool you want.
The tricky part is to get the i... | I don't know if this has changed in the 4+ years since the question was posted, but there's a much easier way to do this. I'm on Eclipse Luna (4.4.2).
```
> eclipse&
```
then
`File` > `Import` > `C/C++` > `C/C++ Executable` > `Next` > browse to executable > `Next` > choose a project name > `Finish`
No other project... | How Do I Use Eclipse to Debug a C++ Program on Linux? | [
"",
"c++",
"eclipse",
"debugging",
"eclipse-cdt",
""
] |
What does this mean exactly? I'm doing something like this:
```
File.Copy(@"\\foo\bar\baz.txt", @"c:\test\baz.txt");
```
MSDN doesn't describe this exception except in general terms, and googling around just yields tables of error codes.
I've confirmed the source file exists, and I'm 99% sure that I have the permiss... | Check this article for some information about using symlinks in .Net: "[Manipulating NTFS Junction Points in .NET](http://www.codeproject.com/KB/files/JunctionPointsNet.aspx)".
According to this article:
> "In particular the .NET libraries does
> not include any functionality for
> creating or querying properties of
... | By default local evaluation of remote symbolic links is disabled.
You could use fsutil to change that setting or you could delve into unmanaged code and resolve the link yourself. | System.IO.IOException: The symbolic link cannot be followed because its type is disabled | [
"",
"c#",
""
] |
I am working on a legacy ASP application. I am attempting to insert a value (40.33) into a field in SQL Server 2000 that happens to be a float type. Every place I can see (via some logging) in the application is sending 40.33 to the Stored Procedure. When I run SQL Profiler against the database while the call is happen... | Yes, this is a weird, although [well-known](http://en.wikipedia.org/wiki/Floating_point#Accuracy_problems), side effect of using FLOAT.
In Microsoft SQL Server, you should use exact numeric datatypes such as [NUMERIC, DECIMAL](http://msdn.microsoft.com/en-us/library/ms187746(SQL.90).aspx), [MONEY or SMALLMONEY](http:/... | I think this is probably just a precision issue - the 0.33 part of the number can't be represented exactly in binary - this is probably the closest that you can get to. | Inserting a value into an SQL float column generates a weird result | [
"",
"sql",
"sql-server",
"floating-point",
""
] |
Developing a heavily XML-based Java-application, I recently encountered an interesting problem on Ubuntu Linux.
My application, using the [Java Plugin Framework](http://jpf.sourceforge.net/), appears unable to convert a [dom4j](http://www.dom4j.org/)-created XML document to [Batik's](http://xmlgraphics.apache.org/bati... | LinkageError is what you'll get in a classic case where you have a class C loaded by more than one classloader and those classes are being used together in the same code (compared, cast, etc). It doesn't matter if it is the same Class name or even if it's loaded from the identical jar - a Class from one classloader is ... | Sounds like a classloader hierarchy problem. I can't tell what type of environment your application is deployed in, but sometimes this problem can occur in a web environment - where the application server creates a hierarchy of classloaders, resembling something like:
javahome/lib - as root
appserver/lib - as child ... | How to deal with LinkageErrors in Java? | [
"",
"java",
"linux",
"classloader",
"linkageerror",
""
] |
I have a certain POJO which needs to be persisted on a database, current design specifies its field as a single string column, and adding additional fields to the table is not an option.
Meaning, the objects need to be serialized in some way. So just for the basic implementation I went and designed my own serialized f... | Elliot Rusty Harold wrote up a [nice argument](http://xom.nu/designprinciples.xhtml#d0e323) against using Java Object serialization for the objects in his XOM library. The same principles apply to you. The built-in Java serialization is Java-specific, fragile, and slow, and so is best avoided.
You have roughly the rig... | You might try [Protocol Buffers](http://code.google.com/p/protobuf/), it is a open-source project from Google, it is said to be fast (generates shorter serialized form than XML, and works faster). It also handles addition of new field gently (inserts default values). | Homemade vs. Java Serialization | [
"",
"java",
"database",
"serialization",
""
] |
I am developing a little app that retrieves an XML file, located on a remote server (`http://example.com/myfile.xml`)
This file is relatively big, and it contains a big list of geolocations with other information that I need to use for my app.
So I read this file remotely once and insert it into a little SqlCE file (`d... | Re protobuf-net, there isn't a separate download for the CF version at the moment, but there is a csproj in the source for both CF 2.0 and CF 3.5.
To clarify on your question; actually protobuf-net doesn't even use a `.proto` file (at the moment); a `.proto` file just describes what the data is - protobuf-net simply l... | Load the big XML file, convert it into an appropriate different data structure, save it to a file in an efficient format. (XML really isn't terribly efficient.)
I believe [Marc Gravell's Protocol Buffers](http://code.google.com/p/protobuf-net/) implementation works on the Compact Framework...
(None of the protobuf im... | How to read remote XML file the most efficiently way? | [
"",
"c#",
"xml",
"compact-framework",
"sdf",
"sql-server-mobile",
""
] |
I have one std::list<> container and these threads:
* One writer thread which adds elements indefinitely.
* One reader/writer thread which reads and removes elements while available.
* Several reader threads which access the SIZE of the container (by using the size() method)
There is a normal mutex which protects the... | Yes, the read threads will need some sort of mutex control, otherwise the write will change things from under it.
A reader/writer mutex should be enough. But strictly speaking this is an implmentation-specific issue. It's possible that an implementation may have mutable members even in const objects that are read-only... | Checkout the concurrent containers provided by Intel's Open Source [Threading Building Blocks](http://www.threadingbuildingblocks.org/) library. Look under "Container Snippets" on the [Code Samples page](http://www.threadingbuildingblocks.org/codesamples.php) for some examples. They have concurrent / thread-safe contai... | Do I need to protect read access to an STL container in a multithreading environment? | [
"",
"c++",
"multithreading",
"visual-c++",
"stl",
"concurrency",
""
] |
Given a list of urls, I would like to check that each url:
* Returns a 200 OK status code
* Returns a response within X amount of time
The end goal is a system that is capable of flagging urls as potentially broken so that an administrator can review them.
The script will be written in PHP and will most likely run o... | Use the PHP cURL extension. Unlike fopen() it can also make HTTP HEAD requests which are sufficient to check the availability of a URL and save you a ton of bandwith as you don't have to download the entire body of the page to check.
As a starting point you could use some function like this:
```
function is_available... | Look into cURL. There's a library for PHP.
There's also an executable version of cURL so you could even write the script in bash. | How do I check for valid (not dead) links programmatically using PHP? | [
"",
"php",
"url",
"cron",
""
] |
I'm planning to make a very simple program using php and mySQL. The main page will take information and make a new row in the database with that information. However, I need a number to put in for the primary key. Unfortunately, I have no idea about the normal way to determine what umber to use. Preferably, if I delete... | In MySQL that's the [standard solution.](http://dev.mysql.com/doc/refman/5.0/en/example-auto-increment.html)
```
CREATE TABLE animals (
id MEDIUMINT NOT NULL AUTO_INCREMENT,
name CHAR(30) NOT NULL,
PRIMARY KEY (id)
);
``` | Unless you have an overriding reason to generate your own PK then using the autoincrement would be good enough. That way the database manages the keys. When you are inserting a row you have to leave out the primary key column.
Say you have a table table = (a, b, c) where a is the primary key then the insert statement ... | What's the standard way to determine the number for a primary key? | [
"",
"php",
"mysql",
"database",
""
] |
I was playing around with my own Sudoku solver and was looking for some pointers to good and fast design when I came across this:
```
def r(a):i=a.find('0');~i or exit(a);[m
in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for
j in range(81)]or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import*;r(argv[1])
```
M... | Well, you can make things a little easier by fixing up the syntax:
```
def r(a):
i = a.find('0')
~i or exit(a)
[m in[(i-j)%9*(i/9^j/9)*(i/27^j/27|i%9/3^j%9/3)or a[j]for j in range(81)] or r(a[:i]+m+a[i+1:])for m in'%d'%5**18]
from sys import *
r(argv[1])
```
Cleaning up a little:
```
from sys import exit, argv... | unobfuscating it:
```
def r(a):
i = a.find('0') # returns -1 on fail, index otherwise
~i or exit(a) # ~(-1) == 0, anthing else is not 0
# thus: if i == -1: exit(a)
inner_lexp = [ (i-j)%9*(i/9 ^ j/9)*(i/27 ^ j/27 | i%9/3 ^ j%9/3) or a[j]
for j in range(81)] # r appears... | Shortest Sudoku Solver in Python - How does it work? | [
"",
"python",
"algorithm",
""
] |
I need to do a few very simple URL manipulations in Java. Like get the value for a parameter in the query, or update it, ... I was expecting to find a simple utility class doing that in the commons-lang package, but no. I know it is a simple problem, but if there is something already written, why do it again ? Do you k... | I think what you want is called a query string parser instead of an url manipulator and here's one: <http://ostermiller.org/utils/CGIParser.java.html> | Apache's httpcomponents library has a URL decoder: <http://hc.apache.org/httpcomponents-client-ga/httpclient/apidocs/org/apache/http/client/utils/URLEncodedUtils.html>
Httpcomponents is the successor to commons http client. | A good library to do URL Query String manipulation in Java | [
"",
"java",
"url",
""
] |
In Visual Studio, is there any way to make the debugger break whenever a certain file (or class) is entered? Please don't answer "just set a breakpoint at the beginning of every method" :)
I am using C#. | Macros can be your friend. Here is a macro that will add a breakpoint to every method in the current class (put the cursor somewhere in the class before running it).
```
Public Module ClassBreak
Public Sub BreakOnAnyMember()
Dim debugger As EnvDTE.Debugger = DTE.Debugger
Dim sel As EnvDTE.TextSelec... | You could start by introducing some sort of Aspect-Oriented Programming - see for instance
[this explanation](http://blogs.msdn.com/saveenr/archive/2008/11/20/c-aop-elegant-tracing-with-postsharp-and-aspect-oriented-programming.aspx) - and then put a breakpoint in the single OnEnter method.
Depending on which AOP fram... | break whenever a file (or class) is entered | [
"",
"c#",
"visual-studio",
"debugging",
""
] |
Given that a function `a_method` has been defined like
```
def a_method(arg1, arg2):
pass
```
Starting from `a_method` itself, how can I get the argument names - for example, as a tuple of strings, like `("arg1", "arg2")`? | Take a look at the [`inspect`](http://docs.python.org/library/inspect.html) module - this will do the inspection of the various code object properties for you.
```
>>> inspect.getfullargspec(a_method)
(['arg1', 'arg2'], None, None, None)
```
The other results are the name of the \*args and \*\*kwargs variables, and t... | In CPython, the number of arguments is
```
a_method.func_code.co_argcount
```
and their names are in the beginning of
```
a_method.func_code.co_varnames
```
These are implementation details of CPython, so this probably does not work in other implementations of Python, such as IronPython and Jython.
One portable wa... | How to get method parameter names? | [
"",
"python",
"decorator",
"introspection",
"python-datamodel",
""
] |
I have a number of child tables that have a foreign key to a parent table.
How do I add an entry in the parent table and get the primary key of that entry, so that I can then enter rows in the child tables that point to the entry in the parent table?
I'm doing this in a MS Access Database from a C# application. | Microsoft Access 2000 or later does support the @@IDENTITY property to retrieve the value of an Autonumber field after an INSERT. ([msdn](http://msdn.microsoft.com/en-us/library/ks9f57t0(VS.71).aspx))
Edit: [This](http://msdn.microsoft.com/en-us/library/ks9f57t0.aspx) is the link to a similar article for .NET 3.5 | [Getting the identity of the most recently added record](http://www.mikesdotnetting.com/Article.aspx?ArticleID=54) | Get the Primary Key of a new Entry | [
"",
"c#",
".net",
"database",
"ms-access",
"primary-key",
""
] |
I need to search a string and replace all occurrences of `%FirstName%` and `%PolicyAmount%` with a value pulled from a database. The problem is the capitalization of FirstName varies. That prevents me from using the `String.Replace()` method. I've seen web pages on the subject that suggest
```
Regex.Replace(strInput, ... | [From MSDN](http://msdn.microsoft.com/en-us/library/ewy2t5e0.aspx)
$0 - "Substitutes the last substring matched by group number number (decimal)."
In .NET Regular expressions group 0 is always the entire match. For a literal $ you need to
```
string value = Regex.Replace("%PolicyAmount%", "%PolicyAmount%", @"$$0", ... | Seems like `string.Replace` *should* have an overload that takes a `StringComparison` argument. Since it doesn't, you could try something like this:
```
public static string ReplaceString(string str, string oldValue, string newValue, StringComparison comparison)
{
StringBuilder sb = new StringBuilder();
int p... | Is there an alternative to string.Replace that is case-insensitive? | [
"",
"c#",
".net",
"string",
".net-2.0",
"replace",
""
] |
I need to know the default port settings for the following services
1. SQL Server
2. SQL Browser
3. SQL Reporting services
4. SQL Analysis services
I need to know the port settings for these services for different versions of SQL Server (2000,2005,2008)
Also let me know whether the default port setting will change b... | 1. The default SQL Server port is 1433 but only if it's a default install. Named instances get a random port number.
2. The browser service runs on port UDP 1434.
3. Reporting services is a web service - so it's port 80, or 443 if it's SSL enabled.
4. Analysis services is 2382 but only if it's a default install. Named ... | If you have access to the server then you can use
```
select local_tcp_port from sys.dm_exec_connections where local_tcp_port is not null
```
For full details see [port number of SQL Server](https://stackoverflow.com/questions/1281150/port-number-of-sql-server/5035779#5035779) | Default port for SQL Server | [
"",
"asp.net",
"sql",
"sql-server",
""
] |
I allow users to enter a regular expression to match IP addresses, for doing an IP filtration in a related system. I would like to validate if the entered regular expressions are valid as a lot of userse will mess op, with good intentions though.
I can of course do a Regex.IsMatch() inside a try/catch and see if it bl... | As long as you catch very specific exceptions, just do the try/catch.
Exceptions are not evil if used correctly. | I think exceptions are OK in this case.
Just make sure to shortcircuit and eliminate the exceptions you can:
```
private static bool IsValidRegex(string pattern)
{
if (string.IsNullOrWhiteSpace(pattern)) return false;
try
{
Regex.Match("", pattern);
}
catch (ArgumentException)
{
... | Can I test if a regex is valid in C# without throwing exception | [
"",
"c#",
"regex",
""
] |
I'm interested in how garbage collection works. I've read up on how some work such as mark-and-sweep, stop-and-copy, generational GC, etc... I'd like to experiment with implementing some of these and comparing their behaviors. What's a good way to get started experimenting with my own? Ideally something in C, Java or P... | Never played with it myself, but the one that always gets mentioned for use with C/C++ is [Hans Boehm's](http://www.hpl.hp.com/personal/Hans_Boehm/gc/). | the .NET runtime and Java runtime are now open source, so you can experiment with the runtime it self if you want to play around with a current support programming language. However if you wanted to do this yourself you would probably have to create your own runtime which has it's own language. | How can I experiment with garbage collection? | [
"",
"c++",
"c",
"garbage-collection",
""
] |
I have a block of product images we received from a customer. Each product image is a picture of something and it was taken with a white background. I would like to crop all the surrounding parts of the image but leave only the product in the middle. Is this possible?
As an example: [<http://www.5dnet.de/media/catalog... | I've written code to do this myself - it's not too difficult to get the basics going.
Essentially, you need to scan pixel rows/columns to check for non-white pixels and isolate the bounds of the product image, then create a new bitmap with just that region.
Note that while the `Bitmap.GetPixel()` method works, it's r... | I found I had to adjust Dmitri's answer to ensure it works with images that don't actually need cropping (either horizontally, vertically or both)...
```
public static Bitmap Crop(Bitmap bmp)
{
int w = bmp.Width;
int h = bmp.Height;
Func<int, bool> allWhiteRow = row =>
{
... | Remove surrounding whitespace from an image | [
"",
"c#",
"vb.net",
"graphics",
""
] |
I'm using `org.w3c` `XML API` to open an existing `XML` file. I'm removing some nodes , and I'm adding others instead.
The problem is that the new nodes that are added are written one after the other, with no newline and no indentation what so ever. While it's true that the `XML` file is valid , it is very hard for a ... | I'm assuming that you're using a [`Transformer`](http://java.sun.com/javase/6/docs/api/javax/xml/transform/Transformer.html) to do the actual writing (to a [`StreamResult`](http://java.sun.com/javase/6/docs/api/javax/xml/transform/stream/StreamResult.html)). In which case, do this before you call `transform`:
```
tran... | ```
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
```
source
[How to pretty print XML from Java?](https://stackoverflow.com/questions/139076/how-to-pretty-print-xml-from-java) | Java: Writing a DOM to an XML file (formatting issues) | [
"",
"java",
"xml",
"formatting",
"pretty-print",
""
] |
`Connection.close()` may throw `SqlException`, but I have always assumed that it is safe to ignore any such exceptions (and I have never seen code that does not ignore them).
Normally I would write:
```
try{
connection.close();
}catch(Exception e) {}
```
Or
```
try{
connection.close();
}catch(Exception ... | Actually, what you're doing is (almost) best practice :-) here's what I saw in Spring's JdbcUtils.java. So, you might want to add
another Catch block.
```
/**
* Close the given ResultSet and ignore any thrown exception.
* This is useful for typical finally blocks in manual code.
* @param resultSet the ResultSet ... | In general, I've had days wasted by people throwing away exceptions like that.
I recommend following a few basic rules with exceptions:
If you are ABSOLUTELY SURE you will NEVER cause a problem with a checked exception, catch JUST that exception and comment exactly why you don't need to handle it. (Sleep throws an In... | Should I catch exceptions thrown when closing java.sql.Connection | [
"",
"java",
"jdbc",
"coding-style",
""
] |
This is baffling me, maybe somebody can shine the light of education on my ignorance. This is in a C# windows app. I am accessing the contents of a listbox from a thread. When I try to access it like this
```
prgAll.Maximum = lbFolders.SelectedItems.Count;
```
I get the error. However, here is the part I don't get. I... | ```
prgAll.Maximum = lbFolders.SelectedItems.Count;
```
On that line you perform an assignment (**set/add**), which by default is not thread-safe.
On the second line it's just a **get** operation, where thread-safety merely doesn't matter.
EDIT: I don't mean access to the prgAll element.
Accessing the Count propert... | You can't access GUI elements from a separate thread. Use a delegate to make the change.
eg.
```
lblStatus.Invoke((Action)(() => lblStatus.Text = counter.ToString()));
```
or older skool:
```
lblTest.Invoke((MethodInvoker)(delegate()
{
lblTest.Text = i.ToString();
}));
```
I've got a blog post on how to do th... | Why am I getting this error:"Cross-thread operation not valid: Control lbFolders accessed from a thread other than the thread it was created on."? | [
"",
"c#",
".net",
"multithreading",
""
] |
How can I write an insert statement which includes the & character? For example, if I wanted to insert "J&J Construction" into a column in the database.
I'm not sure if it makes a difference, but I'm using Oracle 9i. | I keep on forgetting this and coming back to it again! I think the best answer is a combination of the responses provided so far.
Firstly, & is the variable prefix in sqlplus/sqldeveloper, hence the problem - when it appears, it is expected to be part of a variable name.
SET DEFINE OFF will stop sqlplus interpreting ... | If you are doing it from SQLPLUS use
```
SET DEFINE OFF
```
to stop it treading & as a special case | How to insert a string which contains an "&" | [
"",
"sql",
"oracle",
"escaping",
"sqlplus",
""
] |
I have YAML data that looks sort of like this, but ~150k of it:
```
---
all:
foo: 1025
bar:
baz: 37628
quux:
a: 179
b: 7
```
...or the same thing in JSON:
```
{"all":{"bar":{"baz":"37628","quux":{"a":"179","b":"7"}},"foo":"1025"}}
```
I want to present this content in an expandable JavaScrip... | I finally came up with a super-elegant way to do this in about 5 lines of code, based on the fact that the simple [YAML](http://en.wikipedia.org/wiki/YAML) looks a lot like [Markdown](http://en.wikipedia.org/wiki/Markdown).
We're starting off with this:
```
---
all:
foo: 1025
bar:
baz: 37628
quux:
a... | You can convert your JSON data to nicely nested DIVs with this. I haven't tested it with a wide number of datasets, but it seems to work.
```
function renderJSON(obj) {
'use strict';
var keys = [],
retValue = "";
for (var key in obj) {
if (typeof obj[key] === 'object') {
retValu... | Display JSON/YAML hierarchy as a tree in HTML? | [
"",
"javascript",
"html",
"json",
"treeview",
"yui",
""
] |
I'm looking for the equivalent in Qt to `GetTickCount()`
Something that will allow me to measure the time it takes for a segment of code to run as in:
```
uint start = GetTickCount();
// do something..
uint timeItTook = GetTickCount() - start;
```
any suggestions? | How about [`QTime`](http://doc.qt.io/qt-5/qtime.html)? Depending on your platform it should have 1 millisecond accuracy. Code would look something like this:
```
QTime myTimer;
myTimer.start();
// do something..
int nMilliseconds = myTimer.elapsed();
``` | I think it's probably better to use [`QElapsedTimer`](http://doc.qt.io/qt-5/qelapsedtimer.html) since that is why the class exists in the first place. It was introduced with Qt 4.7. Note that it is also immuned to system's clock time change.
Example usage:
```
#include <QDebug>
#include <QElapsedTimer>
...
...
QElaps... | Get elapsed time in Qt | [
"",
"c++",
"qt",
""
] |
I am using the Maven (2) Cobertura plug-in to create reports on code coverage, and I have the following stub I am using in a method:
```
try {
System.exit(0);
} catch (final SecurityException exception) {
exception.printStackTrace();
}
System.err.println("The program never exited!");
```
I know that I need to... | I haven't used Cobertura in a while (2005?), and saw this behavior back then. A similar problem exists with NCover for C# and curly braces following catch/finally blocks.
My suggestion would be to add to [this Cobertura bug report detailing a similar issue](http://sourceforge.net/tracker/index.php?func=detail&aid=1474... | I would look at the coverage report. Double check my tests. Notice that the code really is getting covered and not worry about hitting 100%. Code coverage is best used to find areas that you may have neglected to hit with your tests, but just focusing on getting 100% coverage as a goal is bad habit that can lead to you... | Cobertura refuses to acknowledge code was covered | [
"",
"java",
"maven-2",
"code-coverage",
"cobertura",
""
] |
I have a validation control that has the following expression:
```
(?=(.*\\d.*){2,})(?=(.*\\w.*){2,})(?=(.*\\W.*){1,}).{8,}
```
That's a password with at least **2 digits**, **2 alpha characters**, **1 non-alphanumeric** and **8 character minimum**. Unfortunately this doesn't seem to be cross-browser compliant.
This... | `(?=(.*\W.*){0,})` is not 0 non-alphanumeric characters. It is *at least 0* non-alphanumeric characters. If you wanted the password to not contain any non-alphanumeric characters you could do either `(?!.*\W)` or `(?=\w*$)`.
A simpler solution would be to skip the `\W` look-ahead, and use `\w{8,}` instead of `.{8,}`.
... | This will get you 2 min digits, 2 min characters, and min 8 character length... I refuse to show you how to not allow users to have non-alphanumeric characters in their passwords, why do sites want to enforce less secure passwords?
```
^(?=.*\d{2})(?=.*[a-zA-Z]{2}).{8,}$
``` | ASP.NET Regular Expression Validator (Password Strength) | [
"",
"javascript",
"asp.net",
"regex",
"validation",
""
] |
**UPDATE** - A comprehensive comparison, updated as of February 2015, can be found here:
# [Alternatives to Ext JS](https://stackoverflow.com/questions/200284/what-are-alternatives-to-extjs/2144878#2144878)
---
*2008 question*:
There are a number of great and not so-great Javascript GUI frameworks out there. I've l... | When considering a JavaScript library/framework for usage you should first define on your goals. I used to separate all JavaScript libraries/frameworks into three categories by their purpose and architecture:
1. I want to **pimp up my page** with some really "cool" features. Go for *JavaScript library*.
* jQuery
... | On the contrary I find qooxdoo syntax and code organization very clear. It is much like swing or gtk. I have tried Dojo as well, without much success. My no.1 choice for RIAs is qooxdoo. It is rich, coder-friendly, free and well documented.
My choice for any other (browser based) JavaScript work is jQuery. Although ot... | Your choice of cross-browser javascript GUI | [
"",
"javascript",
"user-interface",
"frameworks",
"cross-browser",
"widget",
""
] |
I am working on an embedded systems project and have run into an issue of the compiler being programatically embedded in the Paradigm C++ IDE. I would like to be able to automate building.
The processor is the AMD186ES. I am not working with the OS - just baremetal stuff.
I need to generate real-mode 16-bit 8086 machi... | I am currently using gnu `as` (part of binutils and the assembler used for gcc) and I have successfully been assembling 16bit assembly code with the following:
```
as <file>
ld --oformat binary -Ttext 0x0 -e start <file>
```
with my assembly files starting out with:
```
.code16
.globl start
.text
start:
```
since i... | Your best bet is probably [OpenWatcom](http://www.openwatcom.org/index.php/Main_Page), which includes a C++ compiler. Back in the early-to-mid 90s, I believe this was the best C/C++ compiler around. It was open-sourced a few years ago. | Looking for 16-bit x86 compiler | [
"",
"c++",
"compiler-construction",
"embedded",
"x86-16",
""
] |
My goal is to recognize simple gestures from accelerometers mounted on a sun spot. A gesture could be as simple as rotating the device or moving the device in several different motions. The device currently only has accelerometers but we are considering adding gyroscopes if it would make it easier/more accurate.
Does ... | The accelerometers will be registering a constant acceleration due to gravity, plus any acceleration the device is subjected to by the user, plus noise.
You will need to low pass filter the samples to get rid of as much irrelevant noise as you can. The worst of the noise will generally be higher frequency than any pos... | Since no one seems to have mentioned existing libraries, as requested by OP, here goes:
<http://www.wiigee.org/>
Meant for use with the Wiimote, **wiigee** is an open-source Java based implementation for pattern matching based on accelerometer readings. It accomplishes this using **Hidden Markov Models**[1]. ... | How to do Gesture Recognition using Accelerometers | [
"",
"java",
"embedded",
"accelerometer",
"gesture-recognition",
""
] |
I'm working on a service that needs to detect user states for all user(s) logged on to a single machine. Specifically, I want to check to see whether or not the screen saver is active and whether or not their session is locked.
This code will run under a system-level service, and has no visible UI, so that may rule ou... | The most straightforward way would be to have a small app running in each user's session. Each instance of this app could communicate with the main instance of the service.
Windows tries pretty hard to keep logon sessions separate -- both between services and the interactive desktop, and between individual Terminal Se... | As a serivce you can use the event OnSessionChange to catch all your relevant moments.
```
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceProcess;
using System.Diagnostics;
namespace MyCode
{
class MyService : ServiceBase
{
public MyService()
... | Service needs to detect if workstation is locked, and screen saver is active | [
"",
"c#",
".net",
""
] |
I have a table with two fields of interest for this particular exercise: a CHAR(3) ID and a DATETIME. The ID identifies the submitter of the data - several thousand rows. The DATETIME is not necessarily unique, either. (The primary keys are other fields of the table.)
Data for this table is submitted every six months.... | I later realised that I was supposed to check to make sure that there was data for *both* July to December and January to June. So this is what I wound up in v2:
```
SELECT @avgmonths = AVG(x.[count])
FROM ( SELECT CAST(COUNT(DISTINCT DATEPART(month,
DATEADD(mont... | For interest, this is what I wound up using. It was based off Stephen's answer, but with a few adaptations.
It's part of a larger script that's run every six months, but we're only checking this every twelve months - hence the "If FullYear = 1". I'm sure there's a more stylish way to identify the boundary dates, but t... | Identify full vs half yearly datasets in SQL | [
"",
"sql",
"sql-server-2005",
"t-sql",
""
] |
Hey all I'm hoping someone has enough experience with Cake PHP to make this work.
I'm working on something that at the moment could affectionately be called a twitter clone. Essentially I have a set up like this.
Users have many friends. This is a many to many relationship to the user table. It is stored in a link ta... | If all you need in the results of the query is a list of tips, I'd be tempted to do this in 2 queries. The first to find a list of user ids of this user and their friends, the second to find the tips that belong to any one of these ids. So, in your Tip model:
```
function findTipsByUserAndFriends($userId) {
//Friend... | I would recommend that you use containable it works great.
```
$aCond = array(
'fields' => array(
'Discount.*'
),
'contain' => array(
'Event' => array(
'conditions' => array('Event.id' => $iEventId)
)
)
... | How can I write a complex find query in CakePHP without using `$this->Model->query()`? | [
"",
"php",
"mysql",
"cakephp",
""
] |
I'm debating the best way to propagate fairly complex permissions from the server to an AJAX application, and I'm not sure the best approach to take.
Essentially, I want my permissions to be defined so I can request a whole set of permissions in one shot, and adjust the UI as appropriate (the UI changes can be as low ... | If you have a clear set of permissions, like a "user level" or "user type", you could just pass the value down in a hidden field and access the value through the DOM. You could still do this if your permissions were more granular, but you would either have a lot of hidden fields or you would have to encode the informat... | If you transmit the permission structure to the client as a JSON object (or XML, if you prefer), you can manipulate that object with the client-side code, and send it back to the server, which can do whatever it needs to validate the data and persist it. | Propagate Permissions to Javascript | [
"",
"javascript",
"permissions",
""
] |
I have been running [StyleCop](http://en.wikipedia.org/wiki/StyleCop) over some C# code, and it keeps reporting that my `using` directives should be inside the namespace.
Is there a technical reason for putting the `using` directives inside instead of outside the namespace? | There is actually a (subtle) difference between the two. Imagine you have the following code in File1.cs:
```
// File1.cs
using System;
namespace Outer.Inner
{
class Foo
{
static void Bar()
{
double d = Math.PI;
}
}
}
```
Now imagine that someone adds another file (File... | This thread already has some great answers, but I feel I can bring a little more detail with this additional answer.
First, remember that a namespace declaration with periods, like:
```
namespace MyCorp.TheProduct.SomeModule.Utilities
{
...
}
```
is entirely equivalent to:
```
namespace MyCorp
{
namespace T... | Should 'using' directives be inside or outside the namespace in C#? | [
"",
"c#",
".net",
"namespaces",
"stylecop",
"code-organization",
""
] |
Do any queries exist that require RIGHT JOIN, or can they always be re-written with LEFT JOIN?
And more specifically, how do you re-write this one without the right join (and I guess implicitly without any subqueries or other fanciness):
```
SELECT *
FROM t1
LEFT JOIN t2 ON t1.k2 = t2.k2
RIGHT JOIN t3 ON t3.k3 = t2.k... | You can always use only left Joins...
```
SELECT * FROM t1
LEFT JOIN t2 ON t1.k2 = t2.k2
RIGHT JOIN t3 ON t3.k3 = t2.k3
```
is equivilent to:
```
Select * From t3
Left Join (t1 Left Join t2
On t2.k2 = t1.k2)
On T2.k3 = T3.K3
```
In general I always try to use only Left Joins, as... | You can always re-write them to get the same result set. However, sometimes the execution plan may be different in significant ways (performance) and sometimes a right join let's you express the query in a way that makes more sense.
Let me illustrate the performance difference. Programmers tend to think in terms of an... | Is RIGHT JOIN Ever Required? | [
"",
"sql",
""
] |
So I'm teaching myself Python, and I'm having an issue with lists. I want to pass my function a list and pop items off it while retaining the original list. How do I make python "instance" the passed list rather that passing a pointer to the original one?
Example:
```
def burninate(b):
c = []
for i in range(3... | As other answers have suggested, you can provide your function with a copy of the list.
As an alternative, your function could take a copy of the argument:
```
def burninate(b):
c = []
b = list(b)
for i in range(3):
c.append(b.pop())
return c
```
Basically, you need to be clear in your mind (... | You can call `burninate()` with a copy of the list like this:
`d = burninate(a[:])`
or,
`d = burninate(list(a))`
The other alternative is to make a copy of the list in your method:
```
def burninate(b):
c=[]
b=b[:]
for i in range(3):
c.append(b.pop())
return c
>>> a = range(6)
>>> b = burn... | Passing a list while retaining the original | [
"",
"python",
"list",
""
] |
I have a helper class that is just a bunch of static methods and would like to subclass the helper class. Some behavior is unique depending on the subclass so I would like to call a virtual method from the base class, but since all the methods are static I can't create a plain virtual method (need object reference in o... | Virtual static methods don't make sense. If I call `HelperClass.HelperMethod();`, why would I expect some random subclass' method to be called? The solution really breaks down when you have 2 subclasses of `HelperClass` - which one would you use?
If you want to have overrideable static-type methods you should probably... | I don't think you are crazy. You just want to use what is impossible currently in .NET.
Your request for virtual static method would have so much sense if we are talking about generics.
For example my future request for CLR designers is to allow me to write intereface like this:
```
public interface ISumable<T>
{... | Why can't I declare C# methods virtual and static? | [
"",
"c#",
"oop",
""
] |
Given a date range, I need to know how many Mondays (or Tuesdays, Wednesdays, etc) are in that range.
I am currently working in C#. | Try this:
```
static int CountDays(DayOfWeek day, DateTime start, DateTime end)
{
TimeSpan ts = end - start; // Total duration
int count = (int)Math.Floor(ts.TotalDays / 7); // Number of whole weeks
int remainder = (int)(ts.TotalDays % 7); // Number of remaining days
int... | Since you're using C#, if you're using C#3.0, you can use LINQ.
Assuming you have an Array/List/IQueryable etc that contains your dates as DateTime types:
```
DateTime[] dates = { new DateTime(2008,10,6), new DateTime(2008,10,7)}; //etc....
var mondays = dates.Where(d => d.DayOfWeek == DayOfWeek.Monday); // = {10/6/... | Count number of Mondays in a given date range | [
"",
"c#",
"datetime",
"date",
"datediff",
""
] |
I'm looking for a way to add a close button to a .NET ToolTip object similar to the one the NotifyIcon has. I'm using the tooltip as a message balloon called programatically with the Show() method. That works fine but there is no onclick event or easy way to close the tooltip. You have to call the Hide() method somewhe... | You could try an implement your own tool tip window by overriding the existing one and customizing the onDraw function. I never tried adding a button, but have done other customizations with the tooltip before.
```
1 class MyToolTip : ToolTip
2 {
3 public MyToolTip()
4 {
5 ... | You can subclass the ToolTip class with your own CreateParams that sets the TTS\_CLOSE style:
```
private const int TTS_BALLOON = 0x80;
private const int TTS_CLOSE = 0x40;
protected override CreateParams CreateParams
{
get
{
var cp = base.CreateParams;
cp.Style = TTS_BALLOON | TTS_CLOSE;
r... | Add close button (red x) to a .NET ToolTip | [
"",
"c#",
".net",
"winforms",
"tooltip",
""
] |
My basic question is, in .NET, how do I clone WebControls?
I would like to build a custom tag, which can produce multiple copies of its children.
Ultimately I intend to build a tag similar to in JSP/Struts.
But the first hurdle I have is the ability to duplicate/clone the contents of a control.
Consider this rather ... | What's wrong with using a Repeater and binding a dud data source. It'll duplicate the templated controls and handle the ID creation and all. | Just as a reference for others which really want to clone a **custom server control**.
```
public class MyCustomServerCtrl
{
...
public MyCustomServerCtrl Clone()
{
return MemberwiseClone() as MyCustomServerCtrl;
}
}
```
But note: this is needed very rarely and if so, most probably just when you'... | How do you 'clone' WebControls in C# .NET? | [
"",
"c#",
".net",
"asp.net",
""
] |
I am getting the following error when I get to the line that invokes a REALLY BASIC web service I have running on Tomcat/Axis.
```
Element or attribute do not match QName production: QName::=(NCName':')?NCName
```
Have I got something wrong with QName?- I can't even find any useful information about it.
My client co... | As the exception says, you call the QName constructor incorrectly:
```
new QName("http://testPackage.fc.com/, doBasicStuff")
```
is incorrect. I think you have to pass two strings, one containing the namespace, one the localname. The documentation will typically contain a description on how to use that class. | Could it be a typo in your QName?:
```
new QName("http://testPackage.fc.com/", "doBasicStuff")
```
instead of:
```
new QName("http://testPackage.fc.com/, doBasicStuff")
``` | Simple java client code for Web Service - something to do with QName? | [
"",
"java",
"web-services",
"client",
"rpc",
""
] |
I'm aware that I can grab the CPU identifier and the volume serial number for a physical drive by querying WMI, but WMI usually takes its sweet time. What other speedier options, if any, are available to retrieve this information? Are there Win32 APIs that would accomplish this?
**Edit:** Allow me to clarify. By CPU i... | Just keep in mind that ID of the CPU is not always available.
By the way, what are you trying to accomplish? If you want to generate a unique key for a computer instance, check the [Generating Unique Key (Finger Print) for a Computer for Licensing Purposes](http://www.codeproject.com/KB/cs/GenerateUniqueKey.aspx) post... | You can query the windows registry for the drive information, not sure about the CPU though. It seems that your question is addressed in this SO q/a (demonstrates a number of methods to get this info, but for speed, maybe getting it from registry is your best bet):
[How to list physical disks?](https://stackoverflow.c... | APIs in C# for grabbing CPU IDs and drive/volume serial | [
"",
"c#",
".net",
"winapi",
"wmi",
""
] |
So what I have right now is something like this:
```
PropertyInfo[] info = obj.GetType().GetProperties(BindingFlags.Public);
```
where `obj` is some object.
The problem is some of the properties I want aren't in `obj.GetType()` they're in one of the base classes further up. If I stop the debugger and look at obj, th... | Use this:
```
PropertyInfo[] info = obj.GetType().GetProperties(BindingFlags.Public | BindingFlags.Instance);
```
EDIT: Of course the correct answer is that of [Jay](https://stackoverflow.com/questions/245055/how-do-you-get-the-all-properties-of-a-class-and-its-base-classes-up-the-hierar#245131). `GetProperties()` wi... | I don't think it's that complicated.
If you remove the `BindingFlags` parameter to GetProperties, I think you get the results you're looking for:
```
class B
{
public int MyProperty { get; set; }
}
class C : B
{
public string MyProperty2 { get; set; }
}
static void Main(s... | How do you get the all properties of a class and its base classes (up the hierarchy) with Reflection? (C#) | [
"",
"c#",
"reflection",
"getproperties",
""
] |
Lately I've been using XPathDocument and XNavigator to parse an XML file for a given XPath and attribute. It's been working very well, when I know in advance what the XPath is.
Sometimes though, the XPath will be one of several possible XPath values, and I'd like to be able to test whether or not a given XPath exists.... | If you've given valid XPath but it doesn't match anything, `SelectSingleNode` won't *throw* a `NullReferenceException` - it will just return null.
If you pass `SelectSingleNode` some syntactically invalid XPath, that's when it will throw an `XPathException`.
So normally, you'd just need to test whether the returned v... | ```
var baz = navigator.SelectSingleNode("//foo/bar/@baz");
if (baz != null) Console.WriteLine(baz);
``` | Best way test for XPath existence in an XML file? | [
"",
"c#",
"xml",
""
] |
I'm planning to write gateway web application, which would need "terminal window" with VT100/ANSI escape code support. Are there any AJAX based alternatives for such a task?
I'm thinking something like this: <http://tryruby.hobix.com/>
My preferred backend for the system is Python/Twisted/Pylons, but since I'm just p... | Try
[AnyTerm](http://wiki.kartbuilding.net/index.php/Anyterm)
[AjaxTerm](http://wiki.kartbuilding.net/index.php/Ajaxterm)
[WebShell](http://www-personal.umich.edu/~mressl/webshell/) | There's also [Shell In A Box](http://shellinabox.com). | AJAX console window with ANSI/VT100 support? | [
"",
"python",
"ajax",
"vt100",
""
] |
I want to setup a CRON that runs a PHP script that in turn moves XML file (holding non-sensitive information) from one server to another.
I have been given the proper username/password, and want to use SFTP protocol. The jobs will run daily. There is the potential that one server is Linux and the other is Windows. Bot... | If both servers would be on Linux you could use [rsync](http://samba.anu.edu.au/rsync/) for any kind of files (php, xml, html, binary, etc). Even if one of them will be Windows there are rsync ports to Windows. | Why not try using PHP's [FTP functions](http://www.php.net/manual/en/ref.ftp.php)?
Then you could do something like:
```
// open some file for reading
$file = 'somefile.txt';
$fp = fopen($file, 'r');
// set up basic connection
$conn_id = ftp_connect($ftp_server);
// login with username and password
$login_result = ... | What is the best way to move files from one server to another with PHP? | [
"",
"php",
"file",
"data-transfer",
""
] |
I'm looking for an open-source pastebin web-application written in either Python or Perl.
I need it in order to implement a web-based specialized editor for my own needs, and I want to borrow code / ideas from the pastebin since I don't have much experience in web programming.
Can you point to one (or a few) ?
Thanks... | [Lodgeit](http://dev.pocoo.org/projects/lodgeit/) is written in Python and is a nice pastebin | I like [pastebot](http://sourceforge.net/projects/pastebot/), which powers <http://paste.pocoo.org/> (for example). It's Perl and uses POE. | What is a good open source pastebin in Python or Perl? | [
"",
"python",
"perl",
"open-source",
"pastebin",
""
] |
The picture below explains all:
[alt text http://img133.imageshack.us/img133/4206/accentar9.png](http://img133.imageshack.us/img133/4206/accentar9.png)
The variable textInput comes from `File.ReadAllText(path);` and characters like : ' é è ... do not display. When I run my UnitTest, all is fine! I see them... Why? | I do not know why It works with NUnit, but I open the file with NotePad++ and I see ANSI in the format. Now I converted to UTF-8 and it works.
I am still wondering why it was working with NUnit and not in the console? but at least it works now.
**Update**
I do not get why I get down voted on the question and in this ... | The .NET classes (`System.IO.StreamReader` and the likes) take UTF-8 as the default encoding. If you want to read a different encoding you have to pass this explicitly to the appropriate constructor overload.
Also note that there's not one single encoding called “ANSI”. You're probably referring to the Windows codepag... | C# : Characters do not display well when in Console, why? | [
"",
"c#",
".net",
"encoding",
".net-2.0",
"io",
""
] |
Is there a typedef equivalent in C#, or someway to get some sort of similar behaviour? I've done some googling, but everywhere I look seems to be negative. Currently I have a situation similar to the following:
```
class GenericClass<T>
{
public event EventHandler<EventData> MyEvent;
public class EventData : ... | No, there's no true equivalent of typedef. You can use 'using' directives within one file, e.g.
```
using CustomerList = System.Collections.Generic.List<Customer>;
```
but that will only impact that source file. In C and C++, my experience is that `typedef` is usually used within .h files which are included widely - ... | Jon really gave a nice solution, I didn't know you could do that!
At times what I resorted to was inheriting from the class and creating its constructors. E.g.
```
public class FooList : List<Foo> { ... }
```
Not the best solution (unless your assembly gets used by other people), but it works. | Equivalent of typedef in C# | [
"",
"c#",
"typedef",
""
] |
How should I configure the class to bind three dropdowns (date, month, year) to a single Date property so that it works the way it works for 'single request parameter per property' scenario ?
I guess a should add some custom PropertyEditors by overriding initBinder method. What else ? | Aleksey Kudryavtsev: you can override the onBind method in your controller, i which you cant fiddle something special in command object, like
```
dateField = new SimpleFormat("YYYY-mm-dd").parse(this.year + "-" + this.month + "-" this.day);
```
or:
```
Calendar c = Calendar.getInstance();
c.set(year, month, day);
da... | You could create a hidden input in your form and populate it using JavaScript when user selects date, then bind to this input in your command object.
Probably you will be using javascript anyway for things like checking correctness of the date, so why not format the ready to use date in one parameter.
Then you need t... | Spring MVC : Binding 3 dropdowns to a date property in SimpleFormController | [
"",
"java",
"spring-mvc",
"propertyeditor",
""
] |
I'm doing some PHP work recently, and in all the code I've seen, people tend to use few methods. (They also tend to use few variables, but that's another issue.) I was wondering why this is, and I found this note "A function call with one parameter and an empty function body takes about the same time as doing 7-8 $loca... | I think Joomla and Wordpress are not the greatest examples of *good* PHP code, with no offense. I have nothing personal against the people working on it and it's great how they enable people to have a website/blog and I know that a lot of people spend all their free time on either of those projects but the code quality... | How much "efficiency" do you need? Have you even measured? Premature optimization is the root of all evil, and optimization without measurement is ALWAYS premature.
Remember also the [rules of Optimization Club](http://xoa.petdance.com/Rules_of_Optimization_Club).
1. The first rule of Optimization Club is, you do not... | Seriously, should I write bad PHP code? | [
"",
"php",
"optimization",
"code-generation",
"translation",
""
] |
I have some HTML that looks like this:
```
<ul class="faq">
<li class="open">
<a class="question" href="">This is my question?</a>
<p>Of course you can, it will be awesome. </p>
</li>
</ul>
```
Using CSS I'm setting the `p` tag to `display:none;`. I want to use jQuery to display or hide the `p... | Try using:
```
$(this).siblings('p').css()
``` | ```
$(this).next("p").css("...")
```
the "p" above is optional, if you just want the next non-whitespace node in the DOM. | Using "this" with jQuery Selectors | [
"",
"javascript",
"jquery",
"css-selectors",
""
] |
I'm working on an application for work that is going to query our employee database. The end users want the ability to search based on the standard name/department criteria, but they also want the flexibility to query for all people with the first name of "James" that works in the Health Department. The one thing I wan... | While the `COALESCE` trick is neat, my preferred method is:
```
CREATE PROCEDURE ps_Customers_SELECT_NameCityCountry
@Cus_Name varchar(30) = NULL
,@Cus_City varchar(30) = NULL
,@Cus_Country varchar(30) = NULL
,@Dept_ID int = NULL
,@Dept_ID_partial varchar(10) = NULL
AS
SELECT Cus_Name
,Cus_C... | The most efficient way to implement this type of search is with a stored procedure. The statement shown here creates a procedure that accepts the required parameters. When a parameter value is not supplied it is set to NULL.
```
CREATE PROCEDURE ps_Customers_SELECT_NameCityCountry
@Cus_Name varchar(30) = NULL,
@Cus_Ci... | How do I create a stored procedure that will optionally search columns? | [
"",
"sql",
"sql-server",
"search",
"stored-procedures",
"parameters",
""
] |
I'm looking for the simplest, most straightforward way to implement the following:
* The main program instantiates worker
threads to do a task.
* Only `n` tasks can be running at once.
* When `n` is reached, no more workers
are started until the count of
running threads drops back below `n`. | I think that [Executors.newFixedThreadPool](http://docs.oracle.com/javase/8/docs/api/java/util/concurrent/Executors.html#newFixedThreadPool(int)) fits your requirements. There are a number of different ways to use the resulting ExecutorService, depending on whether you want a result returned to the main thread, or whet... | ```
/* Get an executor service that will run a maximum of 5 threads at a time: */
ExecutorService exec = Executors.newFixedThreadPool(5);
/* For all the 100 tasks to be done altogether... */
for (int i = 0; i < 100; i++) {
/* ...execute the task to run concurrently as a runnable: */
exec.execute(new Runnable() ... | How to implement simple threading with a fixed number of worker threads | [
"",
"java",
"multithreading",
"concurrency",
""
] |
Is there a way to compile an Eclipse-based Java project from the command line?
I'm trying to automate my build (using FinalBuilder not ant), and I'm neither a Java nor Eclipse expert. I can probably figure out how to do this with straight java command line options, but then the Eclipse project feels like a lot of wast... | You can build an eclipse project via a workspace from the command line:
```
eclipsec.exe -noSplash -data "D:\Source\MyProject\workspace" -application org.eclipse.jdt.apt.core.aptBuild
```
It uses the `jdt apt` plugin to build your workspace automatically. This is also known as a 'Headless Build'. Damn hard to figure ... | To complete André's answer, an ant solution could be like the one described in [Emacs, JDEE, Ant, and the Eclipse Java Compiler](http://www.emacsblog.org/2007/02/13/emacs-jdee-ant-and-the-eclipse-java-compiler/), as in:
```
<javac
srcdir="${src}"
destdir="${build.dir}/classes">
<comp... | Build Eclipse Java Project from Command Line | [
"",
"java",
"eclipse",
"command-line",
""
] |
Is there some way to get a value from the last inserted row?
I am inserting a row where the PK will automatically increase, and I would like to get this PK. Only the PK is guaranteed to be unique in the table.
I am using Java with a JDBC and PostgreSQL. | With PostgreSQL you can do it via the RETURNING keyword:
[PostgresSQL - RETURNING](http://www.postgresql.org/docs/8.3/interactive/sql-insert.html)
```
INSERT INTO mytable( field_1, field_2,... )
VALUES ( value_1, value_2 ) RETURNING anyfield
```
It will return the value of "anyfield". "anyfield" may be a sequence or... | See the API docs for [java.sql.Statement](http://java.sun.com/javase/6/docs/api/java/sql/Statement.html).
Basically, when you call `executeUpdate()` or `executeQuery()`, use the `Statement.RETURN_GENERATED_KEYS` constant. You can then call `getGeneratedKeys` to get the auto-generated keys of all rows created by that e... | How to get a value from the last inserted row? | [
"",
"java",
"database",
"postgresql",
"jdbc",
""
] |
Anyone have any thoughts on how/if it is possible to integrate Google Code commits to cause a Google AppEngine deployment of the most recent code?
I have a simple Google AppEngine project's source hosted on Google Code and would love if everytime I committed to Subversion, that AppEngine would reflect the latest commi... | Google Code Project Hosting now supports [Post-Commit Web Hooks](http://code.google.com/p/support/wiki/PostCommitWebHooks), which ping a project-owner-specified URL after every commit. This would eliminate the need to regularly poll your Google Code repository. | [Made By Sofa](http://www.madebysofa.com) had a [blog post](http://www.madebysofa.com/#blog/appengine_hosting) about their workflow with Google App Engine. In the second last paragraph they have [attached a subversion hook](http://www.madebysofa.com/media/downloads/appengine_deploy.sh) that when when someone commits co... | Possible to integrate Google AppEngine and Google Code for continuous integration? | [
"",
"python",
"svn",
"google-app-engine",
"continuous-integration",
"google-code",
""
] |
I'm creating a series of builders to clean up the syntax which creates domain classes for my mocks as part of improving our overall unit tests. My builders essentially populate a domain class (such as a `Schedule`) with some values determined by invoking the appropriate `WithXXX` and chaining them together.
I've encou... | All I can say is that if there *is* a way of doing it, I want to know about it too - I use *exactly* this pattern in my [Protocol Buffers port](http://github.com/jskeet/dotnet-protobufs/tree/master). In fact, I'm glad to see that someone else has resorted to it - it means we're at least somewhat likely to be right! | I know this is an old question, but I think you can use a simple cast to avoid the `abstract BLDR This { get; }`
The resulting code would then be:
```
public abstract class BaseBuilder<T, BLDR> where BLDR : BaseBuilder<T, BLDR>
where T : new()
{
public abstract T Build()... | Builder design pattern with inheritance: is there a better way? | [
"",
"c#",
"generics",
"builder",
""
] |
I was recently tasked with debugging a strange problem within an e-commerce application. After an application upgrade the site started to hang from time to time and I was sent in to debug. After checking the event log I found that the SQL-server wrote ~200 000 events in a couple of minutes with the message saying that ... | Are you operating in explicit or implicit [transaction mode](http://doc.ddart.net/mssql/sql70/ta-tz_8.htm)?
Since you're in explicit mode, I think you need to surround the DELETE operation with BEGIN TRANSACTION and COMMIT TRANSACTION statements.
```
WHILE EXISTS (SELECT * FROM ShoppingCartItem WHERE ShoppingCartItem... | ```
FROM
ShoppingCartItem
INNER JOIN
GoodsForSale
on ShoppingCartItem.GFSID = GoodsForSale.GFSID
```
Oops, your join brings the result set down to zero rows.
```
SELECT TOP 1
@TmpGFSID = ShoppingCartItem.GFSID,
@TmpQuantity = ShoppingCartItem.Quantity,
@TmpShoppingCartItemID =
ShoppingC... | While-clause in T-SQL that loops forever | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
I'm busy with an asignment where i have to make a graphical interface for a simple program. But i'm strugling with the layout.
This is the idea:

What is the easiest way to accomplish such a layout?
And what method do you use to make layouts in... | Well considering how simple the layout is I would suggest you use a BorderLayout with NORTH set to the top section in a container and the JTable in the CENTER of the BorderLayout. For the Top it appears to be a simple BorderLayout again with NORTH as the Instruction: south as the black box (possibly in a container with... | > And what method do you use to make layouts in java. Just code it, or use an IDE like netbeans?
NetBeans for GUI developers is like a calculator for grade schoolers: you really shouldn't use it until you know how to do things without it, but then it will save you a lot of time.
(I'd love to answer your primary quest... | Java GUI LayoutManagers | [
"",
"java",
"swing",
"user-interface",
""
] |
I am trying to build a dropdown list for a winform interop, and I am creating the dropdown in code. However, I have a problem getting the data to bind based on the DataTemplate I specify.
What am I missing?
```
drpCreditCardNumberWpf = new ComboBox();
DataTemplate cardLayout = new DataTemplate {DataType = typeof (C... | Assuming that you've already set up the `ItemsSource` etc for `drpCreditCardNumberWpf`...
```
//create the data template
DataTemplate cardLayout = new DataTemplate();
cardLayout.DataType = typeof(CreditCardPayment);
//set up the stack panel
FrameworkElementFactory spFactory = new FrameworkElementFactory(typeof(StackP... | The full version
```
var ms = new MemoryStream(Encoding.UTF8.GetBytes(@"<DataTemplate xmlns=""http://schemas.microsoft.com/winfx/2006/xaml/presentation""
xmlns:x=""http://schemas.microsoft.com/winfx/2006/xaml"" ... | How do I build a DataTemplate in c# code? | [
"",
"c#",
"wpf",
"datatemplate",
""
] |
YAML seems like a great format for configuration files & data binding persistent objects in human-readable form...
Is there a C++ library that handles YAML? Does `Boost::Serialization` have plans for a YAML option?
**EDIT: I would prefer an OO library.** | A quick search gave me this: [yaml-cpp](https://github.com/jbeder/yaml-cpp) | Try the YAML component from the [BOOST vault serialization library](https://github.com/boost-vault/serialization).
**EDIT 2014**: A recent development, <https://groups.google.com/d/msg/boost-devel-archive/mhT7qIh1nsI/uXAuXFAWrxQJ>
**EDIT 2019**: Didn't try it yet, but this seems to be a serious take: <https://github.... | YAML serialization library for C++? | [
"",
"c++",
"serialization",
"yaml",
"persistence",
"boost-serialization",
""
] |
For my web service component, I need to generate a relatively large XML (~500 lines) according to many factors. I am facing a few different choices here:
1. StringBuilder
2. XmlWriter class
3. C# object with serialization???
Which one should I use. Is there any other ways that I am not aware of? | If you populate the XML with data from database, you can generate the whole XML by using SQL query and create a class with a property holds the XML blob. The property type can be XElement. This is the easiest I can think of. | I generate an RSS feed very simply using LINQ to XML. It's the nicest XML API I know of, to be honest.
I have a a couple of extension methods which I use to make it even easier - it converts from an anonymous type to either elements or attributes:
```
public static IEnumerable<XElement> AsXElements(this object sour... | What's the Best way to Generate a Dynamic XML for Web Service? | [
"",
"c#",
".net",
"xml",
""
] |
I've recently created these two (unrelated) methods to replace lots of boiler-plate code in my winforms application. As far as I can tell, they work ok, but I need some reassurance/advice on whether there are some problems I might be missing.
(from memory)
```
static class SafeInvoker
{
//Utility to avoid boiler-... | This is good stuff. Make them extension methods though to clean up your code a little more. For example:
```
//Replaces OnMyEventRaised boiler-plate code
//Usage: SafeInvoker.RaiseEvent(this, MyEventRaised)
public static void Raise(this EventHandler eventToRaise, object sender)
{
EventHandler eventHandler ... | Due to the fact, that Benjol doesn't know, why he places the Action into a MethodInvoker and broccliman meant to use it as an Extension Function, here is the clean up code:
```
static class SafeInvoker
{
//Utility to avoid boiler-plate InvokeRequired code
//Usage: myCtrl.SafeInvoke(() => myCtrl.Enabled = false... | Boiler plate code replacement - is there anything bad about this code? | [
"",
"c#",
"coding-style",
""
] |
I'm not sure how to look for this online... I think they might be called something different in C++
I want to have a simple event system, somthing like
```
event myCustomEvent;
myCustomEvent.subscribe( void myHandler(string) );
myCustomEvent.fire("a custom argument");
// myHandler prints out the string passed in the ... | I use [sigslot](http://sigslot.sourceforge.net/) for exactly this purpose. | Take a look at the boost [signal](http://www.boost.org/doc/libs/1_36_0/doc/html/signals.html) library. Combined with the [function](http://www.boost.org/doc/libs/1_36_0/doc/html/function.html) and [bind](http://www.boost.org/doc/libs/1_36_0/libs/bind/bind.html) libraries, you can do exactly what you are looking for. | Events in C++ | [
"",
"c++",
""
] |
I need to solve a few mathematical equations in my application. Here's a typical example of such an equation:
```
a + b * c - d / e = a
```
Additional rules:
* b % 10 = 0
* b >= 0
* b <= 100
* Each number must be integer
* ...
I would like to get the possible solution sets for a, b, c, d and e.
Are there **any lib... | Solving [linear systems](http://en.wikipedia.org/wiki/Linear_systems) can *generally* be solved using linear programming. I'd recommend taking a look at [Boost uBLAS](http://www.boost.org/doc/libs/1_36_0/libs/numeric/ublas/doc/index.htm) for starters - it has a simple triangular solver. Then you might checkout librarie... | You're venturing into the world of numerical analysis, and here be dragons. Seemingly small differences in specification can make a huge difference in what is the right approach.
I hesitate to make specific suggestions without a fairly precise description of the problem domain. It sounds superficiall like you are solv... | Equation Solvers for linear mathematical equations | [
"",
"c++",
"equation",
"algebra",
"solver",
""
] |
I have topics(id\*) and tags(id\*,name) and a linking table topic\_tags(topicFk\*,tagFk\*).
Now I want to select every single topic, that has all of the good tags (a,b,c) but none of the bad tags (d,e,f).
How do I do that? | My own solution using Pauls and Bills ideas.
The idea is to inner join topics with good tags (to throw out topics with no good tags) and then count the unique tags for each topic (to verify that all the good tags are present).
At the same time an outer join with bad tags should have not a single match (all fields are... | Assuming your Topic\_Tags table is unique, this answers your *exact* question - but may not be generalizable to your actual problem:
```
SELECT
TopicId
FROM Topic_Tags
JOIN Tags ON
Topic_Tags.TagId = Tags.TagId
WHERE
Tags.Name IN ('A', 'B', 'C', 'D', 'E', 'F')
GROUP BY
TopicId
HAVING
COUNT(*) = 3
AND MAX(... | MINUS in MySQL? | [
"",
"sql",
"mysql",
""
] |
I'm stuck with .Net 1.1 application (i.e. I can not use the generics goodies from 2.0 for now), and I was trying to optimize some parts of the code. As it deals a lot with runtime callable wrappers, which need to be released, I ended up to create a utility method which loops until all references are released. The signa... | Why is it better to call a method than to just set the variable to null? They're both single line calls, and the latter is a lot simpler.
It does sound very odd that you need to set them to null in the first place though. Are these static variables, or instance variables whose values need to be released earlier than t... | Sunny, ref and out are a marshalling hints + contract to the compiler. Ref and out are a carryover to COM days - the marshalling hints for objects when sent over the wire / between processes.
The `out` contract
```
void foo( out MyClass x)
```
1. foo() will set `x` to something before it returns.
2. `x` has no value... | Using "ref" and/or "out" for Object type | [
"",
"c#",
".net",
"casting",
"ref",
"out",
""
] |
Is there a way to generate a hash of a string so that the hash itself would be of specific length? I've got a function that generates 41-byte hashes (SHA-1), but I need it to be 33-bytes max (because of certain hardware limitations). If I truncate the 41-byte hash to 33, I'd probably (certainly!) lost the uniqueness.
... | The way hashes are calculated that's unfortunately not possible. To limit the hash length to 33 bytes, you will have to cut it. You could xor the first and last 33 bytes, as that might keep more of the information. But even with 33 bytes you don't have that big a chance of a collision.
md5: <http://www.md5hashing.com/... | > If I truncate the 41-byte hash to 33, I'd probably (certainly!) lost the uniqueness.
What makes you think you've got uniqueness now? Yes, there's clearly a higher chance of collision when you're only playing with 33 bytes instead of 41, but you need to be fully aware that collisions are only ever unlikely, not impos... | Hash of a string to be of specific length | [
"",
"c++",
"algorithm",
"hash",
""
] |
I've introduced visitors as one of core architecture ideas in one of my apps. I have several visitors that operate on a same stuff. Now, how should I test it? Some tests I'm thinking of are a bit larger then a unit test should be (integration test? whatever) but I still wanna do it. How would you test code like the C++... | make a test visitor object and make it visit things.... test that it visited the right things. | Unit testing isn't really about testing patterns, it is about testing the correct implementation of methods and functions. The visitor pattern is a specific class structure, and for each of the classes (ConcreteVisitor and ConcreteElement, specifically) involved you'll want unit tests.
When you've developed confidence... | Unit testing Visitor pattern architecture | [
"",
"c++",
"unit-testing",
"design-patterns",
"visitor-pattern",
""
] |
I have a text file in the root of my web app *<http://localhost/foo.txt>* and I'd like to load it into a variable in javascript.. in groovy I would do this:
```
def fileContents = 'http://localhost/foo.txt'.toURL().text;
println fileContents;
```
How can I get a similar result in javascript? | XMLHttpRequest, i.e. AJAX, without the XML.
The precise manner you do this is dependent on what JavaScript framework you're using, but if we disregard interoperability issues, your code will look something like:
```
var client = new XMLHttpRequest();
client.open('GET', '/foo.txt');
client.onreadystatechange = functio... | ## Update 2019: Using Fetch:
```
fetch('http://localhost/foo.txt')
.then(response => response.text())
.then((data) => {
console.log(data)
})
```
<https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API> | How do I load the contents of a text file into a javascript variable? | [
"",
"javascript",
""
] |
I've got a save dialog box which pops up when i press a button. However i dont want to save a file at that point, i want to take the name and place it in the text box next to the button, for the name to be used later.
Can anybody tell me how to obtain the file path from the save dialog box to use it later? | Here is a sample code I just wrote very fast... instead of Console.Write you can simply store the path in a variable and use it later.
```
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = Convert.ToString(Environment.SpecialFolder.MyDocuments);
saveFileDialog1.Filter = "Your ... | Addressing the textbox...
```
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
this.textBox1.Text = saveFileDialog.FileName;
}
``` | Obtain file path of C# save dialog box | [
"",
"c#",
"dialog",
""
] |
I have a range of random numbers. The range is actually determined by the user but it will be up to 1000 integers. They are placed in this:
```
vector<int> n
```
and the values are inserted like this:
```
srand(1);
for (i = 0; i < n; i++)
v[i] = rand() % n;
```
I'm creating a separate function to find all the no... | In this code:
```
if(i % v[j] == 0)
cout << v[j] << endl;
```
You are testing your index to see if it is divisible by v[j]. I think you meant to do it the other way around, i.e.:
```
if(v[j] % i == 0)
```
Right now, you are printing random divisors of i. You are not printing out random numbers which are known not... | First off, I think Knuth said it first: premature optimization is the cause of many bugs. Make the slow version first, and then figure out how to make it faster.
Second, for your outer loop, you really only need to go to sqrt(n) rather than n. | Finding composite numbers | [
"",
"c++",
"primes",
"sieve",
""
] |
I have some thread-related questions, assuming the following code. Please ignore the possible inefficiency of the code, I'm only interested in the thread part.
```
//code without thread use
public static int getNextPrime(int from) {
int nextPrime = from+1;
boolean superPrime = false;
while(!superPrime) {
... | By putting the join() in the loop, you're starting a thread, then waiting for that thread to stop before running the next one. I think you probably want something more like this:
```
public static void main(String[] args) {
int primeStart = 5;
// Make thread-safe list for adding results to
List list = Collec... | You can test this better by making the exact code in your first example run with threads. Sub your main method with this:
```
private static int currentPrime;
public static void main(String[] args) throws InterruptedException {
for (currentPrime = 0; currentPrime < 10000; currentPrime++) {
Thread t = n... | comparison of code performance, threaded versus non-threaded | [
"",
"java",
"multithreading",
"concurrency",
""
] |
I have a simple Google App Engine app, that I wrote using ordinary strings. I realize I want to make it handle unicode. Are there any gotchas with this? I'm thinking of all the strings that I currently already have in the live database. (From real users who I don't want to upset.) | [Alexander Kojevnikov](https://stackoverflow.com/questions/245094/upgrading-google-application-engine-program-to-use-unicode#245159) said: "The datastore internally keeps all strings in unicode."
In other words, your application is already using unicode everywhere. Thank the google folks for a sensible API. No further... | The datastore internally keeps all strings [in unicode](http://code.google.com/appengine/docs/datastore/typesandpropertyclasses.html#str). | Upgrading Google Application Engine program to use unicode | [
"",
"python",
"google-app-engine",
"unicode",
""
] |
Can dynamic variables in C# 4.0 be members on a class or passed into or returned from methods? var from C# 3.0 couldn't but I haven't seen any mention anywhere of whether it is possible or not with dynamic. | All of the above. I tried them out in the VPC and was able to do all of these. See the ['New Features in C#' document here](http://code.msdn.microsoft.com/csharpfuture) | Yes. There's a big difference between `var` and `dynamic`.
`var` just means "let the compiler infer the real type of the variable".
`dynamic` *is* the type of the variable - so anywhere you can specify a type, you can specify `dynamic` instead, as I understand it. (I'm sure there are some exceptions to this, but that... | New dynamic variable in C# 4.0 | [
"",
"c#",
"c#-4.0",
""
] |
I have a generic list...
public List<ApprovalEventDto> ApprovalEvents
The ApprovalEventDto has
```
public class ApprovalEventDto
{
public string Event { get; set; }
public DateTime EventDate { get; set; }
}
```
How do I sort the list by the event date? | You can use List.Sort() as follows:
```
ApprovalEvents.Sort((lhs, rhs) => (lhs.EventDate.CompareTo(rhs.EventDate)));
``` | ```
using System.Linq;
void List<ApprovalEventDto> sort(List<ApprovalEventDto> list)
{ return list.OrderBy(x => x.EventDate).ToList();
}
``` | How do I sort a generic list? | [
"",
"c#",
"generics",
""
] |
I was just writing some quick code and noticed this complier error
> Using the iteration variable in a lambda expression may have unexpected results.
> Instead, create a local variable within the loop and assign it the value of the iteration variable.
I know what it means and I can easily fix it, not a big deal.
... | Consider this code:
```
List<Action> actions = new List<Action>();
for (int i = 0; i < 10; i++)
{
actions.Add(() => Console.WriteLine(i));
}
foreach (Action action in actions)
{
action();
}
```
What would you expect this to print? The obvious answer is 0...9 - but actually it prints 10, ten times. It's beca... | Assuming you mean C# here.
It's because of the way the compiler implements closures. Using an iteration variable *can* cause a problem with accessing a modified closure (note that I said 'can' not 'will' cause a problem because sometimes it doesn't happen depending on what else is in the method, and sometimes you actu... | Why is it bad to use an iteration variable in a lambda expression | [
"",
"c#",
"vb.net",
"lambda",
"iteration",
"warnings",
""
] |
I have discovered through trial and error that the MATLAB engine function is not completely thread safe.
Does anyone know the rules?
Discovered through trial and error:
On Windows, the connection to MATLAB is via COM, so the COM Apartment threading rules apply. All calls must occur in the same thread, but multiple c... | When I first started using the engine, I didn't run across any documentation on thread safety, so I assumed that it was not thread-safe.
I use a C++ class to synchronize access to an engine instance. For more parallel processing designs, I instantiate multiple instances of the engine class.
(edit) I'm using MATLAB R1... | From the [documentation](http://www.mathworks.com/access/helpdesk/help/techdoc/matlab_external/f29148.html),
> MATLAB libraries are not thread-safe.
> If you create multithreaded
> applications, make sure only one
> thread accesses the engine
> application. | Thread safety of Matlab engine API | [
"",
"c++",
"matlab",
"thread-safety",
"matlab-engine",
""
] |
I'm looking for best practices for performing strict (whitelist) validation/filtering of user-submitted HTML.
Main purpose is to filter out XSS and similar nasties that may be entered via web forms. Secondary purpose is to limit breakage of HTML content entered by non-technical users e.g. via WYSIWYG editor that has a... | I've tested all exploits I know on HTML Purifier and it did very well. It filters not only HTML, but also CSS and URLs.
Once you narrow elements and attributes to innocent ones, the pitfalls are in attribute content – `javascript:` pseudo-URLs (IE allows tab characters in protocol name - `java	script:` still works... | User-submitted HTML isn't always valid, or indeed complete. Browsers will interpret a wide range of invalid HTML and you should make sure you can catch it.
Also be aware of the valid-looking:
```
<img src="http://www.mysite.com/logout" />
```
and
```
<a href="javascript:alert('xss hole');">click</a>
``` | Strict HTML Validation and Filtering in PHP | [
"",
"php",
"html",
"security",
"validation",
"xss",
""
] |
How to create a table with a timestamp column that defaults to `DATETIME('now')`?
Like this:
```
CREATE TABLE test (
id INTEGER PRIMARY KEY AUTOINCREMENT,
t TIMESTAMP DEFAULT DATETIME('now')
);
```
This gives an error. | As of [version 3.1.0](https://www.sqlite.org/releaselog/3_1_0.html) you can use `CURRENT_TIMESTAMP` with the [DEFAULT](https://www.sqlite.org/lang_createtable.html#the_default_clause) clause:
> If the default value of a column is CURRENT\_TIME, CURRENT\_DATE or CURRENT\_TIMESTAMP, then the value used in the new row is... | according to dr. hipp in a recent list post:
```
CREATE TABLE whatever(
....
timestamp DATE DEFAULT (datetime('now','localtime')),
...
);
``` | How to create timestamp column with default value 'now'? | [
"",
"sql",
"sqlite",
""
] |
I've been reading many a tutorial/article on unmanaged DLLs in C++. For the life of me, however, I cannot seem to grasp the concept. I'm easily confused by the seeming disagreement about whether it needs a header file, how to export it, whether I need a .lib file and what have you.
So, let's assume I have just a funct... | I cannot stress this enough, the C++ compiler does not see header files, after the preprocessor is done, there's just one big source file ( also called the compilation unit ). So strictly you don't need a header to export this function from a dll.
What you do need is some form of conditional compilation to export the f... | QBziZ' answer is right enough. See [Unmanaged DLLs in C++](https://stackoverflow.com/questions/236035/unmanaged-dlls-in-c#236052)
To complete it: *In C++, if you need to use a symbol, you must tell the compiler it exists, and often, its prototype*.
In other languages, the compiler will just explore the library on its... | Unmanaged DLLs in C++ | [
"",
"c++",
"dll",
"unmanaged",
""
] |
I am currently porting a lot of code from an MFC-based application to a DLL for client branding purposes.
I've come across an unusual problem. This bit of code is the same in both systems:
```
// ...
CCommsProperties props;
pController->GetProperties( props );
if (props.handshake != HANDSHAKE_RTS_CTS)
... | After Saratv posting, I decided to ditch what I had done and restart it from working source again.
This time however it works...I guess I will never know why passing a structure caused it to change. | It is difficult to see what is wrong from the given code alone. Some general pointers:
1. The object is initialized and processed in different binary modules with incompatible linking (such as C-run times)
2. If the class/structure is shared it is not exported/imported correctly.
3. The class(s) are defined in more th... | Referenced structure not 'sticking' | [
"",
"c++",
"mfc",
""
] |
In C# I could easily write the following:
```
string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;
```
Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement? | In Python 2.5, there is
```
A if C else B
```
which behaves a lot like ?: in C. However, it's frowned upon for two reasons: readability, and the fact that there's usually a simpler way to approach the problem. For instance, in your case:
```
stringValue = otherString or defaultString
``` | @Dan
> ```
> if otherString:
> stringValue = otherString
> else:
> stringValue = defaultString
> ```
>
> This type of code is longer and more expressive, but also more readable
Well yes, it's longer. Not so sure about “more expressive” and “more readable”. At the very least, your claim is disputable. I would ev... | How can I closely achieve ?: from C++/C# in Python? | [
"",
"python",
"syntax",
"ternary-operator",
"syntax-rules",
""
] |
I'd like to open the intelligence window without typing a character and then backspacing it. I can't seem to remember the shortcut for this. What is it? | `Ctrl` + `Space`?
Also, go to [Tools -> Options -> Environment -> Keyboard](https://msdn.microsoft.com/en-us/library/5zwses53.aspx) or [Default Keyboard Shortcuts in Visual Studio](https://msdn.microsoft.com/en-us/library/da5kh0wa.aspx), you can then search for commands and see what is assigned to that (and remap). | `Ctrl` + `Space` for normal Intellisense, and `Ctrl` + `Shift` + `Space` for parameter Intellisense (e.g. to see what overloads are available in a method call which you've actually already filled in). I find the latter very handy :) | What's the default intellisense shortcut in vs2008? | [
"",
"c#",
"visual-studio",
"visual-studio-2008",
"keyboard-shortcuts",
""
] |
I am working on a windows service that polls for a connection to a network enabled devices every 15 seconds. If the service is not able to connect to a device, it throws an exception and tries again in 15 seconds. All of this works great.
But, lets say one of the devices is down for a day or more. I am filling up my e... | One good way to achieve what you need is to employ the Circuit Breaker design pattern.
I first read about this in the book "Release It! Design and Deploy Production Ready Software" by Michael T. Nygard, from the Pragmatic Press, p104-107.
The idea of the circuit breaker is that it sits in the path of the connection b... | Maybe have a workflow that if the polls fails for a certain number of times, the polling interval is increased. e.g. polls every 15 seconds for like 3 times, if it fails then increase the polling interval to one minute, if it fails for n times then increase the time to one hour.
To be honest the workflow above doesnt ... | How do I conditionally suppress application exceptions written to the event log? | [
"",
"c#",
"exception",
"windows-services",
"event-log",
""
] |
**Question**
I have an application written in Java. It is designed to run on a Linux box standalone. I am trying to spawn a new *firefox* window. However, *firefox* never opens. It always has a shell exit code of 1. I can run this same code with *gnome-terminal* and it opens fine.
**Background**
So, here is its init... | after having read the various answers and various comments(from questioner), here's what I would do
1) try this java approach
<http://java.sun.com/j2se/1.5.0/docs/api/java/lang/ProcessBuilder.html>
```
ProcessBuilder pb = new ProcessBuilder("myCommand", "myArg1", "myArg2");
Map<String, String> env = pb.environment();... | If you can narrow it down to Java 6, you can use the desktop API:
<http://java.sun.com/developer/technicalArticles/J2SE/Desktop/javase6/desktop_api/>
Should look something like:
```
if (Desktop.isDesktopSupported()) {
Desktop desktop = Desktop.getDesktop();
if (desktop.isSupported(Desktop.Action.... | Open Browser window from Java program | [
"",
"java",
"linux",
"browser",
"x11",
"daemon",
""
] |
I have a Spring MVC web app which uses Spring Security. I want to know the username of the currently logged in user. I'm using the code snippet given below . Is this the accepted way?
I don't like having a call to a static method inside this controller - that defeats the whole purpose of Spring, IMHO. Is there a way t... | If you are using [Spring 3](http://static.springsource.org/spring/docs/3.0.x/spring-framework-reference/html/mvc.html#mvc-ann-requestmapping-arguments), the easiest way is:
```
@RequestMapping(method = RequestMethod.GET)
public ModelAndView showResults(final HttpServletRequest request, Principal principal) {
... | A lot has changed in the Spring world since this question was answered. Spring has simplified getting the current user in a controller. For other beans, Spring has adopted the suggestions of the author and simplified the injection of 'SecurityContextHolder'. More details are in the comments.
---
This is the solution ... | When using Spring Security, what is the proper way to obtain current username (i.e. SecurityContext) information in a bean? | [
"",
"java",
"spring",
"spring-mvc",
"spring-security",
""
] |
I often use Dictionary in C#2.0 with the first key as string that was containing a unique identifier.
I am learning C#3.0+ and it seems that I can now simply use a List and simply do LINQ on that object to get the specific object (with the .where()).
So, if I understand well, the Dictionary class has lost its purpose... | no, a dictionary is still more efficient for getting things back out given a key.
a list you still have to iterate through the list to find what you want. A dictionary does a lookup. | If you just have a List, then doing an LINQ select will scan through every item in the list comparing it against the one you are looking for.
The Dictionary however computes a hash code of the string you are looking for (returned by the GetHashCode method). This value is then used to look up the string more efficientl... | Dictionary<string, MyObject> or List<MyObject> with C# 3.5? | [
"",
"c#",
".net",
"collections",
"c#-3.0",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.