Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm tired of adding ten link libraries into my project, or requiring eight of them to use my own. I'd like to take existing libraries like libpng.a, libz.a, libjpeg.a, and combine them into one single .a library. Is that possible? How about combining .lib libraries? | On Unix like systems, the ld and ar utilities can do this. Check out <http://en.wikipedia.org/wiki/Ar_(Unix)> or lookup the man pages on any Linux box or through Google, e.g., 'Unix man ar'.
Please note that you might be better off linking to a shared (dynamic) library. This would add a dependency to your executable, ... | You could extract the object files from each library with
```
ar x <library name>
```
and then merge them all into a new library with
```
ar cs <new library name> <list each extracted object file>
``` | How can I combine several C/C++ libraries into one? | [
"",
"c++",
"c",
"archive",
""
] |
I have a Windows C# program that uses a C++ dll for data i/o. My goal is to deploy the application as a single EXE.
What are the steps to create such an executable? | Single Assembly Deployment of Managed and Unmanaged Code
Sunday, February 4, 2007
.NET developers love XCOPY deployment. And they love single assembly components. At least I always feel kinda uneasy, if I have to use some component and need remember a list of files to also include with the main assembly of that compon... | Try [boxedapp](http://boxedapp.com/ "boxedapp sdk"); it allows to load all DLLs from memory. Also, it seems that you can even embed .net runtime. Good to create a really standalone applications... | How can a C++ windows dll be merged into a C# application exe? | [
"",
"c#",
"dll",
"merge",
""
] |
```
$output = preg_replace("|(/D)(/s+)(/d+)(;)|", "//1,//3;", $output);
```
I'm trying to replace all alphabetical character followed by one or more whitespace characters (tabs and/or spaces) followed by one or more numerical characters followed by a semicolon with the alphabetical character followed by a comma follow... | The two `|` at the start and end probably are incorrect - and should both be forward-slashes.
All other forward slashes should be backward slashes (and need escaping).
And since PHP 4.04 `$n` is the preferred way of referring to a capture group.
```
$output = preg_replace("/(\\D)\\s+(\\d+;)/", "$1,$2", $output);
```... | Should those forward-slashes be backslashes? You'll need to escape them for PHP too unless you change your double-quotes to single-quotes. | What is wrong with this PHP regular expression? | [
"",
"php",
"regex",
""
] |
I have a class that map objects to objects, but unlike dictionary it maps them both ways. I am now trying to implement a custom `IEnumerator` interface that iterates through the values.
```
public class Mapper<K,T> : IEnumerable<T>, IEnumerator<T>
{
C5.TreeDictionary<K,T> KToTMap = new TreeDictionary<K,T>();
... | First, don't make your collection object implement IEnumerator<>. This leads to bugs. (Consider the situation where two threads are iterating over the same collection).
Implementing an enumerator correctly turns out to be non-trivial, so C# 2.0 added special language support for doing it, based on the 'yield return' s... | Just implement the `IEnumerable<T>` interface. No need to implement the `IEnumerator<T>` unless you want to do some special things in the enumerator, which for your case doesn't seem to be needed.
```
public class Mapper<K,T> : IEnumerable<T> {
public IEnumerator<T> GetEnumerator()
{
return KToTMap.Val... | How would you implement the IEnumerator interface? | [
"",
"c#",
".net",
"collections",
"ienumerable",
"ienumerator",
""
] |
What is the reason for the following warning in some C++ compilers?
> No newline at end of file
Why should I have an empty line at the end of a source/header file? | Think of some of the problems that can occur if there is no newline. According to the ANSI standard the `#include` of a file at the beginning inserts the file exactly as it is to the front of the file and does not insert the new line after the `#include <foo.h>` after the contents of the file. So if you include a file ... | The requirement that every source file end with a non-escaped newline was removed in C++11. The specification now reads:
> A source file that is not empty and that does not end in a new-line character, or that ends in a new-line character immediately preceded by a backslash character before any such splicing takes pla... | "No newline at end of file" compiler warning | [
"",
"c++",
"compiler-construction",
"warnings",
"c-preprocessor",
""
] |
From time to time I get a System.Threading.ThreadStateException when attempting to restart a thread. The code in question is as follows:
```
// Make sure the thread is done stopping
while (this.mThread.ThreadState == ThreadState.Running)
{
Thread.Sleep(0);
}
// Respawn a thread if the current one is stopped or do... | The problem is that you have code that first checks if it should create a new thread object, and another piece of code that determines wether to start the thread object. Due to race conditions and similar things, your code might end up trying to call .Start on an existing thread object. Considering you don't post the d... | It's possible for a thread to be in more than one state at once therefore the ThreadState property is actually a bitmap of possible states. So testing for equality with just one state will not give you the right result. You would need to do something like:
```
if((mThread.ThreadState & ThreadState.Running) != 0)
```
... | A ThreadStateException occures when trying to restart a thread | [
"",
"c#",
".net",
"multithreading",
"exception",
""
] |
I'm trying to load a page that is basically an edit form inside a
dialog (ui.dialog). I can load this page fine from an external (I'm
using asp.net) page.
The problem is that inside of my "popup" form, I need to `$(function()
{my function here});` syntax to do some stuff when the page loads,
along with registering som... | If you really need to load that form via AJAX you could to do all the Javascript stuff in $.ajax callback itself.
So, you load the popup form like this:
```
$.ajax({
//...
success: function(text) {
// insert text into container
// the code from $(function() {});
}
});
``` | The script isn't getting run because the document's ready event has already been fired. Remove your code from within the
```
$()
``` | using load() to load page that also uses jQuery | [
"",
"javascript",
"jquery",
"jquery-ui",
"jquery-ui-dialog",
"jquery-ui-plugins",
""
] |
Background: At my company we are developing a bunch applications that are using the same core dll's. These dll's are using Spring.net's IoC-container to wire things up (auto-wiring). All applications are using the same spring configuration file, and this configuration file points to many classes in many different dll's... | If none of the code from the assembly is ever used, then eventually the pages from that assembly will be moved from memory into the page file in favour of actively used pages. In which case, the overall long-term effect is likely to be minor. Although, there will be a negative effect on startup time. | I don't think it's so bad. Only problem is that because of large metadata and amount of memory your application takes it's more possible that some parts of application which are in use will be located at different memory pages which can 'cause some performance leaks, but it's very low segment of application where this ... | Is it bad to load many managed DLL's without using any types in them? | [
"",
"c#",
".net",
"dll",
"inversion-of-control",
"spring.net",
""
] |
I want to prevent XSS attacks in my web application. I found that HTML Encoding the output can really prevent XSS attacks. Now the problem is that how do I HTML encode every single output in my application? I there a way to automate this?
I appreciate answers for JSP, ASP.net and PHP. | You don't want to encode all HTML, you only want to HTML-encode any user input that you're outputting.
For PHP: [htmlentities](http://us.php.net/htmlentities) and [htmlspecialchars](http://us.php.net/manual/en/function.htmlspecialchars.php) | One thing that you **shouldn't** do is filter the input data as it comes in. People often suggest this, since it's the easiest solution, but it leads to problems.
Input data can be sent to multiple places, besides being output as HTML. It might be stored in a database, for example. The rules for filtering data sent to... | How do I HTML Encode all the output in a web application? | [
"",
"php",
"asp.net",
"jsp",
""
] |
I have two elements:
```
<input a>
<input b onclick="...">
```
When b is clicked, I want to access a and manipulate some of its data. A does not have a globally unique name, so `document.getElementsByName` is out. Looking into the event object, I thought `event.target.parentNode` would have some function like `getEle... | If `a` and `b` are next to each other and have the same parent, you can use the `prevSibling` property of `b` to find `a`. | 1. You should be able to find the element that was clicked from the [event object](http://www.w3schools.com/htmldom/dom_obj_event.asp). Depending on your browser you might want `e.target` or `e.srcElement`. The code below is from this [w3schools example](http://www.w3schools.com/js/tryit.asp?filename=try_dom_event_srce... | Getting closest element by id | [
"",
"javascript",
"html",
"dom",
""
] |
Am I correct in assuming that the only difference between "windows files" and "unix files" is the linebreak?
We have a system that has been moved from a windows machine to a unix machine and are having troubles with the format.
I need to automate the translation between unix/windows before the files get delivered to ... | This is only a difference in text files, where UNIX uses a single Line Feed (LF) to signify a new line, Windows uses a Carriage Return/Line Feed (CRLF) and Mac uses just a CR.
Binary files there should be no difference (i.e. a JPEG on a windows machine will be byte for byte the same as the same JPEG on a unix box.) | There could also be a difference in character encoding for national characters. There is no "unix-encoding" but many linux-variants use UTF-8 as the default encoding. Mac OS (which is also a unix) uses its own encoding (macroman). I am not sure, what windows default encoding is.
But this could be another source of tro... | Differences between unix and windows files | [
"",
"java",
"windows",
"unix",
"file",
""
] |
I've got a multiline textBox that I would like to have a label on the form displaying the current line and column position of, as Visual Studio does.
I know I can get the line # with GetLineFromCharIndex, but how can I get the column # on that line?
(I really want the Cursor Position on that line, not 'column', per s... | ```
int line = textbox.GetLineFromCharIndex(textbox.SelectionStart);
int column = textbox.SelectionStart - textbox.GetFirstCharIndexFromLine(line);
``` | ```
textBox.SelectionStart -
textBox.GetFirstCharIndexFromLine(textBox.GetLineFromCharIndex(textBox.SelectionStart))
``` | How can I get Column number of the cursor in a TextBox in C#? | [
"",
"c#",
"windows",
"user-interface",
""
] |
I've recently inherited a internationalized and text-heavy Struts 1.1 web application. Many of the JSP files look like:
```
<p>
<bean:message key="alert" />
</p>
```
and the properties files look like:
```
messages.properties
alert=Please update your <a href="/address.do">address</a> and <a href="/contact.do">co... | > Avoid creating links within long
> blocks of text. Prefer shorter text
> that can act as a logically complete
> and independent link.
Generally, it will lead to fewer problems. Sometimes you have to compromise your UI design to accommodate localization; sometimes you need to compromise your localization process to a... | One approach that comes to mind is that you could store the translated replacement parameters i.e. "address" and "contact information" in a separate properties file, one per locale. Then have your Action class (or probably some helper class) look up the values from the correct ResourceBundle for the current locale and ... | How can I refactor HTML markup out of my property files? | [
"",
"java",
"jsp",
"internationalization",
"struts",
""
] |
I'm using ADO.NET to access SQL Server 2005 and would like to be able to log from inside the T-SQL stored procedures that I'm calling. Is that somehow possible?
I'm unable to see output from the 'print'-statement when using ADO.NET and since I want to use logging just for debuging the ideal solution would be to emit m... | I solved this by writing a SQLCLR-procedure as Eric Z Beard suggested. The assembly must be signed with a strong name key file.
```
using System;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using Microsoft.SqlServer.Server;
public partial class StoredProcedures
{
[Microsoft.SqlServ... | I think writing to a log table would be my preference.
Alternatively, as you are using 2005, you could write a simple SQLCLR procedure to wrap around the EventLog.
Or you could use **xp\_logevent** if you wanted to write to SQL log | How to log in T-SQL | [
"",
"sql-server",
"t-sql",
"logging",
"ado.net",
"sql",
""
] |
I have been playing with the Ruby library "shoes". Basically you can write a GUI application in the following way:
```
Shoes.app do
t = para "Not clicked!"
button "The Label" do
alert "You clicked the button!" # when clicked, make an alert
t.replace "Clicked!" # ..and replace the label's text
end
end
```... | You could actually pull this off, but it would require using metaclasses, which are *deep* magic (there be dragons). If you want an intro to metaclasses, there's a series of [articles from IBM](http://www.ibm.com/developerworks/linux/library/l-pymeta.html) which manage to introduce the ideas without melting your brain.... | This is extremely contrived and not pythonic at all, but here's my attempt at a semi-literal translation using the new "with" statement.
```
with Shoes():
t = Para("Not clicked!")
with Button("The Label"):
Alert("You clicked the button!")
t.replace("Clicked!")
```
The hardest part is dealing with the fact... | How would you design a very "Pythonic" UI framework? | [
"",
"python",
"user-interface",
"frameworks",
""
] |
If you declare variables of type byte or short and attempt to perform arithmetic operations on these, you receive the error "Type mismatch: cannot convert int to short" (or correspondingly "Type mismatch: cannot convert int to byte").
```
byte a = 23;
byte b = 34;
byte c = a + b;
```
In this example, the compile erro... | Although the arithmetic operators are defined to operate on any numeric type, according the Java language specification (5.6.2 Binary Numeric Promotion), operands of type byte and short are automatically promoted to int before being handed to the operators.
To perform arithmetic operations on variables of type byte or... | The answer to your follow-up question is here:
> operands of type byte and short are automatically promoted to int before being handed to the operators
So, in your example, `a` and `b` are both converted to an `int` before being handed to the + operator. The result of adding two `int`s together is also an `int`. Tryi... | Java: why do I receive the error message "Type mismatch: cannot convert int to byte" | [
"",
"java",
"type-conversion",
"byte",
"type-mismatch",
""
] |
I wrote a quick program in python to add a gtk GUI to a cli program. I was wondering how I can create an installer using distutils. Since it's just a GUI frontend for a command line app it only works in \*nix anyway so I'm not worried about it being cross platform.
my main goal is to create a .deb package for debian/u... | See the [distutils simple example](http://docs.python.org/dist/simple-example.html). That's basically what it is like, except real install scripts usually contain a bit more information. I have not seen any that are fundamentally more complicated, though. In essence, you just give it a list of what needs to be installe... | `apt-get install python-stdeb`
Python to Debian source package conversion utility
This package provides some tools to produce Debian packages from Python packages via a new distutils command, sdist\_dsc. Automatic defaults are provided for the Debian package, but many aspects of the resulting package can be customize... | How to use Python distutils? | [
"",
"python",
"linux",
"installation",
"debian",
"distutils",
""
] |
Can anyone provide a good explanation of the [`volatile`](https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/volatile) keyword in C#? Which problems does it solve and which it doesn't? In which cases will it save me the use of locking? | I don't think there's a better person to answer this than [Eric Lippert](https://ericlippert.com/2011/06/16/atomicity-volatility-and-immutability-are-different-part-three/) (emphasis in the original):
> In C#, "volatile" means not only "make sure that the compiler and the
> jitter do not perform any code reordering or... | If you want to get slightly more technical about what the volatile keyword does, consider the following program (I'm using DevStudio 2005):
```
#include <iostream>
void main()
{
int j = 0;
for (int i = 0 ; i < 100 ; ++i)
{
j += i;
}
for (volatile int i = 0 ; i < 100 ; ++i)
{
j += i;
}
std::cout... | When should the volatile keyword be used in C#? | [
"",
"c#",
"multithreading",
"volatile",
"lock-free",
""
] |
I want to be able to generate PDF output from my (native) C++ Windows application. Are there any free/open source libraries available to do this?
I looked at the answers to [this question](https://stackoverflow.com/questions/177/how-do-i-programmatically-create-a-pdf-in-my-net-application), but they mostly relate to .... | [LibHaru](https://github.com/libharu/libharu)
> Haru is a free, cross platform,
> open-sourced software library for
> generating PDF written in ANSI-C. It
> can work as both a static-library (.a,
> .lib) and a shared-library (.so,
> .dll).
Didn't try it myself, but maybe it can help you | I worked on a project that required a pdf report. After searching for online I found the PoDoFo library. Seemed very robust. I did not need all the features, so I created a wrapper to abstract away some of the complexity. Wasn't too difficult. You can find the library here:
<http://podofo.sourceforge.net/>
Enjoy! | Open source PDF library for C/C++ application? | [
"",
"c++",
"c",
"pdf",
"open-source",
""
] |
I'm trying to use some data from a PlanPlusOnline account. They only provide a java web services API. The server for the site where the data will be used does not allow me to install Tomcat (edit: or a JVM for that matter). I'm not going to lie, I am a Java software engineer, and I do some web work on the side. I'm not... | To follow up with jodonnell's comment, a Web service connection can be made in just about any server-side language. It is just that the API example they provided was in Java probably because PlanPlusOnline is written in Java. If you have a URL for the service, and an access key, then all you really need to do is figure... | Are you trying to implement a client to a web service hosted somewhere else? If so, Java's not necessary. You can do web service clients in [.NET](http://www.dotnetjunkies.ddj.com/Tutorial/4D13CEFA-D0FD-44BE-8749-8D17B5757564.dcik), [PHP](http://sourceforge.net/projects/nusoap/), [Ruby](http://raa.ruby-lang.org/project... | Java Web Services API, however I can't run a JVM on my server | [
"",
"java",
"json",
"web-services",
""
] |
We have a situation in our product where for a long time some data has been stored in the application's database as SQL string (choice of MS SQL server or sybase SQL anywhere) which was encrypted via the Windows API function [CryptEncrypt.](http://msdn.microsoft.com/en-us/library/aa379924.aspx) (direct and de-cryptable... | Any semi-decent algorithm will end up with a strong chance of generating a NULL value somewhere in the resulting ciphertext.
Why not do something like [base-64 encode](http://en.wikipedia.org/wiki/Base64) your resulting binary blob before persisting to the DB? ([sample implementation in C++](http://synesis.com.au/soft... | Storing a hash is a good idea. However, please definitely read Jeff's [You're Probably Storing Passwords Incorrectly](http://www.codinghorror.com/blog/archives/000953.html). | Suitable alternative to CryptEncrypt | [
"",
"c++",
"encryption",
"winapi",
""
] |
I am thinking of using a PHP framework called [CodeIgniter](http://codeigniter.com/).
One of the things I am interested in is its speed. I have, however, no way to find out how fast it is, and would rather not simply take the word of their website for it. Does anybody know how I can determine its speed myself, or can ... | Code Igniter also has some built-in benchmarking tools:
<http://codeigniter.com/user_guide/general/profiling.html> | Yes, the problem is you have to build your application to profile it.
At work we had a couple of projects written outside which we load-tested before putting them on our main boxes. We were quite surprised to find critical performance problems with both; one was written in CakePHP and the other was written using Drupa... | How can I determine CodeIgniter speed? | [
"",
"php",
"performance",
"codeigniter",
"benchmarking",
""
] |
I want to copy the entire contents of a directory from one location to another in C#.
There doesn't appear to be a way to do this using `System.IO` classes without lots of recursion.
There is a method in VB that we can use if we add a reference to `Microsoft.VisualBasic`:
```
new Microsoft.VisualBasic.Devices.Comput... | Much easier
```
private static void CopyFilesRecursively(string sourcePath, string targetPath)
{
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(sourcePath, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(sourcePath, targetPath)... | Hmm, I think I misunderstand the question but I'm going to risk it. What's wrong with the following straightforward method?
```
public static void CopyFilesRecursively(DirectoryInfo source, DirectoryInfo target) {
foreach (DirectoryInfo dir in source.GetDirectories())
CopyFilesRecursively(dir, target.Creat... | Copy the entire contents of a directory in C# | [
"",
"c#",
".net",
"directory",
"copy",
""
] |
I am trying to implement AJAX in my Google App Engine application, and so I am looking for a good AJAX framework that will help me. Anyone has any idea?
I am thinking about Google Web Toolkit, how good it is in terms of creating AJAX for Google App Engine? | As Google Web Toolkit is a [subset of Java](http://code.google.com/support/bin/answer.py?answer=54830&topic=10208) it works best when you Java at the backend too. Since Google App Engine is currently [Python only](http://code.google.com/appengine/kb/general.html#language) I think you'd have to do a lot of messing about... | A nice way is to use an AJAX library is to take advantage of [Google's AJAX Libraries API service](http://code.google.com/apis/ajaxlibs/). This is a bit faster and cleaner than downloading the JS and putting it in your `/static/` folder and doesn't eat into your disk quota.
In your javascript you would just put, for e... | Any good AJAX framework for Google App Engine apps? | [
"",
"python",
"ajax",
"google-app-engine",
""
] |
Which parsers are available for parsing C# code?
I'm looking for a C# parser that can be used in C# and give me access to line and file informations about each artefact of the analysed code. | Works on source code:
* [CSParser](http://www.codeplex.com/csparser):
From C# 1.0 to 2.0, open-source
* [Metaspec C# Parser](http://www.csharpparser.com/csparser.php):
From C# 1.0 to 3.0, commercial product (about 5000$)
* [#recognize!](http://www.sharprecognize.com/):
From C# 1.0 to 3.0, commercial product (abo... | [Mono](http://www.mono-project.com/) (open source) includes C# compiler (and of course parser) | Which parsers are available for parsing C# code? | [
"",
"c#",
"parsing",
""
] |
I've got a [site](http://notebooks.readerville.com/) that provides blog-friendly widgets via JavaScript. These work fine in most circumstances, including self-hosted Wordpress blogs. With blogs hosted at Wordpress.com, however, JavaScript isn't allowed in sidebar text modules. Has anyone seen a workaround for this limi... | you could always petition wp to add your widget to their 'approved' list, but who knows how long that would take. you're talking about a way to circumvent the rules they have in place about posting arbitrary script. myspace javascript exploits in particular have increased awareness of the possibility of such workaround... | From the official [WordPress.com FAQ](http://faq.wordpress.com/2006/05/07/javascript-can-i-use-that-on-my-blog/):
> Javascript can be used for malicious purposes and while what you want to do is okay it does not mean all javascript will be okay.
It goes on to remind the reader that both MySpace and LiveJournal had be... | How do you add a JavaScript widget to a Wordpress.com hosted blog? | [
"",
"javascript",
"wordpress",
"widget",
""
] |
I have a UserControl that consists of three TextBoxes. On a form I can have one or more or my UserControl. I want to implement my own tab behavior so if the user presses Tab in the second TextBox I should only move to the third TextBox if the the second TextBox has anything entered. If nothing is entered in the second ... | As a general rule, I would say overriding the standard behavior of the TAB key would be a bad idea. Maybe you can do something like disabling the 3rd text box until a valid entry is made in the 2nd text box.
*Now, having said this, I've also broken this rule at the request of the customer. We made the enter key functi... | The reason for this odd tab behavior is all about speed in the input process. It was really good to get some input, I hadn't thought about disabling a textbox but that could actually work. But using the Enter key to accept the input hadn't even crossed my mind. That will work so much better. The user can enter the numb... | Override tab behavior in WinForms | [
"",
"c#",
".net",
"winforms",
""
] |
here is what a I'm doing:
```
object ReturnMatch(System.Type type)
{
foreach(object obj in myObjects)
{
if (obj == type)
{
return obj;
}
}
}
```
However, if obj is a subclass of `type`, it will not match. But I would like the function to return the same ... | I've used the IsAssignableFrom method when faced with this problem.
```
Type theTypeWeWant; // From argument or whatever
foreach (object o in myCollection)
{
if (theTypeWeWant.IsAssignableFrom(o.GetType))
return o;
}
```
Another approach that may or may not work with your problem is to use a generic meth... | Not using the is operator, but the Type.IsInstanceOfType Method appears to be what you're looking for.
<http://msdn.microsoft.com/en-us/library/system.type.isinstanceoftype.aspx> | How to use the "is" operator in System.Type variables? | [
"",
"c#",
""
] |
I've got a div that uses overflow:auto to keep the contents inside the div as it is resized and dragged around the page. I'm using some ajax to retrieve lines of text from the server, then append them to the end of the div, so the content is growing downwards. Every time this happens, I'd like to use JS to scroll the d... | `scrollHeight` should be the total height of content. `scrollTop` specifies the pixel offset into that content to be displayed at the top of the element's client area.
So you really want (still using jQuery):
```
$("#thediv").each( function()
{
// certain browsers have a bug such that scrollHeight is too small
... | [`scrollIntoView`](https://developer.mozilla.org/en/DOM/element.scrollIntoView)
> The **scrollIntoView** method scrolls the element into view. | Scrolling Overflowed DIVs with JavaScript | [
"",
"javascript",
"jquery",
"ajax",
"html",
"scroll",
""
] |
I'm working with a team that's building an engine for a variety of 2D and eventually 3D mini-games. The problem we're facing is a solid, cross-platform, sound API. Obviously, DirectX is out of the question due to our needs for cross-platform capabilities. SDL is nice, and works great, but let's face it SDL\_Mixer is a ... | *(note: I have experience with FMOD, BASS, OpenAL and DirectSound; and while I list other libraries below, I haven't used them).*
[BASS](http://www.un4seen.com/) and [FMOD](http://www.fmod.org/) are both good (and actually I liked FMOD's documentation a lot; why would you say it's "non existing"?). There are also [Mil... | I have used DirectX, FMOD and Wwise on a range of platforms in shipped games. I won't talk about DirectX here since other people will have plenty of feedback here ;-)
Here's what you need to consider:
* License, I put this first because this may make your decision for you. Have your lawyer go over them and make sure ... | Game Development Sound Frameworks | [
"",
"c++",
"openal",
"audio",
""
] |
I'm trying to use the following code but it's returning the wrong day of month.
```
Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
cal.set(Calendar.MONTH, sampleDay.get(Calendar.MONTH)+1);
cal.set(Calendar.DAY_OF_MONTH, 0);
return cal.getTime();
``` | Get the number of days for this month:
```
Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
int noOfLastDay = cal.getActualMaximum(Calendar.DAY_OF_MONTH);
```
Set the Calendar to the last day of this month:
```
Calendar cal = Calendar.getInstance();
cal.setTime(sampleDay.getTime());
cal.set(C... | I would create a date object for the first day of the NEXT month, and then just subtract a single day from the date object. | Given a Date Object how do I determine the last day of its month? | [
"",
"java",
"date",
""
] |
When a user goes to my site, my script checks for 2 cookies which store the user id + part of the password, to automatically log them in.
It's possible to edit the contents of cookies via a cookie editor, so I guess it's possible to add some malicious content to a written cookie?
Should I add `mysql_real_escape_strin... | What you *really* need to do is not send these cookie values that are hackable in the first place. Instead, why not hash the username and password and a (secret) salt and set that as the cookie value? i.e.:
```
define('COOKIE_SALT', 'secretblahblahlkdsfklj');
$cookie_value = sha1($username.$password.COOKIE_SALT);
```
... | The point of mysql\_real\_escape\_string isn't to protect against injection attacks, it's to ensure your data is accurately stored in the database. Thus, it should be called on ANY string going into the database, regardless of its source.
You should, however, *also* be using parameterized queries (via mysqli or PDO) t... | Should I mysql_real_escape_string all the cookies I get from the user to avoid mysql injection in php? | [
"",
"php",
"validation",
""
] |
A tutorial I have on Regex in python explains how to use the re module in python, I wanted to grab the URL out of an A tag so knowing Regex I wrote the correct expression and tested it in my regex testing app of choice and ensured it worked. When placed into python it failed:
```
result = re.match("a_regex_of_pure_awe... | In Python, there's a distinction between "match" and "search"; match only looks for the pattern at the start of the string, and search looks for the pattern starting at any location within the string.
[Python regex docs](http://docs.python.org/lib/module-re.html)
[Matching vs searching](http://docs.python.org/lib/ma... | ```
from BeautifulSoup import BeautifulSoup
soup = BeautifulSoup(your_html)
for a in soup.findAll('a', href=True):
# do something with `a` w/ href attribute
print a['href']
``` | Python and "re" | [
"",
"python",
"regex",
""
] |
Is it possible to use an **IF** clause within a **WHERE** clause in MS SQL?
Example:
```
WHERE
IF IsNumeric(@OrderNumber) = 1
OrderNumber = @OrderNumber
ELSE
OrderNumber LIKE '%' + @OrderNumber + '%'
``` | Use a [CASE](http://msdn.microsoft.com/en-us/library/ms181765.aspx) statement
**UPDATE:** The previous syntax (as pointed out by a few people) doesn't work. You can use CASE as follows:
```
WHERE OrderNumber LIKE
CASE WHEN IsNumeric(@OrderNumber) = 1 THEN
@OrderNumber
ELSE
'%' + @OrderNumber
END
```
... | You should be able to do this without any IF or CASE
```
WHERE
(IsNumeric(@OrderNumber) AND
(CAST OrderNumber AS VARCHAR) = (CAST @OrderNumber AS VARCHAR)
OR
(NOT IsNumeric(@OrderNumber) AND
OrderNumber LIKE ('%' + @OrderNumber))
```
Depending on the flavour of SQL you may need to tweak the cast... | SQL: IF clause within WHERE clause | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Nant seems very compiler-centric - which is guess is because it's considered a .NET development system. But I know it can be done! I've seen it. The platform we're building on has its own compiler and doesn't use 'cl.exe' for c++. We're building a C++ app on a different platform and would like to override with our own ... | Here is one I did for Delphi. Each 'arg' is a separate param with a value defined elsewhere. The target is called with the params set up before calling it.
```
<target name="build.application">
<exec program="dcc32" basedir="${Delphi.Bin}" workingdir="${Application.Folder}" verbose="true">
<arg value="${Ap... | You need to write your own task. [This](http://www.atalasoft.com/cs/blogs/jake/archive/2008/05/07/writing-custom-nant-tasks.aspx) is a nice reference. | How do I use my own compiler with Nant? | [
"",
"c++",
"build",
"cross-platform",
"makefile",
"nant",
""
] |
I've kind of backed myself into a corner here.
I have a series of UserControls that inherit from a parent, which contains a couple of methods and events to simplify things so I don't have to write lines and lines of near-identical code. As you do. The parent contains no other controls.
What I want to do is just have ... | Declare the parent method virtual, override it in the child classes and call
```
base.checkReadyness(sender, e);
```
(or derevation thereof) from within the child class. This allows for future design evolution say if you want to do some specific error checking code before calling the parent event handler. You might n... | I've just come across this one as well, I agree that it feels like you're doing everything correctly. Declaring the method virtual is a work-around at best, not a solution.
What is being done is valid - a control which only exists in the derived class, and the derived class is attaching an event handler to one of that... | Inheriting Event Handlers in C# | [
"",
"c#",
"events",
"inheritance",
""
] |
How would you design a database to support the following tagging features:
* items can have a large number of tags
* searches for all items that are tagged with a given set of tags must be quick (the items must have ALL tags, so it's an AND-search, not an OR-search)
* creating/writing items may be slower to enable qui... | About ANDing: It sounds like you are looking for the "relational division" operation. [This article](http://www.dbazine.com/ofinterest/oi-articles/celko1) covers relational division in concise and yet comprehendible way.
About performance: A bitmap-based approach intuitively sounds like it will suit the situation well... | Here's a good article on tagging Database schemas:
<http://howto.philippkeller.com/2005/04/24/Tags-Database-schemas/>
along with performance tests:
<http://howto.philippkeller.com/2005/06/19/Tagsystems-performance-tests/>
Note that the conclusions there are very specific to MySQL, which (at least in 2005 at the tim... | Database Design for Tagging | [
"",
"sql",
"database-design",
"tags",
"tagging",
""
] |
In most C or C++ environments, there is a "debug" mode and a "release" mode compilation.
Looking at the difference between the two, you find that the debug mode adds the debug symbols (often the -g option on lots of compilers) but it also disables most optimizations.
In "release" mode, you usually have all sorts of... | Without any optimization on, the flow through your code is linear. If you are on line 5 and single step, you step to line 6. With optimization on, you can get instruction re-ordering, loop unrolling and all sorts of optimizations.
For example:
```
void foo() {
1: int i;
2: for(i = 0; i < 2; )
3: i++;
4: return... | Another crucial difference between debug and release is how local variables are stored. Conceptually local variables are allocated storage in a functions stack frame. The symbol file generated by the compiler tells the debugger the offset of the variable in the stack frame, so the debugger can show it to you. The debug... | Why does a C/C++ program often have optimization turned off in debug mode? | [
"",
"c++",
"c",
"compiler-construction",
""
] |
What's the "best" (taking both speed and readability into account) way to determine if a list is empty? Even if the list is of type `IEnumerable<T>` and doesn't have a Count property.
Right now I'm tossing up between this:
```
if (myList.Count() == 0) { ... }
```
and this:
```
if (!myList.Any()) { ... }
```
My gue... | You could do this:
```
public static Boolean IsEmpty<T>(this IEnumerable<T> source)
{
if (source == null)
return true; // or throw an exception
return !source.Any();
}
```
**Edit**: Note that simply using the .Count method will be fast if the underlying source actually has a fast Count property. A val... | I would make one small addition to the code you seem to have settled on: check also for `ICollection`, as this is implemented even by some non-obsolete generic classes as well (i.e., `Queue<T>` and `Stack<T>`). I would also use `as` instead of `is` as it's more idiomatic and [has been shown to be faster](http://www.cod... | Checking if a list is empty with LINQ | [
"",
"c#",
".net",
"linq",
"list",
""
] |
Feel free to edit the title if you know how to formulate the question better. (Tagging is a problem as well.) The problem may be too difficult in this general form, so let us consider a concrete example.
You get a screenful of stackoverflow questions by requesting `/questions ?sort=newest` page. Next page link leads t... | This can't be done an easy way. For instance, the "Unanswered" list here at stackoverflow is sorted by number of votes. So if you'd save the last ID of the page you're viewing (in a cookie, request, session, whereever) and someone upvotes a post while you're browsing page 2, page 3 isn't complete since the recently upv... | Most web sites I've seen don't solve this problem - they show you a page including some content you've already seen.
You might consider that a feature - when you click "next" and see some content you're seen before, it's a signal that you want to go back to the front again because there's some new content. | How to provide next page of updated content? | [
"",
"sql",
"paging",
""
] |
Any suggestions for good open source asp.net (C#) apps out there which meet as many of the following:?
1. Designed well and multi tiered
2. Clean & commented code
3. Good use of several design patterns
4. Web pages display properly in all common browsers
5. Produces valid html and has good use of css
6. Use of css the... | I would have to agree with [BlogEngine](http://www.dotnetblogengine.net/). It implements a ton of different abilities and common needs in asp.net as well as allowing it to be fully customizable and very easy to understand. It can work with XML or SQL (your choice) and has a huge community behind it.
As for your reques... | You should have a look at [SharpArchitecture](http://code.google.com/p/sharp-architecture/) which uses ASP.NET MVC, and which is an open source architecture foundation for web applications. | Good asp.net (C#) apps? | [
"",
"c#",
"asp.net",
"css",
"design-patterns",
""
] |
How best to make the selected date of an ASP.NET Calendar control available to JavaScript?
Most controls are pretty simple, but the calendar requires more than just a simple *document.getElementById().value*. | When you click on a date with the calendar, ASP does a postback, you could always put the SelectedDate value of the calendar control into a hidden field on the page during the OnLoad event of the page or the SelectionChanged event of the Calendar control. | I'm using Page.ClientScript.RegisterClientScriptBlock() to put a small script on the page that just declare a variable with the desired value. I was hoping for some a little less... clunky. | How best to make the selected date of an ASP.NET Calendar control available to JavaScript? | [
"",
"asp.net",
"javascript",
"calendar",
""
] |
*(see [here](https://stackoverflow.com/questions/53316/hibernate-crops-clob-values-oddly) for the problem I'm trying to solve)*
How do you get hibernate to log clob values it's going to insert. It is logging other value types, such as Integer etc.
I have the following in my log4j config:
```
log4j.logger.net.sf.hibe... | Try using:
```
log4j.logger.net.sf.hibernate=DEBUG
log4j.logger.org.hibernate=DEBUG
```
That's the finest level you'll get. If it does not show the information you want, then it's not possible. | Well, it looks like you can't. *(Thanks [Marcio](https://stackoverflow.com/questions/53365/getting-hibernate-to-log-clob-parameters#53419) for the suggestion, but sadly that didn't add anything useful)* | Getting hibernate to log clob parameters | [
"",
"java",
"oracle",
"hibernate",
""
] |
I've recently started developing applications for the Blackberry. Consequently, I've had to jump to Java-ME and learn that and its associated tools. The syntax is easy, but I keep having issues with various gotchas and the environment.
For instance, something that surprised me and wasted a lot of time is absence of re... | This [guy here](http://crfdesign.net/programming/top-10-differences-between-java-and-c) had to make the inverse transition. So he listed the top 10 differences of Java and C#. I'll take his topics and show how it is made in Java:
## Gotcha #10 - Give me my standard output!
To print to the standard output in Java:
``... | Java is not significantly different from C#. On a purely syntactic level, here are some pointers that may get you through the day:
1. In Java you have two families of exceptions: `java.lang.Exception` and everything that derives from it, and `RuntimeException`. This is meaningful because in Java exceptions are *checke... | Best way to really grok Java-ME for a C# guy | [
"",
"c#",
"blackberry",
"java-me",
"migration",
""
] |
How to center text over an image in a table cell using javascript, css, and/or html?
I have an HTML table containing images - all the same size - and I want to center a text label over each image. The text in the labels may vary in size. Horizontal centering is not difficult, but vertical centering is.
ADDENDUM: i di... | you could try putting the images in the background.
```
<table>
<tr>
<td style="background: url(myImg.jpg) no-repeat; vertical-align: middle; text-align: center">
Here is my text
</td>
</tr>
</table>
```
You'll just need to set the height and width on the cell and that should be it... | There's no proper way of doing it in CSS (although there should be). But here's a method that works for me.
CSS:
```
#image1, #image1-text, #image1-container {
overflow: hidden;
height: 100px;
width: 100px;
}
#image1 {
top: -100px;
position: relative;
z-index: -1;
}
#image1-text {
text-align: center;
... | How to center text over an image in a table using javascript, css, and/or html? | [
"",
"javascript",
"html",
"css",
""
] |
I have ASP.NET web pages for which I want to build automated tests (using WatiN & MBUnit). How do I start the ASP.Net Development Server from my code? I do not want to use IIS. | From what I know, you can fire up the dev server from the command prompt with the following path/syntax:
```
C:\Windows\Microsoft.NET\Framework\v2.0.50727\Webdev.WebServer.exe /port:[PORT NUMBER] /path: [PATH TO ROOT]
```
...so I could imagine you could easily use Process.Start() to launch the particulars you need th... | This is what I used that worked:
```
using System;
using System.Diagnostics;
using System.Web;
...
// settings
string PortNumber = "1162"; // arbitrary unused port #
string LocalHostUrl = string.Format("http://localhost:{0}", PortNumber);
string PhysicalPath = Environment.CurrentDirectory // the path of compiled web... | How can I programmatically run the ASP.Net Development Server using C#? | [
"",
"c#",
"asp.net",
""
] |
anyone have any experience using this?
if so, is it worth while? | I just used jdb for the first time yesterday and am really pleased with the results. You see, I program in Eclipse on my laptop, then deploy to a VM to make sure the whole shebang still works. Very occasionaly, I'll have to work on something that gets executed standalone, as a commandline. These things sometimes need d... | Assume your program is started by the following command:
```
java -Xdebug -Xrunjdwp:transport=dt_socket,server=y,address=<port> <class>
```
You can attach to this process by jdb:
```
jdb -attach <port>
```
In some cases you need to use the following command .
```
jdb -sourcepath \.src -connect com.sun.jdi.SocketA... | Java jdb remote debugging command line tool | [
"",
"java",
"jdb",
""
] |
How to implement a web page that scales when the browser window is resized?
I can lay out the elements of the page using either a table or CSS float sections, but i want the display to rescale when the browser window is resized
i have a working solution using AJAX PRO and DIVs with overflow:auto and an onwindowresize... | instead of using in css say "width: 200px", use stuff like "width: 50%"
This makes it use 50% of whatever it's in, so in the case of:
```
<body>
<div style="width:50%">
<!--some stuff-->
</div>
</body>
```
The div will now always take up half the window horizontaly. | Unless you have some specific requirement here I'm not sure why JS is needed here. Tabular layouts are the easy (and archaic) way to make fluid layouts in html, but div layouts with css allow for fluid layouts as well, see <http://www.glish.com/css/2.asp> | How to implement a web page that scales when the browser window is resized? | [
"",
"javascript",
"html",
"css",
"ajax",
""
] |
Does anyone have examples of how to use [DBMS\_APPLICATION\_INFO](http://www.oracle-base.com/articles/8i/DBMS_APPLICATION_INFO.php) package with JBOSS?
We have a various applications which run within JBOSS and share db pools. I would like, at the start of each session these applications to identify themselves to the d... | yes, you can write a wrapper class around your connection pool, and a wraper around the connection
so lets say you have:
```
OracleConnection conn=connectionPool.getConnection("java:scott@mydb");
```
Change it to:
```
public class LoggingConnectionPool extends ConnectionPool{
public OracleConnection getConnectio... | If you are using JBoss, you can use a "valid-connection-checker".
This class is normaly used to check the validity of the Connection.
But, as it will be invoked every time the Connection pool gives the user a Connection, you can use it to set the DBMS\_ APPLICATION \_INFO.
You declare such a class in the oracle-ds.xml... | using DBMS_APPLICATION_INFO with Jboss | [
"",
"java",
"oracle",
"jboss",
""
] |
Hey so what I want to do is snag the content for the first paragraph. The string `$blog_post` contains a lot of paragraphs in the following format:
```
<p>Paragraph 1</p><p>Paragraph 2</p><p>Paragraph 3</p>
```
The problem I'm running into is that I am writing a regex to grab everything between the first `<p>` tag an... | Well, sysrqb will let you match anything in the first paragraph assuming there's no other html in the paragraph. You might want something more like this
```
<p>.*?</p>
```
Placing the `?` after your `*` makes it non-greedy, meaning it will only match as little text as necessary before matching the `</p>`. | If you use `preg_match`, use the **"U"** flag to make it un-greedy.
```
preg_match("/<p>(.*)<\/p>/U", $blog_post, &$matches);
```
`$matches[1]` will then contain the first paragraph. | How to grab the contents of HTML tags? | [
"",
"php",
"html",
"regex",
"html-parsing",
""
] |
I know the answer is not going to be simple, and I already use a couple of (I think ugly) cludges. I am simply looking for some elegant answers.
Abstract class:
```
public interface IOtherObjects;
public abstract class MyObjects<T> where T : IOtherObjects
{
...
public List<T> ToList()
{
...
}
}
`... | If you have
```
class B : A
class C : A
```
And you have
```
List<B> listB;
List<C> listC;
```
that you wish to treat as a List of the parent type
Then you should use
```
List<A> listA = listB.Cast<A>().Concat(listC.Cast<A>()).ToList()
``` | In your case MyObjectsA and MyObjectsB don't have common predecessor. Generic class is template for *different* classes not a common base class. If you want to have common properties in different classes use interfaces. You can't call *ToList* in a loop cause it has different signature in different classes. You can cre... | Suggestions wanted with Lists or Enumerators of T when inheriting from generic classes | [
"",
"c#",
"generics",
""
] |
In a few weeks, we'll be teaching a crash course on C++ for Java programmers straight out of college. They have little or no experience yet with C or C++.
Previous editions of this course were just 1 or 2 half-day sessions and covered topics including:
* new language features, e.g.
+ header vs. implementation
+ p... | I can only once again point to [Stroustrup](http://www.research.att.com/~bs/new_learning.pdf) and preach: Don't teach the C subset! It's important, but not for beginners! C++ is complex enough as it is and the standard library classes, especially the STL, is much more important and (at least superficially) easier to un... | If they are coming from a Java world, they are used to garbage collection. As such, I'd probably spend a bit of time talking about smart (reference counted) pointers, and how they compare to garbage collection. | How to teach a crash course on C++? | [
"",
"c++",
""
] |
Can someone explain this result to me. The first test succeeds but the second fails, although the variable tested is changed in the first test.
```
>>> class MyTest(unittest.TestCase):
def setUp(self):
self.i = 1
def testA(self):
self.i = 3
self.assertEqual(self.i, 3)
def testB(self... | Each test is run using a new instance of the MyTest class. That means if you change self in one test, changes will not carry over to other tests, since self will refer to a different instance.
Additionally, as others have pointed out, setUp is called before each test. | From <http://docs.python.org/lib/minimal-example.html> :
> When a setUp() method is defined, the
> test runner will run that method prior
> to each test.
So setUp() gets run before both testA and testB, setting i to 1 each time. Behind the scenes, the entire test object is actually being re-instantiated for each test... | Python's unittest logic | [
"",
"python",
"unit-testing",
""
] |
Has anyone else found VIM's syntax highlighting of Javascript sub-optimal? I'm finding that sometimes I need to scroll around in order to get the syntax highlighting adjusted, as sometimes it mysteriously drops all highlighting.
Are there any work-arounds or ways to fix this? I'm using vim 7.1. | You might like to try this [improved Javascript syntax highlighter](http://www.vim.org/scripts/script.php?script_id=1491) rather than the one that ships with VIMRUNTIME. | Well, I've modified [Yi Zhao's Javascript Syntax](http://www.vim.org/scripts/script.php?script_id=1491), and added Ajax Keywords support, also highlight DOM Methods and others.
Here it is, it is far from being perfect as I'm still new to Vim, but so far it has work for me. [My Javascript Syntax](http://www.vim.org/scr... | Javascript syntax highlighting in vim | [
"",
"javascript",
"vim",
"editing",
"vim-syntax-highlighting",
""
] |
My boss found a bug in a query I created, and I don't understand the reasoning behind the bug, although the query results prove he's correct. Here's the query (simplified version) before the fix:
```
select PTNO,PTNM,CATCD
from PARTS
left join CATEGORIES on (CATEGORIES.CATCD=PARTS.CATCD);
```
and here it is after th... | I'm afraid I can't tell you why you're not getting an exception, but I can postulate as to why it chose CATEGORIES' version of the column over PARTS' version.
> As far as I understood, in the case of left joins, the "main" table in the query (PARTS) has precedence in ambiguity
It's not clear whether by "main" you mea... | > Here's the query (simplified version)
I think by simplifying the query you removed the real cause of the bug :-)
What oracle version are you using? Oracle 10g ( 10.2.0.1.0 ) gives:
```
create table parts (ptno number , ptnm number , catcd number);
create table CATEGORIES (catcd number);
select PTNO,PTNM,CATCD f... | Ambiguity in Left joins (oracle only?) | [
"",
"sql",
"oracle",
"join",
""
] |
I'm evaluating and looking at using CherryPy for a project that's basically a JavaScript front-end from the client-side (browser) that talks to a Python web service on the back-end. So, I really need something fast and lightweight on the back-end that I can implement using Python that then speaks to the PostgreSQL DB v... | SQLAlchemy is more full-featured and powerful (uses the DataMapper pattern). Django ORM has a cleaner syntax and is easier to write for (ActiveRecord pattern). I don't know about performance differences.
SQLAlchemy also has a [declarative layer](http://docs.sqlalchemy.org/en/rel_0_9/orm/extensions/declarative/index.ht... | If you're looking for lightweight and are already familiar with django-style declarative models, check out peewee:
<https://github.com/coleifer/peewee>
Example:
```
import datetime
from peewee import *
class Blog(Model):
name = CharField()
class Entry(Model):
blog = ForeignKeyField(Blog)
title = CharFie... | What are some good Python ORM solutions? | [
"",
"python",
"orm",
""
] |
I am running an application through gdb and I want to set a breakpoint for any time a specific variable is accessed / changed. Is there a good method for doing this? I would also be interested in other ways to monitor a variable in C/C++ to see if/when it changes. | *watch* only breaks on write, *rwatch* let you break on read, and *awatch* let you break on read/write.
You can set read watchpoints on memory locations:
```
gdb$ rwatch *0xfeedface
Hardware read watchpoint 2: *0xfeedface
```
but one limitation applies to the rwatch and awatch commands; you can't use gdb variables
i... | What you're looking for is called a *watchpoint*.
**Usage**
`(gdb) watch foo`: watch the value of **variable** `foo`
`(gdb) watch *(int*)0x12345678`: watch the value pointed by an **address**, casted to whatever type you want
`(gdb) watch a*b + c/d`: watch an arbitrarily **complex expression**, valid in the program... | Can I set a breakpoint on 'memory access' in GDB? | [
"",
"c++",
"debugging",
"gdb",
"breakpoints",
"memory-access",
""
] |
While creating classes in Java I often find myself creating instance-level collections that I know ahead of time will be very small - less than 10 items in the collection. But I don't know the number of items ahead of time so I typically opt for a dynamic collection (ArrayList, Vector, etc).
```
class Foo
{
ArrayLis... | The `ArrayList` class in Java has only two data members, a reference to an `Object[]` array and a size—which you need anyway if you don't use an `ArrayList`. So the only advantage to not using an `ArrayList` is saving one object allocation, which is unlikely ever to be a big deal.
If you're creating and disposing of m... | For the sake of keeping things simple, I think this is pretty much a non-issue. Your implementation is flexible enough that if the requirements change in the future, you aren't forced into a refactoring. Also, adding more logic to your code for a hybrid solution just isn't worth it taking into account your small data s... | Using Small (1-10 Items) Instance-Level Collections in Java | [
"",
"java",
"collections",
""
] |
Right, I know I am totally going to look an idiot with this one, but my brain is just *not* kicking in to gear this morning.
I want to have a method where I can say "if it goes bad, come back with this type of Exception", right?
For example, something like (**and this doesn't work**):
```
static ExType TestExcep... | You can almost do it like this:
```
static void TestException<E>(string message) where E : Exception, new()
{
var e = new E();
e.Message = message;
throw e;
}
```
However, that doesn't compile because Exception.Message is read only. It can only be assigned by passing it to the constructor, and there's no ... | The only issue with the solution is that it is possible to create a subclass of Exception which does not implement a constructor with a single string parameter, so the MethodMissingException might be thrown.
```
static void TestException<E>(string message) where E : Exception, new()
{
try
{
return Activ... | Asking a Generic Method to Throw Specific Exception Type on FAIL | [
"",
"c#",
"generics",
"exception",
""
] |
I am looking to do this in C/C++. I came across [**Variable Length Arguments**](http://www.swig.org/Doc1.3/Varargs.html), but this suggests a solution with Python and C using [libffi](http://sourceware.org/libffi/).
Now, if I want to wrap the `printf` function with `myprintf`.
I do it like below:
```
void myprintf(c... | The problem is that you cannot use 'printf' with *va\_args*. You must use **vprintf** if you are using variable argument lists. *vprint*, *vsprintf*, *vfprintf*, etc. (there are also 'safe' versions in Microsoft's C runtime that will prevent buffer overruns, etc.)
You sample works as follows:
```
void myprintf(char* ... | In [C++11](https://en.wikipedia.org/wiki/C%2B%2B11), this is one possible solution using [variadic templates](http://en.cppreference.com/w/cpp/language/parameter_pack):
```
template<typename... Args>
void myprintf(const char* fmt, Args... args)
{
std::printf(fmt, args...);
}
```
As [rubenvb points out](https://st... | How can I wrap a function with variable length arguments? | [
"",
"c++",
"c",
"variadic-functions",
""
] |
Using Oracle 10g, accessed via Perl DBI, I have a table with a few tens of million rows being updated a few times per second while being read from much more frequently form another process.
Soon the update frequency will increase by an order of magnitude (maybe two).
Someone suggested that committing every N updates i... | A commit results in Oracle writing stuff to the disk - i.e. in the redo log file so that whatever the transaction being commited has done can be recoverable in the event of a power failure, etc.
Writing in file is slower than writing in memory so a commit will be slower if performed for many operations in a row rather ... | Reducing the frequency of commits will certainly speed things up, however as you are reading and writing to this table frequently there is the potential for locks. Only you can determine the likelihood of the same data being updated at the same time. If the chance of this is low, commit every 50 rows and monitor the si... | When to commit changes? | [
"",
"sql",
"oracle",
"commit",
""
] |
Given a declaration like this:
```
class A {
public:
void Foo() const;
};
```
What does it mean?
Google turns up this:
> Member functions should be declared with the const keyword after them if they can operate on a const (this) object. If the function is not declared const, in can not be applied to a const obj... | Consider a variation of your class `A`.
```
class A {
public:
void Foo() const;
void Moo();
private:
int m_nState; // Could add mutable keyword if desired
int GetState() const { return m_nState; }
void SetState(int val) { m_nState = val; }
};
const A *A1 = new A();
A *A2 = new A();
A1->Foo(); ... | This is not an answer, just a side comment. It is **highly** recommended to declare variables and constants `const` as much as possible.
1. This communicates your intent to users of your class (even/especially yourself).
2. The compiler will keep you honest to those intentions. -- i.e., it's like compiler checked docu... | What does the const operator mean when used with a method in C++? | [
"",
"c++",
""
] |
I need to flip an image so that a character faces in the right direction. This needs to be done "on the fly' as they say.
The issue I am having is that with Gif images, I seem to lose the transparency. (The background goes white)
Below is the code: (Alternatively someone could send me to a good example)
```
$img = i... | Shouldn't this:
```
imagecolortransparent($img, imagecolorallocate($img, 0, 0, 0));
imagealphablending($img, false);
imagesavealpha($img, true);
```
...be this:
```
imagecolortransparent($temp, imagecolorallocate($img, 0, 0, 0));
imagealphablending($temp, false);
imagesavealpha($temp, true);
```
Note you should be ... | Final Results:
```
$size_x = imagesx($img);
$size_y = imagesy($img);
$temp = imagecreatetruecolor($size_x, $size_y);
imagecolortransparent($temp, imagecolorallocate($temp, 0, 0, 0));
imagealphablending($temp, false);
imagesavealpha($temp, true);
$x = imagecopyresampled($temp, $img, 0, 0, ($size_x-1), 0, $size_x, $si... | Flip an Image horizontally | [
"",
"php",
""
] |
I have an Enumerable array
```
int meas[] = new double[] {3, 6, 9, 12, 15, 18};
```
On each successive call to the mock's method that I'm testing I want to return a value from that array.
```
using(_mocks.Record()) {
Expect.Call(mocked_class.GetValue()).Return(meas);
}
using(_mocks.Playback()) {
foreach(var i i... | There is alway static fake object, but this question is about rhino-mocks, so I present you with the way I'll do it.
The trick is that you create a local variable as the counter, and use it in your anonymous delegate/lambda to keep track of where you are on the array. Notice that I didn't handle the case that GetValue(... | If the functionality is the GetValue() returns each array element in succession then you should be able to set up multiple expectations eg
```
using(_mocks.Record()) {
Expect.Call(mocked_class.GetValue()).Return(3);
Expect.Call(mocked_class.GetValue()).Return(6);
Expect.Call(mocked_class.GetValue()).Return(9);... | Rhino Mocks: How do I return numbers from a sequence | [
"",
"c#",
".net",
"rhino-mocks",
""
] |
Why does `n` not equal to `8` in the following function?
```
void foo(char cvalue[8])
{
int n = sizeof (cvalue);
}
```
But `n` *does* equal to `8` in this version of the function:
```
void bar()
{
char cvalue[8];
int n = sizeof (cvalue);
}
``` | Because you can't pass entire arrays as function parameters in C. You're actually passing a pointer to it; the brackets are syntactic sugar. There are no guarantees the array you're pointing to has size 8, since you could pass this function any character pointer you want.
```
// These all do the same thing
void foo(ch... | C and C++ arrays are not first class objects; you cannot pass arrays to functions, they always decay to pointers.
You can, however, pass pointers and references to arrays. This prevents the array bounds from decaying. So this is legal:
```
template<typename T, size_t N>
void foo(const T(&arr)[N])
{
int n = sizeof... | Different sizeof results | [
"",
"c++",
"c",
"sizeof",
""
] |
What makes a module/service/bit of application functionality a particularly good candidate for an OSGi module?
I'm interested in using [OSGi](http://en.wikipedia.org/wiki/OSGi) in my applications. We're a Java shop and we use Spring pretty extensively, so I'm leaning toward using [Spring Dynamic Modules for OSGi(tm) S... | Well, since you can not have one part OSGi and one part non-OSGi you'll need to make your entire app OSGi. In its simplest form you make a single OSGi bundle out of your entire application. Clearly this is not a best practice but it can be useful to get a feel for deploying a bundle in an OSGi container (Equinox, Felix... | When learning a new technology rich tooling gets you into things without big headaches.
At this point the community at [ops4j.org](http://wiki.ops4j.org/confluence/x/Bg/) provides a rich toolset called "PAX" which includes:
* **Pax Runner**: Run and switch between Felix, Equinox, Knopflerfish and Concierge easily
* **... | What's the best way to get started with OSGI? | [
"",
"java",
"spring",
"osgi",
""
] |
Why do we need to use:
```
extern "C" {
#include <foo.h>
}
```
**Specifically:**
* When should we use it?
* What is happening at the compiler/linker level that requires us to use it?
* How in terms of compilation/linking does this solve the problems which require us to use it? | C and C++ are superficially similar, but each compiles into a very different set of code. When you include a header file with a C++ compiler, the compiler is expecting C++ code. If, however, it is a C header, then the compiler expects the data contained in the header file to be compiled to a certain format—the C++ 'ABI... | extern "C" determines how symbols in the generated object file should be named. If a function is declared without extern "C", the symbol name in the object file will use C++ name mangling. Here's an example.
Given test.C like so:
```
void foo() { }
```
Compiling and listing symbols in the object file gives:
```
$ g... | Why do we need extern "C"{ #include <foo.h> } in C++? | [
"",
"c++",
"linkage",
"name-mangling",
"extern-c",
""
] |
I have a a property defined as:
```
[XmlArray("delete", IsNullable = true)]
[XmlArrayItem("contact", typeof(ContactEvent)),
XmlArrayItem("sms", typeof(SmsEvent))]
public List<Event> Delete { get; set; }
```
If the List<> Delete has no items
```
<delete />
```
is emitted. If the List<> Delete is set to null
```
<d... | If you set IsNullable=false or just remove it (it is false by default), then the "delete" element will not be emitted. This will work only if the collection equals to null.
My guess is that there is a confusion between "nullability" in terms of .NET, and the one related to nullable elements in XML -- those that are ma... | I've had the same issue where I did not want an element outputted if the field is empty or 0.
The XML outputted could not use xsi:null="true" (by design).
I've read somewhere that if you include a property of type bool with the same name as the field you want to control but appended with 'Specified', the XMLSerializer... | XML Serialization and empty collections | [
"",
"c#",
"xml-serialization",
""
] |
I'm trying to find a way to fake the result of a method called from within another method.
I have a "LoadData" method which calls a separate helper to get some data and then it will transform it (I'm interested in testing the transformed result).
So I have code like this:
```
public class MyClass(){
public void Lo... | As far as I know, you should create an interface or a base abstract class for the Helper object. With Rhino Mocks you can then return the value you want.
Alternatively, you can add an overload for LoadData that accepts as parameters the data that you normally retrieve from the Helper object. This might even be easier. | You have a problem there. I don't know if thats a simplified scenario of your code, but if the Helper class is used that way, then your code is not testable. First, the Helper class is used directly, so you **can't replace it with a mock**. Second, you're calling a static method. I don't know about C#, but in Java you ... | Mocking method results | [
"",
"c#",
"mocking",
"rhino-mocks",
""
] |
I have two identical tables and need to copy rows from table to another. What is the best way to do that? (I need to programmatically copy just a few rows, I don't need to use the bulk copy utility). | As long as there are no identity columns you can just
```
INSERT INTO TableNew
SELECT * FROM TableOld
WHERE [Conditions]
``` | Alternative syntax:
```
INSERT tbl (Col1, Col2, ..., ColN)
SELECT Col1, Col2, ..., ColN
FROM Tbl2
WHERE ...
```
The select query can (of course) include expressions, case statements, constants/literals, etc. | How to copy a row from one SQL Server table to another | [
"",
"sql",
"sql-server",
""
] |
Most mature C++ projects seem to have an own **reflection and attribute system**, i.e for defining attributes which can be accessed by string and are automatically serializable. At least many C++ projects I participated in seemed to **reinvent the wheel**.
Do you know any **good open source libraries** for C++ which s... | You could have a look at the two tools below. I've never used either of them, so I can't tell you how (im)practical they are.
**[XRTTI](http://www.ischo.com/xrtti/)**:
> Xrtti is a tool and accompanying C++ library which extends the standard runtime type system of C++ to provide a much richer set of reflection inform... | There is a new project providing reflection in C++ using a totally different approach: **CAMP**.
<https://github.com/tegesoft/camp>
CAMP doesn't use a precompiler, the classes/properties/functions/... are declared manually using a syntax similar to boost.python or luabind. Of course, people can use a precompiler like ... | Attribute & Reflection libraries for C++? | [
"",
"c++",
"reflection",
"attributes",
""
] |
In Notepad++, I was writing a JavaScript file and something didn't work: an alert had to be shown when a button was clicked, but it wasn't working.
I has used the auto-complete plugin provided with Notepad++, which presented me with `onClick`.
When I changed the capital `C` to a small `c`, it did work.
So first of a... | Javascript is **ALWAYS** case-sensitive, html is not.
It sounds as thought you are talking about whether html attributes (e.g. onclick) are or are not case-sensitive. The answer is that the attributes are not case sensitive, but the way that we access them through the DOM is.
So, you can do this:
```
<div id='divYo' ... | A few objects is IE aren't always case-sensitive, including some/most/all ActiveX -- why both **XHR.onReadyStateChange** and **XHR.onreadystatechange** would work fine in IE5 or IE6, but only the latter would work with the native **XMLHttpRequest** object in IE7, FF, etc.
But, a quick reference for "*standard*" API ca... | JavaScript and why capital letters sometimes work and sometimes don't | [
"",
"javascript",
"html",
"dom",
"case-sensitive",
""
] |
Suppose I have BaseClass with public methods A and B, and I create DerivedClass through inheritance.
e.g.
```
public DerivedClass : BaseClass {}
```
Now I want to develop a method C in DerivedClass that uses A and B. Is there a way I can override methods A and B to be private in DerivedClass so that only method C is... | **It's not possible, why?**
In C#, it is forced upon you that if you inherit public methods, you must make them public. Otherwise they expect you not to derive from the class in the first place.
Instead of using the is-a relationship, you would have to use the has-a relationship.
The language designers don't allow t... | When you, for instance, try to inherit from a `List<object>`, and you want to hide the direct `Add(object _ob)` member:
```
// the only way to hide
[Obsolete("This is not supported in this class.", true)]
public new void Add(object _ob)
{
throw NotImplementedException("Don't use!!");
}
```
It's not really the mos... | C# - Can publicly inherited methods be hidden (e.g. made private to derived class) | [
"",
"c#",
"class",
"derived",
""
] |
At the company I work for we have a "Utility" project that is referenced by pretty much ever application we build. It's got lots of things like NullHelpers, ConfigSettingHelpers, Common ExtensionMethods etc.
The way we work is that when we want to make a new project, we get the latest version of the project from sourc... | That's exactly what we're doing. We have a Utility project which has some non project specific useful functions. We increase the version manually (minor), build the project in Release version, sign it and put it to a shared location.
People then use the specific version of the *library*.
If some useful methods are im... | We use branching in source control; everyone uses the head branch until they make a release. When they branch the release, they'll branch the common utilities project as well.
Additionally, our utilities project has its own unit tests. That way, other teams can know if they would break the build for other teams.
Of c... | Working with Common/Utility Libraries | [
"",
"c#",
"visual-studio",
"api",
""
] |
I'm trying to write a page that calls PHP that's stored in a MySQL database. The page that is stored in the MySQL database contains PHP (and HTML) code which I want to run on page load.
How could I go about doing this? | You can use the [eval](http://php.net/manual/en/function.eval.php) command for this. **I would recommend against this though, because there's a lot of pitfalls using this approach.** Debugging is hard(er), it implies some security risks (bad content in the DB gets executed, uh oh).
See [When is eval evil in php?](http... | Easy:
```
$x // your variable with the data from the DB
<?php echo eval("?>".$x."<?") ?>
```
Let me know, works great for me in MANY applications, can't help but notice that everyone is quick to say how bad it is, but slow to actually help out with a straight answer... | How do I execute PHP that is stored in a MySQL database? | [
"",
"php",
"mysql",
""
] |
I'm currently working on a parser for our internal log files (generated by log4php, log4net and log4j). So far I have a nice regular expression to parse the logs, except for one annoying bit: Some log messages span multiple lines, which I can't get to match properly. The regex I have now is this:
```
(?<date>\d{2}/\d{... | This will only work if the log message doesn't contain a date at the beginning of the line, but you could try adding a negative look-ahead assertion for a date in the "message" group:
```
(?<date>\d{2}/\d{2}/\d{2})\s(?<time>\d{2}:\d{2}:\d{2},\d{3})\s(?<message>(.(?!^\d{2}/\d{2}/
\d{2}))+)
```
Note that this requires ... | You obviously need that "messages lines" can be distinguished from "log lines"; if you allow the message part to start with date/time after a new line, then there is simply no way to determine what is part of a message and what not. So, instead of using the dot, you need an expression that allows anything that does not... | Parsing a log file with regular expressions | [
"",
"c#",
"regex",
""
] |
In Oracle, what is the difference between :
```
CREATE TABLE CLIENT
(
NAME VARCHAR2(11 BYTE),
ID_CLIENT NUMBER
)
```
and
```
CREATE TABLE CLIENT
(
NAME VARCHAR2(11 CHAR), -- or even VARCHAR2(11)
ID_CLIENT NUMBER
)
``` | Let us assume the database character set is UTF-8, which is the recommended setting in recent versions of Oracle. In this case, some characters take more than 1 byte to store in the database.
If you define the field as `VARCHAR2(11 BYTE)`, Oracle can use up to 11 bytes for storage, but you may not actually be able to ... | One has exactly space for 11 bytes, the other for exactly 11 characters. Some charsets such as Unicode variants may use more than one byte per char, therefore the 11 byte field might have space for less than 11 chars depending on the encoding.
See also <http://www.joelonsoftware.com/articles/Unicode.html> | Difference between BYTE and CHAR in column datatypes | [
"",
"sql",
"oracle",
"unicode",
"varchar",
""
] |
I am planning to create a web app that allows users to downgrade their visual studio project files. However, It seems Google App Engine accepts files uploading and flat file storing on the Google Server through `db.TextProperty` and `db.BlobProperty`.
I'll be glad anyone can provide code sample (both the client and th... | Here is a complete, working file. I pulled the original from the Google site and modified it to make it slightly more real world.
A few things to notice:
1. This code uses the [BlobStore API](http://code.google.com/appengine/docs/python/blobstore/)
2. The purpose of this line in the
ServeHandler class is to "fix" ... | In fact, this question is answered in the App Egnine documentation. See an example on [Uploading User Images](http://code.google.com/appengine/docs/images/usingimages.html#Uploading).
HTML code, inside <form></form>:
```
<input type="file" name="img"/>
```
Python code:
```
class Guestbook(webapp.RequestHandler):
... | Upload files in Google App Engine | [
"",
"python",
"google-app-engine",
""
] |
In how many languages is Null not equal to anything not even Null? | It's this way in SQL (as a logic language) because null means unknown/undefined.
However, in programming languages (like say, C++ or C#), a null pointer/reference is a specific value with a specific meaning -- nothing.
Two nothings are equivilent, but two unknowns are not. The confusion comes from the fact that the s... | In VB6 the expression `Null = Null` will produce `Null` instead of `True` as you would expect.
This will cause a runtime error if you try to assign it to a Boolean, however if you use it
as the condition of "`If ... Then`" it will act like `False`. Moreover `Null <> Null` will **also**
produce `Null`, so:
**In VB6 you... | In how many languages is Null not equal to anything not even Null? | [
"",
"sql",
"ruby",
"oracle",
"language-agnostic",
"vb6",
""
] |
The built-in `PHP` extension for `SOAP` doesn't validate everything in the incoming `SOAP` request against the `XML Schema` in the `WSDL`. It does check for the existence of basic entities, but when you have something complicated like `simpleType` restrictions the extension pretty much ignores their existence.
What is... | Been digging around on this matter a view hours.
Neither the native PHP SoapServer nore the NuSOAP Library does any Validation.
PHP SoapServer simply makes a type cast.
For Example if you define
```
<xsd:element name="SomeParameter" type="xsd:boolean" />
```
and submit
```
<get:SomeParameter>dfgdfg</get:SomeParamete... | Besides the native PHP5 SOAP libs, I can also tell you that neither the PEAR nor Zend SOAP libs will do schema validation of messages at present. (I don't know of any PHP SOAP implementation that does, unfortunately.)
What I would do is load the XML message into a [DOMDocument](http://www.php.net/manual/en/class.domdo... | Validate an incoming SOAP request to the WSDL in PHP | [
"",
"php",
"soap",
"wsdl",
"xsd",
""
] |
I'd like to populate an arraylist by specifying a list of values just like I would an integer array, but am unsure of how to do so without repeated calls to the "add" method.
For example, I want to assign { 1, 2, 3, "string1", "string2" } to an arraylist. I know for other arrays you can make the assignment like:
```
... | Array list has ctor which accepts ICollection, which is implemented by the Array class.
```
object[] myArray = new object[] {1,2,3,"string1","string2"};
ArrayList myArrayList = new ArrayList(myArray);
``` | Depending on the version of C# you are using, you have different options.
C# 3.0 has collection initializers, detail at [Scott Gu's Blog](http://weblogs.asp.net/scottgu/archive/2007/03/08/new-c-orcas-language-features-automatic-properties-object-initializers-and-collection-initializers.aspx)
Here is an example of you... | C#: Is Implicit Arraylist assignment possible? | [
"",
"c#",
"arraylist",
""
] |
I just installed Java 1.6\_07 so I could try profiling with VisualVM. It tells me that my app is spending 60% of its time in `sun.rmi.transport.tcp.TCPTransport$ConnectionHandler.run`
How do I find out what it was doing during that time? How much of the time was it waiting for something to call it, or doing something ... | I don't have experience with VisualVM -- but JRockit's profiler *does* provide this information; you may consider using it instead.
**Update:** a question with a list of java profilers can be found [here](https://stackoverflow.com/questions/14762/please-recommend-a-java-profiler), for users with sufficient rep to view... | Does your App use RMI over TCP? If not, is it possible that this is a heisenbug, caused by instrumenting the VM? I assume VisualVM must use RMI calls to figure out what's going on in the JVM.... | Drilling down in VisualVM | [
"",
"java",
"visualvm",
""
] |
I've been trying to convert SVG images to PNG using C#, without having to write too much code. Can anyone recommend a library or example code for doing this? | You can call the command-line version of inkscape to do this:
<http://harriyott.com/2008/05/converting-svg-images-to-png-in-c.aspx>
Also there is a C# SVG rendering engine, primarily designed to allow SVG files to be used on the web on codeplex that might suit your needs if that is your problem:
**Original Project**... | There is a much easier way using the library <http://svg.codeplex.com/> (Newer version @[GIT](https://github.com/vvvv/SVG), @[NuGet](https://www.nuget.org/packages/Svg/)). Here is my code
```
var byteArray = Encoding.ASCII.GetBytes(svgFileContents);
using (var stream = new MemoryStream(byteArray))
{
var svgDocumen... | Converting SVG to PNG using C# | [
"",
"c#",
".net",
"png",
"svg",
""
] |
I'm handling the `onSelectIndexChanged` event. An event is raised when the DropDownList selection changes. the problem is that the DropDownList still returns the old values for `SelectedValue` and `SelectedIndex`. What am I doing wrong?
Here is the DropDownList definition from the aspx file:
```
<div style="margin: 0... | Do you have any code in page load that is by chance re-defaulting the value to the first value?
When the page reloads do you see the new value? | If you are using AJAX you may also be doing a callback, not a full postback. In that case you may want to use this in your page load method:
```
if (!IsCallback && !IsPostBack)
{
// Do your page setup here
}
``` | SelectedIndexChanged event handler getting old index | [
"",
"c#",
"asp.net",
"webforms",
""
] |
In general, I occasionally have a chain of nested macros with a few preprocessor conditional elements in their definitions. These can be painful to debug since it's hard to directly see the actual code being executed.
A while ago I vaguely remember finding a compiler (gcc) flag to expand them, but I had trouble gettin... | gcc -E will output the preprocessed source to stdout. | For MSVC users, you can right-click on the file/project, view the settings and change the file properties to output preprocessed source (which typically in the obj directory). | Is there a good general method for debugging C++ macros? | [
"",
"c++",
"debugging",
"gcc",
"macros",
""
] |
I have a winforms application where users will be creating stock items, and a time of creation there are a number of different things that need to happen.
I think the UI for this should probably be a wizard of some kind, but I'm unsure as to the best way to achieve this. I have seen a couple of 3rd party Wizard contro... | Here are a few more resources you should check out:
1. This DevExpress WinForms control: <http://www.devexpress.com/Products/NET/Controls/WinForms/Wizard/>
2. A home-grown wizards framework: <http://weblogs.asp.net/justin_rogers/articles/60155.aspx>
3. A wizard framework by Shawn Wildermut part of the Chris Sells's Ge... | I know this answer has already been accepted, but I just found a better Wizard control that's free, and of course, since it's on CodeProject, includes the source, so you can modify it if it's not exactly what you want. I'm adding this as an answer for the next person to stumble across this question looking for a good W... | What is the best way to create a wizard in C# 2.0? | [
"",
"c#",
"visual-studio",
"winforms",
"user-interface",
"wizard",
""
] |
Using C# and ASP.NET I want to programmatically fill in some values (4 text boxes) on a web page (form) and then 'POST' those values. How do I do this?
Edit: Clarification: There is a service (www.stopforumspam.com) where you can submit ip, username and email address on their 'add' page. I want to be able to create a ... | The code will look something like this:
```
WebRequest req = WebRequest.Create("http://mysite/myform.aspx");
string postData = "item1=11111&item2=22222&Item3=33333";
byte[] send = Encoding.Default.GetBytes(postData);
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
req.ContentLength = send.... | You can use the UploadValues method on WebClient - all it requires is passing a URL and a NameValueCollection. It is the easiest approach that I have found, and the MS documentation has a nice example:
<http://msdn.microsoft.com/en-us/library/9w7b4fz7.aspx>
Here is a simple version with some error handling:
```
var... | How do you programmatically fill in a form and 'POST' a web page? | [
"",
"c#",
"asp.net",
""
] |
I'm trying to get an event to fire whenever a choice is made from a `JComboBox`.
The problem I'm having is that there is no obvious `addSelectionListener()` method.
I've tried to use `actionPerformed()`, but it never fires.
Short of overriding the model for the `JComboBox`, I'm out of ideas.
How do I get notified o... | It should respond to [ActionListeners](http://docs.oracle.com/javase/7/docs/api/java/awt/event/ActionListener.html), like this:
```
combo.addActionListener (new ActionListener () {
public void actionPerformed(ActionEvent e) {
doSomething();
}
});
```
[@John Calsbeek](https://stackoverflow.com/a/58965/... | Code example of `ItemListener` implementation
```
class ItemChangeListener implements ItemListener{
@Override
public void itemStateChanged(ItemEvent event) {
if (event.getStateChange() == ItemEvent.SELECTED) {
Object item = event.getItem();
// do something with object
}
} ... | JComboBox Selection Change Listener? | [
"",
"java",
"swing",
"jcombobox",
"itemlistener",
""
] |
I'm using SQL Server 2005, and I would like to know how to access different result sets from within transact-sql. The following stored procedure returns two result sets, how do I access them from, for example, another stored procedure?
```
CREATE PROCEDURE getOrder (@orderId as numeric) AS
BEGIN
select order_ad... | The short answer is: you can't do it.
From T-SQL there is no way to access multiple results of a nested stored procedure call, without changing the stored procedure as others have suggested.
To be complete, if the procedure were returning a single result, you could insert it into a temp table or table variable with t... | I was easily able to do this by creating a SQL2005 CLR stored procedure which contained an internal dataset.
You see, a new SqlDataAdapter will .Fill a multiple-result-set sproc into a multiple-table dataset by default. The data in these tables can in turn be inserted into #Temp tables in the calling sproc you wish to... | Access to Result sets from within Stored procedures Transact-SQL SQL Server | [
"",
"sql",
"sql-server",
"t-sql",
""
] |
Can anyone tell me what exactly does this Java code do?
```
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
byte[] bytes = new byte[20];
synchronized (random)
{
random.nextBytes(bytes);
}
return Base64.encode(bytes);
```
---
Step by step explanation will be useful so that I can recreate this code in... | Using code snippets you can get to something like this
```
Dim randomNumGen As RandomNumberGenerator = RNGCryptoServiceProvider.Create()
Dim randomBytes(20) As Byte
randomNumGen.GetBytes(randomBytes)
return Convert.ToBase64String(randomBytes)
``` | This creates a random number generator (SecureRandom). It then creates a byte array (byte[] bytes), length 20 bytes, and populates it with random data.
This is then encoded using BASE64 and returned.
So, in a nutshell,
1. Generate 20 random bytes
2. Encode using Base 64 | equivalent vb code for a java code | [
"",
"java",
"vba",
"random",
""
] |
How can I load an external JavaScript file using a bookmarklet? This would overcome the URL length limitations of IE and generally keep things cleaner. | ### 2015 Update
[Content security policy](https://developer.mozilla.org/en-US/docs/Web/Security/CSP/Introducing_Content_Security_Policy) will prevent this from working in many sites now. For example, the code below won't work on Facebook.
### 2008 answer
Use a bookmarklet that creates a script tag which includes you... | Firefox and perhaps others support multiline bookmarklets, no need for one liner. When you paste in the code it just replaces newlines with spaces.
```
javascript:
var q = document.createElement('script');
q.src = 'http://svnpenn.github.io/bm/yt.js';
document.body.appendChild(q);
void 0;
```
[Example](http://github.c... | Load external JS from bookmarklet? | [
"",
"javascript",
"load",
"external",
"bookmarklet",
""
] |
I am working on designing and building a desktop application. I am thinking about using eclipse or netbeans for the base of this application. However, I have never built on either of these platforms. I am personally leaning to using netbeans because it seams like that platform is an easer learning curve. But, I wanted ... | I can't say enough about the Eclipse RCP platform. I would recommend it for any Java desktop app development.
It's free, has great tutorials, and allows cross-platform development of rich desktop applications that use native OS windowing toolkit, meaning that your application will look native in any platform. It also ... | * **Easy to use**: I have experience developing on Eclipse and I have to say it's not easy to understand its development model. Sure for basic stuff it has some wizards that make easier, but for something a little more complex it's just difficult. I don't know about Netbeans, but I heard its easier.
* **Consistent API*... | Java Desktop application framework | [
"",
"java",
"eclipse",
"netbeans",
"desktop",
"platform",
""
] |
I've got some (C#) code that relies on today's date to correctly calculate things in the future. If I use today's date in the testing, I have to repeat the calculation in the test, which doesn't feel right. What's the best way to set the date to a known value within the test so that I can test that the result is a know... | My preference is to have classes that use time actually rely on an interface, such as
```
interface IClock
{
DateTime Now { get; }
}
```
With a concrete implementation
```
class SystemClock: IClock
{
DateTime Now { get { return DateTime.Now; } }
}
```
Then if you want, you can provide any other kind of cl... | Ayende Rahien [uses](http://www.ayende.com/Blog/archive/2008/07/07/Dealing-with-time-in-tests.aspx) a static method that is rather simple...
```
public static class SystemTime
{
public static Func<DateTime> Now = () => DateTime.Now;
}
``` | What's a good way to overwrite DateTime.Now during testing? | [
"",
"c#",
"unit-testing",
"datetime",
"testing",
""
] |
Say you have a shipment. It needs to go from point A to point B, point B to point C and finally point C to point D. You need it to get there in five days for the least amount of money possible. There are three possible shippers for each leg, each with their own different time and cost for each leg:
```
Array
(
[le... | Could alter some of the [shortest path algorithms](http://en.wikipedia.org/wiki/Shortest_path_problem), like Dijkstra's, to weight each path by cost but also keep track of time and stop going along a certain path if the time exceeds your threshold. Should find the cheapest that gets you in under your threshold that way | Sounds like what you have is called a "linear programming problem". It also sounds like a homework problem, no offense.
The classical solution to a LP problem is called the "Simplex Method". Google it.
However, to use that method, you must have the problem correctly formulated to describe your requirements.
Still, i... | Find the best combination from a given set of multiple sets | [
"",
"php",
"algorithm",
"puzzle",
"combinations",
"np-complete",
""
] |
I am looking into game programming in Java to see if it is feasible. When googling for it I find several old references to Java2D, Project Darkstar (Sun's MMO-server) and some books on Java game programming. But alot of the information seems to be several years old.
So the question I am asking, is anyone creating any ... | there is the excellent open source 3d engine called jMonkey (<http://www.jmonkeyengine.com>) which is being used for a few commercial projects as well as hobby developers...
there is also at a lower level the lwjgl library which jmonkeyengine is built on which is a set of apis to wrap opengl as well as provide other ga... | <http://www.javagaming.org/> is a good source for up-to-date information.
Another framework not mentioned yet is [Xith3D](http://xith.org/) | Game programming in Java? | [
"",
"java",
""
] |
EDIT: Learned that Webmethods actually uses NLST, not LIST, if that matters
Our business uses the WebMethods integration server to handle most of our outbound communications, and its FTP functionality leaves something to be desired. We are having a problem that may be specific to WebMethods, but if anyone can point me... | I tried this in WebMethods IS Version 6.5 Updates WmPRT\_6-5-1\_SP1, IS\_6-5\_SP3.
It worked perfectly first time.
I turned on debugging on the FTP server (Debian's default ftpd). WebMethods' NLST honours the active/passive parameter passed to it.
There's nothing special about the NLST command, nor its correct behav... | I am not sure if it was the same problem but I had similar symptoms a while ago using another FTP client in Java (commons.net). The problem turned out to be caused by the active/passive mode of the connection.
I am sorry I can't give you more details, that's all I can remember... hope that help. | FTP Timeout on NLST when directory is empty | [
"",
"java",
"ftp",
"webmethods",
""
] |
I would like to put a link to a webpage in an alert dialog box so that I can give a more detailed description of how to fix the error that makes the dialog box get created.
How can I make the dialog box show something like this:
```
There was an error. Go to this page to fix it.
wwww.TheWebPageToFix.com
```
Thanks. | You could try asking them if they wish to visit via window.prompt:
```
if(window.prompt('Do you wish to visit the following website?','http://www.google.ca'))
location.href='http://www.google.ca/';
```
Also, Internet Explorer supports modal dialogs so you could try showing one of those:
```
if (window.showModalDia... | You can't. Alert boxes don't support html. You should display the error as part of the page, it's nicer than JS alerts anyway. | How do I put a link to a webpage in a JScript Alert dialog box? | [
"",
"javascript",
"alert",
""
] |
How can you implement trackbacks on a custom-coded blog (written in C#)? | The TrackBack specification was created by Six Apart back in the day for their [Movable Type](http://www.movabletype.org/) blogging system. After some corporate changes it seems to be no longer available, but here's an archived version:
<http://web.archive.org/web/20081228043036/http://www.sixapart.com/pronet/docs/tra... | Personally, I wouldn't. Trackbacks became completely unusable years ago from all the spammers and even Akismet hasn't been enough to drag them back to usable (obviously IMO). The best way I've seen to handle trackbacks any more is to have a function that will turn an article's "referrer" (you are tracking those, right?... | How can you implement trackbacks on a custom-coded blog (written in C#)? | [
"",
"c#",
"blogs",
"trackback",
""
] |
I am working on an application for college music majors. A feature i am considering is slowing down music playback without changing its pitch. I have seen this done in commercial software, but cannot find any libraries or open source apps that do anything like this.
1. Are there libraries out there?
2. How could this ... | Timestretching is quite hard. The more you slow down or speed up the sound the more artifacts you get. If you want to know what they sound like listen to "The Rockafeller Skank" by Fat Boy Slim. There are a lot of ways to do it that all have their own strengths and weaknesses. The math can get really complex. That's wh... | I use [soundstretch](http://www.iki.fi/oparviai/soundtouch) to speed up podcasts which is works quite well, haven't tried it on music though. | Slowing down the playback of an audio file without changing its pitch? | [
"",
"java",
"audio",
"media",
""
] |
I have a Windows application that uses a .NET PropertyGrid control. Is it possible to change the type of control that is used for the value field of a property?
I would like to be able to use a RichTextBox to allow better formatting of the input value.
Can this be done without creating a custom editor class? | To add your own custom editing when the user selects a property grid value you need to implement a class that derives from UITypeEditor. You then have the choice of showing just a small popup window below the property area or a full blown dialog box.
What is nice is that you can reuse the existing implementations. So ... | You can control whether the PropertyGrid displays a simple edit box, a drop-down arrow, or an ellipsis control.
Look up EditorAttribute, and follow it on from there. I did have a sample somewhere; I'll try to dig it out. | How do I change the type of control that is used in a .NET PropertyGrid | [
"",
"c#",
".net",
"windows",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.