Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have a .ini file with sensitive information in my php wab app. I denied access to it using a .htaccess file:
```
<files my.ini>
order deny,allow
deny from all
</files>
```
I don't have access to folders outside of htdocs, so I can't move the .ini file out of browsable territory.
Is my solution safe? | The .htaccess will block access from the web. However, if you're using a shared hosting environment, it might be possible for other users to access your ini. If its on a (virtual private) server and you're the only user for that server you're safe.
In case of shared hosting it depends on server configuration.
For more... | Another good solution and my personal favourite (especially when developing code that might not remain under my stringent .htaccess control) is securing the actual .ini file. Thanks to a kind soul [here - user notes: pd at frozen-bits dot de](http://php.net/manual/en/function.parse-ini-file.php), what I do is:
```
my.... | Is it safe to deny access to .ini file in .htaccess? | [
"",
"php",
".htaccess",
""
] |
When browsing ASP.NET MVC source code in [codeplex](http://www.codeplex.com/aspnet/SourceControl/FileView.aspx?itemId=266503&changeSetId=17272), I found it is common to have a class explicitly implementing interface. The explicitly implemented method/property then invoke another "protected virtual" method/property with... | Well, not specific to MVC, but this approach allows you to **keep the core public API clean**. It is also useful if there is ever a risk of different interfaces / etc having the same name & signature, but different meaning. In reality this is rare.
It also allows you to provide an implementation where you want the ret... | If a class implements `IFoo.Bar` explicitly, and a derived class needs `IFoo.Bar` to do something different, there will be no way for the derived class to call the base-class implementation of that method. A derived class which does not re-implement `IFoo.Bar` could call the base-class implementation via `((IFoo)this).... | Why to Use Explicit Interface Implementation To Invoke a Protected Method? | [
"",
"c#",
"interface",
"implicit",
"explicit-interface",
""
] |
I'm creating a CSS editor and am trying to create a regular expression that can get data from a CSS document. This regex works if I have one property but I can't get it to work for all properties. I'm using preg/perl syntax in PHP.
### Regex
```
(?<selector>[A-Za-z]+[\s]*)[\s]*{[\s]*((?<properties>[A-Za-z0-9-_]+)[\s]... | That just seems too convoluted for a single regular expression. Well, I'm sure that with the right extentions, an advanced user could create the right regex. But then you'd need an even more advanced user to debug it.
Instead, I'd suggest using a regex to pull out the pieces, and then tokenising each piece separately.... | You are trying to pull structure out of the data, and not just individual values. Regular expressions might could be painfully stretched to do the job, but you are really entering parser territory, and should be pulling out the big guns, namely parsers.
I have never used the PHP parser generating tools, but they look ... | Parsing CSS by regex | [
"",
"php",
"css",
"regex",
"css-parsing",
""
] |
I've almost completely installed Boost, but I have a problem with how to set my path to Boost in *Tools->options->projects->VC++ Directories*.
I've written the path to include files and libraries (my folder contains two subfolders, `lib` and `include`), but when I try to use Boost with
`#include boost/regex.hpp`, I go... | Use the [Boost Installer](http://www.boostpro.com/download/) by the Boost consulting group. | You might be interested in the Visual Studio 2008 Feature pack. It adds many of the features that have only been available from Boost until now, the features that are part of the C++ TR1. | how to install boost to the VS 2008? | [
"",
"c++",
"visual-studio-2008",
"boost",
"installation",
""
] |
Is there a better way to do the following:
```
$array = array('test1', 'test2', 'test3', 'test4', 'test5');
// do a bunch of other stuff, probably a loop
$array[] = 'test6';
end($array);
echo key($array); // gives me 6
```
This will give the key of the most recently add array element.
Is there a better way to do thi... | You could also do:
```
$end = end(array_keys($array));
```
But I think your way makes it clear what you want to do, so you could whip something up like:
```
function array_last_key($array) {
end($array);
return key($array);
}
```
That's about it. | Simply put no. Both end and key are Big O(1) time. Any other way slows your code down and adds complexity. | What is the best method of getting the key of the last added array item in PHP? | [
"",
"php",
"arrays",
"key",
""
] |
I am parsing an input text file. If I grab the input one line at a time using getline(), is there a way that I can search through the string to get an integer? I was thinking something similar to getNextInt() in Java.
I know there has to be 2 numbers in that input line; however, these values will be separated by one o... | If the only thing in there is whitespace and integers, just try something like this:
```
int i1, i2;
stringstream ss(lineFromGetLine);
ss >> i1 >> i2;
```
or easier:
```
int i1, i2;
theFileStream >> i1 >> i2;
``` | There are a couple of things to consider:
Lets assume you have two numbers on each line followed by text you don't care about.
```
while(inFile >> rows >> columns)
{
// Successfully read rows and columns
// Now remove the extra stuff on the line you do not want.
inFile.ignore( std::numeric_limits<std::s... | Parsing integers from a line | [
"",
"c++",
"string",
"parsing",
""
] |
I'm trying to create a POST request, unfortunately the body of the POST never seems to be sent.
Below is the code that I'm using. The code is invoked when a user clicks on a link, not a form "submit" button. It runs without error, invokes the servlet that is being called but, as I mentioned earlier, the body of the PO... | These are the kind of situations where Firebug and Firefox are really helpful. I suggest you install Firebug if you don't have it and check the request that is being sent.
You also definitely need to stick to `parameters` instead of `requestBody`.
This:
```
new Ajax.Request(sURL,
{
method: 'POST',
parameters... | Simply pass the data as **`parameters`** to the Ajax Request constructor:
```
new Ajax.Request(url, {
method: 'POST',
parameters: {
hello: "world", test: "test"
},
onSuccess: function(transport){
var data = transport.responseText.evalJSON();
}
});
``` | AJAX.Request POST body not send | [
"",
"javascript",
"post",
"prototypejs",
""
] |
Please one library per answer so that people can vote for the individually. | [Calendar Date Select](http://code.google.com/p/calendardateselect/) | [Timeframe](http://stephencelis.com/projects/timeframe) for visual selection of date ranges... | What's your favorite Prototype framework compatible, javascript date picker? | [
"",
"javascript",
"ruby-on-rails",
"user-interface",
""
] |
I have an interesting problem and would appreciate your thoughts for the best solution.
I need to parse a set of logs. The logs are produced by a multi-threaded program and a single process cycle produces several lines of logs.
When parsing these logs I need to pull out specific pieces of information from each process... | It sounds like there are some existing parser classes already in use that you wish to leverage. In this scenario, I would write a [decorator](http://en.wikipedia.org/wiki/Decorator_pattern) for the parser which strips out lines not associated with the process you are monitoring.
It sounds like your classes might look ... | I would write a simple distributor that reads the log file line by line and stores them in different VirtualLog objects in memory -- a VirtualLog being a kind of virtual file, actually just a String or something that the existing parsers can be applied to. The VirtualLogs are stored in a Map with the process ID (PID) a... | How to parse logs written by multiple threads? | [
"",
"java",
"regex",
"multithreading",
"inheritance",
"parsing",
""
] |
I'm not the best at PHP and would be extremely grateful if somebody could help. Basically I need to parse each line of a datafeed and just get each bit of information between each "|" - then I can add it to a database. I think I can handle getting the information from between the "|"'s by using explode but I need a bit... | You can read a file into an array of lines and do all the splitting with:
```
$lines = file("filename");
foreach($lines as $line) {
$parts = explode("|", $line);
// do the database inserts here
}
```
If you already have all the text in a variable as you said (e.g., with something like file\_get\_contents() ),... | If you are reading out of your textarea post, you can use the explode function using the newline character as your separator to get each "line" in the variable as a new element of an array, then you can do explode on your array elements.
i.e.
```
$sometext = "balh | balh blah| more blah \n extra balh |some blah |this... | Parsing A Data Feed | [
"",
"php",
"database",
"parsing",
"explode",
"datafeed",
""
] |
I am having a peculiar problem with the order in which FlowLayoutPanels are added in to the form's **controls** property. This is what I tried,
I added 7 FlowLayoutPanels in to a C# window application from left to right in vertical strips. Then I tagged the flow layouts as 1, 2, 3, ... 7 again from left to right. Now ... | look at the order in which they are added to the form in the yourForm.designer.cs | I know this is quite an old question, but...
You might want to use `SetChildIndex`. e.g. `this.Controls.SetChildIndex(button1, 0);` | Order of controls in a form's Control property in C# | [
"",
"c#",
"winforms",
"user-interface",
"controls",
""
] |
I could do this in C#..
```
int number = 2;
string str = "Hello " + number + " world";
```
..and str ends up as "Hello 2 world".
In VB.NET i could do this..
```
Dim number As Integer = 2
Dim str As String = "Hello " + number + " world"
```
..but I get an InvalidCastException "Conversion from string "Hello " to typ... | In VB I believe the string concatenation operator is & rather than + so try this:
```
Dim number As Integer = 2
Dim str As String = "Hello " & number & " world"
```
Basically when VB sees + I suspect it tries do numeric addition or use the addition operator defined in a type (or no doubt other more complicated things... | Visual Basic makes a distinction between the `+` and `&` operators. The `&` will make the conversion to a string if an expression is not a string.
[`&`Operator (Visual Basic)](http://msdn.microsoft.com/en-us/library/wfx50zyk.aspx)
The `+` operator uses more complex evaluation logic to determine what to make the final... | Automatic casting to string in C# and VB.NET | [
"",
"c#",
"vb.net",
"casting",
""
] |
Sometimes when I am debugging code in Eclipse it happens that although I can see and inspect class member variables without any difficulty I am unable to inspect the values of variables declared locally within functions. As an aside, any parameters to the current function lose their 'real' names and instead one sees th... | Apparently, the [answer](http://dev.eclipse.org/newslists/news.eclipse.platform/msg56943.html) is:
> the rt.jar that ships with the JDK (where the core Java classes live) is not compiled with full debug information included in the .class files, so the debugger does not have local variable info.
>
> Unfortunately, this... | It [used to be](http://forums.java.net/jive/thread.jspa?messageID=10811&tstart=0) that you can get debug rt.jar from http: //download.java.net/jdk6/binaries/, but not any more.
So [building your own rt.jar with -g](http://www.javalobby.org/java/forums/t103334.html) seems to be the only option now. It's very simple: ju... | Locally declared variables can not be inspected | [
"",
"java",
"eclipse",
"debugging",
""
] |
I use `x != null` to avoid [`NullPointerException`](https://docs.oracle.com/javase/9/docs/api/java/lang/NullPointerException.html). Is there an alternative?
```
if (x != null) {
// ...
}
``` | This to me sounds like a reasonably common problem that junior to intermediate developers tend to face at some point: they either don't know or don't trust the contracts they are participating in and defensively overcheck for nulls. Additionally, when writing their own code, they tend to rely on returning nulls to indi... | If you use (or planning to use) a Java IDE like [JetBrains IntelliJ IDEA](https://www.jetbrains.com/idea/), [Eclipse](https://www.eclipse.org/) or [Netbeans](https://netbeans.org/) or a tool like findbugs then you can use annotations to solve this problem.
Basically, you've got `@Nullable` and `@NotNull`.
You can use... | How do I avoid checking for nulls in Java? | [
"",
"java",
"nullpointerexception",
"null",
""
] |
There is an application with an extensive object graph. This graph mainly consists of a set of subgraphs which are connected to the rest of the graph through the only reference. But internally each such subgraph has some number of cross-references among objects. Once in a while such a sub graph needs to be thrown away.... | As stated in this [SO question](https://stackoverflow.com/questions/176745/circular-references-in-java), circular reference is well managed.
Java does not do reference counting, it does uses [tracing garbage collection](https://en.wikipedia.org/wiki/Tracing_garbage_collection) (for example mark-and-sweep, copying coll... | Yes - the garbage collector can cope with circular references etc. | Cross-references and garbage collection | [
"",
"java",
""
] |
I need to search a string in the string array. I dont want to use any for looping in it
```
string [] arr = {"One","Two","Three"};
string theString = "One"
```
I need to check whether theString variable is present in arr. | Every method, mentioned earlier does looping either internally or externally, so it is not really important how to implement it. Here another example of finding all references of target string
```
string [] arr = {"One","Two","Three"};
var target = "One";
var results = Array.FindAll(arr, s => s.Eq... | Well, something is going to have to look, and looping is more efficient than recursion (since tail-end recursion isn't fully implemented)... so if you just don't want to loop yourself, then either of:
```
bool has = arr.Contains(var); // .NET 3.5
```
or
```
bool has = Array.IndexOf(arr, var) >= 0;
```
For info: **a... | How to search a string in String array | [
"",
"c#",
"asp.net",
""
] |
I have the following interface:
```
internal interface IRelativeTo<T> where T : IObject
{
T getRelativeTo();
void setRelativeTo(T relativeTo);
}
```
and a bunch of classes that (should) implement it, such as:
```
public class AdminRateShift : IObject, IRelativeTo<AdminRateShift>
{
AdminRateShift getRelat... | If I understand the question, then the most common approach would be to declare a non-generic base-interface, i.e.
```
internal interface IRelativeTo
{
object getRelativeTo(); // or maybe something else non-generic
void setRelativeTo(object relativeTo);
}
internal interface IRelativeTo<T> : IRelativeTo
whe... | unfortunately inheritance doesn't work with generics. If your function expects IRelativeTo, you can make the function generic as well:
```
void MyFunction<T>(IRelativeTo<T> sth) where T : IObject
{}
```
If I remember correctly, when you use the function above you don't even need to specify the type, the compiler shou... | Casting an object to a generic interface | [
"",
"c#",
"generics",
"interface",
"casting",
""
] |
Using Java, how can I test that a URL is contactable, and returns a valid response?
```
http://stackoverflow.com/about
``` | The solution as a unit test:
```
public void testURL() throws Exception {
String strUrl = "http://stackoverflow.com/about";
try {
URL url = new URL(strUrl);
HttpURLConnection urlConn = (HttpURLConnection) url.openConnection();
urlConn.connect();
assertEquals(HttpURLConnection.... | Since java 5 if i recall, the InetAdress class contains a method called isReachable(); so you can use it to make a ping implementation in java. You can also specify a timeout for this method. This is just another alternative to the unit test method posted above, which is probably more efficient. | How can I programmatically test an HTTP connection? | [
"",
"java",
"http",
"url",
"httpconnection",
""
] |
> **EDIT**: This question duplicates [How to access the current Subversion build number?](https://stackoverflow.com/questions/110175/how-to-access-the-current-subversion-build-number#111173) (Thanks for the heads up, Charles!)
Hi there,
This question is similar to [Getting the subversion repository number into code](... | There is a command called `svnversion` which comes with subversion and is meant to solve exactly that kind of problem. | Stolen directly from django:
```
def get_svn_revision(path=None):
rev = None
if path is None:
path = MODULE.__path__[0]
entries_path = '%s/.svn/entries' % path
if os.path.exists(entries_path):
entries = open(entries_path, 'r').read()
# Versions >= 7 of the entries file are flat... | How does one add a svn repository build number to Python code? | [
"",
"python",
"svn",
""
] |
You can pass a function pointer, function object (or boost lambda) to std::sort to define a strict weak ordering of the elements of the container you want sorted.
However, sometimes (enough that I've hit this several times), you want to be able to chain "primitive" comparisons.
A trivial example would be if you were ... | You could build a little chaining system like so:
```
struct Type {
string first, last;
int age;
};
struct CmpFirst {
bool operator () (const Type& lhs, const Type& rhs) { return lhs.first < rhs.first; }
};
struct CmpLast {
bool operator () (const Type& lhs, const Type& rhs) { return lhs.last < rhs.last; }
}... | One conventional way to handle this is to sort in multiple passes and use a stable sort. Notice that `std::sort` is generally *not* stable. However, there’s `std::stable_sort`.
That said, I would write a wrapper around functors that return a tristate (representing less, equals, greater). | Chaining of ordering predicates (e.g. for std::sort) | [
"",
"c++",
"stl",
"sorting",
"compare",
"predicate",
""
] |
Say I have the following interface that I want to share between my server (a regular web service) and my client (a silverlight 2.0 application):
```
public interface ICustomerService
{
Customer GetCustomer(string name);
}
```
My web service implements this interface, and references a class library where `Customer... | I think you will find this [thread](http://silverlight.net/forums/t/34368.aspx) interesting. You can share code files between separate projects or compile a single project against multiple targets. | I could be wrong, but I think if you decorate objects being returned by your WCF Service with the DataContract and DataMember attributes, you should be able to share objects between your Silverlight application and WCF service without creating the class in your client (should be handled by the proxy. | Sharing service interfaces and model in Silverlight, using WCF | [
"",
"c#",
".net",
"wcf",
"silverlight",
""
] |
> **Possible Duplicate:**
> [Why does C# not provide the C++ style ‘friend’ keyword?](https://stackoverflow.com/questions/203616/why-does-c-sharp-not-provide-the-c-style-friend-keyword)
I'd like the private member variables of a class to be accessible to a Tester class without exposing them to other classes.
In C++... | There's no direct equivalent of "friend" - the closest that's available (and it isn't very close) is [InternalsVisibleTo](http://msdn.microsoft.com/en-us/library/system.runtime.compilerservices.internalsvisibletoattribute.aspx). I've only ever used this attribute for testing - where it's very handy!
**Example:** To be... | The closest equivalent is to create a nested class which will be able to access the outer class' private members. Something like this:
```
class Outer
{
class Inner
{
// This class can access Outer's private members
}
}
```
or if you prefer to put the Inner class in another file:
```
Outer.cs
part... | What is the C# equivalent of friend? | [
"",
"c#",
"encapsulation",
"friend",
""
] |
In c#, is there any difference in the excecution speed for the order in which you state the condition?
```
if (null != variable) ...
if (variable != null) ...
```
Since recently, I saw the first one quite often, and it caught my attention since I was used to the second one.
If there is no difference, what is the adv... | It's a hold-over from C. In C, if you either use a bad compiler or don't have warnings turned up high enough, this will compile with no warning whatsoever (and is indeed legal code):
```
// Probably wrong
if (x = 5)
```
when you actually probably meant
```
if (x == 5)
```
You can work around this in C by doing:
``... | Like everybody already noted it comes more or less from the C language where you could get false code if you accidentally forget the second equals sign. But there is another reason that also matches C#: Readability.
Just take this simple example:
```
if(someVariableThatShouldBeChecked != null
&& anotherOne != null... | Why does one often see "null != variable" instead of "variable != null" in C#? | [
"",
"c#",
"coding-style",
""
] |
Here's my problem: I have a virtual method defined in a .h file that I want to call in a class that inherits from the base class. Sadly though, the method in the derived class doesn't get called. Is there a better way to implement what I'm trying to do?
```
#ifndef ofxBASE_SND_OBJ
#define ofxBASE_SND_OBJ
#include "of... | Change this line:
```
string ofxSndObj::createFilter(ofxBaseSndObj obj)
```
to
```
string ofxSndObj::createFilter(ofxBaseSndObj& obj)
```
What you are doing is passing by value (passing a copy).
This means you are copying the object to the function. Because the function does not know what type you are actually pas... | You need to pass the instance to createFilter as a **pointer** (or reference) to the object. You are [passing by value](http://cplus.about.com/od/glossar1/g/passbyvaldefn.htm), and this causes the compiler to copy the derived object you use as an argument into an instance of the base class. When it does this you lose t... | Inheritance in C++ | [
"",
"c++",
"oop",
"inheritance",
""
] |
I'm trying to delete a directory that contains XML files from a remote computer. My code compiles and runs fine, but when I go to get a list of XML files in the path I specify, it is not returning anything. Am I missing something permission wise?
I have ran it from my computer logged on as myself and from another comp... | I think you should be using \*.xml instead of simply .xml. But I also concur with Kyralessa, test on your local machine first, then add in the complexity of going across a network. | in DeleteFiles, you have the following line:
fi = di.GetFiles(ext);
where ext is the extension you pass in, which I believe is just '.xml'. Get files is looking for any files called '.xml'. GetFiles takes wildcards, which I believe is what you are intending to do. Put an asterisk (\*) at the front and give that a try... | Delete files from remote computer | [
"",
"c#",
"windows",
"file-io",
"permissions",
""
] |
I launch the following command line (process) from a Windows VC++ 6 program using CreateProcess (or \_spawnv()):
* java -cp c:\dir\updates.jar;c:\dir\main.jar Main
and class updates in updates.jar (overiding some in main.jar) are not read or found. It is as if the updates.jar library cannot be found or read.
If I la... | Try using Microsoft's FileMon utility to figure out what's happening. Set the include filter to "updates" to focus in on the problem.
<http://technet.microsoft.com/en-us/sysinternals/bb896642.aspx> | Thanks **jdigital**!
I tried FileMon and it showed me what I was doing wrong. The executable calling CreateProcess() had an unclosed file handle to updates.jar from an attempt to copy the update JAR earlier. Bad code that works in the production environment, but not in the test environment. | JVM Launched via CreateProcess() Loses Classpath Library | [
"",
"java",
"windows",
"process",
"jvm",
"classpath",
""
] |
How do you automate [integration testing](http://en.wikipedia.org/wiki/Integration_testing)? I use JUnit for some of these tests. This is one of the solutions or is totally wrong? What do you suggest? | JUnit works. There are no limitations that restrict it to being unit tests only. We use JUnit, Maven and CruiseControl to do CI.
There may be tools that are specific for integration testing, but I would think their usefulness is dependent on what type of system components you are integrating. JUnit will work fine for ... | I've used JUnit for doing a lot of integration testing. Integration testing can, of course, mean many different things. For more system level integration tests, I prefer to let scripts drive my testing process from outside.
Here's an approach that works well for me for applications that use http and databases and I wa... | Can we use JUNIT for Automated Integration Testing? | [
"",
"java",
"unit-testing",
"integration-testing",
""
] |
Is there a way to pass null arguments to C# methods (something like null arguments in c++)?
For example:
Is it possible to translate the following c++ function to C# method:
```
private void Example(int* arg1, int* arg2)
{
if(arg1 == null)
{
//do something
}
if(arg2 == null)
{
//d... | Yes. There are two kinds of types in .NET: reference types and value types.
References types (generally classes) are always referred to by references, so they support null without any extra work. This means that if a variable's type is a reference type, the variable is automatically a reference.
Value types (e.g. int... | I think the nearest C# equivalent to `int*` would be `ref int?`. Because `ref int?` allows the called method to pass a value back to the calling method.
`int*`
* Can be null.
* Can be non-null and point to an integer value.
* ***If not null, value can be changed***, and the change propagates to the caller.
* ***Setti... | Passing null arguments to C# methods | [
"",
"c#",
"methods",
"null",
""
] |
For debugging purposes, I need to recursively search a directory for all files which start with a UTF-8 byte order mark (BOM). My current solution is a simple shell script:
```
find -type f |
while read file
do
if [ "`head -c 3 -- "$file"`" == $'\xef\xbb\xbf' ]
then
echo "found BOM in: $file"
fi
do... | What about this one simple command which not just finds but clears the nasty BOM? :)
```
find . -type f -exec sed '1s/^\xEF\xBB\xBF//' -i {} \;
```
I love "find" :)
**Warning** The above will **modify** binary files which contain those three characters.
If you want just to show BOM files, use this one:
```
grep -r... | The best and easiest way to do this on Windows:
[Total Commander](https://en.wikipedia.org/wiki/Total_Commander) → go to project's root dir → find files (`Alt` + `F7`) → file types \*.\* → Find text "EF BB BF" → check 'Hex' checkbox → search
And you get the list :) | Elegant way to search for UTF-8 files with BOM? | [
"",
"php",
"utf-8",
"shell",
"text-editor",
""
] |
Looking for code samples to access a memory map file in C# | Looks like C# 4.0 will have MemoryMappedFile support in the library | You can take a look at [this CodeProject article](http://www.codeproject.com/KB/recipes/MemoryMappedGenericArray.aspx) which shows a simple array over MMF implementation using [Winterdom's FileMap library](http://www.winterdom.com/dev/dotnet/index.html) - basically a wrapper around the Win32 APIs for memory mapped file... | C# accessing memory map file | [
"",
"c#",
"memory",
""
] |
I've got a Java application that I'm writing an installer for. We're using the AdvancedInstaller program to create our installer (well, we're evaluating it currently, but will definitely purchase a license soon), and although it has special support for Java applications, it is geared more towards repackaging them as de... | I agree with [bdumitriu's answer](https://stackoverflow.com/questions/271596/how-do-i-properly-repackage-the-jre-installer-in-my-installer#271622):
a simple zip of a jre is enough, unless you want to link that jre to:
* default java (meaning you must add java.exe of the unzipped jre to the path, before any other java... | I have not idea if this is "the way" to do it, but confronted with a somewhat similar problem, we simply archive an *installed* JRE with the rest of our application files and make sure that all our start scripts don't use `java ...`, but rather `..\..\jre\bin\java ...` or similar. The JRE is unpackaged as part of our i... | How do I properly repackage the JRE installer in my installer? | [
"",
"java",
"installation",
""
] |
Given two absolute paths, e.g.
```
/var/data/stuff/xyz.dat
/var/data
```
How can one create a relative path that uses the second path as its base? In the example above, the result should be: `./stuff/xyz.dat` | It's a little roundabout, but why not use URI? It has a relativize method which does all the necessary checks for you.
```
String path = "/var/data/stuff/xyz.dat";
String base = "/var/data";
String relative = new File(base).toURI().relativize(new File(path).toURI()).getPath();
// relative == "stuff/xyz.dat"
```
Pleas... | Since Java 7 you can use the [relativize](http://docs.oracle.com/javase/7/docs/api/java/nio/file/Path.html#relativize%28java.nio.file.Path%29) method:
```
import java.nio.file.Path;
import java.nio.file.Paths;
public class Test {
public static void main(String[] args) {
Path pathAbsolute = Paths.get("/v... | How to construct a relative path in Java from two absolute paths (or URLs)? | [
"",
"java",
"url",
"file",
"path",
""
] |
I believe the following VB.Net code is the equivalent of the proceeding C# code; however the VB.Net test fails - the event handling Lambda is never called.
What is going on?
VB.Net version - fails:
```
<TestFixture()> _
Public Class TestClass
<Test()> _
Public Sub EventTest()
Dim eventClass As New Ev... | > **Note:** This relates to older versions of VB.net Prior to Visual Studio 2010 and VB.net 10
The difference is that in VB.Net a lambda expression must return a value i.e. they must be functions not subs. The lambda expression `eventRaised = true` is being interpreted as a boolean expression rather than an assignment... | For those finding this question now: since Visual Basic 2010 (VB 10.0), anonymous `Sub`s do work, so you can write something like:
```
Sub() eventRaised = True
``` | How to declare lambda event handlers in VB.Net? | [
"",
"c#",
"vb.net",
"unit-testing",
"events",
"lambda",
""
] |
I have written a web app in PHP which makes use of Ajax requests (made using YUI.util.Connect.asyncRequest).
Most of the time, this works fine. The request is sent with an **X-Requested-With** value of **XMLHttpRequest**. My PHP controller code uses apache\_request\_headers() to check whether an incoming request is Aj... | I'm not sure why the apache\_request\_headers() and firebug mismatching, but in order to read request headers you can use the $\_SERVER super global
each header that is being sent by a client (and it doesn't matter how is the client) will arrive to the $*SERVER array.
The key of that header will be with HTTP* prefix, ... | For future reference of those coming across this question, the "intermittent" may be due to a redirect happening server-side. If a 302 redirect occurs the X-Requested-With header isn't passed along even though it's been sent in the original request. This may have been the original cause of the problem. | PHP apache_request_headers() diagrees with reality (as confirmed by Firebug): why? | [
"",
"php",
"ajax",
"http-headers",
"firebug",
""
] |
Does anyone know how to use the [Raw Input](http://msdn.microsoft.com/en-us/library/ms645543(VS.85).aspx) facility on Windows from a WX Python application?
What I need to do is be able to differentiate the input from multiple keyboards. So if there is another way to achieving that, that would work too. | Have you tried using ctypes?
```
>>> import ctypes
>>> ctypes.windll.user32.RegisterRawInputDevices
<_FuncPtr object at 0x01FCFDC8>
```
It would be a little work setting up the Python version of the necessary structures, but you may be able to query the Win32 API directly this way without going through wxPython. | Theres a nice looking library here
<http://code.google.com/p/pymultimouse/>
It's not wx-python specific - but it does use raw input in python with ctypes (and worked in my test with 2 mice) | WX Python and Raw Input on Windows (WM_INPUT) | [
"",
"python",
"windows",
"wxpython",
"raw-input",
""
] |
Some databases support commands such as:
```
SELECT TOP 10 START AT 10 * FROM <TABLE>
```
Essentially I need to pull the first 10 records, then the next 10, then the next 10 etc. Maybe there is another way to do this but in the past I've done it like the above for databases that support 'START AT'. | Which version of SQL Server?
In SQL Server 2000 this is a real pain (though possible using ugly tricks like that posted by stingyjack).
In 2005 and later it's a little easier- look at the [Row\_Number()](http://msdn.microsoft.com/en-us/library/ms186734.aspx) function.
And, depending on your client application it may... | For [SQL Server 2012](http://msdn.microsoft.com/en-us/library/ms188385%28v=SQL.110%29.aspx)
```
SELECT *
FROM <TABLE>
ORDER BY <SomeCol>
OFFSET 10 ROWS
FETCH NEXT 10 ROWS ONLY;
``` | Is there a 'START AT' equivalent in MS-SQL? | [
"",
"sql",
"sql-server",
""
] |
Help!
I have a PHP (PHP 5.2.5) script on HOST1 trying to connect to an MySql database HOST2. Both hosts are in Shared Host environments controlled through CPanel.
HOST2 is set to allow remote database connections from HOST1.
The PHP connect I'm using is:-
$h2 = IPADDRESS;
$dbu = DBUSER;
$dbp = DBPASS;
```
$DBlink =... | somestring is probably the reverse-lookup for your web-server.
Can you modify privileges from your cPanel? Have you done anything to allow access from your workstation (ODBC)?
The error-message seems to indicate that you have network-access to the mysql-server, but not privileges for your username from that specific ... | * Have you read the MySQL documentation on [Causes of Access denied Errors](http://dev.mysql.com/doc/refman/5.0/en/access-denied.html)?
* Have you contacted support for your hosting provider? They should have access to troubleshoot the database connection. People on the internet do not have access.
* Do you need to spe... | php access to remote database | [
"",
"php",
"mysql",
""
] |
There's a lot to C# & ASP.net. Where should I start? What should I not bother focusing on?
Should I learn Winforms then WPF? Ditto for webforms / Silverlight?
Should I learn ASP.MVC or classic ASP.NET? If both, which first?
In the either/or cases - which will make more sense having known the other first?
What major ... | I had the same question when I moved from Classic ASP to .NET 2.0... .NET is huge: so where should I start?
What i did was put my hand dirty and started slow, take a project (in my case was a **very important project** - a finance web app that would cover and automatize all 4 persons work) and start to implement, ever... | What do you want to write? If you want to write a Windows client-side app, look into WinForms and WPF (no real need to learn WinForms before WPF, other than the way that a lot of tutorials/books will probably compare WPF concepts with WinForms concepts). If you're looking at a web app, then ASP.NET or ASP.MVC - I don't... | Learning C#, ASP.NET 3.5 - what order should I learn in / what to skip? | [
"",
"c#",
".net",
"asp.net",
""
] |
I am instantiating a local COM server using CoCreateInstance. Sometimes the application providing the server takes a long time to start. When this happens, Windows pops a dialog box like this:
**Server Busy**
The action cannot be completed because the other program is busy. Choose 'Switch To' to activate the busy pro... | If you're using MFC, we used to do stuff like this:
```
// prevent the damned "Server Busy" dialog.
AfxOleGetMessageFilter()->EnableBusyDialog(0);
AfxOleGetMessageFilter()->EnableNotRespondingDialog(0);
``` | Have a look at `IMessageFilter` and `CoRegisterMessageFilter`. | Set OLE Request Timeout from C++ | [
"",
"c++",
"com",
"ole",
""
] |
We have a couple of applications running on Java 5 and would like now to bring in an application based on Java 6. Can both java versions live together under Windows?
Is there any control panel to set the appropriate Java version for different applications, or any other way to set up, what version of Java will be used ... | Of course you can use multiple versions of Java under Windows. And different applications can use different Java versions. How is your application started? Usually you will have a batch file where there is something like
```
java ...
```
This will search the Java executable using the PATH variable. So if Java 5 is fi... | I was appalled at the clumsiness of the CLASSPATH, JAVA\_HOME, and PATH ideas, in Windows, to keep track of Java files. I got here, because of multiple JREs, and how to content with it. Without regurgitating information, from a guy much more clever than me, I would rather point to to his article on this issue, which fo... | Multiple Java versions running concurrently under Windows | [
"",
"java",
""
] |
My requirement is I have server J2EE web application and client J2EE web application. Sometimes client can go offline. When client comes online he should be able to synchronize changes to and fro. Also I should be able to control which rows/tables need to be synchronized based on some filters/rules. Is there any existi... | There are a number of Java libraries for data synchronizing/replication. Two that I'm aware of are [daffodil](http://opensource.replicator.daffodilsw.com/) and [SymmetricDS](http://www.symmetricds.org/). In a previous life I foolishly implemented (in Java) my own data replication process. It seems like the sort of thin... | The biggist issue with synchronization is when the user edits something offline, and it is edited online at the same time. You need to merge the two changed pieces of data, or deal with the UI to allow the user to say which version is correct. If you eliminate the possibility of both being edited at the same time, then... | Strategy for Offline/Online data synchronization | [
"",
"java",
"database",
"jakarta-ee",
"data-synchronization",
""
] |
I have the following file/line:
```
pc=1 ct=1 av=112 cv=1100 cp=1700 rec=2 p=10001 g=0 a=0 sz=5 cr=200
pc=1 ct=1 av=113 cv=1110 cp=1800 rec=2 p=10001 g=0 a=10 sz=5 cr=200
```
and so on.
I wish to parse this and take the key value pairs and put them in a structure:
```
struct pky
{
pky() :
a_id(0),
sz... | You can do something like this:
```
std::string line;
std::map<std::string, std::string> props;
std::ifstream file("foo.txt");
while(std::getline(file, line)) {
std::string token;
std::istringstream tokens(line);
while(tokens >> token) {
std::size_t pos = token.find('=');
if(pos != std::str... | This is the perfect place to define the stream operators for your structure:
```
#include <string>
#include <fstream>
#include <sstream>
#include <istream>
#include <vector>
#include <algorithm>
#include <iterator>
std::istream& operator>> (std::istream& str,pky& value)
{
std::string line;
std::getline(str,li... | Parse a file using C++, load the value to a structure | [
"",
"c++",
"file",
"parsing",
""
] |
I was reading *[Java Platform Performance](http://java.sun.com/docs/books/performance/1st_edition/html/JPAppGC.fm.html)* (sadly the link seems to have disappeared from the internet since I originally posed this question) and section A.3.3 worried me.
I had been working on the assumption that a variable that dropped ou... | This code should clear it up:
```
public class TestInvisibleObject{
public static class PrintWhenFinalized{
private String s;
public PrintWhenFinalized(String s){
System.out.println("Constructing from "+s);
this.s = s;
}
protected void finalize() throws Throwable {
System.out.printl... | The problem is still there. I tested it with Java 8 and could prove it.
You should note the following things:
1. The only way to force a guaranteed garbage collection is to try an allocation which ends in an OutOfMemoryError as the JVM is required to try freeing unused objects before throwing. This however does not h... | Are invisible references still an issue in recent JVMs? | [
"",
"java",
"memory-leaks",
"garbage-collection",
"jvm",
"sun",
""
] |
Is there any reason why I should pick JSON over XML, or vice-versa if both are available? Tips for optimizing performance when dealing with data feeds are also appreciated! | When it comes to PHP the one reason I choose XML over JSON is because even in PHP 5 there is no officially supported API for traversal. You can encode, and you can decode, and that is it. There is no validation, no efficient way to traverse key/value pairs, and all-in-all, very little support for it. Don't get me wrong... | I would go with JSON myself, simply because XML is very bloaty and excessively difficult to parse. JSON is small and neat, and thus saves on bandwidth, and should also speed up response times simply because it's easier to generate, faster to transmit, and quicker to decode. | Which is faster for PHP to deal with/easier to work with in PHP; XML or JSON, and file_get_contents or cURL? | [
"",
"php",
"json",
"xml",
""
] |
Having some Geometry data and a Transform how can the transform be applied to the Geometry to get a new Geometry with it's data transformed ?
Ex: I Have a Path object that has it's Path.Data set to a PathGeometry object, I want to tranform **the points** of the PathGeometry object **in place** using a transform, and n... | You could try and use Geometry.Combine. It applies a transform during the combine. One catch is that Combine only works if your Geometry has area, so single lines will not work.
Here is a sample that worked for me.
```
PathGeometry geometry = new PathGeometry();
geometry.Figures.Add(new PathFigure(new Point(10, 10), ... | I've found a solution with which arbitrary tranform can be applied to a path geometry, thanks to [Todd White](https://stackoverflow.com/questions/249971/wpf-how-to-apply-a-generaltransform-to-a-geometry-data-and-return-the-new-geome#250587)'s answer:
Basically Geometry.Combine is used to combine the desired geometry w... | WPF: How to apply a GeneralTransform to a Geometry data and return the new geometry? | [
"",
"c#",
".net",
"wpf",
"geometry",
"transform",
""
] |
My WinForms app uses a number of [BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx) objects to retrieve information from a database. I'm using BackgroundWorker because it allows the UI to remain unblocked during long-running database queries and it simplifies the thr... | If the operation raises an exception that your code does not handle, the `BackgroundWorker` catches the exception and passes it into the `RunWorkerCompleted` event handler, where it is exposed as the Error property of `System.ComponentModel.RunWorkerCompletedEventArgs`. If you are running under the Visual Studio debugg... | I am fully using `BackgroundWorker` over a years and really know it in deep.
Just recently, My `RunWorkerCompleted` does not catch the `e.Error` when I simply `Throw New Exception("Test")` in `DoWork`. However Unhandled Exception raised. Catch in `DoWork` is not the best practice thus `e.Error` got no meaning.
When I... | Unhandled exceptions in BackgroundWorker | [
"",
"c#",
".net",
"multithreading",
"debugging",
"backgroundworker",
""
] |
Is there a possible htaccess directive that can transparently forward request from index.php to index\_internal.php if the request is coming from an internal ip range? | ```
RewriteEngine on
RewriteCond %{REMOTE_ADDR} ^192\.168\.1\. [OR]
RewriteCond %{REMOTE_ADDR} ^10\.15\.
RewriteRule ^index\.php$ index_internal.php [R,NC,QSA,L]
```
What this does:
start mod\_rewrite engine (you may have that already)
if (client IP address starts with "192.168.1." [or]
client IP address starts wi... | Something like this should do it (obviously change the IP address to match your network):
```
RewriteCond %{REMOTE_ADDR} ^192\.168\.
RewriteRule index.php index_internal.php
```
If you want an actual header then make it `RewriteRule index.php index_internal.php [L,R,QSA]` | htaccess request forwarding if internal ip | [
"",
"php",
".htaccess",
"forwarding",
""
] |
I'm not talking about a pointer to an instance, I want a pointer to a class itself. | In C++, classes are not "[first class objects](http://en.wikipedia.org/wiki/First-class_object)". The closest you can get is a pointer to its `type_info` instance. | No. A pointer is the address of something in the memory of the computer at run-time. A class is just a set of instructions to the compiler. | In C++ You Can Have a Pointer to a Function, Can you also have a pointer to a class? | [
"",
"c++",
"class",
"pointers",
""
] |
I want to create a file on the webserver dynamically in PHP.
First I create a directory to store the file. THIS WORKS
```
// create the users directory and index page
$dirToCreate = "..".$_SESSION['s_USER_URL'];
mkdir($dirToCreate, 0777, TRUE); // create the directory for the user
```
Now I want to create a file cal... | First you do :
```
$dirToCreate = "..".$_SESSION['s_USER_URL'];
```
But the filename you try to write to is not prefixed with the '..', so try changing
```
$ourFileName = $_SESSION['s_USER_URL']."/"."index.php";
```
to
```
$ourFileName = '..' . $_SESSION['s_USER_URL'] . '/index.php';
```
or probably tidier:
```
... | It could be a result of one of your php ini settings, or possibly an apache security setting.
Try creating the dir as only rwxr-x--- and see how that goes.
I recall a shared hosting setup where "safemode" was compiled in and this behaviour tended to occur, basically, if the files/dirs were writable by too many people... | php: writing files | [
"",
"php",
"file-io",
""
] |
On my current project, I came across our master DB script. Taking a closer look at it, I noticed that all of our original primary keys have a data type of **numeric(38,0)**.
We are running SQL Server 2005 as our primary DB platform.
For a little context, we support both Oracle and SQL Server as our back-end. In Oracle... | Well, you *are* spending more data to store numbers that you will never really reach.
bigint goes up to 9,223,372,036,854,775,807 in 8 Bytes
int goes up to 2,147,483,647 in 4 bytes
A NUMERIC(38,0) is going to take, if I am doing the math right, 17 bytes.
Not a huge difference, but: smaller datatypes = more rows in ... | This is overly large because you are never going to have that many rows. The larger size will result in more storage space. This is not a big deal in itself but will also mean more disk reads to retrieve data from a table or index. It will mean less rows will fit into memory on the database server.
I don't think it's ... | numeric(38,0) as primary key column; good, bad, who cares? | [
"",
"sql",
"sql-server",
"sql-server-2005",
"primary-key",
""
] |
This is related to some other questions, such as: [this](https://stackoverflow.com/questions/34987/how-to-declare-an-array-of-strings-in-c), and some of my other questions.
In [this question](https://stackoverflow.com/questions/34987/how-to-declare-an-array-of-strings-in-c), and others, we see we can declare and initi... | Use the keyword static and external initialization to make the array a static member of the class:
In the header file:
```
class DataProvider : public SomethingElse
{
static const char* const mStringData[];
public:
DataProvider();
~DataProvider();
const char* const GetData()
{
int index ... | This is not possible in C++. You cannot directly initialize the array. Instead you have to give it the size it will have (4 in your case), and you have to initialize the array in the constructor of DataProvider:
```
class DataProvider {
enum { SIZEOF_VALUES = 4 };
const char * values[SIZEOF_VALUES];
publi... | How do you declare arrays in a c++ header? | [
"",
"c++",
"arrays",
"header",
"initialization",
"constants",
""
] |
My project requires a file where I will store key/value pair data that should be able to be read and modified by the user. I want the program to just expect the keys to be there, and I want to parse them from the file as quickly as possible.
I could store them in XML, but XML is way to complex, and it would require tr... | Use the [KeyValuePair](http://msdn.microsoft.com/en-us/library/5tbh8a42.aspx) class for you Key and Value, then just serialize a [List](http://msdn.microsoft.com/en-us/library/6sh2ey19.aspx) to disk with an [XMLSerializer](http://msdn.microsoft.com/en-us/library/system.xml.serialization.xmlserializer.aspx).
That would... | If you're looking for a quick easy function and don't want to use .Net app\user config setting files or worry about serialization issues that sometimes occur of time.
The following static function can load a file formatted like `KEY=VALUE`.
```
public static Dictionary<string, string> LoadConfig(string settingfile)
{... | Simplest possible key/value pair file parsing in .NET | [
"",
"c#",
".net",
"key-value",
""
] |
I am working on a desktop application in PyGTK and seem to be bumping up against some limitations of my file organization. Thus far I've structured my project this way:
* application.py - holds the primary application class (most functional routines)
* gui.py - holds a loosely coupled GTK gui implementation. Handles s... | In the project [Wader](http://wader-project.org) we use [python gtkmvc](http://pygtkmvc.sourceforge.net/), that makes much easier to apply the MVC patterns when using pygtk and glade, you can see the file organization of our project in the [svn repository](http://trac.wader-project.org/browser/trunk/wader):
```
wader/... | "holds the primary application class (most functional routines)"
As in singular -- one class?
I'm not surprised that the **One Class Does Everything** design isn't working. It might not be what I'd call object-oriented. It doesn't sound like it follows the typical MVC design pattern if your functionality is piling up... | How do I coherently organize modules for a PyGTK desktop application? | [
"",
"python",
"gtk",
"module",
"pygtk",
"organization",
""
] |
I have two lists of custom objects and want to update a field for all objects in one list if there is an object in the other list which matches on another pair of fields.
This code explains the problem better and produces the results I want. However for larger lists 20k, and a 20k list with matching objects, this take... | That join should be fairly fast, as it will first loop through all of `adjList` to create a lookup, then for each element in `propList` it will just use the lookup. This is faster than your O(N \* M) method in the larger code - although that could easily be fixed by calling [`ToLookup`](http://msdn.microsoft.com/en-us/... | If adjList might have duplicate names, you should group the items before pushing to dictionary.
```
Dictionary<string, decimal> adjDictionary = adjList
.GroupBy(a => a.PropName)
.ToDictionary(g => g.Key, g => g.Sum(a => a.AdjVal))
propList.ForEach(p =>
{
decimal a;
adjDictionary.TryGetValue(p.Name, out... | Better performance on updating objects with linq | [
"",
"c#",
"linq",
"performance",
"optimization",
"linq-to-objects",
""
] |
I try get the [mp3 flash player](http://flash-mp3-player.net/players/js/) to work with my javascript on all browsers. All went well for first, but fast realized that my code doesn't work on MSIE.
After trying to find out I found this in the reference code:
```
<!--[if IE]>
<script type="text/javascript" event="FSComm... | That syntax, with the <script> tag with the "event" and "for" attributes is an Internet Explorer-only way of setting up an event handler on an DOM object. Here, it adds a FSCommand event handler to the myFlash object. This is needed because code running inside the Flash object may want to run JavaScript in the browser.... | Maybe this is more about embedding flash dynamically.
I got stuck on exactly the same thing with mp3 flash player. The thing is that IE doesn't care about the special script tag with 'event' and 'for' attribute, if it is added AFTER the page has loaded. My IE wouldn't event eat jquery's .html() when the page loaded, o... | flash fscommands and javascript | [
"",
"javascript",
"jquery",
"flash",
"internet-explorer",
""
] |
ExtJS has Ext.each() function, but is there a map() also hidden somewhere?
I have tried hard, but haven't found anything that could fill this role. It seems to be something simple and trivial, that a JS library so large as Ext clearly must have.
Or when Ext really doesn't include it, what would be the best way to add... | It appears, that my colleges here are using [ext-basex](http://code.google.com/p/ext-basex/), which extends Array.prototype with map() and other methods.
So I can just write:
```
[1, 2, 3].map( function(){ ... } );
```
Problem solved. | As of at least Ext4, Ext.Array.map is included.
<http://docs.sencha.com/extjs/5.0.1/#!/api/Ext.Array-method-map> | Is there a map() function in ExtJS? | [
"",
"javascript",
"dictionary",
"extjs",
""
] |
In the past people used to wrap HTML comment tags around blocks of JavaScript in order to prevent "older" browsers from displaying the script. Even Lynx is smart enough to ignore JavaScript, so why do some people keep doing this? Are there any valid reasons these days?
```
<script type="text/javascript">
<!--
//some j... | No, absolutely not. Any user agent, search engine spider, or absolutely anything else these days is smart enough to ignore Javascript if it can't execute it.
There was only a very brief period when this was at all helpful, and it was around 1996. | There isn't a good reason to do this anymore, as the browsers which required this have by and large disappeared from the web.
In fact, doing this can actually cause unintended problems with certain older browsers' attempts to interpret the page if it uses XHTML - from [developer.mozilla.org](http://developer.mozilla.o... | Does it still make sense to use HTML comments on blocks of JavaScript? | [
"",
"javascript",
"html",
""
] |
Wow, I just got back a huge project in C# from outsourced developers and while going through my code review my analysis tool revealed bunches of what it considered bad stuff. One of the more discouraging messages was:
```
Exceptions.DontSwallowErrorsCatchingNonspecificExceptionsRule : 2106 defects
```
The developers... | While there are some reasonable reasons for ignoring exceptions; however, generally it is only specific exceptions that you are able to safely ignore. As noted by [Konrad Rudolph](https://stackoverflow.com/questions/204814/is-there-any-valid-reason-to-ever-ignore-a-caught-exception#204827), you might have to catch and ... | I don't catch exceptions unless I plan to do something about them. Ignoring them isn't doing something about them. | Is there any valid reason to ever ignore a caught exception | [
"",
"c#",
"exception",
""
] |
Situation:
* text: a string
* R: a regex that matches part of the string. This might be expensive to calculate.
I want to both delete the R-matches from the text, and see what they actually contain. Currently, I do this like:
```
import re
ab_re = re.compile("[ab]")
text="abcdedfe falijbijie bbbb laifsjelifjl"
ab_re... | ```
import re
r = re.compile("[ab]")
text = "abcdedfe falijbijie bbbb laifsjelifjl"
matches = []
replaced = []
pos = 0
for m in r.finditer(text):
matches.append(m.group(0))
replaced.append(text[pos:m.start()])
pos = m.end()
replaced.append(text[pos:])
print matches
print ''.join(replaced)
```
Outputs:
... | What about this:
```
import re
text = "abcdedfe falijbijie bbbb laifsjelifjl"
matches = []
ab_re = re.compile( "[ab]" )
def verboseTest( m ):
matches.append( m.group(0) )
return ''
textWithoutMatches = ab_re.sub( verboseTest, text )
print matches
# ['a', 'b', 'a', 'b', 'b', 'b', 'b', 'b', 'a']
print textW... | Capture the contents of a regex and delete them, efficiently | [
"",
"python",
"regex",
""
] |
I have a List of beans, each of which has a property which itself is a List of email addresses.
```
<c:forEach items="${upcomingSchedule}" var="conf">
<div class='scheduled' title="${conf.subject}" id="scheduled<c:out value="${conf.id}"/>">
...
</div>
</c:forEach>
```
This renders one `<div>` per bean in ... | Figured out a somewhat dirty way to do this:
```
<c:forEach items="${upcomingSchedule}" var="conf">
<c:set var="title" value="${conf.subject}: "/>
<c:forEach items="${conf.invitees}" var="invitee">
<c:set var="title" value="${title} ${invitee}, "/>
</c:forEach>
<div class='scheduled' title="${t... | The "clean" way to do this would be to use a function. As the JSTL `join` function won't work on a `Collection`, you can write your own without too much trouble, and reuse it all over the place instead of cut-and-pasting a large chunk of loop code.
You need the function implementation, and a TLD to let your web applic... | Concatenate strings in JSP EL? | [
"",
"java",
"jsp",
"el",
"taglib",
""
] |
Is it possible to insert a row, but only if one of the values already in the table does not exist?
I'm creating a *Tell A Friend* with referral points for an ecommerce system, where I need to insert the friend's email into the database table, but only if it doesn't already exist in the table. This is because I don't w... | If the column is a primary key or a unique index:
```
INSERT INTO table (email) VALUES (email_address) ON DUPLICATE KEY UPDATE
email=email_address
```
Knowing my luck there's a better way of doing it though. AFAIK there's no equivalent of "ON DUPLICATE KEY DO NOTHING" in MySQL. I'm not sure about the email=email\_Add... | This works if you have a unique index or primary key on the column (EmailAddr in this example):
```
INSERT IGNORE INTO Table (EmailAddr) VALUES ('test@test.com')
```
Using this if a record with that email already exists (duplicate key violation) instead of an error, the statement just fails and nothing is inserted.
... | Is it possible to insert a row but only if a value does not already exist? | [
"",
"php",
"mysql",
""
] |
Given an HTML link like
```
<a href="urltxt" class="someclass" close="true">texttxt</a>
```
how can I isolate the url and the text?
**Updates**
I'm using Beautiful Soup, and am unable to figure out how to do that.
I did
```
soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
links = soup.findAll('a')
for li... | Use [Beautiful Soup](http://crummy.com/software/BeautifulSoup). Doing it yourself is harder than it looks, you'll be better off using a tried and tested module.
**EDIT:**
I think you want:
```
soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url).read())
```
By the way, it's a bad idea to try opening the URL there... | Here's a code example, showing getting the attributes and contents of the links:
```
soup = BeautifulSoup.BeautifulSoup(urllib.urlopen(url))
for link in soup.findAll('a'):
print link.attrs, link.contents
``` | Decomposing HTML to link text and target | [
"",
"python",
"html",
"regex",
"beautifulsoup",
""
] |
I wish to calculate the time it took for an API to return a value.
The time taken for such an action is in the space of nanoseconds. As the API is a C++ class/function, I am using the timer.h to calculate the same:
```
#include <ctime>
#include <iostream>
using namespace std;
int main(int argc, char** argv) ... | What others have posted about running the function repeatedly in a loop is correct.
For Linux (and BSD) you want to use [clock\_gettime()](http://opengroup.org/onlinepubs/007908799/xsh/clock_gettime.html).
```
#include <sys/time.h>
int main()
{
timespec ts;
// clock_gettime(CLOCK_MONOTONIC, &ts); // Works on F... | This new answer uses C++11's `<chrono>` facility. While there are other answers that show how to use `<chrono>`, none of them shows how to use `<chrono>` with the `RDTSC` facility mentioned in several of the other answers here. So I thought I would show how to use `RDTSC` with `<chrono>`. Additionally I'll demonstrate ... | Timer function to provide time in nano seconds using C++ | [
"",
"c++",
"c",
"timer",
""
] |
I'm trying to write a wstring to file with ofstream in binary mode, but I think I'm doing something wrong. This is what I've tried:
```
ofstream outFile("test.txt", std::ios::out | std::ios::binary);
wstring hello = L"hello";
outFile.write((char *) hello.c_str(), hello.length() * sizeof(wchar_t));
outFile.close();
```... | I suspect that sizeof(wchar\_t) is 4 in your environment - i.e. it's writing out UTF-32/UCS-4 instead of UTF-16. That's certainly what the hex dump looks like.
That's easy enough to test (just print out sizeof(wchar\_t)) but I'm pretty sure it's what's going on.
To go from a UTF-32 wstring to UTF-16 you'll need to ap... | Here we run into the little used locale properties.
If you output your string as a string (rather than raw data) you can get the locale to do the appropriate conversion auto-magically.
**N.B.**This code does not take into account edianness of the wchar\_t character.
```
#include <locale>
#include <fstream>
#include <... | Writing utf16 to file in binary mode | [
"",
"c++",
"unicode",
"utf-16",
""
] |
A string will be made up of certain symbols (ax,bx,dx,c,acc for example) and numbers.
ex:
ax 5 5
dx 3 acc
c ax bx
I want to replace one or all of the symbols (randomly) with another symbol of the same set. ie, replace one of {ax,bx,dx,c,acc} with one of {ax,bx,dx,c,acc}.
replacement example:
acc 5 5
dx 3 acc
c ax bx... | I think this is the most clean solution for replacing a certain set of symbols from a string containing a superset of them.
appendreplacement is the key to this method.
one important caveat: do not include any unescped dollar characters ($) in your elements list. escape them by using "\$"
eventually use
.replaceall("... | To answer the first question: no.
Since you are doing a random replace, regex will not help you, nothing about regex is random. \* Since your strings are in an array, you don't need to find them with any pattern matching, so again regex isn't necessary.
\*\*Edit: the question has been edited so it no longer says the ... | Java: Easiest way to replace strings with random strings | [
"",
"java",
"regex",
"replace",
""
] |
I have several strings in the rough form:
```
[some text] [some number] [some more text]
```
I want to extract the text in [some number] using the Java regex classes.
I know roughly what regular expression I want to use (though all suggestions are welcome). What I'm really interested in are the Java calls to take th... | Full example:
```
private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
public static void main(String[] args) {
// create matcher for pattern p and given string
Matcher m = p.matcher("Testing123Testing");
// if an occurrence if a pattern was found in a given string...
if (m.fi... | ```
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class Regex1 {
public static void main(String[]args) {
Pattern p = Pattern.compile("\\d+");
Matcher m = p.matcher("hello1234goodboy789very2345");
while(m.find()) {
System.out.println(m.group());
}... | Using regular expressions to extract a value in Java | [
"",
"java",
"regex",
""
] |
The `equals()` method of the URL class in the Java class library makes a DNS request to get the IP for the hostname, to check the two IP's for equality. This happens even for URLs that are created from the same `String`. Is there a way to avoid this internet access? | Use [java.net.URI](http://docs.oracle.com/javase/8/docs/api/java/net/URI.html) instead of URL. | If you just want to compare the url strings, try
```
url1.toString().equals(url2.toString())
``` | How to avoid, that URL.equals needs access to the internet in Java? | [
"",
"java",
"url",
"dns",
"equals",
"equality",
""
] |
Is there any clever method out there to make my executeEveryDayMethod() execute once a day, without having to involve the Windows TaskScheduler? | Take a look at [quartz.net](http://quartznet.sourceforge.net/). It is a scheduling library for .net.
More specifically take a look [here](http://quartznet.sourceforge.net/tutorial/lesson_4.html). | I achieved this by doing the following...
1. Set up a timer that fires every 20 minutes (although the actual timing is up to you - I needed to run on several occasions throughout the day).
2. on each Tick event, check the system time. Compare the time to the scheduled run time for your method.
3. If the current time i... | Run once a day in C# | [
"",
"c#",
"scheduling",
""
] |
I am trying to read a custom (non-standard) CSS property, set in a stylesheet (not the inline style attribute) and get its value. Take this CSS for example:
```
#someElement {
foo: 'bar';
}
```
I have managed to get its value with the currentStyle property in IE7:
```
var element = document.getElementById('someEle... | Firefox does not carry over tags, attributes or CSS styles it does not understand from the code to the DOM. That is by design. Javascript only has access to the DOM, not the code. So no, there is no way to access a property from javascript that the browser itself does not support. | Modern browsers will just throw away any invalid css. However, you can use the content property since it only has effect with
`:after`, `:before` etc. You can store JSON inside it:
```
#someElement {
content: '{"foo": "bar"}';
}
```
Then use code like this to retrieve it:
```
var CSSMetaData = function() {
... | Can I fetch the value of a non-standard CSS property via Javascript? | [
"",
"javascript",
"css",
""
] |
I have a user that keeps getting this error. Is there a tool that does window handle counting that i can use to figure out why he keeps getting this error.
System.ComponentModel.Win32Exception: Error creating window handle.
at System.Windows.Forms.NativeWindow.CreateHandle(CreateParams cp)
at System.Windows.Forms.Cont... | The best counter I know is Taskmgr.exe. View + Select Columns and check "User objects", "Handle count" and "GDI Objects".
The generic diagnostic is that you're leaking handles and consumed 10,000 of them. Beware of a handle leak bug in .NET 2.0 SP1 and .NET 3.5's Graphics.CopyFromScreen(), fixed in 3.5 SP1. | If the Form you are creating overrides WndProc(), be careful to ensure that it always calls base.WndProc() during the window creation process.
I inadvertently omitted a call to base.WndProc() in my override, and got your stack trace. | Window handle debugging in Winforms | [
"",
"c#",
"winforms",
"window",
""
] |
I am trying to gain a better understanding of tcp/ip sockets in c#, as i want to challenge myself to see if i can create a working MMO infrastructure (game world, map, players, etc) purely for educational purposes as i have no intention of being another one of those "OMGZ iz gonna make my r0x0r MMORPG that will be bett... | If you are doing socket level programming, then regardless of how many ports you open for each message type, you still need to have a header of some sort. Even if it is just the length of the rest of the message. Having said that it is easy to add a simple header and tail structure to a message. I would think it is eas... | I think you need to crawl before you walk and before you run. First get the design of the framework and connections right, then worry about scalability. If your goal is to learn C# and tcp/ip programming, then don't make this harder on yourself.
Go ahead with your initial thoughts and keep the data streams separate.
... | Multi-client, async sockets in c#, best practices? | [
"",
"c#",
"sockets",
"client-server",
""
] |
Is it possible to create a toggle button in C# WinForms? I know that you can use a CheckBox control and set it's Appearance property to "Button", but it doesn't look right. I want it to appear sunken, not flat, when pressed. Any thoughts? | I ended up overriding the OnPaint and OnBackgroundPaint events and manually drawing the button exactly like I need it. It worked pretty well. | You can just use a `CheckBox` and set its appearance to `Button`:
```
CheckBox checkBox = new System.Windows.Forms.CheckBox();
checkBox.Appearance = System.Windows.Forms.Appearance.Button;
``` | ToggleButton in C# WinForms | [
"",
"c#",
"winforms",
"button",
""
] |
In .Net, I found this great library, [HtmlAgilityPack](http://www.codeplex.com/htmlagilitypack) that allows you to easily parse non-well-formed HTML using XPath. I've used this for a couple years in my .Net sites, but I've had to settle for more painful libraries for my Python, Ruby and other projects. Is anyone aware ... | In python, [ElementTidy](http://pypi.python.org/pypi/elementtidy/1.0-20050212) parses tag soup and produces an element tree, which allows querying using XPath:
```
>>> from elementtidy.TidyHTMLTreeBuilder import TidyHTMLTreeBuilder as TB
>>> tb = TB()
>>> tb.feed("<p>Hello world")
>>> e= tb.close()
>>> e.find(".//{htt... | I'm surprised there isn't a single mention of lxml. It's blazingly fast and will work in any environment that allows CPython libraries.
Here's how [you can parse HTML via XPATH using lxml](http://codespeak.net/lxml/xpathxslt.html).
```
>>> from lxml import etree
>>> doc = '<foo><bar></bar></foo>'
>>> tree = etree.HTM... | Parse HTML via XPath | [
"",
"python",
"html",
"ruby",
"xpath",
"parsing",
""
] |
I need to configure Tomcat memory settings as part of a larger installation, so manually configuring tomcat with the configuration app after the fact is out of the question. I thought I could just throw the JVM memory settings into the JAVA\_OPTS environment variable, but I'm testing that with jconsole to see if it wor... | Serhii's suggestion works and here is some more detail.
If you look in your installation's bin directory you will see catalina.sh
or .bat scripts. If you look in these you will see that they run a
setenv.sh or setenv.bat script respectively, if it exists, to set environment variables.
The relevant environment variable... | Create a setenv.(sh|bat) file in the tomcat/bin directory with the environment variables that you want modified.
The catalina script checks if the setenv script exists and runs it to set the environment variables. This way you can change the parameters to only one instance of tomcat and is easier to copy it to another... | How to tune Tomcat 5.5 JVM Memory settings without using the configuration program | [
"",
"java",
"tomcat",
"memory",
"jvm",
""
] |
I got an image with which links to another page using `<a href="..."> <img ...> </a>`.
How can I make it make a post like if it was a button `<input type="submit"...>`? | ```
<input type="image" name="your_image_name" src="your_image_url.png" />
```
This will send the `your_image_name.x` and `your_image_name.y` values as it submits the form, which are the x and y coordinates of the position the user clicked the image. | More generic approatch using **[JQuery](http://jquery.com/)** library [closest](http://api.jquery.com/closest/)() and [submit](http://api.jquery.com/submit/)() buttons.
Here you do not have to specify whitch form you want to submit, submits the form it is in.
```
<a href="#" onclick="$(this).closest('form').submit()">... | How to make a submit out of a <a href...>...</a> link? | [
"",
"javascript",
"html",
"form-submit",
"url-link",
""
] |
In a table I have the following schema
```
table1:
playerID int primary key,
nationalities nvarchar
table2:
playerID int,
pubVisited nvarchar
```
Now, I want to set all the players' playedVisited to null, for player whose nationality is "England", any idea on how to do this? | Tested on SQL Server 2005
```
update table2 set pubVisited = NULL
from
table1 t1
inner join
table2 t2
on (t1.playerID = t2.playerID and t1.nationalities = 'England')
``` | Judging by the *nvarchar* type, you're using MSSQL. Now, in MySQL you could use a subselect in the update .. where clause but MSSQL has its own update .. from clause:
```
UPDATE table2
SET
table2.pubVisited = null
FROM table1
WHERE
table2.playerID = table1.playerID and table1.nationalities = 'England'
```
Hav... | Update data in different tables in SQL Server | [
"",
"sql",
"sql-server",
""
] |
```
SELECT `name` , COUNT(*) AS `count`
FROM `t1`, `t2`
WHERE `t2`.`id` = `t1`.`id`
GROUP BY `t2`.`id`
```
I want to obtain the name from t1 and the number of rows in t2 where the id is the same as on t1.
I've got the above so far, however it won't return any data if there are no rows in t2 that match. I'd prefer `co... | This should work for you:
```
SELECT `t1`.`id` , COUNT(`t2`.`id`) AS `count`
FROM `t1` LEFT JOIN `t2` ON `t1`.`id` = `t2`.`id`
GROUP BY `t1`.`id`
```
Left join ensures you have all rows from t1, and COUNT(`t2`.`id`) makes it count only records where t2.id is not null (that is - those that really exist in t2) | This sorts descending by COUNT, and within same counts ascending by `name`. Names with no rows in `t2` will return with a count of 0.
```
SELECT
`t1`.`name`,
COUNT(`t2`.`id`) AS `count`
FROM
`t1`
LEFT JOIN `t2` ON`t2`.`id` = `t1`.`id`
GROUP BY
`t1`.`name`
ORDER BY
COUNT(`t2`.`id`) DESC,
`t1`.`name`
`... | MySQL Cross-Table Count(*) Query Help | [
"",
"sql",
"mysql",
""
] |
I have to deal with very large text files (2 GBs), it is mandatory to read/write them line by line. To write 23 millions of lines using ofstream is really slow so, at the beginning, I tried to speed up the process writing large chunks of lines in a memory buffer (for example 256 MB or 512 MB) and then write the buffer ... | A 2GB file is pretty big, and you need to be aware of all the possible areas that can act as bottlenecks:
* The HDD itself
* The HDD interface (IDE/SATA/RAID/USB?)
* Operating system/filesystem
* C/C++ Library
* Your code
I'd start by doing some measurements:
* How long does your code take to read/write a 2GB file,
... | I would also suggest memory-mapped files but if you're going to use boost I think [boost::iostreams::mapped\_file](http://www.boost.org/doc/libs/1_36_0/libs/iostreams/doc/classes/mapped_file.html#mapped_file) is a better match than boost::interprocess. | When to build your own buffer system for I/O (C++)? | [
"",
"c++",
"linux",
"performance",
"io",
"buffer",
""
] |
We currently have a web application loading a Spring application context which instantiates a stack of business objects, DAO objects and Hibernate. We would like to share this stack with another web application, to avoid having multiple instances of the same objects.
We have looked into several approaches; exposing th... | Are the web applications deployed on the same server?
I can't speak for Spring, but it is straightforward to move your business logic in to the EJB tier using Session Beans.
The application organization is straight forward. The Logic goes in to Session Beans, and these Session Beans are bundled within a single jar as... | What about spring parentContext?
Check out this article:
<http://springtips.blogspot.com/2007/06/using-shared-parent-application-context.html> | What's the best way to share business object instances between Java web apps using JBoss and Spring? | [
"",
"java",
"hibernate",
"spring",
"jboss",
"ejb-3.0",
""
] |
When I ran [ReSharper](http://en.wikipedia.org/wiki/ReSharper) on my code, for example:
```
if (some condition)
{
Some code...
}
```
ReSharper gave me the above warning (Invert "if" statement to reduce nesting), and suggested the following correction:
```
if (!some condition) retur... | A return in the middle of the method is not necessarily bad. It might be better to return immediately if it makes the intent of the code clearer. For example:
```
double getPayAmount() {
double result;
if (_isDead) result = deadAmount();
else {
if (_isSeparated) result = separatedAmount();
... | **It is not only aesthetic**, but it also reduces the [maximum nesting level](http://codebetter.com/patricksmacchia/2008/03/07/a-simple-trick-to-code-better-and-to-increase-testability/) inside the method. This is generally regarded as a plus because it makes methods easier to understand (and indeed, [many](http://www.... | Invert "if" statement to reduce nesting | [
"",
"c#",
"resharper",
""
] |
Given a date how can I add a number of days to it, but exclude weekends. For example, given 11/12/2008 (Wednesday) and adding five will result in 11/19/2008 (Wednesday) rather than 11/17/2008 (Monday).
I can think of a simple solution like looping through each day to add and checking to see if it is a weekend, but I'd... | using Fluent DateTime <https://github.com/FluentDateTime/FluentDateTime>
```
var dateTime = DateTime.Now.AddBusinessDays(4);
``` | ```
public DateTime AddBusinessDays(DateTime dt, int nDays)
{
int weeks = nDays / 5;
nDays %= 5;
while(dt.DayOfWeek == DayOfWeek.Saturday || dt.DayOfWeek == DayOfWeek.Sunday)
dt = dt.AddDays(1);
while (nDays-- > 0)
{
dt = dt.AddDays(1);
if (dt.DayOfWeek == DayOfWeek.Saturday... | Adding Days to a Date but Excluding Weekends | [
"",
"c#",
"f#",
"date",
""
] |
I know about using a -vsdoc.js file for [IntelliSense](http://en.wikipedia.org/wiki/IntelliSense), and the one for jQuery is easy to find. What other JavaScript, Ajax, and DHTML libraries have them and where can I find those files? Also, is there a document which outlines the specifications for -vsdoc.js files? | An excellent blog posting from Betrand LeRoy on IntelliSense format for JavaScript:
*[The format for JavaScript doc comments](http://weblogs.asp.net/bleroy/archive/2007/04/23/the-format-for-javascript-doc-comments.aspx)*.
In a nutshell:
Summary - used to describe a function/method or event. Syntax:
```
<summary loci... | I wrote on article to sum up (from investigation) what parts of vsdoc are used to help Intellisense in VS 2010 : <http://www.scottlogic.co.uk/2010/08/vs-2010-vs-doc-and-javascript-intellisense/> | IntelliSense for Ajax and JavaScript libraries in Visual Studio | [
"",
"javascript",
"visual-studio",
""
] |
I'm probably going to be using Tomcat and the Apache Axis webapp plugin, but I'm curious as to any other potential lightweight solutions.
The main goal of this is to connect to MySQL database for doing some demos.
Thanks,
Todd | Define lightweight? (What DOES that mean anyway nowadays??)
With JAX-WS/Metro you need to simply make a boiler plate change to the web.xml, and then annotate a POJO with @WebService, and, tada, instant web service.
The distribution has several jars in it (around a dozen I think, but they're all in the install -- you ... | [Jetty](http://www.mortbay.org/jetty/) is a lightweight servlet container that you might want to look into. | Looking for lightweight java stack for creating SOAP based web services | [
"",
"java",
"web-services",
"soap",
""
] |
I want to use the [php simple HTML DOM parser](http://simplehtmldom.sourceforge.net/manual_api.htm) to grab the image, title, date, and description from each article on a page full of articles. When looking at the API I notice it has a set\_callback which Sets a callback function. However im not sure what this does or ... | Here's a basic callback function example:
```
<?php
function thisFuncTakesACallback($callbackFunc)
{
echo "I'm going to call $callbackFunc!<br />";
$callbackFunc();
}
function thisFuncGetsCalled()
{
echo "I'm a callback function!<br />";
}
thisFuncTakesACallback( 'thisFuncGetsCalled' );
?>
```
You can ... | A callback function will use that function on whatever data is returned by a particular method.
I'm not sure how this particular library works, but it could be something as simple as:
```
$html = file_get_html('http://example.com');
$html->set_callback('make_bold');
$html->find('#title'); // returns an array
functio... | What is a callback function and how do I use it with OOP | [
"",
"php",
"oop",
"dom",
"callback",
"function-calls",
""
] |
Ok. I'm having an issue with the following bit of code:
```
StreamReader arrComputer = new StreamReader(FileDialog.FileName);
```
My first question had been answered already now my second question focuses on the tail end of this code.
I'm reading a text file `StreamReader` that the user selects with a button event u... | Looks to me like you're creating a new OpenFileDialog object in your button1\_Click method, and storing the only reference to that object in a local variable, fileDialog.
Then, in your buttonRun\_Click method, it looks like you wanted to get the file name from the dialog you created in the previous method. That's not ... | Don't you think you need to use textBox1.Text?
```
StreamReader arrComputer = new StreamReader(textBox1.Text);
``` | An object reference is required for the non-static field, method, or property | [
"",
"c#",
".net",
"visual-studio-2008",
""
] |
I have many emails coming in from different sources.
they all have attachments, many of them have attachment names in chinese, so these
names are converted to base64 by their email clients.
When I receive these emails, I wish to decode the name. but there are other names which are
not base64. How can I differentiate w... | > Please note both `Content-Transfer-Encoding` have base64
Not relevant in this case, the `Content-Transfer-Encoding` only applies to the body payload, not to the headers.
```
=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=
```
That's an **RFC2047**-encoded header atom. The stdlib function to decode it is `email.header.decode... | The header value tells you this:
```
=?gb2312?B?uLGxvmhlbrixsb5nLnhscw==?=
"=?" introduces an encoded value
"gb2312" denotes the character encoding of the original value
"B" denotes that B-encoding (equal to Base64) was used (the alternative
is "Q", which refers to something close to quoted-printab... | how to tell if a string is base64 or not | [
"",
"python",
"jython",
"base64",
"mime",
""
] |
One of the frequent causes of memory leaks in .Net are event handlers which are never removed from their source objects.
Will this WCF code cause a memory leak, or will the lambda go out of scope too, allowing both the proxy class and the handler to be GCed?
```
void AMethod()
{
WCFClient proxy;
proxy = new W... | Here's my test - note the explicit `proxy` set to `null` in the lambda - without it the `WeakReference` lives and therefore a leak is likely:
```
public class Proxy
{
private bool _isOpen;
public event EventHandler Complete;
public void Close()
{
_isOpen = false;
}
public void Open(... | Don't forget that the proxy's don't correctly implement IDisposable. If an error occurs the code above will not clean up the connection and the handle will remain until the parent process is closed. | Will this WCF client side code cause a memory leak? | [
"",
"c#",
".net",
"wcf",
"lambda",
""
] |
> **Possible Duplicate:**
> [Where do I find the current C or C++ standard documents?](https://stackoverflow.com/questions/81656/where-do-i-find-the-current-c-or-c-standard-documents)
I want to use STL with the current program I'm working on and the vendor doesn't support what I feel is a reasonable STL, working is ... | Information on where to get the current standard document:
[Where do I find the current C or C++ standard documents?](https://stackoverflow.com/questions/81656/where-do-i-find-the-current-x-standard#83763)
Other responses in that question have information on downloads of various drafts of the standards which can be o... | The draft of the current C++0x standard is available from [this page](http://www.research.att.com/~bs/C++.html) and the official homepage of the C++ standards committee is [here](http://www.open-std.org/jtc1/sc22/wg21/). | Where can I look at the C++ standard | [
"",
"c++",
"stl",
""
] |
My app has a DataGridView object and a List of type MousePos. MousePos is a custom class that holds mouse X,Y coordinates (of type "Point") and a running count of this position. I have a thread (System.Timers.Timer) that raises an event once every second, checks the mouse position, adds and/or updates the count of the ... | **UPDATE!** -- I *partially* figured out the answer to **part #1** in the book "Pro .NET 2.0 Windows Forms and Customer Controls in C#"
I had originally thought that **Refresh()** wasn't doing anything and that I needed to call the **Invalidate()** method, to tell Windows to repaint my control at it's leisure. (which ... | You have to update the grid on the main UI thread, like all the other controls. See control.Invoke or Control.BeginInvoke. | How do I safely populate with data and Refresh() a DataGridView in a multi-threaded application? | [
"",
"c#",
".net",
"multithreading",
"datagridview",
"delegates",
""
] |
I'm trying to put a Message back into an MSMQ when an exception is thrown. The following code appears to work but the Message is not put back in the queue?
```
Message msg = null;
try
{
MessageQueue MQueue = new MessageQueue(txtMsgQPath.Text);
msg = MQueue.ReceiveById(txtQItemToRead.Text);
lblMsgRead.Text ... | Couple of points: The best way to do this would be using a transaction spanning both queues; that way you'll know you won't lose a message.
The second part of it is to be careful about how the queues are created and how you submit messages to the second queue. In particular, MSMQ sometimes appears to "fail silently" w... | Is it really your intention to send that message back to the originator? Sending it back to yourself is very dangerous, you'll just bomb again, over and over. | Resend to MSMQ after exception | [
"",
"c#",
".net",
"msmq",
""
] |
Im trying to find a best practice to load usercontrols using Ajax.
My first approach where simply using an UpdatePanel and popuplating it with LoadControl() on ajax postbacks but this would rerender other loaded usercontrols in the same UpdatePanel. Also I cannot have a predefined set of UpdatePanels since the number ... | Probably dozens of high-brow reasons for not doing it this way, but simply initalizing a page, adding the usercontrol, then executing and dump the resulting HTML wherever it may behoove you, is (in my simpleminded view) so mind-numbingly fast & fun that I just have to mention it...
Skip the UpdatePanels, just use a La... | I'm not sure, but maybe [this tutorial by Scott Guthrie](http://weblogs.asp.net/scottgu/archive/2006/10/22/Tip_2F00_Trick_3A00_-Cool-UI-Templating-Technique-to-use-with-ASP.NET-AJAX-for-non_2D00_UpdatePanel-scenarios.aspx) could be useful. | Load usercontrols using Ajax | [
"",
"c#",
"asp.net",
"ajax",
""
] |
This loop is slower than I would expect, and I'm not sure where yet. See anything?
I'm reading an Accces DB, using client-side cursors. When I have 127,000 rows with 20 columns, this loop takes about 10 seconds. The 20 columns are string, int, and date types. All the types get converted to ANSI strings before they are... | Try commenting out the code in the for loop and comparing the time. Once you have a reading, start uncommenting various sections until you hit the bottle-neck. | I can't tell from looking at your code, someone more familiar with COM/ATL may have a better answer.
By trial n error I would find the slow code by commenting out inner loop operations out until you see perf spike, then you have your culprit and should focus on that. | What do you think is making this C++ code slow? (It loops through an ADODB recordset, converts COM types to strings, and fills an ostringstream) | [
"",
"c++",
"com",
"stl",
"adodb",
""
] |
I was wondering peoples opinions on the naming of ID columns in database tables.
If I have a table called Invoices with a primary key of an identity column I would call that column InvoiceID so that I would not conflict with other tables and it's obvious what it is.
Where I am workind current they have called all ID ... | ID is a SQL Antipattern.
See <http://www.amazon.com/s/ref=nb_sb_ss_i_1_5?url=search-alias%3Dstripbooks&field-keywords=sql+antipatterns&sprefix=sql+a>
If you have many tables with ID as the id you are making reporting that much more difficult. It obscures meaning and makes complex queries harder to read as well as requ... | I always prefered ID to TableName + ID for the id column and then TableName + ID for a foreign key. That way all tables have a the same name for the id field and there isn't a redundant description. This seems simpler to me because all the tables have the same primary key field name.
As far as joining tables and not k... | Naming of ID columns in database tables | [
"",
"sql",
"naming-conventions",
""
] |
I'm trying to find out how to read/write to the extended file properties in C#
e.g. Comment, Bit Rate, Date Accessed, Category etc that you can see in Windows explorer.
Any ideas how to do this?
EDIT: I'll mainly be reading/writing to video files (AVI/DIVX/...) | For those of not crazy about VB, here it is in c#:
Note, you have to add a reference to *Microsoft Shell Controls and Automation* from the COM tab of the References dialog.
```
public static void Main(string[] args)
{
List<string> arrHeaders = new List<string>();
Shell32.Shell shell = new Shell32.Shell();
... | # Solution 2016
Add following NuGet packages to your project:
* `Microsoft.WindowsAPICodePack-Shell` by Microsoft
* `Microsoft.WindowsAPICodePack-Core` by Microsoft
### Read and Write Properties
```
using Microsoft.WindowsAPICodePack.Shell;
using Microsoft.WindowsAPICodePack.Shell.PropertySystem;
string filePath =... | Read/Write 'Extended' file properties (C#) | [
"",
"c#",
"extended-properties",
""
] |
How do I enable double-buffering of a control using C# (Windows forms)?
I have a panel control which I am drawing stuff into and also an owner-drawn tab control. Both suffer from flicker, so how can I enable double-buffering? | In the constructor of your control, set the DoubleBuffered property, and/or ControlStyle appropriately.
For example, I have a simple DoubleBufferedPanel whose constructor is the following:
```
this.DoubleBuffered = true;
this.SetStyle(ControlStyles.UserPaint |
ControlStyles.AllPaintingInWmPaint |
... | some info here:
[How to double buffer .NET controls on a form?](https://stackoverflow.com/questions/76993/how-to-double-buffer-net-controls-on-a-form) | How do I enable double-buffering of a control using C# (Windows forms)? | [
"",
"c#",
".net",
"winforms",
"doublebuffered",
"ownerdrawn",
""
] |
What's the best .NET PDF editing library available, and why?
It needs to be used on an IIS web-server.
Specifically, I need to edit a PDF which was generated by reporting services.
Factors I'm interested in:
1. Speed
2. Memory Consumption
3. Price
4. Quality of documentation
5. Library stability
6. Size of library
7... | Have a look at [iTextSharp](http://itextsharp.sourceforge.net/). iTextSharp is a port of the [iText](http://www.lowagie.com/iText/) , a free Java-Pdf library.
To quote iText:
You can use iText to:
* Serve PDF to a browser
* Generate dynamic documents from XML files or databases
* Use PDF's many interactive features
... | [Syncfusion Essential PDF](https://www.syncfusion.com/products/file-formats/pdf) is the best. I have been using it for years. Also, Syncfusion provides a best support compared to other vendors. | Best Server-side .NET PDF editing library | [
"",
"c#",
".net",
"asp.net",
"vb.net",
"pdf",
""
] |
What ist most concise way to read the contents of a file or input stream in Java? Do I always have to create a buffer, read (at most) line by line and so on or is there a more concise way? I wish I could do just
```
String content = new File("test.txt").readFully();
``` | Use the [Apache Commons IOUtils](http://commons.apache.org/io/description.html) package. In particular the `IOUtils` class provides a set of methods to read from streams, readers etc. and handle all the exceptions etc.
e.g.
```
InputStream is = ...
String contents = IOUtils.toString(is);
// or
List lines = IOUtils.re... | I think using a Scanner is quite OK with regards to conciseness of Java on-board tools:
```
Scanner s = new Scanner(new File("file"));
StringBuilder builder = new StringBuilder();
while(s.hasNextLine()) builder.append(s.nextLine());
```
Also, it's quite flexible, too (e.g. regular expressions support, number parsing)... | Most concise way to read the contents of a file/input stream in Java? | [
"",
"java",
""
] |
I have one user who gets an error message when he closes his browser. This only happens when he has visited a page which contains my applet. It seems to have been registered as a bug at Sun but that was many years ago. He is using Java 1.6 and IE7.
Has anyone seen this before and know a solution or work-around?
```
j... | I used to get that error a lot for just about every applet that was loaded in the browser. I never figured out *how*, but Google Desktop was breaking java in some way. After uninstalling google desktop the error went away. | I don't know a solution but I know a prevention of this problem.
If javascript is enabled in your web browser then place this code in a script tag inside your head tag of the html file from which applet is opened:
```
<SCRIPT language = "JavaScript">
window.onunload = function() { document.body.innerHTML = ""; }
... | Applet - 'java.lang.NullPointerException: null pData' when browser closed | [
"",
"java",
"applet",
"nullpointerexception",
""
] |
I'm trying to decode a WBXML encoded SyncML message from a Nokia N95.
My first attempt was to use the python pywbxml module which wraps calls to libwbxml. Decoding the message with this gave a lot of <unknown> tags and a big chunk of binary within a <Collection> tag. I tried running the contents of the <Collection> thr... | I ended up writing a python parser myself. I managed to do it by following the spec here:
<http://www.w3.org/TR/wbxml/>
And then taking the code tables from the horde.org cvs.
The open mobile alliance's site and documentation are terrible, this was a very trying project :( | Funnily enough I've been working on the same problem. I'm about halfway through writing my own pure-Python WBXML parser, but it's not yet complete enough to be useful, and I have very little time to work on it right now.
Those <Unknown> tags might be because pywbxml / libwbxml doesn't have the right tag vocabulary loa... | Decoding a WBXML SyncML message from an S60 device | [
"",
"python",
"s60",
"syncml",
"wbxml",
""
] |
In eclipse 3.4 I'm trying to do some performance tests on a large product, one of the included libraries is the vecmath.jar (javax.vecmath package) from the Java3D project. Everything was working fine and then when trying to run it yesterday I get this exception/error not long after starting it up:
```
java.lang.Unsup... | Could there be another javax.vecmath.Point2f on your classpath? | I believe JRE 1.5 is required for the latest version of Java3D. | Eclipse class version bug | [
"",
"java",
"eclipse",
"class",
"classpath",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.