Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I want to attach a 'click' event handler to the first child of an element with ID 'foo' using [jQuery](http://en.wikipedia.org/wiki/JQuery). I understand that the syntax for doing this is:
```
$('#foo:first-child').bind('click', function(event) {
// I want to access the first child here
})
```
Within the handler ... | Just use "this":
```
$('#foo:first-child').bind('click', function(event) {
alert(this === $('#foo:first-child')); // True
this.style.color = "red"; // First child now has red text.
})
``` | ```
$(this).doStuff()
``` | jQuery-bound event handlers | [
"",
"javascript",
"jquery",
"events",
""
] |
I'm trying to construct a query that will include a column indicating whether or not a user has downloaded a document. I have a table called HasDownloaded with the following columns: id, documentID, memberID. Finding out whether a user has downloaded a *specific* document is easy; but I need to generate a query where t... | Move the condition in the WHERE clause to the join condition.
```
SELECT Documents.name, HasDownloaded.id FROM Documents
LEFT JOIN HasDownloaded ON HasDownloaded.documentID = Documents.id
AND HasDownloaded.memberID = @memberID
```
This is necessary whenever you want to refer to a left join-ed table in what would o... | ```
WHERE HasDownloaded.memberId IS NULL OR HasDownloaded.memberId = @memberId
```
would be the normal way to do that. Some would shorten it to:
```
WHERE COALESCE(HasDownloaded.memberId, @memberId) = @memberId
```
You can, as Matt B. shows, do it in your JOIN condition - but I think that's much more likely to confu... | Help with a WHERE on a LEFT JOIN SQL Query | [
"",
"sql",
"join",
"left-join",
""
] |
Is it possible to easily embed ActiveX controls in Java application? Is it worth it. In my next project I should either use existing activex in Java app or have to reimplement everything from scratch, so I'm wondering what will be less hassle. | I don't think there's a way to do this without resorting to a third party library. (Or rolling your own, but you did say "easily".)
[SWT](http://www.eclipse.org/swt) (The "Standard Widget Toolkit") contains support for embedding ActiveX controls. SWT is an alternative to Swing, though there is a degree of interoperabi... | It really depends on how much you are going to have to re-implement. The [Jacob project](http://sourceforge.net/projects/jacob-project/) is quite good (we use it extensively for automation of Excel and Word), but you have to *really* understand COM to use it, especially the vagaries of the IDispatch interface (very few... | Activex from java application? | [
"",
"java",
"windows",
"activex",
""
] |
When are objects or something else said to be "first-class" in a given programming language, and why? In what way do they differ from languages where they are not?
When one says "everything is an object" (like in Python), do they indeed mean that "everything is first-class"? | In short, it means there are no restrictions on the object's use. It's the same as
any other object.
A first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have.
> Depending on the ... | "When one says "everything is an object" (like in Python), does he indeed mean that "everything is first-class"?"
Yes.
Everything in Python is a proper object. Even things that are "primitive types" in other languages.
You find that an object like `2` actually has a fairly rich and sophisticated interface.
```
>>> ... | What are "first-class" objects? | [
"",
"python",
"language-agnostic",
""
] |
I have a class with some abstract methods, but I want to be able to edit a subclass of that class in the designer. However, the designer can't edit the subclass unless it can create an instance of the parent class. So my plan is to replace the abstract methods with stubs and mark them as virtual - but then if I make an... | Well you could do some really messy code involving `#if` - i.e. in `DEBUG` it is virtual (for the designer), but in `RELEASE` it is abstract. A real pain to maintain, though.
But other than that: basically, no. If you want designer support it can't be abstract, so you are left with "virtual" (presumably with the base ... | You could use the reference to implementation idiom in your class.
```
public class DesignerHappy
{
private ADesignerHappyImp imp_;
public int MyMethod()
{
return imp_.MyMethod()
}
public int MyProperty
{
get { return imp_.MyProperty; }
set { imp_.MyProperty = valu... | Can I force subclasses to override a method without making it abstract? | [
"",
"c#",
".net",
"visual-studio-2008",
"abstract-class",
""
] |
I've never learnt JavaScript, but I imagine this is quite a simple problem. Just wanted to know which method is most advised these days. | ```
// use this to avoid redirects when a user clicks "back" in their browser
window.location.replace('http://somewhereelse.com');
// use this to redirect, a back button call will trigger the redirection again
window.location.href = "http://somewhereelse.com";
// given for completeness, essentially an alias to window... | Most advised? To not do it. [HTTP is **far** better suited to the job](http://www.w3.org/QA/Tips/reback) than JavaScript is (search engines follow them, you can state if it is permanent or not, they are faster, etc).
Failing that…
If you want an immediate redirect:
```
window.location.replace('http://example.com/');... | What's the best way to automatically redirect someone to another webpage? | [
"",
"javascript",
"browser",
"redirect",
""
] |
I've got a Method that gets a IDictionary as a parameter.
Now I want to provide a method that retrieves the value from this dictionary, but it should be case-invariant.
So my solution to this right now was to have a static function that loops through the keys and converts them toLower() like this:
```
private static ... | Yes - pass the Dictionary constructor `StringComparer.OrdinalIgnoreCase` (or another case-ignoring comparer, depending on your culture-sensitivity needs). | By using a StringDictionary the keys are converted to lower case at creating time.
<http://simiansoftware.blogspot.com/2008/11/have-const-string-with-ui-description.html> | Convert IDictionary<string, string> keys to lowercase (C#) | [
"",
"c#",
".net",
"idictionary",
""
] |
How does the event creation and handling work in Java Swing? | The java event mechanism is actually an implementation of the Observer design pattern.
I suggest you do alittle reading on the observer pattern, this will give you a lot of insight on how the event mechanism in Java works.
[See observer pattern on Wikipedia](http://en.wikipedia.org/wiki/Observer_pattern) | Generally events are handled by registering a callback function with the class that would raise the event. When the event occurs, that class will call the callback function.
You will find a lot of examples from swing. Here is a non-swing example from a chat application i made some time back
This was a library that wo... | How do events work in Java Swing? | [
"",
"java",
"swing",
"events",
""
] |
There are a group of private methods in my class, and I need to call one dynamically based on an input value. Both the invoking code and the target methods are in the same instance. The code looks like this:
```
MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType);
dynMethod.Invoke(this, new object[] { ... | Simply change your code to use the overloaded [version of `GetMethod`](http://msdn.microsoft.com/en-us/library/system.type.getmethod.aspx) that accepts BindingFlags:
```
MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType,
BindingFlags.NonPublic | BindingFlags.Instance);
dynMethod.Invoke(this, new ... | `BindingFlags.NonPublic` will not return any results by itself. As it turns out, combining it with `BindingFlags.Instance` does the trick.
```
MethodInfo dynMethod = this.GetType().GetMethod("Draw_" + itemType,
BindingFlags.NonPublic | BindingFlags.Instance);
``` | How do I use reflection to invoke a private method? | [
"",
"c#",
".net",
"reflection",
"private-methods",
""
] |
How do I check if an object has a specific property in JavaScript?
Consider:
```
x = {'key': 1};
if ( x.hasOwnProperty('key') ) {
//Do this
}
```
Is that the best way to do it? | ## 2022 UPDATE
## [`Object.hasOwn()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn)
> `Object.hasOwn()` is recommended over `Object.hasOwnProperty()` because it works for objects created using `Object.create(null)` and with objects that have overridden the inherited `... | With [Underscore.js](http://underscorejs.org/) or ([even better](https://stackoverflow.com/questions/13789618/differences-between-lodash-and-underscore-js)) [Lodash](http://lodash.com/):
```
_.has(x, 'key');
```
Which calls `Object.prototype.hasOwnProperty`, but (a) is shorter to type, and (b) uses "a safe reference ... | How do I check if an object has a specific property in JavaScript? | [
"",
"javascript",
""
] |
I want to create a list of methods to execute. Each method has the same signature.
I thought about putting delegates in a generic collection, but I keep getting this error:
> 'method' is a 'variable' but is used like a 'method'
In theory, here is what I would like to do:
```
List<object> methodsToExecute;
int Add(i... | You need to cast the `object` in the list to a `BinaryOp`, or, better, use a more specific type parameter for the list:
```
delegate int BinaryOp(int x, int y);
List<BinaryOp> methodsToExecute = new List<BinaryOp>();
methodsToExecute.add(Add);
methodsToExecute.add(Subtract);
foreach(BinaryOp method in methodsToExec... | Using .NET 3.0 (or 3.5?) you have generic delegates.
Try this:
```
List<Func<int, int, int>> methodsToExecute = new List<Func<int, int, int>>();
methodsToExecute.Add(Subtract);
methodsToExecute.Add[0](1,2); // equivalent to Subtract(1,2)
``` | Can I use a List<T> as a collection of method pointers? (C#) | [
"",
"c#",
"generics",
"delegates",
""
] |
Im just starting a project and since this project is personal I was wondering what are the advantages of using Enterprise Library? We use the version 2 for several projects in the office but im not quite sure (aside of the good practices) of the advantages of it, especially in the database component. Any advice? Thanks | For the database application block, the main advantage is that it makes it easier to produce database-agnostic code. The developer interacts mainly with generic Database and DbCommand objects, rather than eg SqlConnection, SqlCommand, etc. Thus, switching to a different database (ie Oracle) becomes more feasible. Depen... | My team did an evaluation of the [Microsoft Patterns and Practices Enterprise Library](http://msdn.microsoft.com/en-us/library/cc467894.aspx) about 2 years ago as part of a re-engineering of our product line. The only part we ended up using was the database block. We even wrapped that in some classes that we could inst... | Advantages and disadvantages of using Enterprise Library | [
"",
"c#",
".net",
"enterprise-library",
""
] |
I have an index on columns A, B, C, D of table T
I have a query that pulls from T with A, B, C in the WHERE clause.
Will the index be used or will a separate index be needed that only includes A, B, C? | David B is right that you should check the execution plan to verify the index is being used.
> Will the index be used or will a separate index be needed that only includes A, B, C?
To answer this last part of the question, which I think is the core underlying topic (as opposed to the immediate solution), there is \*a... | It depends!
```
WHERE A like '%x%'
and B = 1
and C = 1
//
WHERE A = 1
OR B = 1
OR C = 1
//
WHERE DateAdd(dd, 1, A) = '2008-01-01'
AND B = 1
AND C = 1
```
These will not rely on the index, because the index is not useful.
Click on "display estimated execution plan" to confirm potential index usage. | Will my index be used if all columns are not used? | [
"",
"sql",
"sql-server",
"sql-execution-plan",
""
] |
Our clients use a vb6 version of our software.
We are upgrading them to a .NET application written in C#...
Is there less bulk using .net 2.0 than .net 3.5?
My definition of less bulk would be: Smaller size, smaller installation time, etc.
Most of them probably already have 2.0 anyway.
I only ask because I would l... | For taking advantage of LINQ, you need 3.5 (unless you want to use [LINQBridge](http://www.albahari.com/nutshell/linqbridge.aspx) with 2.0).
For a smaller installer, .Net 3.5 **Sp1** has a new feature called "[Client Profile](http://weblogs.asp.net/scottgu/archive/2008/05/12/visual-studio-2008-and-net-framework-3-5-se... | 1. Is not installing .NET 3.5 just to save a few Mb really that much more important that gaining a huge increase in productivity with LINQ and other .NET 3.5 features?
2. Why start off behind in technology? | .NET 2.0 or 3.5? | [
"",
"c#",
".net",
"linq",
"vb6",
"vb6-migration",
""
] |
Been having a "heated debate" with a colleague about his practice of wrapping most of his functions in a try/catch but the catch has JUST a "throw" in it e.g.
```
Private sub foo()
try
'Do something'
catch
throw 'And nothing else!'
End Try
End Sub
```
My thought was to not even bother (ass... | The reason you have a lone throw inside a catch rather than throwing a new exception is because this causes the original stack trace/exception data to be preserved. And one reason you might do this is because you can now set a break-point there for debugging. | Microsoft recommends not to catch an exception when the only thing you do is to rethrow it immediately (i dont remember the source for now).
Your code should only catch exceptions that you want to handle for clean up things or similar actions.
So generally its not a good practice to catch and rethrow an exception.
Re... | Is there a benefit to JUST a "throw" in a catch? | [
"",
"c#",
".net",
"vb.net",
""
] |
I keep on hearing about concurrent programing every where.
Can you guys throw some light on what it's and how c++ new standards facilitate doing the same? | Concurrency is about your code doing multiple things at the same time. This is typically done with explicit "threads", but there are other possibilities. For example, if you use OpenMP directives in your code then a compiler that supports OpenMP will automatically generate threads for you.
Thread is short for "thread ... | When you say "how c++ new standards facilitate" concurrent programming, I assume you're talking about the soon (?) to be released C++09 standard.
The new standard as it currently stands in draft form supports the following items that help with concurrent programming:
* atomic types and addresses
* a thread class
* th... | Concurrent programming c++? | [
"",
"c++",
"concurrency",
"c++11",
""
] |
I'm trying to use jcarousel to build a container with multiple rows, I've tried a few things but have had no luck. Can anyone make any suggestions on how to create it? | We have had to make a similar modifiaction. We do this by extending the default options, to include a rows value, and the width of each item (we call them modules) then divide the width by the number of rows.
Code added to jCarousel function...
Add to default options:
```
moduleWidth: null,
rows:null,
```
Then set ... | This is .js code substitutions according to @Sike and a little additional of me, the height was not set dynamically, now it is.
```
var defaults = {
vertical: false,
rtl: false,
start: 1,
offset: 1,
size: null,
scroll: 3,
visible: null,
animation: 'normal... | Multiple rows with jcarousel | [
"",
"javascript",
"jquery",
"jcarousel",
""
] |
I'm doing something like the following:
```
SELECT * FROM table WHERE user='$user';
$myrow = fetchRow() // previously I inserted a pass to the db using base64_encode ex: WRM2gt3R=
$somepass = base64_encode($_POST['password']);
if($myrow[1] != $somepass) echo 'error';
else echo 'welcome';
```
Im always getting error... | Try using `var_dump` instead of echo - maybe one of them has a space or newline at the start/end.
Edit:
You must be storing it as CHAR(40): `A fixed-length string that is always right-padded with spaces to the specified length when stored`
Use VARCHAR or `trim()` | If $myrow[1] is actually the correct password in base64-encoding, I don't see any errors.
Try this ind the end:
```
echo "<br />$myrow[1] != $somepass";
```
What does it say?
And by the way: I don't see any reason to base64-encode the passwords. What are you trying to accomplish? | base64_encode weird behavior | [
"",
"php",
"base64",
""
] |
I have an application that behaves oddly, and just to verify, I'd like to see which security zone it is currently running under.
I've found the System.Security.SecurityZone enum, but can't seem to find anything that will return which of these I'm running under.
Does anyone have any tips?
Basically I want to find out... | You need to look at the CAS evidence for the current assembly;
this.GetType().Assembly.Evidence
[Assembly.Evidence](http://msdn.microsoft.com/en-us/library/system.reflection.assembly.evidence.aspx) is a property [Evidence](http://msdn.microsoft.com/en-us/library/system.security.policy.evidence.aspx) object. From this... | In .NET 3.5 you can simplify the code with LINQ:
```
Zone z = a.Evidence.OfType<Zone>().First();
```
From .NET 4.0 you have a convenient `GetHostEvidence` method:
```
Zone z = Assembly.GetExecutingAssembly().Evidence.GetHostEvidence<Zone>();
```
Note that from .NET 4.0 evidence classes derive from the `EvidenceBase... | Get current/active security zone of a .NET application? | [
"",
"c#",
".net",
"security",
"cas",
"security-zone",
""
] |
I need to validate this simple pick list:
```
<select name="<%= key %>">
<option value="ETC" SELECTED>Select an option...</option>
<option value="ONE">Lorem ipsum</option>
<option value="TWO">dolor sit amet</option>
</select>
```
So the user would never submit the form with the, excuse the repetition, "Se... | You can never really satisfy the condition 'never submit a given value' because you don't have control over the client side. The user can always manipulate HTML to submit whatever they want.
It is a good approach is to use JavaScript to do client-side validation and give the user quick feedback and catch 99%+ of the c... | JSP is a "view" in MVC pattern, and should therefore only be used to present the data to the user. Any application logic, including validation logic, should be done server-side.
If this JSP is intended to be a part of a large app, I would recommend using Spring MVC to set up your app, and writing a validator to validat... | How would you easily validate a JSP option pick list? | [
"",
"java",
"validation",
"jsp",
"xhtml",
"forms",
""
] |
I'm a PHPer, and am not writing object-oriented code.
What are the advantages of OO over procedural code, and where can I learn how to apply these ideas to PHP? | **It doesn't help you automatically.** You can write worse "OO" programs than structural programs, and vice versa. OOP is a tool which allows you to create more powerful abstractions.
* As with every powerful tool, you have to use it properly.
* As with every powerful tool, it takes time to learn how to use it properl... | Objects help keep your code isolated between different sections, so that if you need to make a change to one section you can be confident it won't affect other sections: loose coupling.
Then, when you've done that for a while, you'll start finding that objects you created for one app are also useful in others, and you... | What are the benefits of OO programming? Will it help me write better code? | [
"",
"php",
"oop",
""
] |
I've looked at both the [Named Parameter Idiom](http://www.parashift.com/c++-faq-lite/ctors.html#faq-10.20) and the [Boost::Parameter library](http://www.boost.org/doc/libs/1_36_0/libs/parameter/doc/html/index.html). What advantages does each one have over the other? Is there a good reason to always choose one over the... | Implementing the Named Parameter Idiom is really easy, almost about as easy as using Boost::Parameter, so it kind of boils down to one main point.
-Do you already have boost dependencies? If you don't, Boost::parameter isn't special enough to merit adding the dependency.
Personally I've never seen Boost::parameter in... | Normally, I'm a big fan of Boost, but I wouldn't use the Boost.Parameter library for a couple of reasons:
1. If you don't know what's going on,
the call looks like you're assigning
a value to a variable in the scope
on the calling function before
making the call. That can be very
confusing.
2. There is ... | C++ "Named Parameter Idiom" vs. Boost::Parameter library | [
"",
"c++",
"named-parameters",
"boost-parameter",
""
] |
I need to add multiple empty divs to a container element using jQuery.
At the moment I am generating a string containing the empty html using a loop
```
divstr = '<div></div><div></div>...<div></div>';
```
and then injecting that into my container:
```
$('#container').html(divstr);
```
Is there a more elegant way ... | If you want IE to be fast - or generally consider speed, then you'll want to build up a DOM fragment first before inserting it.
John Resig explains the technique and includes a performance benchmark:
<http://ejohn.org/blog/dom-documentfragments/>
```
var i = 10,
fragment = document.createDocumentFragment(),
... | The fastest way to do this is to build the content first with strings. It is MUCH faster to work with strings to build your document fragment before working with the DOM or jquery at all. Unfortunately, IE does a really poor job of concatenating strings, so the best way to do it is to use an array.
```
var cont = []; ... | How should I add multiple identical elements to a div with jQuery | [
"",
"javascript",
"jquery",
"dom",
""
] |
The output of my JSON call can either be an Array or a Hash. How do I distinguish between these two? | **Modern browsers support the `Array.isArray(obj)` method.**
[See MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/isArray) for documentation and a polyfill.
= *original answer from 2008* =
you can use the constuctor property of your output:
```
if(output.constructor == Ar... | Is object:
```
function isObject ( obj ) {
return obj && (typeof obj === "object");
}
```
Is array:
```
function isArray ( obj ) {
return isObject(obj) && (obj instanceof Array);
}
```
Because arrays are objects you'll want to test if a variable is an array first, and then if it is an object:
```
if (isArra... | In javascript how can we identify whether an object is a Hash or an Array? | [
"",
"javascript",
""
] |
I've got a `DateTime?` that I'm trying to insert into a field using a `DbParameter`. I'm creating the parameter like so:
```
DbParameter datePrm = updateStmt.CreateParameter();
datePrm.ParameterName = "@change_date";
```
And then I want to put the value of the `DateTime?` into the `dataPrm.Value` while accounting for... | Ah ha! I found an even more efficient solution than @Trebz's!
```
datePrm.Value = nullableDate ?? (object)DBNull.Value;
``` | If you are using SQLServer, the `System.Data.SqlTypes` namespace contains some utility classes that avoid the annoying type casting. For example instead of this:
```
var val = (object) "abc" ?? DBNull.Value;
```
you can write this:
```
var val = "abc" ?? SqlString.Null;
``` | C# ADO.NET: nulls and DbNull -- is there more efficient syntax? | [
"",
"c#",
"ado.net",
"null",
"nullable",
"dbnull",
""
] |
I have a static method in my code that I would like somehow to mock.
I am using jmock.
One way I suppose I could do this is to have "wrapper class" around the static method and
mock this but I was hoping for a better solution.
I am going about this the wrong way?
FEEDBACK:
I was going to have a interface and class... | We don't support mocking static methods in jMock because it doesn't fit our design approach. We prefer not to use static methods for significant features that can affect the state of the system. We tend to use them just to support the OO code and make it more readable. That's why we view mocking a static methods as a h... | [JMockit](http://code.google.com/p/jmockit) is another toolkit which allows mocking of static methods (as well as final methods, constructors, etc.).
I don't see any problem with the *judicious* use of static methods when designing an otherwise OO solution.
For example, one pattern/idiom I like to use is the *static ... | jmock mocking a static method | [
"",
"java",
"mocking",
"jmock",
""
] |
Just got a question about generics, why doesn't this compile when using a generic List? If its not possible, anyway around it? Much appreciate any answer.
```
// Interface used in the ServiceAsync inteface.
public interface BaseObject
{
public String getId();
}
// Class that implements the interface
public class ... | This has got to do with the subtyping rules for parametrized types. I'll explain it in three steps:
## Non-nested case
When you have the following subtype relation (where `<:` is the symbol for "is a subtype of"):
```
_ModelDto <: BaseObject
```
The following relation does **not** hold:
```
List<_ModelDto> <: List... | The fact that your MyAsync interface doesn't contain any method signatures and doesn't have a particularly informative name is a code smell from my perspective, but I'll assume that this is just a dummy example. As it is written, getList() couldn't ever have any reasonable implementation that used the callback in any w... | Can't compile class calling a method in an interface with a generic list argument | [
"",
"java",
"generics",
""
] |
I'm writing a custom swing component (something completely new, but think JTree or JList). I'm trying to follow the general design of JTree, JTable, JList etc for consistency (I've also seen various poor 3rd party components abandon the separable model and/or renderer approach).
So, I have a model full of nodes, the c... | Good question. This is not specific to Swing, but a philosophical question about the difference between a model and a view.
In general, is converting objects into text the job of the model or the view? My purist head says that actually you want a hierarchy of views - one to convert object model to text, and one to dis... | If you had to write your own component do it as simple as possible. In a lot of cases if you need a custom renderer then you don't care about interpretation by component or model. Model holds your data. And in this case is also custom written. From my point of view the good choice is based on first option. Provide Defa... | Custom swing component - Turning a node into text | [
"",
"java",
"swing",
""
] |
Let's say I have one class `Foo` that has a bunch of logic in it and another class `Bar` which is essentially the same. However, as `Foo` and `Bar` are different (but related) entities I need the difference to be apparent from my code (i.e. I can tell whether an instance is a `Foo` or a `Bar`)
As I was whacking this t... | In my opinion, it's best if `Foo` and `Bar` subclass off a common ancestor class (maybe `AbstractFoo`), which has all the functionality. What difference in behaviour should exist between `Foo` and `Bar`? Code that difference as an abstract method in `AbstractFoo`, not by using a `if` statement in your code.
Example: R... | **It all depends on meaning of the Foo and Bar classes. What they represent, and what's their purpose. Please clarify.**
I can imagine situations when each of your solutions and proposed solutions is the right one. | Is it OK to have an 'empty' class that extends another class? | [
"",
"java",
""
] |
I was recently tasked to document a large JavaScript application I have been maintaining for some time. So I do have a good knowledge of the system.
But due the sheer size of the application, it will probably take a lot of time even with prior knowledge around the code and the source code itself in uncompressed form.
... | [Firebug](https://addons.mozilla.org/firefox/addon/1843)'s [DOM tab](http://getfirebug.com/dom.html) lets you browse the contents of the global `window` object, and you can inspect a particular object by entering `inspect(whatever)` in the command line.
You won't be able to use it to detect relationships unless an ins... | Take a look at [Aptana](http://www.aptana.com), they have an outline that can help you to determine what are the objects and somtetimes their relationship. | JavaScript object browser? | [
"",
"javascript",
""
] |
I have some code that raises `PropertyChanged` events and I would like to be able to unit test that the events are being raised correctly.
The code that is raising the events is like
```
public class MyClass : INotifyPropertyChanged
{
public event PropertyChangedEventHandler PropertyChanged;
protected void N... | Everything you've done is correct, providing you want your test to ask "What is the last event that was raised?"
Your code is firing these two events, in this order
* Property Changed (... "My Property" ...)
* Property Changed (... "MyOtherProperty" ...)
Whether this is "correct" or not depends upon the purpose of t... | If you're doing TDD then event testing can start to generate a *lot* of repetitive code. I wrote an event monitor that enables a much cleaner approach to unit test writing for these situations.
```
var publisher = new PropertyChangedEventPublisher();
Action test = () =>
{
publisher.X = 1;
publisher.Y = 2;
};
... | Unit testing that events are raised in C# (in order) | [
"",
"c#",
"unit-testing",
"events",
""
] |
What is the easiest way to use a `DLL` file from within `Python`?
Specifically, how can this be done *without* writing any additional wrapper `C++` code to expose the functionality to `Python`?
Native `Python` functionality is strongly preferred over using a third-party library. | For ease of use, [ctypes](http://docs.python.org/library/ctypes.html) is the way to go.
The following example of ctypes is from actual code I've written (in Python 2.5). This has been, by far, the easiest way I've found for doing what you ask.
```
import ctypes
# Load DLL into memory.
hllDll = ctypes.WinDLL ("c:\\P... | [This page](http://web.archive.org/web/20111006042404/http://www.knowledgetantra.com/component/content/article/2-python/1-call-dll-function-in-python.html) has a very simple example of calling functions from a DLL file.
Paraphrasing the details here for completeness:
> It's very easy to call a DLL function in Python.... | How can I use a DLL file from Python? | [
"",
"python",
"dll",
""
] |
I have a table like as follows:
```
SoftwareName Count Country
Project 15 Canada
Visio 12 Canada
Project 10 USA
Visio 5 USA
```
How do I query it to give me a summary like...
```
SoftwareName Canada USA Total
Project 15 10 ... | ```
SELECT SoftwareName,
SUM( CASE Country WHEN 'Canada' THEN [Count] ELSE 0 END ) AS Canada,
SUM( CASE Country WHEN 'USA' THEN [Count] ELSE 0 END ) AS USA,
SUM( [Count] ) AS Total
FROM [Table]
GROUP BY SoftwareName;
``` | OK...Here's how to do it using PIVOT:
```
SELECT Softwarename, Canada, USA, Canada + USA As TOTAL from SoftwareDemo
PIVOT
(
SUM([Count])
FOR Country
IN (Canada, USA)
) AS x
Softwarename Canada USA TOTAL
--------------------------------------... | Summarize aggregated data | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
All,
I'm working on a SharePoint project, but this isn't a SharePoint-specific question per-se. I have an assembly I've deployed to a SharePoint farm, and I'd like to verify whether my "newest version" is sitting in the GAC, or if an older version from late yesterday is sitting there instead. This is a test farm, so y... | Assembly Version is the intended mechanism for this, but you could roll your own by comparing an MD5 hash of the GAC assembly with the MD5 of your latest version. | You could use AssemblyFileVersion attribute. From the docs, the AssemblyFileVersion
*Instructs a complier to use a specific version number for the Win32 file version resource. The Win32 file version is not required to be the same as the assembly's version number.* | How can I check my .NET assembly for freshness? | [
"",
"c#",
".net",
"sharepoint",
"clr",
""
] |
When you create an instance of a class with the `new` operator, memory gets allocated on the heap. When you create an instance of a struct with the `new` operator where does the memory get allocated, on the heap or on the stack ? | Okay, let's see if I can make this any clearer.
Firstly, Ash is right: the question is *not* about where value type *variables* are allocated. That's a different question - and one to which the answer isn't just "on the stack". It's more complicated than that (and made even more complicated by C# 2). I have an [articl... | The memory containing a struct's fields can be allocated on either the stack or the heap depending on the circumstances. If the struct-type variable is a local variable or parameter that is not captured by some anonymous delegate or iterator class, then it will be allocated on the stack. If the variable is part of some... | Does using "new" on a struct allocate it on the heap or stack? | [
"",
"c#",
".net",
"memory-management",
""
] |
Suppose I have a "tags" table with two columns: **tagid** and **contentid**. Each row represents a tag assigned to a piece of content. I want a query that will give me the contentid of every piece of content which is tagged with tagids 334, 338, and 342.
The "easy" way to do this would be (*pseudocode*):
```
select c... | ```
SELECT contentID
FROM tags
WHERE tagID in (334, 338, 342)
GROUP BY contentID
HAVING COUNT(DISTINCT tagID) = 3
--In general
SELECT contentID
FROM tags
WHERE tagID in (...) --taglist
GROUP BY contentID
HAVING COUNT(DISTINCT tagID) = ... --tagcount
``` | Here's a solution that has worked much faster than the for me on a very large database of objects and tags. This is an example for a three-tag intersection. It just chains many joins on the object-tag table (`objtags`) to indicate the same object and stipulates the tag IDs in the `WHERE` clause:
```
SELECT w0.objid
F... | SQL query: Simulating an "AND" over several rows instead of sub-querying | [
"",
"sql",
"join",
""
] |
I would like to implement a command line interface for a Java application. This wouldn't be too difficult to do, except I would like the command line program to affect the state of another Java GUI program. So for example, I could type:
```
java CliMain arg1 arg2
```
And another running GUI instance would perform an ... | You could have the GUI application listen on a TCP port (on the `localhost` interface) and the CLI application would connect to it.
One way to do this would be to use REST over HTTP. | Another way is through JMX. It gives you a lot of stuff "for free" (in the simple case you just implement a bean and register it -- very simple), and is particularly well suited to this task. | Java IPC: GUI and Command Line | [
"",
"java",
"ipc",
""
] |
What's an easy to use SNMP client library for c++? | Probably the best choice is [net-snmp](http://www.net-snmp.org/). Note that the library has "C" linkage but will work just fine with C++. | SNMP++ is also a nice and open source library for C++ developers.
<http://www.agentpp.com/api/cpp/snmp_pp.html> | Easy to use SNMP client library for c++? | [
"",
"c++",
"snmp",
""
] |
I am working with a set of data that looks something like the following.
> ```
> StudentName | AssignmentName | Grade
> ---------------------------------------
> StudentA | Assignment 1 | 100
> StudentA | Assignment 2 | 80
> StudentA | Total | 180
> StudentB | Assignment 1 | 100
> Stud... | I know you said no dynamic `SQL`, but I don't see any way to do it in straight `SQL`.
If you check out my answers to similar problems at [Pivot Table and Concatenate Columns](https://stackoverflow.com/questions/159456/pivot-table-and-concatenate-columns-sql-problem#159803) and [PIVOT in sql 2005](https://stackoverflow... | To `PIVOT` this data using dynamic sql you can use the following code in SQL Server 2005+:
**Create Table:**
```
CREATE TABLE yourtable
([StudentName] varchar(8), [AssignmentName] varchar(12), [Grade] int)
;
INSERT INTO yourtable
([StudentName], [AssignmentName], [Grade])
VALUES
('StudentA', 'Assignment ... | SQL Server 2005 Pivot on Unknown Number of Columns | [
"",
"sql",
"sql-server",
"pivot",
""
] |
I have been trying to make a case for using Python at my work. We use C# and ASP.NET for basically all of our development. 80% or more of our projects are web applications. It seems natural that we would look at some of the nice dynamic web languages (Ruby, Python, etc), and with things like [IronRuby](http://en.wikipe... | "Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?"
Nope.
Nothing succeeds like success. Use Python. Be successful. Make people jealous.
When asked why you're successful, you can talk about Python. Not before.
Choose projects wisely: things wh... | Almost no problem **requires** a specific programming language, that's just not how things work.
The easiest way to get a new language into an environment like yours is to start a new work project in your own time in the new language. Make it do something you need doing, and write it on your own time. Use it yourself,... | I need a really good reason to use Python | [
"",
"python",
""
] |
I just want to know how to validate (or clean) user input in ASP.NET MVC so that an HttpRequestValidationException will not be thrown regardless of the values submitted. For example, with a text input, if the user inputs `<BR/>`, it will cause an exception and the Yellow Screen of Death will be shown. I don't want that... | With the latest version of ASP.NET MVC (the RC, at the time of writing this) you can just put an attribute on either your controller class or your action method, e.g.:
```
[ValidateInput(false)]
public ActionResult create()
{
// ...method body
}
```
The ValidateInputAttribute is in System.Web.Mvc.
But as others ... | In ASP MVC 3 you can use the `[AllowHtml]` attribute on individual fields/properties in your Model/ViewModel to turn off validation for just that field, which is pretty nice. I will add this attribute to certain fields in my model, and then use the excellent [AntiXSS](http://wpl.codeplex.com/) library (also available v... | How to avoid HttpRequestValidationException in ASP.NET MVC rendering the same view which caused the exception | [
"",
"c#",
".net",
"asp.net",
"asp.net-mvc",
"vb.net",
""
] |
I want to convert an XML document containing many elements within a node (around 150) into another XML document with a slightly different schema but mostly with the same element names. Now do I have to manually map each element/node between the 2 documents. For that I will have to hardcode 150 lines of mapping and elem... | Use an [XSLT transform](http://www.w3schools.com/xsl/xsl_transformation.asp) instead. You can use the built-in .NET [XslCompiledTransform](http://msdn.microsoft.com/en-us/library/system.xml.xsl.xslcompiledtransform.aspx) to do the transformation. Saves you from having to type out stacks of code. If you don't already kn... | Use an XSLT transformation to translate your old xml document into the new format. | Converting one XML document into another XML document | [
"",
"c#",
"xml",
"linq",
".net-3.5",
""
] |
I'm sure there are a million posts about this out there, but surprisingly I'm having trouble finding something.
I have a simple script where I want to set the onClick handler for an `<A>` link on initialization of the page.
When I run this I **immediately** get a 'foo' alert box where I expected to only get an alert ... | jQuery:
```
$('#foo').click(function() { alert('foo'); });
```
Or if you don't want it to follow the link href:
```
$('#foo').click(function() { alert('foo'); return false; });
``` | Try:
```
document.getElementById("foo").onclick = function (){alert('foo');};
``` | How to change onClick handler dynamically? | [
"",
"javascript",
"function",
""
] |
What is the latest version of the Boost library that is compatible with Microsoft Visual C++ 6? And can you provide a link to download it directly?
The Downloads link at <http://www.boost.org> only gives a download for version 1.36.0, and the documentation for that version lists Visual C++ 7.1 as the lowest version of... | Boost [1.34.1](http://www.boost.org/users/history/version_1_34_1) has been tested with vc6. The old versions are still available. | You can get all older versions from [the boost download page on SourceForge](http://sourceforge.net/project/showfiles.php?group_id=7586&package_id=8041).
The compilers used for regression tests are probably buried somewhere on the boost.org website. | What's the latest version of Boost compatible with VC++6? | [
"",
"c++",
"visual-c++",
"boost",
"visual-c++-6",
""
] |
In C++, what's the generic way to convert any floating point value (float) to [**fixed point**](http://en.wikipedia.org/wiki/Fixed-point_arithmetic) (int, 16:16 or 24:8)?
**EDIT:** For clarification, fixed-point values have two parts to them: an integer part and a fractional part. The integer part can be represented b... | Here you go:
```
// A signed fixed-point 16:16 class
class FixedPoint_16_16
{
short intPart;
unsigned short fracPart;
public:
FixedPoint_16_16(double d)
{
*this = d; // calls operator=
}
FixedPoint_16_16& operator=(double d)
{
intPart = static_cast<short>(d);
... | A cast from float to integer will throw away the fractional portion so if you want to keep that fraction around as fixed point then you just multiply the float before casting it. The below code will not check for overflow mind you.
If you want 16:16
```
double f = 1.2345;
int n;
n=(int)(f*65536);
```
if you want 24... | Converting floating point to fixed point | [
"",
"c++",
"fixed-point",
""
] |
This is a question that's been nagging me for some time. I always thought that C++ should have been designed so that the `delete` operator (without brackets) works even with the `new[]` operator.
In my opinion, writing this:
```
int* p = new int;
```
should be equivalent to allocating an array of 1 element:
```
int... | It's so that the destructors of the individual elements will be called. Yes, for arrays of PODs, there isn't much of a difference, but in C++, you can have arrays of objects with non-trivial destructors.
Now, your question is, why not make `new` and `delete` behave like `new[]` and `delete[]` and get rid of `new[]` an... | Damn, I missed the whole point of question but I will leave my original answer as a sidenote. Why we have `delete[]` is because long time ago we had `delete[cnt]`, even today if you write `delete[9]` or `delete[cnt]`, the compiler just ignores the thing between `[]` but compiles OK. At that time, C++ was first processe... | Why do we even need the "delete[]" operator? | [
"",
"c++",
"arrays",
"memory-management",
"heap-memory",
""
] |
I'm using c#, and have an open tcpip connection receiving data. Is it possible to save the stream to an ms sql server database as I'm receiving it, instead of receiving all the data then saving it all? If the stream could be sent to the database as it's being received, you wouldn't have to keep the entire chunk of data... | Are you writing to the DB as a BLOB, or translating the data in some form, then executing inserts for each row?
Your answer in the comments has me confused. Writing a stream to a BLOB column is vastly different then getting the data then translating it into inserts for separate rows.
Regardless, streaming into a BLOB... | SQL Server 2005 supports HTTP endpoints (without requiring IIS) so one solution would be to create a web service on SQL Server to directly receive the streamed data.
These links explain setting one up:
<http://codebetter.com/blogs/raymond.lewallen/archive/2005/06/23/65089.aspx>
<http://msdn.microsoft.com/en-us/library... | Streaming directly to a database | [
"",
"c#",
".net",
"sql-server",
".net-2.0",
""
] |
How can I calculate the number of work days between two dates in SQL Server?
Monday to Friday and it must be T-SQL. | For workdays, Monday to Friday, you can do it with a single SELECT, like this:
```
DECLARE @StartDate DATETIME
DECLARE @EndDate DATETIME
SET @StartDate = '2008/10/01'
SET @EndDate = '2008/10/31'
SELECT
(DATEDIFF(dd, @StartDate, @EndDate) + 1)
-(DATEDIFF(wk, @StartDate, @EndDate) * 2)
-(CASE WHEN DATENAME(dw, ... | In *[Calculating Work Days](http://www.sqlservercentral.com/articles/Advanced+Querying/calculatingworkdays/1660/)* you can find a good article about this subject, but as you can see it is not that advanced.
```
--Changing current database to the Master database allows function to be shared by everyone.
USE MASTER
GO
-... | Count work days between two dates | [
"",
"sql",
"t-sql",
"date",
""
] |
I have a Django model with a large number of fields and 20000+ table rows. To facilitate human readable URLs and the ability to break down the large list into arbitrary sublists, I would like to have a URL that looks like this:
```
/browse/<name1>/<value1>/<name2>/<value2>/ .... etc ....
```
where 'name' maps to a mo... | A possibility that you might consider is matching the entire string of possible values within the url pattern portion and pull out the specific pieces within your view. As an example:
```
urlpatterns = patterns('',
url(r'^browse/(?P<match>.+)/$', 'app.views.view', name='model_browse'),
)
def view(request, match):... | I agree with Adam, but I think the pattern in urls.py should be:
```
... r'^browse/(?P<match>.+)/$' ...
```
The '\w' will only match 'word' characters, but the '.' will match anything. | Django: Arbitrary number of unnamed urls.py parameters | [
"",
"python",
"django",
"django-urls",
""
] |
I'm using `$.post()` to call a servlet using Ajax and then using the resulting HTML fragment to replace a `div` element in the user's current page. However, if the session times out, the server sends a redirect directive to send the user to the login page. In this case, jQuery is replacing the `div` element with the co... | The solution that was eventually implemented was to use a wrapper for the callback function of the Ajax call and in this wrapper check for the existence of a specific element on the returned HTML chunk. If the element was found then the wrapper executed a redirection. If not, the wrapper forwarded the call to the actua... | I read this question and implemented the approach that has been stated regarding setting the response *HTTP status code* to 278 in order to avoid the browser transparently handling the redirects. Even though this worked, I was a little dissatisfied as it is a bit of a hack.
After more digging around, I ditched this ap... | How to manage a redirect request after a jQuery Ajax call | [
"",
"javascript",
"jquery",
"ajax",
"redirect",
""
] |
In the (otherwise) excellent book [C++ Coding Standards](http://www.gotw.ca/publications/c++cs.htm), Item 44, titled **"Prefer writing nonmember nonfriend functions"**, Sutter and Alexandrescu recommend that only functions that really need access to the members of a class be themselves members of that class. All other ... | I'm going to have to disagree with Sutter and Alexandrescu on this one. I think if the behavior of function `foo()` falls within the realm of class `Bar`'s responsibilities, then `foo()` should be part of `bar()`.
The fact that `foo()` doesn't need direct access to `Bar`'s member data doesn't mean it isn't conceptuall... | Scott Meyers has a similar opinion to Sutter, see [here](http://www.ddj.com/cpp/184401197).
He also clearly states the following:
*"Based on his work with various string-like classes, Jack Reeves has observed that some functions just don't "feel" right when made non-members, even if they could be non-friend non-membe... | Class design vs. IDE: Are nonmember nonfriend functions really worth it? | [
"",
"c++",
"ide",
"function",
"class-design",
"friend",
""
] |
I have this function in my Javascript Code that updates html fields with their new values whenever it is called. The problem cannot be with the function itself because it works brilliantly in every section except for one. Here is the JS function:
```
function updateFields() {
document.getElementById('bf').innerH... | I'm curious, is it possible that there are actually 2 elements with an id of "cost"? That could, by updating the first one it finds, cause this issue. Different browsers may have different ways of implementing document.getElementById() so you might get even more inconsistent results with different browsers if this is t... | My experience with getElementById has been mixed at best, and that's most likely your issue. Probably some sort of browser DOM bug where you've got two items with the same ID, or something like that.
I use [Prototype](http://www.prototypejs.org) which lets you avoid ambiguities and finicky browsers with a simple call:... | Inconsistent JavaScript Function Results | [
"",
"javascript",
"html",
""
] |
I'm using SimpleDateFormat with the pattern `EEE MM/dd hh:mma`, passing in the date String `Thu 10/9 08:15PM` and it's throwing an Unparseable date exception. Why? I've used various patterns with `SimpleDateFormat` before so I'm fairly familiar with its usage. Maybe I'm missing something obvious from staring at it too ... | To test if it's the date format, write a test class to prove it out. For these types of things, I like to use bsh (beanshell). Here was my test:
```
sdf = new java.text.SimpleDateFormat("EEE MM/dd hh:mma");
System.out.println(sdf.format(sdf.parse("Thu 10/9 08:15PM")));
```
Which outputted: Fri 10/09 08:15PM
So, at l... | First question here on StackOverFlow so I'm not sure what the proper way to mark this resolved is. Most of the answers are in the comments of Eric's answer.
The root cause was a 'space' character in the date string that was not recognized as such. It was a hex char of 'A0', which is a non-breaking space. I ended up co... | why does parsing this date string throw an unparseable date exception? | [
"",
"java",
"date",
""
] |
I am working on a business problem in C#.NET. I have two classes, named C and W that will be instantiated independently at different times.
An object of class C needs to contain references to 0 ... n objects of class W, i.e. a C object can contain up to n W objects.
Each W object needs to contain a reference to exact... | If you have the Martin Fowler's Refactoring book, just follow the "Change Unidirectional Association to Bidirectional" refactoring.
In case you don't have it, here's how your classes will look like after the refactoring:
```
class C
{
// Don't to expose this publicly so that
// no one can get behind your back an... | I generally do it something like this:
```
class C
{
private List<W> _contents = new List<W>();
public IEnumerable<W> Contents
{
get { return _contents; }
}
public void Add(W item)
{
item.C = this;
_contents.Add(item);
}
}
```
Thus, your Contents property is readonly and you ad... | What is a good design pattern in C# for classes that need to reference other classes? | [
"",
"c#",
".net",
"class",
"reference",
"class-design",
""
] |
I have some tables that I build as a part of my report rollup. I don't need them afterwards at all. Someone mentioned to truncate them as it would be faster. | Deleting records from a table logs every deletion and executes delete triggers for the records deleted. Truncate is a more powerful command that empties a table without logging each row. SQL Server prevents you from truncating a table with foreign keys referencing it, because of the need to check the foreign keys on ea... | DROP TABLE deletes the table.
TRUNCATE TABLE empties it, but leaves its structure for future data. | Difference between drop table and truncate table? | [
"",
"sql",
"sql-server",
"sybase",
""
] |
For example, how much memory is required to store a list of one million (32-bit) integers?
```
alist = range(1000000) # or list(range(1000000)) in Python 3.0
``` | Useful links:
[How to get memory size/usage of python object](http://bytes.com/forum/thread757255.html)
[Memory sizes of python objects?](http://mail.python.org/pipermail/python-list/2002-March/135223.html)
[if you put data into dictionary, how do we calculate the data size?](http://groups.google.com/group/comp.lang... | "It depends." Python allocates space for lists in such a way as to achieve [amortized constant time](http://effbot.org/zone/python-list.htm) for appending elements to the list.
In practice, what this means with the current implementation is... the list always has space allocated for a power-of-two number of elements. ... | How many bytes per element are there in a Python list (tuple)? | [
"",
"python",
"memory-management",
""
] |
How can you programmatically tell an HTML `select` to drop down (for example, due to mouseover)? | You can't do this with a HTML select tag, but you can do it with JavaScript *and* HTML. There are variety of existing controls that do this - for instance, the "suggest" list attached to the SO "interesting/ignored tag" entry, or Gmail's lookup for email adresses.
There are many JavaScript+HTML controls that provide t... | *This used to actually be possible with HTML+Javascript, despite everywhere else people say it is not, but it was deprecated later on and does not work now.*
**However, this only worked in Chrome. Read more if you're interested.**
---
According to [W3C Working Draft for HTML5, Section 3.2.5.1.7. Interactive Content]... | How can you programmatically tell an HTML SELECT to drop down (for example, due to mouseover)? | [
"",
"javascript",
"html",
""
] |
My Program overrides `public void paint(Graphics g, int x, int y);` in order to draw some stings using `g.drawString(someString, x+10, y+30);`
Now someString can be quite long and thus, it may not fit on one line.
What is the best way to write the text on multiple line.
For instance, in a rectangle (x1, y1, x2, y2... | Thanks to Epaga's hint and a couple of examples on the Net (not so obvious to find! I used mainly [Break a Line for text layout](http://www.roseindia.net/java/example/java/swing/graphics2D/line-break-text-layout.shtml "Break a Line for text layout")), I could make a component to display wrapped text. It is incomplete, ... | [java.awt.font.TextLayout](http://java.sun.com/j2se/1.4.2/docs/api/java/awt/font/TextLayout.html) might be helpful. Here's a snippet of their example code:
```
Graphics2D g = ...;
Point2D loc = ...;
Font font = Font.getFont("Helvetica-bold-italic");
FontRenderContext frc = g.getFontRenderContext();
Text... | How to output a String on multiple lines using Graphics | [
"",
"java",
"string",
"graphics",
""
] |
Languages like C and even C# (which technically doesn't have a preprocessor) allow you to write code like:
```
#DEFINE DEBUG
...
string returnedStr = this.SomeFoo();
#if DEBUG
Debug.WriteLine("returned string =" + returnedStr);
#endif
```
This is something I like to use in my code as a form of scaffolding, and I... | PHP doesn't have anything like this. but you could definitely whip up something quickly (and perhaps a regex parse to strip it out later if you wanted). i'd do it as such:
```
define('DEBUG', true);
...
if (DEBUG):
$debug->writeLine("stuff");
endif;
```
of course you'd have to write your own debug module to handle ... | xdump is one of my personal favorites for debugging.
<http://freshmeat.net/projects/xdump/>
```
define(DEBUG, true);
[...]
if(DEBUG) echo xdump::dump($debugOut);
``` | Does PHP have a DEBUG symbol that can be used in code? | [
"",
"php",
"debugging",
""
] |
When loading XML into an XmlDocument, i.e.
```
XmlDocument document = new XmlDocument();
document.LoadXml(xmlData);
```
is there any way to stop the process from replacing entities? I've got a strange problem where I've got a TM symbol (stored as the entity #8482) in the xml being converted into the TM character. As ... | This is a standard misunderstanding of the XML toolset. The whole business with "&#x", is a syntactic feature designed to cope with character encodings. Your XmlDocument isn't a stream of characters - it has been freed of character encoding issues - instead it contains an abstract model of XML type data. Words for this... | What are you writing it to? A TextWriter? a Stream? what?
The following keeps the entity (well, it replaces it with the hex equivalent) - but if you do the same with a StringWriter it detects the unicode and uses that instead:
```
XmlDocument doc = new XmlDocument();
doc.LoadXml(@"<xml>™</xml>");
us... | .NET XmlDocument LoadXML and Entities | [
"",
"c#",
"xml",
"entity",
""
] |
Is there any way instead of a JS hack where I can post from an iframe to another page outside the iframe?
the iframe is posting data to a 3rd party and then just responding back with a URL which is the redirection URl thus we cannot set the form target. We are PCI compliant and thus we cannot use `window.parent.locati... | What it boils down to, it seems, is this:
1. You get a text url from a 3rd party in the iframe.
2. You want to **change your page's location** to that url.
3. Unless you have control over that 3rd party, all you are going to get is that text url.
Now, the only way to **change your page's location** automatically... | `<form>` accepts a target parameter, e.g. target="\_parent" | Is there any way instead of a JS hack where I can post from an iframe to another page outside the iframe? | [
"",
"javascript",
"iframe",
"post",
"parent",
"pci-dss",
""
] |
I'm writing a command line tool to help my web app. It needs a password to connect to the service. I'd like the script to show a password prompt so I don't have to pass it as a command line argument.
That's easy enough, but I'd like it to not echo the password to the screen as it's typed. How can I do this with PHP?
... | Found on [sitepoint](http://www.sitepoint.com/blogs/2009/05/01/interactive-cli-password-prompt-in-php/).
```
function prompt_silent($prompt = "Enter Password:") {
if (preg_match('/^win/i', PHP_OS)) {
$vbscript = sys_get_temp_dir() . 'prompt_password.vbs';
file_put_contents(
$vbscript, 'wscript.echo(Inp... | Depending on your environment (i.e., not on Windows), you can use the ncurses library (specifically, the [ncurses\_noecho()](http://us.php.net/manual/en/function.ncurses-noecho.php) function to stop keyboard echo and [ncurses\_getch()](http://us.php.net/manual/en/function.ncurses-getch.php) to read the input) to get th... | Command Line Password Prompt in PHP | [
"",
"php",
"passwords",
""
] |
I have this:
```
public string Log
{
get { return log; }
protected set
{
if (log != value)
{
MarkModified(PropertyNames.Log, log);
log = value;
}
}
}
```
And my util... | An alternative to the suggested changes to ReflectionHelper in other answers is to call `pi.GetSetMethod(false)` and see if the result is null. | You need to use the [BindingFlags](http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx). Something like
```
PropertyInfo property = type.GetProperty("MyProperty", BindingFlags.Public | BindingFlags.SetProperty | BindingFlags.Instance);
``` | How do I tell if a class property has a public set (.NET)? | [
"",
"c#",
".net",
"data-binding",
"reflection",
""
] |
I'm a fan of extension methods in C#, but haven't had any success adding an extension method to a static class, such as `Console`.
For example, if I want to add an extension to `Console`, called '`WriteBlueLine`', so that I can go:
```
Console.WriteBlueLine("This text is blue");
```
I tried this by adding a local, p... | No. Extension methods require an instance variable (value) for an object. You can however, write a static wrapper around the `ConfigurationManager` interface. If you implement the wrapper, you don't need an extension method since you can just add the method directly.
```
public static class ConfigurationManagerWrappe... | Can you add static extensions to classes in C#? No but you can do this:
```
public static class Extensions
{
public static T Create<T>(this T @this)
where T : class, new()
{
return Utility<T>.Create();
}
}
public static class Utility<T>
where T : class, new()
{
static Utility()
... | Can I add extension methods to an existing static class? | [
"",
"c#",
"static",
"extension-methods",
""
] |
Which of these pieces of code is faster?
```
if (obj is ClassA) {}
if (obj.GetType() == typeof(ClassA)) {}
```
Edit:
I'm aware that they don't do the same thing. | [This should answer that question, and then some.](https://learn.microsoft.com/en-us/archive/blogs/vancem/drilling-into-net-runtime-microbenchmarks-typeof-optimizations)
The second line, `if (obj.GetType() == typeof(ClassA)) {}`, is faster, for those that don't want to read the article.
*(Be aware that they don't do ... | Does it matter which is faster, if they don't do the same thing? Comparing the performance of statements with different meaning seems like a bad idea.
`is` tells you if the object implements `ClassA` anywhere in its type heirarchy. `GetType()` tells you about the most-derived type.
Not the same thing. | Which is faster between is and typeof | [
"",
"c#",
"rtti",
""
] |
Is it possible to add an image overlay to a google map that scales as the user zooms?
My current code works like this:
```
var map = new GMap2(document.getElementById("gMap"));
var customIcon = new GIcon();
customIcon.iconSize = new GSize(100, 100);
customIcon.image = "/images/image.png";
map.addOverlay(new GMarker... | Well after messing around trying to scale it myself for a little bit I found a helper called [EInserts](http://econym.org.uk/gmap/einsert.htm) which I'm going to check out.
Addition:
Okay EInserts is about the coolest thing ever.
It even has a method to allow you to drag the image and place it in development mode for... | There is a zoomend event, fired when the map reaches a new zoom level. The event handler receives the previous and the new zoom level as arguments.
<http://code.google.com/apis/maps/documentation/reference.html#Events_GMap> | Scalable google maps overlay | [
"",
"javascript",
"google-maps",
""
] |
I recently migrated a website to a new CMS (Umbraco). A lot of the links have changed, but they can be easily corrected by searching for patters in the url, so I would like to write something that will redirect to the correct page if the old one is not found. That part isn't a problem.
How can I obtain the requested U... | I do basically the same thing you ask in a custom 404 error handling page. On IIS 6 the original URL is in the query string. The code below shows how to grab the original URL and then forward the user. In my case I switched from old ASP to new ASP.NET, so all the .asp pages had to be forwarded to .aspx pages. Also, som... | How about:
```
Request.ServerVariables("HTTP_REFERER");
``` | 404 page that displays requested page | [
"",
"c#",
"asp.net",
"vb.net",
"asp-classic",
"umbraco",
""
] |
If I have variable of type `IEnumerable<List<string>>` is there a LINQ statement or lambda expression I can apply to it which will combine the lists returning an `IEnumerable<string>`? | SelectMany - i.e.
```
IEnumerable<List<string>> someList = ...;
IEnumerable<string> all = someList.SelectMany(x => x);
```
For each item in someList, this then uses the lambda "x => x" to get an IEnumerable<T> for the inner items. In this case, each "x" is a List<T>, which is already IEnumerable<T>.
... | How about
```
myStrings.SelectMany(x => x)
``` | Combining Lists in Lambda/LINQ | [
"",
"c#",
".net",
"linq",
"lambda",
""
] |
I have a script to extract certain data from a much bigger table, with one field in particular changing regularly, e.g.
```
SELECT CASE @Flag WHEN 1 THEN t.field1 WHEN 2 THEN t.field2 WHEN 3
THEN t.field3 END as field,
...[A bunch of other fields]
FROM table t
```
However, the issue is now I want to do... | A simpler solution, and one suggested by a workmate:
```
SELECT CASE @Flag WHEN 1 THEN t.field1 WHEN 2 THEN t.field2 WHEN 3
THEN t.field3 END as field,
[A bunch of other fields],
@Flag as flag
FROM table t
```
Then base the decision making on the last field. A lot simpler, and probably should have occurred ... | I think you need to pull `@Flag` out of the query altogether, and use it to decide which of three separate SELECT statements to run. | Select from different tables via SQL depending on flag | [
"",
"sql",
"sql-server",
"sql-server-2005",
"t-sql",
""
] |
I was browsing the [Hidden Features of C#](https://stackoverflow.com/questions/9033/hidden-features-of-c) question and thought I would try out one of the features I was unfamiliar with. Unfortunately I use Visual Studio 2005 and the feature in question was introduced later. Is there a good list for new features in C# 3... | This is not a comprehensive list but these are some of my favorite new features of C# 3.0:
New type initializers. Instead of saying this:
```
Person person = new Person();
person.Name = "John Smith";
```
I can say this:
```
Person person = new Person() { Name = "John Smith" };
```
Similarly, instead of adding item... | A couple features I like:
* VS 2008 supports targeting various version of the .NET framework so you can target 2.0, 3.0 or 3.5
* Automatic properties are nice.
For example:
```
public int Id { get; set; }
```
instead of:
```
private int _id;
public int Id {
get { return _id; }
set { _id = value; }
}
``` | What is new in Visual Studio 2008 vs 2005 or C# 3.0 vs C# 2.0? | [
"",
"c#",
"visual-studio-2008",
"visual-studio-2005",
".net-2.0",
".net-3.0",
""
] |
I have a large xml document that needs to be processed 100 records at a time
It is being done within a Windows Service written in c#.
The structure is as follows :
```
<docket xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="docket.xsd">
<order>
<Date>2008-10-13</Date>... | Another naive solution; this time for .NET 2.0. It should give you an idea of how to go about what you want. Uses Xpath expressions instead of Linq to XML. Chunks a 100 order docket into 10 dockets in under a second on my devbox.
```
public List<XmlDocument> ChunkDocket(XmlDocument docket, int chunkSize)
{
... | Naive, iterative, but works [EDIT: in .NET 3.5 only]
```
public List<XDocument> ChunkDocket(XDocument docket, int chunkSize)
{
var newDockets = new List<XDocument>();
var d = new XDocument(docket);
var orders = d.Root.Elements("order");
XDocument newDocket = null;
do
... | split xml document into chunks | [
"",
"c#",
"xml",
".net-2.0",
""
] |
Is there a pure-Java equivalent to <jsp:forward page="..." /> that I can use within a <% ... %> block?
For example, I currently have a JSP page something like this:
```
<%
String errorMessage = SomeClass.getInstance().doSomething();
if (errorMessage != null) {
session.setAttribute("error", errorMessag... | The `someObject` you are looking for is [pageContext](http://java.sun.com/products/jsp/2.1/docs/jsp-2_1-pfd2/javax/servlet/jsp/PageContext.html#forward(java.lang.String)).
This object is implicitly defined in JSP, so you can use it like this:
```
pageContext.forward("<some relative jsp>");
``` | You really should try and avoid scriplets if you can, and in your case, a lot of what you are doing can be replaced with JSTL code. The following replacement for your example is much cleaner, IMO:
```
<%
// Consider moving to a servlet or controller/action class
String errorMessage = SomeClass.getInstance().doSome... | jsp:forward in Java without using JSP tag? | [
"",
"java",
"jsp",
"jsp-tags",
"forward",
""
] |
which would you recommend?
which is faster, reliable?
apache mod\_python or nginx/lighttpd FastCGI? | I've done both, and Apache/mod\_python tended to be easier to work with and more stable. But these days I've jumped over to Apache/mod\_wsgi, which is everything I've ever wanted and more:
* Easy management of daemon processes.
* As a result, **much** better process isolation (running multiple sites in the same Apache... | lighttpd with FastCGI will be nominally faster, but really the time it takes to run your python code and any database hits it does is going to absolutely dwarf any performance benefit you get between web servers.
mod\_python and apache will give you a bit more flexibility feature-wise if you want to write code outside... | Running Django with FastCGI or with mod_python | [
"",
"python",
"django",
"apache",
"fastcgi",
""
] |
I've been using virtualenv lately while developing in python. I like the idea of a segregated development environment using the **--no-site-packages** option, but doing this while developing a PyGTK app can be a bit tricky.
The PyGTK modules are installed on Ubuntu by default, and I would like to make a virtualenv (wit... | ```
$ virtualenv --no-site-packages --python=/usr/bin/python2.6 myvirtualenv
$ cd myvirtualenv
$ source bin/activate
$ cd lib/python2.6/
$ ln -s /usr/lib/pymodules/python2.6/gtk-2.0/
$ ln -s /usr/lib/pymodules/python2.6/pygtk.pth
$ ln -s /usr/lib/pymodules/python2.6/pygtk.py
$ ln -s /usr/lib/pymodules/python2.6/cair... | One way is to add the paths to your code using sys.path.
```
import sys
sys.path.append(somepath)
```
Another way is to use site, which processes .pth files in addition to adding to sys.path.
```
import site
site.addsitedir(sitedir, known_paths=None)
```
<https://docs.python.org/library/site.html>
But you probab... | Virtualenv on Ubuntu with no site-packages | [
"",
"python",
"ubuntu",
"pygtk",
"virtualenv",
""
] |
How can I check the version of my script against an online file to see if it's the latest version?
*For clarification, I'm talking about a script I wrote, not the version of PHP. I'd like to incorporate a way for the end user to tell when I've updated the script.* | To specify the second (more simple) solution [phjr](https://stackoverflow.com/questions/236070/php-version-checking#236098) proposed:
Have a file `version.txt` on your own public server and include the following function into your deployed project/script:
```
define('REMOTE_VERSION', 'http://your.public.server/versio... | Per comments on [this answer](https://stackoverflow.com/questions/236070/php-version-checking#236084)
```
// Substitue path to script with the version information in place of __FILE__ if necessary
$script = file_get_contents(__FILE__);
$version = SOME_SENSIBLE_DEFAULT_IN_CASE_OF_FAILURE;
if(preg_match('/<!-- Script ve... | PHP Script Version Checking/Notification | [
"",
"php",
""
] |
Why do some sites (or advertisers that give clients javascript code) employ a technique of splitting the `<script>` and/or `</script>` tags up within `document.write()` calls?
I noticed that Amazon does this as well, for example:
```
<script type='text/javascript'>
if (typeof window['jQuery'] == 'undefined') docume... | `</script>` has to be broken up because otherwise it would end the enclosing `<script></script>` block too early. Really it should be split between the `<` and the `/`, because a script block is supposed (according to SGML) to be [terminated by any end-tag open (ETAGO) sequence (i.e. `</`)](http://www.w3.org/TR/html4/t... | Here's another variation I've used when wanting to generate a script tag inline (so it executes immediately) without needing any form of escapes:
```
<script>
var script = document.createElement('script');
script.src = '/path/to/script.js';
document.write(script.outerHTML);
</script>
```
(Note: contrary t... | Why split the <script> tag when writing it with document.write()? | [
"",
"javascript",
"html",
""
] |
I like to generate a thread dump programmatically. I've learned that there a basically two ways to do it:
1. Use the "Java Virtual Machine Tool Interface" JVM-TI
2. Use the higher abstracted "Java Debugger Interface" JDI
For the JVM-TI I was able to find some useful information, but I would have to write a JNI-DLL wh... | Did you consider the remote alternative ? I.e. [VisualVM](http://java.sun.com/javase/6/docs/technotes/guides/visualvm/applications_local.html)

[jps and jstack](http://wiki.caucho.com/Thread_dump) are also useful tools included in JDK 5, providing a quic... | There is a third way: Thread.getAllStackTraces()
<http://java.sun.com/javase/6/docs/api/java/lang/Thread.html#getAllStackTraces()>
This is much easier than the debugger interface... | Thread dump programmatically /JDI (Java Debugger Interface) | [
"",
"java",
"debugging",
"thread-dump",
""
] |
I have a table that has a `processed_timestamp` column -- if a record has been processed then that field contains the datetime it was processed, otherwise it is null.
I want to write a query that returns two rows:
```
NULL xx -- count of records with null timestamps
NOT NULL yy -- count of records with non-... | Oracle:
group by nvl2(field, 'NOT NULL', 'NULL') | In MySQL you could do something like
```
SELECT
IF(ISNULL(processed_timestamp), 'NULL', 'NOT NULL') as myfield,
COUNT(*)
FROM mytable
GROUP BY myfield
``` | How do I return my records grouped by NULL and NOT NULL? | [
"",
"sql",
"null",
"group-by",
""
] |
Is there such a thing as too many stored procedures?
I know there is not a limit to the number you can have but is this any performance or architectural reason not to create hundreds, thousands?? | To me the biggest limitation to that hundreds or thousands store procedure is maintainability. Even though that is not a direct performance hit, it should be a consideration. That is an architectural stand point, you have to plan not just for the initial development of the application, but future changes and maintenanc... | Yes you can.
[If you have more than zero, you have too many](https://stackoverflow.com/questions/15142/what-are-the-pros-and-cons-to-keeping-sql-in-stored-procs-versus-code#15153) | Can you have too many stored procedures? | [
"",
"sql",
"database-design",
""
] |
i got a client side javascript function which is triggered on a button click (basically, its a calculator!!). Sometimes, due to enormous data on the page, the javascript calculator function take to long & makes the page appear inactive to the user. I was planning to display a transparent div over entire page, maybe wit... | Javacript to show a curtain:
```
function CalculateAmountOnClick () {
var curtain = document.body.appendChild( document.createElement('div') );
curtain.id = "curtain";
curtain.onkeypress = curtain.onclick = function(){ return false; }
try {
// your operations
}
finally {
curtain.parentNode.removeCh... | I'm going to make some heavy assumptions here, but it sounds to me what is happening is that because you are directly locking the browser up with intense processing immediately after having set up the curtain element, the browser never has a chance to draw the curtain.
The browser doesn't redraw every time you update ... | Javascript - loading/busy indicator or transparent div over page on event click | [
"",
"javascript",
"css",
""
] |
I need to create some windows service which will execute every N period of time.
The question is:
Which timer control should I use: `System.Timers.Timer` or `System.Threading.Timer` one? Does it influence on something?
I am asking because I heard many evidences to non correct work of `System.Timers.Timer` in windo... | Both [`System.Timers.Timer`](http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx) and [`System.Threading.Timer`](http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx) will work for services.
The timers you want to avoid are [`System.Web.UI.Timer`](http://msdn.microsoft.com/en-us/library/sys... | Don't use a service for this. Create a normal application and create a scheduled task to run it.
This is the commonly held best practice. [Jon Galloway agrees with me. Or maybe its the other way around.](http://weblogs.asp.net/jgalloway/archive/2005/10/24/428303.aspx) Either way, the fact is that it is not best practi... | Best Timer for using in a Windows service | [
"",
"c#",
"timer",
"windows-services",
""
] |
I'd like to check ancestry using two jQuery objects. They don't have IDs, and are only going to be available as jQuery objects (or DOM nodes if you called `get()`). jQuery's `is()` only works with expressions, so this code would be ideal but will not work:
```
var someDiv = $('#div');
$('a').click(function() {
if... | You can use the index() method to check if an element exists in a list, so would the following work?
```
var someDiv = $('#div');
$('a').click(function() {
if ($(this).parents().index(someDiv) >= 0) {
alert('boo');
}
}
```
From [#index reference](http://docs.jquery.com/Core/index#subject). | Checking for `(this).parents().index(someDiv) >= 0`, as @Gareth suggests, will work just fine.
However, using the [jQuery ancestry plugin](http://plugins.jquery.com/project/ancestry) is **way faster / more efficient**. | jQuery ancestors using jQuery objects | [
"",
"javascript",
"jquery",
""
] |
I've recently been trying to create units tests for some legacy code.
I've been taking the approach of using the linker to show me which functions cause link errors, greping the source to find the definition and creating a stub from that.
Is there an easier way?
Is there some kind of C++ parser that can give me class... | You may want to investigate <http://os.inf.tu-dresden.de/vfiasco/related.html#parsing>. But C++ parsing is hard.
On the other hand, maybe ctags or something similar can extract class definitions...
You may also try to write your own simple (?) parser to generate class stubs from header files...
I tried to give you s... | [Gcc XML](http://www.gccxml.org/HTML/Index.html) is used in some projects, such as [automatic FFI for Common Lisp.](http://www.cliki.net/Verrazano)
It ties into the G++ compiler to generate XML representing the source. From there, any XML processing tool could help you reach your goal. | Parsing C++ to generate unit test stubs | [
"",
"c++",
"unit-testing",
"parsing",
"stub",
""
] |
Is there an **efficient** way to create a file with a given size in Java?
In C it can be done with [ftruncate](http://linux.die.net/man/2/ftruncate) (see [that answer](https://stackoverflow.com/questions/139261/how-to-create-a-file-with-a-given-size-in-linux#245239)).
Most people would just write **n** dummy bytes in... | Create a new [RandomAccessFile](https://docs.oracle.com/javase/8/docs/api/java/io/RandomAccessFile.html) and call the setLength method, specifying the desired file length. The underlying JRE implementation should use the most efficient method available in your environment.
The following program
```
import java.io.*;
... | Since Java 8, this method works on Linux and Windows :
```
final ByteBuffer buf = ByteBuffer.allocate(4).putInt(2);
buf.rewind();
final OpenOption[] options = { StandardOpenOption.WRITE, StandardOpenOption.CREATE_NEW , StandardOpenOption.SPARSE };
final Path hugeFile = Paths.get("hugefile.txt");
try (final SeekableB... | Create file with given size in Java | [
"",
"java",
"file",
""
] |
We have a common problem of moving our development SQL 2005 database onto shared web servers at website hosting companies.
Ideally we would like a system that transfers the database structure and data as an exact replica.
This would be commonly achieved by restoring a backup. But because they are shared SQL servers, ... | Scott Gu had written few posts on this topic :
[SQL Server Database Publishing Toolkit for Web Hosting](http://weblogs.asp.net/scottgu/archive/2007/04/19/update-of-sql-server-database-publishing-toolkit-for-web-hosting.aspx) | Generation scripts are fine for creating the database objects, but not for transporting database information. For example, client-specific databases where the developer is required to pre-populate some data.
One of the issues I've run into with this is the new MAX types in SQL Server 2005+. (nvarchar(max), varchar(max... | How do you upload SQL Server databases to shared hosting environments? | [
"",
"sql",
"database",
"upload",
""
] |
Actually [here](https://stackoverflow.com/questions/564/what-is-the-difference-between-an-int-and-an-integer-in-javac) is a similar topic with little practical value.
As far as I understand, primitives perform better and should be used everywhere except for the cases where Object-related features (e.g. `null` check) ar... | Do not forget that, since creating a new wrapper for every boxing occurrence is quite expensive, especially considering it usually being used at a single scope of a method, [Autoboxing](http://chaoticjava.com/posts/autoboxing-tips/) uses a pool of common wrappers.
This is in fact an implementation of the [flyweight de... | Primitives are faster when they are *used*, as objects need to be unboxed before use; thus there is an extra step for the VM to perform. For example, In order perform arithmetic on an Integer, it must first be converted to an int before the arithmetic can be performed.
In many business applications this probably rarel... | When should I use primitives instead of wrapping objects? | [
"",
"java",
"performance",
"object",
"primitive",
""
] |
On large files (~200+ MB), I get the 503 error when I read the stream.
```
ftp = (FtpWebRequest)WebRequest.Create(new Uri(address.AbsoluteUri + @"/" + file.Name));
ftp.Credentials = new NetworkCredential(username, password);
ftp.Method = WebRequestMethods.Ftp.DownloadFile;
response = (FtpWebResponse)ftp.GetResponse()... | Do you receive the 503 after every attempt or only subsequent attempts?
Have you tried setting the disabling KeepAlive?
```
ftp.KeepAlive = false;
```
I would try a more rubust ftp client library, a basic free one can be at [sourceforge](http://sourceforge.net/projects/dotnetftpclient/). | I'd concur that minimizing the number of NetworkCredential objects solves the problem. I experienced this problem and created a single CredentialCache and added each credential once. No more ftp errors. | .Net: FtpWebRequest "(503) Bad sequence of commands" error | [
"",
"c#",
".net",
"ftp",
""
] |
I have a C++ STL set with a custom ordering defined.
The idea was that when items get added to the set, they're naturally ordered as I want them.
However, what I've just realised is that the ordering predicate can change as time goes by.
Presumably, the items in the set will then no longer be in order.
So two quest... | `set` uses the ordering to lookup items. If you would insert N items according to ordering1 and insert an item according to ordering2, the set cannot find out if the item is already in.
It will violate the class invariant that every item is in there only once.
So it *does* harm. | The only safe way to do this with the STL is to create a new set with the changed predicate. For example you could do something like this when you needed to sort the set with a new predicate:
```
std::set<int> newset( oldset.begin(), oldset.end(), NewPred() );
``` | STL sorted set where the conditions of order may change | [
"",
"c++",
"stl",
"set",
""
] |
I need to get the Class of an object at runtime.
For an non-abstract class I could do something like:
```
public class MyNoneAbstract{
public static Class MYNONEABSTRACT_CLASS = new MyNoneAbstract().getClass();
```
But for an abstract class this does NOT work (always gives me `Object`)
```
public abstract class... | You just need
```
MyAbstract.class
```
That expression returns the Class object representing MyAbstract. | The code you want in the abstract case is:
```
public abstract class MyAbstract{
public static Class MYABSTRACT_CLASS = MyAbstract.class;
}
```
although I personally wouldn't bother defining the constant and just used MyAbstract.class throughout.
I would have expected the code you wrote to have returned the clas... | How do you get the Class of an Abstract class (Object) in JavaME? | [
"",
"java",
"java-me",
""
] |
How do I implement the singleton pattern in C#? I want to put my constants and some basic functions in it as I use those everywhere in my project. I want to have them 'Global' and not need to manually bind them every object I create. | If you are just storing some global values and have some methods that don't need state, you don't need singleton. Just make the class and its properties/methods static.
```
public static class GlobalSomething
{
public static int NumberOfSomething { get; set; }
public static string MangleString( string someValue... | Singletons only make sense if **both** of these conditions are true:
1. The object must be **global**
2. There must only ever exist a **single** instance of the object
Note that #2 does not mean that you'd *like* the object to only have a single instance - if thats the case, simply instantiate it only once - it means... | How to implement a singleton in C#? | [
"",
"c#",
".net",
"singleton",
""
] |
I need to be able to lock down the valid characters in a textbox, I presently have a regex which I can check each character against such as
> [A-Za-z]
would lock down to just Alpha characters.
```
protected override void OnKeyPress(KeyPressEventArgs e)
{
if (e.KeyChar == (char)Keys.Back)
{
base.OnKeyPress(e)... | You can use one of the OnKeyPress / OnKeyUp / OkKeyDown events and then use the Char.IsLetter method to check that the entered key is a letter. | [MaskedTextBox](http://msdn.microsoft.com/en-us/library/system.windows.forms.maskedtextbox(VS.80).aspx) may be right for you.
You can also look at the [FilterTextBox](http://www.codeproject.com/KB/miscctrl/FilterTextBox.aspx) over at CodeProjct. You can use it (or the approach described) to do what you intend. The bas... | Locking down valid characters in a Textbox | [
"",
"c#",
".net",
"winforms",
"validation",
"textbox",
""
] |
I have data from MySQL showing all organisations a customer got, with all details of employess in each organisation. I want to list each organisation name only once i.e. in a single cell ( row span) and all employees in that organisation against this name like:
```
Org1 Emp1 Name, Emp1 Phone, Emp1 Address
... | Classic.
Workaround: only display the name if different than the previous one. You can even not bother about the rowspan (you keep an empty cell).
```
$currentOrg = '';
while ($row = mysql_fetch_object($query)) {
if ($row->org != $currentOrg) {
echo "$row->org".
}
$currentorg = $row->org;
}
```
Not th... | ```
// Get the data
$data = mysql_query('SELECT org, emp_name, emp_phone, emp_address FROM x');
// Store it all in a 2D array, keyed by org
$rows = array();
while ($row = mysql_fetch_assoc($data))
{
// Initialise each org to an empty array (not really needed in PHP but I prefer it)
if (empty($rows[$row['org']]... | How do I display mysql data in row span using PHP? | [
"",
"php",
"mysql",
"html",
""
] |
I have got the following problem since the server has safe mode turned on, and directories are being created under different users:
1. I upload my script to the server, it shows as belonging to 'user1'. All it is doing is making a new directory when a new user is created so it can store files in it.
2. New directory i... | I've used this workaround:
instead of php mkdir you can create directories by FTP with proper rights.
```
function FtpMkdir($path, $newDir) {
$path = 'mainwebsite_html/'.$path;
$server='ftp.myserver.com'; // ftp server
$connection = ftp_connect($server); // connection
// login to ftp... | You might be able to turn safe mode off for a specific directory via a .htaccess file (if on Apache).
```
php_value safe_mode = Off
```
You might need to get your hosting provider to make this change for you though in the httpd.conf. | Getting around PHP safe mode to write to server. Is it possible? | [
"",
"php",
"safe-mode",
""
] |
I have 3 classes that are essentially the same but don't implement an interface because they all come from different web services.
e.g.
* Service1.Object1
* Service2.Object1
* Service3.Object1
They all have the same properties and I am writing some code to map them to each other using an intermediary object which im... | Assuming the generated classes are partial, you can create an interface and then add another partial source file to make your generated classes implement the interface. Then you can constrain by interface as normal. No changes to the actual generated code required :) | Constraining to a list of classes in an "OR" fashion like you want to do isn't possible in C#. (In fact, I'm not even sure it's legal directly in IL either.)
Your only option is to keep using the checktypes style functions. If you own the code for the different webservices, you can also implement a "sentinel" interfac... | C# Generics: Can I constrain to a set of classes that don't implement an interface? | [
"",
"c#",
".net",
"generics",
""
] |
How do I take an efficient simple random sample in SQL? The database in question is running MySQL; my table is at least 200,000 rows, and I want a simple random sample of about 10,000.
The "obvious" answer is to:
```
SELECT * FROM table ORDER BY RAND() LIMIT 10000
```
For large tables, that's too slow: it calls `RAN... | There's a very interesting discussion of this type of issue here: [<http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/>](http://www.titov.net/2005/09/21/do-not-use-order-by-rand-or-how-to-get-random-rows-from-table/)
I think with absolutely no assumptions about the table tha... | I think the fastest solution is
```
select * from table where rand() <= .3
```
Here is why I think this should do the job.
* It will create a random number for each row. The number is between 0 and 1
* It evaluates whether to display that row if the number generated is between 0 and .3 (30%).
This assumes that rand... | Simple Random Samples from a MySQL Sql database | [
"",
"mysql",
"sql",
"random",
""
] |
What does the following code do? A link to something in the PHP manual would also be nice.
```
if ($_SERVER['SERVER_PORT'] <> 443) {
doSomething();
}
``` | Same as !=, "Not equal"
```
false <> true // operator will evaluate expression as true
false != true // operator will evaluate expression as true
```
Here is some reference: [PHP Comparison Operators](http://www.php.net/operators.comparison) | It's another way of saying "not equal to" (the `!=` operator). I think of it as the "less than or greater than" operator which really just means "not equal to". | PHP operator <> | [
"",
"php",
"comparison",
"operators",
""
] |
I need some information about localization. I am using .net 2.0 with C# 2.0 which takes care of most of the localization related issues. However, I need to manually draw the alphabets corresponding to the current culture on the screen in one particular screen.
This would be similar to the Contacts screen in Microsoft ... | In native code there's LOCALE\_SSCRIPTS for GetLocaleInfoEx() (Vista & above) that shows you what scripts are expected for a locale. There isn't a similar concept for .Net at this time. | Chinese has thousands of characters, so it might not be feasible to show all the characters in their character set. There's no native concept of 'alphabet' in Chinese, and I don't think Chinese has a syllabary like Japanese does.
Pinyin (Chinese written in roman alphabet) can be used to represent the Chinese character... | Localization: How to map culture info to a script name or Unicode character range? | [
"",
"c#",
"localization",
".net-2.0",
"globalization",
"culture",
""
] |
Has anyone ever seen the storage class `auto` explicitly used in C/C++? If so, in what situation? | auto is never useful in current C/C++ because all variables are implicitly auto. It is useful in C++0x, where it can replace the type declaration entirely - if you have a variable with an initial assignment, 'auto' will just make it the type of that assignment value, as in the comments. | I haven't seen `auto` used in code written in the last 10+ years. There is no reason to use `auto` since the only places you *can* use it is where it is implied anyway. The only reason it still exists is for backwards compatibility but it should be avoided in new code. | Is auto ever useful in C/C++? | [
"",
"c++",
"c",
"syntax",
"keyword",
""
] |
I've always been curious to see if I can show, hide or change a NotifyIcon created by another application via a C# application.
Could someone please post an example on how to do this? :) | To modify icons in the systray, you can use [Shell\_NotifyIcon](http://msdn.microsoft.com/en-us/library/bb762159.aspx) Win32 API ([P/Invoke declaration](http://pinvoke.net/default.aspx/shell32/Shell_NotifyIcon.html)). The icons are associated with a window handle and an id. That means that to modify or hide another pro... | You can hook the SystemTray window itself to intercept all Shell\_NotifyIcon() requests. Then you will know the exact HWNDs and IDs that are registered for each icon. Details can be found via any search engine. | Modify the behaviour of a NotifyIcon with via a 3rd party application | [
"",
"c#",
"winapi",
"notifyicon",
""
] |
When starting a django application using `python manage.py shell`, I get an InteractiveConsole shell - I can use tab completion, etc.
```
Python 2.5.1 (r251:54863, Apr 15 2008, 22:57:26)
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveCo... | I may have found a way to do it.
Create a file .pythonrc
```
# ~/.pythonrc
# enable syntax completion
try:
import readline
except ImportError:
print("Module readline not available.")
else:
import rlcompleter
readline.parse_and_bind("tab: complete")
```
then in your .bashrc file, add
```
export PYTHO... | I think django does something like <https://docs.python.org/library/rlcompleter.html>
If you want to have a really good interactive interpreter have a look at
[IPython](https://ipython.org/). | How do I add tab completion to the Python shell? | [
"",
"python",
"shell",
"interpreter",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.