Prompt stringlengths 10 31k | Chosen stringlengths 3 29.4k | Rejected stringlengths 3 51.1k | Title stringlengths 9 150 | Tags listlengths 3 7 |
|---|---|---|---|---|
I've given a client the following query to delete duplicate phone no. records in an MSSQL database, but now they need to also do it on MySQL, and they report that MySQL complains about the format of the query. I've included the setup of a test table with duplicates for my code sample, but the actual delete query is what counts.
I'm asking this in ignorance and urgency, as I am still busy downloading and installing MySQL, and just maybe somebody can help in the mean time.
```
create table bkPhone
(
phoneNo nvarchar(20),
firstName nvarchar(20),
lastName nvarchar(20)
)
GO
insert bkPhone values('0783313780','Brady','Kelly')
insert bkPhone values('0845319792','Mark','Smith')
insert bkPhone values('0834976958','Bill','Jones')
insert bkPhone values('0845319792','Mark','Smith')
insert bkPhone values('0828329792','Mickey','Mouse')
insert bkPhone values('0834976958','Bill','Jones')
alter table bkPhone add phoneId int identity
delete from bkPhone
where phoneId not in
(
select min(phoneId)
from bkPhone
group by phoneNo,firstName,lastName
having count(*) >= 1
)
``` | Many ways lead to Rome. This is one. It is very fast. So you can use it with big databases. Don't forget the indeces.
The trick is: make phoneNo unique and use "ignore".
```
drop table if exists bkPhone_template;
create table bkPhone_template (
phoneNo varchar(20),
firstName varchar(20),
lastName varchar(20)
);
insert into bkPhone_template values('0783313780','Brady','Kelly');
insert into bkPhone_template values('0845319792','Mark','Smith');
insert into bkPhone_template values('0834976958','Bill','Jones');
insert into bkPhone_template values('0845319792','Mark','Smith');
insert into bkPhone_template values('0828329792','Mickey','Mouse');
insert into bkPhone_template values('0834976958','Bill','Jones');
drop table if exists bkPhone;
create table bkPhone like bkPhone_template;
alter table bkPhone add unique (phoneNo);
insert ignore into bkPhone (phoneNo,firstName,lastName) select phoneNo,firstName,lastName from bkPhone_template;
drop table bkPhone_template;
```
If the data table already exists, then you only have to run a create table select with a following insert ignore select. At the end you have to run some table renaming statements. That's all.
This workaround is much,much faster then a delete operation. | You can select out the unique ones by:
```
select distinct(phoneNo) from bkPhone
```
and put them into another table, delete the old table and rename the new one to the old name. | How to delete Duplicates in MySQL table | [
"",
"sql",
"mysql",
"database",
""
] |
I need a java library to read vcard files (vcf). | A [search for Java and vcard](http://www.google.com/search?q=java+vcard) yields quite a few results.
In particular there's the [Mime-Dir-j](http://sourceforge.net/projects/mime-dir-j/) which is no longer under active development, but may be all you need, and [vcard4j](http://sourceforge.net/projects/vcard4j) which seems to have been dormant for even longer (last release 2003!). | [ez-vcard](https://github.com/mangstadt/ez-vcard) supports versions 2.1, 3.0, and 4.0 of the vCard standard, as well as XML-encoded vCards ("xCard" standard), HTML-encoded vCards ("hCard" microformat), and JSON-encoded vCards ("jCard" standard).
<https://github.com/mangstadt/ez-vcard>
To read a vCard file, use the `Ezvcard.parse()` method. Then, call the various getter methods on the returned `VCard` object to retrieve the vCard data fields.
```
File file = new File("my-vcard.vcf");
VCard vcard = Ezvcard.parse(file).first();
System.out.println("Name: " + vcard.getFormattedName().getValue());
System.out.println("Email: " + vcard.getEmails().get(0).getValue());
``` | Where to find a java library to read vcard files? | [
"",
"java",
"vcf-vcard",
""
] |
What is the overhead of generating a lot of temporary objects (i.e. for interim results) that "die young" (never promoted to the next generation during a garbage collection interval)? I'm assuming that the "new" operation is very cheap, as it is really just a pointer increment. However, what are the hidden costs of dealing with this temporary "litter"? | Not a lot - the garbage collector is very fast for gen0. It also tunes itself, adjusting the size of gen0 depending on how much it manages to collect each time it goes. (If it's managed to collect a lot, it will reduce the size of gen0 to collect earlier next time, and vice versa.)
The ultimate test is how *your* application performs though. Perfmon is very handy here, showing how much time has been spent in GC, how many collections there have been of each generation etc. | As you say the allocation itself is very inexpensive. The cost of generating lots of short lived objects is more frequent garbage collections as they are triggered when generation 0's budget is exhausted. However, a generation 0 collection is fairly cheap, so as long as your object really are short lived the overhead is most likely not significant.
On the other hand the common example of concatenating lots of strings in a loop pushes the garbage collector significantly, so it all depends on the number of objects you create. It doesn't hurt to think about allocation.
The cost of garbage collection is that managed threads are suspended during compaction. | Short-lived objects | [
"",
"c#",
".net",
"memory-management",
"garbage-collection",
""
] |
I have a table with a foreign key and a boolean value (and a bunch of other columns that aren't relevant here), as such:
```
CREATE TABLE myTable
(
someKey integer,
someBool boolean
);
insert into myTable values (1, 't'),(1, 't'),(2, 'f'),(2, 't');
```
Each someKey could have 0 or more entries. For any given someKey, I need to know if a) all the entries are true, or b) any of the entries are false (basically an AND).
I've come up with the following function:
```
CREATE FUNCTION do_and(int4) RETURNS boolean AS
$func$
declare
rec record;
retVal boolean = 't'; -- necessary, or true is returned as null (it's weird)
begin
if not exists (select someKey from myTable where someKey = $1) then
return null; -- and because we had to initialise retVal, if no rows are found true would be returned
end if;
for rec in select someBool from myTable where someKey = $1 loop
retVal := rec.someBool AND retVal;
end loop;
return retVal;
end;
$func$ LANGUAGE 'plpgsql' VOLATILE;
```
... which gives the correct results:
```
select do_and(1) => t
select do_and(2) => f
select do_and(3) => null
```
I'm wondering if there's a nicer way to do this. It doesn't look too bad in this simple scenario, but once you include all the supporting code it gets lengthier than I'd like. I had a look at casting the someBool column to an array and using the ALL construct, but I couldn't get it working... any ideas? | No need to redefine functions PostgreSQL already provides: [bool\_and](http://www.postgresql.org/docs/current/interactive/functions-aggregate.html)() will do the job:
```
select bool_and(someBool)
from myTable
where someKey = $1
group by someKey;
```
(Sorry, can't test it now) | Similar to the previous one, but in one query, this will do the trick, however, it is not clean nor easily-understandable code:
```
SELECT someKey,
CASE WHEN sum(CASE WHEN someBool THEN 1 ELSE 0 END) = count(*)
THEN true
ELSE false END as boolResult
FROM table
GROUP BY someKey
```
This will get all the responses at once, if you only want one key just add a WHERE clause | How can I perform an AND on an unknown number of booleans in postgresql? | [
"",
"sql",
"postgresql",
"plpgsql",
""
] |
This question provides more clarity on the problem described [here](https://stackoverflow.com/questions/616270/reasons-for-stack-unwinding-fail). I did some more investigation and found that the stack unwinding is not happening in the following piece of code:
```
class One
{
public:
int x ;
};
class Wrapper
{
public:
Wrapper(CString csText):mcsText(csText)
{
CString csTempText;
csTempText.Format("Wrapper constructor :: %s\n", mcsText);
OutputDebugString(csTempText);
}
~Wrapper()
{
CString csTempText;
csTempText.Format("Wrapper destructor :: %s\n", mcsText);
OutputDebugString(csTempText);
}
CString mcsText;
};
class Test
{
public:
void notifyError()
{
try
{
int x = 10;
}
catch(...) {}
}
void OnRecvBuffer()
{
try
{
Wrapper a("AddRef");
One* p = NULL;
p->x = 10;
}
catch(...)
{
notifyError();
}
}
};
int main()
{
Test* pTest = new Test;
pTest->OnRecvBuffer();
OutputDebugString("Test");
}
```
I compiled this code using VC6 SP5 compiler and the output is "Wrapper constructor :: AddRef!!!" (i.e. the destructor of wrapper object which was constructed on stack is not called. Is this the expected behavior ? or is it a bug with VC compiler ? Can I use some compiler flags so that the stack unwinding happens in this case? | If you want to use SEH, you must use \_set\_se\_translator function and /EHa compiler option. | **The C++ standard does not give anything to work with in case of Undefined Behavior. Even if MS does. That's a platform specific thing -- so beware. Some such floating point exceptions are turned to Win32 exceptions which you can attempt to catch with `_set_se_translator()`. The problem is you can catch Win32 exceptions but then your stack will not be unwound properly. At least that is not something you can bet your life on. Wherein lies the futility of the exercise.**
> Update: The exception is thrown intentionally to check the stack unwinding. The question is why Wrapper class's destructor is not getting called. – Naveen
If this is the case -- don't do it. There are better ways to throw exceptions than via Undefined Behavior.
E.g:
```
void OnRecvBuffer()
{
try
{
Wrapper a("AddRef");
throw 42; // this'll throw an exception without invoking UB
}
catch(...)
{
notifyError();
}
}
```
You cannot dereference a NULL pointer. You are invoking Undefined Behavior here:
```
One* p = NULL;
p->x = 10;
```
After that line all bets are off and you **could** have killed us all ;)
`p` is a pointer to a `One` object. It should contain the address of an `One` object. You have initialized it to 0 -- there is no object at address 0. 0 is not a valid address for any object (this is guranteed by the standard). | Stack unwinding in case of structured exceptions | [
"",
"c++",
"mfc",
"exception",
"stack",
"seh",
""
] |
How do I convert from `std::stringstream` to `std::string` in C++?
Do I need to call a method on the string stream? |
```
yourStringStream.str()
``` | Use the [.str()-method](http://www.cppreference.com/wiki/io/sstream/str):
> Manages the contents of the underlying string object.
>
> 1) Returns a copy of the underlying string as if by calling `rdbuf()->str()`.
>
> 2) Replaces the contents of the underlying string as if by calling `rdbuf()->str(new_str)`...
>
> **Notes**
>
> The copy of the underlying string returned by str is a temporary object that will be destructed at the end of the expression, so directly calling [`c_str()`](http://en.cppreference.com/w/cpp/string/basic_string/c_str) on the result of `str()` (for example in `auto *ptr = out.str().c_str();`) results in a dangling pointer... | How do I convert from stringstream to string in C++? | [
"",
"c++",
"string",
"stringstream",
""
] |
I want to add a new tab page for every newly opened form.
Example:
```
frmReport reportform = new frmReport();
report.Show();
```
When I open the `frmReport` form, it must be opened in a new `TabPage`, as in Windows Internet Explorer 7-8 tabpages. | i used DevExpress Controls for tabPages. | What you would like to achive here is to have "windows inside tab pages". This is not like it supposed to be! It looks like this:
* Windows OS
* Windows of applications (Window class)
* Containers placed on Window (for example: Panel, TabControl!)
* Controls placed on Windows and Containers (for example: Button, but also containers like Panel!)
So when you look on this you see that it's not ok to put Windows class into TabControl!
So what to do?
Create for example UserControl class and move all your controls from Window to this new UserControl. Next place on your Window TabControl nad on one of it's TabPages put this newly created UserControl.
In this way you'll have a good designed UI. Once again: You do not put Window on your TabPage! | TabPages for newly opened Windows Forms C# | [
"",
"c#",
"winforms",
""
] |
I have got a form which a user can use to create a new store and to edit an existing one. When this form is being used to edit a store there are certain fields that I want the user to see but not edit eg. store\_id. I have explored the different Zend\_Form\_Elements hoping to find some kind of static element but with no luck.
So my question is, how do I display information using Zend\_Form that a user can't edit?
Thanks. | I just managed to work this one out myself. The solution was to change the view helper on the elements to the formNote helper eg. $element->helper = 'formNote'. The result of this was that the value gets displayed as straight text instead of being inside a form element.
Thanks for your answers. | `readonly` alone is not enough, because users will still be able to edit it if they really want. You should use `$element->setIgnore(true)` that will ensure that `Zend_Form_Element` won't try to populate the element from POST/GET, and I'd double check that also. You have to make sure the values you are getting into the databases can never contain this element.
Finally, if you would like your element to be displayed in a different way than just with `readonly`, you can do that by changing the element decorators. | Zend Framework - Static form elements | [
"",
"php",
"zend-framework",
"zend-form",
""
] |
I'm basically looking for a way to access a hashtable value using a two-dimensional typed key in c#.
Eventually I would be able to do something like this
```
HashTable[1][false] = 5;
int a = HashTable[1][false];
//a = 5
```
This is what I've been trying...hasn't worked
```
Hashtable test = new Hashtable();
test.Add(new Dictionary<int, bool>() { { 1, true } }, 555);
Dictionary<int, bool> temp = new Dictionary<int, bool>() {{1, true}};
string testz = test[temp].ToString();
``` | I think a better approach is to encapsulate the many fields of your multi-dimensional key into a class / struct. For example
```
struct Key {
public readonly int Dimension1;
public readonly bool Dimension2;
public Key(int p1, bool p2) {
Dimension1 = p1;
Dimension2 = p2;
}
// Equals and GetHashCode ommitted
}
```
Now you can create and use a normal HashTable and use this wrapper as a Key. | You can do this in C# 7.0 now with the new tuples:
```
// Declare
var test = new Dictionary<(int, bool), int>();
// Add
test.Add((1, false), 5);
// Get
int a = test[(1, false)];
``` | Hashtable with MultiDimensional Key in C# | [
"",
"c#",
"dictionary",
"hashtable",
""
] |
I use Wordpress as a CMS, where the front page is static for the most part and the actual blog part of it has been moved to a new page that uses a custom page template that basically acts as if it were the front page on a standard Wordpress install. It works pretty well but it still has a few bugs. The main one is that pagination will no longer work, Wordpress won't recognize the page URLs that are generated.
So far I've configured Wordpress to display the correct URLs (domain.com/blog/page/2 instead of domain.com/page/2), and I've also gotten it to display a specific page of blog posts via a URL parameter (domain.com/blog?page=N). So basically I'm almost done, I just need to map domain.com/blog/page/N to domain.com/blog?page=N. This would be an easy task if it were just a plain old static site, but Wordpress has it's own URL handling that I believe may be interfering with it - not to mention "blog" isn't an actual URL so it needs to go through the rules twice, once for mapping the blog pagination, and once again so Wordpress can handle the generated URL as it would regularly... I think I may need to use the N or NS flags for the rewrite rules but I just don't know how I would use them
The rule I've come up with:
```
RewriteRule ^/blog/page/([0-9]+)$ /blog?page=$1
```
Default Wordpress .htaccess:
```
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
```
As per some suggestions, I've gotten this for the .htaccess, but it still doesn't recognize it.
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteRule /blog/page/([0-9]+)$ /blog?page=$1 [N,QSA]
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
```
And I'm fairly certain changing the page via the URL parameter does work - I change the number in the URL manually and it does in fact change the page. The web server is LiteSpeed, if that makes any difference | I figured it out eventually (a few days after -- I just forgot about this until now). First, make sure you have Wordpress updated. At the time I was using 2.5 or 2.6 but for some reason it didn't work until I updated.
First, create a custom template. You will use this template for your homepage so customize it and all that jazz. Leave the "Main Index" (index.php) template alone -- that template will be used for the blog index page so it needs the WP loop to list your blog posts.
Now, go and create two pages. One for your home page (let's call it "home") and another for your blog (let's call it "blog"). On the "home" page, set the the template to the homepage template you created previously. On the blog page, leave it on the default template -- it will use the "Main Index" template by default.
Now, go into your "Reading" settings and change it to "A static page." For the front page, select the "home" page you created previously. For the posts page, select the "blog" page you created.
That should be it. I had actually tried this beforehand but it did not work so I tried using redirect rules, to no avail. I ended up being an out of date WP install. If you have a sitemap mod installed, make sure you exclude the "home" page so the spiders don't pick up a duplicate of your home page at example.com/home. You can also put it in your robots.txt to be sure.
Once you're done, the root (example.com/) of your domain (assuming you have WP installed there) will point to your "home" page. Your blog page (example.com/blog) will list your posts. Pagination will work as expected (example.com/blog/page/2 etc.). | Try the following
```
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule /blog/page/([0-9]+)$ /blog?page=$1 [R=301]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
``` | WordPress + mod_rewrite | [
"",
"php",
"wordpress",
"mod-rewrite",
""
] |
I wrote a C# program to read an Excel .xls/.xlsx file and output to CSV and Unicode text. I wrote a separate program to remove blank records. This is accomplished by reading each line with `StreamReader.ReadLine()`, and then going character by character through the string and not writing the line to output if it contains all commas (for the CSV) or all tabs (for the Unicode text).
The problem occurs when the Excel file contains embedded newlines (\x0A) inside the cells. I changed my XLS to CSV converter to find these new lines (since it goes cell by cell) and write them as \x0A, and normal lines just use StreamWriter.WriteLine().
The problem occurs in the separate program to remove blank records. When I read in with `StreamReader.ReadLine()`, by definition it only returns the string with the line, not the terminator. Since the embedded newlines show up as two separate lines, I can't tell which is a full record and which is an embedded newline for when I write them to the final file.
I'm not even sure I can read in the \x0A because everything on the input registers as '\n'. I could go character by character, but this destroys my logic to remove blank lines. | I would recommend that you change your architecture to work more like a parser in a compiler.
You want to create a lexer that returns a sequence of tokens, and then a parser that reads the sequence of tokens and does stuff with them.
In your case the tokens would be:
1. Column data
2. Comma
3. End of Line
You would treat '\n' ('\x0a') by its self as an embedded new line, and therefore include it as part of a column data token. A '\r\n' would constitute an End of Line token.
This has the advantages of:
1. Doing only 1 pass over the data
2. Only storing a max of 1 lines worth of data
3. Reusing as much memory as possible (for the string builder and the list)
4. It's easy to change should your requirements change
Here's a sample of what the Lexer would look like:
**Disclaimer:** I haven't even compiled, let alone tested, this code, so you'll need to clean it up and make sure it works.
```
enum TokenType
{
ColumnData,
Comma,
LineTerminator
}
class Token
{
public TokenType Type { get; private set;}
public string Data { get; private set;}
public Token(TokenType type)
{
Type = type;
}
public Token(TokenType type, string data)
{
Type = type;
Data = data;
}
}
private IEnumerable<Token> GetTokens(TextReader s)
{
var builder = new StringBuilder();
while (s.Peek() >= 0)
{
var c = (char)s.Read();
switch (c)
{
case ',':
{
if (builder.Length > 0)
{
yield return new Token(TokenType.ColumnData, ExtractText(builder));
}
yield return new Token(TokenType.Comma);
break;
}
case '\r':
{
var next = s.Peek();
if (next == '\n')
{
s.Read();
}
if (builder.Length > 0)
{
yield return new Token(TokenType.ColumnData, ExtractText(builder));
}
yield return new Token(TokenType.LineTerminator);
break;
}
default:
builder.Append(c);
break;
}
}
s.Read();
if (builder.Length > 0)
{
yield return new Token(TokenType.ColumnData, ExtractText(builder));
}
}
private string ExtractText(StringBuilder b)
{
var ret = b.ToString();
b.Remove(0, b.Length);
return ret;
}
```
Your "parser" code would then look like this:
```
public void ConvertXLS(TextReader s)
{
var columnData = new List<string>();
bool lastWasColumnData = false;
bool seenAnyData = false;
foreach (var token in GetTokens(s))
{
switch (token.Type)
{
case TokenType.ColumnData:
{
seenAnyData = true;
if (lastWasColumnData)
{
//TODO: do some error reporting
}
else
{
lastWasColumnData = true;
columnData.Add(token.Data);
}
break;
}
case TokenType.Comma:
{
if (!lastWasColumnData)
{
columnData.Add(null);
}
lastWasColumnData = false;
break;
}
case TokenType.LineTerminator:
{
if (seenAnyData)
{
OutputLine(lastWasColumnData);
}
seenAnyData = false;
lastWasColumnData = false;
columnData.Clear();
}
}
}
if (seenAnyData)
{
OutputLine(columnData);
}
}
``` | You can't change `StreamReader` to return the line terminators, and you can't change what it uses for line termination.
I'm not entirely clear about the problem in terms of what escaping you're doing, particularly in terms of "and write them as \x0A". A sample of the file would probably help.
It sounds like you *may* need to work character by character, or possibly load the whole file first and do a global replace, e.g.
```
x.Replace("\r\n", "\u0000") // Or some other unused character
.Replace("\n", "\\x0A") // Or whatever escaping you need
.Replace("\u0000", "\r\n") // Replace the real line breaks
```
I'm sure you could do that with a regex and it would probably be more efficient, but I find the long way easier to understand :) It's a bit of a hack having to do a global replace though - hopefully with more information we'll come up with a better solution. | Need to pick up line terminators with StreamReader.ReadLine() | [
"",
"c#",
"readline",
"streamreader",
"newline",
""
] |
I'm using ASP.NET MVC to build a RESTful web application and I plan to tunnel PUT and DELETE requests through POST as it seems like the most pragmatic workaround.
What I'd like to know is, should I tunnel the information through the url like this:
```
<form method='post' action='resource?_method=DELETE'>
<!-- fields -->
</form>
```
Or should I tunnel it through the posted form data like this:
```
<form method='post' action='resource'>
<input type='hidden' name='_method' value='DELETE' />
<!-- fields -->
</form>
```
And what are the pros and cons of each?
**EDIT:** One of the reasons I asked the question is that I read somewhere that putting information like this in the url is a good thing as post data usually gets lost, but urls hang around (in log files, etc) - unfortunately it makes the url look ugly | It's more of personal preference. Restful Web Services, OReilly, describes both somewhat interchangeably.
That being said, I prefer the first method for reasons of programmer intent. In Rest, when I'm looking at the code, I mentally read
VERB <http://someuri.com/someresource/id>
The verb and the resource are close together.
With PUT and DELETE you have to use a workaround like the ones that you've shown. In the first example, the resource and the verb are still close together on the same line.
In your second example, however, the resource is split into two lines. The verb is included on the same line as the resource id, but away from the resource name. It's very, very minor, but to me, that makes the second example less readable. | Have you seen [this](https://stackoverflow.com/questions/467535/is-it-possible-to-implement-x-http-method-override-in-asp-net-mvc) question? From what I understand, the x-http-method-override header is the preferred solution to this problem. | Should I store _method=PUT/DELETE in the post or in the url | [
"",
"c#",
"asp.net-mvc",
"http",
"rest",
""
] |
I need a way to find only **rendered** IMG tags in a HTML snippet. So, I can't just regex the HTML snippet to find all IMG tags because I'd also get IMG tags that are shown as text in the HTML (not rendered).
I'm using Python on AppEngine.
Any ideas?
Thanks,
Ivan | Sounds like a job for [BeautifulSoup](http://www.crummy.com/software/BeautifulSoup/):
```
>>> from BeautifulSoup import BeautifulSoup
>>> doc = """
... <html>
... <body>
... <img src="test.jpg">
... <img src="yay.jpg">
... <!-- <img src="ohnoes.jpg"> -->
... <img src="hurrah.jpg">
... </body>
... </html>
... """
>>> soup = BeautifulSoup(doc)
>>> soup.findAll('img')
[<img src="test.jpg" />, <img src="hurrah.jpg" />]
```
As you can see, BeautifulSoup is smart enough to ignore comments and displayed HTML.
**EDIT**: I'm not sure what you mean by the RSS feed escaping ALL images, though. I wouldn't expect BeautifulSoup to figure out which are meant to be shown if they are all escaped. Can you clarify? | The source code for rendered img tag are something like this:
```
<img src="img.jpg"></img>
```
If the img tag is displayed as text(not rendered), the html code would be like this:
```
<img src="styles/BWLogo.jpg"></img>
```
`<` is "<" character, `>` is ">" character
To match rendered img tag only,you can use regex to match img tag formed by < and >, not `<` and `>`
Img tags in comments also need to be ignored by ingnoring characters between "`<!--`" and "`-->`" | Finding all *rendered* images in a HTML file | [
"",
"python",
"html",
"regex",
"parsing",
""
] |
I have this little function do connect to a MySQL database:
```
function connectSugarCRM()
{
$connectorSugarCRM = mysql_connect ("localhost", "123", "123")
or die ("Connection failed");
mysql_select_db("sugar5") or die ("Failed attempt to connect to database");
return $connectorSugarCRM;
}
```
And then, to run a query, I'm doing something like this, but I allways get an "PHP Fatal error: Cannot redeclare connectSugarCRM() (previously declared in ...", which points to the definition of my function "connectSugarCRM" (line 1).
```
$ExecuteSQL = mysql_query ($sqlSTR, connectSugarCRM()) or die ("Query Failed!");
```
What is wrong with my code?
Thanks | Always use include\_once or require\_once when including other files. | First, search all of your code for 'function connectSugarCRM()' and make sure it appears once and only once. If it's there more than once, that's your problem.
Otherwise, try changing your query line to this:
```
$sugarConnection = connectSugarCRM();
$ExecuteSQL = mysql_query($sqlSTR, $sugarConnection) or die ("Query Failed!");
```
And in the future, the line numbers and full error messages are really helpful for debugging this stuff. | Connecting to MySQL database with PHP | [
"",
"php",
"mysql",
"connection",
""
] |
What is the difference between:
```
some_list1 = []
some_list1.append("something")
```
and
```
some_list2 = []
some_list2 += ["something"]
``` | For your case the only difference is performance: append is twice as fast.
```
Python 3.0 (r30:67507, Dec 3 2008, 20:14:27) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.20177424499999999
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.41192320500000079
Python 2.5.1 (r251:54863, Apr 18 2007, 08:51:08) [MSC v.1310 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import timeit
>>> timeit.Timer('s.append("something")', 's = []').timeit()
0.23079359499999999
>>> timeit.Timer('s += ["something"]', 's = []').timeit()
0.44208112500000141
```
In general case `append` will add one item to the list, while `+=` will copy *all* elements of right-hand-side list into the left-hand-side list.
**Update: perf analysis**
Comparing bytecodes we can assume that `append` version wastes cycles in `LOAD_ATTR` + `CALL_FUNCTION`, and += version -- in `BUILD_LIST`. Apparently `BUILD_LIST` outweighs `LOAD_ATTR` + `CALL_FUNCTION`.
```
>>> import dis
>>> dis.dis(compile("s = []; s.append('spam')", '', 'exec'))
1 0 BUILD_LIST 0
3 STORE_NAME 0 (s)
6 LOAD_NAME 0 (s)
9 LOAD_ATTR 1 (append)
12 LOAD_CONST 0 ('spam')
15 CALL_FUNCTION 1
18 POP_TOP
19 LOAD_CONST 1 (None)
22 RETURN_VALUE
>>> dis.dis(compile("s = []; s += ['spam']", '', 'exec'))
1 0 BUILD_LIST 0
3 STORE_NAME 0 (s)
6 LOAD_NAME 0 (s)
9 LOAD_CONST 0 ('spam')
12 BUILD_LIST 1
15 INPLACE_ADD
16 STORE_NAME 0 (s)
19 LOAD_CONST 1 (None)
22 RETURN_VALUE
```
We can improve performance even more by removing `LOAD_ATTR` overhead:
```
>>> timeit.Timer('a("something")', 's = []; a = s.append').timeit()
0.15924410999923566
``` | ```
>>> a=[]
>>> a.append([1,2])
>>> a
[[1, 2]]
>>> a=[]
>>> a+=[1,2]
>>> a
[1, 2]
```
See that append adds a single element to the list, which may be anything. `+=[]` joins the lists. | In Python, what is the difference between ".append()" and "+= []"? | [
"",
"python",
"list",
"concatenation",
""
] |
I know CodeGear made [BabelCode](http://lingua.codegear.com/babelcode/) that uses the Code DOM to convert C# to Delphi for .NET. I am curious if there are any other similar tools to convert C# to Delphi Prism? If not, what is involved in using the Code DOM to create one (yeah, that is open ended!)
**Update**: This is now built into Delphi Prism. Just paste or import your C# and you have Oxygene aka Delphi Prism Code. | It's in its early stages but Carlo just published a first revision of his open source "C# to Oxygene" tool:
<http://code.remobjects.com/p/csharptoxy/> | One option I saw was to use .NET Reflector on the C# compiled assembly. It has an Oxygene syntax. That is kind of the long way around and not exactly optimal. | C# to Oxygene code converter | [
"",
"c#",
"delphi",
"codedom",
"oxygene",
""
] |
I'm considering an optimisation in a particularly heavy part of my code.
It's task is to insert statistical data into a table. This data is being hit a fair amount by other programs. Otherwise I would consider using SQL Bulk inserts etc.
So my question is...
**Is it ok to try and insert some data knowing that it might (not too often) throw a SqlException for a duplicate row?**
Is the performance hit of an exception worse than checking each row prior to insertion? | First, my advice is to err on the side of correctness, not speed. When you finish your project and profiling shows that you lose *significant* time checking that rows exist before inserting them, only *then* optimize it.
Second, I think there's syntax for inserting and skipping if there are duplicates in all RDBMS, so this shouldn't be a problem in the first place. I try to avoid exceptions as part of the normal application flow and leave them for truly exceptional cases. That is, don't count on exceptions in the DB to work around logic in your code. Maintain as much consistency on your end (code), and let DB exceptions indicate only true bugs. | At a purely performance level, it is faster to just insert the data and handle the error, particularly if the error is infrequent. Running a select query to check for a duplicate, processing that result, and then inserting if successful, will be considerably slower than inserting and handling an occasional error. If its raising an exception, then that will be a bit slower since exception handling is slow in most languages, but handling a exception will be many times faster than an SQL query in any language.
As Assaf said, there is also usually a way to explicitly handle duplicates so you might be able to avoid the error altogether. This would increase performance further and allow you to be explicit that you're handling duplicates in a particular way.
Whether or not to use stored procedures is up to you - it can help with performance at the expense of putting more logic in your database. That's a decision you have to make. I've had bad experiences with this, but it depends on the RDBMS and the language you're using. | SQL Performance - Better to Insert and Raise Exception or Check exists? | [
"",
"sql",
"performance",
"exception",
"duplicates",
""
] |
In c#, I can do this:
```
public int Foo { get; set; }
```
Which is nice. But as soon as I want to do anything in the getter or setter, I have to change it to this:
```
private int foo;
public int Foo {
get { return foo; }
set {
foo = value;
DoSomething(); // all that other code, just to add this line!
}
}
```
Is it possible to avoid this? I would love to be able to do something like this:
```
public int Foo {
get;
set {
DoSomething();
}
}
```
How close can I get to the above? | No, there's no way to do this with properties in an existing version of C#, or C# 4.0. | As others have said, there is no builtin way to do this.
You could achieve something kind of similar with [PostSharp](http://www.postsharp.org/). But I'm not sure its worth the effort.
```
[AfterSet(DoSomething)]
public int Foo {
get;
set;
}
``` | Can I create an automatic property (no private member) with get and set code? | [
"",
"c#",
"properties",
"automatic-properties",
""
] |
If I do 0 == "0" it evaluates to true. Try,
```
if( -777 == "-777" ) alert("same");
```
alert happens.
And, it's also noticeable that true == "true" doesn't evaluate to true. Try,
```
if( false == "false" ) alert("same");
```
alert doesn't happen.
Why is it so? | The behavior of == is a bit lengthy, but clearly defined in the [ecma-262 spec](http://www.ecma-international.org/publications/standards/Ecma-262.htm):
> 11.9.3 The Abstract Equality Comparison Algorithm
>
> The comparison x == y, where x and y
> are values, produces true or false.
> Such a comparison is performed as
> follows:
>
> 1. If Type(x) is different from Type(y), go to step 14.
> 2. If Type(x) is Undefined, return true.
> 3. If Type(x) is Null, return true.
> 4. If Type(x) is not Number, go to step 11.
> 5. If x is NaN, return false.
> 6. If y is NaN, return false.
> 7. If x is the same number value as y, return true.
> 8. If x is +0 and y is −0, return true.
> 9. If x is −0 and y is +0, return true.
> 10. Return false.
> 11. If Type(x) is String, then return true if x and y are exactly the same
> sequence of characters (same length
> and same characters in corresponding
> positions). Otherwise, return false.
> 12. If Type(x) is Boolean, return true if x and y are both true or both
> false. Otherwise, return false.
> 13. Return true if x and y refer to the same object or if they refer to
> objects joined to each other (see 13.1.2). Otherwise, return false.
> 14. If x is null and y is undefined, return true.
> 15. If x is undefined and y is null, return true.
> 16. If Type(x) is Number and Type(y) is String, return the result of the
> comparison x == ToNumber(y).
> 17. If Type(x) is String and Type(y) is Number, return the result of the
> comparison ToNumber(x) == y.
> 18. If Type(x) is Boolean, return the result of the comparison ToNumber(x) == y.
> 19. If Type(y) is Boolean, return the result of the comparison x ==
> ToNumber(y).
> 20. If Type(x) is either String or Number and Type(y) is Object, return
> the result of the comparison x ==
> ToPrimitive(y).
> 21. If Type(x) is Object and Type(y) is either String or Number, return the
> result of the comparison
> ToPrimitive(x) == y.
> 22. Return false.
Step 16 applies to your former example:
```
0 == "0" // apply 16
≡ 0 == toNumber("0")
≡ 0 == 0 // apply 7
≡ true
```
And step 18, then step 16, apply to the latter:
```
true == "true" // apply 18
≡ toNumber(true) == "true"
≡ 1 == "true" // apply 16
≡ 1 == toNumber("true")
≡ 1 == NaN // apply 6
≡ false
``` | Doing this:
```
if(5 == "5")
```
Makes javascript convert the first 5 to a string. Try this:
```
if(5 === "5")
```
The `===` makes Javascript evaluate type as well.
This is actually a duplicate of this [`question`](https://stackoverflow.com/questions/359494/javascript-vs) where it is explained very well. | In Javascript, <int-value> == "<int-value>" evaluates to true. Why is it so? | [
"",
"javascript",
"variables",
"comparison",
""
] |
I have to stop applications when the window is closed. The window stays in the memory when click the (x) button. How can i remove the app in memory? Also another question is that i want the application to be installed when hard restart the pocket pc, how can i do it?
Thanks | By default the form will just hide when you click the X in the top right. You need to set the "MinimizeBox" property of the form to "False" for the application to close instead.
Installing the application on hard restart (often referred to as cold boot) requires that you put a CAB file for the application on the flash (persistent) memory of the device. You will then normally have to write a script and place that somewhere to call the CAB. This can vary from device to device so you'll have to look that one up. | Setting the form's MinimizeBox property to False causes the OK button to appear.
The Ok button is for closing the application instead of minimalizing | Automatically run programs on startup and stop applications from memory on PPC | [
"",
"c#",
"pocketpc",
""
] |
[PEP 263](http://www.python.org/dev/peps/pep-0263/) defines how to declare Python source code encoding. Normally, the first 2 lines of a Python file should start with:
```
#!/usr/bin/python
# -*- coding: <encoding name> -*-
```
But I have seen a lot of files starting with:
```
#!/usr/bin/python
# -*- encoding: <encoding name> -*-
```
I.e., it says `encoding` rather than `coding`.
How should the file encoding be declared?
---
Please use ["SyntaxError: Non-ASCII character ..." or "SyntaxError: Non-UTF-8 code starting with ..." trying to use non-ASCII text in a Python script](https://stackoverflow.com/questions/10589620) to close duplicate questions about syntax errors resulting from a missing or faulty encoding declaration. This question, on the other hand, is the canonical for questions about how the declaration is written and whether it is necessary. | Check the docs [here](http://docs.python.org/reference/lexical_analysis.html#encoding-declarations):
"If a comment in the first or second line of the Python script matches the regular expression `coding[=:]\s*([-\w.]+)`, this comment is processed as an encoding declaration"
"The recommended forms of this expression are
```
# -*- coding: <encoding-name> -*-
```
which is recognized also by GNU Emacs, and
```
# vim:fileencoding=<encoding-name>
```
which is recognized by Bram Moolenaar’s VIM."
So, you can put pretty much anything before the "coding" part, but stick to "coding" (with no prefix) if you want to be 100% python-docs-recommendation-compatible.
More specifically, you need to use whatever is recognized by Python *and the specific editing software you use* (if it needs/accepts anything at all). E.g. the `coding` form is recognized (out of the box) by GNU Emacs but not Vim (yes, without a universal agreement, it's essentially a [turf war](https://en.wikipedia.org/wiki/Turf_war)). | PEP 263:
> the first or second line must match
> the regular
> expression "coding[:=]\s\*([-\w.]+)"
So, "en**coding: UTF-8**" matches.
PEP provides some examples:
```
#!/usr/bin/python
# vim: set fileencoding=<encoding name> :
```
```
# This Python file uses the following encoding: utf-8
import os, sys
``` | Correct way to define Python source code encoding | [
"",
"python",
"encoding",
""
] |
I'm reading a c# book that describes the SyncRoot pattern. It shows
```
void doThis()
{
lock(this){ ... }
}
void doThat()
{
lock(this){ ... }
}
```
and compares to the SyncRoot pattern:
```
object syncRoot = new object();
void doThis()
{
lock(syncRoot ){ ... }
}
void doThat()
{
lock(syncRoot){ ... }
}
```
However, I don't really understand the difference here; it seems that in both cases both methods can only be accessed by one thread at a time.
The book describes *... because the object of the instance can also be used for synchronized access from the outside and you can't control this form the class itself, you can use the SyncRoot pattern* Eh? 'object of the instance'?
Can anyone tell me the difference between the two approaches above? | If you have an internal data structure that you want to prevent simultaneous access to by multiple threads, you should always make sure the object you're locking on is not public.
The reasoning behind this is that a public object can be locked by anyone, and thus you can create deadlocks because you're not in total control of the locking pattern.
This means that locking on `this` is not an option, since anyone can lock on that object. Likewise, you should not lock on something you expose to the outside world.
Which means that the best solution is to use an internal object, and thus the tip is to just use `Object`.
Locking data structures is something you really need to have full control over, otherwise you risk setting up a scenario for deadlocking, which can be very problematic to handle. | The actual purpose of this pattern is implementing correct synchronization with wrappers hierarchy.
For example, if class WrapperA wraps an instance of ClassThanNeedsToBeSynced, and class WrapperB wraps the same instance of ClassThanNeedsToBeSynced, you can't lock on WrapperA or WrapperB, since if you lock on WrapperA, lock on WrappedB won't wait.
For this reason you must lock on wrapperAInst.SyncRoot and wrapperBInst.SyncRoot, which delegate lock to ClassThanNeedsToBeSynced's one.
Example:
```
public interface ISynchronized
{
object SyncRoot { get; }
}
public class SynchronizationCriticalClass : ISynchronized
{
public object SyncRoot
{
// you can return this, because this class wraps nothing.
get { return this; }
}
}
public class WrapperA : ISynchronized
{
ISynchronized subClass;
public WrapperA(ISynchronized subClass)
{
this.subClass = subClass;
}
public object SyncRoot
{
// you should return SyncRoot of underlying class.
get { return subClass.SyncRoot; }
}
}
public class WrapperB : ISynchronized
{
ISynchronized subClass;
public WrapperB(ISynchronized subClass)
{
this.subClass = subClass;
}
public object SyncRoot
{
// you should return SyncRoot of underlying class.
get { return subClass.SyncRoot; }
}
}
// Run
class MainClass
{
delegate void DoSomethingAsyncDelegate(ISynchronized obj);
public static void Main(string[] args)
{
SynchronizationCriticalClass rootClass = new SynchronizationCriticalClass();
WrapperA wrapperA = new WrapperA(rootClass);
WrapperB wrapperB = new WrapperB(rootClass);
// Do some async work with them to test synchronization.
//Works good.
DoSomethingAsyncDelegate work = new DoSomethingAsyncDelegate(DoSomethingAsyncCorrectly);
work.BeginInvoke(wrapperA, null, null);
work.BeginInvoke(wrapperB, null, null);
// Works wrong.
work = new DoSomethingAsyncDelegate(DoSomethingAsyncIncorrectly);
work.BeginInvoke(wrapperA, null, null);
work.BeginInvoke(wrapperB, null, null);
}
static void DoSomethingAsyncCorrectly(ISynchronized obj)
{
lock (obj.SyncRoot)
{
// Do something with obj
}
}
// This works wrong! obj is locked but not the underlaying object!
static void DoSomethingAsyncIncorrectly(ISynchronized obj)
{
lock (obj)
{
// Do something with obj
}
}
}
``` | What's the use of the SyncRoot pattern? | [
"",
"c#",
"multithreading",
"design-patterns",
"concurrency",
""
] |
Creating a WCF Service Library in Visual Studio 2008 on Vista x64 is troublesome when referencing an x86 DLL. A service that calls a 32-bit DLL is required to have a platform target of x86 to run on a 64-bit OS. When you do this, the WcfSvcHost throws a BadImageFormatException when you attempt to debug the service. There is a [bug report](https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=349510) on MS connect. The workaround I used was to [coreflag WcfSvcHost as 32-bit](https://connect.microsoft.com/VisualStudio/feedback/Workaround.aspx?FeedbackID=349510).
**Manifest Problem**
The main issue I've run in to is this third-party native 32-bit DLL fails to load using certain WCF hosts. I receive the following error when **a service operation is invoked** that uses the third-party DLL:
> System.TypeInitializationException: The type initializer for
> '' threw an exception.
>
> .ModuleLoadExceptionHandlerException:
> A nested exception occurred after the
> primary exception that caused the C++
> module to fail to load.
>
> System.BadImageFormatException: The module was expected to contain an
> assembly manifest. (Exception from
> HRESULT: 0x80131018)
NestedException:
> The handle is invalid. (Exception from HRESULT: 0x80070006 (E\_HANDLE))
This exception is not raised when WcfSvcHost starts, it's raised when the a service operation is invoked that references the 32-bit DLL. What's very interesting, hosting this same service with the same app.config on a console app has no exceptions and works perfectly:
```
using (ServiceHost host = new ServiceHost (typeof (MsgBrokerService))) {
host.Open ();
Console.WriteLine ("running");
Console.ReadLine ();
```
This exception occurs right after:
> 'WcfSvcHost.exe' (Managed): Loaded
> 'C:\Windows\WinSxS\x86\_microsoft.vc80.crt\_1fc8b3b9a1e18e3b\_8.0.50727.3053\_
> none\_d08d7bba442a9b36\msvcm80.dll'
Again, the console app does not have an exception and loads the same DLL:
> 'ConsoleApp.vshost.exe' (Managed):
> Loaded
> 'C:\Windows\WinSxS\x86\_microsoft.vc80.crt\_1fc8b3b9a1e18e3b\_8.0.50727.3053\_
> none\_d08d7bba442a9b36\msvcm80.dll'
**See answer** [from Microsoft Product Support](https://stackoverflow.com/questions/727313/wcf-problems-with-hosting-on-wcfsvchost-and-iis/942578#942578).
Update #1: Both the console application and the WcfSvcHost.exe host process runs under the same session and logged-in user (me). I've copied WcfSvcHost.exe to the directory of the service, manually launched and experienced the same result. I've also checked the Windows Event Log for additional information and used *sxstrace*, but nothing was logged.
Running Process Explorer, I've verified the following are the same between the two processes:
* Image: 32-bit
* Current Directory
* User/SID
* Session
* Security (groups denied, privileges disabled)
Running Process Monitor, and [configuring symbols](http://blogs.msdn.com/vijaysk/archive/2009/04/02/getting-better-stack-traces-in-process-monitor-process-explorer.aspx), I see WcfSvcHost looks for the following registry and files, while the console host does not. *Process Monitor logs a lot of data and I'm not sure what I'm looking for :(*.
> HKLM\SOFTWARE\Microsoft\Fusion\PublisherPolicy\Default\policy.8.0.msvcm80\_\_b03f5f7f11d50a3a
> C:\Windows\assembly\GAC\_32\msvcm80\8.0.50727.3053\_\_b03f5f7f11d50a3a
> C:\Windows\assembly\GAC\_MSIL\msvcm80\8.0.50727.3053\_\_b03f5f7f11d50a3a
> C:\Windows\assembly\GAC\msvcm80\8.0.50727.3053\_\_b03f5f7f11d50a3a
Update #2: This same exception occurs when the service is **hosted in production** on IIS 6 / Windows Server 2003.
Update #3: The 3rd-party 32-bit .NET assembly is the [StreamBase API](http://streambase.com/developers/docs/latest/apiguide/creatingdotnetclients.html):
* sbclient.dll (managed)
* monitor.netmodule (managed)
* dotnetapi.dll (unmanaged)
* pthreads-vc8.dll (unmanaged)
Update #4: Added manifests without success:
1. Verified that dotnetapi.dll and pthreads-vc8.dll have RT\_MANIFEST. The sbclient.dll .NET assembly did not have a manifest
2. Removed sbclient.dll from the GAC
3. Registered sbclient.dll for verification skipping
4. Added a manifest via [mt.exe](http://blogs.msdn.com/cheller/archive/2006/08/24/718757.aspx) to both sbclient.dll and monitor.netmodule
5. Verified manifest was added and that the expected files were loaded during testing (via Visual Studio - debug modules window)
6. The same BadImageFormatException is thrown under BackgroundWorker.OnDoWork(), and the call stack shows a call to dotnetapi.dll...DefaultDomain.Initalize().
I have verified that msvcm80.dll does not have a manifest, I believe this is the only file loaded that doesn't have a manifest :)
Interesting find
When I load monitor.netmodule in [Reflector](http://www.red-gate.com/products/reflector/), it says:
> 'monitor.netmodule' does not contain
> an assembly manifest.
Even though it displays an error, Reflector is still able to disassemble the managed code. | Microsoft Product Support has resolved this question: It's by design. The unmanaged code is not loaded in the default AppDomain when using WcfSvcHost or the IIS WCF host.
> A pure image will use a CLR version of
> the C run-time library. However, the
> CRT is not verifiable, so you cannot
> use the CRT when compiling with
> /clr:safe. For more information, see C
> Run-Time Libraries.
<http://msdn.microsoft.com/en-us/library/k8d11d4s.aspx> | a bit late but you can also change the app pool setting "Enable 32-bit Applications" to true in advanced settings. | BadImageFormatException encountered with WcfSvcHost and IIS WCF host | [
"",
"c++",
"wcf",
"interop",
"iis-6",
"was",
""
] |
How do you get the VK code from a char that is a letter? It seems like you should be able to do something like `javax.swing.KeyStroke.getKeyStroke('c').getKeyCode()`, but that doesn't work (the result is zero). Everyone knows how to get the key code if you already have a KeyEvent, but what if you just want to turn chars into VK ints? I'm not interested in getting the FK code for strange characters, only [A-Z],[a-z],[0-9].
Context of this problem --------
All of the Robot tutorials I've seen assume programmers love to spell out words by sending keypresses with VK codes:
> ```
> int keyInput[] = {
> KeyEvent.VK_D,
> KeyEvent.VK_O,
> KeyEvent.VK_N,
> KeyEvent.VK_E
> };//end keyInput array
> ```
Call me lazy, but even with Eclipse this is no way to go about using TDD on GUIs. If anyone happens to know of a Robot-like class that takes strings and then simulates user input for those strings (I'm using [FEST](http://www.javaworld.com/javaworld/jw-07-2007/jw-07-fest.html)), I'd love to know. | Maybe this ugly hack:
```
Map<String, Integer> keyTextToCode = new HashMap<String, Integer>(256);
Field[] fields = KeyEvent.class.getDeclaredFields();
for (Field field : fields) {
String name = field.getName();
if (name.startsWith("VK_")) {
keyTextToCode.put(name.substring("VK_".length()).toUpperCase(),
field.getInt(null));
}
}
```
keyTextToCode would then contain the mapping from strings (e.g. "A" or "PAGE\_UP") to vk codes. | ```
AWTKeyStroke.getAWTKeyStroke('c').getKeyCode();
```
Slight clarification of [Pace's answer](https://stackoverflow.com/a/4001177/369977). It should be single quotes (representing a character), not double quotes (representing a string).
Using double quotes will throw a java.lang.IllegalArgumentException (String formatted incorrectly). | Get the VK int from an arbitrary char in java | [
"",
"java",
"unit-testing",
"keyboard",
"awtrobot",
"fest",
""
] |
I deal with a lot of hierarchies in my day to day development. File systems, nested DAG nodes in Autodesk Maya, etc.
I'm wondering, are there any good modules for Python specifically designed to traverse and compare hierarchies of objects?
Of particular interest would be ways to do 'fuzzy' comparisons between two *nearly* identical hierarchies. Some of the reasons for doing this would be for matching two node hierarchies in Maya from two different characters in order to transfer animation from one to the other.
Based on what I've been reading, I'd probably need something with a name threshold (which I could build myself) for comparing how close two node names are to each other. I'd then need a way to optionally ignore the order that child nodes appear in the hierarchy. Lastly, I'd need to deal with a depth threshold, in cases where a node may have been slightly moved up or down the hierarchy. | I'm not sure I see the need for a complete module -- hierarchies are a design pattern, and each hierarchy has enough unique features that it's hard to generalize.
```
class Node( object ):
def __init__( self, myData, children=None )
self.myData= myData
self.children= children if children is not None else []
def visit( self, aVisitor ):
aVisitor.at( self )
aVisitor.down()
for c in self.children:
aVisitor.at( c )
aVisitor.up()
class Visitor( object ):
def __init__( self ):
self.depth= 0
def down( self ):
self.depth += 1
def up( self ):
self.depth -= 1
```
I find that this is all I need. And I've found that it's hard to make a reusable module out of this because (a) there's so little here and (b) each application adds or changes so much code.
Further, I find that the most commonly used hierarchy is the file system, for which I have the `os` module. The second most commonly used hierarchy is XML messages, for which I have ElementTree (usually via lxml). After those two, I use the above structures as templates for my classes, not as a literal reusable module. | I recommend digging around xmldifff <http://www.logilab.org/859> and seeing how they compare nodes and handle parallel trees. Or, try writing a [recursive] generator that yields each [significant] node in a tree, say `f(t)`, then use `itertools.izip(f(t1),f(t2))` to collect together pairs of nodes for comparison.
Most of the hierarchical structures I deal with have more than one "axis", like elements and attributes in XML, and some nodes are more significant than others.
For a more bizarre solution, serialize the two trees to text files, make a referential note that line #n comes from node #x in a tree. Do that to both trees, feed the files into diff, and scan the results to notice which parts of the tree have changed. You can map that line #n from file 1 (and therefore node #x in the first tree) and line #m from file 2 (and therefore node #y of the second tree) mean that some part of each tree is the same or different.
For any solution your are going to have to establish a "canonical form" of your tree, one that might drop all ignorable whitespace, display attributes, optional nodes, etc., from the comparison process. It might also mean doing a breadth first vs. depth first traversal of the tree(s). | Hierarchy traversal and comparison modules for Python? | [
"",
"python",
"tree",
"module",
"hierarchy",
"traversal",
""
] |
So many server side and the mobile Java applications use the native Java language for Java. Can we use Jython instead to build the enterprise applications, e.g. websites, application servers etc.
Also what do you feel about Java ME applications in Jython.
P.S. Comments on question also welcome. | No, Jython is not a suitable replacement for Java. Consider, for instance, that it provides no way to implement interfaces without writing the interface in Java and then writing a class leveraging it in Jython.
What's needed is a JVM-targeted equivalent to Boo. Boo is a language targeting the .NET CLR which is roughly inspired by Python but not compatible, and which fully exposes the CLR's functionality (thus being feature-equivalent with C#). There presently is no Pythonic language with feature parity with Java -- and such a language would necessarily be incompatible with Python, as Python simply doesn't provide a way to express some of the relevant concepts (such as interface typing information).
---
Since there have been some questions about this, yet me clarify:
Jython is not a replacement for Java in the sense that you can't take an arbitrary Java project, decide to implement a random subset of that project in Jython instead, and not have anyone else on the development team know or care. Certainly, Jython is suitable for many of the same classes of projects that Java is, *except when you're building an interface which will be called from Java, rather than the reverse*. Given as "enterprise applications" tend to have a lot of components which operate closely with each other, being able to build a class with an arbitrary external interface is important... and is something which isn't readily done in pure Jython. | It depends largely what your requirements are. All languages have their strengths and weaknesses. There is no perfect language and making intelligent decisions about language choice is an important skill for a programmer.
I disagree with Charles that Jython can't replace Java because you can't implement Interfaces. In dynamic languages, it's seen as a feature that you don't *need* Interfaces (see duck typing).
Jython takes the great language features of Python and combines it with easy access to huge collection of Java libraries. However it does have a price in terms of overhead, and being a fairly new language you have less programmers and support to back you up.
The nice thing about Jython is that you can rewrite individual modules in Java if performance is a problem. The speed issue is less notable on servers where you can throw hardware at the problem. On mobile phones, performance is still key and I can't see Jython making a big impact there in the near future.
So will Jython replace Java? No, I don't think it will - the momentum behind Java is too great. But we will see increasingly more software with parts written in Jython and other languages targeting the JVM. | Can Jython replace Java? | [
"",
"java",
"java-me",
"jakarta-ee",
"jython",
"jvm-languages",
""
] |
I was just wondering if there are ways of creating my own custom winforms controls?
I've been plundering with Visual Studio 2008 now trying to do some c# apps. And the GUI end up looking terrible because of the standard winforms limitations.
And I noticed that I can add images to buttons for example, but ther's no hover effect. Or, the hover effect makes the whole button area gray. I don't want any of that, I just want to either create my own graphics for the controls or find some free (opensource perhaps) controls that already exist.
Any light on any of this, anyone? :) | I'm puzzled, you are doing WinForms development, yet in comments say you have done many months of WPF development, but WPF is not good enough because it is not cross platform.
How is WinForm more cross platform, and have you seen how ugly WinForms looks under mono on a Mac as it's draw via X11.
If you want style and cross platform, go for Flex or Silverlight, as your already know WPF I'd go the Silverlight route.
It's cross platform, and has all the beauty of WPF, but at the cost of reduced functionality out of the box. | You can write complete Winforms controls from scratch, doing all the painting and input processing yourself - you just create a class derived from 'Control' and get on with it.
There's a fair bit to making a first-class control which integrates nicely with the VS designer, so people tend to derive their custom control from an existing control which has most of the behaviour they want.
Here would be a good place to start: <http://msdn.microsoft.com/en-us/library/6hws6h2t.aspx> | C# + Custom graphics on controls? | [
"",
"c#",
"winforms",
"user-controls",
""
] |
For my previous employer I've worked with Hibernate, and now that I'm in a small startup I would like to use it again. However, downloading both the Hibernate core and the Hibernate annotations distributions is rather painful, as it requires putting a *lot* of JAR files together. Because the JARs are split up into categories such as "required" and "optional" I would assume that every developer ends up with a different contents of his lib folder.
What is the common way to handle this problem? Basically I want to have a formal way to get all the JARs for Hibernate, so that (in theory) I would end up with exactly the same stuff if I would need again for another project next month.
**Edit:** I know roughly what Maven does, but I was wondering if there was another way to manage this sort of thing. | As Aaron has already mentioned, Maven is an option.
If you want something a bit more flexible you could use Apache Ant with [Ivy](http://ant.apache.org/ivy/).
Ivy is a dependency resolution tool which works in a similar way to Maven, you just define what libraries your project needs and it will go off and download all the dependencies for you. | Maybe this is not much of an answer, but I really don't see any problem with Hibernate dependencies. Along with `hibernate3.jar`, you need to have:
1. 6 required jars, out of which commons-collections, dom4j and slf4j are more often used in other open-source projects
2. 1 of either javassist or CGLIB jars
3. depending on cache and connection pooling, up to 2 jar files, which are pretty much Hibernate specific
So, at the very worst, you will have a maximum of 10 jars, Hibernate's own jar included. And out of those, only commons-collections, dom4j and slf4j will probably be used by some other library in your project. That is hardly a zillion, it can be managed easily, and surely does not warrant using an "elephant" like Maven. | How do you manage Hibernate's zillion JAR files | [
"",
"java",
"hibernate",
""
] |
Does anyone know about a PHP library which can produce layered PNG images? (I'm not sure, but I think that tiff image standard supports layers also) | From the [ImageMagic](http://www.imagemagick.org) [API site](http://www.imagemagick.org/script/api.php):
> PHP
> MagickWand for PHP a native PHP-extension to the ImageMagick MagickWand API.
> IMagick is a native PHP extension to create and modify images using the ImageMagick API. Documentation for the extension is available here.
> phMagick is a wrapper class for ImageMagick, wrapping the most common web image manipulation actions in easy to use functions, but allowing full access to ImageMagick's power by issuing system calls to it's command-line programs.
>
> ImageMagick® is a software suite to create, edit, and compose bitmap images. It can read, convert and write images in a variety of formats (over 100) including DPX, EXR, GIF, JPEG, JPEG-2000, PDF, PhotoCD, PNG, Postscript, SVG, and TIFF. Use ImageMagick to translate, flip, mirror, rotate, scale, shear and transform images, adjust image colors, apply various special effects, or draw text, lines, polygons, ellipses and Bézier curves. | AFAIR, PNG does not support layers. MNG does and you can produce these with [ImageMagick](http://www.imagemagick.org).
For PHP extension see: <http://www.php.net/imagick> | layered png image using a PHP library | [
"",
"php",
"image",
"png",
""
] |
I'm searching for a component similiar to this one(Delphi) in .NET 3.5 SP1
[alt text http://img15.imageshack.us/img15/6657/compc.jpg](http://img15.imageshack.us/img15/6657/compc.jpg)
Thanks. | ListView with "View = Detail" or DataGridView. | Look at the [PropertyGrid](http://msdn.microsoft.com/en-us/library/system.windows.forms.propertygrid.aspx) control | Searching for a component in NET 3.5 | [
"",
"c#",
".net",
"controls",
".net-3.5",
""
] |
I need an algorithm to find all of the subsets of a set where the number of elements in a set is `n`.
```
S={1,2,3,4...n}
```
Edit: I am having trouble understanding the answers provided so far. I would like to have step-by-step explanation of how the answers work to find the subsets.
For example,
```
S={1,2,3,4,5}
```
How do you know `{1}` and `{1,2}` are subsets?
Could someone help me with a simple function in c++ to find subsets of {1,2,3,4,5} | It's very simple to do this recursively. The basic idea is that for each element, the set of subsets can be divided equally into those that contain that element and those that don't, and those two sets are otherwise equal.
* For n=1, the set of subsets is {{}, {1}}
* For n>1, find the set of subsets of 1,...,n-1 and make two copies of it. For one of them, add n to each subset. Then take the union of the two copies.
**Edit** To make it crystal clear:
* The set of subsets of {1} is {{}, {1}}
* For {1, 2}, take {{}, {1}}, add 2 to each subset to get {{2}, {1, 2}} and take the union with {{}, {1}} to get {{}, {1}, {2}, {1, 2}}
* Repeat till you reach n | Too late to answer, but an iterative approach sounds easy here:
1) for a set of `n` elements, get the value of `2^n`. There will be 2^n no.of subsets. (2^n because each element can be either present(1) or absent(0). So for n elements there will be 2^n subsets. ). Eg:
`for 3 elements, say {a,b,c}, there will be 2^3=8 subsets`
2) Get a binary representation of `2^n`. Eg:
`8 in binary is 1000`
3) Go from `0` to `(2^n - 1)`. In each iteration, for each 1 in the binary representation, form a subset with elements that correspond to the index of that 1 in the binary representation.
Eg:
```
For the elements {a, b, c}
000 will give {}
001 will give {c}
010 will give {b}
011 will give {b, c}
100 will give {a}
101 will give {a, c}
110 will give {a, b}
111 will give {a, b, c}
```
4) Do a union of all the subsets thus found in step 3. Return. Eg:
`Simple union of above sets!` | Finding all the subsets of a set | [
"",
"c++",
"algorithm",
"math",
"subset",
""
] |
```
class A {
public:
void operator=(const B &in);
private:
int a;
};
class B {
private:
int c;
}
```
sorry. there happened an error. is assignment operator valid ? or is there any way to achieve this? [There is no relation between A and B class.]
```
void A::operator=(const B& in)
{
a = in.c;
}
```
Thanks a lot. | Yes you can do so.
```
#include <iostream>
using namespace std;
class B {
public:
B() : y(1) {}
int getY() const { return y; }
private:
int y;
};
class A {
public:
A() : x(0) {}
void operator=(const B &in) {
x = in.getY();
}
void display() { cout << x << endl; }
private:
int x;
};
int main() {
A a;
B b;
a = b;
a.display();
}
``` | This isn't an answer, but one should be aware that the typical idiom for the assignment operator is to have it return a reference to the object type (rather than void) and to return (\*this) at the end. This way, you can chain the assignent, as in a = b = c:
```
A& operator=(const A& other)
{
// manage any deep copy issues here
return *this;
}
``` | does assignment operator work with different types of objects? | [
"",
"c++",
"operator-overloading",
"virtual-functions",
""
] |
I've got a large xml document in a string. What's the best way to determine if the xml is well formed? | Something like:
```
static void Main() {
Test("<abc><def/></abc>");
Test("<abc><def/><abc>");
}
static void Test(string xml) {
using (XmlReader xr = XmlReader.Create(
new StringReader(xml))) {
try {
while (xr.Read()) { }
Console.WriteLine("Pass");
} catch (Exception ex) {
Console.WriteLine("Fail: " + ex.Message);
}
}
}
```
If you need to check against an xsd, then use `XmlReaderSettings`. | Simply run it through a parser. That will perform the appropriate checks (whether it parses ok).
If it's a large document (as indicated) then an event-based parser (e.g. SAX) will be appropriate since it won't store the document in memory.
It's often useful to have XML utilities around to check this sort of stuff. I use [XMLStarlet](http://xmlstar.sourceforge.net/), which is a command-line set of tools for XML checking/manipulation. | How to determine if XML is well formed? | [
"",
"c#",
"xml",
""
] |
I use INNER JOIN and LEFT OUTER JOINs all the time. However, I never seem to need RIGHT OUTER JOINs, ever.
I've seen plenty of nasty auto-generated SQL that uses right joins, but to me, that code is impossible to get my head around. I always need to rewrite it using inner and left joins to make heads or tails of it.
Does anyone actually write queries using Right joins? | It depends on what side of the join you put each table.
If you want to return all rows from the left table, even if there are no matches in the right table... you use left join.
If you want to return all rows from the right table, even if there are no matches in the left table, you use right join.
Interestingly enough, I rarely used right joins. | In SQL Server one edge case where I have found right joins useful is when used in conjunction with join hints.
The following queries have the same semantics but differ in which table is used as the build input for the hash table (it would be more efficient to build the hash table from the smaller input than the larger one which the right join syntax achieves)
```
SELECT #Large.X
FROM #Small
RIGHT HASH JOIN #Large ON #Small.X = #Large.X
WHERE #Small.X IS NULL
SELECT #Large.X
FROM #Large
LEFT HASH JOIN #Small ON #Small.X = #Large.X
WHERE #Small.X IS NULL
```
Aside from that (product specific) edge case there are other general examples where a `RIGHT JOIN` may be useful.
Suppose that there are three tables for People, Pets, and Pet Accessories. People may optionally have pets and these pets may optionally have accessories
```
CREATE TABLE Persons
(
PersonName VARCHAR(10) PRIMARY KEY
);
INSERT INTO Persons
VALUES ('Alice'),
('Bob'),
('Charles');
CREATE TABLE Pets
(
PetName VARCHAR(10) PRIMARY KEY,
PersonName VARCHAR(10)
);
INSERT INTO Pets
VALUES ('Rover',
'Alice'),
('Lassie',
'Alice'),
('Fifi',
'Charles');
CREATE TABLE PetAccessories
(
AccessoryName VARCHAR(10) PRIMARY KEY,
PetName VARCHAR(10)
);
INSERT INTO PetAccessories
VALUES ('Ball', 'Rover'),
('Bone', 'Rover'),
('Mouse','Fifi');
```
If the requirement is to get a result listing all people irrespective of whether or not they own a pet and information about any pets they own that also have accessories.
This **doesn't work** (Excludes Bob)
```
SELECT P.PersonName,
Pt.PetName,
Pa.AccessoryName
FROM Persons P
LEFT JOIN Pets Pt
ON P.PersonName = Pt.PersonName
INNER JOIN PetAccessories Pa
ON Pt.PetName = Pa.PetName;
```
This **doesn't work** (Includes Lassie)
```
SELECT P.PersonName,
Pt.PetName,
Pa.AccessoryName
FROM Persons P
LEFT JOIN Pets Pt
ON P.PersonName = Pt.PersonName
LEFT JOIN PetAccessories Pa
ON Pt.PetName = Pa.PetName;
```
This **does work** (but the syntax is much less commonly understood as it requires two `ON` clauses in succession to achieve the desired logical join order)
```
SELECT P.PersonName,
Pt.PetName,
Pa.AccessoryName
FROM Persons P
LEFT JOIN Pets Pt
INNER JOIN PetAccessories Pa
ON Pt.PetName = Pa.PetName
ON P.PersonName = Pt.PersonName;
```
All in all probably easiest to use a `RIGHT JOIN`
```
SELECT P.PersonName,
Pt.PetName,
Pa.AccessoryName
FROM Pets Pt
JOIN PetAccessories Pa
ON Pt.PetName = Pa.PetName
RIGHT JOIN Persons P
ON P.PersonName = Pt.PersonName;
```
Though if determined to avoid this another option would be to introduce a derived table that can be left joined to
```
SELECT P.PersonName,
T.PetName,
T.AccessoryName
FROM Persons P
LEFT JOIN (SELECT Pt.PetName,
Pa.AccessoryName,
Pt.PersonName
FROM Pets Pt
JOIN PetAccessories Pa
ON Pt.PetName = Pa.PetName) T
ON T.PersonName = P.PersonName;
```
SQL Fiddles: [MySQL](http://www.sqlfiddle.com/#!2/8ea6a/2), [PostgreSQL](http://www.sqlfiddle.com/#!12/8ea6a/1), [SQL Server](http://www.sqlfiddle.com/#!6/8ea6a/1) | Does "Right Outer Join" have any useful purpose? | [
"",
"sql",
""
] |
I need an algorithm to convert an Excel Column letter to its proper number.
The language this will be written in is C#, but any would do or even pseudo code.
Please note I am going to put this in C# and I don't want to use the office dll.
For 'A' the expected result will be 1
For 'AH' = 34
For 'XFD' = 16384 | ```
public static int ExcelColumnNameToNumber(string columnName)
{
if (string.IsNullOrEmpty(columnName)) throw new ArgumentNullException("columnName");
columnName = columnName.ToUpperInvariant();
int sum = 0;
for (int i = 0; i < columnName.Length; i++)
{
sum *= 26;
sum += (columnName[i] - 'A' + 1);
}
return sum;
}
``` | ```
int result = colName.Select((c, i) =>
((c - 'A' + 1) * ((int)Math.Pow(26, colName.Length - i - 1)))).Sum();
``` | What is the algorithm to convert an Excel Column Letter into its Number? | [
"",
"c#",
"excel",
"math",
""
] |
I'm a little surprised that there isn't some information on this on the web, and I keep finding that the problem is a little stickier than I thought.
Here's the rules:
1. You are starting with delimited/escaped data to split into an array.
2. The delimiter is one arbitrary character
3. The escape character is one arbitrary character
4. Both the delimiter and the escape character could occur in data
5. Regex is fine, but a good-performance solution is best
6. Edit: Empty elements (including leading or ending delimiters) can be ignored
The code signature (in C# would be, basically)
```
public static string[] smartSplit(
string delimitedData,
char delimiter,
char escape) {}
```
The stickiest part of the problem is the escaped consecutive escape character case, of course, since (calling / the escape character and , the delimiter): ////////, = ////,
Am I missing somewhere this is handled on the web or in another SO question? If not, put your big brains to work... I think this problem is something that would be nice to have on SO for the public good. I'm working on it myself, but don't have a good solution yet. | ```
void smartSplit(string const& text, char delim, char esc, vector<string>& tokens)
{
enum State { NORMAL, IN_ESC };
State state = NORMAL;
string frag;
for (size_t i = 0; i<text.length(); ++i)
{
char c = text[i];
switch (state)
{
case NORMAL:
if (c == delim)
{
if (!frag.empty())
tokens.push_back(frag);
frag.clear();
}
else if (c == esc)
state = IN_ESC;
else
frag.append(1, c);
break;
case IN_ESC:
frag.append(1, c);
state = NORMAL;
break;
}
}
if (!frag.empty())
tokens.push_back(frag);
}
``` | A simple state machine is usually the easiest and fastest way. Example in Python:
```
def extract(input, delim, escape):
# states
parsing = 0
escaped = 1
state = parsing
found = []
parsed = ""
for c in input:
if state == parsing:
if c == delim:
found.append(parsed)
parsed = ""
elif c == escape:
state = escaped
else:
parsed += c
else: # state == escaped
parsed += c
state = parsing
if parsed:
found.append(parsed)
return found
``` | What is the best algorithm for arbitrary delimiter/escape character processing? | [
"",
"c#",
"regex",
"algorithm",
""
] |
Say we have a list {a, a, a, b, b, c, c }
We want to loop through the list and make some kind of change when the item value changes... for example:
```
prevEmployer = String.empty;
foreach(Person p in PersonList){
if(p.Employer != prevEmployer){
doSomething();
prevEmployer = p.Employer;
}
... more code
}
```
Is there any alternative to this? It just looks cludgy to me.
Edit: made the code more realistic to the problem at hand. | This really depends on what you are trying to do with the rest of the code. @Marc Gravell's response is correct if you only need to perform an action for each distinct element in the list, however, if doSomething() just sets up some state based on the fact that list element has changed and you are operating on each element in the list (or need the individual elements for another purpose), then your method seems perfectly reasonable. | Do you want the distinct values? i.e. will there ever be {a,a,a,b,b,a,c,c,a}? If not, you could use LINQ:
```
foreach(string s in theList.Distinct()) {
doSomething(); // with s
}
```
---
Re your update; perhaps use something like `DistinctBy`:
```
foreach(var item in data.DistinctBy(x=>x.Foo)) {
Console.WriteLine(item.Bar);
}
public static IEnumerable<TSource> DistinctBy<TSource,TValue>(
this IEnumerable<TSource> source, Func<TSource,TValue> selector) {
var set = new HashSet<TValue>();
foreach (var item in source) {
if (set.Add(selector(item))) {
yield return item;
}
}
}
``` | The whole If prevValue != currValue thing in a loop | [
"",
"c#",
"loops",
"list",
""
] |
I'm trying to write a small program that prints out distinct numbers in an array. For example if a user enters 1,1,3,5,7,4,3 the program will only print out 1,3,5,7,4.
I'm getting an error on the else if line in the function `checkDuplicate`.
Here's my code so far:
```
import javax.swing.JOptionPane;
public static void main(String[] args) {
int[] array = new int[10];
for (int i=0; i<array.length;i++) {
array[i] = Integer.parseInt(JOptionPane.showInputDialog("Please enter"
+ "an integer:"));
}
checkDuplicate (array);
}
public static int checkDuplicate(int array []) {
for (int i = 0; i < array.length; i++) {
boolean found = false;
for (int j = 0; j < i; j++)
if (array[i] == array[j]) {
found = true;
break;
}
if (!found)
System.out.println(array[i]);
}
return 1;
}
}
``` | First of all, the "`else if`" statement is incorrect, since you don't provide any condition to the if (if you want an if, you need to write "`if (condition) ...`").
Second, you cannot decide *inside the inner* loop, if a value should be printed: The way your code works you write a value array[i] *for each value array[j]* that is different from array[i]!
Third: the inner loop needs only to go from 0 to the outer index `i-1`: For each element, you need only to decide, if it is the first occurrence (i.e. if the same value occured at any previous index or not). If it is, print it out, if not, ignore it.
A proper implementation of `CheckDuplicate()` would be:
```
public static void checkDuplicate(int array []) {
for (int i = 0; i < array.length; i++) {
boolean found = false;
for (int j = 0; j < i; j++)
if (array[i] == array[j]) {
found = true;
break;
}
if (!found)
System.out.println(array[i]);
}
}
```
But of course, some kind of `Set` would be much more efficient for bigger arrays...
---
EDIT: Of course, *mmyers* (see comments) is right by saying, that since `CheckDuplicate()` doesn't return any value, it should have return type `void` (instead of `int`). I corrected this in the above code... | The simplest way would be to add all of the elements to a `Set<Integer>` and then just print the contents of the `Set`. | Printing distinct integers in an array | [
"",
"java",
"arrays",
"duplicates",
""
] |
I have
```
std::list<multimap<std::string,std::string>::iterator> >
```
Now i have new element:
```
multimap<std::string,std::string>::value_type aNewMmapValue("foo1","test")
```
I want to avoid the need to set temp multimap and do insert to the new element just to get its iterator back
so i could to push it back to the:
```
std::list<multimap<std::string,std::string>::iterator> >
```
can i somehow avoid this creation of the temp multimap.
Thanks | You need to insert the key-value pair into a multimap before getting an iterator for it.
An iterator does not work by itself. If you are storing iterators from several different multimaps you probably need to store more than just an iterator in the list.
Perhaps:
1. a `pair<multimap<std::string,std::string>::iterator, multimap<std::string,std::string>::iterator>` where first is the iterator and second is the end-iterator.
2. a `pair<multimap<std::string,std::string>::iterator, multimap<std::string,std::string>*>` where first is the iterator, and second is a pointer to the multimap that the iterator belongs to.
3. some other kind of solution.
EDIT: I concur with Mykola Golubyev: It is often a bad idea to store iterators for a longer period of time, as the iterators may be invalidated. | You have not specified the data type that you store in your `list`. Anyway, assuming that you want to add the value(s) pointed to by a particular key, you can call `list.insert(*mapIter)`.
```
multimap<std::string,std::string>::value_type aNewMmapValue("foo1","test")
```
You need to add this to your multimap via `map.insert`. This function returns an iterator. You can then safely add this iterator to your list.
```
std::list<multimap<std::string,std::string>::iterator> yourlist;
// ....
multimap<std::string,std::string>::iterator itr =
yourmultimap.insert(aNewMmapValue);
yourlist.insert(itr);
``` | How to convert c++ std::list element to multimap iterator | [
"",
"c++",
"list",
"stl",
"iterator",
"multimap",
""
] |
I'm using .NET WebBrowser control.
How do I know when a web page is fully loaded?
I want to know when the browser is not fetching any more data. (The moment when IE writes 'Done' in its status bar...).
Notes:
* The DocumentComplete/NavigateComplete events might occur multiple times for a web site containing multiple frames.
* The browser ready state doesn't solve the problem either.
* I have tried checking the number of frames in the frame collection and then count the number of times I get DocumentComplete event but this doesn't work either.
* this.WebBrowser.IsBusy doesn't work either. It is always 'false' when checking it in the Document Complete handler. | Here's what finally worked for me:
```
public bool WebPageLoaded
{
get
{
if (this.WebBrowser.ReadyState != System.Windows.Forms.WebBrowserReadyState.Complete)
return false;
if (this.HtmlDomDocument == null)
return false;
// iterate over all the Html elements. Find all frame elements and check their ready state
foreach (IHTMLDOMNode node in this.HtmlDomDocument.all)
{
IHTMLFrameBase2 frame = node as IHTMLFrameBase2;
if (frame != null)
{
if (!frame.readyState.Equals("complete", StringComparison.OrdinalIgnoreCase))
return false;
}
}
Debug.Print(this.Name + " - I think it's loaded");
return true;
}
}
```
On each document complete event I run over all the html element and check all frames available (I know it can be optimized). For each frame I check its ready state.
It's pretty reliable but just like jeffamaphone said I have already seen sites that triggered some internal refreshes.
But the above code satisfies my needs.
Edit: every frame can contain frames within it so I think this code should be updated to recursively check the state of every frame. | Here's how I solved the problem in my application:
```
private void wbPost_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
if (e.Url != wbPost.Url)
return;
/* Document now loaded */
}
``` | HTML - How do I know when all frames are loaded? | [
"",
"c#",
"html",
"browser",
"mshtml",
""
] |
I have a piece of javascript which is supposed to latch onto a form which gets introduced via XHR. It looks something like:
```
$(document).ready(function() {
$('#myform').live('submit', function() {
$(foo).appendTo('#myform');
$(this).ajaxSubmit(function() {
alert("HelloWorld");
});
return false;
});
});
```
This happens to work in FF3, but not in IE7. Any idea what the problem is? | How are you excuting the submit? Can you try this instead?
```
$(':submit').live('click', function(e) {
$(foo).appendTo('#myform');
$('#myform').ajaxSubmit(function() {
alert('Hello World');
});
e.preventDefault();
return false;
});
``` | The submit event is not currently supported by [Events/live](http://docs.jquery.com/Events/live).
**Possible event values**: click, dblclick, mousedown, mouseup, mousemove, mouseover, mouseout, keydown, keypress, keyup
**Currently not supported:** blur, focus, mouseenter, mouseleave, change, submit | Does .live() binding work for jQuery in IE7? | [
"",
"javascript",
"jquery",
"web-applications",
""
] |
I have a small application with a `CheckBox` option that the user can set if they want the app to start with Windows.
My question is how do I actually set the app to run at startup.
ps: I'm using C# with .NET 2.0. | Several options, in order of preference:
1. Add it to the current user's Startup folder. This requires the least permissions for your app to run, and gives the user the most control and feedback of what's going on. The down-side is it's a little more difficult determining whether to show the checkbox already checked next time they view that screen in your program.
2. Add it to the `HKey_Current_User\Software\Microsoft\Windows\CurrentVersion\Run` registry key. The only problem here is it requires write access to the registry, which isn't always available.
3. Create a Scheduled Task that triggers on User Login
4. Add it to the `HKey_Local_Machine\Software\Microsoft\Windows\CurrentVersion\Run` registry key. The only problem here is it requires write access to the registry, which isn't always available.
5. Set it up as a windows service. Only do this if you *really* mean it, *and* you know for sure you want to run this program for *all* users on the computer.
This answer is older now. Since I wrote this, Windows 10 was released, which changes how the Start Menu folders work... including the `Startup` folder. It's not yet clear to me how easy it is to just add or remove a file in that folder without also referencing the internal database Windows uses for these locations. | Thanks to everyone for responding so fast.
Joel, I used your option 2 and added a registry key to the "Run" folder of the current user.
Here's the code I used for anyone else who's interested.
```
using Microsoft.Win32;
private void SetStartup()
{
RegistryKey rk = Registry.CurrentUser.OpenSubKey
("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
if (chkStartUp.Checked)
rk.SetValue(AppName, Application.ExecutablePath);
else
rk.DeleteValue(AppName,false);
}
``` | How do I set a program to launch at startup | [
"",
"c#",
"windows",
""
] |
I'm looking through a generic list to find items based on a certain parameter.
In General, what would be the best and fastest implementation?
1. Looping through each item in the list and saving each match to a new list and returning that
```
foreach(string s in list)
{
if(s == "match")
{
newList.Add(s);
}
}
return newList;
```
Or
2. Using the FindAll method and passing it a delegate.
```
newList = list.FindAll(delegate(string s){return s == "match";});
```
Don't they both run in ~ O(N)? What would be the best practice here?
Regards,
Jonathan | You should definitely use the `FindAll` method, or the equivalent LINQ method. Also, consider using the more concise lambda instead of your delegate if you can (requires C# 3.0):
```
var list = new List<string>();
var newList = list.FindAll(s => s.Equals("match"));
``` | I would use the [`FindAll` method](http://msdn.microsoft.com/en-us/library/fh1w7y8z.aspx) in this case, as it is more concise, and IMO, has easier readability.
You are right that they are pretty much going to both perform in O(N) time, although the [`foreach` statement](http://msdn.microsoft.com/en-us/library/ttw7t8t6%28v=vs.80%29.aspx) *should* be *slightly* faster given it doesn't have to perform a delegate invocation (delegates incur a slight overhead as opposed to directly calling methods).
I have to stress how insignificant this difference is, it's more than likely never going to make a difference unless you are doing a *massive* number of operations on a *massive* list.
As always, test to see where the bottlenecks are and act appropriately. | Generic list FindAll() vs. foreach | [
"",
"c#",
".net",
"generics",
""
] |
It's possible to define a pointer to a member and using this later on:
```
struct foo
{
int a;
int b[2];
};
```
int main()
{
foo bar;
int foo::\* aptr=&foo::a;
bar.a=1;
std::cout << bar.\*aptr << std::endl;
}
Now I need to have a pointer to a specific element of an array, so normally I'd write
`int foo::* bptr=&(foo::b[0]);`
However, the compiler just complains about an `"invalid use of non-static data member 'foo::b'`"
Is it possible to do this at all (or at least without unions)?
**Edit:** I need a pointer to a specific element of an array, so `int foo::* ptr` points to the second element of the array (`foo::b[1]`).
**Yet another edit:** I need to access the element in the array by `bar.*ptr=2`, as the pointer gets used somewhere else, so it can't be called with `bar.*ptr[1]=2` or `*ptr=2`. | The problem is that, accessing an item in an array is another level of indirection from accessing a plain int. If that array was a pointer instead you wouldn't expect to be able to access the int through a member pointer.
```
struct foo
{
int a;
int *b;
};
int main()
{
foo bar;
int foo::* aptr=&(*foo::b); // You can't do this either!
bar.a=1;
std::cout << bar.*aptr << std::endl;
}
```
What you can do is define member functions that return the int you want:
```
struct foo
{
int a;
int *b;
int c[2];
int &GetA() { return a; } // changed to return references so you can modify the values
int &Getb() { return *b; }
template <int index>
int &GetC() { return c[index]; }
};
typedef long &(Test::*IntAccessor)();
void SetValue(foo &f, IntAccessor ptr, int newValue)
{
cout << "Value before: " << f.*ptr();
f.*ptr() = newValue;
cout << "Value after: " << f.*ptr();
}
int main()
{
IntAccessor aptr=&foo::GetA;
IntAccessor bptr=&foo::GetB;
IntAccessor cptr=&foo::GetC<1>;
int local;
foo bar;
bar.a=1;
bar.b = &local;
bar.c[1] = 2;
SetValue(bar, aptr, 2);
SetValue(bar, bptr, 3);
SetValue(bar, cptr, 4);
SetValue(bar, &foo::GetC<0>, 5);
}
```
Then you at least have a consistent interface to allow you to change different values for foo. | > However, the compiler just complains about an "invalid use of non-static data member 'foo::b'"
This is because `foo::a` and `foo::b` have different types. More specifically, `foo::b` is an array of size 2 of `int`s. Your pointer declaration has to be compatible i.e:
```
int (foo::*aptr)[2]=&foo::b;
```
> Is it possible to do this at all (or at least without unions)?
Yes, see below:
```
struct foo
{
int a;
int b[2];
};
int main()
{
foo bar;
int (foo::*aptr)[2]=&foo::b;
/* this is a plain int pointer */
int *bptr=&((bar.*aptr)[1]);
bar.a=1;
bar.b[0] = 2;
bar.b[1] = 11;
std::cout << (bar.*aptr)[1] << std::endl;
std::cout << *bptr << std::endl;
}
```
Updated post with OP's requirements. | Member pointer to array element | [
"",
"c++",
"class",
"pointers",
""
] |
I want to construct classes for use as decorators with the following principles intact:
1. It should be possible to stack multiple such class decorators on top off 1 function.
2. The resulting function name pointer should be indistinguishable from the same function without a decorator, save maybe for just which type/class it is.
3. Ordering off the decorators should not be relevant unless actually mandated by the decorators. Ie. independent decorators could be applied in any order.
This is for a Django project, and the specific case I am working on now the method needs 2 decorators, and to appear as a normal python function:
```
@AccessCheck
@AutoTemplate
def view(request, item_id) {}
```
@AutoTemplate changes the function so that instead of returning a HttpResponse, it just returns a dictionary for use in the context. A RequestContext is used, and the template name is inferred from the method name and module.
@AccessCheck adds additional checks on the user based on the item\_id.
I am guessing it's just to get the constructor right and copy the appropriate attributes, but which attributes are these?
The following decorator won't work as I describe:
```
class NullDecl (object):
def __init__ (self, func):
self.func = func
def __call__ (self, * args):
return self.func (*args)
```
As demonstrated by the following code:
```
@NullDecl
@NullDecl
def decorated():
pass
def pure():
pass
# results in set(['func_closure', 'func_dict', '__get__', 'func_name',
# 'func_defaults', '__name__', 'func_code', 'func_doc', 'func_globals'])
print set(dir(pure)) - set(dir(decorated));
```
Additionally, try and add "print func.**name**" in the NullDecl constructor, and it will work for the first decorator, but not the second - as name will be missing.
Refined **eduffy**'s answer a bit, and it seems to work pretty well:
```
class NullDecl (object):
def __init__ (self, func):
self.func = func
for n in set(dir(func)) - set(dir(self)):
setattr(self, n, getattr(func, n))
def __call__ (self, * args):
return self.func (*args)
def __repr__(self):
return self.func
``` | A do-nothing decorator class would look like this:
```
class NullDecl (object):
def __init__ (self, func):
self.func = func
for name in set(dir(func)) - set(dir(self)):
setattr(self, name, getattr(func, name))
def __call__ (self, *args):
return self.func (*args)
```
And then you can apply it normally:
```
@NullDecl
def myFunc (x,y,z):
return (x+y)/z
``` | The [decorator module](http://pypi.python.org/pypi/decorator) helps you writing signature-preserving decorators.
And the [PythonDecoratorLibrary](http://wiki.python.org/moin/PythonDecoratorLibrary) might provide useful examples for decorators. | Decorator classes in Python | [
"",
"python",
"decorator",
""
] |
What is a regular expression suitable for C# that'll validate a number if it matches the following?
> ```
> $1,000,000.150
> $10000000.199
> $10000
> 1,000,000.150
> 100000.123
> 10000
> ```
Or the negative equivalents? | You can use csmba's regex if you make one slight modification to it.
```
^\$?(\d{1,3},?(\d{3},?)*\d{3}(.\d{0,3})?|\d{1,3}(.\d{2})?)$
``` | I think ssg is right.
It's not a really good use of Regex, especially if your software has to deal with non-US centric data entry.
For instance, if the currency symbol is the Euro, or the Japanese Yen or the British Pound any of the other dozen currency symbols out there?
What about number formatting rules?
In the US you would enter `1,000,000.00` but in France, this should be `1.000.000,00`. Other countries allow spacing between digit-grouping...
If you use a straight Regex without taking the Culture into account, then you're never going to validate successfully unless you're 100% sure your software will never ever be used in a non-US centric context. | What's a C# regular expression that'll validate currency, float or integer? | [
"",
"c#",
"regex",
"numbers",
"currency",
""
] |
We have an enterprise application written in asp.net c# (3.5) and SQL server that we want to bundle and release for customers.
However, several have expressed concerns that it **requires** a Microsoft server due to the costs. Yes, I know... Therefore, we are considering porting it to a LAMP stack, with the "P" referring to php.
**What challenges can we expect to face developing on a LAMP stack coming from a Visual Studio asp.net environment?**
The issues I am sure of are:
1. Debugging: Visual Studio is awesome for both client and server side debugging.
2. Framework: The code behind model works great, and the MVC framework is nice.
3. Maintenance: We would like the feature set to be common on both platforms.
4. Database layer: Code is loosely coupled to the mssql data types.
If you've been through this exciting process, I'd love to know what it was like with some recommendations/tips.
*As a side to this, is there any way for us to run this code as is? Mono? Others?* | I have more experience with .NET than the \*AMP stacks, but based on my experience with XAMPP, I would offer the following observations
1. Debugging: Visual Studio is awesome for both client and server side debugging.
[Eclipse PDT](http://www.eclipse.org/pdt/) works great for design, development, and debugging. I've heard good things about Zend Studio but haven't worked with it.
2. Framework: The code behind model works great, and the MVC framework is nice.
There are frameworks to allow you to separate presentation from logic (e.g. [Smarty](http://www.smarty.net/rightforme.php) ) and at least one MVC framework is available (e.g. [CakePHP](http://cakephp.org/))
3. Maintenance: We would like the feature set to be common on both platforms.
If you exclude Windows specific functionality (Windows Integrated Security, etc) there shouldn't be much you **can't** do in both stacks, but if you have to reproduce controls like the gridview it will be labor intensive.
4. Database layer: Code is loosely coupled to the mssql data types.
I am not aware of any data types that cannot be mapped between mysql and sql server and there is good documentation for [handling migrations](http://dev.mysql.com/doc/migration-toolkit/en/index.html)
Mono might decrease the amount of time required to port your solution, but I am unaware of any way you could re-use all of your code "as is". | Other MVC frameworks:
* CodeIgniter
* Kohana
* Yii
(Just found out about Yii. [Here's an article](http://www.beyondcoding.com/2009/03/02/choosing-a-php-framework-round-2-yii-vs-kohana-vs-codeigniter/) that compares them.)
There are probably a half-dozen more out there, as well. | What challenges will we face porting a site from asp.net to a LAMP (php) stack? | [
"",
"php",
"asp.net",
"porting",
""
] |
Can anyone help me figure out what the problem is. I am trying to start up a C# winformsa app in visual studio and i keep getting this error:
**Could not load file or assembly, Foo.dll version1.93343 or one of its dependencies
The system can't find the file specified**
vs 2005, C# 2.0
any help | Typically it's about one of your references' reference, possibly deep down in the dependency tree. What I usually do is, fire up Sysinternals Process Monitor (<http://technet.microsoft.com/en-us/sysinternals/bb896645.aspx>), filter by process name, and run the app. It's typically fairly easy at this point to sift through the FILE NOT FOUNDs and locate the offending missing reference. | Fire up [Fuslogvw.ex](http://msdn.microsoft.com/en-us/library/e74a18c4(vs.71).aspx)e and inspect which assembly (or reference) can't be found. | Could not load file or assembly error | [
"",
"c#",
"winforms",
"dependencies",
""
] |
I have a custom made class called Graph in which I use adjacency lists. To be more specific, I have an array of hash maps where each hash map contains all that node's neighbors as edges. The key is the end node and the value is an Edge object.
Now i want to make this Graph class implement Iterable. Is there a way of merging all those hash maps and return a common Iterator for all their elements?
It's very important that the method used is efficient. | According to the [API](http://java.sun.com/javase/6/docs/api/) HashMap has a function called entrySet() which returns a set view of the mapping in the Hash. A set is an iterable object. To make the Iterator, simply iterate through the array turning each hash into a set and then composing the individual iterators into a single Iterator...
There is no built in way to compose Iterators in java, however, writing your own compose function should be trivial. | You can use `ChainedIterator` from apache commons collections:
```
Iterator current = IteratorUtils.emptyIterator();
for(map: arrayOfHashmaps) {
current = IteratorUtils.chainedIterator(current, map.keySet().iterator);
}
```
If you want to avoid commons collections you can just collect the keysets in a list and iterate it:
```
List allKeys = new LinkedList();
for(map: arrayOfHashmaps) {
allKeys.addAll(map.KeySet());
}
return allKey.iterator();
```
The second solution will have uses slightly more memory and will be a little slower. However I doubt it will matter. | Iterator for all elements in hash maps stored in an array | [
"",
"java",
"collections",
""
] |
I'm having trouble installing the "[memcached](http://pecl.php.net/package/memcached)" PHP extension from PECL, though I can successfully installed the "[memcache](http://pecl.php.net/package/memcache)" extension. (They are separate PHP extensions.)
For example, these commands work okay:
> $ sudo pecl install memcache
> $ sudo pecl install APC
> $ sudo pecl install oauth
However, attempting to install memcached causes errors:
> $ sudo pecl install memcached
> ...
> ld: library not found for -lmemcached
> collect2: ld returned 1 exit status
> make: \*\*\* [memcached.la] Error 1
> ERROR: `make' failed
I'm using pecl, memcached, and libmemcached from Mac Ports (macports.org) on a recent Intel Mac. The libmemcached libraries can be found in /opt/local:
> /opt/local/include/libmemcached
> /opt/local/include/libmemcached/libmemcached\_config.h
> /opt/local/lib/libmemcached.2.0.0.dylib
> /opt/local/lib/libmemcached.2.dylib
> /opt/local/lib/libmemcached.a
> /opt/local/lib/libmemcached.dylib
> /opt/local/lib/libmemcached.la
Any idea what I may be doing wrong? | Andrei Zmievski (developer of the memcached plugin) kindly answered my email request with the following instructions:
```
$ pecl download memcached
$ tar zxvf memcached-1.0.0.tgz (or whatever version downloads)
$ cd memcached-1.0.0
$ phpize
$ ./configure --with-libmemcached-dir=/opt/local
$ make
$ sudo make install
```
This worked perfectly. | same situation here. i had to do the above, but with explicit path names (i run my php etc. out of /opt/local)
* **/opt/local/bin**/pecl download memcached
* tar zxvf memcached-1.0.0.tgz
* cd memcached-1.0.0
* **/opt/local/bin**/phpize
* ./configure **--prefix=/opt/local --with-php-config=/opt/local/bin/php-config** --with-libmemcached-dir=/opt/local
* make
* make install
normally this kind of stuff is pretty simple on os x with macports, but there is no php5-memcached package yet (only one for the older, memcache (no "d") package). oh, an i also had to install an older version of libmemcached, since the latest version didn't compile on os x 10.5.8 for me. oy! | Can I install the memcached PHP extension with PECL? | [
"",
"php",
"macos",
"memcached",
"pecl",
""
] |
I am creating a custom control using C# GDI+.
Quick explanation...the control will be say 500 pixels on screen but will contain perhaps 500000 pixels of information. So although i'm only showing 500px at a time i need to obviously scroll in the horizontal plane (left & right). The tricky part is that each 500px chunk of bitmap takes a while (between 100ms - 1000ms) to render.
So my plan is to maintain a 1500px bitmap in memory. i.e. the 500px visible part and 500px either side of the visible area and draw the off-screen parts asynchronously as the user scrolls.
I would like some feedback, advice, criticism or examples of code to help me achieve this. It seems fairly straight forward but after a few initial test attempts its proving more difficult than one would imagine.
Thanks. | The effectiveness of this approach depends on, amongst other things, the amount of moving around the user will do. If the user is making small movement, then stopping to consider the new information, this could work. However, if the user is whizzing back and forth, you'll still have an issue.
Does your application lend itself to gradually improving the quality of the image - i.e. providing a quick usable image and then improving it as the user stops to consider it? | I had a similar problem a few years back. As dommer mentions, if you're processing chunks of the image before displaying them you're best off showing something and improving it later. If you're having problems blitting the original image, you've got something wrong with your method. GDI+ is very particular about pixel depth (you want 32bpp with alpha).
In our case, we processed in 500px tiles and padded out a tile around the visible view Ff the user scrolled outside the area we'd processed we blitted bits of the original image with a dark semi-opaque rectangle super-imposed on them. These chunks were queued for processing. As we processed chunks of the image (centre-out) they semi-opaque rectangles would disappear.
It worked reasonably well, was very responsive and very fast. It's very fast to blit the original bitmap onto the screen, and in our case the processing was usually very close behind. The effect of the tiles getting lighter was actually quite pretty. | GDI+ Offscreen Buffered Scrolling | [
"",
"c#",
"gdi+",
"drawing",
"scroll",
"buffer",
""
] |
This code has the well defined behavior in C# of not working:
```
class Foo
{
static List<int> to = new List<int>( from ); // from is still null
static IEnumerable<int> from = Something();
}
```
*Note: I'm not asking how to fix that code as [I already known how to do that](https://stackoverflow.com/questions/185384/order-of-static-constructors-initializers-in-c)*
What is the justification for this? C# already does run time checks to detect the first access to static members. Why not extend this to a per member thing and have them run on demand or even better have the compiler figure out the order at compile time?
BTW: I think the same question (or almost the same) also holds for non static members. | I can envision a programmer depending on initialization order due to side effects with other static classes. You and I both know that depending on side effects is bad practice, but it's not necessarily illegal.
Consider something like this:
```
class Foo
{
static string header = Bar.GetHeader();
static string version = Bar.GetVersion();
}
```
And `Bar.GetVersion` assumes that `Bar.GetHeader` has been called. If the compiler were free to change the initialization order, then the programmer wouldn't be able to guarantee the initialization order.
Ugly, granted, but perfectly legal. If you imagine second-order effects (i.e. called static methods that themselves depend on classes that have side effects), you see that it's impossible for the compiler to reliably rearrange anything, just as it's impossible (in general) for the compiler to rearrange the order of function calls in your static constructor. | Initializers are just a syntactic sugar. Compiler puts that code in the .cctor when it compiles your class, and it pust them in the orders they're layed out in the code.
It doesn't run any checks, because it wouldn't make sense. You could still have initialization cycles, so it wouldn't work anyway.
I blogged about it some time ago if you're interested:
* [more on inline initialization](http://kozmic.pl/archive/2008/03/13/more-on-inline-initialization.aspx)
* [more on inline initialization (answer)](http://kozmic.pl/archive/2008/03/16/more-on-inline-initialization-answer.aspx) | Why in C# does order matter for static initialization? | [
"",
"c#",
"language-theory",
""
] |
I have a base class called LabFileBase. I have constructed a List and have added my derived classes to it. I want to search the List for a particular object based on a key I've defined. The problem I'm having is how do you downcast in a LINQ expression?
Here is some sample code:
```
public abstract class LabFileBase
{
}
public class Sample1 : LabFileBase
{
public string ID {get;set;}
public string Name {get;set;}
//..
}
public class Sample2 : LabFileBase
{
public string ID {get;set;}
public string Name {get;set;}
//..
}
```
I want to search for a particular Sample2 type, but I need to downcast if i used a regular foreach loop like this:
```
foreach(var s in processedFiles) //processedFiles is a List<LabFileBase>
if (s is Sample2)
var found = s as Sample2;
if (found.ID = ID && found.Name == "Thing I'm looking for")
//do extra work
```
I would much rather have something like this:
```
var result = processedFiles.Select(s => s.ID == SomeID && s.Name == SomeName);
```
Is this possible and what syntactic punctuation is involved, or is the `foreach` my only option because of the different objects. Sample1 and Sample2 only have ID and Name as the same fields.
EDIT: Thanks to all for your support and suggestions, I've entered almost everything into the backlog to implement. | To elaborate on Jon's answer, `OfType` is almost certainly the correct operator if you aren't willing to put these fields into your base class. For example:
```
foreach(var s in processedFiles.OfType<Sample2>())
if(s.ID == ID && s.Name == "Thing I'm looking for")
// whatever
foreach(var s in processedFiles.OfType<Sample1>())
if(s.ID == ID && s.Name == "Some other thing")
// and so on
``` | Why not put `ID` and `Name` into the base class? Then you don't need any downcasting.
If you *do* need casting though, the [`Cast`](http://msdn.microsoft.com/en-us/library/bb341406.aspx) and [`OfType`](http://msdn.microsoft.com/en-us/library/bb360913.aspx) operators may be helpful to you. Each transforms a sequence into a sequence of the specified type: `Cast` assumes that each element *is* the right type (and throws an exception if that's not the case); `OfType` works more like the C# `as` operator, only returning elements which happen to be the right type and ignoring others. | Downcasting and Linq | [
"",
"c#",
"linq",
"casting",
""
] |
I'm looking for a general purpose try and retry with a timeout in C#. Basically, I want the following:
```
bool stopTrying = false;
DateTime time = DateTime.Now;
while (!stopTrying)
{
try
{
//[Statement to Execute]
}
catch (Exception ex)
{
if (DateTime.Now.Subtract(time).Milliseconds > 10000)
{
stopTrying = true;
throw ex;
}
}
}
```
In the case above, I'm waiting for 10 second, but it should be a variable timeout based on a parameter. I don't want to have to repeat this full code wherever I need to use it. There are multiple places in my code where they isn't a timeout built into the API and I'll hit an exception if the application isn't ready for the statement to execute. This would also avoid having to hardcode delays in my application before these satement.
**Clarification:** The statement in question could be something like an assignment. If I use a delegate and method.Invoke, isn't the invokation scoped inside the delegate and not the original method? | Using your example, the solution is simple:
```
bool DoOrTimeout<T>(T method, TimeSpan timeout) where T : delegate // FIXME
{
bool stopTrying = false;
DateTime time = DateTime.Now;
while (!stopTrying)
{
try
{
method.Invoke();
stopTrying = true;
}
catch (Exception ex)
{
if (DateTime.Now.Subtract(time).Milliseconds > timeout.TotalMilliseconds)
{
stopTrying = true;
throw;
}
}
}
}
```
Just call `DoOrTimeout` with a delegate as the first parameter. | It's not the prettiest thing, but I seems to work nicely so far. And it doesn't use exceptions to indicate a timeout.
```
public static class TimeoutOperation
{
private static readonly TimeSpan DefaultTimeout = new TimeSpan(0, 0, 10);
private static readonly TimeSpan DefaultGranularity = new TimeSpan(0, 0, 0, 0, 100);
public static ThreadResult<TResult> DoWithTimeout<TResult>(Func<TResult> action)
{
return DoWithTimeout<TResult>(action, DefaultTimeout);
}
public static ThreadResult<TResult> DoWithTimeout<TResult>(Func<TResult> action, TimeSpan timeout)
{
return DoWithTimeout<TResult>(action, timeout, DefaultGranularity);
}
public static ThreadResult<TResult> DoWithTimeout<TResult>(Func<TResult> action, TimeSpan timeout, TimeSpan granularity)
{
Thread thread = BuildThread<TResult>(action);
Stopwatch stopwatch = Stopwatch.StartNew();
ThreadResult<TResult> result = new ThreadResult<TResult>();
thread.Start(result);
do
{
if (thread.Join(granularity) && !result.WasSuccessful)
{
thread = BuildThread<TResult>(action);
thread.Start(result);
}
} while (stopwatch.Elapsed < timeout && !result.WasSuccessful);
stopwatch.Stop();
if (thread.ThreadState == System.Threading.ThreadState.Running)
thread.Abort();
return result;
}
private static Thread BuildThread<TResult>(Func<TResult> action)
{
return new Thread(p =>
{
ThreadResult<TResult> r = p as ThreadResult<TResult>;
try { r.Result = action(); r.WasSuccessful = true; }
catch (Exception) { r.WasSuccessful = false; }
});
}
public class ThreadResult<TResult>
{
public TResult Result { get; set; }
public bool WasSuccessful { get; set; }
}
}
```
Usage
```
var result = TimeoutOperation.DoWithTimeout<int>(() =>
{
Thread.Sleep(100);
throw new Exception();
});
result.WasSuccessful // = false
result.Value // = 0
var result = TimeoutOperation.DoWithTimeout<int>(() =>
{
Thread.Sleep(2000);
return 5;
});
result.WasSuccessful // = true
result.Value // = 5
``` | General purpose Try and Retry with a Timeout in C#? | [
"",
"c#",
".net",
""
] |
I need to start 1-3 external programs in my Java application that have paths defined by the user. I have few requirements:
1. I don't want the program to execute if it is already running
2. I don't want any of the programs to steal focus from my Java application
3. I don't care if any of them fail to start or not. They just need to fail silently.
Here is what I have come up with so far:
```
ProcessBuilder pb = new ProcessBuilder(userDefinedPath1);
try {
pb.start();
}
catch (Exception e) {
// Something went wrong, just ignore
}
```
And then I repeat that 3 more times with the other two paths. This starts like I would expect and meets my third requirement just fine, but fails on the first two.
What is the best way to do this?
Edit:
1. I don't have any control of these other apps. They are third party. Also, they could have been start or stopped by the user manually at any time.
2. I know the *exact* names of the executables (e.g. "blah.exe") and they will *always* be the same, but the paths to the executables won't necessarily be.
3. Batch file wrappers are not feasible here.
4. The other apps are *not* java apps, just plain old Windows executables. | I'm guessing you don't have control over the other two apps... If you did, this wouldn't be too bad--you could just have them listen to a socket and see if the socket is available when you come up.
The next solution may actually be language independent. You could manage the whole system through batch file wrappers. Write a batch file that creates a file when it starts up and deletes it when it stops. Unix systems use this technique a lot--they call the file a lock file more often than not.
If only your app will ever start these other apps, then you could simply track if you've started it or not, so I'm guessing this isn't possible or you wouldn't be asking, so I'm assuming that the user may have launched these programs through some other mechanism.
If you have NO control over the launching of the other apps and can't even write a batch file to launch them, then you just can't do what you want to do (Note, the apps would have to always use the batch file, even if the user started them by hand).
I just a very-last ditch effort might be to get a process status and parse it, but you'd have to know exactly what the other apps were called in the PS, this isn't really trivial. Also, all java apps tend to have the same exact signature in most process status printouts which could make this useless.
The problem is that if one of these programs were started outside your app, you have virtually NO WAY to identify that fact unless you happen to know it's exact process status signature, and even then it's flaky. | In order to avoid potential lock file / crash issues, it is possible to start a server and catch the port collision. These servers are automatically stopped on system shutdown (Even after a crash)
```
public static ServerSocket ss;
public static void main (String[] args) {
ss = null;
try {
ss = new ServerSocket(1044);
} catch (IOException e) {
System.err.println("Application already running!");
System.exit(-1);
}
}
``` | Start Java program only if not already running | [
"",
"java",
"mutual-exclusion",
""
] |
How can I write an onclick handler that does one thing for regular clicks and a different thing for shift-clicks? | You can look at the click event's shiftKey property.
```
window.addEventListener("click",
function(e) {
if (e.shiftKey) console.log("Shift, yay!");
},
false);
```
```
<p>Click in here somewhere, then shift-click.</p>
``` | You need to make sure you pass `event` as a parameter to your `onclick` function. You can pass other parameters as well.
```
<html>
<head>
<script type="text/javascript">
function doSomething(event, chkbox)
{
if (event.shiftKey)
alert('Shift key was pressed while picking ' + chkbox.value);
else
alert('You picked ' + chkbox.value);
}
</script>
</head>
<body>
<h3>Pick a Color</h3>
<input type="radio" name="myColors" onclick="doSomething(event, this)" value="Red" /> Red<br/>
<input type="radio" name="myColors" onclick="doSomething(event, this)" value="Green" /> Green<br/>
<input type="radio" name="myColors" onclick="doSomething(event, this)" value="Blue" /> Blue<br/>
</body>
</html>
``` | In an onclick handler, how can I detect whether shift was pressed? | [
"",
"javascript",
""
] |
Is it possible, and if so how do I override the `Contains` method of an otherwise normal `List<T>`, where `T` is my own, custom type? | To make your own Contains implementation you could create a class that implements the IList interface. That way your class will look like a IList. You could have a real List internally to do the standard stuff.
```
class MyTypeList : IList<MyType>
{
private List<MyType> internalList = new ...;
public bool Contains(MyType instance)
{
}
....
}
``` | `List<T>` uses `EqualityComparer<T>.Default` to do comparisons; this checks first to see if your object implements `IEquatable<T>`; otherwise is uses `object.Equals`.
So; the easiest thing to do is to override `Equals` (always update `GetHashCode` to match the logic in `Equals`). Alternatively, use LINQ instead:
```
bool hasValue = list.Any(x => x.Foo == someValue);
``` | Override .NET Generic List<MyType>.Contains(MyTypeInstance)? | [
"",
"c#",
".net",
"list",
""
] |
I just read this [article on tdwtf.com](http://thedailywtf.com/Articles/WellIntentioned-Destruction.aspx). Generally, it describes an archiving bot destroying things because it ignores headers. I then realized that I don't know how to do security in a page WITHOUT headers. Therefore my question is:
**What security measures can i take besides using headers?**
I develop mostly in php, so I'm familiar with header("Location: ") function. But what else is out there?
Ideally I'm looking to replace the logic of
```
if (!$something_important) header("Location: somehereharmless.php");
```
with something else (more) secure? | header: location is fine, as long as you include an exit at the end.
You might also want to include a link or something.
I usually use something like this:
```
<?php
function redirect($url)
{
header('Location: ' . $url);
exit('<a href="' . $url . '">Redirecting you to: ' . $url . '</a>');
}
redirect('somepage.php');
?>
```
This way people can't bypass the redirect, and know that they should be redirected.
---
[Edit]
Also, **always** use `POST` when deleting stuff. It is very easy to create a fake `GET` (for example `<img src="http://www.example.org/action.php?do=SetAsAdmin&userid=MyUserId" />`). | This one works pretty well
```
if (!$something_important) {
header("Location: somehereharmless.php");
exit();
}
```
Even if it's bot, so it doesn't respect Location, you will call an exit so the execution flow is halted anyway, so no harm | securing a webpage without headers | [
"",
"php",
"security",
"http-headers",
""
] |
I just want a c# application with a hidden main window that will process and respond to window messages.
I can create a form without showing it, and can then call Application.Run() without passing in a form, but how can I hook the created form into the message loop?
Is there another way to go about this?
Thanks in advance for any tips! | Excellent! That link pointed me in the right direction. This seems to work:
```
Form f = new Form1();
f.FormBorderStyle = FormBorderStyle.FixedToolWindow;
f.ShowInTaskbar = false;
f.StartPosition = FormStartPosition.Manual;
f.Location = new System.Drawing.Point(-2000, -2000);
f.Size = new System.Drawing.Size(1, 1);
Application.Run(f);
```
To keep it from showing up in Alt-Tab, you need it to be a tool window. Unfortunately, this prevents it from starting minimized. But setting the start position to Manual and positioning it offscreen does the trick! | In the process of re-writing a VC++ TaskTray App, in C# .NET, I found the following method truly workable to achieve the following.
1. No initial form dislayed at startup
2. Running Message Loop that can be used with Invoke/BeginInvoke as needed as **IsWindowHandle** is true
The steps I followed:
1. Used an ApplicationContext in Application.Run() Instead of a form. See <http://www.codeproject.com/Articles/18683/Creating-a-Tasktray-Application> for the example I used.
2. Set the Form's **ShowInTaskbar** property to true within the GUI Designer. (This seems counter productive but it works)
3. Override the **OnLoad()** method in your Form Class setting **Visible** and **ShowInTaskbar** to false as shown below.
> ```
> protected override void OnLoad(EventArgs e)
> {
> Visible = false;
> ShowInTaskbar = false;
> base.OnLoad(e);
> }
> ``` | Any way to create a hidden main window in C#? | [
"",
"c#",
"winforms",
""
] |
I want to load to a new `AppDomain` some assembly which has a complex references tree (MyDll.dll -> Microsoft.Office.Interop.Excel.dll -> Microsoft.Vbe.Interop.dll -> Office.dll -> stdole.dll)
As far as I understood, when an assembly is being loaded to `AppDomain`, its references would not be loaded automatically, and I have to load them manually.
So when I do:
```
string dir = @"SomePath"; // different from AppDomain.CurrentDomain.BaseDirectory
string path = System.IO.Path.Combine(dir, "MyDll.dll");
AppDomainSetup setup = AppDomain.CurrentDomain.SetupInformation;
setup.ApplicationBase = dir;
AppDomain domain = AppDomain.CreateDomain("SomeAppDomain", null, setup);
domain.Load(AssemblyName.GetAssemblyName(path));
```
and got `FileNotFoundException`:
> Could not load file or assembly 'MyDll, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null' or one of its dependencies. The system cannot find the file specified.
I think the key part is **one of its dependencies**.
Ok, I do next before `domain.Load(AssemblyName.GetAssemblyName(path));`
```
foreach (AssemblyName refAsmName in Assembly.ReflectionOnlyLoadFrom(path).GetReferencedAssemblies())
{
domain.Load(refAsmName);
}
```
But got `FileNotFoundException` again, on another (referenced) assembly.
How to load all references recursively?
Do I have to create references tree before loading root assembly? How to get an assembly's references without loading it? | You need to invoke `CreateInstanceAndUnwrap` before your proxy object will execute in the foreign application domain.
```
class Program
{
static void Main(string[] args)
{
AppDomainSetup domaininfo = new AppDomainSetup();
domaininfo.ApplicationBase = System.Environment.CurrentDirectory;
Evidence adevidence = AppDomain.CurrentDomain.Evidence;
AppDomain domain = AppDomain.CreateDomain("MyDomain", adevidence, domaininfo);
Type type = typeof(Proxy);
var value = (Proxy)domain.CreateInstanceAndUnwrap(
type.Assembly.FullName,
type.FullName);
var assembly = value.GetAssembly(args[0]);
// AppDomain.Unload(domain);
}
}
public class Proxy : MarshalByRefObject
{
public Assembly GetAssembly(string assemblyPath)
{
try
{
return Assembly.LoadFile(assemblyPath);
}
catch (Exception)
{
return null;
// throw new InvalidOperationException(ex);
}
}
}
```
Also, note that if you use `LoadFrom` you'll likely get a `FileNotFound` exception because the Assembly resolver will attempt to find the assembly you're loading in the GAC or the current application's bin folder. Use `LoadFile` to load an arbitrary assembly file instead--but note that if you do this you'll need to load any dependencies yourself. | Once you pass the assembly instance back to the caller domain, the caller domain will try to load it! This is why you get the exception. This happens in your last line of code:
```
domain.Load(AssemblyName.GetAssemblyName(path));
```
Thus, whatever you want to do with the assembly, should be done in a proxy class - a class which inherit *MarshalByRefObject*.
Take in count that the caller domain and the new created domain should both have access to the proxy class assembly. If your issue is not too complicated, consider leaving the ApplicationBase folder unchanged, so it will be same as the caller domain folder (the new domain will only load Assemblies it needs).
In simple code:
```
public void DoStuffInOtherDomain()
{
const string assemblyPath = @"[AsmPath]";
var newDomain = AppDomain.CreateDomain("newDomain");
var asmLoaderProxy = (ProxyDomain)newDomain.CreateInstanceAndUnwrap(Assembly.GetExecutingAssembly().FullName, typeof(ProxyDomain).FullName);
asmLoaderProxy.GetAssembly(assemblyPath);
}
class ProxyDomain : MarshalByRefObject
{
public void GetAssembly(string AssemblyPath)
{
try
{
Assembly.LoadFrom(AssemblyPath);
//If you want to do anything further to that assembly, you need to do it here.
}
catch (Exception ex)
{
throw new InvalidOperationException(ex.Message, ex);
}
}
}
```
If you do need to load the assemblies from a folder which is different than you current app domain folder, create the new app domain with specific dlls search path folder.
For example, the app domain creation line from the above code should be replaced with:
```
var dllsSearchPath = @"[dlls search path for new app domain]";
AppDomain newDomain = AppDomain.CreateDomain("newDomain", new Evidence(), dllsSearchPath, "", true);
```
This way, all the dlls will automaically be resolved from dllsSearchPath. | How to Load an Assembly to AppDomain with all references recursively? | [
"",
"c#",
".net",
"reflection",
"assemblies",
"appdomain",
""
] |
I am pretty new in C# and my English is not so good - sorry in advance if I miss a point.
I tried to build an ASP.NET web site with a `ReportService` control. As you might already know, SSRS 2008 does not allow anonymous login. So, I tried to pass Credentials to SSRS which will be stored inside my web page so that users will be able to see the report without logging in.
I found the code below and put it on my `WebForm`, but I'm having a problem with the report parameters.
* If there are default values for the report parameters, the below code
works okay.
* But, if I try to change the value of a parameter, the whole page is
refreshed and before I click the "View Report" button, all
parameters are reset to default or null values.
Any suggestion on how to avoid refreshing the whole page, or another way to pass the login info to SSRS? Thanks a lot in advance.
```
using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Net;
using Microsoft.Reporting.WebForms;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
ReportViewer1.Width = 800;
ReportViewer1.Height = 600;
ReportViewer1.ProcessingMode = ProcessingMode.Remote;
IReportServerCredentials irsc =new CustomReportCredentials("administrator", "MYpassworw", "domena");
ReportViewer1.ServerReport.ReportServerCredentials = irsc;
ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://192.168.0.1/ReportServer/");
ReportViewer1.ServerReport.ReportPath = "/autonarudzba/listanarudzbi";
ReportViewer1.ServerReport.Refresh();
}
}
public class CustomReportCredentials : IReportServerCredentials
{
private string _UserName;
private string _PassWord;
private string _DomainName;
public CustomReportCredentials(string UserName, string PassWord, string DomainName)
{
_UserName = UserName;
_PassWord = PassWord;
_DomainName = DomainName;
}
public System.Security.Principal.WindowsIdentity ImpersonationUser
{
get { return null; }
}
public ICredentials NetworkCredentials
{
get { return new NetworkCredential(_UserName, _PassWord, _DomainName); }
}
public bool GetFormsCredentials(out Cookie authCookie, out string user,
out string password, out string authority)
{
authCookie = null;
user = password = authority = null;
return false;
}
}
``` | I really haven't messed with SSRS - but my ASP.NET hat tells me you may want to wrap that stuff in an `if (!IsPostBack)` block to keep it from running on the page refresh. My guess is that `ReportViewer1.ServerReport.Refresh()` pulls the default values again.
```
protected void Page_Load(object sender, EventArgs e)
{
if (!this.IsPostBack)
{
ReportViewer1.Width = 800;
ReportViewer1.Height = 600;
ReportViewer1.ProcessingMode = ProcessingMode.Remote;
IReportServerCredentials irsc =new CustomReportCredentials("administrator", "MYpassworw", "domena");
ReportViewer1.ServerReport.ReportServerCredentials = irsc;
ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://192.168.0.1/ReportServer/");
ReportViewer1.ServerReport.ReportPath = "/autonarudzba/listanarudzbi";
ReportViewer1.ServerReport.Refresh();
}
}
``` | I made new function and picked it up in the design view on properties, events, reportViewer. (In selection INIT i)
After that, the page works normally and I can change values for parameters.
Default.aspx now looks like:
```
</head>
<body>
<form id="form1" runat="server">
<div>
<rsweb:ReportViewer ID="ReportViewer1" runat="server" onload="Admir">
</rsweb:ReportViewer>
</div>
</form>
</body>
```
And Default.aspx.cs looks like this
```
public void Admir(object sender, EventArgs e)
{
ReportViewer1.Width = 800;
ReportViewer1.Height = 600;
ReportViewer1.ProcessingMode = ProcessingMode.Remote;
IReportServerCredentials irsc = new CustomReportCredentials("administrator", "mypass", "domena");
ReportViewer1.ServerReport.ReportServerCredentials = irsc;
ReportViewer1.ServerReport.ReportServerUrl = new Uri("http://192.168.0.1/ReportServer/");
ReportViewer1.ServerReport.ReportPath = "/autonarudzba/listanarudzbi";
ReportViewer1.ServerReport.Refresh();
}
protected void Page_Load(object sender, EventArgs e)
{
}
``` | Passing Credentials to Sql Report Server 2008 | [
"",
"c#",
"asp.net",
"reporting-services",
"ssrs-2008",
""
] |
I have a string which has several html comments in it. I need to count the unique matches of an expression.
For example, the string might be:
```
var teststring = "<!--X1-->Hi<!--X1-->there<!--X2-->";
```
I currently use this to get the matches:
```
var regex = new Regex("<!--X.-->");
var matches = regex.Matches(teststring);
```
The results of this is 3 matches. However, I would like to have this be only 2 matches since there are only two unique matches.
I know I can probably loop through the resulting MatchCollection and remove the extra Match, but I'm hoping there is a more elegant solution.
*Clarification*: The sample string is greatly simplified from what is actually being used. There can easily be an X8 or X9, and there are likely dozens of each in the string. | I would just use the [Enumerable.Distinct Method](http://msdn.microsoft.com/en-us/library/system.linq.enumerable.distinct.aspx) for example like this:
```
string subjectString = "<!--X1-->Hi<!--X1-->there<!--X2--><!--X1-->Hi<!--X1-->there<!--X2-->";
var regex = new Regex(@"<!--X\d-->");
var matches = regex.Matches(subjectString);
var uniqueMatches = matches
.OfType<Match>()
.Select(m => m.Value)
.Distinct();
uniqueMatches.ToList().ForEach(Console.WriteLine);
```
Outputs this:
```
<!--X1-->
<!--X2-->
```
---
For regular expression, you could maybe use this one?
```
(<!--X\d-->)(?!.*\1.*)
```
Seems to work on your test string in RegexBuddy at least =)
```
// (<!--X\d-->)(?!.*\1.*)
//
// Options: dot matches newline
//
// Match the regular expression below and capture its match into backreference number 1 «(<!--X\d-->)»
// Match the characters “<!--X” literally «<!--X»
// Match a single digit 0..9 «\d»
// Match the characters “-->” literally «-->»
// Assert that it is impossible to match the regex below starting at this position (negative lookahead) «(?!.*\1.*)»
// Match any single character «.*»
// Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
// Match the same text as most recently matched by capturing group number 1 «\1»
// Match any single character «.*»
// Between zero and unlimited times, as many times as possible, giving back as needed (greedy) «*»
``` | It appears you're doing two different things:
1. Matching comments like /<-- X. -->/
2. Finding the set of unique comments
So it is fairly logical to handle these as two different steps:
```
var regex = new Regex("<!--X.-->");
var matches = regex.Matches(teststring);
var uniqueMatches = matches.Cast<Match>().Distinct(new MatchComparer());
class MatchComparer : IEqualityComparer<Match>
{
public bool Equals(Match a, Match b)
{
return a.Value == b.Value;
}
public int GetHashCode(Match match)
{
return match.Value.GetHashCode();
}
}
``` | How can I get a regex match to only be added once to the matches collection? | [
"",
"c#",
"regex",
""
] |
We have an existing ServiceContract
```
[ServiceContract(Namespace = "http://somesite.com/ConversationService")]
public interface IConversationService
{
[OperationContract(IsOneWay = true)]
void ProcessMessage(Message message);
[OperationContract(IsOneWay = true)]
void ProcessMessageResult(MessageResult result);
}
```
and we need to add a method to it
```
[ServiceContract(Namespace = "http://somesite.com/ConversationService")]
public interface IConversationService
{
[OperationContract(IsOneWay = true)]
void ProcessMessage(Message message);
[OperationContract(IsOneWay = true)]
void ProcessMessageResult(MessageResult result);
[OperationContract(IsOneWay = true)]
void ProcessBlastMessage(BlastMessage blastMessage);
}
```
Will this break any existing wcf clients that are using this service? Or will we have to update all existing wcf clients?
EDIT: This service is using both netTcpBinding and netMsmqBinding | I think your existing clients will continue to work. After all this is very similar to SOAP and web services in that the client will connect to the given URL and request a specific service. If you take methods away you will risk breakage (only if the method is used I believe) but adding should be pain free.
I've only dabbled in WCF but have used the ASP.NET web services in this way to great success. | I just tested this with a WCF client Windows app (UWP) and it continued to work after updating the WCF service application. So **no**: as previously answered, your clients will not break when you add a method.
I thought it was worth mentioning, however, how easy it is to update your service clients with Visual Studio 2015:
1. Make sure your WFC service is running.
2. Simply go to the `Solution Explorer`,
3. Expand `Service References`
4. Right-click on your service reference
5. Click `Update Service Reference`
6. If you get an error message, repeat the last step. I had to try a few times for some reason. | Does adding a method to a WCF ServiceContract break existing clients? | [
"",
"c#",
".net",
"wcf",
""
] |
I've installed various PHP packages to be able to use PHP with Apache but also in the commandline. From both I need to be able to connect to MySQL databases. Pretty simple right? That's what I thought but with php-cli I receive following error:
```
Fatal error: Call to undefined function mysql_pconnect()
```
I have tried starting from scratch by removing all depending packages and configuration like this:
```
sudo apt-get --purge remove php5 libapache2-mod-php5 php5-cli php5-mysql
```
Then I've run following command to install the packages:
```
sudo apt-get install php5 libapache2-mod-php5 php5-cli php5-mysql
```
Then I've found out which php.ini the cli uses like that:
```
php -r "phpinfo();" | grep php.ini
```
Which gives me this:
```
Configuration File (php.ini) Path => /etc/php5/cli/php.ini
```
Then i've uncommented 'mysql.so' in the extensions section but when i do and run following command it says:
```
PHP Warning: Module 'mysql' already loaded in Unknown on line 0
```
So for some reason he thinks it is already loaded, but with or without the 'mysql.so' enabled the php cli does not find the 'mysql\_pconnect' function.
I know there's a sections to enable persistent connections, it on by default and the standard function 'mysql\_connect' is also not available.
What am I missing? Thanks!
UPDATE:
As suggested by Bart S. 'php -r "phpinfo();" | grep mysql':
> ```
> MYSQL_SOCKET => /var/run/mysqld/mysqld.sock
> MYSQL_INCLUDE => -I/usr/include/mysql
> MYSQL_LIBS => -L/usr/lib -lmysqlclient
> mysql.allow_persistent => On => On
> ... and more
> ```
From Jaka Jančar. 'php -v' shows:
> PHP 5.1.2 (cli) (built: Feb 11 2009 19:55:22)
And from php interactive mode 'php -r 'var\_dump(extension\_loaded("mysql"));' gives nothing! | ```
php -i | grep mysql
```
The first line should contain:
```
Configure Command => '../configure' ... '--with-mysql=shared,/usr'
```
Also check
```
grep extension_dir /etc/php5/cli/php.ini
```
Should be something like: `extension_dir = /usr/lib/php5/extensions`
Then check permissions of `/usr/lib/php5/extensions/mysql.so` and if it's properly linked:
```
ldd /usr/lib/php5/extensions/mysql.so
``` | You cant use pconnect in CLI mode. You dont have a persistent process like the web server which can hold the open connection. | Problems with php-cli and mysql, why is mysql_pconnect() not available? | [
"",
"php",
""
] |
Due to the use of Generics in Java I ended up in having to implement a function having `Void` as return type:
```
public Void doSomething() {
//...
}
```
and the compiler demands that I return *something*. For now I'm just returning `null`, but I'm wondering if that is good coding practice...
I'm asking about **V**oid, not **v**oid. The class `Void`, **not** the reserved keyword `void`.
I've also tried `Void.class`, `void`, `Void.TYPE`, `new Void()`, no return at all, but all that doesn't work at all. (For more or less obvious reasons) (See [this answer](https://stackoverflow.com/questions/676663/what-do-i-return-if-the-return-type-of-a-method-is-void-not-void/881358#881358) for details)
* So what am I supposed to return if the return type of a function is `Void`?
* What's the general use of the `Void` class? | > So what am I supposed to return if the return type of a function has to be `Void`?
Use `return null`. `Void` can't be instantiated and is merely a placeholder for the `Class<T>` type of `void`.
> What's the point of `Void`?
As noted above, it's a placeholder. `Void` is what you'll get back if you, for example, use reflection to look at a method with a return type of `void`. (Technically, you'll get back `Class<Void>`.) It has other assorted uses along these lines, like if you want to parameterize a `Callable<T>`.
> Due to the use of generics in Java I ended up in having to implement this function
I'd say that something may be funky with your API if you needed to implement a method with this signature. Consider carefully whether there's a better way to do what you want (perhaps you can provide more details in a different, follow-up question?). I'm a little suspicious, since this only came up "due to the use of generics". | There's no way to instantiate a Void, so the only thing you *can* return is null. | What do I return if the return type of a method is Void? (Not void!) | [
"",
"java",
"generics",
"void",
""
] |
Creating an item(Under the key) is easy,but how to add subitems(Value)?
```
listView1.Columns.Add("Key");
listView1.Columns.Add("Value");
listView1.Items.Add("sdasdasdasd");
//How to add "asdasdasd" under value?
``` | Like this:
```
ListViewItem lvi = new ListViewItem();
lvi.SubItems.Add("SubItem");
listView1.Items.Add(lvi);
``` | You whack the subitems into an array and add the array as a list item.
The order in which you add values to the array dictates the column they appear under so think of your sub item headings as [0],[1],[2] etc.
Here's a code sample:
```
//In this example an array of three items is added to a three column listview
string[] saLvwItem = new string[3];
foreach (string wholeitem in listofitems)
{
saLvwItem[0] = "Status Message";
saLvwItem[1] = wholeitem;
saLvwItem[2] = DateTime.Now.ToString("dddd dd/MM/yyyy - HH:mm:ss");
ListViewItem lvi = new ListViewItem(saLvwItem);
lvwMyListView.Items.Add(lvi);
}
``` | C#: How to add subitems in ListView | [
"",
"c#",
".net",
"winforms",
"list",
"view",
""
] |
Are there rules of thumb for developers when to use join instead of subquery or are they the same. | Depends on RDBMS. You should compare execution plans for both queries.
In my experience with Oracle 10 and 11, execution plans are always the same. | The first principle is "State the query accurately". The second principle is "state the query simply and obviously" (which is where you usually make choices). The third is "state the query so it will process efficiently".
If its a dbms with a good query processor, equivalent query designs should should result in query plans that are the same (or at least equally efficient).
My greatest frustration upon using MySQL for the first time was how conscious I had to be to anticipate the optimizer. After long experience with Oracle, SQL Server, Informix, and other dbms products, I very seldom expected to concern myself with such issues. It's better now with newer versions of MySQL, but it's still something I end up needing to pay attention to more often than with the others. | Join query or subquery | [
"",
"sql",
"join",
"subquery",
""
] |
In Python, I often have tests which look something like this:
```
tests = [
(2, 4),
(3, 9),
(10, 100),
]
for (input, expected_output) in tests:
assert f(input) == expected_output
```
What is the "right" way to write tests like this (where a set of test cases is specified, then a loop runs each of them) in Java with JUnit?
Thanks!
**Preemptive response**: I realize I *could* do something like:
```
assertEquals(4, f(2))
assertEquals(9, f(3))
....
```
But... I'm hoping there is a better way. | Same thing.
```
int[][] tests = {
{2, 4},
{3, 9},
{10, 100}
};
for (int[] test : tests) {
assertEquals(test[1], f(test[0]));
}
```
Certainly not as pretty as python but few things are.
You may also want to look into [JUnit Theories](http://junit.sourceforge.net/doc/ReleaseNotes4.4.html), a future feature... | The right way is writing separate assert statements, even if you don't like it.
It avoids unnecessary complications, and when it fails it is sometimes easier to see which value failed (no need to start up the debugger).
However, if you generate your test data automatically it is a different story. | What is the "right" way to test the output of Java methods? | [
"",
"java",
"unit-testing",
"testing",
"junit",
""
] |
I have a messaging aspect of my application using [Jabber-net](http://code.google.com/p/jabber-net/) (an [XMPP library](http://en.wikipedia.org/wiki/List_of_XMPP_library_software).)
What I would like to do, if for some reason the connection to the Server is ended, is keep trying to connect every minute or so.
If I start a Timer to wait for a period of time before the next attempt, does that timer run asynchronously and the resulting Tick event join the main thread, or would I need to start my own thread and start the timer from within there? | What kind of timer are you using?
* `System.Windows.Forms.Timer` will execute in the UI thread
* `System.Timers.Timer` executes in a thread-pool thread unless you specify a `SynchronizingObject`
* `System.Threading.Timer` executes its callback in a thread-pool thread
In all cases, the timer itself will be asynchronous - it won't "take up" a thread until it fires. | The timer will effectively run in the background and cause events in your main thread to be executed. | Do .NET Timers Run Asynchronously? | [
"",
"c#",
".net",
"multithreading",
"timer",
""
] |
I need to find the bandwidth available at a particular time. The code must be developed in Visual C++ or in .Net family . If anyone knows how, please help me out. | The only way to check your bandwidth is to actually try to use it, i.e. by downloading a file from somewhere else and measuring the throughput.
Even then it'll only be an approximation, because other network effects will affect the results:
* latency
* asymmetric upload / download
* other traffic | If you mean the current network utilisation, you can call
[`DeviceIoControl`](http://msdn.microsoft.com/en-us/library/aa365915.aspx)`(hDevice,` [`OID_GEN_STATISTICS`](http://msdn.microsoft.com/en-us/library/ms798985.aspx)`,` ...`)`
on Vista and above to get the device-specific information. Otherwise, call [GetIpStatisticsEx](http://msdn.microsoft.com/en-us/library/aa365963.aspx) for system-wide information or use WMI's [Win32\_PerfRawData\_Tcpip\_NetworkInterface](http://msdn.microsoft.com/en-us/library/aa394340.aspx).
Trying to get the "available" bandwidth by attempting to saturate the connection is not a sensible or reliable measure. Just try some of the online speed tests available, and consider that it involves non-scalable bandwidth, and is susceptible to congestion control, QoS and traffic shaping. | How to programmatically check Internet bandwidth in VC++? | [
"",
"c++",
"visual-studio",
"winapi",
"mfc",
""
] |
I would like to know the most common scenarios where xml serialization may fail in .NET. | I'm thinking mainly of `XmlSerializer` here:
* it is limited to tree-like data; it can't handle full object graphs
* it is limited to public members, on public classes
* it can't really do much with `object` members
* it has some weaknesses around generics
* like many serializers, it won't touch instance properties on a collection (bad practice in the first place)
* xml simply isn't always a good choice for large data (not least, for performance)
* requires a public parameterless constructor
`DataContractSerializer` solves some of these, but has its own limitations:
* it can't handle values in attributes
* requires .NET 3.0 (so not much use in 2.0) | Cannot easily serialize generic collections.
See another question: [C# XML Serialization Gotchas](https://stackoverflow.com/questions/67959/c-xml-serialization-gotchas) | Scenarios where Xml Serialization fail in .NET | [
"",
"c#",
".net",
"xml-serialization",
""
] |
I'm using PHP to extract data from a MySQL database. I am able to build an XML file using DOM functions. Then using `echo $dom->saveXML();` , I am able to return the XML from an AJAX call. Instead of using AJAX to get the XML, how would I save the XML file to a spot on the server? Thanks | Use the [`DOMDocument::save()` method](http://docs.php.net/manual/en/domdocument.save.php) to save the XML document into a file:
```
$dom->save('document.xml');
``` | Doesn't [DOMDocument::save()](http://www.php.net/manual/en/domdocument.save.php) help you? | Create and Save XML file to Server Using PHP | [
"",
"php",
"xml",
""
] |
I want to have client-side validation for quick response to the user without a roundtrip to the server.
I also want the same validation for securing the code behind action ***on the business and data access layer***.
How do you reuse that kind of code pragmatically in ASP.NET?
(note: ASP.NET, C# 3.0, .NET 3.5, Visual Studio 2008) | A friendly warning not to expect too much success for your efforts. This [article](http://thedailywtf.com/Articles/The-Mythical-Business-Layer.aspx) describes quite well the fallacies in thinking about the mythical "business layer" that you are seeing in your efforts to centralize and avoid duplication of code. The upshot is that doing the kind of unification you're talking about is often too difficult to justify. | I don't know if there is something for regular asp.net, but you might want to check how this open source project is going about it: <http://xval.codeplex.com/>. Note, I haven't really used it, so I am not sure how good it is. | Reuse of validation code in UI, BL and/or DL | [
"",
"c#",
".net",
"asp.net",
"validation",
""
] |
I am trying to write a small web tool which takes an Excel file, parses the contents and then compares the data with another dataset. Can this be easily done in JavaScript? Is there a JavaScript library which does this? | How would you load a file into JavaScript in the first place?
In addition, Excel is a proprietary format and complex enough that server side libraries with years in development (such as [Apache POI](http://poi.apache.org/)) haven't yet managed to correctly 100% reverse engineer these Microsoft formats.
So I think that the answer is that you can't.
**Update:** That is in pure JavaScript.
**Update 2:** It is now possible to load files in JavaScript: <https://developer.mozilla.org/en-US/docs/DOM/FileReader> | In the past four years, there have been many advancements. HTML5 File API has been embraced by the major browser vendors and performance enhancements actually make it somewhat possible to parse excel files (both xls and xlsx) in the browser.
My entries in this space:
* <http://oss.sheetjs.com/js-xls/> (xls)
* <http://oss.sheetjs.com/js-xlsx/> (xlsx)
Both are pure-JS parsers | How to parse an excel file in JavaScript? | [
"",
"javascript",
"html",
"excel",
"parsing",
""
] |
I am trying to get the number of students enrolled in courses via a single SQL statement, but not using sub-queries. So far I can only figure out how to do it using sub-queries. Is there another way?
Consider the following database setup:
```
create table student (id integer not null primary key);
create table course_enrolment (student integer not null references student, course integer not null);
insert into student values (1);
insert into student values (2);
insert into student values (3);
insert into course_enrolment values (2,20);
insert into course_enrolment values (2,30);
insert into course_enrolment values (3,10);
```
I want to get the number of students enrolled in courses. In this case, it's 2.
I can achieve this easily using sub-queries:
> SELECT COUNT(\*) FROM (SELECT DISTINCT STUDENT FROM COURSE\_ENROLMENT) AS DATA;
I want to get the count without using a sub-query.
I am using Postgresql 8.3 but am looking for a vendor agnostic solution. | How about this:
```
SELECT course, COUNT(DISTINCT student)
FROM course_enrolment
GROUP BY course
```
This gives students per course. If you just want the total number enrolled on any course:
```
SELECT COUNT(DISTINCT student)
FROM course_enrolment
```
I believe that's all ANSI-standard SQL, so should work most places. | I don't know about postgres, but on SQL Server:
```
SELECT COUNT(DISTINCT STUDENT) FROM COURSE_ENROLMENT
``` | Simple SQL to return a count without using sub queries | [
"",
"sql",
"postgresql",
""
] |
I have some link buttons in which I am dynamically adding a style to it. I am doing the following in a method:
```
LinkButton lb = new LinkButton();
lb.Style["font-weight"] = "bold";
```
When the another link is clicked, it should unbold the link button that is bold and bold the currently clicked one, so in the method that is doing this, I have tried:
```
lb.Style["font-weight"] = "none";
```
The above does not work though, the previously selected link stays bold.
I just realized the possible problem. I am creating multiple links and what it looks like is that since all the links are named lb, it never removes the bold. I am trying to think of a way for it to remember the previously selected link and to only unbold that one. | Can I suggest an alternative approach?
Set a CSS Style:
```
.selected { font-style: bold; }
```
When a link is clicked set that link's CSS class to "selected" and the others to "";
**EDIT: To accommodate for existing Css Class**
```
const string MY_CLASS = "links";
lb1.CssClass = MY_CLASS + " selected"; // selected
lb.CssClass = MY_CLASS; // not selected
```
You can quickly get into trouble when defining inline styles, in that they're difficult to overwrite.
**EDIT 2:**
Something like this code should work. You may have to loop through all the LinkButtons in the list, but I don't think so. I'd just turn off ViewState on the LinkButtons.
```
// container for links. so you can reference them
// outside of the creation method if you wish. I'd probably call this method in the
// Page_Init Event.
List<LinkButton> listOfLinks = new List<LinkButton>();
const string MY_LB_CLASS = "linkButton"; // generic lb class
private void createSomeLinks() {
for (int i = 0; i < 10; i++) {
// create 10 links.
LinkButton lb = new LinkButton()
{
ID = "lb" + i,
CssClass = MY_LB_CLASS
};
lb.Click += new EventHandler(lb_Click); // Add the click event
}
// You can bind the List of LinkButtons here, or do something with them.
}
void lb_Click(Object sender, EventArgs e) {
LinkButton lb = sender as LinkButton; // cast the sender as LinkButton
if (lb != null) {
// Make the link you clicked selected.
lb.CssClass = MY_LB_CLASS + " selected";
}
}
``` | Try lb.Style.Remove("font-weight"). I didn't test it, but you can try it out.
Alternatively, have you tried settings the Font.Bold property?
```
lb.Font.Bold = true;
``` | Dynamically changing css style in c#? | [
"",
"c#",
"asp.net",
""
] |
I am using a 3rd party library that has a declaration like this:
```
typedef struct {} __INTERNAL_DATA, *HandleType;
```
And I'd like to create a class that takes a *HandleType* in the constructor:
```
class Foo
{
Foo(HandleType h);
}
```
**without** including the header that defines *HandleType*. Normally, I'd just forward-declare such a type, but I can't figure out the syntax for this. I really want to say something like:
```
struct *HandleType;
```
But that says "Expected identifier before \*" in GCC. The only solution I can see is to write my class like this:
```
struct __INTERNAL_DATA;
class Foo
{
Foo(__INTERNAL_DATA *h);
}
```
But this relies on internal details of the library. That is to say, it uses the name \_\_INTERNAL\_DATA, which is an implementation detail.
It seems like it should be possible to forward-declare HandleType (part of the public API) without using \_\_INTERNAL\_DATA (part of the implementation of the library.) Anyone know how?
EDIT: Added more detail about what I'm looking for. | **Update:**
> I am using it in the implementation .cpp of Foo, but I want to avoid including it in my header .h for Foo. Maybe I'm just being too pedantic? :)
Yes you are :) Go ahead with forward declaration.
If HandleType is part of the interface there must be a header declaring that. Use that header.
Your problem is still a vague one. You are trying to protect against something you cannot.
You can add the following line to your client library:
```
typedef struct INTERNAL_DATA *HandleType;
```
but, if the name/structure changes you may be in for some casting nastiness.
Try templates:
```
template <class T>
class Foo
{
Foo(T h);
};
```
Forward declaration is fine. If you are going to use pointers or references you only need a class (`__INTERNAL_DATA`) declaration in scope. However, if you are going to use a member function or an object you will need to include the header. | If you really, really, really don't want to expose \_INTERNAL\_DATA to the caller then your only real choice is to use **typedef void\* HandleType**; Then inside your library you can do anything you want including changing the entire implementation of \*HandleType.
Just create a helper function to access you real data.
```
inline _INTERNAL_DATA* Impl(HandleType h) {
return static_cast<_INTERNAL_DATA*>(h);
}
``` | Forward declare pointers-to-structs in C++ | [
"",
"c++",
"struct",
"forward-declaration",
""
] |
I have a computation that calculates a resulting percentage based on certain input. But these calculations can take quite some time, which can be annoying. Since there are about 12500 possible inputs, I thought it would be a good idea to precompute all the data, and look this up during normal program execution.
My first idea was to just create a simple file which is read at program initialization and populates some arrays. Although this will work, I would like to know if there are some other options? For example that the array is populated during compile time.
BTW, I'm writing my code in C#. | A file with data is probably the easiest and most flexible way to implement it.
If you wanted it in memory without having to read it from somewhere, I would write a program to output your data in C#-like CSV format suitable for copying and pasting into an array/collection initializer, and thereby generate the source code for your precomputed data. | [This tutorial here](http://www.switchonthecode.com/tutorials/csharp-tutorial-serialize-objects-to-a-file) implements a serializer, which you can use to easily convert an object to a binary file and back. Once you have the serializer in hand, you can just create an object that holds all your data and serialize it; when you actually run your program, just deserialize the object and use it.
This has all the benefits of saving an object to the hard drive, with an implementation that is object-agnostic (meaning you don't have to write much code for any object you want to serialize) and outputs in binary (thus saving space, if that is a concern). | What is the best way to implement precomputed data? | [
"",
"c#",
""
] |
The "goto" statement comes straight out of ASM or any other assembler language.
Here's a link: <https://www.php.net/manual/en/control-structures.goto.php>
I'm wondering: what can this do to make my code more well-organized? How can I implement this in larger projects, without screwing it up.
Since the goto will allow you to jump back and forth, accidental assignments and infinite loops are waiting to happen if you use this the wrong way.
Can someone give me an example of a good use of this?
EDIT: allright, I've seen some of the replies and apparently a wide consensus exists about the use of the "goto" statement and it being bad.
So I'm still wondering: why would PHP bother to add it to the language. If they didn't see something in it, they wouldn't do it... so why?
Also: [A discussion here on StackOverflow about "goto" in general](https://stackoverflow.com/questions/46586/goto-still-considered-harmful)
EDIT2: Seeing as this question induced a lot of bad things to be sad about the goto statement, I went and asked my father. He's 52 years old and is an Industrial Engineer.
He told me a couple of times he did a good amount of programming in his days and mostly in FORTRAN and COBOL. Nowadays he does IT services, server&networkmanagment and such.
Anyways, he said some stuff about "back in my day..."
After discussing that a bit, he came back to the goto statement, saying that even back in his days as a student, they allready knew it wasn't a smart idea to use it, but they didn't have much better back then. Try/catch was still years away and error handling hardly excisted.
So what did you do to check your program? Add a few lines at the end that allow you to print output and everything you need to check in your code, and then you place the line: "goto printing;", or something like that, to start the printing of your data.
And in this manner, you gradually debugged your code.
He agrees that the use of goto in the modern programming world is pretty useless. The only use he finds justified is an "emergency break", to be used in extreme debugging and unexpected situations. Kinda like `goto fatal_error;`, and have the "fatal\_error" part of your code do some things to show you in-depth results.
But only during the creation of something. A finished product should not have goto-statements.
LATE EDIT: [Another discussion about "goto" in PHP5.3/PHP6](https://stackoverflow.com/questions/19388/goto-command-in-php6) | If you're writing good PHP code, you shouldn't need to use goto. I think it's a mistake that they're adding it in, as it just leads to lazy programming.
See
<http://www.procata.com/blog/archives/2004/07/29/goto-in-php/>
For a good commentary on the addition of this to PHP, and also, here on stack overflow,
[GOTO still considered harmful?](https://stackoverflow.com/questions/46586/goto-still-considered-harmful) | I have only ever found two uses for `goto`:
1. To break out of nested loops. But most newer languages have a mechanism to do this without `goto` anyway (`break <number>` in PHP, or `break <loop label>` in Java, etc.).
2. To go to a cleanup section at the end of a function. But again, this isn't often useful in a garbage-collected language.
In other words, if you don't know whether you should use `goto` for something, you shouldn't. | PHP and the goto statement to be added in PHP 5.3 | [
"",
"php",
"goto",
""
] |
So I am still asking questions about this topic :-(
So I create an object, decorate it with the Xml Serialization Attributes, from what I have seen I add an empty namespace to the xml serialization namepsace collections so as not to get the superfluous attributes I did not intend to have.
**Edit:** The attribute I mean are these:
```
<url xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"; xmlns:xsd="http://www.w3.org/2001/XMLSchema"; xmlns="">
```
so it gives me two extra attributes.
After further investigation if I change the beginning of the document from:\*\*
```
writer.WriteStartElement("urlset","http://www.sitemaps.org/schemas/sitemap/0.9");
```
to
```
writer.WriteStartElement("urlset");
```
\*\*Then I do not get the empty xmlns="" attribute in the url tags. This is great BUT I do require that the root element have `xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"`, i.e.:
```
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
```
But I still get an empty `xmlns=""` attribute in the serialized type.
```
[XmlRoot(ElementName = "url", Namespace="")]
public class SitemapNode
{
[XmlElement(ElementName = "loc")]
public string Location { get; set; }
[XmlElement(ElementName = "lastmod")]
public DateTime LastModified { get; set; }
[XmlElement(ElementName = "changefreq")]
public SitemapChangeFrequency ChangeFrequency { get; set; }
[XmlElement(ElementName = "priority")]
public decimal Priority { get; set; }
public SitemapNode()
{
Location = String.Empty;
LastModified = DateTime.Now;
ChangeFrequency = SitemapChangeFrequency.monthly;
Priority = 0.5M;
}
public SitemapNode(string location, DateTime lastModified, SitemapChangeFrequency changeFrequency, decimal priority)
{
Location = location;
LastModified = lastModified;
ChangeFrequency = changeFrequency;
Priority = priority;
}
}
```
Then I use the following to append to my XmlWriter:
```
foreach (uk.co.andrewrea.SitemapNode node in List)
{
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
ns.Add(String.Empty, String.Empty);
Serializer.Serialize(Writer, node, ns);
}
```
This works out fine except I am left with an emtpy xmlns="" like this
```
<url xmlns="">
```
Anyone any ideas? Again I can achieve this using the XmlTextWriter and the XmlDocument but I need to achieve it using the XmlWriter.
Any help is greatly appreciated. | This works (you just need them to be in the same namespace and you use the namespaces class so the writter doesn't confuse):
```
[TestMethod]
public void TestMethod3()
{
var list = new []{new SitemapNode("1", DateTime.Now, 1), new SitemapNode("2", DateTime.Now.AddDays(1), 2)};
var serializer = new XmlSerializer(typeof(SitemapNode));
var st = new MemoryStream();
using (var writer = XmlWriter.Create(st))
{
var ns = new XmlSerializerNamespaces();
ns.Add("", "test");
writer.WriteStartElement("test", "test");
foreach (SitemapNode node in list)
{
serializer.Serialize(writer, node, ns);
}
writer.WriteEndElement();
}
st.Position = 0;
TestContext.WriteLine(new StreamReader(st).ReadToEnd());
}
[XmlRoot(ElementName = "url", Namespace = "test")]
public class SitemapNode
{
[XmlElement(ElementName = "loc")]
public string Location { get; set; }
[XmlElement(ElementName = "lastmod")]
public DateTime LastModified { get; set; }
[XmlElement(ElementName = "priority")]
public decimal Priority { get; set; }
public SitemapNode()
{
Location = String.Empty;
LastModified = DateTime.Now;
Priority = 0.5M;
}
public SitemapNode(string location, DateTime lastModified, decimal priority)
{
Location = location;
LastModified = lastModified;
Priority = priority;
}
}
```
And the output is (based on your comments that is what you were looking for):
```
<?xml version="1.0" encoding="utf-8"?><test xmlns="test">
<url><loc>1</loc><lastmod>2009-03-05T13:35:54.6468-07:00</lastmod><priority>1</priority></url>
<url><loc>2</loc><lastmod>2009-03-06T13:35:54.6478-07:00</lastmod><priority>2</priority></url></test>
``` | I was having trouble inserting a node into an existing document with multiple namespaces.
No matter what I set the namespace to it would add the xmlns reference attribute every time no matter what. This was breaking something black boxed downstream.
I eventually got around this by doing something like this.
```
XmlNode newNode = newDoc.SelectSingleNode(xpathQuery, manager);
newNode.Attributes.RemoveAll();
node.ParentNode.InsertAfter(node.OwnerDocument.ImportNode(newNode, true), node);
``` | Remove empty xmlns="" after Xml Serialization | [
"",
"c#",
".net",
"xml",
"xml-serialization",
""
] |
So I tried searching SO hoping someone had a good explanation of this, with no luck.
I asked another friend of mine a different question (which I've now forgotten) and his answer was simply "reflection" before he signed off.
I am still very new to the C# world, having been an amateur VB.net programmer (also JavaScript, ActionScript, and C), and am trying as hard as I can to grasp these advanced concepts.
There's lots of philosophical answers -- "application looking at itself" -- but they don't provide any practical hints on what is actually going on or how it is used within that context.
So, what is reflection, why is it important, and why/how do I use it? | Reflection provides the ability to determine things and execute code at runtime.
You don't *have* to use it if you don't want to, but it is extremely handy for dynamic behavior.
For example:
a) You can use reflection to configure your application by loading an external configuration file and starting services based on it. Your application wont have to know in advance about the classes that implement those services, as long as they conform to a specific interface or API.
b) Using reflection you can generate classes and code on the fly, which simplifies certain programming tasks since the programmer does not have to explicitly create all the needed code.
c) Reflection is also invaluable for programs that work by examining code. An example of that would be an IDE or a UI designer.
d) Reflection helps you reduce boilerplate code.
e) Reflection is handy for defining mini Domain Specific Languages (DSL) in your code. | (my defintion)
Reflection is the ability to write static code that executes code at run-time, that is normally determined at compile time.
For instance, I could call a class method to draw by compiling in that command eg:
```
pen.DrawLine()
```
or With reflection, I can first see if my object has a method called "drawline" and if so, call it. (Note this isn't the actual C# Reflection syntax)
```
if(pen.Methods.Contains("DrawLine"))
{
pen.InvokeMethod("DrawLine"))
}
```
I'm no reflection master, but I used reflection for a plug-in architecture.
With reflection I can load a .NET assembly (a dll in this case) at run time, find out all the types that are in the .NET Assembly, see if any of those types implement a specific interface, and if so, instantiate the class, to which I invoke the interface methods.
I know that use-case is a bit technical, but essentially reflection allows me to load plug-ins dynamically (ie at run-time), and lets me make type-safe calls to it. | C#: Can someone explain the practicalities of reflection? | [
"",
"c#",
".net",
"reflection",
""
] |
How can a cross compilation setup be achieved to allow compiling Cell Linux programs on a Windows PC using the cygwin toolchain? The cygwin tools provide a GNU compiler to use in building the cross compiler, and associated tools for the build process e.g. rpm, cpio, make, flex, bison and so on.
I am moderately confident this is possible, but unaware of anyone who has actually done this. It has already been done for [x86 Linux](http://www.cellperformance.com/articles/2006/11/crosscompiling_for_ps3_linux.html), but I wish to use Windows, without requiring the use and overhead of a virtual machine running an entire 2nd operating system.
The Cell Linux toolchain is a patched GNU toolchain, with C and C++ compilers for the PPU and SPU processors, and associated binutils. The sources for the Cell Linux SDK for Cell Linux can be found [here](http://www.bsc.es/projects/deepcomputing/linuxoncell/cellsimulator/sdk3.1/sources/toolchain/). The source RPMS [here](http://www.bsc.es/projects/deepcomputing/linuxoncell/cellsimulator/sdk3.1/SRPMS/) have build scripts for use with the rpmbuild tool on Linux.
The specific question is: how can a set of Cell Linux GNU compilers for the PPU and SPU processors be built, on Windows, using Cygwin. | I've never done it, so I can't give you step by step instructions, but I can give you a general idea.
The instructions you linked will serve as a pretty good outline, but there will be definite changes.
For the host PC, you can install gcc and other build tools from [MinGW](http://www.mingw.org/) or [cygwin](http://www.cygwin.com). That will give you the windows native parts of your toolchain.
Then you'll need to download the sources for the cell portions of the toolchain and compile them (with the appropriate options, --target, etc.) using the build environment you just installed.
Then you download and compile the sources for libspe2, and you're done.
But I'll warn you - it sounds easier than it is. Be prepared to spend a lot of time on it. | Since you can already do this on Linux x86, why don't you just install Linux a virtual machine? Also, what might be even easier, is to install [Portable Ubuntu for Windows.](http://portableubuntu.demonccc.com.ar/) It runs Linux alongside Windows using [coLinux](http://www.colinux.org/). Although this may not be optimal, it is probably *much* easier than trying to compile everything on Windows. | How to Cross Compile for Cell Linux on the PS3 from Windows? | [
"",
"c++",
"linux",
"g++",
"cell",
"playstation3",
""
] |
I need to pass an IntPtr to IStream.Read, and the IntPtr should point to a ulong variable. How do I get this IntPtr that points to my ulong variable? | The best way is to change the IStream definition:
```
void Read([Out, MarshalAs(UnmanagedType.LPArray, SizeParamIndex = 1)] byte[] pv,
int cb, /*IntPtr*/ ref int pcbRead);
```
Then you can write
```
int pcbRead = 0;
Read(..., ref pcbRead);
``` | I believe you have to use the GCHandle method if you want to avoid unsafe code. I am not sure on how this works with boxed value types.
```
var handle = GCHandle.Alloc(myVar, GCHandleType.Pinned);
var ptr = handle.AddrOfPinnedObject()
``` | Getting an IntPtr to a ulong variable in C# | [
"",
"c#",
"interop",
"intptr",
"istream",
""
] |
This is what i want to do............
I am going to let each user upload multiple images into a folder called "pics".
If the user upload say "MyImage.jpg" i will rename it "MyImage\_UserID.jpg".
Where UserID will be the User's unique ID of course.
This way when i look for all the images of a user i will just look for the image name that ends with the UserID.
Is this wrong, or is there another way of doing this?
I am thinking about placing ALL the images from all the users in 1 folder.
It will be stupid to create a folder for each User dont you think?
Also, how save will that folder "pics" be? Like i dont want hackers to add or delete pictures out of that folder.
Any input? | Provided there will be some significant number of users with significant amount of images per user, your File System will start to suffocate (provided it won't crash being unable to handle large number of files).
What I recommend is to create a folder for each user. And no, this is not stupid. | storing too many files in a single directory can lead to problems. not only performance will suffer at a certain point, but a friend (with way more experience than me) told me that some backup programs have problems with this.
so when i had to store thousands of images i always created 256 subdirectories, and stored the files in the directory `files/{id mod 256}/{myfile_id}.jpg`
to protect yourself against hackers there are a lot of things to do, and nothing will be safe (because hackers will most likely try to get root access and then your data isn't safe anyway).
1) so ... regular backups. period.
2) audit log files (who what when). that's not security per se, but may help you in discovering security holes and fix bugs
3) set the file permissions accordingly (important on shared servers without chroot-ing)
4) double-check if an action really is done by the right user. it must be impossible to do harm by guessing the url.
there's more if you want to make the filenames and -paths secret. e.g. it's possible to not directly link to the image, but to a script that serves that image. in this case you're able to store the files outside the webroot (additionally, your more independent of filenames) (see code at the end).
one more step would be to avoid auto\_increment id values to identify images. better use an unique hash (`md5(mt_rand());`) without a correlation to the id and store that in the database (afaik youtube and flickr do that).
ugly php-pseudocode for passing through would be something like:
```
<?php
if (isset($_REQUEST['img'])) {
$hash = $_REQUEST['img']);
if (($res = getImageByHash($hash)) !== false) {
list($id, $name, $mimetype) = $res;
$path = '../images/' . ($id % 256) . '/' . $name;
if (file_exists($path)) {
header('Content-type: ' . $mimetype); // e.g. image/png
readfile($path);
exit();
}
}
}
// if any error happened, then 404 - it's dirty
header("HTTP/1.0 404 Not Found");
echo 'sorry, we couldn\'t find this image';
?>
```
getImageByHash() would query the db.
this solution is slower, because the webserver can't serve images directly anymore.
and: i'd rather not store the images in the database. exports would get huge, backups a pain. | How must i save my Images in my Project? | [
"",
"php",
"asp.net",
"image",
""
] |
I have a mocked object that is passed as a constructor argument to another object.
How can I test that a mocked object's property has been called? This is code I am using currently:
```
INewContactAttributes newContact = MockRepository.GenerateMock<INewContactAttributes>();
newContact.Stub(x => x.Forenames).Return("One Two Three");
someobject.ConsumeContact(newContact);
newContact.AssertWasCalled(x => { var dummy = x.Forenames; });
```
This works except when within the "someobject" the getter on Forenames property is used multiple times. That's when I get "Rhino.Mocks.Exceptions.ExpectationViolationException: INewContactAttributes.get\_Forenames(); Expected #1, Actual #2.."
Simply using
```
newContact.AssertWasCalled(x => { var dummy = x.Forenames; }, options => options.Repeat.Any());
```
does not work and gives the error below:
"The expectation was removed from the waiting expectations list, did you call Repeat.Any() ? This is not supported in AssertWasCalled()."
So how do I cater for the multiple calls? | `newContact.AssertWasCalled(x => { var dummy = x.Forenames; }, options => options.Repeat.AtLeastOnce());`
`Repeat.Any` does not work with `AssertWasCalled` because 0 counts as any... so if it WASN'T called, the `AsserWasCalled` would return TRUE even if it wasn't called. | I agree with chris answer
```
newContact.AssertWasCalled(x => { var dummy = x.Forenames; }, options => options.Repeat.AtLeastOnce());
```
Additionally If you know exactly how many times the property would be called you can do
```
newContact.AssertWasCalled(x => { var dummy = x.Forenames; }, options => options.Repeat.Times(n));
```
where n is an int. | Rhino Mocks AssertWasCalled (multiple times) on property getter using AAA | [
"",
"c#",
"unit-testing",
"properties",
"rhino-mocks",
"getter",
""
] |
I save my images into my SQL Server Database with ASP.NET(2.0).
(imageData -> image) (imageType -> varchar) (imageLength -> bigint)
Thus the imageData will be "Binary data" and the imageType will be like "image/gif" and the imageLength will be like "6458".......
Is it possible to get the image HEIGHT and WIDTH from my VB.NET code inside my ASP.NET?
I want to make my picture box on my web form the size of the actual image that is saved in my database.
Regards
Etienne | Assuming you have the data in a stream:
`System.Drawing.Image.FromStream(yourStream).Height`
You are probally better doing this when you save the image to the DB, as I'm sure that loading the image object isn't going to be cheap.
# Edit
If we take this to email then the next guy with this issue won't have a record of our solution. Let's keep it in the forum for now.
Just so we know, I am a C# developer so I'm not going to try and remember vb.net syntax if this is an issue and you need help converting let me know.
You have an IDataReader I'm assuming which is pulling an Image or binary varbinary etc field from your DB. You need to load it into an object which derives from System.IO.Stream. For our purposes a MemoryStream is the perfect choice as it doesn't require a backing store such as a disk.
```
System.IO.MemoryStream yourStream = new System.IO.MemoryStream(dr["imgLength"] as byte[]);
System.Drawing.Image yourImage=System.Drawing.Image.FromStream(yourStream);
yourImage.Height;
yourImage.width
``` | I would save the height and width of the image in separate columns when you save the image to the database intially. Then when you do your select statement to read the image out of the database, you can also access the height and width fields from the database.
Alternatively you can access the height and width information when you load the image out of the database and then set the height and width properties before assigning the image to the picture box. | Getting image height and width when image is saved in database | [
"",
"asp.net",
"sql",
"sql-server",
"vb.net",
""
] |
This is driving me crazy. I have the following string in a ASP.NET 2.0 WebForm Page
```
string s = "0.009";
```
Simple enough. Now, if my culture is Spanish - which is "es-ES" - and I try to convert the string to Double, I do the following:
```
double d = Double.Parse(s, new CultureInfo("es-ES"));
```
what I'd expect is 0,009. Instead, I get 9. I understand that .NET thinks it is a thousand separator, which in en-US is a comma, but shouldn't it take the culture info I'm passing to the parse method and apply the correct format to the conversion?
If I do
```
double d = 0.009D;
string formatted = d.ToString(new CultureInfo("es-ES"));
```
formatted is now 0,009. Anybody? | It **is** taking the culture you gave and applying the correct formatting. You provided a string of "0.009" and told it that it was Spanish...then you complain that it properly interpreted it as Spanish! Don't tell it that the string is Spanish when you know it isn't.
You should pass the Parse method the culture of the string being parsed, which in this case would be en-US or en-Gb or InvariantCulture. | what Jess's writing works for me. just for anyone who'd need to try out how to get "invariant culture": it looks this
`double d = Double.Parse(myString, CultureInfo.InvariantCulture);`
(first stackoverflow post, so yea, rather marginal ;) | Double.Parse - Internationalization problem | [
"",
"c#",
"string",
"double",
"culture",
"cultureinfo",
""
] |
Duplicate question to :
> [Should I always/ever/never initialize object fields to default values?](https://stackoverflow.com/questions/636102/should-i-always-ever-never-initialize-object-fields-to-default-values)
Environment: Visual Studio 2008 w/ Resharper 4.1 w/ 32bit .NET Framework 3.5
Resharper reports that
> Initializing field by default value is redundant

Is it a bad practice to declare a default **field** value, explicitly?
I find explicitly declaring default value to be more readable.
By the way this is not a duplication of this question
[Are default parameters bad practice in OOP?](https://stackoverflow.com/questions/624057/are-default-parameters-bad-practice-in-oop)
***[UPDATE]*** For those wondering on where to change Resharper 4.1 setting to change the warning to hint/suggestion; Changing following setting

will change Visual Studio 2008
 | It is redundant, but I would stay consistent. If you are always initializing fields, keep it that way regardless of the type. Also, as you pointed out in a comment, being required to think about default values for certain types is distracting, so another reason to initialize first. | If you find it more readable that way, that's fine. I don't *think* it'll affect the JITted code - and even if it does, the performance hit will be absolutely tiny.
If ReSharper is annoying you when it comes to this warning, just configure it not to treat it as a problem. I don't have ReSharper on this machine, but I think it's fairly easy to find the relevant options - let me know if you can't and I'll look for it when I'm on the right machine. | Is it a bad practice to explicitly declare a default field value? | [
"",
"c#",
"resharper",
""
] |
I was for quite some time under the impression that a `for` loop could exist *solely* in the following format:
```
for (INITIALIZER; STOP CONDITION; INC(DEC)REMENTER)
{
CODE
}
```
This is, however, most *definitely* not the case; take a look at this JavaScript implementation of the [Fisher-Yates Shuffle](http://en.wikipedia.org/wiki/Knuth_shuffle):
```
shuffle = function(o)
{
for (var j, x, i = o.length; i; j = parseInt(Math.random() * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
```
This little snippet completely blows my mind; how in the world is so much going on inside a simple for loop declaration? I mean... it doesn't even open a brace! All of the magic is being done *right there* inside the `for` statement. It'd be absolutely wonderful if somebody could provide a relatively thorough explanation as to how in the world this voodoo is doing what it does. Much appreciated in advance. | The generalized format of a for loop (not a for-in loop) is
```
for ( EXPRESSION_1 ; EXPRESSION_2 ; EXPRESSION_3 ) STATEMENT
```
The first EXPRESSION\_1 is *usually* used to initialize the loop variable, EXPRESSION\_2 is the looping condition, and EXPRESSION\_3 is *usually* an increment or decrement operation, but there are no rules that say they have to behave like that. It's equivalent to the following while loop:
```
EXPRESSION_1;
while (EXPRESSION_2) {
STATEMENT
EXPRESSION_3;
}
```
The commas are just an operator that combines two expressions into a single expression, whose value is the second sub-expression. They are used in the for loop because each part (separated by semicolons) needs to be a single expression, not multiple statements. There's really no reason (except maybe to save some space in the file) to write a for loop like that since this is equivalent:
```
shuffle = function(o) {
var j, x;
for (var i = o.length; i > 0; i--) {
j = parseInt(Math.random() * i);
x = o[i - 1];
o[i - 1] = o[j];
o[j] = x;
}
return o;
};
``` | ```
shuffle = function(o){
for (
var j, // declare j
x, // declare x
i = o.length; // declare i and set to o.length
i; // loop while i evaluates true
j = parseInt(Math.random() * i), // j=random number up to i
x = o[--i], // decrement i, and look up this index of o
o[i] = o[j], // copy the jth value into the ith position
o[j] = x // complete the swap by putting the old o[i] into jth position
);
return o;
};
```
This is starting with i equal to the number of positions, and each time swapping the cards i and j, where j is some random number up to i each time, as per the algorithm.
It could be more simply written without the confusing comma-set, true.
By the way, this is **not** the only kind of for loop in javascript. There is also:
```
for(var key in arr) {
value = arr[key]);
}
```
But be careful because this will also loop through the properties of an object, including if you pass in an Array object. | Regarding JavaScript for() loop voodoo | [
"",
"javascript",
""
] |
I have the following DIV markup:
```
<div id="dialog" title="Membership Renewal">
Your membership is going to expire.
</div>
```
I have the following javascript to execute the JQuery:
```
<script type="text/javascript">
function showjQueryDialog() {
$("#dialog").dialog("open");
//alert("Time to renew Membership!");
}
$(document).ready(function() {
$("#dialog").dialog({
autoOpen: false,
modal: true,
buttons: { "Renew Membership": function() { $(this).dialog("close"); } }
});
});
</script>
```
I have an asp:Button which is inside a control and the control is on a master page. The first thing I notice is that when the page is loaded, the div is displayed and then disappears when the page is done loading. When I click the button it executes the following:
```
if (timeSpan.Days >= 30)
{
//Show JQuery Dialog Here
ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "showExpiration",
"showjQueryDialog()", true);
}
```
When I click the button, instead of a dialog popping up, the content of the div just becomes visible. | I believe you have two related issues here.
The reason that the DIV is showing when you first load is because you haven't yet told it not to. The jQuery script that makes the DIV behave as a dialog doesn't run until the HTML DOM is loaded, and until then it will not hide the DIV. A simple solution is to hide the DIV by default using CSS.
```
<div id="dialog" title="Membership Renewal" style="display:none;">
Your membership is going to expire.
</div>
```
The button click problem is related: `RegisterClientScriptBlock` will output a script that runs as soon as it is encountered, so the jQuery code that turns it into a dialog hasn't had a chance to run yet. In order to give it a chance to do so, you can change the C# code to use `RegisterStartupScript`, which will delay execution of `showjQueryDialog()` until the page has finished loading and the jQuery code has had a chance to make the DIV into a dialog.
```
if (timeSpan.Days >= 30)
{
//Show JQuery Dialog Here
ScriptManager.RegisterStartupScript(this, typeof(Page),
"showExpiration", "showjQueryDialog()", true);
}
``` | I know this is old now. However, Set your class to the jQuery UI built in ui-helper-hidden.
```
<div id="dialog" title="Membership Renewal" class="ui-helper-hidden">
Your membership is going to expire.
</div>
```
This will resolve your div's unwanted cameo behaviour. | DIV content shows on page instead of JQuery Dialog | [
"",
"c#",
"asp.net",
"jquery",
"jquery-ui",
""
] |
I am looking to obfuscate our Java web app code within our existing Ant build script, but am running into problems around unit testing. I am obfuscating the code right after it has been compiled, before it is jar-ed and before the unit tests are ran.
However, if I obfuscate my production code and not my test code, all my tests fail because they are trying to call methods that no longer exist because they have been renamed by the obfuscator. I can mark certain methods to not obfuscate so they can be used by external systems such as our test suite, but since we are shooting for high unit test coverage we will need to mark **all** of our methods as un-obfuscatable.
If I obfuscate the test classes as well, I run into two problems:
1: The production classes and the test classes get merged into the same output directory and I am unable to exclude the test classes from the production .jar files
2: I cannot run my normal Ant batchtest call:
```
<batchtest todir="${basedir}/reports">
<fileset dir="${basedir}/components/common/build-zkm">
<include name="**/*Test.class"/>
</fileset>
</batchtest>
```
because the obfuscator has changed the names of the tests.
I could just run the obfuscator on the resulting .war/.ear files, but I want to have our unit tests run against the modified code to drive out any bugs caused by the obfuscator.
I am currently working with Zelix KlassMaster, but I am still in the evaluation phase so I would be open to other options if they would work better. | Can you tell it to run the obfuscator such that it effectively refactors the code *including* the references from the tests (i.e. when a production name changes, the test code changes its reference) but not to obfuscate the tests themselves (i.e. don't change the names of the test classes or their methods)? Given previous experience with obfuscators I'd expect that to work.
So for example, suppose we had unobfuscated source of:
```
public class ProductionCode
{
public void productionMethod() {}
}
public class ProductionCodeTest
{
public void testProductionMethod()
{
new ProductionCode().productionMethod();
}
}
```
You want to set the options of the obfuscator to make it *effectively*:
```
public class Xyzzy
{
public void ababa() {}
}
public class ProductionCodeTest
{
public void testProductionMethod()
{
new Xyzzy(). ababa();
}
}
```
That way your "run the tests" Ant tasks should be able to stay the same, because the API of the tests hasn't changed - merely the implementation of the methods. | I use [yguard](http://www.yworks.com/en/products_yguard_about.htm) (it is free, which is why I mention it).
You should be able to tell the obfuscator not to obfuscate certain things (looking [here](http://www.zelix.com/klassmaster/featuresZKMScript.html) it seems you can).
Some as others have said, don't obfuscate the tests, but do obfuscate the rest.
However, I would suggest that you do the following:
1. compile
2. jar the un-obfuscated files (if desired)
3. test the un-obfuscated files
4. if they pass the tests then obfuscate jar the obfuscated files
5. test the obfuscated files
It will be slower, but if the tests fail in step 3 it'll be easier to fix (potentially) and if the tests fail at 5 then you know there is an issue with the obfuscation not your source code. | Can you Unit Test Obfuscated Code? | [
"",
"java",
"ant",
"obfuscation",
""
] |
Quick regex question (since i am horrible at it)
I have a field that can only have either:
`XXXXXXXXXX` or `XXXXXX-XXXX` where X is a real number.
Bonus if the regex works well with PHP's regex functions.
**The Answer:**
Here's the code from **RoBorg's** answer, for those interested.
```
if(!preg_match("/^\d{6}-?\d{4}$/", $var))
{
// The entry didn't match
}
``` | ```
/^\d{6}-?\d{4}$/
```
That's
```
^ Start of string
\d{6} a digit, repeated exactly 6 times
-? an optional "-"
\d{4} a digit, repeated exactly 4 times
$ end of string
``` | Just quickly, it'd be something like this:
`\d{6}-?\d{4}`
You may have to escape the hyphen in PHP. | Matching fixed-format numbers in regex | [
"",
"php",
"regex",
""
] |
I'm having trouble with the following code. I'm trying to write to a .ppm file, and I get
> Red.java:6: unreported exception java.io.FileNotFoundException; must be caught or declared to be thrown
> FileOutputStream fout = new FileOutputStream(fileName);
> ^
> Any ideas?
import java.io.\*;
public class Red {
```
public static void main(String args[]) {
String fileName = "RedDot.ppm";
FileOutputStream fout = new FileOutputStream(fileName);
DataOutputStream out = new DataOutputStream(fout);
System.out.print("P6 1 1 255 ");
System.out.write(255);
System.out.write(0);
System.out.write(0);
System.out.flush();
}
```
} | The simplest solution is to rewrite your main declaration thus:
```
public static void main(String args[]) throws FileNotFoundException {...
```
thus indicating that it *may* throw this exception if it can't create the outputstream (for whatever reason). Note that FileNotFoundException is not the best name for the exception in this circumstance, but that's a naming issue you can't deal with.
In fact you will *probably* want to declare `IOException` in the `main()` throws clause above. The different methods you're calling will be declared as throwing variants of this. | Th FileNotFoundException is a checked exception. You need to enclose the code that trys to write to the file in a try/catch block, or throw the exception. | FileOutputStream file not found error | [
"",
"java",
"file-io",
""
] |
I've been searching but I can't find how to cast from the type
```
Expression<Func<T, DateTime>>
```
to the type:
```
Expression<Func<T, object>>
```
So I must turn again to the SO vast knowledge ;) | You can't just cast between them, as they're not the same kind of thing. However, you can effectively add a conversion within the expression tree:
```
using System;
using System.Linq.Expressions;
class Test
{
// This is the method you want, I think
static Expression<Func<TInput,object>> AddBox<TInput, TOutput>
(Expression<Func<TInput, TOutput>> expression)
{
// Add the boxing operation, but get a weakly typed expression
Expression converted = Expression.Convert
(expression.Body, typeof(object));
// Use Expression.Lambda to get back to strong typing
return Expression.Lambda<Func<TInput,object>>
(converted, expression.Parameters);
}
// Just a simple demo
static void Main()
{
Expression<Func<string, DateTime>> x = text => DateTime.Now;
var y = AddBox(x);
object dt = y.Compile()("hi");
Console.WriteLine(dt);
}
}
``` | The answers from *Rob* and *Jon Skeet* have one problem.
You get something like `x => Convert(x.PropertyName)`, but often for instance for *ASP.NET MVC* you want an expression like this `x => x.PropertyName`
So `Expression.Convert` is *"polluting"* the expression for some cases.
**Solution:**
```
public static class LambdaExpressionExtensions
{
public static Expression<Func<TInput, object>> ToUntypedPropertyExpression<TInput, TOutput> (this Expression<Func<TInput, TOutput>> expression)
{
var memberName = ((MemberExpression)expression.Body).Member.Name;
var param = Expression.Parameter(typeof(TInput));
var field = Expression.Property(param, memberName);
return Expression.Lambda<Func<TInput, object>>(field, param);
}
}
```
**Usage:**
```
Expression<Func<T, DateTime>> expression = ...;
Expression<Func<T, object>> expr = expression.ToUntypedPropertyExpression();
``` | How to cast Expression<Func<T, DateTime>> to Expression<Func<T, object>> | [
"",
"c#",
"lambda",
""
] |
How can I clone an `ArrayList` and also clone its items in Java?
For example I have:
```
ArrayList<Dog> dogs = getDogs();
ArrayList<Dog> clonedList = ....something to do with dogs....
```
And I would expect that objects in `clonedList` are not the same as in dogs list. | You will need to iterate on the items, and clone them one by one, putting the clones in your result array as you go.
```
public static List<Dog> cloneList(List<Dog> list) {
List<Dog> clone = new ArrayList<Dog>(list.size());
for (Dog item : list) clone.add(item.clone());
return clone;
}
```
For that to work, obviously, you will have to get your `Dog` class to implement the `Cloneable` interface and override the `clone()` method. | I, personally, would add a constructor to Dog:
```
class Dog
{
public Dog()
{ ... } // Regular constructor
public Dog(Dog dog) {
// Copy all the fields of Dog.
}
}
```
Then just iterate (as shown in Varkhan's answer):
```
public static List<Dog> cloneList(List<Dog> dogList) {
List<Dog> clonedList = new ArrayList<Dog>(dogList.size());
for (Dog dog : dogList) {
clonedList.add(new Dog(dog));
}
return clonedList;
}
```
I find the advantage of this is you don't need to screw around with the broken Cloneable stuff in Java. It also matches the way that you copy Java collections.
Another option could be to write your own ICloneable interface and use that. That way you could write a generic method for cloning. | How to clone ArrayList and also clone its contents? | [
"",
"java",
"collections",
"clone",
"deep-copy",
""
] |
```
#include <iostream>
using namespace std;
class Foo
{
public:
Foo(): initialised(0)
{
cout << "Foo() gets called AFTER test() ?!" << endl;
};
Foo test()
{
cout << "initialised= " << initialised << " ?! - ";
cout << "but I expect it to be 0 from the 'initialised(0)' initialiser on Foo()" << endl;
cout << "this method test() is clearly working on an uninitialised object ?!" << endl;
return Foo();
}
~Foo()
{};
private:
int initialised;
};
int main()
{
//SURE this is bad coding but it compiles and runs
//I want my class to DETECT and THROW an error to prevent this type of coding
//in other words how to catch it at run time and throw "not initialised" or something
Foo foo=foo.test();
}
``` | **You can't prevent people from coding poorly**, really. It works just like it "should":
1. Allocate memory for Foo (which is the value of the "this" pointer)
2. Going to Foo::test by doing: Foo::test(this), in which,
3. It gets the value by this->initialised, which is random junk, then it
4. Calls Foo's default constructor (because of return Foo();), then
5. Call Foo's copy constructor, to copy the right-handed Foo().
Just like it should. You can't prevent people from not knowing the right way to use C++.
The best you could do is have a magic number:
```
class A
{
public:
A(void) :
_magicFlag(1337)
{
}
void some_method(void)
{
assert (_magicFlag == 1337); /* make sure the constructor has been called */
}
private:
unsigned _magicFlag;
}
```
This "works" because the chances \_magicFlag gets allocated where the value is already 1337 is low.
But really, don't do this. | Yes, it is calling the function on a yet not constructed object, which is undefined behavior. You can't detect it reliable. I would argue you also should not try to detect it. It's nothing which would happen likely by accident, compared to for example calling a function on an already deleted object. Trying to catch every and all possible mistakes is just about impossible. The name declared is visible already in its initializer, for other useful purposes. Consider this:
```
Type *t = (Type*)malloc(sizeof(*t));
```
Which is a common idiom in C programming, and which still works in C++.
Personally, i like [this story](http://www.gotw.ca/conv/002.htm) by Herb Sutter about null references (which are likewise invalid). The gist is, don't try to protect from cases that the language clearly forbids and in particular are in their general case impossible to diagnose reliably. You will get a false security over time, which becomes quite dangerous. Instead, train your understanding of the language and design interfaces in a way (avoid raw pointers, ...) that reduces the chance of doing mistakes.
In C++ and likewise in C, many cases are not explicitly forbidden, but rather are left undefined. Partially because some things are rather difficult to diagnose *efficiently* and partially because undefined behavior lets the implementation design alternative behavior for it instead of completely ignoring it - which is used often by existing compilers.
In the above case for example, any implementation is free to throw an exception. There are other situations that are likewise undefined behavior which are much harder to diagnose efficiently for the implementation: Having an object in a different translation unit accessed before it was constructed is such an example - which is known as the *static initialization order fiasco*. | method running on an object BEFORE the object has been initialised? | [
"",
"c++",
"initialization",
""
] |
I've scanned over the (outdated) article that is the first hit on google about [ARM cross-compiling](http://www.ailis.de/~k/archives/19-ARM-cross-compiling-howto.html). I've also seen the article about compiling [OpenCV to the iPhone](http://lambdajive.wordpress.com/2008/12/20/cross-compiling-for-iphone/) and the general cross compiling instructions there. My question is can I call the apparently already configured gcc/g++ in the iPhone developer package (which I already have installed) like in the latter article? A lot of the OpenCV stuff seems superfluous to my needs.
If I can, what would the calls look like? Should I create a Makefile to make things easier?
Also, I need -lncurses library. Can I call them like normal, or do I need to specify it's path because I'm not calling the default gcc/g++? | If you're using the official SDK, compiling C++ for the iPhone is as simple as including cpp files in your project and hitting "build". Of course you can still go in and tweak the compiler switches - well, most of them.
As for ncurses, I'm not sure why you'd want to use that - but the only limitation you should have is that you can't link against dynamic libraries - so you'd have to linked the object code in. | [A script that you can use as a basis for crosscompiling your libraries for iOs development.](http://robertcarlsen.net/2009/07/15/cross-compiling-for-iphone-dev-884) | cross compiling c++ to iphone arm | [
"",
"c++",
"iphone",
"g++",
"arm",
"cross-compiling",
""
] |
I have a function A(), that returns a pointer to an object. In function B() I try to change a member of that object in the following way:
```
void B()
{
ObjType o = *getObj();
o.set("abc");
}
```
Object o is stored in an array, and when I print the value of the member, it seems nothing happened, and the member still has the old value;
The solution is quite simple:
```
void B()
{
ObjType * o = getObj();
o->set("abc");
}
```
This does work. But to me, this is quite the same as the first sample. Can anyone explain this? | The following line is most likely copying the object:
```
ObjType o = *getObj();
```
That's why nothing happens. If you don't want to use a pointer as shown in your second snippet, you can use a reference like this:
```
ObjType& o = *getObj();
o.set("abc");
``` | The first one creates a copy of the object. The second one creates a pointer to it. In the first case, you are modifying the copy. | Problem with dereference operator and functions | [
"",
"c++",
"pointers",
""
] |
I’m looking to split '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15...' (comma delimited) into a table or table variable.
Does anyone have a function that returns each one in a row? | Here is somewhat old-fashioned solution:
```
/*
Splits string into parts delimitered with specified character.
*/
CREATE FUNCTION [dbo].[SDF_SplitString]
(
@sString nvarchar(2048),
@cDelimiter nchar(1)
)
RETURNS @tParts TABLE ( part nvarchar(2048) )
AS
BEGIN
if @sString is null return
declare @iStart int,
@iPos int
if substring( @sString, 1, 1 ) = @cDelimiter
begin
set @iStart = 2
insert into @tParts
values( null )
end
else
set @iStart = 1
while 1=1
begin
set @iPos = charindex( @cDelimiter, @sString, @iStart )
if @iPos = 0
set @iPos = len( @sString )+1
if @iPos - @iStart > 0
insert into @tParts
values ( substring( @sString, @iStart, @iPos-@iStart ))
else
insert into @tParts
values( null )
set @iStart = @iPos+1
if @iStart > len( @sString )
break
end
RETURN
END
```
In SQL Server 2008 you can achieve the same with .NET code. Maybe it would work faster, but definitely this approach is easier to manage. | Try this
```
DECLARE @xml xml, @str varchar(100), @delimiter varchar(10)
SET @str = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15'
SET @delimiter = ','
SET @xml = cast(('<X>'+replace(@str, @delimiter, '</X><X>')+'</X>') as xml)
SELECT C.value('.', 'varchar(10)') as value FROM @xml.nodes('X') as X(C)
```
OR
```
DECLARE @str varchar(100), @delimiter varchar(10)
SET @str = '1,2,3,4,5,6,7,8,9,10,11,12,13,14,15'
SET @delimiter = ','
;WITH cte AS
(
SELECT 0 a, 1 b
UNION ALL
SELECT b, CHARINDEX(@delimiter, @str, b) + LEN(@delimiter)
FROM CTE
WHERE b > a
)
SELECT SUBSTRING(@str, a,
CASE WHEN b > LEN(@delimiter)
THEN b - a - LEN(@delimiter)
ELSE LEN(@str) - a + 1 END) value
FROM cte WHERE a > 0
```
Many more ways of doing the same is here [How to split comma delimited string?](http://social.msdn.microsoft.com/Forums/en-IE/transactsql/thread/4126a010-6885-4eb0-b79c-c798c90edb85) | Split function equivalent in T-SQL? | [
"",
"sql",
"sql-server",
"t-sql",
"sql-server-2008",
""
] |
Related to Stack Overflow question *[Scala equivalent of new HashSet(Collection)](https://stackoverflow.com/questions/674545)* , how do I convert a Java collection (`java.util.List` say) into a Scala collection `List`?
I am actually trying to convert a Java API call to [Spring's](http://en.wikipedia.org/wiki/Spring_Framework) `SimpleJdbcTemplate`, which returns a `java.util.List<T>`, into a Scala immutable `HashSet`. So for example:
```
val l: java.util.List[String] = javaApi.query( ... )
val s: HashSet[String] = //make a set from l
```
---
This seems to work. Criticism is welcome!
```
import scala.collection.immutable.Set
import scala.collection.jcl.Buffer
val s: scala.collection.Set[String] =
Set(Buffer(javaApi.query( ... ) ) : _ *)
``` | Your last suggestion works, but you can also avoid using `jcl.Buffer`:
```
Set(javaApi.query(...).toArray: _*)
```
Note that `scala.collection.immutable.Set` is made available by default thanks to `Predef.scala`. | For future reference: With Scala 2.8, it could be done like this:
```
import scala.collection.JavaConversions._
val list = new java.util.ArrayList[String]()
list.add("test")
val set = list.toSet
```
`set` is a `scala.collection.immutable.Set[String]` after this.
Also see [Ben James' answer](https://stackoverflow.com/questions/674713/converting-java-collection-into-scala-collection/6356804#6356804) for a more explicit way (using JavaConverters), which seems to be recommended now. | Converting a Java collection into a Scala collection | [
"",
"java",
"scala",
"scala-collections",
"scala-2.7",
""
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.