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 body I want to access the element which caused the event to be fired. I've read somewhere that you can't simply refer to it via 'this', so how can I access it?
|
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 the results will look like this:
```
name id
----------------------
abc NULL
bbb 2
ccc 53
ddd NULL
eee 13
```
The ID isn't really important; what I'm interested in is whether the document has been downloaded (is it NULL or not).
Here is my query:
```
SELECT Documents.name, HasDownloaded.id FROM Documents
LEFT JOIN HasDownloaded ON HasDownloaded.documentID = Documents.id
WHERE HasDownloaded.memberID = @memberID
```
The problem is, this will only return values if an entry exists for the specified user in the HasDownloaded table. I'd like to keep this simple and only have entries in HasDownloaded for documents that *have* been downloaded. So if user 1 has downloaded abc, bbb, and ccc, I still want ddd and eee to show up in the resulting table, just with the id as NULL. But the WHERE clause only gives me values for which entries exists.
I'm not much of a SQL expert - is there an operator that will give me what I want here? Should I be taking a different approach? Or is this impossible?
|
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 otherwise be the WHERE clause.
|
```
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 confuse folks. If you don't understand WHY moving it to the JOIN clause works, then I'd strongly suggest staying away from it.
|
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 interoperability between them.
[Here's](http://dev.eclipse.org/viewcvs/index.cgi/org.eclipse.swt.snippets/src/org/eclipse/swt/snippets/Snippet265.java?view=co) an example of embedding Windows Media Player in an SWT window.
Alternatively there's the [Jacob](http://jacob-project.wiki.sourceforge.net/) project, though I haven't used that myself.
As for "is it worth it?" Well, I can say from experience that SWT makes it relatively easy, but unless your application can gracefully deal with not having them available, by relying on COM components you are losing the ability to run on multiple platforms that makes Java attractive in the first place.
|
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 people who use ActiveX / COM actually understand COM - they just rely on Microsoft's template generation).
If you are just trying to save yourself some typing for some simple DAO objects, you'll probably be better off re-implementing (heck, you could probably take the DTD and write a script to generate Java code for it).
|
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 language, this can
> imply:
>
> * being expressible as an anonymous literal value
> * being storable in variables
> * being storable in data structures
> * having an intrinsic identity (independent of any given name)
> * being comparable for equality with other entities
> * being passable as a parameter to a procedure/function
> * being returnable as the result of a procedure/function
> * being constructible at runtime
> * being printable
> * being readable
> * being transmissible among distributed processes
> * being storable outside running processes
[Source](http://en.wikipedia.org/wiki/First-class_object).
In C++ functions themselves are not first class objects, however:
* You can override the '()' operator making it possible to have an object function, which is first class.
* Function pointers are first class.
* boost bind, lambda and function do offer first class functions
In C++, classes are not first class objects but instances of those classes are. In Python both the classes *and* the objects are first class objects. (See [this answer](https://stackoverflow.com/a/6581949/1612701) for more details about classes as objects).
Here is an example of Javascript first class functions:
```
// f: function that takes a number and returns a number
// deltaX: small positive number
// returns a function that is an approximate derivative of f
function makeDerivative( f, deltaX )
{
var deriv = function(x)
{
return ( f(x + deltaX) - f(x) )/ deltaX;
}
return deriv;
}
var cos = makeDerivative( Math.sin, 0.000001);
// cos(0) ~> 1
// cos(pi/2) ~> 0
```
[Source](http://en.wikipedia.org/wiki/First-class_function).
Entities that are not first class objects are referred to as second-class objects. Functions in C++ are second class because they can't be dynamically created.
**Regarding the edit:**
> EDIT. When one says "everything is
> an object" (like in Python), does he
> indeed mean that "everything is
> first-class"?
The term object can be used loosely and doesn't imply being first class. And it would probably make more sense to call the whole concept 'first class entities'. But in Python they do aim to make everything first class. I believe the intent of the person who made your statement meant first class.
|
"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.
```
>>> dir(2)
['__abs__', '__add__', '__and__', '__class__', '__cmp__', '__coerce__', '__delattr__', '__div__', '__divmod__', '__doc__', '__float__', '__floordiv__', '__getattribute__', '__getnewargs__', '__hash__', '__hex__', '__index__', '__init__', '__int__', '__invert__', '__long__', '__lshift__', '__mod__', '__mul__', '__neg__', '__new__', '__nonzero__', '__oct__', '__or__', '__pos__', '__pow__', '__radd__', '__rand__', '__rdiv__', '__rdivmod__', '__reduce__', '__reduce_ex__', '__repr__', '__rfloordiv__', '__rlshift__', '__rmod__', '__rmul__', '__ror__', '__rpow__', '__rrshift__', '__rshift__', '__rsub__', '__rtruediv__', '__rxor__', '__setattr__', '__str__', '__sub__', '__truediv__', '__xor__']
```
Because everything's a first-class object in Python, there are relatively few obscure special cases.
In Java, for example, there are primitive types (int, bool, double, char) that aren't proper objects. That's why Java has to introduce Integer, Boolean, Double, and Character as first-class types. This can be hard to teach to beginners -- it isn't obvious why both a primitive type and a class have to exist side-by-side.
It also means that an object's class is -- itself -- an object. This is different from C++, where the classes don't always have a distinct existence at run-time.
The type of `2` is the `type 'int'` object, which has methods, attributes, and a type.
```
>>> type(2)
<class 'int'>
```
The type of a built-in type like `int` is the `type 'type'` object. This has methods and attributes, also.
```
>>> type(type(2))
<class 'type'>
```
|
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 another subclass, I won't get a compile-time error if I forget to implement them.
Is there a way to mark the methods so that they have to be implemented by subclasses, without marking them as abstract?
|
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 method throwing a `NotImplementedException`).
Of course, your unit tests will check that the methods have been implemented, yes? ;-p
Actually, it would probably be quite easy to test via generics - i.e. have a generic test method of the form:
```
[Test]
public void TestFoo() {
ActualTest<Foo>();
}
[Test]
public void TestBar() {
ActualTest<Bar>();
}
static void ActualTest<T>() where T : SomeBaseClass, new() {
T obj = new T();
Assert.blah something involving obj
}
```
|
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 = value; }
}
}
public abstract class ADesignerHappyImp
{
public abstract int MyMethod();
public int MyProperty {get; set;}
}
```
DesignerHappy just exposes the interface you want but forwards all the calls to the implementation object. You extend the behavior by sub-classing ADesignerHappyImp, which forces you to implement all the abstract members.
You can provide a default implementation of ADesignerHappyImp, which is used to initialize DesignerHappy by default and expose a property that allows you to change the implementation.
|
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.location.href
window.location = "http://somewhereelse.com";
```
**edit**: looks like the user who posted the better answer has left SO, i've consolidated his answers here.
|
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/');
```
This will replace the current URI with the new URI in the browser history, so the back button won't land the user on a page that immediately throws them forward again.
If you don't really want to redirect, but want to send the user somewhere in response to an event:
```
window.location.href = 'http://example.com/';
```
Remember to have a non-JavaScript fallback. A link is usually the best option, but it does depend on context.
Time delayed redirects are an even worse idea. The only reason to use them is if you want to display a message to the user - and users read things at different speeds (and have them sitting in another tab while they do something else). If the message is important enough to show, then it should be important enough to leave on screen until the user has read it and clicked a link to the next page.
|
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 IDictionary<ILanguage, IDictionary<string, string>> ConvertKeysToLowerCase(
IDictionary<ILanguage, IDictionary<string, string>> dictionaries)
{
IDictionary<ILanguage, IDictionary<string, string>> resultingConvertedDictionaries
= new Dictionary<ILanguage, IDictionary<string, string>>();
foreach(ILanguage keyLanguage in dictionaries.Keys)
{
IDictionary<string, string> convertedDictionatry = new Dictionary<string, string>();
foreach(string key in dictionaries[keyLanguage].Keys)
{
convertedDictionatry.Add(key.ToLower(), dictionaries[keyLanguage][key]);
}
resultingConvertedDictionaries.Add(keyLanguage, convertedDictionatry);
}
return resultingConvertedDictionaries;
}
```
Now, this is ok, but still it's a pretty huge chunk of code that contradicts my idea of "clean and efficient". Do you know any alternatives to this so that the .ContainsKey() method of the dictionary doesn't differentiate between casing?
|
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 would let the developer embed chat capabilities to their apps. The ChatClient class has a member of IMessageListener type
```
IMessageListener listener;
```
Afer creating the object for the ChatClient class, the user will call setListener on the object. (Could be addListerer for multiple listeners)
```
public void setListener(IMessageListener listener) {
this.listener = listener;
}
```
And in the library method when a message is recieved, i would call the getMessage method on that listener object
This was a basic example. More sophisticated libraries would use more complex methods, like implementing event queues, threading, concurrency etc.
Edit: And Yes. this is the observer pattern indeed
|
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[] { methodParams });
```
In this case, `GetMethod()` will not return private methods. What `BindingFlags` do I need to supply to `GetMethod()` so that it can locate private methods?
|
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 object[] { methodParams });
```
Here's the [BindingFlags enumeration documentation](http://msdn.microsoft.com/en-us/library/system.reflection.bindingflags.aspx).
|
`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 `hasOwnProperty()` method. While it is possible to workaround these problems by calling `Object.prototype.hasOwnProperty()` on an external object, `Object.hasOwn()` is more intuitive.
#### Example
```
const object1 = {
prop: 'exists'
};
console.log(Object.hasOwn(object1, 'prop'));
// expected output: true
```
---
## Original answer
I'm really confused by the answers that have been given - most of them are just outright incorrect. Of course you can have object properties that have undefined, null, or false values. So simply reducing the property check to `typeof this[property]` or, even worse, `x.key` will give you completely misleading results.
It depends on what you're looking for. If you want to know if an object physically contains a property (and it is not coming from somewhere up on the prototype chain) then `object.hasOwnProperty` is the way to go. All modern browsers support it. (It was missing in older versions of Safari - 2.0.1 and older - but those versions of the browser are rarely used any more.)
If what you're looking for is if an object has a property on it that is iterable (when you iterate over the properties of the object, it will appear) then doing: `prop in object` will give you your desired effect.
Since using `hasOwnProperty` is probably what you want, and considering that you may want a fallback method, I present to you the following solution:
```
var obj = {
a: undefined,
b: null,
c: false
};
// a, b, c all found
for ( var prop in obj ) {
document.writeln( "Object1: " + prop );
}
function Class(){
this.a = undefined;
this.b = null;
this.c = false;
}
Class.prototype = {
a: undefined,
b: true,
c: true,
d: true,
e: true
};
var obj2 = new Class();
// a, b, c, d, e found
for ( var prop in obj2 ) {
document.writeln( "Object2: " + prop );
}
function hasOwnProperty(obj, prop) {
var proto = obj.__proto__ || obj.constructor.prototype;
return (prop in obj) &&
(!(prop in proto) || proto[prop] !== obj[prop]);
}
if ( Object.prototype.hasOwnProperty ) {
var hasOwnProperty = function(obj, prop) {
return obj.hasOwnProperty(prop);
}
}
// a, b, c found in modern browsers
// b, c found in Safari 2.0.1 and older
for ( var prop in obj2 ) {
if ( hasOwnProperty(obj2, prop) ) {
document.writeln( "Object2 w/ hasOwn: " + prop );
}
}
```
The above is a working, cross-browser, solution to `hasOwnProperty()`, with one caveat: It is unable to distinguish between cases where an identical property is on the prototype and on the instance - it just assumes that it's coming from the prototype. You could shift it to be more lenient or strict, based upon your situation, but at the very least this should be more helpful.
|
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 to `hasOwnProperty`" (i.e. it works even if `hasOwnProperty` is overwritten).
In particular, Lodash defines `_.has` as:
```
function has(object, key) {
return object ? hasOwnProperty.call(object, key) : false;
}
// hasOwnProperty = Object.prototype.hasOwnProperty
```
## 2023 Update
As noted in John Resig's answer, this is now essentially built-in with [`Object.hasOwn`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/hasOwn). Lodash/underscore remain fallbacks for cases where `Object.hasOwn` is [not available](https://caniuse.com/?search=object.hasown).
|
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(int x, int y)
{ return x+y; }
int Subtract(int x, int y)
{ return x-y; }
delegate int BinaryOp(int x, int y);
methodsToExecute.add(new BinaryOp(add));
methodsToExecute.add(new BinaryOp(subtract));
foreach(object method in methodsToExecute)
{
method(1,2);
}
```
Any ideas on how to accomplish this?
Thanks!
|
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 methodsToExecute)
{
method(1,2);
}
```
|
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. Depending on your business needs, this could be a definite advantage. EntLib also gently prods the developer in the direction of using DbParameter for query parameters, which reduces the risk of SQL injection attacks.
As another poster mentionned, the data app block is somewhat higher-level than the straight ADO.NET classes, so it tends to require fewer lines of code to do the same thing.
From my point of view, the data, exception and logging blocks are the most useful. Exception and Logging together make it very easy to log exceptions (duh) to a number of places and in a number of formats. For example, they can put the entire exception log entry, including the stack trace, in the Windows event log making it relatively easy to diagnose a problem.
One disadvantage of EntLib is that some app blocks place quite a bit of logic into configuration files. So your logic is more spread out; some of it is in code, some in config files. The upside is that the configuration can be modified post-build and even post-deployment.
|
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 instantiate so we could mock out the DAL for unit testing; the Microsoft code block used static calls for database work. I am not sure if Microsoft has integrated any of the LINQtoSQL or Entity Framework stuff into the db block. I would be hesitant to use the db block now if it did not leverage one of those.
As far as logging goes, we found [Log4Net](http://logging.apache.org/log4net/index.html) to be a much more robust and flexible solution that the Microsoft logging. We went with that for our logging needs.
For exception handling, we rolled our own. The Microsoft code did not handle the remoting cases we wanted to handle, and since we were using a 3rd party logging framework it made more sense to write our own exception library and integrate with that. I have found that some level of integration of the logging framework into the exception framework can be very useful. We wrote some lightweight wrapper classes around Log4Net and called those from our exception logging so we didn't introduce dependencies on Log4Net.
|
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 \*almost\* never a reason to index a subset of your indexed columns. If your index is (A, B, C, D), a WHERE against (A, B, C) will most likely result in an index \*\*seek\*\*, which is the ideal situation -- the index includes all the information the engine needs to go directly to the result set. I believe this holds true for numeric types and for equality tests in string types, though it can break down with LIKE '%'s). On the other hand, if your WHERE only referenced D, you would most likely end up with an index \*\*scan\*\*, which would mean that the SQL engine would have to scan across all combinations of A, B, and C, and then check whether D met your criteria before deciding whether to add the row to the result set. On a particularly large table, when I found myself having to do a lot of queries against column "D", I added an additional index for D only, and saw about 90% performance improvement.
Edit: I should also recommend using the Database Engine Tuning Advisor in SQL Management Studio. It will tell you if your table isn't indexed ideally for the query you want to run.
|
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 like to take advantage of LINQ in 3.5.
|
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-service-pack-1-beta.aspx)".
The .NET Framework Client Profile setup contains just those assemblies and files in the .NET Framework that are typically used for client application scenarios. For example: it includes Windows Forms, WPF, and WCF. It does not include ASP.NET and those libraries and components used primarily for server scenarios. We expect this setup package to be about **26MB** in size, and it can be downloaded and installed much quicker than the full .NET Framework setup package.
|
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 (assuming you don't need to do anything at this point) - the exception would bubble to the next exception handler in a parent member.
The only argument that sounded plausible was that sometimes exceptions weren't caught and your code stopped (in debug mode) with the current line highlighted in green...and that this may be something to do with multiple threads?
Best practice does state "an exception handler for each thread" but mostly we work single-threaded.
The good thing may be it could be useful in debug mode to not suddenly pop out to a parent member (yes, Joel!) - you'd move to the "throw" statement and be able to examine your locals.
But then your code would be "littered with try/catch/throws" (to quote another thread here)?
And what sort of overhead would be involved in adding try/catch/throws everywhere if no exception occurs (i.e. should you avoid try/catches in tight loops)?
|
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.
Reasons for catching and replacing it with another exception might be
* Logging
* Hiding sensitive information from the caller (Stacktrace, exception details)
And for debugging you might want to change your "Break when an exception is:"-Handler (Press Ctrl+Alt+e) the value "thrown" on selected CLR Exceptions.
You might want to take a look at the entlib exception handler block (EHB), with which you can establish a pattern on how to deal with exceptions in your code.
Regarding your question on performance i think its not a propblem to have many try/catch blocks in your code but you will get performance hits when your code raises and catches many exceptions.
|
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 of execution". In a single-threaded C++ program, execution starts at main(), and then proceeds in a sequential fashion. In a multi-threaded program, the first thread starts at main, but additional threads may be started by the application which start at a user-specified function. These then run concurrently, or in parallel with the original thread.
In C++0x threads are started using the `std::thread` class:
```
void my_function()
{
// do stuff
}
std::thread my_thread(my_function); // run my_function in its own thread
```
The new C++0x standard also supports:
* atomic values and operations with the `std::atomic<>` class template,
* mutexes for data protection (`std::mutex`, `std::recursive_mutex`, etc.)
* lock classes for ease of managing lock lifetime (`std::lock_guard<>`, `std::unique_lock<>`)
* `std::lock` and `std::try_lock` functions to manage acquiring multiple locks at the same time without risking deadlock
* condition variables to ease waiting for an event (`std::condition_variable`, `std::condition_variable_any`)
* futures, promises and packaged tasks to simplify passing data between threads, and waiting for a value to be ready. This addresses the classic "how do I return a value from a thread" question.
* thread-safe initialization of local static objects
* the `thread_local` keyword to declare thread-local data
I gave a more detailed overview of the new C++0x thread library in my article on devx.com: [Simpler Multithreading in C++0x](http://www.devx.com/SpecialReports/Article/38883)
I write about multithreading and concurrency in C++ on [my blog](http://www.justsoftwaresolutions.co.uk/blog). I'm also writing a book on the topic: [C++ Concurrency in Action](http://www.manning.com/williams).
|
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
* thread\_local storage (which was just added into the draft standard a few months ago)
* mutual exclusion (mutex classes)
* condition variables - this is particularly nice for Windows, since condition variables are difficult to implement correctly in Win32. This means that eventually Microsoft should provide support for condition variables at least in the MSVC++ runtime, so it will be easy to get correct condition variable semantics on WIn32.
|
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 when creating jCarousel:
```
$('.columns2.rows2 .mycarousel').jcarousel( {
scroll: 1,
moduleWidth: 290,
rows:2,
itemLoadCallback: tonyTest,
animation: 'slow'
});
```
The find and edit the lines in:
```
$.jcarousel = function(e, o) {
if (li.size() > 0) {
...
moduleCount = li.size();
wh = this.options.moduleWidth * Math.ceil( moduleCount / this.options.rows );
wh = wh + this.options.moduleWidth;
this.list.css(this.wh, wh + 'px');
// Only set if not explicitly passed as option
if (!o || o.size === undefined)
this.options.size = Math.ceil( li.size() / this.options.rows );
```
Hope this helps,
Tony Dillon
|
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',
easing: 'swing',
auto: 0,
wrap: null,
initCallback: null,
setupCallback: null,
reloadCallback: null,
itemLoadCallback: null,
itemFirstInCallback: null,
itemFirstOutCallback: null,
itemLastInCallback: null,
itemLastOutCallback: null,
itemVisibleInCallback: null,
itemVisibleOutCallback: null,
animationStepCallback: null,
buttonNextHTML: '<div></div>',
buttonPrevHTML: '<div></div>',
buttonNextEvent: 'click',
buttonPrevEvent: 'click',
buttonNextCallback: null,
buttonPrevCallback: null,
moduleWidth: null,
rows: null,
itemFallbackDimension: null
}, windowLoaded = false;
this.clip.addClass(this.className('jcarousel-clip')).css({
position: 'relative',
height: this.options.rows * this.options.moduleWidth
});
this.container.addClass(this.className('jcarousel-container')).css({
position: 'relative',
height: this.options.rows * this.options.moduleWidth
});
if (li.size() > 0) {
var moduleCount = li.size();
var wh = 0, j = this.options.offset;
wh = this.options.moduleWidth * Math.ceil(moduleCount / this.options.rows);
wh = wh + this.options.moduleWidth;
li.each(function() {
self.format(this, j++);
//wh += self.dimension(this, di);
});
this.list.css(this.wh, wh + 'px');
// Only set if not explicitly passed as option
if (!o || o.size === undefined) {
this.options.size = Math.ceil(li.size() / this.options.rows);
}
}
```
This is the call in using the static\_sample.html of the code bundle in the download of jscarousel:
```
<script type="text/javascript">
jQuery(document).ready(function() {
jQuery('#mycarousel').jcarousel( {
scroll: 1,
moduleWidth: 75,
rows:2,
animation: 'slow'
});
});
</script>
```
In case you need to change the content of the carousel and reload the carousel you need to do this:
```
// Destroy contents of wrapper
$('.wrapper *').remove();
// Create UL list
$('.wrapper').append('<ul id="carousellist"></ul>')
// Load your items into the carousellist
for (var i = 0; i < 10; i++)
{
$('#carouselist').append('<li>Item ' + i + '</li>');
}
// Now apply carousel to list
jQuery('#carousellist').jcarousel({ // your config });
```
The carousel html definition needs to be like this:
```
<div class="wrapper">
<ul id="mycarousel0" class="jcarousel-skin-tango">
...<li></li>
</ul>
</div>
```
Thanks to [Webcidentes](http://www.cabezabomba.com/webcidentes/?p=308)
|
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, I even echo $somepass and $myrow[1] they are the same, but still error. What Am I doing wrong? Thanks
|
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 if my application is running in MyComputer, Intranet, Internet, Untrusted, Trusted, etc.
---
**Edit:** Here's the minor test-app I wrote to find this code, thanks to [@blowdart](https://stackoverflow.com/users/2525/blowdart).
```
using System;
using System.Reflection;
namespace zone_check
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(".NET version: " + Environment.Version);
foreach (Object ev in Assembly.GetExecutingAssembly().Evidence)
{
if (ev is System.Security.Policy.Zone)
{
System.Security.Policy.Zone zone = (System.Security.Policy.Zone)ev;
Console.WriteLine("Security zone: " + zone.SecurityZone);
break;
}
}
}
}
}
```
|
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 you can [enumerate the evidence](http://www.improve.dk/blog/2008/06/11/analyzing-assembly-evidence) and look for the zone which appears as a <System.Security.Policy.Zone> element.
|
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` base class.
HTH,
György
|
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, "Select an option..." option selected. In principle I'm allowed to use JavaScript but It'd be interesting to learn how to solve it within JSP too.
|
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 cases, then do a server-side validation of the submitted parameters to catch the minority that don't have JS enabled or who manipulate the HTML to submit non-expected values.
Just remember that the client-side validation is optional, and is good for those 'common mistakes' input validation, but the server-side validation is mandatory for all input whether or not any client-side checks have been done on the given input.
|
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 validate the input.
But even if we're not talking about some large application here, the validation should still be done server-side, as others before me have already noted.
|
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 properly.
* As with every powerful tool you will make mistakes.
* As with every powerful tool you will have to practice a lot.
* As with every powerful tool you should read a lot about it, and read what other people think. Learn from others.
* But, as with every powerful tool, there are people out there who misuse it. Learn to not learn bad practices from them. This is hard.
|
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 start getting better code re-use as well. So the new app has part of the work already done, and is using time-tested code: software is built faster with fewer bugs.
|
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 other, or might each of them be better than the other in some situations (and if so, what situations)?
|
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 production code, 100% of the time its been a custom implementation of Named Parameters, but that's not necessarily a good thing.
|
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 too much boilerplate code necessary to set it up in the first place.
|
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 to insert multiple, identical elements?
I'm hoping to find something that wouldn't break chaining but wouldn't bring the browser to its knees. A chainable `.repeat()` plugin?
|
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(),
div = document.createElement('div');
while (i--) {
fragment.appendChild(div.cloneNode(true));
}
$('#container').append(fragment);
```
I realise it's not making a lot of use of jQuery in building up the fragment, but I've run a few tests and I can't seem to do $(fragment).append() - but I've read John's jQuery 1.3 release is supposed to include changes based on the research linked above.
|
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 = []; //Initialize an array to build the content
for (var i = 0;i<10;i++) cont.push('<div>bunch of text</div>');
$('#container').html(cont.join(''));
```
I use this technique a ton in my code. You can build very large html fragments using this method and it is very efficient in all browsers.
|
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 == Array){
}
else if(output.constructor == Object){
}
```
|
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 (isArray(myObject)) {
// do stuff for arrays
}
else if (isObject(myObject)) {
// do stuff for objects
}
```
|
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 `null`s.
I thought initially I'd be clever:
```
datePrm.Value = nullableDate ?? DBNull.Value;
```
but that fails with the error
> Operator '??' cannot be applied to operands of type 'System.DateTime?' and 'System.DBNull'
So I guess that only works if the second argument is a non-nullable version of the first argument. So then I went for:
```
datePrm.Value = nullableDate.HasValue ? nullableDate.Value : DBNull.Value;
```
but that doesn't work either:
> Type of conditional expression cannot be determined because there is no implicit conversion between 'System.DateTime' and 'System.DBNull'
But I don't want to convert between those types!
So far the only thing I can get to work is:
```
if (nullableDate.HasValue)
datePrm.Value = nullableDate.Value;
else
datePrm.Value = DBNull.Value;
```
Is that really the only way I can write this? Is there a way to get a one-liner using the ternary operator to work?
**Update:** I don't really get why the ?? version doesn't work. MSDN says:
> The ?? operator returns the left-hand operand if it is not null, or else it returns the right operand.
That's exactly what I want!
**Update2:** Well it was kind of obvious in the end:
```
datePrm.Value = nullableDate ?? (object)DBNull.Value;
```
|
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 that had a method that just called the static method. It would allow me to mock the logic by just mocking the call to this wrapper class. (I feel dirty even talking about it :) )
|
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 hint that there's a problem. One exception is where it's in a third-party library, but we would probably wrap that in something more object-oriented anyway.
|
[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 facade*, particularly to provide a simpler and easier to use API to the persistence subsystem in a business application. In my opinion, no other solution is more elegant than something like:
```
List<Person> peopleAboveAge =
find("select p from Person p where p.age >= ?", age);
```
where the `find` method is statically imported from a `PersistenceFacade` class which defines only static methods, and encapsulates how to obtain the proper Session/EntityManager instance. This solution is unit-testing friendly and flexible. I used it in a business application which had 500+ persistent entities, using Hibernate. The static facade helped when we migrated from Hibernate 2 to Hibernate 3, when we migrated from Oracle to Sybase and then back to Oracle, and when we started using JPA annotations instead of "hbm.xml" files for ORM mapping.
|
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 _ModelDto implements BaseObject, IsSerializable
{
protected String id;
public void setId(String id)
{
this.id = id;
}
public String getId()
{
return id;
}
}
// Interface used in the ServiceAsync inteface.
public interface MyAsync<T>
{
// Nothing here.
}
// Service interface use both interfaces above.
public interface ServiceAsync
{
public void getList(MyAsync<List<? extends BaseObject>> callback);
}
public class MyClass
{
ServiceAsync service = (some implementation);
MyAsync<List<_ModelDto>> callBack = new MyAsync<List<_ModelDto>>()
{
};
service.getList(callBack); // This does not compile, says arguments are not applicable????
}
```
|
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<BaseObject>
```
But the following relations do:
```
List<_ModelDto> <: List<? extends _ModelDto> <: List<? extends BaseObject>
```
This is the reason why Java has wildcards: to enable these kind of subtype relations. All of this is explained in the [Generics tutorial](http://java.sun.com/j2se/1.5/pdf/generics-tutorial.pdf). If you understand this, we can continue with the nested case...
## Nested case
Let's do exactly the same, but with one more level of nesting. Starting from the subtype relation:
```
List<_ModelDto> <: List<? extends BaseObject>
```
The following relation does **not** hold, for exactly the same reasons as above:
```
MyAsync<List<_ModelDto>> <: MyAsync<List<? extends BaseObject>>
```
This is *precisely* the conversion you are trying to do when calling `service.getList(callBack)`, and since the subtype relation does not hold, the conversion fails.
However, as above, you **do** have the following relations:
```
MyAsync<List<_ModelDto>>
<: MyAsync<? extends List<_ModelDto>>
<: MyAsync<? extends List<? extends BaseObject>>
```
## Solution
So you should write the signature of `getList` as follows to make the call work:
```
public void getList(MyAsync<? extends List<? extends BaseObject>> callback);
```
The difference will be that the body of `getList` will be constrained with how it can use the `callback`. If `MyAsync` contains the following members:
```
public interface MyAsync<T> {
T get();
void set(T t);
}
```
Then, the body of `getList` will be able to `get` a list from the callback. However, it cannot `set` the list (except setting it to `null`), because it does not know exactly what kind of list is represented by the `?`.
In contrast, with your original signature, `set` is available, and that is why the compiler cannot allow your argument.
|
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 way; remember that type erasure will erase this method signature to `getList(MyAsync callback);`
The reason that this doesn't compile is that your bound is wrong. `MyAsync<List<? extends BaseObject>>` gives T as `List<? extends BaseObject>`, a list of some unknown type.
It looks to me like what you want is for the getList method itself to be generic:
```
public interface ServiceAsync {
public <T extends BaseObject> void getList(MyAsync<List<T>> callback);
}
public class MyClass {
public void foo() {
ServiceAsync service = null;
MyAsync<List<_ModelDto>> callBack = new MyAsync<List<_ModelDto>>() {};
service.getList (callBack); // This compiles
}
}
```
|
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 component itself and a renderer. At some point the node has to be turned into text and displayed by a renderer. I'm not clear on the best way to do this:
* Pass the node itself (as Object) to the renderer, and let the renderer decide how to display it.
+ This is how JList does it.
+ Requires a customised renderer just to change the text.
+ Allows great flexibility in how to display the node (doesn't even have to be text).
* Pass the node itself (as Object) to the renderer, but have a convertValueToText() method in the component class.
+ This is how JTree does it.
+ Renderers can be just as flexibile as before - don't *have* to use this method.
+ Have to override component to change the text transformation.
* As above, but delegate convertValueTotext() to the model.
+ This is how JXTable does it.
+ The model is probably the best place for this method - and it's easier to override there.
I don't want to have to customise the renderer just to change the text, but I'd like to be *able* to customise the renderer to do more than display a model-displayed string (else why bother with renderers). I really don't like the fact that JXTable uses reflection to look for convertValueToText() in the model - this smells of bad magic to me.
Can anyone shed any light on this oft-neglected part of Swing?
**SOLUTION**
What I ended up doing was this:
* Add a method to the model which returns a string for the given node. Importantly, this can be null to indicate that the renderer should know what to do or that we simply can't provide anything useful.
* The component has the same method, and passes the call on to the model. This is important for view-model separation. The renderer calls this method, so it doesn't talk to the model directly.
* The default renderer calls the above method and if it's not null, it uses it, otherwise it can call toString on the value, or provide a default, or whatever.
This leaves developers a choice when they want to override the displayed value
- Override the method with a non-null return value knowing that the default renderer will display this text.
- Provide a custom renderer which is passed the actual node object so it can do "clever" things if it needs to.
I'm quite happy with it - it "feels" right, it works, and it's easy to use.
Thanks for your perspectives!
|
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 display the text. You might even want more than two - for instance, object-to-text, text-to-document-structure, document-structure-to-HTML, and then CSS to present to the user.
However, pragmatism says this may get too hard to remember and maintain. So in your circumstance I would suggest: think about how likely it is you'll ever want to extract non-text data from the model. If it is not very likely, then put the equivalent of convertValueToText in the model.
Otherwise, allow the component to either use a renderer, if it is given one, or else take the object value and convert it to text internally.
This allows maximum flexibility and probably makes things feel most natural to the users of the API. I believe this is the JTable model though I haven't used Swing for a long time.
|
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 DefaultRenderer which implements AbstractRenderer and add there all methods like toText(Object o) and so on. Then allow me to decide whether I want to use default functionality or I prefer to wrote my own. Do you really need custom component? To make it works correctly it is a LOT of work. Is this component worth all this?
|
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 together without much thought I ended up with the following:
```
public class Foo {
/* constructors, fields, method, logic and what-not */
}
public class Bar extends Foo {
/* nothing here but constructors */
}
```
Is this OK? Is it better to make `Bar` a composite class? e.g:
```
public class Bar {
private Foo foo;
/* constructors and a bunch of wrapper methods that call
into foo */
}
```
Or even, while we're at it, something much more low-tech:
```
public class Foo {
/* constructors, fields, method, logic and what-not */
private boolean isABar; // Could be an enum
}
```
What do you think? **How do you deal with these 'marker classes'?**
---
As an example of how my code may wish to treat `Foo` and `Bar` differently, my code would need to be able to do stuff like `List<Foo>` and `List<Bar>`. A `Foo` couldn't go in a `List<Bar>` and vice versa.
|
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: Rather than this:
```
if (foo instanceof Bar) {
// Do Bar-specific things
}
```
Do this instead:
```
class Bar extends AbstractFoo {
public void specialOp() {
// Do Bar-specific things
}
}
// ...
foo.specialOp();
```
The benefit of this approach is that if you need a third class, that's much like `Foo` but has just a little bit of difference, you don't have to go through all your code and add edit all the `if` statements. :-)
|
**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.
So I'm looking for tools that would help me explore classes and methods and their relationships in JavaScript and if possible, document them along the way, is there one available?
Something like object browser in VS would be nice, but any tools that help me get things done faster will do.
Thanks!
|
[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 instance of one object holds an instance of a related object, but it's a start.
You can also use the Options menu on the DOM tab to restrict what's shown to user-defined functions and properties, which should help reduce clutter.
|
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 NotifyPropertyChanged(String info)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(info));
}
}
public string MyProperty
{
set
{
if (_myProperty != value)
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
}
}
}
}
```
I get a nice green test from the following code in my unit tests, that uses delegates:
```
[TestMethod]
public void Test_ThatMyEventIsRaised()
{
string actual = null;
MyClass myClass = new MyClass();
myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
{
actual = e.PropertyName;
};
myClass.MyProperty = "testing";
Assert.IsNotNull(actual);
Assert.AreEqual("MyProperty", actual);
}
```
However, if I then try and chain the setting of properties together like so:
```
public string MyProperty
{
set
{
if (_myProperty != value)
{
_myProperty = value;
NotifyPropertyChanged("MyProperty");
MyOtherProperty = "SomeValue";
}
}
}
public string MyOtherProperty
{
set
{
if (_myOtherProperty != value)
{
_myOtherProperty = value;
NotifyPropertyChanged("MyOtherProperty");
}
}
}
```
My test for the event fails - the event that it captures is the event for the MyOtherProperty.
I'm pretty sure the event fires, my UI reacts like it does, but my delegate only captures the last event to fire.
So I'm wondering:
1. Is my method of testing events correct?
2. Is my method of raising *chained* events correct?
|
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 these events.
If you want to test the number of events that gets raised, and the order they get raised in, you can easily extend your existing test:
```
[TestMethod]
public void Test_ThatMyEventIsRaised()
{
List<string> receivedEvents = new List<string>();
MyClass myClass = new MyClass();
myClass.PropertyChanged += delegate(object sender, PropertyChangedEventArgs e)
{
receivedEvents.Add(e.PropertyName);
};
myClass.MyProperty = "testing";
Assert.AreEqual(2, receivedEvents.Count);
Assert.AreEqual("MyProperty", receivedEvents[0]);
Assert.AreEqual("MyOtherProperty", receivedEvents[1]);
}
```
|
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;
};
var expectedSequence = new[] { "X", "Y" };
EventMonitor.Assert(test, publisher, expectedSequence);
```
Please see my answer to the following for more details.
[Unit testing that an event is raised in C#, using reflection](https://stackoverflow.com/questions/2567047/unit-testing-that-an-event-is-raised-in-c-using-reflection/2697721#2697721)
|
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:\\PComm\\ehlapi32.dll")
# Set up prototype and parameters for the desired function call.
# HLLAPI
hllApiProto = ctypes.WINFUNCTYPE (
ctypes.c_int, # Return type.
ctypes.c_void_p, # Parameters 1 ...
ctypes.c_void_p,
ctypes.c_void_p,
ctypes.c_void_p) # ... thru 4.
hllApiParams = (1, "p1", 0), (1, "p2", 0), (1, "p3",0), (1, "p4",0),
# Actually map the call ("HLLAPI(...)") to a Python name.
hllApi = hllApiProto (("HLLAPI", hllDll), hllApiParams)
# This is how you can actually call the DLL function.
# Set up the variables and call the Python name with them.
p1 = ctypes.c_int (1)
p2 = ctypes.c_char_p (sessionVar)
p3 = ctypes.c_int (1)
p4 = ctypes.c_int (0)
hllApi (ctypes.byref (p1), p2, ctypes.byref (p3), ctypes.byref (p4))
```
The `ctypes` stuff has all the C-type data types (`int`, `char`, `short`, `void*`, and so on) and can pass by value or reference. It can also return specific data types although my example doesn't do that (the HLL API returns values by modifying a variable passed by reference).
---
In terms of the specific example shown above, IBM's EHLLAPI is a fairly consistent interface.
All calls pass four void pointers (EHLLAPI sends the return code back through the fourth parameter, a pointer to an `int` so, while I specify `int` as the return type, I can safely ignore it) as per IBM's documentation [here](http://publib.boulder.ibm.com/infocenter/pcomhelp/v5r9/index.jsp?topic=/com.ibm.pcomm.doc/books/html/emulator_programming08.htm). In other words, the C variant of the function would be:
```
int hllApi (void *p1, void *p2, void *p3, void *p4)
```
This makes for a single, simple `ctypes` function able to do anything the EHLLAPI library provides, but it's likely that other libraries will need a separate `ctypes` function set up per library function.
The return value from `WINFUNCTYPE` is a function prototype but you still have to set up more parameter information (over and above the types). Each tuple in `hllApiParams` has a parameter "direction" (1 = input, 2 = output and so on), a parameter name and a default value - see the `ctypes` doco for details
Once you have the prototype and parameter information, you can create a Python "callable" `hllApi` with which to call the function. You simply create the needed variable (`p1` through `p4` in my case) and call the function with them.
|
[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. I have a self-made DLL file with two functions: `add` and `sub` which take two arguments.
>
> `add(a, b)` returns addition of two numbers
> `sub(a, b)` returns substraction of two numbers
>
> The name of the DLL file will be "demo.dll"
>
> **Program:**
>
> ```
> from ctypes import*
> # give location of dll
> mydll = cdll.LoadLibrary("C:\\demo.dll")
> result1= mydll.add(10,1)
> result2= mydll.sub(10,1)
> print("Addition value:"+result1)
> print("Substraction:"+result2)
> ```
>
> **Output:**
>
> ```
> Addition value:11
> Substraction:9
> ```
|
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 25
Visio 12 5 17
```
How to do in T-SQL?
|
```
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
-------------------------------------------------- ----------- ----------- -----------
Project 15 10 25
Visio 12 5 17
(2 row(s) affected)
```
|
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 yes, we are revving versions constantly.
Without doing anything crazy like changing the assembly version itself every time I compile\*, is there some assembly property I can check (or set at compile-time)?
\*I should clarify, in SharePoint projects we hardcode the assembly's full name in multiple places (including XML files), so changing the assembly version is a less savory option than you might think.
|
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 [article on the topic](https://jonskeet.uk/csharp/memory.html) and will expand on it if requested, but let's deal with just the `new` operator.
Secondly, all of this really depends on what level you're talking about. I'm looking at what the compiler does with the source code, in terms of the IL it creates. It's more than possible that the JIT compiler will do clever things in terms of optimising away quite a lot of "logical" allocation.
Thirdly, I'm ignoring generics, mostly because I don't actually know the answer, and partly because it would complicate things too much.
Finally, all of this is just with the current implementation. The C# spec doesn't specify much of this - it's effectively an implementation detail. There are those who believe that managed code developers really shouldn't care. I'm not sure I'd go that far, but it's worth imagining a world where in fact all local variables live on the heap - which would still conform with the spec.
---
There are two different situations with the `new` operator on value types: you can either call a parameterless constructor (e.g. `new Guid()`) or a parameterful constructor (e.g. `new Guid(someString)`). These generate significantly different IL. To understand why, you need to compare the C# and CLI specs: according to C#, all value types have a parameterless constructor. According to the CLI spec, *no* value types have parameterless constructors. (Fetch the constructors of a value type with reflection some time - you won't find a parameterless one.)
It makes sense for C# to treat the "initialize a value with zeroes" as a constructor, because it keeps the language consistent - you can think of `new(...)` as *always* calling a constructor. It makes sense for the CLI to think of it differently, as there's no real code to call - and certainly no type-specific code.
It also makes a difference what you're going to do with the value after you've initialized it. The IL used for
```
Guid localVariable = new Guid(someString);
```
is different to the IL used for:
```
myInstanceOrStaticVariable = new Guid(someString);
```
In addition, if the value is used as an intermediate value, e.g. an argument to a method call, things are slightly different again. To show all these differences, here's a short test program. It doesn't show the difference between static variables and instance variables: the IL would differ between `stfld` and `stsfld`, but that's all.
```
using System;
public class Test
{
static Guid field;
static void Main() {}
static void MethodTakingGuid(Guid guid) {}
static void ParameterisedCtorAssignToField()
{
field = new Guid("");
}
static void ParameterisedCtorAssignToLocal()
{
Guid local = new Guid("");
// Force the value to be used
local.ToString();
}
static void ParameterisedCtorCallMethod()
{
MethodTakingGuid(new Guid(""));
}
static void ParameterlessCtorAssignToField()
{
field = new Guid();
}
static void ParameterlessCtorAssignToLocal()
{
Guid local = new Guid();
// Force the value to be used
local.ToString();
}
static void ParameterlessCtorCallMethod()
{
MethodTakingGuid(new Guid());
}
}
```
Here's the IL for the class, excluding irrelevant bits (such as nops):
```
.class public auto ansi beforefieldinit Test extends [mscorlib]System.Object
{
// Removed Test's constructor, Main, and MethodTakingGuid.
.method private hidebysig static void ParameterisedCtorAssignToField() cil managed
{
.maxstack 8
L_0001: ldstr ""
L_0006: newobj instance void [mscorlib]System.Guid::.ctor(string)
L_000b: stsfld valuetype [mscorlib]System.Guid Test::field
L_0010: ret
}
.method private hidebysig static void ParameterisedCtorAssignToLocal() cil managed
{
.maxstack 2
.locals init ([0] valuetype [mscorlib]System.Guid guid)
L_0001: ldloca.s guid
L_0003: ldstr ""
L_0008: call instance void [mscorlib]System.Guid::.ctor(string)
// Removed ToString() call
L_001c: ret
}
.method private hidebysig static void ParameterisedCtorCallMethod() cil managed
{
.maxstack 8
L_0001: ldstr ""
L_0006: newobj instance void [mscorlib]System.Guid::.ctor(string)
L_000b: call void Test::MethodTakingGuid(valuetype [mscorlib]System.Guid)
L_0011: ret
}
.method private hidebysig static void ParameterlessCtorAssignToField() cil managed
{
.maxstack 8
L_0001: ldsflda valuetype [mscorlib]System.Guid Test::field
L_0006: initobj [mscorlib]System.Guid
L_000c: ret
}
.method private hidebysig static void ParameterlessCtorAssignToLocal() cil managed
{
.maxstack 1
.locals init ([0] valuetype [mscorlib]System.Guid guid)
L_0001: ldloca.s guid
L_0003: initobj [mscorlib]System.Guid
// Removed ToString() call
L_0017: ret
}
.method private hidebysig static void ParameterlessCtorCallMethod() cil managed
{
.maxstack 1
.locals init ([0] valuetype [mscorlib]System.Guid guid)
L_0001: ldloca.s guid
L_0003: initobj [mscorlib]System.Guid
L_0009: ldloc.0
L_000a: call void Test::MethodTakingGuid(valuetype [mscorlib]System.Guid)
L_0010: ret
}
.field private static valuetype [mscorlib]System.Guid field
}
```
As you can see, there are lots of different instructions used for calling the constructor:
* `newobj`: Allocates the value on the stack, calls a parameterised constructor. Used for intermediate values, e.g. for assignment to a field or use as a method argument.
* `call instance`: Uses an already-allocated storage location (whether on the stack or not). This is used in the code above for assigning to a local variable. If the same local variable is assigned a value several times using several `new` calls, it just initializes the data over the top of the old value - it *doesn't* allocate more stack space each time.
* `initobj`: Uses an already-allocated storage location and just wipes the data. This is used for all our parameterless constructor calls, including those which assign to a local variable. For the method call, an intermediate local variable is effectively introduced, and its value wiped by `initobj`.
I hope this shows how complicated the topic is, while shining a bit of light on it at the same time. In *some* conceptual senses, every call to `new` allocates space on the stack - but as we've seen, that isn't what really happens even at the IL level. I'd like to highlight one particular case. Take this method:
```
void HowManyStackAllocations()
{
Guid guid = new Guid();
// [...] Use guid
guid = new Guid(someBytes);
// [...] Use guid
guid = new Guid(someString);
// [...] Use guid
}
```
That "logically" has 4 stack allocations - one for the variable, and one for each of the three `new` calls - but in fact (for that specific code) the stack is only allocated once, and then the same storage location is reused.
EDIT: Just to be clear, this is only true in some cases... in particular, the value of `guid` won't be visible if the `Guid` constructor throws an exception, which is why the C# compiler is able to reuse the same stack slot. See Eric Lippert's [blog post on value type construction](https://ericlippert.com/2010/10/11/debunking-another-myth-about-value-types/) for more details and a case where it *doesn't* apply.
I've learned a lot in writing this answer - please ask for clarification if any of it is unclear!
|
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 class, then it will be allocated within the class on the heap.
If the struct is allocated on the heap, then calling the new operator is not actually necessary to allocate the memory. The only purpose would be to set the field values according to whatever is in the constructor. If the constructor is not called, then all the fields will get their default values (0 or null).
Similarly for structs allocated on the stack, except that C# requires all local variables to be set to some value before they are used, so you have to call either a custom constructor or the default constructor (a constructor that takes no parameters is always available for structs).
|
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 contentid from tags where tagid = 334 and contentid in (
select contentid from tags where tagid = 338 and contentid in (
select contentid from tags where tagid = 342
)
)
```
However, my gut tells me that there's a better, faster, more extensible way to do this. For example, what if I needed to find the intersection of 12 tags? This could quickly get horrendous. Any ideas?
**EDIT**: Turns out that this is also covered in [this excellent blog post](http://weblogs.sqlteam.com/jeffs/jeffs/archive/2007/06/12/60230.aspx).
|
```
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
FROM objtags t0
INNER JOIN objtags t1 ON t1.objid=t0.objid
INNER JOIN objtags t2 ON t2.objid=t1.objid
WHERE t0.tagid=512
AND t1.tagid=256
AND t2.tagid=128
```
I have no idea why this runs faster. It was inspired by the search code in the MusicBrainz server. Doing this in Postgres, I usually get a ~8-10x speedup over the `HAVING COUNT(...)` solution.
|
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 appropriate action.
What is the easiest way of implementing something like this?
|
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
> StudentB | Assignment 2 | 80
> StudentB | Assignment 3 | 100
> StudentB | Total | 280
> ```
The name and number of assignments are dynamic, I need to get results simlilar to the following.
> ```
> Student | Assignment 1 | Assignment 2 | Assignment 3 | Total
> --------------------------------------------------------------------
> Student A | 100 | 80 | null | 180
> Student B | 100 | 80 | 100 | 280
> ```
Now ideally I would like to sort the column based on a "due date" that could be included/associated with each assignment. The total should be at the end if possible (It can be calculated and removed from the query if possible.)
I know how to do it for the 3 assignments using pivot with simply naming the columns, it is trying to do it in a dynamic fashion that I haven't found a GOOD solution for yet. I am trying to do this on SQL Server 2005
**EDIT**
Ideally I would like to implement this WITHOUT using Dynamic SQL, as that is against the policy. If it isn't possible...then a working example with Dynamic SQL will work.
|
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.com/questions/198716/pivot-in-sql-2005#199763)
The dynamic `SQL` there is not vulnerable to injection, and there is no good reason to prohibit it. Another possibility (if the data is changing very infrequently) is to do code-generation - instead of dynamic `SQL`, the `SQL` is generated to a stored procedure on a regular basis.
|
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 1', 100),
('StudentA', 'Assignment 2', 80),
('StudentA', 'Total', 180),
('StudentB', 'Assignment 1', 100),
('StudentB', 'Assignment 2', 80),
('StudentB', 'Assignment 3', 100),
('StudentB', 'Total', 280)
;
```
**Dynamic PIVOT:**
```
DECLARE @cols AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(AssignmentName)
from yourtable
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query = 'SELECT StudentName, ' + @cols + ' from
(
select StudentName, AssignmentName, grade
from yourtable
) x
pivot
(
min(grade)
for assignmentname in (' + @cols + ')
) p '
execute(@query)
```
See [SQL Fiddle with Demo](http://sqlfiddle.com/#!3/42b01/2)
The result is:
```
| STUDENTNAME | ASSIGNMENT 1 | ASSIGNMENT 2 | ASSIGNMENT 3 | TOTAL |
--------------------------------------------------------------------
| StudentA | 100 | 80 | (null) | 180 |
| StudentB | 100 | 80 | 100 | 280 |
```
|
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.wikipedia.org/wiki/Ironruby) and [IronPython](http://en.wikipedia.org/wiki/Ironpython), I started seriously investigating.
I love Python. It's a beautiful, expressive language. It's a joy to code in, for sure. The multitude of python modules and frameworks make it very appealing. Problem is, I cannot think of any specific problems, any specific hurdles that would **require** a language like Python. ASP.NET gives us RAD, it gives us a full-featured framework and all that good stuff. Also, we all already know C# and have lots of projects in C#, learning a new language just *because* doesn't quite work.
Can you guys help me think of something to finally convince my boss to really learn Python and start using it on projects?
Edit: I know that no problem requires only one language, I just meant, are there any specific problems in which dynamic languages excel over static languages.
Edit again: Let me also mention that my boss prompted ME to investigate this. He has put aside hours to research these languages, find a good one, learn it, and then figure out how we can use it. I'm at the last step here, I do not need a lecture on why I should consider my motivation for changing something my company does because they do it for a reason.
|
"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 where a dynamic language has significant advantages. Things where the requirements are **not** nailed down in detail. Things like data transformations, log-file scraping, and super-sophisticated replacements for BAT files.
Use Python to get started doing something useful while everyone else is standing around trying to get enough business and domain information to launch a project to develop a complicated MVC design.
---
Edit: Some Python to the Rescue stories.
* [Exploratory Programming](http://www.itmaybeahack.com/homepage/iblog/C551260341/E20081005191603.html)
* [Tooling to build test cases](http://www.itmaybeahack.com/homepage/iblog/C20071019092637/E20080830091128.html)
* [What's Central Here?](http://www.itmaybeahack.com/homepage/iblog/C465799452/E20080712112540.html)
* [Control-Break Reporting](http://www.itmaybeahack.com/homepage/iblog/C588245363/E20060206184914.html)
* [One More Cool Thing About Python Is...](http://www.itmaybeahack.com/homepage/iblog/C588245363/E20051022112554.html)
* [In Praise of Serialization](http://www.itmaybeahack.com/homepage/iblog/C465799452/E20080603055001.html)
And that's just me.
---
Edit: "boss prompted ME to investigate", "figure out how we can use it" changes everything.
The "finally convince my boss to really learn Python" is misleading. You aren't swimming upstream. See [How Do I Make the Business Case for Python](https://stackoverflow.com/questions/202337/how-do-i-make-the-business-case-for-python) for the "convince my boss" problem. The edit says you're past this phase.
Dynamic languages offer flexibility. Exploit that. My two sets of examples above are two areas where flexibility matters.
* Requirements aren't totally nailed down. With a dynamic language, you can get started. Rework won't be a deal-breaker. With Java (and C++ and C#) you are reluctant to tackle devastating design changes because it's hard to break everything and get it to compile and work again. In Python, devastating changes aren't as expensive.
* Design is in flux because you can't pick components. You can write Wrappers and Facades very easily in Python. It's a scripting language. And, Python modules compose into larger aggregates very simply.
* Coding is in flux because requirements and design keep changing. It's scripted -- not compiled. You just make a change to the code and you're off and running. Testing is easier because the work cycle is shorter. It isn't code-compile-build-test it's code-test.
* Testing is in flux because the requirements keep changing. Same as above. The work cycle is shorter and faster.
|
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, and other people will probably notice it. They then say "Can you send me that program?" and boom, they're using your new language.
If you really want to something, I would probably write a site in Django, simply because its admin interface blows everyone away.
The main point to remember is that if you start using python, that's one more thing everyone else has to learn, and it's another bullet point that will need to be on every prospective employee's resume. That can get expensive, and management won't like it.
|
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. I want to catch the exception and to make visible an user friendly error in the current view, preferably with the controls loaded with the same values submitted.
I have found this <http://www.romsteady.net/blog/2007/06/how-to-catch-httprequestvalidationexcep.html>, but it is useless for my purpose. Also, I have found this <http://msdn.microsoft.com/en-us/library/aa973813.aspx> and tried to put inside a model binder but I couldn't make to work.
|
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 have said, you do then have to perform your own manual input validation or cleaning.
Using MVC 3, you must also ensure this is in your Web.config: `<system.web><httpRuntime requestValidationMode="2.0" /></system.web>`
|
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 via NuGet) to sanitize the user input by calling the `Sanitizer.GetSafeHtmlFragment(mymodel.Description)` (where the "Description" property is a string property on my view model, that has the `[AllowHtml]` attribute applied)
|
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 element names. Something like this:
```
XElement newOrder = new XElement("Order");
newOrder.Add(new XElement("OrderId", (string)oldOrder.Element("OrderId")),
newOrder.Add(new XElement("OrderName", (string)oldOrder.Element("OrderName")),
...............
...............
...............and so on
```
The newOrder document may contain additional nodes which will be set to null if nothing is found for them in the oldOrder. So do I have any other choice than to hardcode 150 element names like orderId, orderName and so on... Or is there some better more maintainable way?
|
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 know XSL/XSLT, then learning it is something that'll bank you CV :)
Good luck!
|
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 when I click on the link.
What stupid thing am I doing wrong? (I've tried click= and onClick=)...
```
<script language="javascript">
function init(){
document.getElementById("foo").click = new function() { alert('foo'); };
}
</script>
<body onload="init()">
<a id="foo" href=#>Click to run foo</a>
</body>
```
---
**Edit:** I changed my accepted answer to a jQuery answer. The answer by '[Már Örlygsson](https://stackoverflow.com/questions/249074/how-to-change-onclick-handler-dynamically/249093#249093)' is technically the correct answer to my original question (`click` should be `onclick` and `new` should be removed) but I **strongly discourage** anyone from using 'document.getElementById(...) directly in their code - and to use [jQuery](http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery) instead.
|
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 Microsoft compiler tested. Do they purge out downloads for older versions?
|
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 by a signed or unsigned integer data type. The fractional part is represented by an unsigned data integer data type.
Let's make an analogy with money for the sake of clarity. The fractional part may represent cents -- a fractional part of a dollar. The range of the 'cents' data type would be 0 to 99. If a 8-bit unsigned integer were to be used for fixed-point math, then the fractional part would be split into 256 evenly divisible parts.
I hope that clears things up.
|
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);
fracPart = static_cast<unsigned short>
(numeric_limits<unsigned short> + 1.0)*d);
return *this;
}
// Other operators can be defined here
};
```
**EDIT:** Here's a more general class based on anothercommon way to deal with fixed-point numbers (and which KPexEA pointed out):
```
template <class BaseType, size_t FracDigits>
class fixed_point
{
const static BaseType factor = 1 << FracDigits;
BaseType data;
public:
fixed_point(double d)
{
*this = d; // calls operator=
}
fixed_point& operator=(double d)
{
data = static_cast<BaseType>(d*factor);
return *this;
}
BaseType raw_data() const
{
return data;
}
// Other operators can be defined here
};
fixed_point<int, 8> fp1; // Will be signed 24:8 (if int is 32-bits)
fixed_point<unsigned int, 16> fp1; // Will be unsigned 16:16 (if int is 32-bits)
```
|
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:8
```
double f = 1.2345;
int n;
n=(int)(f*256);
```
|
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* p = new int[1];
```
If this was true, the `delete` operator could always be deleting arrays, and we wouldn't need the `delete[]` operator.
Is there any reason why the `delete[]` operator was introduced in C++? The only reason I can think of is that allocating arrays has a small memory footprint (you have to store the array size somewhere), so that distinguishing `delete` vs `delete[]` was a small memory optimization.
|
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[]` and `delete[]`? I would go back Stroustrup's "Design and Evolution" book where he said that if you don't use C++ features, you shouldn't have to pay for them (at run time at least). The way it stands now, a `new` or `delete` will behave as efficiently as `malloc` and `free`. If `delete` had the `delete[]` meaning, there would be some extra overhead at run time (as James Curran pointed out).
|
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 processed by a front-end and then fed to an ordinary C compiler. They could not do the trick of storing the count somewhere beneath the curtain, maybe they could not even think of it at that time. And for backward compatibility, the compilers most probably used the value given between the `[]` as the count of array, if there is no such value then they got the count from the prefix, so it worked both ways. Later on, we typed nothing between `[]` and everything worked. Today, I do not think `delete[]` is necessary but the implementations demand it that way.
My original answer (that misses the point):
`delete` deletes a single object. `delete[]` deletes an object array. For `delete[]` to work, the implementation keeps the number of elements in the array. I just double-checked this by debugging ASM code. In the implementation (VS2005) I tested, the count was stored as a prefix to the object array.
If you use `delete[]` on a single object, the count variable is garbage so the code crashes. If you use `delete` for an object array, because of some inconsistency, the code crashes. I tested these cases just now !
"`delete` just deletes the memory allocated for the array." statement in another answer is not right. If the object is a class, `delete` will call the DTOR. Just place a breakpoint int the DTOR code and `delete` the object, the breakpoint will hit.
What occurred to me is that, if the compiler & libraries assumed that all the objects allocated by `new` are object arrays, it would be OK to call `delete` for single objects or object arrays. Single objects just would be the special case of an object array having a count of 1. Maybe there is something I am missing, anyway.
|
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 in memory. Is this at all possible?
|
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 column is possible by first creating the row with the blob column that you need to insert into, the repeatedly calling an update statement:
```
update myTable set myColumn.Write(@data, @offset, @length) where someid = @someId
```
for chunks of bytes from the stream.
[Perfect example located here.](http://weblogs.asp.net/alessandro/archive/2008/09/22/conserving-resources-when-writing-blob-values-to-sql-server-and-streaming-blob-values-back-to-the-client.aspx)
|
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/ms345123.aspx>
|
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, @StartDate) = 'Sunday' THEN 1 ELSE 0 END)
-(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday' THEN 1 ELSE 0 END)
```
If you want to include holidays, you have to work it out a bit...
|
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
--If the function already exists, drop it.
IF EXISTS
(
SELECT *
FROM dbo.SYSOBJECTS
WHERE ID = OBJECT_ID(N'[dbo].[fn_WorkDays]')
AND XType IN (N'FN', N'IF', N'TF')
)
DROP FUNCTION [dbo].[fn_WorkDays]
GO
CREATE FUNCTION dbo.fn_WorkDays
--Presets
--Define the input parameters (OK if reversed by mistake).
(
@StartDate DATETIME,
@EndDate DATETIME = NULL --@EndDate replaced by @StartDate when DEFAULTed
)
--Define the output data type.
RETURNS INT
AS
--Calculate the RETURN of the function.
BEGIN
--Declare local variables
--Temporarily holds @EndDate during date reversal.
DECLARE @Swap DATETIME
--If the Start Date is null, return a NULL and exit.
IF @StartDate IS NULL
RETURN NULL
--If the End Date is null, populate with Start Date value so will have two dates (required by DATEDIFF below).
IF @EndDate IS NULL
SELECT @EndDate = @StartDate
--Strip the time element from both dates (just to be safe) by converting to whole days and back to a date.
--Usually faster than CONVERT.
--0 is a date (01/01/1900 00:00:00.000)
SELECT @StartDate = DATEADD(dd,DATEDIFF(dd,0,@StartDate), 0),
@EndDate = DATEADD(dd,DATEDIFF(dd,0,@EndDate) , 0)
--If the inputs are in the wrong order, reverse them.
IF @StartDate > @EndDate
SELECT @Swap = @EndDate,
@EndDate = @StartDate,
@StartDate = @Swap
--Calculate and return the number of workdays using the input parameters.
--This is the meat of the function.
--This is really just one formula with a couple of parts that are listed on separate lines for documentation purposes.
RETURN (
SELECT
--Start with total number of days including weekends
(DATEDIFF(dd,@StartDate, @EndDate)+1)
--Subtact 2 days for each full weekend
-(DATEDIFF(wk,@StartDate, @EndDate)*2)
--If StartDate is a Sunday, Subtract 1
-(CASE WHEN DATENAME(dw, @StartDate) = 'Sunday'
THEN 1
ELSE 0
END)
--If EndDate is a Saturday, Subtract 1
-(CASE WHEN DATENAME(dw, @EndDate) = 'Saturday'
THEN 1
ELSE 0
END)
)
END
GO
```
If you need to use a custom calendar, you might need to add some checks and some parameters. Hopefully it will provide a good starting point.
|
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 model attribute and 'value' is the search criteria for that attribute. Each "name" will be treated like a category to return subsets of the model instances where the categories match.
Now, this could be handled with GET parameters, but I prefer more readable URLs for both the user's sake and the search engines. These URLs subsets will be embedded on each page that displays this model, so it seems worth the effort to make pretty URLs.
Ideally each name/value pair will be passed to the view function as a parameter named `name1`, `name2`, etc. However, I don't believe it's possible to defined named patterns via a regex's matched text. Am I wrong there?
So, it seems I need to do something like this:
```
urlpatterns = patterns('',
url(r'^browse/(?:([\w]+)/([\w]+)/)+$', 'app.views.view', name="model_browse"),
)
```
It seems this should match any sets of two name/value pairs. While it matches it successfully, it only passes the last name/value pair as parameters to the view function. My guess is that each match is overwriting the previous match. Under the guess that the containing (?:...)+ is causing it, I tried a simple repeating pattern instead:
```
urlpatterns = patterns('',
url(r'^browse/([\w]+/)+$', 'app.views.view', name="model_browse"),
)
```
... and got the same problem, but this time `*args` only includes the last matched pattern.
Is this a limitation of Django's url dispatcher, and/or Python's regex support? It seems either of these methods should work. Is there a way to achieve this without hardcoding each possible model attribute in the URL as an optional (.\*) pattern?
|
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):
pieces = match.split('/')
# even indexed pieces are the names, odd are values
...
```
No promises about the regexp I used, but I think you understand what I mean.
(Edited to try and fix the regexp.)
|
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 contents of the login page, forcing the user's eyes to witness a rare scene indeed.
How can I manage a redirect directive from an Ajax call with jQuery 1.2.6?
|
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 actual callback function.
For example, our wrapper function was something like:
```
function cbWrapper(data, funct){
if($("#myForm", data).length > 0)
top.location.href="login.htm";//redirection
else
funct(data);
}
```
Then, when making the Ajax call we used something like:
```
$.post("myAjaxHandler",
{
param1: foo,
param2: bar
},
function(data){
cbWrapper(data, myActualCB);
},
"html"
);
```
This worked for us because all Ajax calls always returned HTML inside a DIV element that we use to replace a piece of the page. Also, we only needed to redirect to the login page.
|
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 approach and used [JSON](http://en.wikipedia.org/wiki/JSON). In this case, all responses to AJAX requests have the *status code* 200 and the body of the response contains a JSON object that is constructed on the server. The JavaScript on the client can then use the JSON object to decide what it needs to do.
I had a similar problem to yours. I perform an AJAX request that has 2 possible responses: one that *redirects* the browser to a new page and one that *replaces* an existing HTML form on the current page with a new one. The jQuery code to do this looks something like:
```
$.ajax({
type: "POST",
url: reqUrl,
data: reqBody,
dataType: "json",
success: function(data, textStatus) {
if (data.redirect) {
// data.redirect contains the string URL to redirect to
window.location.href = data.redirect;
} else {
// data.form contains the HTML for the replacement form
$("#myform").replaceWith(data.form);
}
}
});
```
The JSON object "data" is constructed on the server to have 2 members: `data.redirect` and `data.form`. I found this approach to be much better.
|
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 operations which can be written by using only member functions should not be part of the class. They should be nonmembers and nonfriends. The arguments are that:
* It promotes encapsulation, because there is less code that needs access to the internals of a class.
* It makes writing function templates easier, because you don't have to guess each time whether some function is a member or not.
* It keeps the class small, which in turn makes it easier to test and maintain.
Although I see the value in these argument, I see a huge drawback: **my IDE can't help me find these functions!** Whenever I have an object of some kind, and I want to see what operations are available on it, I can't just type "`pMysteriousObject->`" and get a list of member functions anymore.
Keeping a clean design is in the end about making your programming life easier. But this would actually make mine much harder.
So I'm wondering if it's really worth the trouble. **How do you deal with that?**
|
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 conceptually part of `Bar`. It can also mean that the code is well factored. It's not uncommon to have member functions which perform all their behavior via other member functions, and I don't see why it should be.
I fully agree that peripherally-related functions should *not* be part of the class, but if something is core to the class responsibilities, there's no reason it shouldn't be a member, regardless of whether it is directly mucking around with the member data.
As for these specific points:
> *It promotes encapsulation, because there is less code that needs access to the internals of a class.*
Indeed, the fewer functions that directly access the internals, the better. That means that having member functions do as much as possible *via* other member functions is a good thing. Splitting well-factored functions out of the class just leaves you with a half-class, that requires a bunch of external functions to be useful. Pulling well-factored functions away from their classes also seems to discourage the writing of well-factored functions.
> *It makes writing function templates easier, because you don't have to guess each time whether some function is a member or not.*
I don't understand this at all. If you pull a bunch of functions out of classes, you've thrust more responsibility onto function templates. They are forced to assume that *even less* functionality is provided by their class template arguments, unless we are going to assume that most functions pulled from their classes is going to be converted into a template (ugh).
> *It keeps the class small, which in turn makes it easier to test and maintain.*
Um, sure. It also creates a lot of additional, external functions to test and maintain. I fail to see the value in this.
|
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-members. The "best" interface for a class can be found only by balancing many competing concerns, of which the degree of encapsulation is but one."*
If a function would be something that "just makes sense" to be a member function, make it one. Likewise, if it isn't really part of the main interface, and "just makes sense" to be a non-member, do that.
One note is that with overloaded versions of eg operator==(), the syntax stays the same. So in this case you have no reason **not** to make it a non-member non-friend floating function declared in the same place as the class, unless it really needs access to private members (in my experience it rarely will). And even then you can define operator!=() a non-member and in terms of operator==().
|
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').innerHTML = bill.time[breakfast][bill.pointPartOfWeek];
document.getElementById('ln').innerHTML = bill.time[lunch][bill.pointPartOfWeek];
document.getElementById('dn').innerHTML = bill.time[dinner][bill.pointPartOfWeek];
document.getElementById('se').innerHTML = bill.time[special][bill.pointPartOfWeek];
document.getElementById('fdr').innerHTML = bill.time[full][bill.pointPartOfWeek];
document.getElementById('cost').innerHTML = bill.cost;
}
```
And it executes fine in the following instance:
```
<select onchange='if(this.selectedIndex == 0) {bill.unholiday();updateFields()} else { bill.holiday();updateFields()}' id='date' name='date'>
<option value='else'>Jan. 02 - Nov. 20</option>
<option value='christmas'>Nov. 20 - Jan. 01</option>
</select>
```
but in this very similar code, the last line of the function doesn't seem to execute (it doesn't update the cost field, but updates everything else)
```
<select onchange='if(this.selectedIndex == 0) {bill.pointPartOfWeek = 1;} else { bill.pointPartOfWeek = 2;}updateFields();alert(updateFields());' id='day' name='day'>
<option value='0'>Monday thru Thursday</option>
<option value='1'>Friday, Saturday, or Sunday</option>
</select>
<br />
```
Strangely enough, the total cost variable itself is updated, but the field that represents the variable is not. If you use another section of the page that wouldn't change the value of the total cost but calls the updateFields function again, the cost field then updates correctly. It must be an issue with the function called.
Note: we know that the function executes because it does 5 out of 6 of the things it is supposed to do. This is a strange issue.
Edit: The pastebin for the entire page my be helpful. Here it is:
<http://pastebin.com/f70d584d3>
|
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 the case.
UPDATE: It turns out that you need to call bill.holiday() or bill.unholiday() before calling updateFields() in your second select.
|
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:
```
document.getElementById('bf')
```
becomes
```
$('bf')
```
And similarly you can update the innerHTML of an element easily:
```
$('bf').update(bill.time[breakfast][bill.pointPartOfWeek]);
```
Check it out. It's saved my bacon more than a couple times.
|
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 long.
The other possibility is funky (technical term) whitespace. The context is a screen-scraping app, where I'm using HtmlCleaner to tidy up the messy html. While I've found HtmlCleaner to be pretty good overall, I've noticed strange issues with characters that look like whitespace but aren't recognized as such with a StringTokenizer, for example. I've mostly worked around it and haven't dug into the character encoding or anything like that but am starting to wonder.
|
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 least with my jdk / jre version (1.6), the format strings seem to work just fine. i think the next step is to make sure the string you're dealing with is exactly what you think it is. Can you add logging to your code, and dump out the input string to a log file? Then you could look at it in a nice text editor, run it through your test class, or look at it in a hex editor to make sure that it's just normal text.
Good luck!
|
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 converting the date string to a char array, checking the characters with Character.isSpaceChar(), and replacing those that returned true with a " " char.
|
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 exactly 1 object of class C, i.e. a W object is contained in one C object.
An object of class C is usually instantiated first. At a later point, its W contents are discovered, and instantiated. At this later point, I need to cross reference the C and W objects to each other.
What is a good design pattern for this? I actually have cases where I have three or four classes involved but we can talk about two classes to keep it simple.
I was thinking of something simple like:
```
class C
{
public List<W> contentsW;
}
class W
{
public C containerC;
}
```
This will work for the moment but I can foresee having to write a fair amount of code to keep track of all the references and their validity. I'd like to implement code down the road to do shallow refreshes of just the container and deep refreshes of all referenced classes. Are there any other approaches and what are their advantages?
Edit on 11/3:
Thanks to all for the good answers and good discussion. I finally chose jop's answer because that came closest to what I wanted to do, but the other answers also helped. Thanks again!
|
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 and change
// anything
private List<W> contentsW;
public void Add(W theW)
{
theW.Container = this;
}
public void Remove(W theW)
{
theW.Container = null;
}
#region Only to be used by W
internal void RemoveW(W theW)
{
// do nothing if C does not contain W
if (!contentsW.Contains(theW))
return; // or throw an exception if you consider this illegal
contentsW.Remove(theW);
}
internal void AddW(W theW)
{
if (!contentW.Contains(theW))
contentsW.Add(theW);
}
#endregion
}
class W
{
private C containerC;
public Container Container
{
get { return containerC; }
set
{
if (containerC != null)
containerC.RemoveW(this);
containerC = value;
if (containerC != null)
containerC.AddW(this);
}
}
}
```
Take note that I've made the `List<W>` private. Expose the list of Ws via an enumerator instead of exposing the list directly.
e.g. public List GetWs() { return this.ContentW.ToList(); }
The code above handles transfer of ownership properly. Say you have two instances of C -- C1 and C2 - and the instances of W -- W1 and W2.
```
W1.Container = C1;
W2.Container = C2;
```
In the code above, C1 contains W1 and C2 contains W2. If you reassign W2 to C1
```
W2.Container = C1;
```
Then C2 will have zero items and C1 will have two items - W1 and W2. You can have a floating W
```
W2.Container = null;
```
In this case, W2 will be removed from C1's list and it will have no container. You can also use the Add and Remove methods from C to manipulate W's containers - so C1.Add(W2) will automatically remove W2 from it's original container and add it to the new one.
|
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 add items through your aggregate's method only.
|
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 each row.
Truncate is normally ultra-fast, ideal for cleaning out data from a temporary table. It does preserve the structure of the table for future use.
If you actually want to remove the table *definitions* as well as the data, simply drop the tables.
See [this MSDN article](http://msdn.microsoft.com/en-us/library/aa260621(SQL.80).aspx) for more info
|
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.python/msg/b9afcfc2e1de5b05)
However they don't give a definitive answer. The way to go:
1. Measure memory consumed by Python interpreter with/without the list (use OS tools).
2. Use a third-party extension module which defines some sort of sizeof(PyObject).
**Update**:
[Recipe 546530: Size of Python objects (revised)](http://code.activestate.com/recipes/546530/)
```
import asizeof
N = 1000000
print asizeof.asizeof(range(N)) / N
# -> 20 (python 2.5, WinXP, 32-bit Linux)
# -> 33 (64-bit Linux)
```
|
"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. So range(1000000) will actually allocate a list big enough to hold 2^20 elements (~ 1.045 million).
This is only the space required to store the list structure itself (which is an array of pointers to the Python objects for each element). A 32-bit system will require 4 bytes per element, a 64-bit system will use 8 bytes per element.
Furthermore, you need space to store the actual elements. This varies widely. For small integers (-5 to 256 currently), no additional space is needed, but for larger numbers Python allocates a new object for each integer, which takes 10-100 bytes and tends to fragment memory.
Bottom line: **it's complicated** and Python lists are **not** a good way to store large homogeneous data structures. For that, use the `array` module or, if you need to do vectorized math, use NumPy.
PS- Tuples, unlike lists, are *not designed* to have elements progressively appended to them. I don't know how the allocator works, but don't even think about using it for large data structures :-)
|
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 this capability--look for autocomplete controls for ideas.
See this link for the Autocomplete control...<http://ajaxcontroltoolkit.codeplex.com/>
|
*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](http://www.w3.org/TR/html5/content-models.html#interactive-content):
> Certain elements in HTML have an activation behavior, which means that the user can activate them. This triggers a sequence of events dependent on the activation mechanism [...] **for instance using keyboard or voice input, or through mouse clicks**.
> When the user triggers an element with a defined activation behavior in a manner other than clicking it, **the default action of the interaction event must be to run** synthetic click activation steps on the element.
`<select>` being an Interactive Content, I believed that it is possible to programatically display its `<option>`s. After a few hours of playing around, I discovered that using `document.createEvent()` and `.dispatchEvent()` works.
That said, demo time. [**Here is a working Fiddle.**](http://jsfiddle.net/fz2sY/39/)
```
// <select> element displays its options on mousedown, not click.
showDropdown = function(element) {
var event;
event = document.createEvent('MouseEvents');
event.initMouseEvent('mousedown', true, true, window);
element.dispatchEvent(event);
};
// This isn't magic.
window.runThis = function() {
var dropdown = document.getElementById('dropdown');
showDropdown(dropdown);
};
```
```
<select id="dropdown">
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
</select>
<br>
<button id="fire" type="button" onclick="runThis()">Show dropdown items</button>
```
If anyone finds a way to do the same but not in Chrome, [please feel free to modify this fiddle](http://jsfiddle.net/fz2sY/39/).
|
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, but at least it shows the intended effect.
```
class TextContainer extends JPanel
{
private int m_width;
private int m_height;
private String m_text;
private AttributedCharacterIterator m_iterator;
private int m_start;
private int m_end;
public TextContainer(String text, int width, int height)
{
m_text = text;
m_width = width;
m_height = height;
AttributedString styledText = new AttributedString(text);
m_iterator = styledText.getIterator();
m_start = m_iterator.getBeginIndex();
m_end = m_iterator.getEndIndex();
}
public String getText()
{
return m_text;
}
public Dimension getPreferredSize()
{
return new Dimension(m_width, m_height);
}
public void paint(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
FontRenderContext frc = g2.getFontRenderContext();
LineBreakMeasurer measurer = new LineBreakMeasurer(m_iterator, frc);
measurer.setPosition(m_start);
float x = 0, y = 0;
while (measurer.getPosition() < m_end)
{
TextLayout layout = measurer.nextLayout(m_width);
y += layout.getAscent();
float dx = layout.isLeftToRight() ?
0 : m_width - layout.getAdvance();
layout.draw(g2, x + dx, y);
y += layout.getDescent() + layout.getLeading();
}
}
}
```
Just for fun, I made it fitting a circle (alas, no justification, it seems):
```
public void paint(Graphics g)
{
super.paintComponent(g);
Graphics2D g2 = (Graphics2D) g;
FontRenderContext frc = g2.getFontRenderContext();
LineBreakMeasurer measurer = new LineBreakMeasurer(m_iterator, frc);
measurer.setPosition(m_start);
float y = 0;
while (measurer.getPosition() < m_end)
{
double ix = Math.sqrt((m_width / 2 - y) * y);
float x = m_width / 2.0F - (float) ix;
int width = (int) ix * 2;
TextLayout layout = measurer.nextLayout(width);
y += layout.getAscent();
float dx = layout.isLeftToRight() ?
0 : width - layout.getAdvance();
layout.draw(g2, x + dx, y);
y += layout.getDescent() + layout.getLeading();
}
}
```
I am not too sure about dx computation, though.
|
[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();
TextLayout layout = new TextLayout("This is a string", font, frc);
layout.draw(g, (float)loc.getX(), (float)loc.getY());
Rectangle2D bounds = layout.getBounds();
bounds.setRect(bounds.getX()+loc.getX(),
bounds.getY()+loc.getY(),
bounds.getWidth(),
bounds.getHeight());
g.draw(bounds);
```
Otherwise you could always use a Swing text element to do the job for you, just pass in the Graphics you want it to paint into.
|
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'm wondering if PHP has something like this. I'm sure I can emulate this with variables, but I imagine the fact that PHP is interpreted in most cases will not make it easy to strip/remove the debugging code (since its not needed) automatically when executing it.
|
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 all that. if you wanted to make life easier on regex parsing, perhaps you could use a ternary operator instead:
```
$str = 'string';
DEBUG ? $debug->writeLine("stuff is ".$str) : null;
```
which would make removing debug lines pretty trivial.
|
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 far as I'm concerned this shouldn't happen as the XML document has the encoding ISO-8859-1 (which doesn't have the TM symbol)
Thanks
|
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 include DOM and InfoSet, I'm not sure exactly which is accurate.
The "&#x" gubbins won't exist in this model because the whole issue is irrelevant, it will return - if appropriate - when you transform the Info Set back into a character stream in some specific encoding.
This misunderstanding is sufficiently common to have made it into academic literature as part of a collection of similar quirks. Take a look at "Xml Fever" at this location: <http://doi.acm.org/10.1145/1364782.1364795>
|
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>");
using (MemoryStream ms = new MemoryStream())
{
XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.GetEncoding("ISO-8859-1");
XmlWriter xw = XmlWriter.Create(ms, settings);
doc.Save(xw);
xw.Close();
Console.WriteLine(Encoding.UTF8.GetString(ms.ToArray()));
}
```
Outputs:
```
<?xml version="1.0" encoding="iso-8859-1"?><xml>™</xml>
```
|
.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.location = url;`
|
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 is with `window.parent.location` (or `window.location`.)
If changing the url of the page with javascript is not PCI compliant then you're trying to do something that is not PCI complicant.
|
`<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?
Bonus points for doing it in pure PHP (no `system('stty')`) and replacing the characters with `*`.
**EDIT:**
The script will run on a unix like system (linux or mac). The script is written in PHP, and will most likely stay like that.
Also, for the record, the `stty` way of doing it is:
```
echo "Password: ";
system('stty -echo');
$password = trim(fgets(STDIN));
system('stty echo');
// add a new line since the users CR didn't echo
echo "\n";
```
I'd prefer to not have the `system()` calls in there.
|
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(InputBox("'
. addslashes($prompt)
. '", "", "password here"))');
$command = "cscript //nologo " . escapeshellarg($vbscript);
$password = rtrim(shell_exec($command));
unlink($vbscript);
return $password;
} else {
$command = "/usr/bin/env bash -c 'echo OK'";
if (rtrim(shell_exec($command)) !== 'OK') {
trigger_error("Can't invoke bash");
return;
}
$command = "/usr/bin/env bash -c 'read -s -p \""
. addslashes($prompt)
. "\" mypassword && echo \$mypassword'";
$password = rtrim(shell_exec($command));
echo "\n";
return $password;
}
}
```
|
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 the password without displaying it on screen.
|
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 utility class for databinding does this:
```
PropertyInfo pi = ReflectionHelper.GetPropertyInfo(boundObjectType, sourceProperty);
if (!pi.CanWrite)
SetReadOnlyCharacteristics(boundEditor);
```
But PropertyInfo.CanWrite does not care whether the set is publicly accessible, only that it exists.
How can I determine if there's a **public** set, not just **any** set?
|
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, public static method, with `Console` as a '`this`' parameter... but no dice!
```
public static class Helpers {
public static void WriteBlueLine(this Console c, string text)
{
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine(text);
Console.ResetColor();
}
}
```
This didn't add a '`WriteBlueLine`' method to `Console`... am I doing it wrong? Or asking for the impossible?
|
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 ConfigurationManagerWrapper
{
public static ConfigurationSection GetSection( string name )
{
return ConfigurationManager.GetSection( name );
}
.....
public static ConfigurationSection GetWidgetSection()
{
return GetSection( "widgets" );
}
}
```
|
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()
{
Create = Expression.Lambda<Func<T>>(Expression.New(typeof(T).GetConstructor(Type.EmptyTypes))).Compile();
}
public static Func<T> Create { get; private set; }
}
```
Here's how it works. While you can't technically write static extension methods, instead this code exploits a loophole in extension methods. That loophole being that you can call extension methods on null objects without getting the null exception (unless you access anything via @this).
So here's how you would use this:
```
var ds1 = (null as DataSet).Create(); // as oppose to DataSet.Create()
// or
DataSet ds2 = null;
ds2 = ds2.Create();
// using some of the techniques above you could have this:
(null as Console).WriteBlueLine(...); // as oppose to Console.WriteBlueLine(...)
```
Now WHY did I pick calling the default constructor as an example, and AND why don't I just return new T() in the first code snippet without doing all of that Expression garbage?
Well todays your lucky day because you get a 2fer. As any advanced .NET developer knows, new T() is slow because it generates a call to System.Activator which uses reflection to get the default constructor before calling it. Damn you Microsoft!
However my code calls the default constructor of the object directly.
Static extensions would be better than this but desperate times call for desperate measures.
|
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 the same thing)*
|
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(new GLatLng(50, 50), { icon:customIcon }));
```
However, this adds an overlay that maintains the same size as the user zooms in and out (it is acts as a UI element like the sidebar zoom control).
|
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 easy lining up.
|
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 URL after the browser is redirected to my custom 404 page. I tried using:
```
request.ServerVariables("HTTP_REFERER") 'sorry i corrected the typo from system to server.
```
But that didn't work.
Any Ideas?
The site is on IIS 6.0.
We did consider using 301 redirects, but we don't have any way of knowing what pages people have bookmarked and there are a few hundred pages, so no one is keen on spending the time to create the 301's.
|
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, some URLs changed so I look for keywords in the old URL and forward.
```
//did the error go to a .ASP page? If so, append x (for .aspx) and
//issue a 301 permanently moved
//when we get an error, the querystring will be "404;<complete original URL>"
string targetPage = Request.RawUrl.Substring(Request.FilePath.Length);
if((null == targetPage) || (targetPage.Length == 0))
targetPage = "[home page]";
else
{
//find the original URL
if(targetPage[0] == '?')
{
if(-1 != targetPage.IndexOf("?aspxerrorpath="))
targetPage = targetPage.Substring(15); // ?aspxerrorpath=
else
targetPage = targetPage.Substring(5); // ?404;
}
else
{
if(-1 != targetPage.IndexOf("errorpath="))
targetPage = targetPage.Substring(14); // aspxerrorpath=
else
targetPage = targetPage.Substring(4); // 404;
}
}
string upperTarget = targetPage.ToUpper();
if((-1 == upperTarget.IndexOf(".ASPX")) && (-1 != upperTarget.IndexOf(".ASP")))
{
//this is a request for an .ASP page - permanently redirect to .aspx
targetPage = upperTarget.Replace(".ASP", ".ASPX");
//issue 301 redirect
Response.Status = "301 Moved Permanently";
Response.AddHeader("Location",targetPage);
Response.End();
}
if(-1 != upperTarget.IndexOf("ORDER"))
{
//going to old order page -- forward to new page
Response.Redirect(WebRoot + "/order.aspx");
Response.End();
}
```
|
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>.
These are then returned as a contiguous block. Essentially, SelectMany is something like (simplified):
```
static IEnumerable<TResult> SelectMany<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, IEnumerable<TResult>> selector) {
foreach(TSource item in source) {
foreach(TResult result in selector(item)) {
yield return result;
}
}
}
```
Although that is simplified somewhat.
|
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 other processing on the data. I'm trying to figure out the most effective method. I need to have some way of getting the flag through, so I know I'm talking about data sliced by the right field.
One possible solution I was playing around with a bit (mostly to see what would happen) is to dump the contents of the script into a table function which has the flag passed to it, and then use a SELECT query on the results of the function. I've managed to get it to work, but it's significantly slower than...
The obvious solution, and probably the most efficient use of processor cycles: to create a series of cache tables, one for each of the three flag values. However, the problem then is to find some way of extracting the data from the right cache table to perform the calculation. The obvious, though incorrect, response would be something like
```
SELECT CASE @Flag WHEN 1 THEN table1.field WHEN 2 THEN table2.field WHEN 3
THEN table3.field END as field,
...[The various calculated fields]
FROM table1, table2, table3
```
Unfortunately, as is obvious, this creates a massive cross join - which is not my intended result at all.
Does anyone know how to turn that cross join into an "Only look at x table"? (Without use of Dynamic SQL, which makes things hard to deal with?) Or an alternative solution, that's still reasonably speedy?
EDIT: Whether it's a good reason or not, the idea I was trying to implement was to not have three largely identical queries, that differ only by table - which would then have to be edited identically whenever a change is made to the logic. Which is why I've avoided the "Have the flag entirely separate" thing thus far...
|
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 to me in the first place.
|
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.0 (Visual Studio 2008) vs. C# 2.0 (Visual Studio 2005)?
|
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 items individually, I can initialize types that implement IEnumerable like this:
```
List<string> list = new List<string> { "foo", "bar" };
```
The new syntax for lambda expressions is also nice. Instead of typing this:
```
people.Where(delegate(person) { return person.Age >= 21;);
```
I can type this:
```
people.Where(person => person.Age >= 21 );
```
You can also write extension methods to built in types:
```
public static class StringUtilities
{
public static string Pluralize(this word)
{
...
}
}
```
Which allows something like this:
```
string word = "person";
word.Pluralize(); // Returns "people"
```
And finally. Anonymous types. So you can create anonymous classes on the fly, like this:
```
var book = new { Title: "...", Cost: "..." };
```
|
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>
<orderNumber>050758023</orderNumber>
<ParcelID/>
<CustomerName>sddsf</CustomerName>
<DeliveryName>dsfd</DeliveryName>
<Address1>sdf</Address1>
<Address2>sdfsdd</Address2>
<Address3>sdfdsfdf</Address3>
<Address4>dffddf</Address4>
<PostCode/>
</order>
<order>
<Date>2008-10-13</Date>
<orderNumber>050758023</orderNumber>
<ParcelID/>
<CustomerName>sddsf</CustomerName>
<DeliveryName>dsfd</DeliveryName>
<Address1>sdf</Address1>
<Address2>sdfsdd</Address2>
<Address3>sdfdsfdf</Address3>
<Address4>dffddf</Address4>
<PostCode/>
</order>
.....
.....
</docket>
```
There could be thousands of orders in a docket.
I need to chop this into 100 element chunks
However each of the 100 orders still need to be wrapped with the parent "docket" node and have the same namespace etc
is this possible?
|
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)
{
List<XmlDocument> newDockets = new List<XmlDocument>();
//
int orderCount = docket.SelectNodes("//docket/order").Count;
int chunkStart = 0;
XmlDocument newDocket = null;
XmlElement root = null;
XmlNodeList chunk = null;
while (chunkStart < orderCount)
{
newDocket = new XmlDocument();
root = newDocket.CreateElement("docket");
newDocket.AppendChild(root);
chunk = docket.SelectNodes(String.Format("//docket/order[position() > {0} and position() <= {1}]", chunkStart, chunkStart + chunkSize));
chunkStart += chunkSize;
XmlNode targetNode = null;
foreach (XmlNode c in chunk)
{
targetNode = newDocket.ImportNode(c, true);
root.AppendChild(targetNode);
}
newDockets.Add(newDocket);
}
return newDockets;
}
```
|
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
{
newDocket = new XDocument(new XElement("docket"));
var chunk = orders.Take(chunkSize);
newDocket.Root.Add(chunk);
chunk.Remove();
newDockets.Add(newDocket);
} while (orders.Any());
return newDockets;
}
```
|
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", errorMessage);
%>
<jsp:forward page="error.jsp" />
<%
} else {
String url = response.encodeRedirectURL("index.jsp");
response.sendRedirect(url);
}
%>
```
Having to break the <% ... %> block to use the jsp:forward is ugly and makes it harder to read due to indentation, among other things.
So, can I do the forward in the Java code without use the JSP tag?
Something like this would be ideal:
```
<%
String errorMessage = SomeClass.getInstance().doSomething();
if (errorMessage != null) {
session.setAttribute("error", errorMessage);
someObject.forward("error.jsp");
} else {
String url = response.encodeRedirectURL("index.jsp");
response.sendRedirect(url);
}
%>
```
|
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().doSomething();
pageContext.setAttribute("errorMessage", errorMessage);
%>
<c:choose>
<c:when test="${not empty errorMessage}">
<c:set var="error" scope="session" value="${errorMessage}" />
<jsp:forward page="error.jsp" />
</c:when>
<c:otherwise>
<c:redirect url="index.jsp" />
</c:otherwise>
</c:choose>
```
Ideally, you'd modify error.jsp so that the error message doesn't even need to be set in the session, but I didn't want to change your design too much.
|
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 config with mod\_python almost always ends in trouble -- environment variables and C extensions leak across sites when you do that).
* Easy code reloads (set it up right and you can just touch the `.wsgi` file to reload instead of restarting Apache).
* More predictable resource usage. With mod\_python, a given Apache child process' memory use can jump around a lot. With mod\_wsgi it's pretty stable: once everything's loaded, you know that's how much memory it'll use.
|
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 of django that does stuff like digest auth, or any fancy HTTP header getting/setting. Perhaps you want to use other builtin features of apache such as mod\_rewrite.
If memory is a concern, staying away form apache/mod\_python will help a lot. Apache tends to use a lot of RAM, and the mod\_python code that glues into all of the apache functionality occupies a lot of memory-space as well. Not to mention the multiprocess nature of apache tends to eat up more RAM, as each process grows to the size of it's most intensive request.
|
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 (with --no-site-packages) aware of specific modules that are located elsewhere on the system.
What's the best way to do this? Or should I just suck it up and drop the --no-site-packages option?
|
```
$ 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/cairo/
$ python
>>> import pygtk
>>> import gtk
```
|
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 probably don't want to add this to all your related code.
I've seen mention of sitecustomize.py being used to perform something like this, but after some testing I couldn't get it to work as might be expected.
Here it mentions that auto-import of sitecustomize.py ended in 2.5, if your not on 2.5 try it out. (just add one of the path add methods above to the file and drop it in the directory your program is run)
A work around method is mentioned in the post for users of 2.5 and up.
<http://code.activestate.com/recipes/552729/>
|
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/version.txt');
// this is the version of the deployed script
define('VERSION', '1.0.1');
function isUpToDate()
{
$remoteVersion=trim(file_get_contents(REMOTE_VERSION));
return version_compare(VERSION, $remoteVersion, 'ge');
}
```
`version.txt` should just contain the most recent version number, e.g.:
```
1.0.2
```
|
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 version (\d*(\.\d+)*) -->/', $script, $version_match)) {
$version = $version_match[1];
}
```
|
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') document.write('<scr'+'ipt type="text/javascript" src="http://z-ecx.images-amazon.com/images/G/01/javascripts/lib/jquery/jquery-1.2.6.pack._V265113567_.js"></sc'+'ript>');
</script>
```
|
`</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/types.html#type-cdata):
> Although the STYLE and SCRIPT elements use CDATA for their data model, for these elements, CDATA must be handled differently by user agents. Markup and entities must be treated as raw text and passed to the application as is. The first occurrence of the character sequence "`</`" (end-tag open delimiter) is treated as terminating the end of the element's content. In valid documents, this would be the end tag for the element.
However in practice browsers only end parsing a CDATA script block on an actual `</script>` close-tag.
In XHTML there is no such special handling for script blocks, so any `<` (or `&`) character inside them must be `&escaped;` like in any other element. However then browsers that are parsing XHTML as old-school HTML will get confused. There are workarounds involving CDATA blocks, but it's easiest simply to avoid using these characters unescaped. A better way of writing a script element from script that works on either type of parser would be:
```
<script type="text/javascript">
document.write('\x3Cscript type="text/javascript" src="foo.js">\x3C/script>');
</script>
```
|
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 to most examples on the net, I'm not setting `type="text/javascript"` on neither the enclosing tag, nor the generated one: there is no browser not having that as the default, and so it is redundant, but will not hurt either, if you disagree).
|
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 which, at least for the moment, I would like to avoid. With the JDI I can use Java and it seems I'm able to use it from within the application. But I wasn't able to find some kind of tutorial or HOWTO for it. The only documentation I could find, were the Java-Docs <http://java.sun.com/j2se/1.5.0/docs/guide/jpda/jdi/> which isn't very helpful, because it doesn't show me how to use this classes.
So, does anybody know of a good tutorial/book I could read?
Thx for any help!
|
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 quick command line method for obtaining stack traces of all current threads.
This article suggest JDI is also used as a [remote tool](http://xudegui.blogspot.com/2008/03/jdb-example-generating-thread-dump.html).
So I am not sure you can triggers a thread dump within your own program, instead you find a way to send to yourself a SIGQUIT signal (kill -3) on Unix platforms, or press the Ctrl-\ key on Unix or Ctrl-Break on Windows platforms.
Plus, [JDI wasn't intended to be used to debug the same process in which the JDI client is running](http://x86.sun.com/thread.jspa?threadID=5284700&tstart=0). Still this thread I just linked to is the closest I have found to actually use JDI within the same program.
|
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-null timestamps
```
Is that possible?
**Update:** The table is quite large, so efficiency is important. I could just run two queries to calculate each total separately, but I want to avoid hitting the table twice if I can avoid it.
|
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 maintenance.
That being said you should design/create as many as your application requires. Although with Hibernate, NHibernate, .NET LINQ I would try to keep as much store procedures logic in the code, and only put it in the database when speed is a factor.
|
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 with a busy indicator (in the center) till the calculator function ends, so that user waits till process ends.
```
function CalculateAmountOnClick() {
// Display transparent div
// MY time consuming loop!
{
}
// Remove transparent div
}
```
Any ideas on how to go about this? Should i assign a css class to a div (which surrounds my entire page's content) using javascript when my calculator function starts? I tried that but didnt get desired results. Was facing issues with transparency in IE 6. Also how will i show a loading message + image in such a transparent div?
TIA
|
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.removeChild( curtain );
}
}
```
Your CSS:
```
#curtain {
position: fixed;
_position: absolute;
z-index: 99;
left: 0;
top: 0;
width: 100%;
height: 100%;
_height: expression(document.body.offsetHeight + "px");
background: url(curtain.png);
_background: url(curtain.gif);
}
```
(Move MSIE 6 underscore hacks to conditionally included files as desired.)
You could set this up as add/remove functions for the curtain, or as a wrapper:
```
function modalProcess( callback ) {
var ret;
var curtain = document.body.appendChild( document.createElement('div') );
curtain.id = "curtain";
curtain.onkeypress = curtain.onclick = function(){ return false; }
try {
ret = callback();
}
finally {
curtain.parentNode.removeChild( curtain );
}
return ret;
}
```
Which you could then call like this:
```
var result = modalProcess(function(){
// your operations here
});
```
|
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 the DOM. It may woit to see if you're doing something more, and then draw what is needed (browsers vary their method for this). So in this case it may be refreshing the display only after it has removed the curtain, or you have forced a redraw by scrolling.
A fair waring: This kind of intense processing isn't very nice of you because it not only locks up your page. Because browsers generally implement only a single Javascript thread for ALL tabs, your processing will lock up all open tabs (= the browser). Also, you run the risk of the execution timeout and browser simply stopping your script (this can be as low as 5 seconds).
Here is a way around that.
If you can break your processing up into smaller chunks you could run it with a timeout (to allow the browser breathing space). Something like this should work:
```
function processLoop( actionFunc, numTimes, doneFunc ) {
var i = 0;
var f = function () {
if (i < numTimes) {
actionFunc( i++ ); // closure on i
setTimeout( f, 10 )
}
else if (doneFunc) {
doneFunc();
}
};
f();
}
// add a curtain here
processLoop(function (i){
// loop code goes in here
console.log('number: ', i);
},
10, // how many times to run loop
function (){
// things that happen after the processing is done go here
console.log('done!');
// remove curtain here
});
```
This is essentially a while loop but each iteration of the loop is done in an timed interval so the browser has a bit of time to breathe in between. It will slow down the processing though, and any work done afterwards needs to go into a callback as the loop runs independently of whatwever may follow the call to processLoop.
Another variation on this is to set up the curtain, call your processing function with a setTimeout to allow the browser time to draw the curtain, and then remove it once you're done.
```
// add a curtain
var curtain = document.body.appendChild( document.createElement('div') );
curtain.id = "curtain";
curtain.onkeypress = curtain.onclick = function(){ return false; }
// delay running processing
setTimeout(function(){
try {
// here we go...
myHeavyProcessingFunction();
}
finally {
// remove the curtain
curtain.parentNode.removeChild( curtain );
}
}, 40);
```
If you are using a js-library, you may want to look at a ready made solution for creating curtains. These should exist for most libraries, [here is one for jQuery](http://www.malsup.com/jquery/block/), and they can help with the CSS.
|
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 windows services.
Thank you.
|
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/system.web.ui.timer.aspx) and [`System.Windows.Forms.Timer`](http://msdn.microsoft.com/en-us/library/system.web.ui.timer.aspx), which are respectively for ASP applications and WinForms. Using those will cause the service to load an additional assembly which is not really needed for the type of application you are building.
Use [`System.Timers.Timer`](http://msdn.microsoft.com/en-us/library/system.timers.timer.aspx) like the following example (also, make sure that you use a class level variable to prevent garbage collection, as stated in Tim Robinson's answer):
```
using System;
using System.Timers;
public class Timer1
{
private static System.Timers.Timer aTimer;
public static void Main()
{
// Normally, the timer is declared at the class level,
// so that it stays in scope as long as it is needed.
// If the timer is declared in a long-running method,
// KeepAlive must be used to prevent the JIT compiler
// from allowing aggressive garbage collection to occur
// before the method ends. (See end of method.)
//System.Timers.Timer aTimer;
// Create a timer with a ten second interval.
aTimer = new System.Timers.Timer(10000);
// Hook up the Elapsed event for the timer.
aTimer.Elapsed += new ElapsedEventHandler(OnTimedEvent);
// Set the Interval to 2 seconds (2000 milliseconds).
aTimer.Interval = 2000;
aTimer.Enabled = true;
Console.WriteLine("Press the Enter key to exit the program.");
Console.ReadLine();
// If the timer is declared in a long-running method, use
// KeepAlive to prevent garbage collection from occurring
// before the method ends.
//GC.KeepAlive(aTimer);
}
// Specify what you want to happen when the Elapsed event is
// raised.
private static void OnTimedEvent(object source, ElapsedEventArgs e)
{
Console.WriteLine("The Elapsed event was raised at {0}", e.SignalTime);
}
}
/* This code example produces output similar to the following:
Press the Enter key to exit the program.
The Elapsed event was raised at 5/20/2007 8:42:27 PM
The Elapsed event was raised at 5/20/2007 8:42:29 PM
The Elapsed event was raised at 5/20/2007 8:42:31 PM
...
*/
```
If you choose [`System.Threading.Timer`](http://msdn.microsoft.com/en-us/library/system.threading.timer.aspx), you can use as follows:
```
using System;
using System.Threading;
class TimerExample
{
static void Main()
{
AutoResetEvent autoEvent = new AutoResetEvent(false);
StatusChecker statusChecker = new StatusChecker(10);
// Create the delegate that invokes methods for the timer.
TimerCallback timerDelegate =
new TimerCallback(statusChecker.CheckStatus);
// Create a timer that signals the delegate to invoke
// CheckStatus after one second, and every 1/4 second
// thereafter.
Console.WriteLine("{0} Creating timer.\n",
DateTime.Now.ToString("h:mm:ss.fff"));
Timer stateTimer =
new Timer(timerDelegate, autoEvent, 1000, 250);
// When autoEvent signals, change the period to every
// 1/2 second.
autoEvent.WaitOne(5000, false);
stateTimer.Change(0, 500);
Console.WriteLine("\nChanging period.\n");
// When autoEvent signals the second time, dispose of
// the timer.
autoEvent.WaitOne(5000, false);
stateTimer.Dispose();
Console.WriteLine("\nDestroying timer.");
}
}
class StatusChecker
{
int invokeCount, maxCount;
public StatusChecker(int count)
{
invokeCount = 0;
maxCount = count;
}
// This method is called by the timer delegate.
public void CheckStatus(Object stateInfo)
{
AutoResetEvent autoEvent = (AutoResetEvent)stateInfo;
Console.WriteLine("{0} Checking status {1,2}.",
DateTime.Now.ToString("h:mm:ss.fff"),
(++invokeCount).ToString());
if(invokeCount == maxCount)
{
// Reset the counter and signal Main.
invokeCount = 0;
autoEvent.Set();
}
}
}
```
Both examples comes from the MSDN pages.
|
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 practices to create a windows service to perform an intermittent task run off a timer.
> **"If you're writing a Windows Service that runs a timer, you should re-evaluate your solution."**
>
> –Jon Galloway, ASP.NET MVC community program manager, author, part time superhero
|
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 ($(this).parents().is(someDiv)) {
alert('boo');
}
}
```
Just want to see if one element is a child of another and I'd like to avoid stepping back into DOM land if possible.
|
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 definitions, in some easy to use form, from which I can generate stubs?
|
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 some pointers. As you see, the problem is not easy. But hopefully you can automate at least some part of it.
|
[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 into the file, but there must be a faster way. I'm thinking of [ftruncate](http://linux.die.net/man/2/ftruncate) and also of [Sparse files](http://en.wikipedia.org/wiki/Sparse_file)…
|
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.*;
class Test {
public static void main(String args[]) throws Exception {
RandomAccessFile f = new RandomAccessFile("t", "rw");
f.setLength(1024 * 1024 * 1024);
}
}
```
on a Linux machine will allocate the space using the ftruncate(2)
```
6070 open("t", O_RDWR|O_CREAT, 0666) = 4
6070 fstat(4, {st_mode=S_IFREG|0644, st_size=0, ...}) = 0
6070 lseek(4, 0, SEEK_CUR) = 0
6070 ftruncate(4, 1073741824) = 0
```
while on a Solaris machine it will use the the F\_FREESP64 function of the fcntl(2) system call.
```
/2: open64("t", O_RDWR|O_CREAT, 0666) = 14
/2: fstat64(14, 0xFE4FF810) = 0
/2: llseek(14, 0, SEEK_CUR) = 0
/2: fcntl(14, F_FREESP64, 0xFE4FF998) = 0
```
In both cases this will result in the creation of a sparse file.
|
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 SeekableByteChannel channel = Files.newByteChannel(hugeFile, options);) {
channel.position(HUGE_FILE_SIZE);
channel.write(buf);
}
```
|
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, we cannot restore backups – we are not given access to the actual machine.
We could generate a script to create the database structure, but then we could not do a data transfer through the menu item Tasks/Import Data because we might violate foreign key constraints as tables are imported in an order the conflicts with the database schema. Also, indexes might not be replicated if they are set to auto generate.
Thus we are left with a messy operation:
1. Create a script in SQL 2005 that generates the database in SQL 2000 format.
2. Run the script to create a SQL 2000 database in SQL 2000.
3. Create a script in SQL 2000 that generates the database structure WITHOUT indexes and foreign keys.
4. Run this script on the production server. You now have a database structure to upload data to.
5. Use SQL 2005 to transfer the data to the production server with Tasks/Import data.
6. Use SQL 2000 to generate a script that creates the database with indexes and keys.
7. Copy the commands that generate the indexes and foreign keys only. These are located after the table creation commands. Note: In SQL 2005, the indexes and foreign keys are generated as one and cannot be easily separated.
8. Run this script on the production database.
Voila! The database is uploaded with all data and keys/constraints in place. What a messy and error prone system.
Is there something better?
|
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), etc.) Of course, this is worse when you are actually using Sql Server Express, which doesn't allow for exporting other than creating your own scripts to create the data.
I would recommend switching to a hosting company that allows you to have the ability to FTP backup files and does NOT require you to use your own scripts. That's the whole point of SQL Server, right? To provide more tools that are friendlier to use. If the hosting company takes that away, you may as well move to MySql for its ease in dumping information.
WebHost4Life is a life saver in this category. They offer FTP to the database server to upload your backup file or MDF and LDF files for attachment! I was so upset when I saw GoDaddy had the similar restriction you mentioned. Their tool didn't tell me it was a bad import, and I couldn't figure out why my site was coming back with 500 errors.
One other note: I'm not sure which is considered more secure. I enabled external connections in GoDaddy and connected with Management Studio, and I was able to see every database on that server! I couldn't access them, but I now have that info. A double whammy is that GoDaddy requires that the user name for the DB be the same as the DB! now all you need to do is spam passwords against those hundreds of DBs!
Webhost4life, on the other hand, has only your specific database shown in Management Studio. And they let you pick your own DB name and user name, independent of each other. They only append the same unique id on the end of the user & db names in order to keep them from conflicting with others.
|
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) are needed. Right?
|
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 design pattern](https://web.archive.org/web/20130517072258/http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/FlyweightPattern.htm). When a boxing occurs for a well-known value, instead of creating a new wrapper instance, a pre-created instance is fetched from a pool and returned.
One consequence is: **it’s still not recommended to use autoboxing for scientific calculations**. For example, the code d = a \* b + c is using Integer classes for a, b, c and d, and the generated code is d.valueOf(a.intValue() \* b.intValue() + c.intValue()). All these method invocations have their own overhead, so **it’s usually recommended to use autoboxing when needed to store primitives in collections**.
And even then, if you have a **huge collection** of Integer wrapping int, the overhead can implies longer execution times, up to **20 times longer**, as [reported in this article](http://www.javaspecialists.co.za/archive/Issue090.html).
---
Jb adds this important comment:
> Also Wrapper.valueOf(primitive) uses pool of wrappers. So prefer Integer.valueOf(5) to new Integer(5)
|
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 rarely matters. But if you were writing something very numnber-crunching heavy like, say, a graphics transformation processor you are a lot more likely to care.
|
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();
```
Any clues on what I'm doing wrong or a better practice for larger files?
|
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 questions really:
1. Is it harmful that the items would then be out of order? Am I right in saying that the worst that can happen is that new entries may get put into the wrong place (which actually I can live with). Or, could this cause crashes, lost entries etc?
2. Is there a way to "refresh" the ordering of the set? You can't seem to use std::sort() on a set. The best I can come up with is dumping out the contents to a temp container and re-add them.
Any ideas?
Thanks,
John
|
`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 MyAbstract{
public static Class MYABSTRACT_CLASS = MyAbstract.class.getClass();
```
This code will be running in JavaME environments.
|
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 class 'Class', not the class 'Object'.
|
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 )
{
}
}
```
Singleton is most useful when you have a normal class with state, but you only want one of them. The links that others have provided should be useful in exploring the Singleton pattern.
|
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 that there **must** (as in, it's dangerous for this not to be true) only ever be a single instance.
If you want global, just make a global instance of some (non signleton) object (or make it static or whatever).
If you want only one instance, again, static is your friend. Also, simply instantiate only one object.
Thats my opinion anyway.
|
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);
return;
}
if (String.IsNullOrEmpty(this._ValidCharExpression))
{
base.OnKeyPress(e);
}
else
{
bool isValidChar = Regex.Match(e.KeyChar.ToString(),this._ValidCharExpression).Success;
if (isValidChar)
{
base.OnKeyPress(e);
}
else
{
e.Handled = true;
}
}
}
```
I had placed the regex code in the OnKeyPress code, but I wat to allow all special keys, such as Ctrl-V, Ctrl-C and Backspace to be allowed.
As you can see I have the backspace key being handled. However, Ctrl-V, for example cannot see the V key because it runs once for the ctrl key but does not see any modifiers keys.
What is the best way to handle this situation?
|
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 basic idea is to cancel the change before it is becoming visible (via an OnTextChanging event).
|
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
Emp2 Name, Emp2 Phone, Emp2 Address
Org2 Emp1 Name, Emp1 Phone, Emp1 Address
Emp2 Name, Emp2 Phone, Emp2 Address
```
How do I display this data because the number of employess for each organisation is not known in advanced, so I do'nt about setting value of rowspan. Similarly how do I start a row for other organisation? Do I have to write two queries?
Many Thanks.
|
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 the most beautiful but so simple.
|
```
// 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']]))
$rows[$row['org']] = array();
$rows[$row['org']][] = $row;
}
// Print it out
foreach ($rows as $org => $employees)
{
print('<tr><td rowspan="' . count($employees) . '">' . htmlentities($org) . '</td>');
foreach ($employees as $i => $employee)
{
// If $i == 0, we've already printed the <tr> before the loop
if ($i)
print('<tr>');
print('<td>......</td></tr>');
}
}
```
|
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 is created, but it belongs to 'apache' user.
3. 'user1' and 'apache' are different users; and safe mode is turned on. So the php script cannot write to that newly created directory.
4. Now I have a problem!
One solution is to turn off safe mode. Also, a coworker suggested that there are settings that can be changed to ensure the directories are under the same user as the script. So I am looking to see if latter can be done.
But I have to ask. Is there a programatical solution for my problem?
I am leaning to a 'no', as safe mode was implemented to solve it at the php level. Also the actual problem may seem like the directory being created under a different user, so a programatic fix might just be a band-aid fix.
|
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 server
$user = "user@myserver.com";
$pass = "password";
$result = ftp_login($connection, $user, $pass);
// check if connection was made
if ((!$connection) || (!$result)) {
return false;
exit();
} else {
ftp_chdir($connection, $path); // go to destination dir
if(ftp_mkdir($connection, $newDir)) { // create directory
ftp_site($connection, "CHMOD 777 $newDir") or die("FTP SITE CMD failed.");
return $newDir;
} else {
return false;
}
ftp_close($connection); // close connection
}
}
```
|
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 implements my own interface IObject1
I've done this using generics
```
public static T[] CreateObject1<T>(IObject1[] properties)
where T : class, new()
{
//Check the type is allowed
CheckObject1Types("CreateObject1<T>(IObject1[])", typeof(T));
return CreateObjectArray<T>(properties);
}
private static void CheckObject1Types(string method, Type type)
{
if (type == typeof(Service1.Object1)
|| type == typeof(Service2.Object1)
|| type == typeof(Service3.Object1)
|| type == typeof(Service1.Object1[])
|| type == typeof(Service2.Object1[])
|| type == typeof(Service3.Object1[]))
{
return;
}
throw new ArgumentException("Incorrect type passed to ServiceObjectFactory::" + method + ". Type:" + type.ToString());
}
```
My client code looks like:
```
//properties is an array of my intermediary objects
Object1[] props = ServiceObjectFactory.CreateObject1<Object1>(properties);
```
What I want to do is get rid of the CheckObject1Types method and use constraints instead so that I get a build error if the types aren't valid, because at the moment I can call this method with any type and the ArgumentException is thrown by the CheckObject1Types method.
So I'd like to do something like:
```
public static T[] CreateObject1<T>(IObject1[] properties)
where T : class, new(), Service1.Object1|Service2.Object1|Service3.Object1
{
return CreateObjectArray<T>(properties);
}
```
Any ideas?
**Edit:** I don't want to change the Reference.cs files for each webservice because all it takes is a team mate to update the web reference and BAM! broken code.
|
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" interface and use that as your constraint. I know sentinel interfaces are not recommended practice per the Framework Design Guidelines, but they occasionaly have their uses (this being one of them).
As Jon points out, you may be able to make use of prtial classes in order to implement a common interface. If your References.cs implements a class:
```
namespace TestServices
{
internal partial class Service1SoapClient : System.ServiceModel.ClientBase<T>, K
{
}
}
```
You would then create another partial class in the same namespace (call it References.CommonInterface.cs), which can live anywhere in your project, with the following:
```
namespace TestServices
{
internal interface ICommon
{
}
internal partial class Service1SoapClient : ICommonInterface
{
}
}
```
|
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 `RAND()` for every row (which already puts it at O(n)), and sorts them, making it O(n lg n) at best. Is there a way to do this faster than O(n)?
*Note*: As Andrew Mao points out in the comments, If you're using this approach on SQL Server, you should use the T-SQL function `NEWID()`, because RAND() [may return the same value for all rows](http://msdn.microsoft.com/en-us/library/ms177610.asp).
*EDIT: 5 YEARS LATER*
I ran into this problem again with a bigger table, and ended up using a version of @ignorant's solution, with two tweaks:
* Sample the rows to 2-5x my desired sample size, to cheaply `ORDER BY RAND()`
* Save the result of `RAND()` to an indexed column on every insert/update. (If your data set isn't very update-heavy, you may need to find another way to keep this column fresh.)
To take a 1000-item sample of a table, I count the rows and sample the result down to, on average, 10,000 rows with the the frozen\_rand column:
```
SELECT COUNT(*) FROM table; -- Use this to determine rand_low and rand_high
SELECT *
FROM table
WHERE frozen_rand BETWEEN %(rand_low)s AND %(rand_high)s
ORDER BY RAND() LIMIT 1000
```
(My actual implementation involves more work to make sure I don't undersample, and to manually wrap rand\_high around, but the basic idea is "randomly cut your N down to a few thousand.")
While this makes some sacrifices, it allows me to sample the database down using an index scan, until it's small enough to `ORDER BY RAND()` again.
|
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 that your O(n lg n) solution is the best. Though actually with a good optimizer or a slightly different technique the query you list may be a bit better, O(m\*n) where m is the number of random rows desired, as it wouldn't necesssarily have to sort the whole large array, it could just search for the smallest m times. But for the sort of numbers you posted, m is bigger than lg n anyway.
Three asumptions we might try out:
1. there is a unique, indexed, primary key in the table
2. the number of random rows you want to select (m) is much smaller than the number of rows in the table (n)
3. the unique primary key is an integer that ranges from 1 to n with no gaps
With only assumptions 1 and 2 I think this can be done in O(n), though you'll need to write a whole index to the table to match assumption 3, so it's not necesarily a fast O(n). If we can ADDITIONALLY assume something else nice about the table, we can do the task in O(m log m). Assumption 3 would be an easy nice additional property to work with. With a nice random number generator that guaranteed no duplicates when generating m numbers in a row, an O(m) solution would be possible.
Given the three assumptions, the basic idea is to generate m unique random numbers between 1 and n, and then select the rows with those keys from the table. I don't have mysql or anything in front of me right now, so in slightly pseudocode this would look something like:
```
create table RandomKeys (RandomKey int)
create table RandomKeysAttempt (RandomKey int)
-- generate m random keys between 1 and n
for i = 1 to m
insert RandomKeysAttempt select rand()*n + 1
-- eliminate duplicates
insert RandomKeys select distinct RandomKey from RandomKeysAttempt
-- as long as we don't have enough, keep generating new keys,
-- with luck (and m much less than n), this won't be necessary
while count(RandomKeys) < m
NextAttempt = rand()*n + 1
if not exists (select * from RandomKeys where RandomKey = NextAttempt)
insert RandomKeys select NextAttempt
-- get our random rows
select *
from RandomKeys r
join table t ON r.RandomKey = t.UniqueKey
```
If you were really concerned about efficiency, you might consider doing the random key generation in some sort of procedural language and inserting the results in the database, as almost anything other than SQL would probably be better at the sort of looping and random number generation required.
|
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() is generating numbers in a uniform distribution. It is the quickest way to do this.
I saw that someone had recommended that solution and they got shot down without proof.. here is what I would say to that -
* This is O(n) but no sorting is required so it is faster than the O(n lg n)
* mysql is very capable of generating random numbers for each row. Try this -
select rand() from INFORMATION\_SCHEMA.TABLES limit 10;
Since the database in question is mySQL, this is the right solution.
|
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 Outlook (Address Cards view or Detailed Address Cards View under Contacts), and so it needs a the column of buttons at the right end, one for each alphabet.
I am trying to emulate that, but I don't want to ask the user to choose the script. If the current culture is say, Chinese, I want to draw Chinese alphabets. When the user changes the culture info to English (and when he restarts the application) I want to draw English alphabets instead. Hope you understand where I am going with this query.
I can determine the culture of the current user (Application.CurrentCulture or System.Globalization.CultureInfo.CurrentCulture will give the culture related information). I also have all the scripts to render the alphabets. However, the problem is that I don't know how to map the culture info to the name of a script.
In other words, is there a way to determine the script name corresponding to a culture? Or is it possible to determine the range of Unicode character values corresponding to a culture? Either of them would allow me to render the alphabets on the button properly.
Any suggestions or guidance regarding this is truly appreciated. If there is something fundamentally wrong with my approach (or with what I am trying to achieve), please point out that as well. Thanks for your time.
PS: I know the easiest solution is to either configure the script name as part of user preferences or display a list of languages for the user to choose from (a la Contact in Outlook 2007). But I am just trying to see whether I can render the alphabets corresponding to the culture without the user having to do anything.
|
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 characters, and that might help you index them. I know this doesn't answer your question, but I hope it's helpful.
|
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 program's icon, you need to know the window and the id used by that application to register it. You might be able to brute force it by enumerating all windows for that process and making calls with each handle and each number between 0 and 5000 thousands for example, but your chances of success are very slim.
|
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.
(InteractiveConsole)
```
When just starting a python interpreter using `python`, it doesn't offer tab completion.
Can someone tell me what django is doing to give me an interactive console, or what I need to do to start an interactive console without a django app?
|
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 PYTHONSTARTUP=~/.pythonrc
```
That seems to work.
|
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.