Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I've got a potentially rather large list of objects I'd like to bind to a ListBox in WPF. However, I'd like to have the List load itself incrementally. How can I bind a ListBox to an IEnumerable that loads itself on-demand in such a way that the listbox only tries to enumerate as much as it needs for the display? | WPF ListBox's use a [VirtualizingStackPanel](http://msdn.microsoft.com/en-us/library/system.windows.controls.virtualizingstackpanel.aspx) as the layout control for its items. You can set the VirtualizingStackPanel to only load items as needed with the following XAML:
```
<ListBox
VirtualizingStackPanel.IsVirtuali... | You could store the list in a database - maybe an in-memory one - and then retrieve the needed chunk in your IEnumerable using LINQ. | On-demand IEnumerable binding to ListBox | [
"",
"c#",
"wpf",
"data-binding",
""
] |
My schema specifies a namespace, but the documents don't. What's the simplest way to ignore namespace during JAXB unmarshalling (XML -> object)?
In other words, I have
```
<foo><bar></bar></foo>
```
instead of,
```
<foo xmlns="http://tempuri.org/"><bar></bar></foo>
``` | I believe you must [add the namespace](https://download.oracle.com/javaee-archive/jaxb.java.net/users/2008/05/7860.html) to your xml document, with, for example, the use of a [SAX filter](https://web.archive.org/web/20090113211510/http://www.digitalkarate.net/?p=63).
That means:
* Define a ContentHandler interface wi... | Here is an extension/edit of VonCs solution just in case someone doesn´t want to go through the hassle of implementing their own filter to do this. It also shows how to output a JAXB element without the namespace present. This is all accomplished using a SAX Filter.
Filter implementation:
```
import org.xml.sax.Attri... | JAXB: How to ignore namespace during unmarshalling XML document? | [
"",
"java",
"xml",
"xml-serialization",
"jaxb",
""
] |
I am fetching an array of floats from my database but the array I get has converted the values to strings.
How can I convert them into floats again without looping through the array?
Alternatively, how can I fetch the values from the database without converting them to strings?
---
### EDIT:
* I am using the Zend... | You could use
```
$floats = array_map('floatval', $nonFloats);
```
There is the option `PDO::ATTR_STRINGIFY_FETCHES` but from what I remember, MySQL always has it as `true`
Edit: see [Bug 44341](http://bugs.php.net/bug.php?id=44341) which confirms MySQL doesn't support turning off stringify.
Edit: you can also map ... | How are you getting your data? mysql, mysqli or PDO, some other way or even some other database?
you could use `array_map` with `floatval` like so:
`$data = array_map('floatval', $data);`
but that still executes a loop and i think it assumes you only have one column in your data.
you're probably best of casting to fl... | How can I convert all values of an array to floats in PHP? | [
"",
"php",
""
] |
There is `ConnectionManager` which waits for incoming connections. For each incoming connection it creates a `Connection` instance which handles the inbound and outbound traffic on this connection. Each `Connection` has a `Watchdog` which handles "bad connection" conditions and calls registered "Listerners". One "Liste... | If the watchdog is running in a different thread, then the problem isn't too bad - the watchdog signals the ConnectionManager to delete with a asynchronous message, then exits it's own thread.
Mean-while, the ConnectionManager thread gets the delete message, and starts deleting the watchdog.
To avoid race-conditions ... | Messaging.
Instead of having the Watchdog call a method of the `ConnectionManager`, post a message to a queue in the connection manager. This queue needs to be thread safe. When the `ConnectionManager` processes the queue in its thread, it will be safe to wait for the Connection thread to end.
```
Watchdog Q... | Threading issue (chase your own tail) | [
"",
"c++",
"multithreading",
""
] |
Fun with enums in C#. Take one generic list that is created to store some Enum that you had defined previously and add few items in it. Iterate with foreach or `GetEnumerator<T>()` but specify some other enum then the original and see what happens. I was expecting InvalidCastException or something like that but it perf... | Enum types are distinct, but you're being confused by an implicit cast which is in foreach.
Let's rewrite your loop a bit:
```
public static void Main()
{
List<Cars> cars = new List<Cars>();
List<Animals> animals = new List<Animals>();
cars.Add(Cars.Chevrolet);
cars.Add(Cars.Honda);
cars.Add(Cars.... | Conceptually, an Enum is a statically-typed value with a string representation and a number. When you call `ToString()` on an enum, it will return the string representation. When you call `GetType()` on an enum, you'll get the static enumeration type. If you cast an enum to `int`, you'll get the integer value for the e... | Are enums only named integers, types or neither of both? | [
"",
"c#",
"enums",
""
] |
I am working on [Conway's Game of Life](http://en.wikipedia.org/wiki/Conway%27s_Game_of_Life) currently and have gotten stuck. My code doesn't work.
When I run my code in GUI, it says:
```
[[0 0 0 0]
[0 1 1 0]
[0 1 0 0]
[0 0 0 0]]
Traceback (most recent call last):
File "C:\Users\Documents\Physics\Python\MainPr... | Well, I guess that you are also quite new to programming *per se*, otherwise you should not have any problems in interpreting that simple error message.
I'll help you dissect it:
* First, all "current" line numbers of your project's files are displayed, in calling order.
* Then, it shows you the function in which the... | You're trying to increment a variable that doesn't exist yet. Python can't increment something if it doesn't know what is. Try adding the following line at the top of your def number\_neighbours function.
```
neighbours = 0
``` | Problem with Python implementation of Conway's Game of Life | [
"",
"python",
""
] |
I have a database with two main tables `notes` and `labels`. They have a many-to-many relationship (similar to how stackoverflow.com has questions with labels). What I am wondering is how can I search for a note using multiple labels using SQL?
For example if I have a note "test" with three labels "one", "two", and "t... | To obtain the details of notes that have **both** labels 'One' and 'Two':
```
select * from notes
where note_id in
( select note_id from labels where label = 'One'
intersect
select note_id from labels where label = 'Two'
)
``` | ```
select * from notes a
inner join notes_labels mm on (mm.note = a.id and mm.labeltext in ('one', 'two') )
```
Of course, replace with your actual column names, hopefully my assumptions about your table were correct.
And actually there's a bit of possible ambiguity in your question thanks to English and how the wor... | SQL how to search a many to many relationship | [
"",
"sql",
"search",
"many-to-many",
"relational-division",
""
] |
If I have an inner class, like this:
```
public class Test
{
public class Inner
{
// code ...
}
public static void main(String[] args)
{
// code ...
}
}
```
When I compile it, I expect it should generate two files:
```
Test.class
Test$Inner.class
```
So why do I sometimes se... | The SomeClass$1.class represent anonymous inner class
hava a look at the anonymous inner class section [here](http://java.sun.com/docs/books/tutorial/java/javaOO/innerclasses.html) | You'll also get something like `SomeClass$1.class` if your class contains a private inner class (not anonymous) but you instantiate it at some point in the parent class.
For example:
```
public class Person {
private class Brain{
void ponderLife() {
System.out.println("The meaning of life is.... | Why does Java code with an inner class generates a third SomeClass$1.class file? | [
"",
"java",
"compiler-construction",
""
] |
I have a vector-like class that contains an array of objects of type `"T"`, and I want to implement 4 arithmetic operators, which will apply the operation on each item:
```
// Constructors and other functions are omitted for brevity.
template<class T, unsigned int D>
class Vector {
public:
// Add a value to each ... | First, you should really return a reference from your operator+=, since you can later use them to implement operator+, operator- and so on. I will change that accordingly.
Also, your do\_for\_each has to be a template, since it has to know the precise type of the function object, as binary function objects are not pol... | You should really have a look at [Boost Operators](http://www.boost.org/doc/libs/1_37_0/libs/utility/operators.htm), a header-only library that really simplifies creating orthogonal and consistent arithmetic operator overloads.
Specifically: you might find that deriving from `boost::operators::integer_arithmatic<T>` s... | C++: Using operator of two intrinsic types as a function object | [
"",
"c++",
"templates",
"functional-programming",
""
] |
I developed a greasemonkey script that refreshes a page and checks for certain updates. I would like to run this script in a tab and browse the internet in another tab, but then have the script automatically activate it's tab when an update is found.
Im not sure how clear that was, maybe this is better:
Tab 1 is runn... | I'm pretty sure that firefox gives focus to tabs that call `alert()`. So just pop up an
`alert('found foo')` | You can achieve this with [Scriptish](https://addons.mozilla.org/en-US/firefox/addon/scriptish/)'s [`GM_openInTab`](https://github.com/erikvold/scriptish/wiki/GM_openInTab) implementation, like so:
```
GM_openInTab(window.location.href, true);
```
That should cause the page that a GM script is on to be focused. | Activate Firefox tab in Greasemonkey/Javascript? Is this possible? | [
"",
"javascript",
"firefox",
"tabs",
"greasemonkey",
""
] |
Assume I allow the user to input a arbitrary numerical expression that allows usage of the explicit set of functions and predefined variables.
Interpreting this is pretty straight forward but what if performance is a critical factor?
I need a way to compile (in runtime) a string with a expression into something that ... | So really you want to parse the string into (eventually) a typed delegate.
One option, then it to parse the string into an `Expression`, which you can then compile to a lambda. This is quite complex, but I have some code that will do much of this - but there may be existing parsers that already do the job in full.
As... | Linq Samples by Microsoft already contain implementation of extensible Linq parser.
```
sealed class Order
{
public double SubTotal { get; set; }
public double Shipping { get; set; }
}
static void Main()
{
var calculateTotal = DynamicExpression
.ParseLambda<Order, double>("SubTotal*@0+Shipping", 0.12)
.C... | C# compile numerical expression | [
"",
"c#",
"compilation",
""
] |
What exactly do `*args` and `**kwargs` mean?
According to the Python documentation, from what it seems, it passes in a tuple of arguments.
```
def foo(hello, *args):
print(hello)
for each in args:
print(each)
if __name__ == '__main__':
foo("LOVE", ["lol", "lololol"])
```
This prints out:
```
L... | Putting `*args` and/or `**kwargs` as the last items in your function definition’s argument list allows that function to accept an arbitrary number of arguments and/or keyword arguments.
For example, if you wanted to write a function that returned the sum of all its arguments, no matter how many you supply, you could w... | Also, we use them for managing inheritance.
```
class Super( object ):
def __init__( self, this, that ):
self.this = this
self.that = that
class Sub( Super ):
def __init__( self, myStuff, *args, **kw ):
super( Sub, self ).__init__( *args, **kw )
self.myStuff= myStuff
x= Super( 2.7, ... | What do *args and **kwargs mean? | [
"",
"python",
""
] |
Let's say I have some pointers called:
```
char * pChar;
int * pInt;
```
I know they both simply hold memory addresses that point to some other location, and that the types declare how big the memory location is pointed to by the particular pointer. So for example, a char might be the size of a byte on a system, whil... | "++" is just another name for X = X + 1;
For pointers it doesn't matter if you increment by 1 or by N.
Anyway, sizeof(type)\*N is used. In the case of 1 it will be just sizeof(type).
So, when you increment by 2 (your second case):
for char is 2\*sizeof(char)=2\*1=2 bytes,
for int will be 2\*sizeof(int)=2\*4=8 byt... | Ahh, now I understand. You should have asked - **"What is the point of pointers having types?"**
There are two points, actually:
* Pointer arithmetics;
* Dereferencing (getting the value back that is stored in the address that the pointer is pointing to).
Both would be impossible without knowing the type of the poin... | What is the point of pointer types in C++? | [
"",
"c++",
"pointers",
"memcpy",
""
] |
Some websites have code to "break out" of `IFRAME` enclosures, meaning that if a page `A` is loaded as an `IFRAME` inside an parent page `P` some Javascript in `A` redirects the outer window to `A`.
Typically this Javascript looks something like this:
```
<script type="text/javascript">
if (top.location.href != sel... | Try using the onbeforeunload property, which will let the user choose whether he wants to navigate away from the page.
Example: <https://developer.mozilla.org/en-US/docs/Web/API/Window.onbeforeunload>
In HTML5 you can use sandbox property. Please see Pankrat's answer below.
<http://www.html5rocks.com/en/tutorials/sec... | With HTML5 the [iframe sandbox](http://www.w3schools.com/tags/att_iframe_sandbox.asp) attribute was added. At the time of writing this [works on Chrome, Safari, Firefox and recent versions of IE and Opera](http://caniuse.com/iframe-sandbox) but does pretty much what you want:
```
<iframe src="url" sandbox="allow-forms... | How to prevent IFRAME from redirecting top-level window | [
"",
"javascript",
"html",
"iframe",
""
] |
Is there a C# port of the [optparse (command line option parser)](http://www.python.org/doc/2.5.2/lib/module-optparse.html) module from Python available under some [OSI-approved license](http://www.opensource.org/licenses/alphabetical)? | Have you already looked at <http://csharpoptparse.sourceforge.net/> ? I did not read the licensing, but since it it's on sourceforge, I would guess it is OSI approved. | CSharpOptParse homepage says it is a port of Perl's GetOpt, not of Python's optparse. Anyway, I looks terribly, unline the original optparse :/ | C# version of optparse? | [
"",
"c#",
"command-line",
""
] |
I found the [Computational Geometry Algorithms Library](http://www.cgal.org/) in my search for an algorithm to decompose a concave polygon into the minimum number of convex components. Links off the site and numerous google results indicate there are python bindings for it, which would be really handy, but all the link... | A rewrite of the CGAL-Python bindings has been done as part of the cgal-bindings project. Check it out : <http://code.google.com/p/cgal-bindings/> | You may also be interested in the GEOS library, which is available in Python through [Shapely](https://github.com/Toblerity/Shapely) and [the GEOS API included in GeoDjango](http://geodjango.org/docs/geos.html). | What happened to the python bindings for CGAL? | [
"",
"python",
"geometry",
"polygon",
"computational-geometry",
"cgal",
""
] |
In Java (And in general) is there a way to make a class so public that it's methods etc... are accessible from little classes all around that don't even instantiate it? Ha, what I mean is... If I have a daddy class that has a method `draw()` and it instantiates a baby class called Hand and one called Deck, and then dec... | When the Daddy class instantiates the Baby classes, it (Daddy) could pass a reference to itself to the Baby constructor, giving Baby access to all of its public methods.
```
class Daddy {
public foo(){...}
public createBaby(){
Baby baby = new Baby(this);
// baby now has a reference to Daddy
... | You can:
* Pass the object reference through the constructor. Or by getters and setters. Or directly to the function.
* Use inheritance.
* Use static classes. | method visibility between classes in java | [
"",
"java",
"visibility",
""
] |
I'm trying to find an zip compression and encryption component with [encryption suitable for use by the US Federal Government](http://www.networkworld.com/careers/2004/0315manonline.html), so I can't use Zip 2.0 encryption, it has to be AES or the like. I've already found [SharpZipLib](http://www.icsharpcode.net/OpenSo... | How much would you be willing to pay for AES in DotNetZip?
;)
DotNetZip supports AES Encryption, with 128 or 256-bit keys.
<http://www.codeplex.com/DotNetZip>
Example code:
```
using (ZipFile zip = new ZipFile())
{
zip.AddFile("ReadMe.txt"); // no password for this entry
// use a password for subsequen... | If money is a big issue, you could take an open source library like this <http://www.codeplex.com/DotNetZip>, which now has AES support | Suggestions for a cheap/free .NET library for doing Zip with AES encryption? | [
"",
"c#",
".net",
"vb.net",
"encryption",
"zip",
""
] |
I'm using a streamwriter to log errors
the way it has been designed (please dont ask why) is to open a new streamwriter everytime the application has to log a message. It outputs everything to ./Logs/[current-date].txt which usually resolves to "c:\myappfolder\logs[current-date].txt"
Everything works correctly, but a... | The current directory is a process wide value.
The `OpenFileDialog` is changing the current directory.
If you're using the .NET `OpenFileDialog` class, you can set the `RestoreDirectory` property to `true` to tell the dialog to leave the current directory alone (although the way the docs for `RestoreDirectory` is wri... | As Mike B said, `OpenFileDialog` may change current directory. Since `./` is relative to current, that changes too.
The `RestoreDirectory` property modifies this behavior.
Do something like this rather:
```
OpenFileDialog openFileDialog1 = new OpenFileDialog();
OpenFileDialog1.InitialDirectory = "c:\\" ;
openFileDi... | ./ changes target when i use OpenFileDialog | [
"",
".net",
"c++",
"relative-path",
"openfiledialog",
""
] |
I am not understanding the point of using .def files with DLLs.
It seems that it replaces the need to use explicit exports within your DLL code (ie. explicit \_\_declspec(dllexport)) however I am unable to generate a lib file when not using these which then creates linker issues later when using the DLL.
So how do yo... | My understanding is that .def files provide an alternative to the \_\_declspec(dllexport) syntax, with the additional benefit of being able to explicitly specify the ordinals of the exported functions. This can be useful if you export some functions only by ordinal, which doesn't reveal as much information about the fu... | I find the use of both \_\_declspec(dllexport) and the .def file together to be useful in creating portable DLLs, i.e. DLLs that can be called from code compiled with a different compiler or with different compiler settings.
Just putting \_\_declspec(dllexport) on your function declarations will cause those functions ... | .def files C/C++ DLLs | [
"",
"c++",
"c",
"dll",
""
] |
I'm working on a site now that have to fetch users feeds. But how can I best optimize fetching if I have a database with, lets say, 300 feeds. I'm going to set up a cron-job to which fetches the feeds, but should I do it like 5 every second minute or something?
Any ideas on how to do this the best way in PHP? | Based on the new information I think I would do something like this:
Let the "first" client initiate the updatework and store timestamp with it.
Everey other clients that will ask for the information get a cashed information until that information are to old. Next hit from a client will then refresh the cashe that the... | If I understand you question, you are basically working on a feed agregator site?
You can do the following; start by refreshing every 1 hor (for example). When you have anough entries from some feed - calculate the average interval between entries. Then use that interval as an interval for fetching that feed.
For exa... | Optimize feed fetching | [
"",
"php",
"mysql",
"cron",
"feed",
"fetch",
""
] |
Assume you have some objects which have several fields they can be compared by:
```
public class Person {
private String firstName;
private String lastName;
private String age;
/* Constructors */
/* Methods */
}
```
So in this example, when you ask if:
```
a.compareTo(b) > 0
```
you might be... | You can implement a `Comparator` which compares two `Person` objects, and you can examine as many of the fields as you like. You can put in a variable in your comparator that tells it which field to compare to, although it would probably be simpler to just write multiple comparators. | With Java 8:
```
Comparator.comparing((Person p)->p.firstName)
.thenComparing(p->p.lastName)
.thenComparingInt(p->p.age);
```
If you have accessor methods:
```
Comparator.comparing(Person::getFirstName)
.thenComparing(Person::getLastName)
.thenComparingInt(Person::getAge);
```... | How to compare objects by multiple fields | [
"",
"java",
"oop",
""
] |
Is there any way to find all references to an object while debugging? | If you're willing to dig into WinDbg it is fairly easy to find references to a specific object. However, WinDbg is not the easiest tool to use.
This [blog](http://blogs.msdn.com/tess/) has lots of info on using WinDbg. | Not without using the profiling/debugger API, as far as I'm aware. (Even with the API, I don't know how to do it.) | Finding references to an object | [
"",
"c#",
"debugging",
""
] |
Here's an example:
```
Double d = (1/3);
System.out.println(d);
```
This returns 0, not 0.33333... as it should.
Does anyone know? | That's because `1` and `3` are treated as `integers` when you don't specify otherwise, so `1/3` evaluates to the `integer` `0` which is then cast to the `double` `0`. To fix it, try `(1.0/3)`, or maybe `1D/3` to explicitly state that you're dealing with double values. | If you have `int`s that you want to divide using floating-point division, you'll have to cast the `int` to a `double`:
```
double d = (double)intValue1 / (double)intValue2
```
(Actually, only casting `intValue2` should be enough to have the `intValue1` be casted to `double` automatically, I believe.) | Double value returns 0 | [
"",
"java",
"division",
""
] |
On a page I want to dynamically list years and all the months in each year so an archive for each month can be viewed. I want to show the current year first but the current year may not be over yet so I only want to show the months that have passed, and the current month. Then I want all years and all months in the pas... | ```
$current_year = date('Y');
$months = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12);
$month_names = array('January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December');
// Loop through all the months and create an array up to and including the current month... | try this it will out put a descending list of months/years for the past 5 years
```
$years = 5;
for ($i = 0; $i < (12* $years); $i++)
{
if (date('Y',strtotime("-".$i." month")) > (date('Y') - $years) )
{
echo date('F Y',strtotime("-".$i." month")) . '<br />';
}
}
```
Then if you need it in an arra... | Is there a more efficient way of creating a list of years/months? | [
"",
"php",
"language-agnostic",
"datetime",
"performance",
""
] |
```
#include<iostream>
using namespace std;
class A
{
int a;
int b;
public:
void eat()
{
cout<<"A::eat()"<<endl;
}
};
class B: public A
{
public:
void eat()
{
cout<<"B::eat()"<<endl;
}
};
class C: public A
{
public:
void eat()
{
cout<<"C::eat()"<<endl;
... | ## Inheriting twice
With double inheritance you have an ambiguity - the compiler cannot know which of the two A bases do you want to use. If you want to have two A bases (sometimes you may want to do this), you may select between them by casting to B or C. The most appropriate from default casts here is the `static_ca... | Use a cast - `static_cast` is required here to cast up the heirarchy.
```
main()
{
D obj;
foo(static_cast<B*>(&obj));
}
``` | Multiple Inheritance | [
"",
"c++",
"inheritance",
"multiple-inheritance",
""
] |
I'm using SQL Server 2008 Management studio viewing a 2005 server and have just added 2 users. For some reason they both have slightly different icons and I'm not sure why.
Anyone have a definitive list of the icons and their meaning or a link to microsoft's doc on it as I can't find anything anywhere.
Thanks. | One icon for user account, another icon is for group account. | If the user icon has a red down arrow, it means the associated login is disabled. | what do the sql server icons mean? | [
"",
"sql",
"sql-server-2005",
"sql-server-2008",
"icons",
""
] |
I am looking for a way to localize properties names displayed in a PropertyGrid. The property's name may be "overriden" using the DisplayNameAttribute attribute. Unfortunately attributes can not have non constant expressions. So I can not use strongly typed resources such as:
```
class Foo
{
[DisplayAttribute(Resou... | Here is the solution I ended up with in a separate assembly (called "Common" in my case):
```
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Event)]
public class DisplayNameLocalizedAttribute : DisplayNameAttribute
{
public DisplayNameLoca... | There is the [Display attribute](http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.displayattribute.aspx) from System.ComponentModel.DataAnnotations in .NET 4. It works on the MVC 3 `PropertyGrid`.
```
[Display(ResourceType = typeof(MyResources), Name = "UserName")]
public string UserName {... | Localization of DisplayNameAttribute | [
"",
"c#",
"visual-studio-2008",
"localization",
"attributes",
""
] |
I am doing something like this:
```
#include <signal.h>
class myClass {
public:
void myFunction ()
{
signal(SIGIO,myHandler);
}
void myHandler (int signum)
{
/**
* Handling code
*/
}
}
```
I am working on Ubuntu, using gcc.
But it won't compile. It is comp... | The second parameter of signal should be a pointer to a function accepting an int and returning void. What you're passing to signal is a pointer to a *member* function accepting an int and returning void (its type being `void (myClass::*)(int)`). I can see three possibilities to overcome this issue:
1 - Your method `m... | To pass a pointer to a method, it must be a static method and you must specify the class name.
Try this:
```
class myClass {
void myFunction ()
{
signal(SIGIO, myClass::myHandler);
}
static void myHandler (int signum)
{
// blabla
}
};
```
And you should also read the link supplied by Baget, th... | Is it possible to use signal inside a C++ class? | [
"",
"c++",
"signal-handling",
""
] |
How can I select the good method (I have in the example below show 2 differents way that doesn't work). I was using instead of a variable of type Object with a IF and IS to do the job but I am trying to avoid using Object and boxing/unboxing. So I thought that Generic could do the job but I am stuck here.
Here is a sm... | No, you can't do this. Generics don't work like C++ templates - the generic method is compiled just once. The only information that the compiler can use for overload resolution is the information it knows about within the generic method, regardless of what code uses it.
As an example to show this, here's a bit of code... | Have you considered interfaces?
```
interface IAction
{
void action();
}
class ObjectType1 : IAction
{
void action() {
Console.WriteLine("1");
}
}
class ObjectType2 : IAction
{
void action() {
Console.WriteLine("2");
}
}
class Parser
{
public IAction execute(IAction obj)
{
o... | C# Generic and method | [
"",
"c#",
".net",
"generics",
".net-2.0",
"c#-2.0",
""
] |
does anybody know any resources that I can refer to? | I believe you are referring to the [JQuery FadeOut effect](http://docs.jquery.com/Effects/fadeOut#speedcallback) (since [Stackoverflow uses JQuery](http://ttp://blog.stackoverflow.com/2008/09/what-was-stack-overflow-built-with/)) | Stackoverflow uses the JQuery library, and it uses the [fadeOut effect](http://docs.jquery.com/Effects/fadeOut#speedcallback) for what you are describing.
I have never used JQuery, but I have used the [scriptaculous](http://github.com/madrobby/scriptaculous/wikis) library to do this same thing in the past.
The [Effec... | javascript flashing effect after you answer a question, or when you cannot vote down and close the warning | [
"",
"javascript",
""
] |
I have a 3 table SQLServer Database.
```
Project
ProjectID
ProjectName
Thing
ThingID
ThingName
ProjectThingLink
ProjectID
ThingID
CreatedDate
```
When a Thing is ascribed to a Project an entry is put in the ProjectThingLink table.
Things can move between Projects. The CreatedDate is used to know which Project a Thi... | ```
select p.projectName, t.ThingName
from projects p
join projectThingLink l on l.projectId = p.projectId
join thing t on t.thingId = l.thingId
where l.createdDate =
( select max(l2.createdDate)
from projectThingLink l2
where l2.thingId = l.thingId
);
```
NOTE: Corrected after comment | This will almost always give you better performance than the subquery method. You're basically looking for the row which doesn't have any other rows past it rather than looking for the row with the greatest date:
```
SELECT
P.ProjectID,
P.ProjectName,
T.ThingID,
T.ThingName
FROM
dbo.Projects P... | How do I select only the latest entry in a table? | [
"",
"sql",
"sql-server",
""
] |
I have got a template class as follows:
```
class MyClass<T>
{
T field;
public void myMethod()
{
field = new T(); // gives compiler error
}
}
```
How do I create a new instance of T in my class? | After type erasure, all that is known about `T` is that it is some subclass of `Object`. You need to specify some factory to create instances of `T`.
One approach could use a [`Supplier<T>`](http://docs.oracle.com/javase/8/docs/api/java/util/function/Supplier.html):
```
class MyClass<T> {
private final Supplier<? ... | Another non-reflective approach is to use a hybrid Builder / Abstract Factory pattern.
In Effective Java, Joshua Bloch goes over the Builder pattern in detail, and advocates a generic Builder interface:
```
public interface Builder<T> {
public T build();
}
```
Concrete builders can implement this interface, and ou... | Instantiating object of type parameter | [
"",
"java",
"generics",
"reflection",
""
] |
I need an equivalent to c++'s `std::multimap<K, V, Comp, Alloc>` in C-sharp. Does it exist in the standard library? | Because it's almost christmas :)
```
//////////////////////////////////////////////////////////////////////
// Algorithmia is (c) 2008 Solutions Design. All rights reserved.
// http://www.sd.nl
//////////////////////////////////////////////////////////////////////
// COPYRIGHTS:
// Copyright (c) 2008 Solutions Design.... | [ILookup](http://msdn.microsoft.com/en-us/library/bb534291.aspx) may be good enough for you - but unfortunately there are no public implementations. You've basically got to go through [Enumerable.ToLookup](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.tolookup.aspx), as far as I'm aware. That means it'... | multimap in .NET | [
"",
"c#",
"multimap",
""
] |
That is, all text and subtags, without the tag of an element itself?
Having
```
<p>blah <b>bleh</b> blih</p>
```
I want
```
blah <b>bleh</b> blih
```
element.text returns "blah " and etree.tostring(element) returns:
```
<p>blah <b>bleh</b> blih</p>
``` | This is the solution I ended up using:
```
def element_to_string(element):
s = element.text or ""
for sub_element in element:
s += etree.tostring(sub_element)
s += element.tail
return s
``` | ElementTree works perfectly, you have to assemble the answer yourself. Something like this...
```
"".join( [ "" if t.text is None else t.text ] + [ xml.tostring(e) for e in t.getchildren() ] )
```
Thanks to JV amd PEZ for pointing out the errors.
---
Edit.
```
>>> import xml.etree.ElementTree as xml
>>> s= '<p>bla... | How do I get the full XML or HTML content of an element using ElementTree? | [
"",
"python",
"xml",
"api",
"elementtree",
""
] |
How do I parameterize a query containing an `IN` clause with a variable number of arguments, like this one?
```
SELECT * FROM Tags
WHERE Name IN ('ruby','rails','scruffy','rubyonrails')
ORDER BY Count DESC
```
In this query, the number of arguments could be anywhere from 1 to 5.
I would prefer not to use a dedicate... | Here's a quick-and-dirty technique I have used:
```
SELECT * FROM Tags
WHERE '|ruby|rails|scruffy|rubyonrails|'
LIKE '%|' + Name + '|%'
```
So here's the C# code:
```
string[] tags = new string[] { "ruby", "rails", "scruffy", "rubyonrails" };
const string cmdText = "select * from tags where '|' + @tags + '|' like '%... | You can parameterize *each* value, so something like:
```
string[] tags = new string[] { "ruby", "rails", "scruffy", "rubyonrails" };
string cmdText = "SELECT * FROM Tags WHERE Name IN ({0})";
string[] paramNames = tags.Select(
(s, i) => "@tag" + i.ToString()
).ToArray();
string inClause = string.Join(", ",... | Parameterize an SQL IN clause | [
"",
"sql",
"sql-server-2008",
"parameters",
""
] |
I’ve just found out that the execution plan performance between the following two select statements are massively different:
```
select * from your_large_table
where LEFT(some_string_field, 4) = '2505'
select * from your_large_table
where some_string_field like '2505%'
```
The execution plans are 98% and 2% respecti... | More generally speaking, you should never use a function on the LEFT side of a WHERE clause in a query. If you do, SQL won't use an index--it has to evaluate the function for every row of the table. The goal is to make sure that your where clause is "[Sargable](http://en.wikipedia.org/wiki/Sargable)"
Some other exampl... | It looks like the expression LEFT(some\_string\_field, 4) is evaluated for every row of a full table scan, while the "like" expression will use the index.
Optimizing "like" to use an index if it is a front-anchored pattern is a much easier optimization than analyzing arbitrary expressions involving string functions. | Surprising SQL speed increase | [
"",
"sql",
"performance",
""
] |
I am doing the following statements in Java,
```
Obj t[] = new Obj[10];
Obj a = new Obj("a");
t[0] = a;
a = new Obj("b");
t[1] = a;
```
Why in java, when i access t[0] , it returns me "a", rather than "b"?
Is this because of the GC? and can i believe it is safe to do such an operation | Here's exactly what's happening.
```
Obj t[] = new Obj[10]; // 1
Obj a = new Obj("a"); // 2
t[0] = a;
a = new Obj("b"); // 3
t[1] = a; // 4
```
1. You create an array that can hold 10 references to instances of `Obj`. Call this `obj01`. You assign it to `t`. Note that the variable `t` and the... | The problem is, Java doesn't have pointers.
When you assign one object variable to another, it changes what that variable points to but not any other references you might have.
So:
```
Object a = new Object("a");
Object b = new Object("b");
a = b;
b = new Object("c");
// At this point, a = "b"
// and b = "c"
```
... | What exactly happens while you assign a reference to an element in Array in Java? | [
"",
"java",
"arrays",
""
] |
I need your expertise once again. I have a java class that searches a directory for xml files (displays the files it finds in the eclipse console window), applies the specified xslt to these and sends the output to a directory.
What I want to do now is create an xml containing the file names and file format types. The... | Have a look at DOM and ECS. The following example was adapted to you requirements from [here](https://web.archive.org/web/1/http://articles.techrepublic%2ecom%2ecom/5100-10878_11-1044810.html#):
```
XMLDocument document = new XMLDocument();
for (File f : files) {
document.addElement( new XML("file")
.addXM... | Use an XML library. There are plenty around, and the third party ones are almost all easier to use than the built-in DOM API in Java. Last time I used it, [JDom](http://jdom.org/) was pretty good. (I haven't had to do much XML recently.)
Something like:
```
Element rootElement = new Element("root"); // You didn't sho... | Creating xml from with java | [
"",
"java",
"xml",
""
] |
Is there a way for a Windows application to access another applications data, more specifically a text input field in the GUI, and grab the text there for processing in our own application?
If it is possible, is there a way to "shield" your application to prevent it?
---
**EDIT:** The three first answers seem to be ... | For reading text content from another application's text box you will need to get that text box control's window handle somehow. Depending on how your application UI is designed (if it has a UI that is) there are a couple of different ways that you can use to get this handle. You might use "FindWindow"/"FindWindowEx" t... | OK, I have somewhat figured this out.
The starting point is now knowing the window handle exactly, we only know partial window title, so first thing to do is find that main window:
```
...
EnumWindows((WNDENUMPROC)on_enumwindow_cb, 0);
...
```
which enumerates through all the windows on desktop. It makes a callback ... | Reading from a text field in another application's window | [
"",
"c++",
"user-interface",
"winapi",
"textbox",
"ipc",
""
] |
I would like to search my table having a column of first names and a column of last names. I currently accept a search term from a field and compare it against both columns, one at a time with
```
select * from table where first_name like '%$search_term%' or
last_name like '%$search_term%';
```
This works fi... | What you have should work but can be reduced to:
```
select * from table where concat_ws(' ',first_name,last_name)
like '%$search_term%';
```
Can you provide an example name and search term where this doesn't work? | Note that the search query is now case sensitive.
When using
```
SELECT * FROM table WHERE `first_name` LIKE '%$search_term%'
```
It will match both "Larry" and "larry". With this concat\_ws, it will suddenly become case sensitive!
This can be fixed by using the following query:
```
SELECT * FROM table WHERE UPPER... | Using mysql concat() in WHERE clause? | [
"",
"php",
"mysql",
""
] |
I'm building an XML DOM document in C++. My problem is this: I execute an XPATH query from an Element in my Document, which I know will return another Element. The elementPtr->selectSingleNode call returns an IXMLDOMNode. How can I gain access to the attributes of this node?
Part of me wants to downcast the Node to an... | I don't see anything wrong with what you have written.
The smart com pointers will help you convert if they can, you don't have to write the query interface yourself.
```
MSXML2::IXMLDOMNodePtr pParentNode = pParameterElement->selectSingleNode("parent");
MSXML2::IXMLDOMElementPtr pParentElement( pParentNode );
```
U... | How did you try to do the downcast from IXMLDOMNode to IXMLDOMElement? You can't just use a C++ cast for that, as it's a COM object: you've got to use QueryInterface().
---
Looking at your QueryInterface() code, some thoughts:
* Is pParentNode definitely not null? I don't think that this is the problem, given what y... | How can I access element attributes from an IXMLDOMNode? | [
"",
"c++",
"dom",
"msxml",
"ixmldomelement",
"ixmldomnode",
""
] |
Given either the binary or string representation of an IPv6 address and its prefix length, what's the best way to extract the prefix in Python?
Is there a library that would do this for me, or would I have to:
1. convert the address from string to an int (inet\_ntop)
2. Mask out the prefix
3. Convert prefix back to b... | See <http://code.google.com/p/ipaddr-py/>
With this, you can do
```
py> p=ipaddr.IPv6("2001:888:2000:d::a2")
py> p.SetPrefix(64)
py> p
IPv6('2001:888:2000:d::a2/64')
py> p.network_ext
'2001:888:2000:d::'
```
etc. | Using the python [netaddr](https://github.com/drkjam/netaddr) library:
```
>>> from netaddr.ip import IPNetwork, IPAddress
>>> IPNetwork('2001:888:2000:d::a2/64').network
2001:888:2000:d::
``` | Extract ipv6 prefix in python | [
"",
"python",
"ipv6",
""
] |
I'd like to be able to print the definition code of a lambda function.
Example if I define this function through the lambda syntax:
```
>>>myfunction = lambda x: x==2
>>>print_code(myfunction)
```
I'd like to get this output:
```
x==2
``` | *As long as you save your code to a source file* you can retrieve the source code of
an object using the inspect module.
example:
open editor type:
```
myfunction = lambda x: x==2
```
save as lamtest.py
open shell type python to get to interactive python
type the following:
```
>>>from lamtest import myfunc
>>>imp... | It will only work for mathematical based operations, but you might look at [SymPy](http://code.google.com/p/sympy/)'s `Lambda()` object. It was designed exactly for this purpose:
```
>>> from sympy import *
>>> x = Symbol('x')
>>> l = Lambda(x, x**2)
>>> l
Lambda(_x, _x**2)
>>> l(3)
9
```
It even supports pretty prin... | print the code which defined a lambda function | [
"",
"python",
""
] |
What are the benefits of passing by pointer over passing by reference in C++?
Lately, I have seen a number of examples that chose passing function arguments by pointers instead of passing by reference. Are there benefits to doing this?
Example:
```
func(SPRITE *x);
```
with a call of
```
func(&mySprite);
```
vs.
... | A pointer can receive a NULL parameter, a reference parameter can not. If there's ever a chance that you could want to pass "no object", then use a pointer instead of a reference.
Also, passing by pointer allows you to explicitly see at the call site whether the object is passed by value or by reference:
```
// Is my... | ### Passing by pointer
* Caller has to take the address -> not transparent
* A 0 value can be provided to mean `nothing`. This can be used to provide optional arguments.
### Pass by reference
* Caller just passes the object -> transparent. Has to be used for operator overloading, since overloading for pointer types ... | Are there benefits of passing by pointer over passing by reference in C++? | [
"",
"c++",
"pointers",
"parameter-passing",
"pass-by-reference",
""
] |
It is not possible to fire an event in C# that has no handlers attached to it. So before each call it is necessary to check if the event is null.
```
if ( MyEvent != null ) {
MyEvent( param1, param2 );
}
```
I would like to keep my code as clean as possible and get rid of those null checks. I don't think it will af... | I saw this on another post and have shamelessly stolen it and used it in much of my code ever since:
```
public delegate void MyClickHandler(object sender, string myValue);
public event MyClickHandler Click = delegate {}; // add empty delegate!
//Let you do this:
public void DoSomething() {
Click(this, "foo");
}
... | The notation:
```
if ( MyEvent != null ) {
MyEvent( param1, param2 );
}
```
is not thread safe. You should do it this way:
```
EventHandler handler = this.MyEvent;
if ( null != handler ) { handler( param1, param2 ); }
```
I understand, that this is a bother, so you can do helper method:
```
static void RaiseEven... | Create empty C# event handlers automatically | [
"",
"c#",
"events",
"delegates",
"clr",
""
] |
In Java you can define a new class inline using anonymous inner classes. This is useful when you need to rewrite only a single method of the class.
Suppose that you want create a subclass of `OptionParser` that overrides only a single method (for example `exit()`). In Java you can write something like this:
```
new O... | You can use the [`type(name, bases, dict)`](http://docs.python.org/library/functions.html#type) builtin function to create classes on the fly. For example:
```
op = type("MyOptionParser", (OptionParser,object), {"foo": lambda self: "foo" })
op().foo()
```
Since OptionParser isn't a new-style class, you have to explic... | Java uses anonymous classes mostly to imitate closures or simply code blocks. Since in Python you can easily pass around methods there's no need for a construct as clunky as anonymous inner classes:
```
def printStuff():
print "hello"
def doit(what):
what()
doit(printStuff)
```
Edit: I'm aware that this is no... | Does Python have something like anonymous inner classes of Java? | [
"",
"python",
"class",
"anonymous-class",
""
] |
In the following code doesn't work as
```
public void Foo()
{
CompanyDataContext db = new CompanyDataContext();
Client client = (select c from db.Clients ....).Single();
Bar(client);
}
public void Bar(Client client)
{
CompanyDataContext db = new CompanyDataContext();
db.Client.Attach(client);
client... | The [PLINQO](http://plinqo.com) framework generates detach for all entities making it easy to detach and reattach objects without receiving that error.
```
public void Foo()
{
CompanyDataContext db = new CompanyDataContext();
Client client = (select c from db.Clients ....).Single();
// makes it possible to ca... | They really mean it with 'This is not supported.'. Attaching to an object fetched from another data context is not implemented.
There are a number of workarounds to the problem, the recommended way is by serializing objects, however this is not easy nor a clean approach.
The most simple approach I found is to use a r... | Linq2Sql: Manage DataContext | [
"",
"c#",
"asp.net",
"linq-to-sql",
""
] |
I have nested dictionaries:
```
{'key0': {'attrs': {'entity': 'p', 'hash': '34nj3h43b4n3', 'id': '4130'},
u'key1': {'attrs': {'entity': 'r',
'hash': '34njasd3h43b4n3',
'id': '4130-1'},
u'key2': {'attrs': {'entity': 'c',
... | Your structure is unpleasantly irregular. Here's a version with a **Visitor** function that traverses the `attrs` sub-dictionaries.
```
def walkDict( aDict, visitor, path=() ):
for k in aDict:
if k == 'attrs':
visitor( path, aDict[k] )
elif type(aDict[k]) != dict:
pass
... | If you want to solve the problem in a general way, no matter how many level of nesting you have in your dict, then create a recursive function which will traverse the tree:
```
def traverse_tree(dictionary, id=None):
for key, value in dictionary.items():
if key == 'id':
if value == id:
... | How do I traverse and search a python dictionary? | [
"",
"python",
"parsing",
"dictionary",
"struct",
"nested",
""
] |
I have a [pseudorandom number generator](http://en.wikipedia.org/wiki/Pseudorandom_number_generator) (PRNG) with nice properties which uses six `UInt32`s as state. I need to come up with a reasonable way to seed it. Two obvious possibilities are: 1) generate six random numbers using `System.Random` and use them as seed... | If it needs `UInt32`, then `Random` is more convenient? just `Next()`, `Next()`, `Next()` etc (and cast)... (use the same `Random` instance however - don't create `new Random()` each time).
It depends on what the intent is as to whether this offers enough randomness. Since this is just the seed, it should be OK... | Unfortunately System.Random() also requires a seed value. By default it uses the current Tick count which is predictable and not actually random. So you'll need a seed for Random which leads you back to your original question ...
I haven't ever used Guid.GetHashCode() as a seed before but my 2 second reaction is that ... | Seeding a random number generator in .NET | [
"",
"c#",
"random",
""
] |
What do you guys think about this for a generic singleton?
```
using System;
using System.Reflection;
// Use like this
/*
public class Highlander : Singleton<Highlander>
{
private Highlander()
{
Console.WriteLine("There can be only one...");
}
}
*/
public class Singleton<T> where T : class
{
... | Creating a singleton class is just a few lines of code, and with the difficulty of making a generic singleton i always write those lines of code.
```
public class Singleton
{
private Singleton() {}
static Singleton() {}
private static Singleton _instance = new Singleton();
public static Singleton Insta... | Well, it isn't really singleton - since you can't control `T`, there can be as many `T` instances as you like.
(removed thread-race; noted the double-checked usage) | A generic singleton | [
"",
"c#",
"singleton",
"generics",
""
] |
I have a WebBrowser control which is being instantiated dynamically from a background STA thread because the parent thread is a BackgroundWorker and has lots of other things to do.
The problem is that the Navigated event never fires, unless I pop a MessageBox.Show() in the method that told it to .Navigate(). I shall e... | `WebBrowser` won't do much unless it is shown and has a UI thread associated; are you showing the form on which it resides? You need to, to use the DOM etc. The form could be off-screen if you don't want to display it to the user, but it won't work well in a service (for example).
For scraping purposes, you can normal... | The Navigated and DocumentComplete events will not fire if the visibility of the WebBrowser is set to false. You can work around this limitation by making the WebBrowser visible but setting it's location so that it is outside of the user interface like:
```
wb.Visible = true;
wb.Left = -wb.Width; // notice the minus s... | WebBrowser.Navigated Only Fires when I MessageBox.Show(); | [
"",
"c#",
"multithreading",
"delegates",
"browser",
"apartments",
""
] |
I have an NHibernate Dao..lets call it MyClassDao for want of a better name.
I am writing the following code.
```
MyClassDao myDao = new MyClassDao();
var values = myDao.GetByCriteria(Restrictions.Eq("Status", someStatusValue));
```
I am using this in a Unit Test to pull back values from the database. However, it i... | Use ICriteria.SetMaxResults() | You can use the SetMaxResults method on IQuery (if you use HQL) or ICriteria (if you use criteria API). | How do I limit the result set being pulled back by NHibernate's GetByCriteria? | [
"",
"c#",
"nhibernate",
"criteria",
"resultset",
"restriction",
""
] |
I was browsing through the questions and noticed this:
```
SELECT prodid, issue
FROM Sales
WHERE custid = @custid
AND datesold = SELECT MAX(datesold)
FROM Sales s
WHERE s.prodid = Sales.prodid
AND s.issue = Sales.issue
AND s.custid = @custid
```
I was ... | The @CustID means it's a parameter that you will supply a value for later in your code. This is the best way of protecting against SQL injection. Create your query using parameters, rather than concatenating strings and variables. The database engine puts the parameter value into where the placeholder is, and there is ... | @ is used as a prefix denoting stored procedure and function parameter names, and also variable names | What does the "@" symbol do in SQL? | [
"",
"sql",
""
] |
We use Sharepoint as CMS for our webpages at work. I know how to create controls that can be only visible if you have logged in in SharePoint with:
<Sharepoint:SPSecurityTrimmedControl ID="SPSecurityTrimmedControl1" runat="server" PermissionsString="AddAndCustomizePages"><br />
<Sharepoint:CssLink ID="CssLink1" runa... | How are the users authenticated? With forms authentication or Windows/active directory?
If active directory, then I think in that case you might need to get a reference to the current SPWeb, and then do web.CurrentUser.ID. This might come out null when you are anonymous. If not, try web.SiteUsers.GetByID(web.CurrentUs... | [DoesUserHavePermissions](http://msdn.microsoft.com/en-us/library/ms456041.aspx)
You can use this method on the current web to check if the current user has a specific permission.
I assume your authenticated users have some permission to check for that the anonymous crowd is denied. | How do I know you have logged in a Sharepoint WebPage? | [
"",
"c#",
".net",
"sharepoint",
"sharepoint-2007",
"moss",
""
] |
Upcasting is allowed in Java, however downcasting gives a compile error.
The compile error can be removed by adding a cast but would anyway break at the runtime.
In this case why Java allows downcasting if it cannot be executed at the runtime?
Is there any practical use for this concept?
```
public class demo {
... | Downcasting is allowed when there is a possibility that it succeeds at run time:
```
Object o = getSomeObject(),
String s = (String) o; // this is allowed because o could reference a String
```
In some cases this will not succeed:
```
Object o = new Object();
String s = (String) o; // this will fail at runtime, beca... | Using your example, you could do:
```
public void doit(A a) {
if(a instanceof B) {
// needs to cast to B to access draw2 which isn't present in A
// note that this is probably not a good OO-design, but that would
// be out-of-scope for this discussion :)
((B)a).draw2();
}
a.... | Downcasting in Java | [
"",
"java",
"casting",
""
] |
I want to otherwise block code execution on the main thread while still allowing UI changes to be displayed.
I tried to come up with a simplified example version of what I'm trying to do; and this is the best I could come up with. Obviously it doesn't demonstrate the behavior I'm wanting or I wouldn't be posting the q... | I went with something I haven't seen posted yet which is to use MessageQueues.
* The MainThread blocks while waiting for the next message on a queue.
* The background thread posts different types of messages to the MessageQueue.
* Some of the message types signal the MainThread to update UI elements.
* Of course, ther... | You want to use the "[BackgroundWorker](http://msdn.microsoft.com/en-us/library/system.componentmodel.backgroundworker.aspx)" class, which will take most of this pain out of this for you.. but as mentioned before, you'll also want to structure it so that the main thread is updating the UI and the worker is doing the he... | In C#, wait on the mainthread while continuing to process UI updates? (.NET 2.0 CF) | [
"",
"c#",
"multithreading",
""
] |
Here is what I am trying to do:
Given a date, a day of the week, and an integer `n`, determine whether the date is the `n`th day of the month.
For example:
* input of `1/1/2009,Monday,2`
would be false because `1/1/2009` is not the second Monday
* input of
`11/13/2008,Thursday,2`
would return true because it is... | You could change the check of the week so the function would read:
```
private bool NthDayOfMonth(DateTime date, DayOfWeek dow, int n){
int d = date.Day;
return date.DayOfWeek == dow && (d-1)/7 == (n-1);
}
```
Other than that, it looks pretty good and efficient. | The answer is from [this website](http://blog.lab49.com/archives/206). Copy/pasted here in case that site is ever lost.
```
public static DateTime FindTheNthSpecificWeekday(int year, int month,int nth, System.DayOfWeek day_of_the_week)
{
// validate month value
if(month < 1 || month > 12)
{
throw n... | How do I determine if a given date is the Nth weekday of the month? | [
"",
"c#",
".net",
"date",
"calendar",
""
] |
I am in search for a database with translations so I can have comonly used phrases and words translated by a machine and not by an expensive translator. Is there such a thing as a translation database with words and often used phrases?
If you don't know any would you use such a service?
edit: the database should only... | Check: [open-tran.eu](http://open-tran.eu/). It is a database of translations taken from various open source projects. | > edit: the database should only be monitored by people and not some automatic translater since they tend to be VERY bad
I don't think this is enough. If you're going to translate single words, you need to have some idea of the context in which the word will be used.
For instance, consider the english word "row"
Doe... | Is there something like a translating database for strings? | [
"",
"php",
"localization",
"translation",
""
] |
I'm trying to do the following in my Django template:
```
{% for embed in embeds %}
{% embed2 = embed.replace("<", "<") %}
{{embed2}}<br />
{% endfor %}
```
However, I always get an invalid block or some syntax error when I do anything like that (by that I mean {% %} code inside a loo... | Instead of using a slice assignment to grow a list
`embed_list[len(embed_list):] = [foo]`
you should probably just do
`embed_list.append(foo)`
But really you should try unescaping html with a library function rather than doing it yourself.
That NoneType error sounds like embed.replace is None at some point, which ... | I am quite sure that Django templates does not support that.
For your replace operation I would look into different filters.
You really should try to keep as much logic as you can in your views and not in the templates. | Syntax error whenever I put Python code inside a Django template | [
"",
"python",
"django",
"templates",
"django-templates",
""
] |
Is there an easy way to delete an element from an array using PHP, such that `foreach ($array)` no longer includes that element?
I thought that setting it to `null` would do it, but apparently it does not work. | There are different ways to delete an array element, where some are more useful for some specific tasks than others.
## Deleting a Single Array Element
If you want to delete just one single array element you can use [`unset()`](https://secure.php.net/manual/en/function.unset.php) and alternatively [`array_splice()`](... | It should be noted that [`unset()`](http://php.net/unset) will keep indexes untouched, which is what you'd expect when using string indexes (array as hashtable), but can be quite surprising when dealing with integer indexed arrays:
```
$array = array(0, 1, 2, 3);
unset($array[2]);
var_dump($array);
/* array(3) {
[0]... | Deleting an element from an array in PHP | [
"",
"php",
"arrays",
"unset",
""
] |
I have a string that represents a non indented XML that I would like to pretty-print. For example:
```
<root><node/></root>
```
should become:
```
<root>
<node/>
</root>
```
Syntax highlighting is not a requirement. To tackle the problem I first transform the XML to add carriage returns and white spaces and then ... | From the text of the question **I get the impression that a string result is expected**, as opposed to an HTML-formatted result.
If this is so, **the simplest way to achieve this is to process the XML document with the [identity transformation](http://www.w3.org/TR/xslt#copying) and with an [`<xsl:output indent="yes"/... | This can be done using [native](https://developer.mozilla.org/en-US/docs/Web/API/XSLTProcessor) javascript tools, without 3rd party libs, extending the @Dimitre Novatchev's answer:
```
var prettifyXml = function(sourceXml)
{
var xmlDoc = new DOMParser().parseFromString(sourceXml, 'application/xml');
var xsltDo... | Pretty printing XML with javascript | [
"",
"javascript",
"xml",
"xslt",
"pretty-print",
""
] |
I'm new to jQuery, and I'm totally struggling with using jQuery UI's `sortable`.
I'm trying to put together a page to facilitate grouping and ordering of items.
My page has a list of groups, and each group contains a list of items. I want to allow users to be able to do the following:
> 1. Reorder the groups
> 2. Re... | Can you include the syntax you used for `connectWith`? Did you place the list of other groups inside brackets(even if it's a selector)? That is:
```
...sortable({connectWith:['.group'], ... }
``` | This should work:
```
$('#groupsList').sortable();
$('.itemsList').sortable({
connectWith: $('.itemsList')
});
``` | How do I connect multiple sortable lists to each other in jQuery UI? | [
"",
"javascript",
"jquery",
"ajax",
"jquery-ui",
"jquery-ui-sortable",
""
] |
**I am very, very new to MYSQL.I tried to create a table named "option".**
**My SQL Query is :**
create table option(
id int not null primary key auto\_increment,
choice varchar(30)
)
**While executing this query it shows the following error**
Error Code : 1064
You have an error in your SQL syntax; check the manu... | Pick a different name (one that isn't a reserved word in your RDBMS) and save yourself and whoever else might work on it many headaches. | If you want to have a table name Option, you should be able to, just remember that whenever you use the table in a query, you will have to encase it in ` symbols. Like this.
```
`option`
```
The ` key on the top left of your keyboard, with the tilde. | Can we have the table name as "option" in MySQL? | [
"",
"sql",
"mysql",
"database",
""
] |
I am using LINQ-to-SQL for an application that queries a legacy database. I need to call a stored procedure, that selects a single integer value. Changing the stored procedure is not an option.
The designer creates a method with this signature:
```
private ISingleResult<sp_xal_seqnoResult> NextRowNumber([Parameter(Db... | This would be trivial with a scalar function (UDF) rather than an SP. However, it should work easily enough - although if the SP is complex (i.e. FMT\_ONLY can't inspect it 100%) then you might need to "help" it...
Here's some dbml that I generated from a simplfied SP that returns an integer; you can edit the dbml via... | RETURN @VALUE as the last statement of the proc.
then it will auto detect the type int, string, bool etc and generate the wrapper method accordingly. | LINQ-to-SQL: Stored Procedure that returns a single scalar value? | [
"",
"c#",
"linq-to-sql",
""
] |
I've seen some methods of [checking if a PEFile is a .NET assembly by examining the binary structure](http://www.anastasiosyal.com/archive/2007/04/17/3.aspx).
Is that the fastest method to test multiple files? I assume that trying to load each file (e.g. via [Assembly.ReflectionOnlyLoad](http://msdn.microsoft.com/en-u... | Maybe this helps
from <https://web.archive.org/web/20110930194955/http://www.grimes.demon.co.uk/dotnet/vistaAndDotnet.htm>
> Next, I check to see if it is a .NET assembly. To do this I check to see if the file contains the CLR header. This header contains important information about the location of the .NET code in t... | I guess Stormenet's answer isn't technically *programmatic*, so I'll seperate my response into an answer.
For best performance, nothing is going to beat opening the file(s) with a `StreamReader`, reading the first (n) bytes and checking for the .NET file signature data structures in the byte stream.
Pretty much the s... | Checking if a file is a .NET assembly | [
"",
"c#",
".net",
"reflection",
"clr",
""
] |
Is tight looping in a program bad?
I have an application that has two threads for a game-physics simulator. An updateGame thread and a render thread. The render thread is throttled by causing the thread to sleep for some milliseconds (to achieve the frame-rate I want) and the updateGame thread (that updates my in game... | I read a really great post about efficiently and effectively executing physics calculations loop: [Fix Your Timestep!](http://gafferongames.com/game-physics/fix-your-timestep/)
When a game is running that is usually the main application that the user cares about so tight looping is not that big of a deal. What you rea... | It's only "bad" if it has an adverse impact on something else in your system. Rather than sleeping for 1ms, you might block on a condition that warrants updating, with a minimum of 1ms. That way you'll always sleep for at least 1ms, and longer if there's nothing to do. | Is tight looping bad? | [
"",
"java",
""
] |
I have my main GUI thread, and a second thread running inside it's own ApplicationContext (to keep it alive, even when there is no work to be done). I want to call a method on my 2nd thread from my GUI thread, but if I just call thread.Method(); it seems to be running on my main GUI thread and causes my GUI to become u... | .Net already comes with a `System.ComponentModel.BackgroundWorker` class specifically to handle performing background tasks and communicating with a GUI. Use it. | Wow, I can't believe how may people didn't bother reading the question.
Anyways, this is what I do.
1. Create you "message" classes. This stores all the information you want to share.
2. Create a Queue<T> for each thread. Use a SyncLock (C# lock) to read/write to it.
3. When you want to talk to a thread, send it a me... | In C# what is the recommended way of passing data between 2 threads? | [
"",
"c#",
"multithreading",
""
] |
What is the correct syntax to create objects in javascript that will work across the majority of web browsers (by that I mean : IE 6+, Firefox 2+, Opera 9+ )
Is this valid
```
var a = {
"class": "Person",
"name": "William Shakespeare",
"birthday": -12802392000000,
"nickname": "Bill"
};
```
Or is this:
```
v... | [@AndreasN is correct](https://stackoverflow.com/questions/380855/json-syntax-for-property-names#380860): the [JSON specification](http://www.json.org/) dictates the use of quotes in order for it to actually be JSON. If you don't use quotes, it may be a valid object literal in Javascript, but it is not JSON. Other serv... | The [spec](http://www.json.org/) say to use "".
Firefox accept without, but IE doesn't.
Pair is defined as
```
string : value
```
Value can be a string
string is defined as
```
" chars "
``` | JSON syntax for property names | [
"",
"javascript",
"json",
"syntax",
""
] |
Is there a Pythonic way to have only one instance of a program running?
The only reasonable solution I've come up with is trying to run it as a server on some port, then second program trying to bind to same port - fails. But it's not really a great idea, maybe there's something more lightweight than this?
(Take into... | The following code should do the job, it is cross-platform and runs on Python 2.4-3.2. I tested it on Windows, OS X and Linux.
```
from tendo import singleton
me = singleton.SingleInstance() # will sys.exit(-1) if other instance is running
```
The latest code version is available [singleton.py](https://github.com/pyc... | Simple, ~~cross-platform~~ solution, found in **[another question](https://stackoverflow.com/questions/220525/ensuring-a-single-instance-of-an-application-in-linux#221159)** by [zgoda](https://stackoverflow.com/users/12138/zgoda):
```
import fcntl
import os
import sys
def instance_already_running(label="default"):
... | Make sure only a single instance of a program is running | [
"",
"python",
"process",
"locking",
"mutual-exclusion",
""
] |
I am working on someone else's PHP code and seeing this pattern over and over:
(pseudocode)
```
result = SELECT blah1, blah2, foreign_key FROM foo WHERE key=bar
if foreign_key > 0
other_result = SELECT something FROM foo2 WHERE key=foreign_key
end
```
The code needs to branch if there is no related row in the... | There is not enough information to really answer the question. I've worked on applications where decreasing the query count for one reason and increasing the query count for another reason *both* gave performance improvements. In the same application!
For certain combinations of table size, database configuration and ... | This is definitely wrong. You are going over the wire a second time for no reason. DBs are very fast at their problem space. Joining tables is one of those and you'll see more of a performance degradation from the second query then the join. Unless your tablespace is hundreds of millions of records, this is not a good ... | LEFT JOIN vs. multiple SELECT statements | [
"",
"sql",
""
] |
I am not able to use the breakpoint in Studio with Javascript. I'm able to debug if I use the debugger;
I've seen this [Breakpoint not hooked up when debugging in VS.Net 2005](https://stackoverflow.com/questions/163133/breakpoint-not-hooked-up-when-debugging-in-vsnet-2005) question already. I tried the answer and it d... | try typing "debugger" in the source where you want to break | Make sure you are attached to the correct process. For example, once you have your page loaded in IE,
1. Switch to Visual Studio and go to the Debug menu.
2. Choose "Attach to Process"
3. Find iexplore in the list and select it.
4. Click the "Select..." button.
5. In the dialog, choose "Debug these code types:" and se... | Using breakpoints to debug Javascript in IE and VS2008 | [
"",
"javascript",
"visual-studio-2008",
"breakpoints",
""
] |
Below is a stored procedure to check if there is a duplicate entry in the database based upon checking all the fields individually (don't ask why I should do this, it just has to be this way).
It sounds perfectly straightforward but the SP fails.
The problem is that some parameters passed into the SP may have a null v... | I think you need something like this for each possibly-null parameter:
```
AND (aCode = @aCode OR (aCode IS NULL AND @aCode IS NULL))
``` | If I understand your question correctly, then I encourage you to do a little research on:
```
SET ANSI_NULLS OFF
```
If you use this command in your stored procedure, then you can use = NULL in your comparison. Take a look at the following example code to see how this works.
```
Declare @Temp Table(Data Int)
Insert... | T-SQL Stored Procedure NULL input values cause select statement to fail | [
"",
"sql",
"t-sql",
"stored-procedures",
"parameters",
"null",
""
] |
I'm trying to setup Spring using Hibernate and JPA, but when trying to persist an object, nothing seems to be added to the database.
Am using the following:
```
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
<property name="url" value="${jdbc.url}"/>
<property name="driverClassName" va... | Thanks to eric and Juan Manuel's answers, I was able to figure out that the transaction wasn't committed.
Adding @Transactional to the storeAccount method did the trick! | I actually came across another way that this can happen.
In an injected EntityManager, no updates will ever occur if you have persistence.xml specified like this:
`<persistence-unit name="primary" transaction-type="RESOURCE_LOCAL">`
You need to remove the transaction-type attribute and just use the default which is ... | Spring, Hibernate & JPA: Calling persist on entitymanager does not seem to commit to database | [
"",
"java",
"hibernate",
"spring",
"jpa",
"persistence",
""
] |
I am thinking about a DB Design Problem.
For example, I am designing this stackoverflow website where I have a list of Questions.
Each Question contains certain meta data that will probably not change.
Each Question also contains certain data that will be consistently changing (Recently Viewed Date, Total Views...etc... | When designing a database structure, it's best to [normalize](http://en.wikipedia.org/wiki/Database_normalization) first and change for performance after you've profiled and benchmarked your queries. Normalization aims to prevent data-duplication, increase integrity and define the correct relationships between your dat... | Your initial database design should be based on conceptual and relational considerations only, completely indepedent of physical considerations. Database software is designed and intended to support good relational design. You will hardly ever need to relax those considerations to deal with performance. Don't even thin... | DB Design: Does having 2 Tables (One is optimized for Read, one for Write) improve performance? | [
"",
"sql",
"database-design",
""
] |
Obviously I can do and `DateTime.Now.After` - `DateTime.Now.Before` but there must be something more sophisticated.
Any tips appreciated. | [System.Environment.TickCount](http://msdn.microsoft.com/en-us/library/system.environment.tickcount.aspx) and the [System.Diagnostics.Stopwatch](http://msdn.microsoft.com/en-us/library/system.diagnostics.stopwatch.aspx) class are two that work well for finer resolution and straightforward usage.
See Also:
* [Is DateT... | I would definitely advise you to have a look at `System.Diagnostics.Stopwatch`
And when I looked around for more about Stopwatch I found this site;
[Beware of the stopwatch](http://kristofverbiest.blogspot.com/2008/10/beware-of-stopwatch.html)
There mentioned another possibility
> Process.TotalProcessorTime | What is the best way to measure execution time of a function? | [
"",
"c#",
"performance",
"benchmarking",
"execution-time",
""
] |
As a "look under the covers" tutorial for myself I am building a PHP script to gather emails from a POP3 mailbox. While attempting to make use of binary attachments I am stuck trying to figure out what to do with the attachment information.
Given a string that would be gathered from an email:
> ------=\_Part\_16735\_... | Pass the data to [base64\_decode()](http://php.net/base64_decode) to get the binary data, write it out to a file with [file\_put\_contents()](http://php.net/file_put_contents) | If you have a lot of data to write out that needs to be decoded before writing I would suggest using stream filters so decode the data as you write it...
```
$fh = fopen('where_you_are_writing', 'wb');
stream_filter_append($fh, 'convert.base64-decode');
// Do a lot of writing here. It will be automatically decoded fr... | Saving a Base64 string to disk as a binary using PHP | [
"",
"php",
"binary",
"base64",
""
] |
In the application I'm writing using a combination of development environments and languages, I have need of accessing a cookie from two different subdomains, each on a separate host.
The cookie is being set on `www.mydomain.com` using the PHP code that follows, and I'm attempting to access it from `distant.mydomain.c... | For the benefit of anyone reading this question the code and information contained in the original post are exactly correct and work fine.
The problem is when you introduce other technology. For instance, **I have since learned that sending PHP code through a Python module, one that allows Django to serve PHP files/co... | Cookies set in domain
`'.aaa.sub.domain.com'`
will collide with identically named cookies set in domain
`'.sub.domain.com'`
and `'.some.stupidly.obscure.multi.sub.domain.com'`
That means (and this took some time to wade thru) if you're going to use the same-named cookie across multiple domains, you must set it onc... | Cookies across subdomains and hosts | [
"",
"php",
"django",
"apache",
"iis",
"cookies",
""
] |
Can I load an stand alone aspx page in another stand alone aspx page using System.Reflection?
I am using the ASP.NET 2.0 Web site project model. | Try using [BuildManager.CreateInstanceFromVirtualPath](http://msdn.microsoft.com/en-us/library/system.web.compilation.buildmanager.createinstancefromvirtualpath.aspx). Sample usage:
```
Page p = BuildManager.CreateInstanceFromVirtualPath("~/Default.aspx", typeof(Page))
```
This answers this specific question, althoug... | Don't know about doing it using Reflection, which may well be possible, but you can capture the output of an aspx or asp page to a string writer using HttpContext.Server.Execute().
I have used this for rendering some complex email templates, but don't know if that is quite what you are after. | Load an ASP.NET 2.0 aspx page using System.Reflection? | [
"",
"c#",
"asp.net",
"reflection",
"system.reflection",
""
] |
Between [Yahoo! UI Compressor](http://developer.yahoo.com/yui/compressor/), [Dean Edwards Packer](http://dean.edwards.name/packer/) and [jsmin](http://www.crockford.com/javascript/jsmin.html), which produces better results, both in terms of resulting footprint and fewer errors when obfuscating. | Better is a bit subjective here, since there are multiple factors to consider (even beyond those you list):
1. Compressed size doesn't tell the whole story, since an aggressive compressor can result in slower run-time performance due to the additional time needed to run unpacking code prior to browser interpretation.
... | A great way to compare the best compressors is [The JavaScript CompressorRater](http://compressorrater.thruhere.net/) by Arthur Blake.
What you're usually interested in is the size after compressing with GZIP (you should configure your web server to perform the compression).
The best results are usually from the [YUI... | Which javascript minification library produces better results? | [
"",
"javascript",
"benchmarking",
"jscompress",
"minify",
""
] |
Let's say I have a simple chunck of XML:-
```
<root>
<item forename="Fred" surname="Flintstone" />
<item forename="Barney" surname="Rubble" />
</root>
```
Having fetched this XML in Silverlight I would like to bind it with [XAML](http://en.wikipedia.org/wiki/Extensible_Application_Markup_Language) of this ilke:... | See *[Binding to Anonymous types in Silverlight](http://grahammurray.wordpress.com/2010/05/30/binding-to-anonymous-types-in-silverlight/)* for information. | You can do this with an IValueConverter. Here is a simple one:
```
public class XAttributeConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)
{
var xml = value as XElement;
var name = parameter as string;... | Binding XML in Silverlight without nominal classes | [
"",
"c#",
"xml",
"silverlight",
"linq-to-xml",
"xml-binding",
""
] |
I am using a program that talks to my COMM port, but I have made another program that I want to "sniff" the comm port messages and perform it's own actions against those messages in addition. Is this possible in .NET c#? | There are third party libraries/tools/products that expose the traffic f you are interested.
Here is one I used for serial port emulation - but I think it provides something you can use:
<http://com0com.sourceforge.net/> | If you have control over the first program that talks to you COMM port, why not change the program to pass data received from the port to the 2nd program of yours via remoting or any other type of IPC. Better still if you can write a proxy program that connected to the COMM port, and have 2 of the other program talk to... | In C# how could I listen to a COM (Serial) Port that is already open? | [
"",
"c#",
"serial-port",
"listener",
"sniffing",
""
] |
I have 2 wav files that I want to concatenate into one file with the two sound tracks.
Is there any api for that task or some built in commands in .NET that can I can use in some genius way to make this task possible?
Many thanks for the help. :) | If I'm not mistaken, you can just append the bytes from the second file to the end of the first. If there is any header data, you'll want to exclude that (see [here](http://filext.com/file-extension/WAV))
Be advised that you may hear a click or pop between the two clips, as there will be no blending. You could probabl... | If you only need to do this once then your best bet is to use some software specifically for the task. [Praat](http://www.fon.hum.uva.nl/praat/) or [audacity](http://audacity.sourceforge.net/) will do this (join or merge two tracks).
Praat can also be scripted so it is possible to script Praat and then call Praat and ... | How to concatenate WAV files in C# | [
"",
"c#",
"merge",
"wav",
""
] |
I googled for this for a while but can't seem to find it and it should be easy. I want to append a CR to then end of an XML file that I am creating with a Transformer. Is there a way to do this>
I tried the following but this resulted in a blank file?
```
Transformer xformer = TransformerFactory.newInstance().newTran... | Simple... just add the [append](http://java.sun.com/j2se/1.4.2/docs/api/java/io/FileOutputStream.html#FileOutputStream(java.io.File,%20boolean)) option:
```
new FileOutputStream(f, true /* append */);
``` | There are a couple of options here.
I assume that your result is a `StreamResult` that you are creating with a `String` specifying the destination file path. You might consider opening a `FileOutputStream` yourself, and constructing your `StreamResult` with that. Then, when the transformer is done, append the line ter... | java append to file | [
"",
"java",
"xml",
"xslt",
"jaxp",
"transformer-model",
""
] |
Hi I have a JSON object that is a 2-dimentional array and I need to pass it to PHP using Ajax.Request (only way I know how). ...Right now I manually serialized my array using a js function...and get the data in this format: s[]=1&d[]=3&[]=4 etc. ....
my question is: Is there a way to pass the JSON object more directly... | You can also use Prototype's function [toJSON()](http://www.prototypejs.org/api/array/tojson) to convert an array into a JSON object. After passing it to server via Ajax call, simply use PHP's function [json\_decode()](http://us.php.net/json_decode) to decode the object. | Pass the object as a JSON-string to PHP, and in PHP use the builtin json\_decode to get a PHP-object from the string.
In Javascript, use a "stringify" function on your object to get it as a string, library available for example here: <https://github.com/douglascrockford/JSON-js/blob/master/json2.js> | Best way to pass JSON from Browser to PHP using Ajax.Request | [
"",
"php",
"json",
"prototypejs",
"ajax.request",
""
] |
```
void some_func(int param = get_default_param_value());
``` | Default parameter can be a subset of the full set of expressions. It must be bound at compile time and at the place of declaration of the default parameter. This means that it can be a function call or a static method call, and it can take any number of arguments as far as they are constants and/or global variables or ... | They don't have to be! A default parameter can be any expression within certain limitations. It is evaluated every time the function is called. | Must default function parameters be constant in C++? | [
"",
"c++",
""
] |
Just for the sake of experimentation, I've been trying to determine different ways to non-destructively chain `window.onload` functions in a web browser. This is the idea of what I have so far:
```
var load = window.onload;
var newFunction = function(){
alert("ha!");
}
window.onload = function(){
load();
n... | May be it will be better to use addEventListener/attachEvent?
[Advanced event registration models](http://www.quirksmode.org/js/events_advanced.html) | You could have a look at [jQuery](http://jquery.com/) how they handle that.
From the [jQuery docs](http://docs.jquery.com/Events/ready#fn):
> You can have as many $(document).ready events on your page as you like. The functions are then executed in the order they were added. | Javascript Window.Onload Function Chaining | [
"",
"javascript",
"function",
"onload",
"method-chaining",
""
] |
Our company (xyz) is moving a lot of our Flash code to Python.
In Flash, we have a shared library between our Flash apps - package xyz. We can make changes to the package without fear of breaking other apps when they are deployed because Flash compiles their code and includes the contents of the library. We deploy the... | I also favour the solution of packing everything together and limit the dependency on the OS libraries to the minimal (glibc and that's it). Hard drive is cheap, customer and support time is not.
On windows, it's trivial with py2exe + InnoSetup.
On Linux, it looks like [bbfreeze](http://pypi.python.org/pypi/bbfreeze/... | "explicitly tested against App1,2,3 every time there was a new library" actually isn't that onerous.
Two things.
* You need a formal set of API unit tests that the library *must* pass. This is just the API, not every nuance of functionality. If this passes, then your changes are good to go. If this fails, your change... | Best way of sharing/managing our internal python library between applications | [
"",
"python",
"deployment",
"shared-libraries",
"projects-and-solutions",
""
] |
I'm developing a Django app, and I'm trying to use Python's logging module for error/trace logging. Ideally I'd like to have different loggers configured for different areas of the site. So far I've got all of this working, but one thing has me scratching my head.
I have the root logger going to sys.stderr, and I have... | Allow me to answer my own question. The underlying problem here is that settings.py gets imported twice, or maybe even more (See [here](http://www.mail-archive.com/django-users@googlegroups.com/msg39059.html)). (I still don't understand why this is. Maybe some Django expert could explain that to me.) This seems to be t... | As of version 1.3, Django uses standard python logging, configured with the `LOGGING` setting (documented here: [1.3](http://docs.djangoproject.com/en/1.3/ref/settings/#std:setting-LOGGING), [dev](http://docs.djangoproject.com/en/dev/ref/settings/#std:setting-LOGGING)).
Django logging reference: [1.3](http://docs.djan... | Python logging in Django | [
"",
"python",
"django",
"logging",
"python-logging",
""
] |
Given an instance `x` of `Callable<T>`, how can I run `x` in a separate process such that I can redirect the standard input and output of the process? For example, is there a way to build a `Process` from a `Callable`? Is there a standard `Executor` that gives control over input and output?
[UPDATE] It's not important... | More generally:
> Given an instance x of Callable utilizing global variables A and B, how can I run x concurrently such that x sees custom values for A and B, rather than the "original" values of A and B?
And the best answer is, don't use global variables. Dependency inject things like that. Extend Callable and add m... | stdin/stdout can be redirected for the entire system, but I'm not sure it can be redirected for a single thread--you are always just getting it from System. (You can make System.out go to another stream though, I've used that to catch stack traces before there was a method to get the trace as a string)
You could redir... | Java: Run a Callable in a separate process | [
"",
"java",
"multithreading",
"process",
"stdout",
"stdin",
""
] |
```
public class Address
{
public string ZipCode {get; set;}
}
public class Customer
{
public Address Address {get; set;}
}
```
how can I access eitther "ZipCode" or "Address.ZipCode" with reflection? For example:
```
Typeof(Customer).GetProperty("ZipCode")?
``` | You'd need something like:
```
PropertyInfo addressProperty = typeof(Customer).GetProperty("Address");
ProportyInfo zipCodeProperty = addressProperty.PropertyType.GetProperty("ZipCode");
object address = addressProperty.GetValue(customer, null);
object zipCode = zipCodeProperty.GetValue(address, null);
```
Basically... | Jon Skeet's answer is fine, I had to extend his method a bit though, in order to account for derived instances within the property path:
```
public static class ReflectorUtil
{
public static object FollowPropertyPath(object value, string path)
{
if (value == null) throw new ArgumentNullException("value... | Best way to get sub properties using GetProperty | [
"",
"c#",
"reflection",
"getproperty",
""
] |
I am using a makefile system with the pvcs compiler (using Microsoft Visual C++, 2008 compiler) and I am getting several link errors of the form:
> `error LNK2019: unresolved external symbol __imp__RegisterFilter@8 referenced in function _main`
This is happening DESPITE using the `extern "C"` declaration, viz.:
```
... | I was creating a simple Win32 c++ application in VS2005 and I was getting this error:
```
LNK2019: unresolved external symbol __imp__somefunction
```
This application was using property sheets, hence it required this header (prsht.h).
The solution to my problem was as follows: in program **Properties→Configuration P... | The `__imp_` prefix indicates that the linker expects this function to be imported from a DLL.
Is the clrdump library from [this page](http://www.debuginfo.com/tools/clrdump.html)? If so, note that `extern "C"` is not used in the header file supplied with the library. I confirmed this using the following command:
```... | Clrdump (C++) error LNK2019: unresolved external symbol __imp__RegisterFilter@8 referenced in function _main | [
"",
"c++",
"visual-studio",
"makefile",
"clrdump",
""
] |
I was just wondering how I could *automatically* increment the build (and version?) of my files using Visual Studio (2005).
If I look up the properties of say `C:\Windows\notepad.exe`, the Version tab gives "File version: 5.1.2600.2180". I would like to get these cool numbers in the version of my dll's too, not versio... | In visual Studio 2008, the following works.
Find the AssemblyInfo.cs file and find these 2 lines:
```
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
```
You could try changing this to:
```
[assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyFileVersion("1.0.*")]
```
But this ... | open up the AssemblyInfo.cs file and change
```
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
```
to
```
[assembly: Asse... | Can I automatically increment the file build version when using Visual Studio? | [
"",
"c#",
"asp.net",
"visual-studio",
"version-control",
"assemblyinfo",
""
] |
I created a simple dialog-based application, and in the default CDialog added three buttons (by drag-and-dropping them) using the Visual Studio editor.
The default OK and Cancel buttons are there too.
I want to set the focus to button 1 when I click button 3.
I set the property Flat to true in the properties for muy... | This draws the thick border around the button:
```
static_cast<CButton*>(GetDlgItem(IDC_BUTTON1))->SetButtonStyle(BS_DEFPUSHBUTTON);
```
A more elegant way to do this would be to define a CButton member variable in CbuttonfocusDlg and associate it to the IDC\_BUTTON1 control, and then calling
```
this->m_myButton.Se... | Use `WM_NEXTDLGCTL`.
See [Reymond Chen's "How to set focus in a dialog box"](http://blogs.msdn.com/oldnewthing/archive/2004/08/02/205624.aspx):
```
void SetDialogFocus(HWND hdlg, HWND hwndControl)
{
SendMessage(hdlg, WM_NEXTDLGCTL, (WPARAM)hwndControl, TRUE);
}
``` | How to SetFocus to a CButton so that the border and focus dotted line are visible? | [
"",
"c++",
"mfc",
"setfocus",
"cdialog",
"cbutton",
""
] |
Here's a fictitious example of the problem I'm trying to solve. If I'm working in C#, and have XML like this:
```
<?xml version="1.0" encoding="utf-8"?>
<Cars>
<Car>
<StockNumber>1020</StockNumber>
<Make>Nissan</Make>
<Model>Sentra</Model>
</Car>
<Car>
<StockNumber>1010</StockNumber>
<Make>To... | It might be a bit old thread, but i will post anyway. i had the same problem (needed to deserialize like 10kb of data from a file that had more than 1MB). In main object (which has a InnerObject that needs to be deserializer) i implemented a IXmlSerializable interface, then changed the ReadXml method.
We have xmlTextR... | The accepted [answer](https://stackoverflow.com/a/2251545/193414) from user271807 is a great solution but I found, that I also needed to set the xml root of the fragment to avoid an exception with an inner exception saying something like this:
```
...xmlns=''> was not expected
```
This exception was trown when I trie... | How to deserialize only part of an XML document in C# | [
"",
"c#",
"xml",
"xml-serialization",
"serialization",
""
] |
I have to choose a technology to connect my **Application/Presentation Layer** (Java Based) with the **Service Layer** (Java Based). Basically looking up appropriate Spring Service from the Business Delegate Object.
There are so many options out there that it is confusing me. Here are the options I've narrowed down to... | It mostly boils down to do you want to use Spring Remoting (which Spring RMI and [Apache Camel](http://activemq.apache.org/camel/spring-remoting.html) are implementations of) - or do you want to use JAX-WS for web services (which CXF or Metro implement). i.e. do you want automatic remoting for your POJOs - or do you wa... | Spring Remoting would seem like the simplest approach. It also would leave you open to more complex approaches in the future if that is the direction you want to take.
From the limited view of your requirements, I would stick with a simple solution with a lower learning curve, and leave the ESB till you determine you ... | Making a Service Layer call from Presentation layer | [
"",
"java",
"spring",
"jakarta-ee",
"soa",
"esb",
""
] |
I am using a third party application and would like to change one of its files. The file is stored in XML but with an invalid doctype.
When I try to read use a it errors out becuase the doctype contains "file:///ReportWiz.dtd"
(as shown, with quotes) and I get an exception for cannot find file. Is there a way to tell ... | Tell your DocumentBuilderFactory to ignore the DTD declaration like this:
```
docFactory.setFeature("http://apache.org/xml/features/nonvalidating/load-external-dtd", false);
```
See [here](http://xerces.apache.org/xerces2-j/features.html) for a list of available features.
You also might find JDOM a lot easier to wor... | Handle resolution of the DTD manually, either by returning a copy of the DTD file (loaded from the classpath) or by returning an empty one. You can do this by setting an entity resolver on your document builder:
```
EntityResolver er = new EntityResolver() {
@Override
public InputSource resolveEnti... | Java change and move non-standard XML file | [
"",
"java",
"xml",
"dom",
"parsing",
""
] |
I'm looking for turn-key [ANTLR](http://www.antlr.org/) grammar for C# that generates a usable Abstract Syntax Tree (AST) and is either back-end language agnostic or targets C#, C, C++ or D.
It doesn't need to support error reporting.
P.S. I'm not willing to do hardly any fix-up as the alternative is not very hard. | This may be waaaay too late, but you can get a [C# 4 grammar](http://www.antlr3.org/grammar/list.html). | Here's a [C# grammar](http://www.antlr.org/grammar/1151612545460/CSharpParser.g) link, as well as an overview of [C# and ANTLR](http://www.manuelabadia.com/blog/PermaLink,guid,ff1dc504-f854-40b4-bfe7-250ce91efad7.aspx). There are others for the other languages you mentioned [here](http://www.antlr.org/grammar/list). | C# ANTLR grammar? | [
"",
"c#",
"antlr",
""
] |
Optimization of PHP code via runtime benchmarking is straight forward. Keep track of $start and $end times via microtime() around a code block - I am not looking for an answer that involves microtime() usage.
What I would like to do is measure the time it takes PHP to get prepared to run it's code - code-parse/op-code... | Yes. There is.
```
<?php return; rest of the code ?>
```
or
```
<?php whole code; $%^parse erorr!@! ?>
```
and then compare time of running empty script
```
time php empty.php
```
with time it takes to run (or fail) regular script with the additions I've mentioned above:
```
time php test.php
```
I've used this... | One method could be timing the execution of the script from the command line.
In Linux for example:
```
$ time php5 -r 'echo "Hello world";'
Hello world
real 0m1.565s
user 0m0.036s
sys 0m0.024s
```
Does that help at all? Perhaps it is helpful for discovering relative times between different scripts, but it... | Is there a way to measure parse time in PHP? | [
"",
"php",
"benchmarking",
"opcode-cache",
""
] |
The following doesn't work, because it doesn't wait until the process is finished:
```
import subprocess
p = subprocess.Popen('start /WAIT /B MOZILL~1.LNK', shell=True)
p.wait()
```
Any idea how to run a shortcut and wait that the subprocess returns ?
**Edit:** originally I was trying this without the **shell** opti... | You will need to invoke a shell to get the subprocess option to work:
```
p = subprocess.Popen('start /B MOZILL~1.LNK', shell=True)
p.wait()
```
This however will still exit immediately (see @R. Bemrose).
If `p.pid` contains the correct pid (I'm not sure on windows), then you could use [`os.waitpid()`](http://docs.p... | cmd.exe is terminating as soon as start launches the program. This behavior is documented (in start /? ):
> If Command Extensions are enabled,
> external command invocation through
> the command line or the START command
> changes as follows:
...
> When executing an application that is
> a 32-bit GUI application, CM... | Run a shortcut under windows | [
"",
"python",
"windows",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.