question_id
int64
4
6.31M
answer_id
int64
7
6.31M
title
stringlengths
9
150
question_body
stringlengths
0
28.8k
answer_body
stringlengths
60
27.2k
question_text
stringlengths
40
28.9k
combined_text
stringlengths
124
39.6k
tags
listlengths
1
6
question_score
int64
0
26.3k
answer_score
int64
0
28.8k
view_count
int64
15
14M
answer_count
int64
0
182
favorite_count
int64
0
32
question_creation_date
stringdate
2008-07-31 21:42:52
2011-06-10 18:12:18
answer_creation_date
stringdate
2008-07-31 22:17:57
2011-06-10 18:14:17
24,470
40,434
SQL Server: Examples of PIVOTing String data
Trying to find some simple SQL Server PIVOT examples. Most of the examples that I have found involve counting or summing up numbers. I just want to pivot some string data. For example, I have a query returning the following. Action1 VIEW Action1 EDIT Action2 VIEW Action3 VIEW Action3 EDIT I would like to use PIVOT (if even possible) to make the results like so: Action1 VIEW EDIT Action2 VIEW NULL Action3 VIEW EDIT Is this even possible with the PIVOT functionality?
Remember that the MAX aggregate function will work on text as well as numbers. This query will only require the table to be scanned once. SELECT Action, MAX( CASE data WHEN 'View' THEN data ELSE '' END ) ViewCol, MAX( CASE data WHEN 'Edit' THEN data ELSE '' END ) EditCol FROM t GROUP BY Action
SQL Server: Examples of PIVOTing String data Trying to find some simple SQL Server PIVOT examples. Most of the examples that I have found involve counting or summing up numbers. I just want to pivot some string data. For example, I have a query returning the following. Action1 VIEW Action1 EDIT Action2 VIEW Action3 VIEW Action3 EDIT I would like to use PIVOT (if even possible) to make the results like so: Action1 VIEW EDIT Action2 VIEW NULL Action3 VIEW EDIT Is this even possible with the PIVOT functionality?
TITLE: SQL Server: Examples of PIVOTing String data QUESTION: Trying to find some simple SQL Server PIVOT examples. Most of the examples that I have found involve counting or summing up numbers. I just want to pivot some string data. For example, I have a query returning the following. Action1 VIEW Action1 EDIT Action2 VIEW Action3 VIEW Action3 EDIT I would like to use PIVOT (if even possible) to make the results like so: Action1 VIEW EDIT Action2 VIEW NULL Action3 VIEW EDIT Is this even possible with the PIVOT functionality? ANSWER: Remember that the MAX aggregate function will work on text as well as numbers. This query will only require the table to be scanned once. SELECT Action, MAX( CASE data WHEN 'View' THEN data ELSE '' END ) ViewCol, MAX( CASE data WHEN 'Edit' THEN data ELSE '' END ) EditCol FROM t GROUP BY Action
[ "sql-server", "t-sql", "pivot" ]
131
166
196,531
7
0
2008-08-23T18:36:33.953000
2008-09-02T19:55:19.270000
24,481
24,501
What is the "best" way to store international addresses in a database?
What is the " best " way to store international addresses in a database? Answer in the form of a schema and an explanation of the reasons why you chose to normalize (or not) the way you did. Also explain why you chose the type and length of each field. Note: You decide what fields you think are necessary.
Plain freeform text. Validating all the world's post/zip codes is too hard; a fixed list of countries is too politically sensitive; mandatory state/region/other administrative subdivision is just plain inappropriate (all too often I'm asked which county I live in--when I don't, because Greater London is not a county at all). More to the point, it's simply unnecessary. Your application is highly unlikely to be modelling addresses in any serious way. If you want a postal address, ask for the postal address. Most people aren't so stupid as to put in something other than a postal address, and if they do, they can kiss their newly purchased item bye-bye. The exception to this is if you're doing something that's naturally constrained to one country anyway. In this situation, you should ask for, say, the { postcode, house number } pair, which is enough to identify a postal address. I imagine you could achieve similar things with the extended zip code in the US.
What is the "best" way to store international addresses in a database? What is the " best " way to store international addresses in a database? Answer in the form of a schema and an explanation of the reasons why you chose to normalize (or not) the way you did. Also explain why you chose the type and length of each field. Note: You decide what fields you think are necessary.
TITLE: What is the "best" way to store international addresses in a database? QUESTION: What is the " best " way to store international addresses in a database? Answer in the form of a schema and an explanation of the reasons why you chose to normalize (or not) the way you did. Also explain why you chose the type and length of each field. Note: You decide what fields you think are necessary. ANSWER: Plain freeform text. Validating all the world's post/zip codes is too hard; a fixed list of countries is too politically sensitive; mandatory state/region/other administrative subdivision is just plain inappropriate (all too often I'm asked which county I live in--when I don't, because Greater London is not a county at all). More to the point, it's simply unnecessary. Your application is highly unlikely to be modelling addresses in any serious way. If you want a postal address, ask for the postal address. Most people aren't so stupid as to put in something other than a postal address, and if they do, they can kiss their newly purchased item bye-bye. The exception to this is if you're doing something that's naturally constrained to one country anyway. In this situation, you should ask for, say, the { postcode, house number } pair, which is enough to identify a postal address. I imagine you could achieve similar things with the extended zip code in the US.
[ "database", "internationalization", "globalization", "street-address" ]
39
25
14,201
6
0
2008-08-23T18:45:47.863000
2008-08-23T19:04:38.800000
24,496
24,498
What Alternatives Are There to Model-View-Controller?
While going through university and from following the development of SO, I've heard a lot about the Model-View-Controller architectural design pattern. I inadvertently used the MVC pattern even before I knew what it was, and still use it in my everyday job. From what I've seen, it's probably the most popular pattern used today. What I haven't heard much about though, are the alternative patterns you can use instead of MVC. What options are there, and for what reasons would you decide to use them over MVC? I'm also interested in knowing the types of systems they are typical of being used for. Finally, what are the pros and cons that come along with using them?
Passive View - http://martinfowler.com/eaaDev/PassiveScreen.html Supervising Controller - http://martinfowler.com/eaaDev/SupervisingPresenter.html Model-View-Presenter - http://martinfowler.com/eaaDev/ModelViewPresenter.html My personal favorite is the Passive View. More testable than others I've seen including MVC.
What Alternatives Are There to Model-View-Controller? While going through university and from following the development of SO, I've heard a lot about the Model-View-Controller architectural design pattern. I inadvertently used the MVC pattern even before I knew what it was, and still use it in my everyday job. From what I've seen, it's probably the most popular pattern used today. What I haven't heard much about though, are the alternative patterns you can use instead of MVC. What options are there, and for what reasons would you decide to use them over MVC? I'm also interested in knowing the types of systems they are typical of being used for. Finally, what are the pros and cons that come along with using them?
TITLE: What Alternatives Are There to Model-View-Controller? QUESTION: While going through university and from following the development of SO, I've heard a lot about the Model-View-Controller architectural design pattern. I inadvertently used the MVC pattern even before I knew what it was, and still use it in my everyday job. From what I've seen, it's probably the most popular pattern used today. What I haven't heard much about though, are the alternative patterns you can use instead of MVC. What options are there, and for what reasons would you decide to use them over MVC? I'm also interested in knowing the types of systems they are typical of being used for. Finally, what are the pros and cons that come along with using them? ANSWER: Passive View - http://martinfowler.com/eaaDev/PassiveScreen.html Supervising Controller - http://martinfowler.com/eaaDev/SupervisingPresenter.html Model-View-Presenter - http://martinfowler.com/eaaDev/ModelViewPresenter.html My personal favorite is the Passive View. More testable than others I've seen including MVC.
[ "model-view-controller", "mvp", "passive-view", "architectural-patterns" ]
34
27
8,029
10
0
2008-08-23T19:01:06.890000
2008-08-23T19:03:06.900000
24,506
24,523
What is the purpose of the AppManifest.xaml file in Silverlight applications?
In opening up the.xap file that is generated as output from a Silverlight application I've been tinkering with lately, I noticed a file called AppManifest.xaml. I've also noticed an option in the property pages for the Silverlight project that appears to allow you to optionally not output AppManifest.xaml for the project. When unchecking that option, however, I get errors when running the application: Invalid or malformed application: Check manifest. What is the purpose of the AppManifest.xaml file?
Maybe this blog post will help: http://blogs.msdn.com/katriend/archive/2008/03/16/silverlight-2-structure-of-the-new-xap-file-silverlight-packaged-application.aspx. It discusses the.xap file and its parts including the AppManifest. To save people a link click, in short, it defines the application for deployment, its entry point, and references all the assemblies needed to run.
What is the purpose of the AppManifest.xaml file in Silverlight applications? In opening up the.xap file that is generated as output from a Silverlight application I've been tinkering with lately, I noticed a file called AppManifest.xaml. I've also noticed an option in the property pages for the Silverlight project that appears to allow you to optionally not output AppManifest.xaml for the project. When unchecking that option, however, I get errors when running the application: Invalid or malformed application: Check manifest. What is the purpose of the AppManifest.xaml file?
TITLE: What is the purpose of the AppManifest.xaml file in Silverlight applications? QUESTION: In opening up the.xap file that is generated as output from a Silverlight application I've been tinkering with lately, I noticed a file called AppManifest.xaml. I've also noticed an option in the property pages for the Silverlight project that appears to allow you to optionally not output AppManifest.xaml for the project. When unchecking that option, however, I get errors when running the application: Invalid or malformed application: Check manifest. What is the purpose of the AppManifest.xaml file? ANSWER: Maybe this blog post will help: http://blogs.msdn.com/katriend/archive/2008/03/16/silverlight-2-structure-of-the-new-xap-file-silverlight-packaged-application.aspx. It discusses the.xap file and its parts including the AppManifest. To save people a link click, in short, it defines the application for deployment, its entry point, and references all the assemblies needed to run.
[ "silverlight" ]
6
6
5,934
1
0
2008-08-23T19:06:17.063000
2008-08-23T19:25:14.990000
24,515
24,615
"bad words" filter
Not very technical, but... I have to implement a bad words filter in a new site we are developing. So I need a "good" bad words list to feed my db with... any hint / direction? Looking around with google I found this one, and it's a start, but nothing more. Yes, I know that this kind of filters are easily escaped... but the client will is the client will!!!:-) The site will have to filter out both english and italian words, but for italian I can ask my colleagues to help me with a community-built list of "parolacce":-) - an email will do. Thanks for any help.
I didn't see any language specified but you can use this for PHP it will generate a RegEx for each instered work so that even intentional mis-spellings (i.e. @ss, i3itch ) will also be caught. "; $i++; } echo ' '; }?> RegEx Generator Word: List Words
"bad words" filter Not very technical, but... I have to implement a bad words filter in a new site we are developing. So I need a "good" bad words list to feed my db with... any hint / direction? Looking around with google I found this one, and it's a start, but nothing more. Yes, I know that this kind of filters are easily escaped... but the client will is the client will!!!:-) The site will have to filter out both english and italian words, but for italian I can ask my colleagues to help me with a community-built list of "parolacce":-) - an email will do. Thanks for any help.
TITLE: "bad words" filter QUESTION: Not very technical, but... I have to implement a bad words filter in a new site we are developing. So I need a "good" bad words list to feed my db with... any hint / direction? Looking around with google I found this one, and it's a start, but nothing more. Yes, I know that this kind of filters are easily escaped... but the client will is the client will!!!:-) The site will have to filter out both english and italian words, but for italian I can ask my colleagues to help me with a community-built list of "parolacce":-) - an email will do. Thanks for any help. ANSWER: I didn't see any language specified but you can use this for PHP it will generate a RegEx for each instered work so that even intentional mis-spellings (i.e. @ss, i3itch ) will also be caught. "; $i++; } echo ' '; }?> RegEx Generator Word: List Words
[ "list", "dictionary", "profanity" ]
54
39
104,638
9
0
2008-08-23T19:17:34.353000
2008-08-23T21:27:01.017000
24,516
24,589
Resolving reduce/reduce conflict in yacc/ocamlyacc
I'm trying to parse a grammar in ocamlyacc (pretty much the same as regular yacc) which supports function application with no operators (like in Ocaml or Haskell), and the normal assortment of binary and unary operators. I'm getting a reduce/reduce conflict with the '-' operator, which can be used both for subtraction and negation. Here is a sample of the grammar I'm using: %token INT %token ID %token MINUS %start expr %type expr %nonassoc INT ID %left MINUS %left APPLY %% expr: INT { ExprInt $1 } | ID { ExprId $1 } | expr MINUS expr { ExprSub($1, $3) } | MINUS expr { ExprNeg $2 } | expr expr %prec APPLY { ExprApply($1, $2) }; The problem is that when you get an expression like "a - b" the parser doesn't know whether this should be reduced as "a (-b)" (negation of b, followed by application) or "a - b" (subtraction). The subtraction reduction is correct. How do I resolve the conflict in favor of that rule?
Unfortunately, the only answer I can come up with means increasing the complexity of the grammar. split expr into simple_expr and expr_with_prefix allow only simple_expr or (expr_with_prefix) in an APPLY The first step turns your reduce/reduce conflict into a shift/reduce conflict, but the parentheses resolve that. You're going to have the same problem with 'a b c': is it a(b(c)) or (a(b))(c)? You'll need to also break off applied_expression and required (applied_expression) in the grammar. I think this will do it, but I'm not sure: expr:= INT | parenthesized_expr | expr MINUS expr parenthesized_expr:= ( expr ) | ( applied_expr ) | ( expr_with_prefix ) applied_expr:= expr expr expr_with_prefix:= MINUS expr
Resolving reduce/reduce conflict in yacc/ocamlyacc I'm trying to parse a grammar in ocamlyacc (pretty much the same as regular yacc) which supports function application with no operators (like in Ocaml or Haskell), and the normal assortment of binary and unary operators. I'm getting a reduce/reduce conflict with the '-' operator, which can be used both for subtraction and negation. Here is a sample of the grammar I'm using: %token INT %token ID %token MINUS %start expr %type expr %nonassoc INT ID %left MINUS %left APPLY %% expr: INT { ExprInt $1 } | ID { ExprId $1 } | expr MINUS expr { ExprSub($1, $3) } | MINUS expr { ExprNeg $2 } | expr expr %prec APPLY { ExprApply($1, $2) }; The problem is that when you get an expression like "a - b" the parser doesn't know whether this should be reduced as "a (-b)" (negation of b, followed by application) or "a - b" (subtraction). The subtraction reduction is correct. How do I resolve the conflict in favor of that rule?
TITLE: Resolving reduce/reduce conflict in yacc/ocamlyacc QUESTION: I'm trying to parse a grammar in ocamlyacc (pretty much the same as regular yacc) which supports function application with no operators (like in Ocaml or Haskell), and the normal assortment of binary and unary operators. I'm getting a reduce/reduce conflict with the '-' operator, which can be used both for subtraction and negation. Here is a sample of the grammar I'm using: %token INT %token ID %token MINUS %start expr %type expr %nonassoc INT ID %left MINUS %left APPLY %% expr: INT { ExprInt $1 } | ID { ExprId $1 } | expr MINUS expr { ExprSub($1, $3) } | MINUS expr { ExprNeg $2 } | expr expr %prec APPLY { ExprApply($1, $2) }; The problem is that when you get an expression like "a - b" the parser doesn't know whether this should be reduced as "a (-b)" (negation of b, followed by application) or "a - b" (subtraction). The subtraction reduction is correct. How do I resolve the conflict in favor of that rule? ANSWER: Unfortunately, the only answer I can come up with means increasing the complexity of the grammar. split expr into simple_expr and expr_with_prefix allow only simple_expr or (expr_with_prefix) in an APPLY The first step turns your reduce/reduce conflict into a shift/reduce conflict, but the parentheses resolve that. You're going to have the same problem with 'a b c': is it a(b(c)) or (a(b))(c)? You'll need to also break off applied_expression and required (applied_expression) in the grammar. I think this will do it, but I'm not sure: expr:= INT | parenthesized_expr | expr MINUS expr parenthesized_expr:= ( expr ) | ( applied_expr ) | ( expr_with_prefix ) applied_expr:= expr expr expr_with_prefix:= MINUS expr
[ "parsing", "ocaml", "grammar", "yacc" ]
11
9
9,022
2
0
2008-08-23T19:18:48.050000
2008-08-23T20:49:00.047000
24,528
24,531
What are your experiences running SVN on Windows?
I'm curious to hear the experiences of those who are currently running their SVN server on Windows. Jeff Atwood has a post on how to setup SVN as a Windows service. It's a great first step, but it doesn't touch on other topics, such as: What to use for a web-based repository browser? WebSVN can work on Windows, but it ain't pretty. How to manage the passwd file? Is it possible to integrate with Active Directory without running Apache? Strategies for backing up the repository. Useful global ignore patterns for Visual Studio development (suggestions here, here, and here for example). Our company switched from SourceGear Vault to Subversion about one month ago. We've got the basics down pat, but would love to discover people's tips and tricks for running SVN in a MSFT world.
Use VisualSVN Server. It integrates with Windows authentication and it handles all the apache setup. It's as painless as SVN can be on Windows.
What are your experiences running SVN on Windows? I'm curious to hear the experiences of those who are currently running their SVN server on Windows. Jeff Atwood has a post on how to setup SVN as a Windows service. It's a great first step, but it doesn't touch on other topics, such as: What to use for a web-based repository browser? WebSVN can work on Windows, but it ain't pretty. How to manage the passwd file? Is it possible to integrate with Active Directory without running Apache? Strategies for backing up the repository. Useful global ignore patterns for Visual Studio development (suggestions here, here, and here for example). Our company switched from SourceGear Vault to Subversion about one month ago. We've got the basics down pat, but would love to discover people's tips and tricks for running SVN in a MSFT world.
TITLE: What are your experiences running SVN on Windows? QUESTION: I'm curious to hear the experiences of those who are currently running their SVN server on Windows. Jeff Atwood has a post on how to setup SVN as a Windows service. It's a great first step, but it doesn't touch on other topics, such as: What to use for a web-based repository browser? WebSVN can work on Windows, but it ain't pretty. How to manage the passwd file? Is it possible to integrate with Active Directory without running Apache? Strategies for backing up the repository. Useful global ignore patterns for Visual Studio development (suggestions here, here, and here for example). Our company switched from SourceGear Vault to Subversion about one month ago. We've got the basics down pat, but would love to discover people's tips and tricks for running SVN in a MSFT world. ANSWER: Use VisualSVN Server. It integrates with Windows authentication and it handles all the apache setup. It's as painless as SVN can be on Windows.
[ "windows", "svn" ]
11
17
1,916
12
0
2008-08-23T19:30:47.660000
2008-08-23T19:33:58.497000
24,541
24,548
Create a database from another database?
Is there an automatic way in SQL Server 2005 to create a database from several tables in another database? I need to work on a project and I only need a few tables to run it locally, and I don't want to make a backup of a 50 gig DB. UPDATE I tried the Tasks -> Export Data in Management studio, and while it created a new sub database with the tables I wanted, it did not copy over any table metadata, ie...no PK/FK constraints and no Identity data (Even with Preserve Identity checked). I obviously need these for it to work, so I'm open to other suggestions. I'll try that database publishing tool. I don't have Integration Services available, and the two SQL Servers cannot directly connect to each other, so those are out. Update of the Update The Database Publishing Tool worked, the SQL it generated was slightly buggy, so a little hand editing was needed (Tried to reference nonexistent triggers), but once I did that I was good to go.
You can use the Database Publishing Wizard for this. It will let you select a set of tables with or without the data and export it into a.sql script file that you can then run against your other db to recreate the tables and/or the data.
Create a database from another database? Is there an automatic way in SQL Server 2005 to create a database from several tables in another database? I need to work on a project and I only need a few tables to run it locally, and I don't want to make a backup of a 50 gig DB. UPDATE I tried the Tasks -> Export Data in Management studio, and while it created a new sub database with the tables I wanted, it did not copy over any table metadata, ie...no PK/FK constraints and no Identity data (Even with Preserve Identity checked). I obviously need these for it to work, so I'm open to other suggestions. I'll try that database publishing tool. I don't have Integration Services available, and the two SQL Servers cannot directly connect to each other, so those are out. Update of the Update The Database Publishing Tool worked, the SQL it generated was slightly buggy, so a little hand editing was needed (Tried to reference nonexistent triggers), but once I did that I was good to go.
TITLE: Create a database from another database? QUESTION: Is there an automatic way in SQL Server 2005 to create a database from several tables in another database? I need to work on a project and I only need a few tables to run it locally, and I don't want to make a backup of a 50 gig DB. UPDATE I tried the Tasks -> Export Data in Management studio, and while it created a new sub database with the tables I wanted, it did not copy over any table metadata, ie...no PK/FK constraints and no Identity data (Even with Preserve Identity checked). I obviously need these for it to work, so I'm open to other suggestions. I'll try that database publishing tool. I don't have Integration Services available, and the two SQL Servers cannot directly connect to each other, so those are out. Update of the Update The Database Publishing Tool worked, the SQL it generated was slightly buggy, so a little hand editing was needed (Tried to reference nonexistent triggers), but once I did that I was good to go. ANSWER: You can use the Database Publishing Wizard for this. It will let you select a set of tables with or without the data and export it into a.sql script file that you can then run against your other db to recreate the tables and/or the data.
[ "sql-server-2005", "t-sql" ]
5
4
6,910
5
0
2008-08-23T19:51:31.433000
2008-08-23T19:55:31.143000
24,542
24,560
Using bitwise operators for Booleans in C++
Is there any reason not to use the bitwise operators &, |, and ^ for "bool" values in C++? I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression. I also sometimes want all parts of a condition to be evaluated whether the result is true or not (rather than short-circuiting), so I use & and |. I also need to accumulate Boolean values sometimes, and &= and |= can be quite useful. I've gotten a few raised eyebrows when doing this, but the code is still meaningful and cleaner than it would be otherwise. Is there any reason NOT to use these for bools? Are there any modern compilers that give bad results for this?
|| and && are boolean operators and the built-in ones are guaranteed to return either true or false. Nothing else. |, & and ^ are bitwise operators. When the domain of numbers you operate on is just 1 and 0, then they are exactly the same, but in cases where your booleans are not strictly 1 and 0 – as is the case with the C language – you may end up with some behavior you didn't want. For instance: BOOL two = 2; BOOL one = 1; BOOL and = two & one; //and = 0 BOOL cand = two && one; //cand = 1 In C++, however, the bool type is guaranteed to be only either a true or a false (which convert implicitly to respectively 1 and 0 ), so it's less of a worry from this stance, but the fact that people aren't used to seeing such things in code makes a good argument for not doing it. Just say b = b && x and be done with it.
Using bitwise operators for Booleans in C++ Is there any reason not to use the bitwise operators &, |, and ^ for "bool" values in C++? I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression. I also sometimes want all parts of a condition to be evaluated whether the result is true or not (rather than short-circuiting), so I use & and |. I also need to accumulate Boolean values sometimes, and &= and |= can be quite useful. I've gotten a few raised eyebrows when doing this, but the code is still meaningful and cleaner than it would be otherwise. Is there any reason NOT to use these for bools? Are there any modern compilers that give bad results for this?
TITLE: Using bitwise operators for Booleans in C++ QUESTION: Is there any reason not to use the bitwise operators &, |, and ^ for "bool" values in C++? I sometimes run into situations where I want exactly one of two conditions to be true (XOR), so I just throw the ^ operator into a conditional expression. I also sometimes want all parts of a condition to be evaluated whether the result is true or not (rather than short-circuiting), so I use & and |. I also need to accumulate Boolean values sometimes, and &= and |= can be quite useful. I've gotten a few raised eyebrows when doing this, but the code is still meaningful and cleaner than it would be otherwise. Is there any reason NOT to use these for bools? Are there any modern compilers that give bad results for this? ANSWER: || and && are boolean operators and the built-in ones are guaranteed to return either true or false. Nothing else. |, & and ^ are bitwise operators. When the domain of numbers you operate on is just 1 and 0, then they are exactly the same, but in cases where your booleans are not strictly 1 and 0 – as is the case with the C language – you may end up with some behavior you didn't want. For instance: BOOL two = 2; BOOL one = 1; BOOL and = two & one; //and = 0 BOOL cand = two && one; //cand = 1 In C++, however, the bool type is guaranteed to be only either a true or a false (which convert implicitly to respectively 1 and 0 ), so it's less of a worry from this stance, but the fact that people aren't used to seeing such things in code makes a good argument for not doing it. Just say b = b && x and be done with it.
[ "c++", "boolean", "bitwise-operators" ]
108
71
88,071
9
0
2008-08-23T19:52:39.933000
2008-08-23T20:06:20.430000
24,546
24,574
Why can't I fetch wikipedia pages with LWP::Simple?
I'm trying to fetch Wikipedia pages using LWP::Simple, but they're not coming back. This code: #!/usr/bin/perl use strict; use LWP::Simple; print get("http://en.wikipedia.org/wiki/Stack_overflow"); doesn't print anything. But if I use some other webpage, say http://www.google.com, it works fine. Is there some other name that I should be using to refer to Wikipedia pages? What could be going on here?
Apparently Wikipedia blocks LWP::Simple requests: http://www.perlmonks.org/?node_id=695886 The following works instead: #!/usr/bin/perl use strict; use LWP::UserAgent; my $url = "http://en.wikipedia.org/wiki/Stack_overflow"; my $ua = LWP::UserAgent->new(); my $res = $ua->get($url); print $res->content;
Why can't I fetch wikipedia pages with LWP::Simple? I'm trying to fetch Wikipedia pages using LWP::Simple, but they're not coming back. This code: #!/usr/bin/perl use strict; use LWP::Simple; print get("http://en.wikipedia.org/wiki/Stack_overflow"); doesn't print anything. But if I use some other webpage, say http://www.google.com, it works fine. Is there some other name that I should be using to refer to Wikipedia pages? What could be going on here?
TITLE: Why can't I fetch wikipedia pages with LWP::Simple? QUESTION: I'm trying to fetch Wikipedia pages using LWP::Simple, but they're not coming back. This code: #!/usr/bin/perl use strict; use LWP::Simple; print get("http://en.wikipedia.org/wiki/Stack_overflow"); doesn't print anything. But if I use some other webpage, say http://www.google.com, it works fine. Is there some other name that I should be using to refer to Wikipedia pages? What could be going on here? ANSWER: Apparently Wikipedia blocks LWP::Simple requests: http://www.perlmonks.org/?node_id=695886 The following works instead: #!/usr/bin/perl use strict; use LWP::UserAgent; my $url = "http://en.wikipedia.org/wiki/Stack_overflow"; my $ua = LWP::UserAgent->new(); my $res = $ua->get($url); print $res->content;
[ "perl", "wikipedia", "lwp" ]
11
18
3,671
5
0
2008-08-23T19:54:09.650000
2008-08-23T20:33:00.787000
24,551
24,558
Initialize class fields in constructor or at declaration?
I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields. Should I do it at declaration?: public class Dice { private int topFace = 1; private Random myRand = new Random(); public void Roll() { //...... } } or in a constructor?: public class Dice { private int topFace; private Random myRand; public Dice() { topFace = 1; myRand = new Random(); } public void Roll() { //..... } } I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach.
My rules: Don't initialize with the default values in declaration ( null, false, 0, 0.0 …). Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field. If the value of the field changes because of a constructor parameter put the initialization in the constructors. Be consistent in your practice (the most important rule).
Initialize class fields in constructor or at declaration? I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields. Should I do it at declaration?: public class Dice { private int topFace = 1; private Random myRand = new Random(); public void Roll() { //...... } } or in a constructor?: public class Dice { private int topFace; private Random myRand; public Dice() { topFace = 1; myRand = new Random(); } public void Roll() { //..... } } I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach.
TITLE: Initialize class fields in constructor or at declaration? QUESTION: I've been programming in C# and Java recently and I am curious where the best place is to initialize my class fields. Should I do it at declaration?: public class Dice { private int topFace = 1; private Random myRand = new Random(); public void Roll() { //...... } } or in a constructor?: public class Dice { private int topFace; private Random myRand; public Dice() { topFace = 1; myRand = new Random(); } public void Roll() { //..... } } I'm really curious what some of you veterans think is the best practice. I want to be consistent and stick to one approach. ANSWER: My rules: Don't initialize with the default values in declaration ( null, false, 0, 0.0 …). Prefer initialization in declaration if you don't have a constructor parameter that changes the value of the field. If the value of the field changes because of a constructor parameter put the initialization in the constructors. Be consistent in your practice (the most important rule).
[ "java" ]
470
347
168,085
16
0
2008-08-23T19:59:42.083000
2008-08-23T20:04:09.530000
24,556
24,592
Attaching entities to data contexts
In LINQ to SQL, is it possible to check to see if an entity is already part of the data context before trying to attach it? A little context if it helps... I have this code in my global.asax as a helper method. Normally, between requests, this isn't a problem. But right after signing in, this is getting called more than once, and the second time I end up trying to attach the Member object in the same unit of work where it was created. private void CheckCurrentUser() { if (!HttpContext.Current.User.Identity.IsAuthenticated) { AppHelper.CurrentMember = null; return; } IUserService userService = new UserService(); if (AppHelper.CurrentMember!= null) userService.AttachExisting(AppHelper.CurrentMember); else AppHelper.CurrentMember = userService.GetMember( HttpContext.Current.User.Identity.Name, AppHelper.CurrentLocation); }
I believe there are two methods to do this. DataContext.TableName.Contains(Item) or we use the id field. If the item is inserted in the Database, then it will be assigned a row. if(Item.id == 0) DataContext.Insert(Item) else DataContext.Update(Item)
Attaching entities to data contexts In LINQ to SQL, is it possible to check to see if an entity is already part of the data context before trying to attach it? A little context if it helps... I have this code in my global.asax as a helper method. Normally, between requests, this isn't a problem. But right after signing in, this is getting called more than once, and the second time I end up trying to attach the Member object in the same unit of work where it was created. private void CheckCurrentUser() { if (!HttpContext.Current.User.Identity.IsAuthenticated) { AppHelper.CurrentMember = null; return; } IUserService userService = new UserService(); if (AppHelper.CurrentMember!= null) userService.AttachExisting(AppHelper.CurrentMember); else AppHelper.CurrentMember = userService.GetMember( HttpContext.Current.User.Identity.Name, AppHelper.CurrentLocation); }
TITLE: Attaching entities to data contexts QUESTION: In LINQ to SQL, is it possible to check to see if an entity is already part of the data context before trying to attach it? A little context if it helps... I have this code in my global.asax as a helper method. Normally, between requests, this isn't a problem. But right after signing in, this is getting called more than once, and the second time I end up trying to attach the Member object in the same unit of work where it was created. private void CheckCurrentUser() { if (!HttpContext.Current.User.Identity.IsAuthenticated) { AppHelper.CurrentMember = null; return; } IUserService userService = new UserService(); if (AppHelper.CurrentMember!= null) userService.AttachExisting(AppHelper.CurrentMember); else AppHelper.CurrentMember = userService.GetMember( HttpContext.Current.User.Identity.Name, AppHelper.CurrentLocation); } ANSWER: I believe there are two methods to do this. DataContext.TableName.Contains(Item) or we use the id field. If the item is inserted in the Database, then it will be assigned a row. if(Item.id == 0) DataContext.Insert(Item) else DataContext.Update(Item)
[ "c#", "linq-to-sql" ]
0
0
216
2
0
2008-08-23T20:03:52.120000
2008-08-23T20:54:12.047000
24,579
24,607
WYSIWYG editor gem for Rails?
Is there a good ruby gem for a WYSIWYG editor that will easily work with a rails app?
Though it's certainly not a direct answer, in the past I've found I prefer to use RedCloth (or a Markdown parser if you don't enjoy Textile) and use a simple textarea with an AJAXy preview. Generally speaking, WYSIWYG editors have a long history of creating redundant tags and similar, leading to potentially broken pieces of HTML.
WYSIWYG editor gem for Rails? Is there a good ruby gem for a WYSIWYG editor that will easily work with a rails app?
TITLE: WYSIWYG editor gem for Rails? QUESTION: Is there a good ruby gem for a WYSIWYG editor that will easily work with a rails app? ANSWER: Though it's certainly not a direct answer, in the past I've found I prefer to use RedCloth (or a Markdown parser if you don't enjoy Textile) and use a simple textarea with an AJAXy preview. Generally speaking, WYSIWYG editors have a long history of creating redundant tags and similar, leading to potentially broken pieces of HTML.
[ "ruby-on-rails", "ruby", "rubygems" ]
18
24
17,077
12
0
2008-08-23T20:39:23.067000
2008-08-23T21:11:42.677000
24,580
34,063
How do you automate a Visual Studio build?
How do you turn a Visual Studio build that you'd perform in the IDE into a script that you can run from the command line?
With VS2008 you can do this: devenv solution.sln /build configuration
How do you automate a Visual Studio build? How do you turn a Visual Studio build that you'd perform in the IDE into a script that you can run from the command line?
TITLE: How do you automate a Visual Studio build? QUESTION: How do you turn a Visual Studio build that you'd perform in the IDE into a script that you can run from the command line? ANSWER: With VS2008 you can do this: devenv solution.sln /build configuration
[ "visual-studio", "build-automation" ]
52
32
57,778
11
0
2008-08-23T20:42:25.943000
2008-08-29T06:38:23.303000
24,595
24,613
Code Classic ASP in Linux
What should i use to code Classic ASP under Linux. I have really tried to use Emacs and Vim but I don't have the time to learn them. What i'm looking for is: Syntax highlighting Code Browser (Ctags) Preferably som sort of code insight Something like Ultra Edit or E-texteditor.
I'm not sure what you're asking here, but if you are simply looking for a text-editor, my recommendations would be: Console-based: jed (simple, with a DOS Edit-like menubar, supports syntax-highlighing) nano / pico (even simpler) X-based: Kate (KDE, syntax-highlighing) Mousepad (like notepad) SciTE (syntax-highlighing) There are of course likely to be a gazillion other text-editors better than the ones listed above, but these are the ones I tend to use.
Code Classic ASP in Linux What should i use to code Classic ASP under Linux. I have really tried to use Emacs and Vim but I don't have the time to learn them. What i'm looking for is: Syntax highlighting Code Browser (Ctags) Preferably som sort of code insight Something like Ultra Edit or E-texteditor.
TITLE: Code Classic ASP in Linux QUESTION: What should i use to code Classic ASP under Linux. I have really tried to use Emacs and Vim but I don't have the time to learn them. What i'm looking for is: Syntax highlighting Code Browser (Ctags) Preferably som sort of code insight Something like Ultra Edit or E-texteditor. ANSWER: I'm not sure what you're asking here, but if you are simply looking for a text-editor, my recommendations would be: Console-based: jed (simple, with a DOS Edit-like menubar, supports syntax-highlighing) nano / pico (even simpler) X-based: Kate (KDE, syntax-highlighing) Mousepad (like notepad) SciTE (syntax-highlighing) There are of course likely to be a gazillion other text-editors better than the ones listed above, but these are the ones I tend to use.
[ "linux", "asp-classic", "editor" ]
1
4
1,383
2
0
2008-08-23T20:56:56.423000
2008-08-23T21:23:58.200000
24,596
24,707
What are the pros and cons of the assorted Java web frameworks?
I am considering creating my own website using Java and am trying to decide what framework to use. However, doing a quick search for Java frameworks returns more than 50 to choose from! My website is just going to be for my own enjoyment of building it in the beginning, but if it becomes popular, it would be good for it to have some scalability, or to at least be able to redesign for that. What are the main differences between the more popular frameworks? Are there instances where one significantly outperforms the others? For example, high-traffic enterprise applications versus low-traffic small applications. I'm also wondering if some are much easier to learn and use than others. Is there anyone who has experience with some of these frameworks and can make a recommendation? Does the sheer number of choices just serve as an early warning to avoid Java-based web development where possible?
I've used Tapestry 3, Wicket, Echo, and JSF fairly extensively. I'd really recommend you look those over and pick the one that appears the easiest for you, and to most closely fit the way you prefer to work. Of them, the most comfortable for me to work with was Wicket, due to the lightweight nature of component building and simplicity of page templating. That goes doubly so if you are using your own db code instead of Hibernate or some other framework (I was never completely happy with Wicket Hibernate or Spring Integration). Echo is great if you don't mind writing all of your layout in Java. I know that is different now, but I still think that product serves a fairly narrow niche. They change the development model with every major release as well it seems. Tapestry is a great product, but it is obviously very different from the others in terms of development model as it is led mainly by one dude. Howard Lewis Ship is no doubt quite smart, but I am disappointed with their decision to basically forget backwards compatibility with each release. Again, though, for your needs this may not matter, and I've always found the Tapestry products pleasurable to work against. JSF has been out for years, and still feels like something that a Struts guy built to fix all of the problems of Struts. Without really understanding all of the problems with Struts. It still has an unfinished feel to it, although the product is obviously very flexible. I use it and have some fondness for it, with great hopes for its future. I think the next release (2.0) to be delivered in JEE6 will really bring it into its own, with a new template syntax (similar to Facelets) and a simplified component model (custom components in only 1 file... finally). And, of course, there are a million smaller frameworks and tools that get their own following ( Velocity for basic needs, raw JSPs, Struts, etc). I generally prefer component oriented frameworks myself, though. In the end, I'd recommend just taking a look at Tapestry, Wicket, and JSF and just picking the one that feels the best to you. You'll probably find one that just fits the way you like to work very quickly.
What are the pros and cons of the assorted Java web frameworks? I am considering creating my own website using Java and am trying to decide what framework to use. However, doing a quick search for Java frameworks returns more than 50 to choose from! My website is just going to be for my own enjoyment of building it in the beginning, but if it becomes popular, it would be good for it to have some scalability, or to at least be able to redesign for that. What are the main differences between the more popular frameworks? Are there instances where one significantly outperforms the others? For example, high-traffic enterprise applications versus low-traffic small applications. I'm also wondering if some are much easier to learn and use than others. Is there anyone who has experience with some of these frameworks and can make a recommendation? Does the sheer number of choices just serve as an early warning to avoid Java-based web development where possible?
TITLE: What are the pros and cons of the assorted Java web frameworks? QUESTION: I am considering creating my own website using Java and am trying to decide what framework to use. However, doing a quick search for Java frameworks returns more than 50 to choose from! My website is just going to be for my own enjoyment of building it in the beginning, but if it becomes popular, it would be good for it to have some scalability, or to at least be able to redesign for that. What are the main differences between the more popular frameworks? Are there instances where one significantly outperforms the others? For example, high-traffic enterprise applications versus low-traffic small applications. I'm also wondering if some are much easier to learn and use than others. Is there anyone who has experience with some of these frameworks and can make a recommendation? Does the sheer number of choices just serve as an early warning to avoid Java-based web development where possible? ANSWER: I've used Tapestry 3, Wicket, Echo, and JSF fairly extensively. I'd really recommend you look those over and pick the one that appears the easiest for you, and to most closely fit the way you prefer to work. Of them, the most comfortable for me to work with was Wicket, due to the lightweight nature of component building and simplicity of page templating. That goes doubly so if you are using your own db code instead of Hibernate or some other framework (I was never completely happy with Wicket Hibernate or Spring Integration). Echo is great if you don't mind writing all of your layout in Java. I know that is different now, but I still think that product serves a fairly narrow niche. They change the development model with every major release as well it seems. Tapestry is a great product, but it is obviously very different from the others in terms of development model as it is led mainly by one dude. Howard Lewis Ship is no doubt quite smart, but I am disappointed with their decision to basically forget backwards compatibility with each release. Again, though, for your needs this may not matter, and I've always found the Tapestry products pleasurable to work against. JSF has been out for years, and still feels like something that a Struts guy built to fix all of the problems of Struts. Without really understanding all of the problems with Struts. It still has an unfinished feel to it, although the product is obviously very flexible. I use it and have some fondness for it, with great hopes for its future. I think the next release (2.0) to be delivered in JEE6 will really bring it into its own, with a new template syntax (similar to Facelets) and a simplified component model (custom components in only 1 file... finally). And, of course, there are a million smaller frameworks and tools that get their own following ( Velocity for basic needs, raw JSPs, Struts, etc). I generally prefer component oriented frameworks myself, though. In the end, I'd recommend just taking a look at Tapestry, Wicket, and JSF and just picking the one that feels the best to you. You'll probably find one that just fits the way you like to work very quickly.
[ "java", "web-frameworks", "rich-internet-application" ]
85
59
19,418
24
0
2008-08-23T20:58:25.437000
2008-08-23T23:39:36.317000
24,610
24,658
Vi editing for Visual Studio
I'm used to the Vi(m) editor and am using MS Visual Studio 2005 at work. I couldn't find a free Vi add-in (there's only one for the 2003 version). I googled a bit, saw that there was a 'Google summer of code' project this year to write such an add-in, and am eagerly awaiting the result. I've also heard of ViEmu (not free, and I can't test it at work). Has anyone in my situation has found a solution (and/or tested ViEmu)? Edit: I can't test ViEmu at work because they are paranoid about what we install on our boxes: it has to go through required channels, and for 30 days I don't reckon it's worth it (and I have no Windows box at home). Edit: Since both answers were equivalent, I ended up accepting the first one that came in.
ViEmu works great with Visual Studio. I used Vi(m) strictly in Linux, but I was turned on to bringing the Vi(m) editing process into the Windows world by JP Boodhoo. JP praises about it also.
Vi editing for Visual Studio I'm used to the Vi(m) editor and am using MS Visual Studio 2005 at work. I couldn't find a free Vi add-in (there's only one for the 2003 version). I googled a bit, saw that there was a 'Google summer of code' project this year to write such an add-in, and am eagerly awaiting the result. I've also heard of ViEmu (not free, and I can't test it at work). Has anyone in my situation has found a solution (and/or tested ViEmu)? Edit: I can't test ViEmu at work because they are paranoid about what we install on our boxes: it has to go through required channels, and for 30 days I don't reckon it's worth it (and I have no Windows box at home). Edit: Since both answers were equivalent, I ended up accepting the first one that came in.
TITLE: Vi editing for Visual Studio QUESTION: I'm used to the Vi(m) editor and am using MS Visual Studio 2005 at work. I couldn't find a free Vi add-in (there's only one for the 2003 version). I googled a bit, saw that there was a 'Google summer of code' project this year to write such an add-in, and am eagerly awaiting the result. I've also heard of ViEmu (not free, and I can't test it at work). Has anyone in my situation has found a solution (and/or tested ViEmu)? Edit: I can't test ViEmu at work because they are paranoid about what we install on our boxes: it has to go through required channels, and for 30 days I don't reckon it's worth it (and I have no Windows box at home). Edit: Since both answers were equivalent, I ended up accepting the first one that came in. ANSWER: ViEmu works great with Visual Studio. I used Vi(m) strictly in Linux, but I was turned on to bringing the Vi(m) editing process into the Windows world by JP Boodhoo. JP praises about it also.
[ "visual-studio", "vim", "ide", "editor" ]
12
6
1,651
2
0
2008-08-23T21:19:34.640000
2008-08-23T22:08:49.607000
24,622
24,631
Setting PHP Include Path on a per site basis?
I can set the PHP include path in the php.ini: include_path = /path/to/site/includes/ But then other websites are affected so that is no good. I can set the PHP include in the start of every file: $path = '/path/to/site/includes/'; set_include_path(get_include_path(). PATH_SEPARATOR. $path); But that seems like bad practice and clutters things up. So I can make an include of that and then include it into every file: include 'includes/config.php'; or include '../includes/config.php'; This is what I'm doing right now, but the include path of config.php will change depending on what is including it. Is there a better way? Does it matter?
If you're using apache as a webserver you can override (if you allow it) settings using.htaccess files. See the PHP manual for details. Basically you put a file called.htaccess in your website root, which contains some PHP ini values. Provided you configured Apache to allow overrides, this site will use all values in your PHP config, + the values you specify in the.htaccess file. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives as stated in the page I linked. If you click through to the full listing, you see that the include path is a PHP_INI_ALL directive.
Setting PHP Include Path on a per site basis? I can set the PHP include path in the php.ini: include_path = /path/to/site/includes/ But then other websites are affected so that is no good. I can set the PHP include in the start of every file: $path = '/path/to/site/includes/'; set_include_path(get_include_path(). PATH_SEPARATOR. $path); But that seems like bad practice and clutters things up. So I can make an include of that and then include it into every file: include 'includes/config.php'; or include '../includes/config.php'; This is what I'm doing right now, but the include path of config.php will change depending on what is including it. Is there a better way? Does it matter?
TITLE: Setting PHP Include Path on a per site basis? QUESTION: I can set the PHP include path in the php.ini: include_path = /path/to/site/includes/ But then other websites are affected so that is no good. I can set the PHP include in the start of every file: $path = '/path/to/site/includes/'; set_include_path(get_include_path(). PATH_SEPARATOR. $path); But that seems like bad practice and clutters things up. So I can make an include of that and then include it into every file: include 'includes/config.php'; or include '../includes/config.php'; This is what I'm doing right now, but the include path of config.php will change depending on what is including it. Is there a better way? Does it matter? ANSWER: If you're using apache as a webserver you can override (if you allow it) settings using.htaccess files. See the PHP manual for details. Basically you put a file called.htaccess in your website root, which contains some PHP ini values. Provided you configured Apache to allow overrides, this site will use all values in your PHP config, + the values you specify in the.htaccess file. Can be used only with PHP_INI_ALL and PHP_INI_PERDIR type directives as stated in the page I linked. If you click through to the full listing, you see that the include path is a PHP_INI_ALL directive.
[ "php", "include" ]
19
17
24,805
7
0
2008-08-23T21:39:54.793000
2008-08-23T21:43:16.687000
24,626
24,748
Abstraction VS Information Hiding VS Encapsulation
Can you tell me what is the difference between abstraction and information hiding in software development? I am confused. Abstraction hides detail implementation and information hiding abstracts whole details of something. Update: I found a good answer for these three concepts. See the separate answer below for several citations taken from there.
Go to the source! Grady Booch says (in Object Oriented Analysis and Design, page 49, second edition): Abstraction and encapsulation are complementary concepts: abstraction focuses on the observable behavior of an object... encapsulation focuses upon the implementation that gives rise to this behavior... encapsulation is most often achieved through information hiding, which is the process of hiding all of the secrets of object that do not contribute to its essential characteristics. In other words: abstraction = the object externally; encapsulation (achieved through information hiding) = the object internally, Example: In the.NET Framework, the System.Text.StringBuilder class provides an abstraction over a string buffer. This buffer abstraction lets you work with the buffer without regard for its implementation. Thus, you're able to append strings to the buffer without regard for how the StringBuilder internally keeps track of things such the pointer to the buffer and managing memory when the buffer gets full (which it does with encapsulation via information hiding). rp
Abstraction VS Information Hiding VS Encapsulation Can you tell me what is the difference between abstraction and information hiding in software development? I am confused. Abstraction hides detail implementation and information hiding abstracts whole details of something. Update: I found a good answer for these three concepts. See the separate answer below for several citations taken from there.
TITLE: Abstraction VS Information Hiding VS Encapsulation QUESTION: Can you tell me what is the difference between abstraction and information hiding in software development? I am confused. Abstraction hides detail implementation and information hiding abstracts whole details of something. Update: I found a good answer for these three concepts. See the separate answer below for several citations taken from there. ANSWER: Go to the source! Grady Booch says (in Object Oriented Analysis and Design, page 49, second edition): Abstraction and encapsulation are complementary concepts: abstraction focuses on the observable behavior of an object... encapsulation focuses upon the implementation that gives rise to this behavior... encapsulation is most often achieved through information hiding, which is the process of hiding all of the secrets of object that do not contribute to its essential characteristics. In other words: abstraction = the object externally; encapsulation (achieved through information hiding) = the object internally, Example: In the.NET Framework, the System.Text.StringBuilder class provides an abstraction over a string buffer. This buffer abstraction lets you work with the buffer without regard for its implementation. Thus, you're able to append strings to the buffer without regard for how the StringBuilder internally keeps track of things such the pointer to the buffer and managing memory when the buffer gets full (which it does with encapsulation via information hiding). rp
[ "encapsulation", "abstraction", "glossary", "ooad", "information-hiding" ]
186
163
161,978
22
0
2008-08-23T21:41:49.670000
2008-08-24T00:57:31.370000
24,644
24,671
Hooking my program with windows explorer's rename event
Is there any way, in any language, to hook my program when a user renames a file? For example: A user renames a file and presses enter (or clicks away) to confirm the rename action. BEFORE the file is actually renamed, my program "listens" to this event and pops up a message saying "Are you sure you want to rename C:\test\file.txt to C:\test\test.txt?". I'm thinking/hoping this is possible with C++, C# or.NET.. But I don't have any clue where to look for.
You can probably solve this by using the FileSystemWatcher class in.NET framework. From the class remarks: You can watch for renaming, deletion, or creation of files or directories. For example, to watch for renaming of text files, set the Filter property to "*.txt" and call the WaitForChanged method with a Renamed specified for its parameter.
Hooking my program with windows explorer's rename event Is there any way, in any language, to hook my program when a user renames a file? For example: A user renames a file and presses enter (or clicks away) to confirm the rename action. BEFORE the file is actually renamed, my program "listens" to this event and pops up a message saying "Are you sure you want to rename C:\test\file.txt to C:\test\test.txt?". I'm thinking/hoping this is possible with C++, C# or.NET.. But I don't have any clue where to look for.
TITLE: Hooking my program with windows explorer's rename event QUESTION: Is there any way, in any language, to hook my program when a user renames a file? For example: A user renames a file and presses enter (or clicks away) to confirm the rename action. BEFORE the file is actually renamed, my program "listens" to this event and pops up a message saying "Are you sure you want to rename C:\test\file.txt to C:\test\test.txt?". I'm thinking/hoping this is possible with C++, C# or.NET.. But I don't have any clue where to look for. ANSWER: You can probably solve this by using the FileSystemWatcher class in.NET framework. From the class remarks: You can watch for renaming, deletion, or creation of files or directories. For example, to watch for renaming of text files, set the Filter property to "*.txt" and call the WaitForChanged method with a Renamed specified for its parameter.
[ "c#", ".net", "file", "io" ]
7
5
2,006
3
0
2008-08-23T21:56:47.810000
2008-08-23T22:31:11.813000
24,648
24,682
What's the best way to get to know linux or BSD kernel internals?
I'd like to gain better knowledge of operating system internals. Process management, memory management, and stuff like that. I was thinking of learning by getting to know either linux or BSD kernel. Which one kernel is better for learning purposes? What's the best place to start? Can you recommend any good books?
In college, I had an operating systems class where we used a book by Tanenbaum. In the class, we implemented a device driver in the Minix operating system. It was a lot of fun, and we learned a lot. One thing to note though, if you pick Minix, it is designed for learning. It is a microkernel, while Linux and BSD are a monolithic kernel, so what you learn may not be 100% translatable to be able to work with Linux or BSD, but you can still gain a lot out of it, without having to process quite as much information. As a side note, if you've read Just for Fun, Linus actually was playing with Minix before he wrote Linux, but it just wasn't enough for his purposes.
What's the best way to get to know linux or BSD kernel internals? I'd like to gain better knowledge of operating system internals. Process management, memory management, and stuff like that. I was thinking of learning by getting to know either linux or BSD kernel. Which one kernel is better for learning purposes? What's the best place to start? Can you recommend any good books?
TITLE: What's the best way to get to know linux or BSD kernel internals? QUESTION: I'd like to gain better knowledge of operating system internals. Process management, memory management, and stuff like that. I was thinking of learning by getting to know either linux or BSD kernel. Which one kernel is better for learning purposes? What's the best place to start? Can you recommend any good books? ANSWER: In college, I had an operating systems class where we used a book by Tanenbaum. In the class, we implemented a device driver in the Minix operating system. It was a lot of fun, and we learned a lot. One thing to note though, if you pick Minix, it is designed for learning. It is a microkernel, while Linux and BSD are a monolithic kernel, so what you learn may not be 100% translatable to be able to work with Linux or BSD, but you can still gain a lot out of it, without having to process quite as much information. As a side note, if you've read Just for Fun, Linus actually was playing with Minix before he wrote Linux, but it just wasn't enough for his purposes.
[ "linux", "operating-system", "kernel", "bsd", "osdev" ]
22
12
6,108
12
0
2008-08-23T21:58:53.500000
2008-08-23T22:51:16.073000
24,675
24,689
Tactics for using PHP in a high-load site
Before you answer this I have never developed anything popular enough to attain high server loads. Treat me as (sigh) an alien that has just landed on the planet, albeit one that knows PHP and a few optimisation techniques. I'm developing a tool in PHP that could attain quite a lot of users, if it works out right. However while I'm fully capable of developing the program I'm pretty much clueless when it comes to making something that can deal with huge traffic. So here's a few questions on it (feel free to turn this question into a resource thread as well). Databases At the moment I plan to use the MySQLi features in PHP5. However how should I setup the databases in relation to users and content? Do I actually need multiple databases? At the moment everything's jumbled into one database - although I've been considering spreading user data to one, actual content to another and finally core site content (template masters etc.) to another. My reasoning behind this is that sending queries to different databases will ease up the load on them as one database = 3 load sources. Also would this still be effective if they were all on the same server? Caching I have a template system that is used to build the pages and swap out variables. Master templates are stored in the database and each time a template is called its cached copy (a html document) is called. At the moment I have two types of variable in these templates - a static var and a dynamic var. Static vars are usually things like page names, the name of the site - things that don't change often; dynamic vars are things that change on each page load. My question on this: Say I have comments on different articles. Which is a better solution: store the simple comment template and render comments (from a DB call) each time the page is loaded or store a cached copy of the comments page as a html page - each time a comment is added/edited/deleted the page is recached. Finally Does anyone have any tips/pointers for running a high load site on PHP. I'm pretty sure it's a workable language to use - Facebook and Yahoo! give it great precedence - but are there any experiences I should watch out for?
No two sites are alike. You really need to get a tool like jmeter and benchmark to see where your problem points will be. You can spend a lot of time guessing and improving, but you won't see real results until you measure and compare your changes. For example, for many years, the MySQL query cache was the solution to all of our performance problems. If your site was slow, MySQL experts suggested turning the query cache on. It turns out that if you have a high write load, the cache is actually crippling. If you turned it on without testing, you'd never know. And don't forget that you are never done scaling. A site that handles 10req/s will need changes to support 1000req/s. And if you're lucking enough to need to support 10,000req/s, your architecture will probably look completely different as well. Databases Don't use MySQLi -- PDO is the 'modern' OO database access layer. The most important feature to use is placeholders in your queries. It's smart enough to use server side prepares and other optimizations for you as well. You probably don't want to break your database up at this point. If you do find that one database isn't cutting, there are several techniques to scale up, depending on your app. Replicating to additional servers typically works well if you have more reads than writes. Sharding is a technique to split your data over many machines. Caching You probably don't want to cache in your database. The database is typically your bottleneck, so adding more IO's to it is typically a bad thing. There are several PHP caches out there that accomplish similar things like APC and Zend. Measure your system with caching on and off. I bet your cache is heavier than serving the pages straight. If it takes a long time to build your comments and article data from the db, integrate memcache into your system. You can cache the query results and store them in a memcached instance. It's important to remember that retrieving the data from memcache must be faster than assembling it from the database to see any benefit. If your articles aren't dynamic, or you have simple dynamic changes after it's generated, consider writing out html or php to the disk. You could have an index.php page that looks on disk for the article, if it's there, it streams it to the client. If it isn't, it generates the article, writes it to the disk and sends it to the client. Deleting files from the disk would cause pages to be re-written. If a comment is added to an article, delete the cached copy -- it would be regenerated.
Tactics for using PHP in a high-load site Before you answer this I have never developed anything popular enough to attain high server loads. Treat me as (sigh) an alien that has just landed on the planet, albeit one that knows PHP and a few optimisation techniques. I'm developing a tool in PHP that could attain quite a lot of users, if it works out right. However while I'm fully capable of developing the program I'm pretty much clueless when it comes to making something that can deal with huge traffic. So here's a few questions on it (feel free to turn this question into a resource thread as well). Databases At the moment I plan to use the MySQLi features in PHP5. However how should I setup the databases in relation to users and content? Do I actually need multiple databases? At the moment everything's jumbled into one database - although I've been considering spreading user data to one, actual content to another and finally core site content (template masters etc.) to another. My reasoning behind this is that sending queries to different databases will ease up the load on them as one database = 3 load sources. Also would this still be effective if they were all on the same server? Caching I have a template system that is used to build the pages and swap out variables. Master templates are stored in the database and each time a template is called its cached copy (a html document) is called. At the moment I have two types of variable in these templates - a static var and a dynamic var. Static vars are usually things like page names, the name of the site - things that don't change often; dynamic vars are things that change on each page load. My question on this: Say I have comments on different articles. Which is a better solution: store the simple comment template and render comments (from a DB call) each time the page is loaded or store a cached copy of the comments page as a html page - each time a comment is added/edited/deleted the page is recached. Finally Does anyone have any tips/pointers for running a high load site on PHP. I'm pretty sure it's a workable language to use - Facebook and Yahoo! give it great precedence - but are there any experiences I should watch out for?
TITLE: Tactics for using PHP in a high-load site QUESTION: Before you answer this I have never developed anything popular enough to attain high server loads. Treat me as (sigh) an alien that has just landed on the planet, albeit one that knows PHP and a few optimisation techniques. I'm developing a tool in PHP that could attain quite a lot of users, if it works out right. However while I'm fully capable of developing the program I'm pretty much clueless when it comes to making something that can deal with huge traffic. So here's a few questions on it (feel free to turn this question into a resource thread as well). Databases At the moment I plan to use the MySQLi features in PHP5. However how should I setup the databases in relation to users and content? Do I actually need multiple databases? At the moment everything's jumbled into one database - although I've been considering spreading user data to one, actual content to another and finally core site content (template masters etc.) to another. My reasoning behind this is that sending queries to different databases will ease up the load on them as one database = 3 load sources. Also would this still be effective if they were all on the same server? Caching I have a template system that is used to build the pages and swap out variables. Master templates are stored in the database and each time a template is called its cached copy (a html document) is called. At the moment I have two types of variable in these templates - a static var and a dynamic var. Static vars are usually things like page names, the name of the site - things that don't change often; dynamic vars are things that change on each page load. My question on this: Say I have comments on different articles. Which is a better solution: store the simple comment template and render comments (from a DB call) each time the page is loaded or store a cached copy of the comments page as a html page - each time a comment is added/edited/deleted the page is recached. Finally Does anyone have any tips/pointers for running a high load site on PHP. I'm pretty sure it's a workable language to use - Facebook and Yahoo! give it great precedence - but are there any experiences I should watch out for? ANSWER: No two sites are alike. You really need to get a tool like jmeter and benchmark to see where your problem points will be. You can spend a lot of time guessing and improving, but you won't see real results until you measure and compare your changes. For example, for many years, the MySQL query cache was the solution to all of our performance problems. If your site was slow, MySQL experts suggested turning the query cache on. It turns out that if you have a high write load, the cache is actually crippling. If you turned it on without testing, you'd never know. And don't forget that you are never done scaling. A site that handles 10req/s will need changes to support 1000req/s. And if you're lucking enough to need to support 10,000req/s, your architecture will probably look completely different as well. Databases Don't use MySQLi -- PDO is the 'modern' OO database access layer. The most important feature to use is placeholders in your queries. It's smart enough to use server side prepares and other optimizations for you as well. You probably don't want to break your database up at this point. If you do find that one database isn't cutting, there are several techniques to scale up, depending on your app. Replicating to additional servers typically works well if you have more reads than writes. Sharding is a technique to split your data over many machines. Caching You probably don't want to cache in your database. The database is typically your bottleneck, so adding more IO's to it is typically a bad thing. There are several PHP caches out there that accomplish similar things like APC and Zend. Measure your system with caching on and off. I bet your cache is heavier than serving the pages straight. If it takes a long time to build your comments and article data from the db, integrate memcache into your system. You can cache the query results and store them in a memcached instance. It's important to remember that retrieving the data from memcache must be faster than assembling it from the database to see any benefit. If your articles aren't dynamic, or you have simple dynamic changes after it's generated, consider writing out html or php to the disk. You could have an index.php page that looks on disk for the article, if it's there, it streams it to the client. If it isn't, it generates the article, writes it to the disk and sends it to the client. Deleting files from the disk would cause pages to be re-written. If a comment is added to an article, delete the cached copy -- it would be regenerated.
[ "php", "performance", "high-load" ]
253
94
27,487
24
0
2008-08-23T22:37:49.707000
2008-08-23T23:03:03.703000
24,678
25,124
JavaScript editor within Eclipse
I'm looking for the best JavaScript editor available as an Eclipse plugin. I've been using Spket which is good. But, is there more better one?
Disclaimer, I work at Aptana. I would point out there are some nice features for JS that you might not get so easily elsewhere. One is plugin-level integration of JS libraries that provide CodeAssist, samples, snippets and easy inclusion of the libraries files into your project; we provide the plugins for many of the more commonly used libraries, including YUI, jQuery, Prototype, dojo and EXT JS. Second, we have a server-side JavaScript engine called Jaxer that not only lets you run any of your JS code on the server but adds file, database and networking functionality so that you don't have to use a scripting language but can write the entire app in JS.
JavaScript editor within Eclipse I'm looking for the best JavaScript editor available as an Eclipse plugin. I've been using Spket which is good. But, is there more better one?
TITLE: JavaScript editor within Eclipse QUESTION: I'm looking for the best JavaScript editor available as an Eclipse plugin. I've been using Spket which is good. But, is there more better one? ANSWER: Disclaimer, I work at Aptana. I would point out there are some nice features for JS that you might not get so easily elsewhere. One is plugin-level integration of JS libraries that provide CodeAssist, samples, snippets and easy inclusion of the libraries files into your project; we provide the plugins for many of the more commonly used libraries, including YUI, jQuery, Prototype, dojo and EXT JS. Second, we have a server-side JavaScript engine called Jaxer that not only lets you run any of your JS code on the server but adds file, database and networking functionality so that you don't have to use a scripting language but can write the entire app in JS.
[ "javascript", "eclipse", "plugins", "editor" ]
133
14
104,281
8
0
2008-08-23T22:42:50.757000
2008-08-24T15:52:48.160000
24,680
24,704
Using Subversion with Visual Basic 6
My team is moving from Visual SourceSafe to Subversion soon, while developing/supporting a legacy project in Visual Basic 6.0, so I have a couple of questions: What's the best tool for Subversion IDE integration in Visual Studio 6? (or is it not worth the trouble...) Are there any best practices for using Subversion with Visual Basic 6.0? (file types to ignore, etc.)
I would agree that Tortoise SVN in Windows Explorer would be the best way to use SVN with VB6. The biggest change you will find migrating to SVN is the idea of "Check out" and "Check in" aren't exactly the same as "Update" and "Commit"... thus, any IDE integration with VB6 is limited because VB6 supports MSSCCI, a check-out/check-in mechanism. I once used TamTam SVN ( http://www.daveswebsite.com/software/tamtamsvn/index.shtml ) with Visual Studio 2003, but stopped since I found it limiting. Merging/branching/blaming, etc. are very powerful features Tortoise SVN provides that weren't in TamTam. Tigris also has http://svnvb6.tigris.org/, but I have not tried it. Again, while you quite possibly get an IDE to work with VB6, I would not recommend it since the greatest strength of migrating to SVN is to break the Source Safe philosophy of check-in/check-out.
Using Subversion with Visual Basic 6 My team is moving from Visual SourceSafe to Subversion soon, while developing/supporting a legacy project in Visual Basic 6.0, so I have a couple of questions: What's the best tool for Subversion IDE integration in Visual Studio 6? (or is it not worth the trouble...) Are there any best practices for using Subversion with Visual Basic 6.0? (file types to ignore, etc.)
TITLE: Using Subversion with Visual Basic 6 QUESTION: My team is moving from Visual SourceSafe to Subversion soon, while developing/supporting a legacy project in Visual Basic 6.0, so I have a couple of questions: What's the best tool for Subversion IDE integration in Visual Studio 6? (or is it not worth the trouble...) Are there any best practices for using Subversion with Visual Basic 6.0? (file types to ignore, etc.) ANSWER: I would agree that Tortoise SVN in Windows Explorer would be the best way to use SVN with VB6. The biggest change you will find migrating to SVN is the idea of "Check out" and "Check in" aren't exactly the same as "Update" and "Commit"... thus, any IDE integration with VB6 is limited because VB6 supports MSSCCI, a check-out/check-in mechanism. I once used TamTam SVN ( http://www.daveswebsite.com/software/tamtamsvn/index.shtml ) with Visual Studio 2003, but stopped since I found it limiting. Merging/branching/blaming, etc. are very powerful features Tortoise SVN provides that weren't in TamTam. Tigris also has http://svnvb6.tigris.org/, but I have not tried it. Again, while you quite possibly get an IDE to work with VB6, I would not recommend it since the greatest strength of migrating to SVN is to break the Source Safe philosophy of check-in/check-out.
[ "svn", "vb6" ]
20
16
16,393
7
0
2008-08-23T22:46:06.100000
2008-08-23T23:33:46.610000
24,715
24,754
SQL many-to-many matching
I'm implementing a tagging system for a website. There are multiple tags per object and multiple objects per tag. This is accomplished by maintaining a table with two values per record, one for the ids of the object and the tag. I'm looking to write a query to find the objects that match a given set of tags. Suppose I had the following data (in [object] -> [tags]* format) apple -> fruit red food banana -> fruit yellow food cheese -> yellow food firetruck -> vehicle red If I want to match (red), I should get apple and firetruck. If I want to match (fruit, food) I should get (apple, banana). How do I write a SQL query do do what I want? @Jeremy Ruten, Thanks for your answer. The notation used was used to give some sample data - my database does have a table with 1 object id and 1 tag per record. Second, my problem is that I need to get all objects that match all tags. Substituting your OR for an AND like so: SELECT object WHERE tag = 'fruit' AND tag = 'food'; Yields no results when run.
Given: object table (primary key id) objecttags table (foreign keys objectId, tagid) tags table (primary key id) SELECT distinct o.* from object o join objecttags ot on o.Id = ot.objectid join tags t on ot.tagid = t.id where t.Name = 'fruit' or t.name = 'food'; This seems backwards, since you want and, but the issue is, 2 tags aren't on the same row, and therefore, an and yields nothing, since 1 single row cannot be both a fruit and a food. This query will yield duplicates usually, because you will get 1 row of each object, per tag. If you wish to really do an and in this case, you will need a group by, and a having count = in your query for example. SELECT distinct o.name, count(*) as count from object o join objecttags ot on o.Id = ot.objectid join tags t on ot.tagid = t.id where t.Name = 'fruit' or t.name = 'food' group by o.name having count = 2;
SQL many-to-many matching I'm implementing a tagging system for a website. There are multiple tags per object and multiple objects per tag. This is accomplished by maintaining a table with two values per record, one for the ids of the object and the tag. I'm looking to write a query to find the objects that match a given set of tags. Suppose I had the following data (in [object] -> [tags]* format) apple -> fruit red food banana -> fruit yellow food cheese -> yellow food firetruck -> vehicle red If I want to match (red), I should get apple and firetruck. If I want to match (fruit, food) I should get (apple, banana). How do I write a SQL query do do what I want? @Jeremy Ruten, Thanks for your answer. The notation used was used to give some sample data - my database does have a table with 1 object id and 1 tag per record. Second, my problem is that I need to get all objects that match all tags. Substituting your OR for an AND like so: SELECT object WHERE tag = 'fruit' AND tag = 'food'; Yields no results when run.
TITLE: SQL many-to-many matching QUESTION: I'm implementing a tagging system for a website. There are multiple tags per object and multiple objects per tag. This is accomplished by maintaining a table with two values per record, one for the ids of the object and the tag. I'm looking to write a query to find the objects that match a given set of tags. Suppose I had the following data (in [object] -> [tags]* format) apple -> fruit red food banana -> fruit yellow food cheese -> yellow food firetruck -> vehicle red If I want to match (red), I should get apple and firetruck. If I want to match (fruit, food) I should get (apple, banana). How do I write a SQL query do do what I want? @Jeremy Ruten, Thanks for your answer. The notation used was used to give some sample data - my database does have a table with 1 object id and 1 tag per record. Second, my problem is that I need to get all objects that match all tags. Substituting your OR for an AND like so: SELECT object WHERE tag = 'fruit' AND tag = 'food'; Yields no results when run. ANSWER: Given: object table (primary key id) objecttags table (foreign keys objectId, tagid) tags table (primary key id) SELECT distinct o.* from object o join objecttags ot on o.Id = ot.objectid join tags t on ot.tagid = t.id where t.Name = 'fruit' or t.name = 'food'; This seems backwards, since you want and, but the issue is, 2 tags aren't on the same row, and therefore, an and yields nothing, since 1 single row cannot be both a fruit and a food. This query will yield duplicates usually, because you will get 1 row of each object, per tag. If you wish to really do an and in this case, you will need a group by, and a having count = in your query for example. SELECT distinct o.name, count(*) as count from object o join objecttags ot on o.Id = ot.objectid join tags t on ot.tagid = t.id where t.Name = 'fruit' or t.name = 'food' group by o.name having count = 2;
[ "sql", "many-to-many", "tagging" ]
3
4
5,043
6
0
2008-08-24T00:09:34.760000
2008-08-24T01:02:22.747000
24,723
535,022
Best regex to catch XSS (Cross-site Scripting) attack (in Java)?
Jeff actually posted about this in Sanitize HTML. But his example is in C# and I'm actually more interested in a Java version. Does anyone have a better version for Java? Is his example good enough to just convert directly from C# to Java? [Update] I have put a bounty on this question because SO wasn't as popular when I asked the question as it is today (*). As for anything related to security, the more people look into it, the better it is! (*) In fact, I think it was still in closed beta
Don't do this with regular expressions. Remember, you're not protecting just against valid HTML; you're protecting against the DOM that web browsers create. Browsers can be tricked into producing valid DOM from invalid HTML quite easily. For example, see this list of obfuscated XSS attacks. Are you prepared to tailor a regex to prevent this real world attack on Yahoo and Hotmail on IE6/7/8? How about this attack that works on IE6? How about attacks that are not listed on this site? The problem with Jeff's approach is that it's not a whitelist, as claimed. As someone on that page adeptly notes: The problem with it, is that the html must be clean. There are cases where you can pass in hacked html, and it won't match it, in which case it'll return the hacked html string as it won't match anything to replace. This isn't strictly whitelisting. I would suggest a purpose built tool like AntiSamy. It works by actually parsing the HTML, and then traversing the DOM and removing anything that's not in the configurable whitelist. The major difference is the ability to gracefully handle malformed HTML. The best part is that it actually unit tests for all the XSS attacks on the above site. Besides, what could be easier than this API call: public String toSafeHtml(String html) throws ScanException, PolicyException { Policy policy = Policy.getInstance(POLICY_FILE); AntiSamy antiSamy = new AntiSamy(); CleanResults cleanResults = antiSamy.scan(html, policy); return cleanResults.getCleanHTML().trim(); }
Best regex to catch XSS (Cross-site Scripting) attack (in Java)? Jeff actually posted about this in Sanitize HTML. But his example is in C# and I'm actually more interested in a Java version. Does anyone have a better version for Java? Is his example good enough to just convert directly from C# to Java? [Update] I have put a bounty on this question because SO wasn't as popular when I asked the question as it is today (*). As for anything related to security, the more people look into it, the better it is! (*) In fact, I think it was still in closed beta
TITLE: Best regex to catch XSS (Cross-site Scripting) attack (in Java)? QUESTION: Jeff actually posted about this in Sanitize HTML. But his example is in C# and I'm actually more interested in a Java version. Does anyone have a better version for Java? Is his example good enough to just convert directly from C# to Java? [Update] I have put a bounty on this question because SO wasn't as popular when I asked the question as it is today (*). As for anything related to security, the more people look into it, the better it is! (*) In fact, I think it was still in closed beta ANSWER: Don't do this with regular expressions. Remember, you're not protecting just against valid HTML; you're protecting against the DOM that web browsers create. Browsers can be tricked into producing valid DOM from invalid HTML quite easily. For example, see this list of obfuscated XSS attacks. Are you prepared to tailor a regex to prevent this real world attack on Yahoo and Hotmail on IE6/7/8? How about this attack that works on IE6? How about attacks that are not listed on this site? The problem with Jeff's approach is that it's not a whitelist, as claimed. As someone on that page adeptly notes: The problem with it, is that the html must be clean. There are cases where you can pass in hacked html, and it won't match it, in which case it'll return the hacked html string as it won't match anything to replace. This isn't strictly whitelisting. I would suggest a purpose built tool like AntiSamy. It works by actually parsing the HTML, and then traversing the DOM and removing anything that's not in the configurable whitelist. The major difference is the ability to gracefully handle malformed HTML. The best part is that it actually unit tests for all the XSS attacks on the above site. Besides, what could be easier than this API call: public String toSafeHtml(String html) throws ScanException, PolicyException { Policy policy = Policy.getInstance(POLICY_FILE); AntiSamy antiSamy = new AntiSamy(); CleanResults cleanResults = antiSamy.scan(html, policy); return cleanResults.getCleanHTML().trim(); }
[ "java", "html", "regex", "xss" ]
34
81
101,367
10
0
2008-08-24T00:21:10.413000
2009-02-11T00:59:10.610000
24,730
24,744
What is this 'Multiple-step OLE DB' error?
I'm doing a little bit of work on a horrid piece of software built by Bangalores best. It's written in mostly classic ASP/VbScript, but "ported" to ASP.NET, though most of the code is classic ASP style in the ASPX pages:( I'm getting this message when it tries to connect to my local database: Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done. Line 38: MasterConn = New ADODB.Connection() Line 39: MasterConn.connectiontimeout = 10000 Line 40: MasterConn.Open(strDB) Anybody have a clue what this error means? Its connecting to my local machine (running SQLEXPRESS) using this connection string: PROVIDER=MSDASQL;DRIVER={SQL Server};Server=JONATHAN-PC\SQLEXPRESS\;DATABASE=NetTraining;Integrated Security=true Which is the connection string that it was initially using, I just repointed it at my database. UPDATE: The issue was using "Integrated Security" with ADO. I changed to using a user account and it connected just fine.
I ran into this a long time ago with working in ASP. I found this knowledge base article and it helped me out. I hope it solves your problem. http://support.microsoft.com/kb/269495 If this doesn't work and everything checks out, then it is probably your connection string. I would try these steps next: Remove: DRIVER={SQL Server}; Edit the Provider to this: Provider=SQLOLEDB;
What is this 'Multiple-step OLE DB' error? I'm doing a little bit of work on a horrid piece of software built by Bangalores best. It's written in mostly classic ASP/VbScript, but "ported" to ASP.NET, though most of the code is classic ASP style in the ASPX pages:( I'm getting this message when it tries to connect to my local database: Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done. Line 38: MasterConn = New ADODB.Connection() Line 39: MasterConn.connectiontimeout = 10000 Line 40: MasterConn.Open(strDB) Anybody have a clue what this error means? Its connecting to my local machine (running SQLEXPRESS) using this connection string: PROVIDER=MSDASQL;DRIVER={SQL Server};Server=JONATHAN-PC\SQLEXPRESS\;DATABASE=NetTraining;Integrated Security=true Which is the connection string that it was initially using, I just repointed it at my database. UPDATE: The issue was using "Integrated Security" with ADO. I changed to using a user account and it connected just fine.
TITLE: What is this 'Multiple-step OLE DB' error? QUESTION: I'm doing a little bit of work on a horrid piece of software built by Bangalores best. It's written in mostly classic ASP/VbScript, but "ported" to ASP.NET, though most of the code is classic ASP style in the ASPX pages:( I'm getting this message when it tries to connect to my local database: Multiple-step OLE DB operation generated errors. Check each OLE DB status value, if available. No work was done. Line 38: MasterConn = New ADODB.Connection() Line 39: MasterConn.connectiontimeout = 10000 Line 40: MasterConn.Open(strDB) Anybody have a clue what this error means? Its connecting to my local machine (running SQLEXPRESS) using this connection string: PROVIDER=MSDASQL;DRIVER={SQL Server};Server=JONATHAN-PC\SQLEXPRESS\;DATABASE=NetTraining;Integrated Security=true Which is the connection string that it was initially using, I just repointed it at my database. UPDATE: The issue was using "Integrated Security" with ADO. I changed to using a user account and it connected just fine. ANSWER: I ran into this a long time ago with working in ASP. I found this knowledge base article and it helped me out. I hope it solves your problem. http://support.microsoft.com/kb/269495 If this doesn't work and everything checks out, then it is probably your connection string. I would try these steps next: Remove: DRIVER={SQL Server}; Edit the Provider to this: Provider=SQLOLEDB;
[ "asp-classic", "oledb", "ado" ]
3
4
13,127
3
0
2008-08-24T00:35:22.390000
2008-08-24T00:49:21.233000
24,731
24,743
Displaying version of underlying software in footer of web app?
I am thinking about providing a version of say, the database schema and the dlls for business logic in the footer of my web application. Is this advised? Are there any pitfalls, or pointers of how to do this best? Usability concerns? I already have a version scheme, for both schema and dlls, used in my CI solution.
I quite like what is done e.g. here. If you look towards the bottom of the page, there's a piece of text "powered by eve community". If you click that text you get a small chunk of technical information. To me, this is a nice tradeoff between having the (useful) information readily available (for bug reports, etc.) and having to have (unpleasant) technical jargon visible to users of the site.
Displaying version of underlying software in footer of web app? I am thinking about providing a version of say, the database schema and the dlls for business logic in the footer of my web application. Is this advised? Are there any pitfalls, or pointers of how to do this best? Usability concerns? I already have a version scheme, for both schema and dlls, used in my CI solution.
TITLE: Displaying version of underlying software in footer of web app? QUESTION: I am thinking about providing a version of say, the database schema and the dlls for business logic in the footer of my web application. Is this advised? Are there any pitfalls, or pointers of how to do this best? Usability concerns? I already have a version scheme, for both schema and dlls, used in my CI solution. ANSWER: I quite like what is done e.g. here. If you look towards the bottom of the page, there's a piece of text "powered by eve community". If you click that text you get a small chunk of technical information. To me, this is a nice tradeoff between having the (useful) information readily available (for bug reports, etc.) and having to have (unpleasant) technical jargon visible to users of the site.
[ "web-applications", "assemblies", "versioning" ]
5
6
2,175
3
0
2008-08-24T00:38:00.653000
2008-08-24T00:48:37.913000
24,734
24,755
SelectNodes not working on stackoverflow feed
I'm trying to add support for stackoverflow feeds in my rss reader but SelectNodes and SelectSingleNode have no effect. This is probably something to do with ATOM and xml namespaces that I just don't understand yet. I have gotten it to work by removing all attributes from the feed tag, but that's a hack and I would like to do it properly. So, how do you use SelectNodes with atom feeds? Here's a snippet of the feed. StackOverflow.com - Questions tagged: c Check out the latest from StackOverflow.com 2008-08-24T12:25:30Z http://stackoverflow.com/feeds/tag/c http://www.creativecommons.org/licenses/by-nc/2.5/rdf http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server What is the best way to communicate with a SQL server? Ed 2008-08-22T05:09:04Z 2008-08-23T04:52:39Z <p>I am going to be using c/c++, and would like to know the best way to talk to a MySQL server. Should I use the library that comes with the server installation? Are they any good libraries I should consider other than the official one?</p> 2 The Solution XmlDocument doc = new XmlDocument(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom"); doc.Load(feed); // successful XmlNodeList itemList = doc.DocumentElement.SelectNodes("atom:entry", nsmgr);
Don't confuse the namespace names in the XML file with the namespace names for your namespace manager. They're both shortcuts, and they don't necessarily have to match. So you can register " http://www.w3.org/2005/Atom " as "atom", and then do a SelectNodes for "atom:entry".
SelectNodes not working on stackoverflow feed I'm trying to add support for stackoverflow feeds in my rss reader but SelectNodes and SelectSingleNode have no effect. This is probably something to do with ATOM and xml namespaces that I just don't understand yet. I have gotten it to work by removing all attributes from the feed tag, but that's a hack and I would like to do it properly. So, how do you use SelectNodes with atom feeds? Here's a snippet of the feed. StackOverflow.com - Questions tagged: c Check out the latest from StackOverflow.com 2008-08-24T12:25:30Z http://stackoverflow.com/feeds/tag/c http://www.creativecommons.org/licenses/by-nc/2.5/rdf http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server What is the best way to communicate with a SQL server? Ed 2008-08-22T05:09:04Z 2008-08-23T04:52:39Z <p>I am going to be using c/c++, and would like to know the best way to talk to a MySQL server. Should I use the library that comes with the server installation? Are they any good libraries I should consider other than the official one?</p> 2 The Solution XmlDocument doc = new XmlDocument(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom"); doc.Load(feed); // successful XmlNodeList itemList = doc.DocumentElement.SelectNodes("atom:entry", nsmgr);
TITLE: SelectNodes not working on stackoverflow feed QUESTION: I'm trying to add support for stackoverflow feeds in my rss reader but SelectNodes and SelectSingleNode have no effect. This is probably something to do with ATOM and xml namespaces that I just don't understand yet. I have gotten it to work by removing all attributes from the feed tag, but that's a hack and I would like to do it properly. So, how do you use SelectNodes with atom feeds? Here's a snippet of the feed. StackOverflow.com - Questions tagged: c Check out the latest from StackOverflow.com 2008-08-24T12:25:30Z http://stackoverflow.com/feeds/tag/c http://www.creativecommons.org/licenses/by-nc/2.5/rdf http://stackoverflow.com/questions/22901/what-is-the-best-way-to-communicate-with-a-sql-server What is the best way to communicate with a SQL server? Ed 2008-08-22T05:09:04Z 2008-08-23T04:52:39Z <p>I am going to be using c/c++, and would like to know the best way to talk to a MySQL server. Should I use the library that comes with the server installation? Are they any good libraries I should consider other than the official one?</p> 2 The Solution XmlDocument doc = new XmlDocument(); XmlNamespaceManager nsmgr = new XmlNamespaceManager(doc.NameTable); nsmgr.AddNamespace("atom", "http://www.w3.org/2005/Atom"); doc.Load(feed); // successful XmlNodeList itemList = doc.DocumentElement.SelectNodes("atom:entry", nsmgr); ANSWER: Don't confuse the namespace names in the XML file with the namespace names for your namespace manager. They're both shortcuts, and they don't necessarily have to match. So you can register " http://www.w3.org/2005/Atom " as "atom", and then do a SelectNodes for "atom:entry".
[ "c#", ".net", "rss", "atom-feed" ]
16
9
8,518
4
0
2008-08-24T00:40:48.773000
2008-08-24T01:03:03.587000
24,772
24,783
How do I write a Firefox Addon?
What are some resources for getting started writing a Firefox Addon? Is there an API guide somewhere? Is there a getting started tutorial somewhere? Is there a developer discussion board somewhere?
We tried to make https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions answer all those questions. The first three links in the documentation section are about getting started (that includes something like Adam's link, before it became stale). The newsgroup and the irc channel in the Community section are the official discussion boards. Mozilla is very complex, so any kind of API guide would be overwhelming and hard to write. So your best bet is to check the code snippets page (also linked from the MDC Extensions page), then search MDC/google, then ask in the forums.
How do I write a Firefox Addon? What are some resources for getting started writing a Firefox Addon? Is there an API guide somewhere? Is there a getting started tutorial somewhere? Is there a developer discussion board somewhere?
TITLE: How do I write a Firefox Addon? QUESTION: What are some resources for getting started writing a Firefox Addon? Is there an API guide somewhere? Is there a getting started tutorial somewhere? Is there a developer discussion board somewhere? ANSWER: We tried to make https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions answer all those questions. The first three links in the documentation section are about getting started (that includes something like Adam's link, before it became stale). The newsgroup and the irc channel in the Community section are the official discussion boards. Mozilla is very complex, so any kind of API guide would be overwhelming and hard to write. So your best bet is to check the code snippets page (also linked from the MDC Extensions page), then search MDC/google, then ask in the forums.
[ "firefox", "firefox-addon", "add-on" ]
145
98
88,639
6
0
2008-08-24T01:26:34.467000
2008-08-24T01:42:07.893000
24,797
25,073
Effectively Converting dates between UTC and Local (ie. PST) time in SQL 2005
What is the best way to convert a UTC datetime into local datetime. It isn't as simple as a getutcdate() and getdate() difference because the difference changes depending on what the date is. CLR integration isn't an option for me either. The solution that I had come up with for this problem a few months back was to have a daylight savings time table that stored the beginning and ending daylight savings days for the next 100 or so years, this solution seemed inelegant but conversions were quick (simple table lookup)
Create two tables and then join to them to convert stored GMT dates to local time: TimeZones e.g. --------- ---- TimeZoneId 19 Name Eastern (GMT -5) Offset -5 Create the daylight savings table and populate it with as much information as you can (local laws change all the time so there's no way to predict what the data will look like years in the future) DaylightSavings --------------- TimeZoneId 19 BeginDst 3/9/2008 2:00 AM EndDst 11/2/2008 2:00 AM Join them like this: inner join TimeZones tz on x.TimeZoneId=tz.TimeZoneId left join DaylightSavings ds on tz.TimeZoneId=ds.LocalTimeZone and x.TheDateToConvert between ds.BeginDst and ds.EndDst Convert dates like this: dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, TheDateToConvert)
Effectively Converting dates between UTC and Local (ie. PST) time in SQL 2005 What is the best way to convert a UTC datetime into local datetime. It isn't as simple as a getutcdate() and getdate() difference because the difference changes depending on what the date is. CLR integration isn't an option for me either. The solution that I had come up with for this problem a few months back was to have a daylight savings time table that stored the beginning and ending daylight savings days for the next 100 or so years, this solution seemed inelegant but conversions were quick (simple table lookup)
TITLE: Effectively Converting dates between UTC and Local (ie. PST) time in SQL 2005 QUESTION: What is the best way to convert a UTC datetime into local datetime. It isn't as simple as a getutcdate() and getdate() difference because the difference changes depending on what the date is. CLR integration isn't an option for me either. The solution that I had come up with for this problem a few months back was to have a daylight savings time table that stored the beginning and ending daylight savings days for the next 100 or so years, this solution seemed inelegant but conversions were quick (simple table lookup) ANSWER: Create two tables and then join to them to convert stored GMT dates to local time: TimeZones e.g. --------- ---- TimeZoneId 19 Name Eastern (GMT -5) Offset -5 Create the daylight savings table and populate it with as much information as you can (local laws change all the time so there's no way to predict what the data will look like years in the future) DaylightSavings --------------- TimeZoneId 19 BeginDst 3/9/2008 2:00 AM EndDst 11/2/2008 2:00 AM Join them like this: inner join TimeZones tz on x.TimeZoneId=tz.TimeZoneId left join DaylightSavings ds on tz.TimeZoneId=ds.LocalTimeZone and x.TheDateToConvert between ds.BeginDst and ds.EndDst Convert dates like this: dateadd(hh, tz.Offset + case when ds.LocalTimeZone is not null then 1 else 0 end, TheDateToConvert)
[ "sql-server" ]
30
29
81,514
13
0
2008-08-24T02:08:15.553000
2008-08-24T14:17:17.423000
24,812
24,927
Recommendations needed for good AI references
I've been asked to help out on an XNA project with the AI. I'm not totally new to the concepts (pathfinding, flocking, etc.) but this would be the first "real" code. I'd be very thankful for any resources (links or books); I want to make sure I do this right.
These links might be useful to check out, for a beginning (even if most are mostly game-oriented): http://www.a-i.com http://www.kynogon.com http://openai.sourceforge.net http://www.botspot.com http://aigamedev.com http://www.aiwisdom.com http://igda.org/ai/ http://gamedev.net and http://www.gameai.com, who has already been mentioned..
Recommendations needed for good AI references I've been asked to help out on an XNA project with the AI. I'm not totally new to the concepts (pathfinding, flocking, etc.) but this would be the first "real" code. I'd be very thankful for any resources (links or books); I want to make sure I do this right.
TITLE: Recommendations needed for good AI references QUESTION: I've been asked to help out on an XNA project with the AI. I'm not totally new to the concepts (pathfinding, flocking, etc.) but this would be the first "real" code. I'd be very thankful for any resources (links or books); I want to make sure I do this right. ANSWER: These links might be useful to check out, for a beginning (even if most are mostly game-oriented): http://www.a-i.com http://www.kynogon.com http://openai.sourceforge.net http://www.botspot.com http://aigamedev.com http://www.aiwisdom.com http://igda.org/ai/ http://gamedev.net and http://www.gameai.com, who has already been mentioned..
[ "xna", "artificial-intelligence" ]
23
6
1,982
13
0
2008-08-24T02:40:19.097000
2008-08-24T08:36:14.590000
24,813
24,825
Automating MSI Build Process
Does anyone have a good way to build MSI (vdproj) projects using MsBuild or Nant? I know one answer was to install Visual Studio on the build server and just use devenv.exe to build the project, but, I prefer not to install Visual Studio on our build servers.
Short of the method you mentioned above (devenv), there is no way to do this with the current version of MSBuild. The method the Visual Studio team uses to run their MSI builds is with Windows Installer XML. You can learn more about using WiX to deploy setup packages here. Please note WiX doesn't support vdproj files so it means you'll be recreating your installer projects. Edit: Looks like I was beat to the chase when grabbing my references:)
Automating MSI Build Process Does anyone have a good way to build MSI (vdproj) projects using MsBuild or Nant? I know one answer was to install Visual Studio on the build server and just use devenv.exe to build the project, but, I prefer not to install Visual Studio on our build servers.
TITLE: Automating MSI Build Process QUESTION: Does anyone have a good way to build MSI (vdproj) projects using MsBuild or Nant? I know one answer was to install Visual Studio on the build server and just use devenv.exe to build the project, but, I prefer not to install Visual Studio on our build servers. ANSWER: Short of the method you mentioned above (devenv), there is no way to do this with the current version of MSBuild. The method the Visual Studio team uses to run their MSI builds is with Windows Installer XML. You can learn more about using WiX to deploy setup packages here. Please note WiX doesn't support vdproj files so it means you'll be recreating your installer projects. Edit: Looks like I was beat to the chase when grabbing my references:)
[ "build-process", "build-automation" ]
11
8
2,884
2
0
2008-08-24T02:42:07.797000
2008-08-24T03:11:46.400000
24,816
25,207
Escaping HTML strings with jQuery
Does anyone know of an easy way to escape HTML from strings in jQuery? I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks). I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this.
Since you're using jQuery, you can just set the element's text property: // before: // text var someHtmlString = " "; // set a DIV's text: $("div.someClass").text(someHtmlString); // after: // <script>alert('hi!');</script> // get the text in a string: var escaped = $(" ").text(someHtmlString).html(); // value: // <script>alert('hi!');</script>
Escaping HTML strings with jQuery Does anyone know of an easy way to escape HTML from strings in jQuery? I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks). I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this.
TITLE: Escaping HTML strings with jQuery QUESTION: Does anyone know of an easy way to escape HTML from strings in jQuery? I need to be able to pass an arbitrary string and have it properly escaped for display in an HTML page (preventing JavaScript/HTML injection attacks). I'm sure it's possible to extend jQuery to do this, but I don't know enough about the framework at the moment to accomplish this. ANSWER: Since you're using jQuery, you can just set the element's text property: // before: // text var someHtmlString = " "; // set a DIV's text: $("div.someClass").text(someHtmlString); // after: // <script>alert('hi!');</script> // get the text in a string: var escaped = $(" ").text(someHtmlString).html(); // value: // <script>alert('hi!');</script>
[ "javascript", "jquery", "string", "escaping" ]
657
486
771,985
27
0
2008-08-24T02:52:42.280000
2008-08-24T17:22:15.480000
24,823
25,016
Implementing a custom Windows Workflow activity that executes an asynchronous operation
I'm having some conceptual trouble on figuring out how to best implement this... I want to create a custom Activity class for Windows Workflow. The activity has to call out to a third party library method that itself runs another process asynchronously and may take anywhere from seconds to many hours to complete. This library offers the ability for me to either poll for the method result or to subscribe to an event that indicates its completion. In my non-workflow apps, I typically just subscribe to that event, but that doesn't seem to be reasonable in the workflow case. I'm also not sure exactly how to best implement a polling scheme. Can someone recommend some pointers to similar problems?
Kirk Allen Evans wrote an interesting blog about this with some pretty good code examples.
Implementing a custom Windows Workflow activity that executes an asynchronous operation I'm having some conceptual trouble on figuring out how to best implement this... I want to create a custom Activity class for Windows Workflow. The activity has to call out to a third party library method that itself runs another process asynchronously and may take anywhere from seconds to many hours to complete. This library offers the ability for me to either poll for the method result or to subscribe to an event that indicates its completion. In my non-workflow apps, I typically just subscribe to that event, but that doesn't seem to be reasonable in the workflow case. I'm also not sure exactly how to best implement a polling scheme. Can someone recommend some pointers to similar problems?
TITLE: Implementing a custom Windows Workflow activity that executes an asynchronous operation QUESTION: I'm having some conceptual trouble on figuring out how to best implement this... I want to create a custom Activity class for Windows Workflow. The activity has to call out to a third party library method that itself runs another process asynchronously and may take anywhere from seconds to many hours to complete. This library offers the ability for me to either poll for the method result or to subscribe to an event that indicates its completion. In my non-workflow apps, I typically just subscribe to that event, but that doesn't seem to be reasonable in the workflow case. I'm also not sure exactly how to best implement a polling scheme. Can someone recommend some pointers to similar problems? ANSWER: Kirk Allen Evans wrote an interesting blog about this with some pretty good code examples.
[ "asynchronous", "workflow", "workflow-foundation", "workflow-activity" ]
0
1
1,073
1
0
2008-08-24T03:05:47.303000
2008-08-24T12:51:43.617000
24,829
24,876
How does .net managed memory handle value types inside objects?
public class MyClass { public int Age; public int ID; } public void MyMethod() { MyClass m = new MyClass(); int newID; } To my understanding, the following is true: The reference m lives on the stack and goes out of scope when MyMethod() exits. The value type newID lives on the stack and goes out of scope when MyMethod() exits. The object created by the new operator lives in the heap and becomes reclaimable by the GC when MyMethod() exits, assuming no other reference to the object exists. Here is my question: Do value types within objects live on the stack or the heap? Is boxing/unboxing value types in an object a concern? Are there any detailed, yet understandable, resources on this topic? Logically, I'd think value types inside classes would be in the heap, but I'm not sure if they have to be boxed to get there. Edit: Suggested reading for this topic: CLR Via C# by Jeffrey Richter Essential.NET by Don Box
Value-type values for a class have to live together with the object instance in the managed heap. The thread's stack for a method only lives for the duration of a method; how can the value persist if it only exists within that stack? A class' object size in the managed heap is the sum of its value-type fields, reference-type pointers, and additional CLR overhead variables like the Sync block index. When one assigns a value to an object's value-type field, the CLR copies the value to the space allocated within the object for that particluar field. Take for example, a simple class with a single field. public class EmbeddedValues { public int NumberField; } And with it, a simple testing class. public class EmbeddedTest { public void TestEmbeddedValues() { EmbeddedValues valueContainer = new EmbeddedValues(); valueContainer.NumberField = 20; int publicField = valueContainer.NumberField; } } If you use the MSIL Disassembler provided by the.NET Framework SDK to peek at the IL code for EmbeddedTest.TestEmbeddedValues().method public hidebysig instance void TestEmbeddedValues() cil managed { // Code size 23 (0x17).maxstack 2.locals init ([0] class soapextensions.EmbeddedValues valueContainer, [1] int32 publicField) IL_0000: nop IL_0001: newobj instance void soapextensions.EmbeddedValues::.ctor() IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.s 20 IL_000a: stfld int32 soapextensions.EmbeddedValues::NumberField IL_000f: ldloc.0 IL_0010: ldfld int32 soapextensions.EmbeddedValues::NumberField IL_0015: stloc.1 IL_0016: ret } // end of method EmbeddedTest::TestEmbeddedValues Notice the CLR is being told to stfld the loaded value of "20" in the stack to the loaded EmbeddValues' NumberField field location, directly into the managed heap. Similarly, when retrieving the value, it uses ldfld instruction to directly copy the value out of that managed heap location into the thread stack. No box/unboxing happens with these types of operations.
How does .net managed memory handle value types inside objects? public class MyClass { public int Age; public int ID; } public void MyMethod() { MyClass m = new MyClass(); int newID; } To my understanding, the following is true: The reference m lives on the stack and goes out of scope when MyMethod() exits. The value type newID lives on the stack and goes out of scope when MyMethod() exits. The object created by the new operator lives in the heap and becomes reclaimable by the GC when MyMethod() exits, assuming no other reference to the object exists. Here is my question: Do value types within objects live on the stack or the heap? Is boxing/unboxing value types in an object a concern? Are there any detailed, yet understandable, resources on this topic? Logically, I'd think value types inside classes would be in the heap, but I'm not sure if they have to be boxed to get there. Edit: Suggested reading for this topic: CLR Via C# by Jeffrey Richter Essential.NET by Don Box
TITLE: How does .net managed memory handle value types inside objects? QUESTION: public class MyClass { public int Age; public int ID; } public void MyMethod() { MyClass m = new MyClass(); int newID; } To my understanding, the following is true: The reference m lives on the stack and goes out of scope when MyMethod() exits. The value type newID lives on the stack and goes out of scope when MyMethod() exits. The object created by the new operator lives in the heap and becomes reclaimable by the GC when MyMethod() exits, assuming no other reference to the object exists. Here is my question: Do value types within objects live on the stack or the heap? Is boxing/unboxing value types in an object a concern? Are there any detailed, yet understandable, resources on this topic? Logically, I'd think value types inside classes would be in the heap, but I'm not sure if they have to be boxed to get there. Edit: Suggested reading for this topic: CLR Via C# by Jeffrey Richter Essential.NET by Don Box ANSWER: Value-type values for a class have to live together with the object instance in the managed heap. The thread's stack for a method only lives for the duration of a method; how can the value persist if it only exists within that stack? A class' object size in the managed heap is the sum of its value-type fields, reference-type pointers, and additional CLR overhead variables like the Sync block index. When one assigns a value to an object's value-type field, the CLR copies the value to the space allocated within the object for that particluar field. Take for example, a simple class with a single field. public class EmbeddedValues { public int NumberField; } And with it, a simple testing class. public class EmbeddedTest { public void TestEmbeddedValues() { EmbeddedValues valueContainer = new EmbeddedValues(); valueContainer.NumberField = 20; int publicField = valueContainer.NumberField; } } If you use the MSIL Disassembler provided by the.NET Framework SDK to peek at the IL code for EmbeddedTest.TestEmbeddedValues().method public hidebysig instance void TestEmbeddedValues() cil managed { // Code size 23 (0x17).maxstack 2.locals init ([0] class soapextensions.EmbeddedValues valueContainer, [1] int32 publicField) IL_0000: nop IL_0001: newobj instance void soapextensions.EmbeddedValues::.ctor() IL_0006: stloc.0 IL_0007: ldloc.0 IL_0008: ldc.i4.s 20 IL_000a: stfld int32 soapextensions.EmbeddedValues::NumberField IL_000f: ldloc.0 IL_0010: ldfld int32 soapextensions.EmbeddedValues::NumberField IL_0015: stloc.1 IL_0016: ret } // end of method EmbeddedTest::TestEmbeddedValues Notice the CLR is being told to stfld the loaded value of "20" in the stack to the loaded EmbeddValues' NumberField field location, directly into the managed heap. Similarly, when retrieving the value, it uses ldfld instruction to directly copy the value out of that managed heap location into the thread stack. No box/unboxing happens with these types of operations.
[ ".net", "memory" ]
5
9
3,039
6
0
2008-08-24T03:37:47.490000
2008-08-24T06:11:55.997000
24,849
24,852
Execute script after specific delay using JavaScript
Is there any JavaScript method similar to the jQuery delay() or wait() (to delay the execution of a script for a specific amount of time)?
There is the following: setTimeout(function, milliseconds); function which can be passed the time after which the function will be executed. See: Window setTimeout() Method.
Execute script after specific delay using JavaScript Is there any JavaScript method similar to the jQuery delay() or wait() (to delay the execution of a script for a specific amount of time)?
TITLE: Execute script after specific delay using JavaScript QUESTION: Is there any JavaScript method similar to the jQuery delay() or wait() (to delay the execution of a script for a specific amount of time)? ANSWER: There is the following: setTimeout(function, milliseconds); function which can be passed the time after which the function will be executed. See: Window setTimeout() Method.
[ "javascript", "settimeout" ]
204
196
486,631
15
0
2008-08-24T05:10:57.347000
2008-08-24T05:18:18.467000
24,853
24,858
What is the difference between ++i and i++?
In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop?
++i will increment the value of i, and then return the incremented value. i = 1; j = ++i; (i is 2, j is 2) i++ will increment the value of i, but return the original value that i held before being incremented. i = 1; j = i++; (i is 2, j is 1) For a for loop, either works. ++i seems more common, perhaps because that is what is used in K&R. In any case, follow the guideline "prefer ++i over i++ " and you won't go wrong. There's a couple of comments regarding the efficiency of ++i and i++. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical. The efficiency question is interesting... here's my attempt at an answer: Is there a performance difference between i++ and ++i in C? As @OnFreund notes, it's different for a C++ object, since operator++() is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value.
What is the difference between ++i and i++? In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop?
TITLE: What is the difference between ++i and i++? QUESTION: In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop? ANSWER: ++i will increment the value of i, and then return the incremented value. i = 1; j = ++i; (i is 2, j is 2) i++ will increment the value of i, but return the original value that i held before being incremented. i = 1; j = i++; (i is 2, j is 1) For a for loop, either works. ++i seems more common, perhaps because that is what is used in K&R. In any case, follow the guideline "prefer ++i over i++ " and you won't go wrong. There's a couple of comments regarding the efficiency of ++i and i++. In any non-student-project compiler, there will be no performance difference. You can verify this by looking at the generated code, which will be identical. The efficiency question is interesting... here's my attempt at an answer: Is there a performance difference between i++ and ++i in C? As @OnFreund notes, it's different for a C++ object, since operator++() is a function and the compiler can't know to optimize away the creation of a temporary object to hold the intermediate value.
[ "c", "for-loop", "post-increment", "pre-increment" ]
1,167
1,430
1,698,453
21
0
2008-08-24T05:19:19.713000
2008-08-24T05:23:18.487000
24,866
24,902
Is it essential that I use libraries to manipulate XML?
I am using Java back end for creating an XML string which is passed to the browser. Currently I am using simple string manipulation to produce this XML. Is it essential that I use some XML library in Java to produce the XML string? I find the libraries very difficult to use compared to what I need.
It's not essential, but advisable. However, if string manipulation works for you, then go for it! There are plenty of cases where small or simple XML text can be safely built by hand. Just be aware that creating XML text is harder than it looks. Here's some criteria I would consider: First: how much control do you have on the information that goes into the xml? The less control you have on the source data, the more likely you will have trouble, and the more advantageous the library becomes. For example: (a) Can you guarantee that the element names will never have a character that is illegal in a name? (b) How about quotes in an attribute's content? Can they happen, and are you handling them? (c) Does the data ever contain anything that might need to be encoded as an entity (like the less-than which often needs to be output as < ); are you doing it correctly? Second, maintainability: is the code that builds the XML easy to understand by someone else? You probably don't want to be stuck with the code for life. I've worked with second-hand C++ code that hand-builds XML and it can be surprisingly obscure. Of course, if this is a personal project of yours, then you don't need to worry about "others": substitute "in a year" for "others" above. I wouldn't worry about performance. If your XML is simple enough that you can hand-write it, any overhead from the library is probably meaningless. Of course, your case might be different, but you should measure to prove it first. Finally, Yes; you can hand build XML text by hand if it's simple enough; but not knowing the libraries available is probably not the right reason. A modern XML library is a quite powerful tool, but it can also be daunting. However, learning the essentials of your XML library is not that hard, and it can be quite handy; among other things, it's almost a requisite in today's job marketplace. Just don't get bogged down by namespaces, schemas and other fancier features until you get the essentials. Good luck.
Is it essential that I use libraries to manipulate XML? I am using Java back end for creating an XML string which is passed to the browser. Currently I am using simple string manipulation to produce this XML. Is it essential that I use some XML library in Java to produce the XML string? I find the libraries very difficult to use compared to what I need.
TITLE: Is it essential that I use libraries to manipulate XML? QUESTION: I am using Java back end for creating an XML string which is passed to the browser. Currently I am using simple string manipulation to produce this XML. Is it essential that I use some XML library in Java to produce the XML string? I find the libraries very difficult to use compared to what I need. ANSWER: It's not essential, but advisable. However, if string manipulation works for you, then go for it! There are plenty of cases where small or simple XML text can be safely built by hand. Just be aware that creating XML text is harder than it looks. Here's some criteria I would consider: First: how much control do you have on the information that goes into the xml? The less control you have on the source data, the more likely you will have trouble, and the more advantageous the library becomes. For example: (a) Can you guarantee that the element names will never have a character that is illegal in a name? (b) How about quotes in an attribute's content? Can they happen, and are you handling them? (c) Does the data ever contain anything that might need to be encoded as an entity (like the less-than which often needs to be output as < ); are you doing it correctly? Second, maintainability: is the code that builds the XML easy to understand by someone else? You probably don't want to be stuck with the code for life. I've worked with second-hand C++ code that hand-builds XML and it can be surprisingly obscure. Of course, if this is a personal project of yours, then you don't need to worry about "others": substitute "in a year" for "others" above. I wouldn't worry about performance. If your XML is simple enough that you can hand-write it, any overhead from the library is probably meaningless. Of course, your case might be different, but you should measure to prove it first. Finally, Yes; you can hand build XML text by hand if it's simple enough; but not knowing the libraries available is probably not the right reason. A modern XML library is a quite powerful tool, but it can also be daunting. However, learning the essentials of your XML library is not that hard, and it can be quite handy; among other things, it's almost a requisite in today's job marketplace. Just don't get bogged down by namespaces, schemas and other fancier features until you get the essentials. Good luck.
[ "java", "xml" ]
11
12
797
11
0
2008-08-24T05:48:22.090000
2008-08-24T07:17:49.817000
24,881
24,882
How do I fix "for loop initial declaration used outside C99 mode" GCC error?
I'm trying to solve the 3n+1 problem and I have a for loop that looks like this: for(int i = low; i <= high; ++i) { res = runalg(i); if (res > highestres) { highestres = res; } } Unfortunately I'm getting this error when I try to compile with GCC: 3np1.c:15: error: 'for' loop initial declaration used outside C99 mode I don't know what C99 mode is. Any ideas?
I'd try to declare i outside of the loop! Good luck on solving 3n+1:-) Here's an example: #include int main() { int i; /* for loop execution */ for (i = 10; i < 20; i++) { printf("i: %d\n", i); } return 0; } Read more on for loops in C here.
How do I fix "for loop initial declaration used outside C99 mode" GCC error? I'm trying to solve the 3n+1 problem and I have a for loop that looks like this: for(int i = low; i <= high; ++i) { res = runalg(i); if (res > highestres) { highestres = res; } } Unfortunately I'm getting this error when I try to compile with GCC: 3np1.c:15: error: 'for' loop initial declaration used outside C99 mode I don't know what C99 mode is. Any ideas?
TITLE: How do I fix "for loop initial declaration used outside C99 mode" GCC error? QUESTION: I'm trying to solve the 3n+1 problem and I have a for loop that looks like this: for(int i = low; i <= high; ++i) { res = runalg(i); if (res > highestres) { highestres = res; } } Unfortunately I'm getting this error when I try to compile with GCC: 3np1.c:15: error: 'for' loop initial declaration used outside C99 mode I don't know what C99 mode is. Any ideas? ANSWER: I'd try to declare i outside of the loop! Good luck on solving 3n+1:-) Here's an example: #include int main() { int i; /* for loop execution */ for (i = 10; i < 20; i++) { printf("i: %d\n", i); } return 0; } Read more on for loops in C here.
[ "c", "gcc", "for-loop" ]
126
160
387,479
11
0
2008-08-24T06:30:09.760000
2008-08-24T06:31:16.480000
24,886
24,887
Is there a performance difference between i++ and ++i in C?
Is there a performance difference between i++ and ++i if the resulting value is not used?
Executive summary: No. i++ could potentially be slower than ++i, since the old value of i might need to be saved for later use, but in practice all modern compilers will optimize this away. We can demonstrate this by looking at the code for this function, both with ++i and i++. $ cat i++.c extern void g(int i); void f() { int i; for (i = 0; i < 100; i++) g(i); } The files are the same, except for ++i and i++: $ diff i++.c ++i.c 6c6 < for (i = 0; i < 100; i++) --- > for (i = 0; i < 100; ++i) We'll compile them, and also get the generated assembler: $ gcc -c i++.c ++i.c $ gcc -S i++.c ++i.c And we can see that both the generated object and assembler files are the same. $ md5 i++.s ++i.s MD5 (i++.s) = 90f620dda862cd0205cd5db1f2c8c06e MD5 (++i.s) = 90f620dda862cd0205cd5db1f2c8c06e $ md5 *.o MD5 (++i.o) = dd3ef1408d3a9e4287facccec53f7d22 MD5 (i++.o) = dd3ef1408d3a9e4287facccec53f7d22
Is there a performance difference between i++ and ++i in C? Is there a performance difference between i++ and ++i if the resulting value is not used?
TITLE: Is there a performance difference between i++ and ++i in C? QUESTION: Is there a performance difference between i++ and ++i if the resulting value is not used? ANSWER: Executive summary: No. i++ could potentially be slower than ++i, since the old value of i might need to be saved for later use, but in practice all modern compilers will optimize this away. We can demonstrate this by looking at the code for this function, both with ++i and i++. $ cat i++.c extern void g(int i); void f() { int i; for (i = 0; i < 100; i++) g(i); } The files are the same, except for ++i and i++: $ diff i++.c ++i.c 6c6 < for (i = 0; i < 100; i++) --- > for (i = 0; i < 100; ++i) We'll compile them, and also get the generated assembler: $ gcc -c i++.c ++i.c $ gcc -S i++.c ++i.c And we can see that both the generated object and assembler files are the same. $ md5 i++.s ++i.s MD5 (i++.s) = 90f620dda862cd0205cd5db1f2c8c06e MD5 (++i.s) = 90f620dda862cd0205cd5db1f2c8c06e $ md5 *.o MD5 (++i.o) = dd3ef1408d3a9e4287facccec53f7d22 MD5 (i++.o) = dd3ef1408d3a9e4287facccec53f7d22
[ "c", "performance", "oop", "post-increment", "pre-increment" ]
532
461
139,508
14
0
2008-08-24T06:48:23.243000
2008-08-24T06:48:58.827000
24,891
24,922
C Memory Management
I've always heard that in C you have to really watch how you manage memory. And I'm still beginning to learn C, but thus far, I have not had to do any memory managing related activities at all.. I always imagined having to release variables and do all sorts of ugly things. But this doesn't seem to be the case. Can someone show me (with code examples) an example of when you would have to do some "memory management"?
There are two places where variables can be put in memory. When you create a variable like this: int a; char c; char d[16]; The variables are created in the " stack ". Stack variables are automatically freed when they go out of scope (that is, when the code can't reach them anymore). You might hear them called "automatic" variables, but that has fallen out of fashion. Many beginner examples will use only stack variables. The stack is nice because it's automatic, but it also has two drawbacks: (1) The compiler needs to know in advance how big the variables are, and (2) the stack space is somewhat limited. For example: in Windows, under default settings for the Microsoft linker, the stack is set to 1 MB, and not all of it is available for your variables. If you don't know at compile time how big your array is, or if you need a big array or struct, you need "plan B". Plan B is called the " heap ". You can usually create variables as big as the Operating System will let you, but you have to do it yourself. Earlier postings showed you one way you can do it, although there are other ways: int size; //... // Set size to some value, based on information available at run-time. Then: //... char *p = (char *)malloc(size); (Note that variables in the heap are not manipulated directly, but via pointers) Once you create a heap variable, the problem is that the compiler can't tell when you're done with it, so you lose the automatic releasing. That's where the "manual releasing" you were referring to comes in. Your code is now responsible to decide when the variable is not needed anymore, and release it so the memory can be taken for other purposes. For the case above, with: free(p); What makes this second option "nasty business" is that it's not always easy to know when the variable is not needed anymore. Forgetting to release a variable when you don't need it will cause your program to consume more memory that it needs to. This situation is called a "leak". The "leaked" memory cannot be used for anything until your program ends and the OS recovers all of its resources. Even nastier problems are possible if you release a heap variable by mistake before you are actually done with it. In C and C++, you are responsible to clean up your heap variables like shown above. However, there are languages and environments such as Java and.NET languages like C# that use a different approach, where the heap gets cleaned up on its own. This second method, called "garbage collection", is much easier on the developer but you pay a penalty in overhead and performance. It's a balance. (I have glossed over many details to give a simpler, but hopefully more leveled answer)
C Memory Management I've always heard that in C you have to really watch how you manage memory. And I'm still beginning to learn C, but thus far, I have not had to do any memory managing related activities at all.. I always imagined having to release variables and do all sorts of ugly things. But this doesn't seem to be the case. Can someone show me (with code examples) an example of when you would have to do some "memory management"?
TITLE: C Memory Management QUESTION: I've always heard that in C you have to really watch how you manage memory. And I'm still beginning to learn C, but thus far, I have not had to do any memory managing related activities at all.. I always imagined having to release variables and do all sorts of ugly things. But this doesn't seem to be the case. Can someone show me (with code examples) an example of when you would have to do some "memory management"? ANSWER: There are two places where variables can be put in memory. When you create a variable like this: int a; char c; char d[16]; The variables are created in the " stack ". Stack variables are automatically freed when they go out of scope (that is, when the code can't reach them anymore). You might hear them called "automatic" variables, but that has fallen out of fashion. Many beginner examples will use only stack variables. The stack is nice because it's automatic, but it also has two drawbacks: (1) The compiler needs to know in advance how big the variables are, and (2) the stack space is somewhat limited. For example: in Windows, under default settings for the Microsoft linker, the stack is set to 1 MB, and not all of it is available for your variables. If you don't know at compile time how big your array is, or if you need a big array or struct, you need "plan B". Plan B is called the " heap ". You can usually create variables as big as the Operating System will let you, but you have to do it yourself. Earlier postings showed you one way you can do it, although there are other ways: int size; //... // Set size to some value, based on information available at run-time. Then: //... char *p = (char *)malloc(size); (Note that variables in the heap are not manipulated directly, but via pointers) Once you create a heap variable, the problem is that the compiler can't tell when you're done with it, so you lose the automatic releasing. That's where the "manual releasing" you were referring to comes in. Your code is now responsible to decide when the variable is not needed anymore, and release it so the memory can be taken for other purposes. For the case above, with: free(p); What makes this second option "nasty business" is that it's not always easy to know when the variable is not needed anymore. Forgetting to release a variable when you don't need it will cause your program to consume more memory that it needs to. This situation is called a "leak". The "leaked" memory cannot be used for anything until your program ends and the OS recovers all of its resources. Even nastier problems are possible if you release a heap variable by mistake before you are actually done with it. In C and C++, you are responsible to clean up your heap variables like shown above. However, there are languages and environments such as Java and.NET languages like C# that use a different approach, where the heap gets cleaned up on its own. This second method, called "garbage collection", is much easier on the developer but you pay a penalty in overhead and performance. It's a balance. (I have glossed over many details to give a simpler, but hopefully more leveled answer)
[ "c", "memory" ]
103
247
54,372
12
0
2008-08-24T06:50:56.497000
2008-08-24T08:21:22.927000
24,901
24,904
Is there a performance difference between i++ and ++i in C++?
We have the question is there a performance difference between i++ and ++i in C? What's the answer for C++?
[Executive Summary: Use ++i if you don't have a specific reason to use i++.] For C++, the answer is a bit more complicated. If i is a simple type (not an instance of a C++ class), then the answer given for C ("No there is no performance difference") holds, since the compiler is generating the code. However, if i is an instance of a C++ class, then i++ and ++i are making calls to one of the operator++ functions. Here's a standard pair of these functions: Foo& Foo::operator++() // called for ++i { this->data += 1; return *this; } Foo Foo::operator++(int ignored_dummy_value) // called for i++ { Foo tmp(*this); // variable "tmp" cannot be optimized away by the compiler ++(*this); return tmp; } Since the compiler isn't generating code, but just calling an operator++ function, there is no way to optimize away the tmp variable and its associated copy constructor. If the copy constructor is expensive, then this can have a significant performance impact.
Is there a performance difference between i++ and ++i in C++? We have the question is there a performance difference between i++ and ++i in C? What's the answer for C++?
TITLE: Is there a performance difference between i++ and ++i in C++? QUESTION: We have the question is there a performance difference between i++ and ++i in C? What's the answer for C++? ANSWER: [Executive Summary: Use ++i if you don't have a specific reason to use i++.] For C++, the answer is a bit more complicated. If i is a simple type (not an instance of a C++ class), then the answer given for C ("No there is no performance difference") holds, since the compiler is generating the code. However, if i is an instance of a C++ class, then i++ and ++i are making calls to one of the operator++ functions. Here's a standard pair of these functions: Foo& Foo::operator++() // called for ++i { this->data += 1; return *this; } Foo Foo::operator++(int ignored_dummy_value) // called for i++ { Foo tmp(*this); // variable "tmp" cannot be optimized away by the compiler ++(*this); return tmp; } Since the compiler isn't generating code, but just calling an operator++ function, there is no way to optimize away the tmp variable and its associated copy constructor. If the copy constructor is expensive, then this can have a significant performance impact.
[ "c++", "performance", "oop", "post-increment", "pre-increment" ]
420
503
109,809
20
0
2008-08-24T07:14:22.243000
2008-08-24T07:23:13.033000
24,915
217,975
BizTalk DB2 adapter connection error
My colleagues are attempting to connect BizTalk 2006 R2 via DB2/MVS adapter to a database hosted on z/OS mainframe. When testing the connecting settings, they are getting the following error Could not connect to data source 'New Data Source': The network connection was terminated because the host failed to send any data. SQLSTATE: 08S01, SQLCODE: -605 When putting the settings in a regular connection string and opening with.NET code, that is fine. I am new to BizTalk and DB2. Can anybody suggest what to look out for when this error surfaces? 24 Aug 08: Well, if normal.NET code with a regular DB2 connection string is used, the connection can be made and queries submitted. What this DB2 adapter is reporting is it cannot even make a proper connection handshake, let alone submitting queries. I am unsure of what are the actual mechanisms involved to make a DB2 connection happen. 25 Aug 08: According to this MSDN forums posting, it seems to be a login issue. I have seen that and that is not the case here. If we put the user name as the Package Collection it still hits the same problem. 26 Aug 08: Because of the scarcity of information regarding connecting to mainframe DB2 databases from Microsoft products, I undertook the task of inspecting raw network packets to get a clue what is going on between the.NET DB2 provider's connection (which works) and the BizTalk 2006 DB2 adapter (which bombs). I observed DB2 traffic is done using the DRDA protocol. And ultimately concluded the BizTalk adapter method fails because of what's recorded in the server's reply SECCHKRM packet DRDA (Security Check) DDM (SECCHKRM) Length: 55 Magic: 0xd0 Format: 0x02 0... = Reserved: Not set.0.. = Chained: Not set..0. = Continue: Not set...0 = Same correlation: Not set DSS type: RPYDSS (2) CorrelId: 0 Length2: 49 Code point: SECCHKRM (0x1219) Parameter (Severity Code) Length: 6 Code point: SVRCOD (0x1149) Data (ASCII): Data (EBCDIC): Parameter (Security Check Code) Length: 5 Code point: SECCHKCD (0x11a4) Data (ASCII): Data (EBCDIC): Parameter (Server Diagnostic Information) Length: 34 Code point: SRVDGN (0x1153) Data (ASCII): \304\331\304\301@\301\331z@\301\344\343\310\305\325\343\311\303\301\343\311\326\325@\206\201\211\223\205\204 Data (EBCDIC): DRDA AR: AUTHENTICATION failed Why the same credentials fails here while succeeding in the.NET provider is beyond me. Right now, what I can observe is a marked difference between each method when it comes to the sequence of packets transferred..NET DB2 provider No. Time Source Destination Protocol Info 1 0.000000 [client IP] [DB2 server IP] TCP kpop > 50000 [SYN] Seq=0 Win=65535 Len=0 MSS=1460 WS=1 2 0.000399 [DB2 server IP] [client IP] TCP 50000 > kpop [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0 3 0.000414 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1 Ack=1 Win=65536 [TCP CHECKSUM INCORRECT] Len=0 4 0.000532 [client IP] [DB2 server IP] DRDA EXCSAT | ACCSEC 5 0.038162 [DB2 server IP] [client IP] DRDA EXCSATRD | ACCSECRD 6 0.041829 [client IP] [DB2 server IP] DRDA ACCSEC | SECCHK | ACCRDB 7 0.083626 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=108 Ack=542 Win=65535 Len=0 8 0.190534 [DB2 server IP] [client IP] DRDA ACCSECRD | SECCHKRM | ACCRDBRM | SQLCARD 9 0.199776 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY 10 0.293307 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 11 0.293359 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 12 0.293377 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=1444 Win=64092 [TCP CHECKSUM INCORRECT] Len=0 13 0.293404 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 14 0.293452 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 15 0.293461 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=2516 Win=65536 [TCP CHECKSUM INCORRECT] Len=0 16 0.293855 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 17 0.293908 [DB2 server IP] [client IP] DRDA SQLDARD 18 0.293918 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=3588 Win=64464 [TCP CHECKSUM INCORRECT] Len=0 19 0.293957 [DB2 server IP] [client IP] DRDA QRYDSC 20 0.294008 [DB2 server IP] [client IP] DRDA QRYDTA 21 0.294017 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=4660 Win=65536 [TCP CHECKSUM INCORRECT] Len=0 22 0.294023 [DB2 server IP] [client IP] DRDA SQLCARD 23 0.295346 [client IP] [DB2 server IP] DRDA RDBCMM 24 0.297868 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD 25 0.421392 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY 26 0.456504 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD 27 0.456756 [client IP] [DB2 server IP] DRDA RDBCMM 28 0.488311 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD 29 0.498806 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY 30 0.630477 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=5157 Ack=1579 Win=65171 Len=0 31 0.788165 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA 32 0.788203 [DB2 server IP] [client IP] DRDA ENDQRYRM 33 0.788225 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1579 Ack=5815 Win=64380 [TCP CHECKSUM INCORRECT] Len=0 34 0.788648 [client IP] [DB2 server IP] DRDA RDBCMM 35 0.795951 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD 36 0.807365 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY 37 0.838046 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD 38 0.838328 [client IP] [DB2 server IP] DRDA RDBCMM 39 0.841866 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD 40 0.973506 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1906 Ack=6304 Win=65482 [TCP CHECKSUM INCORRECT] Len=0 BizTalk DB2 adapter No. Time Source Destination Protocol Info 1 0.000000 [client IP] [DB2 server IP] TCP 28165 > 50000 [SYN] Seq=0 Win=8192 Len=0 MSS=1460 WS=8 2 0.002587 [DB2 server IP] [client IP] TCP 50000 > 28165 [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0 3 0.010146 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=1 Ack=1 Win=65536 Len=0 4 0.019698 [client IP] [DB2 server IP] DRDA EXCSAT 5 0.020849 [DB2 server IP] [client IP] DRDA EXCSATRD 6 0.034699 [client IP] [DB2 server IP] DRDA ACCSEC 7 0.036584 [DB2 server IP] [client IP] DRDA ACCSECRD 8 0.042031 [client IP] [DB2 server IP] DRDA SECCHK 9 0.046350 [DB2 server IP] [client IP] DRDA SECCHKRM 10 0.046642 [DB2 server IP] [client IP] TCP 50000 > 28165 [FIN, ACK] Seq=160 Ack=200 Win=65336 Len=0 11 0.053787 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=200 Ack=161 Win=65536 Len=0 12 0.056891 [client IP] [DB2 server IP] DRDA ACCRDB 13 0.058084 [DB2 server IP] [client IP] TCP 50000 > 28165 [RST, ACK] Seq=161 Ack=295 Win=0 Len=0 It is interesting to witness the.NET provider issue out various DRDA protocol packets within in a single TCP segment. The BizTalk adapter on the other hand, places only one protocol packet per TCP segment. I do not know why this is so. However, I at the moment think that is a red herring and the true difference causing the failure in authentication is in the DRDA data exchange. I do not know the DRDA protocol so will have to study it before I can make more sense of it. 18 Sep 08: At this stage the problem is still not solved, as getting cooperation from the DB2 DBA team and help from Microsoft have been met with many obstacles. What I do want to report is, I have observed perhaps one crucial difference between all the cases of successful connection versus the failed attempt: The BizTalk DB2 adapter is underlyingly using Microsoft ODBC Driver for DB2. The other software tests that succeed make use of IBM DB2 ODBC DRIVER or IBM DB2 ODBC DRIVER – IBMCL1. The IBM driver's parameter configuration is different from Microsoft's driver. But we do not see any obviously critical difference that may lead to a failed authentication for the Microsoft driver.
Why, it certainly took Microsoft long enough to explicitly confirm this: proxy connections via DB2Connect is not supported by BizTalk DB2 Adapter Since our customer's policy is to only access DB2 databases via DB2Connect, the adapter is out of the question. MORE BACKGROUND INFO The reason why the DB2 Adapter only works for a direct connection to a z/OS mainframe host, is due to legal restrictions. Technically it is possible to work a connection with DB2Connect, but IBM has made it a priorietary node and prevented other parties from legally establishing the correct DRDA sequence to connect to it.
BizTalk DB2 adapter connection error My colleagues are attempting to connect BizTalk 2006 R2 via DB2/MVS adapter to a database hosted on z/OS mainframe. When testing the connecting settings, they are getting the following error Could not connect to data source 'New Data Source': The network connection was terminated because the host failed to send any data. SQLSTATE: 08S01, SQLCODE: -605 When putting the settings in a regular connection string and opening with.NET code, that is fine. I am new to BizTalk and DB2. Can anybody suggest what to look out for when this error surfaces? 24 Aug 08: Well, if normal.NET code with a regular DB2 connection string is used, the connection can be made and queries submitted. What this DB2 adapter is reporting is it cannot even make a proper connection handshake, let alone submitting queries. I am unsure of what are the actual mechanisms involved to make a DB2 connection happen. 25 Aug 08: According to this MSDN forums posting, it seems to be a login issue. I have seen that and that is not the case here. If we put the user name as the Package Collection it still hits the same problem. 26 Aug 08: Because of the scarcity of information regarding connecting to mainframe DB2 databases from Microsoft products, I undertook the task of inspecting raw network packets to get a clue what is going on between the.NET DB2 provider's connection (which works) and the BizTalk 2006 DB2 adapter (which bombs). I observed DB2 traffic is done using the DRDA protocol. And ultimately concluded the BizTalk adapter method fails because of what's recorded in the server's reply SECCHKRM packet DRDA (Security Check) DDM (SECCHKRM) Length: 55 Magic: 0xd0 Format: 0x02 0... = Reserved: Not set.0.. = Chained: Not set..0. = Continue: Not set...0 = Same correlation: Not set DSS type: RPYDSS (2) CorrelId: 0 Length2: 49 Code point: SECCHKRM (0x1219) Parameter (Severity Code) Length: 6 Code point: SVRCOD (0x1149) Data (ASCII): Data (EBCDIC): Parameter (Security Check Code) Length: 5 Code point: SECCHKCD (0x11a4) Data (ASCII): Data (EBCDIC): Parameter (Server Diagnostic Information) Length: 34 Code point: SRVDGN (0x1153) Data (ASCII): \304\331\304\301@\301\331z@\301\344\343\310\305\325\343\311\303\301\343\311\326\325@\206\201\211\223\205\204 Data (EBCDIC): DRDA AR: AUTHENTICATION failed Why the same credentials fails here while succeeding in the.NET provider is beyond me. Right now, what I can observe is a marked difference between each method when it comes to the sequence of packets transferred..NET DB2 provider No. Time Source Destination Protocol Info 1 0.000000 [client IP] [DB2 server IP] TCP kpop > 50000 [SYN] Seq=0 Win=65535 Len=0 MSS=1460 WS=1 2 0.000399 [DB2 server IP] [client IP] TCP 50000 > kpop [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0 3 0.000414 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1 Ack=1 Win=65536 [TCP CHECKSUM INCORRECT] Len=0 4 0.000532 [client IP] [DB2 server IP] DRDA EXCSAT | ACCSEC 5 0.038162 [DB2 server IP] [client IP] DRDA EXCSATRD | ACCSECRD 6 0.041829 [client IP] [DB2 server IP] DRDA ACCSEC | SECCHK | ACCRDB 7 0.083626 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=108 Ack=542 Win=65535 Len=0 8 0.190534 [DB2 server IP] [client IP] DRDA ACCSECRD | SECCHKRM | ACCRDBRM | SQLCARD 9 0.199776 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY 10 0.293307 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 11 0.293359 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 12 0.293377 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=1444 Win=64092 [TCP CHECKSUM INCORRECT] Len=0 13 0.293404 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 14 0.293452 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 15 0.293461 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=2516 Win=65536 [TCP CHECKSUM INCORRECT] Len=0 16 0.293855 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 17 0.293908 [DB2 server IP] [client IP] DRDA SQLDARD 18 0.293918 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=3588 Win=64464 [TCP CHECKSUM INCORRECT] Len=0 19 0.293957 [DB2 server IP] [client IP] DRDA QRYDSC 20 0.294008 [DB2 server IP] [client IP] DRDA QRYDTA 21 0.294017 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=4660 Win=65536 [TCP CHECKSUM INCORRECT] Len=0 22 0.294023 [DB2 server IP] [client IP] DRDA SQLCARD 23 0.295346 [client IP] [DB2 server IP] DRDA RDBCMM 24 0.297868 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD 25 0.421392 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY 26 0.456504 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD 27 0.456756 [client IP] [DB2 server IP] DRDA RDBCMM 28 0.488311 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD 29 0.498806 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY 30 0.630477 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=5157 Ack=1579 Win=65171 Len=0 31 0.788165 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA 32 0.788203 [DB2 server IP] [client IP] DRDA ENDQRYRM 33 0.788225 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1579 Ack=5815 Win=64380 [TCP CHECKSUM INCORRECT] Len=0 34 0.788648 [client IP] [DB2 server IP] DRDA RDBCMM 35 0.795951 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD 36 0.807365 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY 37 0.838046 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD 38 0.838328 [client IP] [DB2 server IP] DRDA RDBCMM 39 0.841866 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD 40 0.973506 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1906 Ack=6304 Win=65482 [TCP CHECKSUM INCORRECT] Len=0 BizTalk DB2 adapter No. Time Source Destination Protocol Info 1 0.000000 [client IP] [DB2 server IP] TCP 28165 > 50000 [SYN] Seq=0 Win=8192 Len=0 MSS=1460 WS=8 2 0.002587 [DB2 server IP] [client IP] TCP 50000 > 28165 [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0 3 0.010146 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=1 Ack=1 Win=65536 Len=0 4 0.019698 [client IP] [DB2 server IP] DRDA EXCSAT 5 0.020849 [DB2 server IP] [client IP] DRDA EXCSATRD 6 0.034699 [client IP] [DB2 server IP] DRDA ACCSEC 7 0.036584 [DB2 server IP] [client IP] DRDA ACCSECRD 8 0.042031 [client IP] [DB2 server IP] DRDA SECCHK 9 0.046350 [DB2 server IP] [client IP] DRDA SECCHKRM 10 0.046642 [DB2 server IP] [client IP] TCP 50000 > 28165 [FIN, ACK] Seq=160 Ack=200 Win=65336 Len=0 11 0.053787 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=200 Ack=161 Win=65536 Len=0 12 0.056891 [client IP] [DB2 server IP] DRDA ACCRDB 13 0.058084 [DB2 server IP] [client IP] TCP 50000 > 28165 [RST, ACK] Seq=161 Ack=295 Win=0 Len=0 It is interesting to witness the.NET provider issue out various DRDA protocol packets within in a single TCP segment. The BizTalk adapter on the other hand, places only one protocol packet per TCP segment. I do not know why this is so. However, I at the moment think that is a red herring and the true difference causing the failure in authentication is in the DRDA data exchange. I do not know the DRDA protocol so will have to study it before I can make more sense of it. 18 Sep 08: At this stage the problem is still not solved, as getting cooperation from the DB2 DBA team and help from Microsoft have been met with many obstacles. What I do want to report is, I have observed perhaps one crucial difference between all the cases of successful connection versus the failed attempt: The BizTalk DB2 adapter is underlyingly using Microsoft ODBC Driver for DB2. The other software tests that succeed make use of IBM DB2 ODBC DRIVER or IBM DB2 ODBC DRIVER – IBMCL1. The IBM driver's parameter configuration is different from Microsoft's driver. But we do not see any obviously critical difference that may lead to a failed authentication for the Microsoft driver.
TITLE: BizTalk DB2 adapter connection error QUESTION: My colleagues are attempting to connect BizTalk 2006 R2 via DB2/MVS adapter to a database hosted on z/OS mainframe. When testing the connecting settings, they are getting the following error Could not connect to data source 'New Data Source': The network connection was terminated because the host failed to send any data. SQLSTATE: 08S01, SQLCODE: -605 When putting the settings in a regular connection string and opening with.NET code, that is fine. I am new to BizTalk and DB2. Can anybody suggest what to look out for when this error surfaces? 24 Aug 08: Well, if normal.NET code with a regular DB2 connection string is used, the connection can be made and queries submitted. What this DB2 adapter is reporting is it cannot even make a proper connection handshake, let alone submitting queries. I am unsure of what are the actual mechanisms involved to make a DB2 connection happen. 25 Aug 08: According to this MSDN forums posting, it seems to be a login issue. I have seen that and that is not the case here. If we put the user name as the Package Collection it still hits the same problem. 26 Aug 08: Because of the scarcity of information regarding connecting to mainframe DB2 databases from Microsoft products, I undertook the task of inspecting raw network packets to get a clue what is going on between the.NET DB2 provider's connection (which works) and the BizTalk 2006 DB2 adapter (which bombs). I observed DB2 traffic is done using the DRDA protocol. And ultimately concluded the BizTalk adapter method fails because of what's recorded in the server's reply SECCHKRM packet DRDA (Security Check) DDM (SECCHKRM) Length: 55 Magic: 0xd0 Format: 0x02 0... = Reserved: Not set.0.. = Chained: Not set..0. = Continue: Not set...0 = Same correlation: Not set DSS type: RPYDSS (2) CorrelId: 0 Length2: 49 Code point: SECCHKRM (0x1219) Parameter (Severity Code) Length: 6 Code point: SVRCOD (0x1149) Data (ASCII): Data (EBCDIC): Parameter (Security Check Code) Length: 5 Code point: SECCHKCD (0x11a4) Data (ASCII): Data (EBCDIC): Parameter (Server Diagnostic Information) Length: 34 Code point: SRVDGN (0x1153) Data (ASCII): \304\331\304\301@\301\331z@\301\344\343\310\305\325\343\311\303\301\343\311\326\325@\206\201\211\223\205\204 Data (EBCDIC): DRDA AR: AUTHENTICATION failed Why the same credentials fails here while succeeding in the.NET provider is beyond me. Right now, what I can observe is a marked difference between each method when it comes to the sequence of packets transferred..NET DB2 provider No. Time Source Destination Protocol Info 1 0.000000 [client IP] [DB2 server IP] TCP kpop > 50000 [SYN] Seq=0 Win=65535 Len=0 MSS=1460 WS=1 2 0.000399 [DB2 server IP] [client IP] TCP 50000 > kpop [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0 3 0.000414 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1 Ack=1 Win=65536 [TCP CHECKSUM INCORRECT] Len=0 4 0.000532 [client IP] [DB2 server IP] DRDA EXCSAT | ACCSEC 5 0.038162 [DB2 server IP] [client IP] DRDA EXCSATRD | ACCSECRD 6 0.041829 [client IP] [DB2 server IP] DRDA ACCSEC | SECCHK | ACCRDB 7 0.083626 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=108 Ack=542 Win=65535 Len=0 8 0.190534 [DB2 server IP] [client IP] DRDA ACCSECRD | SECCHKRM | ACCRDBRM | SQLCARD 9 0.199776 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY 10 0.293307 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 11 0.293359 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 12 0.293377 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=1444 Win=64092 [TCP CHECKSUM INCORRECT] Len=0 13 0.293404 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 14 0.293452 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 15 0.293461 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=2516 Win=65536 [TCP CHECKSUM INCORRECT] Len=0 16 0.293855 [DB2 server IP] [client IP] TCP [TCP segment of a reassembled PDU] 17 0.293908 [DB2 server IP] [client IP] DRDA SQLDARD 18 0.293918 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=3588 Win=64464 [TCP CHECKSUM INCORRECT] Len=0 19 0.293957 [DB2 server IP] [client IP] DRDA QRYDSC 20 0.294008 [DB2 server IP] [client IP] DRDA QRYDTA 21 0.294017 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=870 Ack=4660 Win=65536 [TCP CHECKSUM INCORRECT] Len=0 22 0.294023 [DB2 server IP] [client IP] DRDA SQLCARD 23 0.295346 [client IP] [DB2 server IP] DRDA RDBCMM 24 0.297868 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD 25 0.421392 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY 26 0.456504 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD 27 0.456756 [client IP] [DB2 server IP] DRDA RDBCMM 28 0.488311 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD 29 0.498806 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY 30 0.630477 [DB2 server IP] [client IP] TCP 50000 > kpop [ACK] Seq=5157 Ack=1579 Win=65171 Len=0 31 0.788165 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA 32 0.788203 [DB2 server IP] [client IP] DRDA ENDQRYRM 33 0.788225 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1579 Ack=5815 Win=64380 [TCP CHECKSUM INCORRECT] Len=0 34 0.788648 [client IP] [DB2 server IP] DRDA RDBCMM 35 0.795951 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD 36 0.807365 [client IP] [DB2 server IP] DRDA PRPSQLSTT | SQLATTR | SQLSTT | OPNQRY 37 0.838046 [DB2 server IP] [client IP] DRDA SQLDARD | OPNQRYRM | TYPDEFNAM | QRYDSC | QRYDTA | ENDQRYRM | TYPDEFNAM | SQLCARD 38 0.838328 [client IP] [DB2 server IP] DRDA RDBCMM 39 0.841866 [DB2 server IP] [client IP] DRDA ENDUOWRM | SQLCARD 40 0.973506 [client IP] [DB2 server IP] TCP kpop > 50000 [ACK] Seq=1906 Ack=6304 Win=65482 [TCP CHECKSUM INCORRECT] Len=0 BizTalk DB2 adapter No. Time Source Destination Protocol Info 1 0.000000 [client IP] [DB2 server IP] TCP 28165 > 50000 [SYN] Seq=0 Win=8192 Len=0 MSS=1460 WS=8 2 0.002587 [DB2 server IP] [client IP] TCP 50000 > 28165 [SYN, ACK] Seq=0 Ack=1 Win=16384 Len=0 MSS=1460 WS=0 3 0.010146 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=1 Ack=1 Win=65536 Len=0 4 0.019698 [client IP] [DB2 server IP] DRDA EXCSAT 5 0.020849 [DB2 server IP] [client IP] DRDA EXCSATRD 6 0.034699 [client IP] [DB2 server IP] DRDA ACCSEC 7 0.036584 [DB2 server IP] [client IP] DRDA ACCSECRD 8 0.042031 [client IP] [DB2 server IP] DRDA SECCHK 9 0.046350 [DB2 server IP] [client IP] DRDA SECCHKRM 10 0.046642 [DB2 server IP] [client IP] TCP 50000 > 28165 [FIN, ACK] Seq=160 Ack=200 Win=65336 Len=0 11 0.053787 [client IP] [DB2 server IP] TCP 28165 > 50000 [ACK] Seq=200 Ack=161 Win=65536 Len=0 12 0.056891 [client IP] [DB2 server IP] DRDA ACCRDB 13 0.058084 [DB2 server IP] [client IP] TCP 50000 > 28165 [RST, ACK] Seq=161 Ack=295 Win=0 Len=0 It is interesting to witness the.NET provider issue out various DRDA protocol packets within in a single TCP segment. The BizTalk adapter on the other hand, places only one protocol packet per TCP segment. I do not know why this is so. However, I at the moment think that is a red herring and the true difference causing the failure in authentication is in the DRDA data exchange. I do not know the DRDA protocol so will have to study it before I can make more sense of it. 18 Sep 08: At this stage the problem is still not solved, as getting cooperation from the DB2 DBA team and help from Microsoft have been met with many obstacles. What I do want to report is, I have observed perhaps one crucial difference between all the cases of successful connection versus the failed attempt: The BizTalk DB2 adapter is underlyingly using Microsoft ODBC Driver for DB2. The other software tests that succeed make use of IBM DB2 ODBC DRIVER or IBM DB2 ODBC DRIVER – IBMCL1. The IBM driver's parameter configuration is different from Microsoft's driver. But we do not see any obviously critical difference that may lead to a failed authentication for the Microsoft driver. ANSWER: Why, it certainly took Microsoft long enough to explicitly confirm this: proxy connections via DB2Connect is not supported by BizTalk DB2 Adapter Since our customer's policy is to only access DB2 databases via DB2Connect, the adapter is out of the question. MORE BACKGROUND INFO The reason why the DB2 Adapter only works for a direct connection to a z/OS mainframe host, is due to legal restrictions. Technically it is possible to work a connection with DB2Connect, but IBM has made it a priorietary node and prevented other parties from legally establishing the correct DRDA sequence to connect to it.
[ "db2", "biztalk", "mainframe", "zos", "biztalk2006r2" ]
2
3
2,166
3
0
2008-08-24T07:53:13.353000
2008-10-20T10:09:48.293000
24,931
24,949
How to capture Python interpreter's and/or CMD.EXE's output from a Python script?
Is it possible to capture Python interpreter's output from a Python script? Is it possible to capture Windows CMD's output from a Python script? If so, which librar(y|ies) should I look into?
If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation: python script_a.py | python script_b.py This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on standard streams on Wikipedia. If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication): import subprocess # Of course you can open things other than python here:) process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) x = process.stderr.readline() y = process.stdout.readline() process.wait() See the Python subprocess module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard file objects. For use with pipes, reading from standard input as lassevk suggested you'd do something like this: import sys x = sys.stderr.readline() y = sys.stdin.readline() sys.stdin and sys.stdout are standard file objects as noted above, defined in the sys module. You might also want to take a look at the pipes module. Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into polling which unfortunately does not work in windows, but I'm sure there's some alternative out there.
How to capture Python interpreter's and/or CMD.EXE's output from a Python script? Is it possible to capture Python interpreter's output from a Python script? Is it possible to capture Windows CMD's output from a Python script? If so, which librar(y|ies) should I look into?
TITLE: How to capture Python interpreter's and/or CMD.EXE's output from a Python script? QUESTION: Is it possible to capture Python interpreter's output from a Python script? Is it possible to capture Windows CMD's output from a Python script? If so, which librar(y|ies) should I look into? ANSWER: If you are talking about the python interpreter or CMD.exe that is the 'parent' of your script then no, it isn't possible. In every POSIX-like system (now you're running Windows, it seems, and that might have some quirk I don't know about, YMMV) each process has three streams, standard input, standard output and standard error. Bu default (when running in a console) these are directed to the console, but redirection is possible using the pipe notation: python script_a.py | python script_b.py This ties the standard output stream of script a to the standard input stream of script B. Standard error still goes to the console in this example. See the article on standard streams on Wikipedia. If you're talking about a child process, you can launch it from python like so (stdin is also an option if you want two way communication): import subprocess # Of course you can open things other than python here:) process = subprocess.Popen(["python", "main.py"], stdout=subprocess.PIPE, stderr=subprocess.PIPE) x = process.stderr.readline() y = process.stdout.readline() process.wait() See the Python subprocess module for information on managing the process. For communication, the process.stdin and process.stdout pipes are considered standard file objects. For use with pipes, reading from standard input as lassevk suggested you'd do something like this: import sys x = sys.stderr.readline() y = sys.stdin.readline() sys.stdin and sys.stdout are standard file objects as noted above, defined in the sys module. You might also want to take a look at the pipes module. Reading data with readline() as in my example is a pretty naïve way of getting data though. If the output is not line-oriented or indeterministic you probably want to look into polling which unfortunately does not work in windows, but I'm sure there's some alternative out there.
[ "python", "windows", "cmd" ]
10
10
11,022
6
0
2008-08-24T08:46:57.293000
2008-08-24T09:39:08.247000
24,954
24,974
Windows: List and Launch applications associated with an extension
How to determine the applications associated with a particular extension (e.g..JPG) and then determine where the executable to that application is located so that it can be launched via a call to say System.Diagnostics.Process.Start(...). I already know how to read and write to the registry. It is the layout of the registry that makes it harder to determine in a standard way what applications are associated with an extension, what are there display names, and where their executables are located.
Sample code: using System; using Microsoft.Win32; namespace GetAssociatedApp { class Program { static void Main(string[] args) { const string extPathTemplate = @"HKEY_CLASSES_ROOT\{0}"; const string cmdPathTemplate = @"HKEY_CLASSES_ROOT\{0}\shell\open\command"; // 1. Find out document type name for.jpeg files const string ext = ".jpeg"; var extPath = string.Format(extPathTemplate, ext); var docName = Registry.GetValue(extPath, string.Empty, string.Empty) as string; if (!string.IsNullOrEmpty(docName)) { // 2. Find out which command is associated with our extension var associatedCmdPath = string.Format(cmdPathTemplate, docName); var associatedCmd = Registry.GetValue(associatedCmdPath, string.Empty, string.Empty) as string; if (!string.IsNullOrEmpty(associatedCmd)) { Console.WriteLine("\"{0}\" command is associated with {1} extension", associatedCmd, ext); } } } } }
Windows: List and Launch applications associated with an extension How to determine the applications associated with a particular extension (e.g..JPG) and then determine where the executable to that application is located so that it can be launched via a call to say System.Diagnostics.Process.Start(...). I already know how to read and write to the registry. It is the layout of the registry that makes it harder to determine in a standard way what applications are associated with an extension, what are there display names, and where their executables are located.
TITLE: Windows: List and Launch applications associated with an extension QUESTION: How to determine the applications associated with a particular extension (e.g..JPG) and then determine where the executable to that application is located so that it can be launched via a call to say System.Diagnostics.Process.Start(...). I already know how to read and write to the registry. It is the layout of the registry that makes it harder to determine in a standard way what applications are associated with an extension, what are there display names, and where their executables are located. ANSWER: Sample code: using System; using Microsoft.Win32; namespace GetAssociatedApp { class Program { static void Main(string[] args) { const string extPathTemplate = @"HKEY_CLASSES_ROOT\{0}"; const string cmdPathTemplate = @"HKEY_CLASSES_ROOT\{0}\shell\open\command"; // 1. Find out document type name for.jpeg files const string ext = ".jpeg"; var extPath = string.Format(extPathTemplate, ext); var docName = Registry.GetValue(extPath, string.Empty, string.Empty) as string; if (!string.IsNullOrEmpty(docName)) { // 2. Find out which command is associated with our extension var associatedCmdPath = string.Format(cmdPathTemplate, docName); var associatedCmd = Registry.GetValue(associatedCmdPath, string.Empty, string.Empty) as string; if (!string.IsNullOrEmpty(associatedCmd)) { Console.WriteLine("\"{0}\" command is associated with {1} extension", associatedCmd, ext); } } } } }
[ ".net", "windows", "registry" ]
14
7
10,666
5
0
2008-08-24T10:05:38.930000
2008-08-24T11:01:18.470000
24,959
24,982
Debugging asp.net with firefox and visual studio.net - very slow compared to IE
Debugging asp.net websites/web projects in visual studio.net 2005 with Firefox is loads slower than using IE. I've read something somewhere that there is a way of fixing this but i can't for the life of me find it again. Does anyone know what i'm on about and can point me in the right direction please? Cheers John edit sorry rob i haven't explained myself very well(again). I prefer Firefox for debugging (firebug etc) hitting F5 when debugging with IE the browser launches really quickly and clicking around my web application is almost instant and when a breakpont is hit i get to my code straight away with no delays. hitting F5 when debugging with FireFox the browser launches really slowly (ok i have plugins that slow FF loading) but clicking around my web application is really really slow and when a breakpoint is hit it takes ages to break into code. i swear i've read something somewhere that there is a setting in Firefox (about:config maybe?) that when changed to some magic setting sorts all this out.
bingo. found the article i read before. i just changed my network.dns.ipv4OnlyDomains property in about:config to localhost. restarted firefox and now firefox performs the same as IE when debugging asp.net with visual studio (2005). hope this helps anyone else that has the same problem.
Debugging asp.net with firefox and visual studio.net - very slow compared to IE Debugging asp.net websites/web projects in visual studio.net 2005 with Firefox is loads slower than using IE. I've read something somewhere that there is a way of fixing this but i can't for the life of me find it again. Does anyone know what i'm on about and can point me in the right direction please? Cheers John edit sorry rob i haven't explained myself very well(again). I prefer Firefox for debugging (firebug etc) hitting F5 when debugging with IE the browser launches really quickly and clicking around my web application is almost instant and when a breakpont is hit i get to my code straight away with no delays. hitting F5 when debugging with FireFox the browser launches really slowly (ok i have plugins that slow FF loading) but clicking around my web application is really really slow and when a breakpoint is hit it takes ages to break into code. i swear i've read something somewhere that there is a setting in Firefox (about:config maybe?) that when changed to some magic setting sorts all this out.
TITLE: Debugging asp.net with firefox and visual studio.net - very slow compared to IE QUESTION: Debugging asp.net websites/web projects in visual studio.net 2005 with Firefox is loads slower than using IE. I've read something somewhere that there is a way of fixing this but i can't for the life of me find it again. Does anyone know what i'm on about and can point me in the right direction please? Cheers John edit sorry rob i haven't explained myself very well(again). I prefer Firefox for debugging (firebug etc) hitting F5 when debugging with IE the browser launches really quickly and clicking around my web application is almost instant and when a breakpont is hit i get to my code straight away with no delays. hitting F5 when debugging with FireFox the browser launches really slowly (ok i have plugins that slow FF loading) but clicking around my web application is really really slow and when a breakpoint is hit it takes ages to break into code. i swear i've read something somewhere that there is a setting in Firefox (about:config maybe?) that when changed to some magic setting sorts all this out. ANSWER: bingo. found the article i read before. i just changed my network.dns.ipv4OnlyDomains property in about:config to localhost. restarted firefox and now firefox performs the same as IE when debugging asp.net with visual studio (2005). hope this helps anyone else that has the same problem.
[ "debugging", "firefox", "visual-studio-2005" ]
18
30
10,194
4
0
2008-08-24T10:28:10.373000
2008-08-24T11:32:03.233000
24,963
25,663
How to learn MDX
I am currently learning OLAP & MDX after many years of relational database development. Any tips on getting started in MDX? What are the best books and resources to learn MDX?
A classic, albeit a bit dated, book is Fast Track to MDX. It's a great overview and a quick read, though it doesn't cover the new MDX features of SQL Server 2005. The Spofford book MDX Solutions is more up date and a little deeper, but a bit harder to get through. I also highly recommend the blogs of Mosha Pasumansky, Chris Webb, and Darren Gosbell.
How to learn MDX I am currently learning OLAP & MDX after many years of relational database development. Any tips on getting started in MDX? What are the best books and resources to learn MDX?
TITLE: How to learn MDX QUESTION: I am currently learning OLAP & MDX after many years of relational database development. Any tips on getting started in MDX? What are the best books and resources to learn MDX? ANSWER: A classic, albeit a bit dated, book is Fast Track to MDX. It's a great overview and a quick read, though it doesn't cover the new MDX features of SQL Server 2005. The Spofford book MDX Solutions is more up date and a little deeper, but a bit harder to get through. I also highly recommend the blogs of Mosha Pasumansky, Chris Webb, and Darren Gosbell.
[ "ssas", "olap", "mdx" ]
31
19
25,785
10
0
2008-08-24T10:38:17.323000
2008-08-25T04:42:46.437000
24,965
25,203
Beginning TDD - Challenges? Solutions? Recommendations?
OK, I know there have already been questions about getting started with TDD.. However, I guess I kind of know the general concensus is to just do it, However, I seem to have the following problems getting my head into the game: When working with collections, do will still test for obvious add/remove/inserts successful, even when based on Generics etc where we kind of "know" its going to work? Some tests seem to take forever to implement.. Such as when working with string output, is there a "better" way to go about this sort of thing? (e.g. test the object model before parsing, break parsing down into small ops and test there) In my mind you should always test the "end result" but that can vary wildly and be tedious to set up. I don't have a testing framework to use (work wont pay for one) so I can "practice" more. Are there any good ones that are free for commercial use? (at the moment I am using good 'ol Debug.Assert:) Probably the biggest.. Sometimes I don't know what to expect NOT to happen.. I mean, you get your green light but I am always concerned that I may be missing a test.. Do you dig deeper to try and break the code, or leave it be and wait for it all fall over later (which will cost more).. So basically what I am looking for here is not a " just do it " but more " I did this, had problems with this, solved them by this ".. The personal experience:)
First, it is alright and normal to feel frustrated when you first start trying to use TDD in your coding style. Just don't get discouraged and quit, you will need to give it some time. It is a major paradigm shift in how we think about solving a problem in code. I like to think of it like when we switched from procedural to object oriented programming. Secondly, I feel that test driven development is first and foremost a design activity that is used to flesh out the design of a component by creating a test that first describes the API it is going to expose and how you are going to consume it's functionality. The test will help shape and mold the System Under Test until you have been able to encapsulate enough functionality to satisfy whatever tasks you happen to be working on. Taking the above paragraph in mind, let's look at your questions: If I am using a collection in my system under test, then I will setup an expectation to make sure that the code was called to insert the item and then assert the count of the collection. I don't necessarily test the Add method on my internal list. I just make sure it was called when the method that adds the item is called. I do this by adding a mocking framework into the mix, with my testing framework. Testing strings as output can be tedious. You cannot account for every outcome. You can only test what you expect based on the functionality of the system under test. You should always break your tests down to the smallest element that it is testing. Which means you will have a lot of tests, but tests that are small and fast and only test what they should, nothing else. There are a lot of open source testing frameworks to choose from. I am not going to argue which is best. Just find one you like and start using it. MbUnit nUnit xUnit All you can do is setup your tests to account for what you want to happen. If a scenario comes up that introduces a bug in your functionality, at least you have a test around the functionality to add that scenario into the test and then change your functionality until the test passes. One way to find where we may have missed a test is to use code coverage. I introduced you to the mocking term in the answer for question one. When you introduce mocking into your arsenal for TDD, it dramatically makes testing easier to abstract away the parts that are not part of the system under test. Here are some resources on the mocking frameworks out there are: Moq: Open Source RhinoMocks: Open Source TypeMock: Commercial Product NSubstitute: Open Source One way to help in using TDD, besides reading about the process, is to watch people do it. I recommend in watching the screen casts by JP Boodhoo on DNRTV. Check these out: Jean Paul Boodhoo on Test Driven Development Part 1 Jean Paul Boodhoo on Test Driven Development Part 2 Jean Paul Boodhoo on Demystifying Design Patterns Part 1 Jean Paul Boodhoo on Demystifying Design Patterns Part 2 Jean Paul Boodhoo on Demystifying Design Patterns Part 3 Jean Paul Boodhoo on Demystifying Design Patterns Part 4 Jean Paul Boodhoo on Demystifying Design Patterns Part 5 OK, these will help you see how the terms I introduced are used. It will also introduce another tool called Resharper and how it can facilitate the TDD process. I couldn't recommend this tool enough when doing TDD. Seems like you are learning the process and you are just finding some of the problems that have already been solved with using other tools. I think I would be doing an injustice to the community, if I didn't update this by adding Kent Beck's new series on Test Driven Development on Pragmatic Programmer.
Beginning TDD - Challenges? Solutions? Recommendations? OK, I know there have already been questions about getting started with TDD.. However, I guess I kind of know the general concensus is to just do it, However, I seem to have the following problems getting my head into the game: When working with collections, do will still test for obvious add/remove/inserts successful, even when based on Generics etc where we kind of "know" its going to work? Some tests seem to take forever to implement.. Such as when working with string output, is there a "better" way to go about this sort of thing? (e.g. test the object model before parsing, break parsing down into small ops and test there) In my mind you should always test the "end result" but that can vary wildly and be tedious to set up. I don't have a testing framework to use (work wont pay for one) so I can "practice" more. Are there any good ones that are free for commercial use? (at the moment I am using good 'ol Debug.Assert:) Probably the biggest.. Sometimes I don't know what to expect NOT to happen.. I mean, you get your green light but I am always concerned that I may be missing a test.. Do you dig deeper to try and break the code, or leave it be and wait for it all fall over later (which will cost more).. So basically what I am looking for here is not a " just do it " but more " I did this, had problems with this, solved them by this ".. The personal experience:)
TITLE: Beginning TDD - Challenges? Solutions? Recommendations? QUESTION: OK, I know there have already been questions about getting started with TDD.. However, I guess I kind of know the general concensus is to just do it, However, I seem to have the following problems getting my head into the game: When working with collections, do will still test for obvious add/remove/inserts successful, even when based on Generics etc where we kind of "know" its going to work? Some tests seem to take forever to implement.. Such as when working with string output, is there a "better" way to go about this sort of thing? (e.g. test the object model before parsing, break parsing down into small ops and test there) In my mind you should always test the "end result" but that can vary wildly and be tedious to set up. I don't have a testing framework to use (work wont pay for one) so I can "practice" more. Are there any good ones that are free for commercial use? (at the moment I am using good 'ol Debug.Assert:) Probably the biggest.. Sometimes I don't know what to expect NOT to happen.. I mean, you get your green light but I am always concerned that I may be missing a test.. Do you dig deeper to try and break the code, or leave it be and wait for it all fall over later (which will cost more).. So basically what I am looking for here is not a " just do it " but more " I did this, had problems with this, solved them by this ".. The personal experience:) ANSWER: First, it is alright and normal to feel frustrated when you first start trying to use TDD in your coding style. Just don't get discouraged and quit, you will need to give it some time. It is a major paradigm shift in how we think about solving a problem in code. I like to think of it like when we switched from procedural to object oriented programming. Secondly, I feel that test driven development is first and foremost a design activity that is used to flesh out the design of a component by creating a test that first describes the API it is going to expose and how you are going to consume it's functionality. The test will help shape and mold the System Under Test until you have been able to encapsulate enough functionality to satisfy whatever tasks you happen to be working on. Taking the above paragraph in mind, let's look at your questions: If I am using a collection in my system under test, then I will setup an expectation to make sure that the code was called to insert the item and then assert the count of the collection. I don't necessarily test the Add method on my internal list. I just make sure it was called when the method that adds the item is called. I do this by adding a mocking framework into the mix, with my testing framework. Testing strings as output can be tedious. You cannot account for every outcome. You can only test what you expect based on the functionality of the system under test. You should always break your tests down to the smallest element that it is testing. Which means you will have a lot of tests, but tests that are small and fast and only test what they should, nothing else. There are a lot of open source testing frameworks to choose from. I am not going to argue which is best. Just find one you like and start using it. MbUnit nUnit xUnit All you can do is setup your tests to account for what you want to happen. If a scenario comes up that introduces a bug in your functionality, at least you have a test around the functionality to add that scenario into the test and then change your functionality until the test passes. One way to find where we may have missed a test is to use code coverage. I introduced you to the mocking term in the answer for question one. When you introduce mocking into your arsenal for TDD, it dramatically makes testing easier to abstract away the parts that are not part of the system under test. Here are some resources on the mocking frameworks out there are: Moq: Open Source RhinoMocks: Open Source TypeMock: Commercial Product NSubstitute: Open Source One way to help in using TDD, besides reading about the process, is to watch people do it. I recommend in watching the screen casts by JP Boodhoo on DNRTV. Check these out: Jean Paul Boodhoo on Test Driven Development Part 1 Jean Paul Boodhoo on Test Driven Development Part 2 Jean Paul Boodhoo on Demystifying Design Patterns Part 1 Jean Paul Boodhoo on Demystifying Design Patterns Part 2 Jean Paul Boodhoo on Demystifying Design Patterns Part 3 Jean Paul Boodhoo on Demystifying Design Patterns Part 4 Jean Paul Boodhoo on Demystifying Design Patterns Part 5 OK, these will help you see how the terms I introduced are used. It will also introduce another tool called Resharper and how it can facilitate the TDD process. I couldn't recommend this tool enough when doing TDD. Seems like you are learning the process and you are just finding some of the problems that have already been solved with using other tools. I think I would be doing an injustice to the community, if I didn't update this by adding Kent Beck's new series on Test Driven Development on Pragmatic Programmer.
[ "unit-testing", "language-agnostic", "tdd" ]
43
50
21,251
11
0
2008-08-24T10:43:17.500000
2008-08-24T17:19:30.090000
24,986
24,987
How do I profile a Maven Application in Netbeans?
I've got a project using Maven 2 as the build tool. Now I am using Netbeans 6 as my IDE and really want to be able to use the profiler. Is there any way I can get this to work?
I thought this might be more complicated. It wasn't. To use the Netbeans profiler with your Maven 2 project you simply need to add a single pair of parameters when running your java app. Call up the project's Properties dialogue, select the "Run" tab and add something like the following to the jvm args: -agentpath:"C:\Program Files\NetBeans 6.0\profiler2\lib\deployed\jdk15\windows\profilerinterface.dll=\"C:\\\"Program Files\"\\\"NetBeans 6.0\"\\profiler2\\lib\\"",5140 This meant that now when I ran my app (F6) execution would wait for me to attach the profiler. Cue real time graphy goodness. Sweet.
How do I profile a Maven Application in Netbeans? I've got a project using Maven 2 as the build tool. Now I am using Netbeans 6 as my IDE and really want to be able to use the profiler. Is there any way I can get this to work?
TITLE: How do I profile a Maven Application in Netbeans? QUESTION: I've got a project using Maven 2 as the build tool. Now I am using Netbeans 6 as my IDE and really want to be able to use the profiler. Is there any way I can get this to work? ANSWER: I thought this might be more complicated. It wasn't. To use the Netbeans profiler with your Maven 2 project you simply need to add a single pair of parameters when running your java app. Call up the project's Properties dialogue, select the "Run" tab and add something like the following to the jvm args: -agentpath:"C:\Program Files\NetBeans 6.0\profiler2\lib\deployed\jdk15\windows\profilerinterface.dll=\"C:\\\"Program Files\"\\\"NetBeans 6.0\"\\profiler2\\lib\\"",5140 This meant that now when I ran my app (F6) execution would wait for me to attach the profiler. Cue real time graphy goodness. Sweet.
[ "maven-2", "netbeans", "profiling", "profiler" ]
1
1
2,831
1
0
2008-08-24T11:50:08.057000
2008-08-24T11:51:09.613000
24,991
25,877
Why can't I explicitly pass the type argument to a generic Java method?
I have defined a Java function: static List createEmptyList() { return new ArrayList (); } One way to call it is like so: List myList = createEmptyList(); // Compiles Why can't I call it by explicitly passing the generic type argument?: Object myObject = createEmtpyList (); // Doesn't compile. Why? I get the error Illegal start of expression from the compiler.
When the java compiler cannot infer the parameter type by itself for a static method, you can always pass it using the full qualified method name: Class. < Type > method(); Object list = Collections. emptyList();
Why can't I explicitly pass the type argument to a generic Java method? I have defined a Java function: static List createEmptyList() { return new ArrayList (); } One way to call it is like so: List myList = createEmptyList(); // Compiles Why can't I call it by explicitly passing the generic type argument?: Object myObject = createEmtpyList (); // Doesn't compile. Why? I get the error Illegal start of expression from the compiler.
TITLE: Why can't I explicitly pass the type argument to a generic Java method? QUESTION: I have defined a Java function: static List createEmptyList() { return new ArrayList (); } One way to call it is like so: List myList = createEmptyList(); // Compiles Why can't I call it by explicitly passing the generic type argument?: Object myObject = createEmtpyList (); // Doesn't compile. Why? I get the error Illegal start of expression from the compiler. ANSWER: When the java compiler cannot infer the parameter type by itself for a static method, you can always pass it using the full qualified method name: Class. < Type > method(); Object list = Collections. emptyList();
[ "java", "generics", "syntax" ]
32
49
29,906
4
0
2008-08-24T12:03:28.367000
2008-08-25T11:28:51.017000
24,993
25,075
InvalidOperationException while creating wcf web service instance
I have a WCF Web Service which is referenced from a class library. After the project is run, when creating the service client object from inside a class library, I receive an InvalidOperationException with message: Could not find default endpoint element that references contract 'MyServiceReference.IMyService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element. The code I am using to create the instance is: myServiceClient = new MyServiceClient(); where MyServiceClient inherits from System.ServiceModel.ClientBase How do I solve this? Note: I have a seperate console application which simply creates the same service object and makes calls to it and it works without no problems.
Here is my app.config file of the class library: You should put this configuration settings to main app's config file..NET application (which is calling your class library) uses data from it's own config file not from your library config file.
InvalidOperationException while creating wcf web service instance I have a WCF Web Service which is referenced from a class library. After the project is run, when creating the service client object from inside a class library, I receive an InvalidOperationException with message: Could not find default endpoint element that references contract 'MyServiceReference.IMyService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element. The code I am using to create the instance is: myServiceClient = new MyServiceClient(); where MyServiceClient inherits from System.ServiceModel.ClientBase How do I solve this? Note: I have a seperate console application which simply creates the same service object and makes calls to it and it works without no problems.
TITLE: InvalidOperationException while creating wcf web service instance QUESTION: I have a WCF Web Service which is referenced from a class library. After the project is run, when creating the service client object from inside a class library, I receive an InvalidOperationException with message: Could not find default endpoint element that references contract 'MyServiceReference.IMyService' in the ServiceModel client configuration section. This might be because no configuration file was found for your application, or because no endpoint element matching this contract could be found in the client element. The code I am using to create the instance is: myServiceClient = new MyServiceClient(); where MyServiceClient inherits from System.ServiceModel.ClientBase How do I solve this? Note: I have a seperate console application which simply creates the same service object and makes calls to it and it works without no problems. ANSWER: Here is my app.config file of the class library: You should put this configuration settings to main app's config file..NET application (which is calling your class library) uses data from it's own config file not from your library config file.
[ ".net", "wcf", "web-services" ]
6
4
10,742
4
0
2008-08-24T12:11:01.360000
2008-08-24T14:21:06.540000
25,007
25,024
Conditional formatting -- percentage to color conversion
What's the easiest way to convert a percentage to a color ranging from Green (100%) to Red (0%), with Yellow for 50%? I'm using plain 32bit RGB - so each component is an integer between 0 and 255. I'm doing this in C#, but I guess for a problem like this the language doesn't really matter that much. Based on Marius and Andy's answers I'm using the following solution: double red = (percent < 50)? 255: 256 - (percent - 50) * 5.12; double green = (percent > 50)? 255: percent * 5.12; var color = Color.FromArgb(255, (byte)red, (byte)green, 0); Works perfectly - Only adjustment I had to make from Marius solution was to use 256, as (255 - (percent - 50) * 5.12 yield -1 when 100%, resulting in Yellow for some reason in Silverlight (-1, 255, 0) -> Yellow...
I made this function in JavaScript. It returns the color is a css string. It takes the percentage as a variable, with a range from 0 to 100. The algorithm could be made in any language: function setColor(p){ var red = p<50? 255: Math.round(256 - (p-50)*5.12); var green = p>50? 255: Math.round((p)*5.12); return "rgb(" + red + "," + green + ",0)"; }
Conditional formatting -- percentage to color conversion What's the easiest way to convert a percentage to a color ranging from Green (100%) to Red (0%), with Yellow for 50%? I'm using plain 32bit RGB - so each component is an integer between 0 and 255. I'm doing this in C#, but I guess for a problem like this the language doesn't really matter that much. Based on Marius and Andy's answers I'm using the following solution: double red = (percent < 50)? 255: 256 - (percent - 50) * 5.12; double green = (percent > 50)? 255: percent * 5.12; var color = Color.FromArgb(255, (byte)red, (byte)green, 0); Works perfectly - Only adjustment I had to make from Marius solution was to use 256, as (255 - (percent - 50) * 5.12 yield -1 when 100%, resulting in Yellow for some reason in Silverlight (-1, 255, 0) -> Yellow...
TITLE: Conditional formatting -- percentage to color conversion QUESTION: What's the easiest way to convert a percentage to a color ranging from Green (100%) to Red (0%), with Yellow for 50%? I'm using plain 32bit RGB - so each component is an integer between 0 and 255. I'm doing this in C#, but I guess for a problem like this the language doesn't really matter that much. Based on Marius and Andy's answers I'm using the following solution: double red = (percent < 50)? 255: 256 - (percent - 50) * 5.12; double green = (percent > 50)? 255: percent * 5.12; var color = Color.FromArgb(255, (byte)red, (byte)green, 0); Works perfectly - Only adjustment I had to make from Marius solution was to use 256, as (255 - (percent - 50) * 5.12 yield -1 when 100%, resulting in Yellow for some reason in Silverlight (-1, 255, 0) -> Yellow... ANSWER: I made this function in JavaScript. It returns the color is a css string. It takes the percentage as a variable, with a range from 0 to 100. The algorithm could be made in any language: function setColor(p){ var red = p<50? 255: Math.round(256 - (p-50)*5.12); var green = p>50? 255: Math.round((p)*5.12); return "rgb(" + red + "," + green + ",0)"; }
[ "c#", "colors", "rgb" ]
21
14
15,291
9
0
2008-08-24T12:33:58.967000
2008-08-24T13:14:41.957000
25,033
25,043
I Am Not Getting the Result I Expect Using readLine() in Java
I am using the code snippet below, however it's not working quite as I understand it should. public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; try { line = br.readLine(); while(line!= null) { System.out.println(line); line = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } } From reading the Javadoc about readLine() it says: Reads a line of text. A line is considered to be terminated by any one of a line feed ( \n ), a carriage return ( \r ), or a carriage return followed immediately by a linefeed. Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached Throws: IOException - If an I/O error occurs From my understanding of this, readLine should return null the first time no input is entered other than a line termination, like \r. However, this code just ends up looping infinitely. After debugging, I have found that instead of null being returned when just a termination character is entered, it actually returns an empty string (""). This doesn't make sense to me. What am I not understanding correctly?
From my understanding of this, readLine should return null the first time no input is entered other than a line termination, like '\r'. That is not correct. readLine will return null if the end of the stream is reached. That is, for example, if you are reading a file, and the file ends, or if you're reading from a socket and the socket closses. But if you're simply reading the console input, hitting the return key on your keyboard does not constitute an end of stream. It's simply a character that is returned ( \n or \r\n depending on your OS). So, if you want to break on both the empty string and the end of line, you should do: while (line!= null &&!line.equals("")) Also, your current program should work as expected if you pipe some file directly into it, like so: java -cp. Echo < test.txt
I Am Not Getting the Result I Expect Using readLine() in Java I am using the code snippet below, however it's not working quite as I understand it should. public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; try { line = br.readLine(); while(line!= null) { System.out.println(line); line = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } } From reading the Javadoc about readLine() it says: Reads a line of text. A line is considered to be terminated by any one of a line feed ( \n ), a carriage return ( \r ), or a carriage return followed immediately by a linefeed. Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached Throws: IOException - If an I/O error occurs From my understanding of this, readLine should return null the first time no input is entered other than a line termination, like \r. However, this code just ends up looping infinitely. After debugging, I have found that instead of null being returned when just a termination character is entered, it actually returns an empty string (""). This doesn't make sense to me. What am I not understanding correctly?
TITLE: I Am Not Getting the Result I Expect Using readLine() in Java QUESTION: I am using the code snippet below, however it's not working quite as I understand it should. public static void main(String[] args) { BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line; try { line = br.readLine(); while(line!= null) { System.out.println(line); line = br.readLine(); } } catch (IOException e) { e.printStackTrace(); } } From reading the Javadoc about readLine() it says: Reads a line of text. A line is considered to be terminated by any one of a line feed ( \n ), a carriage return ( \r ), or a carriage return followed immediately by a linefeed. Returns: A String containing the contents of the line, not including any line-termination characters, or null if the end of the stream has been reached Throws: IOException - If an I/O error occurs From my understanding of this, readLine should return null the first time no input is entered other than a line termination, like \r. However, this code just ends up looping infinitely. After debugging, I have found that instead of null being returned when just a termination character is entered, it actually returns an empty string (""). This doesn't make sense to me. What am I not understanding correctly? ANSWER: From my understanding of this, readLine should return null the first time no input is entered other than a line termination, like '\r'. That is not correct. readLine will return null if the end of the stream is reached. That is, for example, if you are reading a file, and the file ends, or if you're reading from a socket and the socket closses. But if you're simply reading the console input, hitting the return key on your keyboard does not constitute an end of stream. It's simply a character that is returned ( \n or \r\n depending on your OS). So, if you want to break on both the empty string and the end of line, you should do: while (line!= null &&!line.equals("")) Also, your current program should work as expected if you pipe some file directly into it, like so: java -cp. Echo < test.txt
[ "java", "java-io" ]
5
10
4,938
3
0
2008-08-24T13:29:20.330000
2008-08-24T13:41:06.963000
25,041
25,053
span tag height in Firefox
Using CSS, I'm trying to specify the height of a span tag in Firefox, but it's just not accepting it (IE does). Firefox accepts the height if I use a div, but the problem with using a div is the annoying line break after it, which I can't have in this particular instance. I tried setting the CSS style attribute of: display: inline for the div, but Firefox seems to revert that to span behavior anyway and ignores the height attribute once again.
FirstDiv SecondDiv As long as the container for whatever is holding div's 1 and 2 is wide enough for them to fit, this should be fine.
span tag height in Firefox Using CSS, I'm trying to specify the height of a span tag in Firefox, but it's just not accepting it (IE does). Firefox accepts the height if I use a div, but the problem with using a div is the annoying line break after it, which I can't have in this particular instance. I tried setting the CSS style attribute of: display: inline for the div, but Firefox seems to revert that to span behavior anyway and ignores the height attribute once again.
TITLE: span tag height in Firefox QUESTION: Using CSS, I'm trying to specify the height of a span tag in Firefox, but it's just not accepting it (IE does). Firefox accepts the height if I use a div, but the problem with using a div is the annoying line break after it, which I can't have in this particular instance. I tried setting the CSS style attribute of: display: inline for the div, but Firefox seems to revert that to span behavior anyway and ignores the height attribute once again. ANSWER: FirstDiv SecondDiv As long as the container for whatever is holding div's 1 and 2 is wide enough for them to fit, this should be fine.
[ "html", "css", "firefox", "cross-browser" ]
17
17
32,360
9
0
2008-08-24T13:40:00.773000
2008-08-24T13:47:05.343000
25,046
25,435
Lisp Executable
I've just started learning Lisp and I can't figure out how to compile and link lisp code to an executable. I'm using clisp and clisp -c produces two files:.fas.lib What do I do next to get an executable?
I was actually trying to do this today, and I found typing this into the CLisp REPL worked: (EXT:SAVEINITMEM "executable.exe":QUIET t:INIT-FUNCTION 'main:EXECUTABLE t:NORC t) where main is the name of the function you want to call when the program launches,:QUIET t suppresses the startup banner, and:EXECUTABLE t makes a native executable. It can also be useful to call (EXT:EXIT) at the end of your main function in order to stop the user from getting an interactive lisp prompt when the program is done. EDIT: Reading the documentation, you may also want to add:NORC t (read link ). This suppresses loading the RC file (for example, ~/.clisprc.lisp ).
Lisp Executable I've just started learning Lisp and I can't figure out how to compile and link lisp code to an executable. I'm using clisp and clisp -c produces two files:.fas.lib What do I do next to get an executable?
TITLE: Lisp Executable QUESTION: I've just started learning Lisp and I can't figure out how to compile and link lisp code to an executable. I'm using clisp and clisp -c produces two files:.fas.lib What do I do next to get an executable? ANSWER: I was actually trying to do this today, and I found typing this into the CLisp REPL worked: (EXT:SAVEINITMEM "executable.exe":QUIET t:INIT-FUNCTION 'main:EXECUTABLE t:NORC t) where main is the name of the function you want to call when the program launches,:QUIET t suppresses the startup banner, and:EXECUTABLE t makes a native executable. It can also be useful to call (EXT:EXIT) at the end of your main function in order to stop the user from getting an interactive lisp prompt when the program is done. EDIT: Reading the documentation, you may also want to add:NORC t (read link ). This suppresses loading the RC file (for example, ~/.clisprc.lisp ).
[ "build", "lisp", "common-lisp", "clisp" ]
60
48
24,926
6
0
2008-08-24T13:42:35.320000
2008-08-24T23:10:00.980000
25,063
25,069
How to mentor a junior programmer
Does anyone have any suggestions on how to mentor a junior programmer? If you have mentored someone did you follow any process or was it quite informal? If you've been mentored in the past what kind of things did you find most helpful?
Try to set aside between 30-60 minutes a day to review their code together. If you can't do this, then try to get together to review their code whenever they make a code commit, unless it was very basic. Have them explain why they chose the approach they took in lieu of others. A process like this helps to establish a great relationship, as well as really stimulate the student to think on their own and be able to defend their decisions. Not only does the student end up with someone approachable whom they can trust, but you'll notice an improvement in their quality of code and logic almost immediately. Edit: Also, If you are unable to commit this much time to co-review with your junior, then you probably shouldn't be mentoring them and instead see if anyone else has a schedule that would allow it. The whole point of mentoring is to actively aid in the professional development of the student, and they're not going to learn much if proper attention and guidance is not given to them.
How to mentor a junior programmer Does anyone have any suggestions on how to mentor a junior programmer? If you have mentored someone did you follow any process or was it quite informal? If you've been mentored in the past what kind of things did you find most helpful?
TITLE: How to mentor a junior programmer QUESTION: Does anyone have any suggestions on how to mentor a junior programmer? If you have mentored someone did you follow any process or was it quite informal? If you've been mentored in the past what kind of things did you find most helpful? ANSWER: Try to set aside between 30-60 minutes a day to review their code together. If you can't do this, then try to get together to review their code whenever they make a code commit, unless it was very basic. Have them explain why they chose the approach they took in lieu of others. A process like this helps to establish a great relationship, as well as really stimulate the student to think on their own and be able to defend their decisions. Not only does the student end up with someone approachable whom they can trust, but you'll notice an improvement in their quality of code and logic almost immediately. Edit: Also, If you are unable to commit this much time to co-review with your junior, then you probably shouldn't be mentoring them and instead see if anyone else has a schedule that would allow it. The whole point of mentoring is to actively aid in the professional development of the student, and they're not going to learn much if proper attention and guidance is not given to them.
[ "language-agnostic" ]
47
48
5,880
12
0
2008-08-24T14:05:31.537000
2008-08-24T14:14:25.510000
25,128
25,139
How to create images in PHP
Is it possible to create images with PHP (as opposed to simply linking to them via HTML) and if so, where should I go first to learn about such a thing?
I prefer the GD library - check out the Examples, and this example: Outputs: (source: php.net ) See imagecreatetruecolor.
How to create images in PHP Is it possible to create images with PHP (as opposed to simply linking to them via HTML) and if so, where should I go first to learn about such a thing?
TITLE: How to create images in PHP QUESTION: Is it possible to create images with PHP (as opposed to simply linking to them via HTML) and if so, where should I go first to learn about such a thing? ANSWER: I prefer the GD library - check out the Examples, and this example: Outputs: (source: php.net ) See imagecreatetruecolor.
[ "php", "image" ]
6
12
743
7
0
2008-08-24T16:01:46.907000
2008-08-24T16:11:39.580000
25,132
25,173
Are named entities in HTML still necessary in the age of Unicode aware browsers?
I did a lot of PHP programming in the last years and one thing that keeps annoying me is the weak support for Unicode and multibyte strings (to be sure, natively there is none). For example, "htmlentities" seems to be a much used function in the PHP world and I found it to be absolutely annoying when you've put an effort into keeping every string localizable, only store UTF-8 in your database, only deliver UTF-8 webpages etc. Suddenly, somewhere between your database and the browser there's this hopelessly naive function pretending every byte is a character and messes everything up. I would just love to just dump this kind of functions, they seem totally superfluous. Is it still necessary these days to write 'ä' instead of 'ä'? At least my Firefox seems perfectly happy to display even the strangest Asian glyphs as long as they're served in a proper encoding. Update: To be more precise: Are named entities necessary for anything else than displaying HTML tags (as in "<" for "<") Update 2: @Konrad: Are you saying that, no, named entities are not needed? @Ross: But wouldn't it be better to sanitize user input when it's entered, to keep my output logic free from such issues? (assuming of course, that reliable sanitizing on input is possible - but then, if it isn't, can it be on output?)
Named entities in "real" XHTML (i.e. with application/xhtml+xml, rather than the more frequently-used text/html compatibility mode) are discouraged. Aside from the five defined in XML itself ( <, >, &, ", ' ), they'd all have to be defined in the DTD of the particular DocType you're using. That means your browser has to explicitly support that DocType, which is far from a given. Numbered entities, on the other hand, obviously only require a lookup table to get the right Unicode character. As for whether you need entities at all these days: you can pretty much expect any modern browser to support UTF-8. Therefore, as long as you can guarantee that the database, the markup and the web server all agree to serve that, ditch the entities.
Are named entities in HTML still necessary in the age of Unicode aware browsers? I did a lot of PHP programming in the last years and one thing that keeps annoying me is the weak support for Unicode and multibyte strings (to be sure, natively there is none). For example, "htmlentities" seems to be a much used function in the PHP world and I found it to be absolutely annoying when you've put an effort into keeping every string localizable, only store UTF-8 in your database, only deliver UTF-8 webpages etc. Suddenly, somewhere between your database and the browser there's this hopelessly naive function pretending every byte is a character and messes everything up. I would just love to just dump this kind of functions, they seem totally superfluous. Is it still necessary these days to write 'ä' instead of 'ä'? At least my Firefox seems perfectly happy to display even the strangest Asian glyphs as long as they're served in a proper encoding. Update: To be more precise: Are named entities necessary for anything else than displaying HTML tags (as in "<" for "<") Update 2: @Konrad: Are you saying that, no, named entities are not needed? @Ross: But wouldn't it be better to sanitize user input when it's entered, to keep my output logic free from such issues? (assuming of course, that reliable sanitizing on input is possible - but then, if it isn't, can it be on output?)
TITLE: Are named entities in HTML still necessary in the age of Unicode aware browsers? QUESTION: I did a lot of PHP programming in the last years and one thing that keeps annoying me is the weak support for Unicode and multibyte strings (to be sure, natively there is none). For example, "htmlentities" seems to be a much used function in the PHP world and I found it to be absolutely annoying when you've put an effort into keeping every string localizable, only store UTF-8 in your database, only deliver UTF-8 webpages etc. Suddenly, somewhere between your database and the browser there's this hopelessly naive function pretending every byte is a character and messes everything up. I would just love to just dump this kind of functions, they seem totally superfluous. Is it still necessary these days to write 'ä' instead of 'ä'? At least my Firefox seems perfectly happy to display even the strangest Asian glyphs as long as they're served in a proper encoding. Update: To be more precise: Are named entities necessary for anything else than displaying HTML tags (as in "<" for "<") Update 2: @Konrad: Are you saying that, no, named entities are not needed? @Ross: But wouldn't it be better to sanitize user input when it's entered, to keep my output logic free from such issues? (assuming of course, that reliable sanitizing on input is possible - but then, if it isn't, can it be on output?) ANSWER: Named entities in "real" XHTML (i.e. with application/xhtml+xml, rather than the more frequently-used text/html compatibility mode) are discouraged. Aside from the five defined in XML itself ( <, >, &, ", ' ), they'd all have to be defined in the DTD of the particular DocType you're using. That means your browser has to explicitly support that DocType, which is far from a given. Numbered entities, on the other hand, obviously only require a lookup table to get the right Unicode character. As for whether you need entities at all these days: you can pretty much expect any modern browser to support UTF-8. Therefore, as long as you can guarantee that the database, the markup and the web server all agree to serve that, ditch the entities.
[ "php", "html", "unicode", "internationalization" ]
17
7
951
3
0
2008-08-24T16:04:39.443000
2008-08-24T16:44:04.450000
25,137
25,255
What is your experience with software model checking?
What types of applications have you used model checking for? What model checking tool did you use? How would you summarize your experience w/ the technique, specifically in evaluating its effectiveness in delivering higher quality software? In the course of my studies, I had a chance to use Spin, and it aroused my curiosity as to how much actual model checking is going on and how much value are organizations getting out of it. In my work experience, I've worked on business applications, where there is (naturally) no consideration of applying formal verification to the logic. I'd really like to learn about SO folks model checking experience and thoughts on the subject. Will model checking ever become a more widely used developing practice that we should have in our toolkit?
I just finished a class on model checking and the big tools we used were Spin and SMV. We ended up using them to check properties on common synchronization problems, and I found SMV just a little bit easier to use. Although these tools were fun to use, I think they really shine when you combine them with something that dynamically enforces constraints on your program (so that it's a bit easier to verify 'useful' things about your program). We ended up taking the Spring WebFlow framework, which uses XML to write a state-machine like file that specifies which web pages can transition to which other ones, and using SMV to be able to perform verification on said applications ( shameless plug here ). To answer your last question, I think model checking is definitely useful to have, but I lean more towards using unit testing as a technique that makes me feel comfortable about delivering my final product.
What is your experience with software model checking? What types of applications have you used model checking for? What model checking tool did you use? How would you summarize your experience w/ the technique, specifically in evaluating its effectiveness in delivering higher quality software? In the course of my studies, I had a chance to use Spin, and it aroused my curiosity as to how much actual model checking is going on and how much value are organizations getting out of it. In my work experience, I've worked on business applications, where there is (naturally) no consideration of applying formal verification to the logic. I'd really like to learn about SO folks model checking experience and thoughts on the subject. Will model checking ever become a more widely used developing practice that we should have in our toolkit?
TITLE: What is your experience with software model checking? QUESTION: What types of applications have you used model checking for? What model checking tool did you use? How would you summarize your experience w/ the technique, specifically in evaluating its effectiveness in delivering higher quality software? In the course of my studies, I had a chance to use Spin, and it aroused my curiosity as to how much actual model checking is going on and how much value are organizations getting out of it. In my work experience, I've worked on business applications, where there is (naturally) no consideration of applying formal verification to the logic. I'd really like to learn about SO folks model checking experience and thoughts on the subject. Will model checking ever become a more widely used developing practice that we should have in our toolkit? ANSWER: I just finished a class on model checking and the big tools we used were Spin and SMV. We ended up using them to check properties on common synchronization problems, and I found SMV just a little bit easier to use. Although these tools were fun to use, I think they really shine when you combine them with something that dynamically enforces constraints on your program (so that it's a bit easier to verify 'useful' things about your program). We ended up taking the Spring WebFlow framework, which uses XML to write a state-machine like file that specifies which web pages can transition to which other ones, and using SMV to be able to perform verification on said applications ( shameless plug here ). To answer your last question, I think model checking is definitely useful to have, but I lean more towards using unit testing as a technique that makes me feel comfortable about delivering my final product.
[ "algorithm", "correctness", "formal-methods", "formal-verification", "model-checking" ]
6
3
1,883
5
0
2008-08-24T16:08:46.983000
2008-08-24T18:17:20.777000
25,142
25,150
Stored Procedure and Timeout
I'm running a long process stored procedure. I'm wondering if in case of a timeout or any case of disconnection with the database after initiating the call to the stored procedure. Is it still working and implementing the changes on the server? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
Anyway if the client is not there to commit at the end of the job the changes should be rolled back by the server. In other words, if you have a stored procedure making changes to the database and there is a possibility that the connection might disconnect in the middle, be sure to enclose all changes within a transaction.
Stored Procedure and Timeout I'm running a long process stored procedure. I'm wondering if in case of a timeout or any case of disconnection with the database after initiating the call to the stored procedure. Is it still working and implementing the changes on the server? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
TITLE: Stored Procedure and Timeout QUESTION: I'm running a long process stored procedure. I'm wondering if in case of a timeout or any case of disconnection with the database after initiating the call to the stored procedure. Is it still working and implementing the changes on the server? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ ANSWER: Anyway if the client is not there to commit at the end of the job the changes should be rolled back by the server. In other words, if you have a stored procedure making changes to the database and there is a possibility that the connection might disconnect in the middle, be sure to enclose all changes within a transaction.
[ "database", "stored-procedures", "timeout" ]
0
2
874
3
0
2008-08-24T16:16:21.647000
2008-08-24T16:23:04.780000
25,147
25,166
How can I merge PHP arrays?
I have two arrays of animals (for example). $array = array( array( 'id' => 1, 'name' => 'Cat', ), array( 'id' => 2, 'name' => 'Mouse', ) ); $array2 = array( array( 'id' => 2, 'age' => 321, ), array( 'id' => 1, 'age' => 123, ) ); How can I merge the two arrays into one by the ID?
This does what Erik suggested (id no. as array key) and merges vlaues in $array2 to $results. $results = array(); foreach($array as $subarray) { $results[$subarray['id']] = array('name' => $subarray['name']); } foreach($array2 as $subarray) { if(array_key_exists($subarray['id'], $results)) { // Loop through $subarray would go here if you have extra $results[$subarray['id']]['age'] = $subarray['age']; } }
How can I merge PHP arrays? I have two arrays of animals (for example). $array = array( array( 'id' => 1, 'name' => 'Cat', ), array( 'id' => 2, 'name' => 'Mouse', ) ); $array2 = array( array( 'id' => 2, 'age' => 321, ), array( 'id' => 1, 'age' => 123, ) ); How can I merge the two arrays into one by the ID?
TITLE: How can I merge PHP arrays? QUESTION: I have two arrays of animals (for example). $array = array( array( 'id' => 1, 'name' => 'Cat', ), array( 'id' => 2, 'name' => 'Mouse', ) ); $array2 = array( array( 'id' => 2, 'age' => 321, ), array( 'id' => 1, 'age' => 123, ) ); How can I merge the two arrays into one by the ID? ANSWER: This does what Erik suggested (id no. as array key) and merges vlaues in $array2 to $results. $results = array(); foreach($array as $subarray) { $results[$subarray['id']] = array('name' => $subarray['name']); } foreach($array2 as $subarray) { if(array_key_exists($subarray['id'], $results)) { // Loop through $subarray would go here if you have extra $results[$subarray['id']]['age'] = $subarray['age']; } }
[ "php", "arrays" ]
12
3
8,641
10
0
2008-08-24T16:21:17.763000
2008-08-24T16:38:01.733000
25,158
25,512
Building C# .NET windows application with multiple views
I'm rewriting an old application and use this as a good opportunity to try out C# and.NET development (I usually do a lot of plug-in stuff in C). The application is basically a timer collecting data. It has a start view with a button to start the measurement. During the measurement the app has five different views depending on what information the user wants to see. What is the best practice to switch between the views? From start to running? Between the running views? Ideas: Use one form and hide and show controls Use one start form and then a form with a TabControl Use six separate forms
Creating a bunch of overlaid panels is a design-time nightmare. I would suggest using a tab control with each "view" on a separate tab, and then picking the correct tab at runtime. You can avoid showing the tab headers by putting something like this in your form's Load event: tabControl1.Top = tabControl1.Top - tabControl1.ItemSize.Height; tabControl1.Height = tabControl1.Height + tabControl1.ItemSize.Height; tabControl1.Region = new Region(new RectangleF(tabPage1.Left, tabPage1.Top, tabPage1.Width, tabPage1.Height + tabControl1.ItemSize.Height));
Building C# .NET windows application with multiple views I'm rewriting an old application and use this as a good opportunity to try out C# and.NET development (I usually do a lot of plug-in stuff in C). The application is basically a timer collecting data. It has a start view with a button to start the measurement. During the measurement the app has five different views depending on what information the user wants to see. What is the best practice to switch between the views? From start to running? Between the running views? Ideas: Use one form and hide and show controls Use one start form and then a form with a TabControl Use six separate forms
TITLE: Building C# .NET windows application with multiple views QUESTION: I'm rewriting an old application and use this as a good opportunity to try out C# and.NET development (I usually do a lot of plug-in stuff in C). The application is basically a timer collecting data. It has a start view with a button to start the measurement. During the measurement the app has five different views depending on what information the user wants to see. What is the best practice to switch between the views? From start to running? Between the running views? Ideas: Use one form and hide and show controls Use one start form and then a form with a TabControl Use six separate forms ANSWER: Creating a bunch of overlaid panels is a design-time nightmare. I would suggest using a tab control with each "view" on a separate tab, and then picking the correct tab at runtime. You can avoid showing the tab headers by putting something like this in your form's Load event: tabControl1.Top = tabControl1.Top - tabControl1.ItemSize.Height; tabControl1.Height = tabControl1.Height + tabControl1.ItemSize.Height; tabControl1.Region = new Region(new RectangleF(tabPage1.Left, tabPage1.Top, tabPage1.Width, tabPage1.Height + tabControl1.ItemSize.Height));
[ "c#", ".net", "windows" ]
11
8
20,716
5
0
2008-08-24T16:31:25.713000
2008-08-25T00:43:07.200000
25,161
25,262
Tooltips on an image
I have an image and on it are logos (it's a map), I want to have a little box popup with information about that logo's location when the user moves their mouse over said logo. Can I do this without using a javascript framework and if so, are there any small libraries/scripts that will let me do such a thing?
Yes, you can do this without Javascript. Use an HTML image map, with title attributes, like this: The Stack Overflow logo refers to the image map, which defines a rectangle for each of the two words using an area tag. Each area tag's title element specifies the text that browsers generally show as a tooltip. The shape attribute can also specify a circle or polygon.
Tooltips on an image I have an image and on it are logos (it's a map), I want to have a little box popup with information about that logo's location when the user moves their mouse over said logo. Can I do this without using a javascript framework and if so, are there any small libraries/scripts that will let me do such a thing?
TITLE: Tooltips on an image QUESTION: I have an image and on it are logos (it's a map), I want to have a little box popup with information about that logo's location when the user moves their mouse over said logo. Can I do this without using a javascript framework and if so, are there any small libraries/scripts that will let me do such a thing? ANSWER: Yes, you can do this without Javascript. Use an HTML image map, with title attributes, like this: The Stack Overflow logo refers to the image map, which defines a rectangle for each of the two words using an area tag. Each area tag's title element specifies the text that browsers generally show as a tooltip. The shape attribute can also specify a circle or polygon.
[ "javascript", "html" ]
9
9
6,116
7
0
2008-08-24T16:32:34.257000
2008-08-24T18:24:07.343000
25,174
26,200
How to prevent session timeout in Symfony 1.0?
I've used the PHP MVC framework Symfony to build an on-demand web app. It has an annoying bug - the session expires after about 15-30 minutes of inactivity. There is a config directive to prevent session expiration but it does not work. Even workarounds such as this one did not help me. I intend not to migrate to Symfony 1.1 (which fixes this bug) in the foreseeable future. Has anyone been there and solved it? I would be most grateful for a hint or two!
I looked into it, and my coworker agrees that a heartbeat page call should work, you just have to make sure that the action invoked does reset the session timer (things like ajax field completion don't do this on their own).
How to prevent session timeout in Symfony 1.0? I've used the PHP MVC framework Symfony to build an on-demand web app. It has an annoying bug - the session expires after about 15-30 minutes of inactivity. There is a config directive to prevent session expiration but it does not work. Even workarounds such as this one did not help me. I intend not to migrate to Symfony 1.1 (which fixes this bug) in the foreseeable future. Has anyone been there and solved it? I would be most grateful for a hint or two!
TITLE: How to prevent session timeout in Symfony 1.0? QUESTION: I've used the PHP MVC framework Symfony to build an on-demand web app. It has an annoying bug - the session expires after about 15-30 minutes of inactivity. There is a config directive to prevent session expiration but it does not work. Even workarounds such as this one did not help me. I intend not to migrate to Symfony 1.1 (which fixes this bug) in the foreseeable future. Has anyone been there and solved it? I would be most grateful for a hint or two! ANSWER: I looked into it, and my coworker agrees that a heartbeat page call should work, you just have to make sure that the action invoked does reset the session timer (things like ajax field completion don't do this on their own).
[ "php", "symfony1" ]
4
2
2,195
4
0
2008-08-24T16:45:06.757000
2008-08-25T15:12:33.710000
25,182
25,293
What's optimal? UNION vs WHERE IN (str1, str2, str3)
I'm writing a program that sends an email out at a client's specific local time. I have a.NET method that takes a timezone & time and destination timezone and returns the time in that timezone. So my method is to select every distinct timezone in the database, check if it is the correct time using the method, then select every client out of the database with that timezone(s). The query will look like one of these. Keep in mind the order of the result set does not matter, so a union would be fine. Which runs faster, or do they really do the same thing? SELECT email FROM tClient WHERE timezoneID in (1, 4, 9) or SELECT email FROM tClient WHERE timezoneID = 1 UNION ALL SELECT email FROM tClient WHERE timezoneID = 4 UNION ALL SELECT email FROM tCLIENT WHERE timezoneID = 9 Edit: timezoneID is a foreign key to tTimezone, a table with primary key timezoneID and varchar(20) field timezoneName. Also, I went with WHERE IN since I didn't feel like opening up the analyzer. Edit 2: Query processes 200k rows in under 100 ms, so at this point I'm done.
Hey! These queries are not equivalent. Results will be same only if assuming that one email belongs only to the one time zone. Of course it does however SQL engine doesn't know that and tries to remove duplicities. So the first query should be faster. Always use UNION ALL, unless you know why you want to use UNION. If you are not sure what is difference see this SO question. Note: that yell belongs to previous version of question.
What's optimal? UNION vs WHERE IN (str1, str2, str3) I'm writing a program that sends an email out at a client's specific local time. I have a.NET method that takes a timezone & time and destination timezone and returns the time in that timezone. So my method is to select every distinct timezone in the database, check if it is the correct time using the method, then select every client out of the database with that timezone(s). The query will look like one of these. Keep in mind the order of the result set does not matter, so a union would be fine. Which runs faster, or do they really do the same thing? SELECT email FROM tClient WHERE timezoneID in (1, 4, 9) or SELECT email FROM tClient WHERE timezoneID = 1 UNION ALL SELECT email FROM tClient WHERE timezoneID = 4 UNION ALL SELECT email FROM tCLIENT WHERE timezoneID = 9 Edit: timezoneID is a foreign key to tTimezone, a table with primary key timezoneID and varchar(20) field timezoneName. Also, I went with WHERE IN since I didn't feel like opening up the analyzer. Edit 2: Query processes 200k rows in under 100 ms, so at this point I'm done.
TITLE: What's optimal? UNION vs WHERE IN (str1, str2, str3) QUESTION: I'm writing a program that sends an email out at a client's specific local time. I have a.NET method that takes a timezone & time and destination timezone and returns the time in that timezone. So my method is to select every distinct timezone in the database, check if it is the correct time using the method, then select every client out of the database with that timezone(s). The query will look like one of these. Keep in mind the order of the result set does not matter, so a union would be fine. Which runs faster, or do they really do the same thing? SELECT email FROM tClient WHERE timezoneID in (1, 4, 9) or SELECT email FROM tClient WHERE timezoneID = 1 UNION ALL SELECT email FROM tClient WHERE timezoneID = 4 UNION ALL SELECT email FROM tCLIENT WHERE timezoneID = 9 Edit: timezoneID is a foreign key to tTimezone, a table with primary key timezoneID and varchar(20) field timezoneName. Also, I went with WHERE IN since I didn't feel like opening up the analyzer. Edit 2: Query processes 200k rows in under 100 ms, so at this point I'm done. ANSWER: Hey! These queries are not equivalent. Results will be same only if assuming that one email belongs only to the one time zone. Of course it does however SQL engine doesn't know that and tries to remove duplicities. So the first query should be faster. Always use UNION ALL, unless you know why you want to use UNION. If you are not sure what is difference see this SO question. Note: that yell belongs to previous version of question.
[ "sql", "optimization" ]
8
3
6,954
7
0
2008-08-24T16:53:34.223000
2008-08-24T19:25:50.520000
25,192
1,067,648
Java SWIFT Library
I'm looking for a Java library for SWIFT messages. I want to parse SWIFT messages into an object model validate SWIFT messages (including SWIFT network validation rules) build / change SWIFT messages by using an object model Theoretically, I need to support all SWIFT message types. But at the moment I need MT103+, MT199, MT502, MT509, MT515 and MT535. So far I've looked at two libraries AnaSys Message Objects ( link text ) Datamation SWIFT Message Suite ( link text ) Both libraries allow to accomplish the tasks mentioned above but in both cases I'm not really happy. AnaSys uses a internal XML representation for all SWIFT messages which you need to know in order to access the fields of a message. And you need to operate on the DOM of the XML representation, there is no way to say "get the contents of field '50K' of the SWIFT message". And the Datamation library seems to have the nicer API but does not find all errors. So does anyone know other SWIFT libraries to use?
SWIFT is releasing a "Standards Developer Kit" which includes an "MT/XML Schema Library". From the doc: "The MT/XML Schema Library is a complete set of XML schema definitions for MT messages, and software which shows how to convert messages from an MT format to an MT XML representation and back. This approach allows XML integration between applications while the MT (FIN) format will continue to be transported over the SWIFT network." Java source code will also be made available, again from the doc: "Working sample Java source code that converts a message in MT format to an XML instance and from an XML instance to a message in MT format." See: http://www.swift.com/support/drc/develop/standards.page This can be a great aid in dealing with FIN messages in XML syntax.
Java SWIFT Library I'm looking for a Java library for SWIFT messages. I want to parse SWIFT messages into an object model validate SWIFT messages (including SWIFT network validation rules) build / change SWIFT messages by using an object model Theoretically, I need to support all SWIFT message types. But at the moment I need MT103+, MT199, MT502, MT509, MT515 and MT535. So far I've looked at two libraries AnaSys Message Objects ( link text ) Datamation SWIFT Message Suite ( link text ) Both libraries allow to accomplish the tasks mentioned above but in both cases I'm not really happy. AnaSys uses a internal XML representation for all SWIFT messages which you need to know in order to access the fields of a message. And you need to operate on the DOM of the XML representation, there is no way to say "get the contents of field '50K' of the SWIFT message". And the Datamation library seems to have the nicer API but does not find all errors. So does anyone know other SWIFT libraries to use?
TITLE: Java SWIFT Library QUESTION: I'm looking for a Java library for SWIFT messages. I want to parse SWIFT messages into an object model validate SWIFT messages (including SWIFT network validation rules) build / change SWIFT messages by using an object model Theoretically, I need to support all SWIFT message types. But at the moment I need MT103+, MT199, MT502, MT509, MT515 and MT535. So far I've looked at two libraries AnaSys Message Objects ( link text ) Datamation SWIFT Message Suite ( link text ) Both libraries allow to accomplish the tasks mentioned above but in both cases I'm not really happy. AnaSys uses a internal XML representation for all SWIFT messages which you need to know in order to access the fields of a message. And you need to operate on the DOM of the XML representation, there is no way to say "get the contents of field '50K' of the SWIFT message". And the Datamation library seems to have the nicer API but does not find all errors. So does anyone know other SWIFT libraries to use? ANSWER: SWIFT is releasing a "Standards Developer Kit" which includes an "MT/XML Schema Library". From the doc: "The MT/XML Schema Library is a complete set of XML schema definitions for MT messages, and software which shows how to convert messages from an MT format to an MT XML representation and back. This approach allows XML integration between applications while the MT (FIN) format will continue to be transported over the SWIFT network." Java source code will also be made available, again from the doc: "Working sample Java source code that converts a message in MT format to an XML instance and from an XML instance to a message in MT format." See: http://www.swift.com/support/drc/develop/standards.page This can be a great aid in dealing with FIN messages in XML syntax.
[ "java", "swift-mt" ]
33
21
52,202
9
0
2008-08-24T17:05:40.997000
2009-07-01T06:59:19.537000
25,200
33,726
C#.NET Winforms: Is it possible to override Label.Autosize?
I don't like the AutoSize property of the Label control. I have a custom Label that draws a fancy rounded border among other things. I'm placing a AutoSize = false in my constructor, however, when I place it in design mode, the property always is True. I have overridden other properties with success but this one is happily ignoring me. Does anybody has a clue if this is "by MS design"? Here's the full source code of my Label in case anyone is interested. using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace Dentactil.UI.WinControls { [DefaultProperty("TextString")] [DefaultEvent("TextClick")] public partial class RoundedLabel: UserControl { private static readonly Color DEFAULT_BORDER_COLOR = Color.FromArgb( 132, 100, 161 ); private const float DEFAULT_BORDER_WIDTH = 2.0F; private const int DEFAULT_ROUNDED_WIDTH = 16; private const int DEFAULT_ROUNDED_HEIGHT = 12; private Color mBorderColor = DEFAULT_BORDER_COLOR; private float mBorderWidth = DEFAULT_BORDER_WIDTH; private int mRoundedWidth = DEFAULT_ROUNDED_WIDTH; private int mRoundedHeight = DEFAULT_ROUNDED_HEIGHT; public event EventHandler TextClick; private Padding mPadding = new Padding(8); public RoundedLabel() { InitializeComponent(); } public Cursor TextCursor { get { return lblText.Cursor; } set { lblText.Cursor = value; } } public Padding TextPadding { get { return mPadding; } set { mPadding = value; UpdateInternalBounds(); } } public ContentAlignment TextAlign { get { return lblText.TextAlign; } set { lblText.TextAlign = value; } } public string TextString { get { return lblText.Text; } set { lblText.Text = value; } } public override Font Font { get { return base.Font; } set { base.Font = value; lblText.Font = value; } } public override Color ForeColor { get { return base.ForeColor; } set { base.ForeColor = value; lblText.ForeColor = value; } } public Color BorderColor { get { return mBorderColor; } set { mBorderColor = value; Invalidate(); } } [DefaultValue(DEFAULT_BORDER_WIDTH)] public float BorderWidth { get { return mBorderWidth; } set { mBorderWidth = value; Invalidate(); } } [DefaultValue(DEFAULT_ROUNDED_WIDTH)] public int RoundedWidth { get { return mRoundedWidth; } set { mRoundedWidth = value; Invalidate(); } } [DefaultValue(DEFAULT_ROUNDED_HEIGHT)] public int RoundedHeight { get { return mRoundedHeight; } set { mRoundedHeight = value; Invalidate(); } } private void UpdateInternalBounds() { lblText.Left = mPadding.Left; lblText.Top = mPadding.Top; int width = Width - mPadding.Right - mPadding.Left; lblText.Width = width > 0? width: 0; int heigth = Height - mPadding.Bottom - mPadding.Top; lblText.Height = heigth > 0? heigth: 0; } protected override void OnLoad(EventArgs e) { UpdateInternalBounds(); base.OnLoad(e); } protected override void OnPaint(PaintEventArgs e) { SmoothingMode smoothingMode = e.Graphics.SmoothingMode; e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; int roundedWidth = RoundedWidth > (Width - 1)/2? (Width - 1)/2: RoundedWidth; int roundedHeight = RoundedHeight > (Height - 1)/2? (Height - 1)/2: RoundedHeight; GraphicsPath path = new GraphicsPath(); path.AddLine(0, roundedHeight, 0, Height - 1 - roundedHeight); path.AddArc(new RectangleF(0, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 180, -90); path.AddLine(roundedWidth, Height - 1, Width - 1 - 2*roundedWidth, Height - 1); path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 90, -90); path.AddLine(Width - 1, Height - 1 - roundedHeight, Width - 1, roundedHeight); path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, 0, 2*roundedWidth, 2*roundedHeight), 0, -90); path.AddLine(Width - 1 - roundedWidth, 0, roundedWidth, 0); path.AddArc(new RectangleF(0, 0, 2*roundedWidth, 2*roundedHeight), -90, -90); e.Graphics.DrawPath(new Pen(new SolidBrush(BorderColor), BorderWidth), path); e.Graphics.SmoothingMode = smoothingMode; base.OnPaint(e); } protected override void OnResize(EventArgs e) { UpdateInternalBounds(); base.OnResize(e); } private void lblText_Click(object sender, EventArgs e) { if (TextClick!= null) { TextClick(this, e); } } } } (there are some issues with Stack Overflow's markup and the Underscore, but it's easy to follow the code). I have actually removed that override some time ago when I saw that it wasn't working. I'll add it again now and test. Basically I want to replace the Label with some new label called: IWillNotAutoSizeLabel;) I basically hate the autosize property "on by default".
I've seen similar behaviour when setting certain properties of controls in the constructor of the form itself. They seem to revert back to their design-time defaults. I notice you're already overriding the OnLoad method. Have you tried setting AutoSize = false there? Or are you mainly concerned with providing a default value of false?
C#.NET Winforms: Is it possible to override Label.Autosize? I don't like the AutoSize property of the Label control. I have a custom Label that draws a fancy rounded border among other things. I'm placing a AutoSize = false in my constructor, however, when I place it in design mode, the property always is True. I have overridden other properties with success but this one is happily ignoring me. Does anybody has a clue if this is "by MS design"? Here's the full source code of my Label in case anyone is interested. using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace Dentactil.UI.WinControls { [DefaultProperty("TextString")] [DefaultEvent("TextClick")] public partial class RoundedLabel: UserControl { private static readonly Color DEFAULT_BORDER_COLOR = Color.FromArgb( 132, 100, 161 ); private const float DEFAULT_BORDER_WIDTH = 2.0F; private const int DEFAULT_ROUNDED_WIDTH = 16; private const int DEFAULT_ROUNDED_HEIGHT = 12; private Color mBorderColor = DEFAULT_BORDER_COLOR; private float mBorderWidth = DEFAULT_BORDER_WIDTH; private int mRoundedWidth = DEFAULT_ROUNDED_WIDTH; private int mRoundedHeight = DEFAULT_ROUNDED_HEIGHT; public event EventHandler TextClick; private Padding mPadding = new Padding(8); public RoundedLabel() { InitializeComponent(); } public Cursor TextCursor { get { return lblText.Cursor; } set { lblText.Cursor = value; } } public Padding TextPadding { get { return mPadding; } set { mPadding = value; UpdateInternalBounds(); } } public ContentAlignment TextAlign { get { return lblText.TextAlign; } set { lblText.TextAlign = value; } } public string TextString { get { return lblText.Text; } set { lblText.Text = value; } } public override Font Font { get { return base.Font; } set { base.Font = value; lblText.Font = value; } } public override Color ForeColor { get { return base.ForeColor; } set { base.ForeColor = value; lblText.ForeColor = value; } } public Color BorderColor { get { return mBorderColor; } set { mBorderColor = value; Invalidate(); } } [DefaultValue(DEFAULT_BORDER_WIDTH)] public float BorderWidth { get { return mBorderWidth; } set { mBorderWidth = value; Invalidate(); } } [DefaultValue(DEFAULT_ROUNDED_WIDTH)] public int RoundedWidth { get { return mRoundedWidth; } set { mRoundedWidth = value; Invalidate(); } } [DefaultValue(DEFAULT_ROUNDED_HEIGHT)] public int RoundedHeight { get { return mRoundedHeight; } set { mRoundedHeight = value; Invalidate(); } } private void UpdateInternalBounds() { lblText.Left = mPadding.Left; lblText.Top = mPadding.Top; int width = Width - mPadding.Right - mPadding.Left; lblText.Width = width > 0? width: 0; int heigth = Height - mPadding.Bottom - mPadding.Top; lblText.Height = heigth > 0? heigth: 0; } protected override void OnLoad(EventArgs e) { UpdateInternalBounds(); base.OnLoad(e); } protected override void OnPaint(PaintEventArgs e) { SmoothingMode smoothingMode = e.Graphics.SmoothingMode; e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; int roundedWidth = RoundedWidth > (Width - 1)/2? (Width - 1)/2: RoundedWidth; int roundedHeight = RoundedHeight > (Height - 1)/2? (Height - 1)/2: RoundedHeight; GraphicsPath path = new GraphicsPath(); path.AddLine(0, roundedHeight, 0, Height - 1 - roundedHeight); path.AddArc(new RectangleF(0, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 180, -90); path.AddLine(roundedWidth, Height - 1, Width - 1 - 2*roundedWidth, Height - 1); path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 90, -90); path.AddLine(Width - 1, Height - 1 - roundedHeight, Width - 1, roundedHeight); path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, 0, 2*roundedWidth, 2*roundedHeight), 0, -90); path.AddLine(Width - 1 - roundedWidth, 0, roundedWidth, 0); path.AddArc(new RectangleF(0, 0, 2*roundedWidth, 2*roundedHeight), -90, -90); e.Graphics.DrawPath(new Pen(new SolidBrush(BorderColor), BorderWidth), path); e.Graphics.SmoothingMode = smoothingMode; base.OnPaint(e); } protected override void OnResize(EventArgs e) { UpdateInternalBounds(); base.OnResize(e); } private void lblText_Click(object sender, EventArgs e) { if (TextClick!= null) { TextClick(this, e); } } } } (there are some issues with Stack Overflow's markup and the Underscore, but it's easy to follow the code). I have actually removed that override some time ago when I saw that it wasn't working. I'll add it again now and test. Basically I want to replace the Label with some new label called: IWillNotAutoSizeLabel;) I basically hate the autosize property "on by default".
TITLE: C#.NET Winforms: Is it possible to override Label.Autosize? QUESTION: I don't like the AutoSize property of the Label control. I have a custom Label that draws a fancy rounded border among other things. I'm placing a AutoSize = false in my constructor, however, when I place it in design mode, the property always is True. I have overridden other properties with success but this one is happily ignoring me. Does anybody has a clue if this is "by MS design"? Here's the full source code of my Label in case anyone is interested. using System; using System.ComponentModel; using System.Drawing; using System.Drawing.Drawing2D; using System.Windows.Forms; namespace Dentactil.UI.WinControls { [DefaultProperty("TextString")] [DefaultEvent("TextClick")] public partial class RoundedLabel: UserControl { private static readonly Color DEFAULT_BORDER_COLOR = Color.FromArgb( 132, 100, 161 ); private const float DEFAULT_BORDER_WIDTH = 2.0F; private const int DEFAULT_ROUNDED_WIDTH = 16; private const int DEFAULT_ROUNDED_HEIGHT = 12; private Color mBorderColor = DEFAULT_BORDER_COLOR; private float mBorderWidth = DEFAULT_BORDER_WIDTH; private int mRoundedWidth = DEFAULT_ROUNDED_WIDTH; private int mRoundedHeight = DEFAULT_ROUNDED_HEIGHT; public event EventHandler TextClick; private Padding mPadding = new Padding(8); public RoundedLabel() { InitializeComponent(); } public Cursor TextCursor { get { return lblText.Cursor; } set { lblText.Cursor = value; } } public Padding TextPadding { get { return mPadding; } set { mPadding = value; UpdateInternalBounds(); } } public ContentAlignment TextAlign { get { return lblText.TextAlign; } set { lblText.TextAlign = value; } } public string TextString { get { return lblText.Text; } set { lblText.Text = value; } } public override Font Font { get { return base.Font; } set { base.Font = value; lblText.Font = value; } } public override Color ForeColor { get { return base.ForeColor; } set { base.ForeColor = value; lblText.ForeColor = value; } } public Color BorderColor { get { return mBorderColor; } set { mBorderColor = value; Invalidate(); } } [DefaultValue(DEFAULT_BORDER_WIDTH)] public float BorderWidth { get { return mBorderWidth; } set { mBorderWidth = value; Invalidate(); } } [DefaultValue(DEFAULT_ROUNDED_WIDTH)] public int RoundedWidth { get { return mRoundedWidth; } set { mRoundedWidth = value; Invalidate(); } } [DefaultValue(DEFAULT_ROUNDED_HEIGHT)] public int RoundedHeight { get { return mRoundedHeight; } set { mRoundedHeight = value; Invalidate(); } } private void UpdateInternalBounds() { lblText.Left = mPadding.Left; lblText.Top = mPadding.Top; int width = Width - mPadding.Right - mPadding.Left; lblText.Width = width > 0? width: 0; int heigth = Height - mPadding.Bottom - mPadding.Top; lblText.Height = heigth > 0? heigth: 0; } protected override void OnLoad(EventArgs e) { UpdateInternalBounds(); base.OnLoad(e); } protected override void OnPaint(PaintEventArgs e) { SmoothingMode smoothingMode = e.Graphics.SmoothingMode; e.Graphics.SmoothingMode = SmoothingMode.AntiAlias; int roundedWidth = RoundedWidth > (Width - 1)/2? (Width - 1)/2: RoundedWidth; int roundedHeight = RoundedHeight > (Height - 1)/2? (Height - 1)/2: RoundedHeight; GraphicsPath path = new GraphicsPath(); path.AddLine(0, roundedHeight, 0, Height - 1 - roundedHeight); path.AddArc(new RectangleF(0, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 180, -90); path.AddLine(roundedWidth, Height - 1, Width - 1 - 2*roundedWidth, Height - 1); path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, Height - 1 - 2*roundedHeight, 2*roundedWidth, 2*roundedHeight), 90, -90); path.AddLine(Width - 1, Height - 1 - roundedHeight, Width - 1, roundedHeight); path.AddArc(new RectangleF(Width - 1 - 2*roundedWidth, 0, 2*roundedWidth, 2*roundedHeight), 0, -90); path.AddLine(Width - 1 - roundedWidth, 0, roundedWidth, 0); path.AddArc(new RectangleF(0, 0, 2*roundedWidth, 2*roundedHeight), -90, -90); e.Graphics.DrawPath(new Pen(new SolidBrush(BorderColor), BorderWidth), path); e.Graphics.SmoothingMode = smoothingMode; base.OnPaint(e); } protected override void OnResize(EventArgs e) { UpdateInternalBounds(); base.OnResize(e); } private void lblText_Click(object sender, EventArgs e) { if (TextClick!= null) { TextClick(this, e); } } } } (there are some issues with Stack Overflow's markup and the Underscore, but it's easy to follow the code). I have actually removed that override some time ago when I saw that it wasn't working. I'll add it again now and test. Basically I want to replace the Label with some new label called: IWillNotAutoSizeLabel;) I basically hate the autosize property "on by default". ANSWER: I've seen similar behaviour when setting certain properties of controls in the constructor of the form itself. They seem to revert back to their design-time defaults. I notice you're already overriding the OnLoad method. Have you tried setting AutoSize = false there? Or are you mainly concerned with providing a default value of false?
[ "c#", "winforms" ]
7
3
7,161
5
0
2008-08-24T17:17:51.763000
2008-08-29T00:53:56.283000
25,224
25,248
joining latest of various usermetadata tags to user rows
I have a postgres database with a user table (userid, firstname, lastname) and a usermetadata table (userid, code, content, created datetime). I store various information about each user in the usermetadata table by code and keep a full history. so for example, a user (userid 15) has the following metadata: 15, 'QHS', '20', '2008-08-24 13:36:33.465567-04' 15, 'QHE', '8', '2008-08-24 12:07:08.660519-04' 15, 'QHS', '21', '2008-08-24 09:44:44.39354-04' 15, 'QHE', '10', '2008-08-24 08:47:57.672058-04' I need to fetch a list of all my users and the most recent value of each of various usermetadata codes. I did this programmatically and it was, of course godawful slow. The best I could figure out to do it in SQL was to join sub-selects, which were also slow and I had to do one for each code.
I suppose you're not willing to modify your schema, so I'm afraid my answe might not be of much help, but here goes... One possible solution would be to have the time field empty until it was replaced by a newer value, when you insert the 'deprecation date' instead. Another way is to expand the table with an 'active' column, but that would introduce some redundancy. The classic solution would be to have both 'Valid-From' and 'Valid-To' fields where the 'Valid-To' fields are blank until some other entry becomes valid. This can be handled easily by using triggers or similar. Using constraints to make sure there is only one item of each type that is valid will ensure data integrity. Common to these is that there is a single way of determining the set of current fields. You'd simply select all entries with the active user and a NULL 'Valid-To' or 'deprecation date' or a true 'active'. You might be interested in taking a look at the Wikipedia entry on temporal databases and the article A consensus glossary of temporal database concepts.
joining latest of various usermetadata tags to user rows I have a postgres database with a user table (userid, firstname, lastname) and a usermetadata table (userid, code, content, created datetime). I store various information about each user in the usermetadata table by code and keep a full history. so for example, a user (userid 15) has the following metadata: 15, 'QHS', '20', '2008-08-24 13:36:33.465567-04' 15, 'QHE', '8', '2008-08-24 12:07:08.660519-04' 15, 'QHS', '21', '2008-08-24 09:44:44.39354-04' 15, 'QHE', '10', '2008-08-24 08:47:57.672058-04' I need to fetch a list of all my users and the most recent value of each of various usermetadata codes. I did this programmatically and it was, of course godawful slow. The best I could figure out to do it in SQL was to join sub-selects, which were also slow and I had to do one for each code.
TITLE: joining latest of various usermetadata tags to user rows QUESTION: I have a postgres database with a user table (userid, firstname, lastname) and a usermetadata table (userid, code, content, created datetime). I store various information about each user in the usermetadata table by code and keep a full history. so for example, a user (userid 15) has the following metadata: 15, 'QHS', '20', '2008-08-24 13:36:33.465567-04' 15, 'QHE', '8', '2008-08-24 12:07:08.660519-04' 15, 'QHS', '21', '2008-08-24 09:44:44.39354-04' 15, 'QHE', '10', '2008-08-24 08:47:57.672058-04' I need to fetch a list of all my users and the most recent value of each of various usermetadata codes. I did this programmatically and it was, of course godawful slow. The best I could figure out to do it in SQL was to join sub-selects, which were also slow and I had to do one for each code. ANSWER: I suppose you're not willing to modify your schema, so I'm afraid my answe might not be of much help, but here goes... One possible solution would be to have the time field empty until it was replaced by a newer value, when you insert the 'deprecation date' instead. Another way is to expand the table with an 'active' column, but that would introduce some redundancy. The classic solution would be to have both 'Valid-From' and 'Valid-To' fields where the 'Valid-To' fields are blank until some other entry becomes valid. This can be handled easily by using triggers or similar. Using constraints to make sure there is only one item of each type that is valid will ensure data integrity. Common to these is that there is a single way of determining the set of current fields. You'd simply select all entries with the active user and a NULL 'Valid-To' or 'deprecation date' or a true 'active'. You might be interested in taking a look at the Wikipedia entry on temporal databases and the article A consensus glossary of temporal database concepts.
[ "database", "postgresql" ]
2
1
370
3
0
2008-08-24T17:48:12.983000
2008-08-24T18:11:02.603000
25,225
25,231
Combining values from different files into one CSV file
I have a couple of files containing a value in each line. EDIT: I figured out the answer to this question while in the midst of writing the post and didn't realize I had posted it by mistake in its incomplete state. I was trying to do: paste -d ',' file1 file2 file 3 file 4 > file5.csv and was getting a weird output. I later realized that was happening because some files had both a carriage return and a newline character at the end of the line while others had only the newline character. I got to always remember to pay attention to those things. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
file 1: 1 2 3 file2: 2 4 6 paste --delimiters=\; file1 file2 Will yield: 1;2 3;4 5;6
Combining values from different files into one CSV file I have a couple of files containing a value in each line. EDIT: I figured out the answer to this question while in the midst of writing the post and didn't realize I had posted it by mistake in its incomplete state. I was trying to do: paste -d ',' file1 file2 file 3 file 4 > file5.csv and was getting a weird output. I later realized that was happening because some files had both a carriage return and a newline character at the end of the line while others had only the newline character. I got to always remember to pay attention to those things. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
TITLE: Combining values from different files into one CSV file QUESTION: I have a couple of files containing a value in each line. EDIT: I figured out the answer to this question while in the midst of writing the post and didn't realize I had posted it by mistake in its incomplete state. I was trying to do: paste -d ',' file1 file2 file 3 file 4 > file5.csv and was getting a weird output. I later realized that was happening because some files had both a carriage return and a newline character at the end of the line while others had only the newline character. I got to always remember to pay attention to those things. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ ANSWER: file 1: 1 2 3 file2: 2 4 6 paste --delimiters=\; file1 file2 Will yield: 1;2 3;4 5;6
[ "regex", "linux", "unix", "shell" ]
2
2
1,111
5
0
2008-08-24T17:49:02.390000
2008-08-24T17:54:52.437000
25,252
340,769
Remote Debugging PHP Command Line Scripts with Zend?
I'm using Zend Studio to do remote debugging of my php scripts on a dev server. It works great for web code, but can I make it work with command line scripts? I have several helper apps to make my application run. It would be really useful to fire up the remote debugger through command line instead of a web browser so I can test these out. I assume it's possible, since I think Zend is using xdebug to talk to Eclipse. Apparently, it adds some parameters to the request to wake the Zend code up on a request. I'm guessing I'd need to tap into that? UPDATE I ended up using xdebug with protoeditor over X to do my debugging.
I was able to get remote CLI debugging working in Eclipse, using xdebug, though I've not tried it with the zend debugger. I would assume this should work the same with ZSfE, if that's the "Zend Studio" you're using.
Remote Debugging PHP Command Line Scripts with Zend? I'm using Zend Studio to do remote debugging of my php scripts on a dev server. It works great for web code, but can I make it work with command line scripts? I have several helper apps to make my application run. It would be really useful to fire up the remote debugger through command line instead of a web browser so I can test these out. I assume it's possible, since I think Zend is using xdebug to talk to Eclipse. Apparently, it adds some parameters to the request to wake the Zend code up on a request. I'm guessing I'd need to tap into that? UPDATE I ended up using xdebug with protoeditor over X to do my debugging.
TITLE: Remote Debugging PHP Command Line Scripts with Zend? QUESTION: I'm using Zend Studio to do remote debugging of my php scripts on a dev server. It works great for web code, but can I make it work with command line scripts? I have several helper apps to make my application run. It would be really useful to fire up the remote debugger through command line instead of a web browser so I can test these out. I assume it's possible, since I think Zend is using xdebug to talk to Eclipse. Apparently, it adds some parameters to the request to wake the Zend code up on a request. I'm guessing I'd need to tap into that? UPDATE I ended up using xdebug with protoeditor over X to do my debugging. ANSWER: I was able to get remote CLI debugging working in Eclipse, using xdebug, though I've not tried it with the zend debugger. I would assume this should work the same with ZSfE, if that's the "Zend Studio" you're using.
[ "php", "debugging", "xdebug", "zend-studio" ]
1
4
3,398
5
0
2008-08-24T18:14:54.887000
2008-12-04T14:32:47.310000
25,259
25,486
How does Stack Overflow generate its SEO-friendly URLs?
What is a good complete regular expression or some other process that would take the title: How do you change a title to be part of the URL like Stack Overflow? and turn it into how-do-you-change-a-title-to-be-part-of-the-url-like-stack-overflow that is used in the SEO-friendly URLs on Stack Overflow? The development environment I am using is Ruby on Rails, but if there are some other platform-specific solutions (.NET, PHP, Django ), I would love to see those too. I am sure I (or another reader) will come across the same problem on a different platform down the line. I am using custom routes, and I mainly want to know how to alter the string to all special characters are removed, it's all lowercase, and all whitespace is replaced.
Here's how we do it. Note that there are probably more edge conditions than you realize at first glance. This is the second version, unrolled for 5x more performance (and yes, I benchmarked it). I figured I'd optimize it because this function can be called hundreds of times per page. /// /// Produces optional, URL-friendly version of a title, "like-this-one". /// hand-tuned for speed, reflects performance refactoring contributed /// by John Gietzen (user otac0n) /// public static string URLFriendly(string title) { if (title == null) return ""; const int maxlen = 80; int len = title.Length; bool prevdash = false; var sb = new StringBuilder(len); char c; for (int i = 0; i < len; i++) { c = title[i]; if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) { sb.Append(c); prevdash = false; } else if (c >= 'A' && c <= 'Z') { // tricky way to convert to lowercase sb.Append((char)(c | 32)); prevdash = false; } else if (c == ' ' || c == ',' || c == '.' || c == '/' || c == '\\' || c == '-' || c == '_' || c == '=') { if (!prevdash && sb.Length > 0) { sb.Append('-'); prevdash = true; } } else if ((int)c >= 128) { int prevlen = sb.Length; sb.Append(RemapInternationalCharToAscii(c)); if (prevlen!= sb.Length) prevdash = false; } if (i == maxlen) break; } if (prevdash) return sb.ToString().Substring(0, sb.Length - 1); else return sb.ToString(); } To see the previous version of the code this replaced (but is functionally equivalent to, and 5x faster), view revision history of this post (click the date link). Also, the RemapInternationalCharToAscii method source code can be found here.
How does Stack Overflow generate its SEO-friendly URLs? What is a good complete regular expression or some other process that would take the title: How do you change a title to be part of the URL like Stack Overflow? and turn it into how-do-you-change-a-title-to-be-part-of-the-url-like-stack-overflow that is used in the SEO-friendly URLs on Stack Overflow? The development environment I am using is Ruby on Rails, but if there are some other platform-specific solutions (.NET, PHP, Django ), I would love to see those too. I am sure I (or another reader) will come across the same problem on a different platform down the line. I am using custom routes, and I mainly want to know how to alter the string to all special characters are removed, it's all lowercase, and all whitespace is replaced.
TITLE: How does Stack Overflow generate its SEO-friendly URLs? QUESTION: What is a good complete regular expression or some other process that would take the title: How do you change a title to be part of the URL like Stack Overflow? and turn it into how-do-you-change-a-title-to-be-part-of-the-url-like-stack-overflow that is used in the SEO-friendly URLs on Stack Overflow? The development environment I am using is Ruby on Rails, but if there are some other platform-specific solutions (.NET, PHP, Django ), I would love to see those too. I am sure I (or another reader) will come across the same problem on a different platform down the line. I am using custom routes, and I mainly want to know how to alter the string to all special characters are removed, it's all lowercase, and all whitespace is replaced. ANSWER: Here's how we do it. Note that there are probably more edge conditions than you realize at first glance. This is the second version, unrolled for 5x more performance (and yes, I benchmarked it). I figured I'd optimize it because this function can be called hundreds of times per page. /// /// Produces optional, URL-friendly version of a title, "like-this-one". /// hand-tuned for speed, reflects performance refactoring contributed /// by John Gietzen (user otac0n) /// public static string URLFriendly(string title) { if (title == null) return ""; const int maxlen = 80; int len = title.Length; bool prevdash = false; var sb = new StringBuilder(len); char c; for (int i = 0; i < len; i++) { c = title[i]; if ((c >= 'a' && c <= 'z') || (c >= '0' && c <= '9')) { sb.Append(c); prevdash = false; } else if (c >= 'A' && c <= 'Z') { // tricky way to convert to lowercase sb.Append((char)(c | 32)); prevdash = false; } else if (c == ' ' || c == ',' || c == '.' || c == '/' || c == '\\' || c == '-' || c == '_' || c == '=') { if (!prevdash && sb.Length > 0) { sb.Append('-'); prevdash = true; } } else if ((int)c >= 128) { int prevlen = sb.Length; sb.Append(RemapInternationalCharToAscii(c)); if (prevlen!= sb.Length) prevdash = false; } if (i == maxlen) break; } if (prevdash) return sb.ToString().Substring(0, sb.Length - 1); else return sb.ToString(); } To see the previous version of the code this replaced (but is functionally equivalent to, and 5x faster), view revision history of this post (click the date link). Also, the RemapInternationalCharToAscii method source code can be found here.
[ "regex", "language-agnostic", "seo", "friendly-url", "slug" ]
268
322
45,765
21
0
2008-08-24T18:21:11.237000
2008-08-25T00:11:43.763000
25,261
25,281
Set and Oldset in sigprocmask()
I haven't completely understood, how to use sigprocmask(). Particularly, how the set and oldset and its syntax work and how to use them. int sigprocmask(int how, const sigset_t *set, sigset_t *oldset); Please explain with an example, to block, say SIGUSR1 for a few seconds and then unblock and handle it. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
The idea is that you provide a mask in set, effectively a list of signals. The how argument says what you should do with the mask in set. You can either use SIG_BLOCK to block the signals in the set list, or SIG_UNBLOCK to unblock them. Neither of these changes the signals that aren't set in the list. SIG_SETMASK blocks the signals in the list, and unblocks the ones that aren't set in the list. For instance, assume that the old blocking list was {SIGSEGV, SIGSUSP} and you call sigprocmask with these arguments: sigset_t x; sigemptyset (&x); sigaddset(&x, SIGUSR1); sigprocmask(SIG_BLOCK, &x, NULL) The new blocking list will now be {SIGSEGV, SIGSUSP, SIGUSR1}. If you call sigprocmask with these arguments now: sigprocmask(SIG_UNBLOCK, &x, NULL) The new blocking list will go back to being {SIGSEGV, SIGSUSP}. If you call sigprocmask with these arguments now: sigprocmask(SIG_SETMASK, &x, NULL) The new blocking list will now be set to {SIGUSR1}. The oldset argument tells you what the previous blocking list was. If we have this declaration: sigset_t y; and we call the code in the previous examples like this: sigprocmask(SIG_BLOCK, &x, &y) now we have: y == {SIGSEGV, SIGSUSP} If we now do: sigprocmask(SIG_UNBLOCK, &x, &y) we'll get y == {SIGSEGV, SIGSUSP, SIGUSR1} and if we do: sigprocmask(SIG_SET, &x, &y) we'll get this: y == {SIGSEGV, SIGSUSP} because this is the previous value of the blocking set.
Set and Oldset in sigprocmask() I haven't completely understood, how to use sigprocmask(). Particularly, how the set and oldset and its syntax work and how to use them. int sigprocmask(int how, const sigset_t *set, sigset_t *oldset); Please explain with an example, to block, say SIGUSR1 for a few seconds and then unblock and handle it. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
TITLE: Set and Oldset in sigprocmask() QUESTION: I haven't completely understood, how to use sigprocmask(). Particularly, how the set and oldset and its syntax work and how to use them. int sigprocmask(int how, const sigset_t *set, sigset_t *oldset); Please explain with an example, to block, say SIGUSR1 for a few seconds and then unblock and handle it. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ ANSWER: The idea is that you provide a mask in set, effectively a list of signals. The how argument says what you should do with the mask in set. You can either use SIG_BLOCK to block the signals in the set list, or SIG_UNBLOCK to unblock them. Neither of these changes the signals that aren't set in the list. SIG_SETMASK blocks the signals in the list, and unblocks the ones that aren't set in the list. For instance, assume that the old blocking list was {SIGSEGV, SIGSUSP} and you call sigprocmask with these arguments: sigset_t x; sigemptyset (&x); sigaddset(&x, SIGUSR1); sigprocmask(SIG_BLOCK, &x, NULL) The new blocking list will now be {SIGSEGV, SIGSUSP, SIGUSR1}. If you call sigprocmask with these arguments now: sigprocmask(SIG_UNBLOCK, &x, NULL) The new blocking list will go back to being {SIGSEGV, SIGSUSP}. If you call sigprocmask with these arguments now: sigprocmask(SIG_SETMASK, &x, NULL) The new blocking list will now be set to {SIGUSR1}. The oldset argument tells you what the previous blocking list was. If we have this declaration: sigset_t y; and we call the code in the previous examples like this: sigprocmask(SIG_BLOCK, &x, &y) now we have: y == {SIGSEGV, SIGSUSP} If we now do: sigprocmask(SIG_UNBLOCK, &x, &y) we'll get y == {SIGSEGV, SIGSUSP, SIGUSR1} and if we do: sigprocmask(SIG_SET, &x, &y) we'll get this: y == {SIGSEGV, SIGSUSP} because this is the previous value of the blocking set.
[ "c", "posix", "signals", "sigprocmask" ]
31
77
34,733
1
0
2008-08-24T18:23:21.527000
2008-08-24T18:57:50.587000
25,268
1,067,011
What are the best practices when using SWIG with C#?
Has anybody out there used the SWIG library with C#? If you have, what pitfalls did you find and what is the best way to use the library? I am thinking about using it as a wrapper for a program that was written in C and I want to wrap the header files where I can use them in my.NET application. Edit: Some clarification on target OS's. I plan on running the application on Linux and Windows, therefore the reason I am looking into SWIG. P/Invoke is not an option.
I think the mistake the earlier posters did was read the docs and not look at the examples. A few hours ago I needed to interface some C++ classes to C#. I looked in my Swig dir (I already had it for other work), found the directory Examples/csharp/class, browsed the code, loaded the solution, grokked it, copied it, put in my code, it worked, my job was done. With that said, generated P/Invoke code isn't a solution for all needs. Depending on your project, it may be just as simple to write some simple API wrappers yourself or write managed C++ (Look up SlimDX for a superb example of this). For my needs, it was simple and easy - I had mystuff.dll, and now in addition I can ship mystuffnet.dll. I'll agree that the doc is difficult to get into. Edit: I noticed the OP only mentioned C. For that, you don't really need Swig, just use the usual C#/C DLLImport interop syntax. Swig becomes useful when you want to let C++ classes be invoked from C#.
What are the best practices when using SWIG with C#? Has anybody out there used the SWIG library with C#? If you have, what pitfalls did you find and what is the best way to use the library? I am thinking about using it as a wrapper for a program that was written in C and I want to wrap the header files where I can use them in my.NET application. Edit: Some clarification on target OS's. I plan on running the application on Linux and Windows, therefore the reason I am looking into SWIG. P/Invoke is not an option.
TITLE: What are the best practices when using SWIG with C#? QUESTION: Has anybody out there used the SWIG library with C#? If you have, what pitfalls did you find and what is the best way to use the library? I am thinking about using it as a wrapper for a program that was written in C and I want to wrap the header files where I can use them in my.NET application. Edit: Some clarification on target OS's. I plan on running the application on Linux and Windows, therefore the reason I am looking into SWIG. P/Invoke is not an option. ANSWER: I think the mistake the earlier posters did was read the docs and not look at the examples. A few hours ago I needed to interface some C++ classes to C#. I looked in my Swig dir (I already had it for other work), found the directory Examples/csharp/class, browsed the code, loaded the solution, grokked it, copied it, put in my code, it worked, my job was done. With that said, generated P/Invoke code isn't a solution for all needs. Depending on your project, it may be just as simple to write some simple API wrappers yourself or write managed C++ (Look up SlimDX for a superb example of this). For my needs, it was simple and easy - I had mystuff.dll, and now in addition I can ship mystuffnet.dll. I'll agree that the doc is difficult to get into. Edit: I noticed the OP only mentioned C. For that, you don't really need Swig, just use the usual C#/C DLLImport interop syntax. Swig becomes useful when you want to let C++ classes be invoked from C#.
[ "c#", "c", "swig" ]
22
11
9,579
3
0
2008-08-24T18:31:54.580000
2009-07-01T02:21:09.190000
25,277
25,456
Can you perform an AND search of keywords using FREETEXT() on SQL Server 2005?
There is a request to make the SO search default to an AND style functionality over the current OR when multiple terms are used. The official response was: not as simple as it sounds; we use SQL Server 2005's FREETEXT() function, and I can't find a way to specify AND vs. OR -- can you? So, is there a way? There are a number of resources on it I can find, but I am not an expert.
OK, this change is in -- we now use CONTAINS() with implicit AND instead of FREETEXT() and its implicit OR.
Can you perform an AND search of keywords using FREETEXT() on SQL Server 2005? There is a request to make the SO search default to an AND style functionality over the current OR when multiple terms are used. The official response was: not as simple as it sounds; we use SQL Server 2005's FREETEXT() function, and I can't find a way to specify AND vs. OR -- can you? So, is there a way? There are a number of resources on it I can find, but I am not an expert.
TITLE: Can you perform an AND search of keywords using FREETEXT() on SQL Server 2005? QUESTION: There is a request to make the SO search default to an AND style functionality over the current OR when multiple terms are used. The official response was: not as simple as it sounds; we use SQL Server 2005's FREETEXT() function, and I can't find a way to specify AND vs. OR -- can you? So, is there a way? There are a number of resources on it I can find, but I am not an expert. ANSWER: OK, this change is in -- we now use CONTAINS() with implicit AND instead of FREETEXT() and its implicit OR.
[ "sql-server-2005", "search", "full-text-search", "freetext" ]
3
1
1,290
3
0
2008-08-24T18:47:16.197000
2008-08-24T23:40:09.253000
25,297
25,300
Reserved Keyword in Enumeration in C#
I would like to use as and is as members of an enumeration. I know that this is possible in VB.NET to write it like this: Public Enum Test [as] = 1 [is] = 2 End Enum How do I write the equivalent statement in C#? The following code does not compile: public enum Test { as = 1, is = 2 }
Prefixing reserved words in C# is done with @. public enum Test { @as = 1, @is = 2 }
Reserved Keyword in Enumeration in C# I would like to use as and is as members of an enumeration. I know that this is possible in VB.NET to write it like this: Public Enum Test [as] = 1 [is] = 2 End Enum How do I write the equivalent statement in C#? The following code does not compile: public enum Test { as = 1, is = 2 }
TITLE: Reserved Keyword in Enumeration in C# QUESTION: I would like to use as and is as members of an enumeration. I know that this is possible in VB.NET to write it like this: Public Enum Test [as] = 1 [is] = 2 End Enum How do I write the equivalent statement in C#? The following code does not compile: public enum Test { as = 1, is = 2 } ANSWER: Prefixing reserved words in C# is done with @. public enum Test { @as = 1, @is = 2 }
[ "c#", "vb.net", ".net-2.0" ]
21
37
3,994
3
0
2008-08-24T19:37:24.237000
2008-08-24T19:39:17.447000
25,323
28,710
WCF - Domain Objects and IExtensibleDataObject
Typical scenario. We use old-school XML Web Services internally for communicating between a server farm and several distributed and local clients. No third parties involved, only our applications used by ourselves and our customers. We're currently pondering moving from XML WS to a WCF/object-based model and have been experimenting with various approaches. One of them involves transferring the domain objects/aggregates directly over the wire, possibly invoking DataContract attributes on them. By using IExtensibleDataObject and a DataContract using the Order property on the DataMembers, we should be able to cope with simple property versioning issues (remember, we control all clients and can easily force-update them). I keep hearing that we should use dedicated, transfer-only Data Transfer Objects ( DTOs ) over the wire. Why? Is there still a reason to do so? We use the same domain model on the server side and client side, of course, prefilling collections, etc. only when deemed right and "necessary." Collection properties utilize the service locator principle and IoC to invoke either an NHibernate-based "service" to fetch data directly (on the server side), and a WCF "service" client on the client side to talk to the WCF server farm. So - why do we need to use DTOs?
In my experience DTOs are most useful for: Strictly defining what will be sent over the wire and having a type specifically devoted to that definition. Isolating the rest of your application, client and server, from future changes. Interoperability with non-.Net systems. DTOs certainly aren't a requirement, but they make it easier to design "safe" types. In your scenario these design features may not matter that much. I've used WCF with both strict DTOs and shared Domain Objects and in both scenarios it worked great. The only thing I noticed when sending Domain Objects over the wire was that I tended to send more data (and in unexpected ways) then I needed to. This was likely more due to my lack of experience with WCF than anything else; but it's something you should definitely be wary of should you choose to go that route.
WCF - Domain Objects and IExtensibleDataObject Typical scenario. We use old-school XML Web Services internally for communicating between a server farm and several distributed and local clients. No third parties involved, only our applications used by ourselves and our customers. We're currently pondering moving from XML WS to a WCF/object-based model and have been experimenting with various approaches. One of them involves transferring the domain objects/aggregates directly over the wire, possibly invoking DataContract attributes on them. By using IExtensibleDataObject and a DataContract using the Order property on the DataMembers, we should be able to cope with simple property versioning issues (remember, we control all clients and can easily force-update them). I keep hearing that we should use dedicated, transfer-only Data Transfer Objects ( DTOs ) over the wire. Why? Is there still a reason to do so? We use the same domain model on the server side and client side, of course, prefilling collections, etc. only when deemed right and "necessary." Collection properties utilize the service locator principle and IoC to invoke either an NHibernate-based "service" to fetch data directly (on the server side), and a WCF "service" client on the client side to talk to the WCF server farm. So - why do we need to use DTOs?
TITLE: WCF - Domain Objects and IExtensibleDataObject QUESTION: Typical scenario. We use old-school XML Web Services internally for communicating between a server farm and several distributed and local clients. No third parties involved, only our applications used by ourselves and our customers. We're currently pondering moving from XML WS to a WCF/object-based model and have been experimenting with various approaches. One of them involves transferring the domain objects/aggregates directly over the wire, possibly invoking DataContract attributes on them. By using IExtensibleDataObject and a DataContract using the Order property on the DataMembers, we should be able to cope with simple property versioning issues (remember, we control all clients and can easily force-update them). I keep hearing that we should use dedicated, transfer-only Data Transfer Objects ( DTOs ) over the wire. Why? Is there still a reason to do so? We use the same domain model on the server side and client side, of course, prefilling collections, etc. only when deemed right and "necessary." Collection properties utilize the service locator principle and IoC to invoke either an NHibernate-based "service" to fetch data directly (on the server side), and a WCF "service" client on the client side to talk to the WCF server farm. So - why do we need to use DTOs? ANSWER: In my experience DTOs are most useful for: Strictly defining what will be sent over the wire and having a type specifically devoted to that definition. Isolating the rest of your application, client and server, from future changes. Interoperability with non-.Net systems. DTOs certainly aren't a requirement, but they make it easier to design "safe" types. In your scenario these design features may not matter that much. I've used WCF with both strict DTOs and shared Domain Objects and in both scenarios it worked great. The only thing I noticed when sending Domain Objects over the wire was that I tended to send more data (and in unexpected ways) then I needed to. This was likely more due to my lack of experience with WCF than anything else; but it's something you should definitely be wary of should you choose to go that route.
[ "wcf", "serialization", "soap", "domain-driven-design", "soa" ]
10
6
2,865
2
0
2008-08-24T20:34:10.293000
2008-08-26T17:48:12.530000
25,343
25,346
Is there any way to automate windows forms testing?
I am familiar with nunit for unit testing of the business layer however I am looking now to automate the test of the win forms gui layer. I have seen watin and the watin recorder for automating tests on web application by accessing the controls and automating them. However I am struggling to find a watin equivalent for windows forms (written in c# or vb.net) preferably that is open source. Does one exist or are all products based on recording mouse and keyboard presses? Update: I have looked at this blog post on white and it seems the sort of thing I am looking for. The blog post raises some issues but as white is only in version 0.6 these may be resolved. Be interested if others have used white or any others for comparison.
Check out http://www.codeplex.com/white and http://nunitforms.sourceforge.net/. We've used the White project with success. Same Answer to a previous question Edit The White project has moved, and is now located on GitHub as part of TestStack.
Is there any way to automate windows forms testing? I am familiar with nunit for unit testing of the business layer however I am looking now to automate the test of the win forms gui layer. I have seen watin and the watin recorder for automating tests on web application by accessing the controls and automating them. However I am struggling to find a watin equivalent for windows forms (written in c# or vb.net) preferably that is open source. Does one exist or are all products based on recording mouse and keyboard presses? Update: I have looked at this blog post on white and it seems the sort of thing I am looking for. The blog post raises some issues but as white is only in version 0.6 these may be resolved. Be interested if others have used white or any others for comparison.
TITLE: Is there any way to automate windows forms testing? QUESTION: I am familiar with nunit for unit testing of the business layer however I am looking now to automate the test of the win forms gui layer. I have seen watin and the watin recorder for automating tests on web application by accessing the controls and automating them. However I am struggling to find a watin equivalent for windows forms (written in c# or vb.net) preferably that is open source. Does one exist or are all products based on recording mouse and keyboard presses? Update: I have looked at this blog post on white and it seems the sort of thing I am looking for. The blog post raises some issues but as white is only in version 0.6 these may be resolved. Be interested if others have used white or any others for comparison. ANSWER: Check out http://www.codeplex.com/white and http://nunitforms.sourceforge.net/. We've used the White project with success. Same Answer to a previous question Edit The White project has moved, and is now located on GitHub as part of TestStack.
[ "c#", ".net", "vb.net", "winforms", "automated-tests" ]
57
30
41,589
9
0
2008-08-24T21:10:33.373000
2008-08-24T21:15:25.483000
25,349
25,354
What would be the fastest way to remove Newlines from a String in C#?
I have a string that has some Environment.Newline in it. I'd like to strip those from the string and instead, replace the Newline with something like a comma. What would be, in your opinion, the best way to do this using C#.NET 2.0?
Why not: string s = "foobar\ngork"; string v = s.Replace(Environment.NewLine,","); System.Console.WriteLine(v);
What would be the fastest way to remove Newlines from a String in C#? I have a string that has some Environment.Newline in it. I'd like to strip those from the string and instead, replace the Newline with something like a comma. What would be, in your opinion, the best way to do this using C#.NET 2.0?
TITLE: What would be the fastest way to remove Newlines from a String in C#? QUESTION: I have a string that has some Environment.Newline in it. I'd like to strip those from the string and instead, replace the Newline with something like a comma. What would be, in your opinion, the best way to do this using C#.NET 2.0? ANSWER: Why not: string s = "foobar\ngork"; string v = s.Replace(Environment.NewLine,","); System.Console.WriteLine(v);
[ "c#", ".net", "string", "replace" ]
12
20
9,559
5
0
2008-08-24T21:23:23.310000
2008-08-24T21:29:06.277000
25,355
25,371
Custom Attribute Binding in Silverlight
I've got two Silverlight Controls in my project, both have properties TeamId. I would like to bind these together in XAML in the control hosting both user controls similar to: In the first control, I'm implementing System.ComponentModel.INotifyPropertyChanged and raising the PropertyChanged event upon the TeamId property changing. In the second control, I've used the propdp snippet to identify the TeamId as a Dependency property. // Using a DependencyProperty as the backing store for TeamId. This enables animation, styling, binding, etc... public static readonly DependencyProperty TeamIdProperty = DependencyProperty.Register( "TeamId", typeof(string), typeof(OnlineUsers), new System.Windows.PropertyMetadata(new System.Windows.PropertyChangedCallback(TeamChanged))); However when the silverlight controls first gets created, I get the follow exception from Silverlight: Unhandled Error in Silverlight 2 Application Invalid attribute value {Binding ElementName=oUserTeams, Path=TeamId} for property TeamId. [Line: 21 Position: 146] at System.Windows.Application.LoadComponent(Object component, Uri xamlUri) at agChat.Page.InitializeComponent() at agChat.Page..ctor() at agChat.App.Application_Startup(Object sender, StartupEventArgs e) at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args) at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName) Any ideas what I'm doing wrong? Obviously this could all be done in code-behind, but this seems like the correct approach.
That is the correct approach in WPF, but not in Silverlight. You cannot bind to elements using xaml in Silverlight. This is the offending line: TeamId="{Binding ElementName=oUserTeams, Path=TeamId}" Specificly ElementName If you can, place the data object into Resources and declare it there, then you can do this:
Custom Attribute Binding in Silverlight I've got two Silverlight Controls in my project, both have properties TeamId. I would like to bind these together in XAML in the control hosting both user controls similar to: In the first control, I'm implementing System.ComponentModel.INotifyPropertyChanged and raising the PropertyChanged event upon the TeamId property changing. In the second control, I've used the propdp snippet to identify the TeamId as a Dependency property. // Using a DependencyProperty as the backing store for TeamId. This enables animation, styling, binding, etc... public static readonly DependencyProperty TeamIdProperty = DependencyProperty.Register( "TeamId", typeof(string), typeof(OnlineUsers), new System.Windows.PropertyMetadata(new System.Windows.PropertyChangedCallback(TeamChanged))); However when the silverlight controls first gets created, I get the follow exception from Silverlight: Unhandled Error in Silverlight 2 Application Invalid attribute value {Binding ElementName=oUserTeams, Path=TeamId} for property TeamId. [Line: 21 Position: 146] at System.Windows.Application.LoadComponent(Object component, Uri xamlUri) at agChat.Page.InitializeComponent() at agChat.Page..ctor() at agChat.App.Application_Startup(Object sender, StartupEventArgs e) at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args) at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName) Any ideas what I'm doing wrong? Obviously this could all be done in code-behind, but this seems like the correct approach.
TITLE: Custom Attribute Binding in Silverlight QUESTION: I've got two Silverlight Controls in my project, both have properties TeamId. I would like to bind these together in XAML in the control hosting both user controls similar to: In the first control, I'm implementing System.ComponentModel.INotifyPropertyChanged and raising the PropertyChanged event upon the TeamId property changing. In the second control, I've used the propdp snippet to identify the TeamId as a Dependency property. // Using a DependencyProperty as the backing store for TeamId. This enables animation, styling, binding, etc... public static readonly DependencyProperty TeamIdProperty = DependencyProperty.Register( "TeamId", typeof(string), typeof(OnlineUsers), new System.Windows.PropertyMetadata(new System.Windows.PropertyChangedCallback(TeamChanged))); However when the silverlight controls first gets created, I get the follow exception from Silverlight: Unhandled Error in Silverlight 2 Application Invalid attribute value {Binding ElementName=oUserTeams, Path=TeamId} for property TeamId. [Line: 21 Position: 146] at System.Windows.Application.LoadComponent(Object component, Uri xamlUri) at agChat.Page.InitializeComponent() at agChat.Page..ctor() at agChat.App.Application_Startup(Object sender, StartupEventArgs e) at System.Windows.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex, Delegate handlerDelegate, Object sender, Object args) at MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr unmanagedObjArgs, Int32 argsTypeIndex, String eventName) Any ideas what I'm doing wrong? Obviously this could all be done in code-behind, but this seems like the correct approach. ANSWER: That is the correct approach in WPF, but not in Silverlight. You cannot bind to elements using xaml in Silverlight. This is the offending line: TeamId="{Binding ElementName=oUserTeams, Path=TeamId}" Specificly ElementName If you can, place the data object into Resources and declare it there, then you can do this:
[ "silverlight" ]
3
4
3,045
1
0
2008-08-24T21:31:33.510000
2008-08-24T21:45:48.170000
25,356
87,558
Flash designer/coder collaboration best practices
I've done several flash projects working as the ActionScripter with a designer doing all the pretty things and animation. When starting out I found quite a lot of information about ActionScript coding and flash design. Most of the information available seems to focus on one or the other. I didn't find any information about building flash projects in a way that lets the coder do their thing AND gives the designer freedom as well. Hopefully more experienced people can share, these are some of the things i discovered after a few projects Version control is a must (as always) but can be difficult to explain to designers No ActionScript in the flash.fla files, they are binary and as a coder you want to try to keep away as much as possible Model View Controller is the best way I've found to isolate visual design changes Try to build the views so that they use frame labels, this allows the designer to decide what actually happens What are your experiences? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
I've been doing Flash for 9 years and I still find this a difficult thing to get right. There is a balance of power between designers and developers, which will inevitably tip one way or the other. If you work for a developer led studio, then you are lucky, as the designers will be instructed to make a design that fits your functionality. In Flex / MXML this is the only way to work. If, on the other hand, you work in a graphic design/creative/advertising studio, you will be instructed to build whatever the designer puts together in PhotoShop, whether or not it is feasible to build within the time. The key to getting around this is communication and education. Designers and design-focussed managers may not know what is involved in creating a particular piece of functionality, and if you explain to them why a particular thing is hard to do they might be persuaded to go and rethink their design. On the other hand, they may well think you're just a whiner! It never feels good when you have to tell someone "sorry, I can't really do that" when you know that you could make it work, given a few late nights! As well as the things you and others have already noted, like using FlashDevelop and external AS classes, here's some other things I recommend: Start with a site map / wireframe that both the developers and designers agree to. Load all your text from XML into dynamic text fields, and make sure your buttons etc are designed to expand to fit content Make sure your designers have some idea how to correctly cut-up graphics and lay them out in Flash. A developer shouldn't be messing about in PhotoShop when you're up against a deadline. Make sure you get all you graphics assets well before the deadline - inevitably there'll be things they've missed and things that need changing. Be firm and don't let your design team try to sneak in extra features at the last minute. Let the designers use the timeline for character animation etc, but for simple tweens use an ActionScript tweening engine. Hope these tips are some use!
Flash designer/coder collaboration best practices I've done several flash projects working as the ActionScripter with a designer doing all the pretty things and animation. When starting out I found quite a lot of information about ActionScript coding and flash design. Most of the information available seems to focus on one or the other. I didn't find any information about building flash projects in a way that lets the coder do their thing AND gives the designer freedom as well. Hopefully more experienced people can share, these are some of the things i discovered after a few projects Version control is a must (as always) but can be difficult to explain to designers No ActionScript in the flash.fla files, they are binary and as a coder you want to try to keep away as much as possible Model View Controller is the best way I've found to isolate visual design changes Try to build the views so that they use frame labels, this allows the designer to decide what actually happens What are your experiences? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
TITLE: Flash designer/coder collaboration best practices QUESTION: I've done several flash projects working as the ActionScripter with a designer doing all the pretty things and animation. When starting out I found quite a lot of information about ActionScript coding and flash design. Most of the information available seems to focus on one or the other. I didn't find any information about building flash projects in a way that lets the coder do their thing AND gives the designer freedom as well. Hopefully more experienced people can share, these are some of the things i discovered after a few projects Version control is a must (as always) but can be difficult to explain to designers No ActionScript in the flash.fla files, they are binary and as a coder you want to try to keep away as much as possible Model View Controller is the best way I've found to isolate visual design changes Try to build the views so that they use frame labels, this allows the designer to decide what actually happens What are your experiences? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ ANSWER: I've been doing Flash for 9 years and I still find this a difficult thing to get right. There is a balance of power between designers and developers, which will inevitably tip one way or the other. If you work for a developer led studio, then you are lucky, as the designers will be instructed to make a design that fits your functionality. In Flex / MXML this is the only way to work. If, on the other hand, you work in a graphic design/creative/advertising studio, you will be instructed to build whatever the designer puts together in PhotoShop, whether or not it is feasible to build within the time. The key to getting around this is communication and education. Designers and design-focussed managers may not know what is involved in creating a particular piece of functionality, and if you explain to them why a particular thing is hard to do they might be persuaded to go and rethink their design. On the other hand, they may well think you're just a whiner! It never feels good when you have to tell someone "sorry, I can't really do that" when you know that you could make it work, given a few late nights! As well as the things you and others have already noted, like using FlashDevelop and external AS classes, here's some other things I recommend: Start with a site map / wireframe that both the developers and designers agree to. Load all your text from XML into dynamic text fields, and make sure your buttons etc are designed to expand to fit content Make sure your designers have some idea how to correctly cut-up graphics and lay them out in Flash. A developer shouldn't be messing about in PhotoShop when you're up against a deadline. Make sure you get all you graphics assets well before the deadline - inevitably there'll be things they've missed and things that need changing. Be firm and don't let your design team try to sneak in extra features at the last minute. Let the designers use the timeline for character animation etc, but for simple tweens use an ActionScript tweening engine. Hope these tips are some use!
[ "flash", "actionscript" ]
8
4
1,197
4
0
2008-08-24T21:32:21.353000
2008-09-17T20:52:59.207000
25,367
25,466
What is the best calendar pop-up to populate a web form?
I want to be able to make an HTTP call updating some select boxes after a date is selected. I would like to be in control of updating the textbox so I know when there has been a "true" change (in the event the same date was selected). Ideally, I would call a function to pop-up the calendar and be able to evaluate the date before populating the text box...so I can do my validation before making a server call.
JQuery's datepicker is an extremely flexible tool. With the ability to attach handlers prior to opening or after date selection, themes, range selection and a variety of other incredibly useful options, I've found that it meets all my needs. The fact that I sit next to one of its maintainers here at work is also fairly useful...
What is the best calendar pop-up to populate a web form? I want to be able to make an HTTP call updating some select boxes after a date is selected. I would like to be in control of updating the textbox so I know when there has been a "true" change (in the event the same date was selected). Ideally, I would call a function to pop-up the calendar and be able to evaluate the date before populating the text box...so I can do my validation before making a server call.
TITLE: What is the best calendar pop-up to populate a web form? QUESTION: I want to be able to make an HTTP call updating some select boxes after a date is selected. I would like to be in control of updating the textbox so I know when there has been a "true" change (in the event the same date was selected). Ideally, I would call a function to pop-up the calendar and be able to evaluate the date before populating the text box...so I can do my validation before making a server call. ANSWER: JQuery's datepicker is an extremely flexible tool. With the ability to attach handlers prior to opening or after date selection, themes, range selection and a variety of other incredibly useful options, I've found that it meets all my needs. The fact that I sit next to one of its maintainers here at work is also fairly useful...
[ "javascript", "calendar" ]
8
9
9,249
7
0
2008-08-24T21:42:41.673000
2008-08-24T23:49:00.700000
25,375
51,944
How can I represent a very large integer in .NET?
Does.NET come with a class capable of representing extremely large integers, such as 100 factorial? If not, what are some good third party libraries to accomplish this?
.NET 4 has a BigInteger class Represents an arbitrarily large signed integer. The BigInteger type is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds. This type differs from the other integral types in the.NET Framework, which have a range indicated by their MinValue and MaxValue properties.
How can I represent a very large integer in .NET? Does.NET come with a class capable of representing extremely large integers, such as 100 factorial? If not, what are some good third party libraries to accomplish this?
TITLE: How can I represent a very large integer in .NET? QUESTION: Does.NET come with a class capable of representing extremely large integers, such as 100 factorial? If not, what are some good third party libraries to accomplish this? ANSWER: .NET 4 has a BigInteger class Represents an arbitrarily large signed integer. The BigInteger type is an immutable type that represents an arbitrarily large integer whose value in theory has no upper or lower bounds. This type differs from the other integral types in the.NET Framework, which have a range indicated by their MinValue and MaxValue properties.
[ ".net", "bignum" ]
27
18
8,996
5
0
2008-08-24T21:51:57.593000
2008-09-09T13:56:30.553000
25,376
25,412
What is appliance and how to use lambda expressions?
I've read that Lambda Expressions are an incredibly powerful addition to C#, yet I find myself mystified by them. How can they improve my life or make my code better? Can anyone point to a good resource for learning such expressions? They seem cool as hell, but how do they relate to my day-to-day life as an asp.net developer? Edit: Thanks for the examples, and thanks for the link to Eric White's articles. I'm still digesting those now. One quick question: are lambda expressions useful for anything other than querying? Every example I've seen has been a query construct.
: are lambda expressions useful for anything other than querying Lamba expressions are nothing much other than a convenient way of writing a function 'in-line'. So they're useful any place you wanted a bit of code which can be called as though it's a separate function but which is actually written inside its caller. (In addition to keeping related code in the same location in a file, this also allows you to play fun games with variable scoping - see 'closures' for a reference.) An example of a non-query-related use of a lamba might be a bit of code which does something asynchronously that you start with ThreadPool.QueueUserWorkItem. The important point is that you could also write this using anonymous delegates (which were a C#2 introduction), or just a plain separate class member function. This http://blogs.msdn.com/jomo_fisher/archive/2005/09/13/464884.aspx is a superb step-by-step introduction into all this stuff, which might help you.
What is appliance and how to use lambda expressions? I've read that Lambda Expressions are an incredibly powerful addition to C#, yet I find myself mystified by them. How can they improve my life or make my code better? Can anyone point to a good resource for learning such expressions? They seem cool as hell, but how do they relate to my day-to-day life as an asp.net developer? Edit: Thanks for the examples, and thanks for the link to Eric White's articles. I'm still digesting those now. One quick question: are lambda expressions useful for anything other than querying? Every example I've seen has been a query construct.
TITLE: What is appliance and how to use lambda expressions? QUESTION: I've read that Lambda Expressions are an incredibly powerful addition to C#, yet I find myself mystified by them. How can they improve my life or make my code better? Can anyone point to a good resource for learning such expressions? They seem cool as hell, but how do they relate to my day-to-day life as an asp.net developer? Edit: Thanks for the examples, and thanks for the link to Eric White's articles. I'm still digesting those now. One quick question: are lambda expressions useful for anything other than querying? Every example I've seen has been a query construct. ANSWER: : are lambda expressions useful for anything other than querying Lamba expressions are nothing much other than a convenient way of writing a function 'in-line'. So they're useful any place you wanted a bit of code which can be called as though it's a separate function but which is actually written inside its caller. (In addition to keeping related code in the same location in a file, this also allows you to play fun games with variable scoping - see 'closures' for a reference.) An example of a non-query-related use of a lamba might be a bit of code which does something asynchronously that you start with ThreadPool.QueueUserWorkItem. The important point is that you could also write this using anonymous delegates (which were a C#2 introduction), or just a plain separate class member function. This http://blogs.msdn.com/jomo_fisher/archive/2005/09/13/464884.aspx is a superb step-by-step introduction into all this stuff, which might help you.
[ "c#", "lambda" ]
24
12
4,111
3
0
2008-08-24T21:53:16.953000
2008-08-24T22:45:01.210000
25,379
1,262,071
Family Website CMS
I am looking for a CMS that would be incredibly user-friendly and would have the following features: really simple message board (no login required) family tree story telling area photo section news section Is there anything out there like this that is really easily configurable? I've already messed around with Mambo and Family Connects, but I didnt like either of those. In the past I've just programmed my own websites, for lack of easily implementable features. However, I've assuming there's something I need out there just like this, that I can't find. Thanks. I don't want anyone to have to login, for one. The is for a family website, and much of my family really don't know what a website is, let alone how to use one. I want a super simple website with huge buttons and not a whole lot of distractions. Family Connects is a good example of what I want, except the photo album is horrible. I want people to post messages without logging in or signing up, and haven't seen that ability in mambo sites I've looked at.
I've been using http://www.myfamily.com/ and it fits all my needs. It includes: Pictures (with option to order prints) Discussion Family Trees (free from ancestry.com) Videos Files Events
Family Website CMS I am looking for a CMS that would be incredibly user-friendly and would have the following features: really simple message board (no login required) family tree story telling area photo section news section Is there anything out there like this that is really easily configurable? I've already messed around with Mambo and Family Connects, but I didnt like either of those. In the past I've just programmed my own websites, for lack of easily implementable features. However, I've assuming there's something I need out there just like this, that I can't find. Thanks. I don't want anyone to have to login, for one. The is for a family website, and much of my family really don't know what a website is, let alone how to use one. I want a super simple website with huge buttons and not a whole lot of distractions. Family Connects is a good example of what I want, except the photo album is horrible. I want people to post messages without logging in or signing up, and haven't seen that ability in mambo sites I've looked at.
TITLE: Family Website CMS QUESTION: I am looking for a CMS that would be incredibly user-friendly and would have the following features: really simple message board (no login required) family tree story telling area photo section news section Is there anything out there like this that is really easily configurable? I've already messed around with Mambo and Family Connects, but I didnt like either of those. In the past I've just programmed my own websites, for lack of easily implementable features. However, I've assuming there's something I need out there just like this, that I can't find. Thanks. I don't want anyone to have to login, for one. The is for a family website, and much of my family really don't know what a website is, let alone how to use one. I want a super simple website with huge buttons and not a whole lot of distractions. Family Connects is a good example of what I want, except the photo album is horrible. I want people to post messages without logging in or signing up, and haven't seen that ability in mambo sites I've looked at. ANSWER: I've been using http://www.myfamily.com/ and it fits all my needs. It includes: Pictures (with option to order prints) Discussion Family Trees (free from ancestry.com) Videos Files Events
[ "plugins", "content-management-system" ]
6
1
3,000
7
0
2008-08-24T21:56:17.227000
2009-08-11T18:14:13.813000
25,449
25,492
How to create a pluginable Java program?
I want to create a Java program that can be extended with plugins. How can I do that and where should I look for? I have a set of interfaces that the plugin must implement, and it should be in a jar. The program should watch for new jars in a relative (to the program) folder and registered them somehow. Although I do like Eclipse RCP, I think it's too much for my simple needs. Same thing goes for Spring, but since I was going to look at it anyway, I might as well try it. But still, I'd prefer to find a way to create my own plugin "framework" as simple as possible.
I've done this for software I've written in the past, it's very handy. I did it by first creating an Interface that all my 'plugin' classes needed to implement. I then used the Java ClassLoader to load those classes and create instances of them. One way you can go about it is this: File dir = new File("put path to classes you want to load here"); URL loadPath = dir.toURI().toURL(); URL[] classUrl = new URL[]{loadPath}; ClassLoader cl = new URLClassLoader(classUrl); Class loadedClass = cl.loadClass("classname"); // must be in package.class name format That has loaded the class, now you need to create an instance of it, assuming the interface name is MyModule: MyModule modInstance = (MyModule)loadedClass.newInstance();
How to create a pluginable Java program? I want to create a Java program that can be extended with plugins. How can I do that and where should I look for? I have a set of interfaces that the plugin must implement, and it should be in a jar. The program should watch for new jars in a relative (to the program) folder and registered them somehow. Although I do like Eclipse RCP, I think it's too much for my simple needs. Same thing goes for Spring, but since I was going to look at it anyway, I might as well try it. But still, I'd prefer to find a way to create my own plugin "framework" as simple as possible.
TITLE: How to create a pluginable Java program? QUESTION: I want to create a Java program that can be extended with plugins. How can I do that and where should I look for? I have a set of interfaces that the plugin must implement, and it should be in a jar. The program should watch for new jars in a relative (to the program) folder and registered them somehow. Although I do like Eclipse RCP, I think it's too much for my simple needs. Same thing goes for Spring, but since I was going to look at it anyway, I might as well try it. But still, I'd prefer to find a way to create my own plugin "framework" as simple as possible. ANSWER: I've done this for software I've written in the past, it's very handy. I did it by first creating an Interface that all my 'plugin' classes needed to implement. I then used the Java ClassLoader to load those classes and create instances of them. One way you can go about it is this: File dir = new File("put path to classes you want to load here"); URL loadPath = dir.toURI().toURL(); URL[] classUrl = new URL[]{loadPath}; ClassLoader cl = new URLClassLoader(classUrl); Class loadedClass = cl.loadClass("classname"); // must be in package.class name format That has loaded the class, now you need to create an instance of it, assuming the interface name is MyModule: MyModule modInstance = (MyModule)loadedClass.newInstance();
[ "java", "plugins", "plugin-architecture" ]
42
50
35,280
6
0
2008-08-24T23:28:38.987000
2008-08-25T00:21:40.637000
25,450
25,467
Abstraction away from CSS
Many frameworks seek to abstract away from HTML (custom tags, JSFs component system) in an effort to make dealing with that particular kettle of fish easier. Is there anything you folks have used that has a similar concept applied to CSS? Something that does a bunch of cross-browser magic for you, supports like variables (why do I have to type #3c5c8d every time I want that colour), supports calculated fields (which are 'compiled' into CSS and JS), etc. Alternatively, am I even thinking about this correctly? Am I trying to push a very square block through a very round hole?
You can always use a template engine to add variables and calculated fields to your CSS files.
Abstraction away from CSS Many frameworks seek to abstract away from HTML (custom tags, JSFs component system) in an effort to make dealing with that particular kettle of fish easier. Is there anything you folks have used that has a similar concept applied to CSS? Something that does a bunch of cross-browser magic for you, supports like variables (why do I have to type #3c5c8d every time I want that colour), supports calculated fields (which are 'compiled' into CSS and JS), etc. Alternatively, am I even thinking about this correctly? Am I trying to push a very square block through a very round hole?
TITLE: Abstraction away from CSS QUESTION: Many frameworks seek to abstract away from HTML (custom tags, JSFs component system) in an effort to make dealing with that particular kettle of fish easier. Is there anything you folks have used that has a similar concept applied to CSS? Something that does a bunch of cross-browser magic for you, supports like variables (why do I have to type #3c5c8d every time I want that colour), supports calculated fields (which are 'compiled' into CSS and JS), etc. Alternatively, am I even thinking about this correctly? Am I trying to push a very square block through a very round hole? ANSWER: You can always use a template engine to add variables and calculated fields to your CSS files.
[ "css", "abstraction" ]
14
9
1,870
18
0
2008-08-24T23:33:25.917000
2008-08-24T23:49:58.373000
25,455
25,573
What is the most efficient way to populate a time (or time range)?
While plenty of solutions exist for entering dates (such as calendars, drop-down menus, etc.), it doesn't seem like there are too many "standard" ways to ask for a time (or time range). I've personally tried drop-down menus for the hour, minute, and second fields (and sometimes an "AM/PM" field, as well). I've also tried several clock-like input devices, most of which are too hard to use for the typical end-user. I've even tried "pop-out" time selection menus (which allow you to, for example, hover over the hour "10" to receive a sub-menu that contains ":00",":15",":30", and ":45") -- but none of these methods seem natural. So far, the best (and most universal) method I have found is just using simple text fields and forcing a user to manually populate the hour, minute, and second. Alternatively, I've had good experiences creating something similar to Outlook's "Day View" which allows you to drag and drop an event to set the start and end times. Is there a "best way" to ask for this information? Is anybody using some type of time input widget that's really intuitive and easy to use? Or is there at least a way that's more efficient than using plain text boxes? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
I find Google Calendar's approach to be the best. Use a text box, but use JavaScript to make it sort of a drop-down for picking your time. A good demo can be found for a jQuery implementation here I haven't implemented this on my site yet so I'm not 100% sure, but I think you also need code from this jQuery plugin here: http://www.texotela.co.uk/code/jquery/timepicker/ Edit The first link I posted does not require the second link's code. It is simply based off of it. To get the actual JavaScript file from the example, you can view the source of the page to find where the file is, or you can go to the URL directly http://labs.perifer.se/timedatepicker/jquery.timePicker.js
What is the most efficient way to populate a time (or time range)? While plenty of solutions exist for entering dates (such as calendars, drop-down menus, etc.), it doesn't seem like there are too many "standard" ways to ask for a time (or time range). I've personally tried drop-down menus for the hour, minute, and second fields (and sometimes an "AM/PM" field, as well). I've also tried several clock-like input devices, most of which are too hard to use for the typical end-user. I've even tried "pop-out" time selection menus (which allow you to, for example, hover over the hour "10" to receive a sub-menu that contains ":00",":15",":30", and ":45") -- but none of these methods seem natural. So far, the best (and most universal) method I have found is just using simple text fields and forcing a user to manually populate the hour, minute, and second. Alternatively, I've had good experiences creating something similar to Outlook's "Day View" which allows you to drag and drop an event to set the start and end times. Is there a "best way" to ask for this information? Is anybody using some type of time input widget that's really intuitive and easy to use? Or is there at least a way that's more efficient than using plain text boxes? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
TITLE: What is the most efficient way to populate a time (or time range)? QUESTION: While plenty of solutions exist for entering dates (such as calendars, drop-down menus, etc.), it doesn't seem like there are too many "standard" ways to ask for a time (or time range). I've personally tried drop-down menus for the hour, minute, and second fields (and sometimes an "AM/PM" field, as well). I've also tried several clock-like input devices, most of which are too hard to use for the typical end-user. I've even tried "pop-out" time selection menus (which allow you to, for example, hover over the hour "10" to receive a sub-menu that contains ":00",":15",":30", and ":45") -- but none of these methods seem natural. So far, the best (and most universal) method I have found is just using simple text fields and forcing a user to manually populate the hour, minute, and second. Alternatively, I've had good experiences creating something similar to Outlook's "Day View" which allows you to drag and drop an event to set the start and end times. Is there a "best way" to ask for this information? Is anybody using some type of time input widget that's really intuitive and easy to use? Or is there at least a way that's more efficient than using plain text boxes? ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ ANSWER: I find Google Calendar's approach to be the best. Use a text box, but use JavaScript to make it sort of a drop-down for picking your time. A good demo can be found for a jQuery implementation here I haven't implemented this on my site yet so I'm not 100% sure, but I think you also need code from this jQuery plugin here: http://www.texotela.co.uk/code/jquery/timepicker/ Edit The first link I posted does not require the second link's code. It is simply based off of it. To get the actual JavaScript file from the example, you can view the source of the page to find where the file is, or you can go to the URL directly http://labs.perifer.se/timedatepicker/jquery.timePicker.js
[ "time" ]
2
0
433
3
0
2008-08-24T23:39:46.400000
2008-08-25T02:12:56.343000
25,458
25,465
How costly is .NET reflection?
I constantly hear how bad reflection is to use. While I generally avoid reflection and rarely find situations where it is impossible to solve my problem without it, I was wondering... For those who have used reflection in applications, have you measured performance hits and, is it really so bad?
It is. But that depends on what you're trying to do. I use reflection to dynamically load assemblies (plugins) and its performance "penalty" is not a problem, since the operation is something I do during startup of the application. However, if you're reflecting inside a series of nested loops with reflection calls on each, I'd say you should revisit your code:) For "a couple of time" operations, reflection is perfectly acceptable and you won't notice any delay or problem with it. It's a very powerful mechanism and it is even used by.NET, so I don't see why you shouldn't give it a try.
How costly is .NET reflection? I constantly hear how bad reflection is to use. While I generally avoid reflection and rarely find situations where it is impossible to solve my problem without it, I was wondering... For those who have used reflection in applications, have you measured performance hits and, is it really so bad?
TITLE: How costly is .NET reflection? QUESTION: I constantly hear how bad reflection is to use. While I generally avoid reflection and rarely find situations where it is impossible to solve my problem without it, I was wondering... For those who have used reflection in applications, have you measured performance hits and, is it really so bad? ANSWER: It is. But that depends on what you're trying to do. I use reflection to dynamically load assemblies (plugins) and its performance "penalty" is not a problem, since the operation is something I do during startup of the application. However, if you're reflecting inside a series of nested loops with reflection calls on each, I'd say you should revisit your code:) For "a couple of time" operations, reflection is perfectly acceptable and you won't notice any delay or problem with it. It's a very powerful mechanism and it is even used by.NET, so I don't see why you shouldn't give it a try.
[ "c#", ".net", "performance", "reflection" ]
232
146
76,964
13
0
2008-08-24T23:40:16.647000
2008-08-24T23:48:33.947000
25,460
25,506
Asynchronous Stored Procedure Calls
Is it possible to call a stored procedure from another stored procedure asynchronously? Edit: Specifically I'm working with a DB2 database. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
Executive summary: Yes, if your database has a message queue service. You can push a message onto a queue and the queue processor will consume it asynchronously. Oracle: queues Sql Server: service broker DB2: event broker For "pure" stored procedure languages (PL/Sql or T-Sql) the answer is no, since it works against the fundamental transaction model most databases have. However, if your database has a queuing mechanism, you can use that to get the same result.
Asynchronous Stored Procedure Calls Is it possible to call a stored procedure from another stored procedure asynchronously? Edit: Specifically I'm working with a DB2 database. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­
TITLE: Asynchronous Stored Procedure Calls QUESTION: Is it possible to call a stored procedure from another stored procedure asynchronously? Edit: Specifically I'm working with a DB2 database. ­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­­ ANSWER: Executive summary: Yes, if your database has a message queue service. You can push a message onto a queue and the queue processor will consume it asynchronously. Oracle: queues Sql Server: service broker DB2: event broker For "pure" stored procedure languages (PL/Sql or T-Sql) the answer is no, since it works against the fundamental transaction model most databases have. However, if your database has a queuing mechanism, you can use that to get the same result.
[ "sql", "stored-procedures", "db2" ]
5
5
8,614
3
0
2008-08-24T23:43:00.370000
2008-08-25T00:34:44.053000
25,461
29,300
interfacing with stdbool.h C++
In a project I am interfacing between C++ and a C library that uses stdbool.h defined as such. #ifndef _STDBOOL_H #define _STDBOOL_H /* C99 Boolean types for compilers without C99 support */ /* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */ #if!defined(__cplusplus) #if!defined(__GNUC__) /* _Bool builtin type is included in GCC */ typedef enum { _Bool_must_promote_to_int = -1, false = 0, true = 1 } _Bool; #endif #define bool _Bool #define true 1 #define false 0 #define __bool_true_false_are_defined 1 #endif #endif Some structures have bool members. So if I have one of these structures defined as local variables within a C++ function and pass it to a C function the sizes are inconsistent between C++ and C as bool is one bye in C++ and 4 in C. Does anyone have any advice to how to overcome this without resorting to my current solution which is //#define bool _Bool #define bool unsigned char Which is against the C99 standard for stdbool.h
I found the answer to my own question by finding a more compatible implementation of stdbool.h that is compliant with the C99 standard. #ifndef _STDBOOL_H #define _STDBOOL_H #include /* C99 Boolean types for compilers without C99 support */ /* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */ #if!defined(__cplusplus) #if!defined(__GNUC__) /* _Bool builtin type is included in GCC */ /* ISO C Standard: 5.2.5 An object declared as type _Bool is large enough to store the values 0 and 1. */ /* We choose 8 bit to match C++ */ /* It must also promote to integer */ typedef int8_t _Bool; #endif /* ISO C Standard: 7.16 Boolean type */ #define bool _Bool #define true 1 #define false 0 #define __bool_true_false_are_defined 1 #endif #endif This is taken from the Ada Class Library project.
interfacing with stdbool.h C++ In a project I am interfacing between C++ and a C library that uses stdbool.h defined as such. #ifndef _STDBOOL_H #define _STDBOOL_H /* C99 Boolean types for compilers without C99 support */ /* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */ #if!defined(__cplusplus) #if!defined(__GNUC__) /* _Bool builtin type is included in GCC */ typedef enum { _Bool_must_promote_to_int = -1, false = 0, true = 1 } _Bool; #endif #define bool _Bool #define true 1 #define false 0 #define __bool_true_false_are_defined 1 #endif #endif Some structures have bool members. So if I have one of these structures defined as local variables within a C++ function and pass it to a C function the sizes are inconsistent between C++ and C as bool is one bye in C++ and 4 in C. Does anyone have any advice to how to overcome this without resorting to my current solution which is //#define bool _Bool #define bool unsigned char Which is against the C99 standard for stdbool.h
TITLE: interfacing with stdbool.h C++ QUESTION: In a project I am interfacing between C++ and a C library that uses stdbool.h defined as such. #ifndef _STDBOOL_H #define _STDBOOL_H /* C99 Boolean types for compilers without C99 support */ /* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */ #if!defined(__cplusplus) #if!defined(__GNUC__) /* _Bool builtin type is included in GCC */ typedef enum { _Bool_must_promote_to_int = -1, false = 0, true = 1 } _Bool; #endif #define bool _Bool #define true 1 #define false 0 #define __bool_true_false_are_defined 1 #endif #endif Some structures have bool members. So if I have one of these structures defined as local variables within a C++ function and pass it to a C function the sizes are inconsistent between C++ and C as bool is one bye in C++ and 4 in C. Does anyone have any advice to how to overcome this without resorting to my current solution which is //#define bool _Bool #define bool unsigned char Which is against the C99 standard for stdbool.h ANSWER: I found the answer to my own question by finding a more compatible implementation of stdbool.h that is compliant with the C99 standard. #ifndef _STDBOOL_H #define _STDBOOL_H #include /* C99 Boolean types for compilers without C99 support */ /* http://www.opengroup.org/onlinepubs/009695399/basedefs/stdbool.h.html */ #if!defined(__cplusplus) #if!defined(__GNUC__) /* _Bool builtin type is included in GCC */ /* ISO C Standard: 5.2.5 An object declared as type _Bool is large enough to store the values 0 and 1. */ /* We choose 8 bit to match C++ */ /* It must also promote to integer */ typedef int8_t _Bool; #endif /* ISO C Standard: 7.16 Boolean type */ #define bool _Bool #define true 1 #define false 0 #define __bool_true_false_are_defined 1 #endif #endif This is taken from the Ada Class Library project.
[ "c++", "c", "boolean", "standards" ]
14
11
10,386
3
0
2008-08-24T23:44:53.330000
2008-08-27T01:14:06.767000
25,475
25,479
How do I put unicode characters in my Antlr grammar?
I'm trying to build a grammar with the following: NUMERIC: INTEGER | FLOAT | INFINITY | PI... INFINITY: '∞' PI: 'π' But Antlr refuses to load the grammar.
Use the Java expression representing the Unicode character: 'π' = '\u03C0' '∞' = '\u221E' That will work up to '\uFFFF'; Java doesn't support five-digit Unicode.
How do I put unicode characters in my Antlr grammar? I'm trying to build a grammar with the following: NUMERIC: INTEGER | FLOAT | INFINITY | PI... INFINITY: '∞' PI: 'π' But Antlr refuses to load the grammar.
TITLE: How do I put unicode characters in my Antlr grammar? QUESTION: I'm trying to build a grammar with the following: NUMERIC: INTEGER | FLOAT | INFINITY | PI... INFINITY: '∞' PI: 'π' But Antlr refuses to load the grammar. ANSWER: Use the Java expression representing the Unicode character: 'π' = '\u03C0' '∞' = '\u221E' That will work up to '\uFFFF'; Java doesn't support five-digit Unicode.
[ "unicode", "internationalization", "antlr", "parsing" ]
4
3
1,847
1
0
2008-08-25T00:03:13.457000
2008-08-25T00:04:48.570000
25,481
25,484
Where do I get the Antlr Ant task?
I'm trying to call an Antlr task in my Ant build.xml as follows:... But Ant can't find the task definition. I've put all of the following in that dir.lib.build: antlr-3.1.jar antlr-2.7.7.jar antlr-runtime-3.1.jar stringtemplate-3.2.jar But none of those seems to have the task definition. (I've also tried putting those jars in my Ant classpath; same problem.)
The current Antlr-task jar is available at http://www.antlr.org/share/1169924912745/antlr3-task.zip It can be found on the antlr.org website under the "File Sharing" heading.
Where do I get the Antlr Ant task? I'm trying to call an Antlr task in my Ant build.xml as follows:... But Ant can't find the task definition. I've put all of the following in that dir.lib.build: antlr-3.1.jar antlr-2.7.7.jar antlr-runtime-3.1.jar stringtemplate-3.2.jar But none of those seems to have the task definition. (I've also tried putting those jars in my Ant classpath; same problem.)
TITLE: Where do I get the Antlr Ant task? QUESTION: I'm trying to call an Antlr task in my Ant build.xml as follows:... But Ant can't find the task definition. I've put all of the following in that dir.lib.build: antlr-3.1.jar antlr-2.7.7.jar antlr-runtime-3.1.jar stringtemplate-3.2.jar But none of those seems to have the task definition. (I've also tried putting those jars in my Ant classpath; same problem.) ANSWER: The current Antlr-task jar is available at http://www.antlr.org/share/1169924912745/antlr3-task.zip It can be found on the antlr.org website under the "File Sharing" heading.
[ "ant", "antlr", "parsing" ]
4
4
4,954
6
0
2008-08-25T00:07:43.087000
2008-08-25T00:11:09.850000
25,519
25,529
Filtering out anchor tags in a string
I need to filter out anchor tags in a string. For instance, Check out this site: stackoverflow I need to be able to filter out the anchor tag to this: Check out this site: http://www.stackoverflow.com That format may not be constant, either. There could be other attributes to the anchor tag. Also, there could be more than 1 anchor tag in the string. I'm doing the filtering in vb.net before it goes to the database.
Here's a simple regular expression that should work. Imports System.Text.RegularExpressions '.... Dim reg As New Regex(".+? ") Dim input As String = "This is a link: Stackoverflow " input = reg.Replace(input, "$1", RegexOptions.IgnoreCase)
Filtering out anchor tags in a string I need to filter out anchor tags in a string. For instance, Check out this site: stackoverflow I need to be able to filter out the anchor tag to this: Check out this site: http://www.stackoverflow.com That format may not be constant, either. There could be other attributes to the anchor tag. Also, there could be more than 1 anchor tag in the string. I'm doing the filtering in vb.net before it goes to the database.
TITLE: Filtering out anchor tags in a string QUESTION: I need to filter out anchor tags in a string. For instance, Check out this site: stackoverflow I need to be able to filter out the anchor tag to this: Check out this site: http://www.stackoverflow.com That format may not be constant, either. There could be other attributes to the anchor tag. Also, there could be more than 1 anchor tag in the string. I'm doing the filtering in vb.net before it goes to the database. ANSWER: Here's a simple regular expression that should work. Imports System.Text.RegularExpressions '.... Dim reg As New Regex(".+? ") Dim input As String = "This is a link: Stackoverflow " input = reg.Replace(input, "$1", RegexOptions.IgnoreCase)
[ "asp.net", "html", "vb.net" ]
7
8
1,238
1
0
2008-08-25T01:00:50.370000
2008-08-25T01:11:56.960000
25,530
25,543
Best Method to run a Java Application as a *nix Daemon or Windows Service?
I am looking for the best method to run a Java Application as a *NIX daemon or a Windows Service. I've looked in to the Java Service Wrapper, the Apache Commons project 'jsvc', and the Apache Commons project 'procrun'. So far, the Java Service Wrapper looks like it's the best option... but, I'm wondering if there are any other "Open Source friendly" licensed products out there.
I've had great success with Java Service Wrapper myself. I haven't looked at the others, but the major strengths of ServiceWrapper are: Great x-platform support - I've used it on Windows and Linux, and found it easy on both Solid Documentation - The docs are clear and to the point, with great examples Deep per-platform support - There are some unique features in the window service management system that are supported perfectly by service wrapper (w/o restarting). And on Windows, you will even see your app name in the process list instead of just "java.exe". Standards Compliant - Unlike many ad-hoc Java init scripts, the scripts for service wrapper tend to be compliant with LSB standards. This can end up being very important if you ever want high availability management from something like Linux Heartbeat/HA. Anyway, just my 2 cents...:)
Best Method to run a Java Application as a *nix Daemon or Windows Service? I am looking for the best method to run a Java Application as a *NIX daemon or a Windows Service. I've looked in to the Java Service Wrapper, the Apache Commons project 'jsvc', and the Apache Commons project 'procrun'. So far, the Java Service Wrapper looks like it's the best option... but, I'm wondering if there are any other "Open Source friendly" licensed products out there.
TITLE: Best Method to run a Java Application as a *nix Daemon or Windows Service? QUESTION: I am looking for the best method to run a Java Application as a *NIX daemon or a Windows Service. I've looked in to the Java Service Wrapper, the Apache Commons project 'jsvc', and the Apache Commons project 'procrun'. So far, the Java Service Wrapper looks like it's the best option... but, I'm wondering if there are any other "Open Source friendly" licensed products out there. ANSWER: I've had great success with Java Service Wrapper myself. I haven't looked at the others, but the major strengths of ServiceWrapper are: Great x-platform support - I've used it on Windows and Linux, and found it easy on both Solid Documentation - The docs are clear and to the point, with great examples Deep per-platform support - There are some unique features in the window service management system that are supported perfectly by service wrapper (w/o restarting). And on Windows, you will even see your app name in the process list instead of just "java.exe". Standards Compliant - Unlike many ad-hoc Java init scripts, the scripts for service wrapper tend to be compliant with LSB standards. This can end up being very important if you ever want high availability management from something like Linux Heartbeat/HA. Anyway, just my 2 cents...:)
[ "java", "unix", "windows-services", "daemon" ]
20
18
4,975
3
0
2008-08-25T01:11:59.080000
2008-08-25T01:38:11.030000
25,532
25,540
ASP.NET Master Pages equivalent in Java
What would be the Master Pages equivalent in the Java web development world? I've heard of Tiles, Tapestry and Velocity but don't know anything about them. Are they as easy to use as Master Pages? I want something as easy as set up one template and subsequent pages derive from the template and override content regions, similar to Master Pages. Any examples would be great!!
First, the equivalent of ASP.Net in Java is going to be a web framework, such as the ones you mention (Tiles, Tapestry and Velocity). Master pages give the ability to define pages in terms of content slotted into a master template. Master pages are a feature of ASP.Net (the.Net web framework), so you are looking for a feature similar to master pages in a Java web framework. http://tiles.apache.org/framework/tutorial/basic/pages.html gives some basic examples using Tiles and JSP to implement something similar with Struts, a Java web framework. In this case, the Master Pages functionality is a plugin on top of Struts. Velocity is a generic templating engine, not specialized for web pages and definitely more complicated than you need. (I've seen it used for code generation.) Tapestry is more of a full featured web stack than Tile, and is probably good for your purposes. Its templating functionality involves creating a component and putting all common markup in that. An example is at http://www.infoq.com/articles/tapestry5-intro. The specifics of this differ based on which Java web framework you choose.
ASP.NET Master Pages equivalent in Java What would be the Master Pages equivalent in the Java web development world? I've heard of Tiles, Tapestry and Velocity but don't know anything about them. Are they as easy to use as Master Pages? I want something as easy as set up one template and subsequent pages derive from the template and override content regions, similar to Master Pages. Any examples would be great!!
TITLE: ASP.NET Master Pages equivalent in Java QUESTION: What would be the Master Pages equivalent in the Java web development world? I've heard of Tiles, Tapestry and Velocity but don't know anything about them. Are they as easy to use as Master Pages? I want something as easy as set up one template and subsequent pages derive from the template and override content regions, similar to Master Pages. Any examples would be great!! ANSWER: First, the equivalent of ASP.Net in Java is going to be a web framework, such as the ones you mention (Tiles, Tapestry and Velocity). Master pages give the ability to define pages in terms of content slotted into a master template. Master pages are a feature of ASP.Net (the.Net web framework), so you are looking for a feature similar to master pages in a Java web framework. http://tiles.apache.org/framework/tutorial/basic/pages.html gives some basic examples using Tiles and JSP to implement something similar with Struts, a Java web framework. In this case, the Master Pages functionality is a plugin on top of Struts. Velocity is a generic templating engine, not specialized for web pages and definitely more complicated than you need. (I've seen it used for code generation.) Tapestry is more of a full featured web stack than Tile, and is probably good for your purposes. Its templating functionality involves creating a component and putting all common markup in that. An example is at http://www.infoq.com/articles/tapestry5-intro. The specifics of this differ based on which Java web framework you choose.
[ "java", "model-view-controller", "master-pages" ]
6
4
10,216
3
0
2008-08-25T01:13:04.337000
2008-08-25T01:34:37.123000
25,546
55,252
Securely sync folders over a public network
I need to keep the files & folders on two Windows-based, non-domain machines synchronized across a public network. I was thinking rsync over SSH - but I was wondering if there is a simpler solution? Any possibility of using the sync framework over SFTP/SCP/SSH? Or I'm open to better ideas?
Figured I'd post what I finally went with - WinSCP - http://winscp.net Connects via GUI to an SFTP server + supports Local/Remote/Both synchronization + scriptable with command-line/batch interface.
Securely sync folders over a public network I need to keep the files & folders on two Windows-based, non-domain machines synchronized across a public network. I was thinking rsync over SSH - but I was wondering if there is a simpler solution? Any possibility of using the sync framework over SFTP/SCP/SSH? Or I'm open to better ideas?
TITLE: Securely sync folders over a public network QUESTION: I need to keep the files & folders on two Windows-based, non-domain machines synchronized across a public network. I was thinking rsync over SSH - but I was wondering if there is a simpler solution? Any possibility of using the sync framework over SFTP/SCP/SSH? Or I'm open to better ideas? ANSWER: Figured I'd post what I finally went with - WinSCP - http://winscp.net Connects via GUI to an SFTP server + supports Local/Remote/Both synchronization + scriptable with command-line/batch interface.
[ "synchronization", "security", "rsync" ]
5
2
3,920
11
0
2008-08-25T01:46:05.737000
2008-09-10T20:32:38.643000
25,550
25,631
What's the best way to import/read data from pdf files?
We get a large amount of data from our clients in pdf files in varying formats [layout-wise], these files are typically report output, and are typically properly annotated [they don't usually need OCR], but not formatted well enough that simply copying several hundred pages of text out of acrobat is not going to work. The best approach I've found so far is to write a script to parse the nearly-valid xml output (the comments are invalid and many characters are escaped in varying ways, é becomes [[[e9]]]é, $ becomes \$, % becomes \%...) of the command-line pdftoipe utility (to convert pdf files for a program called ipe ), which gives me text elements with their positions on each page [see sample below], which works well enough for reports where the same values are on the same place on every page I care about, but would require extra scripting effort for importing matrix [cross-tab] pdf files. pdftoipe is not at all intended for this, and at best can be compiled manually using cygwin for windows. Are there libraries that make this easy from some scripting language I can tolerate? A graphical tool would be awesome too. And a pony. pdftoipe output of this sample looks like this: <-- Page: 1 1 --> 64.8 144 m 486 144 l 486 727.2 l 64.8 727.2 l 64.8 144 l h 64.8 144 m 486 144 l 486 727.2 l 64.8 727.2 l 64.8 144 l h 64.8 144 m 486 144 l 486 727.2 l 64.8 727.2 l 64.8 144 l h This is a sample PDF fil e. If you can read this, you already have A dobe Acrobat Reader i n stalled on your computer. feedcafebabe...
We use Xpdf in one of our applications. Its a c++ library which is primarily used for pdf rendering, although it does have a text extractor which could be useful for this project.
What's the best way to import/read data from pdf files? We get a large amount of data from our clients in pdf files in varying formats [layout-wise], these files are typically report output, and are typically properly annotated [they don't usually need OCR], but not formatted well enough that simply copying several hundred pages of text out of acrobat is not going to work. The best approach I've found so far is to write a script to parse the nearly-valid xml output (the comments are invalid and many characters are escaped in varying ways, é becomes [[[e9]]]é, $ becomes \$, % becomes \%...) of the command-line pdftoipe utility (to convert pdf files for a program called ipe ), which gives me text elements with their positions on each page [see sample below], which works well enough for reports where the same values are on the same place on every page I care about, but would require extra scripting effort for importing matrix [cross-tab] pdf files. pdftoipe is not at all intended for this, and at best can be compiled manually using cygwin for windows. Are there libraries that make this easy from some scripting language I can tolerate? A graphical tool would be awesome too. And a pony. pdftoipe output of this sample looks like this: <-- Page: 1 1 --> 64.8 144 m 486 144 l 486 727.2 l 64.8 727.2 l 64.8 144 l h 64.8 144 m 486 144 l 486 727.2 l 64.8 727.2 l 64.8 144 l h 64.8 144 m 486 144 l 486 727.2 l 64.8 727.2 l 64.8 144 l h This is a sample PDF fil e. If you can read this, you already have A dobe Acrobat Reader i n stalled on your computer. feedcafebabe...
TITLE: What's the best way to import/read data from pdf files? QUESTION: We get a large amount of data from our clients in pdf files in varying formats [layout-wise], these files are typically report output, and are typically properly annotated [they don't usually need OCR], but not formatted well enough that simply copying several hundred pages of text out of acrobat is not going to work. The best approach I've found so far is to write a script to parse the nearly-valid xml output (the comments are invalid and many characters are escaped in varying ways, é becomes [[[e9]]]é, $ becomes \$, % becomes \%...) of the command-line pdftoipe utility (to convert pdf files for a program called ipe ), which gives me text elements with their positions on each page [see sample below], which works well enough for reports where the same values are on the same place on every page I care about, but would require extra scripting effort for importing matrix [cross-tab] pdf files. pdftoipe is not at all intended for this, and at best can be compiled manually using cygwin for windows. Are there libraries that make this easy from some scripting language I can tolerate? A graphical tool would be awesome too. And a pony. pdftoipe output of this sample looks like this: <-- Page: 1 1 --> 64.8 144 m 486 144 l 486 727.2 l 64.8 727.2 l 64.8 144 l h 64.8 144 m 486 144 l 486 727.2 l 64.8 727.2 l 64.8 144 l h 64.8 144 m 486 144 l 486 727.2 l 64.8 727.2 l 64.8 144 l h This is a sample PDF fil e. If you can read this, you already have A dobe Acrobat Reader i n stalled on your computer. feedcafebabe... ANSWER: We use Xpdf in one of our applications. Its a c++ library which is primarily used for pdf rendering, although it does have a text extractor which could be useful for this project.
[ "pdf", "import" ]
4
3
11,477
4
0
2008-08-25T01:49:22.250000
2008-08-25T03:48:40.640000
25,552
25,596
Get OS-level system information
I'm currently building a Java app that could end up being run on many different platforms, but primarily variants of Solaris, Linux and Windows. Has anyone been able to successfully extract information such as the current disk space used, CPU utilisation and memory used in the underlying OS? What about just what the Java app itself is consuming? Preferrably I'd like to get this information without using JNI.
You can get some limited memory information from the Runtime class. It really isn't exactly what you are looking for, but I thought I would provide it for the sake of completeness. Here is a small example. Edit: You can also get disk usage information from the java.io.File class. The disk space usage stuff requires Java 1.6 or higher. public class Main { public static void main(String[] args) { /* Total number of processors or cores available to the JVM */ System.out.println("Available processors (cores): " + Runtime.getRuntime().availableProcessors()); /* Total amount of free memory available to the JVM */ System.out.println("Free memory (bytes): " + Runtime.getRuntime().freeMemory()); /* This will return Long.MAX_VALUE if there is no preset limit */ long maxMemory = Runtime.getRuntime().maxMemory(); /* Maximum amount of memory the JVM will attempt to use */ System.out.println("Maximum memory (bytes): " + (maxMemory == Long.MAX_VALUE? "no limit": maxMemory)); /* Total memory currently available to the JVM */ System.out.println("Total memory available to JVM (bytes): " + Runtime.getRuntime().totalMemory()); /* Get a list of all filesystem roots on this system */ File[] roots = File.listRoots(); /* For each filesystem root, print some info */ for (File root: roots) { System.out.println("File system root: " + root.getAbsolutePath()); System.out.println("Total space (bytes): " + root.getTotalSpace()); System.out.println("Free space (bytes): " + root.getFreeSpace()); System.out.println("Usable space (bytes): " + root.getUsableSpace()); } } }
Get OS-level system information I'm currently building a Java app that could end up being run on many different platforms, but primarily variants of Solaris, Linux and Windows. Has anyone been able to successfully extract information such as the current disk space used, CPU utilisation and memory used in the underlying OS? What about just what the Java app itself is consuming? Preferrably I'd like to get this information without using JNI.
TITLE: Get OS-level system information QUESTION: I'm currently building a Java app that could end up being run on many different platforms, but primarily variants of Solaris, Linux and Windows. Has anyone been able to successfully extract information such as the current disk space used, CPU utilisation and memory used in the underlying OS? What about just what the Java app itself is consuming? Preferrably I'd like to get this information without using JNI. ANSWER: You can get some limited memory information from the Runtime class. It really isn't exactly what you are looking for, but I thought I would provide it for the sake of completeness. Here is a small example. Edit: You can also get disk usage information from the java.io.File class. The disk space usage stuff requires Java 1.6 or higher. public class Main { public static void main(String[] args) { /* Total number of processors or cores available to the JVM */ System.out.println("Available processors (cores): " + Runtime.getRuntime().availableProcessors()); /* Total amount of free memory available to the JVM */ System.out.println("Free memory (bytes): " + Runtime.getRuntime().freeMemory()); /* This will return Long.MAX_VALUE if there is no preset limit */ long maxMemory = Runtime.getRuntime().maxMemory(); /* Maximum amount of memory the JVM will attempt to use */ System.out.println("Maximum memory (bytes): " + (maxMemory == Long.MAX_VALUE? "no limit": maxMemory)); /* Total memory currently available to the JVM */ System.out.println("Total memory available to JVM (bytes): " + Runtime.getRuntime().totalMemory()); /* Get a list of all filesystem roots on this system */ File[] roots = File.listRoots(); /* For each filesystem root, print some info */ for (File root: roots) { System.out.println("File system root: " + root.getAbsolutePath()); System.out.println("Total space (bytes): " + root.getTotalSpace()); System.out.println("Free space (bytes): " + root.getFreeSpace()); System.out.println("Usable space (bytes): " + root.getUsableSpace()); } } }
[ "java", "memory", "resources", "system" ]
244
210
260,837
17
0
2008-08-25T01:49:55.433000
2008-08-25T02:53:21.287000
25,561
25,622
Capturing a repeated group
I am attempting to parse a string like the following using a.NET regular expression: H3Y5NC8E-TGA5B6SB-2NVAQ4E0 and return the following using Split: H3Y5NC8E TGA5B6SB 2NVAQ4E0 I validate each character against a specific character set (note that the letters 'I', 'O', 'U' & 'W' are absent), so using string.Split is not an option. The number of characters in each group can vary and the number of groups can also vary. I am using the following expression: ([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8}-?){3} This will match exactly 3 groups of 8 characters each. Any more or less will fail the match. This works insofar as it correctly matches the input. However, when I use the Split method to extract each character group, I just get the final group. RegexBuddy complains that I have repeated the capturing group itself and that I should put a capture group around the repeated group. However, none of my attempts to do this achieve the desired result. I have been trying expressions like this: (([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){4} But this does not work. Since I generate the regex in code, I could just expand it out by the number of groups, but I was hoping for a more elegant solution. Please note that the character set does not include the entire alphabet. It is part of a product activation system. As such, any characters that can be accidentally interpreted as numbers or other characters are removed. e.g. The letters 'I', 'O', 'U' & 'W' are not in the character set. The hyphens are optional since a user does not need top type them in, but they can be there if the user as done a copy & paste.
I have discovered the answer I was after. Here is my working code: static void Main(string[] args) { string pattern = @"^\s*((? [ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){3}\s*$"; string input = "H3Y5NC8E-TGA5B6SB-2NVAQ4E0"; Regex re = new Regex(pattern); Match m = re.Match(input); if (m.Success) foreach (Capture c in m.Groups["group"].Captures) Console.WriteLine(c.Value); }
Capturing a repeated group I am attempting to parse a string like the following using a.NET regular expression: H3Y5NC8E-TGA5B6SB-2NVAQ4E0 and return the following using Split: H3Y5NC8E TGA5B6SB 2NVAQ4E0 I validate each character against a specific character set (note that the letters 'I', 'O', 'U' & 'W' are absent), so using string.Split is not an option. The number of characters in each group can vary and the number of groups can also vary. I am using the following expression: ([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8}-?){3} This will match exactly 3 groups of 8 characters each. Any more or less will fail the match. This works insofar as it correctly matches the input. However, when I use the Split method to extract each character group, I just get the final group. RegexBuddy complains that I have repeated the capturing group itself and that I should put a capture group around the repeated group. However, none of my attempts to do this achieve the desired result. I have been trying expressions like this: (([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){4} But this does not work. Since I generate the regex in code, I could just expand it out by the number of groups, but I was hoping for a more elegant solution. Please note that the character set does not include the entire alphabet. It is part of a product activation system. As such, any characters that can be accidentally interpreted as numbers or other characters are removed. e.g. The letters 'I', 'O', 'U' & 'W' are not in the character set. The hyphens are optional since a user does not need top type them in, but they can be there if the user as done a copy & paste.
TITLE: Capturing a repeated group QUESTION: I am attempting to parse a string like the following using a.NET regular expression: H3Y5NC8E-TGA5B6SB-2NVAQ4E0 and return the following using Split: H3Y5NC8E TGA5B6SB 2NVAQ4E0 I validate each character against a specific character set (note that the letters 'I', 'O', 'U' & 'W' are absent), so using string.Split is not an option. The number of characters in each group can vary and the number of groups can also vary. I am using the following expression: ([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8}-?){3} This will match exactly 3 groups of 8 characters each. Any more or less will fail the match. This works insofar as it correctly matches the input. However, when I use the Split method to extract each character group, I just get the final group. RegexBuddy complains that I have repeated the capturing group itself and that I should put a capture group around the repeated group. However, none of my attempts to do this achieve the desired result. I have been trying expressions like this: (([ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){4} But this does not work. Since I generate the regex in code, I could just expand it out by the number of groups, but I was hoping for a more elegant solution. Please note that the character set does not include the entire alphabet. It is part of a product activation system. As such, any characters that can be accidentally interpreted as numbers or other characters are removed. e.g. The letters 'I', 'O', 'U' & 'W' are not in the character set. The hyphens are optional since a user does not need top type them in, but they can be there if the user as done a copy & paste. ANSWER: I have discovered the answer I was after. Here is my working code: static void Main(string[] args) { string pattern = @"^\s*((? [ABCDEFGHJKLMNPQRSTVXYZ0123456789]{8})-?){3}\s*$"; string input = "H3Y5NC8E-TGA5B6SB-2NVAQ4E0"; Regex re = new Regex(pattern); Match m = re.Match(input); if (m.Success) foreach (Capture c in m.Groups["group"].Captures) Console.WriteLine(c.Value); }
[ "regex", ".net-2.0" ]
3
4
7,130
9
0
2008-08-25T01:59:45.020000
2008-08-25T03:33:47.303000