Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I'm writing a custom class in C# and I'm throwing a couple exceptions if people give the wrong inputs in some of the methods. If the exception is thrown, will any of the code in the method after the throw still be executed? Do I have to put a break after the throw, or does a throw always quit the method? | When you [throw](http://msdn.microsoft.com/en-us/library/1ah5wsex(VS.80).aspx) an exception, the next code to get executed is any catch block that covers that throw within the method (if any) then, the [finally block](http://msdn.microsoft.com/en-us/library/dszsf989.aspx) (if any). You can have a try, a try-catch, a try-catch-finally or a try-finally. Then, if the exception is not handled, re-thrown by a catch block or not caught at all, control is returned to the caller. For example, you will get "Yes1, Yes2, Yes3" from this code ...
```
try
{
Console.WriteLine("Yes1");
throw (new Exception());
Console.WriteLine("No1");
}
catch
{
Console.WriteLine("Yes2");
throw;
Console.WriteLine("No2");
}
finally
{
Console.WriteLine("Yes3");
}
Console.WriteLine("No3");
``` | Throw will move up the stack, thus exiting the method. | Do I have to break after throwing exception? | [
"",
"c#",
".net",
"exception",
"break",
"throw",
""
] |
I am trying to use a function pointer, but the 3 lines below just do not seem to want to cooperate...
I'm getting error code C3867.
Can you see what I'm doing wrong?
In .h file
```
void MyFunc(int, FILEINFO*(*)(FILEINFO*), FILEINFO*, int);
```
The definition in the .cpp file
```
void MyFunc(int number, FILEINFO*(*GetFiles)(FILEINFO*), FILEINFO* args, int type);
```
Then here is where I'm actually calling the function
```
MyFuncClass->MyFunc(GetNumber(), &BigClass::PassThis, GetArgs(), TheType);
```
Any problems jump out? | You cannot pass a non-static member function of a class as an
ordinary function pointer, since a member function implicitly uses the
this-pointer. A solution for this is to define a static member function that takes a pointer
to the class as it's first argument and wraps the call to `BigClass::PassThis` and pass a pointer to that member function instead. Please see
[The Function Pointer Tutorials](http://www.newty.de/fpt/callback.html#member) for more information.
A better solution might be to look into using functors instead. | What is the definition of `BigClass::PassThis()`? Is it a static class member function or a regular member function? If it's a regular member function, you can't do that, because it has a hidden `this` parameter. See [question 33.4](http://www.parashift.com/c++-faq-lite/pointers-to-members.html#faq-33.4) of the C++ FAQ Lite. | Function pointer problem | [
"",
"c++",
"function",
"pointers",
""
] |
I need to downcast a long to an int in a method where the long is passed as a ref variable:
```
public void Foo(ref long l)
{
// need to consume l as an int
}
```
How can I easily do this? | You can't. However, any value you want to put into a `ref int` can be put into a `ref long` anyway - you've just got to worry about the initial value, and what you want to do if it's outside the range of `int`.
How many places do you need to write to the ref parameter or read it within your code? If it's only in one or two places, you should be okay just to cast appropriately at the right times. Otherwise, you might want to introduce a new method:
```
public void Foo(ref int x)
{
// Here's the body I *really* want
}
public void Foo(ref long x)
{
// But I'm forced to use this signature for whatever
// reasons. Oh well. This hack isn't an *exact* mimic
// of ref behaviour, but it's close.
// TODO: Decide an overflow policy
int tmp = (int) x;
Foo(ref tmp);
x = tmp;
}
```
The reason I say in the comments that it's not an exact mimic for the behaviour is that normally changes to the original ref parameter are visible even before the method returns, but now they'll only be visible at the very end. Also, if the method throws an exception, the value won't have been changed. The latter *could* be fixed with try/finally, but that's a bit clunky. In fact, if you want the try/finally behaviour you can do it all in a single method easily:
```
public void Foo(ref long x)
{
int y = (int) x;
try
{
// Main body of code
}
finally
{
x = y;
}
}
``` | You don't. You can't take your reference and point it to a different type. How would the code calling your method know that it's changed?
If you just want to work with the value as an `int`, then you could do something like this:
```
private void Process(ref long l)
{
int i = (int)l;
// do whatever
}
``` | How to downcast a ref variable within the method | [
"",
"c#",
".net",
"casting",
"ref-parameters",
""
] |
I have a string which contains digits and letters. I wish to split the string into contiguous chunks of digits and contiguous chunks of letters.
Consider the String "34A312O5M444123A".
I would like to output:
["34", "A", "312", "O", "5", "M", "444123", "A"]
I have code which works and looks like:
```
List<String> digitsAsElements(String str){
StringBuilder digitCollector = new StringBuilder();
List<String> output = new ArrayList<String>();
for (int i = 0; i < str.length(); i++){
char cChar = str.charAt(i);
if (Character.isDigit(cChar))
digitCollector.append(cChar);
else{
output.add(digitCollector.toString());
output.add(""+cChar);
digitCollector = new StringBuilder();
}
}
return output;
}
```
I considered splitting str twice to get an array containing all the numbers chunks and an array containing the all letters chunks. Then merging the results. I shied away from this as it would harm readability.
I have intentionally avoided solving this with a regex pattern as I find regex patterns to be a major impediment to readability.
* Debuggers don't handle them well.
* They interrupt the flow of someone reading source code.
* Overtime regex's grow organically and become monsters.
* They are deeply non intuitive.
My questions are:
* How could I improve the readability of the above code?
* Is there a better way to do this? A Util class that solves this problem elegantly.
* Where do you draw the line between using a regEx and coding something simpilar to what I've written above?
* How do you increase the readability/maintainability of regExes? | Would you be willing to use regexes if it meant solving the problem in one line of code?
```
// Split at any position that's either:
// preceded by a digit and followed by a non-digit, or
// preceded by a non-digit and followed by a digit.
String[] parts = str.split("(?<=\\d)(?=\\D)|(?<=\\D)(?=\\d)");
```
With the comment to explain the regex, I think that's more readable than any of the non-regex solutions (or any of the other regex solutions, for that matter). | For this particular task I'd always use a regex instead of hand-writing something similar. The code you have given above is, at least to me, less readable than a simple regular expression (which would be `(\d+|[^\d]+)` in this case, as far as I can see).
You may want to avoid writing regular expressions that exceed a few lines. Those can be and usually are unreadable and hard to understand, *but so is the code they can be replaced with!* Parsers are almost never pretty and you're usually better off reading the original grammar than trying to make sense of the generated (or handwritten) parser. Same goes (imho) for regexes which are just a concise description of a regular grammar.
So, in general I'd say banning regexes in favor of code like you've given in your question sounds like a terribly stupid idea. And regular expressions are just a tool, nothing less, nothing more. If something else does a better job of text parsing (say, a real parser, some substring magic, etc.) then use it. But don't throw away possibilities just because you feel uncomfortable with them – others may have less problems coping with them and all people are able to learn.
EDIT: Updated regex after comment by mmyers. | Help on a better way to parses digits from a String in Java | [
"",
"java",
"regex",
"string",
"readability",
"literate-programming",
""
] |
I have the following queue class (taken from wordpress):
```
#include<iostream.h>
class Queue
{
private:
int data;
Queue*next;
public:
void Enque(int);
int Deque();
}*head,*tail;
void Queue::enque(int data)
{
Queue *temp;
temp=new Queue;
temp->data=data;
temp->next=NULL;
if(heads==NULL)
heads=temp;
else
tail->next=temp;
tail=temp;
}
int Queue::deque()
{
Queue* temp;//
temp=heads;
heads=heads->next;
return temp->data;
}
```
I'm trying to figure out why the compiler tells me that I have a multiple definition
of "head" and "tail"- without success.
edit: When the compiler gives the error message it opens up a locale\_facets.tcc file
from I-don't-know-where and says that the error is on line 2497 in the following function:
```
bool
__verify_grouping(const char* __grouping, size_t __grouping_size,
const string& __grouping_tmp)
```
Does anyone have any insights? | Since this is homework, here is some information about queues and how you could go about implementing one.
A Queue is a standard Abstract Data Type.
It has several properties associated with it:
1. It is a linear data structure - all components are arranged in a straight line.
2. It has a grow/decay rule - queues add and remove from opposite ends.
3. Knowledge of how they're constructed shouldn't be integral in using them because they have public interfaces available.
Queues can be modeled using Sequential Arrays or Linked-Lists.
If you're using an array there are some things to consider because you grow in one direction so you will eventually run out of array. You then have some choices to make (shift versus grow). If you choose to shift back to the beginning of the array (wrap around) you have to make sure the head and tail don't overlap. If you choose to simply grow the queue, you have a lot of wasted memory.
If you're using a Linked-List, you can insert anywhere and the queue will grow from the tail and shrink from the head. You also don't have to worry about filling up your list and having to wrap/shift elements or grow.
However you decide to implement the queue, remember that Queues should provide some common interface to use the queue. Here are some examples:
1. enqueue - Inserts an element at the back (tail) of the queue
2. dequeue - Remove an element from the front (head) of a non-empty queue.
3. empty - Returns whether the queue is empty or not
4. size - Returns the size of the queue
There are other operations you might want to add to your queue (In C++, you may want an iterator to the front/back of your queue) but how you build your queue should not make a difference with regards to the operations it provides.
However, depending on how you want to use your queue, there are better ways to build it. The usual tradeoff is insert/removal time versus search time. Here is [a decent reference](http://en.wikipedia.org/wiki/Linked_list#Linked_lists_vs._arrays). | If your assignment is not directly related to queue implementation, you might want to use the built in `std::queue` class in C++:
```
#include <queue>
void test() {
std::queue<int> myQueue;
myQueue.push(10);
if (myQueue.size())
myQueue.pop();
}
``` | implement a queue | [
"",
"c++",
"queue",
""
] |
I think most coders have used code like the following :
```
ArrayList<String> myStringList = getStringList();
for(String str : myStringList)
{
doSomethingWith(str);
}
```
How can I take advantage of the for each loop with my own classes? Is there an interface I should be implementing? | You can implement [Iterable](http://java.sun.com/j2se/1.5.0/docs/api/java/lang/Iterable.html).
Here's an [example](http://www.java2s.com/Tutorial/Java/0140__Collections/CreatingIterableObjectsusingaforeachforlooponanIterableobject.htm). It's not the best, as the object is its own iterator. However it should give you an idea as to what's going on. | The short version of for loop (`T` stands for my custom type):
```
for (T var : coll) {
//body of the loop
}
```
is translated into:
```
for (Iterator<T> iter = coll.iterator(); iter.hasNext(); ) {
T var = iter.next();
//body of the loop
}
```
and the Iterator for my collection might look like this:
```
class MyCollection<T> implements Iterable<T> {
public int size() { /*... */ }
public T get(int i) { /*... */ }
public Iterator<T> iterator() {
return new MyIterator();
}
class MyIterator implements Iterator<T> {
private int index = 0;
public boolean hasNext() {
return index < size();
}
public type next() {
return get(index++);
}
public void remove() {
throw new UnsupportedOperationException("not supported yet");
}
}
}
``` | How can I use the java for each loop with custom classes? | [
"",
"java",
"class",
"foreach",
""
] |
I’m getting the following error when I start Debug from the Eclipse IDE.
> Message: `“Failed to connect to remote VM. Connection Refused”`
What could be the reason? | Have you setup the remote VM to accept connections?
```
java -Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=10000,suspend=n yourServer
```
Is there a firewall in the way?
Are you specifying the correct host / port?
Are you connected to a VPN? | Use `0.0.0.0` for addresses to be able to connect form any remote machine i.e.:
```
-Xdebug -Xrunjdwp:transport=dt_socket,address=0.0.0.0:8000,server=y,suspend=y
``` | Eclipse Error: "Failed to connect to remote VM" | [
"",
"java",
"eclipse",
""
] |
I have a text string that starts with a number of spaces, varying between 2 & 4.
What is the simplest way to remove the leading whitespace? (ie. remove everything before a certain character?)
```
" Example" -> "Example"
" Example " -> "Example "
" Example" -> "Example"
``` | The [`lstrip()`](http://docs.python.org/library/stdtypes.html#str.lstrip) method will remove leading whitespaces, newline and tab characters on a string beginning:
```
>>> ' hello world!'.lstrip()
'hello world!'
```
**Edit**
[As balpha pointed out in the comments](https://stackoverflow.com/questions/959215/removing-starting-spaces-in-python#comment768038_959216), in order to remove *only* spaces from the beginning of the string, `lstrip(' ')` should be used:
```
>>> ' hello world with 2 spaces and a tab!'.lstrip(' ')
'\thello world with 2 spaces and a tab!'
```
Related question:
* [Trimming a string in Python](https://stackoverflow.com/questions/761804/trimming-a-string-in-python) | The function `strip` will remove whitespace from the beginning and end of a string.
```
my_str = " text "
my_str = my_str.strip()
```
will set `my_str` to `"text"`. | How do I remove leading whitespace in Python? | [
"",
"python",
"string",
"whitespace",
"trim",
""
] |
For compliance reasons, my organization is looking to take our database connection settings out of properties/XML config files and into a central registry - ideally federated over multiple physical machines, to avoid a single point of failure.
I have been looking at the possibility of using JNDI to achieve this, but haven't really got much experience in using it myself. Has anyone got experience attempting to do anything similar? Or any better ideas of how this might be achieved?
I should add that our apps are standalone and do not run within any J2EE container, therefore any container specific connection management techniques may not be particularly useful. | It might be simpler to stick with the XML/properties file approach, but use some kind of centralised configuration management system to control the content of those files.
Presumably if you're having to consider centralising things like datasource configuration, you'll already have something in place (CFEngine, puppet, chef, rdist, ...) to manage operating system configuration files - so why not just use that? | This might be a good start:
```
HashMap<String,String> dsNames = new HashMap<String,String>();
System.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.fscontext.RefFSContextFactory");
System.setProperty(Context.PROVIDER_URL, "file:/home/user/tmp");
InitialContext ic = new InitialContext();
dsNames.put("yourDataSourceName", "jdbc/your_jndi_name");
// Construct BasicDataSource reference
Reference ref = new Reference("javax.sql.DataSource",
"org.apache.commons.dbcp.BasicDataSourceFactory", null);
ref.add(new StringRefAddr("driverClassName", "theDriver"));
ref.add(new StringRefAddr("url","theDBURL"));
ref.add(new StringRefAddr("username", "obvious"));
ref.add(new StringRefAddr("password", "obvious"));
ref.add(new StringRefAddr("maxActive", "10"));
ref.add(new StringRefAddr("maxIdle", "3"));
ref.add(new StringRefAddr("initialSize", "3"));
ref.add(new StringRefAddr("maxWait", "5"));
ic.rebind("jdbc/your_jndi_name", ref);
//And to get a reference to your data source anywhere else in your program:
InitialContext ic2 = new InitialContext();
DataSource myDS = (DataSource) ic2.lookup(dsNames.get(dsName));
```
Now as you can see, I'm using a pooled connection factory, but you can replace that to suit your needs. Also, the initial context factory is an FSContext which means the JNDI name will be looked up in a regular file system, an URL Context Factory must be available but I have never used it. Most classes used are in the javax.naming package.
Hope this helps. | Centralized DB connection management in Java | [
"",
"java",
"database-connection",
"jndi",
""
] |
What does the warning mean?
Why is the second example worse than the first?
```
SELECT product_id, prod.name name, sample_id
FROM lims.sample JOIN lims.product prod USING (product_id)
```
vs.
```
SELECT product_id, prod.name name, sample_id
FROM (SELECT sample_id, product_id FROM lims.sample)
JOIN lims.product prod
/* ADVICE: [131] This item has not been declared, or it refers to a label */
USING (product_id)
/* ADVICE:
ADVICE SUMMARY
Count Recommendation
----- --------------
1 [131] This item has not been declared, or it refers to a label
The Oracle equivalent error messages are PLS-00320 and
PLS-0321.
*/
```
FYI: Both queries run fine and return the same results. | Putting aside the tables' amount of data, indexes, and gathered statistics; in general, **unnested subqueries** should **outperform nested subqueries**. | My guess: It looks like TOAD isn't parsing the query the same way that Oracle would.
In the first query, perhaps TOAD checks the table definitions for lims.sample and lims.product, and finds the column "product\_id" in both, so it's fine.
In the second query, TOAD cannot check the table definition for the first part of the join because it's a nested query; so perhaps it gives up and gives you this advice (which is why the advice says "... or it refers to a label" which is probably a copout).
I would ignore the advice in this instance, especially as it runs fine and returns the same results. | Advice from Toad for Oracle Formatter | [
"",
"sql",
"oracle",
"toad",
""
] |
jQuery plugins are great, except this is about a billion or so of them1, and most of them however will fade into the background noise of the rest. What are those plugins that are so useful that they should be incorporated into jQuery or jQueryUI (if it's a UI/effect type) or included in a jQuery bundle?
1- billion is just a rough estimate | I kind of agree with Cletus, but instead of taking the hardline keeps it super tight, why now have a third "jQuery Essentials" and include things like JavascriptServerTemplates in it. The good thing about having such a package is that it could focus the effort on things so that there aren't 19 ways to do a section of a page that turns into a button when you mouse over it, just one that works.
Some guy is aparently trying to create this - <http://flowplayer.org/tools/index.html>; | None. The reason jQuery is good is because it is lightweight and extensible. | What jQuery plugins should be incorporated into jQuery or jQueryUI | [
"",
"javascript",
"jquery",
"jquery-ui",
""
] |
I'm moving from PHP to C#.
In PHP it was simple and straightforward to use abstract classes to create a "**cascading override**" pattern, basically "**the base class method will take care of it unless the inheriting class has a method with the same signature**".
In C#, however, I just spent about 20 minutes trying out various combinations of the keywords **new**, **virtual**, **abstract**, and **override** in the **base** and **inheriting** classes until I finally got the right combination which does this simple cascading override pattern.
So even those the code below works the way I want it, these added keywords suggest to me that C# can do much more with abstract classes. I've looked up examples of these keywords and understand basically what they do, but still can't imagine a real scenario in which I would use them other than this simple "cascading override" pattern. **What are some *real world* ways that you implement these keywords in your day-to-day programming?**
code that works:
```
using System;
namespace TestOverride23433
{
public class Program
{
static void Main(string[] args)
{
string[] dataTypeIdCodes = { "line", "wn" };
for (int index = 0; index < dataTypeIdCodes.Length; index++)
{
DataType dataType = DataType.Create(dataTypeIdCodes[index]);
Console.WriteLine(dataType.GetBuildItemBlock());
}
Console.ReadLine();
}
}
public abstract class DataType
{
public static DataType Create(string dataTypeIdCode)
{
switch (dataTypeIdCode)
{
case "line":
return new DataTypeLine();
case "wn":
return new DataTypeWholeNumber();
default:
return null;
}
}
//must be defined as virtual
public virtual string GetBuildItemBlock()
{
return "GetBuildItemBlock executed in the default datatype class";
}
}
public class DataTypeLine : DataType
{
public DataTypeLine()
{
Console.WriteLine("DataTypeLine just created.");
}
}
public class DataTypeWholeNumber : DataType
{
public DataTypeWholeNumber()
{
Console.WriteLine("DataTypeWholeNumber just created.");
}
//new public override string GetBuildItemBlock() //base method is erroneously executed
//public override string GetBuildItemBlock() //gets error "cannot override inherited member because it is not marked virtual, abstract, or override"
public override string GetBuildItemBlock()
{
return "GetBuildItemBlock executed in the WHOLENUMBER class.";
}
}
}
``` | `virtual`/`override` is the core polymorphism pair; sounds like you've already cracked these
`abstract` is like `virtual`, but there **is** no sensible base implementation; use-cases: perhaps a `Stream`, where it is **necessary** for the actual implementation to do something with the bytes. This forces the class to be `abstract`
`new` should usually be avoided; it breaks polymorphism... the most common case is to re-expose with a more specific signature / return-type (perhaps in a sealed class, since it doesn't get prettier up the chain...) - see [`SqlConnection.CreateCommand`](http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlconnection.createcommand.aspx) (vs [`DbConnection.CreateCommand`](http://msdn.microsoft.com/en-us/library/system.data.common.dbconnection.createcommand.aspx)), or (perhaps more notably) [`IEnumerator<T>.Current`](http://msdn.microsoft.com/en-us/library/58e146b7.aspx) (vs [`IEnumerator.Current`](http://msdn.microsoft.com/en-us/library/system.collections.ienumerator.current.aspx)) | It appears you have already figured out `virtual` and `override` from your example, so:
* '`abstract`' can also be applied on members instead of '`virtual`', in which case you do not specify an implementation for the method ('`;`' directly after the signature). This forces all concrete descendants to implement the method.
* '`new`' has nothing to do with inheritance, but can instead be used in a descendant class on a member to hide a member in the base class that has the exact same signature.
In a nutshell ;) | What are some real-world examples of abstract new/virtual/override/abstract keywords? | [
"",
"c#",
"abstract-class",
""
] |
I'm looking for a MS access SQL function similar to SUBSTRING but not quite as the length
of the data varies.
I have several values in a field we'll call field1
The value length varies from 2 to 5.
In all cases I would want to select the values except the very last character.
So for example:
```
computer
browser
mouse
game
zip
```
Becomes:
```
compute
browse
mous
gam
zi
```
Is there such a function?
Thanks. | I would just:
```
select left(field1, len(field1) -1) from [table]
``` | For ACE/Jet, I would use the `MID()` expression. While the `LEFT()` expression would work fine, `MID()` is preferable IMO because it makes code more portable i.e. it would be much simpler to transform the ACE/Jet proprietary `MID()` expression into the Standard SQL `SUBSTRING`.
Note that you need to test the text's length to avoid a nasty error e.g. when testing the currently-accepted answer (by King Avitus using the `LEFT()` expression) 'as is' via OLE DB on a zero-length string I get the error, "Data provider or other service returned an E\_FAIL status" which isn't very helpful :(
I suggest using ACE/Jet's `IIF()` expression (which, again, is easily transformed into Standard SQL's `CASE` expression) to test for a length zero-length string:
```
SELECT column_1,
MID(column_1, 1, IIF(LEN(column_1) = 0, 0, LEN(column_1) - 1))
AS column_1_truncated
FROM (
SELECT DISTINCT 'ab' AS column_1 FROM Calendar
UNION ALL
SELECT DISTINCT 'a' FROM Calendar
UNION ALL
SELECT DISTINCT '' FROM Calendar
UNION ALL
SELECT DISTINCT NULL FROM Calendar
) AS MyTable;
``` | Access SQL, select all but last X char of a field | [
"",
"sql",
"ms-access",
""
] |
I am working with a large XML response from a web service. When I try to get that using a URL, after some time it displays an error in Firebug that "script stack space quota is exhausted"
How can i resolve that? | It *sounds* like there is some recursion going on when processing the xml, that is essentially causing a stack overflow (by any name).
Thoughts:
* work with less data
* if you are processing the data manually, try to use less recursion? perhaps manual tail-call or queue/stack based
* consider json - then you can offload to the script host to rehydrate the object without any extra processing | Have you tried disabling Firebug? | Script stack space exhausted firefox | [
"",
"javascript",
"jquery",
"xml",
"mozilla",
""
] |
I'm fully aware that this question has been asked and answered everywhere, both on SO and off. However, every time there seems to be a different answer, e.g. [this](https://stackoverflow.com/questions/761263/what-is-the-best-way-to-preload-multiple-images-in-javascript/761332#761332), [this](https://stackoverflow.com/questions/257550/php-ajax-best-practice-for-pre-loading-images/257594#257594) and [that](https://stackoverflow.com/questions/476679/preloading-images-with-jquery/476681#476681).
I don't care whether it's using jQuery or not - what's important is that it works, and is cross-browser.]
So, what is the best way to preload images? | Unfortunately, that depends on your purpose.
If you plan to use the images for purposes of style, your best bet is to use sprites.
<http://www.alistapart.com/articles/sprites2>
However, if you plan to use the images in <img> tags, then you'll want to pre-load them with
```
function preload(sources)
{
var images = [];
for (i = 0, length = sources.length; i < length; ++i) {
images[i] = new Image();
images[i].src = sources[i];
}
}
```
(modified source taken from [What is the best way to preload multiple images in JavaScript?](https://stackoverflow.com/questions/761263/what-is-the-best-way-to-preload-multiple-images-in-javascript/761332))
using `new Image()` does not involve the expense of using DOM methods but a new request for the image specified will be added to the queue. As the image is, at this point, not actually added to the page, there is no re-rendering involved. I would recommend, however, adding this to the end of your page (as all of your scripts should be, when possible) to prevent it from holding up more critical elements.
Edit: Edited to reflect comment quite correctly pointing out that separate `Image` objects are required to work properly. Thanks, and my bad for not checking it more closely.
Edit2: edited to make the reusability more obvious
**Edit 3 (3 years later):**
Due to changes in how browsers handle non-visible images (display:none or, as in this answer, never appended to the document) a new approach to pre-loading is preferred.
You can use an Ajax request to force early retrieval of images. Using jQuery, for example:
```
jQuery.get(source);
```
Or in the context of our previous example, you could do:
```
function preload(sources)
{
jQuery.each(sources, function(i,source) { jQuery.get(source); });
}
```
Note that this doesn't apply to the case of sprites which are fine as-is. This is just for things like photo galleries or sliders/carousels with images where the images aren't loading because they are not visible initially.
Also note that this method does not work for IE (ajax is normally not used to retrieve image data). | **Spriting**
As others have mentioned, spriting works quite well for a variety of reasons, however, it's not as good as its made out to be.
* On the upside, you end up making only one HTTP request for your images. YMMV though.
* On the down side you are loading everything in one HTTP request. Since most current browsers are limited to 2 concurrent connections the image request can block other requests. Hence YMMV and something like your menu background might not render for a bit.
* Multiple images share the same color palette so there is some saving but this is not always the case and even so it's negligible.
* Compression is improved because there is more shared data between images.
Dealing with irregular shapes is tricky though. Combining all new images into the new one is another annoyance.
**Low jack approach using <img> tags**
If you are looking for the **most definitive** solution then you should go with the low-jack approach which I still prefer. Create <img> links to the images at the end of your document and set the `width` and `height` to 1x1 pixel and additionally put them in a hidden div. If they are at the end of the page, they will be loaded after other content. | The definitive best way to preload images using JavaScript/jQuery? | [
"",
"javascript",
"jquery",
"image-preloader",
""
] |
I know that I can output an image using GD by using
```
<img src='draw.php'>
```
Where draw.php is a file containing the code to create an image. How can I instead output the image via a function call (I am using the Zend Framework so will be using a View Helper) rather than simply pointing to a .php file in an img tag as above?
Any help greatly appreciated. | you can't.
at least not in a useable way - you could encode the image with base64:
```
<img src="data:image/png;base64,iVBORw0KGgoAAAANS..." alt=""/>
```
i don't have any idea which browsers support this, though ... quick test:
* firefox: ok
* chrome: ok
* opera: ok
* ie6: fail
* ie7: fail
* safari: fail
ok, forget it.
but, you're probably trying to do something different - passing the file through ZF. i can't help you with that, but it should work roughly like this:
in your controller, set the output type to image/png (however ZF handles that) pass through your image and make sure ZF doesn't add anything to the output (like additional html and stuff). | Why not make your View Helper create an image, write it to disk, and then output/return the img tag with the correct source attribute? | Outputting image using php GD library via function call | [
"",
"php",
"zend-framework",
"gd",
""
] |
Is it possible to check if the client browser has javascript enabled from ASP.NET code?
I was hoping to ideally do this on PreRender of controls, or PageLoad, so that I can change how they look.
Any suggestions, work arounds etc would be much appreciated. | You can't do it, without making a subsequent request I'm afraid.
There are explanations that can be found by doing a search on Google most use an AJAX call or a hidden field that gets popluated via some javascript, that won't get run if Javascript is disabled.
If you have to do it then I'd try doing it on the very first request from the client, and save a cookie (or somethign similar), then check the value of the cookie on subsequent requests. This assumes that the user doesn't enable / disable Javascript often. You could also store a value in the session.
I hope that helps | Page.Request.Browser.EcmaScriptVersion will indicate what *ASP.NET* thinks is true. This assumes that the BrowserCaps are correct. It does give you a first pass indication which is probably pretty close.
**EDIT:** I initially misunderstood the question (enabled vs. supported). You could use the BrowserCaps server side to weed out those UserAgents that *don't* support JavaScript. Then use one line of script on each request to determine if it is enabled via cookie:
```
// let the server know JavaScript is enabled via session cookie
document.cookie = "js=1; path=/";
```
Then detect existence server-side:
```
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("js");
bool js = (cookie != null) && (cookie.Value == "1");
```
Once they close the browser this cookie will go away. | Check if Javascript is enabled server side ASP.NET | [
"",
"asp.net",
"javascript",
""
] |
What does it mean to sign an assembly? And why is it done?
What is the simplest way to sign it? What is the .snk file for? | The other two answers are fine, but one additional point. It is easy to get confused between "certificate" signing and "strong name" signing.
The purpose of strong name signing is as Stefan Steinegger says: to allow your customer to establish that the code they THINK they're loading really is precisely the code that they ARE loading. That is ALL strong names are for. Specifically, strong names do not *establish* any kind of trust relationship between your customer and you. If the customer decides that they trust code that comes from you, it is up to THEM to figure out exactly what the correct strong name is for your code. The "key management" problem is not in any way solved; the customer has the burden of figuring out how to know what key to trust.
Certificate signing, that is, signing with a certificate you get from Verisign or some other certifying authority, has a much more complex purpose. The purpose of certificate signing is to establish an authenticated chain of trust and identity from the certifying authority down to the organization which signed the code. Your customer might not trust you, your customer might not have even *heard* of you, but your customer can say "if Verisign vouches for the identity of the author of this code, then I will trust them". The key management problem is reduced for the customer because the certifying authority has taken on that burden for them. | ## What does it mean to sign an assembly?
To sign an assembly is to give the assembly a strong name.
## Why is it done?
First, let's make an important distinction.
One way to categorize assemblies in .NET is as follows:
* **[Private Assembly](http://msdn.microsoft.com/en-us/library/ff951638%28VS.85%29.aspx)**, is isolated for use by a single application (the default). It is usually found in the same directory as the application.
* **[Shared Assembly](http://msdn.microsoft.com/en-us/library/ff951639%28v=VS.85%29.aspx)**, is globally accessible by all the applications in your machine. It is usually found in the [GAC](http://msdn.microsoft.com/en-us/library/yf1d93sz.aspx), and it must be signed, i.e., it must have a strong name (made up of the name, version, public key and culture of the assembly).
Why? Having a strong name guarantees that your assembly is unique and that nobody can steal the GUID (as in COM) to create a different object with the same name. In other words, you are ensuring that when you load a signed assembly, you are loading exactly what you think you are loading. Eric Lippert offered a great answer to this particular question [here](https://stackoverflow.com/questions/1334631/signing-of-net-assemblies).
This is not the same as saying that a signed assembly can be trusted. For that, an assembly can include [Authenticode](http://msdn.microsoft.com/en-us/library/ms537359%28v=VS.85%29.aspx), a digital signature to provide information about the assembly developer/company.
## What is the simplest way to sign it?
The following is the short version of the [MSDN step-by-step](http://support.microsoft.com/kb/815808):
1. Create a strong key using SN.EXE
> sn -k C:\mykey.snk
2. From Visual Studio, on your project Properties page, go to the Signing tab, and check on "Sign the assembly" to pick the file just created

3. Rebuild your project, and voila. Your assembly is now signed. You can see this in the CSPROJ file of your project:
> ```
> <PropertyGroup>
> <SignAssembly>true</SignAssembly>
> </PropertyGroup>
> <PropertyGroup>
> <AssemblyOriginatorKeyFile>mykey.snk</AssemblyOriginatorKeyFile>
> </PropertyGroup>
> ```
4. The **gacutil** tool allows you to manage your shared assembly in the GAC:
* Install: gacutil /i myassembly.dll
* View assembly in GAC: gacutil /l myassembly.dll
* Uninstall: gacutil /u myassembly.dll
## What is the .SNK file for?
The [SNK](http://www.fileinfo.com/extension/snk) is the 'Strong Name Key' file. | Signing assemblies - basics | [
"",
"c#",
".net",
"assemblies",
""
] |
I am working on a cron job which sends report to hundreds of users around the world. The cron should send an email to all my users at exactly 12am in the morning according to their timezone. Thanks in advance | ```
Your Time | Timezone You Need
-----------------------------
12:00am 0
1:00am -1
2:00am -2
3:00am -3
4:00am -4
5:00am -5
...
12:00pm +/- 12
1:00pm +11
2:00pm +10
3:00pm +9
...
------------------------------
```
You should be able to see the pattern start to develop here. The pattern should end up being something like Timezone Difference = (12-your current hour) | You need a list of which timezone all your users are in + whether they're using daylight savings or not.
For a complete list of timezones see this [wikipedia article](http://en.wikipedia.org/wiki/Time_zone)
Then every 15 minutes you need to have cron run a script to all the users in the current timezone offset.
e.g. at UTC + 5:45 send your mails to all users in the "Kathmandu" timezone | How do you determine which timezone is at 12am right now? | [
"",
"php",
"datetime",
""
] |
I want to develop an application with simple Quiz-like games (think of a question , answer, a timer, high-scores/ranking, not much more)
For that I want to use Rails and some javascript library that let me have some modern effects on the GUI (being a GUI the least you can ask is for an atractive interface)
I first considered ExtJS but now I think is too serious for this.
Also there are millions of extensions for prototype(<http://stickmanlabs.com/lightwindow/> <http://underwhelm.net/pinwheel/> etc) that looks more casual but dont know if they will play well with rails
So what is in general the best Javascript gui/widgets library out there when the backend is going to be Rails?
And in my particular case what would you recommend? | Scriptaculous will be your best choice. Other libraries will conflict with Prototype, if it is present. If you are creating one simple interface with the features you mentioned, you can probably get away just using Prototype/Scriptaculous and a few plugins. JQuery is great, but the $ conflicts with the Prototype override, causing it to be more difficult to work with.
If you need help with prototype, I found that <http://prototypejs.org/learn> is useful. | jQuery works just fine. In addition, jQuery works with Prototype if jQuery is run in the compatibility mode (Google: jQuery compatibility mode).
If you want to use all Rails' helper methods for AJAX requests with jQuery, go and try jRails. I prefer working with jQuery, since it is more widely used than Prototype.
**All in all, both jQuery and Prototype are very good choices with Rails**.
Its also worth looking Mootools. Here is one artictle worth reading [jQuery vs. Mootools](http://jqueryvsmootools.com/). I am not sure how well Mootools works with Rails' helper methods. | Best javascript libraries to work with rails? | [
"",
"javascript",
"ruby-on-rails",
"ruby",
"widget",
""
] |
This topic expands on [When do/should I use \_\_construct(), \_\_get(), \_\_set(), and \_\_call() in PHP?](https://stackoverflow.com/questions/250616/when-do-should-i-use-construct-get-set-and-call-in-php) which talks about the `__construct`, `__get` and `__set` magic methods.
As of PHP 5.3 there is a new Magic Method called `__invoke`. The `__invoke` method is called when a script tries to call an object as a function.
Now on research I have done for this method, people liken it to the Java method `.run()` - see [Interface Runnable](http://java.sun.com/j2se/1.4.2/docs/api/java/lang/Runnable.html).
Having thought long and hard about this I can't think of any reason why you would call `$obj();` as opposed to `$obj->function();`
Even if you were iterating over an array of objects, you would still know the main function name that you would want to run.
So is the `__invoke` magic method another example of 'just because you can, doesn't mean you should' shortcut in PHP, or are there cases where this would actually be the right thing to do? | > This answer is slightly outdated for being written in 2009. Please take it with a grain of salt.
PHP does not allow the passing of function pointers like other languages. Functions are not [first class](http://en.wikipedia.org/wiki/First-class_function) in PHP. Functions being first class mainly means that you can save a function to a variable, and pass it around and execute it at any time.
The `__invoke` method is a way that PHP can accommodate pseudo-first-class functions.
The `__invoke` method can be used to pass a class that can act as a [closure](http://en.wikipedia.org/wiki/Closure_(computer_science)) or a [continuation](http://en.wikipedia.org/wiki/Continuation), or simply as a function that you can pass around.
A lot of functional programming relies on first class functions. Even normal imperative programming can benefit from this.
Say you had a sort routine, but wanted to support different compare functions. Well, you can have different compare classes that implement the \_\_invoke function and pass in instances to the class to your sort function, and it doesn't even have to know the name of the function.
Really, you could always have done something like passing a class and have a function call a method, but now you can almost talk about passing a "function" instead of passing a class, although it's not as clean as in other languages. | The use of [`__invoke`](http://php.net/manual/en/language.oop5.magic.php#language.oop5.magic.invoke) makes sense when you need a [callable](http://php.net/manual/en/language.types.callable.php) that has to to maintain some internal state. Lets say you want to sort the following array:
```
$arr = [
['key' => 3, 'value' => 10, 'weight' => 100],
['key' => 5, 'value' => 10, 'weight' => 50],
['key' => 2, 'value' => 3, 'weight' => 0],
['key' => 4, 'value' => 2, 'weight' => 400],
['key' => 1, 'value' => 9, 'weight' => 150]
];
```
The [usort](http://php.net/manual/en/function.usort.php) function allows you to sort an array using some function, very simple. However in this case we want to sort the array using its inner arrays `'value'` key, what could be done this way:
```
$comparisonFn = function($a, $b) {
return $a['value'] < $b['value'] ? -1 : ($a['value'] > $b['value'] ? 1 : 0);
};
usort($arr, $comparisonFn);
// ['key' => 'w', 'value' => 2] will be the first element,
// ['key' => 'w', 'value' => 3] will be the second, etc
```
Now maybe you need to sort the array again, but this time using `'key'` as the target key, it would be necessary to rewrite the function:
```
usort($arr, function($a, $b) {
return $a['key'] < $b['key'] ? -1 : ($a['key'] > $b['key'] ? 1 : 0);
});
```
As you can see the logic of the function is identical to the previous one, however we can't reuse the previous due to the necessity of sorting with a different key. This problem can be addressed with a class that encapsulates the logic of comparison in the `__invoke` method and that define the key to be used in its constructor:
```
class Comparator {
protected $key;
public function __construct($key) {
$this->key = $key;
}
public function __invoke($a, $b) {
return $a[$this->key] < $b[$this->key] ?
-1 : ($a[$this->key] > $b[$this->key] ? 1 : 0);
}
}
```
A Class object that implements `__invoke` it's a "callable", it can be used in any context that a function could be, so now we can simply instantiate `Comparator` objects and pass them to the `usort` function:
```
usort($arr, new Comparator('key')); // sort by 'key'
usort($arr, new Comparator('value')); // sort by 'value'
usort($arr, new Comparator('weight')); // sort by 'weight'
```
**The following paragraphs reflect my subjective opinion, so if you want you can stop reading the answer now ;)**: Although the previous example showed a very interesting use of `__invoke`, such cases are rare and I would avoid its use since it can be done in really confusing ways and generally there are simpler implementation alternatives. An example of an alternative in the same sorting problem would be the use of a function that returns a comparison function:
```
function getComparisonByKeyFn($key) {
return function($a, $b) use ($key) {
return $a[$key] < $b[$key] ? -1 : ($a[$key] > $b[$key] ? 1 : 0);
};
}
usort($arr, getComparisonByKeyFn('weight'));
usort($arr, getComparisonByKeyFn('key'));
usort($arr, getComparisonByKeyFn('value'));
```
Although this example requires a little more intimacy with [lambdas | closures | anonymous functions](http://php.net/manual/en/functions.anonymous.php) it's much more concise since it doesn't create a whole class structure just to store an outer value. | PHP 5.3 Magic Method __invoke | [
"",
"php",
"oop",
"magic-methods",
""
] |
I want to declare an array of "jumplabels".
Then I want to jump to a "jumplabel" in this array.
But I have not any idea how to do this.
It should look like the following code:
```
function()
{
"gotolabel" s[3];
s[0] = s0;
s[1] = s1;
s[2] = s2;
s0:
....
goto s[v];
s1:
....
goto s[v];
s2:
....
goto s[v];
}
```
Does anyone have a idea how to perform this? | It is possible with GCC feature known as "[labels as values](http://gcc.gnu.org/onlinedocs/gcc/Labels-as-Values.html)".
```
void *s[3] = {&&s0, &&s1, &&s2};
if (n >= 0 && n <=2)
goto *s[n];
s0:
...
s1:
...
s2:
...
```
**It works only with GCC!** | `goto` needs a compile-time label.
From this example it seems that you are implementing some kind of state machine. Most commonly they are implemented as a switch-case construct:
```
while (!finished) switch (state) {
case s0:
/* ... */
state = newstate;
break;
/* ... */
}
```
If you need it to be more dynamic, use an array of function pointers. | How to store goto labels in an array and then jump to them? | [
"",
"c++",
"c",
"goto",
"jump-table",
""
] |
I have a hierarchy of types - GenericClass and a number of derived classes, InterestingDerivedClass included, GenericClass is polymorphic. There's an interface
```
interface ICallback {
virtual void DoStuff( GenericClass* ) = 0;
};
```
which I need to implement. Then I want to detect the case when GenericClass\* pointer passed into ICallback::DoStuff() is really a pointer to InterestingDerivedClass:
```
class CallbackImpl : public ICallback {
void DoStuff( GenericClass* param ) {
if( dynamic_cast<InterestingDerivedClass*>( param ) != 0 ) {
return; //nothing to do here
}
//do generic stuff
}
}
```
The GenericClass and the derived classes are out of my control, I only control the CallbackImpl.
I timed the dynamic\_cast statement - it takes about 1400 cycles which is acceptable for the moment, but looks like not very fast. I tried to read the disassembly of what is executed during dynamic\_cast in the debugger and saw it takes a lot of instructions.
Since I really don't need the pointer to the derived class is there a faster way of detecting object type at runtime using RTTI only? Maybe some implementation-specific method that only checks the "is a" relationship but doesn't retrieve the pointer? | I always look on the use of `dynamic_cast` as a code smell. You can replace it in all circumstances with polymorphic behaviour and improve your code quality. In your example I would do something like this:
```
class GenericClass
{
virtual void DoStuff()
{
// do interesting stuff here
}
};
class InterestingDerivedClass : public GenericClass
{
void DoStuff()
{
// do nothing
}
};
class CallbackImpl : public ICallback {
void DoStuff( GenericClass* param ) {
param->DoStuff();
}
}
```
In your case, you cannot modify the target classes, you are programming to a contract implied by the declaration of the `GenericClass` type. Therefore, there is unlikely to be anything that you can do that would be faster than `dynamic_cast` would be, since anything else would require modifying the client code. | As others have said, using a virtual function is good practice. There is another reason for using it, not applicable in your case, as you can't add the VF, but still worth mentioning I think - it may be much faster than using dynamic cast. In some (not very stringent) tests I've done with g++, the virtual function out-performed the dynamic\_cast by a factor of 4.
Because there is such a disparity, it may be worth creating your own inheritance hierarchy which wraps the code you don't control. You would create instances of the wrapper using dynamic\_cast (once) to decide what derived type to create, and then use virtual functions from there on. | Is there a faster way to detect object type at runtime than using dynamic_cast? | [
"",
"c++",
"visual-c++",
"dynamic",
"polymorphism",
""
] |
I need a function that will return a random integer that can be only -1, 0, or 1.
Thanks? | As Apocalisp wrote, you could do something like:
```
import java.util.Random;
Random generator = new Random();
int randomIndex = generator.nextInt( 3 ) - 1;
``` | How about generating a random from 0 to 2 and subtracting 1? | Java Generate Random number {-1,0,1} | [
"",
"java",
"random",
""
] |
I got a question about Java Reflections: I have to checkout, if a certain field of a class is an array.
But my problem is: If i run isArray() on the attribute of the class directly, it works. But if I use it in the way below, it won"t work. I guess because the "real" array is in this Field class?
Any idea how i get it to work - I think there is missing a cast or sth like that?
Thanks!
```
Field fields[] = object.getClass().getDeclaredFields();
for (Field field : fields) {
if (field.getClass().isArray()) {
//Always false.
}
}
``` | [`field.getType()`](http://java.sun.com/javase/6/docs/api/java/lang/reflect/Field.html#getType())! | Your code should read
```
Field fields[] = obj.getClass().getDeclaredFields();
for(Field field : fields) {
if(field.getType().isArray()){
//Actually works
}
}
```
Using field.getClass() as you are will always return Field.class or a Class instance of a subclass of Field\*.
\*My apologizes for such a confusingly worded sentence. | Java Reflection isArray() always false | [
"",
"java",
"arrays",
"reflection",
""
] |
In JSLint, it warns that
```
var x = new Array();
```
(That's not a real variable name) should be
```
var result = [];
```
What is wrong with the 1st syntax? What's the reasoning behind the suggestion? | [Crockford doesn't like `new`](https://stackoverflow.com/questions/383402/is-javascript-s-new-keyword-considered-harmful). Therefore, [JSLint expects you to avoid it](http://www.jslint.com/lint.html#new) when possible. And creating a new array object is possible without using `new`.... | It's safer to use `[]` than it is to use `new Array()`, because you can actually override the value of `Array` in JavaScript:
```
Array = function() { };
var x = new Array();
// x is now an Object instead of an Array.
```
In other words, `[]` is unambiguous. | What's wrong with var x = new Array(); | [
"",
"javascript",
"jslint",
""
] |
I want to simulate data changing in the model and having that data be reflected in XAML. As I understand I need to implement INotifyPropertyChanged.
However, in the following code example, XAML displays the data from the customer only once but the date and time never changes.
**What do I have to change in the following example to make XAML continually display the current date and time as it changes in the model?**
In particular, I don't understand how the Binding would know when to check the model, every second? 10 times a second? There is no event that it is responding to. What am I missing here?
**XAML:**
```
<Window x:Class="TestBinding99382.Window1"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:TestBinding99382"
Title="Window1" Height="300" Width="300">
<Window.Resources>
<ObjectDataProvider
x:Key="DataSourceCustomer"
ObjectType="{x:Type local:ShowCustomerViewModel}"
MethodName="GetCurrentCustomer"/>
</Window.Resources>
<DockPanel DataContext="{StaticResource DataSourceCustomer}">
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
<TextBlock Text="{Binding Path=FirstName}"/>
<TextBlock Text=" "/>
<TextBlock Text="{Binding Path=LastName}"/>
</StackPanel>
<StackPanel DockPanel.Dock="Top" Orientation="Horizontal">
<TextBlock Text="{Binding Path=TimeOfMostRecentActivity}"/>
</StackPanel>
</DockPanel>
</Window>
```
**Code Behind:**
```
using System.Windows;
using System.ComponentModel;
using System;
namespace TestBinding99382
{
public partial class Window1 : Window
{
public Window1()
{
InitializeComponent();
}
}
//view model
public class ShowCustomerViewModel : INotifyPropertyChanged
{
private Customer _currentCustomer;
public Customer CurrentCustomer
{
get
{
return _currentCustomer;
}
set
{
_currentCustomer = value;
this.RaisePropertyChanged("CurrentCustomer");
}
}
public ShowCustomerViewModel()
{
_currentCustomer = Customer.GetCurrentCustomer();
}
public Customer GetCurrentCustomer()
{
return _currentCustomer;
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
//model
public class Customer : INotifyPropertyChanged
{
private string _firstName;
private string _lastName;
private DateTime _timeOfMostRecentActivity;
public string FirstName
{
get
{
return _firstName;
}
set
{
_firstName = value;
this.RaisePropertyChanged("FirstName");
}
}
public string LastName
{
get
{
return _lastName;
}
set
{
_lastName = value;
this.RaisePropertyChanged("LastName");
}
}
public DateTime TimeOfMostRecentActivity
{
get
{
return _timeOfMostRecentActivity;
}
set
{
_timeOfMostRecentActivity = value;
this.RaisePropertyChanged("TimeOfMostRecentActivity");
}
}
public static Customer GetCurrentCustomer()
{
return new Customer
{ FirstName = "Jim"
, LastName = "Smith"
, TimeOfMostRecentActivity = DateTime.Now};
}
public event PropertyChangedEventHandler PropertyChanged;
private void RaisePropertyChanged(string property)
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(property));
}
}
}
}
``` | Maybe I'm not getting what you wish this code to do.
You have created a Customer Object which implements INotifyPropertyChanged. You have another class which is a factory for the XAML to get to the instance.
Now you create a Customer instance with predefined properties. The View displays them. Unless you change the properties somehow, the View will not update.
I added a button to your WPF View
```
<Button DockPanel.Dock="Bottom"
x:Name="UpdateTime"
Click="UpdateTime_Click">
Update Activity Timestamp
</Button>
```
C# code-behind:
```
private void UpdateTime_Click(object sender, RoutedEventArgs e)
{
Customer.GetCurrentCustomer().TimeOfMostRecentActivity = DateTime.Now;
}
```
I also changed Customer type to create a single instance for Current Customer
```
private static Customer _CurrentCustomer;
public static Customer GetCurrentCustomer()
{
if (null == _CurrentCustomer)
{
_CurrentCustomer = new Customer
{ FirstName = "Jim"
, LastName = "Smith"
, TimeOfMostRecentActivity = DateTime.Now
};
}
return _CurrentCustomer;
}
```
Now each time I click the button, the `DateTime` Property is modified and the view auto-updates due to the `INotifyPropertyChanged` mechanism. The code seems to be working AFAISee. | Your code is working correctly. The current date and time will not update automatically by magic. You have to implement some timer to update it.
For exemple you could add this to your Customer class:
```
private Timer _timer;
public Customer()
{
_timer = new Timer(UpdateDateTime, null, 0, 1000);
}
private void UpdateDateTime(object state)
{
TimeOfMostRecentActivity = DateTime.Now;
}
``` | Why is INotifyPropertyChanged not updating the variables in XAML? | [
"",
"c#",
"wpf",
"xaml",
"data-binding",
"inotifypropertychanged",
""
] |
I'm getting the error:
`This report requires a default or user-defined value for the report parameter '*'. To run or subscribe to this report, you must provide a parameter value.`
very occasionally from my reporting server even when the value '\*' is being populated. Any ideas or leads that might allow me to track it down? Some points.
* I run the reports 4-way asynchronously (meaning 4 threads generating reports at a time).
* The reports have 2 provided parameters (always supplied) and one derived parameter.
* I run 1,000 reports per session with ~250 reports per thread.
* Sometimes the error will hit after a few seconds, sometimes after many hours.
```
using System;
using System.Globalization;
using System.IO;
using Cns.ReportExecution2005;
public class PdfGenerator
{
private readonly ReportExecutionService reportExecutionService;
public PdfGenerator(string executionServiceAddress)
{
// Create a new proxy to the web service
this.reportExecutionService = new ReportExecutionService
{
Credentials = System.Net.CredentialCache.DefaultNetworkCredentials,
Url = executionServiceAddress
};
}
public Stream GenerateReport(string reportName, string format, ReportGeneratorParameter[] parameters)
{
if (reportName == null)
{
throw new ArgumentNullException("reportName");
}
if (format == null)
{
throw new ArgumentNullException("format");
}
this.reportExecutionService.LoadReport(reportName, null);
if (parameters != null)
{
var executionParameters = new ParameterValue[parameters.Length];
for (int i = 0; i < parameters.Length; ++i)
{
executionParameters[i] = new ParameterValue
{
Label = parameters[i].Name,
Name = parameters[i].Name,
Value = Convert.ToString(parameters[i].Value, CultureInfo.InvariantCulture)
};
}
this.reportExecutionService.SetExecutionParameters(executionParameters, "en-us");
}
string extension;
string encoding;
string mimeType;
Warning[] warnings;
string[] streamIDs;
byte[] results = this.reportExecutionService.Render(format, null, out extension, out encoding, out mimeType, out warnings, out streamIDs);
return new MemoryStream(results);
}
}
``` | When working with external web services it's important to realize that each request made through an instance of automatically generated wrapper class is tied to all other calls made through that instance. So here one `PdfGenerator` class is being instantiated, but the four threads that are making calls to it are making them all through the same interface so that you have:
> Thread A: Setup Parameters
> Thread B: Setup Parameters
> Thread A: Execute (consuming thread B's parameters)
> Thread B: Execute (no parameters given, exception thrown)
Each thread will need its own instance of the `PdfGenerator` class in that each one needs its own instance of the `ReportExecutionService` | For others looking for answers on this subject (google search brought me here) it can also be caused by a parameter being defined as "From Query" rather than "Non Queried". Then if you pass in a parameter that is not valid as per the query, you can get this error.
For instance, you have a parameter called CustomerId which is presented via the web interface as Select CustomerId, CustomerName from Customer
Lets say valid customer ids in the database are 1 to 10.
If you pass in a parameter in c# with a value of 24, (Ie out of that range) RS acts as if the parameter was never passed in since it detects it is not in the valid range.
hope this helps | How to solve error: This report requires a default or user-defined value for the report parameter '*' | [
"",
"c#",
"sql-server",
"reporting-services",
""
] |
*I would like to use single a href link to call different functions .
On first click it should call first\_function() and on second click it should call second\_function.
Like toggling between two functions using same link. Suggest the best way to be done.*
> ***Jquery Code :***
```
$(function() {
var IntervalId;
function first_function() {
//code goes here
};
function second_function(){
//code goes here
}
$("#link2").click((function(){
second_function();
}));
$("#link1").click((function(){
first_function();
}));
});
```
> ***Html Code :***
```
<a href="javascript:void(0);" id="link2">Call function2</a>
<a href="javascript:void(0);" id="link1">Call function1</a>
``` | > "Like toggling between two functions using same link."
```
$("#link1").toggle(
function first_function() {
// Code goes here
},
function second_function(){
// Code goes here
}
);
```
From the jQuery docs on [`toggle(fn1, fn2, [fn3, [fn4, [...]]]`)](http://docs.jquery.com/Events/toggle#fnfn2fn3.2Cfn4.2C...):
> Toggle among two or more function calls every other click. | the easiest way would be
```
var performFirstAction = true;
$(function() {
function first_function() {
// Code goes here
}
function second_function(){
// Code goes here
}
$("#link1").click(function(){
if(performFirstAction) {
first_function(); performFirstAction = false; }
else {
second_function(); performFirstAction = true; }
});
});
```
or using toggle as Tomalak mention and well,
```
$(function() {
function first_function() {
// Code goes here
}
function second_function(){
// Code goes here
}
$("#link1").toggle(
first_function,
second_function
);
});
``` | Using Jquery calling different functions with a singe link | [
"",
"javascript",
"jquery",
"html",
""
] |
The first parser generator I've worked with was Parse::RecDescent, and the guides/tutorials available for it were great, but the most useful feature it has was it's debugging tools, specifically the **tracing** capabilities ( activated by setting $RD\_TRACE to 1 ). I am looking for a parser generator that can help you debug it's rules.
The thing is, it has to be written in Python or in Ruby, and have a verbose mode/trace mode or very helpful debugging techniques.
Does anyone know such a parser generator ?
## Edit
When I said debugging, I wasn't referring to debugging Python or Ruby. I was referring to debugging the parser generator, see what it's doing at every step, see every char it's reading, rules it's trying to match.
## Edit
I am seeking a parser generator framework, and an illustration of some of its debugging features. I'm not interested in pdb, but in parser's debugging framework. Also, please don't mention treetop. I'm not interested in it. | Python is a pretty easy language to debug. You can just do import pdb pdb.settrace().
However, these parser generators supposedly come with good debugging facilities.
<http://www.antlr.org/>
<http://www.dabeaz.com/ply/>
<http://pyparsing.wikispaces.com/>
**In response to bounty**
Here is PLY debugging in action.
Source Code
```
tokens = (
'NAME','NUMBER',
)
literals = ['=','+','-','*','/', '(',')']
# Tokens
t_NAME = r'[a-zA-Z_][a-zA-Z0-9_]*'
def t_NUMBER(t):
r'\d+'
t.value = int(t.value)
return t
t_ignore = " \t"
def t_newline(t):
r'\n+'
t.lexer.lineno += t.value.count("\n")
def t_error(t):
print("Illegal character '%s'" % t.value[0])
t.lexer.skip(1)
# Build the lexer
import ply.lex as lex
lex.lex(debug=1)
# Parsing rules
precedence = (
('left','+','-'),
('left','*','/'),
('right','UMINUS'),
)
# dictionary of names
names = { }
def p_statement_assign(p):
'statement : NAME "=" expression'
names[p[1]] = p[3]
def p_statement_expr(p):
'statement : expression'
print(p[1])
def p_expression_binop(p):
'''expression : expression '+' expression
| expression '-' expression
| expression '*' expression
| expression '/' expression'''
if p[2] == '+' : p[0] = p[1] + p[3]
elif p[2] == '-': p[0] = p[1] - p[3]
elif p[2] == '*': p[0] = p[1] * p[3]
elif p[2] == '/': p[0] = p[1] / p[3]
def p_expression_uminus(p):
"expression : '-' expression %prec UMINUS"
p[0] = -p[2]
def p_expression_group(p):
"expression : '(' expression ')'"
p[0] = p[2]
def p_expression_number(p):
"expression : NUMBER"
p[0] = p[1]
def p_expression_name(p):
"expression : NAME"
try:
p[0] = names[p[1]]
except LookupError:
print("Undefined name '%s'" % p[1])
p[0] = 0
def p_error(p):
if p:
print("Syntax error at '%s'" % p.value)
else:
print("Syntax error at EOF")
import ply.yacc as yacc
yacc.yacc()
import logging
logging.basicConfig(
level=logging.INFO,
filename="parselog.txt"
)
while 1:
try:
s = raw_input('calc > ')
except EOFError:
break
if not s: continue
yacc.parse(s, debug=1)
```
Output
```
lex: tokens = ('NAME', 'NUMBER')
lex: literals = ['=', '+', '-', '*', '/', '(', ')']
lex: states = {'INITIAL': 'inclusive'}
lex: Adding rule t_NUMBER -> '\d+' (state 'INITIAL')
lex: Adding rule t_newline -> '\n+' (state 'INITIAL')
lex: Adding rule t_NAME -> '[a-zA-Z_][a-zA-Z0-9_]*' (state 'INITIAL')
lex: ==== MASTER REGEXS FOLLOW ====
lex: state 'INITIAL' : regex[0] = '(?P<t_NUMBER>\d+)|(?P<t_newline>\n+)|(?P<t_NAME>[a-zA-Z
_][a-zA-Z0-9_]*)'
calc > 2+3
PLY: PARSE DEBUG START
State : 0
Stack : . LexToken(NUMBER,2,1,0)
Action : Shift and goto state 3
State : 3
Stack : NUMBER . LexToken(+,'+',1,1)
Action : Reduce rule [expression -> NUMBER] with [2] and goto state 9
Result : <int @ 0x1a1896c> (2)
State : 6
Stack : expression . LexToken(+,'+',1,1)
Action : Shift and goto state 12
State : 12
Stack : expression + . LexToken(NUMBER,3,1,2)
Action : Shift and goto state 3
State : 3
Stack : expression + NUMBER . $end
Action : Reduce rule [expression -> NUMBER] with [3] and goto state 9
Result : <int @ 0x1a18960> (3)
State : 18
Stack : expression + expression . $end
Action : Reduce rule [expression -> expression + expression] with [2,'+',3] and goto state
3
Result : <int @ 0x1a18948> (5)
State : 6
Stack : expression . $end
Action : Reduce rule [statement -> expression] with [5] and goto state 2
5
Result : <NoneType @ 0x1e1ccef4> (None)
State : 4
Stack : statement . $end
Done : Returning <NoneType @ 0x1e1ccef4> (None)
PLY: PARSE DEBUG END
calc >
```
Parse Table generated at parser.out
```
Created by PLY version 3.2 (http://www.dabeaz.com/ply)
Grammar
Rule 0 S' -> statement
Rule 1 statement -> NAME = expression
Rule 2 statement -> expression
Rule 3 expression -> expression + expression
Rule 4 expression -> expression - expression
Rule 5 expression -> expression * expression
Rule 6 expression -> expression / expression
Rule 7 expression -> - expression
Rule 8 expression -> ( expression )
Rule 9 expression -> NUMBER
Rule 10 expression -> NAME
Terminals, with rules where they appear
( : 8
) : 8
* : 5
+ : 3
- : 4 7
/ : 6
= : 1
NAME : 1 10
NUMBER : 9
error :
Nonterminals, with rules where they appear
expression : 1 2 3 3 4 4 5 5 6 6 7 8
statement : 0
Parsing method: LALR
state 0
(0) S' -> . statement
(1) statement -> . NAME = expression
(2) statement -> . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
NAME shift and go to state 1
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
expression shift and go to state 6
statement shift and go to state 4
state 1
(1) statement -> NAME . = expression
(10) expression -> NAME .
= shift and go to state 7
+ reduce using rule 10 (expression -> NAME .)
- reduce using rule 10 (expression -> NAME .)
* reduce using rule 10 (expression -> NAME .)
/ reduce using rule 10 (expression -> NAME .)
$end reduce using rule 10 (expression -> NAME .)
state 2
(7) expression -> - . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 9
state 3
(9) expression -> NUMBER .
+ reduce using rule 9 (expression -> NUMBER .)
- reduce using rule 9 (expression -> NUMBER .)
* reduce using rule 9 (expression -> NUMBER .)
/ reduce using rule 9 (expression -> NUMBER .)
$end reduce using rule 9 (expression -> NUMBER .)
) reduce using rule 9 (expression -> NUMBER .)
state 4
(0) S' -> statement .
state 5
(8) expression -> ( . expression )
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 10
state 6
(2) statement -> expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
$end reduce using rule 2 (statement -> expression .)
+ shift and go to state 12
- shift and go to state 11
* shift and go to state 13
/ shift and go to state 14
state 7
(1) statement -> NAME = . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 15
state 8
(10) expression -> NAME .
+ reduce using rule 10 (expression -> NAME .)
- reduce using rule 10 (expression -> NAME .)
* reduce using rule 10 (expression -> NAME .)
/ reduce using rule 10 (expression -> NAME .)
$end reduce using rule 10 (expression -> NAME .)
) reduce using rule 10 (expression -> NAME .)
state 9
(7) expression -> - expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
+ reduce using rule 7 (expression -> - expression .)
- reduce using rule 7 (expression -> - expression .)
* reduce using rule 7 (expression -> - expression .)
/ reduce using rule 7 (expression -> - expression .)
$end reduce using rule 7 (expression -> - expression .)
) reduce using rule 7 (expression -> - expression .)
! + [ shift and go to state 12 ]
! - [ shift and go to state 11 ]
! * [ shift and go to state 13 ]
! / [ shift and go to state 14 ]
state 10
(8) expression -> ( expression . )
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
) shift and go to state 16
+ shift and go to state 12
- shift and go to state 11
* shift and go to state 13
/ shift and go to state 14
state 11
(4) expression -> expression - . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 17
state 12
(3) expression -> expression + . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 18
state 13
(5) expression -> expression * . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 19
state 14
(6) expression -> expression / . expression
(3) expression -> . expression + expression
(4) expression -> . expression - expression
(5) expression -> . expression * expression
(6) expression -> . expression / expression
(7) expression -> . - expression
(8) expression -> . ( expression )
(9) expression -> . NUMBER
(10) expression -> . NAME
- shift and go to state 2
( shift and go to state 5
NUMBER shift and go to state 3
NAME shift and go to state 8
expression shift and go to state 20
state 15
(1) statement -> NAME = expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
$end reduce using rule 1 (statement -> NAME = expression .)
+ shift and go to state 12
- shift and go to state 11
* shift and go to state 13
/ shift and go to state 14
state 16
(8) expression -> ( expression ) .
+ reduce using rule 8 (expression -> ( expression ) .)
- reduce using rule 8 (expression -> ( expression ) .)
* reduce using rule 8 (expression -> ( expression ) .)
/ reduce using rule 8 (expression -> ( expression ) .)
$end reduce using rule 8 (expression -> ( expression ) .)
) reduce using rule 8 (expression -> ( expression ) .)
state 17
(4) expression -> expression - expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
+ reduce using rule 4 (expression -> expression - expression .)
- reduce using rule 4 (expression -> expression - expression .)
$end reduce using rule 4 (expression -> expression - expression .)
) reduce using rule 4 (expression -> expression - expression .)
* shift and go to state 13
/ shift and go to state 14
! * [ reduce using rule 4 (expression -> expression - expression .) ]
! / [ reduce using rule 4 (expression -> expression - expression .) ]
! + [ shift and go to state 12 ]
! - [ shift and go to state 11 ]
state 18
(3) expression -> expression + expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
+ reduce using rule 3 (expression -> expression + expression .)
- reduce using rule 3 (expression -> expression + expression .)
$end reduce using rule 3 (expression -> expression + expression .)
) reduce using rule 3 (expression -> expression + expression .)
* shift and go to state 13
/ shift and go to state 14
! * [ reduce using rule 3 (expression -> expression + expression .) ]
! / [ reduce using rule 3 (expression -> expression + expression .) ]
! + [ shift and go to state 12 ]
! - [ shift and go to state 11 ]
state 19
(5) expression -> expression * expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
+ reduce using rule 5 (expression -> expression * expression .)
- reduce using rule 5 (expression -> expression * expression .)
* reduce using rule 5 (expression -> expression * expression .)
/ reduce using rule 5 (expression -> expression * expression .)
$end reduce using rule 5 (expression -> expression * expression .)
) reduce using rule 5 (expression -> expression * expression .)
! + [ shift and go to state 12 ]
! - [ shift and go to state 11 ]
! * [ shift and go to state 13 ]
! / [ shift and go to state 14 ]
state 20
(6) expression -> expression / expression .
(3) expression -> expression . + expression
(4) expression -> expression . - expression
(5) expression -> expression . * expression
(6) expression -> expression . / expression
+ reduce using rule 6 (expression -> expression / expression .)
- reduce using rule 6 (expression -> expression / expression .)
* reduce using rule 6 (expression -> expression / expression .)
/ reduce using rule 6 (expression -> expression / expression .)
$end reduce using rule 6 (expression -> expression / expression .)
) reduce using rule 6 (expression -> expression / expression .)
! + [ shift and go to state 12 ]
! - [ shift and go to state 11 ]
! * [ shift and go to state 13 ]
! / [ shift and go to state 14 ]
``` | I don't know anything about its debugging features, but I've heard good things about PyParsing.
<http://pyparsing.wikispaces.com/> | Seeking an appropriate Ruby/Python parser generator | [
"",
"python",
"ruby",
"debugging",
"parser-generator",
""
] |
I am building a tracking system for refererrals to our websites and on behalf of other 3rd party website owners. This will include placing a cookie when a customer clicks through to the site and subseqently reading their ID from this cookie if they reach the defined 'success' page.
I have seen a number of different methods used for tracking and they all seem to fall into 2 categories:
1. Including an IMG tag which will link to a script that processes what it needs to and returns an image
2. Including an external javascript file, usually with the same approach as in 1 within tags.
What are the benefits of one approach over the other? I feel I must be missing something quite simple here however can only see that the javascript approach can be used to avoid image caching.
The server-side script is ASP.net
EDIT: The cookie / tracking approach is being used because it seems to be the industry standard, and we need to be able to track goals over a long period of time and / or many visits however alternatvies to this approach would be welcomed!
Thanks | If you include an external script in the <head> section, it is downloaded and executed before the page is shown, so you are sure that if a user saw the page they got tracked. For <img> tags there is no such guarantee, as the user might navigate away before the browser launches the load request for that image.
So, if you want to optimize for trackability, use a <script>, but if you want to optimize for performance (no slowdown if the tracking site is slow), use an <img>.
The caching issue exists in both cases, and can be solved by sending correct headers from the server or by appending cache-busting arguments to the URL. | It's worth noting that many tracking software pieces like Google Analytics utilize 1x1 pixels. If you are trying to avoid caching you can set the cache expiration on the particular page so that content will not be cached on the user end. As it stands though you really just need the cookie to be set the one time and if the user has not cleared their cache on subsequent visits chances are they haven't cleared their cookies either.
You can use either method and expect that there will be some small percentage of users that monitor cookies or scripts and will try to avoid having your cookie set on their machine. Almost no one browses with images disabled.
Those users who fall into that minority of people who are paranoid about cookies and/or javascript will not generally affect your tracking information overall unless of course your site specializes in serving content to that demographic (highly technical users etc). So, I wouldn't go overboard on tailoring your solution for that minority unless absolutely necessary. | tracking pixel or javascript include? | [
"",
"asp.net",
"javascript",
"html",
"tracking",
""
] |
With this
```
PROCEDURE "ADD_BOOKMARK_GROUP" (
"NAME" IN VARCHAR2,
"BOOKMARK_GROUP_ID" IN NUMBER,
"STAFF_ID" IN VARCHAR2,
"MAX_NO" IN INT,
"NUMFOUND" OUT INT,
"NEW_ID" OUT NUMBER) IS
BEGIN
NEW_ID := -1;
SELECT COUNT(*) INTO NUMFOUND FROM BOOKMARK_GROUP_TABLE WHERE STAFF_ID = STAFF_ID;
IF NUMFOUND < MAX_NO THEN
INSERT INTO BOOKMARK_GROUP_TABLE (NAME, BOOKMARK_GROUP_ID, STAFF_ID) VALUES(NAME, BOOKMARK_GROUP_ID, STAFF_ID);
SELECT BGT_SEQUENCE.currval INTO NEW_ID FROM dual;
END IF;
END;
```
I find it interesting that if I don't add parameters in the order they were defined in, e.g.
```
OracleCommand cmd = new OracleCommand("ADD_BOOKMARK_GROUP", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new OracleParameter("NAME", name));
...
cmd.Parameters.Add(new OracleParameter("NEW_ID", OracleDbType.Decimal)).Direction = ParameterDirection.Output;
cmd.Parameters.Add(new OracleParameter("NUMFOUND", OracleDbType.Int32)).Direction = ParameterDirection.Output;
```
instead of
```
OracleCommand cmd = new OracleCommand("ADD_BOOKMARK_GROUP", conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new OracleParameter("NAME", name));
...
cmd.Parameters.Add(new OracleParameter("NUMFOUND", OracleDbType.Int32)).Direction = ParameterDirection.Output;
cmd.Parameters.Add(new OracleParameter("NEW_ID", OracleDbType.Decimal)).Direction = ParameterDirection.Output;
```
The values returned by
```
cmd.Parameters["NEW_ID"].Value.ToString()
```
and
```
cmd.Parameters["NUMFOUND"].Value.ToString()
```
get swapped, although running the procedure through the VS2008 Server Explorer returns correct data.
Why is this? | I'm not an Oracle buff, so I can't verify - but it *sounds* like they are being passed by position (rather than passed by name). The moral equivelent to:
```
EXEC SomeProc 'Foo', 'Bar'
```
instead of:
```
EXEC SomeProc @arg1='Foo', @arg2='Bar'
```
This isn't hugely uncommon - for years (in the COM days) a lot of my code had to work with a pass-by-position ADODB driver.
In this case, the name that you give serves **only** as a local key to lookup the value from the collection collection. You can verify easily by inventing a name:
```
cmd.Parameters.Add(new OracleParameter("BANANA", ...
cmd.Parameters.Add(new OracleParameter("GUITAR", ...
...
cmd.Parameters["BANANA"].Value.ToString()
cmd.Parameters["GUITAR"].Value.ToString()
```
If the above runs without error, it is passing by position. And it they **are** passed by position... then simply add them in the right order ;-p And never add new parameters except at the end... | You can probably set the BindByName parameter on the OracleCommand object. This works for straight SQL queries with parameters, I've not tried it with stored procedures but it would be logical...
```
cmd.BindByName = true;
``` | C# Oracle Stored Procedure Parameter Order | [
"",
"c#",
"oracle",
"stored-procedures",
""
] |
I need some information from a website that's not mine, in order to get this information I need to login to the website to gather the information, this happens through a HTML form. How can I do this authenticated screenscaping in C#?
Extra information:
* Cookie based authentication.
* POST action needed. | You'd make the request as though you'd just filled out the form. Assuming it's POST for example, you make a POST request with the correct data. Now if you can't login directly to the same page you want to scrape, you will have to track whatever cookies are set after your login request, and include them in your scraping request to allow you to stay logged in.
It might look like:
```
HttpWebRequest http = WebRequest.Create(url) as HttpWebRequest;
http.KeepAlive = true;
http.Method = "POST";
http.ContentType = "application/x-www-form-urlencoded";
string postData="FormNameForUserId=" + strUserId + "&FormNameForPassword=" + strPassword;
byte[] dataBytes = UTF8Encoding.UTF8.GetBytes(postData);
http.ContentLength = dataBytes.Length;
using (Stream postStream = http.GetRequestStream())
{
postStream.Write(dataBytes, 0, dataBytes.Length);
}
HttpWebResponse httpResponse = http.GetResponse() as HttpWebResponse;
// Probably want to inspect the http.Headers here first
http = WebRequest.Create(url2) as HttpWebRequest;
http.CookieContainer = new CookieContainer();
http.CookieContainer.Add(httpResponse.Cookies);
HttpWebResponse httpResponse2 = http.GetResponse() as HttpWebResponse;
```
Maybe. | You can use a [WebBrowser](http://msdn.microsoft.com/en-us/library/system.windows.forms.webbrowser.aspx) control. Just feed it the URL of the site, then use the DOM to set the username and password into the right fields, and eventually send a click to the submit button. This way you don't care about anything but the two input fields and the submit button. No cookie handling, no raw HTML parsing, no HTTP sniffing - all that is done by the browser control.
If you go that way, a few more suggestions:
1. You can prevent the control from loading add-ins such as Flash - could save you some time.
2. Once you login, you can obtain whatever information you need from the DOM - no need to parse raw HTML.
3. If you want to make the tool even more portable in case the site changes in the future, you can replace your explicit DOM manipulation with an injection of JavaScript. The JS can be obtained from an external resource, and once called it can do the fields population and the submit. | How to programmatically log in to a website to screenscape? | [
"",
"c#",
"forms",
"authentication",
"web-scraping",
""
] |
I was using Boost 1.38, and I just upgraded to 1.39. Upgrading broke the following bit of code:
```
std::vector<std::wstring> consoleParser::loadStringsFromFile(const std::wstring &fileName)
{
std::vector<std::wstring> files;
std::wstring fileString(loadFileAsString(fileName));
boost::algorithm::split(files, fileString, boost::is_any_of(L"\r\n'\"")); //Error on this line
return files;
}
```
Any ideas on what's causing the failure? My compiler helpfully emits the following:
```
c:\boost\boost\utility\addressof.hpp(30) : error C2220: warning treated as error - no 'object' file generated
c:\boost\boost\utility\addressof.hpp(56) : see reference to class template instantiation 'boost::detail::addr_impl_ref<T>' being compiled
with
[
T=boost::algorithm::detail::token_finderF<boost::algorithm::detail::is_any_ofF<wchar_t>>
]
c:\boost\boost\function\function_template.hpp(600) : see reference to function template instantiation 'T *boost::addressof<FunctionObj>(T &)' being compiled
with
[
T=boost::algorithm::detail::token_finderF<boost::algorithm::detail::is_any_ofF<wchar_t>>,
FunctionObj=boost::algorithm::detail::token_finderF<boost::algorithm::detail::is_any_ofF<wchar_t>>
]
c:\boost\boost\function\function_template.hpp(491) : see reference to function template instantiation 'bool boost::detail::function::basic_vtable2<R,T0,T1>::assign_to<F>(FunctionObj,boost::detail::function::function_buffer &,boost::detail::function::function_obj_tag)' being compiled
with
[
R=boost::iterator_range<std::_String_iterator<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>>,
T0=std::_String_iterator<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>,
T1=std::_String_iterator<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>,
F=boost::algorithm::detail::token_finderF<boost::algorithm::detail::is_any_ofF<wchar_t>>,
FunctionObj=boost::algorithm::detail::token_finderF<boost::algorithm::detail::is_any_ofF<wchar_t>>
]
c:\boost\boost\function\function_template.hpp(906) : see reference to function template instantiation 'bool boost::detail::function::basic_vtable2<R,T0,T1>::assign_to<Functor>(F,boost::detail::function::function_buffer &)' being compiled
with
[
R=boost::iterator_range<std::_String_iterator<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>>,
T0=std::_String_iterator<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>,
T1=std::_String_iterator<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>,
Functor=boost::algorithm::detail::token_finderF<boost::algorithm::detail::is_any_ofF<wchar_t>>,
F=boost::algorithm::detail::token_finderF<boost::algorithm::detail::is_any_ofF<wchar_t>>
]
c:\boost\boost\function\function_template.hpp(720) : see reference to function template instantiation 'void boost::function2<R,T0,T1>::assign_to<Functor>(Functor)' being compiled
with
[
R=boost::iterator_range<std::_String_iterator<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>>,
T0=std::_String_iterator<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>,
T1=std::_String_iterator<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>,
Functor=boost::algorithm::detail::token_finderF<boost::algorithm::detail::is_any_ofF<wchar_t>>
]
c:\boost\boost\algorithm\string\detail\find_iterator.hpp(51) : see reference to function template instantiation 'boost::function2<R,T0,T1>::function2<FinderT>(Functor,int)' being compiled
with
[
R=boost::iterator_range<std::_String_iterator<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>>,
T0=std::_String_iterator<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>,
T1=std::_String_iterator<wchar_t,std::char_traits<wchar_t>,std::allocator<wchar_t>>,
FinderT=boost::algorithm::detail::token_finderF<boost::algorithm::detail::is_any_ofF<wchar_t>>,
Functor=boost::algorithm::detail::token_finderF<boost::algorithm::detail::is_any_ofF<wchar_t>>
]
c:\boost\boost\algorithm\string\find_iterator.hpp(261) : see reference to function template instantiation 'boost::algorithm::detail::find_iterator_base<IteratorT>::find_iterator_base<FinderT>(FinderT,int)' being compiled
with
[
IteratorT=input_iterator_type,
FinderT=boost::algorithm::detail::token_finderF<boost::algorithm::detail::is_any_ofF<wchar_t>>
]
c:\boost\boost\algorithm\string\iter_find.hpp(167) : see reference to function template instantiation 'boost::algorithm::split_iterator<IteratorT>::split_iterator<FinderT>(IteratorT,IteratorT,FinderT)' being compiled
with
[
IteratorT=input_iterator_type,
FinderT=boost::algorithm::detail::token_finderF<boost::algorithm::detail::is_any_ofF<wchar_t>>
]
c:\boost\boost\algorithm\string\split.hpp(149) : see reference to function template instantiation 'SequenceSequenceT &boost::algorithm::iter_split<SequenceSequenceT,RangeT,boost::algorithm::detail::token_finderF<PredicateT>>(SequenceSequenceT &,RangeT &,FinderT)' being compiled
with
[
SequenceSequenceT=std::vector<std::wstring>,
RangeT=std::wstring,
PredicateT=boost::algorithm::detail::is_any_ofF<wchar_t>,
FinderT=boost::algorithm::detail::token_finderF<boost::algorithm::detail::is_any_ofF<wchar_t>>
]
c:\documents and settings\user\my documents\visual studio 2008\projects\pevfind\pevfind\consoleparser.cpp(1529) : see reference to function template instantiation 'SequenceSequenceT &boost::algorithm::split<std::vector<_Ty>,std::wstring,boost::algorithm::detail::is_any_ofF<CharT>>(SequenceSequenceT &,RangeT &,PredicateT,boost::algorithm::token_compress_mode_type)' being compiled
with
[
SequenceSequenceT=std::vector<std::wstring>,
_Ty=std::wstring,
CharT=wchar_t,
RangeT=std::wstring,
PredicateT=boost::algorithm::detail::is_any_ofF<wchar_t>
]
c:\boost\boost\utility\addressof.hpp(30) : warning C4512: 'boost::detail::addr_impl_ref<T>' : assignment operator could not be generated
with
[
T=boost::algorithm::detail::token_finderF<boost::algorithm::detail::is_any_ofF<wchar_t>>
]
``` | Your compile failed because there's a new warning being emitted (`boost::detail::addr_impl_ref<T>' : assignment operator could not be generated`), and your settings are set to treat warnings as errors. Judging from [this](http://www.nabble.com/-utility--foreach--1.39.0--warning-C4512-td23446419.html) and [this](https://svn.boost.org/trac/boost/ticket/2993), it's indeed an issue with Boost 1.39.0 and VS2008.
The latter link provides a patch that fixes the issue. It should be fixed in Boost 1.40.0.
The alternative would be to disable the "treat warnings as errors" flag temporarily. | If I switch to warning level 4 and set treat warnings as errors mine breaks too.
Try changing those settings. | Upgrading from boost 1.38 to 1.39 causes my call to boost::algorithm::split not to compile | [
"",
"c++",
"boost",
""
] |
Forgive my naivety, but I am new to using Delphi with databases (which may seem odd to some).
I have setup a connection to my database (MSSQL) using a TADOConnection. I am using TADOStoredProc to access my stored procedure.
My stored procedure returns 2 columns, a column full of server names, and a 2nd column full of users on the server. It typically returns about 70 records...not a lot of data.
How do I enumerate this stored procedure programmatically? I am able to drop a DBGrid on my form and attach it to a TDataSource (which is then attached to my ADOStoredProc) and I can verify that the data is correctly being retrieved.
Ideally, I'd like to enumerate the returned data and move it into a TStringList.
Currently, I am using the following code to enumerate the ADOStoredProc, but it only returns '@RETURN\_VALUE':
```
ADOStoredProc1.Open;
ADOStoredProc1.ExecProc;
ADOStoredProc1.Parameters.Refresh;
for i := 0 to AdoStoredProc1.Parameters.Count - 1 do
begin
Memo1.Lines.Add(AdoStoredProc1.Parameters.Items[i].Name);
Memo1.Lines.Add(AdoStoredProc1.Parameters.Items[i].Value);
end;
``` | Call Open to get a dataset returned
```
StoredProc.Open;
while not StoredProc.EOF do
begin
Memo1.Lines.Add(StoredProc.FieldByName('xyz').Value);
StoredProc.Next;
end;
``` | Use Open to get the records from the StoredProc
Use either design-time Fields, ad-hoc Fields grabbed with FieldByName before the loop or Fields[nn] to get the values.
```
procedure GetADOResults(AStoredProc: TADOStoredProc; AStrings: TStrings);
var
fldServer, fldUser: TField;
begin
AStoredProc.Open;
fldServer := AStoredProc.FieldByName('ServerName');
fldUser := AStoredProc.FieldByName('User');
while not AStoredProc.EOF do
begin
AStrings.Add(Format('Server: %s - / User: %s',[fldServer.AsString, fldUser.AsString]));
// or with FFields and Index (asumming ServerName is the 1st and User the 2nd) and no local vars
AStrings.Add(Format('Server: %s - / User: %s',[AStoredProc.Fields[0].AsString, AStoredProc.Fields[1].AsString]));
AStoredProc.Next;
end;
end;
//use like
GetADOResults(ADOStoredProc1, Memo1.Lines);
```
Note: Fields[nn] allows to write less code but beware if the StoredProc changes the order of the returned columns. | How do I return all values from a stored procedure? | [
"",
"sql",
"delphi",
"stored-procedures",
""
] |
If i have a component derived from `ItemsControl`, can I access a collection of it's children so that I can loop through them to perform certain actions? I can't seem to find any easy way at the moment. | A solution similar to [Seb's](https://stackoverflow.com/a/1000438/3195477) but probably with better performance :
```
for(int i = 0; i < itemsControl.Items.Count; i++)
{
UIElement uiElement =
(UIElement)itemsControl.ItemContainerGenerator.ContainerFromIndex(i);
}
``` | See if this helps you out:
```
foreach(var item in itemsControl.Items)
{
UIElement uiElement =
(UIElement)itemsControl.ItemContainerGenerator.ContainerFromItem(item);
}
```
There is a difference between logical items in a control and an `UIElement`. | How do I access the children of an ItemsControl? | [
"",
"c#",
"wpf",
"itemscontrol",
""
] |
Now I want to transform a Array from object\_c to javascript, just like label1 , label2 , label3... in the array. I use this method :
```
WebScriptObject* win = [webview windowScriptObject];
NSMutableArray *nameArray; // in this have some file name : label1,label2...
[win callWebScriptMethod:@"transArray" withArguments:nameArray];
```
and then in the javascript I var a array and implement a func:
```
var labelArray= []; // maybe var labelArray = new Array (%@);but it didn't work
function transArray(param)
{
for(var i=0;i < param.length;i++)
labelArray[i] = param[i];
}
```
then I found that the labelArray isn't like I want. it just like : `labelArray[0] = l,labelArray[1] = a; labelArray[2] = b`..... .I thought maybe I could `var labelArray = new Array (%@)`.but it didn't work. I don't know the javascript clearly , and if I can transform a array from object\_c to javascript or not , how to do ? thanks!
---
Now I found the method that transformming the argu from object\_c to Javascript. But I didn't know how to get the array in the javascript , I thought maybe my method was wrong , but how to get the array and var the array,Thanks ! | ```
id win = [webView windowScriptObject];
NSArray *args = [NSArray arrayWithObjects:
@"sample_graphic.jpg",
[NSNumber numberWithInt:320],
[NSNumber numberWithInt:240],
nil];
[win callWebScriptMethod:@"addImage"
withArguments:args];
```
from [WebKit Objective-C Programming Guide](http://developer.apple.com/documentation/Cocoa/Conceptual/DisplayWebContent/Tasks/JavaScriptFromObjC.html) | You could take a peek at JSON encoding/decoding. This is by far the easiest way I know of to get data from and to javascript.
<http://www.json.org/> has a list of available classes at the bottom of the homepage. I'm pretty sure there is one that will suit your needs.
Hope this helps! | how to transform array argu from object_c to javascript? | [
"",
"javascript",
"cocoa",
""
] |
I want to check if a variable has a number in it, I just want to see if there is one I don't care if it has any thing else in it like so:
```
"abc" - false
"!./#()" - false
"!./#()abc" - false
"123" - true
"abc123" - true
"!./#()123" - true
"abc !./#() 123" -true
```
There are easy ways of doing this if you want to know that is all numbers but not if it just has one. Thanks for your help. | You can use the [`strcspn`](http://php.net/manual/en/function.strcspn.php) function:
```
if (strcspn($_REQUEST['q'], '0123456789') != strlen($_REQUEST['q']))
echo "true";
else
echo "false";
```
`strcspn` returns the length of the part that does not contain any integers. We compare that with the string length, and if they differ, then there must have been an integer.
There is no need to invoke the regular expression engine for this. | ```
$result = preg_match("/\\d/", $yourString) > 0;
``` | Check if variable has a number php | [
"",
"php",
"variables",
"numbers",
""
] |
Considering the class below
- can I do anything to implement a case-insensitive string?
```
public class Attibute
{
// The Name should be case-insensitive
public string Name
{
get;
set;
}
public Attibute()
{
}
}
public class ClassWithAttributes
{
private List<Attributes> _attributes;
public ClassWithAttributes(){}
public AddAttribute(Attribute attribute)
{
// Whats the best way to implement the check?
_attributes.add(attribute);
}
}
```
[Structure of an HTML 4 Document](http://htmlhelp.com/reference/html40/structure.html#elements)
I have edited the class to be a bit more objective and specific | In answer to the restructured question, you could do it like this:
```
public class Attribute { public string Name { get; set; } }
public class AttributeCollection : KeyedCollection<string, Attribute> {
public AttributeCollection() : base(StringComparer.OrdinalIgnoreCase) { }
protected override string GetKeyForItem(Attribute item) { return item.Name; }
}
public class ClassWithAttributes {
private AttributeCollection _attributes;
public void AddAttribute(Attribute attribute) {
_attributes.Add(attribute);
//KeyedCollection will throw an exception
//if there is already an attribute with
//the same (case insensitive) name.
}
}
```
If you use this, you should either make `Attribute.Name` read-only or call ChangeKeyForItem whenever it's changed. | You can't have case-insensitive properties—you can only have case-insensitive operations, like a comparison. If someone accesses XHtmlOneDTDElementAttibute.Name, they will get back a string with whatever case it was created with.
Whenever you use .Name, you can implement that method in a way that ignores the case of the string. | C# Case-Insensitive String | [
"",
"c#",
"string",
"case-insensitive",
""
] |
I need to check the `checked` property of a checkbox and perform an action based on the checked property using jQuery.
For example, if the `age` checkbox is checked, then I need to show a textbox to enter `age`, else hide the textbox.
But the following code returns `false` by default:
```
if ($('#isAgeSelected').attr('checked')) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">
Age is selected
</div>
```
How do I successfully query the `checked` property? | This worked for me:
```
$get("isAgeSelected ").checked == true
```
Where `isAgeSelected` is the id of the control.
Also, @karim79's [answer](https://stackoverflow.com/questions/901712/check-checkbox-checked-property-using-jquery/901727#901727) works fine. I am not sure what I missed at the time I tested it.
**Note, this is answer uses Microsoft Ajax, not jQuery** | > How do I successfully query the checked property?
The `checked` property of a checkbox DOM element will give you the `checked` state of the element.
Given your existing code, you could therefore do this:
```
if(document.getElementById('isAgeSelected').checked) {
$("#txtAge").show();
} else {
$("#txtAge").hide();
}
```
However, there's a much prettier way to do this, using [`toggle`](http://api.jquery.com/toggle/):
```
$('#isAgeSelected').click(function() {
$("#txtAge").toggle(this.checked);
});
```
```
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>
``` | How do I check whether a checkbox is checked in jQuery? | [
"",
"javascript",
"jquery",
"html",
"checkbox",
""
] |
```
class A
{
public:
A(const int n_);
A(const A& that_);
A& operator=(const A& that_);
};
A::A(const int n_)
{ cout << "A::A(int), n_=" << n_ << endl; }
A::A(const A& that_) // This is line 21
{ cout << "A::A(const A&)" << endl; }
A& A::operator=(const A& that_)
{ cout << "A::operator=(const A&)" << endl; }
int foo(const A& a_)
{ return 20; }
int main()
{
A a(foo(A(10))); // This is line 38
return 0;
}
```
Executing this code gives o/p:
> A::A(int), n\_=10
> A::A(int), n\_=20
Apparently the copy constructor is never called.
```
class A
{
public:
A(const int n_);
A& operator=(const A& that_);
private:
A(const A& that_);
};
```
However, if we make it private, this compile error occurs:
> Test.cpp: In function ‘int main()’:
> Test.cpp:21: error: ‘A::A(const A&)’ is private
> Test.cpp:38: error: within this context
Why does the compiler complain when it doesn't actually use the copy constructor?
I am using gcc version 4.1.2 20070925 (Red Hat 4.1.2-33) | [Core defect 391](http://www.comeaucomputing.com/iso/cwg_defects.html#391) explains the issue.
Basically, the current C++ standard requires a copy constructor to be available when passing a temporary of class type to a const reference.
This requirement will be removed in C++0x.
The logic behind requiring a copy constructor comes from this case:
```
C f();
const C& r = f(); // a copy is generated for r to refer to
``` | The 2003 standard, in §12.2/1, states:
> Even when the creation of the
> temporary object is avoided (12.8),
> all the semantic restrictions must be
> respected as if the temporary object
> was created. [Example: even if the
> copy constructor is not called, all
> the semantic restrictions, such as
> accessibility (clause 11), shall be
> satisfied. ]
There are similar examples around. From what I gather, the compiler is free to generate temporaries or optimize them away. | Why is the copy ctor used in this code? | [
"",
"c++",
"copy-constructor",
""
] |
C# 2008 SP1
I am wondering what is the best way to handle revision numbers.
I had always thought there is normally only 3 numbers. (Major, Minor, and Bug fixes).
However, I am left wondering what the build number is and the Revision number.
For example, in the past I have normally used only 3 numbers. I there is some very minor change or a bug fix I would increment the 3rd number (bug fixes).
Because I am new to this. What is normally done in the professional world?
Many thanks for any advice,
In my AssemblyInfo file I have the following:
```
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.2.*")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// 1.0.2 Added feature for detecting if a sound card is installed.
``` | Thanks for all your suggestions.
I have decided to use the following.
My project has the following version number: 1.0.2.20.
1. :Major changes
0. :Minor changes
2. :Bug fixes
20 :Subversion revision number
So I have changed the following in my assemblyinfo.c file
```
[assembly: AssemblyVersion("1.0.2.20")]
```
Any suggestions on this idea, I would be happy to hear.
Many thanks, | From [MSDN](http://msdn.microsoft.com/en-us/library/system.version.aspx):
> * Build : A difference in build number represents a recompilation of
> the same source. This would be
> appropriate because of processor,
> platform, or compiler changes.
> * Revision : Assemblies with the same name, major, and minor version numbers
> but different revisions are intended
> to be fully interchangeable. This
> would be appropriate to fix a security
> hole in a previously released
> assembly.
Phil Haack has a [nice deconstruction](http://haacked.com/archive/2006/09/27/Which_Version_of_Version.aspx) of the .NET versioning system, but in practice I don't think his concerns really matter since in my experience the .NET/MS versioning system is only really used by technical for debugging/support/tracking purposes, the public and project management will often be date or made-up-marketing-version-number based.
FWIW every .NET project I've worked on ha been governed by "X.Y.\*" i.e. we like to manually control what the major and minors are but let the system control the build and revision. | C# Effective way to manage revision number | [
"",
"c#",
""
] |
Is there a way to determine whether or not a CSS class exists using JavaScript? | This should be possible to do using the `document.styleSheets[].rules[].selectorText` and `document.styleSheets[].imports[].rules[].selectorText` properties. Refer to [MDN documentation](https://developer.mozilla.org/en-US/docs/Web/API/document.styleSheets). | ```
function getAllSelectors() {
var ret = [];
for(var i = 0; i < document.styleSheets.length; i++) {
var rules = document.styleSheets[i].rules || document.styleSheets[i].cssRules;
for(var x in rules) {
if(typeof rules[x].selectorText == 'string') ret.push(rules[x].selectorText);
}
}
return ret;
}
function selectorExists(selector) {
var selectors = getAllSelectors();
for(var i = 0; i < selectors.length; i++) {
if(selectors[i] == selector) return true;
}
return false;
}
``` | Determine if a CSS class exists with Javascript | [
"",
"javascript",
"typescript",
""
] |
Before starting, I ask you all to apologize for the question. Maybe it is stupid, but I cannot find a solution.
I am working on a remote machine, and have no idea what type.
My python code, that seems to work, is the one below. The problem is that I am trying to print some outputs on the screen but nothing happens.
I have tried both print and raw\_input but nothing happens ... Do you know any other way to do it ?
```
# Set up fields of reply message based on query
def prepareReply():
global authorReply, authorReplyLen, localConvId, originConvId, blbContentAndUntUnz, linkName
print "PLOP!"
raw_input("blabla")
#print "="*10
```
Thanks ! | To redirect stdout to something that you can read, a file in this case:
```
class PyLogger:
def __init__(self, source):
self.file_handle = open('Python_Log.txt', 'a')
self.source=source
self.buf = []
def write(self, data):
self.buf.append(data)
if data.endswith('\n'):
self.file_handle = open('Python_Log.txt', 'a')
self.file_handle.write('\t' * indent_level)
self.file_handle.write(self.source + "::" + ''.join(self.buf))
self.file_handle.close()
self.buf = []
def __del__(self):
if self.buf != []:
self.file_handle = open('Python_Log.txt', 'a')
self.file_handle.write('\t' * indent_level)
self.file_handle.write(self.source + "::" + ''.join(self.buf) + '\n')
self.file_handle.close()
self.file_handle.close()
import sys
sys.stdout = PyLogger('stdout')
sys.stderr = PyLogger('stderr')
``` | ```
import sys
print "Hi!"
sys.stdout.flush()
``` | Python - Print on stdout on a "terminal" | [
"",
"python",
"stdout",
""
] |
I'm creating a webform that has combos containing 100 values or so. The values are the same.
The form may have several records. So if there are 100 records there are 10,000 lines which seems pretty wrong from a "download" point of view.
The thing is: I want to keep that combo dynamic to keep the id from the database.
So I came up to the following:
```
.....
<script>
stupidCombo = "<option>a"+
"<option>b"+
...
"<option>99zzz"+
"</select>";
</script>
..... form here
.... for each item in huge list do paint <table><tr> etc. etc
<td>
<select name="comb-<%=id%>">
<option selected><%=obj.val%>
<script>document.write(stupidCombo);</script>
</td>
... close form, table, html etc.
```
I have rendered it and "look" fine. The page has decreased from 50k lines to 5k and the select is created by the javascript on the client side.
My question is.....
Is this ok?
Is there any risk involved?
I borrow this Idea after understanding who most of the javascript frameworks work, but most of them work on a **<div>** element rather that just to the document it self.
I'm targeting IE6 and this is a quick fix that has to be on production tomorrow morning ( so I don't want to spend too much time on this ) but I don't want to have 50,000 lines written for each request if I can help it.
Thanks | HTML produced by document.write works in same way as normal one, so there is no any technical problems with your solution. ( of course, such solution works only if javascript enabled )
By the way, for the lists with big count of options, you can look at ["suggest box" component](http://plugins.jquery.com/project/suggest), which can replace native selectbox. | HTTP compression (mod\_gzip, etc.) will compress all that nicely.
If you insist on `document.write`, you will have to use JavaScript to write `<select>` element as well, because in HTML you're not allowed to put `<script>` inside `<select>`.
Another approach is to send one copy of the control to the browser and then duplicate it with help of `selectElement.cloneNode(true)`. | Using document.write for fixed html | [
"",
"javascript",
"dom",
"dynamic-data",
""
] |
I have written a chart that displays financial data. Performance was good while I was drawing less than 10.000 points displayed as a connected line using `PathGeometry` together with `PathFigure` and `LineSegment`s. But now I need to display up to 100.000 points at the same time (without scrolling) and it's already very slow with 50.000 points. I was thinking of `StreamGeometry`, but I am not sure since it's basically the same as a `PathGeometry` stroring the information as byte stream. Does any one have an idea to make this much more performant or maybe someone has even done something similar already?
EDIT: These data points do not change once drawn so if there is potential optimizing it, please let me know (line segments are frozen right now).
EDIT: I tried StreamGeometry. Creating the graphic took even longer for some reason, but this is not the issue. Drawing on the chart after drawing all the points is still as slow as the previous method. I think it's just too many data points for WPF to deal with.
EDIT: I've experimented a bit and I noticed that performance improved a bit by converting the coordinates which were previously in double to int to prevent WPF anti-aliasing sub-pixel lines.
EDIT: Thanks for all the responses suggesting to reduce the number of line segments. I have reduced them to at most twice the horizontal resolution for stepped lines and at most the horizontal resolution for simple lines and the performance is pretty good now. | I'd consider downsampling the number of points you are trying to render. You may have 50,000 points of data but you're unlikely to be able to fit them all on the screen; even if you charted every single point in one display you'd need [100,000](http://en.wikipedia.org/wiki/Nyquist_frequency) pixels of horizontal resolution to draw them all! Even in D3D that's a lot to draw.
Since you are more likely to have something like 2,048 pixels, you may as well reduce the points you are graphing and draw an approximate curve that fits onto the screen and has only a couple thousand verts. If for example the user graphs a time frame including 10000 points, then downsample those 10000 points to 1000 before graphing. There are numerous techniques you could try, from simple averaging to median-neighbor to Gaussian convolution to (my suggestion) [bicubic interpolation](http://en.wikipedia.org/wiki/Bicubic_interpolation). [Drawing any number of points greater than 1/2 the screen resolution will simply be a waste](http://en.wikipedia.org/wiki/Nyquist_frequency).
As the user zooms in on a part of a graph, you can resample to get higher resolutions and more accurate curve fitting. | When you start dealing with hundreds of thousands of distinct vertices and vectors in your geometry, you should probably consider migrating your graphics code to use a graphics framework instead of depending on WPF (which, while built on top of Direct3D and therefore capable of remarkably efficient vector graphics rendering, has a lot of extra overhead going on that hampers its efficiency). It's possible to host both Direct3D and OpenGL graphics rendering windows within WPF -- I'd suggest moving that direction instead of continuing to work solely within WPF.
(EDIT: changed "DirectX" in original answer to "Direct3D") | Most performant way to graph thousands of data points with WPF? | [
"",
"c#",
".net",
"wpf",
"performance",
"2d",
""
] |
I need to create a page that will load divs from an external page using Jquery and AJAX.
I have come across a few good tutorials, but they are all based on static content, my links and content are generated by PHP.
The main tutorial I am basing my code on is from:
[http://yensdesign.com/2008/12/how-to-load-content-via-ajax-in-jquery/](http://yensdesign.com/2008/12/how-to-load-content-via-ajax-in-jquery/ "http://yensdesign.com/2008/12/how-to-load-content-via-ajax-in-jquery/")
The exact function i need is as follows:
1. Main page contains a permanent div listing some links containing a parameter.
2. Upon click, link passes parameter to external page.
3. External page filters recordset against parameter and populates div with results.
4. The new div contains a new set of links with new parameters.
5. The external div is loaded underneath the main pages first div.
6. Process can then be repeated creating a chain of divs under each other.
7. The last div in the chain will then direct to a new page collating all the previously used querystrings.
I can handle all of the PHP work with populating the divs on the main and external pages.
It's the JQuery and AJAX part i'm struggling with.
```
$(document).ready(function(){
var sections = $('a[id^=link_]'); // Link that passes parameter to external page
var content = $('div[id^=content_]'); // Where external div is loaded to
sections.click(function(){
//load selected section
switch(this.id){
case "div01":
content.load("external.php?param=1 #section_div01");
break;
case "div02":
content.load("external.php?param=2 #section_div02");
break;
}
});
```
The problem I am having is getting JQuery to pass the dynamically generated parameters to the external page and then retrieve the new div.
I can currently only do this with static links (As above). | I'm not sure if you've solved this already, but I'm surprised no one's mentioned to use the ajax() function.
This would allow you to define the request type as GET:
```
function loadContent(id) {
$.ajax({
type: "GET",
url: "external.php",
dataType: 'html',
data: {param: id},
success: function(html){
$("#container").html(html);
},
error: function(){
},
complete: function(){
}
});
}
```
Just call this function instead of using load. Obviously you'll have to tinker with the code (mainly what goes in the success function) a little, but this should give you a good starting point. | You can use the optional data argument to pass parameters to the GET request. Read the [documentation](http://docs.jquery.com/Ajax/load#urldatacallback). This is far better than building the URL yourself. You can of course add dynamic generated data to the parameters list. | JQuery/AJAX: Loading external DIVs using dynamic content | [
"",
"php",
"jquery",
"ajax",
""
] |
Whenever I add a new class to a Visual Studio (C#) project, I get the following usings automatically:
* using System;
* using System.Collections.Generic;
* using System.Linq;
* using System.Text;
Additionally, the following DLL references are added if they weren't there already:
* System.Core
* System.Data
* System.Xml
I'd like to prevent VS from doing this (except "using System" of course). Does any one know of a way to prevent this from happening? | Marc and Brian both have a good idea: create a new custom template that includes only the usings and references I want. With Export Template it's really simple to do so, and I'll be sure to do so for all sorts of specific items.
For general-purpose new classes (ie: what you get from the "Add->Class..." menu item in VS), here's what I did to achieve my goal:
* Find the appropriate template Zip. On my system it was located at C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplates\CSharp\Code\1033\Class.zip
* Extract the zip file. This gives two files: Class.cs and Class.vstemplate
* Edit Class.cs to remove the undesired using statements. (I also changed the default class access modifier to "public" while I was here)
* Edit Class.vstemplate to remove the undesired `<reference>` elements.
* Rezip the files into the existing Class.zip archive
* Replace the cached template files with the updated versions. On my system, the files were located at C:\Program Files\Microsoft Visual Studio 9.0\Common7\IDE\ItemTemplatesCache\CSharp\Code\1033\Class.zip (a directory containing the old Class.cs and Class.vstemplate).
+ I tried simply deleting this directory, expecting VS to rebuild the cache from the "original" source. This didn't work though; I got an error message saying that it couldn't find the files in the cache directory. Replacing the cached files worked well though.
* Restart Visual Studio
Now, whenever I add a new class, I get exactly what I want. | You can change your template files... either by editing the files in the install location, or by writing a class how *you* want it, and choosing [Export Template](http://msdn.microsoft.com/en-us/library/ms185318(VS.80).aspx). There is also a template add-in somewhere... | Prevent Visual Studio from adding default references and usings for new classes | [
"",
"c#",
".net",
"visual-studio",
"visual-studio-2008",
"default",
""
] |
Consider the following code:
```
typedef vector<int> intVec;
intVec& operator<<(intVec& dst, const int i) {
dst.push_back(i);
return dst;
}
int intResult0() {
return 23;
}
int intResult1() {
return 42;
}
// main
intVec v;
v << intResult0() << intResult1();
```
The weird thing is, that the compiler generates code, which evaluates `intResult1` **BEFORE** `intResult0` (tested with newest VC und gcc).
Why would the compiler do this? By doing so, the time between evaluation and usage of the respective values is (unnecessarily) increased(?), i.e. 42 is fetched first, but pushed last to the vector.
Does the C++ standard dictate this? | According to Stroustrup section 6.2.2:
> The order of evaluation of
> subexpressions within an expression is
> undefined. | The order of evaluation of sub-expressions between two sequence point is undefined.
The above code is syntactic sugar for:
```
v.operator<<(intResult0()).operator<<(intResult1());
```
The only constraint the compiler has, is that it must evaluate all parameters before a method is called and obey the precedence rules. But as long as it follows these rules each implementation is allowed to choose the details and as such this order may change between compilers.
In this example:
* So it is perfectly legal to call intResult1() before intResult2().
* But intResult0() must be called before the call to operator<<() (left)
* and intResult1() must be called before the call to operator<<() (right)
* and operator<<() (left) must be called before operator<<() (right)
See here for more info:
[What are all the common undefined behaviours that a C++ programmer should know about?](https://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviour-that-c-programmer-should-know-about/367663#367663)
and
[What are all the common undefined behaviours that a C++ programmer should know about?](https://stackoverflow.com/questions/367633/what-are-all-the-common-undefined-behaviour-that-c-programmer-should-know-about/367690#367690) | C++ shift operator precedence weirdness | [
"",
"c++",
"operator-overloading",
""
] |
I'm trying to accomplish the following in C#/.NET 2.0:
Given an IPAddress object (say, 192.168.127.100) and another IPAddress object containing the IPv4Mask / subnet mask (say, 255.255.248.0), I should be able calculate the start and end of the IP Address range.
(Yes, I'm trying to do a for-loop thru a range of addresses on a subnet.)
Theoretically, I should be able to bitwise AND on the IPAddress and the SubnetMask to get the IPStart. Then I should be able to perform a bitwise XOR on the IPStart and the inverted (NOT'd) SubnetMask, to get the IPEnd.
The IPAddress object provides methods to output the address as a "long" or as "byte[]" (array of bytes).
Performing the bitwise operation on the long (because it is signed?) produces invalid results. And I can't seem to perform bitwise operation on the IPAddresses as an array of bytes.
EDIT-1: Okay, looping thru each byte in the array and performing bitwise AND, NOT, and XOR (in each respective situation) gets the right results.
The next problem I am running into is that I cannot perform the for-loop easily after converting the byte[] arrays into UInt32 or long. So, the first value works properly, but incrementing the uint/long by one makes the IPaddress increase from 192.168.127.0 to 193.168.127.0 -- It seems that after the byte[] array is transformed to uint/long, the order of the bytes gets reversed. So there is no easy way to increment from IPStart to IPEnd.
Any have any suggestions? | Crawl through the two byte[] arrays together, for each byte pair perform the bitwise comparison and place the result into a third byte[] array for the range start. You can crawl through the network address byte[] array and invert each bit to generate the wildcard mask (as you called it, inverted subnetmask), and then repeat the process as before using the wildcard mask in place of the subnet mask to calculate the range end. Remember also that the first value in the range is the subnet network address and the last value is the broadcast address, so those two addresses are not in the actual host address range. Here is your example in a step-by-step summary:
```
Address: 192.168.127.100 11000000.10101000.01111 111.01100100
Netmask: 255.255.248.0 = 21 11111111.11111111.11111 000.00000000
Wildcard: 0.0.7.255 00000000.00000000.00000 111.11111111
=>
Network: 192.168.120.0/21 11000000.10101000.01111 000.00000000
Broadcast: 192.168.127.255 11000000.10101000.01111 111.11111111
HostMin: 192.168.120.1 11000000.10101000.01111 000.00000001
HostMax: 192.168.127.254 11000000.10101000.01111 111.11111110
``` | You can use [BitConverter](http://msdn.microsoft.com/en-us/library/system.bitconverter.aspx) to turn those arrays into uints.
Try this:
```
uint address = BitConverter.ToUInt32(IPAddress.Parse("192.168.127.100").GetAddressBytes(), 0);
uint mask = BitConverter.ToUInt32(IPAddress.Parse("255.255.248.0").GetAddressBytes(), 0);
``` | How to use IPAddress and IPv4Mask to obtain IP address range? | [
"",
"c#",
"ip-address",
"range",
""
] |
I have a stored proc were I want to insert a GUID (user id) into a table in MS SQL but I keep getting an error about the hyphen '-' that is part of the guid value, here's my proc defined below;
```
@userID uniqueidentifier,
@bookID int,
@dateReserved datetime,
@status bit
INSERT INTO Reservation(BookId, DateReserved, [Status], UserId)
VALUES (@bookID, @dateReserved, @status, @userID)
```
But when I put single quotes around the value if the stored proc is executed in Management Studio, it runs fine. How can I handle the guid insertion without problems from my stored proc?
Thanks guys.
**Update**
Here's the sql exec
```
DECLARE @return_value int
EXEC @return_value = [dbo].[usp_ReserveBook]
@userID = AE019609-99E0-4EF5-85BB-AD90DC302E70,
@bookID = 7,
@dateReserved = N'09/03/2009',
@status = 1
SELECT 'Return Value' = @return_value
```
Here's the error message
```
Msg 102, Level 15, State 1, Line 5
Incorrect syntax near '-'.
``` | Just cast it from a varchar.
```
DECLARE @return_value int
EXEC @return_value = [dbo].[usp_ReserveBook]
@userID = CONVERT(uniqueidentifier, 'AE019609-99E0-4EF5-85BB-AD90DC302E70'),
@bookID = 7,
@dateReserved = N'09/03/2009',
@status = 1
SELECT 'Return Value' = @return_value
``` | You simply need to **QUOTE** your GUID:
```
DECLARE @return_value int
EXEC @return_value = [dbo].[usp_ReserveBook]
@userID = 'AE019609-99E0-4EF5-85BB-AD90DC302E70',
@bookID = 7,
@dateReserved = N'09/03/2009',
@status = 1
SELECT 'Return Value' = @return_value
```
Marc | Inserting GUID into SQL Server | [
"",
"sql",
"insert",
"guid",
""
] |
In
```
SELECT a.NAME, a.NUMBER, a.STRING, a.RDB$DB_KEY FROM ADMIN a
```
what does a stand for?
Thanks. | a is an alias for the table **ADMIN**
[SQL Alias](http://www.w3schools.com/SQL/sql_alias.asp) | The underlying concept is that of a ‘range variable’.
Chris Date and Hugh Darwen consider both the colloquial term ‘alias’ and the SQL Standard’s term ‘correlation name’ to be “inappropriate” and “seriously [misrepresenting] the true state of affairs”.
[Hugh Darwen, “SQL: A Comparative Survey”](http://bookboon.com/en/sql-a-comparative-survey-ebook):
> You may have
> learned a different term for range variable, which was used by Codd in
> his early papers but not adopted by the SQL standard until 2003. In
> some SQL texts it is called alias but this is not at all appropriate,
> really, because that would imply that it is a table name and therefore
> denotes a table rather than a row. The SQL standard uses the equally
> inappropriate term correlation name (it doesn’t denote a correlation,
> whatever that might be), but only for the case where the name is
> explicitly given (via `AS` in the example) and not for the case where
> a simple table name doubles as a range variable name. In SQL:2003
> range variable was adopted as a convenient single term to cover the
> more general case.
[C. J. Date, “SQL and Relational Theory: How to Write Accurate SQL Code”](http://books.google.co.uk/books?id=WuZGD5tBfMwC&pg=PA275&dq=%22Many+SQL+text+refer+to+range+variables%22&hl=en&sa=X&ei=IBzAUcyACuOH0AX6ooG4DA&ved=0CDsQ6AEwAQ#v=onepage&q=%22Many%20SQL%20text%20refer%20to%20range%20variables%22&f=false):
> a range variable in the relational model is a variable that "ranges
> over" the set of rows in some table (or the set of tuples in some
> relation, to be more precise). In SQL, such variables are defined by
> means of `AS` specifications in the context of either `FROM` or
> `JOIN`, as in the following example:
>
> ```
> SELECT SX.SNO
> FROM S AS SX
> WHERE SX.STATUS > 15
> ```
>
> `SX` here is a range variable that ranges over table `S`; in other
> words, its permitted values are rows of table `S`. You can think of
> the `SELECT` expression overall as being evaluated as follows. First,
> the range variable takes on one of its permitted values, say the row
> for supplier `SNO = ‘S1’`. Is the status value in that row greater
> than 15? If it is, then supplier number `’S1’` appears in the result.
> Next, the range variable moves on to another row of table `S`, say the
> row for supplier `SNO = ‘S2’`; again, if the status value in that row
> is greater than 15, then the relevant supplier number appears in the
> result. And so on
>
> SQL requires `SELECT` expressions always to be
> formulated in terms of range variables; if no such variables are
> specified explicitly, it assumes the existence of implicit ones with
> the same names as the corresponding tables
>
> Caveat: Many SQL texts
> refer to range variable names (or correlation names) as *aliases*, and
> describe them as if they were just alternative names for the tables
> they range over. But such a characterization seriously misrepresents
> the true state of affairs—indeed, it betrays a serious lack of
> understanding of what's really going on—and is strongly deprecated on
> that account.
---
Interestingly, LINQ correctly recognizes range variables e.g.
 | In SQL, what is the letter after a table name in a select statement? | [
"",
"sql",
""
] |
I'm not sure what the technical term for this is, but consider an interface:
```
public interface SomeInterface<T> {
public T doSomething();
}
```
And then a second interface:
```
public interface SomeRelatedInterface<T, D extends SomeInterface<T>> {
public T doSomethingRelated(D relative);
}
```
Is it possible to craft the second interface to only require one generic parameter, and then have the doSomethingRelated method implicitly extract the return type in its declaration. This is not legal, but this is what I am wondering if can be done in some other means:
```
public interface <T> SomeRelatedInterface<D extends SomeInterface<T>> {
public T doSomethingRelated(D relative);
}
```
EDIT (On posting the bounty): At this point what I am looking for on this question is the reason that the language requires this duplication. That is what has been missing from the answers until now to get one accepted. | ```
public interface SomeRelatedInterface<T> {
T doSomethingRelated(SomeInterface<T> relative);
}
``` | > *"At this point what I am looking for on this question is the reason that the language requires this duplication"*
Well, the language requires that you define 2 type parameters in your example because there are, um, 2 type parameters in the problem you describe: you wish a method to be variable in both the type `T` *and also* in the implementation of `SomeInterface`.
These are **orthogonal considerations** and hence you need more than one type parameter to represent them.
Type parameters do not of course need to be defined on a class/interface; they can be defined on a method. *J-16 SDiZ*'s answer allows your related class/interface to have one type parameter only. The second type parameter is then declared only where it is needed, on the `doSomethingRelated` method | Is it possible to reference a nested generic parameter in java? | [
"",
"java",
"generics",
""
] |
Currently, I'm spawning a message box with a OS-library function (Windows.h), which *magically* keeps my program alive and responding to calls to the callback function.
What alternative approach could be used to silently let the program run forever?
Trapping 'Ctrl-c' or SIGINT and subsequently calling RemoveHook() for a clean exit would be nice to have but is not essential.
```
HOOK my_hook;
CALLBACK my_callback_fn()
{
...
}
int main()
{
my_hook = SetHook(my_callback_fn);
MessageBox("Press OK to stop."); // This is bad.
RemoveHook(my_hook);
return 0;
}
``` | You probably want to [pump messages](http://msdn.microsoft.com/en-us/library/ms644936(VS.85).aspx). A typical message loop looks like something like this:
```
BOOl ret;
MSG msg;
while ((ret=::GetMessage(&msg, hWnd, 0, 0))!=0)
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
```
You don't seem to have an actual window to pump on, and you don't say what `SetHook` is actually doing - maybe that will be able to provide one for you?
Another method is to use the `MsgWait` [functions](http://msdn.microsoft.com/en-us/library/ms684242(VS.85).aspx). Maybe you have some kind of handle that you are waiting to become signalled so you can exit?:
```
while (::MsgWaitForMultipleObjects(1, &handle, FALSE, INFINITE, QS_ALLEVENTS)==WAIT_OBJECT_0+1+
{
BOOl ret;
MSG msg;
while ((ret=::PeekMessage(&msg, hWnd, 0, 0, TRUE))!=0)
{
::TranslateMessage(&msg);
::DispatchMessage(&msg);
}
}
``` | A simple solution is to call Sleep() in a loop
```
int main() {
// your stuff
while(1) {
Sleep( 10000 );
}
return 0;
}
```
but note that if you want to do the remove hook stuff, you will need to do Ctrl-C trapping.. | My C Program provides a callback function for a hook. How can I keep it alive, un-kludgily? | [
"",
"c++",
"c",
"windows",
"hook",
"callback",
""
] |
I have this table on MySQL. I want to query the `port` number for `user_id`s 1 and 2.
```
umeta_id user_id meta_key meta_value
------------------------------------------
1 1 nickname admin
8 1 userDir D
9 1 port 8080
10 1 paymentopt bankin
13 2 port 8081
20 2 a_renew 1240098300
21 2 userDir D
22 2 paymentopt paypal
```
How do I do it in PHP?
Thank you! | A very simple bit of example code should work based on example from <http://uk.php.net/manual/en/mysqli-result.fetch-row.php>
```
<?php
$mysqli = new mysqli("localhost", "my_user", "my_password", "world");
/* check connection */
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$query = "SELECT `umeta_id`, `user_id`, `meta_key`, `meta_value` FROM TableName WHERE (`user_id` = 1 OR `user_id` = 2) AND (`meta_key` = 'port')"; //You will need to change TableName to whatever your table is called.
if ($result = $mysqli->query($query)) {
/* fetch object array */
while ($row = $result->fetch_row()) {
echo $row[3];
}
/* free result set */
$result->close();
}
/* close connection */
$mysqli->close();
?>
``` | ```
SELECT * FROM table
WHERE user_id = 1
AND meta_key = 'port'
```
Do the same for `user_id = 2` or if you want to retrieve the ports of both users simultaneously do this in one query:
```
SELECT * FROM table
WHERE (user_id = 1 OR user_id = 2)
AND meta_key = 'port'
```
This answer reflects just the SQL-part - I assume that you know how to send queries to a MySQL server using the desired MySQL library (`ext/mysql`, `ext/mysqli` or `ext/PDO`). | MySQL: Get a certain row | [
"",
"php",
"mysql",
"wordpress",
""
] |
does anyone know how to prevent hibernate from loading a collection or many-to-one assocation?
i have a use case where i need to load an object, but the calling program can determine whether certain properties are loaded or not. the same goes for part of a collections: certain rows have to be fetched, others not.
domain classes:
```
public class SomeClass {
private SomeClass parent;
private Set<OtherClass> collection;
}
public class OtherClass {
private Date startDate;
private Date endDate;
}
public class Dao {
public SomeClass loadClass(long id, boolean parents, boolean historicalData) {
// load SomeClass
// if parents == true, load parent, otherwise leave <null>
// if historicalData == false, load OtherClass where endDate == <null>
}
}
```
I have thought of 2 solutions, but I ont to now if its possible with an criteria or query.
Solution 1 is don't make the assocation from SomeClass to OtherClass and the parent/child relation in the hibernate configuration and load the assocation in the code.
Solution 2 is to define different mappings with different entity-names with serve the special cases.
In this case the caller can be in an other JVM or transaction, so the session is closed, thus lazy loading is not an real option. | Write an Criteria query and use the setFetchMode method to change the fetching behavior for the parent and createCriteria method to additionally query the collection.
```
Criteria c = session.createCriteria(SomeClass.class).add(Restrictions.idEq(id));
if (parents) {
c.setFetchMode("parents", FetchMode.EAGER);
}
if (historicalData) {
c.createCriteria("collection", Criteria.LEFT_JOIN)
.add(Restriction.lt("date", date))
.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);
}
return c.uniqueResult();
```
...this is assuming the default setting is LAZY (as per Hibernate default).
It is no option in Hibernate to leave properties **null** that do have a value (in this case a many-to-one association. The field will hold a proxy that can be used to lazily load the referred object. If the code never touches the object, it will not get loaded.
The same is true for the collection: if not fetched, it will hold a collection-proxy (a hibernate class that implements a collection interface), which will only load the contents when invoked. | You should leverage Hibernate's lazy loading features for this.
You can annotate a collection like:
```
@OneToMany(fetch=FetchType.LAZY)
```
In that case Hibernate only loads the collection if you actually access it in code. | disable property/collection loading with hibernate | [
"",
"java",
"hibernate",
""
] |
Occasionally I'll write a PHP function with a single input, an associative array containing all of that function's inputs. This has benefits such as not having to remember the correct order of inputs, but I've also noticed it makes implementing changes to large codebases much easier; when I need to add another variable, and that variable has to pass through 4 or 5 pre-existing functions, it's much easier when I can just stick it in the array and pass it along.
My question is, is there a downside to doing this?
I rarely see functions written this way in examples, or in open source I use, which leads me to believe there is probably a downside. If there *isn't* a reason not to do it then why not write all functions this way?
**UPDATE**
Thanks for all your answers. It looks like two major problems stand out:
**Code readability** - impossible to tell what variables are going into a function and what they're for
**Variable creep** - Could wind up with massive arrays bouncing from one function to the next; one should not pass parameters to functions that don't require them
Which are both great points I did not think about.
It seems the general gist as well is that code where this is an issue, should probably be converted to a class. Unfortunately in this specific project such a refactoring is beyond the scope, but I also think Bill Karwin's solution is good - pass an array of optional variables | > why not write all functions this way?
For that matter, why not forget about parameters completely, and use global variables for everything? (kidding)
Passing an associative array has one useful advantage: you can make multiple function parameters optional, and you can pass a value for the *N*th parameter without having to pass a value for the \*N-1\*th parameter.
But you have no way to make mandatory parameters with a compile-time error if you don't pass them. Neither can you declare type-checking.
You'll have to write code inside the called function to check for the presence and the type of required parameters.
An alternative I have used is to declare conventional parameters for those that are mandatory, and then as the last (optional) argument, declare an associative array called `$options` that contains only the optional items.
```
function database_connect($dbname, $user, $password, array $options = array())
``` | The downside is that anyone looking at your code (other than you) would have no idea what parameters are coming into a method, where they came from, or what they are for. They would also have no idea how to call a method since it isn't clear without looking at the code exactly what is required inside that "parameter array". | Using an associative array as php function's input | [
"",
"php",
"arrays",
"object",
"function",
""
] |
This is a newbie theory question - I'm just starting to use Python and looking into Django and orm. Question: If I develop my objects and through additional development modify the base object structures, inheritance, etc. - would Django's ORM solution modify the database automatically OR do I need to perform a conversion (if the app is live)?
So, I start with a basic Phone app
Object person: name, address, city, state, zip, phone
and I change to
Object person: title, name, address, city, state, zip, phone object
Object phone: type, phone #
Do I manually convert via the db and change the code OR does the ORM middleware make the change? and if so - how? | The Django book covers this issue in [Chapter 5](http://www.djangobook.com/en/1.0/chapter05/), near the end of the chapter (or bottom of the page, in the web edition). Basically, the rules are:
* When *adding* a field, first add it to the database manually (using, e.g., `ALTER TABLE`) and then add the field to the model. (You can use `manage.py sqlall` to see what SQL statement to execute.)
* When removing a field, remove it from your model and then execute the appropriate SQL statement to remove the column (e.g., an `ALTER TABLE` command), and any join tables that were created.
* Renaming a field is basically a combination of adding/removing fields, as well as copying data.
So to answer your question, in Django's case, no, the ORM will *not* handle modifications for you -- but they're not that hard to do. See that chapter of the book (linked above) for more info. | As of Django 1.02 (and as of the latest run-up to 1.1 in subversion), there is no automatic "schema migration". Your choices are to drop the schema and have Django recreate it (via manage.py syncdb), or alter the schema by hand yourself.
There are some tools on the horizon for Django schema migration. (I'm watching [South](http://south.aeracode.org/).) | python orm | [
"",
"python",
"database",
"django",
"django-models",
""
] |
What would be the correct regex to check wether a checkbox is checked in javascript?
update: i know it is usually not done with a regex. But since its part of a form module and all the validations are done with a regex. I thought this could also be checked with a regex. My quyestion is how. | You really just want to access the `checked` property. (Truly, regex has no place here - it should be used only with lack of anything better.)
Try this:
```
var checkbox = document.getElementById("myCheckbox");
if (checkbox.checked)
{
alert("Checkbox is CHECKED.");
}
else
{
alert("Checkbox is UNCHECKED.");
}
``` | Regex? How about just looking at the `.checked` property? | check a checkbox with a regex | [
"",
"javascript",
"regex",
""
] |
In MS Access, I have some reports that use some queries, to show data, within a date range. The queries use aliases, if, sum, and avg functions, and join multiple tables to get its data.
I'd like to know if i could use a UNION ALL, with a table that has all the needed fields, to display this new data from this table, along with the older data, if someone selects a range that spans the new and the old.
Here's an example "old" query:
```
SELECT tblAssessment.fldValid, tblATraining.fldTID, tblATraining.fldTCrsID,
tblCourses.fldCrsName, [fldCrsHrs]/8 AS Days, tblATraining.fldTLocAbr,
tblDistrict.fldDistAbr, tblRegion.fldRegName, tblATraining.fldTDateStart,
tblATraining.fldTDateEnd, tblATraining.fldTEnrolled, tblATraining.fldTPID,
tblPersonnel.fldPName, tblAssessment.fldTrngSID, tblAssessment.Q1,
IIf([fldValid]=True,IIf([Q1]>0,1,0),0) AS Q1Valid, tblAssessment.Q2,
IIf([fldValid]=True,IIf([Q2]>0,1,0),0) AS Q2Valid, tblAssessment.Q3,
IIf([fldValid]=True,IIf([Q3]>0,1,0),0) AS Q3Valid, tblAssessment.Q4,
IIf([fldValid]=True,IIf([Q4]>0,1,0),0) AS Q4Valid, tblAssessment.Q5,
IIf([fldValid]=True,IIf([Q5]>0,1,0),0) AS Q5Valid, tblAssessment.Q6,
IIf([fldValid]=True,IIf([Q6]>0,1,0),0) AS Q6Valid, tblAssessment.Q7,
IIf([fldValid]=True,IIf([Q7]>0,1,0),0) AS Q7Valid, tblAssessment.Q8,
tblAssessment.Q9,
IIf([fldValid]=True,IIf([Q9]>0,1,0),0) AS Q9Valid, tblAssessment.Q10,
IIf([fldValid]=True,IIf([Q10]>0,1,0),0) AS Q10Valid, tblAssessment.Q11,
IIf([fldValid]=True,IIf([Q11]>0,1,0),0) AS Q11Valid, tblAssessment.Q12,
IIf([fldValid]=True,IIf([Q12]>0,1,0),0) AS Q12Valid, tblAssessment.Q13,
tblAssessment.Q14,
IIf([fldValid]=True,IIf([Q14]>0,1,0),0) AS Q14Valid, tblAssessment.Q15,
IIf([fldValid]=True,IIf([Q15]>0,1,0),0) AS Q15Valid, tblAssessment.Q16,
IIf([fldValid]=True,IIf([Q16]>0,1,0),0) AS Q16Valid, tblAssessment.Q17,
IIf([fldValid]=True,IIf([Q17]>0,1,0),0) AS Q17Valid, tblAssessment.Q18,
IIf([fldValid]=True,IIf([Q18]>0,1,0),0) AS Q18Valid, tblAssessment.Q19,
IIf([fldValid]=True,IIf([Q19]>0,1,0),0) AS Q19Valid, tblAssessment.Q20,
tblAssessment.Q21,
IIf([fldValid]=True,IIf([Q21]>0,1,0),0) AS Q21Valid, tblAssessment.Q22,
IIf([fldValid]=True,IIf([Q22]>0,1,0),0) AS Q22Valid, tblAssessment.Q23,
IIf([fldValid]=True,IIf([Q23]>0,1,0),0) AS Q23Valid, tblAssessment.Q24,
IIf([fldValid]=True,IIf([Q24]>0,1,0),0) AS Q24Valid, tblAssessment.Q25,
IIf([fldValid]=True,IIf([Q25]>0,1,0),0) AS Q25Valid, tblAssessment.Q26,
IIf([fldValid]=True,IIf([Q26]>0,1,0),0) AS Q26Valid, tblAssessment.Q27,
IIf([fldValid]=True,IIf([Q27]>0,1,0),0) AS Q27Valid, tblAssessment.Q28,
IIf([fldValid]=True,IIf([Q28]>0,1,0),0) AS Q28Valid, tblAssessment.Q29,
tblAssessment.Q30,
tblAssessment.Q31, tblAssessment.Q32
FROM ((tblDistrict
LEFT JOIN tblRegion ON tblDistrict.fldDRegID = tblRegion.fldRegID)
RIGHT JOIN (((tblATraining
LEFT JOIN tblCourses ON tblATraining.fldTCrsID = tblCourses.fldCrsID)
LEFT JOIN tblPersonnel ON tblATraining.fldTPID = tblPersonnel.fldPID)
LEFT JOIN tblLocations ON tblATraining.fldTLocAbr = tblLocations.fldLID) ON tblDistrict.fldDistAbr = tblATraining.fldTDistAbr)
LEFT JOIN tblAssessment ON tblATraining.fldTID = tblAssessment.fldTrngCID
WHERE (((tblAssessment.fldValid)=True)
AND ((tblATraining.fldTCrsID) Like [forms]![fdlgRptCriteria].[selCrsCd])
AND ((tblATraining.fldTDateStart) Between [forms]![fdlgRptCriteria].[seldate1] And [forms]![fdlgRptCriteria].[seldate2])
AND ((tblAssessment.fldTrngSID) Is Not Null));
``` | Yes, but you might consider creating a new querydef for the union.
(You'll need to use the SQL design window last time I checked.)
It would be approximately:
```
SELECT
tblATraining.fldTID,
tblATraining.fldTCrsID,
tblATraining.fldTLocAbr,
tblATraining.fldTDateStart,
tblATraining.fldTDateStart,
tblATraining.fldTDateEnd,
tblATraining.fldTEnrolled,
tblATraining.fldTPID
UNION ALL
tblATrainingArchive.fldTID,
tblATrainingArchive.fldTCrsID,
tblATrainingArchive.fldTLocAbr,
tblATrainingArchive.fldTDateStart,
tblATrainingArchive.fldTDateStart,
tblATrainingArchive.fldTDateEnd,
tblATrainingArchive.fldTEnrolled,
tblATrainingArchive.fldTPID
```
and name it something like tblATrainingUnion.
Then just plug that into your existing query wherever you have tblATraining.
Note: Many people also tend to create an archive table sooner than it really makes sense - you might consider just leaving it all in the main table, and make the split when you can actually measure the difference. (You may already have reached that point and done that; and it can make more sense with Access than with say SQL Server.) | Yes, Access supports `UNION ALL`. A simple example would be:
```
select foo from OldData
union all
select foo from NewData
``` | SQL Union All to display old data with new data? | [
"",
"sql",
"ms-access",
"union",
""
] |
I want to store an array in a record.
Table1:
```
ID, Name, Friends (friends should be an array)
1, Bill, 2&3
2, Charles, 1&3
3, Clare, 1
```
I want to be able to do a search like this:
```
SELECT * FROM Table1 WHERE Friends='3'
```
to find everyone who has Clare listed as a friend | Unless you have a really good reason for doing this, you should keep your data normalized and store the relationships in a different table. I think perhaps what you are looking for is this:
```
CREATE TABLE people (
id int not null auto_increment,
name varchar(250) not null,
primary key(id)
);
CREATE TABLE friendships (
id int not null auto_increment,
user_id int not null,
friend_id int not null,
primary key(id)
);
INSERT INTO people (name) VALUES ('Bill'),('Charles'),('Clare');
INSERT INTO friendships (user_id, friend_id) VALUES (1,3), (2,3);
SELECT *
FROM people p
INNER JOIN friendships f
ON f.user_id = p.id
WHERE f.friend_id = 3;
```
> ```
> +----+---------+----+---------+-----------+
> | id | name | id | user_id | friend_id |
> +----+---------+----+---------+-----------+
> | 1 | Bill | 1 | 1 | 3 |
> | 2 | Charles | 2 | 2 | 3 |
> +----+---------+----+---------+-----------+
> 2 rows in set (0.00 sec)
> ``` | You might want a comma-separated value, but it's not recommended. Why not use another table for showing relationships?
```
Table2
----------------------
PARENT_ID | FRIEND_ID
----------------------
1 | 2
1 | 3
2 | 1
2 | 3
----------------------
``` | array in MySQL | [
"",
"php",
"mysql",
""
] |
Does PHP have a built in function for doing string to integer hashes, something that's difficult to reverse?
Now, I know I can probably get away with doing an md5, and treating a substring of it as a radix 16 number, but I'm looking for something built in.
Thanks. | I think the best bet would chose a standard hash [either `md5()` or `sha1()`] to obtain a hash of your string, and then to get an integer hash, to a `base_convert($hash, 16, 10)` and that should convert your hash into a integer hash.
Hope I am understanding your issue correctly. | I think you are on the right path in approaching this problem in two steps.
First, you should probably stick with the md5 hash to fulfill your "difficult to reverse" requirement.
Second, you could take the md5 output as input to your "convert this to an integer" function.
for the second part, what are you going after exactly? Does it *have* to be an integer? Or just printable characters? if you are just looking to convert your hash into something you can store in a database, transmit over the wire, or some other reason the md5 string won't do, the convertuuencode function might work for you: <http://us.php.net/manual/en/function.convert-uuencode.php>
Another roundabout hackish approach would be to get the binary value of your hash, and convert it to a decimal using: <http://us.php.net/manual/en/function.bindec.php> although, i've never tried this and am not sure if it would work like you want it to. | php hash form string to integer | [
"",
"php",
"hash",
"integer",
""
] |
I've been feeling like start doing some fun stuff with my delicious bookmarks and LINQ to XML, and I was wondering if there's a way to split the tag attribute *within* LINQ.
What I've meant with *split the tag within LINQ* was generating a collection of strings for each post element, so the expected result would be a generic collection of `post` elements, with its attributes as properties, where the `tag` property is itself another collection of strings, with its items being each tag.
For those not quite familiar with delicious.com's exported xml, here´s the basic structure of an element:
```
<post
href="http://stackoverflow.com/"
hash="e4a42d992025b928a586b8bdc36ad38d"
description="Stack Overflow"
tag="code development programming community tips answers reference"
time="2009-05-22T19:44:09Z"
extended="Stack Overflow is a programming Q & A site that's free."
meta="e0bf85c9df073cd51cc5528637db5277"
/>
```
Here's the snippet of code I'm using:
```
XDocument delicious = XDocument.Load("all.xml");
var bookmarks = from posts in delicious.Descendants().Attributes("tag")
select (string)posts;
```
Any ideas, suggestions, comments would be really appreciated. | What is your desired output actually like? Do you want an array of each value in the "tag" field?
```
var bookmarks = from posts in delicious.Descendants().Attributes("tag")
select ((string)posts).Split(" ");
```
That would give you a list of arrays. It's hard to say how to accomplish what you want, since it isn't very well specified. | string class has a Split method.
Is this what you are looking for?
EDIT: string.Join(Environment.NewLine, bookmarks.ToArray()); | How can I split an attribute's value within LINQ(-to-XML)? | [
"",
"c#",
".net-3.5",
"linq-to-xml",
"delicious-api",
""
] |
I am new to web programming, coming from a video game development background (c++), and am really starting to feel information overload. There are so many competing libraries which all pick something they don't like in some other library, and build an entirely new way of doing the same thing! I am sure there there are good reasons for this, and I don't want to complain, so I'll explain my problem.
To ease my journey, I've decided to start learning Google App Engine + GWT + Java. I like it because it's a distributed server architecture out of the box, and I've chosen Java because of my C++ background.
To begin with I wrote little Twitter-like application because it tests various aspects of web development, namely: REST, JSON parsing/creation, AJAX comms, and HTML generation. It didn't take me too long to create a little site that allows a user to enter their name and password into page in the browser, send the data across to my app, I login on their behalf, grab their friends list, and emit it back to the client as JSON, where I parse it and display it.
Pretty simple stuff.
So, the next step was that I didn't like sending the password the user has entered over the network as plain text (obviously). That got me thinking about all the plumbing I would need:
1. Authenticate users against my own database, not Google's. (Login/Lost password/Logout)
2. Enter/exit (track) a session (logged in/logged out).
3. Store user data in my Google app's database.
All pretty standard stuff that's been around forever. Well I started looking around for a Java authentication library and there were such large, monolithic libraries with huge learning curves, and some are old or not in favour any more... I feel like a total beginner programmer all over again! I just want to have a login page! :)
So then I started reading up on how the plumbing of authentication works, and there is a huge amount to take in. Apparently it's quite common for people to (insecurely) roll their own. I'd rather take a solution that exists and is solid.
So the question becomes, what do people do about this? Twitter supports both HTTP and HTTPS, but defaults to HTTP for its REST API, does that mean people's passwords are flying around unprotected, ready to be intercepted by man-on-the-middle hacks?
I also looked at OAuth, which looks excellent, but it doesn't have a case for just a good old "I don't want know or care what OpenID is". Non technical people I've showed OpenID to are like "wha? I just want to put my username/password in".
As a side note, has anyone had any luck with Spring.Security on Google App Engine?
Anyway, I'm ranting. I just want to know what people do (not in Python, Rails etc, but in good old Java). I'd love to have a login page like Digg, with even an option one day for OpenID :)
Cheers,
Shane | I can't speak to Spring Security alongside Google App Engine, but I can say a few things about it that may be helpful.
First, it is very simple to setup, and they have good tutorials for getting it up and going. Personally, I used the [pet-clinic tutorial](http://static.springframework.org/spring-security/site/petclinic-tutorial.html) as a guide for how to apply spring security to my project the first time. I was able to get it setup in a matter of an hour or two and had basic security using my database over a few different pages. Your mileage may vary of course, but worst case scenario you have their full fledged tutorial you can poke and prod to see how it reacts.
Secondly, the library is very configurable. If you search through the [manual](http://static.springframework.org/spring-security/site/docs/3.0.x/reference/springsecurity.html) you'll get a good idea of the things you can do, and I had no problems reworking the areas I needed to change for my project. I have confidence that you should be able to work those Spring Security and Google App Engine together. In general I have been pleased with the Spring source's foresight and ability to interact with other libraries.
Finally, Spring Security supports OpenID if that's something you decide you want to layer in. I haven't played with this portion yet, but from the tutorial it also looks pretty intuitive. The nice thing here, is that you should be able to add that after the fact if it turns out that you should have supported OpenID after all.
I wish you the best of luck! | I just stumbled upon your post. You seemed (past tense since it's been a long time) to be confused about HTTP / HTTPS usage and authentication. If you are using HTTP, your password is not being bounced around in plain text. Typically, the login information is POSTed via HTTPS. By this time, a session has been established, which is tracked via a large randomly generated identifier in a cookie. The user is authenticated on the server and their id is stored in the session (stored on the server) to mark that they're signed in.
From that point onwards, the user is tracked via the session. Yes it's possible that a man-in-the-middle could hijack the cookie and assume your identity. This is the case for 100% of sites that work over HTTP but it clearly is just not a problem or you'd hear more about it. For HTTPS, the session cookie can be marked as secure, meaning that it will only ever be sent via HTTPS from the browser. In the past, I've found that browsers behave differently, sometimes sharing the same value for a secure and non-secure same-named cookie (which is a dumb idea). Your best bet is to use a separately named secure cookie to ensure the user is logged in for secure functions on your website.
I agree with you that the JAAS framework is plain awful. It must have been written by a bunch of deranged lunatics with no common sense.
As for using Google App Engine - they will take care of all the authentication for you. It looks like you have no choice but to use Google Accounts which is a shame. It's also a shame that they insist that you redirect to their login page because this breaks the way a GWT app works. I'm currently looking into managing my own accounts because I don't want google to own them and I don't want that disjointed experience on my site.
However, it seems impossible to track a user without a session (Sessions can be supported in GAE but are strongly discouraged to promote scalability in GAE). Without a session I literally do need to send the password and authenticate the user with every RPC request. Google are pulling some tricks to make the getUserPrincipal() method work across their server clusters - and it seems you only get that magic if you go with Google Accounts.
Maybe I'm missing something, but the Google docs just skim over this gaping hole :( | Web site login in Java + Google App Engine | [
"",
"java",
"google-app-engine",
"authentication",
""
] |
I'm writing a simple telnet client library. I open sockets using fsockopen() and read and write to the socket using fgetc() and fwrite(). I use fgetc() instead of fread() to handle Telnet special commands and options like (IAC, ...).
the problem is that most of times I'm reading from the socket, it takes too long to return. as I have profiled it, it takes as long as the connection times out, and after that I have the results.
here are my reading method:
```
protected function getChar()
{
$char = fgetc( $this->_socket );
return $char;
} // public function getChar()
```
currently I use this condition to make sure stream is finished:
```
$char = $this->getChar();
if ( $char === false ) {
// end of the stream.
}
```
is there any other way to find out that the stream is finished an all data is read?
Udate: I think the EOF character in Telnet protocol is not what PHP expects as EOF, and that's why the script can not find end of the stream. does anyone know what is the EOF (end of file) character in Telnet protocol? | Try echoing out the hex values of each character you receive. You should be able to see just what you are receiving as EOF, even if PHP doesn't recognize it as such. Look into [ord()](https://www.php.net/manual/en/function.ord.php) and [bin2hex()](http://us.php.net/manual/en/function.bin2hex.php) | There is `feof()` that may be useful. | read all data recieved from a socket in PHP | [
"",
"php",
"sockets",
"telnet",
""
] |
I have a need for an Image Library within my organization and I was wondering if anyone knows of any that they could recommend. It will need to be able to integrate with any number of our own solutions (meaning it will have a set of services or APIs that one can use for integration).
Also I would be great if it had: facial recognition, geo-tagging, indexing of colors, people, places, photo content, (meaning it can detect the primary colors used in the photo, read content from the photo, like OCR, tell where the focus of the photo is), search by any of these (i.e. color, geo position, etc).
Basically a cross between, iPhoto (with its facial recognition, geo-tagging, etc) and iStockPhoto (with its color, content, focus placement detection, etc) for an Organization.
As you can imagine I would prefer not to have to build this myself.
Cheers
Anthony
* Note: I am more after a commercial piece of software that is an Image Library and does the above, that allows for integration | I have used both [DotImage](http://www.atalasoft.com/products/DotImage/) and [LeadTools](http://www.leadtools.com/) to work with images... they are the top .NET Imaging libraries out there (that I know of) and provide rich imaging functionality to develop applications. | Are you talking about an image processing library or a program for storing images and with some extra features? In the first case, you might take a look at [OpenCV](http://opencv.willowgarage.com/wiki/). | Image Library Software | [
"",
"c#",
".net",
"image-processing",
"integration",
""
] |
I am looking to implement a 1 on 1 user to user web chat application for a new website in the works. Something similar to [Omegle](http://omegle.com) is the aim for the final product. Does anyone know of ready made solutions that are capable of this?
Due to my experience, PHP is the language of choice. Omegle was written in Python using the twisted library. Should it come down to building the application from scratch, can anyone give advice on a solution to networking between users via PHP?
Thanks in advance for the help. As you may have picked up, I have not ventured far out of mainstream websites, so although PHP is fine, the connection / networking layer is fairly foreign to me.
Lobe
Long time reader, first time poster | There are a number of solutions based on Jabber with a JS or Flash client. One easy server to install is [Openfire](http://www.igniterealtime.org/projects/openfire/index.jsp) and the company that publishes the (open source) server, also has services to help integration onto websites. At previous website I worked at, I installed the server, but had someone write a flash-based client for it (it's problematic, I'd not do it that way again for the client), but the server itself performed flawlessly with sub-second responses.
It had replaced an in-house AJAX-based chat system, but with a fraction of the client base using it, that ajax client was responsible for 72% of the HTTP hits against the website (and without it we did 700K+ hits/day). Going Jabber-based removed those overnight and helped to speed the site. The Jabber system would also be able to be scaled up 10x with very little extra work. | You can't "connect different php users together". All of it will go from user1 to server and user2 to server. Then each user's browser must periodically poll for new content. When you say "the connection / networking layer is fairly foreign to me" I get the impression you think you can do this without having the browsers poll the server. You can't. I haven't used phpfreechat but if it has the capability to do different rooms then you might investigate if it is viable by setting up unique rooms for each user pair. | User to User web chat application (PHP) - what choice? | [
"",
"php",
"chat",
"social-networking",
""
] |
```
var valueAsText = $('#counts span').text();
```
I use this tiny script to parse a span that contains the value 10, but I got this value instead **100000000000**
can someone tell me what is wrong?
and here is the code:
```
<div id="counts"><span>10</span> </div>;
```
thanks. | You can use
```
$('#counts span').html();
```
and it will only return the innerHtml from the first match. The simplest solution would be to add a id to the span to make sure you get just what you want.
```
$('#span-id').text();
```
or
```
$('#span-id').html();
```
They should both return the same value at this point. | Are there multiple spans inside #count?
If so, you could try
```
$("#counts span:first").text()
``` | parsing a Value in JQuery? | [
"",
"javascript",
"jquery",
""
] |
I'm familiar with the use of Parameterized tests in JUnit, e.g:
<http://junit.org/apidocs/org/junit/runners/Parameterized.html>
but I wondered whether there were any alternative (possibly better) approaches to externally defined test data. I don't really want to hardcode my test data in my source file - I'd prefer to define it in XML or in some sort of other structured manner.
Is there a particular framework, or extension to a framework that provides me with a better solution than the standard JUnit approach. What specifically was the best approach you found to this?
EDIT: I'm familiar with the FIT framework and the use of it in this case, I want to avoid that if possible. If there is a JUnit extension or similar framework that provides a better solution than TestNG then please let me know. | So I found TestNG's approach to this, which allows you to specify parameters for tests, more info available here:
<http://testng.org/doc/documentation-main.html#parameters-testng-xml>
An example of this would be:
```
@Parameters({ "first-name" })
@Test
public void testSingleString(String firstName) {
System.out.println("Invoked testString " + firstName);
assert "Cedric".equals(firstName);
}
```
and:
```
<suite name="My suite">
<parameter name="first-name" value="Cedric"/>
<test name="Simple example">
```
You can also use a datasource (such as Apache Derby) to specify this testdata, I wonder how flexible a solution this is though. | You can try [Dependency Injection or Inversion of Control](http://en.wikipedia.org/wiki/Dependency_injection) for this. The [Spring Framework](http://en.wikipedia.org/wiki/Spring_Framework) does this. | Solution for Parameterized Tests | [
"",
"java",
"unit-testing",
"junit",
""
] |
I'm writing to the [windows event log](http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx) using C#. I can set every field visible in the mmc.exe "Computer Management" tool, except for the User field.
The client application is ASP.NET and uses forms authentication.
```
public static void WriteOnce()
{
EventLog log = new EventLog("MyApp");
if (!EventLog.SourceExists("MySource"))
{
EventSourceCreationData data = new EventSourceCreationData("MySource", "MyApp");
EventLog.CreateEventSource(data);
}
log.Source = "MySource";
log.WriteEntry("Hello World", EventLogEntryType.Information,123,456,new byte[]{1,2,3});
}
```
UPDATE: I checked, in ASP.NET even if set identity impersonation=true & authentication=windows and still no user.
I also checked, in a console app, no user. | I found a blog entry that explains how to do it, although there doesn't seem to be a completely managed way to do it. To capture the user Id, you have to use pinvoke/native method calls.
<http://www.infosysblogs.com/microsoft/2007/09/logging_events_with_user_detai_1.html>
For the above, it logs the user as ASPNET or NETWORK SERVICES, or the logged in user for console apps. The api call itself takes a pointer parameter to a SID. I didn't try to see if spoofing was possible.
JPucket may be right, that the only way to get the ID of a forms authenticated user in the System Event Log is via the message field. | Well the user is the current user your AppDomain is running as. This cannot be set and Windows won't allow you to "spoof" another user. | How to get EventLog to record user name into Window Event Log? | [
"",
"c#",
"event-log",
""
] |
I am trying to channel data via pipes whenever a signal arrives from a thread to the main process.
Is this possible?
How can this be done?
---
### The problem:
1. A child thread reads data and puts it into a queue.
2. Main application does its own stuff, however, when data is available on the queue, it should be notified by the thread, and start processing the data (main thread has access to the queue).
How should this scenario be implemented? | Yes its possible through pipes.
Step one call [pipe](http://linux.die.net/man/3/pipe) to get a pipe:
```
#include <unistd.h>
int main(...)
{
int fileDescriptors[2];
pipe(fileDescriptors);
```
Step 2 pass the fileDescriptors[0] to the main process, and fileDescriptors[1](http://linux.die.net/man/3/pipe) to the thread. In Main you wait for the pipe to be written to to by reading from fileDescriptors[0]
```
...
char msg[100];
read(fileDescriptors[0], msg, 100); // block until pipe is read
}
```
Step 3, from your thread write to fileDescritpors[1](http://linux.die.net/man/3/pipe) when the signal occurs
```
void signal_handler( int sig )
{
// Write to the file descriptor
if (sig == SIGKILL)
{
const char* msg = "Hello Mama!";
write(fileDescriptors[1], msg, strlen(msg));
}
}
``` | It can be done, but it's rather unnecessary. Pipes are intended for inter-process communication. Threads share the same memory and can therefore communicate directly, as long as you use locking correctly. | How can Unix pipes be used between main process and thread? | [
"",
"c++",
"multithreading",
"pipe",
"unix",
""
] |
We're about to run side-by-side testing to compare a legacy system with a new shiny version. We have an Oracle database table, A, that stores data for the legacy system, and an equivalent table, B, that stores data for the new system, so for the duration of the test, the database is denormalized. (Also, the legacy system and table A are fixed - no changes allowed)
What I want to do is to allow the infrequent DML operations on A to propagate to B, and vice-versa. I started with a pair of triggers to do this, but hit the obvious problem that when the triggers run, the tables are mutating, and an exception is thrown.
Is there a standard way of handling this issue? I've read differing reports on whether or not using dbms\_scheduler is the way to go...
Thanks,
Andy
**Update:**
I've ended up chickening out of the whole issue and ensured that all stored procedures that update A, also update B, and vice versa.
I've marked Quassnoi's answer as accepted, because I'd follow his suggestions if faced with the same issue in the future.
I've marked up JosephStyon's answer, because I briefly got things working by adding two insert/update statement level triggers on tables A and B, then doing his merge procedure using A or B as the master table, depending on which trigger ran (although first I checked that the target table would be changed by the merge, earlying out if not). | I'd create `A` and `B` as views over a single normalized (or denormalized) table, and created an `INSTEAD OF` trigger over these views to handle `DML` operations.
If the query plans matter, it's better to keep two copies of tables: `A_underlying` and `B_underlying` and create the views just like this:
```
CREATE VIEW A
AS
SELECT *
FROM A_underlying
CREATE VIEW B
AS
SELECT *
FROM B_underlying
```
The predicates will be pushed into the views, and the query plans for actual tables and views will be the same.
In `INSTEAD OF` triggers over both view, you should put the data into both underlying tables. | Do you really mean DDL, not DML?
With DML you can have a look at Oracles [Multi Master Replication](http://download-uk.oracle.com/docs/cd/B10501_01/server.920/a96567/repmaster.htm) to keep the tables in synch or you could also have a look at the tool [SymmetricDS](http://symmetricds.codehaus.org) for this purpose.
With DDL the only solution I'm aware of is again the [Oracle advanced replication](http://www.orafaq.com/wiki/Advanced_Replication_FAQ#How_does_one_change_the_definition_of_a_replicated_table.3F). | Keeping tables synchronized in Oracle | [
"",
"sql",
"oracle",
"synchronization",
"triggers",
"denormalization",
""
] |
Is it true that no matter which type of join you use, if your WHERE clause checks one table's pk = other table's fk, it becomes same as an inner join as far as the result set is conncerned? In other words, if your sql query has some stuff like:
"Select ... from A Left join B On (...) E, F Full Outer Join G on (A.pk = G.fk) ... WHERE A.pk = G.fk and A.pk = B.fk and etc..."
In the above query, A is left-joined to B, whereas G is outer-joined to A on its fk. But as the where clause has the two checks, so the whole query reduces to something like:
"Select ... from A INNER JOIN B On (...) E, F INNER Join G on (A.pk = G.fk) ... WHERE etc ..."
?
The reason for asking this query is that I have many cartesian-type joins along with where clauses that are on one table's pk = other table's fk, that are slowing the query down. I was thinking of replacing the cartesian products with either Left Joins combined with keeping all the where clauses, or all Inner Joins. | Yes if you refernce the right side of a left outer join in a where clause with anything except "where myfield is null", you have created an inner join. This is because it filters out anything that that doesn't meet that condition including all the records that don't have a match to the intial table. Same with the other non-inner joins. To get around it you put the condition in the join. Example (this turns it into an inner join):
```
Select field1, field2 from mytable mt
left join mytable2 mt2 on mt.id = m2.id
where mt1.field1 = 'hello' and mt2.field2 = 'test'
```
Rewritten to preserve the left join:
```
Select field1, field2 from mytable mt
left join mytable2 mt2 on mt.id = m2.id and mt2.field2 = 'test'
where mt1.field1 = 'hello'
```
I also want to comment on something you said in a comment but figured my response would be too long for another comment.
"Select ... From A Inner Join B on (A.id = B.a\_id),C,D, F where A.id=F.id"
to: "Select ... From A Inner Join B on (A.id = B.a\_id),C,D INNER JOIN F on A.id = F.a\_id"
You do not want to combine syntaxes like this; this becomes very hard to maintain. In fact I recommend never using the old style comma syntax as it is subject to accidental cross joins. So in your example I would write to get the result set you currently get (at least someone maintaining will know you indended a cross join instead of did it by accident):
```
Select ... From A
INNER JOIN B on A.id = B.a_id
INNER JOIN F on A.id = F.a_id
CROSS JOIN C
CROSS JOIN D
```
Altenatively if the cross join is accidental, the code would change to:
```
Select ... From A
INNER JOIN B on A.id = B.a_id
INNER JOIN F on A.id = F.a_id
INNER JOIN C on (fill in the join fields)
INNER JOIN D on (fill in the join fields)
``` | Yes, that is a roundabout way of getting an inner join.
Think about how this works: It pulls everything from A, then the matching B's or nulls, then all G (nulls on the A/B and G sides), and then it essentially filters out everything that has a null side to it (the WHERE clause). So, yes, the INNER JOIN is probably faster.
A common source of this confusion is that this:
```
SELECT * FROM a INNER JOIN b ON a.id = b.id AND b.something = 'awesome'
```
is equivalent to:
```
SELECT * FROM a INNER JOIN b ON a.id = b.id WHERE b.something = 'awesome'
```
However, this same transitive approach doesn't work with full/outer joins, as it will do the join and then filter (depending on the filters, of course, and the optimizer).
So, in short: use inner joins if you really want an inner join.
Edit: I should also note that it's not the PK/FK deal, it's if you essentially repeat your ON clause in the WHERE clause that the full/outer joins will become equivalent to inner joins. | Is it true that all types of joins reduce to Inner joins in the presence of the check of one table's pk = other table's fk? | [
"",
"sql",
""
] |
I'm curious as to what other people use in the Java world for configuring their applications. I've previously used Spring's [PropertyPlaceHolderConfigurer](http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/beans/factory/config/PropertyPlaceholderConfigurer.html) and [PropertyOverrideConfigurer](http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/beans/factory/config/PropertyOverrideConfigurer.html) to load various properties files and bind them using the default Spring property editors.
This is a perfectly acceptable solution for what I've done, but I wondered is there was a better alternative for application configuration that somebody has used?
If you have used a better approach could you provide a list of advantages of using a Spring approach. Many thanks in advance. | You could also try something like [Constretto](http://constretto.org/), which handles different environments (test, acceptance, production etc) a little more gracefully.
Before diving into Constretto also be advised that [Spring 3.0](http://www.springsource.com/) *is* changing this landscape quite dramatically, with spring-el being the first thing that comes to mind. Even today the documentation [spring 3.0-M3](http://s3.amazonaws.com/dist.springframework.org/milestone/SPR/spring-framework-3.0.0.M3-with-docs.zip) reveals quite a lot. | If you are using Spring, the approach you've adopted IS the best. Otherwise you'd have to load property or XML files yourself. | Java Project Configuration | [
"",
"java",
"spring",
"configuration",
""
] |
I am tasked with pulling all the rows from a 3rd party vendor's SQLite data table, creating business objects from those records, and sending the new business objects off to another class.
Pseudo-code:
```
var databasePath = "%user profile%\application data\some3rdPartyVendor\vendor.sqlite"
var connection = OpenSqliteConnection(databasePath);
var allGizmoRecords = connection.Query(...);
var businessObjects = TransformIntoBizObjs(allGizmoRecords);
someOtherClass.HandleNewBizObjs(businessObjects);
```
I've got all that working.
My question is: **How can I write this class so it's unit testable?**
Should I:
* use the repository pattern to mock out the data access
* actually provide a dummy SQLite database in the unit test
Or any better ideas? I'm using C#, but this question seems rather language-agnostic. | You *could* inject a test-only Sqlite database quite easily, refactoring the code to look like below. But **how are you asserting the results**? The business objects are passed to `someOtherClass`. If you inject an `ISomeOtherClass`, that class's actions need to be visible too. It seems like a bit of pain.
```
public class KillerApp
{
private String databasePath;
private ISomeOtherClass someOtherClass;
public KillerApp(String databasePath, ISomeOtherClass someOtherClass)
{
this.databasePath = databasePath;
this.someOtherClass = someOtherClass;
}
public void DoThatThing()
{
var connection = OpenSqliteConnection(databasePath);
var allGizmoRecords = connection.Query(...);
var businessObjects = TransformIntoBizObjs(allGizmoRecords);
someOtherClass.HandleNewBizObjs(businessObjects);
}
}
[TestClass]
public class When_Doing_That_Thing
{
private const String DatabasePath = /* test path */;
private ISomeOtherClass someOtherClass = new SomeOtherClass();
private KillerApp app;
[TestInitialize]
public void TestInitialize()
{
app = new KillerApp(DatabasePath, someOtherClass);
}
[TestMethod]
public void Should_convert_all_gizmo_records_to_busn_objects()
{
app.DoThatThing();
Assert.AreEqual(someOtherClass.Results, /* however you're confirming */);
}
}
```
Using an `IRepository` would remove some of the code from this class, allowing you to mock the `IRepository` implementation, or fake one just for test.
```
public class KillerApp
{
private IRepository<BusinessObject> repository;
private ISomeOtherClass someOtherClass;
public KillerApp(IRepository<BusinessObject> repository, ISomeOtherClass someOtherClass)
{
this.repository = repository;
this.someOtherClass = someOtherClass;
}
public void DoThatThing()
{
BusinessObject[] entities = repository.FindAll();
someOtherClass.HandleNewBizObjs(entities);
}
}
[TestClass]
public class When_Doing_That_Thing
{
private const String DatabasePath = /* test path */;
private IRepository<BusinessObject> repository;
private ISomeOtherClass someOtherClass = new SomeOtherClass();
private KillerApp app;
[TestInitialize]
public void TestInitialize()
{
repository = new BusinessObjectRepository(DatabasePath);
app = new KillerApp(repository, someOtherClass);
}
[TestMethod]
public void Should_convert_all_gizmo_records_to_busn_objects()
{
app.DoThatThing();
Assert.AreEqual(someOtherClass.Results, /* however you're confirming */);
}
}
```
But this still feels quite cumbersome. There are two reasons, 1) the Repository pattern has been [getting some](http://ayende.com/Blog/archive/2008/11/16/the-fallacy-of-irepository.aspx) [bad press](http://ayende.com/Blog/archive/2009/04/17/repository-is-the-new-singleton.aspx) lately from [Ayende](http://ayende.com/Blog/), who knows a thing or two about Repository. And 2) what are you doing **writing your own data access**!? Use [NHibernate](https://www.hibernate.org/343.html) and [ActiveRecord](http://www.castleproject.org/activerecord/index.html)!
```
[ActiveRecord] /* You define your database schema on the object using attributes */
public BusinessObject
{
[PrimaryKey]
public Int32 Id { get; set; }
[Property]
public String Data { get; set; }
/* more properties */
}
public class KillerApp
{
private ISomeOtherClass someOtherClass;
public KillerApp(ISomeOtherClass someOtherClass)
{
this.someOtherClass = someOtherClass;
}
public void DoThatThing()
{
BusinessObject[] entities = BusinessObject.FindAll() /* built-in ActiveRecord call! */
someOtherClass.HandleNewBizObjs(entities);
}
}
[TestClass]
public class When_Doing_That_Thing : ActiveRecordTest /* setup active record for testing */
{
private ISomeOtherClass someOtherClass = new SomeOtherClass();
private KillerApp app;
[TestInitialize]
public void TestInitialize()
{
app = new KillerApp(someOtherClass);
}
[TestMethod]
public void Should_convert_all_gizmo_records_to_busn_objects()
{
app.DoThatThing();
Assert.AreEqual(someOtherClass.Results, /* however you're confirming */);
}
}
```
The result is a much smaller class and a business object and data-layer that you can change more easily. And you don't even have to mock the database calls, you can configure and initialize ActiveRecord to use a test database (in-memory, even). | Well, the only thing that would really need to be tested here is TransformIntoBizObjs, I would think, since the connection code should have been written/tested elsewhere. Simply passing things that might show up to Transform and seeing if the right thing pops out would be what you need to do.
Remember to test all usecases of Transform, even potentially weird items that probably shouldn't end up in the function call, but might. Never know what people have been shoving in their databases. | Writing a testable "import data from database" class | [
"",
"c#",
"database",
"unit-testing",
"class-design",
"integration-testing",
""
] |
I'm having problem getting the source and header files added into my Eclipse CDT project with CMake. In my test project (which generates and builds fine) I have the following CMakeLists.txt:
```
cmake_minimum_required(VERSION 2.6)
project(WINCA)
file(GLOB WINCA_SRC_BASE "${WINCA_SOURCE_DIR}/src/*.cpp")
file(GLOB WINCA_SRC_HPP_BASE "${WINCA_SOURCE_DIR}/inc/*.hpp")
add_library(WINCABase ${WINCA_SRC_BASE} ${WINCA_SRC_HPP_BASE})
```
This works fine but the resulting Eclipse project files contains no links to the source or header files. Anyone knows why? Are there any other cmake command I have to use to actually add the files into the project? | The problem I had was I made an "in-source" build instead of an "out-of-source" build. Now it works fine, and it was actually lots of info on this on the Wiki but somehow I misunderstood it. | I realize it's been a while since you've post this, but fwiw, it work's for me fine with CMake 2.6 or 2.7 (trunk) versions, generating for Eclipse/Ganymede. What I do is first run
```
cmake -G "Eclipse CDT4 - Unix Makefiles" /path/to/src
```
which generates the Eclipse project files as well as the makefiles, then "Import Project" in Eclipse.
Works beautifully...
sly | How to add files to Eclipse CDT project with CMake? | [
"",
"c++",
"eclipse",
"cmake",
""
] |
I want to convert some numbers which I got as strings into Doubles, but these numbers are not in US standard locale, but in a different one. How can I do that? | Try [`java.text.NumberFormat`](http://java.sun.com/javase/6/docs/api/java/text/NumberFormat.html). From the Javadocs:
> To format a number for a different Locale, specify it in the call to getInstance.
>
> ```
> NumberFormat nf = NumberFormat.getInstance(Locale.FRENCH);
> ```
>
> You can also use a NumberFormat to parse numbers:
>
> ```
> myNumber = nf.parse(myString);
> ```
[`parse()`](http://java.sun.com/javase/6/docs/api/java/text/NumberFormat.html#parse(java.lang.String)) returns a [`Number`](http://java.sun.com/javase/6/docs/api/java/lang/Number.html); so to get a `double`, you must call [`myNumber.doubleValue()`](http://java.sun.com/javase/6/docs/api/java/lang/Number.html#doubleValue()):
```
double myNumber = nf.parse(myString).doubleValue();
```
Note that `parse()` will never return `null`, so this cannot cause a `NullPointerException`. Instead, `parse` throws a checked `ParseException` if it fails.
**Edit:** I originally said that there was another way to convert to `double`: cast the result to `Double` and use unboxing. I thought that since a general-purpose instance of `NumberFormat` was being used (per the Javadocs for [`getInstance`](http://java.sun.com/javase/6/docs/api/java/text/NumberFormat.html#getInstance(java.util.Locale))), it would always return a `Double`. But [DJClayworth](https://stackoverflow.com/users/19276/djclayworth) points out that the Javadocs for [`parse(String, ParsePosition)`](http://java.sun.com/javase/6/docs/api/java/text/NumberFormat.html#parse(java.lang.String,%20java.text.ParsePosition)) (which is called by `parse(String)`) say that a `Long` is returned if possible. Therefore, **casting the result to `Double` is unsafe and should not be tried!**
*Thanks, DJClayworth!* | NumberFormat is the way to go, but you should be aware of its peculiarities which crop up when your data is less than 100% correct.
I found the following usefull:
<http://www.ibm.com/developerworks/java/library/j-numberformat/index.html>
If your input can be trusted then you don't have to worry about it. | How do I convert a String to Double in Java using a specific locale? | [
"",
"java",
"localization",
""
] |
Let's call it "<<<"
```
int32variable <<< numberOfBits
```
equals
```
(int32variable << numberOfBits) | (int32variable >> (32 - numberOfBits))
```
(Assuming << and >> discards overflown bits)
There is such an operator? | That would be a called a bit rotate and C# does not have such an operator.
Here's an interesting post:
[Is there a way to perform a circular bit shift in C#?](https://stackoverflow.com/questions/35167/is-there-a-way-to-perform-a-circular-bit-shift-in-c)
Note that your int32integer should be of type `uint` (unsigned int).
I believe bit rotate is an instructions in the Intel instruction set but as far as I know the CLR does not have bit rotate instructions. | This is called a bitwise rotation. Other languages have it, but C# does not. See [this question](https://stackoverflow.com/questions/812022/c-bitwise-rotate-left-and-rotate-right) for a little more detail, but the gist of it is that your current approach is about as good as you can do. | Is there any C# bitwise shift operator that moves the overflown bits to the other tip of the variable? | [
"",
"c#",
".net",
"bit-shift",
""
] |
A particular class has a Hashtable containing 1..N elements. I'm wondering if there are generic getter/setter methods for the Hashtable used in a class. I'm looking to make the hashtable values behave more like regular object properties:
```
public class foo
{
private HashTable _stuff;
public HashTable stuff { get; set; }
public foo() {}
}
```
I was wondering if something like this can happen:
```
foo bar = new foo();
bar.stuff.name; //returns the data in the 'name' index if it exists
bar.stuff.name = "Me"; //sets the stuff[name] value = "me"
``` | There's nothing like that in the current version of C#. The dynamic stuff in C# 4.0 will make this easier.
In the meantime, why not just make Name (and other values) simple properties? While you're at it, you'll find the generic `Dictionary<K,V>` easier to work with than `HashTable`. | You can't do this with C#, at least not in the current version. What you'd need is the equivalent of method\_missing in ruby.
If this was C# 4.0 you could do something similar to this with anonymous types and the dynamic keyword, however you'd need to know the keys up front. | Hashtable "default" getter? | [
"",
"c#",
".net",
"asp.net-2.0",
""
] |
For an example, there is a set\_user function
$facebook->set\_user
but I typed in set\_user at the facebook developer wiki search box, it returns
'There is no page titled "set\_user"'
<http://wiki.developers.facebook.com/index.php/Special:Search?search=set_user&go=Go>
Where can I find the list of the functions and properties for the facebook object user object etc?
Many thanks. | The Developers wiki basically only documents the raw API. The official PHP library is a thin(-nish) wrapper around this API, and includes some minimal phpdoc documentation in its comments.
If you want to generate documentation for the library, you need a copy of [phpDocumentor](http://www.phpdoc.org/) (and the CLI version of PHP installed). Then you can run:
```
./phpdoc -t /path/to/write/documentation -o HTML:default:default -d /path/to/facebook-platform/php/
```
or in Windows:
```
php.exe "C:\Path\To\phpdoc" -t C:\Path\For\Documentation -o HTML:default:default -d C:\Path\To\facebook-platform\php
```
to generate some local HTML documentation. But like I say, it's pretty minimal, and there's not much benefit over just reading the documentation inline with the code. | I may have found what you are looking for. Check <http://wiki.developers.facebook.com/index.php/JS_API_T_FB.Facebook>
If you scroll down, you can view the whole namespace.
It took a lot of digging to find this. | Where can I find the facebook php class reference? | [
"",
"php",
"class",
"facebook",
""
] |
I am maintaining a project which uses inter-process COM with C++. At the top level of the callee functions there are try/catch statements directly before the return back through COM. The catch converts any C++ exceptions into custom error codes that are passed back to the caller through the COM layer.
For the purpose of debugging I want to disable this try/catch, and simply let the exception cause a crash in the callee process (as would normally happen with an uncaught C++ exception). Unfortunately for me the COM boundary seems to swallow these uncaught C++ exceptions and I don't get a crash.
**Is there a way to change this behaviour in COM? Ie, I want it to allow the uncaught C++ exception to cause a crash in the callee process.**
I want this to happen so that I can attach a debugger and see the context in which the exception is thrown. If I simply leave our try/catch in place, and breakpoint on the catch, then the stack has already unwound, and so this is too late for me.
The original "COM masters" who wrote this application are all either unavailable or can't remember enough details. | This just in, a year and a half after the question was asked -
Raymond Chen has written a post about "[How to turn off the exception handler that COM 'helpfully' wraps around your server](http://blogs.msdn.com/b/oldnewthing/archive/2011/01/20/10117963.aspx)". Seems like the ultimate answer to the question. If not for the OP, for future readers. | I don't think you can disable this behaviour, however there is a way around it if you are using Visual Studio and don't mind getting flooded in exceptions. If you go to Debug>Exceptions in VS and select "When the exception is thrown>Break into the Debugger" for C++ exceptions, it will drop into the debugger at the point the exception is thrown. Unfortunately you then get to work out which exceptions you can ignore and which ones are of interest to you.
The default setting for this is "Continue" with "If the exception is not handled" being set to "break into the debugger". If it doesn't do that already this would suggest that you'll have to find out exactly where the exceptions are being caught. | Can I stop COM from swallowing uncaught C++ exceptions in the callee process? | [
"",
"c++",
"exception",
"com",
""
] |
I have my MainApplication Window that launches a new Window with .ShowDialog() so that it is modal.
```
UploadWindow uploadWindow = new UploadWindow();
uploadWindow.ShowDialog();
```
Now users are often leaving this window open and it can get lost under other windows. When the MainApplication is clicked you get an error-like beep and are unable to interact with it, so the modal window is blocking properly as expected, but it would be nice if the modal window was focused at this point to show the user it was still open.
Currently it just looks as if the MainApplication window has locked up. | Try setting the dialog's owner:
```
var uploadWindow = new UploadWindow();
uploadWindow.Owner = this;
uploadWindow.ShowDialog();
``` | I have the problem, that I can't use this, if someone have the same problem, you can use
```
Window.GetWindow(this)
``` | How do I focus a modal WPF Window when the main application window is clicked | [
"",
"c#",
"wpf",
"window",
""
] |
I am following the quickstart guide for boost::spirit, and I get this compiler warning when I include : "This header is deprecated. Please use: boost/spirit/include/classic\_core.hpp" Should I be worried about this?
(quick start guide: <http://spirit.sourceforge.net/distrib/spirit_1_8_5/libs/spirit/doc/quick_start.html> , with full source of the program I am trying to compile here: <http://spirit.sourceforge.net/distrib/spirit_1_8_5/libs/spirit/example/fundamental/number_list.cpp>)
edit: Additionally, when I try to compile with the recommended classic\_core.hpp and classic\_push\_back\_actor.hpp headers, I get the following compiler errors:
```
test7.cpp: In function 'bool parse_numbers(const char*, __gnu_debug_def::vector<double, std::allocator<double> >&)':
test7.cpp:18: error: 'real_p' was not declared in this scope
test7.cpp:18: error: 'push_back_a' was not declared in this scope
test7.cpp:23: error: 'space_p' was not declared in this scope
test7.cpp:23: error: 'parse' was not declared in this scope
``` | [EDIT:] The original answer is badly out of date; in particular the link is broken. The current version of Boost (since 2012-02-24) is 1.49.0.
The warning mentioned is a result of `#include <boost/spirit.hpp>` which is a deprecated header; however old examples on the web use this form. To get started, try the [boost tutorials](http://www.boost.org/doc/libs/1_48_0/libs/spirit/doc/html/spirit/qi/tutorials.html). Once you see the correct includes and namespaces, most old examples can easily be converted.
[OLD ANSWER:]
You must be using boost 1.39 or later (via SVN). This presentation should help:
* <http://www.boostcon.com/site-media/var/sphene/sphwiki/attachment/2009/05/07/SpiritV2.pdf>
In short, there's a brand new way of doing thing and these are the namespaces to use:
* `boost::spirit:qi` (for the parser)
* `boost::spirit::karma` (for the generator lib)
The official release is 1.40 so probably by that time the doc will be updated.
EDIT: [the doc in the boost SVN repository](http://svn.boost.org/svn/boost/trunk/libs/spirit/doc/html/index.html) is being worked on and probably reflect the new architecture in a more faithful manner. | When you're including the classic headers the parsers are in the boost::spirit::classic namespace. Try:
> using namespace boost::spirit::classic; | boost spirit headers deprecated | [
"",
"c++",
"boost",
"boost-spirit",
""
] |
Why python compile the source to bytecode before interpreting?
Why not interpret from the source directly? | Nearly no interpreter really interprets code *directly*, line by line – it's simply too inefficient. Almost all interpreters use some intermediate representation which can be executed easily. Also, small optimizations can be performed on this intermediate code.
Python furthermore stores this code which has a huge advantage for the next time this code gets executed: Python doesn't have to parse the code anymore; parsing is the slowest part in the compile process. Thus, a bytecode representation reduces execution overhead quite substantially. | Because you can compile to a `.pyc` once and interpret from it many times.
So if you're running a script many times you only have the overhead of parsing the source code once. | Why python compile the source to bytecode before interpreting? | [
"",
"python",
"compiler-construction",
"interpreter",
"bytecode",
""
] |
Following is my JavaScript (mootools) code:
```
$('orderNowForm').addEvent('submit', function (event) {
event.preventDefault();
allFilled = false;
$$(".required").each(function (inp) {
if (inp.getValue() != '') {
allFilled = true;
}
});
if (!allFilled) {
$$(".errormsg").setStyle('display', '');
return;
} else {
$$('.defaultText').each(function (input) {
if (input.getValue() == input.getAttribute('title')) {
input.setAttribute('value', '');
}
});
}
this.send({
onSuccess: function () {
$('page_1_table').setStyle('display', 'none');
$('page_2_table').setStyle('display', 'none');
$('page_3_table').setStyle('display', '');
}
});
});
```
In all browsers except IE, this works fine. But in IE, this causes an error. I have IE8 so while using its JavaScript debugger, I found out that the `event` object does not have a `preventDefault` method which is causing the error and so the form is getting submitted. The method is supported in case of Firefox (which I found out using Firebug).
Any Help? | in IE, you can use
```
event.returnValue = false;
```
to achieve the same result.
And in order not to get an error, you can test for the existence of preventDefault:
```
if(event.preventDefault) event.preventDefault();
```
You can combine the two with:
```
event.preventDefault ? event.preventDefault() : (event.returnValue = false);
``` | If you bind the event through mootools' addEvent function your event handler will get a fixed (augmented) event passed as the parameter. It will always contain the preventDefault() method.
Try out this fiddle to see the difference in event binding.
<http://jsfiddle.net/pFqrY/8/>
```
// preventDefault always works
$("mootoolsbutton").addEvent('click', function(event) {
alert(typeof(event.preventDefault));
});
// preventDefault missing in IE
<button
id="htmlbutton"
onclick="alert(typeof(event.preventDefault));">
button</button>
```
For all **jQuery** users out there you can fix an event when needed. Say that you used HTML onclick=".." and get a IE specific event that lacks preventDefault(), just use this code to get it.
```
e = $.event.fix(e);
```
After that e.preventDefault(); works fine. | event.preventDefault() function not working in IE | [
"",
"javascript",
"internet-explorer",
"events",
"mootools",
"preventdefault",
""
] |
Is there a way to update every email address in MySQL with regexp? What I want to do is to change something@domain.xx addresses to something@domain.yy. Is it possible to do with SQL or should I do it with PHP for example?
Thanks! | You can search for a `REGEXP` with `MySQL`, but, unfortunately, it cannot return the matched part.
It's possible to do it with `SQL` as follows:
```
UPDATE mytable
SET email = REPLACE(email, '@domain.xx', '@domain.yy')
WHERE email REGEXP '@domain.xx$'
```
You can omit the `WHERE` clause, but it could lead to unexpected results (like `@example.xxx.com` will be replaced with `@example.yyx.com`), so it's better to leave it. | ```
UPDATE tableName
SET email = CONCAT(SUBSTRING(email, 1, locate('@',email)), 'domain.yy')
WHERE email REGEXP '@domain.xx$';
``` | Updating email addresses in MySQL (regexp?) | [
"",
"sql",
"mysql",
"regex",
""
] |
In my asp.net project, I have two strings (actually, they are stored in a Session object, then i do a .ToString() )
This project is part of my free Japanese language exercises on my website (Italian only for now, so i won't link/spam)
For now i do an `if (original == inputted.ToLower())` , but I would like to compare the strings and highlight the differences on the screen
like this:
original: hiroyashi
wrote by user: hiro**yo**shi
i was thinking to compare the two strings and save the differences in another variable, with HTML tags, and then show it on a Literal control... but... if the differences are many, or the input is shorter... how to do that?
It looks there is the needing of an huge amount of coding... or not? | I seem to remember someone asking this not too long ago, and essentially they were pointed at difference engines.
A quick search on codeplex brings up:
<http://www.codeplex.com/site/search?projectSearchText=diff>
May be worth a hunt through some of those that come up - you may be able to plug something into your existing code?
Cheers,
Terry | John Resig wrote a [javascript diff algorithm](http://ejohn.org/files/jsdiff.js), but he's removed the page explaining what it does from his site. It's still available through the [google cache](http://74.125.153.132/search?q=cache:mJ-TvGeQO4sJ:ejohn.org/projects/tags/diff/+site:ejohn.org+resig+javascript+diff&cd=15&hl=en&ct=clnk&gl=au) though. *Apologies if linking that is bad John*. It should do what you want, someone else took it, tweaked it and put an article up about it [here](http://blog.lotusnotes.be/domino/archive/2007-10-29-js-diff.html) - complete with a [test page](http://blog.lotusnotes.be/domino/js-diff.html) | C# - Show the differences when comparing strings | [
"",
"c#",
"asp.net",
"string",
""
] |
My SQL skills are rather limited and since I find myself working with a DB (Oracle) a lot lately I would like to get beyond the basic select statements.
I want to write queries that do things like get data from multiple tables, sum quantities, compare dates, group, filter etc.
What sites can you recommend for getting SQL reporting skills to a more advanced level? | Pick up Joe Celcko's [SQL For Smarties](https://rads.stackoverflow.com/amzn/click/com/1558605762). That's one of the definitive take-your-sql-to-the-next-level books. Otherwise, just keep writing queries.
Make sure you understand joins. Since the beginning of time, my SQL methodology has always been row-count driven - In other words, as I write a complicated query, I'm always #1 making sure it returns the correct number of rows. If your rowcount is correct, then your sums/groups/aggregates will all be correct. And they are VERY easy to mess up.
Make sure you understand the data. Make sure you understand keys and uniqueness so that you can enforce your joins.
You can also read [asktom.oracle.com](http://asktom.oracle.com) for a lot of really cool SQL trickery. [Laurent Schneider](http://laurentschneider.com/) is also very cutting-edge sql-wise. I wouldn't be half the DBA/Developer I am today had I not set asktom as my home page for the last 5-6 years.
Finally, make sure you understand set based operations. Think of the result set as a whole, not just a collection of rows. It'll click as you do it. This relates back to the row-count-driven methodology. | I know this isn't online, but it fits your bill to a T:
I would recommend picking up a copy of Anthony Mollinaro's [SQL Cookbook](http://oreilly.com/catalog/9780596009762/). It describes how to do lots of complicated things that go beyond the basic SELECT FROM WHERE . In a prev. life, when doing lots of queries for a prev. job, that book was my life saver and people borrowed that book a lot. It has lots of very clear examples, and they range from the simple (How to retrieve a subset of rows on a table) to the complex (using window functions to generate histograms).
It's not free, but the book will pay for itself rather quickly, and I imagine would answer most of the questions you would have. NOTE: I have no connection with O'Reilly or Mr. Mollinaro, I simply think this book is awesome and ridiculously helpful. | What is the best online SQL tutorial for learning to write complex reporting queries? | [
"",
"sql",
"oracle",
"reporting",
""
] |
I have a C library that needs a callback function to be registered to customize some processing. Type of the callback function is `int a(int *, int *)`.
I am writing C++ code similar to the following and try to register a C++ class function as the callback function:
```
class A {
public:
A();
~A();
int e(int *k, int *j);
};
A::A()
{
register_with_library(e)
}
int
A::e(int *k, int *e)
{
return 0;
}
A::~A()
{
}
```
The compiler throws following error:
```
In constructor 'A::A()',
error:
argument of type ‘int (A::)(int*, int*)’ does not match ‘int (*)(int*, int*)’.
```
My questions:
1. First of all is it possible to register a C++ class member function like I am trying to do and if so how?
(I read 32.8 at <http://www.parashift.com/c++-faq-lite/mixing-c-and-cpp.html>. But in my opinion it does not solve the problem)
2. Is there a alternate/better way to tackle this? | You can do that if the member function is static.
Non-static member functions of class A have an implicit first parameter of type `class A*` which corresponds to *this* pointer. That's why you could only register them if the signature of the callback also had the first parameter of `class A*` type. | You can also do this if the member function is not static, but it requires a bit more work (see also [Convert C++ function pointer to c function pointer](https://stackoverflow.com/questions/19808054/convert-c-function-pointer-to-c-function-pointer/19809787)):
```
#include <stdio.h>
#include <functional>
template <typename T>
struct Callback;
template <typename Ret, typename... Params>
struct Callback<Ret(Params...)> {
template <typename... Args>
static Ret callback(Args... args) {
return func(args...);
}
static std::function<Ret(Params...)> func;
};
template <typename Ret, typename... Params>
std::function<Ret(Params...)> Callback<Ret(Params...)>::func;
void register_with_library(int (*func)(int *k, int *e)) {
int x = 0, y = 1;
int o = func(&x, &y);
printf("Value: %i\n", o);
}
class A {
public:
A();
~A();
int e(int *k, int *j);
};
typedef int (*callback_t)(int*,int*);
A::A() {
Callback<int(int*,int*)>::func = std::bind(&A::e, this, std::placeholders::_1, std::placeholders::_2);
callback_t func = static_cast<callback_t>(Callback<int(int*,int*)>::callback);
register_with_library(func);
}
int A::e(int *k, int *j) {
return *k - *j;
}
A::~A() { }
int main() {
A a;
}
```
This example is complete in the sense that it compiles:
```
g++ test.cpp -std=c++11 -o test
```
You will need the `c++11` flag. In the code you see that `register_with_library(func)` is called, where `func` is a static function dynamically bound to the member function `e`. | Using a C++ class member function as a C callback function | [
"",
"c++",
"c",
"interop",
"callback",
""
] |
I've got this:
```
string cmd = " -i """ + finPath + """ -ar 44100 -ab 160k """ + foutPath + """";
```
and I need to pass it to command prompt from C# using `Systems.Diagnostics.Process`.
No combination seems to work. Program works just fine if I run it in command prompt.
Also runs just fine if I use the same string in VB.Net
`finPath` has spaces as does `foutPath` and it's making the program not run.
I need to have `finPath` expressed as `finPath`. Same with `foutPath`.
---
More of the code (used the line suggested here, no luck):
```
string inputPath = RootPath + "videoinput\\";
string ffmpegpath = RootPath + "ffmpeg.exe"; //ffmpeg path
string outputPath = RootPath +"videooutput\\";
//define new extension
string fileext = ".flv";
string newfilename = namenoextension + fileext;
string namenoextension = Path.GetFileNameWithoutExtension(savedfile);
string fileoutPath = outputPath + newfilename;
string fileinPath = "/videoinput/" + savedfile;
string cmd = " -i \"" + fileinPath + "\" -ar 44100 -ab 160k \"" + fileoutPath + "\"";
//Begin encoding process
Process proc = new Process();
proc.StartInfo.FileName = ffmpegpath;
proc.StartInfo.Arguments = cmd;
proc.StartInfo.UseShellExecute = true;
proc.StartInfo.CreateNoWindow = false;
proc.StartInfo.RedirectStandardOutput = false;
proc.Start();
``` | This should work for you:
```
string arguments = string.Format("-i \"{0}\" -ar 44100 -ab 160k \"{1}\"", finPath, foutPath);
Process.Start(thePathToExecutable, arguments);
```
Make sure to specify the executable's path separate from the command line arguments.
---
Edit in response to comments and question edit:
I just ran this in a console, using the following code:
```
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string RootPath = "C:\\";
string savedFile = "test.avi";
string inputPath = Path.Combine(RootPath, "videoinput");
string ffmpegpath = Path.Combine(RootPath, "ffmpeg.exe"); //ffmpeg path
string outputPath = Path.Combine(RootPath, "videooutput");
//define new extension
string fileext = ".flv";
string namenoextension = Path.GetFileNameWithoutExtension(savedFile);
string newfilename = namenoextension + fileext;
string fileoutPath = Path.Combine(outputPath, newfilename);
string fileinPath = Path.Combine(inputPath, savedFile);
string arguments = string.Format("-i \"{0}\" -ar 44100 -ab 160k \"{1}\"", fileinPath, fileoutPath);
Console.WriteLine(ffmpegpath);
Console.WriteLine(arguments);
Console.ReadKey();
}
}
```
This writes out:
```
C:\ffmpeg.exe
-i "C:\videoinput\test.avi" -ar 44100 -ab 160k "C:\videooutput\test.flv"
```
As I said - if you do it this way, it should work. That being said, I'd recommend reading up on the [System.IO.Path](http://msdn.microsoft.com/en-us/library/system.io.path.aspx) class, and use Path.Combine(), Path.GetFullPath(), etc, to fix your input files. This may help you correct part of your issue, as well. | The documentation for [CommandLineToArgvW](http://msdn.microsoft.com/en-us/library/bb776391(VS.85).aspx) describes how the arguments are parsed. Interpreting this:
1. Any argument that contains whitespace should be surrounded in
outer quotes.
2. Any inner quotes in the argument should be preceded by
backslashes.
3. Backslashes (or sequences of backslashes) that precede
a quote should be doubled up.
The following class can be used to achieve these results:
```
/// <summary>
/// Provides helper functionality for working with Windows process command-lines.
/// </summary>
public static class WindowsCommandLineHelper
{
/// <summary>
/// Performs escaping and quoting of arguments where necessary to
/// build up a command-line suitable for use with the
/// <see cref="System.Diagnostics.Process.Start(string,string)" /> method.
/// </summary>
/// <param name="arguments">The arguments to be included on the command-line.</param>
/// <returns>The resulting command-line.</returns>
public static string FormatCommandLine(params string[] arguments)
{
return string.Join(" ", arguments.Select(GetQuotedArgument));
}
private static string GetQuotedArgument(string argument)
{
// The argument is processed in reverse character order.
// Any quotes (except the outer quotes) are escaped with backslash.
// Any sequences of backslashes preceding a quote (including outer quotes) are doubled in length.
var resultBuilder = new StringBuilder();
var outerQuotesRequired = HasWhitespace(argument);
var precedingQuote = false;
if (outerQuotesRequired)
{
resultBuilder.Append('"');
precedingQuote = true;
}
for (var index = argument.Length - 1; index >= 0; index--)
{
var @char = argument[index];
resultBuilder.Append(@char);
if (@char == '"')
{
precedingQuote = true;
resultBuilder.Append('\\');
}
else if (@char == '\\' && precedingQuote)
{
resultBuilder.Append('\\');
}
else
{
precedingQuote = false;
}
}
if (outerQuotesRequired)
{
resultBuilder.Append('"');
}
return Reverse(resultBuilder.ToString());
}
private static bool HasWhitespace(string text)
{
return text.Any(char.IsWhiteSpace);
}
private static string Reverse(string text)
{
return new string(text.Reverse().ToArray());
}
}
```
For the command line described in this question, you'd call it like this:
```
string commandLine = WindowsCommandLineHelper.FormatCommandLine(
"-i", finPath, "-ar", "44100", "-ab", "160k", foutPath);
Process.Start(exePath, commandLine);
```
**UPDATE**
There is more interesting information along these lines in [this blog post](https://blogs.msdn.microsoft.com/twistylittlepassagesallalike/2011/04/23/everyone-quotes-command-line-arguments-the-wrong-way/), and a [C# implementation here](https://github.com/natemcmaster/CommandLineUtils/blob/master/src/CommandLineUtils/Utilities/ArgumentEscaper.cs). | Problems launching a process with Process.Start() - how do I construct the argument list? | [
"",
"c#",
"string",
""
] |
I'd like to know your thoughts about HTML code generation in my JS code.
I just think that the `html.push("<tag>" + something + "</tag>")` style pretty annoying.
I've already tried something with templates inside my HTML file (and put some placeholders therein), and then used its content to a replace the placeholders to my real values.
But maybe you guys have other ideas, possibly one using jQuery. | jQuery has javascript template plugins like [jBind](http://plugins.jquery.com/project/jBind) and [jTemplate](http://plugins.jquery.com/project/jTemplates). I haven't used them myself but I do recommend jQuery whenever possible.
A note on html generation, it is not searchable by search engines in most cases. | jQuery is the way to go. You can do things like this:
```
// create some HTML
var mySpan = $("<span/>").append("Something").addClass("highlight");
```
* it is cross-browser compatible,
* it is an easy to use syntax
There is also a [templating plugin](http://plugins.jquery.com/project/jquerytemplate). | HTML generation in JS code | [
"",
"javascript",
""
] |
I'm loading an SWF movie into an HTML page using [SWFObject](http://code.google.com/p/swfobject/). I want to resize this SWF dynamically. How can SWFObject help? I'm sure I don't have to [write my own](http://www.mustardlab.com/developer/flash/objectresize/) solution. | The easiest solution is to embed the SWF within a container div, then use JavaScript and CSS to dynamically resize the container DIV. If the SWF is set to 100% width/height, it will stretch to fit the wrapper whenever the wrapper is resized.
In the body:
```
<div id="wrapper">
<div id="flash">This div will be replaced by an object via SWFObject</div>
</div>
```
In the head:
```
<script>
var flashvars = {};
var params = { scale: "exactFit" };
var attributes = {};
swfobject.embedSWF("myContent.swf", "flash", "100%", "100%", "9.0.0","expressInstall.swf", flashvars, params, attributes);
</script>
<style type="text/css">
#flash {
display: block;
width: 100%;
height: 100%;
}
</style>
```
Now whenever you resize #wrapper, the SWF will scale to fill it. | Check out [swffit](http://swffit.millermedeiros.com/), it should fit the bill perfectly. | Resize an SWF when loading it with SWFObject | [
"",
"javascript",
"html",
"flash",
"swfobject",
""
] |
The related questions that appear after entering the title, and those that are in the right side bar when viewing a question seem to suggest very apt questions.
Stack Overflow only does a SQL search for it and uses no special algorithms, said Spolsky in a talk.
What algorithms exist to give good answers in such a case.
How do U do database search in such a case? Make the title searchable and search on the keywords or search on tags and those questions with many votes on top? | The related questions sidebar will be building on the tags for each question (probably by ranking them based on tag overlap, so 5 tags in common > 4 tags in common etc).
The rest will be building on heuristics and algorithms suitable for natural language processing. These aren't normally very good in general purpose language, but most of them are VERY good once the vocabulary is reduced down to a single technical area such as programming. | If you listen to the [Stack Overflow podcast 32](https://blog.stackoverflow.com/2008/12/podcast-32/) (unfortunately the transcript doesn't have much in) you can hear Jeff Atwood say a little about how he does it.
It seems like the algorithm is something like:
* Take the question
* Remove the most common words in English (from a list he got from google)
* submit a full text search to the SQL server 2008 full text search engine
More details about the full text search can be found here: <http://msdn.microsoft.com/en-us/library/ms142571.aspx>
This may be out of date by now - they were talking about moving to a better/faster full text search such as [Lucene](http://lucene.apache.org/java/docs/), and I vaguely remember Jeff saying in the podcast that this had been done. | Stack Overflow Related questions algorithm | [
"",
"sql",
"search",
"full-text-search",
"nlp",
""
] |
I'm having trouble understanding why java secure coding is important. For example, why is it important to declare variables private? I mean I get that it will make it impossible to access those variables from outside the class, but I could simply decompile the class to get the value.
Similarly, defining a class as final will make it impossible to subclass this class. When would subclassing a class be dangerous for security? Again if necessary, I could decompile the original class and reimplement it with whatever malicious code I could want.
Does the problem come when applications are "trusted" by the user? And people could then abuse this trust somehow?
Basically what I'm looking for is a good example as to why secure coding guidelines should be followed. | Programming is hard.
If you define strict APIs, that don't expose variables that are not supposed to be exposed (we like to call this [encapsulation](http://en.wikipedia.org/wiki/Encapsulation_%28computer_science%29)), you help users of your APIs, and thus make programming easier. This is considered a good thing.
The reasons are not primarily "security", as in keeping secret things secret, as much as clarity, simplicity, and understandability.
As a bonus, it's far easier to make things work correctly if you can know that the user of the API is not changing "your" variables behind your back, of course. | It is "secure" meaning that a class internal working are hidden to whoever uses it.
The term secure is not used as in "securing a server" is used to intend the fact that a user of one class does not have to worry about how the class will perform the task he wants it to.
Taking your example:
Exposing variables of a class would let the user of your class know of their existance, which is something you don't want, for example: you just press a button to turn on the light, you don't need to now that inside there is copper or whater it needs to perform the task. | Why is java secure coding important? | [
"",
"java",
"encapsulation",
"security",
""
] |
I have a C# console application that logs a lot to the console (using `Trace`). Some of the stuff it logs is the compressed representation of a network message (so a lot of that is rendered as funky non-alphabetic characters).
I'm getting system beeps every so often while the application is running. Is it possible that some "text" I am writing to the console is causing them?
(By system beep, I mean from the low-tech speaker inside the PC case, not any kind of Windows sound scheme WAV)
---
If so, is there any way to disable it for my application? I want to be able to output any possible text without the it being interpreted as a sound request. | If you don't want if to beep, you'll either have to replace the 0x7 character before outputting it, or disable the "Beep" device driver, which you'll find in the Non-Plug and Play Drivers section, visible if you turn on the Show Hidden Devices option. Or take the speaker out. | That's usually caused by outputting character code 7, CTRL-G, which is the BEL (bell) character.
The first thing I normally do when buying a new computer or motherboard is to ensure the wire from the motherboard to the speaker is not connected. I haven't used the speaker since the days of Commander Keen (and removing that wire is the best OS-agnostic way of stopping the sound :-). | Windows - Can console output inadvertently cause a system beep? | [
"",
"c#",
".net",
"windows",
"console",
"beep",
""
] |
When I try to add constraints to my tables I get the error:
> Introducing FOREIGN KEY constraint 'FK74988DB24B3C886' on table 'Employee' may cause cycles or multiple cascade paths. Specify ON DELETE NO ACTION or ON UPDATE NO ACTION, or modify other FOREIGN KEY constraints.
My constraint is between a `Code` table and an `employee` table. The `Code` table contains `Id`, `Name`, `FriendlyName`, `Type` and a `Value`. The `employee` has a number of fields that reference codes, so that there can be a reference for each type of code.
How can I set the fields to null if the code that is referenced is deleted? | SQL Server does simple counting of cascade paths and, rather than trying to work out whether any cycles actually exist, it assumes the worst and refuses to create the referential actions (CASCADE): you can and should still create the constraints without the referential actions. If you can't alter your design (or doing so would compromise things) then you should consider using triggers as a last resort.
FWIW resolving cascade paths is a complex problem. Other SQL products will simply ignore the problem and allow you to create cycles, in which case it will be a race to see which will overwrite the value last, probably to the ignorance of the designer (e.g. ACE/Jet does this). I understand some SQL products will attempt to resolve simple cases. Fact remains, SQL Server doesn't even try, plays it ultra safe by disallowing more than one path and at least it tells you so.
Microsoft themselves [advises](https://support.microsoft.com/en-us/help/321843/error-message-1785-occurs-when-you-create-a-foreign-key-constraint-tha) the use of triggers instead of FK constraints. | A typical situation with multiple cascasing paths will be this:
A master table with two details, let's say "Master" and "Detail1" and "Detail2". Both details are cascade delete. So far no problems. But what if both details have a one-to-many-relation with some other table (say "SomeOtherTable"). SomeOtherTable has a Detail1ID-column AND a Detail2ID-column.
```
Master { ID, masterfields }
Detail1 { ID, MasterID, detail1fields }
Detail2 { ID, MasterID, detail2fields }
SomeOtherTable {ID, Detail1ID, Detail2ID, someothertablefields }
```
In other words: some of the records in SomeOtherTable are linked with Detail1-records and some of the records in SomeOtherTable are linked with Detail2 records. Even if it is guaranteed that SomeOtherTable-records never belong to both Details, it is now impossible to make SomeOhterTable's records cascade delete for both details, because there are multiple cascading paths from Master to SomeOtherTable (one via Detail1 and one via Detail2).
Now you may already have understood this. Here is a possible solution:
```
Master { ID, masterfields }
DetailMain { ID, MasterID }
Detail1 { DetailMainID, detail1fields }
Detail2 { DetailMainID, detail2fields }
SomeOtherTable {ID, DetailMainID, someothertablefields }
```
All ID fields are key-fields and auto-increment. The crux lies in the DetailMainId fields of the Detail tables. These fields are both key and referential contraint. It is now possible to cascade delete everything by only deleting master-records. The downside is that for each detail1-record AND for each detail2 record, there must also be a DetailMain-record (which is actually created first to get the correct and unique id). | Foreign key constraint may cause cycles or multiple cascade paths? | [
"",
"sql",
"sql-server",
"constraints",
""
] |
I'm trying to get hold of Django. I use Pydev on Eclipse. I have written a simple signup page that I can't get to work. Eclipse complains that User.DoesNotExist is undefined. Most likely, I am missing something trivial. Here's the relevant portion of the code:
```
from django.contrib.auth.models import User
...
class SignUpForm (forms.Form):
...
def clean_username (self):
try:
User.objects.get(username=self.cleaned_data['username'])
except User.DoesNotExist:
return self.cleaned_data['username']
raise forms.ValidationError(USERNAME_ALREADY_IN_USE)
...
``` | The problem is really with PyDev, not your code. What you have done is absolutely correct, but IDEs will always have difficulty resolving attributes in a dynamic language like Python. In the case of the DoesNotExist exception, it is added via a `__metaclass__` rather than through normal object inheritance, so PyDev is unlikely to be able to find it. However, it should definitely work. | I just discovered Pydev actually has a nice workaround for this.
Go to **Window** > **Preferences**, then **Pydev** > **Editor** > **Code Analysis**.
Click the **Undefined** tab and add "DoesNotExist" to the text box titled **Consider the following names as globals**. | Django -- User.DoesNotExist does not exist? | [
"",
"python",
"django",
"authentication",
"django-models",
"pydev",
""
] |
I need to create a file that embeds an image as text within some records. I'm having some trouble writing the images as text. What I'm doing is gathering the image as a byte array from a SQL database (image type) then I'm writing that image to a text file by going through each byte and writing that byte's ASCII equivalent to the file.
Before I can write that image to a text file, I must convert it to a TIFF (it was formerly a jpeg) in CCITT4 format. To double check that this is being done correctly, I also save the stream as a TIFF and view it in "AsTiffTagViewer," which shows that the compression is correct. I AM able to view the tiff in a proper viewer; however, when gathering the text from the file, I am unable to view the image.
Here's the code:
```
byte[] frontImage = (byte[])imageReader["front_image"];
MemoryStream frontMS = new MemoryStream(frontImage);
Image front = Image.FromStream(frontMS);
Bitmap frontBitmap = new Bitmap(front);
Bitmap bwFront = ConvertToBitonal(frontBitmap);
bwFront.SetResolution(200, 200);
MemoryStream newFrontMS = new MemoryStream();
bwFront.Save(newFrontMS, ici, ep);
bwFront.Save("c:\\Users\\aarong\\Desktop\\C#DepositFiles\\" + checkReader["image_id"].ToString() + "f.tiff", ici, ep);
frontImage = newFrontMS.ToArray();
String frontBinary = toASCII(frontImage);
private String toASCII(byte[] image)
{
String returnValue = "";
foreach (byte imageByte in image)
{
returnValue += Convert.ToChar(imageByte);
}
return returnValue;
}
```
It is frontBinary that's being written to the file. Does anyone have an idea as to what is wrong? The tiff that's saved is correct, yet the exact same byte array, when written as ASCII text, is not being written correctly.
Thank you.
**EDIT** This issue has been corrected by using a BinaryWriter(byte[]) to correctly write the images as text. Thank you all for your help! | Well ASCII is only seven-bit, for one thing. However, I don't believe your code actually uses ASCII. It sort of uses ISO-8859-1, implicitly.
*Never* treat text as binary or vice versa. It will *always* lead to problems.
The best way of converting binary to ASCII text is to use Base64:
```
string text = Convert.ToBase64String(frontImage);
byte[] data = Convert.FromBaseString(text);
```
Also note that if your code *did* work, it would still be painfully inefficient - read up on [StringBuilders](http://pobox.com/~skeet/csharp/stringbuilder.html) and then consider that your code is semi-equivalent to
```
Encoding.GetEncoding(28591).GetString(data);
```
However, base64 is definitely the way to go to convert between text and binary data losslessly. You'll need to convert it back to binary in order to view the TIFF again, of course.
Note that you haven't shown how you're saving or loading your data - you may have problems there too. In fact, I suspect that if you were able to save the string accurately, you *might* have been lucky and preserved the data, depending on exactly what you're doing with it... but go with base64 anyway. | One approach to taking binary data and converting it to text data is to use a StreamReader and provide the desired encoding. Like Jon mentioned above it is unwise to use ASCII, but in case any one DOES want to stream binary to some other text encoding, here is some code to do it.
```
public static String GetString(System.IO.Stream inStream)
{
string str = string.Empty;
using (StreamReader reader = new StreamReader(inStream, System.Text.ASCIIEncoding.ASCII)) // or any other encoding.
{
str = reader.ReadToEnd();
}
return str;
}
``` | Writing an image to a text file as binary data C# | [
"",
"c#",
"image",
"stream",
""
] |
I'm dealing with unknown data and trying to insert into a MySQL database using Python/Django. I'm getting some errors that I don't quite understand and am looking for some help. Here is the error.
```
Incorrect string value: '\xEF\xBF\xBDs m...'
```
My guess is that the string is not being properly converted to unicode? Here is my code for unicode conversion.
```
s = unicode(content, "utf-8", errors="replace")
```
Without the above unicode conversion, the error I get is
```
'utf8' codec can't decode byte 0x92 in position 31: unexpected code byte. You passed in 'Fabulous home on one of Decatur\x92s most
```
Any help is appreciated! | What is the original encoding? I'm assuming "cp1252", from [pixelbeat's](https://stackoverflow.com/questions/873419/converting-to-safe-unicode-in-python/873450#873450) answer. In that case, you can do
```
>>> orig # Byte string, encoded in cp1252
'Fabulous home on one of Decatur\x92s most'
>>> uni = orig.decode('cp1252')
>>> uni # Unicode string
u'Fabulous home on one of Decatur\u2019s most'
>>> s = uni.encode('utf8')
>>> s # Correct byte string encoded in utf-8
'Fabulous home on one of Decatur\xe2\x80\x99s most'
``` | 0x92 is right single curly quote in windows cp1252 encoding.
\xEF\xBF\xBD is the UTF8 encoding of the unicode replacement character
(which was inserted instead of the erroneous cp1252 character).
So it looks like your database is not accepting the valid UTF8 data?
2 options:
1. Perhaps you should be using unicode(content,"cp1252")
2. If you want to insert UTF-8 into the DB, then you'll need to config it appropriately. I'll leave that answer to others more knowledgeable | Converting to safe unicode in python | [
"",
"python",
"django",
"unicode",
""
] |
How can I change the default filter choice from 'ALL'? I have a field named as `status` which has three values: `activate`, `pending` and `rejected`. When I use `list_filter` in Django admin, the filter is by default set to 'All' but I want to set it to pending by default. | ```
class MyModelAdmin(admin.ModelAdmin):
def changelist_view(self, request, extra_context=None):
if not request.GET.has_key('decommissioned__exact'):
q = request.GET.copy()
q['decommissioned__exact'] = 'N'
request.GET = q
request.META['QUERY_STRING'] = request.GET.urlencode()
return super(MyModelAdmin,self).changelist_view(request, extra_context=extra_context)
``` | In order to achieve this *and* have a usable 'All' link in your sidebar (ie one that shows all rather than showing pending), you'd need to create a custom list filter, inheriting from `django.contrib.admin.filters.SimpleListFilter` and filtering on 'pending' by default. Something along these lines should work:
```
from datetime import date
from django.utils.translation import ugettext_lazy as _
from django.contrib.admin import SimpleListFilter
class StatusFilter(SimpleListFilter):
title = _('Status')
parameter_name = 'status'
def lookups(self, request, model_admin):
return (
(None, _('Pending')),
('activate', _('Activate')),
('rejected', _('Rejected')),
('all', _('All')),
)
def choices(self, cl):
for lookup, title in self.lookup_choices:
yield {
'selected': self.value() == lookup,
'query_string': cl.get_query_string({
self.parameter_name: lookup,
}, []),
'display': title,
}
def queryset(self, request, queryset):
if self.value() in ('activate', 'rejected'):
return queryset.filter(status=self.value())
elif self.value() == None:
return queryset.filter(status='pending')
class Admin(admin.ModelAdmin):
list_filter = [StatusFilter]
```
EDIT: Requires Django 1.4 (thanks Simon) | Default filter in Django admin | [
"",
"python",
"django",
"django-admin",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.