Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
Can anyone give me a hand with a touch of regex?
I'm reading in a list of "locations" for a simple text adventure (those so popular back in the day). However, I'm unsure as to how to obtain the input.
The locations all follow the format:
```
<location_name>, [<item>]
[direction, location_name]
```
Such as:
```
Albus Square, Flowers, Traffic Cone
NORTH, Franklandclaw Lecture Theatre
WEST, Library of Enchanted Books
SOUTH, Furnesspuff College
Library of Enchanted Books
EAST, Albus Square
UP, Reading Room
```
(Subsequent locations are separated by a blank line.)
I'm storing these as Location objects with the structure:
```
public class Location {
private String name;
private Map<Direction, Location> links;
private List<Item> items;
}
```
I use a method to retrieve the data from a URL and create the Location objects from the read text, but I'm at a complete block as to do this. I think regex would be of help. Can anyone lend me a well-needed hand? | Agree w/ willcodejavaforfood, regex could be used but isn't a big boost here.
Sounds like you just need a little algorithm help (sloppy p-code follows)...
```
currloc = null
while( line from file )
if line begins w/ whitespace
(dir, loc) = split( line, ", " )
add dir, loc to currloc
else
newlocdata = split( line, ", " )
currloc = newlocdata[0]
for i = 1 to size( newlocdata ) - 1
item = newlocdata[i]
add item to currloc
``` | You don't want to use a text-only format for this:
* What happens when you have more than a single flower item? Are they all the same? Can't an adventurer collect a bouqet at by picking single flowers at several locations?
* There will probably be several rooms with the same name ("cellar", "street corner"), i.e. filler rooms which add to the atmosphere but nothing to the game. They don't get a description of their own, though. How to keep them apart?
* What if a name contains a comma?
* Eventually, you'll want to use Unicode for foreign names or formatting instructions.
Since this is structured data which can contain lots of odd cases, I suggest to use XML for this:
```
<locations>
<location>
<name>Albus Square</name>
<summary>Short description for returning adventurer</summary>
<description>Long text here ... with formatting, etc.</description>
<items>
<item>Flowers</item>
<item>Traffic Cone</item>
<items>
<directions>
<north>Franklandclaw Lecture Theatre</north>
<west>Library of Enchanted Books</west>
<south>Furnesspuff College</south>
</directions>
</location>
<location>
<name>Library of Enchanted Books</name>
<directions>
<east>Albus Square</east>
<up>Reading Room</up>
</directions>
</location>
</locations>
```
This allows for much greater flexibility, solves a lot of issues like formatting description text, Unicode characters, etc. plus you can use more than a single item/location with the same name by using IDs (numbers) instead of text.
Use [JDom](http://www.jdom.org/) or [DecentXML](http://code.google.com/p/decentxml/) to parse the game config. | Regex for Parsing Simple Text-Based Datafile | [
"",
"java",
"regex",
"parsing",
"adventure",
""
] |
I have a bit of an architecture problem here. Say I have two tables, **Teacher** and **Student**, both of them on separate servers. Since this tables share a lot of data and functionality, I would like to use [this inheritance scheme](http://www.sqlteam.com/article/implementing-table-inheritance-in-sql-server) and create a **People** table; however, I would need tho keep the **Teacher** table and the **People** records relating **Teacher** in one server, and the **Student** table and the **People** records relating **Student** in another server. This was a requirement made by the lead developer, since we have too many (and I mean too many) records for **Teacher** and **Student**, and a single database containing all of the People would collapse. Moreover, the clients **NEED** to have them on separate servers (sigh\*).
I would really like to implement the inheritance scheme, since a lot of the funcionality could be shared among the databases. Is there any possible way to do this? any other architecture that may suit this type of problem? I'm I just crazy?
--- EDIT ---
Ok, I don't really have Teachers and Students per se, I just used those names to simplify my explanation. Truth is, there are about 9 sub-tables that would inherit the super table, all of them in separate servers for separate applications, and no, I don't have [this](http://www.wintercorp.com/VLDB/2005%5FTopTen%5FSurvey/TopTenWinners%5F2005.asp) type of database, but we have pretty low end servers for the amount of transactions we have ;). You're right, my statements are a bit exagerated and I apologize for that, it was just to make you guys answer faster (sorry :P). The different servers are more of a business restriction than anything else (although the lead developer DID say that a common database to store the SuperTable would collapse under it's own weight -his words, not mine :S). Our clients don't like their information mixed with other clients information, so we must have their information on different servers -pretty stupid, but the decision-makers have spoken :(. | I think Paul is correct - perhaps look at your hardware infrastructure rather than your DB schema.
Using clustering, proper indexing, and possibly a data archive scheme *should* solve any performance problems. The inheritance scheme seems to be the best data model.
It is possible to split the data over multiple servers and keep the scheme, but I think you'd definitely have more performance problems than if you looked at clustering/proper indexing. By setting up linked servers you can do cross-server queries.
e.g. Students query
```
SELECT *
FROM SERVER_A.People.dbo.Persons P
INNER JOIN SERVER_B.People.dbo.Students S
ON P.PersonID = S.PersonID
```
--EDIT-- As Paul said, you could perform your database separation in your abstraction layer.
E.g. have your Student class extend your Person class. In your Person class constructor, have it connect to Server A to populate whichever fields are available. In your student class constructor, have it connect to Server B (the Person attributes will already be populated by the Person constructor). | Under what assumption did you determine that you have too much data? I'm pretty sure you could list every teacher and student in the world, and not cause SQL Server any grief.
This seems like an arbitrary decision that is going to have significant impact on the complexity of any solution you design.
Take a look [here](http://www.wintercorp.com/VLDB/2005_TopTen_Survey/TopTenWinners_2005.asp) - I'm sure you don't measure your database in anything close to the scale represented on this page, and many of these db's are running on SQL Server. | (hard question) how can I store specific rows of a table in a different sql server? | [
"",
"sql",
"sql-server",
"replication",
""
] |
I need to create a script where someone will post an opening for a position, and anyone who is eligible will see the opening but anyone who is not (or opts out) will not see the opening. So two people could go to the same page and see different content, some potentially the same, some totally unique. I'm not sure the best way to arrange that data in a MySQL DB/table.
For instance, I could have it arranged by the posting, but that would look sort of like:
```
PostID VisibleTo
PostingA user1,user2
```
And that seems wrong (the CSV style in the column). Or I could go with by person:
```
User VisiblePosts
```
user1 posting1, posting2
But it's the same problem. Is there a way to make the user's unique, the posting unique, and have them join only where they match?
The decision is initially made by doing a series of queries to another set of tables, but once that is run, it seems inefficient to have that some chunk of code run again and again when it won't change after the user posts the position.
...On second thought, it MIGHT change, but if we assume it doesn't (as it is unlikely, and as little consequence if a user sees something that they are no longer eligible for), is there a standard solution for this scenario? | This is a many-to-many relationship or n:m relationship.
You would create an additional table, say `PostVisibility`, with a column `PostID` and `UserID`. If a combination of `PostID` and `UserID` is present in the table, that post is visible to that user. | Three tables...
User:
[UserId]
[OtherField]
Post:
[PostId]
[OtherFields]
UserPost:
[UserId]
[PostId]
User.UserId Joins to UserPost.UserId,
Post.PostId Joins to UserPost.PostId
Then look up the table UserPost, joining to Post when you are selecting which posts to show | Recommended Table Set up for one to many/many to one situation | [
"",
"sql",
"architecture",
"one-to-many",
""
] |
I'm doing the exercises in Stroustrup's new book ["Programming Principles and Practice Using C++"](http://www.stroustrup.com/Programming/) and was wondering if anyone on Stack Overflow has done them and is willing to share the knowledge?
Specifically about the calculator that's developed in Chap 6 and 7. For example, the questions about adding the `!` operator and sqrt(), pow(), etc. I have done these, but I don't know if the solution I have is the "good" way of doing things, and there are no published solutions on Bjarne's website. I'd like to know if I am going down the right track. Maybe we can make a wiki for the exercises?
Basically I have a token parser. It reads a char at a time from cin. It's meant to tokenise expressions like 5\*3+1 and it works great for that. One of the exercises is to add a sqrt() function. So I modified the tokenising code to detect "sqrt(" and then return a Token object representing sqrt. In this case I use the char 's'. Is this how others would do it? What if I need to implement sin()? The case statement would get messy.
```
char ch;
cin >> ch; // Note that >> skips whitespace (space, newline, tab, etc.)
switch (ch) {
case ';': // For "print"
case 'q': // For "quit"
case '(':
case ')':
case '+':
case '-':
case '*':
case '/':
case '!':
return Token(ch); // Let each character represent itself
case '.':
case '0': case '1': case '2': case '3': case '4':
case '5': case '6': case '7': case '8': case '9':
{
cin.putback(ch); // Put digit back into the input stream
double val;
cin >> val; // Read a floating-point number
return Token('8', val); // Let '8' represent "a number"
}
case 's':
{
char q, r, t, br;
cin >> q >> r >> t >> br;
if (q == 'q' && r == 'r' && t == 't' && br == '(') {
cin.putback('('); // Put back the bracket
return Token('s'); // Let 's' represent sqrt
}
}
default:
error("Bad token");
}
``` | 1. There are a few solutions posted on [Stroustrup - Programming](http://www.stroustrup.com/Programming/) and more will be coming over time.
2. Try solving exercises only with the language features and the library facilities presented so far in the book -- real novice users can't do anything else. Then return later to see how a solution can be improved. | I thought a map of strings to function pointers might be a concise way to represent things like sqrt, sin, cos, etc. that take a single double and return a double:
```
map<std::string, double (*)(double)> funcs;
funcs["sqrt"] = &sqrt;
funcs["sin"] = &sin;
funcs["cos"] = &cos;
```
Then when the parser detects a correct string (str) it can call the function with an argument (`arg`) like so:
```
double result = funcs[str](arg);
```
With this method, a single call can handle all cases of functions (of that type).
Actually I'm not sure if that's the correct syntax, can anyone confirm?
Does this seem like a usable method? | Adding the ! operator and sqrt(), pow(), etc. to a calculator example application | [
"",
"c++",
""
] |
While doing some random experimentation with a factorial program in C, Python and Scheme. I came across this fact:
In C, using 'unsigned long long' data type, the largest factorial I can print is of 65. which is '9223372036854775808' that is 19 digits as specified [here](http://en.wikipedia.org/wiki/Integer_(computer_science)#Common_integral_data_types).
In Python, I can find the factorial of a number as large as 999 which consists of a large number of digits, much more than 19.
How does CPython achieve this? Does it use a data type like '[octaword](http://en.wikipedia.org/wiki/Integer_(computer_science)#Common_integral_data_types)' ?
I might be missing some fundamental facts here. So, I would appreciate some insights and/or references to read. Thanks!
UPDATE: Thank you all for the explanation. Does that means, CPython is using the GNU Multi-precision library (or some other similar library)?
UPDATE 2: I am looking for Python's 'bignum' implementation in the sources. Where exactly it is? Its here at <http://svn.python.org/view/python/trunk/Objects/longobject.c?view=markup>. Thanks Baishampayan. | It's called *Arbitrary Precision Arithmetic*. There's more here: <http://en.wikipedia.org/wiki/Arbitrary-precision_arithmetic> | Looking at the Python source code, it seems the `long` type (at least in pre-Python 3 code) is defined in [longintrepr.h](http://svn.python.org/view/python/trunk/Include/longintrepr.h?view=markup) like this -
```
/* Long integer representation.
The absolute value of a number is equal to
SUM(for i=0 through abs(ob_size)-1) ob_digit[i] * 2**(SHIFT*i)
Negative numbers are represented with ob_size < 0;
zero is represented by ob_size == 0.
In a normalized number, ob_digit[abs(ob_size)-1] (the most significant
digit) is never zero. Also, in all cases, for all valid i,
0 <= ob_digit[i] <= MASK.
The allocation function takes care of allocating extra memory
so that ob_digit[0] ... ob_digit[abs(ob_size)-1] are actually available.
CAUTION: Generic code manipulating subtypes of PyVarObject has to
aware that longs abuse ob_size's sign bit.
*/
struct _longobject {
PyObject_VAR_HEAD
digit ob_digit[1];
};
```
The actual usable interface of the `long` type is then defined in [longobject.h](http://svn.python.org/view/python/trunk/Include/longobject.h?view=markup) by creating a new type PyLongObject like this -
```
typedef struct _longobject PyLongObject;
```
And so on.
There is more stuff happening inside [longobject.c](http://svn.python.org/view/python/trunk/Objects/longobject.c?view=markup), you can take a look at those for more details. | How do languages such as Python overcome C's Integral data limits? | [
"",
"python",
"c",
"types",
"integer",
""
] |
What are your opinions on how disposable objects are implemented in .Net? And how do you solve the repetitiveness of implementing IDisposable classes?
I feel that IDisposable types are not the first-class citizens that they should've been. Too much is left to the mercy of the developer.
Specifically, I wonder if there should'nt have been better support in the languages and tools to make sure that disposable things are both implemented correctly and properly disposed of.
In C# for instance, what if my class that needs to implement the disposable semantics could be declared like this:
```
public class disposable MyDisposableThing
{
~MyDisposableThing()
{
// Dispose managed resources
}
}
```
The compiler could in this case easily generate an implementation of the IDisposable interface. The destructor ~MyDisposableThing could be transformed into the actual Dispose method that should release managed resources.
The intermediate C# code would look like this:
```
public class MyDisposableThing : IDisposable
{
private void MyDisposableThingDestructor()
{
// Dispose my managed resources
}
~MyDisposableThing()
{
DisposeMe(false);
}
public void Dispose()
{
DisposeMe(true);
GC.SuppressFinalize(this);
}
private bool _disposed;
private void DisposeMe(bool disposing)
{
if (!_disposed)
{
if (disposing)
{
// Call the userdefined "destructor"
MyDisposableThingDestructor();
}
}
_disposed = true;
}
}
```
This would make for much cleaner code, less boilerplate disposing code, and a consistent way of disposing managed resources. Implementing IDisposable by hand would still be supported for edge cases and unmanaged resources.
Ensuring that instances are properly disposed is another challenge. Consider the following code:
```
private string ReadFile(string filename)
{
var reader = new StreamReader();
return reader.ReadToEnd(filename);
}
```
The reader variable never outlives the scope of the method but would have to wait for the GC to dispose it. In this case, the compiler could raise an error that the StreamReader object was not explicitly disposed. This error would prompt the developer to wrap it in a using statement:
```
private string ReadFile(string filename)
{
using (var reader = new StreamReader())
{
return reader.ReadToEnd(filename);
}
}
``` | An oft-stated principle is that "design patterns are needed to address language deficiencies". This is an example of that principle. We need the disposable pattern because the language doesn't give it to you.
I agree that disposability *could* have been elevated out of the "pattern" world and into the C# language proper, as we did with, say, property getters and setters (which are standardizations of the pattern of having getter and setter methods), or events (which standardize the idea of storing a delegate and calling it when something interesting happens.)
But language design is expensive and there is a finite amount of effort that can be applied to it. Thus we try to find the most useful, compelling patterns to put into the language proper. And we try to find a way that does so in a way that is not merely convenient, but actually adds more expressive power to the language. LINQ, for example, moves the concepts of filtering, projecting, joining, grouping and ordering data into the language proper, which adds a lot of expressive power to the language.
Though this is certainly a good idea, I don't think it meets the bar. It would be a nice convenience, I agree, but it doesn't enable any really rich new scenarios. | In addition to the other answers, there is the problem of how much should this implement and what should people expect from it? Say I declared my class like this:
```
public disposable class MyClass
{
readonly AnotherDisposableObject resource = new AnotherDisposableObject();
~MyClass()
{
this.resource.Dispose();
}
public void DoStuff()
{
this.resource.SomeMethod();
}
}
```
Then what would you expect to happen if a caller called `DoStuff` *after* the instance had been disposed? Should the compiler automatically insert something like
```
if (this.disposed) throw new ObjectDisposedException();
```
at the start of every method because you have declared the class as disposable?
If so then what about cases where methods are explicitly allowed to be called after an object is disposed (e.g. [MemoryStream.GetBuffer](http://msdn.microsoft.com/en-us/library/system.io.memorystream.getbuffer.aspx))? Would you have to introduce a new keyword that indicated this to the compiler, e.g. `public useafterdispose void ...`?
If not then how do you explain to people that the new keyword implements some of the boiler-plate code for you, but that they still need to write code to check whether the object is disposed in each method? Moreover, how *can* they even check this, because all the state information about whether the object has been disposed is auto-generated! Now they need to track their own flag in the `~MyClass` method which undoes half the work the compiler should be doing for you.
I think as a specific language pattern there are too many holes in the concept, and it only attempts to solve one specific problem. Now what *could* solve this entire class of problem in a general-purpose fashion is mixins (i.e. a Disposable mixin) and this language feature would be generally reusable for different concepts (e.g. Equatable mixin, Comparable mixin, etc.). That's where my money would go. | Consider a "disposable" keyword in C# | [
"",
"c#",
"design-patterns",
"language-features",
"idisposable",
""
] |
As I write code in Python and suddenly feel like adding a new block in front of the code I have already written... the indentation of the complete code is affected...
It is a very tedious process to move to each line and change the indentation...is there a way to do auto indent or something?
For example:
```
def somefunction:
x =5
return x
```
If I want to add a control block
For example:
```
def somefunction:
if True:
x =5
return x
return 0
```
this small change of adding a control block took a lot of tab work...
Is there a shortcut or something to do this easily? | I don't know what wacky planets everyone is coming from, but in most editors that don't date back to the stone age, indenting blocks of code typically only requires that a block of text be selected and Tab be pressed. On the flip side, Shift+Tab usually UNdents the block.
This is true for Visual Studio, Notepad2, e, Textmate, Slickedit, #Develop, etc. etc. etc.
If you're not doing large multi-file projects, I strongly recommend [Notepad2](http://www.flos-freeware.ch/notepad2.html). Its a very lightweight, free, easy-to-use notepad replacement with just enough code-centric features (line numbers, indentation guides, code highlighting, etc.) | In the Idle editor, you can just select the lines you want to indent and hit Tab.
I should note that this doesn't actually insert any tabs into your source, just spaces. | Indentation in a Python GUI | [
"",
"python",
"user-interface",
"indentation",
""
] |
I need to import some ANSI C code into a project I'm working on. For reasons I prefer not to go into, I want to refactor the code to C# rather than trying to wrap the original code. It will take me perhaps a couple of days to do the work by hand, but before I start, is there an automated tool that can get me most of the way there? I'm a cheapskate and the work I'm doing is pro bono, so free tools only please. | If manual refactoring is "only" going to take a few days, that would get my vote. Depending on what the C code is doing and how it is written (pointers, custom libraries, etc.) an automated converter may just make a mess. And untangling that mess could be a larger task than just converting by hand. | Setting up, cleaning up, refactoring, and just plain making converted code (if there is even a converter available) would probably be something in the magnitude of weeks or months, so you'll be better served just to go ahead with the manual rewrite. | Is there a tool to convert ANSI C code to C#? | [
"",
"c#",
"c",
""
] |
Is there a fast way (without having to explicitly looping through each character in a string) and either stripping or keeping it. In Visual FoxPro, there is a function CHRTRAN() that does it great. Its on a 1:1 character replacement, but if no character in the alternate position, its stripped from the final string. Ex
CHRTRAN( "This will be a test", "it", "X" )
will return
"ThXs wXll be a es"
Notice the original "i" is converted to "X", and lower case "t" is stripped out.
I looked at the replace for similar intent, but did not see an option to replace with nothing.
I'm looking to make some generic routines to validate multiple origins of data that have different types of input restrictions. Some of the data may be coming from external sources, so its not just textbox entry validation I need to test for.
Thanks | Here was my final function and works perfectly as expected.
```
public static String ChrTran(String ToBeCleaned,
String ChangeThese,
String IntoThese)
{
String CurRepl = String.Empty;
for (int lnI = 0; lnI < ChangeThese.Length; lnI++)
{
if (lnI < IntoThese.Length)
CurRepl = IntoThese.Substring(lnI, 1);
else
CurRepl = String.Empty;
ToBeCleaned = ToBeCleaned.Replace(ChangeThese.Substring(lnI, 1), CurRepl);
}
return ToBeCleaned;
}
``` | All you need is a couple of calls to [String.Replace()](http://msdn.microsoft.com/en-us/library/system.string.replace.aspx).
```
string s = "This will be a test";
s = s.Replace("i", "X");
s = s.Replace("t", "");
```
Note that Replace() *returns* a new string. It does not alter the string itself. | C# Stripping / converting one or more characters | [
"",
"c#",
"parsing",
"character",
"strip",
""
] |
I know the naming convention for class methods in C# is to begin with a capital letter and each new word is a capital letter (e.g. GetDeviceName).
So my question is why when I create a form, place a control on it, then double click the control (for the method to be created automatically for me by the IDE) I get a method begining with a non-capital letter ? (e.g. **s**electButton\_Click(object sender, EventArgs e) ) | The naming convention for event handlers of controls have always been `controlName_EventName`, so basically, it reuses your own naming convention for the control, and then tucks on the name of the event.
This might be contrary to the general naming standard, but it has always been this way.
The upshot of this, is that tools like [GhostDoc](http://www.roland-weigelt.de/ghostdoc/) can recognize this format, and thus generate documentation that, while still generic, is more to the point, than if it were to try to deduce the purpose of the method by itself.
For instance, the "controlName\_EventName" method could be documented like this:
```
/// <summary>
/// Handles the EventName event of the controlName control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.EventArgs"/> instance
/// containing the event data.</param>
protected void controlName_EventName(object sender, EventArgs e)
{
```
instead of more like this (since GhostDoc handles the above, I'm ad libbing here based on experience with bad method names):
```
/// <summary>
/// Control names the event name.
/// </summary>
/// <param name="sender">The sender.</param>
/// <param name="e">The e.</param>
protected void controlName_EventName(object sender, EventArgs e)
{
``` | It doesn't strictly break the .Net naming convention because the guidelines only apply to **public** methods. However you could consider it breaking the spirit of the guidelines. | Why does visual studio break the naming convention for methods in C#? | [
"",
"c#",
"visual-studio",
"naming-conventions",
""
] |
Apparently `boost::asio::async_read` doesn't like strings, as the only overload of `boost::asio::buffer` allows me to create `const_buffer`s, so I'm stuck with reading everything into a streambuf.
Now I want to copy the contents of the streambuf into a string, but it apparently only supports writing to char\* (`sgetn()`), creating an istream with the streambuf and using `getline()`.
Is there any other way to create a string with the streambufs contents without excessive copying? | I mostly don't like answers that say "You don't want X, you want Y instead and here's how to do Y" but in this instance I'm pretty sure I know what tstenner wanted.
In Boost 1.66, the [dynamic string buffer](https://www.boost.org/doc/libs/1_66_0/doc/html/boost_asio/reference/dynamic_string_buffer.html) type was added so `async_read` can directly resize and write to a string buffer. | I don't know whether it counts as "*excessive copying*", but you can use a stringstream:
```
std::ostringstream ss;
ss << someStreamBuf;
std::string s = ss.str();
```
Like, to read everything from stdin into a string, do
```
std::ostringstream ss;
ss << std::cin.rdbuf();
std::string s = ss.str();
```
Alternatively, you may also use a `istreambuf_iterator`. You will have to measure whether this or the above way is faster - i don't know.
```
std::string s((istreambuf_iterator<char>(someStreamBuf)),
istreambuf_iterator<char>());
```
Note that `someStreamBuf` above is meant to represent a `streambuf*`, so take its address as appropriate. Also note the additional parentheses around the first argument in the last example, so that it doesn't interpret it as a function declaration returning a string and taking an iterator and another function pointer ("most vexing parse"). | Copy a streambuf's contents to a string | [
"",
"c++",
"string",
"boost",
"boost-asio",
"streambuf",
""
] |
I just designed a simple "For Loop" using window form application. I would like that this will be only clickable once & that it will not repeat the same information if I click the button. How could I do that? thanks
Here is my code:
```
int count;
for (count = 0; count < 5; count = count + 1)
{
listBox1.Items.Add("This is count: " + count);
}
const string textEnd = "Done!!!";
{
listBox1.Items.Add(textEnd);
}
```
==== Additional Info ===
I've made it this way now. This will only click once, but the button is still enable. I think this is ok:
```
int count;
for (count = 0; count < 5; count++)
{
string newItem = "This is count: " + count;
if (listBox1.Items.IndexOf(newItem) < 0)
{
listBox1.Items.Add(newItem);
}
}
const string textEnd = "Done!!!";
if (listBox1.Items.IndexOf(textEnd) <0)
{
listBox1.Items.Add(textEnd);
}
``` | I'm assuming you don't want the same items added to the list multiple times?
Instead of
```
{
listBox1.Items.Add("This is count: " + count);
}
```
You need something like
```
{
string newItem = "This is count: " + count;
if(listBox1.Items.IndexOf(newItem) < 0)
{
listBox1.Items.Add(newItem);
}
}
``` | ```
button1.Enabled = false;
``` | for loop in window forms applications | [
"",
"c#",
"for-loop",
""
] |
I was looking at an [answer to an SO question today where the variable names are ua, rv, etc](https://stackoverflow.com/questions/917252/how-to-detect-if-a-user-is-running-ie-6/917257#917257). And I thought, "Man, when will people learn to use full-size variable names, memory is not a problem any more" but then, **it is Javascript** so it has to come across the wire and perhaps long variable names even slow down interpretation.
Is using short variable names in Javascript premature optimization?
While I'm here, are there any libraries for Rails or PHP that will compress Javscript on the fly, so I can keep my Javascript with long names on the server? | The only reason to use short variable names in JS is to save bytes over the wire. However, developing like that is ridiculous. Do they write JS without whitespace, too? There are tools which optimize finished JS. [Crockford's](http://www.crockford.com/javascript/jsmin.html) is one of the most popular (though it does not shorten variable names). I can't recall offhand one that does obfuscate/shorten variable names, but they do exist and it's not that hard to write one, either. [Google Closure](http://code.google.com/closure/compiler/) is a very impressive JavaScript *compiler* that turns this:
```
var myFunction = function(arg1, arg2) {
var foo = getValue(arg2);
for(var count = 0; count < arg1.length; count++) {
alert(foo);
}
};
```
into this:
```
function a(b,c){var d=e(c);for(var f=0;f<b.length;f++){alert(d)}}
``` | Dont use short variable names for optimization, during development. That would severely decrease readability. Compress your JS/CSS files at compile/deploy time, using something like [YUI Compressor](http://developer.yahoo.com/yui/compressor/). | Two-letter Variable Names in Javascript? | [
"",
"javascript",
"optimization",
""
] |
Has anyone managed to get a custom IMessageInterpolator working to
enable customisation of error messages. I have tried following the
instructions on this web page but to no avail.
<http://codelog.climens.net/2009/03/04/nhibernate-validator-custom-messages/>
Looking into the code the DefaultMessageInterpolator seems pretty
baked into the framework so is there anything I am missing.
I have included my unit tests to show how I am implementing it.
```
namespace TestValidator
{
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestValidator()
{
var customer = new Customer();
ClassValidator classValidator = new ClassValidator(customer.GetType());
InvalidValue[] validationMessages = classValidator.GetInvalidValues(customer);
Assert.IsTrue(validationMessages.Length == 1);
Assert.IsTrue(validationMessages[0].Message == "may not be null or empty");
}
[TestMethod]
public void TestCustomInterpolator()
{
ValidatorEngine ve = new ValidatorEngine();
NHVConfiguration nhvc = new NHVConfiguration();
nhvc.Properties[Environment.MessageInterpolatorClass] = typeof(CustomMessageInterpolator).AssemblyQualifiedName;
ve.Configure(nhvc);
var customer = new Customer();
ClassValidator classValidator = new ClassValidator(customer.GetType());
InvalidValue[] validationMessages = classValidator.GetInvalidValues(customer);
Assert.IsTrue(validationMessages.Length == 1);
// THIS TEST FAILS!!
Assert.IsTrue(validationMessages[0].Message == "CustomMessageInterpolator");
}
}
public class Customer
{
public virtual int CustomerId { get; set; }
[NotNullNotEmpty]
public string CustomerName { get; set; }
}
public class CustomMessageInterpolator : IMessageInterpolator
{
public CustomMessageInterpolator()
{
}
public string Interpolate(string message, IValidator validator, IMessageInterpolator defaultInterpolator)
{
return "CustomMessageInterpolator";
}
}
}
``` | I have got this to work finally. Before calling the validator in my repository I explicitly create and pass the Interpolator as a parameter.
```
ClassValidator classValidator = new ClassValidator(obj.GetType(), null, new CustomMessageInterpolator(),
CultureInfo.CurrentCulture, ValidatorMode.UseAttribute);
InvalidValue[] validationMessages = classValidator.GetInvalidValues(obj);
``` | I looked over your problem and the most interesting is that:
```
Assert.AreEqual(typeof(CustomMessageInterpolator), ve.Interpolator.GetType());
```
is true. I assume the problem is in the fact that CFG was already configured with DefaultMessageInterpolator, and the
```
ve.Configure(nhvc);
```
does not have the effect, because ClassValidator uses nomatter of this configuration the DefaultMessageInterpolator. This is the cause why for Climens, it worked in App.config, not in nhvalidator.cfg.xml. | nHibernate Validator custom IMessageInterpolator | [
"",
"c#",
"nhibernate",
"validation",
""
] |
i need to know how can i connect telephone using php languages | If you refer to the [Windows "TAPI" interface](http://msdn.microsoft.com/en-us/library/ms734273(VS.85).aspx), have a look at the [w32api PHP extension](http://www.php.net/w32api), which allows to call Win32 API functions from PHP. | AFAIK you cannot use php to connect through telephone lines. PHP is a scripting language. You can try out [Asterisk](http://www.asterisk.org/). There are [questions](https://stackoverflow.com/questions/tagged/asterisk) about Asterisk dev in SO | Can i use telephone api in PHP? | [
"",
"php",
""
] |
I have an UPDATE statement that's intended to update a status field for a limited number of records. Here's the statement:
```
UPDATE warehouse_box
SET warehouse_box_status_id = wbsv.warehouse_box_status_id
FROM
warehouse_box_status_vw wbsv INNER JOIN
pallet_warehouse_box pwb ON wbsv.warehouse_box_id = pwb.warehouse_box_id INNER JOIN
routing_shipment_pallet rsp ON pwb.pallet_id = rsp.pallet_id
WHERE
rsp.date_removed IS NULL
AND pwb.date_unpalletized IS NULL
AND rsp.routing_shipment_id = 100002
```
The intended result is for the 6 records that match the WHERE clause to have their statuses updated. What I'm seeing though is that all 200,000+ records are updated. It's as though the WHERE clause is being completely ignored.
Can anyone help shed some light on this for me? | You do not have the table warehouse\_box included in the FROM clause. If you add warehouse\_box and join it to warehouse\_box\_status it should solve your problem. | You don't appear to be selecting on `warehouse_box` in the `WHERE` and `INNER JOIN`s -- only from other tables... | Why is this UPDATE statement updating every record? | [
"",
"sql",
"sql-update",
""
] |
I was originally using SQLCE first starting with LINQ to SQL and then moved to Entity Framework, but it seems that SQLCE is too inflexible. (Right now I can't even drop a table to recreate it because it says I can't remove PrimaryKeyA because it is being referenced by PrimaryKeyA... so I don't have much confidence in being able to modify it later)
I need flexibility in that the app is going to be released over many iterations and data needs to be able to change fairly easily. Newer versions of the app need to be able to read data from older versions, either directly or through a conversion.
It needs to be light-weight to deploy, under 10MB, but preferable under 5. The user will (should) not be modifying the data outside the app, and they don't need to know or care how the data's stored.
High performance isn't an issue, it's just going to be a single user's data. Right now I'm tempted to say just go with XML to leverage LINQ to XML. But I'm wondering if there's any other suggestions. I'd like something that's easily translatable to and from normal objects, would XML serialization work for this?
I guess what I'm looking for is an easy way to persist objects that can be easily updated to new versions with object changes. Performance isn't a huge issue but it should be at least tolerable for a small/medium amount of data. (Basically an electronic form of a cook book for a single user's recipes) | I would suggest that XML route you are considering might be a reasonable idea. While more verbose than binary serialization, it's more easily debuggable if need be; and compresses nicely (on-the-fly) if less disk usage is needed. | There's always binary serialization to a file. It's not sexy, but it works, and it doesn't require any third party tools or software. Just make sure you precede **every** data grouping with a version number (usually referred to as a Schema number). That will alleviate headaches down the road when you change the data model.
In an OOP setup typically every object that needs to be persisted has a Serialize() method that takes a direction parameter (saving vs. loading) and an object that represents the binary file. When writing out you just need to make sure that every object gets serialized out. When reading in you need to create the objects as you go. This process is often made easier by a container that knows how to serialize the object in and out.
Conversion is handled on the fly by the various Serialize() methods. For example, if an object that is currently on Schema version 5 encounters data that was written using Schema version 4 it will know how to handle that.
However, if you need SQL like querying capabilities this may not be your best option. This works best when you are going to read in all of the data.
**EXAMPLE:**
Say you a class Foo that has 2 member variables you want to serialize:
```
class Foo
{
public:
const unsigned int SCHEMA = 1;
int i;
double d;
void Serialize(bool bSaving, CBinaryFile file)
{
if (bSaving)
{
// Serialize everything out
file << SCHEMA << i << d;
}
else
{
// Read in the schema number first
unsigned int nSchema;
file >> nSchema;
// Validate the schema number
if (nSchema > SCHEMA)
{
// We're reading in data that was written with a newer version of the program
// Since we don't know how to handle that let's error out
throw exception;
}
// Read everything in
file >> i >> d;
}
}
}
```
Now let's say in a year you add another member to Foo. You would handle it like this:
```
class Foo
{
public:
const unsigned int SCHEMA = 2;
int i;
double d;
string s;
void Serialize(bool bSaving, CBinaryFile file)
{
if (bSaving)
{
// Serialize everything out
file << SCHEMA << i << d << s;
}
else
{
// Read in the schema number first
unsigned int nSchema;
file >> nSchema;
// Validate the schema number
if (nSchema > SCHEMA)
{
// We're reading in data that was written with a newer version of the program
// Since we don't know how to handle that let's error out
throw exception;
}
// Read everything in
file >> i >> d;
if (nSchema > 1)
file >> s;
}
}
}
```
As long as you wrap everything in Schema numbers on the fly conversion is straight forward. | Light-weight flexible data persistence options | [
"",
"c#",
"persistence",
""
] |
I am attempting to re-implement the Copy behavior for a QTextEdit object. The custom context menu I create works as expected when the 'Copy' button is clicked, but `Ctrl` + `C` isn't being handled correctly. Since the context menu doesn't have any issues, I'll omit that portion of the code.
```
// Create a text edit box for text editing
QTextEdit text_edit_box = new QTextEdit(getBaseWidget());
text_edit_copy_action = new QAction(QString("Copy"), getBaseWidget());
text_edit_copy_action->setShortcut(QKeySequence::Copy);
// Add custom copy action to the text edit box to ensure Ctrl+C uses our copy
// implementation
text_edit_box->addAction(text_edit_copy_action);
```
When I set the shortcut to be an unused key combination (e.g., `Ctrl` + `Q`) it works fine. It seems `Ctrl` + `C` is being handled differently since it's "built in". | Copy is not virtual so this might be problematic. Copying is handled via the private text control API, and is not easily accessible. The best approach is probably to install an event handler for the text edit and intercept the copy key event before it's delivered to the text control processEvent handler - which should allow your own action to correctly trigger. | It might be simpler to derive from `QTextEdit` and reimplement [`QTextEdit::copy()`](http://doc.qtsoftware.com/4.5/qtextedit.html#copy), depending on what the new behaviour is. | How can I redefine a built in keyboard shortcut's behavior? | [
"",
"c++",
"qt",
"keyboard-shortcuts",
""
] |
If I have some xml containing things like the following mediawiki markup:
> " ...collected in the 12th century, of which [[Alexander the Great]] was the
> hero, and in which he was represented,
> somewhat like the British [[King
> Arthur|Arthur]]"
what would be the appropriate arguments to something like:
`re.findall([[__?__]], article_entry)`
I am stumbling a bit on escaping the double square brackets, and getting the proper link for text like: `[[Alexander of Paris|poet named Alexander]]` | Here is an example
```
import re
pattern = re.compile(r"\[\[([\w \|]+)\]\]")
text = "blah blah [[Alexander of Paris|poet named Alexander]] bldfkas"
results = pattern.findall(text)
output = []
for link in results:
output.append(link.split("|")[0])
# outputs ['Alexander of Paris']
```
Version 2, puts more into the regex, but as a result, changes the output:
```
import re
pattern = re.compile(r"\[\[([\w ]+)(\|[\w ]+)?\]\]")
text = "[[a|b]] fdkjf [[c|d]] fjdsj [[efg]]"
results = pattern.findall(text)
# outputs [('a', '|b'), ('c', '|d'), ('efg', '')]
print [link[0] for link in results]
# outputs ['a', 'c', 'efg']
```
Version 3, if you only want the link without the title.
```
pattern = re.compile(r"\[\[([\w ]+)(?:\|[\w ]+)?\]\]")
text = "[[a|b]] fdkjf [[c|d]] fjdsj [[efg]]"
results = pattern.findall(text)
# outputs ['a', 'c', 'efg']
``` | **RegExp:** \w+( \w+)+(?=]])
**input**
[[Alexander of Paris|poet named Alexander]]
**output**
poet named Alexander
**input**
[[Alexander of Paris]]
**output**
Alexander of Paris | Python regex for finding contents of MediaWiki markup links | [
"",
"python",
"regex",
"mediawiki",
""
] |
I have about 20 check boxes. When the user selects these and then uses an **alternate** submit button, I need to change the name of the name/value pair, for the selected inputs.
Why does this function only change the name of *every other* selected input?
```
function sub_d()
{
for (i = 0; i < document.checks.OGname.length; i++) //for all check boxes
{
if (document.checks.OGname[i].checked == true)
{
document.checks.OGname[i].name="newname"; //change name of input
}
}
document.checks.submit();
}
```
The output:
```
newname
'105'
OGname
'106'
newname
'107'
OGname
'108'
newname
'109'
OGname
'110'
``` | By renaming the first element of the list you have reduced the length of the list by one and deleted the first element. Next time through the loop the previous second element is now the first, and the second is the old third.
I'm no javascript expert, but something along the lines of this might work.
```
function sub_d()
{
i=0;
while (document.checks.OGname.length > i)
{
if (document.checks.OGname[i].checked="true")
{
document.checks.OGname[i].name="newname";
}else{
i++;
}
}
document.checks.submit();
}
```
As I said, no warranty or guarantee. | Would be great if you provide a more detailed description of your scenario, but I wish that my answer be useful.
```
function sub_d()
{
for (i = 0; i < document.checks.OGname.length; i++) //for all check boxes
{
if (document.checks.OGname[i].type == 'CHECKBOX')
if (document.checks.OGname[i].checked)
{
document.checks.OGname[i].name="newname"; //change name of input
}
}
document.checks.submit();
}
```
I usually manage dom collections in this way: (I don't know if is the best way)
```
function sub_d()
{
var theInputs = document.checks.getElementsByTagName('input');
for (var i = 0; i < theInputs.length; i++)
{
if (theInputs[i].type == 'CHECKBOX')
if (theInputs[i].checked)
{
theInputs[i].name="newname";
}
}
document.checks.submit();
}
``` | How do I change the name of multiple selected html values? | [
"",
"javascript",
"html",
"dom",
"dom-events",
""
] |
I would like the height\*width of a remote image. Could that be done with Curl, and if so how? | The height and width of an image are attributes inside the image file and you need to retieve the file to be able to access them. Depending on the image format, this attributes will be in diferent places of the image metadata. You can do this with getimagesize, but bear in mind that you are actually retrieving the full image, which will affect the performance of your operation.
In the event of a large image, you can try something like start fecthing the image to your server and, as soon as you start receiving data and know the format of the image, wait until you receive enough from the image to look at the height and width information and stop the transfer. You will most likely need to do this job yourself, as image libraries and built in functions in APIs will probably expect a full image to work properly.
If by chance you control the server where the images are, you are better of writting a small script hosted in that server that given an image file identifier returns the height and width for that image. | [getimagesize()](http://www.php.net/manual/en/function.getimagesize.php) is the function you want.
It should be able to download a remote image and analyze it.
Edit: As a more direct answer to your question, Curl cannot analyze an image directly, but it can certainly fetch it for you, in which case you can then use the GD library to analyze it. getimagesize() manages to do the fetching as well though, so you can leave Curl out of the equation. | Get image dimensions with Curl | [
"",
"php",
"curl",
""
] |
I have a C++ DLL with code like this:
```
LogMessage( "Hello world" );
try {
throw new int;
} catch( int* e ) {
LogMessage( "Caught exception" );
delete e;
}
LogMessage( "Done" );
```
This DLL is loaded by some third-party application and the code above is invoked. The problem is only the first `LogMessage` is invoked - even though there's an exception handler the control flow is transferred to the unknown.
I see this and can't decide whether it's some obscure bug to be investigated or just the evil force of the consumer application.
Is it really possible for a consumer application to override the C++ exception handling in a DLL?
EDIT: The problem resolved after thinking on all things to check outlined in the answers. In real code it's not just *throw*, there'a a special function for throwing exceptions that has a call to MessageBoxW() Win32 call in debug version. And the consumer application had troubles showing the message box (it's an NT service) and effectively hung up. So it's not a problem of C++ exceptions handling in any way. | The code looks OK to me, but I'd be tempted to put a few more catch clauses in to see if it's hitting one of the other ones. Namely, I'd put in:
```
catch (const std::exception &ex) {
... log exception ...
}
catch (...) {
... log exception ..
}
```
I would expect that it'll either hit the pointer catch (even if that's really not a good idea, see the link that Igor Oks provided) or the std::exception in case it can't allocated the memory. That said, it should hit one of the three catch clauses so there is no way for the exception to escape the DLL.
I'd also change the object thrown to a value type (even if it is int) and update the catch clause accordingly to see if you get changed behaviour that way. | The code is OK. I executed it with this function:
```
void LogMessage( char* s )
{
cout << s << endl;
}
```
And got the correct output:
> Hello world
>
> Caught exception
>
> Done
Is it possible that there is some problem with your *LogMessage* function?
I would suggest to investigate (by debugger or adding debug prints), whether your flows reaches the try block, and whether it reaches the catch block.
Not being a problem, it still isn't clear, what do you achieve by throwing a pointer and not a value. I would recommend not to use catch-by-pointer, see the reasoning [here](http://www.parashift.com/c++-faq-lite/exceptions.html#faq-17.8), at the C++-FAQ-lite. | Is it possible for a library consumer to override C++ exceptions handling? | [
"",
"c++",
"windows",
"exception",
"service",
"messagebox",
""
] |
The newspaper for the Computer Science-line at my school (called [readme](http://img.abakus.no/readme-pdf/readme0903_tilweb.pdf), it's norwegian, page 19) had a fun competition to write the shortest possible Java-code for the following problem.
> Take in an integer (as a string in the first entry of a string array, since the Java main method only takes a string array) as an argument, and write out first all numbers below this number that are primes, and then all numbers that are not primes. The shortest code wins!
As an answer, I will post the shortest Java-code that won the competition. I wonder if the Stack Overflow Community can make a code that is shorter If you know Norwegian, you will see that you could've won a bottle of champagne if you had done it, but unfortunately the last submit date of the competition is over.
How would you have solved this problem? | I was already doing it in Haskell before you changed the title to "Java". Since this is a community wiki, here it is anyway.
```
primes n =
let sieve (p:xs) = p : sieve [x | x<-xs, x `mod` p /= 0] in
let primes = takeWhile (<n) $ sieve [2..] in
([0..n] \\ primes, primes)
*Main> primes 20
([0,1,4,6,8,9,10,12,14,15,16,18,20],[2,3,5,7,11,13,17,19])
```
**(edit:)** Shortening names and removing whitespace makes it 79 chars:
```
p n=let s(p:xs)=p:s[x|x<-xs,x`mod`p/=0];r=takeWhile(<n)$s[2..]in(r,[0..n-1]\\r)
```
here also the resulting pair's order is swapped, and `n-1` is used, as per the spec.
Using sub-optimal trial division brings it down to **50 chars**:
```
p n=partition(\k->all((>0).rem k)[2..k-1])[2..n-1]
``` | The Java-code that won the competition (153 bytes without spacing, spacing included here for readability):
```
class F {
public static void main(String[] a) {
for (int i, j, k = 2; k-- > 0;)
for (i = 1; i++ < new Long(a[0]);) {
for (j = i; i % --j > 0;)
;
if (k > 0 ? j < 2 : j > 1)
System.out.println(i);
}
}
}
``` | Shortest-code for prime-calculation | [
"",
"java",
"primes",
"code-golf",
""
] |
I am studying events in C# but there are not much articles or information that show me where or what kinda position I'd need to use events in.
Could some one give me real world example that makes them more understandable.
Thanks in advance. | As Chris Gray said, one use is to signal when something has happened that your code didn't directly call. The most common cause here is probably user actions on the GUI. Another example might be an asynchronous operation completing on another thread.
The other reason to use events is when you don't know who might be interested in what has just happened. The class raising the event doesn't need to know (at design time) anything about how many instances of what other classes might be interested.
```
class Raiser {
public DoSomething() {
//Do something long winded.
OnDidSomething(new DidSomethingEventArgs());
}
public EventHandler<DidSomethingEventArgs> DidSomething;
private OnDidSomething(DidSomethingEventArgs e) {
if (DidSomething != null)
DidSomething(this, e);
}
}
```
Obviously, you also need to define the DidSomethingEventArgs class which passes on the relevant data about the event. This also illustrates a common naming convention for events. If the event is called X, then the event is only ever raised in a method called OnX and any data it passes on is an instance of class XEventArgs. Note that an event can be null if no listeners are subscribed to it, hence the check just before we raise the event.
Note that this class knows nothing about what other classes might be interested in the fact that it did something. It simply announces the fact that it has done it.
Multiple classes can then listen out for the event:
```
class ListenerA {
private Raiser r;
ListenerA(Raiser r) {
this.r = r;
r.DidSomething += R_DidSomething;
}
R_DidSomething(object sender, DidSomethingEventArgs e) {
//Do something with the result.
}
}
```
And:
```
class ListenerB {
private Raiser r;
ListenerB(Raiser r) {
this.r = r;
r.DidSomething += R_DidSomething;
}
R_DidSomething(object sender, DidSomethingEventArgs e) {
//Do something with the result.
}
}
```
Now, when the DoSomething method is called on the Raiser instance, all instances of ListenerA and ListenerB will be informed via the DidSomething event. Note that the listener classes could easily be in different assemblies to the raiser. They need a reference back to the raiser's assembly but it doesn't need a reference to its listeners' assemblies.
Note that the above simple Raiser example may cause you some problems in a multi-threaded program. A more robust example would use something like:
```
class Raiser {
public DoSomething() {
//Do something long winded.
OnDidSomething(new DidSomethingEventArgs());
}
#region DidSomething Event
private object _DidSomethingLock = new object();
private EventHandler<DidSomethingEventArgs> _DidSomething;
public EventHandler<DidSomethingEventArgs> DidSomething {
add { lock(_DidSomethinglock) _DidSomething += value; }
remove { lock(_DidSomethinglock) _DidSomething -= value; }
}
OnDidSomething(DidSomethingEventArgs e) {
EventHandler<DidSomethingEventArgs> handler;
lock (_DidSomethingLock)
handler = _DidSomething;
if (handler == null)
return;
try {
DidSomething(this, e);
} catch (Exception ex) {
//Do something with the exception
}
}
#endregion
}
```
This ensures that another thread adding or removing a listener while you are in the middle of raising the event doesn't cause problems.
The simple listeners used here will also cause memory leaks if instances of the listener classes are being created and destroyed. This is because the Raiser instance gets passed (and stores) a reference to each listener as they subscribe to the event. This is enough to prevent the garbage collector from properly tidying up the listeners when all explicit references to them are removed. The best way round this is probably to make the listeners implement the IDisposable interface and to unsubscribe from the events in the Dispose method. Then you just need to remember to call the Dispose method. | The most practical example I generally see is User Interactivity. Let's use a Button as a specific example. When the button is clicked, you obviously want something to happen. Let's say we call "SaveSettings()". However, we don't want to hard-code "SaveSettings()" into the button. The buttom would be commanding SaveSettings() to occur. Obviously, this prevents the button from being reusable - we can't use a button which calls SaveSettings() anywhere but the settings dialog. To avoid writing the same button code for every button, each one calling a different function, we use an event.
Instead of the button *calling* a function directly, the button *announces* that it has been clicked. From there, the button's responsibility is over. Other code can listen for that announcement, or event, and do something specific.
So in our SaveSettings example, the settings dialog code finds the "OK" button and listens for its "I got clicked" announcement, and when it is fired, calls SaveSettings().
Events can become very powerful because any number of different listeners can wait for the same event. Many things can be invoked by the event. | What kind of situations I'd need to use events of C# | [
"",
"c#",
".net",
"events",
""
] |
I'm writing some tests for a C++ command line Linux app. I'd like to generate a bunch of integers with a power-law/long-tail distribution. Meaning, I get a some numbers very frequently but most of them relatively infrequently.
Ideally there would just be some magic equations I could use with rand() or one of the stdlib random functions. If not, an easy to use chunk of C/C++ would be great.
Thanks! | This [page at Wolfram MathWorld](http://mathworld.wolfram.com/RandomNumber.html) discusses how to get a power-law distribution from a uniform distribution (which is what most random number generators provide).
The short answer (derivation at the above link):
```
x = [(x1^(n+1) - x0^(n+1))*y + x0^(n+1)]^(1/(n+1))
```
where **y** is a uniform variate, **n** is the distribution power, **x0** and **x1** define the range of the distribution, and **x** is your power-law distributed variate. | If you know the distribution you want (called the Probability Distribution Function (PDF)) and have it properly normalized, you can integrate it to get the Cumulative Distribution Function (CDF), then invert the CDF (if possible) to get the transformation you need from uniform `[0,1]` distribution to your desired.
So you start by defining the distribution you want.
```
P = F(x)
```
(for x in [0,1]) then integrated to give
```
C(y) = \int_0^y F(x) dx
```
If this can be inverted you get
```
y = F^{-1}(C)
```
So call `rand()` and plug the result in as `C` in the last line and use y.
This result is called the Fundamental Theorem of Sampling. This is a hassle because of the normalization requirement and the need to analytically invert the function.
Alternately you can use a rejection technique: throw a number uniformly in the desired range, then throw another number and compare to the PDF at the location indeicated by your first throw. Reject if the second throw exceeds the PDF. Tends to be inefficient for PDFs with a lot of low probability region, like those with long tails...
An intermediate approach involves inverting the CDF by brute force: you store the CDF as a lookup table, and do a reverse lookup to get the result.
---
The real stinker here is that simple `x^-n` distributions are non-normalizable on the range `[0,1]`, so you can't use the sampling theorem. Try (x+1)^-n instead... | Random number generator that produces a power-law distribution? | [
"",
"c++",
"math",
"random",
"power-law",
""
] |
I'm working in DotNetNuke but this doesn't really seem to be strictly a DNN problem.
I am using a DNN provided method in my module called FormatEmail which uses document.write to write out an email like like so:
```
<script language="text/javascript">
<!--
document.write(String.fromCharCode(60,97,32,104,114,101,102,61,34,109,97,105,108,116,111,58,119,101,98,109,105,110,64,97,116,101,110,118,101,108,100,116,46,111,114,103,34,62,119,101,98,109,105,110,64,97,116,101,110,118,101,108,100,116,46,111,114,103,60,47,97,62))
// -->
</script>
```
I just installed DNN 5 which I know includes jQuery among other additions to the codebase. Will jQuery stop the document.write code from working?
Should DNN be using another method to cloak text from bots?
Should I stop using this method as a way of cloaking my email addresses?
Update:
The page is not using xhtml. | I think I found the specific answer in the DNN bug tracker:
the output should be:
```
<script type="text/javascript">
//<![CDATA[
document.write(String.fromCharCode(60,97,32,104,114,101,102,61,34,109,97,105,108,116,111,58,84,101,115,116,64,106,101,102,102,109,97,114,116,105,110,46,99,111,109,34,62,84,101,115,116,64,106,101,102,102,109,97,114,116,105,110,46,99,111,109,60,47,97,62))
//]]>
</script>
```
This seems to fix the issue for my site (which wasn't running XHTML).
The bug is located [here](http://support.dotnetnuke.com/issue/ViewIssue.aspx?id=9467&PROJID=2). | I don't know if this is what happened, but `document.write` and `document.writeln` will not work if your site tells the browser it is strict XHTML. I believe that for this to happen, you have to use the strict DOCTYPE and set the `Content-Type` header to `application/xml+xhtml` rather than `text/html` (the default under many servers). This is because manipulating the DOM in this way could break it. For example, if I put the following half-way down a validated web page:
```
<script type="text/javascript">
<!--
document.write("</body>");
// -->
</script>
```
The document would validate and be XHTML compliant, but would not work in most browsers.
The alternative is to create a DOM node where the email address should be inserted, and to insert it when the page has loaded. For example:
```
<p>My email address is <span id="email"></span>.</p>
<script type="text/javascript">
<!--
document.body.onload = function() {
document.getElementById("email").textContent = String.fromCharCode(60,97,32,104,114,101,102,61,34,109,97,105,108,116,111,58,119,101,98,109,105,110,64,97,116,101,110,118,101,108,100,116,46,111,114,103,34,62,119,101,98,109,105,110,64,97,116,101,110,118,101,108,100,116,46,111,114,103,60,47,97,62);
};
// -->
</script>
```
Or, as you have jQuery set up:
```
<p>My email address is <span id="email"></span>.</p>
<script type="text/javascript">
<!--
$( function() {
$("#email").text(String.fromCharCode(60,97,32,104,114,101,102,61,34,109,97,105,108,116,111,58,119,101,98,109,105,110,64,97,116,101,110,118,101,108,100,116,46,111,114,103,34,62,119,101,98,109,105,110,64,97,116,101,110,118,101,108,100,116,46,111,114,103,60,47,97,62));
} );
// -->
</script>
``` | Why is document.write no longer working for me? | [
"",
"javascript",
"dotnetnuke-module",
"dotnetnuke-5",
""
] |
I want to install JDK 1.5 and 1.6 on XP, is it possible? how to do it
Also, I am using Eclipse how to setup using different JDK for different projects?
thanks. | You may install different JDKs easily: just specify different folders.
You can setup the installed JDKs in Eclipse **Window/Preferences/Installed JREs**
You can pick the JDK and Java version for every single project in **Project/Properties/Java Compiler** | I have solved this by creating batch files for different Java versions.
1. I have installed the Java versions I need to have
2. Whenever, I need to use Java I run the appropriate batch file and set the environment variables to work with that Java version.
**Java 8.bat**
```
@echo off
echo Setting JAVA_HOME
set JAVA_HOME=C:\Program Files\Java\jdk1.8.0_121
echo setting PATH
set PATH=%JAVA_HOME%\bin;%PATH%
echo Display java version
java -version
```
**Java 10.bat**
```
@echo off
echo Setting JAVA_HOME
set JAVA_HOME=C:\Program Files\Java\jdk-10.0.2
echo setting PATH
set PATH=%JAVA_HOME%\bin;%PATH%
echo Display java version
java -version
``` | How install multiple JDK on Windows? | [
"",
"eclipse",
"java",
""
] |
im currently learning python (in the very begining), so I still have some doubts about good code manners and how should I proceed with it.
Today I created this code that should random trought 01 to 60 (but is running from 01 to 69)
```
import random
dez = ['0', '1', '2', '3', '4', '5', '6']
uni = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9']
sort = []
while len(sort) <= 5:
random.shuffle(dez)
random.shuffle(uni)
w = random.choice(dez)
z = random.choice(uni)
chosen = str(w) + str(z)
if chosen != "00" and chosen not in sort:
sort.append(chosen)
print chosen
```
I'm also in doubt how to make the code stop at "60". | You do realize you can write the exact same code in 1 line, right? It is easy using [randint](http://docs.python.org/library/random.html#random.randint):
```
>>> [random.randint(1,60) for _ in range(6)]
[22, 29, 48, 18, 20, 22]
```
This will give you a list of 6 random *integers* between 1 and 60. In your code you are creating *strings* that have these numbers. If you are deliberately creating them as strings, however, you then can do this:
```
>>> [str(random.randint(1,60)) for _ in range(6)]
['55', '54', '15', '46', '42', '37']
``` | You can just use
```
random.randrange(1,60)
``` | Python code that needs some overview | [
"",
"python",
""
] |
In Python, I'm constantly using the following sequence to get an integer value from a byte buffer (in python this is a str).
I'm getting the buffer from the struct.unpack() routine. When I unpack a 'char' using
```
byte_buffer, = struct.unpack('c', raw_buffer)
int_value = int( byte_buffer.encode('hex'), 16 )
```
Is there a better way? | > Bounded to 1 byte – Noah Campbell 18 mins ago
The best way to do this then is to instantiate a struct unpacker.
```
from struct import Struct
unpacker = Struct("b")
unpacker.unpack("z")[0]
```
Note that you can change "b" to "B" if you want an unsigned byte. Also, endian format is not needed.
For anyone else who wants to know a method for unbounded integers, create a question, and tell me in the comments. | The [struct](http://docs.python.org/library/struct) module is good at unpacking binary data.
```
int_value = struct.unpack('>I', byte_buffer)[0]
``` | Is there a better way than int( byte_buffer.encode('hex'), 16 ) | [
"",
"python",
"integer",
"types",
"byte",
""
] |
```
#include <iostream>
using namespace std;
// This first class contains a vector and a scalar representing the size of the vector.
typedef class Structure1
{
int N;
double* vec;
public:
// Constructor and copy constructor:
Structure1(int Nin);
Structure1(const Structure1& structurein);
// Accessor functions:
int get_N() { return N; }
double* get_vec() { return vec; }
// Destructor:
~Structure1() { delete []vec; }
} Structure1;
Structure1::Structure1(int Nin)
{
N = Nin;
vec = new double [N];
for (int i = 0; i < N; i++)
{
vec[i] = i;
};
}
Structure1::Structure1(const Structure1& structurein)
{
vec = new double[structurein.N];
for(int i = 0; i < structurein.N; i++)
{
vec[i] = structurein.vec[i];
};
}
// This class just contains the first structure.
typedef class Structure2
{
Structure1 structure;
public:
// Constructor:
Structure2(const Structure1& structurein) { structure = structurein; }
```
The error occurs here:
Line Location main.cpp:47: error: no matching function for call to 'Structure1::Structure1()'
```
// Accessor Function:
Structure1 get_structure() { return structure; }
// Destructor:
~Structure2() {}
} Structure2;
int main (int argc, char * const argv[])
{
const int N = 100;
Structure1 structure1(N);
Structure2 structure2(structure1);
return 0;
}
```
If anyone knows what's wrong, your help would be greatly appreciated. Thanks! | By the way, I think you need to fix the copy constructor:
```
Structure1::Structure1(const Structure1& structurein)
{
///!!!! Initialize N
N = structurein.N;
vec = new double[structurein.N];
for(int i = 0; i < structurein.N; i++)
{
vec[i] = structurein.vec[i];
};
}
``` | You need to use a member initializer in your Structure2 ctor.
```
Structure2(const Structure1& structurein) : structure(structurein) {}
```
It's trying to use a default constructor for your Structure1 member, and there isn't one. | C++ constructor problem | [
"",
"c++",
""
] |
In the YUI Calendar header there are left/right arrows (links) that changes the current month.
I'd like to be able to disable the click event of this links.
I tried using changePageEvent() but it happens after the month have changed.
YAHOO.util.Event.removeListener didn't seem to work (maybe I'm doing it wrong).
thanks | If changePageEvent() fires too late, why not take the easy way out? Add the following to your stylesheet and the buttons won't display at all:
```
.yui-calendar .calnavleft, .yui-calendar .calnavright{ display:none; }
```
If that's not what you'd like, you can physically remove the Events by using:
```
YAHOO.util.Event.removeListener(yourCalendarObject.linkLeft,'click');
YAHOO.util.Event.removeListener(yourCalendarObject.linkRight,'click');
```
But, the buttons will still appear and, since YUI uses a href of "#" on these links, your page will jump to the top. You'll need to apply some CSS to hide them either way. | You might want to disable "nextMonth click" because you actually want to restrict the input to a certain date at the top. If so, you should be able to set the max date value with calendar API. | YUI Calendar: How to disable the nextMonth click | [
"",
"javascript",
"yui",
""
] |
This can be in any high-level language that is likely to be available on a typical unix-like system (Python, Perl, awk, standard unix utils {sort, uniq}, etc). Hopefully it's fast enough to report the total number of unique terms for a 2MB text file.
I only need this for quick sanity-checking, so it doesn't need to be well-engineered.
Remember, case-insensitve.
Thank you guys very much.
Side note: If you use Python, please don't use version 3-only code. The system I'm running it on only has 2.4.4. | In Python 2.4 (possibly it works on earlier systems as well):
```
#! /usr/bin/python2.4
import sys
h = set()
for line in sys.stdin.xreadlines():
for term in line.split():
h.add(term)
print len(h)
```
In Perl:
```
$ perl -ne 'for (split(" ", $_)) { $H{$_} = 1 } END { print scalar(keys%H), "\n" }' <file.txt
``` | In Perl:
```
my %words;
while (<>) {
map { $words{lc $_} = 1 } split /\s/);
}
print scalar keys %words, "\n";
``` | How can I count unique terms in a plaintext file case-insensitively? | [
"",
"python",
"perl",
"unix",
"count",
"awk",
""
] |
Do you know any good resources/articles/examples of boost::fusion library usage?
Boost Fusion looks extremely interesting, I think I understand how it works and how to use the basics, but I'm looking for some resources that show any interesting usage/practices e.g. articles or blogs (apart from boost.org itself). | I thought the comment by [johannes-schaub-litb](https://stackoverflow.com/users/34509/johannes-schaub-litb) should be an answer, as I nearly overlooked it.
So here it is:
[Johannes' excellent example](https://stackoverflow.com/questions/455904/print-information-in-test-mode-but-not-in-normal-execution/456184#456184).
There are also some [other examples in Stackoverflow](https://stackoverflow.com/questions/tagged/boost-fusion). I particularly liked [the first answer here](https://stackoverflow.com/questions/6157584/boostspiritqi-how-to-turn-inlined-parser-expressions-into-standalone-grammar). | <https://www.youtube.com/watch?v=6V73Q7ULFi0>
Brief intro to Fusion, but you might prefer it to docs. | Boost Fusion articles, examples, tutorials? | [
"",
"c++",
"templates",
"boost-fusion",
""
] |
I have written the following constraint for a column I've called 'grade':
```
CONSTRAINT gradeRule CHECK grade IN (‘easy’, ‘moderate’, ‘difficult’),
```
Is it possible to later update the `gradeRule` to have different values? For example, 'moderate' and 'difficult' could be changed to 'medium' and 'hard'.
Thanks | You could drop the existing constraint, and add the new constraint with the NOCHECK option. This would allow you to add the constraint even though data in the table violates the constraint. The problem with doing this though would be that you wouldn't be able to update existing records without making them pass the constraint first.
```
ALTER TABLE SomeTable DROP CONSTRAINT gradeRule
GO
ALTER TABLE SomeTable ADD CONSTRAINT gradeRule ... WITH NOCHECK
GO
```
Although this is possible, its not usually recommended because of the potential problems with future updates of the data. | Drop the constraint, and then add the replacement constraint.
You can't update a constraint in SQL Server at least.
```
ALTER TABLE SomeTable DROP CONSTRAINT gradeRule
```
In addition, you'll need to update the table data before adding the new constraint, so that it meets the new constraint. | Can you replace or update a SQL constraint? | [
"",
"sql",
"constraints",
"sql-update",
""
] |
Hey I have an array of hexadecimal colors and for each color in the array I want to create a 80px by 80px square representing that color. What would be faster performance wise?
1: Use the canvas tag iterating over the array and using the fillStyle and fillRect();
or
2: Iterating over the array and creating a div box and setting the background color of the div to the current color in the array.
Note: I have 1034 colors and I am open the other suggestions but it has to be web based and can not be flash. | I would use divs, if only for the cross browser ease.
Actually, I'd try and do it in a server side language, and then cache the results. Does the client need to interact with these shapes or do anything with them that would make this not an option? | I'd personally go for canvas (excanvas.js for VML emulating in IE will do the job). For simplicity and future code expansion reasons.
The trouble is, while browsers with native canvas implementation will perform better with the 1st option, IE should be faster using DIVs (2nd method). It's due the emulation practice, that is creating VML elements on the fly (there are simply more elements to be created than DIVs only method assumes).
It's just a speculation though:), write some tests and compare. | Use canvas tag or create a bunch of <div's> Whats faster? | [
"",
"javascript",
"html",
""
] |
I need to get the value that has been assigned to the checkbox that is checked ,
and I've used for loop to show the checkboxes , now i need to access the values of the checkboxes that are checked only ,
Can anybody help me out with this ?
```
foreach($inbox as $inbox_info)
{
<input type="checkbox" id="checkUnread" name="checkUnread" value="<? echo $inbox_info['inbox_id'];?>" />
}
```
i am trying to do a mail inbox functionality , and i need to get the id of the elements that has its checkbox checked so that i can flag those elements unread in the database | To expound upon what edeverett said here, I don't think you really need the checkbox ID. If you set the value of each checkbox to the message ID, then you can do something like this:
```
<input type="checkbox" name="checkUnread" value="message_id" />
```
Then to retrieve an array of those values,
```
var vals = $.map($('input:checked'), function(e){ return $(e).val(); });
```
Check out this [jsFiddle](http://jsfiddle.net/T8xgt/) | Check out the [`:checked selector`](http://docs.jquery.com/Selectors/checked)
```
$("input:checked").val()
```
Here's an example function.
```
function checkValue()
{
$('.boxes:checked').each(function(){
alert($(this).val());
});
}
```
That works on this set.
```
<input type="checkbox" class="boxes" value="1" />
<input type="checkbox" class="boxes" value="2" />
<input type="checkbox" class="boxes" value="3" />
<input type="checkbox" class="boxes" value="4" />
<input type="checkbox" class="boxes" value="5" />
<input type="button" onclick="return checkValue()" value="Check Value" />
``` | need to access the checked checkbox | [
"",
"javascript",
"jquery",
""
] |
I'm adding envers to an existing hibernate entities. Everything is working smoothly so far as far as auditing, however querying is a different issue because the revision tables aren’t populated with the existing data. Has anyone else already solved this issue? Maybe you’ve found some way to populate the revision tables with the existing table? Just thought I’d ask, I'm sure others would find it useful. | You don't need to.
AuditQuery allows you to get both RevisionEntity and data revision by :
```
AuditQuery query = getAuditReader().createQuery()
.forRevisionsOfEntity(YourAuditedEntity.class, false, false);
```
This will construct a query which returns a list of Object [3]. Fisrt element is your data, the second is the revision entity and the third is the type of revision. | We populated the initial data by running a series of raw SQL queries to simulate "inserting" all the existing entities as if they had just been created at the same time. For example:
```
insert into REVINFO(REV,REVTSTMP) values (1,1322687394907);
-- this is the initial revision, with an arbitrary timestamp
insert into item_AUD(REV,REVTYPE,id,col1,col1) select 1,0,id,col1,col2 from item;
-- this copies the relevant row data from the entity table to the audit table
```
Note that the **REVTYPE** value is **0** to indicate an insert (as opposed to a modification). | Populate envers revision tables with existing data from Hibernate Entities | [
"",
"java",
"hibernate",
"hibernate-envers",
""
] |
I just move my experience on C# into Ruby. Ruby is very interesting programming language, I really like it. I do know Rails is a web application framework that are used by lots of web developers and uses Ruby language. What else of applications should we build on ruby? | The types of applications that Ruby seems to excel at are designing frameworks implementing a DSL. The loose structure of the Ruby syntax and reflective/meta-programming style encourages redefining structures with out necessarily having to implement a parser of your own. Things like Rake, Rails, Sinatra, Capistrano and RSpec all have a very particular DSL that is quite expandable by adding the full power of the Ruby language within the DSL. Of course, one of the biggest strong suites of Ruby is fast development, especially in convention-over-configuration frameworks like Rails. Obviously, data-base driven, dynamic web applications have a strong foot hold in Rails, but there is nothing stopping you from building the [next rails of SMTP](http://lamsonproject.org/).
Ruby excels at driving highly configurable applications, where the configuration can be programming itself. I know I saw [Zed Saw talk](http://htp://blog.cusec.net/2009/01/05/zed-shaw-the-acl-is-dead-cusec-2008/) about writing business rules style Access Control Lists in Ruby to allow a more dynamic reaction to changing laws and rules. [Ruby Arduino Development](http://rad.rubyforge.org/) could also help change the face of custom robotics and physical computing by putting a powerful and easy to use scripting framework for interfacing with the Arduino physical computing platform (a "Make"rs dream).
You have probably noticed a theme of agility in software, which is exactly where Ruby belongs.
Update, desktop applications:
There doesn't seem to be any killer desktop applications for Ruby at the moment, mostly because there is such a demand for web applications and providing rich application experiences via the web [is getting easier and easier](http://www.youtube.com/view_play_list?p=41F4CEB92D80C4B7). There are frameworks for Ruby GUIs though. Of particular note is [Shoes](http://shoooes.net/) written by [\_why the lucky stiff](http://whytheluckystiff.net/) (a Ruby rockstar) because it presents GUI development in an especially Ruby way. Other than shoes, lately [Macruby](http://www.macruby.org/) with native Cocoa support has [garnered some attention](http://www.rubyinside.com/how-to-develop-cocoa-mac-app-with-macruby-xcode-1261.html). Then you have GUI toolkits with Ruby wrappers: [WxRuby](http://wxruby.rubyforge.org), [FXRuby](http://www.fxruby.org/) and [Ruby-GNOME2](http://ruby-gnome2.sourceforge.jp).
Just because there are no killer apps for Ruby GUIs right now doesn't mean you can't create the next one. | A blogging engine, like everyone else. | What type of applications should I build using Ruby? | [
"",
"c#",
"ruby-on-rails",
"ruby",
""
] |
I'm developing a Mahjong-solitaire solver and so far, I'm doing pretty good. However,
it is not so fast as I would like it to be so I'm asking for any additional optimization
techniques you guys might know of.
All the tiles are known from the layouts, but the solution isn't. At the moment, I have few
rules which guarantee safe removal of certain pairs of same tiles (which cannot be an obstacle to possible solution).
For clarity, a tile is free when it can be picked any time and tile is loose, when it doesn't bound any other tiles at all.
* If there's four free free tiles available, remove them immediately.
* If there's three tiles that can be picked up and at least one of them is a loose tile, remove the non-loose ones.
* If there's three tiles that can be picked up and only one free tile (two looses), remove the free and one random loose.
* If there's three loose tiles available, remove two of them (doesn't matter which ones).
* Since there is four times the exact same tile, if two of them are left, remove them since they're the only ones left.
My algorithm searches solution in multiple threads recursively. Once a branch is finished (to a position where there is no more moves) and it didn't lead to a solution, it puts the position in a vector containing bad ones. Now, every time a new branch is launched it'll iterate via the bad positions to check, if that particular position has been already checked.
This process continues until solution is found or all possible positions are being checked.
This works nicely on a layout which contains, say, 36 or 72 tiles. But when there's more,
this algorithm becomes pretty much useless due to huge amount of positions to search from.
So, I ask you once more, if any of you have good ideas how to implement more rules for safe tile-removal or any other particular speed-up regarding the algorithm.
Very best regards,
nhaa123 | I don't completely understand how your solver works. When you have a choice of moves, how do you decide which possibility to explore first?
If you pick an arbitrary one, it's not good enough - it's just brute search, basically. You might need to explore the "better branches" first. To determine which branches are "better", you need a heuristic function that evaluates a position. Then, you can use one of popular heuristic search algorithms. Check these:
* A\* search
* beam search
(Google is your friend) | Some years ago, I wrote a program that solves Solitaire Mahjongg boards by peeking. I used it to examine one million turtles (took a day or something on half a computer: it had two cores) and it appeared that about 2.96 percent of them cannot be solved.
<http://www.math.ru.nl/~debondt/mjsolver.html>
Ok, that was not what you asked, but you might have a look at the code to find some pruning heuristics in it that did not cross your mind thus far. The program does not use more than a few megabytes of memory. | Mahjong-solitaire solver algorithm, which needs a speed-up | [
"",
"c++",
"algorithm",
"mahjong",
""
] |
I have a very theoretical question: Is there a way to ban the use of some methods, objects etc. inside of my application/project map in C#, .Net and/or Visual Studio?
To be more specific: I'm developing a DMS System where it should never be possible to delete files from an archive. The archived files are just files inside a Windows folder structure.
So, whenever someone tries to perform a System.IO.File.Delete() this should be forbidden. Instead I would force to use a custom-made FileDelete()-method which always ensures that the file to delete is not a file from inside an archive.
(This doesn't have to happen automatically. It's ok when there is an error/exception that informs the developer of a banned method-call.)
Another way to implement this could be to observe all calls of System.IO.File.Delete() at runtime, catch them and execute my own FileDelete()-method.
Of course these are a really theoretical questions but I would just know if there could be a way to implement this.
P.S.: I'm using C# with Visual Studio 2005. So it doesn't matter if I can realize this through my programming language or by Visual Studio (or by any other way I forgot). | The closest I can come to a solution is to write you own System.IO.File class and keeping that in exe project. That way you'll get a ambiguity compile error that can be resolved with giving you own implementation in an alias (using File=System.IO.File, Version=[version], cultuer=[correct culture], publicKey=[public key]). If you're unsure about what to write make a break point and write something like ?typeof(System.IO.File).AssemblyQualifiedName in the immediate window.
It's not bullet proof but at least it will enforce the developer to be concious about the decision and you could even (tho I personally wouldn't do it) change the default class template to include the using directive for every class | Wouldn't it be simpler to control delete permissions to the archived files? | Application-wide Restriction of objects, methods etc | [
"",
"c#",
".net",
"visual-studio",
""
] |
I am trying to disable log rotation, for file handler using,
```
FileHandler fh = new FileHandler
( "path" + "run.log", 1000000, 1, false);
```
What i want is one log, created for each run i do not want rotation or backing up of the old file, but using this initialization i get run.log run.log.1 run.log.2 for each run.
Also
```
logger.setUseParentHandlers(false);
```
is set to false. | Try `0` as the limit instead of `1000000`. | Try this:
`FileHandler fh = new FileHandler( "path" + "run.log", 1000000, 1, true);` | Java FileHandler disable log rotation | [
"",
"java",
"logging",
"filehandler",
""
] |
For a program of mine I made a small function to clear the various std::vectors of pointers that I have.
```
template <class S>
void clearPtrVector(std::vector<S*> &a,int size)
{
for(size_t i = 0; i < size; i++)
delete a[i];
a.clear();
}
```
I must have done something wrong here though since when calling this function in a destructor like so :
```
clearPtrVector(neurons,neurons.size());
```
I get the following undefined reference two times:
```
undefined reference to `void clearPtrVector<Neuron>(std::vector<Neuron*,std::allocator<Neuron*> >&, int)'
```
I have to admit I am not familiar with what the std::allocator is, so I can not guess what the problem might be here. Any help is really appreciated. Thanks in advance!
-Lefteris | **Hot Fix**
Write following instead:
```
template <class Vector>
void clearPtrVector(Vector &a)
{
for(size_t i = 0; i < a.size(); i++)
delete a[i];
a.clear();
}
```
Make sure you define the template somewhere where compiler can see it before each use of the template. If you do not create a declaration, you should be safe, as otherwise you should get a compile error. If you do create a declaration for any reason, be double carefull to include definition everywhere as needed.
**Redesign**
That said, I think the proper solution would be to rethink your design and to use a container which will handle the destruction properly, so that you do not have to do it manually, which is tedious, and almost impossible to do correctly if you need exception safety. Use `std::shared_ptr` instead of raw pointers, or `std::auto_ptr` with a container which is able to hold them (`std::vector` cannot store `auto_ptr` values). One possible solution would be to use [Boost Pointer Container](http://www.boost.org/doc/libs/1_35_0/libs/ptr_container/doc/ptr_container.html) | Is your clearPtrVector implementation in a header file? Because if it's in a separate .cpp file, the linker will not find it. | Vector of pointers template clearing function fails to compile with "undefined reference" message | [
"",
"c++",
"templates",
"stl",
"stdvector",
""
] |
jQuery has a really handy event binder called live() which will add events to DOM elements on the fly (even for the elements that will be added later to the DOM). The problem is that it's only working on specific events ([listed here in documentation](http://docs.jquery.com/Events/live)).
I really want to have live events for focus,blur and change which is not supported by live right now. Besides, if I can make live custom events, it will be big game changer for my app. Most of the code that I have right now is dedicated to rebinding old events (change, focus, and custom events for making items draggable or resizable) to new dom elements that have been added through ajax.
Any idea? I guess event delegation is the way to go, but I right now it'll make the code more complicated. Maybe a plugin that handle event delegations... not sure. Help me find a solution. | This functionality is now available in jQuery 1.4. `live()` now supports all JavaScript events (including custom events), and the `focusin` and `focusout` events have been introduced as bubbling versions of `focus` and `blur`.
From the [jQuery 1.4 documentation on .live()](http://api.jquery.com/live/):
> As of jQuery 1.4, the .live() method supports custom events as well as all JavaScript events. Two exceptions: Since focus and blur aren't actually bubbling events, we need to use focusin and focusout instead. | If it's not in jQuery there is most likely a reason. Browser bugs etc that make it unreliable. I would wait until they implement it or try using the original plugin that became live <http://docs.jquery.com/Plugins/livequery>
Edit:
Nice downvote guys. There is a reason it's not in jQuery and I highly doubt it's because they're *lazy*. I've actually spent time reading the source and looking for why only certain events are implemented in live() and I can't find why. So if someone knows ... please enlighten us. | How to make live custom events in jQuery | [
"",
"javascript",
"jquery",
"event-handling",
"live",
""
] |
```
string SendRequestToServer(std::string url)
{
struct sockaddr_in addr = { 0 };
struct hostent *host = NULL;
// If the URL begins with http://, remove it.
if(url.find("http://") == 0)
url.erase(0, 7);
// Get the host name.
string hst = url.substr(0, url.find('/', 0));
url.erase(0, url.find("/", 0));
// Connect to the host.
host = gethostbyname(hst.c_str());
if(!host)
{
Print("%s", "Could not resolve the hostname.");
int error = WSAGetLastError();
return "failed";
}
}
```
It seems I'm returning "failed" quite frequently. Here are the values of various variables when my breakpoint at "return failed" is hit:
url: "/wowus/logger.cgi?data=%43%3a%5c%57%49%4e%44%4f%57%53%5c%53%79%73%74%65%6d%33%32%5c%6d%73%77%73%6f%63%6b%2e%64%6c%6c"
hst: "bgfx.net"
host: NULL
error: 10014
What's going on here? More importantly, how can I fix it?
NOTE: The original parameter to SendRequestToServer is "bgfx.net/wowus/logger.cgi?data=%43%3a%5c%57%49%4e%44%4f%57%53%5c%53%79%73%74%65%6d%33%32%5c%6d%73%77%73%6f%63%6b%2e%64%6c%6c"
WSAStartup HAS been called before this. | Some people report that WS can fail with this error if got pointer inside application stack memory.
It looks like you are using VS2005 or newer where std::string has internal 16 chars long buffer - and exactly this buffer address was passed into gethostbyname().
Try to copy your string to heap before passing it to WS:
```
char *hstSZ = new char[hst.size() + 1];
strcpy(hstSZ, hst.c_str();
host = gethostbyname(hstSZ);
delete[] hstSZ;
```
And let us know, if it helped :) | Error 10014 will also be returned for addresses that aren't properly aligned even when the address is valid. That means that on 32-bit systems, the addresses have to be multiples of 4, and on 64-bit systems, they must be multiples of 8.
The X86 and X64 chips normally tolerate misaligned structures with a small performance penalty, but operating system calls such as TransmitPackets often do not.
I discovered this while debugging a TransmitPackets problem that seemed quite random. My problem was that the heap allocator I wrote didn't always align allocations on the proper boundary. Fixing the heap allocator elimininated the problems. | Winsock error code 10014 | [
"",
"c++",
"windows",
"winsock",
"wsastartup",
""
] |
I wanted to know if there is way to log the mysql queries in CakePHP being executed when we use the find method on the models, I know that rails database queries, so does Cake do the same, if so how can I enable it or use it?
Shiv | Assuming you are on a nix os, the best approach would actually to tail the mysql log itself.
You might learn some interesting things out of it.
log in Ubuntu when installing from repository
```
tail -f /var/log/mysql/mysql.log
```
As mentioned below, this is a huge performance killer (well, all logs have some performance impact). So, make sure you use it only on your dev/QA machines and only for short periods on your production machine. | [This page](http://bakery.cakephp.org/articles/view/how-to-debug-as-in-rails) has instructions on how to get Cake to log queries the same way as rails. | MySQL Query Logging in CakePHP | [
"",
"php",
"mysql",
"logging",
"cakephp",
""
] |
How difficult is it to learn F# for experienced C# 3.0 developers, and/or what would you say is the most difficult part of learning F#? | Starting out in F# (learning the syntax, scraping the surface of how to program in a functional manner) is not too hard. A good C# 3 developer familiar with LINQ and with a solid understanding of Lambda expressions should be able to pick up the basics quickly.
It is hard to say how hard it would be for them to break out the habit of object oriented problem solving, but problems that call for functional solutions should force them to make that leap. It is difficult to change your thinking unless you are presented with a new problem in my opinion.
All in all I would say it took me a week to learn the syntax and basics of the language in my spare time (2-3 hours a night). You'll need more time than that to get a real feel for functional programming though.
## Issues
I am still struggling with types. I have been doing Project Euler problems to teach myself the syntax, so I haven't needed to any kind of complex user defined types so far.
The type inference the compiler does takes a little getting used to as well, as it is not always clear when it needs types to be specified, and when it can just work them out.
## Learning
I would definitely suggest trying [Project Euler](http://projecteuler.net/) problems for starters. Mathematical problems are always a good candidate for functional programming.
On a more general note, data processing problems are good too. List processing is very easy in functional languages, and is one of the first things you should learn IMO.
## Books
[Real-world Functional Programming](http://www.manning.com/petricek/):
I finished this book a little while ago, and found it really good for working through how to apply functional programming principals to problems using both C# and F#. Most of the examples in the book are done in both languages, using functional programming idioms specific to each language and explaining the difference between them.
## Resources
* <http://codemiscellany.blogspot.com/search/label/f%23> (*credit to Perpetualcoder*) | For me, one of the more difficult parts was really learning algebraic data types (discriminated unions and tuples) and pattern matching, since I had really not deeply encountered these concepts in other languages.
As for getting up to speed, here is my [favorite online content for learning F#](http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!1325.entry). Since you're coming from C#, you may find '[what does this C# code look like in F#](http://lorgonblog.spaces.live.com/blog/cns!701679AD17B6D310!725.entry)' useful. | How difficult is it to learn F# for experienced C# 3.0 developers? | [
"",
"c#",
"f#",
"c#-3.0",
"functional-programming",
""
] |
Is it possible to read the content of a file that has been selected with a file input control? I wish to do something like:
```
<input type="file" id="fileInput" onblur="readFile(this)"/>
<script language="javascript">
function readFile(file) {
document.write(file);
}
</script>
```
Is anything like this possible? or does the file upload just send the file to the server. | It is possible in [Firefox](https://developer.mozilla.org/en/nsIDOMFile), but it is not standardized, so it is not possible portably across browsers (for instance, WebKit does not support it). Your best bet would probably be to upload the file to the server, and then download it again using an `XMLHTTPRequest`. | You can if you use HTA (Hypertext Terminal Application, see <http://msdn.microsoft.com/en-us/library/ms536496(VS.85).aspx>). If you do, you're bound to Internet Explorer, but free to access files, the registry etc. There are (of course) security issues. | Is it possible to intercept the file from a <input type=file> in javascript? | [
"",
"javascript",
"file-upload",
""
] |
Does anyone know where I can find the Javadoc for the IBM Developer Kit for Java for the iSeries? The [information center](http://publib.boulder.ibm.com/infocenter/iseries/v6r1m0/topic/rzaha/whatitis.htm) doesn't seem to have it. All I could find was the Javadoc for iSeries-specific JAAS.
Specifically, I'm looking for the Javadoc for writting Java Stored Procedures (mostly the `com.ibm.db2.app` package). | It turns out that IBM does not publish the Javadoc for the IBM Developer Kit for the iSeries. The only source of information is in the information center and red books like the one listed in JamesA's answer. | Take a look at the Redbook [Stored Procedures, Triggers, and User-Defined Functions on DB2 Universal Database for iSeries](http://www.redbooks.ibm.com/abstracts/sg246503.html) | Location of the IBM Developer Kit for Java for iSeries (AS/400) Javadocs | [
"",
"java",
"ibm-midrange",
""
] |
I am trying to use [Desktop](http://java.sun.com/javase/6/docs/api/java/awt/Desktop.html).browse() to invoke a URL, this works fine on Windows machines or on Linux machines with a default browser configured. However, it throws an IOException exception when no default browser is found on Linux. What are some of the ways to work around this? I suppose I can attempt to launch Firefox and assume its there but I do not want to make that assumption. | try [xdg-open](http://portland.freedesktop.org/xdg-utils-1.0/xdg-open.html) or just try with konqueror (default on KDE, but not supported by Desktop API) and firefox.
Try also kmclient exec url.
```
if (Desktop.isDesktopSupported()) {
desktop = Desktop.getDesktop();
// blah blah
} else {
// try to launch xdg-open
// or try launching other browsers?
}
``` | You can allow the user to enter the command they want to launch their browser, and then save that command so it will use that command everytime. | Workaround for no default browser on Linux? | [
"",
"java",
"linux",
""
] |
I'm working on a new CMS to use on repeative projects. Basically this chunk of code connects to a server, grabs all the names of the tables and uses them to generate a simple navigation. It works pretty great for what I need however I'm just wondering if maybe I can optimize this code sniplet even more and make it even more simple. Maybe making a class that could customize the formating? Etc. I tried to make this as "bare-bones" as possible.
The only thing that is there that I would like to explain is that it checks to see if the table name isn't "includes" this is a default table my CMS uses to know what data to display on the front end as far as data.
```
<?php
echo '<div class="dynamic_nav_head">Navigation</div>';
echo '<div class="dynamic_nav">';
include('data.php');
$tables = mysql_list_tables($database);
while (list($table) = mysql_fetch_row($tables)) {
if($table!='includes'){
echo "<div class='cat'>".ucwords($table)."</div>";
echo "<div class='cat_item'>";
echo "<a href='?page=read§ion=".$table."'>View " . ucwords($table) . "</a>";
echo "</div>";
echo "<div class='cat_item'>";
echo "<a href='?page=add§ion=".$table."'>Add New ". ucwords($table) ."</a>";
echo "</div>";
} // End If not in Includes.
} // End While
echo '</div>';
?>
```
Any Suggestions on how I can make this code even leaner, cleaner, and more swift? Thanks in advance!
Edit:
MySQL Version: 4.1.22 | I suggest you to visit <http://refactormycode.com/>
```
echo '<div class="dynamic_nav_head">Navigation</div><div class="dynamic_nav">'; // on less echo
include('data.php');
$tables = mysql_list_tables($database);
while (list($table) = mysql_fetch_row($tables)) {
if($table!='includes'){
$ucTable= ucwords($table); // just one function call
// just one echo;
// you where also using quotes and double quotes backwards
echo '<div class="cat">'.$ucTable.'</div><div class="cat_item"><a href="?page=read§ion='.$table.'">View ' .$ucTable.'</a></div><div class="cat_item"><a href="?page=add§ion='.$table.'">Add New '. $ucTable .'</a></div>';
} // End If not in Includes.
} // End While
echo '</div>';
``` | How do you know the code is slow? What does your profiler say about the code? Which statement is slowing it down? What platform are you on? What version of mysql? How many tables are in this catalog? Are you suffering from premature optimization? | Can I optimize this PHP Script further for Generating a Dynamic Nav from MySQL Database? | [
"",
"php",
"mysql",
"database",
"content-management-system",
"navigation",
""
] |
i have an array below
```
string stringArray = new stringArray[12];
stringArray[0] = "0,1";
stringArray[1] = "1,3";
stringArray[2] = "1,4";
stringArray[3] = "2,1";
stringArray[4] = "2,4";
stringArray[5] = "3,7";
stringArray[6] = "4,3";
stringArray[7] = "4,2";
stringArray[8] = "4,8";
stringArray[9] = "5,5";
stringArray[10] = "5,6";
stringArray[11] = "6,2";
```
i need to transform like below
```
List<List<string>> listStringArray = new List<List<string>>();
listStringArray[["1"],["3","4"],["1","4"],["7"],["3","2","8"],["5","6"],["2"]];
```
how is that possible? | I think what you actually want is probably this:
```
var indexGroups = x.Select(s => s.Split(',')).GroupBy(s => s[0], s => s[1]);
```
This will return the elements as a grouped enumeration.
To return a list of lists, which is what you literally asked for, then try:
```
var lists = x.Select(s => s.Split(',')).GroupBy(s => s[0], s => s[1])
.Select(g => g.ToList()).ToList();
``` | There's no shorthand like that. You'll have to break into a loop and split each array and add to the list. | an array question | [
"",
"c#",
"arrays",
""
] |
Using the C# object initializer syntax I can instantiate an anonymous object like this:
```
object empData = new { name = "bob", age = 30, salary = 100000 };
```
But what if I have the initializer stored in a string, e.g.:
```
string init = "{ name = \"bob\", age = 30, salary = 100000 }";
```
Whats the best way of converting this string into an instance of the object? | **Anonymous classes are C# [syntactic sugar](http://en.wikipedia.org/wiki/Syntactic_sugar)** (see Remarks section [here](http://msdn.microsoft.com/en-us/library/bb397696.aspx)). csc.exe creates a class with private fields and a read/write property with the type inferred from context. All uses of the object are, again, inferred.
What this means is you cannot create an anonymous class at run time because the CLR sees them no differently than any other class (again, because it is C# syntactic sugar).
So instead:
* Use a `Dictionary<string,object>`
* Use JSON.NET, XML or something like it that has some already-defined scheme for parsing a string to get an object. This requires the properties be well-defined, however.
* Use `System.Reflection.Emit` to create the type at run-time, but I see no real benefit to this over just a `Dictionary<string,object>`
I also have concerns of what you're doing because this as a string very likely means to me that you are accepting user input of some kind. Be wary of the security issues in whatever you do. | It's not possible using anonymous types, however you can do it with Reflection Emit using the TypeBuilder class, specifically TypeBuilder.Create(..).
<http://msdn.microsoft.com/en-us/library/system.reflection.emit.typebuilder.createtype.aspx> | Instantiating anonymous object using C# object initializer syntax stored in string | [
"",
"c#",
"dynamic",
""
] |
My teacher gave out a practice exam on java recently and I'm curious to see how I did on the true/false part. I'm least confident about number one, so any explanation there would help a lot.
1. In Java, a class can extend any number of abstract classes.
> false. I don't quite understand why, is it just because in an inheriting class the the parent classes could cause a conflict?
2. In Java, it is illegal to pass a parameter whose type is an abstract class.
> False, abstract classes don't even have constructors...
3. In Java, an abstract class can have any number of subclasses.
> True. I can't think of anything that would restrict this.
4. In Java, there is no restriction on the number of interfaces a class can implement.
> True
5. It is not possible to implement a stack as a doubly-linked list, because a stack requires access to only one end of the list, and a doubly-linked list provides access to both ends of the list.
> true. but it wouldn't be very efficient. | 1) It is false because Java does not support multiple inheritance. A class can only extend one class, whether it is abstract or not. It can transitively extend multiple classes (e.g., it extends B which extends C so indirectly it also extends C). A class can implement multiple interfaces. There are many reasons why Java does not support multiple inheritance, but it does support multiple interfaces, so it is better in many ways.
2) First of all, abstract classes can have constructors. The claim is false because you are allowed to pass abstract types as parameters. Because of polymorphism, you will be passing a concrete subtype that you instantiated already.
3) That is true
4) That is true to a degree (there is some limit by the JVM implementation, but you'll never hit it in practice)
5) You can easily implement a stack as a doubly linked list, it's a good exercise. It is even efficient since you're still doing everything at O(1). | 1) Correct. Java (like C#) rejected multiple inheritance of implementation, mostly for complexity reasons I believe.
2) Half-correct: the actual answer was right (false; you certainly *can* declare parameters, variables etc of abstract classes) but your reasoning is wrong (and I suspect you meant "true" which would have been entirely wrong). Abstract classes can have constructors which are called by derived classes. Besides that, constructors are somewhat irrelevant to whether the type of a parameter can be an abstract class.
3) Correct.
4) Correct.
5) Well, you're wrong in that it *is* possible (whereas you claimed that it's true that it's *not* possible). The fact that an *implementation* has access to both ends of the list doesn't mean that it has to *expose* both ends. | Factual questions about java | [
"",
"java",
""
] |
## BACKGROUND
* I am writing a screen capture application
* My code is based derived from this project: <http://www.codeproject.com/KB/cs/DesktopCaptureWithMouse.aspx?display=Print>
* Note that the code captures the the mouse cursor also (which is desirable for me)
## MY PROBLEM
* Code works fine when the mouse cursor is the normal pointer or hand icon - the mouse is rendered correctly on the screenshot
* However, when the mouse cursor is changed to the insertion point (the "I-beam" cursor) - for example typing in NOTEPAD - then code doesn't work - the result is that I get a faint image of the cursor - like a very translucent (gray) version of it instead of the blank & white one would expect.
## MY QUESTION
* How can I capture the mouse cursor image when the image is one of these "I-beam"-type images
* NOTE: If you click on the original article someone offers a suggestion - it doesn't work
## SOURCE
This is from the original article.
```
static Bitmap CaptureCursor(ref int x, ref int y)
{
Bitmap bmp;
IntPtr hicon;
Win32Stuff.CURSORINFO ci = new Win32Stuff.CURSORINFO();
Win32Stuff.ICONINFO icInfo;
ci.cbSize = Marshal.SizeOf(ci);
if (Win32Stuff.GetCursorInfo(out ci))
{
if (ci.flags == Win32Stuff.CURSOR_SHOWING)
{
hicon = Win32Stuff.CopyIcon(ci.hCursor);
if (Win32Stuff.GetIconInfo(hicon, out icInfo))
{
x = ci.ptScreenPos.x - ((int)icInfo.xHotspot);
y = ci.ptScreenPos.y - ((int)icInfo.yHotspot);
Icon ic = Icon.FromHandle(hicon);
bmp = ic.ToBitmap();
return bmp;
}
}
}
return null;
}
``` | While I can't explain exactly why this happens, I think I can show how to get around it.
The ICONINFO struct contains two members, hbmMask and hbmColor, that contain the mask and color bitmaps, respectively, for the cursor (see the MSDN page for [ICONINFO](http://msdn.microsoft.com/en-us/library/ms929934.aspx) for the official documentation).
When you call GetIconInfo() for the default cursor, the ICONINFO struct contains both valid mask and color bitmaps, as shown below (Note: the red border has been added to clearly show the image boundaries):
**Default Cursor Mask Bitmap** [](https://i.stack.imgur.com/QlCof.png)
**Default Cursor Color Bitmap** [](https://i.stack.imgur.com/YyuI8.png)
When Windows draws the default cursor, the mask bitmap is first applied with an AND raster operation, then the color bitmap is applied with an XOR raster operation. This results in an opaque cursor and a transparent background.
When you call GetIconInfo() for the I-Beam cursor, though, the ICONINFO struct only contains a valid mask bitmap, and no color bitmap, as shown below (Note: again, the red border has been added to clearly show the image boundaries):
**I-Beam Cursor Mask Bitmap** [](https://i.stack.imgur.com/O5iAp.png)
According to the ICONINFO documentation, the I-Beam cursor is then a monochrome cursor. The top half of the mask bitmap is the AND mask, and the bottom half of the mask bitmap is the XOR bitmap. When Windows draws the I-Beam cursor, the top half of this bitmap is first drawn over the desktop with an AND raster operation. The bottom half of the bitmap is then drawn over top with an XOR raster operation. Onscreen, The cursor will appear as the inverse of the content behind it.
One of the [comments](http://www.codeproject.com/Messages/1408725/Have-you-solved-the-IBeam-cursor-problem.aspx) for the original article that you linked mentions this. On the desktop, since the raster operations are applied over the desktop content, the cursor will appear correct. However, when the image is drawn over no background, as in your posted code, the raster operations that Windows performs result in a faded image.
That being said, this updated CaptureCursor() method will handle both color and monochrome cursors, supplying a plain black cursor image when the cursor is monochrome.
```
static Bitmap CaptureCursor(ref int x, ref int y)
{
Win32Stuff.CURSORINFO cursorInfo = new Win32Stuff.CURSORINFO();
cursorInfo.cbSize = Marshal.SizeOf(cursorInfo);
if (!Win32Stuff.GetCursorInfo(out cursorInfo))
return null;
if (cursorInfo.flags != Win32Stuff.CURSOR_SHOWING)
return null;
IntPtr hicon = Win32Stuff.CopyIcon(cursorInfo.hCursor);
if (hicon == IntPtr.Zero)
return null;
Win32Stuff.ICONINFO iconInfo;
if (!Win32Stuff.GetIconInfo(hicon, out iconInfo))
return null;
x = cursorInfo.ptScreenPos.x - ((int)iconInfo.xHotspot);
y = cursorInfo.ptScreenPos.y - ((int)iconInfo.yHotspot);
using (Bitmap maskBitmap = Bitmap.FromHbitmap(iconInfo.hbmMask))
{
// Is this a monochrome cursor?
if (maskBitmap.Height == maskBitmap.Width * 2)
{
Bitmap resultBitmap = new Bitmap(maskBitmap.Width, maskBitmap.Width);
Graphics desktopGraphics = Graphics.FromHwnd(Win32Stuff.GetDesktopWindow());
IntPtr desktopHdc = desktopGraphics.GetHdc();
IntPtr maskHdc = Win32Stuff.CreateCompatibleDC(desktopHdc);
IntPtr oldPtr = Win32Stuff.SelectObject(maskHdc, maskBitmap.GetHbitmap());
using (Graphics resultGraphics = Graphics.FromImage(resultBitmap))
{
IntPtr resultHdc = resultGraphics.GetHdc();
// These two operation will result in a black cursor over a white background.
// Later in the code, a call to MakeTransparent() will get rid of the white background.
Win32Stuff.BitBlt(resultHdc, 0, 0, 32, 32, maskHdc, 0, 32, Win32Stuff.TernaryRasterOperations.SRCCOPY);
Win32Stuff.BitBlt(resultHdc, 0, 0, 32, 32, maskHdc, 0, 0, Win32Stuff.TernaryRasterOperations.SRCINVERT);
resultGraphics.ReleaseHdc(resultHdc);
}
IntPtr newPtr = Win32Stuff.SelectObject(maskHdc, oldPtr);
Win32Stuff.DeleteObject(newPtr);
Win32Stuff.DeleteDC(maskHdc);
desktopGraphics.ReleaseHdc(desktopHdc);
// Remove the white background from the BitBlt calls,
// resulting in a black cursor over a transparent background.
resultBitmap.MakeTransparent(Color.White);
return resultBitmap;
}
}
Icon icon = Icon.FromHandle(hicon);
return icon.ToBitmap();
}
```
There are some issues with the code that may or may not be a problem.
1. The check for a monochrome cursor simply tests whether the height is twice the width. While this seems logical, the ICONINFO documentation does not mandate that only a monochrome cursor is defined by this.
2. There is probably a better way to render the cursor that the BitBlt() - BitBlt() - MakeTransparent() combination of method calls I used. | ```
[StructLayout(LayoutKind.Sequential)]
struct CURSORINFO
{
public Int32 cbSize;
public Int32 flags;
public IntPtr hCursor;
public POINTAPI ptScreenPos;
}
[StructLayout(LayoutKind.Sequential)]
struct POINTAPI
{
public int x;
public int y;
}
[DllImport("user32.dll")]
static extern bool GetCursorInfo(out CURSORINFO pci);
[DllImport("user32.dll")]
static extern bool DrawIcon(IntPtr hDC, int X, int Y, IntPtr hIcon);
const Int32 CURSOR_SHOWING = 0x00000001;
public static Bitmap CaptureScreen(bool CaptureMouse)
{
Bitmap result = new Bitmap(Screen.PrimaryScreen.Bounds.Width, Screen.PrimaryScreen.Bounds.Height, PixelFormat.Format24bppRgb);
try
{
using (Graphics g = Graphics.FromImage(result))
{
g.CopyFromScreen(0, 0, 0, 0, Screen.PrimaryScreen.Bounds.Size, CopyPixelOperation.SourceCopy);
if (CaptureMouse)
{
CURSORINFO pci;
pci.cbSize = System.Runtime.InteropServices.Marshal.SizeOf(typeof(CURSORINFO));
if (GetCursorInfo(out pci))
{
if (pci.flags == CURSOR_SHOWING)
{
DrawIcon(g.GetHdc(), pci.ptScreenPos.x, pci.ptScreenPos.y, pci.hCursor);
g.ReleaseHdc();
}
}
}
}
}
catch
{
result = null;
}
return result;
}
``` | C# - Capturing the Mouse cursor image | [
"",
"c#",
"icons",
"screenshot",
"mouse-cursor",
""
] |
How can i concatenate var names to declare new vars in javascript?:
```
var foo = 'var';
var bar = 'Name';
```
How can i declare variable varName? | Try something like:
```
window[foo + bar] = "whatever";
alert(varName);
```
do not use the eval function unless you are absolutely certain about what's going in. window[] is much safer if all you're doing is variable access | WARNING: VaporCode! Off the top of my head...
```
window[foo + bar] = "contents of variable varName";
```
Does that work? | How to concatenate var names in javascript? | [
"",
"javascript",
""
] |
Personal preferences aside, is there an optimal tab size (2 spaces? 3 spaces? 8 spaces?) for code readability? In the different projects I've worked on, people seem to have vastly different standards. I can't seem to read 2 space indents, but companies like Google use it as a standard.
Can anyone point to documentation, studies, or well-reasoned arguments for the optimal size of a tab?
If we want to get specific, I work mostly in python. The goal of this question is to pick a standard for the team I work on. | [Four spaces and no hard tabs](https://david.goodger.org/projects/pycon/2007/idiomatic/handout.html#whitespace-1), if you're a Pythonista. | I like 8 spaces (I know, right?). It makes the start/ end of blocks really obvious.
As to your question, a formal usability study would be required. Let's look at limits though:
**0 spaces**
```
function test(){
var x = 1;
for (i=0; i<=5; i++){
doSomething();
}
}
```
No indentation is obviously bad. You can't tell where anything begins or ends.
**19 Spaces**
```
function test(){
var x = 1;
for (i=0; i<=5; i++){
doSomething();
}
}
```
Loads of indentation is obviously bad too, because you can't visually link code to its parent function or loop (or what have you) as your peripheral vision doesn't extend that far. Your eyes have to flick too far back and forth to facilitate reading.
**8 spaces**
```
function test(){
var x = 1;
for (i=0; i<=5; i++){
doSomething();
}
}
```
I think I decided on 8 spaces because the word 'function' is 8 characters long. But it just seems so useful for readability. All the code is in my peripheral vision, and there's no way I can miss the start of a new block of code if I'm quickly scanning. | Optimal tab size for code readability | [
"",
"python",
"readability",
""
] |
I need to compare dozens of fields in two objects (instances of the same class), and do some logging and updating in case there are differences. Meta code could look something like this:
```
if (a.getfield1 != b.getfield1)
log(a.getfield1 is different than b.getfield1)
b.field1 = a.field1
if (a.getfield2!= b.getfield2)
log(a.getfield2 is different than b.getfield2)
b.field2 = a.field2
...
if (a.getfieldn!= b.getfieldn)
log(a.getfieldn is different than b.getfieldn)
b.fieldn = a.fieldn
```
The code with all the comparisons is very terse, and I would like to somehow make it more compact. It would be nice if I could have a method which would take as a parameter method calls to setter and getter, and call this for all fields, but unfortunately this is not possible with java.
I have come up with three options, each which their own drawbacks.
**1. Use reflection API to find out getters and setters**
Ugly and could cause run time errors in case names of fields change
**2. Change fields to public and manipulate them directly without using getters and setters**
Ugly as well and would expose implementation of the class to external world
**3. Have the containing class (entity) do the comparison, update changed fields and return log message**
Entity should not take part in business logic
All fields are String type, and I can modify code of the class owning the fields if required.
EDIT: There are some fields in the class which must not be compared. | Use [Annotations](http://java.sun.com/j2se/1.5.0/docs/guide/language/annotations.html).
If you mark the fields that you need to compare (no matter if they are private, you still don't lose the encapsulation, and then get those fields and compare them. It could be as follows:
In the Class that need to be compared:
```
@ComparableField
private String field1;
@ComparableField
private String field2;
private String field_nocomparable;
```
And in the external class:
```
public <T> void compare(T t, T t2) throws IllegalArgumentException,
IllegalAccessException {
Field[] fields = t.getClass().getDeclaredFields();
if (fields != null) {
for (Field field : fields) {
if (field.isAnnotationPresent(ComparableField.class)) {
field.setAccessible(true);
if ( (field.get(t)).equals(field.get(t2)) )
System.out.println("equals");
field.setAccessible(false);
}
}
}
}
```
The code is not tested, but let me know if helps. | The [JavaBeans API](http://java.sun.com/javase/6/docs/api/java/beans/package-summary.html) is intended to help with introspection. It has been around in one form or another since Java version 1.2 and has been pretty usable since version 1.4.
Demo code that compares a list of properties in two beans:
```
public static void compareBeans(PrintStream log,
Object bean1, Object bean2, String... propertyNames)
throws IntrospectionException,
IllegalAccessException, InvocationTargetException {
Set<String> names = new HashSet<String>(Arrays
.asList(propertyNames));
BeanInfo beanInfo = Introspector.getBeanInfo(bean1
.getClass());
for (PropertyDescriptor prop : beanInfo
.getPropertyDescriptors()) {
if (names.remove(prop.getName())) {
Method getter = prop.getReadMethod();
Object value1 = getter.invoke(bean1);
Object value2 = getter.invoke(bean2);
if (value1 == value2
|| (value1 != null && value1.equals(value2))) {
continue;
}
log.format("%s: %s is different than %s%n", prop
.getName(), "" + value1, "" + value2);
Method setter = prop.getWriteMethod();
setter.invoke(bean2, value2);
}
}
if (names.size() > 0) {
throw new IllegalArgumentException("" + names);
}
}
```
Sample invocation:
```
compareBeans(System.out, bean1, bean2, "foo", "bar");
```
If you go the annotations route, consider dumping reflection and generating the comparison code with a compile-time [annotation processor](http://java.sun.com/javase/6/docs/api/javax/annotation/processing/Processor.html) or some other code generator. | What is the best way to compare several javabean properties? | [
"",
"java",
"reflection",
""
] |
I would like to show a div based on the Onclick event of an link.
First Click - Show div1
Second Click - Hide remaining div's and Show div2
Third Click - Hide remaining div's and show div3
Fourth Click - Hide remaining div's and show div1 => repeat the loop and goes on..
> ***Code Follows:***
```
<div class="toggle_button">
<a href="javascript:void(0);" id="toggle_value">Toggle</a>
</div>
<div id='div1' style="display:none;">
<!-- content -->
</div>
<div id='div2' style="display:none;">
<!-- content -->
</div>
<div id='div3' style="display:none;">
<!-- content -->
</div>
```
> ***Jquery Code :***
```
$(document).ready(function() {
$("#toggle_value").click(function(){
$("#div1").show("fast");
$("#div2").show("fast");
$("#div3").show("fast");
});
});
```
The above code shows all divs on first click itself but it should show div1 on first click as mentioned. | I'll try my shot.
---
EDIT:
After second though, to avoid global variable use it's better to do the following
```
$(document).ready(function() {
$("#toggle_value").click((function(){
var counter = 0;
return function()
{
$("#div" + counter).hide("fast");
counter = (counter % 3) + 1;
$("#div" + counter).show("fast");
}
})());
});
``` | You should add a counter in the function.
```
$(document).ready(function() {
var count = 0;
$("#toggle_value").click(function(){
if (count == 0) {
$("#div1").show("fast");
$('#div2').hide();
count++;
}
else if (count == 1) {
$("#div2").show("fast");
...
count++;
}
else if (count == 2) {
$("#div3").show("fast");
....
count++;
}
else {
$('div').hide();
count=0;
}
});
});
``` | Using JQuery how to show and hide different div's onClick event | [
"",
"javascript",
"jquery",
"css",
""
] |
I need to remove the sorting arrow from a column header. This can be done by calling `set_sort_indicator(false)` on the column.
The arrow isn't displayed, but the space for it seems to still be reserved. If the title of the column is big enough to fill all the header, the last part is clipped (where the arrow should be).
Is there a way to make the title fill the whole header? | This seems to be a bit weird in GTK+. I [downloaded](http://ftp.gnome.org/pub/gnome/sources/gtk+/2.16/) and read through relevant parts of the GtkTreeViewColumn's code, and it seems to use this logic:
```
if (tree_column->show_sort_indicator ||
(GTK_IS_TREE_SORTABLE (model) && tree_column->sort_column_id >= 0))
gtk_widget_show (arrow);
else
gtk_widget_hide (arrow);
```
Where `arrow` is the widget holding the arrow. This seems to indicate that the arrow widget is always packed into the horizontal box that makes up the column's header, and then just hidden (not removed) if it's not supposed to be visible. That will mean it's still there in the box, occupying space and causing the label to be clipped.
I'd recommend searching through the [GTK+ bugtracker](http://bugzilla.gnome.org/browse.cgi?product=gtk%2B) for an issue about this, and if none is found, create one. | Ok, so I've submitted a bug report to gtk. They said that it is not an issue and it won't be fixed.
I've looked on other graphical toolkits (windows, qt) and their implementation is different, but this doesn't seem to matter to the guys in the gtk team. | How to remove the GtkTreeView sorting arrow? | [
"",
"c++",
"gtk",
"gtkmm",
""
] |
i've got a question about how is it possible (if possible :)
to use a type reference returned by Type.GetType() to, for example, create IList of that type?
here's sample code :
```
Type customer = Type.GetType("myapp.Customer");
IList<customer> customerList = new List<customer>(); // got an error here =[
```
Thank You in Advance ! | Something like this:
```
Type listType = typeof(List<>).MakeGenericType(customer);
IList customerList = (IList)Activator.CreateInstance(listType);
```
Of course you can't declare it as
```
IList<customer>
```
because it is not defined at compile time. But `List<T>` implements IList, so you can use this. | I recently faced this problem..I realize this is an old question, but thought someone might find useful the solution i found (using net 4.0 ).
This is the setup i had:
```
public interface ISomeInterface{
String GetEntityType{ get; }
}
public abstract class BaseClass : ISomeInterface{
public String GetEntityType {
get{ return this.GetType().ToString(); }
}
}
public class ChildA : BaseClass { }
public class ChildB : BaseClass { }
```
What I did was create a factory method:
```
public static dynamic GetRealType { ISomeInterface param } {
return Activator.CreateInstance("dllname", param.GetEntityType);
}
```
Creating the object as a dynamic type was what solved it for me. I inferred the type by having a method:
```
public void DoSomething<T>(T param){
IList<T> list = somecode...
}
```
this allowed me to do a call to the method and let .net infer the type
```
public void myMethod( ISomeInterface param ) {
dynamic value = Factory.GetRealType ( param );
DoSomething(value);
}
```
Hope i didn't make it all confusing and it actually helps, also, sorry for the wall of text | using type returned by Type.GetType() in c# | [
"",
"c#",
"generics",
"reflection",
""
] |
I'm developing a Java Web Application that runs a series of financial calculations for a user. When a financial calculation is run, roughly 30 different inputs are used to calculate 15 different values over a maximum of 18 years (max 15\*18 expected values). As you can tell, there is a considerable amount of information to compute and validate.
What I am looking for is advice on how to prepare test data (simulate the 30 different inputs), load it into a series of objects, and run the objects through the calculator to generate the output which can then be compared to expected values.
I have attempted to stub a database, but this ended up taking **forever**. Mocking everything seems like it would be just as tedious. I'd like to avoid external database dependencies if possible. | If you have data in Db and you just want to create a test data out of it so that your Tests run are not dependent on external db.You can have a look at DbUnit framework and can populate sample data in XML from DB.
These XML's you can use for Testing purpose ,these XMLs can easily be converted into say java objects by number of commanly available parsers. | It sounds like FitNesse (<http://fitnesse.org/>) might be what you are looking for. You'd setup an html table in FitNesse with your inputs and your expected output. When you run the test, FitNesse will let you know if the actual output matches your expected output. | Testing Complex Data Scenarios | [
"",
"java",
"testing",
""
] |
What's the easiest way to do a case-insensitive string replacement in Python? | The `string` type doesn't support this. You're probably best off using [the regular expression sub method](https://docs.python.org/3/library/re.html#re.sub) with the [re.IGNORECASE](http://docs.python.org/library/re.html#re.IGNORECASE) option.
```
>>> import re
>>> insensitive_hippo = re.compile(re.escape('hippo'), re.IGNORECASE)
>>> insensitive_hippo.sub('giraffe', 'I want a hIPpo for my birthday')
'I want a giraffe for my birthday'
``` | ```
import re
pattern = re.compile("hello", re.IGNORECASE)
pattern.sub("bye", "hello HeLLo HELLO")
# 'bye bye bye'
``` | Case insensitive replace | [
"",
"python",
"string",
"case-insensitive",
""
] |
I am about to start a project for university to build a procedural city for a pre existing project.
I was wondering if any of you have had any experience coding L-Systems before and know a good place for me to start out. I have done a bit of work before using procedural methods and Perlin Noise and fBm so I get the premise of what an L-System is in the fractal sense. I am more looking for a place where maybe can push me in the direction of coding the L-System.
Any help or technical documents you can point me towards would be great. | I did a project on using L-Systems to procedurally generate 3D trees and found the book "[The Algorithmic Beauty of Plants](http://algorithmicbotany.org/papers/#abop)" helpful. It's available for free at that link. Not directly related to procedural cities, but very interesting, and a good resource to learn about L-Systems, I think. | I'm working on an L-system project too, and it's been tremendously helpful to look at some pre-existing code: [lsystem.py](http://www.berniepope.id.au/html/pycol/lsystem.py.html) - There's also pseudocode in [Fundamentals of Natural Computing](https://rads.stackoverflow.com/amzn/click/com/1584886439) which I found really helpful. It takes you through the process of using turtle graphics to create a simple L-system tree, and quickly moves on to more advanced stuff. | Information on L-Systems | [
"",
"c++",
"algorithm",
"procedural-programming",
"procedural-generation",
"l-systems",
""
] |
I have a windows application (C#) and i need to configure it to run one instance from the application at the time , It means that one user clicked the .exe file and the application is run and the user didn't close the first instance of the application that is being run and need to run a next instance so it should appear the first instance and not opening new one.
can any one help me how to do that?
thanks in advance | I often solve this by checking for other processes with the same name. The advantage/disadvantage with this is that you (or the user) can "step aside" from the check by renaming the exe. If you do not want that you could probably use the Process-object that is returned.
```
string procName = Process.GetCurrentProcess().ProcessName;
if (Process.GetProcessesByName(procName).Length == 1)
{
...code here...
}
```
It depends on your need, I think it's handy to bypass the check witout recompiling (it's a server process, which sometimes is run as a service). | The VB.Net team has already implemented a solution. You will need to take a dependency on Microsoft.VisualBasic.dll, but if that doesn't bother you, then this is a good solution IMHO.
See the end of the following article: [Single-Instance Apps](http://msdn.microsoft.com/en-us/magazine/cc163741.aspx)
Here's the relevant parts from the article:
1) Add a reference to Microsoft.VisualBasic.dll
2) Add the following class to your project.
```
public class SingleInstanceApplication : WindowsFormsApplicationBase
{
private SingleInstanceApplication()
{
base.IsSingleInstance = true;
}
public static void Run(Form f, StartupNextInstanceEventHandler startupHandler)
{
SingleInstanceApplication app = new SingleInstanceApplication();
app.MainForm = f;
app.StartupNextInstance += startupHandler;
app.Run(Environment.GetCommandLineArgs());
}
}
```
Open Program.cs and add the following using statement:
```
using Microsoft.VisualBasic.ApplicationServices;
```
Change the class to the following:
```
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
SingleInstanceApplication.Run(new Form1(), StartupNextInstanceEventHandler);
}
public static void StartupNextInstanceEventHandler(object sender, StartupNextInstanceEventArgs e)
{
MessageBox.Show("New instance");
}
}
``` | Run one instance from the application | [
"",
"c#",
"semaphore",
""
] |
I need to be able to tell if a link (URL) points to an XML file (RSS feed), or a regular HTML file just by looking at the headers, or something similiar (without downloading it)
Any good advice for me there ? :)
Thanks!
Roey | You could just do a HEAD request instead of a full POST/GET
That will get you the headers for that page which should include the content type.
From that you should be able to distinguish if its text/html or xml
Theres a good example [here on SO](https://stackoverflow.com/questions/153451/c-how-to-check-if-system-net-webclient-downloaddata-is-downloading-a-binary-fi) | Following up on Eoin Campbell's response, here's a code snippet that should do exactly that using the `System.Net` functionality:
```
using (var request = System.Net.HttpWebRequest.Create(
"http://tempuri.org/pathToFile"))
{
request.Method = "HEAD";
using (var response = request.GetResponse())
{
switch (response.ContentType)
{
case "text/xml":
// ...
break;
case "text/html":
// ...
break;
}
}
}
```
Of course, this assumes that the web server publishes the content (MIME) type and does so correctly. But since you stated that want a bandwidth-efficient way of doing this, I assume you don't want to download all the markup and analyse that! To be honest, the content type is usually set correctly in any case. | C# HttpWebRequest - How to disgtinguish between HTML and XML pages without downloading? | [
"",
"c#",
"html",
"xml",
"httpwebrequest",
"xmlreader",
""
] |
I have an application that uses WebSphere MQ Java API along with a configuration (xml) file to access MQ. I would like to migrate to WebSphere JMS API. For this i try creating
1) WebSphere MQ Queue Connection factory and 2) WebSphere MQ Queue destinations from my local WAS. When i configure my Queue destinations and try to set my MQ Config parametes i get an error message like "WMSG0316E: You tried to view a Queue that was not a local Queue. Only administration of local Queues is supported."
The message is correct in the sense that i am trying to connect to a remote queue. Now, cant i configure my WAS as an MQ client trying to connect to a remote Queue ? The MQ Client has the necessary MQ JMS jars in the server classpath.
Would appreciate if anyone could throw some light into this. | I'm working on this same issue - I've found articles where the authors confirm that WebSphere has to be told that "client to remote queue" mode is desired, but I have yet to find details on how to do that, beyond one author mentioning an environment variable.
Still searching ... I'll post the solution if I find one. | I cut & pasted your error message into Google. In their inimitable style, [here](http://publib.boulder.ibm.com/infocenter/wxdinfo/v6r0/index.jsp?topic=/com.ibm.websphere.messages.doc/com.ibm.ejs.jms.messaging.html) are the IBM docs on your issue. Helpful, no?
Where did you set up the queue that you're trying to contact? Is it running on the same server as the WebSphere instance you've deployed on, or is it a remote server? If it's the latter, I wonder if you need a bridge or proxy so you can appear to send the message locally but have it appear on the remote server via proxy.
UPDATE: I don't know, but perhaps one way to get around this is to set up a local queue, similar to what you say is working, and have it simply forward all messages to the remote queue. | WebSphere MQ using JMS | [
"",
"java",
"jms",
"websphere",
"message-queue",
"ibm-mq",
""
] |
The code below is what I currently have and works fine. I feel that I could do more of the work I am doing in Linq instead of C# code.
Is there is anyone out there who can accomplish the same result with more Linq code and less C# code.
```
public List<Model.Question> GetSurveyQuestions(string type, int typeID)
{
using (eMTADataContext db = DataContextFactory.CreateContext())
{
List<Model.Question> questions = new List<Model.Question>();
List<Linq.Survey_Question> survey_questions;
List<Linq.Survey> surveys = db.Surveys
.Where(s => s.Type.Equals(type) && s.Type_ID.Equals(typeID))
.ToList();
if (surveys.Count > 0)
{
survey_questions = db.Survey_Questions
.Where(sq => sq.Survey_ID == surveys[0].ID).ToList();
foreach (Linq.Survey_Question sq in survey_questions)
{
Model.Question q = Mapper.ToBusinessObject(sq.Question);
q.Status = sq.Status;
questions.Add(q);
}
}
else
{
questions = null;
}
return questions;
}
}
```
Here is my Mapper function from my Entity to Biz Object
```
internal static Model.Question ToBusinessObject(Linq.Question q)
{
return new Model.Question
{
ID = q.ID,
Name = q.Name,
Text = q.Text,
Choices = ToBusinessObject(q.Question_Choices.ToList())
};
}
```
I want my mapper funciton to map the Question Status like so.
```
internal static Model.Question ToBusinessObject(Linq.Question q)
{
return new Model.Question
{
ID = q.ID,
Name = q.Name,
Text = q.Text,
Choices = ToBusinessObject(q.Question_Choices.ToList()),
Status = q.Survey_Questions[?].Status
};
}
```
**?** the issue is this function does not know which survey to pull the status from.
Instead of creating the biz object then setting the Status property in a foreach loop like so
```
foreach (Linq.Survey_Question sq in survey_questions)
{
Model.Question q = Mapper.ToBusinessObject(sq.Question);
q.Status = sq.Status;
questions.Add(q);
}
```
I would like to somehow filter the `EntitySet<Survey_Question>` in the q object above in the calling method, such that there would only be one item in the q.Survey\_Questions[?] collection.
below is my database schema and business object schema
[](https://i.stack.imgur.com/phTZ6.png)
[](https://i.stack.imgur.com/tHF0A.png) | What I needed to do was setup a join.
```
public List<Model.Question> GetSurveyQuestions(string type, int typeID)
{
using (eMTADataContext db = DataContextFactory.CreateContext())
{
return db.Survey_Questions
.Where(s => s.Survey.Type.Equals(type) && s.Survey.Type_ID.Equals(typeID))
.Join(db.Questions,
sq => sq.Question_ID,
q => q.ID,
(sq, q) => Mapper.ToBusinessObject(q, sq.Status)).ToList();
}
}
```
And then overload my Mapper Function
```
internal static Model.Question ToBusinessObject(Linq.Question q, string status)
{
return new Model.Question
{
ID = q.ID,
Name = q.Name,
Text = q.Text,
Status = status,
Choices = ToBusinessObject(q.Question_Choices.ToList()),
};
}
``` | ```
from question in db.Survey_Questions
let surveys = (from s in db.Surveys
where string.Equals(s.Type, type, StringComparison.InvariantCultureIgnoreCase) &&
s.Type_ID == typeID)
where surveys.Any() &&
surveys.Contains(s => s.ID == question.ID)
select new Mapper.Question
{
ID = question.Id,
Name = question.Name,
Text = question.Text,
Choices = ToBusinessObject(question.Question_Choices.ToList()),
Status = question.Status
}
```
Does that get you on the right track? | Refactoring C# code - doing more within Linq | [
"",
"c#",
"linq",
"refactoring",
""
] |
I'm involved in a project where a team of developers is building a very long term infrastructure project to replace an existing 10 year old system. By "very long term" I mean it must be operating, supported and maintained for at least 10 years into the future from the point of release. Taking into account ~2 years of development, this means we should at this point choose a technology/language/framework to last at least 12 years. We have full control over the computers running the project, their operating systems, etc. I was the developer of the to-be-replaced 10 year old system, and I'm helping the team build the new one right.
The application has a very complex user interface. The UI is built dynamically from configuration files at start-up, each UI component has dependencies on logic and other UI components, which it must receive in run-time. UI elements themselves are very complex, imagine custom gauges, graphs, knobs etc.
Two choices have already been made in the project, that I do not judge or try to change:
1. It will be a desktop application
2. It will be developed in C#
Now we are at a point of choosing the right framework to make our very flexible UI system "easy to develop", i.e. reduce the number of developer bugs by relying on a debugged, already-made framework.
The team examined Microsoft's CAB (Composite UI), which suited its purposes extremely well, however the fact Microsoft discontinued it in 2007 is a huge problem taking into account the long-term aspects of the project (think of a framework bug being discovered in 6 years - who will provide support? - and I know we could fix the code in the CAB itself, but that's something we would like to avoid).
One thing that obviously pops to mind is relying Microsoft's WPF. It seems to be "the future" of UI development, however it frightens me when thinking about it long term. My main concern is that the market will not accept it, that 3 years from now Microsoft will discontinue it, and that 6 years from now I will not be able to receive proper support for it.
However I don't really see an alternative, besides writing our own framework. I don't want disrespect any 3rd party framework developers, but for such a long term project I can only use products/frameworks/etc from very well-established vendor.
I would appreciate thoughts on whether choosing WPF is the right call given the above context (and if not - what is the right "complex UI framework" for such a long term desktop application project using C# ?).
Thanks (and sorry for the long question) | Ultra-long-term? 10 years? COBOL is STILL being used!
Joking aside, I believe WPF is your best bet. Microsoft has invested heavily in WPF and XAML over the past few years and using the same core infrastructure on Silverlight (which Microsoft really cares about) is a strong point for sticking to it for enough time. I don't think WPF is going to be thrown away anytime soon. | The fact that the Visual Studio 2010 UI has been rewritten in WPF is quite strong evidence that they'll support it for some time to some. | Choosing C# with WPF for Ultra-Long-Term Project? | [
"",
"c#",
"wpf",
""
] |
I want to get the auto incrementing id column for a create\_table rails command to start at 500.
I've found examples of how to set the initial auto\_increment id value in sql:
```
CREATE TABLE student ( id int(2) NOT NULL auto_increment, name varchar(50) NOT NULL default '', class varchar(10) NOT NULL default '', mark int(3) NOT NULL default '0', sex varchar(6) NOT NULL default 'male', UNIQUE KEY id (id) ) auto_increment=100000 TYPE=MyISAM;
```
So I looked at the Rails API and saw these options on the create\_table method:
```
The options hash can include the following keys:
:id
Whether to automatically add a primary key column. Defaults to true. Join tables for has_and_belongs_to_many should set :id => false.
:primary_key
The name of the primary key, if one is to be added automatically. Defaults to id.
:options
Any extra options you want appended to the table definition.
:temporary
Make a temporary table.
:force
Set to true to drop the table before creating it. Defaults to false.
```
Not what I need... I tried this without success:
```
:options => {:auto_increment => 500}
```
Anyone know how to get the auto incrementing id column for this statement to start at 500:
```
create_table :contents do |t|
t.string :type, :null => false
t.string :name, :null => false
end
``` | Try this:
```
create_table(:student, :options => 'AUTO_INCREMENT = 500') do |t|
t.column :name, :string, :limit => 50
# Other fields here
end
``` | The SQL statement to set this would be:
```
ALTER TABLE student AUTO_INCREMENT = 500;
``` | How to set an initial id value on a create_table? | [
"",
"sql",
"ruby-on-rails",
""
] |
I am going to develop a new website with asp.net 3.5 and LinqToSQL. For maintainability purposes, how can I modify a Linq class if an attribute is added to a table in the database ?
Thank you. | Unfortunately LinqToSQL does not have synchronization support in Visual Studio. The options are:
1. Remove the table and add it again. Of course any customization changes are lost
2. Edit the .dbml file file directly and add the attribute. The file has xml content and when saving it will regenerate the .cs file.
3. Use 3'rd party addins like:
* <http://www.huagati.com/dbmltools/>
* <http://www.perpetuumsoft.com/Product.aspx?lang=en&pid=55&tid=linqtosqlsynchronization> | You will need to regenerate the model each time you changes to the underlying database. | keep LinqToSQL sync with the database | [
"",
"c#",
"visual-studio-2008",
"linq-to-sql",
".net-3.5",
""
] |
1. Is it possible to handle this event in some way?
2. What happens in terms of stack unwinding and deallocation of static/global objects? | EDIT: SIGINT, not SIGTERM. And Assaf reports that no objects are destroyed (at least on Windows) for unhanded SIGINT.
The system sends a SIGINT. This concept applies (with some variance) for all C implementations. To handle it, you call signal, specifying a signal handler. See the documentation on the signal function at [Open Group](http://msdn.microsoft.com/en-us/library/xdkz3x12(vs.71).aspx) and [MSDN](http://msdn.microsoft.com/en-us/library/xdkz3x12(vs.71).aspx).
The second question is a little trickier, and may depend on implementation. The best bet is to handle the signal, which allows you to use `delete` and `exit()` manually. | Ctrl-C in console application will generate a signal. The default handler of this signal calls ExitProcess to terminate the application. You can override this behaviour by setting your own handler functions for the signal using [SetConsoleCtrlHandler](http://msdn.microsoft.com/en-us/library/ms686016(VS.85).aspx) function. | What exactly is the effect of Ctrl-C on C++ Win32 console applications? | [
"",
"c++",
"winapi",
"console",
"copy-paste",
""
] |
I'm working on a Spring 2.0 project, without annotations. We're using several PropertyPlaceholderConfigurer beans with different pre- and suffixes to load properties from different property files. This works beautifully.
Because of the large number of property files and properties, I wanted the application to list the properties which are **not used**. That means, properties which are configured in a property file, but never referenced in the Spring application context.
I wrote a bean which implements BeanFactoryPostProcessor, and did some trickery to find references in the application context to the different PropertyPlaceHolderConfigurers. This gives me a list of properties which are used.
However, I can not get to the properties which were loaded by the PlaceHolderConfigurers. Because of that, I can not show the properties which are NOT used.
Is there a (simple) way to get to the properties of a PropertyPlaceholderConfigurer? Any other suggestions on how to solve this problem?
**Edit**: The solution was accessing the mergeProperties metod, like so:
```
PropertyPlaceholderConfigurer ppc =
(PropertyPlaceholderConfigurer) applicationContext.getBean("yourBeanId");
Method m = PropertiesLoaderSupport.class.getDeclaredMethod("mergeProperties",
new Class[] {});
m.setAccessible(true);
Properties loadedProperties = (Properties) m.invoke(propertyPlaceHolder, null);
```
After getting the originally loaded properties, and fetching the beandefinitions during the BeanFactoryPostProcessing, the rest was simple. Subtract the two collections, and voila: We can now list the unused properties. | You might try calling the protected method [mergeProperties](http://static.springframework.org/spring/docs/2.0.x/api/org/springframework/core/io/support/PropertiesLoaderSupport.html#mergeProperties()) using reflection to get a hold of the complete list of properties, and then, as other posters have already said, remove all properties that are actually used to end up with the set of unused properties.
Probably a bit too hackish for production code, but I am assuming you would be running this only in a unit test setting to generate this report. | How about creating your own subclass of PropertyPlaceholderConfigurer that would keep a reference to the its Properties object and provide an accessor. Your BeanFactoryPostProcessor would then be able to access each original Properties objects and combined with the list of properties which are used you could figure out the properties that were not used. | How to detect unused properties in Spring | [
"",
"java",
"spring",
""
] |
I've taken the advice I've seen in other answered questions about when to throw exceptions but now my APIs have new noise. Instead of calling methods wrapped in try/catch blocks (vexing exceptions) I have out argument parameters with a collection of errors that may have occurred during processing. I understand why wrapping everything in a try/catch is a bad way to control the flow of an app but I rarely see code anywhere that reflects this idea.
That's why this whole thing seems so strange to me. It's a practice that is supposedly the right way to code but I don't see it anywhere. Added to that, I don't quite understand how to relate to client code when "bad" behavior has occured.
Here's a snippet of some code I'm hacking around with that deals with saving pictures that are uploaded by users of a web app. Don't sweat the details (it's ugly), just see the way I've added these output parameters to everything to get error messages.
```
public void Save(UserAccount account, UserSubmittedFile file, out IList<ErrorMessage> errors)
{
PictureData pictureData = _loader.GetPictureData(file, out errors);
if(errors.Any())
{
return;
}
pictureData.For(account);
_repo.Save(pictureData);
}
```
Is this the right idea? I can reasonably expect that a user submitted file is in some way invalid so I shouldn't throw an exception, however I'd like to know what was wrong with the file so I produce error messages. Likewise, any client that now consumes this save method will also want to find out what was wrong with the overall picture saving operation.
I had other ideas about returning some status object that contained a result and additional error messages but that feels weird. I know having out parameters everywhere is going to be hard to maintain/refactor/etc.
I would love some guidance on this!
EDIT: I think the user submitted files snippet may lead people to think of exceptions generated by loading invalid images and other "hard" errors. I think this code snippet is a better illustration of where I think the idea of throwing an exception is being discouraged.
With this I'm just saving a new user account. I do a state validation on the user account and then I hit the persistent store to find out if the username has been taken.
```
public UserAccount Create(UserAccount account, out IList<ErrorMessage> errors)
{
errors = _modelValidator.Validate(account);
if (errors.Any())
{
return null;
}
if (_userRepo.UsernameExists(account.Username))
{
errors.Add(new ErrorMessage("Username has already been registered."));
return null;
}
account = _userRepo.CreateUserAccount(account);
return account;
}
```
Should I throw some sort of validation exception? Or should I return error messages? | By definition, "exception" means an exceptional circumstance from which a routine cannot recover. In the example you provided, it looks like that means the image was invalid/corrupt/unreadable/etc. That should be thrown and bubbled up to the topmost layer, and *there* decide what to do with the exception. The exception itself contains the most complete information about what went wrong, which must be available at the upper levels.
When people say you should not use exceptions to control program flow, what they mean is: (for example) if a user tries to create an account but the account already exists, you should not throw an AccountExistsException and then catch it higher up in the application to be able to provide that feedback to the user, because the account already existing is not an exceptional case. You should expect that situation and handle it as part of your normal program flow. If you can't connect to the database, *that* is an exceptional case.
Part of the problem with your User Registration example is that you are trying to encapsulate too much into a single routine. If your method tries to do more than one thing, then you have to track the state of multiple things (hence things getting ugly, like lists of error messages). In this case, what you could do instead is:
```
UsernameStatus result = CheckUsernameStatus(username);
if(result == UsernameStatus.Available)
{
CreateUserAccount(username);
}
else
{
//update UI with appropriate message
}
enum UsernameStatus
{
Available=1,
Taken=2,
IllegalCharacters=3
}
```
Obviously this is a simplified example, but I hope the point is clear: your routines should only try to do one thing, and should have a limited/predictable scope of operation. That makes it easier to halt and redirect program flow to deal with various situations. | Despite the performance concerns, I think it's actually cleaner to allow Exceptions to be thrown out of a method. If there are any exceptions that can be handled within your method, you should handle them appropriately, but otherwise, let them bubble up.
Returning errors in out parameters, or returning status codes feels a bit clunky. Sometimes when faced with this situation, I try to imagine how the .NET framework would handle the errors. I don't believe there are many .NET framework methods that return errors in out parameters, or return status codes. | How does code look when you don't use exceptions to control flow? | [
"",
"c#",
"exception",
""
] |
I am saving all the words from a file like so:
```
sentence = " "
fileName = sys.argv[1]
fileIn = open(sys.argv[1],"r")
for line in open(sys.argv[1]):
for word in line.split(" "):
sentence += word
```
Everything works okay when outputting it except the formatting.
I am moving source code, is there any way I can save the indention? | When you invoke `line.split()`, you remove all leading spaces.
What's wrong with just reading the file into a single string?
```
textWithIndentation = open(sys.argv[1], "r").read()
``` | Since you state, that you want to *move source code files*, why not just copy/move them?
```
import shutil
shutil.move(src, dest)
```
If you read source file,
```
fh = open("yourfilename", "r")
content = fh.read()
```
should load your file as it is (with indention), or not? | How to save indention format of file in Python | [
"",
"python",
""
] |
For my function
```
IEnumerable<CallbackListRecord> LoadOpenListToProcess(CallbackSearchParams usp);
```
This line errors when the sequence contains no elements (as it should)
```
CallbackListRecord nextRecord = CallbackSearch.LoadOpenListToProcess(p).First();
```
I have changed it to the following
```
CallbackListRecord nextRecord = null;
IEnumerable<CallbackListRecord> nextRecords = CallbackSearch.LoadOpenListToProcess(p);
if (nextRecords.Any())
{
nextRecord = nextRecords.First();
}
```
Are there better, easier or more elegant ways to determine if the IEnumerable sequence has no elements? | You should try to avoid enumerating it more times than necessary (even if short-circuited, like `First` and `Any`) - how about:
```
var nextRecord = CallbackSearch.LoadOpenListToProcess(p).FirstOrDefault();
if(nextRecord != null) {
// process it...
}
```
This works well with classes (since you can just compare the reference to null). | You can shorten the code to the following
```
var nextrecord = CallbackSearch.LoadOpenListToProcess(p).FirstOrDefault();
```
nextrecord will either contain the First element if there was one or null if the collection was empty. | Checking if no elements in IEnumerable(Of T) - Linq element and quantifier operators | [
"",
"c#",
"linq",
"ienumerable",
"element",
""
] |
I've been stumped with some SQL where I've got several rows of data, and I want to subtract a row from the previous row and have it repeat all the way down.
So here is the table:
```
CREATE TABLE foo (
id,
length
)
```
```
INSERT INTO foo (id,length) VALUES(1,1090)
INSERT INTO foo (id,length) VALUES(2,888)
INSERT INTO foo (id,length) VALUES(3,545)
INSERT INTO foo (id,length) VALUES(4,434)
INSERT INTO foo (id,length) VALUES(5,45)
```
I want the results to show a third column called difference which is one row subtracting from the one below with the final row subtracting from zero.
```
+------+------------------------+
| id |length | difference |
+------+------------------------+
| 1 | 1090 | 202 |
| 2 | 888 | 343 |
| 3 | 545 | 111 |
| 4 | 434 | 389 |
| 5 | 45 | 45 |
```
I've tried a self join but I'm not exactly sure how to limit the results instead of having it cycle through itself. I can't depend that the id value will be sequential for a given result set so I'm not using that value. I could extend the schema to include some kind of sequential value.
This is what I've tried:
```
SELECT id, f.length, f2.length, (f.length - f2.length) AS difference
FROM foo f, foo f2
```
Thank you for the assist. | This might help you (somewhat).
```
select a.id, a.length,
coalesce(a.length -
(select b.length from foo b where b.id = a.id + 1), a.length) as diff
from foo a
``` | Yipee!!! this does the trick:
```
SELECT f.id, f.length,
(f.length - ISNULL(f2.length,0)) AS diff
FROM foo f
LEFT OUTER JOIN foo f2
ON f2.id = (f.id +1)
```
Please check for other cases also, it is working for the values you posted!
Note this is for SQL Server 2005 | Subtracting one row of data from another in SQL | [
"",
"sql",
"mysql",
"join",
"subtraction",
""
] |
I am using `XAMPP` on a localhost windows `VISTA` m/c...using gmail as smpt server
I am trying to send an email using simple PHP script
here is the configuration details on `sendmail.ini` (I have the `sendmail.exe` and the other 2 dll in that directory)
```
smtp_server=smtp.gmail.com
; smtp port (normally 25)
smtp_port=465
; the default domain for this server will be read from the registry
; this will be appended to email addresses when one isn't provided
; if you want to override the value in the registry, uncomment and modify
default_domain=localhost
; log smtp errors to error.log (defaults to same directory as sendmail.exe)
; uncomment to enable logging
error_logfile=error.log
; create debug log as debug.log (defaults to same directory as sendmail.exe)
; uncomment to enable debugging
debug_logfile=debug.log
; if your smtp server requires authentication, modify the following two lines
auth_username=xxxxxxx
auth_password=xxxxxx
hostname=localhost
and I have changed the php.ini
[mail function]
; For Win32 only.
;SMTP = localhost
;smtp_port = 25
; For Win32 only.
;sendmail_from = xxxxx
; For Unix only. You may supply arguments as well (default: "sendmail -t -i").
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"
```
and Once I call the script it goes into waiting...for localhost...
here is the debug.log...
> 09/05/02 17:34:41 \*\* --- MESSAGE BEGIN ---
> 09/05/02 17:34:41 \*\* To: xxx@yahoo.com
> 09/05/02 17:34:41 \*\* Subject: Form Submission Results
> 09/05/02 17:34:41 \*\* From: My Web Site
> 09/05/02 17:34:41 \*\* Reply-To: xxx@gmail.com
> 09/05/02 17:34:41 \*\*
> 09/05/02 17:34:41 \*\* Name: xxx
> 09/05/02 17:34:41 \*\* E-Mail: xxx@yahoo.com
> 09/05/02 17:34:41 \*\* Message: hey test message
> 09/05/02 17:34:41 \*\*
> 09/05/02 17:34:41 \*\*
> 09/05/02 17:34:41 \*\* --- MESSAGE END ---
> 09/05/02 17:34:41 \*\* Connecting to smtp.gmail.com:465
> 09/05/02 17:34:41 \*\* Connected.
I am new to `PHP` and would like to know if there is a better way to do mail...I am not in for HTML/multipart mails with attachment now...
Also i should be able to test in localhost without `SMTP` server installed . I would like to use `GMAIL` for now testing.
THnks | I strongly suggest you use a library e.g. [PHPMailer](http://phpmailer.codeworxtech.com/index.php). Here is their [gmail example](http://phpmailer.codeworxtech.com/index.php?pg=examplebgmail).
Another good library (which I haven't used) is [SwiftMailer](http://swiftmailer.org/). Here is their [gmail example](http://swiftmailer.org/wikidocs/v3/connections/smtp). | GMAIL needs SSL afaik.
Of free (and probably "good") php mail libraries i know [Zend\_Mail](http://framework.zend.com/manual/en/zend.mail.html) and [Swiftmailer](http://swiftmailer.org/). | php mail using sendmail.exe | [
"",
"php",
"email",
"sendmail.exe",
""
] |
I have added a parameter to my report with the option "Allow Multiple Values" checked.
This is a status column (IE, Proposed, In Progress, Completed, Canceled), and I want the user to be able to select which (and how many) different OrderStatus to report on.
How I normally set parameters is:
```
report.SetParameterValue("@dtBegin", dtBegin.DateTime);
```
What I tried to do for the multiple values was something like this:
```
//pseudo loop
foreach(int intOrderStatus in intSelectedOrderStatuses)
{
report.Parameter_OrderStatus.CurrentValues.AddValue(intOrderStatus);
}
```
I have checked it does add the values to the OrderStatus parameter, but when the report runs, the CrystalReports dialog pops up and asks me to enter values for the OrderStatus parameter. So it seems as though the values aren't "commited" to the parameter. I have done a number of searches and can't figure out why it's not working.
Thanks, | Just set the parameter value with an array of ints.
```
report.SetParameterValue("@OrderStatus", new int[]{1,2,3});
```
in the select expert you would use the *in* operator.
```
{table.order_status_id} in {?@OrderStatus}
``` | What you can do is, make a normal parameter field,i.e without multiple values, only discreet values true, all you need to pass is 1,2,3,4. "," is the delimiter for separation use what ever you think works for you, then in record selection formula simply put
```
{table.order_status_id} in split({@OrderStatus}, ",")
```
all you need to pass from you page is the string 1,2,3,4 and it should work | Assign multiple values to a parameter in Crystal Reports | [
"",
"c#",
".net",
"crystal-reports",
""
] |
I'm attempting to edit the registry with C++ and this is my first time trying to do so, and I'm failing. I'm not getting any error code, everything says it completed successfully, but it doesn't actually change the registry key.
Here is the code I am using:
```
HKEY hkey;
DWORD dwDisposition, dwType, dwSize;
int autorun = 0x00;
int CD_AUTORUN_DISABLED = 0x20;
long errorCode;
errorCode = RegOpenKeyEx(HKEY_CURRENT_USER, TEXT("Software\\Microsoft\\Windows\\CurrentVersion\\Policies\\Explorer"), 0, KEY_ALL_ACCESS, &hkey);
if(errorCode == ERROR_SUCCESS) {
dwType = REG_DWORD;
dwSize = sizeof(dwType);
errorCode = RegQueryValueEx(hkey, TEXT("NoDriveTypeAutoRun"), NULL, &dwType,
(PBYTE)&autorun, &dwSize);
cout << "Autorun value: " << autorun << endl;
if((autorun & CD_AUTORUN_DISABLED) == 0x20){
int newAutorun = (autorun - CD_AUTORUN_DISABLED);
cout << "New value: " << newAutorun << endl;
errorCode = RegSetValueEx(hkey, TEXT("NoDriveTypeAutoRun"), 0, dwType, (PBYTE) &autorun, dwSize);
if(errorCode == ERROR_SUCCESS){
errorCode = RegCloseKey(hkey);
if(errorCode == ERROR_SUCCESS){
cout << "Value changed." << endl;
}
}else{
cout << "Value change failed, error code: " << errorCode << endl;
}
}else{
cout << "Keep current value." << endl;
}
}else{
if(errorCode == ERROR_ACCESS_DENIED){
cout << "Access denied." << endl;
}else{
cout << "Error! " << errorCode << " : " << ERROR_SUCCESS << endl;
}
}
```
What am I doing wrong? | You appear to be setting the registry key to the same value that you read it.
```
int newAutorun = (autorun - CD_AUTORUN_DISABLED);
cout << "New value: " << newAutorun << endl;
errorCode = RegSetValueEx(hkey, TEXT("NoDriveTypeAutoRun"), 0, dwType, (PBYTE) **&autorun**, dwSize);
```
Should be
```
int newAutorun = (autorun - CD_AUTORUN_DISABLED);
cout << "New value: " << newAutorun << endl;
errorCode = RegSetValueEx(hkey, TEXT("NoDriveTypeAutoRun"), 0, dwType, (PBYTE) &newAutorun, dwSize);
``` | I think this:
```
errorCode = RegSetValueEx(hkey, TEXT("NoDriveTypeAutoRun"), 0, dwType, (PBYTE) &autorun, dwSize);
```
should be this:
```
errorCode = RegSetValueEx(hkey, TEXT("NoDriveTypeAutoRun"), 0, dwType, (PBYTE) &newAutorun, dwSize);
```
(look carefully at 2nd to last param) | Why isn't my change to the registry persisting in C++? | [
"",
"c++",
"windows",
"registry",
""
] |
I would like to iterate the rows and columns separately on a two dimensional array:
```
object[,] values;
```
How would I iterate through just the rows and just the columns? | It depends what's columns and rows for you but you could use this snippet of code:
```
for (int i = 0; i < values.GetLength(0); i++)
Console.WriteLine(values[i, 0]);
```
And:
```
for (int i = 0; i < values.GetLength(1); i++)
Console.WriteLine(values[0, i]);
``` | Here's some code to iterate through the first and second dimensions of the array a 2 dimensional array. (There aren't really "rows" and "columns" because a multidimensional array can have any number of dimensions)
```
object[,] values = new object[5,5];
int rowIWant = 3; //Make sure this is less than values.GetLength(0);
//Look at one "row"
for(int i = 0; i < values.GetLength(1); i++
{
//Do something here with values[rowIWant, i];
}
int columnIWant = 2; //Make sure this is less than values.GetLength(1);
//Look at one "column"
for(int i = 0; i < values.GetLength(0); i++
{
//Do something here values[i, columnIWant];
}
``` | How do I iterate rows and columns of a multidimensional array? | [
"",
"c#",
"arrays",
"multidimensional-array",
""
] |
I have this problem domain where I need to able to run a background process that would:
* Run a filter to get an obj collection (time consuming operation)
* Pass the obj coll through a set of rules...maybe thru a rule interface
* Be able to expose any changes that the rules caused to any interested listeners.
Each filter may have many rules and there can be more than one filter.
Would would be the practical way to approach this? I'm thinking:
* Have a WCF app hosted in a Windows Service that would expose callback for rule changes
* Let the service do the grunt work of running filter->rules. Will this need to be a separate threaded work ?
Any thoughts or references to existing frameworks, design patterns, etc. are welcome.
thanks
Sunit | If your background process needs to be instantly (24/7/365) accessible from remote machines, the Windows service makes a lot of sense to me. Assuming you are familiar with C#, it is trivial to create a Windows service. You can follow the step-by-step [here](https://stackoverflow.com/questions/593454/easiest-language-to-create-a-windows-service/593803#593803). Once you've got the Windows service going, it's easy to host the WCF service by creating the System.ServiceModle.ServiceHost instance in the OnStart callback of the Windows service. As far as WCF patterns and good practices, I'll refer you to Juval Lowy's website, [IDesign.net](http://www.idesign.net). The site has a lot of free WCF-related downloads just by providing your email address. | You have a couple options, the two most obvious are either the client calls a method that starts the job and polls the server for status, or, setup a callback.
Either way the job should be run on a seperate thread so it doesn't block the service.
If you go with the poll for status route, put the actual result in the returning status.
If you go with the callback, use the WSDualHttpBinding and setup a callback. This looks a little scary to setup but it's really not that bad.
I'll let someone else chime in for actual patterns or frameworks, I'm just not sure. Also, checkout MSMQ, this might be another viable solution. | C# Thoughts on this design | [
"",
"c#",
"wcf",
""
] |
When I implement an event in Visual Studio, Resharper is kind enough to offer to create an event invocator for me. I usually did this by hand in the past, and my invocators always looked like this
```
private void InvokePropertyChanged(PropertyChangedEventArgs e)
{
if (PropertyChanged != null)
{
PropertyChanged(this, e);
}
}
```
but the invocator created by Resharper looks like this (cleaned up a little by hand)
```
private void InvokePropertyChanged(PropertyChangedEventArgs e)
{
PropertyChangedEventHandler changed = PropertyChanged;
if (changed != null)
{
changed(this, e);
}
}
```
Do the people at jetbrains know something about c# I don't? Is there some technical advantage to having the local variable, or is it just an artifact of them having to auto-generate the code? | Yes. They know that the number of subscribers to an event can change between the "if" and the call to the event handler. They capture it in a local, where it doesn't change any more. | I think John Saunders probably has the best answer.
For the record, I don't even write "Invocators" anymore. I have extension methods that do it for me, and I just call `PropertyChanged.Fire(this, "propName");`
See [this article](http://www.houseofbilz.com/archive/2009/02/15/re-thinking-c-events.aspx) for more info. | Event Invocators in C# | [
"",
"c#",
"events",
""
] |
Technically it should iterate from 0 to rangeLength outputting the user name of the c[i][0].from\_user...but from looking at example online, they seem to replace the brackets with dot notation. I have the following code:
```
<div id="right_pod">
{%for i in rangeLength%}
<div class="user_pod" >
{{c.i.0.from_user}}
</div>
{% endfor %}
```
This currently outputs nothing :( If I replace "i" with 0...{{c.0.0.from\_user}}...it will output something.. (the first user 10 times) | Do you need `i` to be an index? If not, see if the following code does what you're after:
```
<div id="right_pod">
{% for i in c %}
<div class="user_pod">
{{ i.0.from_user }}
</div>
{% endfor %}
``` | Please read the entire [documentation on the template language's for loops](http://docs.djangoproject.com/en/dev/ref/templates/builtins/#for). First of all, that iteration (like in Python) is over objects, not indexes. Secondly, that within any for loop there is a forloop variable with two fields you'll be interested in:
```
Variable Description
forloop.counter The current iteration of the loop (1-indexed)
forloop.counter0 The current iteration of the loop (0-indexed)
``` | Python Django Template: Iterate Through List | [
"",
"python",
"django",
"django-templates",
""
] |
I've got a console app that loads up a datatable; I'd like to export that to an Excel format and attach it to an email that's sent out on a regular basis.
What is the best library to do so that I can pull down for free? I'm working for an academic institution and we don't have a budget for third-party controls.
---
possible related question: [How to store data to Excel from DataSet without going cell-by-cell?](https://stackoverflow.com/questions/918102/how-to-store-data-to-excel-from-dataset-without-going-cell-by-cell) | Another free lib is [CarlosAg Excel Xml Writer Library](http://www.carlosag.net/Tools/ExcelXmlWriter/). Supports the new xml-based format.
**Clarification**: as we are talking about MS Excel here the new xml-based format is [MS Office XML](http://en.wikipedia.org/wiki/Microsoft_Office_XML_formats). | I would just write a CSV file to the hard drive. | Best free Excel writer for C# to output datatable to excel | [
"",
"c#",
"excel",
"writer",
""
] |
I have VS 2008 and SQL Server 2005 Developer edition installed on my desktop. I have a instance of XP running in Virtual PC and want to connect to the dev instance. I am logged on as a domain user on both the desktop and the Virtual instance of XP. When I try to connect I get a message saying "Server does not exist or access denied". What do I need to do to connect. I am using trusted connection and the userid has privileges on the DB.
Paul | I found out that you have to go into the SQL Server Surface Area Configuration tool and set "Remote Connections" to "Local and remote connections". Apparently the default is "Local connections only". | Make sure that the VPC is not using NAT for its network connection.
Also check your configuration to be sure remote connections are allowed. Remote connection is turned off by default. | Connecting to SQL server from Virtual PC | [
"",
"sql",
"sql-server",
"sql-server-2005",
"virtual-pc",
""
] |
I have a PHP5/Zend Framework 1.8.1 web site which is located at:
```
http://www.example.com/foo
```
The older version of this site, which infuriatingly, is still maintained by google's index was located at:
```
http://www.example.com/foo/DEFAULT.ASP
```
So a lot of people are requesting the above link and hitting a dead end.
I figure, the way to fix this would be to issue a 301 redirect to take him to the new site. The two ways to do this that spring to mind are:
1. The first way I thought of was to add a rewrite rule to our .htaccess . Our site implementation is PHP5 / Zend Framework 1.8.1, so there's an existing rewrite rule in the .htaccess (as per Zend Framework MVC requirement) which is:
```
RewriteRule !\.(js|ico|gif|jpg|png|css|jpeg)$ index.php
```
As a mod\_rewrite noob, I did a bit of googling and came up with the following to handle the redirect:
```
RewriteCond %{HTTP_HOST} ^/foo/DEFAULT.ASP
RewriteRule (.*) http://example.com/foo$1 [R=301,L]
```
I added those lines to the .htaccess, but they do not work.
2. The second way I thought of is to use `Zend_Router_Route_Static` as follows:
```
$router = $frontController->getRouter();
$route = new Zend_Controller_Router_Route_Static('foo/DEFAULT.ASP', array('controller' => 'foo', 'action' => 'index'));
$router->addRoute('foo', $route);
```
This redirects to the correct page, but I have no idea how to set a 301 header as well, plus it's quite inelegant having those lines of code in my `bootstrap.php`
Can anyone offer any advice on how to deal with this situation? I would like to know all or any of:
1. How to get the rewrite rule to work
2. How to do a '301' with
`Zend_Controller_Router_Route` if
possible.
3. Is there another way that I'm
missing?
4. Which is the better way and why?
5. Why isn't google figuring this out?
It has been nearly half a year. | This should work (make sure you put it before the Zend rule):
```
RewriteRule ^foo/DEFAULT.ASP /foo [R=301,L]
```
I'm not sure why Google isn't figuring it out - are you sure you're giving a proper 404 status code? You can check by looking at the headers - in Firefox I use [Live HTTP Headers](http://livehttpheaders.mozdev.org/). | I recently solved a similar problem by adding
```
AddType application/x-httpd-php .asp
```
to the .htaccess file, which makes the server run .asp files with php.
Then I created a file default.asp containing header( 'Location: /', etc ) to replace the one that Google was looking for. I had a few other .asp files with complex parameters that needed to be transformed into new URLs before redirecting, in some cases requiring a database lookup, so it was handy being able to write everything in PHP so I could use include files from other parts of the project. | What's the best way to issue a 301 redirect in this situation? | [
"",
"php",
"zend-framework",
"mod-rewrite",
"http-status-code-301",
""
] |
Several comments on a recent answer of mine, [What other useful casts can be used in C++](https://stackoverflow.com/questions/862858/what-other-useful-casts-can-be-used-in-c/862896#862896), suggest that my understanding of C++ conversions is faulty. Just to clarify the issue, consider the following code:
```
#include <string>
struct A {
A( const std::string & s ) {}
};
void func( const A & a ) {
}
int main() {
func( "one" ); // error
func( A("two") ); // ok
func( std::string("three") ); // ok
}
```
My assertion was that the the first function call is an error, becauuse there is no conversion from a const char \* to an A. There is a conversion from a string to an A, but using this would involve more than one conversion. My understanding is that this is not allowed, and this seems to be confirmed by g++ 4.4.0 & Comeau compilers. With Comeau, I get the following error:
```
"ComeauTest.c", line 11: error: no suitable constructor exists
to convert from "const char [4]" to "A"
func( "one" ); // error
```
If you can point out, where I am wrong, either here or in the original answer, preferably with reference to the C++ Standard, please do so.
**And the answer from the C++ standard seems to be:**
> At most one user-defined conversion
> (constructor or conversion function)
> is implicitly applied to a single value.
**Thanks to Abhay for providing the quote.** | I think the answer from sharptooth is precise. The C++ Standard (SC22-N-4411.pdf) section 12.3.4 titled 'Conversions' makes it clear that only one implicit user-defined conversion is allowed.
> 1 Type conversions of class objects can be specified by
> constructors and by conversion
> functions. These
> conversions are called user-defined conversions and are used
> for implicit type conversions (Clause
> 4), for
> initialization (8.5), and for explicit type conversions (5.4,
> 5.2.9).
>
> 2 User-defined conversions are applied only where they are
> unambiguous (10.2, 12.3.2).
> Conversions obey the
> access control rules (Clause 11). Access control is applied after
> ambiguity resolution (3.4).
>
> 3 [ Note: See 13.3 for a discussion of the use of conversions
> in function calls as well as examples
> below. —end
> note ]
>
> 4 At most one user-defined conversion (constructor or conversion
> function) is implicitly applied to a
> single
> value. | That's true, only one *implicit* conversion is allowed.
Two conversions in a row may be performed with a combination of a conversion operator and a parameterized constructor but this causes a [C4927 warning](http://msdn.microsoft.com/en-us/library/727wstex(VS.80).aspx) - "illegal conversion; more than one user-defined conversion has been implicitly applied" - in VC++ for a reason. | C++ implicit conversions | [
"",
"c++",
""
] |
Okay, it took me a little while to narrow down this problem, but it appears python is doing this one purpose. Can someone explain why this is happening and what I can do to fix this?
File: library/testModule.py
```
class testClass:
myvars = dict()
def __getattr__(self, k):
if self.myvars.has_key(k):
return self.myvars[k]
def __setattr__(self, k, v):
self.myvars[k] = v
def __str__(self):
l = []
for k, v in self.myvars.iteritems():
l.append(str(k) + ":" + str(v))
return " - ".join(l)
```
test.py
```
from library import testModule
#I get the same result if I instantiate both classes one after another
c1 = testClass()
c1.foo = "hello"
c2 = testClass()
print("c1: " + str(c1) + "\n")
print("c2: " + str(c2) + "\n")
```
Output:
```
c1: foo:hello
c2: foo:hello
```
My best guess is that because `library` has an `"__init__.py"` file, the whole module is loaded like a class object and it's now become part of a lasting object.. is this the case? | `myvars` is a property of the *class*, not the *instance*. This means that when you insert an attribute into `myvars` from the instance `c1`, the attribute gets associated with the class `testClass`, not the instance `c1` specifically. Since `c2` is an instance of the same class, it also has the same attribute.
You could get the behavior you want by writing this:
```
class testClass:
def __init__(self):
self.myvars = dict()
def __getattr__(self, k):
if self.myvars.has_key(k):
return self.myvars[k]
def __setattr__(self, k, v):
self.myvars[k] = v
def __str__(self):
l = []
for k, v in self.myvars.iteritems():
l.append(str(k) + ":" + str(v))
return " - ".join(l)
``` | The other answers are correct and to the point. Let me address some of what I think your misconceptions are.
> My best guess is that because library has an "`__init__.py`" file, the whole module is loaded like a class object and it's now become part of a lasting object.. is this the case?
All packages have an `__init__.py` file. It is necessary to make something a python package. That package may or may not have any code in it. If it does it is guaranteed to execute. In the general case, this doesn't have anything to do with how the other modules in the package are executed, although it certainly is possible to put a lot of really cool trickery in there that does affect it.
As for how modules and classes work, it is often a really good idea to think of a module as a class object that gets instantiated once. The loader executes the files once and all variables, class definitions, and function definitions that are available at the end of the file are then accessible as part of the module.
The same is true of classes, with the main exception that functions declared within classes are transformed into methods (and one special method let's you instantiate the class). So `testModule` has-a `testClass` has-a `myvars`. All three objects are unique: there will not be multiple instances of any of them. And the has-a relathionship is really more-or-less the same whether we say "module has-a class object" or "class object has-a class variable". (The difference being implementation details that you ought not be concerned with.) | Python Module/Class Variable Bleeding | [
"",
"python",
"oop",
"class",
""
] |
So we have a C# WinForms project with a Form that contains a bazillion `UserControl`s. Each `UserControl` naturally exposes all the `UserControl` methods, properties, etc. in addition to its own specific members.
I've been thinking that one way to reduce the complexity of dealing with these `UserControl`s is to access them through an interface. So instead of drag-and-drop to put the `UserControl` on the form, something like this in the constructor:
```
public class MyGiantForm
{
ICustomerName cName;
public MyForm()
{
InitializeComponent();
var uc = new SomeCustomerNameUserControl();
this.Controls.Add(uc);
cName = uc;
}
}
```
`SomeCustomerNameUserControl` implements `ICustomerName`, naturally, and `ICustomerName` contains the specific properties I really care about (say, `FirstName` and `LastName`). In this way I can refer to the `UserControl` through the `cName` member and, instead of being bowled over by all the `UserControl` members, I get only those in `ICustomerName`.
All well and good, but the problem is that if I do it this way, I can't see `SomeCustomerNameUserControl` in the Designer. Does anybody know I way I can do this but still see the `UserControl` on the form's design surface?
**EDIT:** One way to do this, which isn't overly complicated, is to put the controls on a base form. By default (in C#) the control members are private. Then I create a property for each control exposing it through the interface.
However, I'd be interested in some other way to do this, even if it's more complex. There seems to be some way to do it with IDesignerHost, but I can't find any applicable examples. | After you add the UserControl using the designer, you can set GenerateMember to false in the Properties window to suppress generation of a member.
You could then use some other technique in the constructor to assign your cName reference, e.g.:
```
foreach(Control control in this.Controls)
{
cName = control as ICustomerName;
if (cName != null) break;
}
```
cName would then be the only reference to the UserControl. | If `SomeCustomerNameUserControl` is defined like this:
```
class SomeCustomerNameUserControl : UserControl, ICustomerName
{
}
```
You can still drop this control in the designer (which creates someCustomerNameUserControl1) and do this whenever you need to:
```
ICustomerName cName = someCustomerNameUserControl1;
```
Maybe I'm missing something, but I think it's that simple. | UserControl as an interface, but visible in the Designer | [
"",
"c#",
".net",
"winforms",
"user-controls",
"custom-controls",
""
] |
Is it true that a service written in C# is unable to give visual feedback to the desktop?
I understand that services start up before user logon and at that point ther is no desktop available. My question then, apart from logging events in the system event log which is not a very efficient way of communicating to the user, what are my alternatives for showing a message box from a service?
Only two options come to mind:
1. MessageBox.Show - Looking around it seems this is not going to be an option.
2. Show a custom form
I've not given the reasons for why this messagebox needs to be shown.
Please assume that it needs to be shown as I don't want responses on "good practice". Not at this point at least. | A windows service should not perform interactions with a user. Instead you should create a seperate control or configuration application - often put into the system tray - that communicates with the service an can present information to the user or gather inputs.
See this [Knowledge Base article](http://support.microsoft.com/kb/327618/en-us) and this [MSDN article](http://msdn.microsoft.com/en-us/library/ms683502(VS.85).aspx) if you really want to do this. They contain some hints how to achiev this an you will probably need to use P/Invoke from C#. | [Here are some ways that you can make interactive services.](http://msdn.microsoft.com/en-us/library/ms683502(VS.85).aspx) But, those have gone away with Vista.
One way you can have a user get information from a service is to build a separate UI for the purpose. The service could have a WCF endpoint for example and push messages out that the GUI would show. That way, you only show a message when there is a user logged in and it's not a security risk by popping up a window from the LocalSystem account. You could easily make this GUI run from the tray and pop-up toast so it is non-intrusive and begins when the user logs in. Much much better than trying to interact directly with the desktop. | Visual feedback from C# service | [
"",
"c#",
"user-interface",
"service",
""
] |
Excuse me if this is a silly question but i'm a beginer here.
I have a simply custom dialog with two buttons: Accept and Cancel. The Accept button is the acceptButton of the form.
I want to do some validations on the Accept\_Click event and decide if i can close the dialog or not, but everytime it leaves this method, the dialog automatically closes itself and returns Ok.
What can I do to stop the dialog from closing itself? or i have to do things in some other way?
thanks | I would have a form level variable (call it \_`vetoClosing`) In the accept button's Click event, I would run validation and set the variable based on that:
```
private void acceptButton_Click(object sender, EventArgs e)
{
// Am I valid
_vetoClosing = !isValid();
}
```
Then in the FormClosing event, I would cancel close if \_vetoClosing is true
```
private void Form_FormClosing(object sender, FormClosingEventArgs e)
{
// Am I allowed to close
if (_vetoClosing)
{
_vetoClosing = false;
e.Cancel = true;
}
}
```
Turning Accept button off is suboptimal because you loose the Enter to Press functionality. | A cleaner solution would be to set DialogResult to None:
```
private void acceptButton_Click(object sender, EventArgs e)
{
if (!isValid()) {
this.DialogResult = System.Windows.Forms.DialogResult.None;
}
}
``` | C# Validate before leaving accept_button event | [
"",
"c#",
".net",
"acceptbutton",
""
] |
For my generic grid I currently do this to activate the sorting:
```
Elements.OrderBy(column.SortExpression).AsQueryable();
```
In which `SortExpression` is of type `Func<T, object>` and column is a generic class `Column<T>`
I set SortExpression in a controller like this:
```
new Column<OrderViewData>{Key = "ShippingDate", SortExpression = e => e.ShippingDate}
```
**The 'OrderBy' causes an execution of the sql statement, which I don't want.**
So I'm trying to replace it with this:
```
Elements = from element in Elements
orderby column.SortExpression
select element;
```
Which doesn't trigger the sql execution.
Now, of course column `SortExpression` should be of another type. Only I can't really figure out what type it should be and how to set it on the generic class in the controller.
I should still be able to set `SortExpression` in a generic strong typed way of some sort.
Any suggestions on how I can order by an expression set somewhere else in the application, without executing the sql when applying the order to the IQueryable?
**@ Earwicker:**
This works:
```
Expression<Func<Employee, DateTime?>> sortexpression = e => e.BirthDate;
var db = new NorthwindDataContext();
var query = from e in db.Employees
select e;
query = query.OrderBy(sortexpression);
int count = query.Count();
```
And generates:
```
SELECT COUNT(*) AS [value]
FROM [dbo].[Employees] AS [t0]
```
When I replace `DateTime`? in the first line with object:
```
Expression<Func<Employee, object>> sortexpression = e => e.BirthDate;
```
I get this exception :
> InvalidOperationException: Cannot order by type 'System.Object'
Now, you might say: "then just use `DateTime`?", but I'd like building the columns in my generic grid to require the least amount of code possible. I don't want people to have to type the whole `Expression<Func<Employee, some_type>>`. I want people to be able to just type something small like my first attempt `SortExpression = e => e.BirthDate`, where I take advantage of the generic Column class to define 'T'.
Do you think it would be possible to create some kind of extension that somehow gets the type of `e.BirthDate` and then casts the `Func<T, object>` to `Expression<Func<T,some_type>>` ?
Then I could do something in the internal code like:
Elements.OrderBy(column.SortExpression.FixCast())
I don't care much that my internal code is ugly or complex at this moment. I need to get the SQL queries right & take care of usability for developers using the grid.
Thanks a lot for helping me out!
**@ earwicker 2:**
```
var gridBuilder = new RainbowGridBuilder<Employee> ("Examples_Employees")
{
Elements = GetEmployees(),
//The elements (records) we will show in our grid.
//Define the columns for our grid.
Columns = new List<Column<Employee >>
{
new Column<Employee>
{
Key = "EmployeeId",
//Key is used for sorting, selecting columns, ...
Header = "Employee Id",
//The header of the column. Also used as caption in the column selection checkboxlist.
ValueExpression = e => e.EmployeeID.ToString(),
//The Linq expression which will be executed on each element to fill the cell
SortExpression = e => e.EmployeeID,
//The Linq expression by which to sort the elements in the grid.
Display = false
}, //Is this column visible by default?
new Column<Employee>
{
Key = "Name",
ValueExpression = e =>
e.FirstName + " " + e.LastName,
SortExpression = e => e.LastName
} ,
},
// Some other properties here that are irrelevant.
}
``` | I came up with a solution that achieves what I was after.
**Usage: Setting strong typed sortexpression on columns:**
```
Columns = new List<Column<Employee>>{
new Column<Employee> {
Key = "EmployeeId",
SortExpression = new SortExpression<Employee>(e => e.EmployeeID)
// ... other irrelevant column properties ...
},
new Column<Employee> {
Key = "EmployeeBirthDate",
SortExpression = new SortExpression<Employee>(e => e.BirthDate)
}
};
```
**Underlying code**
These few lines in the "buildGrid()" method in class RainbowGridBuilder apply the sorting:
```
if (columnToSort != null) //sort the elements according to the set column key and the sortexpression
{
var column = Columns.Where(c => c.Key == columnToSort).SingleOrDefault();
if (column != null)
{
Elements = column.SortExpression.ApplySortExpression(Elements, descending);
}
}
```
How it works:
Trough the use of overloaded constructors in the SortExpression class that I made I can set a private `Expression<Func<T, some_specific_Type>>`.
Inside the SortExpression class is a method ApplySortExpression that searches for a non-null private member and sorts accordingly:
```
public class SortExpression<T>
{
private Expression<Func<T, DateTime?>> DateTimeExpression { get; set; }
private Expression<Func<T, int?>> intExpression { get; set; }
private Expression<Func<T, string>> stringExpression { get; set; }
public SortExpression(Expression<Func<T, DateTime?>> expression)
{
DateTimeExpression = expression;
}
public SortExpression(Expression<Func<T, int?>> expression)
{
intExpression = expression;
}
public SortExpression(Expression<Func<T, string>> expression)
{
stringExpression = expression;
}
public IQueryable<T> ApplySortExpression(IQueryable<T> elements, bool? descending)
{
if (DateTimeExpression != null)
{
if (descending.HasValue && descending.Value)
return elements.OrderByDescending(DateTimeExpression);
else
return elements.OrderBy(DateTimeExpression);
}
else if (intExpression != null)
{
if (descending.HasValue && descending.Value)
return elements.OrderByDescending(intExpression);
else
return elements.OrderBy(intExpression);
}
else if (stringExpression != null)
{
if (descending.HasValue && descending.Value)
return elements.OrderByDescending(stringExpression);
else
return elements.OrderBy(stringExpression);
}
else
throw new Exception("Unsuported sortkey type");
}
}
```
This solution may not be super clean under the hood, but it's the usability that I was after. The only change to the consuming code was to add "`new SortExpression<Employee>`". | SortExpression should be of the type `Expression<Func<T, object>>`.
By making it a `Func<T, object>`, you cause the compiler to reduce it directly down to IL, ready to execute. Linq to SQL (or entities, or NHibernate, or whatever) will need the code captured in the form of an expression tree so it can translate it into SQL or some other query language for execution elsewhere. By assigning your lambda to `Expression<Func<...>>` you trigger compilation to an expression tree.
Does it work if you put this?
```
Elements = Elements.OrderBy(e => e.ShippingDate);
```
And how about this?
```
Expression<Func<OrderViewData, object>> sortExpression = e => e.ShippingDate;
Elements = Elements.OrderBy(sortExpression);
```
Based on your updated question, it sounds like you need to capture an expression with a static-typed return value, instead of `object`.
It's hard to know what would be the ideal arrangement for you, but in your original setup code you had:
```
new Column<OrderViewData>{Key = "ShippingDate", SortExpression = e => e.ShippingDate}
```
Suppose `Column` took two type parameters, `TElem` (the kind of value stored in the column) and `TSort` (the type of the value to sort by).
```
new Column<Employee, DateTime?> { SortExpression = e => e.BirthDate }
```
That doesn't look too unwieldy to me, and `SortExpression` would then just be:
```
Expression<Func<TElem, TSort>> SortExpression { get; set; }
``` | c# - Order a linq query | [
"",
"c#",
"linq-to-sql",
""
] |
Let's assume I browse a specific web page that uses JavaScript to update its view constantly (using Web 2.0 techniques to talk to their server to retrieve updates of data).
Now I like to run some code on my own computer that monitors the contents and alerts me if some specific data appears on the page, so that I could record that data, for instance.
I am looking for ways to accomplish that. Since it's a private project, I am flexible in the choices of my tools (I can program in C and REALbasic, and could manage a little JavaScript as well). The only thing out of my control is the page I want to monitor.
I would prefer a solution I can employ on Mac OS X, but Linux or Windows would be feasible, too.
First, I wonder if there are already solutions for this out there. Something like a user-scriptable web browser, for instance.
If that's not available, I wonder how to best approach this by programming it myself. E.g, can someone tell me if Apple's Webkit allows me to introspect a dynamically updating web page?
As a last resort, I guess I would have to insert my own javascript code into the viewed webpage (I could do that easily, I think, at time of loading the page over the internet), and then have that script run periodically, introspecting the page it's in. The only thing I don't know in this case is how to get it to communicate with the outside, i.e. my computer. I could certainly write an app that it could try talking to, but how could it at all access my computer resources to establish such a communication? As far as I understand the sandboxing of web pages, they cannot read/write local files or communicate with a socket on the computer they're running on, or can they?
So, any ideas are welcome, as long as they're clear of the concept that I have to let a browser or its engine render the page and run the page's Javascripts. | This sounds like it could be pretty easy using [Jetpack](http://labs.mozilla.com/2009/05/introducing-jetpack-call-for-participation/) in Firefox.
You can create browser extensions using Javascript - it's still in alpha but looks to be workable (and *awesome*)... | I agree you could definitely do this with a Firefox extension (I haven't used JetPack, and I don't know if it could handle this). Firefox extensions can communicate with arbitrary [XPCOM](http://en.wikipedia.org/wiki/XPCOM) components. So the extension would have a small JavaScript part to suck the data out of the DOM, then communicate with a C(++) XPCOM component to do anything else.
See [Creating a C++ XPCOM component](http://www.iosart.com/firefox/xpcom/) and [Creating Custom Firefox Extensions with the Mozilla Build System](https://developer.mozilla.org/En/Creating_Custom_Firefox_Extensions_with_the_Mozilla_Build_System) | Dynamic web pages (Javascript) - monitoring contents from outside | [
"",
"javascript",
"webkit",
""
] |
I have a question concerning subtypes of built-in types and their constructors. I want a class to inherit both from tuple and from a custom class.
Let me give you the concrete example. I work a lot with graphs, meaning nodes connected with edges. I am starting to do some work on my own graph framework.
There is a class Edge, which has its own attributes and methods. It should also inherit from a class GraphElement. (A GraphElement is every object that has no meaning outside the context of a specific graph.) But at the most basic level, an edge is just a tuple containing two nodes. It would be nice syntactic sugar if you could do the following:
```
edge = graph.create_edge("Spam","Eggs")
(u, v) = edge
```
So (u,v) would contain "Spam" and "Eggs". It would also support iteration like
```
for node in edge: ...
```
I hope you see why I would want to subtype tuple (or other basic types like set).
So here is my Edge class and its **init**:
```
class Edge(GraphElement, tuple):
def __init__(self, graph, (source, target)):
GraphElement.__init__(self, graph)
tuple.__init__((source, target))
```
When i call
```
Edge(aGraph, (source, target))
```
I get a TypeError: tuple() takes at most 1 argument (2 given). What am I doing wrong? | Since tuples are immutable, you need to override the \_\_new\_\_ method as well. See <http://www.python.org/download/releases/2.2.3/descrintro/#__new__>
```
class GraphElement:
def __init__(self, graph):
pass
class Edge(GraphElement, tuple):
def __new__(cls, graph, (source, target)):
return tuple.__new__(cls, (source, target))
def __init__(self, graph, (source, target)):
GraphElement.__init__(self, graph)
``` | For what you need, I would avoid multiple inheritance and would implement an iterator using generator:
```
class GraphElement:
def __init__(self, graph):
pass
class Edge(GraphElement):
def __init__(self, graph, (source, target)):
GraphElement.__init__(self, graph)
self.source = source
self.target = target
def __iter__(self):
yield self.source
yield self.target
```
In this case both usages work just fine:
```
e = Edge(None, ("Spam","Eggs"))
(s, t) = e
print s, t
for p in e:
print p
``` | Python: Inheriting from Built-In Types | [
"",
"python",
"oop",
"graph",
""
] |
We have a table called `table1` ...
```
(c1 int indentity,c2 datetime not null,c3 varchar(50) not null,
c4 varchar(50) not null,c5 int not null,c6 int ,c7 int)
on column c1 is primary key(clusterd Index)
on column c2 is index_2(Nonclusterd)
on column c3 is index_2(Nonclusterd)
on column c4 is index_2(Nonclusterd)
on column c5 is index_2(Nonclusterd)
```
It contains 10 million records. We have several procedures pointing to "table1" with different search criteria:
```
select from table1 where c1=blah..and c2= blah.. and c3=blah..
select from table1 where c2=blah..and c3= blah.. and c4=blah..
select from table1 where c1=blah..and c3= blah.. and c5=blah..
select from table1 where c1=blah..
select from table1 where c2=blah..
select from table1 where c3=blah..
select from table1 where c4=blah..
select from table1 where c5=blah..
```
What is the best way to create non-clustered index apart from above, or modify existing indexes to get good index performance and reduce the execution time? | And now to actually respond...
The trick here is that you have single-column lookups on any number of columns, as well as composite column lookups. You need to understand with what frequency the queries above are executing - for those that are run very seldom, you should probably exclude them from your indexing considerations.
You *may* be better off creating single NCIX's on each of the columns being queried. This would likely be the case if the number of rows being returned is very small, as the NCIX's would be able to handle the "single lookup" queries as well as the composite lookups. Alternatively, you could create single-column NCIX's *in addition to* covering composite indexes - again, the deciding factor being the frequency of execution and the number of results being returned. | This is somewhat tough to answer with just the information you have provided. There are other factors you need to weigh out.
For example:
How often is the table updated and what columns are updated frequently?
You'll be paying a cost on these updates due to index maintenance.
What is the cardinality of your different columns?
What queries are you executing most often and what columns appear in the where clause of those queries?
You need to first figure out what your parameters for acceptable performance are for each of your queries and work from their taking into account the things I have mentioned above.
With 10 million rows, partitioning your table could make a lot of sense here. | SQL Index Performance | [
"",
"sql",
"sql-server",
"database",
"t-sql",
"indexing",
""
] |
Just wondering if there is a Python [MTA](http://en.wikipedia.org/wiki/Mail_transfer_agent). I took a look at [smtpd](http://docs.python.org/library/smtpd.html) but they all look like forwarders without any functionality. | Yes, Twisted includes a framework for building SMTP servers. There's a simple Twisted-based email server available [here](https://launchpad.net/tx/txmailserver) (also see [here](http://oubiwann.blogspot.com/2009/01/twisted-mail-server-conclusion.html) for some information about its development).
If you want something closer to a mail *application* server, there's [Lamson](https://github.com/zedshaw/lamson). | If you're looking for a full MTA solution you should check out <http://slimta.org/> or as previously mentioned here <http://lamsonproject.org>
I myself has experimented a bit with slimta and it seems to work well. | Is there a Python MTA (Mail transfer agent) | [
"",
"python",
"smtp",
"mta",
"smtpd",
""
] |
Suppose I am calling a query "SELECT name, city, country FROM People". Once I execute my SqlDataReader do columns come in the same order as in my sql query?
In other words can I rely that the following code will always work correctly:
```
SqlConnection connection = new SqlConnection(MyConnectionString);
SqlCommand command = new SqlCommand();
command.Connection = connection;
command.CommandText = "SELECT [name], [city], [country] WHERE [id] = @id";
try
{
connection.Open();
SqlDataReader reader = command.ExecuteReader(System.Data.CommandBehavior.SingleRow);
if (reader.Read())
{
// Read values.
name = reader[0].ToString();
city = reader[1].ToString();
country = reader[2].ToString();
}
}
catch (Exception)
{
throw;
}
finally
{
connection.Close();
}
```
Also how much performance do I lose if I use column names instead of ordinals (reader["name"])?
Are there any official microsoft documents describing the behavior of column ordering in SqlDataReader? | Yes they do but you can also use SqlDataReader.GetName(ordinal) and SqlDataReader.GetOrdinal(name).
As for performance, I think it's probably extremely insignificant compared to the overhead of say, retrieving the next row of data. | I totally agree with Josh - the positions of the fields are indeed such as you specify them in your SQL query text.
BUT: I would still prefer to use the column names, since it's more robust. E.g. what if you need to add a field to your SQL query?
```
command.CommandText = "SELECT [name], [jobtitle], [city], [country] WHERE [id] = @id";
```
Now suddenly you have to rewrite all your code to change the positions....
What I normally do outside the loop that enumerates through all the rows returned by the data reader is determine the positions of each field I'm interested in:
```
int namePosition = reader.GetOrdinal("name");
int cityPosition = reader.GetOrdinal("city");
```
and then I use these positions inside my loop handling the data to get quick access to the individual fields. That way you determine the positions only once, but you're using positions in your looping over the data - the best of both worlds! :-)
Marc | SqlDataReader Column Ordinals | [
"",
"asp.net",
"sql",
"sql-server",
"ado.net",
"sqldatareader",
""
] |
Using a `for` loop, how can I loop through all except the last item in a list? I would like to loop through a list checking each item against the one following it. Can I do this without using indices? | ```
for x in y[:-1]
```
If `y` is a generator, then the above will not work. | the easiest way to compare the sequence item with the following:
```
for i, j in zip(a, a[1:]):
# compare i (the current) to j (the following)
``` | How to loop through all but the last item of a list? | [
"",
"python",
"list",
"for-loop",
""
] |
I have the enum structure as follows:
```
public enum MyEnum
{
One=1,
Two=2,
Three=3
}
```
Now I want to get a list of `MyEnum`, i.e., `List<MyEnum>` that contains all the `One`, `Two` `Three`. [Again](https://stackoverflow.com/questions/782096/convert-listt-to-object), I am looking for a one liner that does the thing. I came out with a LINQ query but it was unsatisfactory because it was a bit too long, I think:
```
Enum.GetNames(typeof(MyEnum))
.Select(exEnum =>
(MyEnum)Enum.Parse(typeof(MyEnum), exEnum))
.ToList();
```
A better suggestion? | ```
Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>();
``` | I agree with @mquander's code.
However, I would suggest you also *cache* the list, since it's extremely unlikely to change over the course of the execution of your program. Put it in a static readonly variable in some global location:
```
public static class MyGlobals
{
public static readonly List<MyEnum> EnumList =
Enum.GetValues(typeof(MyEnum)).Cast<MyEnum>().ToList();
}
``` | Get a List of available Enums | [
"",
"c#",
""
] |
I don't like to lock up my code with *synchronized(this)*, so I'm experimenting with using *AtomicBooleans*. In the code snippet, *XMPPConnectionIF.connect()* makes a socket connection to a remote server. Note that the variable *\_connecting* is only ever used in the *connect()* method; whereas *\_connected* is used in every other methods that needs to use the *\_xmppConn*. My questions are listed after the code snippet below.
```
private final AtomicBoolean _connecting = new AtomicBoolean( false );
private final AtomicBoolean _connected = new AtomicBoolean( false );
private final AtomicBoolean _shuttingDown = new AtomicBoolean( false );
private XMPPConnection _xmppConn;
/**
* @throws XMPPFault if failed to connect
*/
public void connect()
{
// 1) you can only connect once
if( _connected.get() )
return;
// 2) if we're in the middle of completing a connection,
// you're out of luck
if( _connecting.compareAndSet( false, true ) )
{
XMPPConnectionIF aXmppConnection = _xmppConnProvider.get();
boolean encounteredFault = false;
try
{
aXmppConnection.connect(); // may throw XMPPException
aXmppConnection.login( "user", "password" ); // may throw XMPPException
_connected.compareAndSet( false, true );
_xmppConn = aXmppConnection;
}
catch( XMPPException xmppe )
{
encounteredFault = true;
throw new XMPPFault( "failed due to", xmppe );
}
finally
{
if( encounteredFault )
{
_connected.set( false );
_connecting.set( false );
}
else
_connecting.compareAndSet( true, false );
}
}
}
```
1. Based on my code, is it thread safe to the point that if 2 threads attempt to call *connect()* at the same time, only one connection attempt is allowed.
2. In the finally block, I am executing two AtomicBoolean.set(..) in succession, will be there be a problem, since during the gap between these 2 atomic calls, some threads might call *\_connected.get()* in other methods ?
3. When using *\_xmppConn*, should I do a *synchronized( \_xmppConn )* ?
**UPDATE** Added missing login call into the method. | 1. Yes. The variable \_connecting acts as a test-and-set lock that prevents multiple concurrent connection attempts.
2. No problem -- even if another thread reads \_connected between the writes, \_connecting will prevent it from attempting to connect concurrently.
3. Yes, assuming that its methods are not already thread-safe.
That being said, your connect() method would drive me nuts in its current form, since it doesn't necessarily connect or throw an exception. You could add a spin loop, but that's not really a good fit because for all but the shortest of network hops from a multiprocessor machine, it will be more efficient to yield. The low-level concurrency primitives, moreover, are a lot more error-prone than synchronized -- I ***strongly*** recommend you stick with synchronized. | Keep in mind that using 3 `AtomicBoolean`s is **not** the same as guarding those three variables with a single lock. It seems to me like the state of those variables constitutes a single state of the object and thus that they should be guarded by the same lock. In your code using atomic variables, it's possible for different threads to update the state of `_connected`, `_connecting`, and `_shuttingDown` independently -- using atomic variables will only ensure that access to the **same** variable is synchronized between multiple threads.
That said, I don't think synchronizing on the `this` is what you want to do. You only want to synchronize access to the connection state. What you could do is create an object to use as the lock for this state without getting the monitor on `this`. Viz:
```
class Thing {
Boolean connected;
Boolean connecting;
Boolean shuttingDown;
Object connectionStateLock = new Object();
void connect() {
synchronized (connectionStateLock) {
// do something with the connection state.
}
}
void someOtherMethodThatLeavesConnectionStateAlone() {
// free range thing-doing, without getting a lock on anything.
}
}
```
If you're doing concurrent programming in Java, I would highly recommend reading [Java Concurrency In Practice](https://rads.stackoverflow.com/amzn/click/com/0321349601). | This class uses AtomicBooleans. Is it thread safe? | [
"",
"java",
"multithreading",
"concurrency",
"xmpp",
"smack",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.