Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I have GridView which I can select a row. I then have a button above the grid called Edit which the user can click to popup a window and edit the selected row. So the button will have Javascript code behind it along the lines of
```
function editRecord()
{
var gridView = document.getElementById("<%= GridView.ClientI... | I worked it out based on JasonS response. What I did was create a hidden field in the Grid View like this:
```
<asp:TemplateField ShowHeader="False">
<ItemTemplate>
<asp:HiddenField ID="hdID" runat="server" Value='<%# Eval("JobID") %>' />
</ItemTemplate>
</asp:TemplateField>
<asp:TemplateField Visible="F... | 1) change your javascript function to use a parameter
```
function editRecord(clientId)
{ ....
```
2) output the call in your editRecord button... if you want to avoid dealing with the .net generated ids, just use a simple
```
<input type="button" onclick="editRecord(your-rows-client-id-goes-here)" />
``` | Get GridView selected row DataKey in Javascript | [
"",
"asp.net",
"javascript",
"gridview",
""
] |
I need to do some performance benchmarks on .NET programs (C#) in Windows, but I haven't done benchmarking much in the Windows world. I've looked into using the Windows 2000/XP Performance monitor with custom counters for this, but I don't think this is quite what I want.
Are there any good system facilities for this ... | For micro-benchmarking I really like MeasureIt (can be downloaded from <http://msdn.microsoft.com/en-us/magazine/cc500596.aspx>). It is a test project written by Vance Morrison a Performance Architect on the CLR. It currently has a good set of benchmarks for a number of .Net/CLR core methods. The best part of it is tha... | ```
using System.Diagnostics;
....
Stopwatch sw = new Stopwatch();
sw.Start();
// Code you want to time...
// Note: for averaged accuracy (without other OS effects),
// run timed code multiple times in a loop
// and then divide by the number of runs.
sw.Stop();
Console.WriteLine("Took " + sw.Elapsed... | What's the best way to benchmark programs in Windows? | [
"",
"c#",
".net",
"windows",
"performance",
"benchmarking",
""
] |
I was wondering what are the benefits of using anything else but Java for Mobile Application Development. | Java is the most ubiquitous and for that alone it is your best choice. | I do think that yes, Java is the most common language for devices, with two exceptions:
* Windows mobile applications, that are frequently built in C++ but that will be built more on the .NET framework in the future.
* iPhone applications, that use Cocoa and Objective-C. | Is Java the best language for Mobile App Devlopment? | [
"",
"java",
"mobile",
""
] |
Consider the following code:
```
void Handler(object o, EventArgs e)
{
// I swear o is a string
string s = (string)o; // 1
//-OR-
string s = o as string; // 2
// -OR-
string s = o.ToString(); // 3
}
```
What is the difference between the three types of casting (okay, the 3rd one is not a casting, bu... | ```
string s = (string)o; // 1
```
Throws [InvalidCastException](https://msdn.microsoft.com/en-us/library/system.invalidcastexception) if `o` is not a `string`. Otherwise, assigns `o` to `s`, even if `o` is `null`.
```
string s = o as string; // 2
```
Assigns `null` to `s` if `o` is not a `string` or if `o` is `null... | 1. `string s = (string)o;` Use when something should
*definitely* be the other thing.
2. `string s = o as string;` Use when something *might be* the other
thing.
3. `string s = o.ToString();` Use when you don't care what
it is but you just want to use the
available string representation. | Direct casting vs 'as' operator? | [
"",
"c#",
"casting",
""
] |
I have two tables containing Tasks and Notes, and want to retrieve a list of tasks with the number of associated notes for each one. These two queries do the job:
```
select t.TaskId,
(select count(n.TaskNoteId) from TaskNote n where n.TaskId = t.TaskId) 'Notes'
from Task t
-- or
select t.TaskId,
coun... | On small datasets they are wash when it comes to performance. When indexed, the LOJ is a little better.
I've found on large datasets that an inner join (an inner join will work too.) will outperform the subquery by a very large factor (sorry, no numbers). | In most cases, the optimizer will treat them the same.
I tend to prefer the second, because it has less nesting, which makes it easier to read and easier to maintain. I have started to use SQL Server's common table expressions to reduce nesting as well for the same reason.
In addition, the second syntax is more flexi... | Transact-SQL - sub query or left-join? | [
"",
"sql",
"t-sql",
""
] |
Using C# .NET 2.0, I have an owner-drawn ListView where I'm overriding the OnDrawColumnHeader, OnDrawItem and OnDrawSubitem events. If I set the View property to Details at design-time, everything works beautifully and I can switch the View property and all view modes display as they should (I'm not using Tile view). H... | The WinForms ListView is mostly a layer of abstraction of the top of the actual Windows control, so there are aspect of its behaviour that are, well, counterintuitive is a polite way of putting things.
I have a vague recollection, from back in my days as a Delphi developer, that when you are Owner drawing a ListView, ... | Either SubItems are not added, or you didn't add any columns. That's my initial feeling. | Why doesn't my ListView display List or Details items? | [
"",
"c#",
".net",
"winforms",
"listview",
""
] |
currently i obtain the below result from the following C# line of code when in es-MX Culture
```
Thread.CurrentThread.CurrentCulture =
Thread.CurrentThread.CurrentUICulture = new
CultureInfo("es-mx");
<span><%=DateTime.Now.ToLongDateString()%></span>
```
# miércoles, 22 de octubre de 2008
... | You don't need to build your own culture. You only need to change the property DateTimeFormat.DayNames and DateTimeFormat.MonthNames in the current culture.
i.e.
```
string[] newNames = { "Lunes", "Martes", "Miercoles", "Jueves", "Viernes", "Sabado", "Domingo" };
Thread.CurrentThread.CurrentCulture.Da... | a little late but this work for me!
```
public static string GetFecha()
{
System.Globalization.CultureInfo culture = new System.Globalization.CultureInfo("es-EC");
System.Threading.Thread.CurrentThread.CurrentCulture = culture;
// maldita sea!
string strDate = culture.TextInfo.ToT... | how to uppercase date and month first letter of ToLongDateString() result in es-mx Culture? | [
"",
"c#",
".net",
"datetime",
"internationalization",
"culture",
""
] |
I'm parsing XML results from an API call using PHP and xpath.
```
$dom = new DOMDocument();
$dom->loadXML($response->getBody());
$xpath = new DOMXPath($dom);
$xpath->registerNamespace("a", "http://www.example.com");
$hrefs = $xpath->query('//a:Books/text()', $dom);
for ($i = 0; $i < $hrefs->length; $i++) {
... | After doing some looking around I came across this solution. This way I can get the element text and access any attributes of the node.
```
$hrefs = $xpath->query('//a:Books', $dom);
for ($i = 0; $i < $hrefs->length; $i++) {
$arrBookTitle[$i] = $hrefs->item($i)->nodeValue;
$arrBookDewey[$i] = $hrefs->item($i)... | One single XPath expression that will select both the text nodes of "a:Books" and their "DeweyDecimal" attribute, is the following
`//a:Books/text() | //a:Books/@DeweyDecimal`
**Do note** the use of the XPath's union operator in the expression above.
**Another note**: try to avoid using the "//" abbreviation as it m... | Pulling both the text and attribute of a given node using Xpath | [
"",
"php",
"dom",
"xpath",
""
] |
My 11 year old son is very interested in programming. He has been working with [Scratch](http://scratch.mit.edu)
for a couple years but has now outgrown it. I recently helped him install Visual C# Express Edition and he is very excited to work with it, but we're having a hard time finding good resources for him online.... | I would recommend [Coding4Fun](http://blogs.msdn.com/coding4fun/). There are some very nice projects out there which would appeal to an 11 year old. I recall seeing some games, screensavers, and even a sample which shows how to make a WinForms app look like it is bleeding (awesome for Halloween, eh?) | Hmm... given that C# isn't really a "teaching language" (and that's not to say it's a bad choice), I suspect there aren't a lot of tutorials targeted at younger kinds. Have you considered doing some parallel learning and trying to pick up C# with your son? It might be a good bonding experience for both of you, and with... | Resources for Kids Learning C# | [
"",
"c#",
""
] |
I have multiple threads (C# application running on IIS) running that all need to communicate with the same MQ backend. To minimize network traffic, I need to only send a backend request when there is work to be done. There will be one thread to monitor if there is work to be done, and it needs to notify the other threa... | Check out [WaitHandle](http://msdn.microsoft.com/en-us/library/system.threading.waithandle.aspx) and its descending classes. [EventWaitHandle](http://msdn.microsoft.com/en-us/library/system.threading.eventwaithandle.aspx) may suit your needs. | As well as the WaitHandle classes pointed out by Kent, simple [Monitor.Wait](http://msdn.microsoft.com/en-us/library/system.threading.monitor.wait.aspx) and Monitor.[Pulse](http://msdn.microsoft.com/en-us/library/system.threading.monitor.pulse.aspx)/[PulseAll](http://msdn.microsoft.com/en-us/library/system.threading.mo... | Suspending and notifying threads when there is work to do | [
"",
"c#",
"multithreading",
""
] |
## How would you unittest a safe-publication guarantee in Java?
To be concrete:
I have a Cache interface that has a method getOrLoad(K key, ObjectLoader loader). Thing is, if a Cache cannot find an object for the given key, then it must load it from the ObjectLoader instance. However, the Cache is required to guarant... | I discovered a [JavaOne presentation](http://developers.sun.com/learning/javaoneonline/j1sessn.jsp?sessn=TS-2220&yr=2007&track=5) by Bill Pugh, Brian Goetz and Cliff Click on the subject of testing concurrent code. They suggested this approach, witch I think is the best I've heard:
A number of producers create statefu... | Maybe you can use [ConTest](http://www.alphaworks.ibm.com/tech/contest) to at least give you a little more confidence that your code is correct.
You'll need to implement a couple of tests that run several threads concurrently. ConTest will then increase the probability that a concurrency bug is actually revealed by in... | Unit testing for safe publication | [
"",
"java",
"unit-testing",
"concurrency",
"junit",
""
] |
A couple of the options are:
```
$connection = {my db connection/object};
function PassedIn($connection) { ... }
function PassedByReference(&$connection) { ... }
function UsingGlobal() {
global $connection;
...
}
```
So, passed in, passed by reference, or using global. I'm thinking in functions that are on... | I use a Singleton ResourceManager class to handle stuff like DB connections and config settings through a whole app:
```
class ResourceManager {
private static $DB;
private static $Config;
public static function get($resource, $options = false) {
if (property_exists('ResourceManager', $resource)) ... | Try designing your code in an object-oriented fashion. Methods that use the database should be grouped in a class, and the class instance should contain the database connection as a class variable. That way the database connection is available to the functions that need it, but it's not global.
```
class MyClass {
p... | What is the best method for getting a database connection/object into a function in PHP? | [
"",
"php",
"database",
""
] |
This is a bit of a lazyweb question but you get the rep so :-)
I have a Java class that returns instances of itself to allow chaining
(e.g. ClassObject.doStuff().doStuff())
For instance:
```
public class Chainer
{
public Chainer doStuff()
{
/* Do stuff ... */
return this;
}
}
```
I would l... | Have you tried the straight-forward
```
public class Chainer
{
public Chainer doStuff()
{
/* Do stuff ... */
return this;
}
}
public class ChainerExtender extends Chainer
{
@Override
public ChainerExtender doStuff()
{
/* Do stuff ... */
super.doStuff();
retur... | Why not have them all return an interface? You'd have to define all of the possible chained methods in the interface and provide "null" implementations in the base class, but you'd be able to chain to your heart's content.
```
public interface IChainer
{
IChainer doStuff();
IChainer doSomethingElse();
}
public cl... | How do I write a Java function that returns a typed instance of 'this' and works when extended? | [
"",
"java",
"generics",
""
] |
I am using the following code:
```
<?php
$stock = $_GET[s]; //returns stock ticker symbol eg GOOG or YHOO
$first = $stock[0];
$url = "http://biz.yahoo.com/research/earncal/".$first."/".$stock.".html";
$data = file_get_contents($url);
$r_header = '/Prev. Week(.+?)Next Week/';
$r_date = '/\<b\>(.+?)\<\/b\>/';
preg_ma... | Problem is that the HTML has newlines in it, which you need to incorporate with the s regex modifier, as below
```
<?php
$stock = "goog";//$_GET[s]; //returns stock ticker symbol eg GOOG or YHOO
$first = $stock[0];
$url = "http://biz.yahoo.com/research/earncal/".$first."/".$stock.".html";
$data = file_get_contents($u... | Your regex doesn't allow for the line breaks in the HTML Try:
```
$r_header = '/Prev\. Week((?s:.*))Next Week/';
```
The `s` tells it to match the newline characters in the `.` (match any). | Supposedly valid regular expression doesn't return any data in PHP | [
"",
"php",
"regex",
""
] |
[tempfile.mkstemp()](http://www.python.org/doc/2.5.2/lib/module-tempfile.html) returns:
> a tuple containing an OS-level handle to an open file (as would be returned by os.open()) and the absolute pathname of that file, in that order.
How do I convert that OS-level handle to a file object?
The [documentation for os.... | You can use
```
os.write(tup[0], "foo\n")
```
to write to the handle.
If you want to open the handle for writing you need to add the **"w"** mode
```
f = os.fdopen(tup[0], "w")
f.write("foo")
``` | Here's how to do it using a with statement:
```
from __future__ import with_statement
from contextlib import closing
fd, filepath = tempfile.mkstemp()
with closing(os.fdopen(fd, 'w')) as tf:
tf.write('foo\n')
``` | Python - How do I convert "an OS-level handle to an open file" to a file object? | [
"",
"python",
"temporary-files",
"mkstemp",
"fdopen",
""
] |
What is MySQL equivalent of the `Nz` Function in Microsoft Access? Is `Nz` a SQL standard?
In Access, the `Nz` function lets you return a value when a variant is null. [Source](http://www.techonthenet.com/access/functions/advanced/nz.php)
The syntax for the `Nz` function is:
```
Nz ( variant, [ value_if_null ] )
``` | The [`COALESCE()`](https://dev.mysql.com/doc/refman/8.0/en/comparison-operators.html#function_coalesce) function does what you describe. It's standard SQL and it should be supported in all SQL databases.
The [`IFNULL()`](https://dev.mysql.com/doc/refman/8.0/en/flow-control-functions.html#function_ifnull) function is n... | COALESCE does just what the OP is asking for, as does IFNULL:
```
SELECT Nz(MightBeNullVar, 0) FROM ... (MS Access version)
SELECT COALESCE(MightBeNullVar, 0) FROM ... (MySQL version)
SELECT IFNULL(MightBeNullVar, 0) FROM ... (MySQL version)
```
The difference is the COALESCE can search through multiple variables an... | What is equivalent of the Nz Function in MS Access in MySQL? Is Nz a SQL standard? | [
"",
"sql",
"mysql",
"database",
"ms-access",
""
] |
I've been recently asked to learn some MATLAB basics for a class.
What does make it so cool for researchers and people that works in university?
I saw it's cool to work with matrices and plotting things... (things that can be done easily in Python using some libraries).
Writing a function or parsing a file is just pa... | Adam is only partially right. Many, if not most, mathematicians will never touch it. If there is a computer tool used at all, it's going to be something like [Mathematica](http://en.wikipedia.org/wiki/Mathematica) or [Maple](http://en.wikipedia.org/wiki/Maple_(software)). Engineering departments, on the other hand, oft... | Most of answers do not get the point.
There is ONE reason matlab is so good and so widely used:
## EXTREMELY FAST CODING
I am a computer vision phD student and have been using matlab for 4 years, before my phD I was using different languages including C++, java, php, python... Most of the computer vision researchers... | What is MATLAB good for? Why is it so used by universities? When is it better than Python? | [
"",
"python",
"matlab",
""
] |
How do I check if an object is of a given type, or if it inherits from a given type?
How do I check if the object `o` is of type `str`?
---
Beginners often wrongly expect the string to *already be* "a number" - either expecting Python 3.x `input` to convert type, or expecting that a string like `'1'` is *also simult... | Use [`isinstance`](https://docs.python.org/library/functions.html#isinstance) to check if `o` is an instance of `str` or any subclass of `str`:
```
if isinstance(o, str):
```
To check if the type of `o` is exactly `str`, *excluding subclasses of `str`*:
```
if type(o) is str:
```
See [Built-in Functions](http://doc... | The **most** Pythonic way to check the type of an object is... not to check it.
Since Python encourages [Duck Typing](http://wikipedia.org/wiki/Duck_typing), you should just `try...except` to use the object's methods the way you want to use them. So if your function is looking for a writable file object, *don't* check... | What's the canonical way to check for type in Python? | [
"",
"python",
"types",
""
] |
I need a cross platform solution for clearing the console in both Linux and Windows written in C++. Are there any functions in doing this? Also make note that I don't want the end-user programmer to have to change any code in my program to get it to clear for Windows vs Linux (for example if it has to pick between two ... | Short answer: you can't.
Longer answer: Use a curses library (ncurses on Unix, [pdcurses](http://pdcurses.sf.net/) on Windows). NCurses should be available through your package manager, and both ncurses and pdcurses have the exact same interface (pdcurses can also create windows independently from the console that beh... | There is no generic command to [clear the console on both platforms](http://www.daniweb.com/software-development/cpp/threads/95284/clearing-screen-in-the-console).
```
#include <cstdlib>
void clear_screen()
{
#ifdef WINDOWS
std::system("cls");
#else
// Assume POSIX
std::system ("clear");
#endif
}
``` | How do I clear the console in BOTH Windows and Linux using C++ | [
"",
"c++",
"windows",
"linux",
"console",
"cross-platform",
""
] |
I keep hearing people complaining that C++ doesn't have garbage collection. I also hear that the C++ Standards Committee is looking at adding it to the language. I'm afraid I just don't see the point to it... using RAII with smart pointers eliminates the need for it, right?
My only experience with garbage collection w... | ## I keep hearing people complaining that C++ doesn't have garbage collection.
I am so sorry for them. Seriously.
C++ has RAII, and I always complain to find no RAII (or a castrated RAII) in Garbage Collected languages.
## What advantages could garbage collection offer an experienced C++ developer?
Another tool.
M... | The short answer is that garbage collection is very similar in principle to RAII with smart pointers. If every piece of memory you ever allocate lies within an object, and that object is only referred to by smart pointers, you have something close to garbage collection (potentially better). The advantage comes from not... | Garbage Collection in C++ -- why? | [
"",
"c++",
"garbage-collection",
"c++11",
""
] |
I have been trying to strip out some data from HTML files. I have the logic coded to get the right cells. Now I am struggling to get the actual contents of the 'cell':
here is my HTML snippet:
headerRows[0][10].contents
```
[<font size="+0"><font face="serif" size="1"><b>Apples Produced</b><font size="3">
... | ```
headerRows[0][10].contents[0].find('b').string
``` | The [BeautifulSoup documentation](http://www.crummy.com/software/BeautifulSoup/documentation.html) should cover everything you need - in this case it looks like you want to use `findNext`:
```
headerRows[0][10].findNext('b').string
```
A more generic solution which doesn't rely on the `<b>` tag would be to use the [t... | How do you get the text from an HTML 'datacell' using BeautifulSoup | [
"",
"python",
"html",
"parsing",
"beautifulsoup",
""
] |
I'm trying to display an array of files in order of date (last modified).
I have done this buy looping through the array and sorting it into another array, but is there an easier (more efficient) way to do this? | > **Warning** `create_function()` has been DEPRECATED as of PHP 7.2.0. Relying on this function is highly discouraged.
For the sake of posterity, in case the forum post linked in the accepted answer is lost or unclear to some, the relevant code needed is:
```
<?php
$myarray = glob("*.*");
usort($myarray, create_func... | ```
<?php
$items = glob('*', GLOB_NOSORT);
array_multisort(array_map('filemtime', $items), SORT_NUMERIC, SORT_DESC, $items);
``` | glob() - sort array of files by last modified datetime stamp | [
"",
"php",
"arrays",
"sorting",
"filemtime",
""
] |
I would like to set the log file name for a log4j and log4net appender to have the current date. We are doing Daily rollovers but the current log file does not have a date. The log file name format would be
```
logname.2008-10-10.log
```
Anyone know the best way for me to do this?
edit: I forgot to mention that we w... | DailyRollingFileAppender is what you exactly searching for.
```
<appender name="roll" class="org.apache.log4j.DailyRollingFileAppender">
<param name="File" value="application.log" />
<param name="DatePattern" value=".yyyy-MM-dd" />
<layout class="org.apache.log4j.PatternLayout">
<param name="Convers... | Using log4j.properties file, and including [apache-log4j-extras](http://logging.apache.org/log4j/extras/) 1.1 in my POM with log4j 1.2.16
```
log4j.appender.LOGFILE=org.apache.log4j.rolling.RollingFileAppender
log4j.appender.LOGFILE.RollingPolicy=org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.LOGFILE.R... | Setting a log file name to include current date in Log4j | [
"",
"java",
".net",
"logging",
"log4net",
"log4j",
""
] |
This may be a simple fix - but I'm trying to sum together all the nodes (Size property from the Node class) on the binary search tree. Below in my BST class I have the following so far, but it returns 0:
```
private long sum(Node<T> thisNode)
{
if (thisNode.Left == null && thisNode.Right == null)
... | It's because you're returning zero when you reach a leaf node. You should be returning the size stored in that leaf node.
In addition, if your non-leaf nodes also have a size, you'll need to process them as well thus:
```
private long sum(Node<T> thisNode)
{
if (thisNode.Left == null && thisNode.Right == null)
... | Maybe you meant
```
if (thisNode.Left == null && thisNode.Right == null)
return thisNode.Size;
```
? | Summing up all nodes | [
"",
"c#",
"recursion",
"tree",
"subtree",
""
] |
I listen to the podcast java posse, on this there is often discussion about components (note components are not (clearly) objects). They lament the fact that Java does not have components, and contrast with .NET that does. Components apparently makes developing applications (not just GUI apps) easier.
I can figure fro... | Software Engineering Radio has an episode on exactly this topic: <https://se-radio.net/2008/02/episode-87-software-components/>
The general idea is that a software component can describe what its own dependencies and services are, in the form of metadata. I don't know why you might have heard that Java does not have c... | The term component is one of the most ambiguous and overused ones in OO.
Most people would agree that a component is made up of a group of classes, which collaborate together to implement one or more interfaces. One of the classes takes on the role of the 'front-end' i.e. it implements the interface but delegates the ... | What is a component | [
"",
"java",
".net",
"object",
""
] |
Assume I have a function template like this:
```
template<class T>
inline
void
doStuff(T* arr)
{
// stuff that needs to use sizeof(T)
}
```
Then in another `.h` filee I have a template class `Foo` that has:
```
public: operator T*() const;
```
Now, I realize that those are different Ts. But If I have a variable `... | GCC is correct. In template arguments only exact matches are considered, type conversions are not. This is because otherwise an infinite (or at least exponential) amount of conversions could have to be considered.
If Foo<T> is the only other template that you're going to run in to, the best solution would be to add:
... | This might be worth a try:
```
doStuff<Bar>(f);
```
I think this will cause the compiler to expect T\* to be Bar\* and then use Foo's operator T\*() to perform the cast, but I can't say I've tried it. | Coercing template class with operator T* when passing as T* argument of a function template | [
"",
"c++",
"templates",
"coercion",
""
] |
Is there a way to deploy a Java program in a format that is not reverse-engineerable?
I know how to convert my application into an executable JAR file, but I want to make sure that the code cannot be reverse engineered, or at least, not easily.
Obfuscation of the source code doesn't count... it makes it harder to und... | You could obfuscate your JAR file with [YGuard](http://www.yworks.com/en/products_yguard_about.htm). **It doesn't obfuscate your source code**, but the compiled classes, so there is no problem about maintaining the code later.
If you want to hide some string, you could encrypt it, making it harder to get it through lo... | The short answer is "No, it does not exist".
**Reverse engineering is a process that does not imply to look at the code at all**. It's basically trying to understand the underlying mechanisms and then mimic them. For example, that's how JScript appears from MS labs, by copying Netscape's JavaScript behavior, without h... | Creating non-reverse-engineerable Java programs | [
"",
"java",
"jar",
"compilation",
""
] |
I want a true deep copy. In Java, this was easy, but how do you do it in C#? | ### Important Note
[BinaryFormatter](https://learn.microsoft.com/en-us/dotnet/api/system.runtime.serialization.formatters.binary.binaryformatter?view=net-5.0) has been deprecated, and will no longer be available in .NET after November 2023. See [BinaryFormatter Obsoletion Strategy](https://github.com/dotnet/designs/bl... | I [wrote a deep object copy extension method](https://github.com/Burtsev-Alexey/net-object-deep-copy), based on recursive **"MemberwiseClone"**. It is fast (**three times faster** than BinaryFormatter), and it works with any object. You don't need a default constructor or serializable attributes.
Source code:
```
usi... | How do you do a deep copy of an object in .NET? | [
"",
"c#",
".net",
"serialization",
"clone",
""
] |
I have a 10 second sound effect wave file. What I would like to do is take that file and repeat it n number of times and then save the longer WAV file to disk. This way I can create a much longer background effect rather than auto-repeat on the media player which is a bit stuttered between repeats. I am trying to do th... | If you only need to do this with a small number of files, you might as well do it by hand with [Audacity](http://audacity.sourceforge.net/). | That's reasonably easy to do, given the [WAV file format](http://ccrma.stanford.edu/courses/422/projects/WaveFormat/) - assuming it's uncompressed audio (most WAV files are - or at least, they were last time I had anything to do with them).
There may well be audio APIs you can use to do this without getting stuck into... | WAV file auto repeat in C# | [
"",
"c#",
"audio",
"media",
"wav",
""
] |
I want to continuously sample from my PC's audio line in using C# (then process that data). What is the best way to do the sampling? | You can do some (basic) audio capture using the open source [NAudio](http://www.codeplex.com/naudio) .NET Audio Library. Have a look at the NAudioDemo project to see a simple example of recording to a WAV file using the WaveIn functions. NAudio also now includes the ability to capture audio using WASAPI (Windows Vista ... | There are no built-in libraries in the .NET framework for dealing with sound, but if you're on Win32, you can use an unmanaged library like DirectSound to do it.
Ianier Munoz shows [how to write a full-duplex audio player in C# using **waveIn** via P/Invoke](http://www.codeproject.com/KB/audio-video/cswavrec.aspx?fid=... | What is the simplest way to continuously sample from the line-in using C# | [
"",
"c#",
"audio",
"signal-processing",
"audio-recording",
""
] |
I am part of a team creating a web application using PHP and MySQL. The application will have multiple users with different roles. The application will also be used in a geographically distributed manner. Accordingly we need to create an access control system that operates at the following two levels:
1. Controls user... | I was in similar situation few months ago. I found that tools like Zend\_ACL work great if you just check access level to single item (or reasonably low number of them). It fails when you need to get a huge list of items the user is allowed to access. I crafted custom solution to this problem using [Business Delegate](... | Don't know about the details of your problem but the Zend Framework has a rather potent [ACL](http://framework.zend.com/manual/en/zend.acl.html) and [AUTH](http://framework.zend.com/manual/en/zend.auth.html) set of components you may want to look at. Good stuff like very precise access control, storing data for persist... | PHP Access Control System | [
"",
"php",
"database-design",
"permissions",
"access-control",
"database-permissions",
""
] |
I have a table that has an insert trigger on it. If I insert in 6000 records into this table in one insert statement from a stored procedure, will the stored procedure return before the insert trigger completes?
Just to make sure that I'm thinking correctly, the trigger should only be called (i know 'called' isn't the... | Your insert trigger will run once for the entire insert statement. This is why it is important to use the `inserted` temporary table to see what has actually been inserted, and not just select the most recent single record, or something like that.
I just tested an insert and update trigger and indeed, they are conside... | Triggers are part of the transaction that called them.
One important thing about triggers that you must be aware of is that the trigger fires once for each transaction (at least in SQL server, you should check other dbs, but even if it will process row by row, that is usually a poor idea), so if you insert 6000 record... | Are Sql Triggers synchronous or asynchronous? | [
"",
"sql",
"stored-procedures",
"triggers",
"timing",
""
] |
I need a compact representation of an array of booleans, does Python have a builtin bitfield type or will I need to find an alternate solution? | [Bitarray](http://pypi.python.org/pypi/bitarray/) was the best answer I found, when I recently had a similar need. It's a C extension (so much faster than BitVector, which is pure python) and stores its data in an actual bitfield (so it's eight times more memory efficient than a numpy boolean array, which appears to us... | If you mainly want to be able to name your bit fields and easily manipulate them, e.g. to work with flags represented as single bits in a communications protocol, then you can use the standard Structure and Union features of [ctypes](http://docs.python.org/library/ctypes.html), as described at [How Do I Properly Declar... | Does Python have a bitfield type? | [
"",
"python",
"bit-fields",
"bitarray",
""
] |
I want to convert a number between 0 and 4096 ( 12-bits ) to its 3 character hexadecimal string representation in C#.
Example:
```
2748 to "ABC"
``` | try
```
2748.ToString("X")
``` | If you want exactly 3 characters and are sure the number is in range, use:
```
i.ToString("X3")
```
If you aren't sure if the number is in range, this will give you more than 3 digits. You could do something like:
```
(i % 0x1000).ToString("X3")
```
Use a lower case "x3" if you want lower-case letters. | How do I convert a 12-bit integer to a hexadecimal string in C#? | [
"",
"c#",
""
] |
I've create a WinForms control that inherits from System.Windows.Forms.UserControl...I've got some custom events on the control that I would like the consumer of my control to be able to see. I'm unable to actually get my events to show up in the Events tab of the Properties window during design time. This means the on... | Make sure your events are exposed as public. For example...
```
[Browsable(true)]
public event EventHandler MyCustomEvent;
``` | A solution using delegate. For example i used for a custom ListView which handle item added event :
Declare your delegate :
```
public delegate void ItemAddedHandler(object sender, ItemEventArgs e)
```
then declare the event which use the delegate :
```
[Browsable(true)]
public event ItemAddedHandler ItemAd... | Design Time viewing for User Control events | [
"",
"c#",
"winforms",
"user-controls",
""
] |
As you can see this is a question from a non web developer. I would like to have an ASPX page which, under certain circumstances, can generate a 401 error from code. Ideally it would show the IIS standard page. | Set [Response.StatusCode](http://msdn.microsoft.com/en-us/library/system.web.httpresponse.statuscode.aspx) and then - if you need to stop execution - call [Response.End()](http://msdn.microsoft.com/en-us/library/system.web.httpresponse.end.aspx). | ```
Response.StatusCode = 401;
Response.End();
``` | How to generate an 401 error programmatically in an ASP.NET page | [
"",
"c#",
"asp.net",
"iis",
"asp.net-2.0",
""
] |
For a product in long run (may be 0.5-1 million users) is it good to use java instead of .net from the cost/profitability perspective. To elaborate more..consider web farm scenario in which one will have to purchase windows + Sql server + some antivirus licenses for .net applications. But for java it's almost free. Wha... | I would expect bandwidth to cost more than software licences is you're reasonably successful - although obviously that will depend somewhat on the kind of app, and I haven't run any figures.
Are you just starting this up yourself, with little firm idea that it will take off? If so, I suggest you go with whatever makes... | Go with what you know. With that many users price may not be important. | For a typical Web 2.0 Social Application - Java vs C# | [
"",
"java",
".net",
"visual-studio",
""
] |
Say I have the classic 4-byte signed integer, and I want something like
```
print hex(-1)
```
to give me something like
> 0xffffffff
In reality, the above gives me `-0x1`. I'm dawdling about in some lower level language, and python commandline is quick n easy.
So.. is there a way to do it? | This will do the trick:
```
>>> print(hex (-1 & 0xffffffff))
0xffffffff
```
or, a variant that always returns fixed size (there may well be a better way to do this):
```
>>> def hex3(n):
... return "0x%s"%("00000000%s"%(hex(n&0xffffffff)[2:-1]))[-8:]
...
>>> print hex3(-1)
0xffffffff
>>> print hex3(17)
0x0000001... | Try this function:
```
'%#4x' % (-1 & 0xffffffff)
``` | How to get hex string from signed integer | [
"",
"python",
""
] |
I have two tables, both with start time and end time fields. I need to find, for each row in the first table, all of the rows in the second table where the time intervals intersect.
For example:
```
<-----row 1 interval------->
<---find this--> <--and this--> <--and this-->
```
Please phrase your answer i... | ```
SELECT *
FROM table1,table2
WHERE table2.start <= table1.end
AND (table2.end IS NULL OR table2.end >= table1.start)
``` | It's sound very complicated until you start working from reverse.
Below I illustrated ONLY GOOD CASES (no overlaps)! defined by those 2 simple conditions, we have no overlap ranges if condA OR condB is TRUE, so we going to reverse those:
NOT condA AND NOT CondB, in our case I just reversed signs (> became <=)
```
/*
|... | What is a simple and efficient way to find rows with time-interval overlaps in SQL? | [
"",
"sql",
""
] |
We are working on a website for a client that (for once) is expected to get a fair amount of traffic on day one. There are press releases, people are blogging about it, etc. I am a little concerned that we're going to fall flat on our face on day one. What are the main things you would look at to ensure (in advance wit... | To prepare or handle a spike (or peak) performance, I would first determine whether you are ready through some simple performance testing with something like [jmeter](http://jakarta.apache.org/jmeter/).
It is easy to set up and get started and will give you early metrics whether you will handle an expected peak load.
... | Measure first, and then optimize. Have you done any load testing? Where are the bottlenecks?
Once you know your bottlenecks then you can intelligently decide if you need additional database boxes or web boxes. Right now you'd just be guessing.
Also, how does your load testing results compare against your expected tra... | Best practices for withstanding launch day traffic burst | [
"",
"php",
"mysql",
"linux",
"apache",
"lamp",
""
] |
I know I'm gonna get down votes, but I have to make sure if this is logical or not.
I have three tables A, B, C. B is a table used to make a many-many relationship between A and C. But the thing is that A and C are also related directly in a 1-many relationship
A customer added the following requirement:
Obtain the ... | I'm supposing that s.id\_class indicates the student's current class, as opposed to classes she has taken in the past.
The solution shown by rcar works, but it repeats the c1.className on every row.
Here's an alternative that doesn't repeat information and it uses one fewer join. You can use an expression to compare ... | This is a doable scenario. You can join a table twice in a query, usually assigning it a different alias to keep things straight.
For example:
```
SELECT s.name AS "student name", c1.className AS "student class", c2.className as "class list"
FROM s
JOIN many_to_many mtm ON s.id_student = mtm.id_student
JOIN c c1 ON s... | Weird many to many and one to many relationship | [
"",
"sql",
"constraints",
""
] |
I want something like an [std::map](http://en.wikipedia.org/wiki/Map_%28C++%29), but I only want to see if the item exists or not, I don't actually need a key AND a value. What should I use? | Looks like you need a [std::set](http://en.cppreference.com/w/cpp/container/set). | If you want the same type of behavior as `std::map`, then you want `std::set`.
If you are mixing insert/delete and query operations, then `std::set` is probably the best choice. However, if you can populate the set first and then follow it with the queries, it might be worth looking at using `std::vector`, sorting it,... | Existence map in C++ | [
"",
"c++",
"stl",
"dictionary",
""
] |
I wish to search a database table on a nullable column. Sometimes the value I'm search for is itself NULL. Since Null is equal to nothing, even NULL, saying
```
where MYCOLUMN=SEARCHVALUE
```
will fail. Right now I have to resort to
```
where ((MYCOLUMN=SEARCHVALUE) OR (MYCOLUMN is NULL and SEARCHVALUE is NULL))
```... | You can do the IsNull or NVL stuff, but it's just going to make the engine do more work. You'll be calling functions to do column conversions which then have to have the results compared.
Use what you have
```
where ((MYCOLUMN=SEARCHVALUE) OR (MYCOLUMN is NULL and SEARCHVALUE is NULL))
``` | @Andy Lester asserts that the original form of the query is more efficient than using NVL. I decided to test that assertion:
```
SQL> DECLARE
2 CURSOR B IS
3 SELECT batch_id, equipment_id
4 FROM batch;
5 v_t1 NUMBER;
6 v_t2 NUMBER;
7 v_c1 NUMBER;
... | Determine Oracle null == null | [
"",
"sql",
"oracle",
"null",
"nullable",
""
] |
I am attempting to have a ReportHandler service to handle report creation. Reports can have multiple, differing number of parameters that could be set. In the system currently there are several different methods of creating reports (MS reporting services, html reports, etc) and the way the data is generated for each re... | From your description, if you're looking for a pattern that matches better than Factory, try Strategy:
[Strategy Pattern](http://en.wikipedia.org/wiki/Strategy_pattern)
1. Your **context** could be a custom class which encapsulates and abstracts the different report inputs (you could use the AbstractFactory pattern f... | In addition to the strategy pattern, you can also create one adaptor for each of your underlying solutions. Then use strategy to vary them. I've built similar with each report solution being supported by what I called engines, In addition to the variable report solution we have variable storage solution as well - outpu... | Report handler architecture question | [
"",
"c#",
"asp.net",
"report",
"activereports",
""
] |
The coding is done using VS2008
There are two divs in my page namely "dvLeftContent" and "dvRightContent".
I cannot statically set the height of the pages since "dvRightContent" have variable heights on various pages (Master Pages are used here)
Is there a client side function(javascript or jquery) that takes the heigh... | Using jQuery:
```
$("#dvRightContent").bind("resize", function(){
$("#dvLeftContent").css('height', $("#dvRightContent").css('height'));
});
``` | Thanks micahwittman. Some minor changes
```
$("#dvRightContent").resize(function(){
$("#dvLeftContent").css("height", ($("#dvRightContent").attr("offsetHeight") - 250 ) +"px");
});
```
Its because height will give only "auto" in this case as its set like that | Dynamically Set the Height of Two floated DIVS | [
"",
"asp.net",
"javascript",
"jquery",
""
] |
As an example, lets say I wanted to list the frequency of each letter of the alphabet in a string. What would be the easiest way to do it?
This is an example of what I'm thinking of... the question is how to make allTheLetters equal to said letters without something like allTheLetters = "abcdefg...xyz". In many other ... | The question you've asked (how to iterate through the alphabet) is not the same question as the problem you're trying to solve (how to count the frequency of letters in a string).
You can use string.lowercase, as other posters have suggested:
```
import string
allTheLetters = string.lowercase
```
To do things the wa... | > the question is how to make
> allTheLetters equal to said letters
> without something like allTheLetters =
> "abcdefg...xyz"
That's actually provided by the string module, it's not like you have to manually type it yourself ;)
```
import string
allTheLetters = string.ascii_lowercase
def alphCount(text):
lowerTe... | How do I iterate through a string in Python? | [
"",
"python",
""
] |
I basically want to run all JUnit ***unit*** tests in my IntelliJ IDEA project (excluding JUnit integration tests), using the static suite() method of JUnit. Why use the static suite() method? Because I can then use IntelliJ IDEA's JUnit test runner to run all unit tests in my application (and easily exclude all integr... | I've written some code to do most of the work. It works only if your files are on the local disk instead of in a JAR. All you need is one class in the package. You could, for this purpose, create a Locator.java class, just to be able to find the package.
```
public class ClassEnumerator {
public static void main(S... | How about putting each major group of junit tests into their own root package. I use this package structure in my project:
```
test.
quick.
com.acme
slow.
com.acme
```
Without any coding, you can set up IntelliJ to run all tests, just the quick ones or just the slow ones. | How can I run all JUnit unit tests except those ending in "IntegrationTest" in my IntelliJ IDEA project using the integrated test runner? | [
"",
"java",
"unit-testing",
"reflection",
"junit",
"intellij-idea",
""
] |
Full disclaimer: I'm a CS student, and this question is related to a recently assigned Java program for Object-Oriented Programming. Although we've done some console stuff, this is the first time we've worked with a GUI and Swing or Awt. We were given some code that created a window with some text and a button that rot... | Instead of writing this:
```
resetButton.addActionListener(this);
```
You could also write this:
```
resetButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
resetButtonActionPerformed(evt);
}
});
```
And instead of writing one big actionPerformed() for all... | As suggested already, you can use anonymous inner classes to implement the ActionListener interface. As an alternative, you don't have to use anonymous inner classes, but you can use a simple nested class instead:
```
resetButton = new JButton(new ResetAction());
redButton = new JButton(new ColorAction("Red", Color.re... | Switching on a string/implementing button actions | [
"",
"java",
"swing",
"awt",
""
] |
I am trying to send an email from a site I am building, but it ends up in the yahoo spam folder. It is the email that sends credentials. What can I do to legitimize it?
```
$header = "From: site <sales@site.com>\r\n";
$header .= "To: $name <$email>\r\n";
$header .= "Subject: $subject\r\n";
$header .= "Reply-To: site <... | In addition to Ted Percival's suggestions, you could try using [PHPMailer](http://phpmailer.codeworxtech.com/index.php?pg=phpmailer) to create the emails for you rather than manually building the headers. I've used this class extensively and not had any trouble with email being rejected as spam by Yahoo, or anyone else... | * Don't use HTML in your email.
* Send it via a legitimate mail server with a static IP and reverse-DNS (PTR) that points to the machine's real host name (and matches a forward lookup).
* Include a Message-ID (or ensure that the local mailer adds one for you).
* Run your email through [SpamAssassin](http://spamassassin... | What do I need for a compliant email header | [
"",
"php",
"email",
"header",
""
] |
This question may sound fairly elementary, but this is a debate I had with another developer I work with.
I was taking care to stack allocate things where I could, instead of heap allocating them. He was talking to me and watching over my shoulder and commented that it wasn't necessary because they are the same perfor... | Stack allocation is much faster since all it really does is move the stack pointer.
Using memory pools, you can get comparable performance out of heap allocation, but that comes with a slight added complexity and its own headaches.
Also, stack vs. heap is not only a performance consideration; it also tells you a lot a... | Stack is much faster. It literally only uses a single instruction on most architectures, in most cases, e.g. on x86:
```
sub esp, 0x10
```
(That moves the stack pointer down by 0x10 bytes and thereby "allocates" those bytes for use by a variable.)
Of course, the stack's size is very, very finite, as you will quickly... | Which is faster: Stack allocation or Heap allocation | [
"",
"c++",
"performance",
"memory",
"stack",
"heap-memory",
""
] |
I'm trying to do some async stuff in a webservice method. Let say I have the following API call: <http://www.example.com/api.asmx>
and the method is called *GetProducts()*.
I this GetProducts methods, I do some stuff (eg. get data from database) then just before i return the result, I want to do some async stuff (eg.... | `BackgroundWorker` is useful when you need to synchronize back to (for example) a UI\* thread, eg for affinity reasons. In this case, it would seem that simply using `ThreadPool` would be more than adequate (and much simpler). If you have high volumes, then a producer/consumer queue may allow better throttling (so you ... | Re producer/consumer; basically - it is just worth keeping *some* kind of throttle. At the simplest level, a `Semaphore` could be used (along with the regular `ThreadPool`) to limit things to a known amount of work (to avoid saturating the thread pool); but a producer/consumer queue would probably be more efficient and... | .NET Web Service & BackgroundWorker threads | [
"",
"c#",
"asp.net",
"multithreading",
"backgroundworker",
""
] |
Many Java Apps don't use anti-aliased fonts by default, despite the capability of Swing to provide them. How can you coerce an arbitrary java application to use AA fonts? (both for applications I'm running, and applications I'm developing) | If you have access to the source, you can do this in the main method:
```
// enable anti-aliased text:
System.setProperty("awt.useSystemAAFontSettings","on");
```
or, (and if you do not have access to the source, or if this is easier) you can simply pass the system properties above into the jvm by adding these op... | Swing controls in the latest versions of Java 6 / 7 should automatically abide by system-wide preferences. (If you're using the Windows L&F on a Windows OS then text should render using ClearType if you have that setting enabled system-wide.) So perhaps one solution could simply be: enable the native Look and Feel?
In... | How do you enable anti aliasing in arbitrary Java apps? | [
"",
"java",
"antialiasing",
""
] |
Given a list `["foo", "bar", "baz"]` and an item in the list `"bar"`, how do I get its index `1`? | ```
>>> ["foo", "bar", "baz"].index("bar")
1
```
See [the documentation](https://docs.python.org/tutorial/datastructures.html#more-on-lists) for the built-in `.index()` method of the list:
> ```
> list.index(x[, start[, end]])
> ```
>
> Return zero-based index in the list of the first item whose value is equal to *x*... | The majority of answers explain how to find **a single index**, but their methods do not return multiple indexes if the item is in the list multiple times. Use [`enumerate()`](https://docs.python.org/library/functions.html#enumerate):
```
for i, j in enumerate(['foo', 'bar', 'baz']):
if j == 'bar':
print(i... | How to find the index for a given item in a list? | [
"",
"python",
"list",
"indexing",
""
] |
I have an ASP.NET page which has a button it it. The button click launches a modal dialog box using JavaScript. Based on the value returned by the modal dialog box, I want to proceed with, or cancel the post back that happens. How do I do this? | Adding "return false;" to the onclick attribute of the button will prevent the automatic postback. | Is this what you are trying to do?
```
<input type="button" id="myButton" value="Click!" />
<script type="text/javascript">
document.getElementById('myButton').onclick = function() {
var agree = confirm('Are you sure?');
if (!agree) return false;
};
</script>
``` | How to avoid a postback in JavaScript? | [
"",
"javascript",
"asp.net",
""
] |
It's common in C++ to name member variables with some kind of prefix to denote the fact that they're member variables, rather than local variables or parameters. If you've come from an MFC background, you'll probably use `m_foo`. I've also seen `myFoo` occasionally.
C# (or possibly just .NET) seems to recommend using ... | The rules (which did not change in C++11):
* Reserved in any scope, including for use as [implementation](https://stackoverflow.com/questions/4297933/c-implementation#4297974) macros:
+ identifiers beginning with an underscore followed immediately by an uppercase letter
+ identifiers containing adjacent underscore... | The rules to avoid collision of names are both in the C++ standard (see Stroustrup book) and mentioned by C++ gurus (Sutter, etc.).
## Personal rule
Because I did not want to deal with cases, and wanted a simple rule, I have designed a **personal** one that is both simple and correct:
**When naming a symbol, you wil... | What are the rules about using an underscore in a C++ identifier? | [
"",
"c++",
"language-lawyer",
"naming-conventions",
"c++-faq",
""
] |
I want to write a odometer-like method in a C#-style-language, but not just using 0-9 for characters, but any set of characters. It will act like a brute-force application, more or less.
If I pass in a char-array of characters from **0** to **J**, and set length to 5, I want results like *00000, 00001, 00002... HJJJJ,... | This is one of the solutions I've found. I like the compactness and separation of it:
```
private static char[] characters =
new char[] { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F', 'G', 'H', 'I', 'J' };
// length: The length of the string created by bruteforce
public static vo... | This isn't *quite* a duplicate of ["recursion instead of multi-loops"](https://stackoverflow.com/questions/207889/recursion-instead-of-multi-loops) but it's pretty close. I'll write up a solution if this doesn't help you.
EDIT: Here's a non-recursive solution. The recursive one is slightly harder to return an `IEnumer... | Algorithm: Odometer / Brute force | [
"",
"c#",
"algorithm",
""
] |
I have a very basic question about MVC web applications in Java.
Since the olden days of raw JSP up until current technologies like Seam, a very basic pattern has always been the internal dispatch from the controller that initially accepted the request to the view layer that creates the output to be sent to the client... | I have now seen a couple of applications that put their internal JSP into `WEB-INF/jsp`. That seems to do the trick, at least for JSP, and also for Velocity. It [does not seem to work for JSF](http://www.coderanch.com/t/212515/JSF/java/hiding-pages-behind-WEB-INF), though. | You can prevent access to internal resources by using a [`security-constraint`](http://wiki.metawerx.net/wiki/Web.xml.SecurityConstraint) in your `web.xml` deployment descriptor.
For example, I use the following configuration to prevent direct access to JSPs:
```
<!-- Prevent direct access to JSPs. -->
<security-cons... | Protecting internal view layer template pages in servlet applications | [
"",
"java",
"architecture",
"servlets",
""
] |
I am curious if anyone has done a comparison between the different options out there. So far I am leaning towards using Moo.fx because loading prototype.js just to use scriptaculous seems a bit much. Does that make sense? Are there any other effects libraries worth trying? Thanks. | I've found a viable alternative to the recommended JS libraries -- a GWT-native Java library called [GWT-FX](http://code.google.com/p/gwt-fx/) developed by Adam Tacy. Some of its features include built-in effects (Fade, Slide, Highlight), physics transition types (linear, ease in/out, elastic), and the ability to build... | "Smart GWT" has interesting effects, especially to mimic desktop items. I pass the ShowCase:
[Smart GWT Showcase](http://www.smartclient.com/smartgwt/showcase/#main) | Which effects library should I integrate with GWT? | [
"",
"javascript",
"css",
"gwt",
"comparison",
"effects",
""
] |
Some of the other questions and answers here on SO extol the virtues of using an enterprise repository tool like Archiva, Artifactory, or Nexus. What are the pros and cons of each? How do I choose between them?
In case it helps:
* We use both Maven 1 and Maven 2 (at least for a while)
* We want to store both internal... | We had been using Archiva for a while, and were happy with it. We recently switched hardware, and decided to try out Nexus because we had read some good things about it. We didn't know what we were missing in Archiva, but Nexus is far better. The repository aspect is easier because it "groups" all the repositories into... | I have used Archiva for over a year and found it met all of the basic requirements, however, we were restricted to a Windows server and as such found a few limitations and had a large memory footprint.
The main reason we started looking for an alternative, however, was the painful process to upload artifacts to the re... | Best enterprise repository tool for Maven 2? | [
"",
"java",
"maven-2",
"build-automation",
"devtools",
""
] |
I guess the real question is:
If I don't care about dirty reads, will adding the **with (NOLOCK)** hint to a SELECT statement affect the performance of:
1. the current SELECT statement
2. other transactions against the given table
Example:
```
Select *
from aTable with (NOLOCK)
``` | 1) **Yes**, a select with `NOLOCK` will complete faster than a normal select.
2) **Yes**, a select with `NOLOCK` will allow other queries against the effected table to complete faster than a normal select.
**Why would this be?**
`NOLOCK` typically (depending on your DB engine) means give me your data, and I don't ca... | NOLOCK makes most SELECT statements faster, because of the lack of shared locks. Also, the lack of issuance of the locks means that writers will not be impeded by your SELECT.
NOLOCK is functionally equivalent to an isolation level of READ UNCOMMITTED. The main difference is that you can use NOLOCK on some tables but ... | Effect of NOLOCK hint in SELECT statements | [
"",
"sql",
"sql-server",
"locking",
""
] |
I've noticed for quite a long time that strange domains such like jsev.com, cssxx.com appered in my firefox status bar from time to time, I always wonder why so many web pages contains resources from these strange domains. I googled it, but found nothing. I guess it's some kind of virus which infect the servers and ins... | This happens if you are using one of Princeton university's CoDeeN project proxy servers. CoDeeN is an academic testbed content distribution network. When you browse a web page using CoDeeN proxy it injects some HTML code to the site's original HTML and redirects requests sent to pseudo adresses to the project's server... | It may be a browser worm installed on your machine. Should scan entire system. | Why so many web pages contain such a strange code snippet in header? | [
"",
"javascript",
"html",
"virus",
""
] |
I'm looking for a free winforms component for an application I'm writing. I basicly need a textbox that contains line numbers in a side column. Being able to tabulate data within it would be a major plus too.
Does anyone know of a premade component that could do this? | Referencing [Wayne's post](https://stackoverflow.com/questions/124975/windows-forms-textbox-that-has-line-numbers#125093), here is the relevant code. It is using GDI to draw line numbers next to the text box.
```
Public Sub New()
MyBase.New()
'This call is required by the Windows Form Designer.
Initialize... | Take a look at the [SharpDevelop](https://github.com/icsharpcode) C# compiler/IDE source code. They have a sophisticated text box with line numbers. You could look at the source, figure out what they're doing, and then implement it yourself.
Here's a sample of what I'm referencing:
[. It can create a patch string from differences and allow to reapply the patch.
**edit**: Another solution might be to <https://code.google.com/p/java-diff-utils/> | Apache Commons has String diff
org.apache.commons.lang.StringUtils
```
StringUtils.difference("foobar", "foo");
``` | How to perform string Diffs in Java? | [
"",
"java",
"diff",
""
] |
what is the best practice for multilanguage website using DOM Manipulating with javascript? I build some dynamic parts of the website using javascript. My first thought was using an array with the text strings and the language code as index. Is this a good idea? | When I've built multi-lingual sites before (not very large ones, so this might not scale too well), I keep a series of "language" files:
* lang.en.js
* lang.it.js
* lang.fr.js
Each of the files declares an object which is basically just a map from key word to language phrase:
```
// lang.en.js
lang = {
greeting ... | There are a few things you need to keep in mind when designing multilanguage support:
1 - Separate code from data (i.e. don't hard-code strings right into your functions)
2 - create a formatting hook function to deal with localization differences. Allowing formattable strings (**"{0}"**) is better than concatenating ... | Best practice javascript and multilanguage | [
"",
"javascript",
"internationalization",
""
] |
My question is quite relevant to [something asked before](https://stackoverflow.com/questions/42785/how-do-you-retrofit-unit-tests-into-a-code-base) but I need some practical advice.
I have "Working effectively with legacy code" in my hands and I 'm using advice from the book as I read it in the project I 'm working o... | If your test app is only linking the object files it needs to test then you are effectively already treating them as a library, it should be possible to group those object files into a separate library for the main and the test app. If you can't then I don't see that what you are doing is too bad an alternative.
If yo... | [Working Effectively With Legacy Code](https://rads.stackoverflow.com/amzn/click/com/0131177052) is the best resource for how to start testing old code. There are really no short term solutions that won't result in things getting worse. | Adding unit tests to an existing project | [
"",
"c++",
"unit-testing",
"legacy",
""
] |
I have this regex I built and tested in regex buddy.
```
"_ [ 0-9]{10}+ {1}+[ 0-9]{10}+ {2}+[ 0-9]{6}+ {2}[ 0-9]{2}"
```
When I use this in .Net C#
I receive the exception
```
"parsing \"_ [ 0-9]{10}+ +[ 0-9]{10}+ +[ 0-9]{6}+ [ 0-9]{2}\" - Nested quantifier +."
```
What does this error mean? Apparently .net does... | .NET is complaining about the `+` after the `{n}` style quantifier as it doesn't make any sense. `{n}` means match exactly n of a given group. `+` means match one or more of a given group. Remove the `+`'s and it'll compile fine.
```
"_ [ 0-9]{10} {1}[ 0-9]{10} {2}[ 0-9]{6} {2}[ 0-9]{2}"
``` | .NET doesn't support the [possessive quantifier](http://www.regular-expressions.info/possessive.html)
```
{10}+
```
However, {10} should have exactly the same effect. The + avoids backtracking and trying shorter matches if the longest match fails, but since {10} can only match exactly 10 characters to start with this... | What is a "Nested Quantifier" and why is it causing my regex to fail? | [
"",
"c#",
".net",
"regex",
""
] |
Wanted to see peoples thoughts on best way to organize directory and project structure on a project / solution for a winforms C# app.
Most people agree its best to seperate view, business logic, data objects, interfaces but wanted to see how different people tackle this. In addition, isolate third party dependencies i... | For me it depends on the model I'm following. If I'm using MVC it would be
```
Project
-Models
-Controllers
-Views
```
Or for MVP it would be
```
Project
-Models
-Presenters
-Views
```
Under the views I seperate them into namespaces relevant to the controllers, i.e. if I have a controller to handle inventory transa... | Bit of a late answer but may as well chime in.
I have been personally using folders based on the actual type of item it is. For example:
```
- Project
+ Forms
+ Classes
+ UserControls
+ Resources
+ Data
```
So I end up with:
```
new Forms.AboutForm().ShowDialog();
Controls.Add(new Controls.UberT... | Winforms - best directory / project structure | [
"",
"c#",
"winforms",
""
] |
I chmod'ed the directory to 777, same with the directory contents. Still, I get a "permission denied" error. Does PHP throw this error if apache is not the group/owner, regardless of the file permissions? Here's the call that's failing:
```
rename('/correct/path/to/dir/1', '/correct/path/to/dir/2');
``` | You're editing the higher level directory, so the PHP user needs to have write access to that directory. | Thats probably because apache is not the owner of the parent directory. Renaming (or moving) a file is basically the same thing as creating a new file. | Why do I get "permission denied" in PHP when trying to rename a directory? | [
"",
"php",
"permissions",
"rename",
""
] |
Definition of variables in use:
```
Guid fldProId = (Guid)ffdPro.GetProperty("FieldId");
string fldProValue = (string)ffdPro.GetProperty("FieldValue");
FormFieldDef fmProFldDef = new FormFieldDef();
fmProFldDef.Key = fldProId;
fmProFldDef.Retrieve();
string fldProName = (string)fmProFldDef.GetProperty("FieldName");
st... | Are you sure that findControl is returning a value?
Is hTxtBox.Text a property that does any computation on a set that could be throwing the NullReferenceException? | findControl is returning a null value. It could be that the particular Label is not a direct child of the current page, i.e., inside an UpdatePanel or some other control so that the actual name of the control is different than the name applied (and thus it can't find it). For example, if it is named "name", the actual ... | C#, ASP.NET - NullReferenceException - Object reference not set to an instance of an object | [
"",
"c#",
"asp.net",
""
] |
I am using a Session Parameter on an ObjectDataSource. It works fine on the local development machine but I get this error after copying the website to the production server:
Type 'System.Web.UI.WebControls.SessionParameter' does not have a public property named 'DbType'. | Me again!
First Answer I gave was WRONG!
Correct answer is that .NET Framework v3.5 was installed, and it needs to be updated to .NET framework 3.5 SP1 | I found the answer but I don't know why it does this.
I just removed the DBType property and it worked fine. | Type 'System.Web.UI.WebControls.SessionParameter' does not have a public property named 'DbType' | [
"",
"asp.net",
"sql",
"parameters",
"objectdatasource",
""
] |
Coming from a desktop background I'm not sure exactly how to pass the exceptions I have caught to an Error page in order to avoid the standard exception screen being seen by my users.
My general question is how do I pass the exception from page X to my Error page in ASP.net? | I suggest using the customErrors section in the web.config:
```
<customErrors mode="RemoteOnly" defaultRedirect="/error.html">
<error statusCode="403" redirect="/accessdenied.html" />
<error statusCode="404" redirect="/pagenotfound.html" />
</customErrors>
```
And then using [ELMAH](https://code.goo... | The pattern I use is to log the error in a try/catch block (using log4net), then do a response.redirect to a simple error page. This assumes you don't need to show any error details.
If you need the exception details on a separate page, you might want to look at Server.GetLastError. I use that in global.asax (in the A... | Passing Exceptions to an error screen in ASP.net/C# | [
"",
"c#",
"asp.net",
"error-handling",
""
] |
What's the best way to connect to a Informix database from .Net?
I'm developing a client-server application based on a legacy Informix DB which used to be connected by JDBC.
I need it, from the most important to the least:
1. To be fast
2. DB server changes not needed
3. No ODBC and no dependencies, other than de .N... | The connections strings to use with OleDb or ADO.NET can be found [here](http://www.connectionstrings.com/?carrier=informix).
Take a look at this [article](https://www.ibm.com/developerworks/data/library/techarticle/dm-0510durity/index.html) on how to connect to an Informix database using ADO.NET. | We connect to Informix from .NET, but we do it via web services that are written in FourJ's BDL | Connecting to Informix database from .Net | [
"",
"c#",
".net",
"database-connection",
"informix",
""
] |
I have a C++ program representing a TCP header as a struct:
```
#include "stdafx.h"
/* TCP HEADER
0 1 2 3
0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
| ... | See this question: [Why isn't sizeof for a struct equal to the sum of sizeof of each member?](https://stackoverflow.com/questions/119123/why-does-the-sizeof-operator-return-a-size-larger-for-a-structure-than-the-tota) .
I believe that compiler takes a hint to disable padding when you use the "unsigned int wWindow:16" ... | Because the compiler is packing your bitfield into a 32-bit int, not a 16-bit entity.
In general you should avoid bitfields and use other manifest constants (enums or whatever) with explicit bit masking and shifting to access the 'sub-fields' in a field.
Here's one reason why bitfields should be avoided - they aren't... | Getting different header size by changing window size | [
"",
"c++",
"c",
"struct",
"packing",
""
] |
What's the best way to format this for readability?
```
if (strpos($file, '.jpg',1) && file_exists("$thumbsdir/$file") == false || strpos($file, '.gif',1) && file_exists("$thumbsdir/$file") == false || strpos($file, '.png',1) && file_exists("$thumbsdir/$file") == false) {
createThumb("$gallerydir/$file", "$thumbsdir... | I'd extract the "is an image" logic into its own function, which makes the `if` more readable and also allows you to centralize the logic.
```
function is_image($filename) {
$image_extensions = array('png', 'gif', 'jpg');
foreach ($image_extensions as $extension)
if (strrpos($filename, ".$extension")... | ```
if ((strpos($file, '.jpg',1) ||
strpos($file, '.gif',1) ||
strpos($file, '.png',1))
&& file_exists("$thumbsdir/$file") == false)
{
createThumb("$gallerydir/$file", "$thumbsdir/$file",$thumbsize);
fwrite($log,date("Y-m-d")." @ ".date("H:i:s")." CREATED: $thumbsdir/$file\n");
}
``` | Formatting an if statement for readability | [
"",
"php",
"formatting",
"readability",
""
] |
Recently, I noticed some people mentioning that `std::list::size()` has a linear complexity.
According to [some](http://www.cplusplus.com/reference/stl/list/size.html) [sources](http://bytes.com/forum/thread60248.html), this is in fact implementation dependent as the standard doesn't say what the complexity has to be... | ## Pre-C++11 answer
You are correct that the standard does not state what the complexity of `list::size()` must be - however, it does recommend that it "should have constant complexity" (Note A in Table 65).
[Here's an interesting article by Howard Hinnant](http://howardhinnant.github.io/On_list_size.html) that expla... | In C++11 it is required that for *any* standard container the `.size()` operation must be complete in "constant" complexity (O(1)). (Table 96 — Container requirements). Previously in C++03 `.size()` *should* have constant complexity, but is not required (see [Is std::string size() a O(1) operation?](https://stackoverfl... | Is list::size() really O(n)? | [
"",
"c++",
"list",
"big-o",
"std",
"complexity-theory",
""
] |
Using SQLite3 with Python 2.5, I'm trying to iterate through a list and pull the weight of an item from the database based on the item's name.
I tried using the "?" parameter substitution suggested to prevent SQL injections but it doesn't work. For example, when I use:
```
for item in self.inventory_names:
self.c... | The `Cursor.execute()` method expects a sequence as second parameter. You are supplying a string which happens to be 8 characters long.
Use the following form instead:
```
self.cursor.execute("SELECT weight FROM Equipment WHERE name = ?", [item])
```
Python library reference: sqlite3 [Cursor Objects](https://docs.py... | I have spent half a day trying to figure out why something like this would give me an error:
```
cursor.execute("SELECT * from ? WHERE name = ?", (table_name, name))
```
only to find out that table names *cannot be parametrized*. Hope this will help other people save some time. | SQLite parameter substitution problem | [
"",
"python",
"sqlite",
""
] |
I've been working on a web crawling .NET app in my free time, and one of the features of this app that I wanted to included was a pause button to pause a specific thread.
I'm relatively new to multi-threading and I haven't been able to figure out a way to pause a thread indefinitely that is currently supported. I can'... | Never, ever use `Thread.Suspend`. The major problem with it is that 99% of the time you can't know what that thread is doing when you suspend it. If that thread holds a lock, you make it easier to get into a deadlock situation, etc. Keep in mind that code you are calling may be acquiring/releasing locks behind the scen... | The [Threading in C#](http://www.albahari.com/threading/part4.aspx#_Suspending_and_Resuming) ebook summarises Thread.Suspend and Thread.Resume thusly:
> The deprecated Suspend and Resume methods have two modes – dangerous and useless!
The book recommends using a synchronization construct such as an [AutoResetEvent](h... | Is there a way to indefinitely pause a thread? | [
"",
"c#",
".net",
"multithreading",
""
] |
I have a simple web form that has a several fields and a gridview on it. I also have a save and cancel button.
I would like a way to undo what was done to the data on the form when the user presses cancel. This is simple enough with the fields however since changes to the gridview happen in real time against the datab... | Keep all the data in a session object and write that to the database when you are ready. If you abstract your data layer you can use the ObjectDataSource that interacts with the session objects.
I'm currently using this method on a checkout system for an e-commerce site. I store the data in custom objects that mimic t... | The simplest solution is to not commit the changes in the gridview to the database until the user clicks the "save" button.
If you do decide to use viewstate or some such to record changes that you will later undo, don't forget to take the same sorts of precautions re: update collisions that you would when making the ... | ASP.net Web App undo support | [
"",
"c#",
"asp.net",
"web-applications",
"undo",
""
] |
I'm building an ASP.NET AJAX application that uses JavaScript to call web services to get its data, and also uses Silverlights Isolated Storage to cache the data on the client machine. Ultimately once the data is downloaded it is passed to JavaScript which displays in on the page using the HTML DOM.
What I'm trying to... | Since Silverlight can handle JSON and XML based services, the format of the response is totally irrelevant. What you must consider, however, is the following:
1) Silverlight is approximately 1000 times faster than JavaScript
2) If your web service is natively SOAP based, Visual Studio can generate a proxy for you, so ... | Another thing to consider - getting your data in JSON format will be faster than XML and Web Services. JSON becomes a JavaScript object pretty quickly and doesn't have to be parsed like XML does. Personally, I'd go with JavaScript.
article: [Speeding Up AJAX with JSON](http://www.developer.com/lang/jscript/article.php... | Call Web Services Using Ajax or Silverlight? Which performs best? | [
"",
"javascript",
"ajax",
"silverlight",
"web-services",
"asp.net-ajax",
""
] |
I am having a problem with FCKeditor reverting html entities entered in the source view back to their original unicode representations.
For example when I enter `€` into the source view, switch to html and then back to source view, the entity is replaced by an actual € symbol.
The bigger problem, as a result, is t... | The problem was a configuration setting - `FCKConfig.ProcessHTMLEntities=true`.
Altough I had tried changing this in fckconfig.js, I did not realise that the value was being over-ridden in a secondary custom configuration file which had been created by a previous developer.
Thanks Anne. | What version of FCKeditor are you using? The current version is 2.6.3. I tested the € symbol in their demo by copying `€` into source view, switched back to display and then back to HTML the ASCII `€` was retained correctly. As such it sounds like there might be a configuration problem with your install of FC... | How do I stop FCKeditor reverting html entities back to their unicode characters | [
"",
"javascript",
"fckeditor",
""
] |
We try to convert from string to `Byte[]` using the following Java code:
```
String source = "0123456789";
byte[] byteArray = source.getBytes("UTF-16");
```
We get a byte array of length 22 bytes, we are not sure where this padding comes from.
How do I get an array of length 20? | [Alexander's answer](https://stackoverflow.com/questions/228987/convert-string-to-byte-in-java#228998) explains why it's there, but not how to get rid of it. You simply need to specify the endianness you want in the encoding name:
```
String source = "0123456789";
byte[] byteArray = source.getBytes("UTF-16LE"); // Or ... | May be the first two bytes are the [Byte Order Mark](http://en.wikipedia.org/wiki/Byte_Order_Mark). It specifies the order of bytes in each 16-bit word used in the encoding. | Why does byteArray have a length of 22 instead of 20? | [
"",
"java",
"encoding",
"string",
"arrays",
""
] |
Java & Oracle both have a *timestamp* type called Date. Developers tend to manipulate these as if they were *calendar* dates, which I've seen cause nasty one-off bugs.
1. For a basic date quantity you can simply chop off the time portion upon input, i.e., reduce the precision. But if you do that with a date range, (e.... | Here's how we do it.
1. Use timestamps.
2. Use Half-open intervals for comparison: `start <= now < end`.
Ignore the whiners who insist that BETWEEN is somehow essential to successful SQL.
With this a series of date ranges is really easy to audit. The database value for `9/30 to 10/1` encompass one day (9/30). The ne... | Oracle has the [TIMESTAMP datatype](http://download.oracle.com/docs/cd/B28359_01/server.111/b28286/sql_elements001.htm#SQLRF00203). It stores the year, month, and day of the DATE datatype, plus hour, minute, second and fractional second values.
Here is a [thread on asktom.oracle.com](http://asktom.oracle.com/pls/askto... | How do you store Date ranges, which are actually timestamps | [
"",
"java",
"oracle",
"architecture",
"types",
"date-range",
""
] |
I would really like to annotate a method with a reference to a single property in a property file for injection.
```
@Resource("${my.service.url}")
private String myServiceUrl;
```
Of course, this syntax does not work ;) Thats why I'm asking here.
I am aware that I can inject the full properties file, but that just ... | There's a thread about this on the [Spring forum](http://forum.springframework.org/showthread.php?t=50790). The short answer is that there's really no way to inject a single property using annotations.
I've heard that the support for using annotations will be improved in Spring 3.0, so it's likely this will be address... | I know it has been a while since the original post but I have managed to stumble across a solution to this for spring 2.5.x
You can create instances of "String" beans in the spring xml configuration which can then be injected into the Annotated components
```
@Component
public class SomeCompent{
@Autowired(required... | How do I inject a single property value into a string using spring 2.5.x? | [
"",
"java",
"spring",
""
] |
Is there any free java library which I can use to convert string in one encoding to other encoding, something like [`iconv`](https://en.wikipedia.org/wiki/Iconv)? I'm using Java version 1.3. | You don't need a library beyond the standard one - just use [Charset](https://docs.oracle.com/javase/6/docs/api/java/nio/charset/Charset.html). (You can just use the String constructors and getBytes methods, but personally I don't like just working with the names of character encodings. Too much room for typos.)
EDIT:... | [`CharsetDecoder`](https://docs.oracle.com/en/java/javase/20/docs/api/java.base/java/nio/charset/CharsetDecoder.html) should be what you are looking for, no ?
Many network protocols and files store their characters with a byte-oriented character set such as `ISO-8859-1` (`ISO-Latin-1`).
However, Java's native charac... | Encoding conversion in java | [
"",
"java",
"character-encoding",
"converters",
""
] |
We want to show a hint for a JList that the user can select multiple items with the platform dependent key for multiselect.
However I have not found any way to show the OS X COMMAND symbol in a JLabel, which means the symbol that's printed on the apple keyboard on the command key, also called apple key.
Here's a pict... | The symbol in question is avaiable through Unicode, and the HTML character sets. All you need to do is make your JLabel display HTML by starting its text string with <html> and then include the character code.
```
JLabel label = new JLabel( "<html>⌘ is the Apple command symbol." );
```
This will work on a Mac, ... | As David points out, you can use the Unicode escape sequence `\u2318` although it must be displayed with a font supporting it. | Display the OSX Command symbol key in a JLabel | [
"",
"java",
"macos",
"command",
"key",
""
] |
How to add offline access functionality to [MoinMoin wiki](http://moinmo.in)?
As a minimum, I would love to have browsing access to all pages on a server-based wiki (while being offline). Search and other things, which do not modify the content, are secondary. An added bonus would be if this solution allowed to update... | *By using Gears with the Firefox Greasemonkey plugin, you can inject Gears code into any website that you want. Don't wait for your favorite website to enable offline support -- do it yourself.* <http://code.google.com/apis/gears/articles/gearsmonkey.html> | If you have the freedom to change the wiki software, I might suggest looking at [ikiwiki](http://ikiwiki.info). You can set it up so the pages are backed by a real VCS such as Git, in which case you can clone the whole wiki and read and even update it offline. | Offline access to MoinMoin wiki using Google Gears | [
"",
"python",
"wiki",
"offline",
"google-gears",
"moinmoin",
""
] |
I would like to drag and drop my data file onto a Python script and have it process the file and generate output. The Python script accepts the name of the data file as a command-line parameter, but Windows Explorer doesn't allow the script to be a drop target.
Is there some kind of configuration that needs to be done... | Sure. From a [mindless technology article called "Make Python Scripts Droppable in Windows"](http://mindlesstechnology.wordpress.com/2008/03/29/make-python-scripts-droppable-in-windows/), you can add a drop handler by adding a registry key:
> Here’s a registry import file that you can use to do this. Copy the
> follow... | write a simple shell script (`file.bat`)
```
"C:\python27\python.exe" yourprogram.py %*
```
where `%*` stands for the all arguments you pass to the script.
Now drag & drop your target files on the `file.bat` icon. | Drag and drop onto Python script in Windows Explorer | [
"",
"python",
"windows",
"drag-and-drop",
"windows-explorer",
""
] |
I'm working on an application that consists of an overall Quartz-based scheduler and "CycledJob" run using CronTriggers. The purpose of the application is to process inputs from different email inboxes based on the source country.
Based on the country that it comes in from (i.e. US, UK, FR, etc.) the application trigg... | At the top of each country's processing thread, put the country code into Log4j's mapped diagnostic context (MDC). This uses a ThreadLocal variable so that you don't have to pass the country up and down the call stack explicitly. Then create a custom filter that looks at the MDC, and filters out any events that don't c... | I wish I could be a bit more helpful than this, but you may want to investigate using some filters? Perhaps your logging could output the country code and you could match your filter based on that?
A StringMatchFilter should probably be able to match it for you.
Couldn't get the below address to work properly as a li... | Splitting log4j Output with Quartz Worker Threads | [
"",
"java",
"multithreading",
"log4j",
"quartz-scheduler",
"scheduler",
""
] |
This Linq to SQL query ...
```
Return (From t In Db.Concessions Where t.Country = "ga" Select t.ConcessionID, t.Title, t.Country)
```
... is generating this SQL:
```
SELECT [t0].[ConcessionID], [t0].[Title], [t0].[Country]
FROM [dbo].[Concessions] AS [t0]
WHERE [t0].[Country] = ga
```
... when what I want is
`... | ## Answer
The Country field was a char(2); I changed it to nvarchar(50), and that fixed the problem. Is this a bug in Linq to SQL? | Wild guess.... could it be?
`t.Country = "ga"`
vs.
`t.Country == "ga"` | Why is LINQ to SQL converting my string parameter to a column name? | [
"",
"asp.net",
"sql",
"vb.net",
"linq-to-sql",
""
] |
Every time I start in deep in a C# project, I end up with lots of events that really just need to pass a single item. I stick with the `EventHandler`/`EventArgs` practice, but what I like to do is have something like:
```
public delegate void EventHandler<T>(object src, EventArgs<T> args);
public class EventArgs<T>: ... | Delegate of the following form has been added since .NET Framework 2.0
```
public delegate void EventHandler<TArgs>(object sender, TArgs args) where TArgs : EventArgs
```
You approach goes a bit further, since you provide out-of-the-box implementation for EventArgs with single data item, but it lacks several properti... | To make generic event declaration easier, I created a couple of code snippets for it. To use them:
* Copy the whole snippet.
* Paste it in a text file (e.g. in Notepad).
* Save the file with a .snippet extension.
* Put the .snippet file in your appropriate snippet directory, such as:
**Visual Studio 2008\Code Snippet... | .NET EventHandlers - Generic or no? | [
"",
"c#",
".net",
"generics",
"events",
""
] |
*Comment on Duplicate Reference: Why would this be marked duplicate when it was asked years prior to the question referenced as a duplicate? I also believe the question, detail, and response is much better than the referenced question.*
I've been a C++ programmer for quite a while but I'm new to Java and new to Eclips... | 1. Create a new Java project in Eclipse. This will create a src folder (to contain your source files).
2. Also create a lib folder (the name isn't that important, but it follows standard conventions).
3. Copy the `./com/*` folders into the `/src` folder (you can just do this using the OS, no need to do any fancy import... | I think you'll have to import the project via the file->import wizard:
<http://www.coderanch.com/t/419556/vc/Open-existing-project-Eclipse>
It's not the last step, but it will start you on your way.
I also feel your pain - there is really no excuse for making it so difficult to do a simple thing like opening an exis... | How do I import a pre-existing Java project into Eclipse and get up and running? | [
"",
"java",
"eclipse",
""
] |
How would you go about dead code detection in C/C++ code? I have a pretty large code base to work with and at least 10-15% is dead code. Is there any Unix based tool to identify this areas? Some pieces of code still use a lot of preprocessor, can automated process handle that? | You could use a code coverage analysis tool for this and look for unused spots in your code.
A popular tool for the gcc toolchain is gcov, together with the graphical frontend lcov (<http://ltp.sourceforge.net/coverage/lcov.php>).
If you use gcc, you can compile with gcov support, which is enabled by the '--coverage'... | Compile it under gcc with -Wunreachable-code.
I think that the more recent the version, the better results you'll get, but I may be wrong in my impression that it's something they've been actively working on. Note that this does flow analysis, but I don't believe it tells you about "code" which is already dead by the ... | Dead code detection in legacy C/C++ project | [
"",
"c++",
"automation",
"static-analysis",
"legacy-code",
"dead-code",
""
] |
The code below gives me this mysterious error, and i cannot fathom it. I am new to regular expressions and so am consequently stumped. The regular expression should be validating any international phone number.
Any help would be much appreciated.
```
function validate_phone($phone)
{
$phoneregexp ="^(\+[1-9][0-9]... | If this is PHP, then the regex must be enclosed in quotes. ~~Furthermore, what's `preg`? Did you mean `preg_match`?~~
Another thing. PHP knows boolean values. The canonical solution would rather look like this:
```
return preg_match($regex, $phone) !== 0;
```
EDIT: Or, using `ereg`:
```
return ereg($regex, $phone) ... | Hmm well the code you pasted isn't quite valid, I fixed it up by adding the missing quotes, missing delimiters, and changed preg to preg\_match. I didn't get the warning.
**Edit**: after seeing the other comment, you meant "ereg" not "preg"... that gives the warning. Try using `preg_match()` instead ;)
```
<?php
func... | Regex error: 'Warning: ereg() [function.ereg]: REG_ERANGE' in PHP | [
"",
"php",
"regex",
""
] |
Is there a best-practice or common way in JavaScript to have class members as event handlers?
Consider the following simple example:
```
<head>
<script language="javascript" type="text/javascript">
ClickCounter = function(buttonId) {
this._clickCount = 0;
document.getElementById(b... | ```
ClickCounter = function(buttonId) {
this._clickCount = 0;
var that = this;
document.getElementById(buttonId).onclick = function(){ that.buttonClicked() };
}
ClickCounter.prototype = {
buttonClicked: function() {
this._clickCount++;
alert('the button was clicked ' + this._clickCount ... | I don't know why [`Function.prototype.bind`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/bind) wasn't mentioned here yet. So I'll just leave this here ;)
```
ClickCounter = function(buttonId) {
this._clickCount = 0;
document.getElementById(buttonId).onclick = this.... | Class methods as event handlers in JavaScript? | [
"",
"javascript",
"html",
"function",
"class",
""
] |
I have been attempting to write some routines to read RSS and ATOM feeds using the new routines available in System.ServiceModel.Syndication, but unfortunately the Rss20FeedFormatter bombs out on about half the feeds I try with the following exception:
> ```
> An error was encountered when parsing a DateTime value in ... | RSS 2.0 formatted syndication feeds utilize the [RFC 822 date-time specification](http://www.w3.org/Protocols/rfc822/#z28) when serializing elements like *pubDate* and *lastBuildDate*. The RFC 822 date-time specification is unfortunately a very 'flexible' syntax for expressing the time-zone component of a DateTime.
*T... | Based on the workaround posted in the [bug report to Microsoft about this](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=325421&wa=wsignin1.0) I made an XmlReader specifically for reading SyndicationFeeds that have non-standard dates.
The code below is slightly different than the cod... | Problems Reading RSS with C# and .net 3.5 | [
"",
"c#",
"rss",
"syndication",
""
] |
What's the best way to get an array of all elements in an html document with a specific CSS class using javascript?
No javascript frameworks like jQuery allowed here right now, and I could loop all the elements and check them manually myself. I'm hoping for something a little more elegant. | The below answer is now pushing four years old, so it's worth noting that native browser support for [`getElementsByClassName()`](https://developer.mozilla.org/en-US/docs/Web/API/document.getElementsByClassName) has gotten a *lot* better. But if you must support older browsers, then...
Use one that's already been writ... | 1) Get all elements in the document (document.getElementsByTagName('\*'))
2) Do a regular expression match on the element's className attribute for each element | Get All Elements in an HTML document with a specific CSS Class | [
"",
"javascript",
"html",
"css",
""
] |
I'm using a Form to show notifications (it appears at the bottom right of the screen), but when I show this form it steals the focus from the main Form. Is there a way to show this "notification" form without stealing focus? | Hmmm, isn't simply overriding Form.ShowWithoutActivation enough?
```
protected override bool ShowWithoutActivation
{
get { return true; }
}
```
And if you don't want the user to click this notification window either, you can override CreateParams:
```
protected override CreateParams CreateParams
{
get
{
Cr... | Stolen from [PInvoke.net](http://www.pinvoke.net/)'s [ShowWindow](http://www.pinvoke.net/default.aspx/user32/ShowWindow.html) method:
```
private const int SW_SHOWNOACTIVATE = 4;
private const int HWND_TOPMOST = -1;
private const uint SWP_NOACTIVATE = 0x0010;
[DllImport("user32.dll", EntryPoint = "SetWindowPos")]
sta... | Show a Form without stealing focus? | [
"",
"c#",
".net",
"winforms",
""
] |
I have a Java client that calls a web service at the moment using the Http protocol.
When i try to use the Https protocol i keep getting this error
java.io.IOException: DerInputStream.getLength(): lengthTag=127, too big.
Any ideas what could be up?
Thanks
Damien | Due to american export regulations in encryption technologies, you can't use strong encryption out of the box. Your error looks like you (or your framework) is trying to use strong encryption, and other parts of the framework is not allowing it.
A discussion of a case that looks similar to yours can be found [here](ht... | Are you sure you are connecting your HTTPS client to the server port that talks over HTTPS (TLS/SSL) rather than HTTP? | Webservices client and ssl | [
"",
"java",
"web-services",
"ssl",
"client",
""
] |
I have a VB 6 application and we are starting to port it over to C#. We have finished one of the screens and wanted to see if there was an incremental way of hosting the winform within VB to start to have the existing users get used to new screens. This is a migration strategy..
Any thoughts. | Have you [looked at this?](http://hubpages.com/hub/Interop_Forms_Toolkit_10) Direct Link to [Product here](http://msdn.microsoft.com/en-us/vbasic/bb419144.aspx) | The Interop Forms Toolkit allows you to create .NET Forms and User Controls that can be used in VB 6.0 applications. This allows you to migrate VB 6.0 applications to .NET over time (a form or part of a form at a time). However, the toolkit relies on features from the Microsoft.VisualBasic assembly and the VB.NET compi... | Host C# winforms in VB6 applications | [
"",
"c#",
"winforms",
"vb6",
""
] |
How can I find out the folder where the windows service .exe file is installed dynamically?
```
Path.GetFullPath(relativePath);
```
returns a path based on `C:\WINDOWS\system32` directory.
However, the `XmlDocument.Load(string filename)` method appears to be working against relative path inside the directory where t... | Try
```
System.Reflection.Assembly.GetEntryAssembly().Location
``` | Try this:
```
AppDomain.CurrentDomain.BaseDirectory
```
(Just like here: [How to find windows service exe path](https://stackoverflow.com/questions/2833959/how-to-find-windows-service-exe-path)) | Getting full path for Windows Service | [
"",
"c#",
".net",
"windows-services",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.