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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
55,594 | 55,597 | CSS not being applied on non authenticated ASP.NET page | When developing (works fine live) the pages for our website don't pick up the correct CSS until the user has authenticated (logged on). So the Logon and Logoff forms look bad, but once inside the site, the CSS works again. I'm guessing it's some kind of authentication issue? Haven't really looked into it too much because it's only when working on dev so not a huge issue, but would be nice to know how to fix it. | Check and make sure that the CSS file itself is not in an area that you are securing. You can manually exclude the file via the web.config if needed. | CSS not being applied on non authenticated ASP.NET page When developing (works fine live) the pages for our website don't pick up the correct CSS until the user has authenticated (logged on). So the Logon and Logoff forms look bad, but once inside the site, the CSS works again. I'm guessing it's some kind of authentication issue? Haven't really looked into it too much because it's only when working on dev so not a huge issue, but would be nice to know how to fix it. | TITLE:
CSS not being applied on non authenticated ASP.NET page
QUESTION:
When developing (works fine live) the pages for our website don't pick up the correct CSS until the user has authenticated (logged on). So the Logon and Logoff forms look bad, but once inside the site, the CSS works again. I'm guessing it's some kind of authentication issue? Haven't really looked into it too much because it's only when working on dev so not a huge issue, but would be nice to know how to fix it.
ANSWER:
Check and make sure that the CSS file itself is not in an area that you are securing. You can manually exclude the file via the web.config if needed. | [
"asp.net",
"css"
] | 14 | 15 | 11,088 | 4 | 0 | 2008-09-11T01:01:53.720000 | 2008-09-11T01:03:35.853000 |
55,607 | 55,681 | Best Technique for Multiple Eval Fields in Gridview ItemTemplate? | What is the best way to use multiple EVAL fields in a GridView ItemTemplate? Looking to have some control over formatting for appearance as well as setting up hyperlinks/javascript etc. | Even clearer, IMO, is: <%# String.Format("{0} - {1}", Eval("Name1"), Eval("Name2")) %> | Best Technique for Multiple Eval Fields in Gridview ItemTemplate? What is the best way to use multiple EVAL fields in a GridView ItemTemplate? Looking to have some control over formatting for appearance as well as setting up hyperlinks/javascript etc. | TITLE:
Best Technique for Multiple Eval Fields in Gridview ItemTemplate?
QUESTION:
What is the best way to use multiple EVAL fields in a GridView ItemTemplate? Looking to have some control over formatting for appearance as well as setting up hyperlinks/javascript etc.
ANSWER:
Even clearer, IMO, is: <%# String.Format("{0} - {1}", Eval("Name1"), Eval("Name2")) %> | [
"asp.net",
"data-binding",
"gridview",
"eval"
] | 34 | 64 | 60,116 | 4 | 0 | 2008-09-11T01:11:08.240000 | 2008-09-11T02:10:35.380000 |
55,611 | 55,637 | JavaScript private methods | To make a JavaScript class with a public method I'd do something like: function Restaurant() {}
Restaurant.prototype.buy_food = function(){ // something here }
Restaurant.prototype.use_restroom = function(){ // something here } That way users of my class can: var restaurant = new Restaurant(); restaurant.buy_food(); restaurant.use_restroom(); How do I create a private method that can be called by the buy_food and use_restroom methods but not externally by users of the class? In other words, I want my method implementation to be able to do: Restaurant.prototype.use_restroom = function() { this.private_stuff(); } But this shouldn't work: var r = new Restaurant(); r.private_stuff(); How do I define private_stuff as a private method so both of these hold true? I've read Doug Crockford's writeup a few times but it doesn't seem like "private" methods can be called by public methods and "privileged" methods can be called externally. | You can do it, but the downside is that it can't be part of the prototype: function Restaurant() { var myPrivateVar;
var private_stuff = function() { // Only visible inside Restaurant() myPrivateVar = "I can set this here!"; }
this.use_restroom = function() { // use_restroom is visible to all private_stuff(); }
this.buy_food = function() { // buy_food is visible to all private_stuff(); } } | JavaScript private methods To make a JavaScript class with a public method I'd do something like: function Restaurant() {}
Restaurant.prototype.buy_food = function(){ // something here }
Restaurant.prototype.use_restroom = function(){ // something here } That way users of my class can: var restaurant = new Restaurant(); restaurant.buy_food(); restaurant.use_restroom(); How do I create a private method that can be called by the buy_food and use_restroom methods but not externally by users of the class? In other words, I want my method implementation to be able to do: Restaurant.prototype.use_restroom = function() { this.private_stuff(); } But this shouldn't work: var r = new Restaurant(); r.private_stuff(); How do I define private_stuff as a private method so both of these hold true? I've read Doug Crockford's writeup a few times but it doesn't seem like "private" methods can be called by public methods and "privileged" methods can be called externally. | TITLE:
JavaScript private methods
QUESTION:
To make a JavaScript class with a public method I'd do something like: function Restaurant() {}
Restaurant.prototype.buy_food = function(){ // something here }
Restaurant.prototype.use_restroom = function(){ // something here } That way users of my class can: var restaurant = new Restaurant(); restaurant.buy_food(); restaurant.use_restroom(); How do I create a private method that can be called by the buy_food and use_restroom methods but not externally by users of the class? In other words, I want my method implementation to be able to do: Restaurant.prototype.use_restroom = function() { this.private_stuff(); } But this shouldn't work: var r = new Restaurant(); r.private_stuff(); How do I define private_stuff as a private method so both of these hold true? I've read Doug Crockford's writeup a few times but it doesn't seem like "private" methods can be called by public methods and "privileged" methods can be called externally.
ANSWER:
You can do it, but the downside is that it can't be part of the prototype: function Restaurant() { var myPrivateVar;
var private_stuff = function() { // Only visible inside Restaurant() myPrivateVar = "I can set this here!"; }
this.use_restroom = function() { // use_restroom is visible to all private_stuff(); }
this.buy_food = function() { // buy_food is visible to all private_stuff(); } } | [
"javascript",
"oop",
"private-methods"
] | 550 | 453 | 472,679 | 34 | 0 | 2008-09-11T01:12:39.030000 | 2008-09-11T01:26:52.583000 |
55,612 | 55,624 | CSS to select/style first word | This one has me kind of stumped. I want to make the first word of all the paragraphs in my #content div at 14pt instead of the default for the paragraphs (12pt). Is there a way to do this in straight CSS or am I left wrapping the first word in a span to accomplish this? | What you are looking for is a pseudo-element that doesn't exist. There is:first-letter and:first-line, but no:first-word. You can of course do this with JavaScript. Here's some code I found that does this: http://www.dynamicsitesolutions.com/javascript/first-word-selector/ | CSS to select/style first word This one has me kind of stumped. I want to make the first word of all the paragraphs in my #content div at 14pt instead of the default for the paragraphs (12pt). Is there a way to do this in straight CSS or am I left wrapping the first word in a span to accomplish this? | TITLE:
CSS to select/style first word
QUESTION:
This one has me kind of stumped. I want to make the first word of all the paragraphs in my #content div at 14pt instead of the default for the paragraphs (12pt). Is there a way to do this in straight CSS or am I left wrapping the first word in a span to accomplish this?
ANSWER:
What you are looking for is a pseudo-element that doesn't exist. There is:first-letter and:first-line, but no:first-word. You can of course do this with JavaScript. Here's some code I found that does this: http://www.dynamicsitesolutions.com/javascript/first-word-selector/ | [
"css"
] | 100 | 107 | 232,413 | 14 | 0 | 2008-09-11T01:13:56.110000 | 2008-09-11T01:18:21.560000 |
55,633 | 55,653 | Where is the console API for WebKit/Safari? | WebKit/Safari supports the console object, which is similar to what Firebug does. But what exactly is supported? There is a console documentation for Firebug, but where can I find the console documentation for Safari/WebKit? | Supported methods were originally: console.log() console.error() console.warn() console.info() Newer versions of WebKit also add the following methods making the WebKit console API almost identical to Firebug's console API: console.count() console.debug() console.profileEnd() console.trace() console.dir() console.dirxml() console.assert() console.time() console.profile() console.timeEnd() console.group() console.groupEnd() (New information based on the WebKit nightly build WebKit-SVN-r37126, at the time of writing these methods aren't available in Safari) | Where is the console API for WebKit/Safari? WebKit/Safari supports the console object, which is similar to what Firebug does. But what exactly is supported? There is a console documentation for Firebug, but where can I find the console documentation for Safari/WebKit? | TITLE:
Where is the console API for WebKit/Safari?
QUESTION:
WebKit/Safari supports the console object, which is similar to what Firebug does. But what exactly is supported? There is a console documentation for Firebug, but where can I find the console documentation for Safari/WebKit?
ANSWER:
Supported methods were originally: console.log() console.error() console.warn() console.info() Newer versions of WebKit also add the following methods making the WebKit console API almost identical to Firebug's console API: console.count() console.debug() console.profileEnd() console.trace() console.dir() console.dirxml() console.assert() console.time() console.profile() console.timeEnd() console.group() console.groupEnd() (New information based on the WebKit nightly build WebKit-SVN-r37126, at the time of writing these methods aren't available in Safari) | [
"javascript",
"console",
"safari"
] | 64 | 66 | 27,920 | 7 | 0 | 2008-09-11T01:23:24.700000 | 2008-09-11T01:39:25.520000 |
55,639 | 55,664 | How do you communicate between Windows Vista Session 0 and Desktop? | In prior versions of Windows before Vista you could have a Windows Service interact with the current logged in desktop user to easy display information on the screen from the service. In Windows Vista Session 0 was added for security to isolate the services from the desktop. What is an easy way to communicate between a service and an application running outside of Session 0? So far I have gotten around this by using TCP/IP to communicate between the two but it seems to be kind of a sloppy way to do it. | You can use shared memory or named pipe to facilitate IPC as well. Conceptually this is similar to TCP/IP, but you don't have to worry about finding an unused port. You have to make sure that the named objects you create are prefixed with "Global\" to allow them to be accessed by all sessions as described here. AFAIK there is no way for a service to directly interact with the desktop any more. | How do you communicate between Windows Vista Session 0 and Desktop? In prior versions of Windows before Vista you could have a Windows Service interact with the current logged in desktop user to easy display information on the screen from the service. In Windows Vista Session 0 was added for security to isolate the services from the desktop. What is an easy way to communicate between a service and an application running outside of Session 0? So far I have gotten around this by using TCP/IP to communicate between the two but it seems to be kind of a sloppy way to do it. | TITLE:
How do you communicate between Windows Vista Session 0 and Desktop?
QUESTION:
In prior versions of Windows before Vista you could have a Windows Service interact with the current logged in desktop user to easy display information on the screen from the service. In Windows Vista Session 0 was added for security to isolate the services from the desktop. What is an easy way to communicate between a service and an application running outside of Session 0? So far I have gotten around this by using TCP/IP to communicate between the two but it seems to be kind of a sloppy way to do it.
ANSWER:
You can use shared memory or named pipe to facilitate IPC as well. Conceptually this is similar to TCP/IP, but you don't have to worry about finding an unused port. You have to make sure that the named objects you create are prefixed with "Global\" to allow them to be accessed by all sessions as described here. AFAIK there is no way for a service to directly interact with the desktop any more. | [
"windows-vista",
"ipc"
] | 7 | 4 | 3,011 | 3 | 0 | 2008-09-11T01:29:21.940000 | 2008-09-11T01:48:13.733000 |
55,641 | 55,650 | Unicode Processing in C++ | What is the best practice of Unicode processing in C++? | Use ICU for dealing with your data (or a similar library) In your own data store, make sure everything is stored in the same encoding Make sure you are always using your unicode library for mundane tasks like string length, capitalization status, etc. Never use standard library builtins like is_alpha unless that is the definition you want. I can't say it enough: never iterate over the indices of a string if you care about correctness, always use your unicode library for this. | Unicode Processing in C++ What is the best practice of Unicode processing in C++? | TITLE:
Unicode Processing in C++
QUESTION:
What is the best practice of Unicode processing in C++?
ANSWER:
Use ICU for dealing with your data (or a similar library) In your own data store, make sure everything is stored in the same encoding Make sure you are always using your unicode library for mundane tasks like string length, capitalization status, etc. Never use standard library builtins like is_alpha unless that is the definition you want. I can't say it enough: never iterate over the indices of a string if you care about correctness, always use your unicode library for this. | [
"c++",
"unicode"
] | 109 | 81 | 46,197 | 9 | 0 | 2008-09-11T01:30:32.140000 | 2008-09-11T01:37:17.303000 |
55,643 | 55,647 | How do I keep a mySQL database secure? | I'm going to be implementing a PHP/mySQL setup to store credit card information. It seems like AES_ENCRYPT/AES_DECRYPT is the way to go, but I'm still confused on one point: How do I keep the encryption key secure? Hardwiring it into my PHP scripts (which will live on the same server as the db) seems like a major security hole. What's the "best practice" solution here? | You should think long and hard about whether you REALLY need to keep the CC#. If you don't have a great reason, DON'T! Every other week you hear about some company being compromised and CC#'s being stolen. All these companies made a fatal flaw - they kept too much information. Keep the CC# until the transaction clears. After that, delete it. As far as securing the server, the best course of action is to secure the hardware and use the internal system socket to MySQL, and make sure to block any network access to the MySQL server. Make sure you're using both your system permissions and the MySQL permissions to allow as little access as needed. For some scripts, you might consider write-only authentication. There's really no encryption method that will be foolproof (as you will always need to decrypt, and thus must store the key). This is not to say you shouldn't - you can store your key in one location and if you detect system compromise you can destroy the file and render the data useless. | How do I keep a mySQL database secure? I'm going to be implementing a PHP/mySQL setup to store credit card information. It seems like AES_ENCRYPT/AES_DECRYPT is the way to go, but I'm still confused on one point: How do I keep the encryption key secure? Hardwiring it into my PHP scripts (which will live on the same server as the db) seems like a major security hole. What's the "best practice" solution here? | TITLE:
How do I keep a mySQL database secure?
QUESTION:
I'm going to be implementing a PHP/mySQL setup to store credit card information. It seems like AES_ENCRYPT/AES_DECRYPT is the way to go, but I'm still confused on one point: How do I keep the encryption key secure? Hardwiring it into my PHP scripts (which will live on the same server as the db) seems like a major security hole. What's the "best practice" solution here?
ANSWER:
You should think long and hard about whether you REALLY need to keep the CC#. If you don't have a great reason, DON'T! Every other week you hear about some company being compromised and CC#'s being stolen. All these companies made a fatal flaw - they kept too much information. Keep the CC# until the transaction clears. After that, delete it. As far as securing the server, the best course of action is to secure the hardware and use the internal system socket to MySQL, and make sure to block any network access to the MySQL server. Make sure you're using both your system permissions and the MySQL permissions to allow as little access as needed. For some scripts, you might consider write-only authentication. There's really no encryption method that will be foolproof (as you will always need to decrypt, and thus must store the key). This is not to say you shouldn't - you can store your key in one location and if you detect system compromise you can destroy the file and render the data useless. | [
"php",
"mysql",
"security",
"aes"
] | 10 | 16 | 11,181 | 5 | 0 | 2008-09-11T01:31:57.080000 | 2008-09-11T01:35:45.560000 |
55,669 | 55,682 | SharePoint Permissions | I would like to create a folder that users who do not have privileges to view the rest of the site can see. This user group would be granted access to the site, but I only want them to be able to view one particular page. Is this possible to do without going to every single page and removing the new user group's access? | yeah, you should be able to create a new group and add the users to that list/subweb/whatever and just that. This is assuming that you didn't grant access to all users somewhere. If you did, then hopefully the default access is granted to a default user group (like sharepoint visitors) and you can alter that group to exclude the users you only want to access the limited part of the site. If created correctly the new group shouldn't have access to the rest of the site. | SharePoint Permissions I would like to create a folder that users who do not have privileges to view the rest of the site can see. This user group would be granted access to the site, but I only want them to be able to view one particular page. Is this possible to do without going to every single page and removing the new user group's access? | TITLE:
SharePoint Permissions
QUESTION:
I would like to create a folder that users who do not have privileges to view the rest of the site can see. This user group would be granted access to the site, but I only want them to be able to view one particular page. Is this possible to do without going to every single page and removing the new user group's access?
ANSWER:
yeah, you should be able to create a new group and add the users to that list/subweb/whatever and just that. This is assuming that you didn't grant access to all users somewhere. If you did, then hopefully the default access is granted to a default user group (like sharepoint visitors) and you can alter that group to exclude the users you only want to access the limited part of the site. If created correctly the new group shouldn't have access to the rest of the site. | [
"sharepoint",
"permissions"
] | 0 | 2 | 793 | 2 | 0 | 2008-09-11T02:01:04.280000 | 2008-09-11T02:11:15.490000 |
55,692 | 55,694 | .NET namespaces | My background is primarily as a Java Developer, but lately I have been doing some work in.NET. So I have been trying to do some simple projects at home to get better at working with.NET. I have been able to transfer much of my Java experience into working with.NET (specifically C#), but the only thing that has really perplexed me is namespaces. I know namespaces are similar to Java packages, but as from what I can tell the main difference is that with Java packages they use actual file folders to show the seperation, while in.NET it does not and all the files reside in a single folder and the namespace is simply declared in each class. I find this odd, because I always saw packages as a way to organize and group related code, making it easier to navigate and comprehend. Since in.NET it does not work this work this way, overtime, the project appears more overcrowded and not as easy to navigate. Am I missing something here? I have to be. Should I be breaking things into separate projects within the solution? Or is there a better way to keep the classes and files organized within a project? Edit: As Blair pointed out this is pretty much the same question asked here. | I can't claim that it's a best practice, but I often see files organized in a directory hierarchy that mirrors the namespace. If it fits your mental model of the code better, then do so - I can't think of any harm. Just because the.NET model doesn't enforce relationships between namespaces, projects, and directory structure doesn't mean you can't have such relationships if you want to. I'd be a little leery of breaking up the code into more projects than you need, as this can slow compilation and add a little bit of overhead when you have to manage multiple assemblies. EDIT: Note that this question is nearly a duplicate of should the folders in a solution match the namespace? | .NET namespaces My background is primarily as a Java Developer, but lately I have been doing some work in.NET. So I have been trying to do some simple projects at home to get better at working with.NET. I have been able to transfer much of my Java experience into working with.NET (specifically C#), but the only thing that has really perplexed me is namespaces. I know namespaces are similar to Java packages, but as from what I can tell the main difference is that with Java packages they use actual file folders to show the seperation, while in.NET it does not and all the files reside in a single folder and the namespace is simply declared in each class. I find this odd, because I always saw packages as a way to organize and group related code, making it easier to navigate and comprehend. Since in.NET it does not work this work this way, overtime, the project appears more overcrowded and not as easy to navigate. Am I missing something here? I have to be. Should I be breaking things into separate projects within the solution? Or is there a better way to keep the classes and files organized within a project? Edit: As Blair pointed out this is pretty much the same question asked here. | TITLE:
.NET namespaces
QUESTION:
My background is primarily as a Java Developer, but lately I have been doing some work in.NET. So I have been trying to do some simple projects at home to get better at working with.NET. I have been able to transfer much of my Java experience into working with.NET (specifically C#), but the only thing that has really perplexed me is namespaces. I know namespaces are similar to Java packages, but as from what I can tell the main difference is that with Java packages they use actual file folders to show the seperation, while in.NET it does not and all the files reside in a single folder and the namespace is simply declared in each class. I find this odd, because I always saw packages as a way to organize and group related code, making it easier to navigate and comprehend. Since in.NET it does not work this work this way, overtime, the project appears more overcrowded and not as easy to navigate. Am I missing something here? I have to be. Should I be breaking things into separate projects within the solution? Or is there a better way to keep the classes and files organized within a project? Edit: As Blair pointed out this is pretty much the same question asked here.
ANSWER:
I can't claim that it's a best practice, but I often see files organized in a directory hierarchy that mirrors the namespace. If it fits your mental model of the code better, then do so - I can't think of any harm. Just because the.NET model doesn't enforce relationships between namespaces, projects, and directory structure doesn't mean you can't have such relationships if you want to. I'd be a little leery of breaking up the code into more projects than you need, as this can slow compilation and add a little bit of overhead when you have to manage multiple assemblies. EDIT: Note that this question is nearly a duplicate of should the folders in a solution match the namespace? | [
".net",
"namespaces"
] | 9 | 11 | 5,008 | 9 | 0 | 2008-09-11T02:26:45.327000 | 2008-09-11T02:29:49.687000 |
55,693 | 57,335 | How do you use FogBugz with an Agile methodology? | "Evidence-based scheduling" in FogBugz is interesting, but how do I use it w/ an Agile methodology? | As eed3si9n said, if you are consistent in your estimates for EBS, FogBugz will take care of this for you. As to the more general, how does FogBugz fit with the Agile methodology, your best bet is to do sprints as mini-releases. Create a sprint and add the cases you want to achieve for that sprint to that release (or milestone). Give it an end date, say a week away, if you do week long sprints. Then EBS can track it and tell you if you are on schedule. The graphs in the Reports section will also show you a burndown chart. The terminology is a bit different because FogBugz isn't Agile-only but the info is there. You want to see if the expected time you are going to finish your sprint is staying steady or going forward. If it is steady you are on track and your burndown rate is on target. If it is creeping up, you are losing ground and your sprint is getting delayed. Time to move things to the next sprint or figure out why you messed up your estimates:) Essentially I suppose this is a burn-up chart instead of a burndown chart, but it gives you the same answer to the same question. Am I going to finish on time? What do I have left to do? Atalasoft's Lou Franco wrote an excellent post on this as well. Patrick Altman also has an article. Update: fixed link to Altman's article | How do you use FogBugz with an Agile methodology? "Evidence-based scheduling" in FogBugz is interesting, but how do I use it w/ an Agile methodology? | TITLE:
How do you use FogBugz with an Agile methodology?
QUESTION:
"Evidence-based scheduling" in FogBugz is interesting, but how do I use it w/ an Agile methodology?
ANSWER:
As eed3si9n said, if you are consistent in your estimates for EBS, FogBugz will take care of this for you. As to the more general, how does FogBugz fit with the Agile methodology, your best bet is to do sprints as mini-releases. Create a sprint and add the cases you want to achieve for that sprint to that release (or milestone). Give it an end date, say a week away, if you do week long sprints. Then EBS can track it and tell you if you are on schedule. The graphs in the Reports section will also show you a burndown chart. The terminology is a bit different because FogBugz isn't Agile-only but the info is there. You want to see if the expected time you are going to finish your sprint is staying steady or going forward. If it is steady you are on track and your burndown rate is on target. If it is creeping up, you are losing ground and your sprint is getting delayed. Time to move things to the next sprint or figure out why you messed up your estimates:) Essentially I suppose this is a burn-up chart instead of a burndown chart, but it gives you the same answer to the same question. Am I going to finish on time? What do I have left to do? Atalasoft's Lou Franco wrote an excellent post on this as well. Patrick Altman also has an article. Update: fixed link to Altman's article | [
"agile",
"fogbugz",
"schedule"
] | 19 | 12 | 6,649 | 4 | 0 | 2008-09-11T02:29:25.413000 | 2008-09-11T18:56:10.020000 |
55,709 | 55,788 | Streaming large files in a java servlet | I am building a java server that needs to scale. One of the servlets will be serving images stored in Amazon S3. Recently under load, I ran out of memory in my VM and it was after I added the code to serve the images so I'm pretty sure that streaming larger servlet responses is causing my troubles. My question is: is there any best practice in how to code a java servlet to stream a large (>200k) response back to a browser when read from a database or other cloud storage? I've considered writing the file to a local temp drive and then spawning another thread to handle the streaming so that the tomcat servlet thread can be re-used. This seems like it would be io heavy. Any thoughts would be appreciated. Thanks. | When possible, you should not store the entire contents of a file to be served in memory. Instead, aquire an InputStream for the data, and copy the data to the Servlet OutputStream in pieces. For example: ServletOutputStream out = response.getOutputStream(); InputStream in = [ code to get source input stream ]; String mimeType = [ code to get mimetype of data to be served ]; byte[] bytes = new byte[FILEBUFFERSIZE]; int bytesRead;
response.setContentType(mimeType);
while ((bytesRead = in.read(bytes))!= -1) { out.write(bytes, 0, bytesRead); }
// do the following in a finally block: in.close(); out.close(); I do agree with toby, you should instead "point them to the S3 url." As for the OOM exception, are you sure it has to do with serving the image data? Let's say your JVM has 256MB of "extra" memory to use for serving image data. With Google's help, "256MB / 200KB" = 1310. For 2GB "extra" memory (these days a very reasonable amount) over 10,000 simultaneous clients could be supported. Even so, 1300 simultaneous clients is a pretty large number. Is this the type of load you experienced? If not, you may need to look elsewhere for the cause of the OOM exception. Edit - Regarding: In this use case the images can contain sensitive data... When I read through the S3 documentation a few weeks ago, I noticed that you can generate time-expiring keys that can be attached to S3 URLs. So, you would not have to open up the files on S3 to the public. My understanding of the technique is: Initial HTML page has download links to your webapp User clicks on a download link Your webapp generates an S3 URL that includes a key that expires in, lets say, 5 minutes. Send an HTTP redirect to the client with the URL from step 3. The user downloads the file from S3. This works even if the download takes more than 5 minutes - once a download starts it can continue through completion. | Streaming large files in a java servlet I am building a java server that needs to scale. One of the servlets will be serving images stored in Amazon S3. Recently under load, I ran out of memory in my VM and it was after I added the code to serve the images so I'm pretty sure that streaming larger servlet responses is causing my troubles. My question is: is there any best practice in how to code a java servlet to stream a large (>200k) response back to a browser when read from a database or other cloud storage? I've considered writing the file to a local temp drive and then spawning another thread to handle the streaming so that the tomcat servlet thread can be re-used. This seems like it would be io heavy. Any thoughts would be appreciated. Thanks. | TITLE:
Streaming large files in a java servlet
QUESTION:
I am building a java server that needs to scale. One of the servlets will be serving images stored in Amazon S3. Recently under load, I ran out of memory in my VM and it was after I added the code to serve the images so I'm pretty sure that streaming larger servlet responses is causing my troubles. My question is: is there any best practice in how to code a java servlet to stream a large (>200k) response back to a browser when read from a database or other cloud storage? I've considered writing the file to a local temp drive and then spawning another thread to handle the streaming so that the tomcat servlet thread can be re-used. This seems like it would be io heavy. Any thoughts would be appreciated. Thanks.
ANSWER:
When possible, you should not store the entire contents of a file to be served in memory. Instead, aquire an InputStream for the data, and copy the data to the Servlet OutputStream in pieces. For example: ServletOutputStream out = response.getOutputStream(); InputStream in = [ code to get source input stream ]; String mimeType = [ code to get mimetype of data to be served ]; byte[] bytes = new byte[FILEBUFFERSIZE]; int bytesRead;
response.setContentType(mimeType);
while ((bytesRead = in.read(bytes))!= -1) { out.write(bytes, 0, bytesRead); }
// do the following in a finally block: in.close(); out.close(); I do agree with toby, you should instead "point them to the S3 url." As for the OOM exception, are you sure it has to do with serving the image data? Let's say your JVM has 256MB of "extra" memory to use for serving image data. With Google's help, "256MB / 200KB" = 1310. For 2GB "extra" memory (these days a very reasonable amount) over 10,000 simultaneous clients could be supported. Even so, 1300 simultaneous clients is a pretty large number. Is this the type of load you experienced? If not, you may need to look elsewhere for the cause of the OOM exception. Edit - Regarding: In this use case the images can contain sensitive data... When I read through the S3 documentation a few weeks ago, I noticed that you can generate time-expiring keys that can be attached to S3 URLs. So, you would not have to open up the files on S3 to the public. My understanding of the technique is: Initial HTML page has download links to your webapp User clicks on a download link Your webapp generates an S3 URL that includes a key that expires in, lets say, 5 minutes. Send an HTTP redirect to the client with the URL from step 3. The user downloads the file from S3. This works even if the download takes more than 5 minutes - once a download starts it can continue through completion. | [
"java",
"java-io"
] | 46 | 58 | 85,288 | 8 | 0 | 2008-09-11T02:40:12.563000 | 2008-09-11T03:53:45.523000 |
55,713 | 56,054 | PHP: How do I check if all public methods of two classes return the same values? | In effect, if I have a class c and instances of $c1 and $c2 which might have different private variable amounts but all their public methods return the same values I would like to be able to check that $c1 == $c2? Does anyone know an easy way to do this? | You can also implement a equal($other) function like or use foreach to iterate over the public properties (this behaviour might be overwritten) of one object and compare them to the other object's properties. $value) { if (!isset($b->$name) || $b->$name!=$value ) { return false; } } return true; } (untested) or (more or less) the same using the Reflection classes, see http://php.net/manual/en/language.oop5.reflection.php#language.oop5.reflection.reflectionobject With reflection you might also implement a more duck-typing kind of comparision, if you want to, like "I don't care if it's an instance of or the same class as long as it has the same public methods and they return the 'same' values" it really depends on how you define "equal". | PHP: How do I check if all public methods of two classes return the same values? In effect, if I have a class c and instances of $c1 and $c2 which might have different private variable amounts but all their public methods return the same values I would like to be able to check that $c1 == $c2? Does anyone know an easy way to do this? | TITLE:
PHP: How do I check if all public methods of two classes return the same values?
QUESTION:
In effect, if I have a class c and instances of $c1 and $c2 which might have different private variable amounts but all their public methods return the same values I would like to be able to check that $c1 == $c2? Does anyone know an easy way to do this?
ANSWER:
You can also implement a equal($other) function like or use foreach to iterate over the public properties (this behaviour might be overwritten) of one object and compare them to the other object's properties. $value) { if (!isset($b->$name) || $b->$name!=$value ) { return false; } } return true; } (untested) or (more or less) the same using the Reflection classes, see http://php.net/manual/en/language.oop5.reflection.php#language.oop5.reflection.reflectionobject With reflection you might also implement a more duck-typing kind of comparision, if you want to, like "I don't care if it's an instance of or the same class as long as it has the same public methods and they return the 'same' values" it really depends on how you define "equal". | [
"php",
"oop"
] | 2 | 2 | 1,038 | 5 | 0 | 2008-09-11T02:42:09.923000 | 2008-09-11T08:43:07.090000 |
55,720 | 55,737 | Find out where your PHP code is slowing down (Performance Issue) | Here's my first question at SO. I have a internal application for my company which I've been recently ask to maintain. The applications is built in PHP and its fairly well coded (OO, DB Abstraction, Smarty) nothing WTF-ish. The problem is the applications is very slow. How do I go about finding out what's slowing the application down? I've optimized the code to make very few DB queries, so I know that it is the PHP code which is taking a while to execute. I need to get some tools which can help me with this and need to devise a strategy for checking my code. I can do the checking/strategy work myself, but I need more PHP tools to figure out where my app is crapping up. Thoughts? | I've used XDebug profiling recently in a similiar situation. It outputs a full profile report that can be read with many common profiling apps ( Can't give you a list though, I just used the one that came with slackware ). | Find out where your PHP code is slowing down (Performance Issue) Here's my first question at SO. I have a internal application for my company which I've been recently ask to maintain. The applications is built in PHP and its fairly well coded (OO, DB Abstraction, Smarty) nothing WTF-ish. The problem is the applications is very slow. How do I go about finding out what's slowing the application down? I've optimized the code to make very few DB queries, so I know that it is the PHP code which is taking a while to execute. I need to get some tools which can help me with this and need to devise a strategy for checking my code. I can do the checking/strategy work myself, but I need more PHP tools to figure out where my app is crapping up. Thoughts? | TITLE:
Find out where your PHP code is slowing down (Performance Issue)
QUESTION:
Here's my first question at SO. I have a internal application for my company which I've been recently ask to maintain. The applications is built in PHP and its fairly well coded (OO, DB Abstraction, Smarty) nothing WTF-ish. The problem is the applications is very slow. How do I go about finding out what's slowing the application down? I've optimized the code to make very few DB queries, so I know that it is the PHP code which is taking a while to execute. I need to get some tools which can help me with this and need to devise a strategy for checking my code. I can do the checking/strategy work myself, but I need more PHP tools to figure out where my app is crapping up. Thoughts?
ANSWER:
I've used XDebug profiling recently in a similiar situation. It outputs a full profile report that can be read with many common profiling apps ( Can't give you a list though, I just used the one that came with slackware ). | [
"php",
"mysql",
"performance",
"profiling"
] | 31 | 40 | 31,922 | 12 | 0 | 2008-09-11T02:47:49.597000 | 2008-09-11T03:06:52.313000 |
55,729 | 55,738 | How often should you use git-gc? | How often should you use git-gc? The manual page simply says: Users are encouraged to run this task on a regular basis within each repository to maintain good disk space utilization and good operating performance. Are there some commands to get some object counts to find out whether it's time to gc? | It depends mostly on how much the repository is used. With one user checking in once a day and a branch/merge/etc operation once a week you probably don't need to run it more than once a year. With several dozen developers working on several dozen projects each checking in 2-3 times a day, you might want to run it nightly. It won't hurt to run it more frequently than needed, though. What I'd do is run it now, then a week from now take a measurement of disk utilization, run it again, and measure disk utilization again. If it drops 5% in size, then run it once a week. If it drops more, then run it more frequently. If it drops less, then run it less frequently. | How often should you use git-gc? How often should you use git-gc? The manual page simply says: Users are encouraged to run this task on a regular basis within each repository to maintain good disk space utilization and good operating performance. Are there some commands to get some object counts to find out whether it's time to gc? | TITLE:
How often should you use git-gc?
QUESTION:
How often should you use git-gc? The manual page simply says: Users are encouraged to run this task on a regular basis within each repository to maintain good disk space utilization and good operating performance. Are there some commands to get some object counts to find out whether it's time to gc?
ANSWER:
It depends mostly on how much the repository is used. With one user checking in once a day and a branch/merge/etc operation once a week you probably don't need to run it more than once a year. With several dozen developers working on several dozen projects each checking in 2-3 times a day, you might want to run it nightly. It won't hurt to run it more frequently than needed, though. What I'd do is run it now, then a week from now take a measurement of disk utilization, run it again, and measure disk utilization again. If it drops 5% in size, then run it once a week. If it drops more, then run it more frequently. If it drops less, then run it less frequently. | [
"git",
"git-gc"
] | 261 | 232 | 138,855 | 11 | 0 | 2008-09-11T02:59:13.830000 | 2008-09-11T03:10:24.350000 |
55,735 | 55,868 | How Do I detect Text and Cursor position changes in Word using VSTO | I want to write a word addin that does some computations and updates some ui whenever the user types something or moves the current insertion point. From looking at the MSDN docs, I don't see any obvious way such as an TextTyped event on the document or application objects. Does anyone know if this is possible without polling the document? | As you've probably discovered, Word has events, but they're for really coarse actions like a document open or a switch to another document. I'm guessing MS did this intentionally to prevent a crappy macro from slowing down typing. In short, there's no great way to do what you want. A Word MVP confirms that in this thread. | How Do I detect Text and Cursor position changes in Word using VSTO I want to write a word addin that does some computations and updates some ui whenever the user types something or moves the current insertion point. From looking at the MSDN docs, I don't see any obvious way such as an TextTyped event on the document or application objects. Does anyone know if this is possible without polling the document? | TITLE:
How Do I detect Text and Cursor position changes in Word using VSTO
QUESTION:
I want to write a word addin that does some computations and updates some ui whenever the user types something or moves the current insertion point. From looking at the MSDN docs, I don't see any obvious way such as an TextTyped event on the document or application objects. Does anyone know if this is possible without polling the document?
ANSWER:
As you've probably discovered, Word has events, but they're for really coarse actions like a document open or a switch to another document. I'm guessing MS did this intentionally to prevent a crappy macro from slowing down typing. In short, there's no great way to do what you want. A Word MVP confirms that in this thread. | [
"ms-word",
"ms-office",
"vsto"
] | 1 | 1 | 3,689 | 2 | 0 | 2008-09-11T03:05:48.353000 | 2008-09-11T05:47:51.693000 |
55,753 | 55,885 | Creating Custom Performance Counters in Visual C++ | Does anybody know of a method for creating custom Performance Counters using ordinary unmanaged Visual C++? I know that it can be done easily using managed C++, but I need to do it using an unmanaged Windows service. I also know that you can retrieve performance counter data, but I need to create some custom counters and increment them during the applications runtime. | See here: http://msdn.microsoft.com/en-us/library/aa371925.aspx It is not really hard, but a bit tedious as the API involves extensive usage of self-referential, variable-length structures and has to employ some IPC mechanism to obtain the data from the monitored process. | Creating Custom Performance Counters in Visual C++ Does anybody know of a method for creating custom Performance Counters using ordinary unmanaged Visual C++? I know that it can be done easily using managed C++, but I need to do it using an unmanaged Windows service. I also know that you can retrieve performance counter data, but I need to create some custom counters and increment them during the applications runtime. | TITLE:
Creating Custom Performance Counters in Visual C++
QUESTION:
Does anybody know of a method for creating custom Performance Counters using ordinary unmanaged Visual C++? I know that it can be done easily using managed C++, but I need to do it using an unmanaged Windows service. I also know that you can retrieve performance counter data, but I need to create some custom counters and increment them during the applications runtime.
ANSWER:
See here: http://msdn.microsoft.com/en-us/library/aa371925.aspx It is not really hard, but a bit tedious as the API involves extensive usage of self-referential, variable-length structures and has to employ some IPC mechanism to obtain the data from the monitored process. | [
"c++",
"visual-c++",
"performancecounter"
] | 5 | 6 | 10,441 | 4 | 0 | 2008-09-11T03:25:26.403000 | 2008-09-11T06:09:49.550000 |
55,754 | 55,782 | How to zero pad numbers in file names in Bash? | What is the best way, using Bash, to rename files in the form: (foo1, foo2,..., foo1300,..., fooN) With zero-padded file names: (foo00001, foo00002,..., foo01300,..., fooN) | In case N is not a priori fixed: for f in foo[0-9]*; do mv "$f" "$(printf 'foo%05d' "${f#foo}")" done | How to zero pad numbers in file names in Bash? What is the best way, using Bash, to rename files in the form: (foo1, foo2,..., foo1300,..., fooN) With zero-padded file names: (foo00001, foo00002,..., foo01300,..., fooN) | TITLE:
How to zero pad numbers in file names in Bash?
QUESTION:
What is the best way, using Bash, to rename files in the form: (foo1, foo2,..., foo1300,..., fooN) With zero-padded file names: (foo00001, foo00002,..., foo01300,..., fooN)
ANSWER:
In case N is not a priori fixed: for f in foo[0-9]*; do mv "$f" "$(printf 'foo%05d' "${f#foo}")" done | [
"bash",
"rename"
] | 66 | 44 | 42,708 | 10 | 0 | 2008-09-11T03:25:41.783000 | 2008-09-11T03:47:46.070000 |
55,755 | 55,760 | ASP.NET - Performance Implications of a sql server database in the app_data folder | The default asp.net membership provider uses a.mdf sql server database file in the app_code database. How scalable is this in terms of calling a flat file database instead of running it in a standard sql environment? Is this recommended only for small/medium traffic sites? | It's a reasonable trade off for any site that can run on one server. It's fairly reasonable for small to medium traffic sites. When you grow to a point of a web farm, then you'll be better off with a separate server. Also, depending on how database dependent your application is, you may find better performance handing off SQL queries to a totally different server/processor to handle the database side. | ASP.NET - Performance Implications of a sql server database in the app_data folder The default asp.net membership provider uses a.mdf sql server database file in the app_code database. How scalable is this in terms of calling a flat file database instead of running it in a standard sql environment? Is this recommended only for small/medium traffic sites? | TITLE:
ASP.NET - Performance Implications of a sql server database in the app_data folder
QUESTION:
The default asp.net membership provider uses a.mdf sql server database file in the app_code database. How scalable is this in terms of calling a flat file database instead of running it in a standard sql environment? Is this recommended only for small/medium traffic sites?
ANSWER:
It's a reasonable trade off for any site that can run on one server. It's fairly reasonable for small to medium traffic sites. When you grow to a point of a web farm, then you'll be better off with a separate server. Also, depending on how database dependent your application is, you may find better performance handing off SQL queries to a totally different server/processor to handle the database side. | [
"asp.net",
"sql-server",
"database"
] | 2 | 3 | 542 | 2 | 0 | 2008-09-11T03:25:56.213000 | 2008-09-11T03:30:09.950000 |
55,757 | 55,767 | PHP Multiform Validation and Redirection | I have buy.php with a form where you enter items, quantity, shipping data, etc. When you click the Submit button, it posts back to buy.php ($_SERVER['PHP_SELF']) and does some data validation. If there are fields missing or errors, they are highlighted. If everything is correct, I save the $_POST data in $_SESSION variables, then do a header('Location: check.php'), where I display the data so the buyer can check the info one last time before actually buying. Now, if I'm in check.php and hit the Back button to buy.php so I can change stuff, the browser asks if I want to resend the POST data. I'm trying to avoid that. Anyone have any good advice or good practices for PHP Multiform validation? Also, if I had n pages for the user to fill, buy.php, buy2.php,... buyn.php before check.php would the same ideas still hold? | You could do a redirect to buy.php after saving to the session object, which then does a server redirect to check.php, it would mean when the user clicks back, they're going back to the GET request not the POST request | PHP Multiform Validation and Redirection I have buy.php with a form where you enter items, quantity, shipping data, etc. When you click the Submit button, it posts back to buy.php ($_SERVER['PHP_SELF']) and does some data validation. If there are fields missing or errors, they are highlighted. If everything is correct, I save the $_POST data in $_SESSION variables, then do a header('Location: check.php'), where I display the data so the buyer can check the info one last time before actually buying. Now, if I'm in check.php and hit the Back button to buy.php so I can change stuff, the browser asks if I want to resend the POST data. I'm trying to avoid that. Anyone have any good advice or good practices for PHP Multiform validation? Also, if I had n pages for the user to fill, buy.php, buy2.php,... buyn.php before check.php would the same ideas still hold? | TITLE:
PHP Multiform Validation and Redirection
QUESTION:
I have buy.php with a form where you enter items, quantity, shipping data, etc. When you click the Submit button, it posts back to buy.php ($_SERVER['PHP_SELF']) and does some data validation. If there are fields missing or errors, they are highlighted. If everything is correct, I save the $_POST data in $_SESSION variables, then do a header('Location: check.php'), where I display the data so the buyer can check the info one last time before actually buying. Now, if I'm in check.php and hit the Back button to buy.php so I can change stuff, the browser asks if I want to resend the POST data. I'm trying to avoid that. Anyone have any good advice or good practices for PHP Multiform validation? Also, if I had n pages for the user to fill, buy.php, buy2.php,... buyn.php before check.php would the same ideas still hold?
ANSWER:
You could do a redirect to buy.php after saving to the session object, which then does a server redirect to check.php, it would mean when the user clicks back, they're going back to the GET request not the POST request | [
"php",
"validation",
"post"
] | 4 | 4 | 1,744 | 2 | 0 | 2008-09-11T03:27:07.007000 | 2008-09-11T03:35:47.033000 |
55,797 | 55,801 | How can one reference a WCF service in a different Visual Studio solution? | A Visual Studio 2008 project in one solution needs to reference a WCF service in another VS 2008 solution on the same development machine. Does anybody have any suggestions on how best to accomplish this? | Host the service, and then use the URI of the hosted service in the other project to have VS create a proxy for you. Here's a step by step article on how to add a reference. And here's an article that teaches you how to host a service in VS (which is probably the simplest thing to do while developing). I'd recommend you host your service in IIS, however, even during development. | How can one reference a WCF service in a different Visual Studio solution? A Visual Studio 2008 project in one solution needs to reference a WCF service in another VS 2008 solution on the same development machine. Does anybody have any suggestions on how best to accomplish this? | TITLE:
How can one reference a WCF service in a different Visual Studio solution?
QUESTION:
A Visual Studio 2008 project in one solution needs to reference a WCF service in another VS 2008 solution on the same development machine. Does anybody have any suggestions on how best to accomplish this?
ANSWER:
Host the service, and then use the URI of the hosted service in the other project to have VS create a proxy for you. Here's a step by step article on how to add a reference. And here's an article that teaches you how to host a service in VS (which is probably the simplest thing to do while developing). I'd recommend you host your service in IIS, however, even during development. | [
"visual-studio-2008",
"wcf"
] | 2 | 1 | 1,797 | 2 | 0 | 2008-09-11T04:18:07.743000 | 2008-09-11T04:20:06.053000 |
55,823 | 56,082 | What, if anything is typically done in a repository's structure to reflect deployed units? | This is a follow-up to the question: Should the folders in a solution match the namespace? The consensus on that question was a qualified "yes": that is, folders == namespaces, generally, but not slavishly (the way java requires). Indeed, that's how I set up projects. But setting up source control has made me hesitate about my current folder structure. As with the.NET Framework, the namespaces in my project do not always match the deployed units one-to-one. Say you have lib -> lib.dll lib.data -> lib.dll lib.ecom -> lib.ecom.dll lib.ecom.paypal -> lib.ecom.paypal.dll In other words, child namespaces may or may not ship with the parent. So are the namespaces that deploy together grouped in any way? By the way, I don't use VS or NAnt — just good old fashioned build batches. | I usually don't really think about this and just do "what feels right" but usually I end up using names that fit the following strategy fairly well. I'll use the highest common namespace in the tree for the.dll name just like you seem to be doing; with lib and lib.data this is lib so the dll is called lib. With lib.ecom and lib.ecom.paypal this is lib.ecom so the dll is called ecom. In some cases you need to think about things a bit more for example we have the following namespaces (warning, simplistic example coming up) and we want to group them in two dll's myapp.view myapp.presentation
myapp.model myapp.dataaccess we can't use myapp because then we would have two myapp assemblies. In this case I use the name of the namespace that is most appropriate. The first might be called myapp.presentation and the second myapp.model if those namespaces are the most important. | What, if anything is typically done in a repository's structure to reflect deployed units? This is a follow-up to the question: Should the folders in a solution match the namespace? The consensus on that question was a qualified "yes": that is, folders == namespaces, generally, but not slavishly (the way java requires). Indeed, that's how I set up projects. But setting up source control has made me hesitate about my current folder structure. As with the.NET Framework, the namespaces in my project do not always match the deployed units one-to-one. Say you have lib -> lib.dll lib.data -> lib.dll lib.ecom -> lib.ecom.dll lib.ecom.paypal -> lib.ecom.paypal.dll In other words, child namespaces may or may not ship with the parent. So are the namespaces that deploy together grouped in any way? By the way, I don't use VS or NAnt — just good old fashioned build batches. | TITLE:
What, if anything is typically done in a repository's structure to reflect deployed units?
QUESTION:
This is a follow-up to the question: Should the folders in a solution match the namespace? The consensus on that question was a qualified "yes": that is, folders == namespaces, generally, but not slavishly (the way java requires). Indeed, that's how I set up projects. But setting up source control has made me hesitate about my current folder structure. As with the.NET Framework, the namespaces in my project do not always match the deployed units one-to-one. Say you have lib -> lib.dll lib.data -> lib.dll lib.ecom -> lib.ecom.dll lib.ecom.paypal -> lib.ecom.paypal.dll In other words, child namespaces may or may not ship with the parent. So are the namespaces that deploy together grouped in any way? By the way, I don't use VS or NAnt — just good old fashioned build batches.
ANSWER:
I usually don't really think about this and just do "what feels right" but usually I end up using names that fit the following strategy fairly well. I'll use the highest common namespace in the tree for the.dll name just like you seem to be doing; with lib and lib.data this is lib so the dll is called lib. With lib.ecom and lib.ecom.paypal this is lib.ecom so the dll is called ecom. In some cases you need to think about things a bit more for example we have the following namespaces (warning, simplistic example coming up) and we want to group them in two dll's myapp.view myapp.presentation
myapp.model myapp.dataaccess we can't use myapp because then we would have two myapp assemblies. In this case I use the name of the namespace that is most appropriate. The first might be called myapp.presentation and the second myapp.model if those namespaces are the most important. | [
".net",
"dll",
"version-control",
"directory"
] | 0 | 1 | 97 | 1 | 0 | 2008-09-11T04:52:07.303000 | 2008-09-11T08:59:10.453000 |
55,835 | 55,849 | Is there a reliable way to prevent cheating in a web based contest where anonymous users can vote? | I'm working on a web-based contest which is supposed to allow anonymous users to vote, but we want to prevent them from voting more than once. IP based limits can be bypassed with anonymous proxies, users can clear cookies, etc. It's possible to use a Silverlight application, which would have access to isolated storage, but users can still clear that. I don't think it's possible to do this without some joker voting himself up with a bot or something. Got an idea? | The short answer is: no. The longer answer is: but you can make it arbitrarily difficult. What I would do: Voting requires solving a captcha (to avoid as much as possible automated voting). To be even more effective I would recommend to have prepared multiple types of simple captchas (like "pick the photo with the cat", "what is 2+2", "type in the word", etc) and rotate them both by the time of the day and by IP, which should make automatic systems ineffective (ie if somebody using IP A creates a bot to solve the captcha, this will become useless the next day or if s/he distributes it onto other computers/uses proxies) When filtering by IP you should be careful to consider situations where multiple hosts are behind one public IP (AFAIK AOL proxies all of their customers through a few IPs - so such a limitation would effectively ban AOL users). Also, many proxies send along headers pointing to the original IP (like X-Forwarded-For), so you can take a look at that too. Finally, using something like FSO (Flash Shared Objects - "Flash cookies") is obscure enough for 99.99% of the people not to know about. Silverlight is even more obscure. To be even sneakier, you could buy an other domain and set the FSO from that domain (so, if the user is looking for FSO's set by your domain, they won't see any) None of these methods is 100%, but hopefully combined they give you the level of assurance you need. If you want to take this a level higher, you need to add some kind of user registration (which can be as simple as asking a valid e-mail address when the vote occurs and sending a confirmation link to the given address and not counting the votes for which the link wasn't clicked - so it doesn't need to be a full-fledged "create an account with username / password / firs name / last name / etc"). | Is there a reliable way to prevent cheating in a web based contest where anonymous users can vote? I'm working on a web-based contest which is supposed to allow anonymous users to vote, but we want to prevent them from voting more than once. IP based limits can be bypassed with anonymous proxies, users can clear cookies, etc. It's possible to use a Silverlight application, which would have access to isolated storage, but users can still clear that. I don't think it's possible to do this without some joker voting himself up with a bot or something. Got an idea? | TITLE:
Is there a reliable way to prevent cheating in a web based contest where anonymous users can vote?
QUESTION:
I'm working on a web-based contest which is supposed to allow anonymous users to vote, but we want to prevent them from voting more than once. IP based limits can be bypassed with anonymous proxies, users can clear cookies, etc. It's possible to use a Silverlight application, which would have access to isolated storage, but users can still clear that. I don't think it's possible to do this without some joker voting himself up with a bot or something. Got an idea?
ANSWER:
The short answer is: no. The longer answer is: but you can make it arbitrarily difficult. What I would do: Voting requires solving a captcha (to avoid as much as possible automated voting). To be even more effective I would recommend to have prepared multiple types of simple captchas (like "pick the photo with the cat", "what is 2+2", "type in the word", etc) and rotate them both by the time of the day and by IP, which should make automatic systems ineffective (ie if somebody using IP A creates a bot to solve the captcha, this will become useless the next day or if s/he distributes it onto other computers/uses proxies) When filtering by IP you should be careful to consider situations where multiple hosts are behind one public IP (AFAIK AOL proxies all of their customers through a few IPs - so such a limitation would effectively ban AOL users). Also, many proxies send along headers pointing to the original IP (like X-Forwarded-For), so you can take a look at that too. Finally, using something like FSO (Flash Shared Objects - "Flash cookies") is obscure enough for 99.99% of the people not to know about. Silverlight is even more obscure. To be even sneakier, you could buy an other domain and set the FSO from that domain (so, if the user is looking for FSO's set by your domain, they won't see any) None of these methods is 100%, but hopefully combined they give you the level of assurance you need. If you want to take this a level higher, you need to add some kind of user registration (which can be as simple as asking a valid e-mail address when the vote occurs and sending a confirmation link to the given address and not counting the votes for which the link wasn't clicked - so it doesn't need to be a full-fledged "create an account with username / password / firs name / last name / etc"). | [
"asp.net",
"silverlight"
] | 12 | 19 | 1,566 | 7 | 0 | 2008-09-11T05:12:42.230000 | 2008-09-11T05:28:14.890000 |
55,843 | 85,732 | How can I test that my Linq IQueryable has executed | I am currently using Linq to NHibernate (although that is not an issue with regards to this question) to execute queries against my database and I want to be able to test whether the current IQueryable result instance has been executed or not. The debugger knows that my IQueryable has not been 'invoked' because it tells me that expanding the Results property will 'enumerate' it. Is there a way for me to programmatically identify that as well. I hope that makes sense:) | How about writing an IQueryable wrapper like this: class QueryableWrapper: IQueryable { private IQueryable _InnerQueryable; private bool _HasExecuted;
public QueryableWrapper(IQueryable innerQueryable) { _InnerQueryable = innerQueryable; }
public bool HasExecuted { get { return _HasExecuted; } }
public IEnumerator GetEnumerator() { _HasExecuted = true;
return _InnerQueryable.GetEnumerator(); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); }
public Type ElementType { get { return _InnerQueryable.ElementType; } }
public System.Linq.Expressions.Expression Expression { get { return _InnerQueryable.Expression; } }
public IQueryProvider Provider { get { return _InnerQueryable.Provider; } } } Then you can use it like this: var query = new QueryableWrapper ( from str in myDataSource select str);
Debug.WriteLine("HasExecuted: " + query.HasExecuted.ToString());
foreach (string str in query) { Debug.WriteLine(str); }
Debug.WriteLine("HasExecuted: " + query.HasExecuted.ToString()); Output is: False String0 String1... True | How can I test that my Linq IQueryable has executed I am currently using Linq to NHibernate (although that is not an issue with regards to this question) to execute queries against my database and I want to be able to test whether the current IQueryable result instance has been executed or not. The debugger knows that my IQueryable has not been 'invoked' because it tells me that expanding the Results property will 'enumerate' it. Is there a way for me to programmatically identify that as well. I hope that makes sense:) | TITLE:
How can I test that my Linq IQueryable has executed
QUESTION:
I am currently using Linq to NHibernate (although that is not an issue with regards to this question) to execute queries against my database and I want to be able to test whether the current IQueryable result instance has been executed or not. The debugger knows that my IQueryable has not been 'invoked' because it tells me that expanding the Results property will 'enumerate' it. Is there a way for me to programmatically identify that as well. I hope that makes sense:)
ANSWER:
How about writing an IQueryable wrapper like this: class QueryableWrapper: IQueryable { private IQueryable _InnerQueryable; private bool _HasExecuted;
public QueryableWrapper(IQueryable innerQueryable) { _InnerQueryable = innerQueryable; }
public bool HasExecuted { get { return _HasExecuted; } }
public IEnumerator GetEnumerator() { _HasExecuted = true;
return _InnerQueryable.GetEnumerator(); }
System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return GetEnumerator(); }
public Type ElementType { get { return _InnerQueryable.ElementType; } }
public System.Linq.Expressions.Expression Expression { get { return _InnerQueryable.Expression; } }
public IQueryProvider Provider { get { return _InnerQueryable.Provider; } } } Then you can use it like this: var query = new QueryableWrapper ( from str in myDataSource select str);
Debug.WriteLine("HasExecuted: " + query.HasExecuted.ToString());
foreach (string str in query) { Debug.WriteLine(str); }
Debug.WriteLine("HasExecuted: " + query.HasExecuted.ToString()); Output is: False String0 String1... True | [
"c#",
"linq"
] | 5 | 3 | 3,396 | 3 | 0 | 2008-09-11T05:18:43.167000 | 2008-09-17T17:41:36 |
55,845 | 55,850 | Should data security be performed on the database side? | We're in the process of setting up a new framework and way of doing business for our new internal apps. Our current design dictates that all security logic should be handled by our database, and all information (and I mean all) will be going in and out of the database via stored procedures. The theory is, the data access layer requests info from a stored procedure and passes over authentication to the database. The database determines the user's role/permissions and decides whether or not to perform the task (whether that be retrieving data or making an update). I guess this means fewer database transactions. One call to the database. If the security was in our data access layer, this would require 1 database call to determine if the user had proper permissions, and then 1 separate database call to perform the action. I, for one, find the SQL Management studio completely lacking as an IDE. My main concern is we will end up having to maintain some nasty amount of business logic in our stored procedures for some very minimal performance gains. Right now, we're using LINQ for our ORM. It seems light and fast, but best of all, its really easy to rapidly develop in. Is the maintenance cost worth the performance gain? Are we fooling ourselves into thinking there will even be a noticeable performance gain? Or are we just making a nightmare for ourselves? Our environment: Internal, non-mission critical business apps C#/ASP.NET 3.5 Windows 2003 MS SQL Server 2005 35 Medium sized web apps with approx 500 users | Don't do that. We recently had a VERY BAD experience when the "database guru" decided to go to another company. The maintenance of all the logic in the procedures are just horrible!! Yes, you're going to have some performance improvement, but that's not worth it. In fact, performance is not even a big concern in internal application. Invest more money in good servers. It'll pay off. | Should data security be performed on the database side? We're in the process of setting up a new framework and way of doing business for our new internal apps. Our current design dictates that all security logic should be handled by our database, and all information (and I mean all) will be going in and out of the database via stored procedures. The theory is, the data access layer requests info from a stored procedure and passes over authentication to the database. The database determines the user's role/permissions and decides whether or not to perform the task (whether that be retrieving data or making an update). I guess this means fewer database transactions. One call to the database. If the security was in our data access layer, this would require 1 database call to determine if the user had proper permissions, and then 1 separate database call to perform the action. I, for one, find the SQL Management studio completely lacking as an IDE. My main concern is we will end up having to maintain some nasty amount of business logic in our stored procedures for some very minimal performance gains. Right now, we're using LINQ for our ORM. It seems light and fast, but best of all, its really easy to rapidly develop in. Is the maintenance cost worth the performance gain? Are we fooling ourselves into thinking there will even be a noticeable performance gain? Or are we just making a nightmare for ourselves? Our environment: Internal, non-mission critical business apps C#/ASP.NET 3.5 Windows 2003 MS SQL Server 2005 35 Medium sized web apps with approx 500 users | TITLE:
Should data security be performed on the database side?
QUESTION:
We're in the process of setting up a new framework and way of doing business for our new internal apps. Our current design dictates that all security logic should be handled by our database, and all information (and I mean all) will be going in and out of the database via stored procedures. The theory is, the data access layer requests info from a stored procedure and passes over authentication to the database. The database determines the user's role/permissions and decides whether or not to perform the task (whether that be retrieving data or making an update). I guess this means fewer database transactions. One call to the database. If the security was in our data access layer, this would require 1 database call to determine if the user had proper permissions, and then 1 separate database call to perform the action. I, for one, find the SQL Management studio completely lacking as an IDE. My main concern is we will end up having to maintain some nasty amount of business logic in our stored procedures for some very minimal performance gains. Right now, we're using LINQ for our ORM. It seems light and fast, but best of all, its really easy to rapidly develop in. Is the maintenance cost worth the performance gain? Are we fooling ourselves into thinking there will even be a noticeable performance gain? Or are we just making a nightmare for ourselves? Our environment: Internal, non-mission critical business apps C#/ASP.NET 3.5 Windows 2003 MS SQL Server 2005 35 Medium sized web apps with approx 500 users
ANSWER:
Don't do that. We recently had a VERY BAD experience when the "database guru" decided to go to another company. The maintenance of all the logic in the procedures are just horrible!! Yes, you're going to have some performance improvement, but that's not worth it. In fact, performance is not even a big concern in internal application. Invest more money in good servers. It'll pay off. | [
"sql",
"security",
"stored-procedures"
] | 6 | 8 | 411 | 8 | 0 | 2008-09-11T05:21:30.757000 | 2008-09-11T05:30:19.957000 |
55,855 | 56,164 | TextBox.TextChanged & ICommandSource | I am following the M-V-VM pattern for my WPF UI. I would like to hook up a command to the TextChanged event of a TextBox to a command that is in my ViewModel class. The only way I can conceive of completing this task is to inherit from the TextBox control, and implement ICommandSource. I can then instruct the command to be fired from the TextChanged event. This seems to be too much work for something which appears to be so simple. Is there an easier way (than subclassing the TextBox and implementing ICommandSource) to hook up the TextChanged event to my ViewModel class? | First off, you've surely considered two-way data binding to your viewmodel, with an UpdateSourceTrigger of PropertyChanged? That way the property setter of the property you bind to will be called every time the text is changed? If that's not enough, then I would tackle this problem using Attached Behaviours. On Julian Dominguez’s Blog you'll find an article about how to do something very similar in Silverlight, which should be easily adaptable to WPF. Basically, in a static class (called, say TextBoxBehaviours) you define an Attached Property called (perhaps) TextChangedCommand of type ICommand. Hook up an OnPropertyChanged handler for that property, and within the handler, check that the property is being set on a TextBox; if it is, add a handler to the TextChanged event on the textbox that will call the command specified in the property. Then, assuming your viewmodel has been assigned to the DataContext of your View, you would use it like: | TextBox.TextChanged & ICommandSource I am following the M-V-VM pattern for my WPF UI. I would like to hook up a command to the TextChanged event of a TextBox to a command that is in my ViewModel class. The only way I can conceive of completing this task is to inherit from the TextBox control, and implement ICommandSource. I can then instruct the command to be fired from the TextChanged event. This seems to be too much work for something which appears to be so simple. Is there an easier way (than subclassing the TextBox and implementing ICommandSource) to hook up the TextChanged event to my ViewModel class? | TITLE:
TextBox.TextChanged & ICommandSource
QUESTION:
I am following the M-V-VM pattern for my WPF UI. I would like to hook up a command to the TextChanged event of a TextBox to a command that is in my ViewModel class. The only way I can conceive of completing this task is to inherit from the TextBox control, and implement ICommandSource. I can then instruct the command to be fired from the TextChanged event. This seems to be too much work for something which appears to be so simple. Is there an easier way (than subclassing the TextBox and implementing ICommandSource) to hook up the TextChanged event to my ViewModel class?
ANSWER:
First off, you've surely considered two-way data binding to your viewmodel, with an UpdateSourceTrigger of PropertyChanged? That way the property setter of the property you bind to will be called every time the text is changed? If that's not enough, then I would tackle this problem using Attached Behaviours. On Julian Dominguez’s Blog you'll find an article about how to do something very similar in Silverlight, which should be easily adaptable to WPF. Basically, in a static class (called, say TextBoxBehaviours) you define an Attached Property called (perhaps) TextChangedCommand of type ICommand. Hook up an OnPropertyChanged handler for that property, and within the handler, check that the property is being set on a TextBox; if it is, add a handler to the TextChanged event on the textbox that will call the command specified in the property. Then, assuming your viewmodel has been assigned to the DataContext of your View, you would use it like: | [
"wpf",
"mvvm",
"command",
"event-binding"
] | 10 | 18 | 22,722 | 3 | 0 | 2008-09-11T05:36:17.557000 | 2008-09-11T09:51:56.537000 |
55,859 | 55,863 | How can I catch all types of exceptions in one catch block? | In C++, I'm trying to catch all types of exceptions in one catch (like catch(Exception) in C#). How is it done? And what's more, how can one catch divide-by-zero exceptions? | catch (...) { // Handle exceptions not covered. } Important considerations: A better approach is to catch specific types of exception that you can actually recover from as opposed to all possible exceptions. catch(...) will also catch certain serious system level exceptions (varies depending on compiler) that you are not going to be able to recover reliably from. Catching them in this way and then swallowing them and continuing could cause further serious problems in your program. Depending on your context it can be acceptable to use catch(...), providing the exception is re-thrown. In this case, you log all useful local state information and then re-throw the exception to allow it to propagate up. However you should read up on the RAII pattern if you choose this route. | How can I catch all types of exceptions in one catch block? In C++, I'm trying to catch all types of exceptions in one catch (like catch(Exception) in C#). How is it done? And what's more, how can one catch divide-by-zero exceptions? | TITLE:
How can I catch all types of exceptions in one catch block?
QUESTION:
In C++, I'm trying to catch all types of exceptions in one catch (like catch(Exception) in C#). How is it done? And what's more, how can one catch divide-by-zero exceptions?
ANSWER:
catch (...) { // Handle exceptions not covered. } Important considerations: A better approach is to catch specific types of exception that you can actually recover from as opposed to all possible exceptions. catch(...) will also catch certain serious system level exceptions (varies depending on compiler) that you are not going to be able to recover reliably from. Catching them in this way and then swallowing them and continuing could cause further serious problems in your program. Depending on your context it can be acceptable to use catch(...), providing the exception is re-thrown. In this case, you log all useful local state information and then re-throw the exception to allow it to propagate up. However you should read up on the RAII pattern if you choose this route. | [
"c++",
"exception",
"try-catch"
] | 13 | 28 | 21,249 | 9 | 0 | 2008-09-11T05:41:15.640000 | 2008-09-11T05:43:38.647000 |
55,862 | 55,904 | How to implement password protection for individual files? | I'm writing a little desktop app that should be able to encrypt a data file and protect it with a password (i.e. one must enter the correct password to decrypt). I want the encrypted data file to be self-contained and portable, so the authentication has to be embedded in the file (or so I assume). I have a strategy that appears workable and seems logical based on what I know (which is probably just enough to be dangerous), but I have no idea if it's actually a good design or not. So tell me: is this crazy? Is there a better/best way to do it? Step 1: User enters plain-text password, e.g. "MyDifficultPassword" Step 2: App hashes the user-password and uses that value as the symmetric key to encrypt/decrypt the data file. e.g. "MyDifficultPassword" --> "HashedUserPwdAndKey". Step 3: App hashes the hashed value from step 2 and saves the new value in the data file header (i.e. the unencrypted part of the data file) and uses that value to validate the user's password. e.g. "HashedUserPwdAndKey" --> "HashedValueForAuthentication" Basically I'm extrapolating from the common way to implement web-site passwords (when you're not using OpenID, that is), which is to store the (salted) hash of the user's password in your DB and never save the actual password. But since I use the hashed user password for the symmetric encryption key, I can't use the same value for authentication. So I hash it again, basically treating it just like another password, and save the doubly-hashed value in the data file. That way, I can take the file to another PC and decrypt it by simply entering my password. So is this design reasonably secure, or hopelessly naive, or somewhere in between? Thanks! EDIT: clarification and follow-up question re: Salt. I thought the salt had to be kept secret to be useful, but your answers and links imply this is not the case. For example, this spec linked by erickson (below) says: Thus, password-based key derivation as defined here is a function of a password, a salt, and an iteration count, where the latter two quantities need not be kept secret. Does this mean that I could store the salt value in the same place/file as the hashed key and still be more secure than if I used no salt at all when hashing? How does that work? A little more context: the encrypted file isn't meant to be shared with or decrypted by others, it's really single-user data. But I'd like to deploy it in a shared environment on computers I don't fully control (e.g. at work) and be able to migrate/move the data by simply copying the file (so I can use it at home, on different workstations, etc.). | Key Generation I would recommend using a recognized algorithm such as PBKDF2 defined in PKCS #5 version 2.0 to generate a key from your password. It's similar to the algorithm you outline, but is capable of generating longer symmetric keys for use with AES. You should be able to find an open-source library that implements PBE key generators for different algorithms. File Format You might also consider using the Cryptographic Message Syntax as a format for your file. This will require some study on your part, but again there are existing libraries to use, and it opens up the possibility of inter-operating more smoothly with other software, like S/MIME-enabled mail clients. Password Validation Regarding your desire to store a hash of the password, if you use PBKDF2 to generate the key, you could use a standard password hashing algorithm (big salt, a thousand rounds of hashing) for that, and get different values. Alternatively, you could compute a MAC on the content. A hash collision on a password is more likely to be useful to an attacker; a hash collision on the content is likely to be worthless. But it would serve to let a legitimate recipient know that the wrong password was used for decryption. Cryptographic Salt Salt helps to thwart pre-computed dictionary attacks. Suppose an attacker has a list of likely passwords. He can hash each and compare it to the hash of his victim's password, and see if it matches. If the list is large, this could take a long time. He doesn't want spend that much time on his next target, so he records the result in a "dictionary" where a hash points to its corresponding input. If the list of passwords is very, very long, he can use techniques like a Rainbow Table to save some space. However, suppose his next target salted their password. Even if the attacker knows what the salt is, his precomputed table is worthless —the salt changes the hash resulting from each password. He has to re-hash all of the passwords in his list, affixing the target's salt to the input. Every different salt requires a different dictionary, and if enough salts are used, the attacker won't have room to store dictionaries for them all. Trading space to save time is no longer an option; the attacker must fall back to hashing each password in his list for each target he wants to attack. So, it's not necessary to keep the salt secret. Ensuring that the attacker doesn't have a pre-computed dictionary corresponding to that particular salt is sufficient. | How to implement password protection for individual files? I'm writing a little desktop app that should be able to encrypt a data file and protect it with a password (i.e. one must enter the correct password to decrypt). I want the encrypted data file to be self-contained and portable, so the authentication has to be embedded in the file (or so I assume). I have a strategy that appears workable and seems logical based on what I know (which is probably just enough to be dangerous), but I have no idea if it's actually a good design or not. So tell me: is this crazy? Is there a better/best way to do it? Step 1: User enters plain-text password, e.g. "MyDifficultPassword" Step 2: App hashes the user-password and uses that value as the symmetric key to encrypt/decrypt the data file. e.g. "MyDifficultPassword" --> "HashedUserPwdAndKey". Step 3: App hashes the hashed value from step 2 and saves the new value in the data file header (i.e. the unencrypted part of the data file) and uses that value to validate the user's password. e.g. "HashedUserPwdAndKey" --> "HashedValueForAuthentication" Basically I'm extrapolating from the common way to implement web-site passwords (when you're not using OpenID, that is), which is to store the (salted) hash of the user's password in your DB and never save the actual password. But since I use the hashed user password for the symmetric encryption key, I can't use the same value for authentication. So I hash it again, basically treating it just like another password, and save the doubly-hashed value in the data file. That way, I can take the file to another PC and decrypt it by simply entering my password. So is this design reasonably secure, or hopelessly naive, or somewhere in between? Thanks! EDIT: clarification and follow-up question re: Salt. I thought the salt had to be kept secret to be useful, but your answers and links imply this is not the case. For example, this spec linked by erickson (below) says: Thus, password-based key derivation as defined here is a function of a password, a salt, and an iteration count, where the latter two quantities need not be kept secret. Does this mean that I could store the salt value in the same place/file as the hashed key and still be more secure than if I used no salt at all when hashing? How does that work? A little more context: the encrypted file isn't meant to be shared with or decrypted by others, it's really single-user data. But I'd like to deploy it in a shared environment on computers I don't fully control (e.g. at work) and be able to migrate/move the data by simply copying the file (so I can use it at home, on different workstations, etc.). | TITLE:
How to implement password protection for individual files?
QUESTION:
I'm writing a little desktop app that should be able to encrypt a data file and protect it with a password (i.e. one must enter the correct password to decrypt). I want the encrypted data file to be self-contained and portable, so the authentication has to be embedded in the file (or so I assume). I have a strategy that appears workable and seems logical based on what I know (which is probably just enough to be dangerous), but I have no idea if it's actually a good design or not. So tell me: is this crazy? Is there a better/best way to do it? Step 1: User enters plain-text password, e.g. "MyDifficultPassword" Step 2: App hashes the user-password and uses that value as the symmetric key to encrypt/decrypt the data file. e.g. "MyDifficultPassword" --> "HashedUserPwdAndKey". Step 3: App hashes the hashed value from step 2 and saves the new value in the data file header (i.e. the unencrypted part of the data file) and uses that value to validate the user's password. e.g. "HashedUserPwdAndKey" --> "HashedValueForAuthentication" Basically I'm extrapolating from the common way to implement web-site passwords (when you're not using OpenID, that is), which is to store the (salted) hash of the user's password in your DB and never save the actual password. But since I use the hashed user password for the symmetric encryption key, I can't use the same value for authentication. So I hash it again, basically treating it just like another password, and save the doubly-hashed value in the data file. That way, I can take the file to another PC and decrypt it by simply entering my password. So is this design reasonably secure, or hopelessly naive, or somewhere in between? Thanks! EDIT: clarification and follow-up question re: Salt. I thought the salt had to be kept secret to be useful, but your answers and links imply this is not the case. For example, this spec linked by erickson (below) says: Thus, password-based key derivation as defined here is a function of a password, a salt, and an iteration count, where the latter two quantities need not be kept secret. Does this mean that I could store the salt value in the same place/file as the hashed key and still be more secure than if I used no salt at all when hashing? How does that work? A little more context: the encrypted file isn't meant to be shared with or decrypted by others, it's really single-user data. But I'd like to deploy it in a shared environment on computers I don't fully control (e.g. at work) and be able to migrate/move the data by simply copying the file (so I can use it at home, on different workstations, etc.).
ANSWER:
Key Generation I would recommend using a recognized algorithm such as PBKDF2 defined in PKCS #5 version 2.0 to generate a key from your password. It's similar to the algorithm you outline, but is capable of generating longer symmetric keys for use with AES. You should be able to find an open-source library that implements PBE key generators for different algorithms. File Format You might also consider using the Cryptographic Message Syntax as a format for your file. This will require some study on your part, but again there are existing libraries to use, and it opens up the possibility of inter-operating more smoothly with other software, like S/MIME-enabled mail clients. Password Validation Regarding your desire to store a hash of the password, if you use PBKDF2 to generate the key, you could use a standard password hashing algorithm (big salt, a thousand rounds of hashing) for that, and get different values. Alternatively, you could compute a MAC on the content. A hash collision on a password is more likely to be useful to an attacker; a hash collision on the content is likely to be worthless. But it would serve to let a legitimate recipient know that the wrong password was used for decryption. Cryptographic Salt Salt helps to thwart pre-computed dictionary attacks. Suppose an attacker has a list of likely passwords. He can hash each and compare it to the hash of his victim's password, and see if it matches. If the list is large, this could take a long time. He doesn't want spend that much time on his next target, so he records the result in a "dictionary" where a hash points to its corresponding input. If the list of passwords is very, very long, he can use techniques like a Rainbow Table to save some space. However, suppose his next target salted their password. Even if the attacker knows what the salt is, his precomputed table is worthless —the salt changes the hash resulting from each password. He has to re-hash all of the passwords in his list, affixing the target's salt to the input. Every different salt requires a different dictionary, and if enough salts are used, the attacker won't have room to store dictionaries for them all. Trading space to save time is no longer an option; the attacker must fall back to hashing each password in his list for each target he wants to attack. So, it's not necessary to keep the salt secret. Ensuring that the attacker doesn't have a pre-computed dictionary corresponding to that particular salt is sufficient. | [
"encryption",
"cryptography",
"passwords"
] | 21 | 24 | 9,069 | 5 | 0 | 2008-09-11T05:43:24.683000 | 2008-09-11T06:37:40.467000 |
55,869 | 55,887 | Determine file type of an image | I'm downloading some images from a service that doesn't always include a content-type and doesn't provide an extension for the file I'm downloading (ugh, don't ask). What's the best way to determine the image format in.NET? The application that is reading these downloaded images needs to have a proper file extension or all hell breaks loose. | A probably easier approach would be to use Image.FromFile() and then use the RawFormat property, as it already knows about the magic bits in the headers for the most common formats, like this: Image i = Image.FromFile("c:\\foo"); if (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(i.RawFormat)) MessageBox.Show("JPEG"); else if (System.Drawing.Imaging.ImageFormat.Gif.Equals(i.RawFormat)) MessageBox.Show("GIF"); //Same for the rest of the formats | Determine file type of an image I'm downloading some images from a service that doesn't always include a content-type and doesn't provide an extension for the file I'm downloading (ugh, don't ask). What's the best way to determine the image format in.NET? The application that is reading these downloaded images needs to have a proper file extension or all hell breaks loose. | TITLE:
Determine file type of an image
QUESTION:
I'm downloading some images from a service that doesn't always include a content-type and doesn't provide an extension for the file I'm downloading (ugh, don't ask). What's the best way to determine the image format in.NET? The application that is reading these downloaded images needs to have a proper file extension or all hell breaks loose.
ANSWER:
A probably easier approach would be to use Image.FromFile() and then use the RawFormat property, as it already knows about the magic bits in the headers for the most common formats, like this: Image i = Image.FromFile("c:\\foo"); if (System.Drawing.Imaging.ImageFormat.Jpeg.Equals(i.RawFormat)) MessageBox.Show("JPEG"); else if (System.Drawing.Imaging.ImageFormat.Gif.Equals(i.RawFormat)) MessageBox.Show("GIF"); //Same for the rest of the formats | [
".net",
"image",
"content-type",
"mime-types"
] | 52 | 55 | 34,704 | 6 | 0 | 2008-09-11T05:50:52.700000 | 2008-09-11T06:11:18.593000 |
55,871 | 55,880 | Track when user hits back button on the browser | Is it possible to detect when the user clicks on the browser's back button? I have an Ajax application and if I can detect when the user clicks on the back button I can display the appropriate data back Any solution using PHP, JavaScript is preferable. Hell a solution in any language is fine, just need something that I can translate to PHP/JavaScript Edit: Cut and paste from below: Wow, all excellent answers. I'd like to use Yahoo but I already use Prototype and Scriptaculous libraries and don't want to add more ajax libraries. But it uses iFrames which gives me a good pointer to write my own code. | There are multiple ways of doing it, though some will only work in certain browsers. One that I know off the top of my head is to embed a tiny near-invisible iframe on the page. When the user hits the back button the iframe is navigated back which you can detect and then update your page. Here is another solution. You might also want to go view source on something like gmail and see how they do it. Here's a library for the sort of thing you're looking for by the way | Track when user hits back button on the browser Is it possible to detect when the user clicks on the browser's back button? I have an Ajax application and if I can detect when the user clicks on the back button I can display the appropriate data back Any solution using PHP, JavaScript is preferable. Hell a solution in any language is fine, just need something that I can translate to PHP/JavaScript Edit: Cut and paste from below: Wow, all excellent answers. I'd like to use Yahoo but I already use Prototype and Scriptaculous libraries and don't want to add more ajax libraries. But it uses iFrames which gives me a good pointer to write my own code. | TITLE:
Track when user hits back button on the browser
QUESTION:
Is it possible to detect when the user clicks on the browser's back button? I have an Ajax application and if I can detect when the user clicks on the back button I can display the appropriate data back Any solution using PHP, JavaScript is preferable. Hell a solution in any language is fine, just need something that I can translate to PHP/JavaScript Edit: Cut and paste from below: Wow, all excellent answers. I'd like to use Yahoo but I already use Prototype and Scriptaculous libraries and don't want to add more ajax libraries. But it uses iFrames which gives me a good pointer to write my own code.
ANSWER:
There are multiple ways of doing it, though some will only work in certain browsers. One that I know off the top of my head is to embed a tiny near-invisible iframe on the page. When the user hits the back button the iframe is navigated back which you can detect and then update your page. Here is another solution. You might also want to go view source on something like gmail and see how they do it. Here's a library for the sort of thing you're looking for by the way | [
"php",
"javascript",
"browser"
] | 26 | 15 | 28,209 | 7 | 0 | 2008-09-11T05:52:56.610000 | 2008-09-11T06:01:42.720000 |
55,878 | 55,902 | How do distributed transactions work (eg. MSDTC)? | I understand, in a fuzzy sort of way, how regular ACID transactions work. You perform some work on a database in such a way that the work is not confirmed until some kind of commit flag is set. The commit part is based on some underlying assumption (like a single disk block write is atomic). In the event of a catastrophic error, you can just clear out the uncommitted data in the recovery phase. How do distributed transactions work? In some of the MS documentation I have read that you can somehow perform a transaction across databases and filesystems (among other things). This technology could be (and probably is) used for installers, where you want the program to be fully installed or fully absent. You simply begin a transaction at the start of the installer. Next you could connect to the registry and filesystem, making the changes that define the installation. When the job is done, simply commit, or rollback if the installation fails for some reason. The registry and filesystem are automatically cleaned for you by this magical distributed transaction coordinator. How is it possible that two disparate systems can be transacted upon in this fashion? It seems to me that it is always possible to leave the system in an inconsistent state, where the filesystem has committed its changes and the registry has not. I think in MSDTC it is even possible to perform a transaction across the network. I have read http://blogs.msdn.com/florinlazar/archive/2004/03/04/84199.aspx, but it feels like only the beginning of the explanation, and that step 4 should be expanded considerably. Edit: From what I gather on http://en.wikipedia.org/wiki/Distributed_transaction, it can be accomplished by a two-phase commit ( http://en.wikipedia.org/wiki/Two-phase_commit ). After reading this, I'm still not understanding the method 100%, it seems like there is a lot of room for error between the steps. | About "step 4": The transaction manager coordinates with the resource managers to ensure that all succeed to do the requested work or none of the work if done, thus maintaining the ACID properties. This of course requires all participants to provide the proper interfaces and (error-free) implementations. The interface looks like vaguely this: public interface ITransactionParticipant { bool WouldCommitWork(); void Commit(); void Rollback(); } The Transaction manager at commit-time queries all participants whether they are willing to commit the transaction. The participants may only assert this if they are able to commit this transaction under all allowable error conditions (validation, system errors, etc). After all participants have asserted the ability to commit the transaction, the manager sends the Commit() message to all participants. If any participant instead raises an error or times out, the whole transaction aborts and individual members are rolled back. This protocol requires participants to have recorded their whole transaction content before asserting their ability to commit. Of course this has to be in a special local transaction log structure to be able to recover from various kinds of failures. | How do distributed transactions work (eg. MSDTC)? I understand, in a fuzzy sort of way, how regular ACID transactions work. You perform some work on a database in such a way that the work is not confirmed until some kind of commit flag is set. The commit part is based on some underlying assumption (like a single disk block write is atomic). In the event of a catastrophic error, you can just clear out the uncommitted data in the recovery phase. How do distributed transactions work? In some of the MS documentation I have read that you can somehow perform a transaction across databases and filesystems (among other things). This technology could be (and probably is) used for installers, where you want the program to be fully installed or fully absent. You simply begin a transaction at the start of the installer. Next you could connect to the registry and filesystem, making the changes that define the installation. When the job is done, simply commit, or rollback if the installation fails for some reason. The registry and filesystem are automatically cleaned for you by this magical distributed transaction coordinator. How is it possible that two disparate systems can be transacted upon in this fashion? It seems to me that it is always possible to leave the system in an inconsistent state, where the filesystem has committed its changes and the registry has not. I think in MSDTC it is even possible to perform a transaction across the network. I have read http://blogs.msdn.com/florinlazar/archive/2004/03/04/84199.aspx, but it feels like only the beginning of the explanation, and that step 4 should be expanded considerably. Edit: From what I gather on http://en.wikipedia.org/wiki/Distributed_transaction, it can be accomplished by a two-phase commit ( http://en.wikipedia.org/wiki/Two-phase_commit ). After reading this, I'm still not understanding the method 100%, it seems like there is a lot of room for error between the steps. | TITLE:
How do distributed transactions work (eg. MSDTC)?
QUESTION:
I understand, in a fuzzy sort of way, how regular ACID transactions work. You perform some work on a database in such a way that the work is not confirmed until some kind of commit flag is set. The commit part is based on some underlying assumption (like a single disk block write is atomic). In the event of a catastrophic error, you can just clear out the uncommitted data in the recovery phase. How do distributed transactions work? In some of the MS documentation I have read that you can somehow perform a transaction across databases and filesystems (among other things). This technology could be (and probably is) used for installers, where you want the program to be fully installed or fully absent. You simply begin a transaction at the start of the installer. Next you could connect to the registry and filesystem, making the changes that define the installation. When the job is done, simply commit, or rollback if the installation fails for some reason. The registry and filesystem are automatically cleaned for you by this magical distributed transaction coordinator. How is it possible that two disparate systems can be transacted upon in this fashion? It seems to me that it is always possible to leave the system in an inconsistent state, where the filesystem has committed its changes and the registry has not. I think in MSDTC it is even possible to perform a transaction across the network. I have read http://blogs.msdn.com/florinlazar/archive/2004/03/04/84199.aspx, but it feels like only the beginning of the explanation, and that step 4 should be expanded considerably. Edit: From what I gather on http://en.wikipedia.org/wiki/Distributed_transaction, it can be accomplished by a two-phase commit ( http://en.wikipedia.org/wiki/Two-phase_commit ). After reading this, I'm still not understanding the method 100%, it seems like there is a lot of room for error between the steps.
ANSWER:
About "step 4": The transaction manager coordinates with the resource managers to ensure that all succeed to do the requested work or none of the work if done, thus maintaining the ACID properties. This of course requires all participants to provide the proper interfaces and (error-free) implementations. The interface looks like vaguely this: public interface ITransactionParticipant { bool WouldCommitWork(); void Commit(); void Rollback(); } The Transaction manager at commit-time queries all participants whether they are willing to commit the transaction. The participants may only assert this if they are able to commit this transaction under all allowable error conditions (validation, system errors, etc). After all participants have asserted the ability to commit the transaction, the manager sends the Commit() message to all participants. If any participant instead raises an error or times out, the whole transaction aborts and individual members are rolled back. This protocol requires participants to have recorded their whole transaction content before asserting their ability to commit. Of course this has to be in a special local transaction log structure to be able to recover from various kinds of failures. | [
"transactions",
"acid",
"mstdc"
] | 14 | 4 | 4,528 | 1 | 0 | 2008-09-11T06:01:04.453000 | 2008-09-11T06:31:04.537000 |
55,899 | 55,914 | How to see the actual Oracle SQL statement that is being executed | I'm using a custom-built inhouse application that generates a standard set of reports on a weekly basis. I have no access to the source code of the application, and everyone tells me there is no documentation available for the Oracle database schema. (Aargh!) I've been asked to define the specs for a variant of an existing report (e.g., apply additional filters to constrain the data set, and modify the layout slightly). This sounds simple enough in principle, but is difficult without any existing documentation. It's my understanding that the logs can't help me because the report only queries the database; it does not actually insert, delete, or update database values, so there is nothing to log (is this correct?). So my question is this: is there a tool or utility (Oracle or otherwise) that I can use to see the actual SQL statement that is being executed while the report generation job is still running? I figure, if I can see what tables are actually being accessed to produce the existing report, I'll have a very good starting point for exploring the schema and determining the correct SQL to use for my own report. | On the data dictionary side there are a lot of tools you can use to such as Schema Spy To look at what queries are running look at views sys.v_$sql and sys.v_$sqltext. You will also need access to sys.all_users One thing to note that queries that use parameters will show up once with entries like and TABLETYPE=’:b16’ while others that dont will show up multiple times such as: and TABLETYPE=’MT’ An example of these tables in action is the following SQL to find the top 20 diskread hogs. You could change this by removing the WHERE rownum <= 20 and maybe add ORDER BY module. You often find the module will give you a bog clue as to what software is running the query (eg: "TOAD 9.0.1.8", "JDBC Thin Client", "runcbl@somebox (TNS V1-V3)" etc) SELECT module, sql_text, username, disk_reads_per_exec, buffer_gets, disk_reads, parse_calls, sorts, executions, rows_processed, hit_ratio, first_load_time, sharable_mem, persistent_mem, runtime_mem, cpu_time, elapsed_time, address, hash_value FROM (SELECT module, sql_text, u.username, round((s.disk_reads/decode(s.executions,0,1, s.executions)),2) disk_reads_per_exec, s.disk_reads, s.buffer_gets, s.parse_calls, s.sorts, s.executions, s.rows_processed, 100 - round(100 * s.disk_reads/greatest(s.buffer_gets,1),2) hit_ratio, s.first_load_time, sharable_mem, persistent_mem, runtime_mem, cpu_time, elapsed_time, address, hash_value FROM sys.v_$sql s, sys.all_users u WHERE s.parsing_user_id=u.user_id and UPPER(u.username) not in ('SYS','SYSTEM') ORDER BY 4 desc) WHERE rownum <= 20; Note that if the query is long.. you will have to query v_$sqltext. This stores the whole query. You will have to look up the ADDRESS and HASH_VALUE and pick up all the pieces. Eg: SELECT * FROM sys.v_$sqltext WHERE address = 'C0000000372B3C28' and hash_value = '1272580459' ORDER BY address, hash_value, command_type, piece; | How to see the actual Oracle SQL statement that is being executed I'm using a custom-built inhouse application that generates a standard set of reports on a weekly basis. I have no access to the source code of the application, and everyone tells me there is no documentation available for the Oracle database schema. (Aargh!) I've been asked to define the specs for a variant of an existing report (e.g., apply additional filters to constrain the data set, and modify the layout slightly). This sounds simple enough in principle, but is difficult without any existing documentation. It's my understanding that the logs can't help me because the report only queries the database; it does not actually insert, delete, or update database values, so there is nothing to log (is this correct?). So my question is this: is there a tool or utility (Oracle or otherwise) that I can use to see the actual SQL statement that is being executed while the report generation job is still running? I figure, if I can see what tables are actually being accessed to produce the existing report, I'll have a very good starting point for exploring the schema and determining the correct SQL to use for my own report. | TITLE:
How to see the actual Oracle SQL statement that is being executed
QUESTION:
I'm using a custom-built inhouse application that generates a standard set of reports on a weekly basis. I have no access to the source code of the application, and everyone tells me there is no documentation available for the Oracle database schema. (Aargh!) I've been asked to define the specs for a variant of an existing report (e.g., apply additional filters to constrain the data set, and modify the layout slightly). This sounds simple enough in principle, but is difficult without any existing documentation. It's my understanding that the logs can't help me because the report only queries the database; it does not actually insert, delete, or update database values, so there is nothing to log (is this correct?). So my question is this: is there a tool or utility (Oracle or otherwise) that I can use to see the actual SQL statement that is being executed while the report generation job is still running? I figure, if I can see what tables are actually being accessed to produce the existing report, I'll have a very good starting point for exploring the schema and determining the correct SQL to use for my own report.
ANSWER:
On the data dictionary side there are a lot of tools you can use to such as Schema Spy To look at what queries are running look at views sys.v_$sql and sys.v_$sqltext. You will also need access to sys.all_users One thing to note that queries that use parameters will show up once with entries like and TABLETYPE=’:b16’ while others that dont will show up multiple times such as: and TABLETYPE=’MT’ An example of these tables in action is the following SQL to find the top 20 diskread hogs. You could change this by removing the WHERE rownum <= 20 and maybe add ORDER BY module. You often find the module will give you a bog clue as to what software is running the query (eg: "TOAD 9.0.1.8", "JDBC Thin Client", "runcbl@somebox (TNS V1-V3)" etc) SELECT module, sql_text, username, disk_reads_per_exec, buffer_gets, disk_reads, parse_calls, sorts, executions, rows_processed, hit_ratio, first_load_time, sharable_mem, persistent_mem, runtime_mem, cpu_time, elapsed_time, address, hash_value FROM (SELECT module, sql_text, u.username, round((s.disk_reads/decode(s.executions,0,1, s.executions)),2) disk_reads_per_exec, s.disk_reads, s.buffer_gets, s.parse_calls, s.sorts, s.executions, s.rows_processed, 100 - round(100 * s.disk_reads/greatest(s.buffer_gets,1),2) hit_ratio, s.first_load_time, sharable_mem, persistent_mem, runtime_mem, cpu_time, elapsed_time, address, hash_value FROM sys.v_$sql s, sys.all_users u WHERE s.parsing_user_id=u.user_id and UPPER(u.username) not in ('SYS','SYSTEM') ORDER BY 4 desc) WHERE rownum <= 20; Note that if the query is long.. you will have to query v_$sqltext. This stores the whole query. You will have to look up the ADDRESS and HASH_VALUE and pick up all the pieces. Eg: SELECT * FROM sys.v_$sqltext WHERE address = 'C0000000372B3C28' and hash_value = '1272580459' ORDER BY address, hash_value, command_type, piece; | [
"sql",
"oracle"
] | 28 | 24 | 113,025 | 6 | 0 | 2008-09-11T06:26:01.040000 | 2008-09-11T06:45:01.540000 |
55,901 | 55,910 | Web service - current time zone for a city? | Is there a web service of some sort (or any other way) to pull a current time zone settings for a (US) city. For the parts of the country that don't follow the Daylight Saving Time and basically jump timezones when everyone else is switching summer/winter time... I don't fancy creating own database of the places that don't follow DST. Is there a way to pull this data on demand? I need this for the database server (not for client workstations) - there entities stored in the database that have City, State as properties. I need know current timezone for these entities at any moment of time. | earthtools.org provides a free web service to get the time zone from a city here: http://www.earthtools.org/webservices.htm#timezone You just pass in the long/lat values like this: (This is for New York) http://www.earthtools.org/timezone-1.1/40.71417/-74.00639 EDIT: It seems like earthtools has been shut down. A good alternative (That did not exist in 2008 when this question was answered) is the Google Time Zone API. To use it you must first activate the Time Zone API on your account. It is free if you stay below these limits: 2500 requests per 24 hour period. 5 requests per second. The documentation is available on Google Developers. | Web service - current time zone for a city? Is there a web service of some sort (or any other way) to pull a current time zone settings for a (US) city. For the parts of the country that don't follow the Daylight Saving Time and basically jump timezones when everyone else is switching summer/winter time... I don't fancy creating own database of the places that don't follow DST. Is there a way to pull this data on demand? I need this for the database server (not for client workstations) - there entities stored in the database that have City, State as properties. I need know current timezone for these entities at any moment of time. | TITLE:
Web service - current time zone for a city?
QUESTION:
Is there a web service of some sort (or any other way) to pull a current time zone settings for a (US) city. For the parts of the country that don't follow the Daylight Saving Time and basically jump timezones when everyone else is switching summer/winter time... I don't fancy creating own database of the places that don't follow DST. Is there a way to pull this data on demand? I need this for the database server (not for client workstations) - there entities stored in the database that have City, State as properties. I need know current timezone for these entities at any moment of time.
ANSWER:
earthtools.org provides a free web service to get the time zone from a city here: http://www.earthtools.org/webservices.htm#timezone You just pass in the long/lat values like this: (This is for New York) http://www.earthtools.org/timezone-1.1/40.71417/-74.00639 EDIT: It seems like earthtools has been shut down. A good alternative (That did not exist in 2008 when this question was answered) is the Google Time Zone API. To use it you must first activate the Time Zone API on your account. It is free if you stay below these limits: 2500 requests per 24 hour period. 5 requests per second. The documentation is available on Google Developers. | [
"web-services",
"timezone"
] | 54 | 47 | 98,775 | 8 | 0 | 2008-09-11T06:30:04.667000 | 2008-09-11T06:43:53.320000 |
55,903 | 55,909 | Eclipse alternative to VS .sln files | I've recently had to switch from Visual Studio to Eclipse CDT. It would seem that Eclipse "workspaces" are not quite like VS solution files. Eclipse workspaces use the.metadata folder for managing multiple projects, but there doesn't seem to be a simple distinction between user settings or IDE preferences and project/solution settings. What I want is a way to group a collection of related (and dependent) projects together and have that data live in source control without all the other user specific stuff that developers don't need to share. You know, like a.sln file in Visual Studio. Does Eclipse just not work this way? (And if not, then why not?) | Yes you are right eclipse does not manage projects in the same way VS does with solution files. However for putting a group of related projects into a VCS eclipse has the concept of a Team Project Set available in File->Export then under the Team folder there is Team Project Set. | Eclipse alternative to VS .sln files I've recently had to switch from Visual Studio to Eclipse CDT. It would seem that Eclipse "workspaces" are not quite like VS solution files. Eclipse workspaces use the.metadata folder for managing multiple projects, but there doesn't seem to be a simple distinction between user settings or IDE preferences and project/solution settings. What I want is a way to group a collection of related (and dependent) projects together and have that data live in source control without all the other user specific stuff that developers don't need to share. You know, like a.sln file in Visual Studio. Does Eclipse just not work this way? (And if not, then why not?) | TITLE:
Eclipse alternative to VS .sln files
QUESTION:
I've recently had to switch from Visual Studio to Eclipse CDT. It would seem that Eclipse "workspaces" are not quite like VS solution files. Eclipse workspaces use the.metadata folder for managing multiple projects, but there doesn't seem to be a simple distinction between user settings or IDE preferences and project/solution settings. What I want is a way to group a collection of related (and dependent) projects together and have that data live in source control without all the other user specific stuff that developers don't need to share. You know, like a.sln file in Visual Studio. Does Eclipse just not work this way? (And if not, then why not?)
ANSWER:
Yes you are right eclipse does not manage projects in the same way VS does with solution files. However for putting a group of related projects into a VCS eclipse has the concept of a Team Project Set available in File->Export then under the Team folder there is Team Project Set. | [
"eclipse"
] | 13 | 4 | 6,560 | 3 | 0 | 2008-09-11T06:33:27.620000 | 2008-09-11T06:41:49.503000 |
55,932 | 212,372 | Win32 CreatePatternBrush | MSDN displays the following for CreatePatternBrush: You can delete a pattern brush without affecting the associated bitmap by using the DeleteObject function. Therefore, you can then use this bitmap to create any number of pattern brushes. My question is the opposite. If the HBRUSH is long lived, can I delete the HBITMAP right after I create the brush? IE: does the HBRUSH store its own copy of the HBITMAP? In this case, I'd like the HBRUSH to have object scope while the HBITMAP would have method scope (the method that creates the HBRUSH). | The HBRUSH and HBITMAP are entirely independent. The handles can be deleted entirely independent from each other, and, once created, no changes to either object will effect the other. | Win32 CreatePatternBrush MSDN displays the following for CreatePatternBrush: You can delete a pattern brush without affecting the associated bitmap by using the DeleteObject function. Therefore, you can then use this bitmap to create any number of pattern brushes. My question is the opposite. If the HBRUSH is long lived, can I delete the HBITMAP right after I create the brush? IE: does the HBRUSH store its own copy of the HBITMAP? In this case, I'd like the HBRUSH to have object scope while the HBITMAP would have method scope (the method that creates the HBRUSH). | TITLE:
Win32 CreatePatternBrush
QUESTION:
MSDN displays the following for CreatePatternBrush: You can delete a pattern brush without affecting the associated bitmap by using the DeleteObject function. Therefore, you can then use this bitmap to create any number of pattern brushes. My question is the opposite. If the HBRUSH is long lived, can I delete the HBITMAP right after I create the brush? IE: does the HBRUSH store its own copy of the HBITMAP? In this case, I'd like the HBRUSH to have object scope while the HBITMAP would have method scope (the method that creates the HBRUSH).
ANSWER:
The HBRUSH and HBITMAP are entirely independent. The handles can be deleted entirely independent from each other, and, once created, no changes to either object will effect the other. | [
"winapi",
"gdi"
] | 5 | 5 | 2,164 | 4 | 0 | 2008-09-11T07:13:24.280000 | 2008-10-17T14:27:04.970000 |
55,943 | 55,954 | How to profile a silverlight application? | Is their any profilers that support Silverlight? I have tried ANTS (Version 3.1) without any success? Does version 4 support it? Any other products I can try? Updated since the release of Silverlight 4, it is now possible to do full profiling on SL applications... check out this article on the topic At PDC, I announced that Silverlight 4 came with the new CoreCLR capability of being profile-able by the VS2010 profilers: this means that for the first time, we give you the power to profile the managed and native code (user or platform) used by a Silverlight application. woohoo. kudos to the CLR team. Sidenote: From silverlight 1-3, one could only use things like xperf (see XPerf: A CPU Sampler for Silverlight) which is very powerful to see the layout/text/media/gfx/etc pipelines, but only gives the native callstack.) From SilverLite ( PDC video, TechEd Iceland, VS2010, profiling, Silverlight 4 ) | Install XPerf and xperfview as available here: http://msdn.microsoft.com/en-us/library/cc305218.aspx (1) Startup your sample (2) xperf -on base (3) wait for a bit (4) xperf –d myprofile.etl (5) when this is done, set your symbol path: set _NT_SYMBOL_PATH= srv C:\symbols http://msdl.microsoft.com/downloads/symbols (6) xperfview myprofile.etl (7) Trace -> Load Symbols Select the area of the CPU graph that you want to see Right-click and select Summary Table (8) Accept the EULA for using symbols, expand IExplore, expand agcore.dll or whatever is your top module | How to profile a silverlight application? Is their any profilers that support Silverlight? I have tried ANTS (Version 3.1) without any success? Does version 4 support it? Any other products I can try? Updated since the release of Silverlight 4, it is now possible to do full profiling on SL applications... check out this article on the topic At PDC, I announced that Silverlight 4 came with the new CoreCLR capability of being profile-able by the VS2010 profilers: this means that for the first time, we give you the power to profile the managed and native code (user or platform) used by a Silverlight application. woohoo. kudos to the CLR team. Sidenote: From silverlight 1-3, one could only use things like xperf (see XPerf: A CPU Sampler for Silverlight) which is very powerful to see the layout/text/media/gfx/etc pipelines, but only gives the native callstack.) From SilverLite ( PDC video, TechEd Iceland, VS2010, profiling, Silverlight 4 ) | TITLE:
How to profile a silverlight application?
QUESTION:
Is their any profilers that support Silverlight? I have tried ANTS (Version 3.1) without any success? Does version 4 support it? Any other products I can try? Updated since the release of Silverlight 4, it is now possible to do full profiling on SL applications... check out this article on the topic At PDC, I announced that Silverlight 4 came with the new CoreCLR capability of being profile-able by the VS2010 profilers: this means that for the first time, we give you the power to profile the managed and native code (user or platform) used by a Silverlight application. woohoo. kudos to the CLR team. Sidenote: From silverlight 1-3, one could only use things like xperf (see XPerf: A CPU Sampler for Silverlight) which is very powerful to see the layout/text/media/gfx/etc pipelines, but only gives the native callstack.) From SilverLite ( PDC video, TechEd Iceland, VS2010, profiling, Silverlight 4 )
ANSWER:
Install XPerf and xperfview as available here: http://msdn.microsoft.com/en-us/library/cc305218.aspx (1) Startup your sample (2) xperf -on base (3) wait for a bit (4) xperf –d myprofile.etl (5) when this is done, set your symbol path: set _NT_SYMBOL_PATH= srv C:\symbols http://msdl.microsoft.com/downloads/symbols (6) xperfview myprofile.etl (7) Trace -> Load Symbols Select the area of the CPU graph that you want to see Right-click and select Summary Table (8) Accept the EULA for using symbols, expand IExplore, expand agcore.dll or whatever is your top module | [
"silverlight",
"profiling"
] | 17 | 20 | 13,369 | 7 | 0 | 2008-09-11T07:29:00.903000 | 2008-09-11T07:35:43.370000 |
55,953 | 56,098 | Can't make an SSL Connection | I'm using a device that's got GPRS media to connect to a PC running stunnel. On TCPIP connections, the number of sessions is limitless. However, when it comes to SSL connections, it could only go as far as 1062 successful sessions. I've tried it like 3 times but makes no difference. I've checked the OpenSSL codes and I couldn't seem to find any code block that limits SSL connection to 1062. On SSL's point of view, is there anything that limits the number of connections? Yes, I'm using a postpaid phone SIM, but there isn't any problem with TCPIP. It only happens with SSL connections. We've tried connecting to other PC's as well using same OpenSSL stunnel, but only ends up to 1062 connections. | Are you connecting via a phone provider - could that be the issue? | Can't make an SSL Connection I'm using a device that's got GPRS media to connect to a PC running stunnel. On TCPIP connections, the number of sessions is limitless. However, when it comes to SSL connections, it could only go as far as 1062 successful sessions. I've tried it like 3 times but makes no difference. I've checked the OpenSSL codes and I couldn't seem to find any code block that limits SSL connection to 1062. On SSL's point of view, is there anything that limits the number of connections? Yes, I'm using a postpaid phone SIM, but there isn't any problem with TCPIP. It only happens with SSL connections. We've tried connecting to other PC's as well using same OpenSSL stunnel, but only ends up to 1062 connections. | TITLE:
Can't make an SSL Connection
QUESTION:
I'm using a device that's got GPRS media to connect to a PC running stunnel. On TCPIP connections, the number of sessions is limitless. However, when it comes to SSL connections, it could only go as far as 1062 successful sessions. I've tried it like 3 times but makes no difference. I've checked the OpenSSL codes and I couldn't seem to find any code block that limits SSL connection to 1062. On SSL's point of view, is there anything that limits the number of connections? Yes, I'm using a postpaid phone SIM, but there isn't any problem with TCPIP. It only happens with SSL connections. We've tried connecting to other PC's as well using same OpenSSL stunnel, but only ends up to 1062 connections.
ANSWER:
Are you connecting via a phone provider - could that be the issue? | [
"ssl",
"connection",
"limits"
] | 0 | 0 | 538 | 2 | 0 | 2008-09-11T07:34:33.857000 | 2008-09-11T09:06:33.137000 |
55,956 | 56,133 | mysql_insert_id alternative for postgresql | is there an alternative for mysql_insert_id() php function for PostgreSQL? Most of the frameworks are solving the problem partially by finding the current value of the sequence used in the ID. However, there are times that the primary key is not a serial column.... | From the PostgreSQL point of view, in pseudo-code: * $insert_id = INSERT...RETURNING foo_id;-- only works for PostgreSQL >= 8.2.
* INSERT...; $insert_id = SELECT lastval(); -- works for PostgreSQL >= 8.1
* $insert_id = SELECT nextval('foo_seq'); INSERT INTO table (foo...) values ($insert_id...) for older PostgreSQL (and newer PostgreSQL) pg_last_oid() only works where you have OIDs. OIDs have been off by default since PostgreSQL 8.1. So, depending on which PostgreSQL version you have, you should pick one of the above method. Ideally, of course, use a database abstraction library which abstracts away the above. Otherwise, in low level code, it looks like: Method one: INSERT... RETURNING // yes, we're not using pg_insert() $result = pg_query($db, "INSERT INTO foo (bar) VALUES (123) RETURNING foo_id"); $insert_row = pg_fetch_row($result); $insert_id = $insert_row[0]; Method two: INSERT; lastval() $result = pg_execute($db, "INSERT INTO foo (bar) values (123);"); $insert_query = pg_query("SELECT lastval();"); $insert_row = pg_fetch_row($insert_query); $insert_id = $insert_row[0]; Method three: nextval(); INSERT $insert_query = pg_query($db, "SELECT nextval('foo_seq');"); $insert_row = pg_fetch_row($insert_query); $insert_id = $insert_row[0]; $result = pg_execute($db, "INSERT INTO foo (foo_id, bar) VALUES ($insert_id, 123);"); The safest bet would be the third method, but it's unwieldy. The cleanest is the first, but you'd need to run a recent PostgreSQL. Most db abstraction libraries don't yet use the first method though. | mysql_insert_id alternative for postgresql is there an alternative for mysql_insert_id() php function for PostgreSQL? Most of the frameworks are solving the problem partially by finding the current value of the sequence used in the ID. However, there are times that the primary key is not a serial column.... | TITLE:
mysql_insert_id alternative for postgresql
QUESTION:
is there an alternative for mysql_insert_id() php function for PostgreSQL? Most of the frameworks are solving the problem partially by finding the current value of the sequence used in the ID. However, there are times that the primary key is not a serial column....
ANSWER:
From the PostgreSQL point of view, in pseudo-code: * $insert_id = INSERT...RETURNING foo_id;-- only works for PostgreSQL >= 8.2.
* INSERT...; $insert_id = SELECT lastval(); -- works for PostgreSQL >= 8.1
* $insert_id = SELECT nextval('foo_seq'); INSERT INTO table (foo...) values ($insert_id...) for older PostgreSQL (and newer PostgreSQL) pg_last_oid() only works where you have OIDs. OIDs have been off by default since PostgreSQL 8.1. So, depending on which PostgreSQL version you have, you should pick one of the above method. Ideally, of course, use a database abstraction library which abstracts away the above. Otherwise, in low level code, it looks like: Method one: INSERT... RETURNING // yes, we're not using pg_insert() $result = pg_query($db, "INSERT INTO foo (bar) VALUES (123) RETURNING foo_id"); $insert_row = pg_fetch_row($result); $insert_id = $insert_row[0]; Method two: INSERT; lastval() $result = pg_execute($db, "INSERT INTO foo (bar) values (123);"); $insert_query = pg_query("SELECT lastval();"); $insert_row = pg_fetch_row($insert_query); $insert_id = $insert_row[0]; Method three: nextval(); INSERT $insert_query = pg_query($db, "SELECT nextval('foo_seq');"); $insert_row = pg_fetch_row($insert_query); $insert_id = $insert_row[0]; $result = pg_execute($db, "INSERT INTO foo (foo_id, bar) VALUES ($insert_id, 123);"); The safest bet would be the third method, but it's unwieldy. The cleanest is the first, but you'd need to run a recent PostgreSQL. Most db abstraction libraries don't yet use the first method though. | [
"php",
"postgresql",
"insert-id"
] | 24 | 44 | 19,439 | 4 | 0 | 2008-09-11T07:37:00.107000 | 2008-09-11T09:32:42.247000 |
55,961 | 55,969 | Exception Handling in .net web apps | I admit it: I don't bother with too much exception handling. I know I should do more but I can never wrap my head around where to start and where to stop. I'm not being lazy. Far from it. It's that I'm overwrought with exception handling ambivalence. It just seems that there is a seemingly infinite number of places in even the smallest app where exception handling can be applied and it can begin to feel like overkill. I've gotten by with careful testing, validating, and silent prayer but this is a bad programming accident waiting to happen. So, what are your exception handling best practices? In particular, where are the most obvious/critical places where exception handling should be applied and where are places where it should be considered? Sorry for the vague the question but I really want to close the book on this once and for all. | Microsoft's Patterns & Practices team did a good job incorporating best practices of exception management into Enterprise Library Exception Handling Application Block Event if wouldn't use Enterprise Library, I highly recommend you to read their documentation. P&P team describes common scenarios and best practices for exceptions handling. To get you started I recommend read following articles: Exception Handling on MSDN Exception Management in.NET on MSDN Exception Handling Best Practices in.NET on CodeProject ASP.NET specific articles: User Friendly ASP.NET Exception Handling Global Exception Handling with ASP.NET Exception handling in C# and ASP.Net | Exception Handling in .net web apps I admit it: I don't bother with too much exception handling. I know I should do more but I can never wrap my head around where to start and where to stop. I'm not being lazy. Far from it. It's that I'm overwrought with exception handling ambivalence. It just seems that there is a seemingly infinite number of places in even the smallest app where exception handling can be applied and it can begin to feel like overkill. I've gotten by with careful testing, validating, and silent prayer but this is a bad programming accident waiting to happen. So, what are your exception handling best practices? In particular, where are the most obvious/critical places where exception handling should be applied and where are places where it should be considered? Sorry for the vague the question but I really want to close the book on this once and for all. | TITLE:
Exception Handling in .net web apps
QUESTION:
I admit it: I don't bother with too much exception handling. I know I should do more but I can never wrap my head around where to start and where to stop. I'm not being lazy. Far from it. It's that I'm overwrought with exception handling ambivalence. It just seems that there is a seemingly infinite number of places in even the smallest app where exception handling can be applied and it can begin to feel like overkill. I've gotten by with careful testing, validating, and silent prayer but this is a bad programming accident waiting to happen. So, what are your exception handling best practices? In particular, where are the most obvious/critical places where exception handling should be applied and where are places where it should be considered? Sorry for the vague the question but I really want to close the book on this once and for all.
ANSWER:
Microsoft's Patterns & Practices team did a good job incorporating best practices of exception management into Enterprise Library Exception Handling Application Block Event if wouldn't use Enterprise Library, I highly recommend you to read their documentation. P&P team describes common scenarios and best practices for exceptions handling. To get you started I recommend read following articles: Exception Handling on MSDN Exception Management in.NET on MSDN Exception Handling Best Practices in.NET on CodeProject ASP.NET specific articles: User Friendly ASP.NET Exception Handling Global Exception Handling with ASP.NET Exception handling in C# and ASP.Net | [
"asp.net",
"exception"
] | 9 | 11 | 1,508 | 6 | 0 | 2008-09-11T07:45:56.340000 | 2008-09-11T07:49:00.840000 |
55,963 | 60,855 | Unsafe C# and pointers for 2D rendering, good or bad? | I am writing a C# control that wraps DirectX 9 and provides a simplified interface to perform 2D pixel level drawing..NET requires that I wrap this code in an unsafe code block and compile with the allow unsafe code option. I'm locking the entire surface which then returns a pointer to the locked area of memory. I can then write pixel data directly using "simple" pointer arithmetic. I have performance tested this and found a substantial speed improvement over other "safe" methods I know of. Is this the fastest way to manipulate individual pixels in a C#.NET application? Is there a better, safer way? If there was an equally fast approach that does not require pointer manipulation it would be my preference to use that. (I know this is 2008 and we should all be using DirectX 3D, OpenGL, etc., however this control is to be used exclusively for 2D pixel rendering and simply does not require 3D rendering.) | Using unsafe pointers is the fastest way to do direct memory manipulation in C# (definitely faster than using the Marshal wrapper functions). Just out of curiosity, what sort of 2D drawing operations are you trying to perform? I ask because locking a DirectX surface to do pixel level manipulations will defeat most of the hardware acceleration benefits that you would hope to gain from using DirectX. Also, the DirectX device will fail to initialize when used over terminal services (remote desktop), so the control will be unusable in that scenario (this may not matter to you). DirectX will be a big win when drawing large triangles and transforming images (texture mapped onto a quad), but it won't really perform that great with single pixel manipulation. Staying in.NET land, one alternative is to keep around a Bitmap object to act as your surface, using LockBits and directly accessing the pixels through the unsafe pointer in the returned BitmapData object. | Unsafe C# and pointers for 2D rendering, good or bad? I am writing a C# control that wraps DirectX 9 and provides a simplified interface to perform 2D pixel level drawing..NET requires that I wrap this code in an unsafe code block and compile with the allow unsafe code option. I'm locking the entire surface which then returns a pointer to the locked area of memory. I can then write pixel data directly using "simple" pointer arithmetic. I have performance tested this and found a substantial speed improvement over other "safe" methods I know of. Is this the fastest way to manipulate individual pixels in a C#.NET application? Is there a better, safer way? If there was an equally fast approach that does not require pointer manipulation it would be my preference to use that. (I know this is 2008 and we should all be using DirectX 3D, OpenGL, etc., however this control is to be used exclusively for 2D pixel rendering and simply does not require 3D rendering.) | TITLE:
Unsafe C# and pointers for 2D rendering, good or bad?
QUESTION:
I am writing a C# control that wraps DirectX 9 and provides a simplified interface to perform 2D pixel level drawing..NET requires that I wrap this code in an unsafe code block and compile with the allow unsafe code option. I'm locking the entire surface which then returns a pointer to the locked area of memory. I can then write pixel data directly using "simple" pointer arithmetic. I have performance tested this and found a substantial speed improvement over other "safe" methods I know of. Is this the fastest way to manipulate individual pixels in a C#.NET application? Is there a better, safer way? If there was an equally fast approach that does not require pointer manipulation it would be my preference to use that. (I know this is 2008 and we should all be using DirectX 3D, OpenGL, etc., however this control is to be used exclusively for 2D pixel rendering and simply does not require 3D rendering.)
ANSWER:
Using unsafe pointers is the fastest way to do direct memory manipulation in C# (definitely faster than using the Marshal wrapper functions). Just out of curiosity, what sort of 2D drawing operations are you trying to perform? I ask because locking a DirectX surface to do pixel level manipulations will defeat most of the hardware acceleration benefits that you would hope to gain from using DirectX. Also, the DirectX device will fail to initialize when used over terminal services (remote desktop), so the control will be unusable in that scenario (this may not matter to you). DirectX will be a big win when drawing large triangles and transforming images (texture mapped onto a quad), but it won't really perform that great with single pixel manipulation. Staying in.NET land, one alternative is to keep around a Bitmap object to act as your surface, using LockBits and directly accessing the pixels through the unsafe pointer in the returned BitmapData object. | [
"c#",
"graphics",
"pointers"
] | 5 | 5 | 2,825 | 4 | 0 | 2008-09-11T07:47:22.343000 | 2008-09-13T20:41:18.503000 |
55,964 | 56,123 | Make WiX installation set upgrade to the same folder | How can I make a major upgrade to an installation set (MSI) built with WiX install into the same folder as the original installation? The installation is correctly detected as an upgrade, but the directory selection screen is still shown and with the default value (not necessarily the current installation folder). Do I have to do manual work like saving the installation folder in a registry key upon first installing and then read this key upon upgrade? If so, is there any example? Or is there some easier way to achieve this in MSI or WiX? As reference, I my current WiX file is below: MsiNetAssemblySupport >= "2.0.50727" NOT Installed AND NOT PATCHFOUND NOT Installed AND NOT PATCHFOUND | There's an example in the WiX tutorial: https://www.firegiant.com/wix/tutorial/getting-started/where-to-install/ Of course, you've got to set the registry key as part of the install too. Stick this inside a component that's part of the original install: | Make WiX installation set upgrade to the same folder How can I make a major upgrade to an installation set (MSI) built with WiX install into the same folder as the original installation? The installation is correctly detected as an upgrade, but the directory selection screen is still shown and with the default value (not necessarily the current installation folder). Do I have to do manual work like saving the installation folder in a registry key upon first installing and then read this key upon upgrade? If so, is there any example? Or is there some easier way to achieve this in MSI or WiX? As reference, I my current WiX file is below: MsiNetAssemblySupport >= "2.0.50727" NOT Installed AND NOT PATCHFOUND NOT Installed AND NOT PATCHFOUND | TITLE:
Make WiX installation set upgrade to the same folder
QUESTION:
How can I make a major upgrade to an installation set (MSI) built with WiX install into the same folder as the original installation? The installation is correctly detected as an upgrade, but the directory selection screen is still shown and with the default value (not necessarily the current installation folder). Do I have to do manual work like saving the installation folder in a registry key upon first installing and then read this key upon upgrade? If so, is there any example? Or is there some easier way to achieve this in MSI or WiX? As reference, I my current WiX file is below: MsiNetAssemblySupport >= "2.0.50727" NOT Installed AND NOT PATCHFOUND NOT Installed AND NOT PATCHFOUND
ANSWER:
There's an example in the WiX tutorial: https://www.firegiant.com/wix/tutorial/getting-started/where-to-install/ Of course, you've got to set the registry key as part of the install too. Stick this inside a component that's part of the original install: | [
"wix",
"windows-installer"
] | 31 | 34 | 10,677 | 3 | 0 | 2008-09-11T07:47:46.663000 | 2008-09-11T09:25:20.593000 |
55,968 | 55,973 | Is there a MySQLAdmin or SQL Server Management Studio equivalent for SQLite databases on Windows? | I need some software to explore and modify some SQLite databases. Does anything similar to SQL Server Management Studio or MySQLAdmin exist for it? | As a Firefox plugin (aimed mainly at gears, but should work) As a (sucky) web based app And a big list of management tools | Is there a MySQLAdmin or SQL Server Management Studio equivalent for SQLite databases on Windows? I need some software to explore and modify some SQLite databases. Does anything similar to SQL Server Management Studio or MySQLAdmin exist for it? | TITLE:
Is there a MySQLAdmin or SQL Server Management Studio equivalent for SQLite databases on Windows?
QUESTION:
I need some software to explore and modify some SQLite databases. Does anything similar to SQL Server Management Studio or MySQLAdmin exist for it?
ANSWER:
As a Firefox plugin (aimed mainly at gears, but should work) As a (sucky) web based app And a big list of management tools | [
"sql",
"windows",
"sqlite"
] | 6 | 10 | 2,230 | 3 | 0 | 2008-09-11T07:48:53.867000 | 2008-09-11T07:52:32.610000 |
55,984 | 56,024 | What is the difference between const and readonly in C#? | What is the difference between const and readonly in C#? When would you use one over the other? | Apart from the apparent difference of having to declare the value at the time of a definition for a const VS readonly values can be computed dynamically but need to be assigned before the constructor exits. After that it is frozen. const 's are implicitly static. You use a ClassName.ConstantName notation to access them. There is a subtle difference. Consider a class defined in AssemblyA. public class Const_V_Readonly { public const int I_CONST_VALUE = 2; public readonly int I_RO_VALUE; public Const_V_Readonly() { I_RO_VALUE = 3; } } AssemblyB references AssemblyA and uses these values in code. When this is compiled: in the case of the const value, it is like a find-replace. The value 2 is 'baked into' the AssemblyB 's IL. This means that if tomorrow I update I_CONST_VALUE to 20, AssemblyB would still have 2 till I recompile it. in the case of the readonly value, it is like a ref to a memory location. The value is not baked into AssemblyB 's IL. This means that if the memory location is updated, AssemblyB gets the new value without recompilation. So if I_RO_VALUE is updated to 30, you only need to build AssemblyA and all clients do not need to be recompiled. So if you are confident that the value of the constant won't change, use a const. public const int CM_IN_A_METER = 100; But if you have a constant that may change (e.g. w.r.t. precision) or when in doubt, use a readonly. public readonly float PI = 3.14; Update: Aku needs to get a mention because he pointed this out first. Also I need to plug where I learned this: Effective C# - Bill Wagner | What is the difference between const and readonly in C#? What is the difference between const and readonly in C#? When would you use one over the other? | TITLE:
What is the difference between const and readonly in C#?
QUESTION:
What is the difference between const and readonly in C#? When would you use one over the other?
ANSWER:
Apart from the apparent difference of having to declare the value at the time of a definition for a const VS readonly values can be computed dynamically but need to be assigned before the constructor exits. After that it is frozen. const 's are implicitly static. You use a ClassName.ConstantName notation to access them. There is a subtle difference. Consider a class defined in AssemblyA. public class Const_V_Readonly { public const int I_CONST_VALUE = 2; public readonly int I_RO_VALUE; public Const_V_Readonly() { I_RO_VALUE = 3; } } AssemblyB references AssemblyA and uses these values in code. When this is compiled: in the case of the const value, it is like a find-replace. The value 2 is 'baked into' the AssemblyB 's IL. This means that if tomorrow I update I_CONST_VALUE to 20, AssemblyB would still have 2 till I recompile it. in the case of the readonly value, it is like a ref to a memory location. The value is not baked into AssemblyB 's IL. This means that if the memory location is updated, AssemblyB gets the new value without recompilation. So if I_RO_VALUE is updated to 30, you only need to build AssemblyA and all clients do not need to be recompiled. So if you are confident that the value of the constant won't change, use a const. public const int CM_IN_A_METER = 100; But if you have a constant that may change (e.g. w.r.t. precision) or when in doubt, use a readonly. public readonly float PI = 3.14; Update: Aku needs to get a mention because he pointed this out first. Also I need to plug where I learned this: Effective C# - Bill Wagner | [
"c#",
".net",
"constants",
"readonly"
] | 1,699 | 1,553 | 514,533 | 30 | 0 | 2008-09-11T08:02:19.297000 | 2008-09-11T08:24:41.770000 |
56,011 | 56,190 | Single quotes vs. double quotes in Python | According to the documentation, they're pretty much interchangeable. Is there a stylistic reason to use one over the other? | I like to use double quotes around strings that are used for interpolation or that are natural language messages, and single quotes for small symbol-like strings, but will break the rules if the strings contain quotes, or if I forget. I use triple double quotes for docstrings and raw string literals for regular expressions even if they aren't needed. For example: LIGHT_MESSAGES = { 'English': "There are %(number_of_lights)s lights.", 'Pirate': "Arr! Thar be %(number_of_lights)s lights." }
def lights_message(language, number_of_lights): """Return a language-appropriate string reporting the light count.""" return LIGHT_MESSAGES[language] % locals()
def is_pirate(message): """Return True if the given message sounds piratical.""" return re.search(r"(?i)(arr|avast|yohoho)!", message) is not None | Single quotes vs. double quotes in Python According to the documentation, they're pretty much interchangeable. Is there a stylistic reason to use one over the other? | TITLE:
Single quotes vs. double quotes in Python
QUESTION:
According to the documentation, they're pretty much interchangeable. Is there a stylistic reason to use one over the other?
ANSWER:
I like to use double quotes around strings that are used for interpolation or that are natural language messages, and single quotes for small symbol-like strings, but will break the rules if the strings contain quotes, or if I forget. I use triple double quotes for docstrings and raw string literals for regular expressions even if they aren't needed. For example: LIGHT_MESSAGES = { 'English': "There are %(number_of_lights)s lights.", 'Pirate': "Arr! Thar be %(number_of_lights)s lights." }
def lights_message(language, number_of_lights): """Return a language-appropriate string reporting the light count.""" return LIGHT_MESSAGES[language] % locals()
def is_pirate(message): """Return True if the given message sounds piratical.""" return re.search(r"(?i)(arr|avast|yohoho)!", message) is not None | [
"python",
"coding-style"
] | 718 | 525 | 814,734 | 19 | 0 | 2008-09-11T08:18:55.293000 | 2008-09-11T10:06:49.557000 |
56,013 | 56,017 | Cross platform .Net? | If you were to write an GUI application that runs locally and calls a webservice, to be cross platform, can you do it with.Net, what tools would you recommend? I was considering Java as it would be relatively easy to pick up due to its C# similarity and then I could use the JVM. | You should get familiar with the Mono project and MonoDevelop; the express purpose of those projects is to allow building and running.NET code on a variety of platforms, including Windows, Linux, and Mac OSX. Since the Mono is a re-implementation of.NET, it always lags a little behind Microsoft.NET, but they've got good coverage of.NET 2.0 and some.NET 3.x features. Note that Mono executes.NET binaries, so as long as your program features are supported by Mono, you can take an application EXE you complied on Windows and run it on Linux/Mono without recompiling. | Cross platform .Net? If you were to write an GUI application that runs locally and calls a webservice, to be cross platform, can you do it with.Net, what tools would you recommend? I was considering Java as it would be relatively easy to pick up due to its C# similarity and then I could use the JVM. | TITLE:
Cross platform .Net?
QUESTION:
If you were to write an GUI application that runs locally and calls a webservice, to be cross platform, can you do it with.Net, what tools would you recommend? I was considering Java as it would be relatively easy to pick up due to its C# similarity and then I could use the JVM.
ANSWER:
You should get familiar with the Mono project and MonoDevelop; the express purpose of those projects is to allow building and running.NET code on a variety of platforms, including Windows, Linux, and Mac OSX. Since the Mono is a re-implementation of.NET, it always lags a little behind Microsoft.NET, but they've got good coverage of.NET 2.0 and some.NET 3.x features. Note that Mono executes.NET binaries, so as long as your program features are supported by Mono, you can take an application EXE you complied on Windows and run it on Linux/Mono without recompiling. | [
".net",
"cross-platform"
] | 7 | 10 | 3,985 | 9 | 0 | 2008-09-11T08:20:29.110000 | 2008-09-11T08:21:49.140000 |
56,022 | 56,043 | Prevent file casing problems in Subversion | We encountered a problem with using Subversion on Windows. A developer committed a file foo.Data.sql and later another developer committed a file called foo.data.sql. Naturally, this caused a problem on Windows clients (all clients are Windows in our environments) because files are case sensitive in Subversion but not in Windows. We managed to resolve this problem by deleting one of the files directly in the repository, but I still have two questions: How is it possible for a developer to do this using a Windows client? Does he have an invalid working copy, or is there a bug in the client (TortoiseSVN)? How can we prevent changes like these from entering the repository (i.e. has anyone written a hook script that performs a sanity check for file casing issues)? | There is definitely a hook script that checks case sensitivity - Sourceforge have it as one of their options. A quick google turns up: http://www.subversionary.org/howto/using-check-case-insensitive-py-on-windows and http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/case-insensitive.py The issue will have arisen on a windows platform if user 1 added foo.data.sql and user 2 added foo.Data.sql before getting an update from user 1. Hope that helps:) | Prevent file casing problems in Subversion We encountered a problem with using Subversion on Windows. A developer committed a file foo.Data.sql and later another developer committed a file called foo.data.sql. Naturally, this caused a problem on Windows clients (all clients are Windows in our environments) because files are case sensitive in Subversion but not in Windows. We managed to resolve this problem by deleting one of the files directly in the repository, but I still have two questions: How is it possible for a developer to do this using a Windows client? Does he have an invalid working copy, or is there a bug in the client (TortoiseSVN)? How can we prevent changes like these from entering the repository (i.e. has anyone written a hook script that performs a sanity check for file casing issues)? | TITLE:
Prevent file casing problems in Subversion
QUESTION:
We encountered a problem with using Subversion on Windows. A developer committed a file foo.Data.sql and later another developer committed a file called foo.data.sql. Naturally, this caused a problem on Windows clients (all clients are Windows in our environments) because files are case sensitive in Subversion but not in Windows. We managed to resolve this problem by deleting one of the files directly in the repository, but I still have two questions: How is it possible for a developer to do this using a Windows client? Does he have an invalid working copy, or is there a bug in the client (TortoiseSVN)? How can we prevent changes like these from entering the repository (i.e. has anyone written a hook script that performs a sanity check for file casing issues)?
ANSWER:
There is definitely a hook script that checks case sensitivity - Sourceforge have it as one of their options. A quick google turns up: http://www.subversionary.org/howto/using-check-case-insensitive-py-on-windows and http://svn.apache.org/repos/asf/subversion/trunk/contrib/hook-scripts/case-insensitive.py The issue will have arisen on a windows platform if user 1 added foo.data.sql and user 2 added foo.Data.sql before getting an update from user 1. Hope that helps:) | [
"svn",
"tortoisesvn"
] | 4 | 4 | 2,008 | 3 | 0 | 2008-09-11T08:23:02.287000 | 2008-09-11T08:38:12.017000 |
56,037 | 56,519 | how to represent an empty field in yaml | I am working with fixtures on rails and I want one of the fixture fields to be blank. Example: two: name: test path: - I want this blank but not to act as a group heading. test: 4 But, I do not know how to leave path: blank without it acting as a group title. Does anybody know how to do that? | YAML files are based on indentation. Once you actually have correct indentation it will read everything at the same level as siblings. two: name: test path: test: 4 | how to represent an empty field in yaml I am working with fixtures on rails and I want one of the fixture fields to be blank. Example: two: name: test path: - I want this blank but not to act as a group heading. test: 4 But, I do not know how to leave path: blank without it acting as a group title. Does anybody know how to do that? | TITLE:
how to represent an empty field in yaml
QUESTION:
I am working with fixtures on rails and I want one of the fixture fields to be blank. Example: two: name: test path: - I want this blank but not to act as a group heading. test: 4 But, I do not know how to leave path: blank without it acting as a group title. Does anybody know how to do that?
ANSWER:
YAML files are based on indentation. Once you actually have correct indentation it will read everything at the same level as siblings. two: name: test path: test: 4 | [
"ruby-on-rails",
"yaml"
] | 8 | 7 | 7,654 | 2 | 0 | 2008-09-11T08:32:21.830000 | 2008-09-11T13:26:18.113000 |
56,045 | 56,626 | Stuts2 Tiles Tomcat suspected of changing UTF-8 to? | I'm having some internationalisation woes: My UTF-8 string fields are being rendered in the browser as???? after being returned from the database. After retrieval from the database using Hibernate, the String fields are presented correctly on inspection using the eclipse debugger. However Struts2/Tiles is rendering these strings as???? in the HTML sent to the browser. The charset directive is present in the HTML header: Perhaps I need to add something to my struts2 or tiles configurations? | You could try something like this. It's taken from sun's page on Character Sets and Encodings. I think this has to be the very first line in your jsp. <%@ page contentType="text/html; charset=UTF-8" %> | Stuts2 Tiles Tomcat suspected of changing UTF-8 to? I'm having some internationalisation woes: My UTF-8 string fields are being rendered in the browser as???? after being returned from the database. After retrieval from the database using Hibernate, the String fields are presented correctly on inspection using the eclipse debugger. However Struts2/Tiles is rendering these strings as???? in the HTML sent to the browser. The charset directive is present in the HTML header: Perhaps I need to add something to my struts2 or tiles configurations? | TITLE:
Stuts2 Tiles Tomcat suspected of changing UTF-8 to?
QUESTION:
I'm having some internationalisation woes: My UTF-8 string fields are being rendered in the browser as???? after being returned from the database. After retrieval from the database using Hibernate, the String fields are presented correctly on inspection using the eclipse debugger. However Struts2/Tiles is rendering these strings as???? in the HTML sent to the browser. The charset directive is present in the HTML header: Perhaps I need to add something to my struts2 or tiles configurations?
ANSWER:
You could try something like this. It's taken from sun's page on Character Sets and Encodings. I think this has to be the very first line in your jsp. <%@ page contentType="text/html; charset=UTF-8" %> | [
"java",
"utf-8",
"internationalization",
"struts2",
"tiles"
] | 1 | 0 | 600 | 4 | 0 | 2008-09-11T08:39:22.403000 | 2008-09-11T14:05:28.127000 |
56,046 | 56,080 | Stop system entering 'standby' | How can i stop the host machine entering standby mode while my application is running? Is there any win32 api call to do this? | There are two APIs, depending on what version of Windows. XP,2000, 2003: http://msdn.microsoft.com/en-us/library/aa373247(VS.85).aspx Respond to PBT_APMQUERYSUSPEND. Vista, 2008: http://msdn.microsoft.com/en-us/library/aa373208(VS.85).aspx There could be many valid reasons to prevent the computer from going to sleep. For example, watching a video, playing music, compiling a long running build, downloading large files, etc. | Stop system entering 'standby' How can i stop the host machine entering standby mode while my application is running? Is there any win32 api call to do this? | TITLE:
Stop system entering 'standby'
QUESTION:
How can i stop the host machine entering standby mode while my application is running? Is there any win32 api call to do this?
ANSWER:
There are two APIs, depending on what version of Windows. XP,2000, 2003: http://msdn.microsoft.com/en-us/library/aa373247(VS.85).aspx Respond to PBT_APMQUERYSUSPEND. Vista, 2008: http://msdn.microsoft.com/en-us/library/aa373208(VS.85).aspx There could be many valid reasons to prevent the computer from going to sleep. For example, watching a video, playing music, compiling a long running build, downloading large files, etc. | [
"c++",
"winapi",
"standards",
"standby"
] | 4 | 6 | 3,520 | 2 | 0 | 2008-09-11T08:40:03.027000 | 2008-09-11T08:57:51.143000 |
56,052 | 56,061 | Best way to insert timestamp in Vim? | EditPad Lite has a nice feature ( CTRL - E, CTRL - I ) which inserts a time stamp e.g. "2008-09-11 10:34:53" into your code. What is the best way to get this functionality in Vim? (I am using Vim 6.1 on a Linux server via SSH. In the current situation a number of us share a login so I don't want to create abbreviations in the home directory if there is another built-in way to get a timestamp.) | http://kenno.wordpress.com/2006/08/03/vim-tip-insert-time-stamp/ Tried it out, it works on my mac::r! date produces: Thu Sep 11 10:47:30 CEST 2008 This::r! date "+\%Y-\%m-\%d \%H:\%M:\%S" produces: 2008-09-11 10:50:56 | Best way to insert timestamp in Vim? EditPad Lite has a nice feature ( CTRL - E, CTRL - I ) which inserts a time stamp e.g. "2008-09-11 10:34:53" into your code. What is the best way to get this functionality in Vim? (I am using Vim 6.1 on a Linux server via SSH. In the current situation a number of us share a login so I don't want to create abbreviations in the home directory if there is another built-in way to get a timestamp.) | TITLE:
Best way to insert timestamp in Vim?
QUESTION:
EditPad Lite has a nice feature ( CTRL - E, CTRL - I ) which inserts a time stamp e.g. "2008-09-11 10:34:53" into your code. What is the best way to get this functionality in Vim? (I am using Vim 6.1 on a Linux server via SSH. In the current situation a number of us share a login so I don't want to create abbreviations in the home directory if there is another built-in way to get a timestamp.)
ANSWER:
http://kenno.wordpress.com/2006/08/03/vim-tip-insert-time-stamp/ Tried it out, it works on my mac::r! date produces: Thu Sep 11 10:47:30 CEST 2008 This::r! date "+\%Y-\%m-\%d \%H:\%M:\%S" produces: 2008-09-11 10:50:56 | [
"vim",
"vi"
] | 104 | 102 | 45,314 | 11 | 0 | 2008-09-11T08:41:56.547000 | 2008-09-11T08:45:50.843000 |
56,070 | 56,163 | DELETE Statement hangs on SQL Server for no apparent reason | Edit: Solved, there was a trigger with a loop on the table (read my own answer further below). We have a simple delete statement that looks like this: DELETE FROM tablename WHERE pk = 12345 This just hangs, no timeout, no nothing. We've looked at the execution plan, and it consists of many lookups on related tables to ensure no foreign keys would trip up the delete, but we've verified that none of those other tables have any rows referring to that particular row. There is no other user connected to the database at this time. We've run DBCC CHECKDB against it, and it reports 0 errors. Looking at the results of sp_who and sp_lock while the query is hanging, I notice that my spid has plenty of PAG and KEY locks, as well as the occasional TAB lock. The table has 1.777.621 rows, and yes, pk is the primary key, so it's a single row delete based on index. There is no table scan in the execution plan, though I notice that it contains something that says Table Spool (Eager Spool), but says Estimated number of rows 1. Can this actually be a table-scan in disguise? It only says it looks at the primary key column. Tried DBCC DBREINDEX and UPDATE STATISTICS on the table. Both completed within reasonable time. There is unfortunately a high number of indexes on this particular table. It is the core table in our system, with plenty of columns, and references, both outgoing and incoming. The exact number is 48 indexes + the primary key clustered index. What else should we look at? Note also that this table did not have this problem before, this problem occured suddently today. We also have many databases with the same table setup (copies of customer databases), and they behave as expected, it's just this one that is problematic. | One piece of information missing is the number of indices on the table you are deleting the data from. As SQL Server uses the Primary Key as a pointer in every index, any change to the primary index requires updating every index. Though, unless we are talking a high number, this shouldn't be an issue. I am guessing, from your description, that this is a primary table in the database, referenced by many other tables in FK relationships. This would account for the large number of locks as it checks the rest of the tables for references. And, if you have cascading deletes turned on, this could lead to a delete in table a requiring checks several tables deep. | DELETE Statement hangs on SQL Server for no apparent reason Edit: Solved, there was a trigger with a loop on the table (read my own answer further below). We have a simple delete statement that looks like this: DELETE FROM tablename WHERE pk = 12345 This just hangs, no timeout, no nothing. We've looked at the execution plan, and it consists of many lookups on related tables to ensure no foreign keys would trip up the delete, but we've verified that none of those other tables have any rows referring to that particular row. There is no other user connected to the database at this time. We've run DBCC CHECKDB against it, and it reports 0 errors. Looking at the results of sp_who and sp_lock while the query is hanging, I notice that my spid has plenty of PAG and KEY locks, as well as the occasional TAB lock. The table has 1.777.621 rows, and yes, pk is the primary key, so it's a single row delete based on index. There is no table scan in the execution plan, though I notice that it contains something that says Table Spool (Eager Spool), but says Estimated number of rows 1. Can this actually be a table-scan in disguise? It only says it looks at the primary key column. Tried DBCC DBREINDEX and UPDATE STATISTICS on the table. Both completed within reasonable time. There is unfortunately a high number of indexes on this particular table. It is the core table in our system, with plenty of columns, and references, both outgoing and incoming. The exact number is 48 indexes + the primary key clustered index. What else should we look at? Note also that this table did not have this problem before, this problem occured suddently today. We also have many databases with the same table setup (copies of customer databases), and they behave as expected, it's just this one that is problematic. | TITLE:
DELETE Statement hangs on SQL Server for no apparent reason
QUESTION:
Edit: Solved, there was a trigger with a loop on the table (read my own answer further below). We have a simple delete statement that looks like this: DELETE FROM tablename WHERE pk = 12345 This just hangs, no timeout, no nothing. We've looked at the execution plan, and it consists of many lookups on related tables to ensure no foreign keys would trip up the delete, but we've verified that none of those other tables have any rows referring to that particular row. There is no other user connected to the database at this time. We've run DBCC CHECKDB against it, and it reports 0 errors. Looking at the results of sp_who and sp_lock while the query is hanging, I notice that my spid has plenty of PAG and KEY locks, as well as the occasional TAB lock. The table has 1.777.621 rows, and yes, pk is the primary key, so it's a single row delete based on index. There is no table scan in the execution plan, though I notice that it contains something that says Table Spool (Eager Spool), but says Estimated number of rows 1. Can this actually be a table-scan in disguise? It only says it looks at the primary key column. Tried DBCC DBREINDEX and UPDATE STATISTICS on the table. Both completed within reasonable time. There is unfortunately a high number of indexes on this particular table. It is the core table in our system, with plenty of columns, and references, both outgoing and incoming. The exact number is 48 indexes + the primary key clustered index. What else should we look at? Note also that this table did not have this problem before, this problem occured suddently today. We also have many databases with the same table setup (copies of customer databases), and they behave as expected, it's just this one that is problematic.
ANSWER:
One piece of information missing is the number of indices on the table you are deleting the data from. As SQL Server uses the Primary Key as a pointer in every index, any change to the primary index requires updating every index. Though, unless we are talking a high number, this shouldn't be an issue. I am guessing, from your description, that this is a primary table in the database, referenced by many other tables in FK relationships. This would account for the large number of locks as it checks the rest of the tables for references. And, if you have cascading deletes turned on, this could lead to a delete in table a requiring checks several tables deep. | [
"sql",
"sql-server",
"sql-server-2005"
] | 11 | 6 | 17,548 | 3 | 0 | 2008-09-11T08:51:39.550000 | 2008-09-11T09:51:37.397000 |
56,078 | 56,100 | Merging two Collection<T> | I got a Function that returns a Collection, and that calls itself recursively to eventually return one big Collection. Now, i just wonder what the best approach to merge the lists? Collection.CopyTo() only copies to string[], and using a foreach() loop feels like being inefficient. However, since I also want to filter out duplicates, I feel like i'll end up with a foreach that calls Contains() on the Collection. I wonder, is there a more efficient way to have a recursive function that returns a list of strings without duplicates? I don't have to use a Collection, it can be pretty much any suitable data type. Only exclusion, I'm bound to Visual Studio 2005 and.net 3.0, so no LINQ. Edit: To clarify: The Function takes a user out of Active Directory, looks at the Direct Reports of the user, and then recursively looks at the direct reports of every user. So the end result is a List of all users that are in the "command chain" of a given user.Since this is executed quite often and at the moment takes 20 Seconds for some users, i'm looking for ways to improve it. Caching the result for 24 Hours is also on my list btw., but I want to see how to improve it before applying caching. | If you're using List<> you can use.AddRange to add one list to the other list. Or you can use yield return to combine lists on the fly like this: public IEnumerable Combine(IEnumerable col1, IEnumerable col2) { foreach(string item in col1) yield return item;
foreach(string item in col2) yield return item; } | Merging two Collection<T> I got a Function that returns a Collection, and that calls itself recursively to eventually return one big Collection. Now, i just wonder what the best approach to merge the lists? Collection.CopyTo() only copies to string[], and using a foreach() loop feels like being inefficient. However, since I also want to filter out duplicates, I feel like i'll end up with a foreach that calls Contains() on the Collection. I wonder, is there a more efficient way to have a recursive function that returns a list of strings without duplicates? I don't have to use a Collection, it can be pretty much any suitable data type. Only exclusion, I'm bound to Visual Studio 2005 and.net 3.0, so no LINQ. Edit: To clarify: The Function takes a user out of Active Directory, looks at the Direct Reports of the user, and then recursively looks at the direct reports of every user. So the end result is a List of all users that are in the "command chain" of a given user.Since this is executed quite often and at the moment takes 20 Seconds for some users, i'm looking for ways to improve it. Caching the result for 24 Hours is also on my list btw., but I want to see how to improve it before applying caching. | TITLE:
Merging two Collection<T>
QUESTION:
I got a Function that returns a Collection, and that calls itself recursively to eventually return one big Collection. Now, i just wonder what the best approach to merge the lists? Collection.CopyTo() only copies to string[], and using a foreach() loop feels like being inefficient. However, since I also want to filter out duplicates, I feel like i'll end up with a foreach that calls Contains() on the Collection. I wonder, is there a more efficient way to have a recursive function that returns a list of strings without duplicates? I don't have to use a Collection, it can be pretty much any suitable data type. Only exclusion, I'm bound to Visual Studio 2005 and.net 3.0, so no LINQ. Edit: To clarify: The Function takes a user out of Active Directory, looks at the Direct Reports of the user, and then recursively looks at the direct reports of every user. So the end result is a List of all users that are in the "command chain" of a given user.Since this is executed quite often and at the moment takes 20 Seconds for some users, i'm looking for ways to improve it. Caching the result for 24 Hours is also on my list btw., but I want to see how to improve it before applying caching.
ANSWER:
If you're using List<> you can use.AddRange to add one list to the other list. Or you can use yield return to combine lists on the fly like this: public IEnumerable Combine(IEnumerable col1, IEnumerable col2) { foreach(string item in col1) yield return item;
foreach(string item in col2) yield return item; } | [
"c#",
"collections"
] | 9 | 18 | 14,487 | 5 | 0 | 2008-09-11T08:57:17.853000 | 2008-09-11T09:06:44.990000 |
56,087 | 57,802 | Does ruby have real multithreading? | I know about the "cooperative" threading of ruby using green threads. How can I create real "OS-level" threads in my application in order to make use of multiple cpu cores for processing? | Updated with Jörg's Sept 2011 comment You seem to be confusing two very different things here: the Ruby Programming Language and the specific threading model of one specific implementation of the Ruby Programming Language. There are currently around 11 different implementations of the Ruby Programming Language, with very different and unique threading models. (Unfortunately, only two of those 11 implementations are actually ready for production use, but by the end of the year that number will probably go up to four or five.) ( Update: it's now 5: MRI, JRuby, YARV (the interpreter for Ruby 1.9), Rubinius and IronRuby). The first implementation doesn't actually have a name, which makes it quite awkward to refer to it and is really annoying and confusing. It is most often referred to as "Ruby", which is even more annoying and confusing than having no name, because it leads to endless confusion between the features of the Ruby Programming Language and a particular Ruby Implementation. It is also sometimes called "MRI" (for "Matz's Ruby Implementation"), CRuby or MatzRuby. MRI implements Ruby Threads as Green Threads within its interpreter. Unfortunately, it doesn't allow those threads to be scheduled in parallel, they can only run one thread at a time. However, any number of C Threads (POSIX Threads etc.) can run in parallel to the Ruby Thread, so external C Libraries, or MRI C Extensions that create threads of their own can still run in parallel. The second implementation is YARV (short for "Yet Another Ruby VM"). YARV implements Ruby Threads as POSIX or Windows NT Threads, however, it uses a Global Interpreter Lock (GIL) to ensure that only one Ruby Thread can actually be scheduled at any one time. Like MRI, C Threads can actually run parallel to Ruby Threads. In the future, it is possible, that the GIL might get broken down into more fine-grained locks, thus allowing more and more code to actually run in parallel, but that's so far away, it is not even planned yet. JRuby implements Ruby Threads as Native Threads, where "Native Threads" in case of the JVM obviously means "JVM Threads". JRuby imposes no additional locking on them. So, whether those threads can actually run in parallel depends on the JVM: some JVMs implement JVM Threads as OS Threads and some as Green Threads. (The mainstream JVMs from Sun/Oracle use exclusively OS threads since JDK 1.3) XRuby also implements Ruby Threads as JVM Threads. Update: XRuby is dead. IronRuby implements Ruby Threads as Native Threads, where "Native Threads" in case of the CLR obviously means "CLR Threads". IronRuby imposes no additional locking on them, so, they should run in parallel, as long as your CLR supports that. Ruby.NET also implements Ruby Threads as CLR Threads. Update: Ruby.NET is dead. Rubinius implements Ruby Threads as Green Threads within its Virtual Machine. More precisely: the Rubinius VM exports a very lightweight, very flexible concurrency/parallelism/non-local control-flow construct, called a " Task ", and all other concurrency constructs (Threads in this discussion, but also Continuations, Actors and other stuff) are implemented in pure Ruby, using Tasks. Rubinius can not (currently) schedule Threads in parallel, however, adding that isn't too much of a problem: Rubinius can already run several VM instances in several POSIX Threads in parallel, within one Rubinius process. Since Threads are actually implemented in Ruby, they can, like any other Ruby object, be serialized and sent to a different VM in a different POSIX Thread. (That's the same model the BEAM Erlang VM uses for SMP concurrency. It is already implemented for Rubinius Actors.) Update: The information about Rubinius in this answer is about the Shotgun VM, which doesn't exist anymore. The "new" C++ VM does not use green threads scheduled across multiple VMs (i.e. Erlang/BEAM style), it uses a more traditional single VM with multiple native OS threads model, just like the one employed by, say, the CLR, Mono, and pretty much every JVM. MacRuby started out as a port of YARV on top of the Objective-C Runtime and CoreFoundation and Cocoa Frameworks. It has now significantly diverged from YARV, but AFAIK it currently still shares the same Threading Model with YARV. Update: MacRuby depends on apples garbage collector which is declared deprecated and will be removed in later versions of MacOSX, MacRuby is undead. Cardinal is a Ruby Implementation for the Parrot Virtual Machine. It doesn't implement threads yet, however, when it does, it will probably implement them as Parrot Threads. Update: Cardinal seems very inactive/dead. MagLev is a Ruby Implementation for the GemStone/S Smalltalk VM. I have no information what threading model GemStone/S uses, what threading model MagLev uses or even if threads are even implemented yet (probably not). HotRuby is not a full Ruby Implementation of its own. It is an implementation of a YARV bytecode VM in JavaScript. HotRuby doesn't support threads (yet?) and when it does, they won't be able to run in parallel, because JavaScript has no support for true parallelism. There is an ActionScript version of HotRuby, however, and ActionScript might actually support parallelism. Update: HotRuby is dead. Unfortunately, only two of these 11 Ruby Implementations are actually production-ready: MRI and JRuby. So, if you want true parallel threads, JRuby is currently your only choice – not that that's a bad one: JRuby is actually faster than MRI, and arguably more stable. Otherwise, the "classical" Ruby solution is to use processes instead of threads for parallelism. The Ruby Core Library contains the Process module with the Process.fork method which makes it dead easy to fork off another Ruby process. Also, the Ruby Standard Library contains the Distributed Ruby (dRuby / dRb) library, which allows Ruby code to be trivially distributed across multiple processes, not only on the same machine but also across the network. | Does ruby have real multithreading? I know about the "cooperative" threading of ruby using green threads. How can I create real "OS-level" threads in my application in order to make use of multiple cpu cores for processing? | TITLE:
Does ruby have real multithreading?
QUESTION:
I know about the "cooperative" threading of ruby using green threads. How can I create real "OS-level" threads in my application in order to make use of multiple cpu cores for processing?
ANSWER:
Updated with Jörg's Sept 2011 comment You seem to be confusing two very different things here: the Ruby Programming Language and the specific threading model of one specific implementation of the Ruby Programming Language. There are currently around 11 different implementations of the Ruby Programming Language, with very different and unique threading models. (Unfortunately, only two of those 11 implementations are actually ready for production use, but by the end of the year that number will probably go up to four or five.) ( Update: it's now 5: MRI, JRuby, YARV (the interpreter for Ruby 1.9), Rubinius and IronRuby). The first implementation doesn't actually have a name, which makes it quite awkward to refer to it and is really annoying and confusing. It is most often referred to as "Ruby", which is even more annoying and confusing than having no name, because it leads to endless confusion between the features of the Ruby Programming Language and a particular Ruby Implementation. It is also sometimes called "MRI" (for "Matz's Ruby Implementation"), CRuby or MatzRuby. MRI implements Ruby Threads as Green Threads within its interpreter. Unfortunately, it doesn't allow those threads to be scheduled in parallel, they can only run one thread at a time. However, any number of C Threads (POSIX Threads etc.) can run in parallel to the Ruby Thread, so external C Libraries, or MRI C Extensions that create threads of their own can still run in parallel. The second implementation is YARV (short for "Yet Another Ruby VM"). YARV implements Ruby Threads as POSIX or Windows NT Threads, however, it uses a Global Interpreter Lock (GIL) to ensure that only one Ruby Thread can actually be scheduled at any one time. Like MRI, C Threads can actually run parallel to Ruby Threads. In the future, it is possible, that the GIL might get broken down into more fine-grained locks, thus allowing more and more code to actually run in parallel, but that's so far away, it is not even planned yet. JRuby implements Ruby Threads as Native Threads, where "Native Threads" in case of the JVM obviously means "JVM Threads". JRuby imposes no additional locking on them. So, whether those threads can actually run in parallel depends on the JVM: some JVMs implement JVM Threads as OS Threads and some as Green Threads. (The mainstream JVMs from Sun/Oracle use exclusively OS threads since JDK 1.3) XRuby also implements Ruby Threads as JVM Threads. Update: XRuby is dead. IronRuby implements Ruby Threads as Native Threads, where "Native Threads" in case of the CLR obviously means "CLR Threads". IronRuby imposes no additional locking on them, so, they should run in parallel, as long as your CLR supports that. Ruby.NET also implements Ruby Threads as CLR Threads. Update: Ruby.NET is dead. Rubinius implements Ruby Threads as Green Threads within its Virtual Machine. More precisely: the Rubinius VM exports a very lightweight, very flexible concurrency/parallelism/non-local control-flow construct, called a " Task ", and all other concurrency constructs (Threads in this discussion, but also Continuations, Actors and other stuff) are implemented in pure Ruby, using Tasks. Rubinius can not (currently) schedule Threads in parallel, however, adding that isn't too much of a problem: Rubinius can already run several VM instances in several POSIX Threads in parallel, within one Rubinius process. Since Threads are actually implemented in Ruby, they can, like any other Ruby object, be serialized and sent to a different VM in a different POSIX Thread. (That's the same model the BEAM Erlang VM uses for SMP concurrency. It is already implemented for Rubinius Actors.) Update: The information about Rubinius in this answer is about the Shotgun VM, which doesn't exist anymore. The "new" C++ VM does not use green threads scheduled across multiple VMs (i.e. Erlang/BEAM style), it uses a more traditional single VM with multiple native OS threads model, just like the one employed by, say, the CLR, Mono, and pretty much every JVM. MacRuby started out as a port of YARV on top of the Objective-C Runtime and CoreFoundation and Cocoa Frameworks. It has now significantly diverged from YARV, but AFAIK it currently still shares the same Threading Model with YARV. Update: MacRuby depends on apples garbage collector which is declared deprecated and will be removed in later versions of MacOSX, MacRuby is undead. Cardinal is a Ruby Implementation for the Parrot Virtual Machine. It doesn't implement threads yet, however, when it does, it will probably implement them as Parrot Threads. Update: Cardinal seems very inactive/dead. MagLev is a Ruby Implementation for the GemStone/S Smalltalk VM. I have no information what threading model GemStone/S uses, what threading model MagLev uses or even if threads are even implemented yet (probably not). HotRuby is not a full Ruby Implementation of its own. It is an implementation of a YARV bytecode VM in JavaScript. HotRuby doesn't support threads (yet?) and when it does, they won't be able to run in parallel, because JavaScript has no support for true parallelism. There is an ActionScript version of HotRuby, however, and ActionScript might actually support parallelism. Update: HotRuby is dead. Unfortunately, only two of these 11 Ruby Implementations are actually production-ready: MRI and JRuby. So, if you want true parallel threads, JRuby is currently your only choice – not that that's a bad one: JRuby is actually faster than MRI, and arguably more stable. Otherwise, the "classical" Ruby solution is to use processes instead of threads for parallelism. The Ruby Core Library contains the Process module with the Process.fork method which makes it dead easy to fork off another Ruby process. Also, the Ruby Standard Library contains the Distributed Ruby (dRuby / dRb) library, which allows Ruby code to be trivially distributed across multiple processes, not only on the same machine but also across the network. | [
"ruby",
"multithreading",
"concurrency"
] | 304 | 620 | 80,710 | 9 | 0 | 2008-09-11T09:01:36.003000 | 2008-09-11T22:25:12.903000 |
56,091 | 56,111 | Pointers to C++ class methods | Whilst refactoring some legacy C++ code I found that I could potentially remove some code duplication by somehow defining a variable that could point to any class method that shared the same signature. After a little digging, I found that I could do something like the following: class MyClass { protected: bool CaseMethod1( int abc, const std::string& str ) { cout << "case 1:" << str; return true; }
bool CaseMethod2( int abc, const std::string& str ) { cout << "case 2:" << str; return true; }
bool CaseMethod3( int abc, const std::string& str ) { cout << "case 3:" << str; return true; }
public: bool TestSwitch( int num ) { bool ( MyClass::*CaseMethod )( int, const std::string& );
switch ( num ) { case 1: CaseMethod = &MyClass::CaseMethod1; break; case 2: CaseMethod = &MyClass::CaseMethod2; break; case 3: CaseMethod = &MyClass::CaseMethod3; break; }...
bool res = CaseMethod( 999, "hello world" );...
reurn res; } }; My question is - is this the correct way to go about this? Should I consider anything that Boost has to offer? Edit... Ok, my mistake - I should be calling the method like so: bool res = ( (*this).*CaseMethod )( 999, "Hello World" ); | What you have there is a pointer-to-member-function. It will solve your problem. I am surprised that your "TestSwitch" function compiles, as the calling syntax is slightly different to what you might expect. It should be: bool res = (this->*CaseMethod)( 999, "hello world" ); However, you might find a combination of boost::function and boost::bind makes things a little easier, as you can avoid the bizarre calling syntax. boost::function f= boost::bind(&MyClass::CaseMethod1,this,_1,_2); Of course, this will bind it to the current this pointer: you can make the this pointer of the member function an explicit third parameter if you like: boost::function f= boost::bind(&MyClass::CaseMethod1,_1,_2,_3); Another alternative might be to use virtual functions and derived classes, but that might require major changes to your code. | Pointers to C++ class methods Whilst refactoring some legacy C++ code I found that I could potentially remove some code duplication by somehow defining a variable that could point to any class method that shared the same signature. After a little digging, I found that I could do something like the following: class MyClass { protected: bool CaseMethod1( int abc, const std::string& str ) { cout << "case 1:" << str; return true; }
bool CaseMethod2( int abc, const std::string& str ) { cout << "case 2:" << str; return true; }
bool CaseMethod3( int abc, const std::string& str ) { cout << "case 3:" << str; return true; }
public: bool TestSwitch( int num ) { bool ( MyClass::*CaseMethod )( int, const std::string& );
switch ( num ) { case 1: CaseMethod = &MyClass::CaseMethod1; break; case 2: CaseMethod = &MyClass::CaseMethod2; break; case 3: CaseMethod = &MyClass::CaseMethod3; break; }...
bool res = CaseMethod( 999, "hello world" );...
reurn res; } }; My question is - is this the correct way to go about this? Should I consider anything that Boost has to offer? Edit... Ok, my mistake - I should be calling the method like so: bool res = ( (*this).*CaseMethod )( 999, "Hello World" ); | TITLE:
Pointers to C++ class methods
QUESTION:
Whilst refactoring some legacy C++ code I found that I could potentially remove some code duplication by somehow defining a variable that could point to any class method that shared the same signature. After a little digging, I found that I could do something like the following: class MyClass { protected: bool CaseMethod1( int abc, const std::string& str ) { cout << "case 1:" << str; return true; }
bool CaseMethod2( int abc, const std::string& str ) { cout << "case 2:" << str; return true; }
bool CaseMethod3( int abc, const std::string& str ) { cout << "case 3:" << str; return true; }
public: bool TestSwitch( int num ) { bool ( MyClass::*CaseMethod )( int, const std::string& );
switch ( num ) { case 1: CaseMethod = &MyClass::CaseMethod1; break; case 2: CaseMethod = &MyClass::CaseMethod2; break; case 3: CaseMethod = &MyClass::CaseMethod3; break; }...
bool res = CaseMethod( 999, "hello world" );...
reurn res; } }; My question is - is this the correct way to go about this? Should I consider anything that Boost has to offer? Edit... Ok, my mistake - I should be calling the method like so: bool res = ( (*this).*CaseMethod )( 999, "Hello World" );
ANSWER:
What you have there is a pointer-to-member-function. It will solve your problem. I am surprised that your "TestSwitch" function compiles, as the calling syntax is slightly different to what you might expect. It should be: bool res = (this->*CaseMethod)( 999, "hello world" ); However, you might find a combination of boost::function and boost::bind makes things a little easier, as you can avoid the bizarre calling syntax. boost::function f= boost::bind(&MyClass::CaseMethod1,this,_1,_2); Of course, this will bind it to the current this pointer: you can make the this pointer of the member function an explicit third parameter if you like: boost::function f= boost::bind(&MyClass::CaseMethod1,_1,_2,_3); Another alternative might be to use virtual functions and derived classes, but that might require major changes to your code. | [
"c++"
] | 3 | 8 | 1,084 | 7 | 0 | 2008-09-11T09:03:13.737000 | 2008-09-11T09:18:24.153000 |
56,096 | 56,214 | Removing web.config from subversion (ASP.NET Project) | I have a project which is source controlled using Subversion and VisualSVN. Since the version of web.config is different on the server and the developers' computers I want the file to remain on the computers but to be ignored by Subversion. I added it to the svn:ignore but it still remains (and still has a red exclamation mark too since we are not committing it). How can I remove it from Subversion safely without it being deleted from the files system Thanks, Adin | you'll have to do both the remove and ignore operation first make a backup of your local file (like @ibz said) then remove the web.config from the repository. then copy back the web.config to the same folder finally use svn:ignore so that subversion does not try to add it again to the repository since i use tortoisesvn i can't really tell you what svn commands you have to use, but using tortoisesvn it would be: make backup right click on web.config on the folder under source control, select TortoiseSVN | Delete right click on web.config on the folder under source control, select SVN Commit => after this you will notice that the file is actually deleted from the file system move up and right click on the folder under source control, select TortoiseSVN | Properties on the properties window click new + property name "svn:ignore"; property value "web.config". accept changes commit changes on my.net projects i include the following exclusion with svn:ignore: bin, obj, *.suo, *.user | Removing web.config from subversion (ASP.NET Project) I have a project which is source controlled using Subversion and VisualSVN. Since the version of web.config is different on the server and the developers' computers I want the file to remain on the computers but to be ignored by Subversion. I added it to the svn:ignore but it still remains (and still has a red exclamation mark too since we are not committing it). How can I remove it from Subversion safely without it being deleted from the files system Thanks, Adin | TITLE:
Removing web.config from subversion (ASP.NET Project)
QUESTION:
I have a project which is source controlled using Subversion and VisualSVN. Since the version of web.config is different on the server and the developers' computers I want the file to remain on the computers but to be ignored by Subversion. I added it to the svn:ignore but it still remains (and still has a red exclamation mark too since we are not committing it). How can I remove it from Subversion safely without it being deleted from the files system Thanks, Adin
ANSWER:
you'll have to do both the remove and ignore operation first make a backup of your local file (like @ibz said) then remove the web.config from the repository. then copy back the web.config to the same folder finally use svn:ignore so that subversion does not try to add it again to the repository since i use tortoisesvn i can't really tell you what svn commands you have to use, but using tortoisesvn it would be: make backup right click on web.config on the folder under source control, select TortoiseSVN | Delete right click on web.config on the folder under source control, select SVN Commit => after this you will notice that the file is actually deleted from the file system move up and right click on the folder under source control, select TortoiseSVN | Properties on the properties window click new + property name "svn:ignore"; property value "web.config". accept changes commit changes on my.net projects i include the following exclusion with svn:ignore: bin, obj, *.suo, *.user | [
"asp.net",
"svn",
"web-config"
] | 4 | 6 | 2,690 | 4 | 0 | 2008-09-11T09:06:06.520000 | 2008-09-11T10:27:02.943000 |
56,112 | 57,760 | WCF, ASP.NET Membership Provider and Authentication Service | I have written a Silverlight 2 application communicating with a WCF service (BasicHttpBinding). The site hosting the Silverlight content is protected using a ASP.NET Membership Provider. I can access the current user using HttpContext.Current.User.Identity.Name from my WCF service, and I have turned on AspNetCompatibilityRequirementsMode. I now want to write a Windows application using the exact same web service. To handle authentication I have enabled the Authentication service, and can call "login" to authenticate my user... Okey, all good... But how the heck do I get that authentication cookie set on my other service client?! Both services are hosted on the same domain MyDataService.svc <- the one dealing with my data AuthenticationService.svc <- the one the windows app has to call to authenticate. I don't want to create a new service for the windows client, or use another binding... The Client Application Services is another alternative, but all the examples is limited to show how to get the user, roles and his profile... But once we're authenticated using the Client Application Services there should be a way to get that authentication cookie attached to my service clients when calling back to the same server. According to input from colleagues the solution is adding a wsHttpBinding end-point, but I'm hoping I can get around that... | I finally found a way to make this work. For authentication I'm using the " WCF Authentication Service ". When authenticating the service will try to set an authentication cookie. I need to get this cookie out of the response, and add it to any other request made to other web services on the same machine. The code to do that looks like this: var authService = new AuthService.AuthenticationServiceClient(); var diveService = new DiveLogService.DiveLogServiceClient();
string cookieHeader = ""; using (OperationContextScope scope = new OperationContextScope(authService.InnerChannel)) { HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty(); OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty; bool isGood = authService.Login("jonas", "jonas", string.Empty, true); MessageProperties properties = OperationContext.Current.IncomingMessageProperties; HttpResponseMessageProperty responseProperty = (HttpResponseMessageProperty)properties[HttpResponseMessageProperty.Name]; cookieHeader = responseProperty.Headers[HttpResponseHeader.SetCookie]; }
using (OperationContextScope scope = new OperationContextScope(diveService.InnerChannel)) { HttpRequestMessageProperty httpRequest = new HttpRequestMessageProperty(); OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest); httpRequest.Headers.Add(HttpRequestHeader.Cookie, cookieHeader); var res = diveService.GetDives(); } As you can see I have two service clients, one fo the authentication service, and one for the service I'm actually going to use. The first block will call the Login method, and grab the authentication cookie out of the response. The second block will add the header to the request before calling the "GetDives" service method. I'm not happy with this code at all, and I think a better alternative might be to use "Web Reference" in stead of "Service Reference" and use the.NET 2.0 stack instead. | WCF, ASP.NET Membership Provider and Authentication Service I have written a Silverlight 2 application communicating with a WCF service (BasicHttpBinding). The site hosting the Silverlight content is protected using a ASP.NET Membership Provider. I can access the current user using HttpContext.Current.User.Identity.Name from my WCF service, and I have turned on AspNetCompatibilityRequirementsMode. I now want to write a Windows application using the exact same web service. To handle authentication I have enabled the Authentication service, and can call "login" to authenticate my user... Okey, all good... But how the heck do I get that authentication cookie set on my other service client?! Both services are hosted on the same domain MyDataService.svc <- the one dealing with my data AuthenticationService.svc <- the one the windows app has to call to authenticate. I don't want to create a new service for the windows client, or use another binding... The Client Application Services is another alternative, but all the examples is limited to show how to get the user, roles and his profile... But once we're authenticated using the Client Application Services there should be a way to get that authentication cookie attached to my service clients when calling back to the same server. According to input from colleagues the solution is adding a wsHttpBinding end-point, but I'm hoping I can get around that... | TITLE:
WCF, ASP.NET Membership Provider and Authentication Service
QUESTION:
I have written a Silverlight 2 application communicating with a WCF service (BasicHttpBinding). The site hosting the Silverlight content is protected using a ASP.NET Membership Provider. I can access the current user using HttpContext.Current.User.Identity.Name from my WCF service, and I have turned on AspNetCompatibilityRequirementsMode. I now want to write a Windows application using the exact same web service. To handle authentication I have enabled the Authentication service, and can call "login" to authenticate my user... Okey, all good... But how the heck do I get that authentication cookie set on my other service client?! Both services are hosted on the same domain MyDataService.svc <- the one dealing with my data AuthenticationService.svc <- the one the windows app has to call to authenticate. I don't want to create a new service for the windows client, or use another binding... The Client Application Services is another alternative, but all the examples is limited to show how to get the user, roles and his profile... But once we're authenticated using the Client Application Services there should be a way to get that authentication cookie attached to my service clients when calling back to the same server. According to input from colleagues the solution is adding a wsHttpBinding end-point, but I'm hoping I can get around that...
ANSWER:
I finally found a way to make this work. For authentication I'm using the " WCF Authentication Service ". When authenticating the service will try to set an authentication cookie. I need to get this cookie out of the response, and add it to any other request made to other web services on the same machine. The code to do that looks like this: var authService = new AuthService.AuthenticationServiceClient(); var diveService = new DiveLogService.DiveLogServiceClient();
string cookieHeader = ""; using (OperationContextScope scope = new OperationContextScope(authService.InnerChannel)) { HttpRequestMessageProperty requestProperty = new HttpRequestMessageProperty(); OperationContext.Current.OutgoingMessageProperties[HttpRequestMessageProperty.Name] = requestProperty; bool isGood = authService.Login("jonas", "jonas", string.Empty, true); MessageProperties properties = OperationContext.Current.IncomingMessageProperties; HttpResponseMessageProperty responseProperty = (HttpResponseMessageProperty)properties[HttpResponseMessageProperty.Name]; cookieHeader = responseProperty.Headers[HttpResponseHeader.SetCookie]; }
using (OperationContextScope scope = new OperationContextScope(diveService.InnerChannel)) { HttpRequestMessageProperty httpRequest = new HttpRequestMessageProperty(); OperationContext.Current.OutgoingMessageProperties.Add(HttpRequestMessageProperty.Name, httpRequest); httpRequest.Headers.Add(HttpRequestHeader.Cookie, cookieHeader); var res = diveService.GetDives(); } As you can see I have two service clients, one fo the authentication service, and one for the service I'm actually going to use. The first block will call the Login method, and grab the authentication cookie out of the response. The second block will add the header to the request before calling the "GetDives" service method. I'm not happy with this code at all, and I think a better alternative might be to use "Web Reference" in stead of "Service Reference" and use the.NET 2.0 stack instead. | [
".net",
"wcf",
"web-services"
] | 13 | 5 | 22,038 | 6 | 0 | 2008-09-11T09:18:49.503000 | 2008-09-11T21:59:47.800000 |
56,118 | 57,362 | Triangle Trigonometry (ActionScript 3) | I am trying to write a formula in ActionScript 3 that will give me var "z" (please see image below) in degrees, which I will then convert to radians. I will already know the value of vars "x" and "y". Using trigonometry, how can I calculate the length of the hypotenuse and therefore the variable angle of var z? A solution in either AS3 or psuedocode would be very helpful. Thanks. | What you need is this: var h:Number = Math.sqrt(x*x + y*y); var z:Number = Math.atan2(y, x); That should give you the angle in radians, you might need to swap x/y and possibly add or remove 90 degrees but it should do the trick! (Note that you don't even need h to get z when you're using atan2) I use multiplication instead of Math.pow() just because Math is pretty slow, you can do: var h:Number = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); And it should be exactly the same. | Triangle Trigonometry (ActionScript 3) I am trying to write a formula in ActionScript 3 that will give me var "z" (please see image below) in degrees, which I will then convert to radians. I will already know the value of vars "x" and "y". Using trigonometry, how can I calculate the length of the hypotenuse and therefore the variable angle of var z? A solution in either AS3 or psuedocode would be very helpful. Thanks. | TITLE:
Triangle Trigonometry (ActionScript 3)
QUESTION:
I am trying to write a formula in ActionScript 3 that will give me var "z" (please see image below) in degrees, which I will then convert to radians. I will already know the value of vars "x" and "y". Using trigonometry, how can I calculate the length of the hypotenuse and therefore the variable angle of var z? A solution in either AS3 or psuedocode would be very helpful. Thanks.
ANSWER:
What you need is this: var h:Number = Math.sqrt(x*x + y*y); var z:Number = Math.atan2(y, x); That should give you the angle in radians, you might need to swap x/y and possibly add or remove 90 degrees but it should do the trick! (Note that you don't even need h to get z when you're using atan2) I use multiplication instead of Math.pow() just because Math is pretty slow, you can do: var h:Number = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); And it should be exactly the same. | [
"actionscript-3",
"trigonometry",
"hypotenuse"
] | 7 | 6 | 8,939 | 4 | 0 | 2008-09-11T09:22:45.187000 | 2008-09-11T19:08:16.997000 |
56,121 | 56,135 | IPC Mechanisms in C# - Usage and Best Practices | I have used IPC in Win32 code a while ago - critical sections, events, and semaphores. How is the scene in the.NET environment? Are there any tutorial explaining all available options and when to use and why? | Most recent Microsoft's stuff in IPC is Windows Communication Foundation. Actually there is nothing new in the lower level (tcp, upd, named pipes etc) But WCF simplifies IPC development greatly. Useful resource: Interprocess Communication with WCF on Dr. Dobb's portal WCF Communication Options in the.NET Framework 3.5 and of course MSDN on WCF | IPC Mechanisms in C# - Usage and Best Practices I have used IPC in Win32 code a while ago - critical sections, events, and semaphores. How is the scene in the.NET environment? Are there any tutorial explaining all available options and when to use and why? | TITLE:
IPC Mechanisms in C# - Usage and Best Practices
QUESTION:
I have used IPC in Win32 code a while ago - critical sections, events, and semaphores. How is the scene in the.NET environment? Are there any tutorial explaining all available options and when to use and why?
ANSWER:
Most recent Microsoft's stuff in IPC is Windows Communication Foundation. Actually there is nothing new in the lower level (tcp, upd, named pipes etc) But WCF simplifies IPC development greatly. Useful resource: Interprocess Communication with WCF on Dr. Dobb's portal WCF Communication Options in the.NET Framework 3.5 and of course MSDN on WCF | [
"c#",
".net",
"ipc"
] | 56 | 31 | 84,988 | 6 | 0 | 2008-09-11T09:24:22.873000 | 2008-09-11T09:34:50.150000 |
56,124 | 56,198 | Can I run a 64-bit VMware image on a 32-bit machine? | Can I run a 64-bit VMware image on a 32-bit machine? I've googled this, but there doesn't seem to be a conclusive answer. I know that it would have to be completely emulated and would run like a dog - but slow performance isn't necessarily an issue as I'm just interested in testing some of my background services code on 64-bit platforms. | The easiest way to check your workstation is to download the VMware Processor Check for 64-Bit Compatibility tool from the VMware website. You can't run a 64-bit VM session on a 32-bit processor. However, you can run a 64-bit VM session if you have a 64-bit processor but have installed a 32-bit host OS and your processor supports the right extensions. The tool linked above will tell you if yours does. | Can I run a 64-bit VMware image on a 32-bit machine? Can I run a 64-bit VMware image on a 32-bit machine? I've googled this, but there doesn't seem to be a conclusive answer. I know that it would have to be completely emulated and would run like a dog - but slow performance isn't necessarily an issue as I'm just interested in testing some of my background services code on 64-bit platforms. | TITLE:
Can I run a 64-bit VMware image on a 32-bit machine?
QUESTION:
Can I run a 64-bit VMware image on a 32-bit machine? I've googled this, but there doesn't seem to be a conclusive answer. I know that it would have to be completely emulated and would run like a dog - but slow performance isn't necessarily an issue as I'm just interested in testing some of my background services code on 64-bit platforms.
ANSWER:
The easiest way to check your workstation is to download the VMware Processor Check for 64-Bit Compatibility tool from the VMware website. You can't run a 64-bit VM session on a 32-bit processor. However, you can run a 64-bit VM session if you have a 64-bit processor but have installed a 32-bit host OS and your processor supports the right extensions. The tool linked above will tell you if yours does. | [
"64-bit",
"vmware",
"virtualization",
"virtual-machine"
] | 90 | 124 | 218,623 | 10 | 0 | 2008-09-11T09:26:25.240000 | 2008-09-11T10:10:18.677000 |
56,145 | 87,399 | MFC IE embedded web browser wackiness | I have this modeless MFC dialog which embeds an Internet Explorer web browser control. The control is derived straight from CWnd with ActiveX wrappers generated by Visual Studio, and I map it to the CDialog using only a DDX_Control(pDX, IDC_EXPLORER, m_explorer);. I have 2 problems. Problem #1: Being modeless, I start and stop the dialog at my own pleasure using new/Create(), then DestroyWindow()/delete(in PostNcDestroy). Trouble begins when the IE control starts loading a Flash video (regular YouTube stuff): when one closes, thus destroying the dialog, the video still loads! Right until fully cached. The Flash ActiveX thread still lingers and continues to run even when the parent dialog has passed PostNcDestroy and all memory was freed. What to do? How do you trully 'kill' that child web control and all its threads? Problem #2: The web browser control covers the whole area of the dialog. I cannot intercept any OnMouseMove() - in the parent dialog or in the web browser mapping class! What gives? Thanks! "Cleanup" "delete this" in PostNcDestroy() - and calling the base func of course. Should it be more? What? Shouldn't the dialog gracefully take care of its children? I tried to explicitly call DestroyWindow on the web control, or send/post him messages like WM_DESTROY, WM_CLOSE, even WM_QUIT - but nothing - same deal. Problem #2: No, like indented, the control takes all space and it's on top so I guess any mouse action doesn't get transmitted 'bellow':)? But then why doesn't his own OnMouseMove get called? Because it goes straight from CWnd? I'm lost... | problem 1) try myBrowser.navigate("about:blank") before destroying the window. | MFC IE embedded web browser wackiness I have this modeless MFC dialog which embeds an Internet Explorer web browser control. The control is derived straight from CWnd with ActiveX wrappers generated by Visual Studio, and I map it to the CDialog using only a DDX_Control(pDX, IDC_EXPLORER, m_explorer);. I have 2 problems. Problem #1: Being modeless, I start and stop the dialog at my own pleasure using new/Create(), then DestroyWindow()/delete(in PostNcDestroy). Trouble begins when the IE control starts loading a Flash video (regular YouTube stuff): when one closes, thus destroying the dialog, the video still loads! Right until fully cached. The Flash ActiveX thread still lingers and continues to run even when the parent dialog has passed PostNcDestroy and all memory was freed. What to do? How do you trully 'kill' that child web control and all its threads? Problem #2: The web browser control covers the whole area of the dialog. I cannot intercept any OnMouseMove() - in the parent dialog or in the web browser mapping class! What gives? Thanks! "Cleanup" "delete this" in PostNcDestroy() - and calling the base func of course. Should it be more? What? Shouldn't the dialog gracefully take care of its children? I tried to explicitly call DestroyWindow on the web control, or send/post him messages like WM_DESTROY, WM_CLOSE, even WM_QUIT - but nothing - same deal. Problem #2: No, like indented, the control takes all space and it's on top so I guess any mouse action doesn't get transmitted 'bellow':)? But then why doesn't his own OnMouseMove get called? Because it goes straight from CWnd? I'm lost... | TITLE:
MFC IE embedded web browser wackiness
QUESTION:
I have this modeless MFC dialog which embeds an Internet Explorer web browser control. The control is derived straight from CWnd with ActiveX wrappers generated by Visual Studio, and I map it to the CDialog using only a DDX_Control(pDX, IDC_EXPLORER, m_explorer);. I have 2 problems. Problem #1: Being modeless, I start and stop the dialog at my own pleasure using new/Create(), then DestroyWindow()/delete(in PostNcDestroy). Trouble begins when the IE control starts loading a Flash video (regular YouTube stuff): when one closes, thus destroying the dialog, the video still loads! Right until fully cached. The Flash ActiveX thread still lingers and continues to run even when the parent dialog has passed PostNcDestroy and all memory was freed. What to do? How do you trully 'kill' that child web control and all its threads? Problem #2: The web browser control covers the whole area of the dialog. I cannot intercept any OnMouseMove() - in the parent dialog or in the web browser mapping class! What gives? Thanks! "Cleanup" "delete this" in PostNcDestroy() - and calling the base func of course. Should it be more? What? Shouldn't the dialog gracefully take care of its children? I tried to explicitly call DestroyWindow on the web control, or send/post him messages like WM_DESTROY, WM_CLOSE, even WM_QUIT - but nothing - same deal. Problem #2: No, like indented, the control takes all space and it's on top so I guess any mouse action doesn't get transmitted 'bellow':)? But then why doesn't his own OnMouseMove get called? Because it goes straight from CWnd? I'm lost...
ANSWER:
problem 1) try myBrowser.navigate("about:blank") before destroying the window. | [
"c++",
"internet-explorer",
"mfc",
"dialog"
] | 5 | 3 | 3,063 | 1 | 0 | 2008-09-11T09:41:53.720000 | 2008-09-17T20:38:17.133000 |
56,149 | 56,212 | Storing file permissions in Subversion repository | How do you store file permissions in a repository? A few files need to be read-only to stop a third party program from trashing it but after checking out of the repository they are set to read-write. I looked on google and found a blog post from 2005 that states that Subversion doesn't store file-permissions. There are patches and hook-scripts listed (only one url still exists). Three years later does Subversion still not store file permissions and are hooks the only way to go about this? (I've never done hooks and rather use something that is native to Subversion.) | One possible solution would be to write a script that you check in with the rest of your code and which is run as the first step of your build process. This script runs through your copy of the codebase and sets read permissions on certain files. Ideally the script would read the list of files from a simple input file. This would make it easy to maintain and easy for other developers to understand which files get marked as read-only. | Storing file permissions in Subversion repository How do you store file permissions in a repository? A few files need to be read-only to stop a third party program from trashing it but after checking out of the repository they are set to read-write. I looked on google and found a blog post from 2005 that states that Subversion doesn't store file-permissions. There are patches and hook-scripts listed (only one url still exists). Three years later does Subversion still not store file permissions and are hooks the only way to go about this? (I've never done hooks and rather use something that is native to Subversion.) | TITLE:
Storing file permissions in Subversion repository
QUESTION:
How do you store file permissions in a repository? A few files need to be read-only to stop a third party program from trashing it but after checking out of the repository they are set to read-write. I looked on google and found a blog post from 2005 that states that Subversion doesn't store file-permissions. There are patches and hook-scripts listed (only one url still exists). Three years later does Subversion still not store file permissions and are hooks the only way to go about this? (I've never done hooks and rather use something that is native to Subversion.)
ANSWER:
One possible solution would be to write a script that you check in with the rest of your code and which is run as the first step of your build process. This script runs through your copy of the codebase and sets read permissions on certain files. Ideally the script would read the list of files from a simple input file. This would make it easy to maintain and easy for other developers to understand which files get marked as read-only. | [
"windows",
"svn",
"file-permissions"
] | 41 | 11 | 37,134 | 12 | 0 | 2008-09-11T09:45:37.613000 | 2008-09-11T10:23:29.503000 |
56,224 | 56,299 | Creating objects driven by the database to populate a Treeview - very slow | I have an application that reads a table from a database. I issue an SQL query to get a result set, based on a unique string value I glean from the results, I use a case/switch statement to generate certain objects (they inherit TreeNode BTW). These created objects get shunted into a Dictionary object to be used later. Whilst generating these objects I use some of the values from the result set to populate values in the object via the setters. I query the Dictionary to return a particular object type and use it to populate a treeview. However it is not possible to populate 2 objects of the same type in a treeview from the Dictionary object (you get a runtime error - which escapes me at the moment, something to with referencing the same object). So what I have to do is use a memberwiseClone and implement IClonable to get around this. Am I doing this right? Is there a better way - because I think this is causing my program to be real slow at this point. At the very least I think its a bit clunky - any advice from people who know more than me - greatly appreciated. | To add to @ Brad, only populate the tree as needed. That means hooking into the expand event of the tree nodes. This is similar to how Windows Explorer functions when dealing with network shares. There should be 1 TreeNode object per actual tree node in the tree - don't try to reuse the things. You may either associate them with your data using the Tag property (this is the recommended method), or you can subclass the TreeNode itself (this is the Java method, but used less in.NET). (The use of cloning methods is usually a hint that you're either (a) doing something wrong, or (b) need to factor your domain model to separate mutable objects from immutable.) | Creating objects driven by the database to populate a Treeview - very slow I have an application that reads a table from a database. I issue an SQL query to get a result set, based on a unique string value I glean from the results, I use a case/switch statement to generate certain objects (they inherit TreeNode BTW). These created objects get shunted into a Dictionary object to be used later. Whilst generating these objects I use some of the values from the result set to populate values in the object via the setters. I query the Dictionary to return a particular object type and use it to populate a treeview. However it is not possible to populate 2 objects of the same type in a treeview from the Dictionary object (you get a runtime error - which escapes me at the moment, something to with referencing the same object). So what I have to do is use a memberwiseClone and implement IClonable to get around this. Am I doing this right? Is there a better way - because I think this is causing my program to be real slow at this point. At the very least I think its a bit clunky - any advice from people who know more than me - greatly appreciated. | TITLE:
Creating objects driven by the database to populate a Treeview - very slow
QUESTION:
I have an application that reads a table from a database. I issue an SQL query to get a result set, based on a unique string value I glean from the results, I use a case/switch statement to generate certain objects (they inherit TreeNode BTW). These created objects get shunted into a Dictionary object to be used later. Whilst generating these objects I use some of the values from the result set to populate values in the object via the setters. I query the Dictionary to return a particular object type and use it to populate a treeview. However it is not possible to populate 2 objects of the same type in a treeview from the Dictionary object (you get a runtime error - which escapes me at the moment, something to with referencing the same object). So what I have to do is use a memberwiseClone and implement IClonable to get around this. Am I doing this right? Is there a better way - because I think this is causing my program to be real slow at this point. At the very least I think its a bit clunky - any advice from people who know more than me - greatly appreciated.
ANSWER:
To add to @ Brad, only populate the tree as needed. That means hooking into the expand event of the tree nodes. This is similar to how Windows Explorer functions when dealing with network shares. There should be 1 TreeNode object per actual tree node in the tree - don't try to reuse the things. You may either associate them with your data using the Tag property (this is the recommended method), or you can subclass the TreeNode itself (this is the Java method, but used less in.NET). (The use of cloning methods is usually a hint that you're either (a) doing something wrong, or (b) need to factor your domain model to separate mutable objects from immutable.) | [
"c#",
"dictionary",
"object",
"clone",
"icloneable"
] | 2 | 1 | 1,062 | 3 | 0 | 2008-09-11T10:33:54.173000 | 2008-09-11T11:25:28.933000 |
56,227 | 56,240 | How do you determine the latest SVN revision number rooted in a directory? | I would like to start tagging my deployed binaries with the latest SVN revision number. However, because SVN is file-based and not directory/project-based, I need to scan through all the directory's and subdirectory's files in order to determine the highest revision number. Using svn info on the root doesn't work (it just reports the version of that directory, not files in subdirectories): I was wondering if there is a shortcut using the svn command to do this. Otherwise, can anyone suggest a simple script that is network-efficient (I would prefer if it didn't hit the remote server at all)? I also understand that one alternative approach is to keep a version file with the svn:keywords. This works (I've used it on other projects), but I get tired of dealing with making sure the file is dirty and dealing with the inevitable merge conflicts. Answer I see my problem lied with not doing a proper svn up before calling svn info in the root directory: $ svn info Path:.... Last Changed Author: fak Last Changed Rev: 713 Last Changed Date: 2008-08-29 00:40:53 +0300 (Fri, 29 Aug 2008)
$ svn up At revision 721.
$ svn info Path:.... Revision: 721 Last Changed Author: reuben Last Changed Rev: 721 Last Changed Date: 2008-08-31 22:55:22 +0300 (Sun, 31 Aug 2008) | One way. When you check out the code, look at the last line of svn output: $ svn up...stuff... Updated to revision 66593. A more direct way: $ svn info Path:. URL: https://svn.example.com/svn/myproject/trunk Repository Root: https://svn.example.com/svn/ Repository UUID: d2a7a951-c712-0410-832a-9abccabd3052 Revision: 66593 Node Kind: directory Schedule: normal Last Changed Author: bnguyen Last Changed Rev: 66591 Last Changed Date: 2008-09-11 18:25:27 +1000 (Thu, 11 Sep 2008) | How do you determine the latest SVN revision number rooted in a directory? I would like to start tagging my deployed binaries with the latest SVN revision number. However, because SVN is file-based and not directory/project-based, I need to scan through all the directory's and subdirectory's files in order to determine the highest revision number. Using svn info on the root doesn't work (it just reports the version of that directory, not files in subdirectories): I was wondering if there is a shortcut using the svn command to do this. Otherwise, can anyone suggest a simple script that is network-efficient (I would prefer if it didn't hit the remote server at all)? I also understand that one alternative approach is to keep a version file with the svn:keywords. This works (I've used it on other projects), but I get tired of dealing with making sure the file is dirty and dealing with the inevitable merge conflicts. Answer I see my problem lied with not doing a proper svn up before calling svn info in the root directory: $ svn info Path:.... Last Changed Author: fak Last Changed Rev: 713 Last Changed Date: 2008-08-29 00:40:53 +0300 (Fri, 29 Aug 2008)
$ svn up At revision 721.
$ svn info Path:.... Revision: 721 Last Changed Author: reuben Last Changed Rev: 721 Last Changed Date: 2008-08-31 22:55:22 +0300 (Sun, 31 Aug 2008) | TITLE:
How do you determine the latest SVN revision number rooted in a directory?
QUESTION:
I would like to start tagging my deployed binaries with the latest SVN revision number. However, because SVN is file-based and not directory/project-based, I need to scan through all the directory's and subdirectory's files in order to determine the highest revision number. Using svn info on the root doesn't work (it just reports the version of that directory, not files in subdirectories): I was wondering if there is a shortcut using the svn command to do this. Otherwise, can anyone suggest a simple script that is network-efficient (I would prefer if it didn't hit the remote server at all)? I also understand that one alternative approach is to keep a version file with the svn:keywords. This works (I've used it on other projects), but I get tired of dealing with making sure the file is dirty and dealing with the inevitable merge conflicts. Answer I see my problem lied with not doing a proper svn up before calling svn info in the root directory: $ svn info Path:.... Last Changed Author: fak Last Changed Rev: 713 Last Changed Date: 2008-08-29 00:40:53 +0300 (Fri, 29 Aug 2008)
$ svn up At revision 721.
$ svn info Path:.... Revision: 721 Last Changed Author: reuben Last Changed Rev: 721 Last Changed Date: 2008-08-31 22:55:22 +0300 (Sun, 31 Aug 2008)
ANSWER:
One way. When you check out the code, look at the last line of svn output: $ svn up...stuff... Updated to revision 66593. A more direct way: $ svn info Path:. URL: https://svn.example.com/svn/myproject/trunk Repository Root: https://svn.example.com/svn/ Repository UUID: d2a7a951-c712-0410-832a-9abccabd3052 Revision: 66593 Node Kind: directory Schedule: normal Last Changed Author: bnguyen Last Changed Rev: 66591 Last Changed Date: 2008-09-11 18:25:27 +1000 (Thu, 11 Sep 2008) | [
"svn",
"build-automation"
] | 36 | 25 | 47,971 | 10 | 0 | 2008-09-11T10:35:02.767000 | 2008-09-11T10:43:00.050000 |
56,229 | 56,470 | XML writing tools for Python | I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of? This is similar to what I'm actually doing: import xml.etree.ElementTree as ET root = ET.Element('html') head = ET.SubElement(root,'head') script = ET.SubElement(head,'script') script.set('type','text/javascript') script.text = "var a = 'I love á letters'" body = ET.SubElement(root,'body') h1 = ET.SubElement(body,'h1') h1.text = "And I like the fact that 3 > 1" tree = ET.ElementTree(root) tree.write('foo.xhtml')
# more foo.xhtml And I like the fact that 3 > 1 | I assume that you're actually creating an XML DOM tree, because you want to validate that what goes into this file is valid XML, since otherwise you'd just write a static string to a file. If validating your output is indeed your goal, then I'd suggest from xml.dom.minidom import parseString
doc = parseString(""" And I like the fact that 3 > 1 """)
with open("foo.xhtml", "w") as f: f.write( doc.toxml() ) This lets you just write the XML you want to output, validate that it's correct (since parseString will raise an exception if it's invalid) and have your code look much nicer. Presumably you're not just writing the same static XML every time and want some substitution. In this case I'd have lines like var a = '%(message)s' and then use the % operator to do the substitution, like """ % {"message": "I love á letters"}) | XML writing tools for Python I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of? This is similar to what I'm actually doing: import xml.etree.ElementTree as ET root = ET.Element('html') head = ET.SubElement(root,'head') script = ET.SubElement(head,'script') script.set('type','text/javascript') script.text = "var a = 'I love á letters'" body = ET.SubElement(root,'body') h1 = ET.SubElement(body,'h1') h1.text = "And I like the fact that 3 > 1" tree = ET.ElementTree(root) tree.write('foo.xhtml')
# more foo.xhtml And I like the fact that 3 > 1 | TITLE:
XML writing tools for Python
QUESTION:
I'm currently trying ElementTree and it looks fine, it escapes HTML entities and so on and so forth. Am I missing something truly wonderful I haven't heard of? This is similar to what I'm actually doing: import xml.etree.ElementTree as ET root = ET.Element('html') head = ET.SubElement(root,'head') script = ET.SubElement(head,'script') script.set('type','text/javascript') script.text = "var a = 'I love á letters'" body = ET.SubElement(root,'body') h1 = ET.SubElement(body,'h1') h1.text = "And I like the fact that 3 > 1" tree = ET.ElementTree(root) tree.write('foo.xhtml')
# more foo.xhtml And I like the fact that 3 > 1
ANSWER:
I assume that you're actually creating an XML DOM tree, because you want to validate that what goes into this file is valid XML, since otherwise you'd just write a static string to a file. If validating your output is indeed your goal, then I'd suggest from xml.dom.minidom import parseString
doc = parseString(""" And I like the fact that 3 > 1 """)
with open("foo.xhtml", "w") as f: f.write( doc.toxml() ) This lets you just write the XML you want to output, validate that it's correct (since parseString will raise an exception if it's invalid) and have your code look much nicer. Presumably you're not just writing the same static XML every time and want some substitution. In this case I'd have lines like var a = '%(message)s' and then use the % operator to do the substitution, like """ % {"message": "I love á letters"}) | [
"python",
"xml",
"xhtml"
] | 35 | 10 | 39,057 | 8 | 0 | 2008-09-11T10:35:37.163000 | 2008-09-11T12:53:06.977000 |
56,249 | 56,286 | WCF service configuration file question regarding <baseAddresses> | From what I've seen the tag is ignored when hosting a WCF service in IIS. I understand that when self-hosting this is required but is this harmful or even used when operating under IIS? ex. From what I've seen you can take a config file describing a service from one machine and use that on a completely different machine and it works fine. It looks as if IIS completely ignores this section. Thanks, kyle | As you have guessed, the baseAddresses element is completely ignored when hosting in IIS. The service's base address is determined by the web site & virtual directory into which your wcf service is placed. Even when self-hosting, baseAddresses is not required. It is merely a convenience that avoids you having to enter a full address for each endpoint. If it is present, the endpoints can have relative addresses (relative to the base address, that is). | WCF service configuration file question regarding <baseAddresses> From what I've seen the tag is ignored when hosting a WCF service in IIS. I understand that when self-hosting this is required but is this harmful or even used when operating under IIS? ex. From what I've seen you can take a config file describing a service from one machine and use that on a completely different machine and it works fine. It looks as if IIS completely ignores this section. Thanks, kyle | TITLE:
WCF service configuration file question regarding <baseAddresses>
QUESTION:
From what I've seen the tag is ignored when hosting a WCF service in IIS. I understand that when self-hosting this is required but is this harmful or even used when operating under IIS? ex. From what I've seen you can take a config file describing a service from one machine and use that on a completely different machine and it works fine. It looks as if IIS completely ignores this section. Thanks, kyle
ANSWER:
As you have guessed, the baseAddresses element is completely ignored when hosting in IIS. The service's base address is determined by the web site & virtual directory into which your wcf service is placed. Even when self-hosting, baseAddresses is not required. It is merely a convenience that avoids you having to enter a full address for each endpoint. If it is present, the endpoints can have relative addresses (relative to the base address, that is). | [
"wcf",
"configuration",
"configuration-files"
] | 19 | 35 | 26,959 | 3 | 0 | 2008-09-11T10:49:46.677000 | 2008-09-11T11:21:15.870000 |
56,256 | 56,301 | Converting a .rptproj from VS2005 to VS2008 | I've got my brand new VS2008 and decided to convert my main solution from VS2005. One of the projects is a SQL2005 reporting services project. Now that I've converted I cannot load it in VS2008. Is there anyway around this? My problem is that my solution is a hybrid and has websites libraries and reports in there. Separating it out breaks the logic the solution entity. | Visual Studio 2008 does not support the 2005 business intelligence projects, so if you have not done so already don't uninstall 2005 Business Intelligence! You can continue to maintain those projects independently in VS2005. SQL Server 2008 Business Intelligence will integrate with VS2008 so you will require that and an upgrade to your existing reporting project to use in VS2008. | Converting a .rptproj from VS2005 to VS2008 I've got my brand new VS2008 and decided to convert my main solution from VS2005. One of the projects is a SQL2005 reporting services project. Now that I've converted I cannot load it in VS2008. Is there anyway around this? My problem is that my solution is a hybrid and has websites libraries and reports in there. Separating it out breaks the logic the solution entity. | TITLE:
Converting a .rptproj from VS2005 to VS2008
QUESTION:
I've got my brand new VS2008 and decided to convert my main solution from VS2005. One of the projects is a SQL2005 reporting services project. Now that I've converted I cannot load it in VS2008. Is there anyway around this? My problem is that my solution is a hybrid and has websites libraries and reports in there. Separating it out breaks the logic the solution entity.
ANSWER:
Visual Studio 2008 does not support the 2005 business intelligence projects, so if you have not done so already don't uninstall 2005 Business Intelligence! You can continue to maintain those projects independently in VS2005. SQL Server 2008 Business Intelligence will integrate with VS2008 so you will require that and an upgrade to your existing reporting project to use in VS2008. | [
"visual-studio-2008",
"reporting-services"
] | 6 | 1 | 4,426 | 2 | 0 | 2008-09-11T10:53:15.813000 | 2008-09-11T11:27:17.743000 |
56,266 | 56,366 | Using Silverlight for an entire website? | We need to build an administration portal website to support our client/server application. Since we're a.Net shop the obvious traditional way would be to do that in ASP.Net. But Silverlight 2 will be coming out of beta a good while before our release date. Should we consider building the whole website in silverlight instead, with a supporting WCF backend? The main function of the portal will be: users, groups and permissions configuration; user profile settings configuration; file upload and download for files needed to support the application. I think the main reason for taking this approach would be that we have good experience with WPF and WCF, but little experience in ASP.Net. Either way we would have to learn ASP.Net or Silverlight, and learning Silverlight seems a more natural extension of our current skills. Are there any big no-nos from the experience of StackOverflowers? What are the big positives? | Depends on your goals. If administration portal is part of application and will only be used from computers where your application is installed, there are plenty of advantages of going fully Silverlight - or even WPF. But if you can see a scenario where it will be used either from random PC or by random person, fully functional HTML/Javascript version is absolutely necessary. Some reasons are: Most people don't have silverlight and you'll earn a good load of swearing if they have to download and install it. Some people who have it installed keep it disabled (together with flash and sometimes even images) to avoid distractions and speed up browsing. When HTML site fails, user gets error page and reloads. When silverlight fails, it can hang or crash. HTML is what is expected - both by users and web browsers: back and refresh buttons work as they should, hyperlinks and forms work as expected. Slow internet is still very common, both in remote areas and mobile devices. | Using Silverlight for an entire website? We need to build an administration portal website to support our client/server application. Since we're a.Net shop the obvious traditional way would be to do that in ASP.Net. But Silverlight 2 will be coming out of beta a good while before our release date. Should we consider building the whole website in silverlight instead, with a supporting WCF backend? The main function of the portal will be: users, groups and permissions configuration; user profile settings configuration; file upload and download for files needed to support the application. I think the main reason for taking this approach would be that we have good experience with WPF and WCF, but little experience in ASP.Net. Either way we would have to learn ASP.Net or Silverlight, and learning Silverlight seems a more natural extension of our current skills. Are there any big no-nos from the experience of StackOverflowers? What are the big positives? | TITLE:
Using Silverlight for an entire website?
QUESTION:
We need to build an administration portal website to support our client/server application. Since we're a.Net shop the obvious traditional way would be to do that in ASP.Net. But Silverlight 2 will be coming out of beta a good while before our release date. Should we consider building the whole website in silverlight instead, with a supporting WCF backend? The main function of the portal will be: users, groups and permissions configuration; user profile settings configuration; file upload and download for files needed to support the application. I think the main reason for taking this approach would be that we have good experience with WPF and WCF, but little experience in ASP.Net. Either way we would have to learn ASP.Net or Silverlight, and learning Silverlight seems a more natural extension of our current skills. Are there any big no-nos from the experience of StackOverflowers? What are the big positives?
ANSWER:
Depends on your goals. If administration portal is part of application and will only be used from computers where your application is installed, there are plenty of advantages of going fully Silverlight - or even WPF. But if you can see a scenario where it will be used either from random PC or by random person, fully functional HTML/Javascript version is absolutely necessary. Some reasons are: Most people don't have silverlight and you'll earn a good load of swearing if they have to download and install it. Some people who have it installed keep it disabled (together with flash and sometimes even images) to avoid distractions and speed up browsing. When HTML site fails, user gets error page and reloads. When silverlight fails, it can hang or crash. HTML is what is expected - both by users and web browsers: back and refresh buttons work as they should, hyperlinks and forms work as expected. Slow internet is still very common, both in remote areas and mobile devices. | [
"asp.net",
"silverlight",
"architecture"
] | 10 | 9 | 9,523 | 12 | 0 | 2008-09-11T10:59:08.590000 | 2008-09-11T12:01:41.827000 |
56,271 | 57,040 | Context.User losing Roles after being assigned in Global.asax.Application_AuthenticateRequest | I am using Forms authentication in my asp.net (3.5) application. I am also using roles to define what user can access which subdirectories of the app. Thus, the pertinent sections of my web.config file look like this: Based on what I have read, this should ensure that the only users able to access the Admin directory will be users who have been Authenticated and assigned the Admin role. User authentication, saving the authentication ticket, and other related issues all work fine. If I remove the tags from the web.config file, everything works fine. The problem comes when I try to enforce that only users with the Admin role should be able to access the Admin directory. Based on this MS KB article along with other webpages giving the same information, I have added the following code to my Global.asax file: protected void Application_AuthenticateRequest(Object sender, EventArgs e) { if (HttpContext.Current.User!= null) { if (Request.IsAuthenticated == true) { // Debug#1 FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[FormsAuthentication.FormsCookieName].Value); // In this case, ticket.UserData = "Admin" string[] roles = new string[1] { ticket.UserData }; FormsIdentity id = new FormsIdentity(ticket); Context.User = new System.Security.Principal.GenericPrincipal(id, roles); // Debug#2 } } } However, when I try to log in, I am unable to access the Admin folder (get redirected to login page). Trying to debug the issue, if I step through a request, if I execute Context.User.IsInRole("Admin") at the line marked Debug#1 above, it returns a false. If I execute the same statement at line Debug#2, it equals true. So at least as far as Global.asax is concerned, the Role is being assigned properly. After Global.asax, execution jumps right to the Login page (since the lack of role causes the page load in the admin folder to be rejected). However, when I execute the same statement on the first line of Page_Load of the login, it returns false. So somewhere after Application_AuthenticateRequest in Global.asax and the initial load of the WebForm in the restricted directory, the role information is being lost, causing authentication to fail (note: in Page_Load, the proper Authentication ticket is still assigned to Context.User.Id - only the role is being lost). What am I doing wrong, and how can I get it to work properly? Update: I entered the solution below | Here was the problem and solution: Earlier in development I had gone to the Website menu and clicked on Asp.net configuration. This resulted in the following line being added to the web.config: From that point on, the app was assuming that I was doing roles through the Asp.net site manager, and not through FormsAuthentication roles. Thus the repeated failures, despite the fact that the actual authentication and roles logic was set up correctly. After this line was removed from web.config everything worked perfectly. | Context.User losing Roles after being assigned in Global.asax.Application_AuthenticateRequest I am using Forms authentication in my asp.net (3.5) application. I am also using roles to define what user can access which subdirectories of the app. Thus, the pertinent sections of my web.config file look like this: Based on what I have read, this should ensure that the only users able to access the Admin directory will be users who have been Authenticated and assigned the Admin role. User authentication, saving the authentication ticket, and other related issues all work fine. If I remove the tags from the web.config file, everything works fine. The problem comes when I try to enforce that only users with the Admin role should be able to access the Admin directory. Based on this MS KB article along with other webpages giving the same information, I have added the following code to my Global.asax file: protected void Application_AuthenticateRequest(Object sender, EventArgs e) { if (HttpContext.Current.User!= null) { if (Request.IsAuthenticated == true) { // Debug#1 FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[FormsAuthentication.FormsCookieName].Value); // In this case, ticket.UserData = "Admin" string[] roles = new string[1] { ticket.UserData }; FormsIdentity id = new FormsIdentity(ticket); Context.User = new System.Security.Principal.GenericPrincipal(id, roles); // Debug#2 } } } However, when I try to log in, I am unable to access the Admin folder (get redirected to login page). Trying to debug the issue, if I step through a request, if I execute Context.User.IsInRole("Admin") at the line marked Debug#1 above, it returns a false. If I execute the same statement at line Debug#2, it equals true. So at least as far as Global.asax is concerned, the Role is being assigned properly. After Global.asax, execution jumps right to the Login page (since the lack of role causes the page load in the admin folder to be rejected). However, when I execute the same statement on the first line of Page_Load of the login, it returns false. So somewhere after Application_AuthenticateRequest in Global.asax and the initial load of the WebForm in the restricted directory, the role information is being lost, causing authentication to fail (note: in Page_Load, the proper Authentication ticket is still assigned to Context.User.Id - only the role is being lost). What am I doing wrong, and how can I get it to work properly? Update: I entered the solution below | TITLE:
Context.User losing Roles after being assigned in Global.asax.Application_AuthenticateRequest
QUESTION:
I am using Forms authentication in my asp.net (3.5) application. I am also using roles to define what user can access which subdirectories of the app. Thus, the pertinent sections of my web.config file look like this: Based on what I have read, this should ensure that the only users able to access the Admin directory will be users who have been Authenticated and assigned the Admin role. User authentication, saving the authentication ticket, and other related issues all work fine. If I remove the tags from the web.config file, everything works fine. The problem comes when I try to enforce that only users with the Admin role should be able to access the Admin directory. Based on this MS KB article along with other webpages giving the same information, I have added the following code to my Global.asax file: protected void Application_AuthenticateRequest(Object sender, EventArgs e) { if (HttpContext.Current.User!= null) { if (Request.IsAuthenticated == true) { // Debug#1 FormsAuthenticationTicket ticket = FormsAuthentication.Decrypt(Context.Request.Cookies[FormsAuthentication.FormsCookieName].Value); // In this case, ticket.UserData = "Admin" string[] roles = new string[1] { ticket.UserData }; FormsIdentity id = new FormsIdentity(ticket); Context.User = new System.Security.Principal.GenericPrincipal(id, roles); // Debug#2 } } } However, when I try to log in, I am unable to access the Admin folder (get redirected to login page). Trying to debug the issue, if I step through a request, if I execute Context.User.IsInRole("Admin") at the line marked Debug#1 above, it returns a false. If I execute the same statement at line Debug#2, it equals true. So at least as far as Global.asax is concerned, the Role is being assigned properly. After Global.asax, execution jumps right to the Login page (since the lack of role causes the page load in the admin folder to be rejected). However, when I execute the same statement on the first line of Page_Load of the login, it returns false. So somewhere after Application_AuthenticateRequest in Global.asax and the initial load of the WebForm in the restricted directory, the role information is being lost, causing authentication to fail (note: in Page_Load, the proper Authentication ticket is still assigned to Context.User.Id - only the role is being lost). What am I doing wrong, and how can I get it to work properly? Update: I entered the solution below
ANSWER:
Here was the problem and solution: Earlier in development I had gone to the Website menu and clicked on Asp.net configuration. This resulted in the following line being added to the web.config: From that point on, the app was assuming that I was doing roles through the Asp.net site manager, and not through FormsAuthentication roles. Thus the repeated failures, despite the fact that the actual authentication and roles logic was set up correctly. After this line was removed from web.config everything worked perfectly. | [
"c#",
".net",
"asp.net",
"forms-authentication",
"roles"
] | 3 | 5 | 6,153 | 2 | 0 | 2008-09-11T11:06:31.973000 | 2008-09-11T16:23:11.433000 |
56,279 | 56,281 | Export ASPX to HTML | We're building a CMS. The site will be built and managed by the users in aspx pages, but we would like to create a static site of HTML's. The way we're doing it now is with code I found here that overloads the Render method in the Aspx Page and writes the HTML string to a file. This works fine for a single page, but the thing with our CMS is that we want to automatically create a few HTML pages for a site right from the start, even before the creator has edited anything in the system. Does anyone know of any way to do this? | Calling the Render method is still pretty simple. Just create an instance of your page, create a stub WebContext along with the WebRequest object, and call the Render method of the page. You are then free to do whatever you want with the results. Alternatively, write a little curl or wget script to download and store whichever pages you want to make static. | Export ASPX to HTML We're building a CMS. The site will be built and managed by the users in aspx pages, but we would like to create a static site of HTML's. The way we're doing it now is with code I found here that overloads the Render method in the Aspx Page and writes the HTML string to a file. This works fine for a single page, but the thing with our CMS is that we want to automatically create a few HTML pages for a site right from the start, even before the creator has edited anything in the system. Does anyone know of any way to do this? | TITLE:
Export ASPX to HTML
QUESTION:
We're building a CMS. The site will be built and managed by the users in aspx pages, but we would like to create a static site of HTML's. The way we're doing it now is with code I found here that overloads the Render method in the Aspx Page and writes the HTML string to a file. This works fine for a single page, but the thing with our CMS is that we want to automatically create a few HTML pages for a site right from the start, even before the creator has edited anything in the system. Does anyone know of any way to do this?
ANSWER:
Calling the Render method is still pretty simple. Just create an instance of your page, create a stub WebContext along with the WebRequest object, and call the Render method of the page. You are then free to do whatever you want with the results. Alternatively, write a little curl or wget script to download and store whichever pages you want to make static. | [
"asp.net",
"html",
"screen-scraping"
] | 5 | 2 | 7,522 | 5 | 0 | 2008-09-11T11:15:54.213000 | 2008-09-11T11:18:53.783000 |
56,296 | 56,320 | Can you view an aggregate changeset in git? If so, how? | In Subversion you can specify a range of versions to get an aggregate view of a series of commits. Is this possible in git? If so, how? | You can pass ranges of revisions using the.. (and...) operator. git diff 6d0918...HEAD instead of giving (abbreviated) SHA hashes, you can also denote revisions relative to branches and tags: git diff HEAD~4 # shows the diff from the last four commits to the current one Have a look at the chapter "Specifying Revisions" in the git-rev-parse manual page | Can you view an aggregate changeset in git? If so, how? In Subversion you can specify a range of versions to get an aggregate view of a series of commits. Is this possible in git? If so, how? | TITLE:
Can you view an aggregate changeset in git? If so, how?
QUESTION:
In Subversion you can specify a range of versions to get an aggregate view of a series of commits. Is this possible in git? If so, how?
ANSWER:
You can pass ranges of revisions using the.. (and...) operator. git diff 6d0918...HEAD instead of giving (abbreviated) SHA hashes, you can also denote revisions relative to branches and tags: git diff HEAD~4 # shows the diff from the last four commits to the current one Have a look at the chapter "Specifying Revisions" in the git-rev-parse manual page | [
"git",
"diff"
] | 8 | 9 | 1,118 | 1 | 0 | 2008-09-11T11:24:53.660000 | 2008-09-11T11:37:09.717000 |
56,313 | 56,338 | ReSharper Code Cleanup/Reformat Code feature vs Versioning Control Systems | ReSharper Code cleanup feature (with " reorder members " and " reformat code " enabled) is really great. You define a layout template using XML, then a simple key combination reorganizes your whole source file (or folder/project/solution) according to the rules you set in the template. Anyway, do you think that could be a problem regarding VCS like subversion, cvs, git, etc.? Is there a chance that it causes many undesired conflicts? Thank you. | Yes, it will definitely cause problems. In addition to creating conflicts that have to be manually resolved, when you check in a file that has been reformatted, the VCS will note almost every line as having been changed. This will make it hard for you or a teammate to look back at the history and see what changed when. That said, if everyone autoformats their code the same way (ie, you distribute that XML template to the team), then it might work well. The problems really only come in when not everyone is doing the same thing. | ReSharper Code Cleanup/Reformat Code feature vs Versioning Control Systems ReSharper Code cleanup feature (with " reorder members " and " reformat code " enabled) is really great. You define a layout template using XML, then a simple key combination reorganizes your whole source file (or folder/project/solution) according to the rules you set in the template. Anyway, do you think that could be a problem regarding VCS like subversion, cvs, git, etc.? Is there a chance that it causes many undesired conflicts? Thank you. | TITLE:
ReSharper Code Cleanup/Reformat Code feature vs Versioning Control Systems
QUESTION:
ReSharper Code cleanup feature (with " reorder members " and " reformat code " enabled) is really great. You define a layout template using XML, then a simple key combination reorganizes your whole source file (or folder/project/solution) according to the rules you set in the template. Anyway, do you think that could be a problem regarding VCS like subversion, cvs, git, etc.? Is there a chance that it causes many undesired conflicts? Thank you.
ANSWER:
Yes, it will definitely cause problems. In addition to creating conflicts that have to be manually resolved, when you check in a file that has been reformatted, the VCS will note almost every line as having been changed. This will make it hard for you or a teammate to look back at the history and see what changed when. That said, if everyone autoformats their code the same way (ie, you distribute that XML template to the team), then it might work well. The problems really only come in when not everyone is doing the same thing. | [
"c#",
"version-control",
"resharper"
] | 8 | 16 | 5,628 | 9 | 0 | 2008-09-11T11:32:16.513000 | 2008-09-11T11:44:21.603000 |
56,315 | 73,127 | D Programming Language in the real world? | Is anyone out there using D for real world applications? If so, what are you using it for? I can't seem to find anything big on the web written in D. Despite the lack of known big users, D seems like a very promissing language to me, and according to TIOBE, it's fairly popular. | I'm using D for my research work in the area of computer graphics. I and others have had papers published in our fields based on work done using D. I think it's definitely ready for use on small to medium sized research projects where performance matters. It's a nice fit for research work because often you're starting from scratch anyway, so you don't have much legacy code to worry about integrating with. Another popular area for use seems to be web services. Hopefully someone else can comment who's in this space, but there too I think the idea is that performance often really matters so you want a compiled-to-the-metal language. Services are often fairly small, self-contained processes, so interop with large amounts of legacy C++ code is not really necessary or useful. Thus D can get its foot in the door. I think D will continue to gain grass-roots followers in this way -- on smaller projects that for whatever reason can afford to ditch the C++ legacy in order to gain a programming language that's much more enjoyable to use, and perhaps more productive too. But until there's a huge number of grass-roots users there won't be much in the way of big corporate users I suspect. | D Programming Language in the real world? Is anyone out there using D for real world applications? If so, what are you using it for? I can't seem to find anything big on the web written in D. Despite the lack of known big users, D seems like a very promissing language to me, and according to TIOBE, it's fairly popular. | TITLE:
D Programming Language in the real world?
QUESTION:
Is anyone out there using D for real world applications? If so, what are you using it for? I can't seem to find anything big on the web written in D. Despite the lack of known big users, D seems like a very promissing language to me, and according to TIOBE, it's fairly popular.
ANSWER:
I'm using D for my research work in the area of computer graphics. I and others have had papers published in our fields based on work done using D. I think it's definitely ready for use on small to medium sized research projects where performance matters. It's a nice fit for research work because often you're starting from scratch anyway, so you don't have much legacy code to worry about integrating with. Another popular area for use seems to be web services. Hopefully someone else can comment who's in this space, but there too I think the idea is that performance often really matters so you want a compiled-to-the-metal language. Services are often fairly small, self-contained processes, so interop with large amounts of legacy C++ code is not really necessary or useful. Thus D can get its foot in the door. I think D will continue to gain grass-roots followers in this way -- on smaller projects that for whatever reason can afford to ditch the C++ legacy in order to gain a programming language that's much more enjoyable to use, and perhaps more productive too. But until there's a huge number of grass-roots users there won't be much in the way of big corporate users I suspect. | [
"d"
] | 140 | 77 | 47,221 | 20 | 0 | 2008-09-11T11:33:05.887000 | 2008-09-16T14:46:45.333000 |
56,324 | 56,335 | Reset screen point to the top of screen in Windows & Linux console | I have a little routine that's run under Linux and Windows written in C and displays output on the console. I'm not linking in any form of curses or anything like that. Currently I clear the screen using #ifdef __WIN32 system( "cls" ); #else system( "clear" ); #endif Then I have a bunch of printf statements to update the status. What I'd like just reset the screenpointer to 0,0 so I can then just overlay my printfs. I'd rather avoid compiling in any more extensions especially since I'm coding for 2 different OS'. | Looks like I may have found a windows specific way of doing it SetConsoleCursorPosition Ansi escape sequence \033[0;0H for Linux - just printf that to the console. | Reset screen point to the top of screen in Windows & Linux console I have a little routine that's run under Linux and Windows written in C and displays output on the console. I'm not linking in any form of curses or anything like that. Currently I clear the screen using #ifdef __WIN32 system( "cls" ); #else system( "clear" ); #endif Then I have a bunch of printf statements to update the status. What I'd like just reset the screenpointer to 0,0 so I can then just overlay my printfs. I'd rather avoid compiling in any more extensions especially since I'm coding for 2 different OS'. | TITLE:
Reset screen point to the top of screen in Windows & Linux console
QUESTION:
I have a little routine that's run under Linux and Windows written in C and displays output on the console. I'm not linking in any form of curses or anything like that. Currently I clear the screen using #ifdef __WIN32 system( "cls" ); #else system( "clear" ); #endif Then I have a bunch of printf statements to update the status. What I'd like just reset the screenpointer to 0,0 so I can then just overlay my printfs. I'd rather avoid compiling in any more extensions especially since I'm coding for 2 different OS'.
ANSWER:
Looks like I may have found a windows specific way of doing it SetConsoleCursorPosition Ansi escape sequence \033[0;0H for Linux - just printf that to the console. | [
"c",
"console"
] | 2 | 0 | 1,550 | 4 | 0 | 2008-09-11T11:39:15.030000 | 2008-09-11T11:43:21.650000 |
56,325 | 56,331 | Team System get-latest-version on checkout | We used to use SourceSafe, and one thing I liked about it was that when you checked out a file, it automatically got you its latest version. Now we work with Team System 2005, and it doesn't work that way - you have to "get latest version" before you start working on a file that you've checked out. Is there a way to configure Team System (2005) to automatically get the latest version when checking out a file? | There's a Visual Studio Add-in for this that someone wrote: http://blogs.microsoft.co.il/blogs/srlteam/archive/2007/03/24/TFS-GetLatest-version-on-check_2D00_out-Add_2D00_In.aspx | Team System get-latest-version on checkout We used to use SourceSafe, and one thing I liked about it was that when you checked out a file, it automatically got you its latest version. Now we work with Team System 2005, and it doesn't work that way - you have to "get latest version" before you start working on a file that you've checked out. Is there a way to configure Team System (2005) to automatically get the latest version when checking out a file? | TITLE:
Team System get-latest-version on checkout
QUESTION:
We used to use SourceSafe, and one thing I liked about it was that when you checked out a file, it automatically got you its latest version. Now we work with Team System 2005, and it doesn't work that way - you have to "get latest version" before you start working on a file that you've checked out. Is there a way to configure Team System (2005) to automatically get the latest version when checking out a file?
ANSWER:
There's a Visual Studio Add-in for this that someone wrote: http://blogs.microsoft.co.il/blogs/srlteam/archive/2007/03/24/TFS-GetLatest-version-on-check_2D00_out-Add_2D00_In.aspx | [
"tfs"
] | 5 | 2 | 418 | 3 | 0 | 2008-09-11T11:39:15.780000 | 2008-09-11T11:42:08.457000 |
56,334 | 56,336 | How do I perform a simple one-statement SQL search across tables? | Suppose that two tables exist: users and groups. How does one provide "simple search" in which a user enters text and results contain both users and groups whose names contain the text? The result of the search must distinguish between the two types. | The trick is to combine a UNION with a literal string to determine the type of 'object' returned. In most (?) cases, UNION ALL will be more efficient, and should be used unless duplicates are required in the sub-queries. The following pattern should suffice: SELECT "group" type, name FROM groups WHERE name LIKE "%$text%" UNION ALL SELECT "user" type, name FROM users WHERE name LIKE "%$text%" NOTE: I've added the answer myself, because I came across this problem yesterday, couldn't find a good solution, and used this method. If someone has a better approach, please feel free to add it. | How do I perform a simple one-statement SQL search across tables? Suppose that two tables exist: users and groups. How does one provide "simple search" in which a user enters text and results contain both users and groups whose names contain the text? The result of the search must distinguish between the two types. | TITLE:
How do I perform a simple one-statement SQL search across tables?
QUESTION:
Suppose that two tables exist: users and groups. How does one provide "simple search" in which a user enters text and results contain both users and groups whose names contain the text? The result of the search must distinguish between the two types.
ANSWER:
The trick is to combine a UNION with a literal string to determine the type of 'object' returned. In most (?) cases, UNION ALL will be more efficient, and should be used unless duplicates are required in the sub-queries. The following pattern should suffice: SELECT "group" type, name FROM groups WHERE name LIKE "%$text%" UNION ALL SELECT "user" type, name FROM users WHERE name LIKE "%$text%" NOTE: I've added the answer myself, because I came across this problem yesterday, couldn't find a good solution, and used this method. If someone has a better approach, please feel free to add it. | [
"sql",
"search"
] | 2 | 3 | 1,232 | 4 | 0 | 2008-09-11T11:43:11.853000 | 2008-09-11T11:43:24.227000 |
56,340 | 154,326 | Can I set a data breakpoint in runtime in System C (or in Plain Vanilla C++)? | I have a class in system-C with some data members as such: long double x[8]; I'm initializing it in the construction like this: for (i = 0; i < 8; ++i) { x[i] = 0; } But the first time I use it in my code I have garbage there. Because of the way the system is built I can't connect a debugger easily. Are there any methods to set a data breakpoint in the code so that it tells me where in the code the variables were actually changed, but without hooking up a debugger? | You could try starting a second thread which spins, looking for changes in the variable: #include void *ThreadProc(void *arg) { volatile long double *x = (volatile long double *)arg; while(1) { for(int i = 0; i < 8; i++) { if(x[i]!= 0) { __asm__ __volatile__ ("int 3"); // breakpoint (x86) } }
return 0; // Never reached, but placate the compiler }... pthread_t threadID; pthread_create(&threadID, NULL, ThreadProc, &x[0]); This will raise a SIGTRAP signal to your application whenever any of the x values is not zero. | Can I set a data breakpoint in runtime in System C (or in Plain Vanilla C++)? I have a class in system-C with some data members as such: long double x[8]; I'm initializing it in the construction like this: for (i = 0; i < 8; ++i) { x[i] = 0; } But the first time I use it in my code I have garbage there. Because of the way the system is built I can't connect a debugger easily. Are there any methods to set a data breakpoint in the code so that it tells me where in the code the variables were actually changed, but without hooking up a debugger? | TITLE:
Can I set a data breakpoint in runtime in System C (or in Plain Vanilla C++)?
QUESTION:
I have a class in system-C with some data members as such: long double x[8]; I'm initializing it in the construction like this: for (i = 0; i < 8; ++i) { x[i] = 0; } But the first time I use it in my code I have garbage there. Because of the way the system is built I can't connect a debugger easily. Are there any methods to set a data breakpoint in the code so that it tells me where in the code the variables were actually changed, but without hooking up a debugger?
ANSWER:
You could try starting a second thread which spins, looking for changes in the variable: #include void *ThreadProc(void *arg) { volatile long double *x = (volatile long double *)arg; while(1) { for(int i = 0; i < 8; i++) { if(x[i]!= 0) { __asm__ __volatile__ ("int 3"); // breakpoint (x86) } }
return 0; // Never reached, but placate the compiler }... pthread_t threadID; pthread_create(&threadID, NULL, ThreadProc, &x[0]); This will raise a SIGTRAP signal to your application whenever any of the x values is not zero. | [
"c++",
"linux",
"debugging"
] | 0 | 0 | 1,213 | 3 | 0 | 2008-09-11T11:45:27.230000 | 2008-09-30T18:27:21.453000 |
56,342 | 56,387 | What's the best way of parsing strings? | We've got a scenario that requires us to parse lots of e-mail (plain text), each e-mail 'type' is the result of a script being run against various platforms. Some are tab delimited, some are space delimited, some we simply don't know yet. We'll need to support more 'formats' in the future too. Do we go for a solution using: Regex Simply string searching (using string.IndexOf etc) Lex/ Yacc Other The overall solution will be developed in C# 2.0 (hopefully 3.5) | The three solutions you stated each cover very different needs. Manual parsing (simple text search) is the most flexible and the most adaptable, however, it very quickly becomes a real pain in the ass as the parsing required is more complicated. Regex are a middle ground, and probably your best bet here. They are powerful, yet flexible as you can yourself add more logic from the code that call the different regex. The main drawback would be speed here. Lex/Yacc is really only adapted to very complicated, predictable syntaxes and lacks a lot of post compile flexibility. You can't easily change parser in mid parsing, well actually you can but it's just too heavy and you'd be better using regex instead. I know this is a cliché answer, it all really comes down to what your exact needs are, but from what you said, I would personally probably go with a bag of regex. As an alternative, as Vaibhav poionted out, if you have several different situations that can arise and that you cna easily detect which one is coming, you could make a plugin system that chooses the right algorithm, and those algorithms could all be very different, one using Lex/Yacc in pointy cases and the other using IndexOf and regex for simpler cases. | What's the best way of parsing strings? We've got a scenario that requires us to parse lots of e-mail (plain text), each e-mail 'type' is the result of a script being run against various platforms. Some are tab delimited, some are space delimited, some we simply don't know yet. We'll need to support more 'formats' in the future too. Do we go for a solution using: Regex Simply string searching (using string.IndexOf etc) Lex/ Yacc Other The overall solution will be developed in C# 2.0 (hopefully 3.5) | TITLE:
What's the best way of parsing strings?
QUESTION:
We've got a scenario that requires us to parse lots of e-mail (plain text), each e-mail 'type' is the result of a script being run against various platforms. Some are tab delimited, some are space delimited, some we simply don't know yet. We'll need to support more 'formats' in the future too. Do we go for a solution using: Regex Simply string searching (using string.IndexOf etc) Lex/ Yacc Other The overall solution will be developed in C# 2.0 (hopefully 3.5)
ANSWER:
The three solutions you stated each cover very different needs. Manual parsing (simple text search) is the most flexible and the most adaptable, however, it very quickly becomes a real pain in the ass as the parsing required is more complicated. Regex are a middle ground, and probably your best bet here. They are powerful, yet flexible as you can yourself add more logic from the code that call the different regex. The main drawback would be speed here. Lex/Yacc is really only adapted to very complicated, predictable syntaxes and lacks a lot of post compile flexibility. You can't easily change parser in mid parsing, well actually you can but it's just too heavy and you'd be better using regex instead. I know this is a cliché answer, it all really comes down to what your exact needs are, but from what you said, I would personally probably go with a bag of regex. As an alternative, as Vaibhav poionted out, if you have several different situations that can arise and that you cna easily detect which one is coming, you could make a plugin system that chooses the right algorithm, and those algorithms could all be very different, one using Lex/Yacc in pointy cases and the other using IndexOf and regex for simpler cases. | [
"c#",
"email",
"parsing",
"projects-and-solutions"
] | 6 | 4 | 1,450 | 10 | 0 | 2008-09-11T11:47:03.903000 | 2008-09-11T12:14:38.970000 |
56,347 | 56,370 | Iterators in C++ (stl) vs Java, is there a conceptual difference? | I'm returning to c++ after being away for a bit and trying to dust off the old melon. In Java Iterator is an interface to a container having methods: hasNext(), next() and remove(). The presence of hasNext() means it has the concept of a limit for the container being traversed. //with an Iterator Iterator iter = trees.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } In the C++ standard template library, iterators seem to represent a datatype or class the supports the operator++ and operator== but has no concept of a limit built in so comparison is required before advancing to the next item. The limit has to checked by the user comparing two iterators in the normal case the second iterator is the container end. vector vec; vector::iterator iter;
// Add some elements to vector v.push_back(1); v.push_back(4); v.push_back(8);
for (iter= v.begin(); iter!= v.end(); iter++) { cout << *i << " "; //Should output 1 4 8 } The interesting part here is that in C++ a pointer is an iterator to an array. The STL took what was existing and build convention around it. It there any further subtlety to this that I am missing? | Yes, there is a large conceptual difference. C++ utilizes different "classes" of iterators. Some are used for random access (unlike Java), some are used for forward access (like java). While even others are used for writing data (for use with, say, transform ). See the iterators concept in the C++ Documentation: Input Iterator Output Iterator Forward Iterator Bidirectional Iterator Random Access Iterator These are far more interesting and powerful compared to Java/C#'s puny iterators. Hopefully these conventions will be codified using C++0x's Concepts. | Iterators in C++ (stl) vs Java, is there a conceptual difference? I'm returning to c++ after being away for a bit and trying to dust off the old melon. In Java Iterator is an interface to a container having methods: hasNext(), next() and remove(). The presence of hasNext() means it has the concept of a limit for the container being traversed. //with an Iterator Iterator iter = trees.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } In the C++ standard template library, iterators seem to represent a datatype or class the supports the operator++ and operator== but has no concept of a limit built in so comparison is required before advancing to the next item. The limit has to checked by the user comparing two iterators in the normal case the second iterator is the container end. vector vec; vector::iterator iter;
// Add some elements to vector v.push_back(1); v.push_back(4); v.push_back(8);
for (iter= v.begin(); iter!= v.end(); iter++) { cout << *i << " "; //Should output 1 4 8 } The interesting part here is that in C++ a pointer is an iterator to an array. The STL took what was existing and build convention around it. It there any further subtlety to this that I am missing? | TITLE:
Iterators in C++ (stl) vs Java, is there a conceptual difference?
QUESTION:
I'm returning to c++ after being away for a bit and trying to dust off the old melon. In Java Iterator is an interface to a container having methods: hasNext(), next() and remove(). The presence of hasNext() means it has the concept of a limit for the container being traversed. //with an Iterator Iterator iter = trees.iterator(); while (iter.hasNext()) { System.out.println(iter.next()); } In the C++ standard template library, iterators seem to represent a datatype or class the supports the operator++ and operator== but has no concept of a limit built in so comparison is required before advancing to the next item. The limit has to checked by the user comparing two iterators in the normal case the second iterator is the container end. vector vec; vector::iterator iter;
// Add some elements to vector v.push_back(1); v.push_back(4); v.push_back(8);
for (iter= v.begin(); iter!= v.end(); iter++) { cout << *i << " "; //Should output 1 4 8 } The interesting part here is that in C++ a pointer is an iterator to an array. The STL took what was existing and build convention around it. It there any further subtlety to this that I am missing?
ANSWER:
Yes, there is a large conceptual difference. C++ utilizes different "classes" of iterators. Some are used for random access (unlike Java), some are used for forward access (like java). While even others are used for writing data (for use with, say, transform ). See the iterators concept in the C++ Documentation: Input Iterator Output Iterator Forward Iterator Bidirectional Iterator Random Access Iterator These are far more interesting and powerful compared to Java/C#'s puny iterators. Hopefully these conventions will be codified using C++0x's Concepts. | [
"java",
"c++",
"iterator",
"iteration"
] | 34 | 21 | 13,934 | 9 | 0 | 2008-09-11T11:50:24.490000 | 2008-09-11T12:05:12.083000 |
56,357 | 56,360 | Precompilation and startup times on ASP.Net | I am developping a (relatively small) website in ASP.Net 2.0. I am also using nAnt to perform some easy tweaking on my project before delivering executables. In its current state, the website is "precompiled" using aspnet_compiler.exe -nologo -v ${Appname} -u ${target} I have noticed that after the IIS pool is restarted (after a idle shutdown or a recycle), the application takes up to 20 seconds before it is back online (and Application_start is reached). I don't have the same issue when I am debugging directly within Visual Studio (it takes 2 seconds to start) so I am wondering if the aspnet_compiler is really such a good idea. I couldn't find much on MSDN. How do you compile your websites for production? | Make sure that: You are using a Web Application project rather than a Web Site project, this will result in a precompiled binary for your code behind You have turned off debug code generation in the web.config file - I guess if this is different to when you used aspnet_compiler the code may be recompiled If you've tried those, you could maybe try running ngen over your assembly thus saving the JIT time? | Precompilation and startup times on ASP.Net I am developping a (relatively small) website in ASP.Net 2.0. I am also using nAnt to perform some easy tweaking on my project before delivering executables. In its current state, the website is "precompiled" using aspnet_compiler.exe -nologo -v ${Appname} -u ${target} I have noticed that after the IIS pool is restarted (after a idle shutdown or a recycle), the application takes up to 20 seconds before it is back online (and Application_start is reached). I don't have the same issue when I am debugging directly within Visual Studio (it takes 2 seconds to start) so I am wondering if the aspnet_compiler is really such a good idea. I couldn't find much on MSDN. How do you compile your websites for production? | TITLE:
Precompilation and startup times on ASP.Net
QUESTION:
I am developping a (relatively small) website in ASP.Net 2.0. I am also using nAnt to perform some easy tweaking on my project before delivering executables. In its current state, the website is "precompiled" using aspnet_compiler.exe -nologo -v ${Appname} -u ${target} I have noticed that after the IIS pool is restarted (after a idle shutdown or a recycle), the application takes up to 20 seconds before it is back online (and Application_start is reached). I don't have the same issue when I am debugging directly within Visual Studio (it takes 2 seconds to start) so I am wondering if the aspnet_compiler is really such a good idea. I couldn't find much on MSDN. How do you compile your websites for production?
ANSWER:
Make sure that: You are using a Web Application project rather than a Web Site project, this will result in a precompiled binary for your code behind You have turned off debug code generation in the web.config file - I guess if this is different to when you used aspnet_compiler the code may be recompiled If you've tried those, you could maybe try running ngen over your assembly thus saving the JIT time? | [
"c#",
"asp.net",
"compilation",
"startup",
"aspnet-compiler"
] | 6 | 4 | 2,644 | 6 | 0 | 2008-09-11T11:53:53.233000 | 2008-09-11T11:56:57.767000 |
56,362 | 62,964 | Directory layout for pure Ruby project | I'm starting to learn ruby. I'm also a day-to-day C++ dev. For C++ projects I usually go with following dir structure / -/bin <- built binaries -/build <- build time temporary object (eg..obj, cmake intermediates) -/doc <- manuals and/or Doxygen docs -/src --/module-1 --/module-2 -- non module specific sources, like main.cpp - IDE project files (.sln), etc. What dir layout for Ruby (non-Rails, non-Merb) would you suggest to keep it clean, simple and maintainable? | Bundler includes the necessary infrastructure to generate a gem: $ bundle gem --coc --mit --test=minitest --exe spider Creating gem 'spider'... MIT License enabled in config Code of conduct enabled in config create spider/Gemfile create spider/lib/spider.rb create spider/lib/spider/version.rb create spider/spider.gemspec create spider/Rakefile create spider/README.md create spider/bin/console create spider/bin/setup create spider/.gitignore create spider/.travis.yml create spider/test/test_helper.rb create spider/test/spider_test.rb create spider/LICENSE.txt create spider/CODE_OF_CONDUCT.md create spider/exe/spider Initializing git repo in /Users/francois/Projects/spider Gem 'spider' was successfully created. For more information on making a RubyGem visit https://bundler.io/guides/creating_gem.html Then, in lib/, you create modules as needed: lib/ spider/ base.rb crawler/ base.rb spider.rb require "spider/base" require "crawler/base" Read the manual page for bundle gem for details on the --coc, --exe and --mit options. | Directory layout for pure Ruby project I'm starting to learn ruby. I'm also a day-to-day C++ dev. For C++ projects I usually go with following dir structure / -/bin <- built binaries -/build <- build time temporary object (eg..obj, cmake intermediates) -/doc <- manuals and/or Doxygen docs -/src --/module-1 --/module-2 -- non module specific sources, like main.cpp - IDE project files (.sln), etc. What dir layout for Ruby (non-Rails, non-Merb) would you suggest to keep it clean, simple and maintainable? | TITLE:
Directory layout for pure Ruby project
QUESTION:
I'm starting to learn ruby. I'm also a day-to-day C++ dev. For C++ projects I usually go with following dir structure / -/bin <- built binaries -/build <- build time temporary object (eg..obj, cmake intermediates) -/doc <- manuals and/or Doxygen docs -/src --/module-1 --/module-2 -- non module specific sources, like main.cpp - IDE project files (.sln), etc. What dir layout for Ruby (non-Rails, non-Merb) would you suggest to keep it clean, simple and maintainable?
ANSWER:
Bundler includes the necessary infrastructure to generate a gem: $ bundle gem --coc --mit --test=minitest --exe spider Creating gem 'spider'... MIT License enabled in config Code of conduct enabled in config create spider/Gemfile create spider/lib/spider.rb create spider/lib/spider/version.rb create spider/spider.gemspec create spider/Rakefile create spider/README.md create spider/bin/console create spider/bin/setup create spider/.gitignore create spider/.travis.yml create spider/test/test_helper.rb create spider/test/spider_test.rb create spider/LICENSE.txt create spider/CODE_OF_CONDUCT.md create spider/exe/spider Initializing git repo in /Users/francois/Projects/spider Gem 'spider' was successfully created. For more information on making a RubyGem visit https://bundler.io/guides/creating_gem.html Then, in lib/, you create modules as needed: lib/ spider/ base.rb crawler/ base.rb spider.rb require "spider/base" require "crawler/base" Read the manual page for bundle gem for details on the --coc, --exe and --mit options. | [
"ruby",
"code-formatting"
] | 23 | 13 | 11,124 | 7 | 0 | 2008-09-11T11:58:06 | 2008-09-15T13:41:54.313000 |
56,375 | 56,380 | Are non-generic collections in .NET obsolete? | Put differently: Is there a good reason to choose a loosely-typed collection over a type-safe one (HashTable vs. Dictionary)? Are they still there only for compatibility? As far as I understand, generic collections not only are type-safe, but their performance is better. Here's a comprehensive article on the topic: An Extensive Examination of Data Structures Using C# 2.0. | The non-generic collections are so obsolete that they've been removed from the CoreCLR used in Silverlight and Live Mesh. | Are non-generic collections in .NET obsolete? Put differently: Is there a good reason to choose a loosely-typed collection over a type-safe one (HashTable vs. Dictionary)? Are they still there only for compatibility? As far as I understand, generic collections not only are type-safe, but their performance is better. Here's a comprehensive article on the topic: An Extensive Examination of Data Structures Using C# 2.0. | TITLE:
Are non-generic collections in .NET obsolete?
QUESTION:
Put differently: Is there a good reason to choose a loosely-typed collection over a type-safe one (HashTable vs. Dictionary)? Are they still there only for compatibility? As far as I understand, generic collections not only are type-safe, but their performance is better. Here's a comprehensive article on the topic: An Extensive Examination of Data Structures Using C# 2.0.
ANSWER:
The non-generic collections are so obsolete that they've been removed from the CoreCLR used in Silverlight and Live Mesh. | [
".net",
"generics",
"collections"
] | 26 | 22 | 8,032 | 9 | 0 | 2008-09-11T12:05:59.850000 | 2008-09-11T12:09:30.513000 |
56,391 | 56,418 | Automatically checking for a new version of my application | Trying to honor a feature request from our customers, I'd like that my application, when Internet is available, check on our website if a new version is available. The problem is that I have no idea about what have to be done on the server side. I can imagine that my application (developped in C++ using Qt) has to send a request (HTTP?) to the server, but what is going to respond to this request? In order to go through firewalls, I guess I'll have to use port 80? Is this correct? Or, for such a feature, do I have to ask our network admin to open a specific port number through which I'll communicate? @ pilif: thanks for your detailed answer. There is still something which is unclear for me: like http://www.example.com/update?version=1.2.4 Then you can return what ever you want, probably also the download-URL of the installer of the new version. How do I return something? Will it be a php or asp page (I know nothing about PHP nor ASP, I have to confess)? How can I decode the?version=1.2.4 part in order to return something accordingly? | I would absolutely recommend to just do a plain HTTP request to your website. Everything else is bound to fail. I'd make a HTTP GET request to a certain page on your site containing the version of the local application. like http://www.example.com/update?version=1.2.4 Then you can return what ever you want, probably also the download-URL of the installer of the new version. Why not just put a static file with the latest version to the server and let the client decide? Because you may want (or need) to have control over the process. Maybe 1.2 won't be compatible with the server in the future, so you want the server to force the update to 1.3, but the update from 1.2.4 to 1.2.6 could be uncritical, so you might want to present the client with an optional update. Or you want to have a breakdown over the installed base. Or whatever. Usually, I've learned it's best to keep as much intelligence on the server, because the server is what you have ultimate control over. Speaking here with a bit of experience in the field, here's a small preview of what can (and will - trust me) go wrong: Your Application will be prevented from making HTTP-Requests by the various Personal Firewall applications out there. A considerable percentage of users won't have the needed permissions to actually get the update process going. Even if your users have allowed the old version past their personal firewall, said tool will complain because the.EXE has changed and will recommend the user not to allow the new exe to connect (users usually comply with the wishes of their security tool here). In managed environments, you'll be shot and hanged (not necessarily in that order) for loading executable content from the web and then actually executing it. So to keep the damage as low as possible, fail silently when you can't connect to the update server before updating, make sure that you have write-permission to the install directory and warn the user if you do not, or just don't update at all. Provide a way for administrators to turn the auto-update off. It's no fun to do what you are about to do - especially when you deal with non technically inclined users as I had to numerous times. | Automatically checking for a new version of my application Trying to honor a feature request from our customers, I'd like that my application, when Internet is available, check on our website if a new version is available. The problem is that I have no idea about what have to be done on the server side. I can imagine that my application (developped in C++ using Qt) has to send a request (HTTP?) to the server, but what is going to respond to this request? In order to go through firewalls, I guess I'll have to use port 80? Is this correct? Or, for such a feature, do I have to ask our network admin to open a specific port number through which I'll communicate? @ pilif: thanks for your detailed answer. There is still something which is unclear for me: like http://www.example.com/update?version=1.2.4 Then you can return what ever you want, probably also the download-URL of the installer of the new version. How do I return something? Will it be a php or asp page (I know nothing about PHP nor ASP, I have to confess)? How can I decode the?version=1.2.4 part in order to return something accordingly? | TITLE:
Automatically checking for a new version of my application
QUESTION:
Trying to honor a feature request from our customers, I'd like that my application, when Internet is available, check on our website if a new version is available. The problem is that I have no idea about what have to be done on the server side. I can imagine that my application (developped in C++ using Qt) has to send a request (HTTP?) to the server, but what is going to respond to this request? In order to go through firewalls, I guess I'll have to use port 80? Is this correct? Or, for such a feature, do I have to ask our network admin to open a specific port number through which I'll communicate? @ pilif: thanks for your detailed answer. There is still something which is unclear for me: like http://www.example.com/update?version=1.2.4 Then you can return what ever you want, probably also the download-URL of the installer of the new version. How do I return something? Will it be a php or asp page (I know nothing about PHP nor ASP, I have to confess)? How can I decode the?version=1.2.4 part in order to return something accordingly?
ANSWER:
I would absolutely recommend to just do a plain HTTP request to your website. Everything else is bound to fail. I'd make a HTTP GET request to a certain page on your site containing the version of the local application. like http://www.example.com/update?version=1.2.4 Then you can return what ever you want, probably also the download-URL of the installer of the new version. Why not just put a static file with the latest version to the server and let the client decide? Because you may want (or need) to have control over the process. Maybe 1.2 won't be compatible with the server in the future, so you want the server to force the update to 1.3, but the update from 1.2.4 to 1.2.6 could be uncritical, so you might want to present the client with an optional update. Or you want to have a breakdown over the installed base. Or whatever. Usually, I've learned it's best to keep as much intelligence on the server, because the server is what you have ultimate control over. Speaking here with a bit of experience in the field, here's a small preview of what can (and will - trust me) go wrong: Your Application will be prevented from making HTTP-Requests by the various Personal Firewall applications out there. A considerable percentage of users won't have the needed permissions to actually get the update process going. Even if your users have allowed the old version past their personal firewall, said tool will complain because the.EXE has changed and will recommend the user not to allow the new exe to connect (users usually comply with the wishes of their security tool here). In managed environments, you'll be shot and hanged (not necessarily in that order) for loading executable content from the web and then actually executing it. So to keep the damage as low as possible, fail silently when you can't connect to the update server before updating, make sure that you have write-permission to the install directory and warn the user if you do not, or just don't update at all. Provide a way for administrators to turn the auto-update off. It's no fun to do what you are about to do - especially when you deal with non technically inclined users as I had to numerous times. | [
"c++",
"qt"
] | 24 | 38 | 11,355 | 12 | 0 | 2008-09-11T12:17:50.820000 | 2008-09-11T12:29:19.823000 |
56,402 | 73,257 | Aligning text in SVG | I am trying to make SVG XML documents with a mixture of lines and brief text snippets (two or three words typically). The major problem I'm having is getting the text aligning with line segments. For horizontal alignment I can use text-anchor with left, middle or right. I can't find a equivalent for vertical alignment; alignment-baseline doesn't seem to do it, so at present I'm using dy="0.5ex" as a kludge for centre alignment. Is there a proper manner for aligning with the vertical centre or top of the text? | It turns out that you don't need explicit text paths. Firefox 3 has only partial support of the vertical alignment tags ( see this thread ). It also seems that dominant-baseline only works when applied as a style whereas text-anchor can be part of the style or a tag attribute. Vertical Horizontal Bit of Both This works in Firefox. Unfortunately Inkscape doesn't seem to handle dominant-baseline (or at least not in the same way). | Aligning text in SVG I am trying to make SVG XML documents with a mixture of lines and brief text snippets (two or three words typically). The major problem I'm having is getting the text aligning with line segments. For horizontal alignment I can use text-anchor with left, middle or right. I can't find a equivalent for vertical alignment; alignment-baseline doesn't seem to do it, so at present I'm using dy="0.5ex" as a kludge for centre alignment. Is there a proper manner for aligning with the vertical centre or top of the text? | TITLE:
Aligning text in SVG
QUESTION:
I am trying to make SVG XML documents with a mixture of lines and brief text snippets (two or three words typically). The major problem I'm having is getting the text aligning with line segments. For horizontal alignment I can use text-anchor with left, middle or right. I can't find a equivalent for vertical alignment; alignment-baseline doesn't seem to do it, so at present I'm using dy="0.5ex" as a kludge for centre alignment. Is there a proper manner for aligning with the vertical centre or top of the text?
ANSWER:
It turns out that you don't need explicit text paths. Firefox 3 has only partial support of the vertical alignment tags ( see this thread ). It also seems that dominant-baseline only works when applied as a style whereas text-anchor can be part of the style or a tag attribute. Vertical Horizontal Bit of Both This works in Firefox. Unfortunately Inkscape doesn't seem to handle dominant-baseline (or at least not in the same way). | [
"xml",
"svg"
] | 71 | 61 | 61,587 | 2 | 0 | 2008-09-11T12:24:24.157000 | 2008-09-16T14:57:13.937000 |
56,411 | 56,447 | How to test randomness (case in point - Shuffling) | First off, this question is ripped out from this question. I did it because I think this part is bigger than a sub-part of a longer question. If it offends, please pardon me. Assume that you have a algorithm that generates randomness. Now how do you test it? Or to be more direct - Assume you have an algorithm that shuffles a deck of cards, how do you test that it's a perfectly random algorithm? To add some theory to the problem - A deck of cards can be shuffled in 52! (52 factorial) different ways. Take a deck of cards, shuffle it by hand and write down the order of all cards. What is the probability that you would have gotten exactly that shuffle? Answer: 1 / 52!. What is the chance that you, after shuffling, will get A, K, Q, J... of each suit in a sequence? Answer 1 / 52! So, just shuffling once and looking at the result will give you absolutely no information about your shuffling algorithms randomness. Twice and you have more information, Three even more... How would you black box test a shuffling algorithm for randomness? | Statistics. The de facto standard for testing RNGs is the Diehard suite (originally available at http://stat.fsu.edu/pub/diehard ). Alternatively, the Ent program provides tests that are simpler to interpret but less comprehensive. As for shuffling algorithms, use a well-known algorithm such as Fisher-Yates (a.k.a "Knuth Shuffle"). The shuffle will be uniformly random so long as the underlying RNG is uniformly random. If you are using Java, this algorithm is available in the standard library (see Collections.shuffle ). It probably doesn't matter for most applications, but be aware that most RNGs do not provide sufficient degrees of freedom to produce every possible permutation of a 52-card deck (explained here ). | How to test randomness (case in point - Shuffling) First off, this question is ripped out from this question. I did it because I think this part is bigger than a sub-part of a longer question. If it offends, please pardon me. Assume that you have a algorithm that generates randomness. Now how do you test it? Or to be more direct - Assume you have an algorithm that shuffles a deck of cards, how do you test that it's a perfectly random algorithm? To add some theory to the problem - A deck of cards can be shuffled in 52! (52 factorial) different ways. Take a deck of cards, shuffle it by hand and write down the order of all cards. What is the probability that you would have gotten exactly that shuffle? Answer: 1 / 52!. What is the chance that you, after shuffling, will get A, K, Q, J... of each suit in a sequence? Answer 1 / 52! So, just shuffling once and looking at the result will give you absolutely no information about your shuffling algorithms randomness. Twice and you have more information, Three even more... How would you black box test a shuffling algorithm for randomness? | TITLE:
How to test randomness (case in point - Shuffling)
QUESTION:
First off, this question is ripped out from this question. I did it because I think this part is bigger than a sub-part of a longer question. If it offends, please pardon me. Assume that you have a algorithm that generates randomness. Now how do you test it? Or to be more direct - Assume you have an algorithm that shuffles a deck of cards, how do you test that it's a perfectly random algorithm? To add some theory to the problem - A deck of cards can be shuffled in 52! (52 factorial) different ways. Take a deck of cards, shuffle it by hand and write down the order of all cards. What is the probability that you would have gotten exactly that shuffle? Answer: 1 / 52!. What is the chance that you, after shuffling, will get A, K, Q, J... of each suit in a sequence? Answer 1 / 52! So, just shuffling once and looking at the result will give you absolutely no information about your shuffling algorithms randomness. Twice and you have more information, Three even more... How would you black box test a shuffling algorithm for randomness?
ANSWER:
Statistics. The de facto standard for testing RNGs is the Diehard suite (originally available at http://stat.fsu.edu/pub/diehard ). Alternatively, the Ent program provides tests that are simpler to interpret but less comprehensive. As for shuffling algorithms, use a well-known algorithm such as Fisher-Yates (a.k.a "Knuth Shuffle"). The shuffle will be uniformly random so long as the underlying RNG is uniformly random. If you are using Java, this algorithm is available in the standard library (see Collections.shuffle ). It probably doesn't matter for most applications, but be aware that most RNGs do not provide sufficient degrees of freedom to produce every possible permutation of a 52-card deck (explained here ). | [
"math",
"theory",
"random",
"puzzle"
] | 47 | 30 | 15,634 | 11 | 0 | 2008-09-11T12:27:22.293000 | 2008-09-11T12:45:04.717000 |
56,417 | 106,464 | Anyone used Dabo for a medium-big project? | We're at the beginning of a new ERP-ish client-server application, developed as a Python rich client. We're currently evaluating Dabo as our main framework and it looks quite nice and easy to use, but I was wondering, has anyone used it for medium-to-big sized projects? Thanks for your time! | I'm one of the authors of the Dabo framework. One of our users pointed out to me the extremely negative answer you received, and so I thought I had better chime in and clear up some of the incorrect assumptions in the first reply. Dabo is indeed well-known in the Python community. I have presented it at 3 of the last 4 US PyCons, and we have several hundred users who subscribe to our email lists. Our website ( http://dabodev.com ) has not had any service interruptions; I don't know why the first responder claimed to have trouble. Support is through our email lists, and we pride ourselves on helping people quickly and efficiently. Many of the newbie questions help us to identify places where our docs are lacking, so we strongly encourage newcomers to ask questions! Dabo has been around for 4 years. The fact that it is still a few days away from a 0.9 release is more of a reflection of the rather conservative version numbering of my partner, Paul McNett, than any instabilities in the framework. I know of Dabo apps that have been in production since 2006; I have used it for my own projects since 2004. Whatever importance you attach to release numbers, we are at revision 4522, with consistent work being done to add more and more stuff to the framework; refactor and streamline some of the older code, and yes, clean up some bugs. Please sign up for our free email support list: http://leafe.com/mailman/listinfo/dabo-users...and ask any questions you may have about Dabo there. Not many people have discovered Stack Overflow yet, so I wouldn't expect very informed answers here yet. There are several regular contributors there who use Dabo on a daily basis, and are usually more than happy to offer their opinions and their help. | Anyone used Dabo for a medium-big project? We're at the beginning of a new ERP-ish client-server application, developed as a Python rich client. We're currently evaluating Dabo as our main framework and it looks quite nice and easy to use, but I was wondering, has anyone used it for medium-to-big sized projects? Thanks for your time! | TITLE:
Anyone used Dabo for a medium-big project?
QUESTION:
We're at the beginning of a new ERP-ish client-server application, developed as a Python rich client. We're currently evaluating Dabo as our main framework and it looks quite nice and easy to use, but I was wondering, has anyone used it for medium-to-big sized projects? Thanks for your time!
ANSWER:
I'm one of the authors of the Dabo framework. One of our users pointed out to me the extremely negative answer you received, and so I thought I had better chime in and clear up some of the incorrect assumptions in the first reply. Dabo is indeed well-known in the Python community. I have presented it at 3 of the last 4 US PyCons, and we have several hundred users who subscribe to our email lists. Our website ( http://dabodev.com ) has not had any service interruptions; I don't know why the first responder claimed to have trouble. Support is through our email lists, and we pride ourselves on helping people quickly and efficiently. Many of the newbie questions help us to identify places where our docs are lacking, so we strongly encourage newcomers to ask questions! Dabo has been around for 4 years. The fact that it is still a few days away from a 0.9 release is more of a reflection of the rather conservative version numbering of my partner, Paul McNett, than any instabilities in the framework. I know of Dabo apps that have been in production since 2006; I have used it for my own projects since 2004. Whatever importance you attach to release numbers, we are at revision 4522, with consistent work being done to add more and more stuff to the framework; refactor and streamline some of the older code, and yes, clean up some bugs. Please sign up for our free email support list: http://leafe.com/mailman/listinfo/dabo-users...and ask any questions you may have about Dabo there. Not many people have discovered Stack Overflow yet, so I wouldn't expect very informed answers here yet. There are several regular contributors there who use Dabo on a daily basis, and are usually more than happy to offer their opinions and their help. | [
"python",
"erp",
"dabo"
] | 21 | 25 | 4,099 | 2 | 0 | 2008-09-11T12:29:09.013000 | 2008-09-19T23:55:08.023000 |
56,424 | 80,707 | What can cause a reduction in frame rate when upgrading a graphics card? | We have a two-screen DirectX application that previously ran at a consistent 60 FPS (the monitors' sync rate) using a NVIDIA 8400GS (256MB). However, when we swapped out the card for one with 512 MB of RAM the frame rate struggles to get above 40 FPS. (It only gets this high because we're using triple-buffering.) The two cards are from the same manufacturer (PNY). All other things are equal, this is a Windows XP Embedded application and we started from a fresh image for each card. The driver version number is 169.21. The application is all 2D. I.E. just a bunch of textured quads and a whole lot of pre-rendered graphics (hence the need to upgrade the card's memory). We also have compressed animations which the CPU decodes on the fly - this involves a texture lock. The locks take forever but I've also tried having a separate system memory texture for the CPU to update and then updating the rendered texture using the device's UpdateTexture method. No overall difference in performance. Although I've read through every FAQ I can find on the internet about DirectX performance, this is still the first time I've worked on a DirectX project so any arcane bits of knowledge you have would be useful.:) One other thing whilst I'm on the subject; when calling Present on the swap chains it seems DirectX waits for the present to complete regardless of the fact that I'm using D3DPRESENT_DONOTWAIT in both present parameters (PresentationInterval) and the flags of the call itself. Because this is a two-screen application this is a problem as the two monitors do not appear to be genlocked, I'm working around it by running the Present calls through a threadpool. What could the underlying cause of this be? | Are the cards exactly the same (both GeForce 8400GS), and only the memory size differ? Quite often with different memory sizes come slightly different clock rates (i.e. your card with more memory might use slower memory!). So the first thing to check would be GPU core & memory clock rates, using something like GPU-Z. | What can cause a reduction in frame rate when upgrading a graphics card? We have a two-screen DirectX application that previously ran at a consistent 60 FPS (the monitors' sync rate) using a NVIDIA 8400GS (256MB). However, when we swapped out the card for one with 512 MB of RAM the frame rate struggles to get above 40 FPS. (It only gets this high because we're using triple-buffering.) The two cards are from the same manufacturer (PNY). All other things are equal, this is a Windows XP Embedded application and we started from a fresh image for each card. The driver version number is 169.21. The application is all 2D. I.E. just a bunch of textured quads and a whole lot of pre-rendered graphics (hence the need to upgrade the card's memory). We also have compressed animations which the CPU decodes on the fly - this involves a texture lock. The locks take forever but I've also tried having a separate system memory texture for the CPU to update and then updating the rendered texture using the device's UpdateTexture method. No overall difference in performance. Although I've read through every FAQ I can find on the internet about DirectX performance, this is still the first time I've worked on a DirectX project so any arcane bits of knowledge you have would be useful.:) One other thing whilst I'm on the subject; when calling Present on the swap chains it seems DirectX waits for the present to complete regardless of the fact that I'm using D3DPRESENT_DONOTWAIT in both present parameters (PresentationInterval) and the flags of the call itself. Because this is a two-screen application this is a problem as the two monitors do not appear to be genlocked, I'm working around it by running the Present calls through a threadpool. What could the underlying cause of this be? | TITLE:
What can cause a reduction in frame rate when upgrading a graphics card?
QUESTION:
We have a two-screen DirectX application that previously ran at a consistent 60 FPS (the monitors' sync rate) using a NVIDIA 8400GS (256MB). However, when we swapped out the card for one with 512 MB of RAM the frame rate struggles to get above 40 FPS. (It only gets this high because we're using triple-buffering.) The two cards are from the same manufacturer (PNY). All other things are equal, this is a Windows XP Embedded application and we started from a fresh image for each card. The driver version number is 169.21. The application is all 2D. I.E. just a bunch of textured quads and a whole lot of pre-rendered graphics (hence the need to upgrade the card's memory). We also have compressed animations which the CPU decodes on the fly - this involves a texture lock. The locks take forever but I've also tried having a separate system memory texture for the CPU to update and then updating the rendered texture using the device's UpdateTexture method. No overall difference in performance. Although I've read through every FAQ I can find on the internet about DirectX performance, this is still the first time I've worked on a DirectX project so any arcane bits of knowledge you have would be useful.:) One other thing whilst I'm on the subject; when calling Present on the swap chains it seems DirectX waits for the present to complete regardless of the fact that I'm using D3DPRESENT_DONOTWAIT in both present parameters (PresentationInterval) and the flags of the call itself. Because this is a two-screen application this is a problem as the two monitors do not appear to be genlocked, I'm working around it by running the Present calls through a threadpool. What could the underlying cause of this be?
ANSWER:
Are the cards exactly the same (both GeForce 8400GS), and only the memory size differ? Quite often with different memory sizes come slightly different clock rates (i.e. your card with more memory might use slower memory!). So the first thing to check would be GPU core & memory clock rates, using something like GPU-Z. | [
"c++",
"hardware",
"directx"
] | 3 | 2 | 387 | 2 | 0 | 2008-09-11T12:31:09.790000 | 2008-09-17T07:10:25.970000 |
56,427 | 56,451 | Are there any resources for becoming a Cygwin "power user"? | I've got it configured, but I want more from it...maybe Cygwin isn't the right tool, but I like how it provides a *nix-like environment within Windows. | I've found Cygwin to be very useful in the past. FWIW, lately however I've shied away from it in favor of the following: XAMPP Unixutils I like these tools even better. | Are there any resources for becoming a Cygwin "power user"? I've got it configured, but I want more from it...maybe Cygwin isn't the right tool, but I like how it provides a *nix-like environment within Windows. | TITLE:
Are there any resources for becoming a Cygwin "power user"?
QUESTION:
I've got it configured, but I want more from it...maybe Cygwin isn't the right tool, but I like how it provides a *nix-like environment within Windows.
ANSWER:
I've found Cygwin to be very useful in the past. FWIW, lately however I've shied away from it in favor of the following: XAMPP Unixutils I like these tools even better. | [
"windows",
"unix",
"cygwin"
] | 11 | 5 | 1,277 | 3 | 0 | 2008-09-11T12:32:47.197000 | 2008-09-11T12:46:57.317000 |
56,443 | 56,483 | Create drop down list options from enum in a DataGridView | I currently have a class and I'm trying to create an easy GUI to create a collection of this class. Most of the attributes of this class are strings. However, one of the attributes I want the user to be able to set is an Enum. Therefore, I would like the user interface, to have a dropdownlist for this enum, to restrict the user from entering a value that is not valid. Currently, I am taking the initial list of objects, adding them to a DataTable and setting the DataSource of my DataGridView to the table. Works nicely, even creates a checkbox column for the one Boolean property. But, I don't know how to make the column for the enum into a dropdownlist. I am using C# and.NET 2.0. Also, I have tried assigning the DataSource of the DataGridView to the list of my objects, but when I do this, it doesn't help with the enum and I'm unable to create new rows in the DataGridView, but I am definitely not bound to using a DataTable as my DataSource, it was simply the option I have semi-working. | I do not know if that would work with a DataGridView column but it works with ComboBoxes: comboBox1.DataSource = Enum.GetValues(typeof(MyEnum)); and: MyEnum value = (MyEnum)comboBox1.SelectedValue; UPDATE: It works with DataGridView columns too, just remember to set the value type. DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn(); col.Name = "My Enum Column"; col.DataSource = Enum.GetValues(typeof(MyEnum)); col.ValueType = typeof(MyEnum); dataGridView1.Columns.Add(col); | Create drop down list options from enum in a DataGridView I currently have a class and I'm trying to create an easy GUI to create a collection of this class. Most of the attributes of this class are strings. However, one of the attributes I want the user to be able to set is an Enum. Therefore, I would like the user interface, to have a dropdownlist for this enum, to restrict the user from entering a value that is not valid. Currently, I am taking the initial list of objects, adding them to a DataTable and setting the DataSource of my DataGridView to the table. Works nicely, even creates a checkbox column for the one Boolean property. But, I don't know how to make the column for the enum into a dropdownlist. I am using C# and.NET 2.0. Also, I have tried assigning the DataSource of the DataGridView to the list of my objects, but when I do this, it doesn't help with the enum and I'm unable to create new rows in the DataGridView, but I am definitely not bound to using a DataTable as my DataSource, it was simply the option I have semi-working. | TITLE:
Create drop down list options from enum in a DataGridView
QUESTION:
I currently have a class and I'm trying to create an easy GUI to create a collection of this class. Most of the attributes of this class are strings. However, one of the attributes I want the user to be able to set is an Enum. Therefore, I would like the user interface, to have a dropdownlist for this enum, to restrict the user from entering a value that is not valid. Currently, I am taking the initial list of objects, adding them to a DataTable and setting the DataSource of my DataGridView to the table. Works nicely, even creates a checkbox column for the one Boolean property. But, I don't know how to make the column for the enum into a dropdownlist. I am using C# and.NET 2.0. Also, I have tried assigning the DataSource of the DataGridView to the list of my objects, but when I do this, it doesn't help with the enum and I'm unable to create new rows in the DataGridView, but I am definitely not bound to using a DataTable as my DataSource, it was simply the option I have semi-working.
ANSWER:
I do not know if that would work with a DataGridView column but it works with ComboBoxes: comboBox1.DataSource = Enum.GetValues(typeof(MyEnum)); and: MyEnum value = (MyEnum)comboBox1.SelectedValue; UPDATE: It works with DataGridView columns too, just remember to set the value type. DataGridViewComboBoxColumn col = new DataGridViewComboBoxColumn(); col.Name = "My Enum Column"; col.DataSource = Enum.GetValues(typeof(MyEnum)); col.ValueType = typeof(MyEnum); dataGridView1.Columns.Add(col); | [
"c#",
".net",
"winforms",
"user-interface",
".net-2.0"
] | 19 | 44 | 33,666 | 2 | 0 | 2008-09-11T12:42:55.767000 | 2008-09-11T13:04:26.260000 |
56,472 | 61,947 | Sending messages to objects while debugging Objective-C in gdb, without symbols | I'm trying to send messages to Objective-C objects in gdb. (gdb) p $esi $2 = (void *) 0x1268160 (gdb) po $esi (gdb) po [$esi count] Target does not respond to this message selector. I can't send any message to it. Am I missing something? Do I really need the symbols, or something else? | If you must override gdb and send a message to an object when it will not let you, you can use performSelector: (gdb) print (int)[receivedData count] Target does not respond to this message selector.
(gdb) print (int)[receivedData performSelector:@selector(count) ] 2008-09-15 00:46:35.854 Executable[1008:20b] *** -[NSConcreteMutableData count]: unrecognized selector sent to instance 0x105f2e0 If you need to pass an argument use withObject: (gdb) print (int)[receivedData performSelector:@selector(count) withObject:myObject ] | Sending messages to objects while debugging Objective-C in gdb, without symbols I'm trying to send messages to Objective-C objects in gdb. (gdb) p $esi $2 = (void *) 0x1268160 (gdb) po $esi (gdb) po [$esi count] Target does not respond to this message selector. I can't send any message to it. Am I missing something? Do I really need the symbols, or something else? | TITLE:
Sending messages to objects while debugging Objective-C in gdb, without symbols
QUESTION:
I'm trying to send messages to Objective-C objects in gdb. (gdb) p $esi $2 = (void *) 0x1268160 (gdb) po $esi (gdb) po [$esi count] Target does not respond to this message selector. I can't send any message to it. Am I missing something? Do I really need the symbols, or something else?
ANSWER:
If you must override gdb and send a message to an object when it will not let you, you can use performSelector: (gdb) print (int)[receivedData count] Target does not respond to this message selector.
(gdb) print (int)[receivedData performSelector:@selector(count) ] 2008-09-15 00:46:35.854 Executable[1008:20b] *** -[NSConcreteMutableData count]: unrecognized selector sent to instance 0x105f2e0 If you need to pass an argument use withObject: (gdb) print (int)[receivedData performSelector:@selector(count) withObject:myObject ] | [
"objective-c",
"debugging",
"macos",
"gdb",
"reversing"
] | 11 | 10 | 3,635 | 3 | 0 | 2008-09-11T12:53:42.573000 | 2008-09-15T06:54:05.183000 |
56,478 | 56,493 | How to interact with Windows Media Player in C# | I am looking for a way to interact with a standalone full version of Windows Media Player. Mostly I need to know the Path of the currently played track. The iTunes SDK makes this really easy but unfortunately there really isn't any way to do it with Windows Media Player, at least not in.Net(C#) without any heavy use of pinvoke, which I am not really comfortable with. Thanks Just to clearify: I don't want to embedded a new instance of Windows Media Player in my app, but instead control/read the "real" full version of Windows Media Player, started seperatly by the user | I had this https://social.msdn.microsoft.com/Forums/vstudio/en-US/dbd43d7e-f3a6-4087-be06-df17e76b635d/windows-media-player-remoting-in-c?forum=clr in my bookmarks but have NOT tested it in anyway. Just a pointer in the right direction. It's nothing official and will require a bit of digging, but you should get a fairly simple wrapper (which will still use PInvoke under the hood - but you won't see it) around Windows Media Player. Hope that helps. Oh, I misunderstood. I thought you were talking about controlling the currently running Windows Media Player instance. If you are hosting Windows Media Player yourself then WMPLib is certainly the better solution. | How to interact with Windows Media Player in C# I am looking for a way to interact with a standalone full version of Windows Media Player. Mostly I need to know the Path of the currently played track. The iTunes SDK makes this really easy but unfortunately there really isn't any way to do it with Windows Media Player, at least not in.Net(C#) without any heavy use of pinvoke, which I am not really comfortable with. Thanks Just to clearify: I don't want to embedded a new instance of Windows Media Player in my app, but instead control/read the "real" full version of Windows Media Player, started seperatly by the user | TITLE:
How to interact with Windows Media Player in C#
QUESTION:
I am looking for a way to interact with a standalone full version of Windows Media Player. Mostly I need to know the Path of the currently played track. The iTunes SDK makes this really easy but unfortunately there really isn't any way to do it with Windows Media Player, at least not in.Net(C#) without any heavy use of pinvoke, which I am not really comfortable with. Thanks Just to clearify: I don't want to embedded a new instance of Windows Media Player in my app, but instead control/read the "real" full version of Windows Media Player, started seperatly by the user
ANSWER:
I had this https://social.msdn.microsoft.com/Forums/vstudio/en-US/dbd43d7e-f3a6-4087-be06-df17e76b635d/windows-media-player-remoting-in-c?forum=clr in my bookmarks but have NOT tested it in anyway. Just a pointer in the right direction. It's nothing official and will require a bit of digging, but you should get a fairly simple wrapper (which will still use PInvoke under the hood - but you won't see it) around Windows Media Player. Hope that helps. Oh, I misunderstood. I thought you were talking about controlling the currently running Windows Media Player instance. If you are hosting Windows Media Player yourself then WMPLib is certainly the better solution. | [
"c#",
"windows",
"media",
"wmp"
] | 9 | 4 | 67,414 | 4 | 0 | 2008-09-11T13:02:32.367000 | 2008-09-11T13:08:26.377000 |
56,479 | 56,489 | Will .NET MVC give me the HTML/CSS/JS separation I need? | I'm working with my ASP.NET development team to try and create "better" (i.e. cleaner) HTML when rendering pages. At the moment,.NET has a nasty tendency to do things like dump JavaScript into the page, making it a mandatory requirement on form controls and not allowing forms to work when JS isn't available. In some instances, we're struggling to overcome this without having to add a notable chunk to development time estimates. I've worked with MVC before - via Struts in Java - and found that in that instance, I was able to keep HTML pages exactly as I'd wanted them to be. (This viewpoint is based on the "best case" static HTML I typically developed beforehand, then handed over to the Java programmers to fill in the holes.) This worked out really well and we were able to produce some of the "best" web pages from a CMS that I've seen. Could.NET MVC give me the separation I need, or would it be a false economy to put aside valuable development time to test this? If.NET MVC isn't going to give me this fine-grained control over separation, any recommendations for.NET coding practices, libraries, etc. which might would be really helpful. | The ASP.NET MVC Framework would give you a much more familiar separation. Because there is no viewstate, etc in the MVC Framework you won't have to worry about JavaScript being dumped into your pages. The only JavaScript calls you see will be ones that you manually add. You can, for the most part, separate HTML / CSS / JS like you would in a different framework. | Will .NET MVC give me the HTML/CSS/JS separation I need? I'm working with my ASP.NET development team to try and create "better" (i.e. cleaner) HTML when rendering pages. At the moment,.NET has a nasty tendency to do things like dump JavaScript into the page, making it a mandatory requirement on form controls and not allowing forms to work when JS isn't available. In some instances, we're struggling to overcome this without having to add a notable chunk to development time estimates. I've worked with MVC before - via Struts in Java - and found that in that instance, I was able to keep HTML pages exactly as I'd wanted them to be. (This viewpoint is based on the "best case" static HTML I typically developed beforehand, then handed over to the Java programmers to fill in the holes.) This worked out really well and we were able to produce some of the "best" web pages from a CMS that I've seen. Could.NET MVC give me the separation I need, or would it be a false economy to put aside valuable development time to test this? If.NET MVC isn't going to give me this fine-grained control over separation, any recommendations for.NET coding practices, libraries, etc. which might would be really helpful. | TITLE:
Will .NET MVC give me the HTML/CSS/JS separation I need?
QUESTION:
I'm working with my ASP.NET development team to try and create "better" (i.e. cleaner) HTML when rendering pages. At the moment,.NET has a nasty tendency to do things like dump JavaScript into the page, making it a mandatory requirement on form controls and not allowing forms to work when JS isn't available. In some instances, we're struggling to overcome this without having to add a notable chunk to development time estimates. I've worked with MVC before - via Struts in Java - and found that in that instance, I was able to keep HTML pages exactly as I'd wanted them to be. (This viewpoint is based on the "best case" static HTML I typically developed beforehand, then handed over to the Java programmers to fill in the holes.) This worked out really well and we were able to produce some of the "best" web pages from a CMS that I've seen. Could.NET MVC give me the separation I need, or would it be a false economy to put aside valuable development time to test this? If.NET MVC isn't going to give me this fine-grained control over separation, any recommendations for.NET coding practices, libraries, etc. which might would be really helpful.
ANSWER:
The ASP.NET MVC Framework would give you a much more familiar separation. Because there is no viewstate, etc in the MVC Framework you won't have to worry about JavaScript being dumped into your pages. The only JavaScript calls you see will be ones that you manually add. You can, for the most part, separate HTML / CSS / JS like you would in a different framework. | [
"javascript",
"html",
"css",
"asp.net-mvc"
] | 8 | 5 | 1,069 | 4 | 0 | 2008-09-11T13:02:52.507000 | 2008-09-11T13:07:47.003000 |
56,500 | 56,514 | Can't access variable in C++ DLL from a C app | I'm stuck on a fix to a legacy Visual C++ 6 app. In the C++ DLL source I have put extern "C" _declspec(dllexport) char* MyNewVariable = 0; which results in MyNewVariable showing up (nicely undecorated) in the export table (as shown by dumpbin /exports blah.dll). However, I can't figure out how to declare the variable so that I can access it in a C source file. I have tried various things, including _declspec(dllimport) char* MyNewVariable; but that just gives me a linker error: unresolved external symbol "__declspec(dllimport) char * MyNewVariable" (__imp_?MyNewVariable@@3PADA) extern "C" _declspec(dllimport) char* MyNewVariable; as suggested by Tony (and as I tried before) results in a different expected decoration, but still hasn't removed it: unresolved external symbol __imp__MyNewVariable How do I write the declaration so that the C++ DLL variable is accessible from the C app? The Answer As identified by botismarius and others (many thanks to all), I needed to link with the DLL's.lib. To prevent the name being mangled I needed to declare it (in the C source) with no decorators, which means I needed to use the.lib file. | you must link against the lib generated after compiling the DLL. In the linker options of the project, you must add the.lib file. And yes, you should also declare the variable as: extern "C" { declspec(dllimport) char MyNewVariable; } | Can't access variable in C++ DLL from a C app I'm stuck on a fix to a legacy Visual C++ 6 app. In the C++ DLL source I have put extern "C" _declspec(dllexport) char* MyNewVariable = 0; which results in MyNewVariable showing up (nicely undecorated) in the export table (as shown by dumpbin /exports blah.dll). However, I can't figure out how to declare the variable so that I can access it in a C source file. I have tried various things, including _declspec(dllimport) char* MyNewVariable; but that just gives me a linker error: unresolved external symbol "__declspec(dllimport) char * MyNewVariable" (__imp_?MyNewVariable@@3PADA) extern "C" _declspec(dllimport) char* MyNewVariable; as suggested by Tony (and as I tried before) results in a different expected decoration, but still hasn't removed it: unresolved external symbol __imp__MyNewVariable How do I write the declaration so that the C++ DLL variable is accessible from the C app? The Answer As identified by botismarius and others (many thanks to all), I needed to link with the DLL's.lib. To prevent the name being mangled I needed to declare it (in the C source) with no decorators, which means I needed to use the.lib file. | TITLE:
Can't access variable in C++ DLL from a C app
QUESTION:
I'm stuck on a fix to a legacy Visual C++ 6 app. In the C++ DLL source I have put extern "C" _declspec(dllexport) char* MyNewVariable = 0; which results in MyNewVariable showing up (nicely undecorated) in the export table (as shown by dumpbin /exports blah.dll). However, I can't figure out how to declare the variable so that I can access it in a C source file. I have tried various things, including _declspec(dllimport) char* MyNewVariable; but that just gives me a linker error: unresolved external symbol "__declspec(dllimport) char * MyNewVariable" (__imp_?MyNewVariable@@3PADA) extern "C" _declspec(dllimport) char* MyNewVariable; as suggested by Tony (and as I tried before) results in a different expected decoration, but still hasn't removed it: unresolved external symbol __imp__MyNewVariable How do I write the declaration so that the C++ DLL variable is accessible from the C app? The Answer As identified by botismarius and others (many thanks to all), I needed to link with the DLL's.lib. To prevent the name being mangled I needed to declare it (in the C source) with no decorators, which means I needed to use the.lib file.
ANSWER:
you must link against the lib generated after compiling the DLL. In the linker options of the project, you must add the.lib file. And yes, you should also declare the variable as: extern "C" { declspec(dllimport) char MyNewVariable; } | [
"c++",
"c",
"interop",
"name-decoration"
] | 8 | 5 | 6,905 | 7 | 0 | 2008-09-11T13:15:18.810000 | 2008-09-11T13:22:07.170000 |
56,518 | 56,539 | Is there any difference between type? and Nullable<type>? | In C# are the nullable primitive types (i.e. bool? ) just aliases for their corresponding Nullable type or is there a difference between the two? | If you look at the IL using Ildasm, you'll find that they both compile down to Nullable. | Is there any difference between type? and Nullable<type>? In C# are the nullable primitive types (i.e. bool? ) just aliases for their corresponding Nullable type or is there a difference between the two? | TITLE:
Is there any difference between type? and Nullable<type>?
QUESTION:
In C# are the nullable primitive types (i.e. bool? ) just aliases for their corresponding Nullable type or is there a difference between the two?
ANSWER:
If you look at the IL using Ildasm, you'll find that they both compile down to Nullable. | [
"c#",
".net",
"nullable"
] | 52 | 67 | 41,856 | 9 | 0 | 2008-09-11T13:25:20.563000 | 2008-09-11T13:36:33.017000 |
56,521 | 56,533 | Windows Forms Designer upset by a control with a nullable property | I have a "numeric textbox" in C#.NET which is nothing more than a derivation of Textbox, with some added logic to prevent the user entering anything non-numeric. As part of this, I have added a Value property of type double? (or Nullable ). It's nullable to support the case where the user doesn't enter anything. The control works fine when run, but the Windows Forms designer doesn't seem to like dealing with it much. When the control is added to a form, the following line of code is generated in InitializeComponent(): this.numericTextBox1.Value = 1; Remember 'Value' is of type Nullable. This generates the following warning whenever I try to reopen the form in the Designer: Object of type 'System.Int32' cannot be converted to type 'System.Nullable`1[System.Double]'. As a result, the form cannot be viewed in the Designer until I manually remove that line and rebuild - after which it's regenerated as soon as I save any changes. Annoying. Any suggestions? | Or, if you don't want the designer adding any code at all... add this to the Property. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] | Windows Forms Designer upset by a control with a nullable property I have a "numeric textbox" in C#.NET which is nothing more than a derivation of Textbox, with some added logic to prevent the user entering anything non-numeric. As part of this, I have added a Value property of type double? (or Nullable ). It's nullable to support the case where the user doesn't enter anything. The control works fine when run, but the Windows Forms designer doesn't seem to like dealing with it much. When the control is added to a form, the following line of code is generated in InitializeComponent(): this.numericTextBox1.Value = 1; Remember 'Value' is of type Nullable. This generates the following warning whenever I try to reopen the form in the Designer: Object of type 'System.Int32' cannot be converted to type 'System.Nullable`1[System.Double]'. As a result, the form cannot be viewed in the Designer until I manually remove that line and rebuild - after which it's regenerated as soon as I save any changes. Annoying. Any suggestions? | TITLE:
Windows Forms Designer upset by a control with a nullable property
QUESTION:
I have a "numeric textbox" in C#.NET which is nothing more than a derivation of Textbox, with some added logic to prevent the user entering anything non-numeric. As part of this, I have added a Value property of type double? (or Nullable ). It's nullable to support the case where the user doesn't enter anything. The control works fine when run, but the Windows Forms designer doesn't seem to like dealing with it much. When the control is added to a form, the following line of code is generated in InitializeComponent(): this.numericTextBox1.Value = 1; Remember 'Value' is of type Nullable. This generates the following warning whenever I try to reopen the form in the Designer: Object of type 'System.Int32' cannot be converted to type 'System.Nullable`1[System.Double]'. As a result, the form cannot be viewed in the Designer until I manually remove that line and rebuild - after which it's regenerated as soon as I save any changes. Annoying. Any suggestions?
ANSWER:
Or, if you don't want the designer adding any code at all... add this to the Property. [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] | [
"c#",
"winforms",
"nullable"
] | 2 | 3 | 1,145 | 3 | 0 | 2008-09-11T13:26:47.860000 | 2008-09-11T13:34:28.577000 |
56,543 | 56,552 | Recovering from a slightly out of date subversion repository backup | A problem I ran into a while back I never found a good solution for... Say you have a working copy checked out from subversion at revision 7500, and the disk holding the current repository dies. You've got a backup of the repository at, say, revision 7450. It's easy to restore the repository backup, but any attempt to use the working copy against it gives an error saying that revision 7500 doesn't exist in the repository. What is the best way to check in one gigantic revision to bring the content of the repository up to match the content of the working copy and get he working copy back to a functional state? (Ideally I'd like something easier than having to check out a brand new working copy and then copying over all the files manually - I think at the time the working copies were used to configuration manage servers, so it was a real pain to have to check out clean working copies) | You could check out a rev.7450 copy somewhere, then export your 7500 copy (to remove the.svn folders). Drag the exported copy (which is the latest copy) over the 7450 copy. All the new files should simply overwrite the older ones, leaving the.svn folders the same. Subversion will assume you just made a bunch of changes to 7450, and the next checkin will set it as 7451. | Recovering from a slightly out of date subversion repository backup A problem I ran into a while back I never found a good solution for... Say you have a working copy checked out from subversion at revision 7500, and the disk holding the current repository dies. You've got a backup of the repository at, say, revision 7450. It's easy to restore the repository backup, but any attempt to use the working copy against it gives an error saying that revision 7500 doesn't exist in the repository. What is the best way to check in one gigantic revision to bring the content of the repository up to match the content of the working copy and get he working copy back to a functional state? (Ideally I'd like something easier than having to check out a brand new working copy and then copying over all the files manually - I think at the time the working copies were used to configuration manage servers, so it was a real pain to have to check out clean working copies) | TITLE:
Recovering from a slightly out of date subversion repository backup
QUESTION:
A problem I ran into a while back I never found a good solution for... Say you have a working copy checked out from subversion at revision 7500, and the disk holding the current repository dies. You've got a backup of the repository at, say, revision 7450. It's easy to restore the repository backup, but any attempt to use the working copy against it gives an error saying that revision 7500 doesn't exist in the repository. What is the best way to check in one gigantic revision to bring the content of the repository up to match the content of the working copy and get he working copy back to a functional state? (Ideally I'd like something easier than having to check out a brand new working copy and then copying over all the files manually - I think at the time the working copies were used to configuration manage servers, so it was a real pain to have to check out clean working copies)
ANSWER:
You could check out a rev.7450 copy somewhere, then export your 7500 copy (to remove the.svn folders). Drag the exported copy (which is the latest copy) over the 7450 copy. All the new files should simply overwrite the older ones, leaving the.svn folders the same. Subversion will assume you just made a bunch of changes to 7450, and the next checkin will set it as 7451. | [
"svn",
"version-control",
"backup",
"system-administration"
] | 7 | 6 | 967 | 4 | 0 | 2008-09-11T13:38:17.287000 | 2008-09-11T13:41:59.777000 |
56,546 | 56,578 | activerecord as model, is this a good idea? | Recently thanks to rails' popularity, many people start using activerecord as model. however, before I heard of rails (my peer group was not a fan of open source stuff, we were taught in a.NET school...) and while I was doing my final year project, i found this definition for a model The model represents enterprise data and the business rules that govern access to and updates of this data. Often the model serves as a software approximation to a real-world process, so simple real-world modeling techniques apply when defining the model. it doesn't say the model should represent one table as what activerecord does. And normally within a transaction, one may have to query a few unrelated tables and then manipulate data from different tables... so if activerecord is used as model, then either one would have to cram all the logic code into the controller (which is kinda popular in some php frameworks) that makes it difficult to test or hack the activerecord model so that it performs database operation on not only the table it maps to, but also other related tables as well... so, what is so great about abusing (IMHO) activerecord as the model in a MVC architectural pattern? | Martin Fowler described this pattern in Patterns of Enterprise Application Architecture together with two other patterns or architectures. These patterns are good for different situations and different amounts of complexity. If you want to so only simple stuff you can use Transaction Script. This is an architecture you saw in lot's of old ASP and PHP pages where a single script contained the business logic, data-access logic and presentation logic. This falls apart fast when things get more complicated. The next thing you can do is add some separation between presentation and model. This is activerecord. The model is still tied to the database but you've a bit more flexibility because you can reuse your model/dataccess between views/pages/whatever. It's not as flexible as it could be but depending on your data-access solution it can be flexible enough. Frameworks like CSLA in.Net have a lot of aspects from this patterm (I think Entity Framework looks a bit too much like this too). It can still handle a lot of complexity without becoming unmaintainable. The next step is separating your data-access layer and your model. This usually requires a good OR mapper or a lot of work. So not everyone wants to go this way. Lot's of methodologies like domain driven design perscribe this approach. So it's all a matter of context. What do you need and what is the best solution. I even still use transaction-script sometimes for simple single use code. | activerecord as model, is this a good idea? Recently thanks to rails' popularity, many people start using activerecord as model. however, before I heard of rails (my peer group was not a fan of open source stuff, we were taught in a.NET school...) and while I was doing my final year project, i found this definition for a model The model represents enterprise data and the business rules that govern access to and updates of this data. Often the model serves as a software approximation to a real-world process, so simple real-world modeling techniques apply when defining the model. it doesn't say the model should represent one table as what activerecord does. And normally within a transaction, one may have to query a few unrelated tables and then manipulate data from different tables... so if activerecord is used as model, then either one would have to cram all the logic code into the controller (which is kinda popular in some php frameworks) that makes it difficult to test or hack the activerecord model so that it performs database operation on not only the table it maps to, but also other related tables as well... so, what is so great about abusing (IMHO) activerecord as the model in a MVC architectural pattern? | TITLE:
activerecord as model, is this a good idea?
QUESTION:
Recently thanks to rails' popularity, many people start using activerecord as model. however, before I heard of rails (my peer group was not a fan of open source stuff, we were taught in a.NET school...) and while I was doing my final year project, i found this definition for a model The model represents enterprise data and the business rules that govern access to and updates of this data. Often the model serves as a software approximation to a real-world process, so simple real-world modeling techniques apply when defining the model. it doesn't say the model should represent one table as what activerecord does. And normally within a transaction, one may have to query a few unrelated tables and then manipulate data from different tables... so if activerecord is used as model, then either one would have to cram all the logic code into the controller (which is kinda popular in some php frameworks) that makes it difficult to test or hack the activerecord model so that it performs database operation on not only the table it maps to, but also other related tables as well... so, what is so great about abusing (IMHO) activerecord as the model in a MVC architectural pattern?
ANSWER:
Martin Fowler described this pattern in Patterns of Enterprise Application Architecture together with two other patterns or architectures. These patterns are good for different situations and different amounts of complexity. If you want to so only simple stuff you can use Transaction Script. This is an architecture you saw in lot's of old ASP and PHP pages where a single script contained the business logic, data-access logic and presentation logic. This falls apart fast when things get more complicated. The next thing you can do is add some separation between presentation and model. This is activerecord. The model is still tied to the database but you've a bit more flexibility because you can reuse your model/dataccess between views/pages/whatever. It's not as flexible as it could be but depending on your data-access solution it can be flexible enough. Frameworks like CSLA in.Net have a lot of aspects from this patterm (I think Entity Framework looks a bit too much like this too). It can still handle a lot of complexity without becoming unmaintainable. The next step is separating your data-access layer and your model. This usually requires a good OR mapper or a lot of work. So not everyone wants to go this way. Lot's of methodologies like domain driven design perscribe this approach. So it's all a matter of context. What do you need and what is the best solution. I even still use transaction-script sometimes for simple single use code. | [
"php",
"model-view-controller",
"activerecord"
] | 7 | 8 | 2,269 | 3 | 0 | 2008-09-11T13:40:04.880000 | 2008-09-11T13:50:52.810000 |
56,547 | 56,612 | How do you perform a CROSS JOIN with LINQ to SQL? | How do you perform a CROSS JOIN with LINQ to SQL? | A cross-join is simply the Cartesian product of two sets. There's no explicit join operator for it. var combo = from p in people from c in cars select new { p.Name, c.Make, c.Model, c.Colour }; | How do you perform a CROSS JOIN with LINQ to SQL? How do you perform a CROSS JOIN with LINQ to SQL? | TITLE:
How do you perform a CROSS JOIN with LINQ to SQL?
QUESTION:
How do you perform a CROSS JOIN with LINQ to SQL?
ANSWER:
A cross-join is simply the Cartesian product of two sets. There's no explicit join operator for it. var combo = from p in people from c in cars select new { p.Name, c.Make, c.Model, c.Colour }; | [
"c#",
"linq",
"linq-to-sql",
"cross-join"
] | 137 | 178 | 68,447 | 5 | 0 | 2008-09-11T13:40:19.203000 | 2008-09-11T14:00:40.963000 |
56,553 | 56,952 | Using an external "windows"-keyboard under Mac OS X | I use a MacBook, but I've got a usual keyboard attached to it. The problem is that the keys don't exactly map 1-to-1. One thing is the APPLE and ALT keys. They map to WIN and ALT, but they are usually physically inverted, so if you want to use them with the same layout you have to invert them in the OS. The Function keys work differently too. Fx on the external = Fn + Fx on the MacBook keyboard. And then there are all the insert, delete, keys. So, the question is, how do you come around this? Now I remap all the things I want at the System Preferences panel, but when I unplug the external keyboard it's all messed up. Is there a way to remap keys only for the external one? Some model of keyboard can store it's own mappings without needing the OS? Am I the only one who is bothered by this? (I would like to avoid buying an external mac keyboard, because I wanted to try one of the ergonomic models, and as far as I know, there are no mac ergonomic models) Update: Thanks for the responses, I fixed this. To set the control keys for different keyboards, you have to go to System Preferences/Modifier Keys, then the drop down menu Select Keyboard allows you to choose one particular keyboard and set these keys. Works after unpluging/pluging it seems The suggestion from @Matthew Schinckel seems to work for the rest of the issues (function keys,...). I didn't try it yet, as the commands keys were my biggest gripe. | In OS X 10.5 they allow you to have different keyboard setups for different keyboards. This works most of the time. I've had issues with very old keyboards that are plugged in via a PS2 to USB but otherwise it works fine. | Using an external "windows"-keyboard under Mac OS X I use a MacBook, but I've got a usual keyboard attached to it. The problem is that the keys don't exactly map 1-to-1. One thing is the APPLE and ALT keys. They map to WIN and ALT, but they are usually physically inverted, so if you want to use them with the same layout you have to invert them in the OS. The Function keys work differently too. Fx on the external = Fn + Fx on the MacBook keyboard. And then there are all the insert, delete, keys. So, the question is, how do you come around this? Now I remap all the things I want at the System Preferences panel, but when I unplug the external keyboard it's all messed up. Is there a way to remap keys only for the external one? Some model of keyboard can store it's own mappings without needing the OS? Am I the only one who is bothered by this? (I would like to avoid buying an external mac keyboard, because I wanted to try one of the ergonomic models, and as far as I know, there are no mac ergonomic models) Update: Thanks for the responses, I fixed this. To set the control keys for different keyboards, you have to go to System Preferences/Modifier Keys, then the drop down menu Select Keyboard allows you to choose one particular keyboard and set these keys. Works after unpluging/pluging it seems The suggestion from @Matthew Schinckel seems to work for the rest of the issues (function keys,...). I didn't try it yet, as the commands keys were my biggest gripe. | TITLE:
Using an external "windows"-keyboard under Mac OS X
QUESTION:
I use a MacBook, but I've got a usual keyboard attached to it. The problem is that the keys don't exactly map 1-to-1. One thing is the APPLE and ALT keys. They map to WIN and ALT, but they are usually physically inverted, so if you want to use them with the same layout you have to invert them in the OS. The Function keys work differently too. Fx on the external = Fn + Fx on the MacBook keyboard. And then there are all the insert, delete, keys. So, the question is, how do you come around this? Now I remap all the things I want at the System Preferences panel, but when I unplug the external keyboard it's all messed up. Is there a way to remap keys only for the external one? Some model of keyboard can store it's own mappings without needing the OS? Am I the only one who is bothered by this? (I would like to avoid buying an external mac keyboard, because I wanted to try one of the ergonomic models, and as far as I know, there are no mac ergonomic models) Update: Thanks for the responses, I fixed this. To set the control keys for different keyboards, you have to go to System Preferences/Modifier Keys, then the drop down menu Select Keyboard allows you to choose one particular keyboard and set these keys. Works after unpluging/pluging it seems The suggestion from @Matthew Schinckel seems to work for the rest of the issues (function keys,...). I didn't try it yet, as the commands keys were my biggest gripe.
ANSWER:
In OS X 10.5 they allow you to have different keyboard setups for different keyboards. This works most of the time. I've had issues with very old keyboards that are plugged in via a PS2 to USB but otherwise it works fine. | [
"macos",
"keyboard",
"ergonomics"
] | 31 | 26 | 48,728 | 4 | 0 | 2008-09-11T13:42:34.237000 | 2008-09-11T15:48:28.083000 |
56,554 | 56,671 | What is the proper regular expression for an unescaped backslash before a character? | Let's say I want to represent \q (or any other particular "backslash-escaped character"). That is, I want to match \q but not \\q, since the latter is a backslash-escaped backslash followed by a q. Yet \\\q would match, since it's a backslash-escaped backslash followed by a backslash-escaped q. (Well, it would match the \q at the end, not the \\ at the beginning.) I know I need a negative lookbehind, but they always tie my head up in knots, especially since the backslashes themselves have to be escaped in the regexp. | Updated: My new and improved Perl regex, supporting more than 3 backslashes: /(? \\\\)* # an even number of backslashes \\q # Followed by a \q /x; or if your regex library doesn't support extended syntax. /(? \\\\)*\\q/ Output of my test program: q does not match \q does match \\q does not match \\\q does match \\\\q does not match \\\\\q does match Older version /(?:(? | What is the proper regular expression for an unescaped backslash before a character? Let's say I want to represent \q (or any other particular "backslash-escaped character"). That is, I want to match \q but not \\q, since the latter is a backslash-escaped backslash followed by a q. Yet \\\q would match, since it's a backslash-escaped backslash followed by a backslash-escaped q. (Well, it would match the \q at the end, not the \\ at the beginning.) I know I need a negative lookbehind, but they always tie my head up in knots, especially since the backslashes themselves have to be escaped in the regexp. | TITLE:
What is the proper regular expression for an unescaped backslash before a character?
QUESTION:
Let's say I want to represent \q (or any other particular "backslash-escaped character"). That is, I want to match \q but not \\q, since the latter is a backslash-escaped backslash followed by a q. Yet \\\q would match, since it's a backslash-escaped backslash followed by a backslash-escaped q. (Well, it would match the \q at the end, not the \\ at the beginning.) I know I need a negative lookbehind, but they always tie my head up in knots, especially since the backslashes themselves have to be escaped in the regexp.
ANSWER:
Updated: My new and improved Perl regex, supporting more than 3 backslashes: /(? \\\\)* # an even number of backslashes \\q # Followed by a \q /x; or if your regex library doesn't support extended syntax. /(? \\\\)*\\q/ Output of my test program: q does not match \q does match \\q does not match \\\q does match \\\\q does not match \\\\\q does match Older version /(?:(? | [
"regex"
] | 11 | 19 | 14,286 | 4 | 0 | 2008-09-11T13:42:35.157000 | 2008-09-11T14:25:06.177000 |
56,561 | 56,694 | What is the best way to convert between char* and System::String in C++/CLI | What is the approved way to convert from char* to System::string and back in C++/CLI? I found a few references to marshal_to<> templated functions on Google, but it appears that this feature never made the cut for Visual Studio 2005 (and isn't in Visual Studio 2008 either, AFAIK). I have also seen some code on Stan Lippman's blog, but it's from 2004. I have also seen Marshal::StringToHGlobalAnsi(). Is there a method that is considered "best practice"? | There's a good overview here (this marshaling support added for VS2008): http://www.codeproject.com/KB/mcpp/OrcasMarshalAs.aspx | What is the best way to convert between char* and System::String in C++/CLI What is the approved way to convert from char* to System::string and back in C++/CLI? I found a few references to marshal_to<> templated functions on Google, but it appears that this feature never made the cut for Visual Studio 2005 (and isn't in Visual Studio 2008 either, AFAIK). I have also seen some code on Stan Lippman's blog, but it's from 2004. I have also seen Marshal::StringToHGlobalAnsi(). Is there a method that is considered "best practice"? | TITLE:
What is the best way to convert between char* and System::String in C++/CLI
QUESTION:
What is the approved way to convert from char* to System::string and back in C++/CLI? I found a few references to marshal_to<> templated functions on Google, but it appears that this feature never made the cut for Visual Studio 2005 (and isn't in Visual Studio 2008 either, AFAIK). I have also seen some code on Stan Lippman's blog, but it's from 2004. I have also seen Marshal::StringToHGlobalAnsi(). Is there a method that is considered "best practice"?
ANSWER:
There's a good overview here (this marshaling support added for VS2008): http://www.codeproject.com/KB/mcpp/OrcasMarshalAs.aspx | [
".net",
"string",
"c++-cli"
] | 50 | 18 | 72,661 | 5 | 0 | 2008-09-11T13:45:30.827000 | 2008-09-11T14:34:28.433000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.