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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
44,630 | 44,647 | version control practice | In my current job the supervisor's practice is to only check in production ready code. Most recently the project I was on involved work by 3 different developers with some file overlap. This meant manually integrating changes despite the fact that some changes took a day and then it was done. I wanted to see if this was a common practice and get suggestions on how to change this practice with the knowledge that many times my opinion means little in the grand scheme of things. | You can use various ways to handle this situation, depending on your source control system. Private branches: Allow you to check in and work on code while you go, merging back and forth at appropriate times. Shelvesets/pacakaged changesets: Allow you to store changesets and send them around for review - ensuring they're production ready before check in. As to whether this is an appropriate way to work, we don't allow check-in to main branches without prior review. To pass review your code must pass various automated tools, and then must be acceptable to your peer reviewer. For some definitions of "production ready" - this is it. Therefore, we do something like what you do. However, we use private branches to ensure that check-ins can still be made while this is in progress, and that other check-ins don't have to interfere. If production ready means tested in an integration environment, then it sounds like you may need staging branches or something similar. | version control practice In my current job the supervisor's practice is to only check in production ready code. Most recently the project I was on involved work by 3 different developers with some file overlap. This meant manually integrating changes despite the fact that some changes took a day and then it was done. I wanted to see if this was a common practice and get suggestions on how to change this practice with the knowledge that many times my opinion means little in the grand scheme of things. | TITLE:
version control practice
QUESTION:
In my current job the supervisor's practice is to only check in production ready code. Most recently the project I was on involved work by 3 different developers with some file overlap. This meant manually integrating changes despite the fact that some changes took a day and then it was done. I wanted to see if this was a common practice and get suggestions on how to change this practice with the knowledge that many times my opinion means little in the grand scheme of things.
ANSWER:
You can use various ways to handle this situation, depending on your source control system. Private branches: Allow you to check in and work on code while you go, merging back and forth at appropriate times. Shelvesets/pacakaged changesets: Allow you to store changesets and send them around for review - ensuring they're production ready before check in. As to whether this is an appropriate way to work, we don't allow check-in to main branches without prior review. To pass review your code must pass various automated tools, and then must be acceptable to your peer reviewer. For some definitions of "production ready" - this is it. Therefore, we do something like what you do. However, we use private branches to ensure that check-ins can still be made while this is in progress, and that other check-ins don't have to interfere. If production ready means tested in an integration environment, then it sounds like you may need staging branches or something similar. | [
"version-control"
] | 5 | 4 | 760 | 11 | 0 | 2008-09-04T19:51:26.267000 | 2008-09-04T19:59:30.287000 |
44,637 | 44,648 | How to start using ndepend? | I recently downloaded ndepend and ran an analysis on an open source project I participate in. I did not now where to look next - a bit of visual and information overload and it turned out I don't even know where to start. Can anyone suggest starting points? What information should I look for first? What points out problems in the code (in a BIG way)? What would the low hanging fruit that can immediately seen? | Scott Hanselman / Stuart Celarier / Patrick Cauldwell's poster with ndepend metrics has some useful information on it. Rather than trying to break down all the heuristics being used I'd focus on only a few at a time starting with "zone of pain / zone of uselessness" and cyclomatic complexity. There is also a podcast which covers some of the basics of the tool. Between that and running nDepend on a few different projects you may be able to start gathering useful data that you can make into insights. | How to start using ndepend? I recently downloaded ndepend and ran an analysis on an open source project I participate in. I did not now where to look next - a bit of visual and information overload and it turned out I don't even know where to start. Can anyone suggest starting points? What information should I look for first? What points out problems in the code (in a BIG way)? What would the low hanging fruit that can immediately seen? | TITLE:
How to start using ndepend?
QUESTION:
I recently downloaded ndepend and ran an analysis on an open source project I participate in. I did not now where to look next - a bit of visual and information overload and it turned out I don't even know where to start. Can anyone suggest starting points? What information should I look for first? What points out problems in the code (in a BIG way)? What would the low hanging fruit that can immediately seen?
ANSWER:
Scott Hanselman / Stuart Celarier / Patrick Cauldwell's poster with ndepend metrics has some useful information on it. Rather than trying to break down all the heuristics being used I'd focus on only a few at a time starting with "zone of pain / zone of uselessness" and cyclomatic complexity. There is also a podcast which covers some of the basics of the tool. Between that and running nDepend on a few different projects you may be able to start gathering useful data that you can make into insights. | [
".net",
"static-analysis",
"ndepend"
] | 19 | 15 | 1,510 | 3 | 0 | 2008-09-04T19:54:37.693000 | 2008-09-04T20:00:04.123000 |
44,644 | 46,874 | Identifying ASP.NET web service references | At my day job we have load balanced web servers which talk to load balanced app servers via web services (and lately WCF). At any given time, we have 4-6 different teams that have the ability to add new web sites or services or consume existing services. We probably have about 20-30 different web applications and corresponding services. Unfortunately, given that we have no centralized control over this due to competing priorities, org structures, project timelines, financial buckets, etc., it is quite a mess. We have a variety of services that are reused, but a bunch that are specific to a front-end. Ideally we would have better control over this situation, and we are trying to get control over it, but that is taking a while. One thing we would like to do is find out more about what all of the inter-relationships between web sites and the app servers. I have used Reflector to find dependencies among assemblies, but would like to be able to see the traffic patterns between services. What are the options for trying to map out web service relationships? For the most part, we are mainly talking about internal services (web to app, app to app, batch to app, etc.). Off the top of my head, I can think of two ways to approach it: Analyze assemblies for any web references. The drawback here is that not everything is a web reference and I'm not sure how WCF connections are listed. However, this would at least be a start for finding 80% of the connections. Does anyone know of any tools that can do that analysis? Like I said, I've used Reflector for assembly references but can't find anything for web references. Possibly tap into IIS and passively monitor the traffic coming in and out and somehow figure out what is being called and where from. We are looking at enterprise tools that could help but it would be a while before they are implemented (and cost a lot). But is there anything out there that could help out quickly and cheaply? One tool in particular (AmberPoint) can tap into IIS on the servers and monitor inbound and outbound traffic, adds a little special sauce and begin to build a map of the traffic. Very nice, but costs a bundle. I know, I know, how the heck did you get into this mess in the first place? Beats me, just trying to help us get control of it and get out of it. Thanks, Matt | You need a service registry (UDDI??)... If you had a means to catalog these services and their consumers, it would make this job of dependency discovery a lot easier. That is not an easy solution, though. It takes time and documentation to get a catalog in place. I think the quickest solution would be to query your IIS logs and find source URLs which originate from your own servers. You would at least be able to track down which servers your consumers are coming from. Also, if you already have some kind of authentication mechanism in place, you could trace who is using a particular service based on login. You are right about AmberPoint. There are other tools that catalog the service traffic and provide reports showing what is happening to your services. Systinet, SOA Software and Actional also has a products similar to Amberpoint but Amberpoint has a free-ware version, I believe. | Identifying ASP.NET web service references At my day job we have load balanced web servers which talk to load balanced app servers via web services (and lately WCF). At any given time, we have 4-6 different teams that have the ability to add new web sites or services or consume existing services. We probably have about 20-30 different web applications and corresponding services. Unfortunately, given that we have no centralized control over this due to competing priorities, org structures, project timelines, financial buckets, etc., it is quite a mess. We have a variety of services that are reused, but a bunch that are specific to a front-end. Ideally we would have better control over this situation, and we are trying to get control over it, but that is taking a while. One thing we would like to do is find out more about what all of the inter-relationships between web sites and the app servers. I have used Reflector to find dependencies among assemblies, but would like to be able to see the traffic patterns between services. What are the options for trying to map out web service relationships? For the most part, we are mainly talking about internal services (web to app, app to app, batch to app, etc.). Off the top of my head, I can think of two ways to approach it: Analyze assemblies for any web references. The drawback here is that not everything is a web reference and I'm not sure how WCF connections are listed. However, this would at least be a start for finding 80% of the connections. Does anyone know of any tools that can do that analysis? Like I said, I've used Reflector for assembly references but can't find anything for web references. Possibly tap into IIS and passively monitor the traffic coming in and out and somehow figure out what is being called and where from. We are looking at enterprise tools that could help but it would be a while before they are implemented (and cost a lot). But is there anything out there that could help out quickly and cheaply? One tool in particular (AmberPoint) can tap into IIS on the servers and monitor inbound and outbound traffic, adds a little special sauce and begin to build a map of the traffic. Very nice, but costs a bundle. I know, I know, how the heck did you get into this mess in the first place? Beats me, just trying to help us get control of it and get out of it. Thanks, Matt | TITLE:
Identifying ASP.NET web service references
QUESTION:
At my day job we have load balanced web servers which talk to load balanced app servers via web services (and lately WCF). At any given time, we have 4-6 different teams that have the ability to add new web sites or services or consume existing services. We probably have about 20-30 different web applications and corresponding services. Unfortunately, given that we have no centralized control over this due to competing priorities, org structures, project timelines, financial buckets, etc., it is quite a mess. We have a variety of services that are reused, but a bunch that are specific to a front-end. Ideally we would have better control over this situation, and we are trying to get control over it, but that is taking a while. One thing we would like to do is find out more about what all of the inter-relationships between web sites and the app servers. I have used Reflector to find dependencies among assemblies, but would like to be able to see the traffic patterns between services. What are the options for trying to map out web service relationships? For the most part, we are mainly talking about internal services (web to app, app to app, batch to app, etc.). Off the top of my head, I can think of two ways to approach it: Analyze assemblies for any web references. The drawback here is that not everything is a web reference and I'm not sure how WCF connections are listed. However, this would at least be a start for finding 80% of the connections. Does anyone know of any tools that can do that analysis? Like I said, I've used Reflector for assembly references but can't find anything for web references. Possibly tap into IIS and passively monitor the traffic coming in and out and somehow figure out what is being called and where from. We are looking at enterprise tools that could help but it would be a while before they are implemented (and cost a lot). But is there anything out there that could help out quickly and cheaply? One tool in particular (AmberPoint) can tap into IIS on the servers and monitor inbound and outbound traffic, adds a little special sauce and begin to build a map of the traffic. Very nice, but costs a bundle. I know, I know, how the heck did you get into this mess in the first place? Beats me, just trying to help us get control of it and get out of it. Thanks, Matt
ANSWER:
You need a service registry (UDDI??)... If you had a means to catalog these services and their consumers, it would make this job of dependency discovery a lot easier. That is not an easy solution, though. It takes time and documentation to get a catalog in place. I think the quickest solution would be to query your IIS logs and find source URLs which originate from your own servers. You would at least be able to track down which servers your consumers are coming from. Also, if you already have some kind of authentication mechanism in place, you could trace who is using a particular service based on login. You are right about AmberPoint. There are other tools that catalog the service traffic and provide reports showing what is happening to your services. Systinet, SOA Software and Actional also has a products similar to Amberpoint but Amberpoint has a free-ware version, I believe. | [
"web-services",
"iis",
"reflection",
"esb"
] | 0 | 0 | 476 | 2 | 0 | 2008-09-04T19:58:27.980000 | 2008-09-05T20:59:34.720000 |
44,656 | 44,761 | Is there a good method in C# for throwing an exception on a given thread | The code that I want to write is like this: void MethodOnThreadA() { for (;;) { // Do stuff if (ErrorConditionMet) ThrowOnThread(threadB, new MyException(...)); } }
void MethodOnThreadB() { try { for (;;) { // Do stuff } } catch (MyException ex) { // Do the right thing for this exception. } } I know I can have thread B periodically check, in thread safe way, to see if a flag has been set by thread A, but that makes the code more complicated. Is there a better mechanism that I can use? Here is a more fleshed out example of periodically checking: Dictionary exceptionDictionary = new Dictionary ();
void ThrowOnThread(Thread thread, Exception ex) { // the exception passed in is going to be handed off to another thread, // so it needs to be thread safe. lock (exceptionDictionary) { exceptionDictionary[thread] = ex; } }
void ExceptionCheck() { lock (exceptionDictionary) { Exception ex; if (exceptionDictionary.TryGetValue(Thread.CurrentThread, out ex)) throw ex; } }
void MethodOnThreadA() { for (;;) { // Do stuff if (ErrorConditionMet) ThrowOnThread(threadB, new MyException(...)); } }
void MethodOnThreadB() { try { for (;;) { // Do stuff ExceptionCheck(); } } catch (MyException ex) { // Do the right thing for this exception. } } | This is NOT a good idea This article talks about ruby's timeout library. which throws exceptions across threads. It explains how doing such a thing is fundamentally broken. It's not just broken in ruby, it's broken anywhere that throws exceptions across threads. In a nutshell, what can (and does) happen is this: ThreadA: At some random time, throw an exception on thread B: ThreadB: try { //do stuff } finally { CloseResourceOne(); // ThreadA's exception gets thrown NOW, in the middle // of our finally block and resource two NEVER gets closed. // Obviously this is BAD, and the only way to stop is to NOT throw // exceptions across threads CloseResourceTwo(); } Your 'periodic checking' example is fine, as you're not actually throwing exceptions across threads. You're just setting a flag which says "throw an exception the next time you look at this flag", which is fine as it doesn't suffer from the "can be thrown in the middle of your catch or finally block" problem. However, if you're going to do that, you may as well just be setting an "exitnow" flag, and using that and save yourself the hassle of creating the exception object. A volatile bool will work just fine for that. | Is there a good method in C# for throwing an exception on a given thread The code that I want to write is like this: void MethodOnThreadA() { for (;;) { // Do stuff if (ErrorConditionMet) ThrowOnThread(threadB, new MyException(...)); } }
void MethodOnThreadB() { try { for (;;) { // Do stuff } } catch (MyException ex) { // Do the right thing for this exception. } } I know I can have thread B periodically check, in thread safe way, to see if a flag has been set by thread A, but that makes the code more complicated. Is there a better mechanism that I can use? Here is a more fleshed out example of periodically checking: Dictionary exceptionDictionary = new Dictionary ();
void ThrowOnThread(Thread thread, Exception ex) { // the exception passed in is going to be handed off to another thread, // so it needs to be thread safe. lock (exceptionDictionary) { exceptionDictionary[thread] = ex; } }
void ExceptionCheck() { lock (exceptionDictionary) { Exception ex; if (exceptionDictionary.TryGetValue(Thread.CurrentThread, out ex)) throw ex; } }
void MethodOnThreadA() { for (;;) { // Do stuff if (ErrorConditionMet) ThrowOnThread(threadB, new MyException(...)); } }
void MethodOnThreadB() { try { for (;;) { // Do stuff ExceptionCheck(); } } catch (MyException ex) { // Do the right thing for this exception. } } | TITLE:
Is there a good method in C# for throwing an exception on a given thread
QUESTION:
The code that I want to write is like this: void MethodOnThreadA() { for (;;) { // Do stuff if (ErrorConditionMet) ThrowOnThread(threadB, new MyException(...)); } }
void MethodOnThreadB() { try { for (;;) { // Do stuff } } catch (MyException ex) { // Do the right thing for this exception. } } I know I can have thread B periodically check, in thread safe way, to see if a flag has been set by thread A, but that makes the code more complicated. Is there a better mechanism that I can use? Here is a more fleshed out example of periodically checking: Dictionary exceptionDictionary = new Dictionary ();
void ThrowOnThread(Thread thread, Exception ex) { // the exception passed in is going to be handed off to another thread, // so it needs to be thread safe. lock (exceptionDictionary) { exceptionDictionary[thread] = ex; } }
void ExceptionCheck() { lock (exceptionDictionary) { Exception ex; if (exceptionDictionary.TryGetValue(Thread.CurrentThread, out ex)) throw ex; } }
void MethodOnThreadA() { for (;;) { // Do stuff if (ErrorConditionMet) ThrowOnThread(threadB, new MyException(...)); } }
void MethodOnThreadB() { try { for (;;) { // Do stuff ExceptionCheck(); } } catch (MyException ex) { // Do the right thing for this exception. } }
ANSWER:
This is NOT a good idea This article talks about ruby's timeout library. which throws exceptions across threads. It explains how doing such a thing is fundamentally broken. It's not just broken in ruby, it's broken anywhere that throws exceptions across threads. In a nutshell, what can (and does) happen is this: ThreadA: At some random time, throw an exception on thread B: ThreadB: try { //do stuff } finally { CloseResourceOne(); // ThreadA's exception gets thrown NOW, in the middle // of our finally block and resource two NEVER gets closed. // Obviously this is BAD, and the only way to stop is to NOT throw // exceptions across threads CloseResourceTwo(); } Your 'periodic checking' example is fine, as you're not actually throwing exceptions across threads. You're just setting a flag which says "throw an exception the next time you look at this flag", which is fine as it doesn't suffer from the "can be thrown in the middle of your catch or finally block" problem. However, if you're going to do that, you may as well just be setting an "exitnow" flag, and using that and save yourself the hassle of creating the exception object. A volatile bool will work just fine for that. | [
"c#",
"multithreading",
"exception"
] | 11 | 10 | 8,599 | 8 | 0 | 2008-09-04T20:03:50.527000 | 2008-09-04T20:55:16.097000 |
44,692 | 45,529 | dotNetNuke/Moodle integration | anyone out there have a moodle module for dotnetnuke, or some kind of integration setup that at least allows SSO? | This webpage provides details on how to implement Single Sign-on between DotNetNuke and Moodle. | dotNetNuke/Moodle integration anyone out there have a moodle module for dotnetnuke, or some kind of integration setup that at least allows SSO? | TITLE:
dotNetNuke/Moodle integration
QUESTION:
anyone out there have a moodle module for dotnetnuke, or some kind of integration setup that at least allows SSO?
ANSWER:
This webpage provides details on how to implement Single Sign-on between DotNetNuke and Moodle. | [
"dotnetnuke",
"single-sign-on",
"moodle"
] | 3 | 0 | 1,038 | 1 | 0 | 2008-09-04T20:22:11.230000 | 2008-09-05T10:56:46.667000 |
44,693 | 44,762 | Efficient alternatives for exposing a Collection | In C++, what alternatives do I have for exposing a collection, from the point of view of performance and data integrity? My problem is that I want to return an internal list of data to the caller, but I don't want to generate a copy. Thant leaves me with either returning a reference to the list, or a pointer to the list. However, I'm not crazy about letting the caller change the data, I just want to let it read the data. Do I have to choose between performance and data integrity? If so, is in general better to go one way or is it particular to the case? Are there other alternatives? | RichQ's answer is a reasonable technique, if you're using an array, vector, etc. If you're using a collection that isn't indexed by ordinal values... or think you might need to at some point in the near future... then you might want to consider exposing your own iterator type(s), and associated begin() / end() methods: class Blah { public: typedef std::vector mydata_collection; typedef myDataCollection::const_iterator mydata_const_iterator;
//...
mydata_const_iterator data_begin() const { return myPreciousData.begin(); } mydata_const_iterator data_end() const { return myPreciousData.end(); }
private: mydata_collection myPreciousData; };...which you can then use in the normal fashion: Blah blah; for (Blah::mydata_const_iterator itr = blah.data_begin(); itr!= blah.data_end(); ++itr) { //... } | Efficient alternatives for exposing a Collection In C++, what alternatives do I have for exposing a collection, from the point of view of performance and data integrity? My problem is that I want to return an internal list of data to the caller, but I don't want to generate a copy. Thant leaves me with either returning a reference to the list, or a pointer to the list. However, I'm not crazy about letting the caller change the data, I just want to let it read the data. Do I have to choose between performance and data integrity? If so, is in general better to go one way or is it particular to the case? Are there other alternatives? | TITLE:
Efficient alternatives for exposing a Collection
QUESTION:
In C++, what alternatives do I have for exposing a collection, from the point of view of performance and data integrity? My problem is that I want to return an internal list of data to the caller, but I don't want to generate a copy. Thant leaves me with either returning a reference to the list, or a pointer to the list. However, I'm not crazy about letting the caller change the data, I just want to let it read the data. Do I have to choose between performance and data integrity? If so, is in general better to go one way or is it particular to the case? Are there other alternatives?
ANSWER:
RichQ's answer is a reasonable technique, if you're using an array, vector, etc. If you're using a collection that isn't indexed by ordinal values... or think you might need to at some point in the near future... then you might want to consider exposing your own iterator type(s), and associated begin() / end() methods: class Blah { public: typedef std::vector mydata_collection; typedef myDataCollection::const_iterator mydata_const_iterator;
//...
mydata_const_iterator data_begin() const { return myPreciousData.begin(); } mydata_const_iterator data_end() const { return myPreciousData.end(); }
private: mydata_collection myPreciousData; };...which you can then use in the normal fashion: Blah blah; for (Blah::mydata_const_iterator itr = blah.data_begin(); itr!= blah.data_end(); ++itr) { //... } | [
"c++",
"performance",
"collections",
"data-integrity"
] | 12 | 5 | 714 | 10 | 0 | 2008-09-04T20:22:18.923000 | 2008-09-04T20:56:04.113000 |
44,714 | 44,738 | How to have two remote origins for Git? | Our git server will be local, but we want an server where our local repo is also kept online but only used in a push to fashion. How can one do that? | You can add remotes with git remote add You can then push to a remote with git push master:master to push your local master branch to the remote master branch. When you create a repo with git clone the remote is named origin but you can create a public repository for your online server and push to it with git push public master:master | How to have two remote origins for Git? Our git server will be local, but we want an server where our local repo is also kept online but only used in a push to fashion. How can one do that? | TITLE:
How to have two remote origins for Git?
QUESTION:
Our git server will be local, but we want an server where our local repo is also kept online but only used in a push to fashion. How can one do that?
ANSWER:
You can add remotes with git remote add You can then push to a remote with git push master:master to push your local master branch to the remote master branch. When you create a repo with git clone the remote is named origin but you can create a public repository for your online server and push to it with git push public master:master | [
"git"
] | 19 | 34 | 7,500 | 1 | 0 | 2008-09-04T20:36:15.597000 | 2008-09-04T20:47:06.147000 |
44,715 | 44,835 | Why do Ruby setters need "self." qualification within the class? | Ruby setters—whether created by (c)attr_accessor or manually—seem to be the only methods that need self. qualification when accessed within the class itself. This seems to put Ruby alone the world of languages: All methods need self / this (like Perl, and I think Javascript) No methods require self / this is (C#, Java) Only setters need self / this (Ruby?) The best comparison is C# vs Ruby, because both languages support accessor methods which work syntactically just like class instance variables: foo.x = y, y = foo.x. C# calls them properties. Here's a simple example; the same program in Ruby then C#: class A def qwerty; @q; end # manual getter def qwerty=(value); @q = value; end # manual setter, but attr_accessor is same def asdf; self.qwerty = 4; end # "self." is necessary in ruby? def xxx; asdf; end # we can invoke nonsetters w/o "self." def dump; puts "qwerty = #{qwerty}"; end end
a = A.new a.xxx a.dump take away the self.qwerty =() and it fails (Ruby 1.8.6 on Linux & OS X). Now C#: using System;
public class A { public A() {} int q; public int qwerty { get { return q; } set { q = value; } } public void asdf() { qwerty = 4; } // C# setters work w/o "this." public void xxx() { asdf(); } // are just like other methods public void dump() { Console.WriteLine("qwerty = {0}", qwerty); } }
public class Test { public static void Main() { A a = new A(); a.xxx(); a.dump(); } } Question: Is this true? Are there other occasions besides setters where self is necessary? I.e., are there other occasions where a Ruby method cannot be invoked without self? There are certainly lots of cases where self becomes necessary. This is not unique to Ruby, just to be clear: using System;
public class A { public A() {} public int test { get { return 4; }} public int useVariable() { int test = 5; return test; } public int useMethod() { int test = 5; return this.test; } }
public class Test { public static void Main() { A a = new A(); Console.WriteLine("{0}", a.useVariable()); // prints 5 Console.WriteLine("{0}", a.useMethod()); // prints 4 } } Same ambiguity is resolved in same way. But while subtle I'm asking about the case where A method has been defined, and No local variable has been defined, and we encounter qwerty = 4 which is ambiguous—is this a method invocation or an new local variable assignment? @Mike Stone Hi! I understand and appreciate the points you've made and your example was great. Believe me when I say, if I had enough reputation, I'd vote up your response. Yet we still disagree: on a matter of semantics, and on a central point of fact First I claim, not without irony, we're having a semantic debate about the meaning of 'ambiguity'. When it comes to parsing and programming language semantics (the subject of this question), surely you would admit a broad spectrum of the notion 'ambiguity'. Let's just adopt some random notation: ambiguous: lexical ambiguity (lex must 'look ahead') Ambiguous: grammatical ambiguity (yacc must defer to parse-tree analysis) AMBIGUOUS: ambiguity knowing everything at the moment of execution (and there's junk between 2-3 too). All these categories are resolved by gathering more contextual info, looking more and more globally. So when you say, "qwerty = 4" is UNAMBIGUOUS in C# when there is no variable defined... I couldn't agree more. But by the same token, I'm saying "qwerty = 4" is un-Ambiguous in ruby (as it now exists) "qwerty = 4" is Ambiguous in C# And we're not yet contradicting each other. Finally, here's where we really disagree: Either ruby could or could not be implemented without any further language constructs such that, For "qwerty = 4," ruby UNAMBIGUOUSLY invokes an existing setter if there is no local variable defined You say no. I say yes; another ruby could exist which behaves exactly like the current in every respect, except "qwerty = 4" defines a new variable when no setter and no local exists, it invokes the setter if one exists, and it assigns to the local if one exists. I fully accept that I could be wrong. In fact, a reason why I might be wrong would be interesting. Let me explain. Imagine you are writing a new OO language with accessor methods looking like instances vars (like ruby & C#). You'd probably start with conceptual grammars something like: var = expr // assignment method = expr // setter method invocation But the parser-compiler (not even the runtime) will puke, because even after all the input is grokked there's no way to know which grammar is pertinent. You're faced which a classic choice. I can't be sure of the details, but basically ruby does this: var = expr // assignment (new or existing) // method = expr, disallow setter method invocation without. that is why it's un-Ambiguous, while and C# does this: symbol = expr // push 'symbol=' onto parse tree and decide later // if local variable is def'd somewhere in scope: assignment // else if a setter is def'd in scope: invocation For C#, 'later' is still at compile time. I'm sure ruby could do the same, but 'later' would have to be at runtime, because as ben points out you don't know until the statement is executed which case applies. My question was never intended to mean "do I really need the 'self.'?" or "what potential ambiguity is being avoided?" Rather I wanted to know why was this particular choice made? Maybe it's not performance. Maybe it just got the job done, or it was considered best to always allow a 1-liner local to override a method (a pretty rare case requirement)... But I'm sort of suggesting that the most dynamical language might be the one which postpones this decision the longest, and chooses semantics based on the most contextual info: so if you have no local and you defined a setter, it would use the setter. Isn't this why we like ruby, smalltalk, objc, because method invocation is decided at runtime, offering maximum expressiveness? | The important thing to remember here is that Ruby methods can be (un)defined at any point, so to intelligently resolve the ambiguity, every assignment would need to run code to check whether there is a method with the assigned-to name at the time of assignment. | Why do Ruby setters need "self." qualification within the class? Ruby setters—whether created by (c)attr_accessor or manually—seem to be the only methods that need self. qualification when accessed within the class itself. This seems to put Ruby alone the world of languages: All methods need self / this (like Perl, and I think Javascript) No methods require self / this is (C#, Java) Only setters need self / this (Ruby?) The best comparison is C# vs Ruby, because both languages support accessor methods which work syntactically just like class instance variables: foo.x = y, y = foo.x. C# calls them properties. Here's a simple example; the same program in Ruby then C#: class A def qwerty; @q; end # manual getter def qwerty=(value); @q = value; end # manual setter, but attr_accessor is same def asdf; self.qwerty = 4; end # "self." is necessary in ruby? def xxx; asdf; end # we can invoke nonsetters w/o "self." def dump; puts "qwerty = #{qwerty}"; end end
a = A.new a.xxx a.dump take away the self.qwerty =() and it fails (Ruby 1.8.6 on Linux & OS X). Now C#: using System;
public class A { public A() {} int q; public int qwerty { get { return q; } set { q = value; } } public void asdf() { qwerty = 4; } // C# setters work w/o "this." public void xxx() { asdf(); } // are just like other methods public void dump() { Console.WriteLine("qwerty = {0}", qwerty); } }
public class Test { public static void Main() { A a = new A(); a.xxx(); a.dump(); } } Question: Is this true? Are there other occasions besides setters where self is necessary? I.e., are there other occasions where a Ruby method cannot be invoked without self? There are certainly lots of cases where self becomes necessary. This is not unique to Ruby, just to be clear: using System;
public class A { public A() {} public int test { get { return 4; }} public int useVariable() { int test = 5; return test; } public int useMethod() { int test = 5; return this.test; } }
public class Test { public static void Main() { A a = new A(); Console.WriteLine("{0}", a.useVariable()); // prints 5 Console.WriteLine("{0}", a.useMethod()); // prints 4 } } Same ambiguity is resolved in same way. But while subtle I'm asking about the case where A method has been defined, and No local variable has been defined, and we encounter qwerty = 4 which is ambiguous—is this a method invocation or an new local variable assignment? @Mike Stone Hi! I understand and appreciate the points you've made and your example was great. Believe me when I say, if I had enough reputation, I'd vote up your response. Yet we still disagree: on a matter of semantics, and on a central point of fact First I claim, not without irony, we're having a semantic debate about the meaning of 'ambiguity'. When it comes to parsing and programming language semantics (the subject of this question), surely you would admit a broad spectrum of the notion 'ambiguity'. Let's just adopt some random notation: ambiguous: lexical ambiguity (lex must 'look ahead') Ambiguous: grammatical ambiguity (yacc must defer to parse-tree analysis) AMBIGUOUS: ambiguity knowing everything at the moment of execution (and there's junk between 2-3 too). All these categories are resolved by gathering more contextual info, looking more and more globally. So when you say, "qwerty = 4" is UNAMBIGUOUS in C# when there is no variable defined... I couldn't agree more. But by the same token, I'm saying "qwerty = 4" is un-Ambiguous in ruby (as it now exists) "qwerty = 4" is Ambiguous in C# And we're not yet contradicting each other. Finally, here's where we really disagree: Either ruby could or could not be implemented without any further language constructs such that, For "qwerty = 4," ruby UNAMBIGUOUSLY invokes an existing setter if there is no local variable defined You say no. I say yes; another ruby could exist which behaves exactly like the current in every respect, except "qwerty = 4" defines a new variable when no setter and no local exists, it invokes the setter if one exists, and it assigns to the local if one exists. I fully accept that I could be wrong. In fact, a reason why I might be wrong would be interesting. Let me explain. Imagine you are writing a new OO language with accessor methods looking like instances vars (like ruby & C#). You'd probably start with conceptual grammars something like: var = expr // assignment method = expr // setter method invocation But the parser-compiler (not even the runtime) will puke, because even after all the input is grokked there's no way to know which grammar is pertinent. You're faced which a classic choice. I can't be sure of the details, but basically ruby does this: var = expr // assignment (new or existing) // method = expr, disallow setter method invocation without. that is why it's un-Ambiguous, while and C# does this: symbol = expr // push 'symbol=' onto parse tree and decide later // if local variable is def'd somewhere in scope: assignment // else if a setter is def'd in scope: invocation For C#, 'later' is still at compile time. I'm sure ruby could do the same, but 'later' would have to be at runtime, because as ben points out you don't know until the statement is executed which case applies. My question was never intended to mean "do I really need the 'self.'?" or "what potential ambiguity is being avoided?" Rather I wanted to know why was this particular choice made? Maybe it's not performance. Maybe it just got the job done, or it was considered best to always allow a 1-liner local to override a method (a pretty rare case requirement)... But I'm sort of suggesting that the most dynamical language might be the one which postpones this decision the longest, and chooses semantics based on the most contextual info: so if you have no local and you defined a setter, it would use the setter. Isn't this why we like ruby, smalltalk, objc, because method invocation is decided at runtime, offering maximum expressiveness? | TITLE:
Why do Ruby setters need "self." qualification within the class?
QUESTION:
Ruby setters—whether created by (c)attr_accessor or manually—seem to be the only methods that need self. qualification when accessed within the class itself. This seems to put Ruby alone the world of languages: All methods need self / this (like Perl, and I think Javascript) No methods require self / this is (C#, Java) Only setters need self / this (Ruby?) The best comparison is C# vs Ruby, because both languages support accessor methods which work syntactically just like class instance variables: foo.x = y, y = foo.x. C# calls them properties. Here's a simple example; the same program in Ruby then C#: class A def qwerty; @q; end # manual getter def qwerty=(value); @q = value; end # manual setter, but attr_accessor is same def asdf; self.qwerty = 4; end # "self." is necessary in ruby? def xxx; asdf; end # we can invoke nonsetters w/o "self." def dump; puts "qwerty = #{qwerty}"; end end
a = A.new a.xxx a.dump take away the self.qwerty =() and it fails (Ruby 1.8.6 on Linux & OS X). Now C#: using System;
public class A { public A() {} int q; public int qwerty { get { return q; } set { q = value; } } public void asdf() { qwerty = 4; } // C# setters work w/o "this." public void xxx() { asdf(); } // are just like other methods public void dump() { Console.WriteLine("qwerty = {0}", qwerty); } }
public class Test { public static void Main() { A a = new A(); a.xxx(); a.dump(); } } Question: Is this true? Are there other occasions besides setters where self is necessary? I.e., are there other occasions where a Ruby method cannot be invoked without self? There are certainly lots of cases where self becomes necessary. This is not unique to Ruby, just to be clear: using System;
public class A { public A() {} public int test { get { return 4; }} public int useVariable() { int test = 5; return test; } public int useMethod() { int test = 5; return this.test; } }
public class Test { public static void Main() { A a = new A(); Console.WriteLine("{0}", a.useVariable()); // prints 5 Console.WriteLine("{0}", a.useMethod()); // prints 4 } } Same ambiguity is resolved in same way. But while subtle I'm asking about the case where A method has been defined, and No local variable has been defined, and we encounter qwerty = 4 which is ambiguous—is this a method invocation or an new local variable assignment? @Mike Stone Hi! I understand and appreciate the points you've made and your example was great. Believe me when I say, if I had enough reputation, I'd vote up your response. Yet we still disagree: on a matter of semantics, and on a central point of fact First I claim, not without irony, we're having a semantic debate about the meaning of 'ambiguity'. When it comes to parsing and programming language semantics (the subject of this question), surely you would admit a broad spectrum of the notion 'ambiguity'. Let's just adopt some random notation: ambiguous: lexical ambiguity (lex must 'look ahead') Ambiguous: grammatical ambiguity (yacc must defer to parse-tree analysis) AMBIGUOUS: ambiguity knowing everything at the moment of execution (and there's junk between 2-3 too). All these categories are resolved by gathering more contextual info, looking more and more globally. So when you say, "qwerty = 4" is UNAMBIGUOUS in C# when there is no variable defined... I couldn't agree more. But by the same token, I'm saying "qwerty = 4" is un-Ambiguous in ruby (as it now exists) "qwerty = 4" is Ambiguous in C# And we're not yet contradicting each other. Finally, here's where we really disagree: Either ruby could or could not be implemented without any further language constructs such that, For "qwerty = 4," ruby UNAMBIGUOUSLY invokes an existing setter if there is no local variable defined You say no. I say yes; another ruby could exist which behaves exactly like the current in every respect, except "qwerty = 4" defines a new variable when no setter and no local exists, it invokes the setter if one exists, and it assigns to the local if one exists. I fully accept that I could be wrong. In fact, a reason why I might be wrong would be interesting. Let me explain. Imagine you are writing a new OO language with accessor methods looking like instances vars (like ruby & C#). You'd probably start with conceptual grammars something like: var = expr // assignment method = expr // setter method invocation But the parser-compiler (not even the runtime) will puke, because even after all the input is grokked there's no way to know which grammar is pertinent. You're faced which a classic choice. I can't be sure of the details, but basically ruby does this: var = expr // assignment (new or existing) // method = expr, disallow setter method invocation without. that is why it's un-Ambiguous, while and C# does this: symbol = expr // push 'symbol=' onto parse tree and decide later // if local variable is def'd somewhere in scope: assignment // else if a setter is def'd in scope: invocation For C#, 'later' is still at compile time. I'm sure ruby could do the same, but 'later' would have to be at runtime, because as ben points out you don't know until the statement is executed which case applies. My question was never intended to mean "do I really need the 'self.'?" or "what potential ambiguity is being avoided?" Rather I wanted to know why was this particular choice made? Maybe it's not performance. Maybe it just got the job done, or it was considered best to always allow a 1-liner local to override a method (a pretty rare case requirement)... But I'm sort of suggesting that the most dynamical language might be the one which postpones this decision the longest, and chooses semantics based on the most contextual info: so if you have no local and you defined a setter, it would use the setter. Isn't this why we like ruby, smalltalk, objc, because method invocation is decided at runtime, offering maximum expressiveness?
ANSWER:
The important thing to remember here is that Ruby methods can be (un)defined at any point, so to intelligently resolve the ambiguity, every assignment would need to run code to check whether there is a method with the assigned-to name at the time of assignment. | [
"ruby"
] | 78 | 18 | 10,365 | 3 | 0 | 2008-09-04T20:36:16.580000 | 2008-09-04T21:28:32.710000 |
44,721 | 44,724 | Howto Enable Font Antialiasing in Windows | I have downloaded a font that looks less than desirable if it is not anti-aliased. I can not figure out how to enable anti-aliasing in VS, I have changed the 'Smooth Edges of Screen Fonts' in the system performance options but that does not seem to help. VS2008 on XP SP3. What am I missing? | Try using ClearType, not Standard font smoothing. It's in Display properties, Appearance, Effects. | Howto Enable Font Antialiasing in Windows I have downloaded a font that looks less than desirable if it is not anti-aliased. I can not figure out how to enable anti-aliasing in VS, I have changed the 'Smooth Edges of Screen Fonts' in the system performance options but that does not seem to help. VS2008 on XP SP3. What am I missing? | TITLE:
Howto Enable Font Antialiasing in Windows
QUESTION:
I have downloaded a font that looks less than desirable if it is not anti-aliased. I can not figure out how to enable anti-aliasing in VS, I have changed the 'Smooth Edges of Screen Fonts' in the system performance options but that does not seem to help. VS2008 on XP SP3. What am I missing?
ANSWER:
Try using ClearType, not Standard font smoothing. It's in Display properties, Appearance, Effects. | [
"fonts",
"windows-xp",
"antialiasing"
] | 21 | 33 | 66,709 | 3 | 0 | 2008-09-04T20:38:31.100000 | 2008-09-04T20:41:09.453000 |
44,737 | 44,753 | Is there a plugin for targetting .NET 1.1 with VS 2008? | Is there a plugin for targetting.NET 1.1 with VS 2008? | According to Scott Guthrie, the reason VS 2008 does not support 1.0 or 1.1... "...is that there were significant CLR engine changes between.NET 1.x and 2.x that make debugging very difficult to support. In the end the costing of the work to support that was so large and impacted so many parts of Visual Studio that we weren't able to add 1.1 support in this release." Sounds like it would be difficult to really create such a plugin. The only hope you might find in his statement is that they "weren't able to add 1.1 support in this release " (emphasis mine). i.e. maybe they will add it down the road. I wouldn't hold my breath though. EDIT: Looks like the link @lassevk provided shows some promise for those people that can't accept running VS 2003 side-by-side with VS 2008. Looks like a lot of work though.:) | Is there a plugin for targetting .NET 1.1 with VS 2008? Is there a plugin for targetting.NET 1.1 with VS 2008? | TITLE:
Is there a plugin for targetting .NET 1.1 with VS 2008?
QUESTION:
Is there a plugin for targetting.NET 1.1 with VS 2008?
ANSWER:
According to Scott Guthrie, the reason VS 2008 does not support 1.0 or 1.1... "...is that there were significant CLR engine changes between.NET 1.x and 2.x that make debugging very difficult to support. In the end the costing of the work to support that was so large and impacted so many parts of Visual Studio that we weren't able to add 1.1 support in this release." Sounds like it would be difficult to really create such a plugin. The only hope you might find in his statement is that they "weren't able to add 1.1 support in this release " (emphasis mine). i.e. maybe they will add it down the road. I wouldn't hold my breath though. EDIT: Looks like the link @lassevk provided shows some promise for those people that can't accept running VS 2003 side-by-side with VS 2008. Looks like a lot of work though.:) | [
".net",
"visual-studio-2008",
".net-1.1",
"multi-targeting"
] | 2 | 4 | 718 | 2 | 0 | 2008-09-04T20:46:51.313000 | 2008-09-04T20:52:17.353000 |
44,757 | 44,770 | How to cache ASP.NET user controls? | I heard on a recent podcast (Polymorphic) that it is possible to cache a user control as opposed to the entire page. I think my header control which displays static content and my footer control could benefit from being cached. How can I go about caching just those controls? | Take a look here You can use VaryByParam and VaryByControl in the output cache. | How to cache ASP.NET user controls? I heard on a recent podcast (Polymorphic) that it is possible to cache a user control as opposed to the entire page. I think my header control which displays static content and my footer control could benefit from being cached. How can I go about caching just those controls? | TITLE:
How to cache ASP.NET user controls?
QUESTION:
I heard on a recent podcast (Polymorphic) that it is possible to cache a user control as opposed to the entire page. I think my header control which displays static content and my footer control could benefit from being cached. How can I go about caching just those controls?
ANSWER:
Take a look here You can use VaryByParam and VaryByControl in the output cache. | [
"asp.net",
"caching",
"user-controls"
] | 3 | 4 | 1,042 | 2 | 0 | 2008-09-04T20:54:32.807000 | 2008-09-04T21:01:12.603000 |
44,760 | 47,127 | Eclipse "Share Project" by hand? | What actually happens to the file system when you do a Subclipse Share Project on an Eclipse project that was externally checked out from Subversion? All the.svn folders are already in place. I get an error when I try to Share Project the right way, and I'd rather not delete and re-checkout the projects from the SVN Repository browser. | Dunno exactly what happens within eclipse, I presume it does some funky stuff in the.metadata directory of the workspace. That said, I would recommend the following to get eclipse to learn about the svn settings of the project: Delete the project from the workspace (keep "Delete project contents on disk" unchecked) File > Import... > General > Existing Projects into Workspace Browse to the folder containing the original project(s) of interest Import the projects into your workspace This seems to have the side effect of subclipse noticing the subversion settings when importing the "new" projects into your workspace. | Eclipse "Share Project" by hand? What actually happens to the file system when you do a Subclipse Share Project on an Eclipse project that was externally checked out from Subversion? All the.svn folders are already in place. I get an error when I try to Share Project the right way, and I'd rather not delete and re-checkout the projects from the SVN Repository browser. | TITLE:
Eclipse "Share Project" by hand?
QUESTION:
What actually happens to the file system when you do a Subclipse Share Project on an Eclipse project that was externally checked out from Subversion? All the.svn folders are already in place. I get an error when I try to Share Project the right way, and I'd rather not delete and re-checkout the projects from the SVN Repository browser.
ANSWER:
Dunno exactly what happens within eclipse, I presume it does some funky stuff in the.metadata directory of the workspace. That said, I would recommend the following to get eclipse to learn about the svn settings of the project: Delete the project from the workspace (keep "Delete project contents on disk" unchecked) File > Import... > General > Existing Projects into Workspace Browse to the folder containing the original project(s) of interest Import the projects into your workspace This seems to have the side effect of subclipse noticing the subversion settings when importing the "new" projects into your workspace. | [
"eclipse",
"svn",
"subclipse"
] | 6 | 12 | 6,601 | 3 | 0 | 2008-09-04T20:54:41.997000 | 2008-09-06T00:20:06.250000 |
44,771 | 44,923 | Ajax Autocomplete Webservice Call - Service Method, am I calling this correctly? | Ok, so my method in my webservice requires a type to be passed, it is called in the ServiceMethod property of the AutoCompleteExtender, I am fuzzy about how I should do that so I called it like this: ServiceMethod="DropDownLoad<<%=(typeof)subCategory%>>" where subCategory is a page property that looks like this: protected SubCategory subCategory { get { var subCategory = NHibernateObjectHelper.LoadDataObject (Convert.ToInt32(Request.QueryString["SCID"])); return subCategory; } } | I dont' think calling a Generic Method on a webservice is possible. If you look at the service description of two identical methods, one generic, one not: [WebMethod] public string[] GetSearchList(string prefixText, int count) { }
[WebMethod] public string[] GetSearchList2 (string prefixText, int count) { } They are identical. It appears that both SOAP 1.x and HTTP POST do not allow this type of operation. | Ajax Autocomplete Webservice Call - Service Method, am I calling this correctly? Ok, so my method in my webservice requires a type to be passed, it is called in the ServiceMethod property of the AutoCompleteExtender, I am fuzzy about how I should do that so I called it like this: ServiceMethod="DropDownLoad<<%=(typeof)subCategory%>>" where subCategory is a page property that looks like this: protected SubCategory subCategory { get { var subCategory = NHibernateObjectHelper.LoadDataObject (Convert.ToInt32(Request.QueryString["SCID"])); return subCategory; } } | TITLE:
Ajax Autocomplete Webservice Call - Service Method, am I calling this correctly?
QUESTION:
Ok, so my method in my webservice requires a type to be passed, it is called in the ServiceMethod property of the AutoCompleteExtender, I am fuzzy about how I should do that so I called it like this: ServiceMethod="DropDownLoad<<%=(typeof)subCategory%>>" where subCategory is a page property that looks like this: protected SubCategory subCategory { get { var subCategory = NHibernateObjectHelper.LoadDataObject (Convert.ToInt32(Request.QueryString["SCID"])); return subCategory; } }
ANSWER:
I dont' think calling a Generic Method on a webservice is possible. If you look at the service description of two identical methods, one generic, one not: [WebMethod] public string[] GetSearchList(string prefixText, int count) { }
[WebMethod] public string[] GetSearchList2 (string prefixText, int count) { } They are identical. It appears that both SOAP 1.x and HTTP POST do not allow this type of operation. | [
"c#",
"asp.net",
"asp.net-ajax"
] | 1 | 1 | 2,235 | 2 | 0 | 2008-09-04T21:01:42.463000 | 2008-09-04T22:52:28.407000 |
44,777 | 44,783 | Sending a mail as both HTML and Plain Text in .net | I'm sending mail from my C# Application, using the SmtpClient. Works great, but I have to decide if I want to send the mail as Plain Text or HTML. I wonder, is there a way to send both? I think that's called multipart. I googled a bit, but most examples essentially did not use SmtpClient but composed the whole SMTP-Body themselves, which is a bit "scary", so I wonder if something is built in the.net Framework 3.0? If not, is there any really well used/robust Third Party Library for sending e-Mails? | What you want to do is use the AlternateViews property on the MailMessage http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews.aspx | Sending a mail as both HTML and Plain Text in .net I'm sending mail from my C# Application, using the SmtpClient. Works great, but I have to decide if I want to send the mail as Plain Text or HTML. I wonder, is there a way to send both? I think that's called multipart. I googled a bit, but most examples essentially did not use SmtpClient but composed the whole SMTP-Body themselves, which is a bit "scary", so I wonder if something is built in the.net Framework 3.0? If not, is there any really well used/robust Third Party Library for sending e-Mails? | TITLE:
Sending a mail as both HTML and Plain Text in .net
QUESTION:
I'm sending mail from my C# Application, using the SmtpClient. Works great, but I have to decide if I want to send the mail as Plain Text or HTML. I wonder, is there a way to send both? I think that's called multipart. I googled a bit, but most examples essentially did not use SmtpClient but composed the whole SMTP-Body themselves, which is a bit "scary", so I wonder if something is built in the.net Framework 3.0? If not, is there any really well used/robust Third Party Library for sending e-Mails?
ANSWER:
What you want to do is use the AlternateViews property on the MailMessage http://msdn.microsoft.com/en-us/library/system.net.mail.mailmessage.alternateviews.aspx | [
"c#",
".net"
] | 53 | 48 | 59,057 | 7 | 0 | 2008-09-04T21:03:48.667000 | 2008-09-04T21:07:00.203000 |
44,778 | 44,781 | How would you make a comma-separated string from a list of strings? | What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, ['a', 'b', 'c'] to 'a,b,c'? (The cases ['s'] and [] should be mapped to 's' and '', respectively.) I usually end up using something like ''.join(map(lambda x: x+',',l))[:-1], but also feeling somewhat unsatisfied. | my_list = ['a', 'b', 'c', 'd'] my_string = ','.join(my_list) 'a,b,c,d' This won't work if the list contains integers And if the list contains non-string types (such as integers, floats, bools, None) then do: my_string = ','.join(map(str, my_list)) | How would you make a comma-separated string from a list of strings? What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, ['a', 'b', 'c'] to 'a,b,c'? (The cases ['s'] and [] should be mapped to 's' and '', respectively.) I usually end up using something like ''.join(map(lambda x: x+',',l))[:-1], but also feeling somewhat unsatisfied. | TITLE:
How would you make a comma-separated string from a list of strings?
QUESTION:
What would be your preferred way to concatenate strings from a sequence such that between every two consecutive pairs a comma is added. That is, how do you map, for instance, ['a', 'b', 'c'] to 'a,b,c'? (The cases ['s'] and [] should be mapped to 's' and '', respectively.) I usually end up using something like ''.join(map(lambda x: x+',',l))[:-1], but also feeling somewhat unsatisfied.
ANSWER:
my_list = ['a', 'b', 'c', 'd'] my_string = ','.join(my_list) 'a,b,c,d' This won't work if the list contains integers And if the list contains non-string types (such as integers, floats, bools, None) then do: my_string = ','.join(map(str, my_list)) | [
"python",
"string",
"list"
] | 704 | 1,310 | 869,278 | 15 | 0 | 2008-09-04T21:04:04.873000 | 2008-09-04T21:06:12.030000 |
44,780 | 45,907 | What's the best way to implement a SQL script that will grant permissions to a database role on all the user tables in a database? | What's the best way to implement a SQL script that will grant select, references, insert, update, and delete permissions to a database role on all the user tables in a database? Ideally, this script could be run multiple times, as new tables were added to the database. SQL Server Management Studio generates scripts for individual database objects, but I'm looking for more of a "fire-and-forget" script. | Dr Zimmerman is on the right track here. I'd be looking to write a stored procedure that has a cursor looping through user objects using execute immediate to affect the grant. Something like this: IF EXISTS ( SELECT 1 FROM sysobjects WHERE name = 'sp_grantastic' AND type = 'P' ) DROP PROCEDURE sp_grantastic GO CREATE PROCEDURE sp_grantastic AS DECLARE @object_name VARCHAR(30),@time VARCHAR(8),@rights VARCHAR(20),@role VARCHAR(20)
DECLARE c_objects CURSOR FOR SELECT name FROM sysobjects WHERE type IN ('P', 'U', 'V') FOR READ ONLY
BEGIN
SELECT @rights = 'ALL',@role = 'PUBLIC'
OPEN c_objects WHILE (1=1) BEGIN FETCH c_objects INTO @object_name IF @@SQLSTATUS <> 0 BREAK
SELECT @time = CONVERT(VARCHAR, GetDate(), 108) PRINT '[%1!] hitting up object %2!', @time, @object_name EXECUTE('GRANT '+ @rights +' ON '+ @object_name+' TO '+@role)
END
PRINT '[%1!] fin!', @time
CLOSE c_objects DEALLOCATE CURSOR c_objects END GO GRANT ALL ON sp_grantastic TO PUBLIC GO Then you can fire and forget: EXEC sp_grantastic | What's the best way to implement a SQL script that will grant permissions to a database role on all the user tables in a database? What's the best way to implement a SQL script that will grant select, references, insert, update, and delete permissions to a database role on all the user tables in a database? Ideally, this script could be run multiple times, as new tables were added to the database. SQL Server Management Studio generates scripts for individual database objects, but I'm looking for more of a "fire-and-forget" script. | TITLE:
What's the best way to implement a SQL script that will grant permissions to a database role on all the user tables in a database?
QUESTION:
What's the best way to implement a SQL script that will grant select, references, insert, update, and delete permissions to a database role on all the user tables in a database? Ideally, this script could be run multiple times, as new tables were added to the database. SQL Server Management Studio generates scripts for individual database objects, but I'm looking for more of a "fire-and-forget" script.
ANSWER:
Dr Zimmerman is on the right track here. I'd be looking to write a stored procedure that has a cursor looping through user objects using execute immediate to affect the grant. Something like this: IF EXISTS ( SELECT 1 FROM sysobjects WHERE name = 'sp_grantastic' AND type = 'P' ) DROP PROCEDURE sp_grantastic GO CREATE PROCEDURE sp_grantastic AS DECLARE @object_name VARCHAR(30),@time VARCHAR(8),@rights VARCHAR(20),@role VARCHAR(20)
DECLARE c_objects CURSOR FOR SELECT name FROM sysobjects WHERE type IN ('P', 'U', 'V') FOR READ ONLY
BEGIN
SELECT @rights = 'ALL',@role = 'PUBLIC'
OPEN c_objects WHILE (1=1) BEGIN FETCH c_objects INTO @object_name IF @@SQLSTATUS <> 0 BREAK
SELECT @time = CONVERT(VARCHAR, GetDate(), 108) PRINT '[%1!] hitting up object %2!', @time, @object_name EXECUTE('GRANT '+ @rights +' ON '+ @object_name+' TO '+@role)
END
PRINT '[%1!] fin!', @time
CLOSE c_objects DEALLOCATE CURSOR c_objects END GO GRANT ALL ON sp_grantastic TO PUBLIC GO Then you can fire and forget: EXEC sp_grantastic | [
"sql",
"sql-server",
"t-sql",
"permissions"
] | 2 | 1 | 4,073 | 5 | 0 | 2008-09-04T21:05:31.923000 | 2008-09-05T14:20:54.880000 |
44,787 | 44,810 | How do you get the current image name from an ASP.Net website? | Scenario: You have an ASP.Net webpage that should display the next image in a series of images. If 1.jpg is currently loaded, the refresh should load 2.jpg. Assuming I would use this code, where do you get the current images name. string currImage = MainPic.ImageUrl.Replace(".jpg", ""); currImage = currImage.Replace("~/Images/", "");
int num = (Convert.ToInt32(currImage) + 1) % 3; MainPic.ImageUrl = "~/Images/" + num.ToString() + ".jpg"; The problem with the above code is that the webpage used is the default site with the image set to 1.jpg, so the loaded image is always 2.jpg. So in the process of loading the page, is it possible to pull the last image used from the pages properties? | int num = 1;
if(Session["ImageNumber"]!= null) { num = Convert.ToInt32(Session["ImageNumber"]) + 1; }
Session["ImageNumber"] = num; | How do you get the current image name from an ASP.Net website? Scenario: You have an ASP.Net webpage that should display the next image in a series of images. If 1.jpg is currently loaded, the refresh should load 2.jpg. Assuming I would use this code, where do you get the current images name. string currImage = MainPic.ImageUrl.Replace(".jpg", ""); currImage = currImage.Replace("~/Images/", "");
int num = (Convert.ToInt32(currImage) + 1) % 3; MainPic.ImageUrl = "~/Images/" + num.ToString() + ".jpg"; The problem with the above code is that the webpage used is the default site with the image set to 1.jpg, so the loaded image is always 2.jpg. So in the process of loading the page, is it possible to pull the last image used from the pages properties? | TITLE:
How do you get the current image name from an ASP.Net website?
QUESTION:
Scenario: You have an ASP.Net webpage that should display the next image in a series of images. If 1.jpg is currently loaded, the refresh should load 2.jpg. Assuming I would use this code, where do you get the current images name. string currImage = MainPic.ImageUrl.Replace(".jpg", ""); currImage = currImage.Replace("~/Images/", "");
int num = (Convert.ToInt32(currImage) + 1) % 3; MainPic.ImageUrl = "~/Images/" + num.ToString() + ".jpg"; The problem with the above code is that the webpage used is the default site with the image set to 1.jpg, so the loaded image is always 2.jpg. So in the process of loading the page, is it possible to pull the last image used from the pages properties?
ANSWER:
int num = 1;
if(Session["ImageNumber"]!= null) { num = Convert.ToInt32(Session["ImageNumber"]) + 1; }
Session["ImageNumber"] = num; | [
"c#",
"asp.net"
] | 0 | 5 | 1,653 | 7 | 0 | 2008-09-04T21:08:28.280000 | 2008-09-04T21:19:23.870000 |
44,795 | 44,863 | How can I determine whether a given date is in Daylight Saving Time for a given timezone in .NET 2.0? | I'm on.NET 2.0, running under Medium Trust (so TimeZoneInfo and the Registry are not allowed options). I'm asking the user for two dates and a time zone, and would really love to be able to automatically determine whether I need to adjust the time zone for DST. This probably isn't even a valid scenario unless I have some very robust support, a la TimeZoneInfo, to differentiate between all of the different varieties of Time Zones in the first place. | In.NET 2.0 you have to code this yourself. It involves researching daylight savings time laws in various regions and building that into your own data structures. The problem is somewhat simplified if you only care about a subset of time zones, for example just in the USA, but if you need all global time zones, you have a lot of work to do, and then the code has to be updated every few years when the laws change. Even the new time zone objects in the latest version of.NET will require windows updates to keep them correct as laws change. Look here, here, and here for more info. | How can I determine whether a given date is in Daylight Saving Time for a given timezone in .NET 2.0? I'm on.NET 2.0, running under Medium Trust (so TimeZoneInfo and the Registry are not allowed options). I'm asking the user for two dates and a time zone, and would really love to be able to automatically determine whether I need to adjust the time zone for DST. This probably isn't even a valid scenario unless I have some very robust support, a la TimeZoneInfo, to differentiate between all of the different varieties of Time Zones in the first place. | TITLE:
How can I determine whether a given date is in Daylight Saving Time for a given timezone in .NET 2.0?
QUESTION:
I'm on.NET 2.0, running under Medium Trust (so TimeZoneInfo and the Registry are not allowed options). I'm asking the user for two dates and a time zone, and would really love to be able to automatically determine whether I need to adjust the time zone for DST. This probably isn't even a valid scenario unless I have some very robust support, a la TimeZoneInfo, to differentiate between all of the different varieties of Time Zones in the first place.
ANSWER:
In.NET 2.0 you have to code this yourself. It involves researching daylight savings time laws in various regions and building that into your own data structures. The problem is somewhat simplified if you only care about a subset of time zones, for example just in the USA, but if you need all global time zones, you have a lot of work to do, and then the code has to be updated every few years when the laws change. Even the new time zone objects in the latest version of.NET will require windows updates to keep them correct as laws change. Look here, here, and here for more info. | [
".net",
".net-2.0",
"timezone",
"medium-trust"
] | 3 | 2 | 1,104 | 5 | 0 | 2008-09-04T21:11:43.360000 | 2008-09-04T21:44:23.483000 |
44,799 | 44,807 | Preventing Command Line Injection Attacks | We're currently building an application that executes a number of external tools. We often have to pass information entered into our system by users to these tools. Obviously, this is a big security nightmare waiting to happen. Unfortunately, we've not yet found any classes in the.NET Framework that execute command line programs while providing the same kind of guards against injection attacks as the IDbCommand objects do for databases. Right now, we're using a very primitive string substitution which I suspect is rather insufficient: protected virtual string Escape(string value) { return value.Replace(@"\", @"\\").Replace(@"$", @"\$").Replace(@"""", @"\""").Replace("`", "'"); } What do you guys do to prevent command-line injection attacks? We're planning to implement a regex that is very strict and only allows a very small subset of characters through, but I was wondering if there was a better way. Some clarifications: Some of these tools do not have APIs we can program against. If they did, we wouldn't be having this problem. The users don't pick tools to execute, they enter meta-data which the tools we've chosen use (for example, injecting meta data such as copyright notices into target files). | Are you executing the programs directly or going through the shell? If you always launch an external program by giving the full path name to the executable and leaving the shell out of the equation, then you aren't really susceptible to any kind of command line injection. EDIT: DrFloyd, the shell is responsible for evaluating things like the backtick. No shell, no shell evaluation. Obviously, you've still got to be aware of any potential security gotchas in the programs that you're calling -- but I don't think this question is about that. | Preventing Command Line Injection Attacks We're currently building an application that executes a number of external tools. We often have to pass information entered into our system by users to these tools. Obviously, this is a big security nightmare waiting to happen. Unfortunately, we've not yet found any classes in the.NET Framework that execute command line programs while providing the same kind of guards against injection attacks as the IDbCommand objects do for databases. Right now, we're using a very primitive string substitution which I suspect is rather insufficient: protected virtual string Escape(string value) { return value.Replace(@"\", @"\\").Replace(@"$", @"\$").Replace(@"""", @"\""").Replace("`", "'"); } What do you guys do to prevent command-line injection attacks? We're planning to implement a regex that is very strict and only allows a very small subset of characters through, but I was wondering if there was a better way. Some clarifications: Some of these tools do not have APIs we can program against. If they did, we wouldn't be having this problem. The users don't pick tools to execute, they enter meta-data which the tools we've chosen use (for example, injecting meta data such as copyright notices into target files). | TITLE:
Preventing Command Line Injection Attacks
QUESTION:
We're currently building an application that executes a number of external tools. We often have to pass information entered into our system by users to these tools. Obviously, this is a big security nightmare waiting to happen. Unfortunately, we've not yet found any classes in the.NET Framework that execute command line programs while providing the same kind of guards against injection attacks as the IDbCommand objects do for databases. Right now, we're using a very primitive string substitution which I suspect is rather insufficient: protected virtual string Escape(string value) { return value.Replace(@"\", @"\\").Replace(@"$", @"\$").Replace(@"""", @"\""").Replace("`", "'"); } What do you guys do to prevent command-line injection attacks? We're planning to implement a regex that is very strict and only allows a very small subset of characters through, but I was wondering if there was a better way. Some clarifications: Some of these tools do not have APIs we can program against. If they did, we wouldn't be having this problem. The users don't pick tools to execute, they enter meta-data which the tools we've chosen use (for example, injecting meta data such as copyright notices into target files).
ANSWER:
Are you executing the programs directly or going through the shell? If you always launch an external program by giving the full path name to the executable and leaving the shell out of the equation, then you aren't really susceptible to any kind of command line injection. EDIT: DrFloyd, the shell is responsible for evaluating things like the backtick. No shell, no shell evaluation. Obviously, you've still got to be aware of any potential security gotchas in the programs that you're calling -- but I don't think this question is about that. | [
"security",
"command-line",
"code-injection"
] | 10 | 6 | 10,266 | 7 | 0 | 2008-09-04T21:12:50.797000 | 2008-09-04T21:18:10.723000 |
44,817 | 45,891 | Flex and ADO.NET Data Services...anyone done it? | Has anyone used ADO.NET Data Services as a data source for Adobe Flex applications? If so, any success stories or tragedies to avoid? If you did use it, how did you handle security? | I use WebORB for.NET to do Flex remoting and then use DLINQ on the server. One tricky thing about using LINQ with WebORB is that WebORB uses Reflection to automatically retrieve all the relationships of the object(s) you return to Flex. This causes severe time penalties as LINQ uses lazy loading to load relationships. To prevent this from happening, I do something like the following: Override your DataContext's constructor and add the following code: this.DeferredLoadingEnabled = false; DataLoadOptions dlo = new DataLoadOptions(); dlo.LoadWith (q => q.Payments); dlo.LoadWith (q => q.Customer); this.LoadOptions = dlo; This tells the DataContext to disable deferred loading of relationships and specifically instructs it to load just the relationships you want, without lazy loading. That way, WebORB isn't causing any lazy loading to happen through Reflection and the number of relationships being transferred to Flex is kept at a minimum. Hope this helps you in some way. It's definitely one of those little "gotchas" when working with Flex/WebORB and LINQ. | Flex and ADO.NET Data Services...anyone done it? Has anyone used ADO.NET Data Services as a data source for Adobe Flex applications? If so, any success stories or tragedies to avoid? If you did use it, how did you handle security? | TITLE:
Flex and ADO.NET Data Services...anyone done it?
QUESTION:
Has anyone used ADO.NET Data Services as a data source for Adobe Flex applications? If so, any success stories or tragedies to avoid? If you did use it, how did you handle security?
ANSWER:
I use WebORB for.NET to do Flex remoting and then use DLINQ on the server. One tricky thing about using LINQ with WebORB is that WebORB uses Reflection to automatically retrieve all the relationships of the object(s) you return to Flex. This causes severe time penalties as LINQ uses lazy loading to load relationships. To prevent this from happening, I do something like the following: Override your DataContext's constructor and add the following code: this.DeferredLoadingEnabled = false; DataLoadOptions dlo = new DataLoadOptions(); dlo.LoadWith (q => q.Payments); dlo.LoadWith (q => q.Customer); this.LoadOptions = dlo; This tells the DataContext to disable deferred loading of relationships and specifically instructs it to load just the relationships you want, without lazy loading. That way, WebORB isn't causing any lazy loading to happen through Reflection and the number of relationships being transferred to Flex is kept at a minimum. Hope this helps you in some way. It's definitely one of those little "gotchas" when working with Flex/WebORB and LINQ. | [
"apache-flex",
"ado.net"
] | 2 | 3 | 1,295 | 4 | 0 | 2008-09-04T21:20:27.317000 | 2008-09-05T14:06:47.973000 |
44,821 | 45,170 | Default smart device project can't find dependencies | When running the default c++ project in Visual Studios for a Windows CE 5.0 device, I get an error complaining about missing resources. Depends says that my executable needs ayghsell.dll (the Windows Mobile shell), and CoreDll.dll. Does this mean that my executable can only be run on Windows Mobile devices, instead of any generic Windows CE installation? If that's the case, how do I create an executable targeting generic WinCE? | Depends what you mean by a generic Windows CE installation. Windows CE itself is a modularised operating system, so different devices can have different modules included. Therefore each Windows CE device can have a radically different OS installed (headless even). Coredll is the standard "common" library that gets included in a Windows CE installation, however it can contain different components depending on the other modules in the system. If you want to target a relatively standard version of Windows CE either target the Standard SDK set of components, or go for a Windows Mobile platform. If you have an SDK then install and use that. If none is available then you can generate an SDK using Platform Builder and the OS project files. To get your application to work on a non-Windows Mobile installation of Windows CE you just have to remove the code that uses the aygshell library, and not link to those libraries. | Default smart device project can't find dependencies When running the default c++ project in Visual Studios for a Windows CE 5.0 device, I get an error complaining about missing resources. Depends says that my executable needs ayghsell.dll (the Windows Mobile shell), and CoreDll.dll. Does this mean that my executable can only be run on Windows Mobile devices, instead of any generic Windows CE installation? If that's the case, how do I create an executable targeting generic WinCE? | TITLE:
Default smart device project can't find dependencies
QUESTION:
When running the default c++ project in Visual Studios for a Windows CE 5.0 device, I get an error complaining about missing resources. Depends says that my executable needs ayghsell.dll (the Windows Mobile shell), and CoreDll.dll. Does this mean that my executable can only be run on Windows Mobile devices, instead of any generic Windows CE installation? If that's the case, how do I create an executable targeting generic WinCE?
ANSWER:
Depends what you mean by a generic Windows CE installation. Windows CE itself is a modularised operating system, so different devices can have different modules included. Therefore each Windows CE device can have a radically different OS installed (headless even). Coredll is the standard "common" library that gets included in a Windows CE installation, however it can contain different components depending on the other modules in the system. If you want to target a relatively standard version of Windows CE either target the Standard SDK set of components, or go for a Windows Mobile platform. If you have an SDK then install and use that. If none is available then you can generate an SDK using Platform Builder and the OS project files. To get your application to work on a non-Windows Mobile installation of Windows CE you just have to remove the code that uses the aygshell library, and not link to those libraries. | [
"c++",
"visual-studio",
"windows-mobile",
"windows-ce"
] | 1 | 3 | 535 | 1 | 0 | 2008-09-04T21:20:43.650000 | 2008-09-05T03:10:02.077000 |
44,824 | 46,191 | Is JINI at all active anymore? | Everyone I talk to who knows (knew) about it claims it was the greatest thing since sliced bread. Why did it fail? Or, if it didn't fail, who's using it now? | Check out GigaSpaces. It's a quite successful Jini/Javaspaces implementation. I think Jini has a great model, but it is stuck with Java. Web-services is more appealing because it works with standarized protocols, even though Jini service discovery is more natural. | Is JINI at all active anymore? Everyone I talk to who knows (knew) about it claims it was the greatest thing since sliced bread. Why did it fail? Or, if it didn't fail, who's using it now? | TITLE:
Is JINI at all active anymore?
QUESTION:
Everyone I talk to who knows (knew) about it claims it was the greatest thing since sliced bread. Why did it fail? Or, if it didn't fail, who's using it now?
ANSWER:
Check out GigaSpaces. It's a quite successful Jini/Javaspaces implementation. I think Jini has a great model, but it is stuck with Java. Web-services is more appealing because it works with standarized protocols, even though Jini service discovery is more natural. | [
"java",
"jini"
] | 7 | 8 | 2,235 | 7 | 0 | 2008-09-04T21:22:03.210000 | 2008-09-05T16:17:27.707000 |
44,834 | 44,842 | What does __all__ mean in Python? | I see __all__ in __init__.py files. What does it do? | It's a list of public objects of that module, as interpreted by import *. It overrides the default of hiding everything that begins with an underscore. | What does __all__ mean in Python? I see __all__ in __init__.py files. What does it do? | TITLE:
What does __all__ mean in Python?
QUESTION:
I see __all__ in __init__.py files. What does it do?
ANSWER:
It's a list of public objects of that module, as interpreted by import *. It overrides the default of hiding everything that begins with an underscore. | [
"python",
"syntax",
"namespaces"
] | 1,702 | 856 | 635,288 | 10 | 0 | 2008-09-04T21:28:18.547000 | 2008-09-04T21:30:46.213000 |
44,851 | 45,061 | Substitution Control at the User Control Level? | I am trying to create some cached user controls. Basically Header and Footer are static. Except the footer has one link that reads in the URL of the page and puts it into the javascript for sending a link to a friend. So I need that link to be dynamic. I set up a substitution control and had the static method return the dynamic link. Go to run and find that substitution controls are not supported at the user control level. Is there any work around to this? Is there another control like substitution that works on the User Controls that I am not aware of? | I would forget about server side caching in this instance and rely on the simplicity of client side caching. Your Javascript code could be client side cached just as easily as HTML, either by linking to an external javascript file and adding the necessary headers/expiries, or by embedding the script within the page itself and ensuring the page itself is cached. Another possible method is by making an Ajax call on the page load to fetch the generated footer complete with correct link. This may take time on the first page load, but subsequent ajax requests would be cached on the client, thus seeing no penalty to future requests. | Substitution Control at the User Control Level? I am trying to create some cached user controls. Basically Header and Footer are static. Except the footer has one link that reads in the URL of the page and puts it into the javascript for sending a link to a friend. So I need that link to be dynamic. I set up a substitution control and had the static method return the dynamic link. Go to run and find that substitution controls are not supported at the user control level. Is there any work around to this? Is there another control like substitution that works on the User Controls that I am not aware of? | TITLE:
Substitution Control at the User Control Level?
QUESTION:
I am trying to create some cached user controls. Basically Header and Footer are static. Except the footer has one link that reads in the URL of the page and puts it into the javascript for sending a link to a friend. So I need that link to be dynamic. I set up a substitution control and had the static method return the dynamic link. Go to run and find that substitution controls are not supported at the user control level. Is there any work around to this? Is there another control like substitution that works on the User Controls that I am not aware of?
ANSWER:
I would forget about server side caching in this instance and rely on the simplicity of client side caching. Your Javascript code could be client side cached just as easily as HTML, either by linking to an external javascript file and adding the necessary headers/expiries, or by embedding the script within the page itself and ensuring the page itself is cached. Another possible method is by making an Ajax call on the page load to fetch the generated footer complete with correct link. This may take time on the first page load, but subsequent ajax requests would be cached on the client, thus seeing no penalty to future requests. | [
"asp.net",
"caching",
"user-controls"
] | 1 | 1 | 671 | 1 | 0 | 2008-09-04T21:33:53.087000 | 2008-09-05T00:58:26.700000 |
44,853 | 44,870 | Why am I getting a ClassCastException when generating javadocs? | I'm using ant to generate javadocs, but get this exception over and over - why? I'm using JDK version 1.6.0_06. [javadoc] java.lang.ClassCastException: com.sun.tools.javadoc.ClassDocImpl cannot be cast to com.sun.javadoc.AnnotationTypeDoc [javadoc] at com.sun.tools.javadoc.AnnotationDescImpl.annotationType(AnnotationDescImpl.java:46) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.getAnnotations(HtmlDocletWriter.java:1739) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1713) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1702) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1681) [javadoc] at com.sun.tools.doclets.formats.html.FieldWriterImpl.writeSignature(FieldWriterImpl.java:130) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildSignature(FieldBuilder.java:184) [javadoc] at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildFieldDoc(FieldBuilder.java:158) [javadoc] at sun.reflect.GeneratedMethodAccessor51.invoke(Unknown Source) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildFieldDetails(ClassBuilder.java:301) [javadoc] at sun.reflect.GeneratedMethodAccessor43.invoke(Unknown Source) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildClassDoc(ClassBuilder.java:124) [javadoc] at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.build(ClassBuilder.java:108) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.generateClassFiles(HtmlDoclet.java:155) [javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.generateClassFiles(AbstractDoclet.java:164) [javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.startGeneration(AbstractDoclet.java:106) [javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.start(AbstractDoclet.java:64) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.start(HtmlDoclet.java:42) [javadoc] at com.sun.tools.doclets.standard.Standard.start(Standard.java:23) [javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.javadoc.DocletInvoker.invoke(DocletInvoker.java:215) [javadoc] at com.sun.tools.javadoc.DocletInvoker.start(DocletInvoker.java:91) [javadoc] at com.sun.tools.javadoc.Start.parseAndExecute(Start.java:340) [javadoc] at com.sun.tools.javadoc.Start.begin(Start.java:128) [javadoc] at com.sun.tools.javadoc.Main.execute(Main.java:41) [javadoc] at com.sun.tools.javadoc.Main.main(Main.java:31) | It looks like this has been reported as a Java bug. It appears to be caused by using annotations from a 3rd party library (like JUnit) and not including the jar with that annotation in the javadoc invocation. If that is the case, just use the -classpath option on javadoc and include the extra jar files. | Why am I getting a ClassCastException when generating javadocs? I'm using ant to generate javadocs, but get this exception over and over - why? I'm using JDK version 1.6.0_06. [javadoc] java.lang.ClassCastException: com.sun.tools.javadoc.ClassDocImpl cannot be cast to com.sun.javadoc.AnnotationTypeDoc [javadoc] at com.sun.tools.javadoc.AnnotationDescImpl.annotationType(AnnotationDescImpl.java:46) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.getAnnotations(HtmlDocletWriter.java:1739) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1713) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1702) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1681) [javadoc] at com.sun.tools.doclets.formats.html.FieldWriterImpl.writeSignature(FieldWriterImpl.java:130) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildSignature(FieldBuilder.java:184) [javadoc] at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildFieldDoc(FieldBuilder.java:158) [javadoc] at sun.reflect.GeneratedMethodAccessor51.invoke(Unknown Source) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildFieldDetails(ClassBuilder.java:301) [javadoc] at sun.reflect.GeneratedMethodAccessor43.invoke(Unknown Source) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildClassDoc(ClassBuilder.java:124) [javadoc] at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.build(ClassBuilder.java:108) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.generateClassFiles(HtmlDoclet.java:155) [javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.generateClassFiles(AbstractDoclet.java:164) [javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.startGeneration(AbstractDoclet.java:106) [javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.start(AbstractDoclet.java:64) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.start(HtmlDoclet.java:42) [javadoc] at com.sun.tools.doclets.standard.Standard.start(Standard.java:23) [javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.javadoc.DocletInvoker.invoke(DocletInvoker.java:215) [javadoc] at com.sun.tools.javadoc.DocletInvoker.start(DocletInvoker.java:91) [javadoc] at com.sun.tools.javadoc.Start.parseAndExecute(Start.java:340) [javadoc] at com.sun.tools.javadoc.Start.begin(Start.java:128) [javadoc] at com.sun.tools.javadoc.Main.execute(Main.java:41) [javadoc] at com.sun.tools.javadoc.Main.main(Main.java:31) | TITLE:
Why am I getting a ClassCastException when generating javadocs?
QUESTION:
I'm using ant to generate javadocs, but get this exception over and over - why? I'm using JDK version 1.6.0_06. [javadoc] java.lang.ClassCastException: com.sun.tools.javadoc.ClassDocImpl cannot be cast to com.sun.javadoc.AnnotationTypeDoc [javadoc] at com.sun.tools.javadoc.AnnotationDescImpl.annotationType(AnnotationDescImpl.java:46) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.getAnnotations(HtmlDocletWriter.java:1739) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1713) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1702) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDocletWriter.writeAnnotationInfo(HtmlDocletWriter.java:1681) [javadoc] at com.sun.tools.doclets.formats.html.FieldWriterImpl.writeSignature(FieldWriterImpl.java:130) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildSignature(FieldBuilder.java:184) [javadoc] at sun.reflect.GeneratedMethodAccessor8.invoke(Unknown Source) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.buildFieldDoc(FieldBuilder.java:158) [javadoc] at sun.reflect.GeneratedMethodAccessor51.invoke(Unknown Source) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.FieldBuilder.invokeMethod(FieldBuilder.java:114) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractMemberBuilder.build(AbstractMemberBuilder.java:56) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildFieldDetails(ClassBuilder.java:301) [javadoc] at sun.reflect.GeneratedMethodAccessor43.invoke(Unknown Source) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.buildClassDoc(ClassBuilder.java:124) [javadoc] at sun.reflect.GeneratedMethodAccessor19.invoke(Unknown Source) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.invokeMethod(ClassBuilder.java:101) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.AbstractBuilder.build(AbstractBuilder.java:90) [javadoc] at com.sun.tools.doclets.internal.toolkit.builders.ClassBuilder.build(ClassBuilder.java:108) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.generateClassFiles(HtmlDoclet.java:155) [javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.generateClassFiles(AbstractDoclet.java:164) [javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.startGeneration(AbstractDoclet.java:106) [javadoc] at com.sun.tools.doclets.internal.toolkit.AbstractDoclet.start(AbstractDoclet.java:64) [javadoc] at com.sun.tools.doclets.formats.html.HtmlDoclet.start(HtmlDoclet.java:42) [javadoc] at com.sun.tools.doclets.standard.Standard.start(Standard.java:23) [javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) [javadoc] at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39) [javadoc] at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25) [javadoc] at java.lang.reflect.Method.invoke(Method.java:597) [javadoc] at com.sun.tools.javadoc.DocletInvoker.invoke(DocletInvoker.java:215) [javadoc] at com.sun.tools.javadoc.DocletInvoker.start(DocletInvoker.java:91) [javadoc] at com.sun.tools.javadoc.Start.parseAndExecute(Start.java:340) [javadoc] at com.sun.tools.javadoc.Start.begin(Start.java:128) [javadoc] at com.sun.tools.javadoc.Main.execute(Main.java:41) [javadoc] at com.sun.tools.javadoc.Main.main(Main.java:31)
ANSWER:
It looks like this has been reported as a Java bug. It appears to be caused by using annotations from a 3rd party library (like JUnit) and not including the jar with that annotation in the javadoc invocation. If that is the case, just use the -classpath option on javadoc and include the extra jar files. | [
"java",
"ant",
"javadoc",
"classcastexception"
] | 55 | 54 | 22,750 | 4 | 0 | 2008-09-04T21:37:43.203000 | 2008-09-04T21:51:26.010000 |
44,899 | 46,996 | How to find the current name of the test being executing? | I know I can figure out the name of the method as its being executed, just wondering if there is a way from the setup method. I guess an attribute method would work but from the setup method it would be the best. EDIT NUnit | I know this is going to sound negative, but don't do it!:-) The idea behind the setup method is that it executes something required by every test, which means that it doesn't matter which test is being executed, so you don't need to know the name of the method. If you are after different data used in initialisation, then call a separate method with the data passed as a parameter from your test method. If you really want what you are asking for, then you may need a different method that takes the name of the current method as a parameter and call that from your test method. | How to find the current name of the test being executing? I know I can figure out the name of the method as its being executed, just wondering if there is a way from the setup method. I guess an attribute method would work but from the setup method it would be the best. EDIT NUnit | TITLE:
How to find the current name of the test being executing?
QUESTION:
I know I can figure out the name of the method as its being executed, just wondering if there is a way from the setup method. I guess an attribute method would work but from the setup method it would be the best. EDIT NUnit
ANSWER:
I know this is going to sound negative, but don't do it!:-) The idea behind the setup method is that it executes something required by every test, which means that it doesn't matter which test is being executed, so you don't need to know the name of the method. If you are after different data used in initialisation, then call a separate method with the data passed as a parameter from your test method. If you really want what you are asking for, then you may need a different method that takes the name of the current method as a parameter and call that from your test method. | [
"visual-studio",
"unit-testing"
] | 1 | 1 | 386 | 1 | 0 | 2008-09-04T22:25:34.087000 | 2008-09-05T22:23:15.487000 |
44,903 | 44,908 | Is there any way to repopulate an Html Select's Options without firing the Change event (using jQuery)? | I have multiple selects: one two three one two three What I want is to select "one" from the first select, then have that option be removed from the second one. Then if you select "two" from the second one, I want that one removed from the first one. Here's the JS I have currently: $(function () { var $one = $("#one"); var $two = $("#two");
var selectOptions = []; $("select").each(function (index) { selectOptions[index] = []; for (var i = 0; i < this.options.length; i++) { selectOptions[index][i] = this.options[i]; } });
$one.change(function () { var selectedValue = $("option:selected", this).val(); for (var i = 0; i < selectOptions[1].length; i++) { var exists = false; for (var x = 0; x < $two[0].options.length; x++) { if ($two[0].options[x].value == selectOptions[1][i].value) exists = true; } if (!exists) $two.append(selectOptions[1][i]); }
$("option[value='" + selectedValue + "']", $two).remove(); }); $two.change(function () { var selectedValue = $("option:selected", this).val(); for (var i = 0; i < selectOptions[0].length; i++) { var exists = false; for (var x = 0; x < $one[0].options.length; x++) { if ($one[0].options[x].value == selectOptions[0][i].value) exists = true; } if (!exists) $one.append(selectOptions[0][i]); }
$("option[value='" + selectedValue + "']", $one).remove(); }); }); But when the elements get repopulated, it fires the change event in the select whose options are changing. I tried just setting the disabled attribute on the option I want to remove, but that doesn't work with IE6. | I am not (currently) a user of jQuery, but I can tell you that you need to temporarily disconnect your event handler while you repopulate the items or, at the least, set a flag that you then test for and based on its value, handle the change. | Is there any way to repopulate an Html Select's Options without firing the Change event (using jQuery)? I have multiple selects: one two three one two three What I want is to select "one" from the first select, then have that option be removed from the second one. Then if you select "two" from the second one, I want that one removed from the first one. Here's the JS I have currently: $(function () { var $one = $("#one"); var $two = $("#two");
var selectOptions = []; $("select").each(function (index) { selectOptions[index] = []; for (var i = 0; i < this.options.length; i++) { selectOptions[index][i] = this.options[i]; } });
$one.change(function () { var selectedValue = $("option:selected", this).val(); for (var i = 0; i < selectOptions[1].length; i++) { var exists = false; for (var x = 0; x < $two[0].options.length; x++) { if ($two[0].options[x].value == selectOptions[1][i].value) exists = true; } if (!exists) $two.append(selectOptions[1][i]); }
$("option[value='" + selectedValue + "']", $two).remove(); }); $two.change(function () { var selectedValue = $("option:selected", this).val(); for (var i = 0; i < selectOptions[0].length; i++) { var exists = false; for (var x = 0; x < $one[0].options.length; x++) { if ($one[0].options[x].value == selectOptions[0][i].value) exists = true; } if (!exists) $one.append(selectOptions[0][i]); }
$("option[value='" + selectedValue + "']", $one).remove(); }); }); But when the elements get repopulated, it fires the change event in the select whose options are changing. I tried just setting the disabled attribute on the option I want to remove, but that doesn't work with IE6. | TITLE:
Is there any way to repopulate an Html Select's Options without firing the Change event (using jQuery)?
QUESTION:
I have multiple selects: one two three one two three What I want is to select "one" from the first select, then have that option be removed from the second one. Then if you select "two" from the second one, I want that one removed from the first one. Here's the JS I have currently: $(function () { var $one = $("#one"); var $two = $("#two");
var selectOptions = []; $("select").each(function (index) { selectOptions[index] = []; for (var i = 0; i < this.options.length; i++) { selectOptions[index][i] = this.options[i]; } });
$one.change(function () { var selectedValue = $("option:selected", this).val(); for (var i = 0; i < selectOptions[1].length; i++) { var exists = false; for (var x = 0; x < $two[0].options.length; x++) { if ($two[0].options[x].value == selectOptions[1][i].value) exists = true; } if (!exists) $two.append(selectOptions[1][i]); }
$("option[value='" + selectedValue + "']", $two).remove(); }); $two.change(function () { var selectedValue = $("option:selected", this).val(); for (var i = 0; i < selectOptions[0].length; i++) { var exists = false; for (var x = 0; x < $one[0].options.length; x++) { if ($one[0].options[x].value == selectOptions[0][i].value) exists = true; } if (!exists) $one.append(selectOptions[0][i]); }
$("option[value='" + selectedValue + "']", $one).remove(); }); }); But when the elements get repopulated, it fires the change event in the select whose options are changing. I tried just setting the disabled attribute on the option I want to remove, but that doesn't work with IE6.
ANSWER:
I am not (currently) a user of jQuery, but I can tell you that you need to temporarily disconnect your event handler while you repopulate the items or, at the least, set a flag that you then test for and based on its value, handle the change. | [
"javascript",
"jquery",
"dom",
"html-select"
] | 9 | 3 | 1,492 | 3 | 0 | 2008-09-04T22:32:51.573000 | 2008-09-04T22:38:57.347000 |
44,905 | 44,921 | C# switch statement limitations - why? | When writing a switch statement, there appears to be two limitations on what you can switch on in case statements. For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!), Type t = typeof(int);
switch (t) {
case typeof(int): Console.WriteLine("int!"); break;
case typeof(string): Console.WriteLine("string!"); break;
default: Console.WriteLine("unknown!"); break; } Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'. Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is, primitive). What is the justification? | This is my original post, which sparked some debate... because it is wrong: The switch statement is not the same thing as a big if-else statement. Each case must be unique and evaluated statically. The switch statement does a constant time branch regardless of how many cases you have. The if-else statement evaluates each condition until it finds one that is true. In fact, the C# switch statement is not always a constant time branch. In some cases the compiler will use a CIL switch statement which is indeed a constant time branch using a jump table. However, in sparse cases as pointed out by Ivan Hamilton the compiler may generate something else entirely. This is actually quite easy to verify by writing various C# switch statements, some sparse, some dense, and looking at the resulting CIL with the ildasm.exe tool. | C# switch statement limitations - why? When writing a switch statement, there appears to be two limitations on what you can switch on in case statements. For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!), Type t = typeof(int);
switch (t) {
case typeof(int): Console.WriteLine("int!"); break;
case typeof(string): Console.WriteLine("string!"); break;
default: Console.WriteLine("unknown!"); break; } Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'. Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is, primitive). What is the justification? | TITLE:
C# switch statement limitations - why?
QUESTION:
When writing a switch statement, there appears to be two limitations on what you can switch on in case statements. For example (and yes, I know, if you're doing this sort of thing it probably means your object-oriented (OO) architecture is iffy - this is just a contrived example!), Type t = typeof(int);
switch (t) {
case typeof(int): Console.WriteLine("int!"); break;
case typeof(string): Console.WriteLine("string!"); break;
default: Console.WriteLine("unknown!"); break; } Here the switch() statement fails with 'A value of an integral type expected' and the case statements fail with 'A constant value is expected'. Why are these restrictions in place, and what is the underlying justification? I don't see any reason why the switch statement has to succumb to static analysis only, and why the value being switched on has to be integral (that is, primitive). What is the justification?
ANSWER:
This is my original post, which sparked some debate... because it is wrong: The switch statement is not the same thing as a big if-else statement. Each case must be unique and evaluated statically. The switch statement does a constant time branch regardless of how many cases you have. The if-else statement evaluates each condition until it finds one that is true. In fact, the C# switch statement is not always a constant time branch. In some cases the compiler will use a CIL switch statement which is indeed a constant time branch using a jump table. However, in sparse cases as pointed out by Ivan Hamilton the compiler may generate something else entirely. This is actually quite easy to verify by writing various C# switch statements, some sparse, some dense, and looking at the resulting CIL with the ildasm.exe tool. | [
"c#",
"switch-statement"
] | 151 | 107 | 124,266 | 17 | 0 | 2008-09-04T22:34:47.030000 | 2008-09-04T22:51:03.980000 |
44,909 | 44,971 | What essential design artifacts do you produce? | In the course of your software development lifecycle, what essential design artifacts do you produce? What makes them essential to your practice? The project I'm currently on has been in production for more than 8 years. This web application has been actively enhanced and maintained over that time. While we have CMMI -based policies and processes in place, with portions of our practice being well defined, the design phase has been largely overlooked. What are the best practices? | Having worked on a lot of waterfall projects in the past and a lot of adhoc and agile projects more recently, there's a number of design artifacts I like to create although I can't state enough that it really depends on the details of the project (methodology, team structure, timescale, tools, etc.). For a generic, server-based 'enterprise application' I'd want the bare minimum to be something along these lines: A detailed functional design document (aka specification). Generally something along the lines of Joel s' WhatsTimeIsIt example specification, although probably with some UML use case diagrams. A software technical design document. It is not necessarily detailed for 100% system coverage, but detailed in all the key areas and containing all the design decisions. Being a bit of an UML freak, it'd be nice to see lots of pictures along the lines of package diagrams, component diagrams, key feature class diagrams, and probably some sequence diagrams thrown in for good measure. An infrastructure design document. Probably with UML deployment diagram for the conceptual design and perhaps a network diagram for something more physical. When I say document, any of the above might be broken down into multiple documents, or perhaps stored on a wiki/some other tool. As for their usefulness, my philosophy has always been that a development team should always be able to hand over an application to a support team without having to hand over their phone numbers. If the design artifacts don't clearly indicate what the application does, how it does it, and where it does it then you know the support teams are going to give the app the same care and attention they would a rabid dog. I should mention I'm not vindicating the practice of handing software over from a development team to a support team once it's finished, which raises all manner of interesting issues; I'm just saying it should be possible if the management so desired. | What essential design artifacts do you produce? In the course of your software development lifecycle, what essential design artifacts do you produce? What makes them essential to your practice? The project I'm currently on has been in production for more than 8 years. This web application has been actively enhanced and maintained over that time. While we have CMMI -based policies and processes in place, with portions of our practice being well defined, the design phase has been largely overlooked. What are the best practices? | TITLE:
What essential design artifacts do you produce?
QUESTION:
In the course of your software development lifecycle, what essential design artifacts do you produce? What makes them essential to your practice? The project I'm currently on has been in production for more than 8 years. This web application has been actively enhanced and maintained over that time. While we have CMMI -based policies and processes in place, with portions of our practice being well defined, the design phase has been largely overlooked. What are the best practices?
ANSWER:
Having worked on a lot of waterfall projects in the past and a lot of adhoc and agile projects more recently, there's a number of design artifacts I like to create although I can't state enough that it really depends on the details of the project (methodology, team structure, timescale, tools, etc.). For a generic, server-based 'enterprise application' I'd want the bare minimum to be something along these lines: A detailed functional design document (aka specification). Generally something along the lines of Joel s' WhatsTimeIsIt example specification, although probably with some UML use case diagrams. A software technical design document. It is not necessarily detailed for 100% system coverage, but detailed in all the key areas and containing all the design decisions. Being a bit of an UML freak, it'd be nice to see lots of pictures along the lines of package diagrams, component diagrams, key feature class diagrams, and probably some sequence diagrams thrown in for good measure. An infrastructure design document. Probably with UML deployment diagram for the conceptual design and perhaps a network diagram for something more physical. When I say document, any of the above might be broken down into multiple documents, or perhaps stored on a wiki/some other tool. As for their usefulness, my philosophy has always been that a development team should always be able to hand over an application to a support team without having to hand over their phone numbers. If the design artifacts don't clearly indicate what the application does, how it does it, and where it does it then you know the support teams are going to give the app the same care and attention they would a rabid dog. I should mention I'm not vindicating the practice of handing software over from a development team to a support team once it's finished, which raises all manner of interesting issues; I'm just saying it should be possible if the management so desired. | [
"artifacts"
] | 2 | 6 | 10,960 | 6 | 0 | 2008-09-04T22:39:52.790000 | 2008-09-04T23:28:49.020000 |
44,912 | 44,928 | Java Delegates? | Does the Java language have delegate features, similar to how C# has support for delegates? | Not really, no. You may be able to achieve the same effect by using reflection to get Method objects you can then invoke, and the other way is to create an interface with a single 'invoke' or 'execute' method, and then instantiate them to call the method your interested in (i.e. using an anonymous inner class). You might also find this article interesting / useful: A Java Programmer Looks at C# Delegates (@blueskyprojects.com) | Java Delegates? Does the Java language have delegate features, similar to how C# has support for delegates? | TITLE:
Java Delegates?
QUESTION:
Does the Java language have delegate features, similar to how C# has support for delegates?
ANSWER:
Not really, no. You may be able to achieve the same effect by using reflection to get Method objects you can then invoke, and the other way is to create an interface with a single 'invoke' or 'execute' method, and then instantiate them to call the method your interested in (i.e. using an anonymous inner class). You might also find this article interesting / useful: A Java Programmer Looks at C# Delegates (@blueskyprojects.com) | [
"java",
"delegates"
] | 224 | 170 | 302,304 | 14 | 0 | 2008-09-04T22:45:00.030000 | 2008-09-04T22:54:49.447000 |
44,914 | 44,934 | Windows Forms Application Performance | My app has many controls on its surface, and more are added dynamically at runtime. Although i am using tabs to limit the number of controls shown, and double-buffering too, it still flickers and stutters when it has to redraw (resize, maximize, etc). What are your tips and tricks to improve WinForms app performance? | I know of two things you can do but they don't always apply to all situations. You're going to get better performance if you're using absolute positioning for each control (myNewlyCreatedButton.Location.X/Y) as opposed to using a flow layout panel or a table layout panel. WinForms has to do a lot less math trying to figure out where controls should be placed. If there is a single operation in which you're adding/removing/modifying a lot of controls, call "SuspendLayout()" on the container of the affected controls (whether it is a panel or the whole form), and when you're done with your work call "ResumeLayout()" on the same panel. If you don't, the form will have to do a layout pass each and every time you add/remove/modify a control, which cost a lot more time. see: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout(VS.80).aspx Although, I'm not sure how these approaches could apply when resizing a window. | Windows Forms Application Performance My app has many controls on its surface, and more are added dynamically at runtime. Although i am using tabs to limit the number of controls shown, and double-buffering too, it still flickers and stutters when it has to redraw (resize, maximize, etc). What are your tips and tricks to improve WinForms app performance? | TITLE:
Windows Forms Application Performance
QUESTION:
My app has many controls on its surface, and more are added dynamically at runtime. Although i am using tabs to limit the number of controls shown, and double-buffering too, it still flickers and stutters when it has to redraw (resize, maximize, etc). What are your tips and tricks to improve WinForms app performance?
ANSWER:
I know of two things you can do but they don't always apply to all situations. You're going to get better performance if you're using absolute positioning for each control (myNewlyCreatedButton.Location.X/Y) as opposed to using a flow layout panel or a table layout panel. WinForms has to do a lot less math trying to figure out where controls should be placed. If there is a single operation in which you're adding/removing/modifying a lot of controls, call "SuspendLayout()" on the container of the affected controls (whether it is a panel or the whole form), and when you're done with your work call "ResumeLayout()" on the same panel. If you don't, the form will have to do a layout pass each and every time you add/remove/modify a control, which cost a lot more time. see: http://msdn.microsoft.com/en-us/library/system.windows.forms.control.suspendlayout(VS.80).aspx Although, I'm not sure how these approaches could apply when resizing a window. | [
"winforms",
"performance"
] | 5 | 5 | 3,676 | 4 | 0 | 2008-09-04T22:48:22.143000 | 2008-09-04T23:00:44.690000 |
44,917 | 44,932 | Explicit vs implicit SQL joins | Is there any efficiency difference in an explicit vs implicit inner join? For example: SELECT * FROM table a INNER JOIN table b ON a.id = b.id; vs. SELECT a.*, b.* FROM table a, table b WHERE a.id = b.id; | Performance-wise, they are exactly the same (at least in SQL Server). PS: Be aware that the "implicit OUTER JOIN " syntax--using *= or =* in a WHERE after using comma--is deprecated since SQL Server 2005. (The "implicit ( CROSS ) JOIN " syntax using comma as used in the question is still supported.) Deprecation of "Old Style" JOIN Syntax: Only A Partial Thing | Explicit vs implicit SQL joins Is there any efficiency difference in an explicit vs implicit inner join? For example: SELECT * FROM table a INNER JOIN table b ON a.id = b.id; vs. SELECT a.*, b.* FROM table a, table b WHERE a.id = b.id; | TITLE:
Explicit vs implicit SQL joins
QUESTION:
Is there any efficiency difference in an explicit vs implicit inner join? For example: SELECT * FROM table a INNER JOIN table b ON a.id = b.id; vs. SELECT a.*, b.* FROM table a, table b WHERE a.id = b.id;
ANSWER:
Performance-wise, they are exactly the same (at least in SQL Server). PS: Be aware that the "implicit OUTER JOIN " syntax--using *= or =* in a WHERE after using comma--is deprecated since SQL Server 2005. (The "implicit ( CROSS ) JOIN " syntax using comma as used in the question is still supported.) Deprecation of "Old Style" JOIN Syntax: Only A Partial Thing | [
"sql",
"join"
] | 495 | 172 | 230,523 | 12 | 0 | 2008-09-04T22:49:58.117000 | 2008-09-04T22:56:56.413000 |
44,937 | 44,939 | How do you make an etag that matches Apache? | I want to make an etag that matches what Apache produces. How does apache create it's etags? | Apache uses the standard format of inode-filesize-mtime. The only caveat to this is that the mtime must be epoch time and padded with zeros so it is 16 digits. Here is how to do it in PHP: $fs = stat($file); header("Etag: ".sprintf('"%x-%x-%s"', $fs['ino'], $fs['size'],base_convert(str_pad($fs['mtime'],16,"0"),10,16))); | How do you make an etag that matches Apache? I want to make an etag that matches what Apache produces. How does apache create it's etags? | TITLE:
How do you make an etag that matches Apache?
QUESTION:
I want to make an etag that matches what Apache produces. How does apache create it's etags?
ANSWER:
Apache uses the standard format of inode-filesize-mtime. The only caveat to this is that the mtime must be epoch time and padded with zeros so it is 16 digits. Here is how to do it in PHP: $fs = stat($file); header("Etag: ".sprintf('"%x-%x-%s"', $fs['ino'], $fs['size'],base_convert(str_pad($fs['mtime'],16,"0"),10,16))); | [
"apache",
"http",
"etag"
] | 13 | 11 | 7,533 | 4 | 0 | 2008-09-04T23:02:07.743000 | 2008-09-04T23:04:03.837000 |
44,940 | 44,947 | Learning CIL | Does anybody know any good resources for learning how to program CIL with in-depth descriptions of commands, etc.? I have looked around but not found anything particularly good. | The only CIL book on my shelf is Expert.NET 2.0 IL Assembler by Serge Lidin. In terms of what the individual opcodes do or mean, the Microsoft documentation on System.Reflection.Emit has some pretty good information. And it's always useful to look at existing IL with Reflector. Edit: CIL (and indeed the CLR in general) has not changed at all between.NET 2.0 and.NET 3.5 -- the underlying runtime is basically the same, modulo fixes and performance improvements. So there's nothing newer available on a CIL level than what would be in a book on 2.0 | Learning CIL Does anybody know any good resources for learning how to program CIL with in-depth descriptions of commands, etc.? I have looked around but not found anything particularly good. | TITLE:
Learning CIL
QUESTION:
Does anybody know any good resources for learning how to program CIL with in-depth descriptions of commands, etc.? I have looked around but not found anything particularly good.
ANSWER:
The only CIL book on my shelf is Expert.NET 2.0 IL Assembler by Serge Lidin. In terms of what the individual opcodes do or mean, the Microsoft documentation on System.Reflection.Emit has some pretty good information. And it's always useful to look at existing IL with Reflector. Edit: CIL (and indeed the CLR in general) has not changed at all between.NET 2.0 and.NET 3.5 -- the underlying runtime is basically the same, modulo fixes and performance improvements. So there's nothing newer available on a CIL level than what would be in a book on 2.0 | [
".net",
"cil"
] | 9 | 20 | 1,676 | 3 | 0 | 2008-09-04T23:04:12.340000 | 2008-09-04T23:09:31.970000 |
44,942 | 44,954 | Cast List<int> to List<string> in .NET 2.0 | Can you cast a List to List somehow? I know I could loop through and.ToString() the thing, but a cast would be awesome. I'm in C# 2.0 (so no LINQ ). | .NET 2.0 has the ConvertAll method where you can pass in a converter function: List l1 = new List (new int[] { 1, 2, 3 } ); List l2 = l1.ConvertAll (delegate(int i) { return i.ToString(); }); | Cast List<int> to List<string> in .NET 2.0 Can you cast a List to List somehow? I know I could loop through and.ToString() the thing, but a cast would be awesome. I'm in C# 2.0 (so no LINQ ). | TITLE:
Cast List<int> to List<string> in .NET 2.0
QUESTION:
Can you cast a List to List somehow? I know I could loop through and.ToString() the thing, but a cast would be awesome. I'm in C# 2.0 (so no LINQ ).
ANSWER:
.NET 2.0 has the ConvertAll method where you can pass in a converter function: List l1 = new List (new int[] { 1, 2, 3 } ); List l2 = l1.ConvertAll (delegate(int i) { return i.ToString(); }); | [
"c#",
"generics",
"casting"
] | 104 | 157 | 95,744 | 8 | 0 | 2008-09-04T23:06:56.360000 | 2008-09-04T23:16:00.050000 |
44,961 | 44,995 | What are the primary differences between Haskell and F#? | I've searched on the Internet for comparisons between F# and Haskell but haven't found anything really definitive. What are the primary differences and why would I want to choose one over the other? | Haskell is a "pure" functional language, where as F# has aspects of both imperative/OO and functional languages. Haskell also has lazy evaluation, which is fairly rare amongst functional languages. What do these things mean? A pure functional language, means there are no side effects (or changes in shared state, when a function is called) which means that you are guaranteed that if you call f(x), nothing else happens besides returning a value from the function, such as console output, database output, changes to global or static variables.. and although Haskell can have non pure functions (through monads), it must be 'explicitly' implied through declaration. Pure functional languages and 'No side effect' programming has gained popularity recently as it lends itself well to multi core concurrency, as it is much harder to get wrong with no shared state, rather than myriad locks & semaphores. Lazy evaluation is where a function is NOT evaluated until it is absolutely necessary required. meaning that many operation can be avoided when not necessary. Think of this in a basic C# if clause such as this: if(IsSomethingTrue() && AnotherThingTrue()) { do something; } If IsSomethingTrue() is false then AnotherThingTrue() method is never evaluated. While Haskell is an amazing language, the major benefit of F# (for the time being), is that it sits on top of the CLR. This lends it self to polyglot programming. One day, you may write your web UI in ASP.net MVC, your business logic in C#, your core algorithms in F# and your unit tests in Ironruby.... All amongst the the.Net framework. Listen to the Software Engineering radio with Simon Peyton Jones for more info on Haskell: Episode 108: Simon Peyton Jones on Functional Programming and Haskell | What are the primary differences between Haskell and F#? I've searched on the Internet for comparisons between F# and Haskell but haven't found anything really definitive. What are the primary differences and why would I want to choose one over the other? | TITLE:
What are the primary differences between Haskell and F#?
QUESTION:
I've searched on the Internet for comparisons between F# and Haskell but haven't found anything really definitive. What are the primary differences and why would I want to choose one over the other?
ANSWER:
Haskell is a "pure" functional language, where as F# has aspects of both imperative/OO and functional languages. Haskell also has lazy evaluation, which is fairly rare amongst functional languages. What do these things mean? A pure functional language, means there are no side effects (or changes in shared state, when a function is called) which means that you are guaranteed that if you call f(x), nothing else happens besides returning a value from the function, such as console output, database output, changes to global or static variables.. and although Haskell can have non pure functions (through monads), it must be 'explicitly' implied through declaration. Pure functional languages and 'No side effect' programming has gained popularity recently as it lends itself well to multi core concurrency, as it is much harder to get wrong with no shared state, rather than myriad locks & semaphores. Lazy evaluation is where a function is NOT evaluated until it is absolutely necessary required. meaning that many operation can be avoided when not necessary. Think of this in a basic C# if clause such as this: if(IsSomethingTrue() && AnotherThingTrue()) { do something; } If IsSomethingTrue() is false then AnotherThingTrue() method is never evaluated. While Haskell is an amazing language, the major benefit of F# (for the time being), is that it sits on top of the CLR. This lends it self to polyglot programming. One day, you may write your web UI in ASP.net MVC, your business logic in C#, your core algorithms in F# and your unit tests in Ironruby.... All amongst the the.Net framework. Listen to the Software Engineering radio with Simon Peyton Jones for more info on Haskell: Episode 108: Simon Peyton Jones on Functional Programming and Haskell | [
"haskell",
"f#",
"functional-programming",
"language-comparisons"
] | 135 | 127 | 32,879 | 5 | 0 | 2008-09-04T23:24:51.883000 | 2008-09-04T23:54:34.247000 |
44,973 | 44,986 | Can I run rubygems in ironruby? | Is it currently possible with pre release of ironruby to run rubygems? It seems as if I have to set an environment variable to find them? | You've been able to run rubygems under IronRuby for quite a while now. Simply download and install the latest IronRuby from codeplex, and run igem on the command line Original Answer: I'm on that mailing list - to save you the digging, someone asked this a few weeks ago, and this was the answer The answer (at this point) is no, you can't, but it doesn't seem like it'll be too far away. PS: listen to curt. He's on the core team for ironruby. <3 | Can I run rubygems in ironruby? Is it currently possible with pre release of ironruby to run rubygems? It seems as if I have to set an environment variable to find them? | TITLE:
Can I run rubygems in ironruby?
QUESTION:
Is it currently possible with pre release of ironruby to run rubygems? It seems as if I have to set an environment variable to find them?
ANSWER:
You've been able to run rubygems under IronRuby for quite a while now. Simply download and install the latest IronRuby from codeplex, and run igem on the command line Original Answer: I'm on that mailing list - to save you the digging, someone asked this a few weeks ago, and this was the answer The answer (at this point) is no, you can't, but it doesn't seem like it'll be too far away. PS: listen to curt. He's on the core team for ironruby. <3 | [
"rubygems",
"ironruby"
] | 3 | 6 | 2,174 | 3 | 0 | 2008-09-04T23:29:54.650000 | 2008-09-04T23:45:04.270000 |
44,980 | 604,042 | Programmatically Determine a Duration of a Locked Workstation? | How can one determine, in code, how long the machine is locked? Other ideas outside of C# are also welcome. I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at work rather than home (or in addition to home, I suppose), but it's locked down pretty hard courtesy of the DoD. That's part of the reason I'm rolling my own, actually. I'll write it up anyway and see if it works. Thanks everyone! | I hadn't found this before, but from any application you can hookup a SessionSwitchEventHandler. Obviously your application will need to be running, but so long as it is: Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e) { if (e.Reason == SessionSwitchReason.SessionLock) { //I left my desk } else if (e.Reason == SessionSwitchReason.SessionUnlock) { //I returned to my desk } } | Programmatically Determine a Duration of a Locked Workstation? How can one determine, in code, how long the machine is locked? Other ideas outside of C# are also welcome. I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at work rather than home (or in addition to home, I suppose), but it's locked down pretty hard courtesy of the DoD. That's part of the reason I'm rolling my own, actually. I'll write it up anyway and see if it works. Thanks everyone! | TITLE:
Programmatically Determine a Duration of a Locked Workstation?
QUESTION:
How can one determine, in code, how long the machine is locked? Other ideas outside of C# are also welcome. I like the windows service idea (and have accepted it) for simplicity and cleanliness, but unfortunately I don't think it will work for me in this particular case. I wanted to run this on my workstation at work rather than home (or in addition to home, I suppose), but it's locked down pretty hard courtesy of the DoD. That's part of the reason I'm rolling my own, actually. I'll write it up anyway and see if it works. Thanks everyone!
ANSWER:
I hadn't found this before, but from any application you can hookup a SessionSwitchEventHandler. Obviously your application will need to be running, but so long as it is: Microsoft.Win32.SystemEvents.SessionSwitch += new Microsoft.Win32.SessionSwitchEventHandler(SystemEvents_SessionSwitch);
void SystemEvents_SessionSwitch(object sender, Microsoft.Win32.SessionSwitchEventArgs e) { if (e.Reason == SessionSwitchReason.SessionLock) { //I left my desk } else if (e.Reason == SessionSwitchReason.SessionUnlock) { //I returned to my desk } } | [
"c#",
"windows"
] | 115 | 155 | 50,607 | 8 | 0 | 2008-09-04T23:37:56.207000 | 2009-03-02T21:19:36.123000 |
44,989 | 44,991 | How do you index into a var in LINQ? | I'm trying to get the following bit of code to work in LINQPad but am unable to index into a var. Anybody know how to index into a var in LINQ? string[] sa = {"one", "two", "three"}; sa[1].Dump();
var va = sa.Select( (a,i) => new {Line = a, Index = i}); va[1].Dump(); // Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable ' | As the comment says, you cannot apply indexing with [] to an expression of type System.Collections.Generic.IEnumerable. The IEnumerable interface only supports the method GetEnumerator(). However with LINQ you can call the extension method ElementAt(int). | How do you index into a var in LINQ? I'm trying to get the following bit of code to work in LINQPad but am unable to index into a var. Anybody know how to index into a var in LINQ? string[] sa = {"one", "two", "three"}; sa[1].Dump();
var va = sa.Select( (a,i) => new {Line = a, Index = i}); va[1].Dump(); // Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable ' | TITLE:
How do you index into a var in LINQ?
QUESTION:
I'm trying to get the following bit of code to work in LINQPad but am unable to index into a var. Anybody know how to index into a var in LINQ? string[] sa = {"one", "two", "three"}; sa[1].Dump();
var va = sa.Select( (a,i) => new {Line = a, Index = i}); va[1].Dump(); // Cannot apply indexing with [] to an expression of type 'System.Collections.Generic.IEnumerable '
ANSWER:
As the comment says, you cannot apply indexing with [] to an expression of type System.Collections.Generic.IEnumerable. The IEnumerable interface only supports the method GetEnumerator(). However with LINQ you can call the extension method ElementAt(int). | [
"c#",
"linq"
] | 10 | 21 | 5,538 | 2 | 0 | 2008-09-04T23:48:17.960000 | 2008-09-04T23:51:26.003000 |
44,999 | 45,034 | reassign value to query string parameter | I have a "showall" query string parameter in the url, the parameter is being added dynamically when "Show All/Show Pages" button is clicked. I want the ability to toggle "showall" query string parameter value depending on user clicking the "Show All/Show Pages" button. I'm doing some nested "if's" and string.Replace() on the url, is there a better way? All manipulations are done on the server. p.s. Toran, good suggestion, however I HAVE TO USE URL PARAMETER due to some other issues. | Just to elaborate on Toran's answer: Use: To toggle your state: protected void ToggleState(object sender, EventArgs e) { //parse string as boolean, invert, and convert back to string ShowAll.Value = (!Boolean.Parse(ShowAll.Value)).ToString(); } | reassign value to query string parameter I have a "showall" query string parameter in the url, the parameter is being added dynamically when "Show All/Show Pages" button is clicked. I want the ability to toggle "showall" query string parameter value depending on user clicking the "Show All/Show Pages" button. I'm doing some nested "if's" and string.Replace() on the url, is there a better way? All manipulations are done on the server. p.s. Toran, good suggestion, however I HAVE TO USE URL PARAMETER due to some other issues. | TITLE:
reassign value to query string parameter
QUESTION:
I have a "showall" query string parameter in the url, the parameter is being added dynamically when "Show All/Show Pages" button is clicked. I want the ability to toggle "showall" query string parameter value depending on user clicking the "Show All/Show Pages" button. I'm doing some nested "if's" and string.Replace() on the url, is there a better way? All manipulations are done on the server. p.s. Toran, good suggestion, however I HAVE TO USE URL PARAMETER due to some other issues.
ANSWER:
Just to elaborate on Toran's answer: Use: To toggle your state: protected void ToggleState(object sender, EventArgs e) { //parse string as boolean, invert, and convert back to string ShowAll.Value = (!Boolean.Parse(ShowAll.Value)).ToString(); } | [
"c#",
"query-string"
] | 1 | 3 | 797 | 4 | 0 | 2008-09-04T23:57:24.647000 | 2008-09-05T00:24:38.513000 |
45,002 | 71,858 | In Lucene how do terms get used in calculating scores, can I override it with a CustomScoreQuery? | Has someone successfully overridden the scoring of documents in a query so that the "relevancy" of a term to the field contents can be determined through one's own function? If so, was it by implementing a CustomScoreQuery and overriding the customScore(int, float, float)? I cannot seem to find a way to build either a custom sort or a custom scorer that can rank exact term matches much higher than other prefix term matches. Any suggestions would be appreciated. | I don't know lucene directly, but I can tell you that Solr, an application based on lucene, has got this feature: Boosting query via functions Let me know if it helps you. | In Lucene how do terms get used in calculating scores, can I override it with a CustomScoreQuery? Has someone successfully overridden the scoring of documents in a query so that the "relevancy" of a term to the field contents can be determined through one's own function? If so, was it by implementing a CustomScoreQuery and overriding the customScore(int, float, float)? I cannot seem to find a way to build either a custom sort or a custom scorer that can rank exact term matches much higher than other prefix term matches. Any suggestions would be appreciated. | TITLE:
In Lucene how do terms get used in calculating scores, can I override it with a CustomScoreQuery?
QUESTION:
Has someone successfully overridden the scoring of documents in a query so that the "relevancy" of a term to the field contents can be determined through one's own function? If so, was it by implementing a CustomScoreQuery and overriding the customScore(int, float, float)? I cannot seem to find a way to build either a custom sort or a custom scorer that can rank exact term matches much higher than other prefix term matches. Any suggestions would be appreciated.
ANSWER:
I don't know lucene directly, but I can tell you that Solr, an application based on lucene, has got this feature: Boosting query via functions Let me know if it helps you. | [
"lucene",
"scoring"
] | 5 | 2 | 1,307 | 1 | 0 | 2008-09-04T23:59:24.533000 | 2008-09-16T12:51:01.120000 |
45,004 | 45,008 | Complex CSS selector for parent of active child | Is there a way to select a parent element based on the class of a child element in the class? The example that is relevant to me relating to HTML output by a nice menu plugin for http://drupal.org. The output renders like this: Active Page Some Other Page My question is whether or not it is possible to apply a style to the list item that contains the anchor with the active class on it. Obviously, I'd prefer that the list item be marked as active, but I don't have control of the code that gets produced. I could perform this sort of thing using javascript (JQuery springs to mind), but I was wondering if there is a way to do this using CSS selectors. Just to be clear, I want to apply a style to the list item, not the anchor. | You can use has(): li:has(a:active) { /*... */ } Unfortunately, there's no way to do that with CSS. It's not very difficult with JavaScript though: // JavaScript code: document.getElementsByClassName("active")[0].parentNode;
// jQuery code: $('.active').parent().get(0); // This would be the 's parent. | Complex CSS selector for parent of active child Is there a way to select a parent element based on the class of a child element in the class? The example that is relevant to me relating to HTML output by a nice menu plugin for http://drupal.org. The output renders like this: Active Page Some Other Page My question is whether or not it is possible to apply a style to the list item that contains the anchor with the active class on it. Obviously, I'd prefer that the list item be marked as active, but I don't have control of the code that gets produced. I could perform this sort of thing using javascript (JQuery springs to mind), but I was wondering if there is a way to do this using CSS selectors. Just to be clear, I want to apply a style to the list item, not the anchor. | TITLE:
Complex CSS selector for parent of active child
QUESTION:
Is there a way to select a parent element based on the class of a child element in the class? The example that is relevant to me relating to HTML output by a nice menu plugin for http://drupal.org. The output renders like this: Active Page Some Other Page My question is whether or not it is possible to apply a style to the list item that contains the anchor with the active class on it. Obviously, I'd prefer that the list item be marked as active, but I don't have control of the code that gets produced. I could perform this sort of thing using javascript (JQuery springs to mind), but I was wondering if there is a way to do this using CSS selectors. Just to be clear, I want to apply a style to the list item, not the anchor.
ANSWER:
You can use has(): li:has(a:active) { /*... */ } Unfortunately, there's no way to do that with CSS. It's not very difficult with JavaScript though: // JavaScript code: document.getElementsByClassName("active")[0].parentNode;
// jQuery code: $('.active').parent().get(0); // This would be the 's parent. | [
"css",
"css-selectors"
] | 383 | 208 | 466,406 | 10 | 0 | 2008-09-05T00:01:36.243000 | 2008-09-05T00:06:05.843000 |
45,015 | 5,686,237 | Safely turning a JSON string into an object | Given a string of JSON data, how can I safely turn that string into a JavaScript object? Obviously I can do this unsafely with something like: var obj = eval("(" + json + ')'); but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval. | JSON.parse(jsonString) is a pure JavaScript approach so long as you can guarantee a reasonably modern browser. | Safely turning a JSON string into an object Given a string of JSON data, how can I safely turn that string into a JavaScript object? Obviously I can do this unsafely with something like: var obj = eval("(" + json + ')'); but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval. | TITLE:
Safely turning a JSON string into an object
QUESTION:
Given a string of JSON data, how can I safely turn that string into a JavaScript object? Obviously I can do this unsafely with something like: var obj = eval("(" + json + ')'); but that leaves me vulnerable to the JSON string containing other code, which it seems very dangerous to simply eval.
ANSWER:
JSON.parse(jsonString) is a pure JavaScript approach so long as you can guarantee a reasonably modern browser. | [
"javascript",
"json",
"parsing"
] | 1,497 | 2,120 | 1,454,822 | 28 | 0 | 2008-09-05T00:12:01.570000 | 2011-04-16T11:45:21.977000 |
45,030 | 45,037 | How to parse a string into a nullable int | I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed. I was kind of hoping that this would work int? val = stringVal as int?; But that won't work, so the way I'm doing it now is I've written this extension method public static int? ParseNullableInt(this string value) { if (value == null || value.Trim() == string.Empty) { return null; } else { try { return int.Parse(value); } catch { return null; } } } Is there a better way of doing this? EDIT: Thanks for the TryParse suggestions, I did know about that, but it worked out about the same. I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int? | int.TryParse is probably a tad easier: public static int? ToNullableInt(this string s) { int i; if (int.TryParse(s, out i)) return i; return null; } Edit @Glenn int.TryParse is "built into the framework". It and int.Parse are the way to parse strings to ints. | How to parse a string into a nullable int I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed. I was kind of hoping that this would work int? val = stringVal as int?; But that won't work, so the way I'm doing it now is I've written this extension method public static int? ParseNullableInt(this string value) { if (value == null || value.Trim() == string.Empty) { return null; } else { try { return int.Parse(value); } catch { return null; } } } Is there a better way of doing this? EDIT: Thanks for the TryParse suggestions, I did know about that, but it worked out about the same. I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int? | TITLE:
How to parse a string into a nullable int
QUESTION:
I'm wanting to parse a string into a nullable int in C#. ie. I want to get back either the int value of the string or null if it can't be parsed. I was kind of hoping that this would work int? val = stringVal as int?; But that won't work, so the way I'm doing it now is I've written this extension method public static int? ParseNullableInt(this string value) { if (value == null || value.Trim() == string.Empty) { return null; } else { try { return int.Parse(value); } catch { return null; } } } Is there a better way of doing this? EDIT: Thanks for the TryParse suggestions, I did know about that, but it worked out about the same. I'm more interested in knowing if there is a built-in framework method that will parse directly into a nullable int?
ANSWER:
int.TryParse is probably a tad easier: public static int? ToNullableInt(this string s) { int i; if (int.TryParse(s, out i)) return i; return null; } Edit @Glenn int.TryParse is "built into the framework". It and int.Parse are the way to parse strings to ints. | [
"c#",
".net",
"string",
".net-3.5",
"nullable"
] | 358 | 407 | 235,075 | 23 | 0 | 2008-09-05T00:22:54.630000 | 2008-09-05T00:25:27.433000 |
45,036 | 45,049 | Will the Garbage Collector call IDisposable.Dispose for me? | The.NET IDisposable Pattern implies that if you write a finalizer, and implement IDisposable, that your finalizer needs to explicitly call Dispose. This is logical, and is what I've always done in the rare situations where a finalizer is warranted. However, what happens if I just do this: class Foo: IDisposable { public void Dispose(){ CloseSomeHandle(); } } and don't implement a finalizer, or anything. Will the framework call the Dispose method for me? Yes I realise this sounds dumb, and all logic implies that it won't, but I've always had 2 things at the back of my head which have made me unsure. Someone a few years ago once told me that it would in fact do this, and that person had a very solid track record of "knowing their stuff." The compiler/framework does other 'magic' things depending on what interfaces you implement (eg: foreach, extension methods, serialization based on attributes, etc), so it makes sense that this might be 'magic' too. While I've read a lot of stuff about it, and there's been lots of things implied, I've never been able to find a definitive Yes or No answer to this question. | The.Net Garbage Collector calls the Object.Finalize method of an object on garbage collection. By default this does nothing and must be overidden if you want to free additional resources. Dispose is NOT automatically called and must be explicity called if resources are to be released, such as within a 'using' or 'try finally' block see http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx for more information | Will the Garbage Collector call IDisposable.Dispose for me? The.NET IDisposable Pattern implies that if you write a finalizer, and implement IDisposable, that your finalizer needs to explicitly call Dispose. This is logical, and is what I've always done in the rare situations where a finalizer is warranted. However, what happens if I just do this: class Foo: IDisposable { public void Dispose(){ CloseSomeHandle(); } } and don't implement a finalizer, or anything. Will the framework call the Dispose method for me? Yes I realise this sounds dumb, and all logic implies that it won't, but I've always had 2 things at the back of my head which have made me unsure. Someone a few years ago once told me that it would in fact do this, and that person had a very solid track record of "knowing their stuff." The compiler/framework does other 'magic' things depending on what interfaces you implement (eg: foreach, extension methods, serialization based on attributes, etc), so it makes sense that this might be 'magic' too. While I've read a lot of stuff about it, and there's been lots of things implied, I've never been able to find a definitive Yes or No answer to this question. | TITLE:
Will the Garbage Collector call IDisposable.Dispose for me?
QUESTION:
The.NET IDisposable Pattern implies that if you write a finalizer, and implement IDisposable, that your finalizer needs to explicitly call Dispose. This is logical, and is what I've always done in the rare situations where a finalizer is warranted. However, what happens if I just do this: class Foo: IDisposable { public void Dispose(){ CloseSomeHandle(); } } and don't implement a finalizer, or anything. Will the framework call the Dispose method for me? Yes I realise this sounds dumb, and all logic implies that it won't, but I've always had 2 things at the back of my head which have made me unsure. Someone a few years ago once told me that it would in fact do this, and that person had a very solid track record of "knowing their stuff." The compiler/framework does other 'magic' things depending on what interfaces you implement (eg: foreach, extension methods, serialization based on attributes, etc), so it makes sense that this might be 'magic' too. While I've read a lot of stuff about it, and there's been lots of things implied, I've never been able to find a definitive Yes or No answer to this question.
ANSWER:
The.Net Garbage Collector calls the Object.Finalize method of an object on garbage collection. By default this does nothing and must be overidden if you want to free additional resources. Dispose is NOT automatically called and must be explicity called if resources are to be released, such as within a 'using' or 'try finally' block see http://msdn.microsoft.com/en-us/library/system.object.finalize.aspx for more information | [
".net",
"dispose",
"idisposable"
] | 151 | 137 | 38,238 | 9 | 0 | 2008-09-05T00:25:21.287000 | 2008-09-05T00:40:06.167000 |
45,042 | 45,046 | How do you retrieve the commit message and file list for a particular revision? | I need to deploy a few files that were checked in sometime ago (can't remember the exact ones), so I'm looking to get a list so I can deploy just those files. What is the svn command to do this? | svn log has a --verbose parameter. I don't have a repository here to test with, but does that return a list of modified files? You can also use svn diff -r to retrieve the full change details, which you can parse or read manually to find out which files were changed. | How do you retrieve the commit message and file list for a particular revision? I need to deploy a few files that were checked in sometime ago (can't remember the exact ones), so I'm looking to get a list so I can deploy just those files. What is the svn command to do this? | TITLE:
How do you retrieve the commit message and file list for a particular revision?
QUESTION:
I need to deploy a few files that were checked in sometime ago (can't remember the exact ones), so I'm looking to get a list so I can deploy just those files. What is the svn command to do this?
ANSWER:
svn log has a --verbose parameter. I don't have a repository here to test with, but does that return a list of modified files? You can also use svn diff -r to retrieve the full change details, which you can parse or read manually to find out which files were changed. | [
"svn",
"version-control"
] | 14 | 5 | 15,395 | 2 | 0 | 2008-09-05T00:35:51.480000 | 2008-09-05T00:39:34.747000 |
45,045 | 83,999 | What can I do to resolve a "Row not found or changed" Exception in LINQ to SQL on a SQL Server Compact Edition Database? | When executing SubmitChanges to the DataContext after updating a couple properties with a LINQ to SQL connection (against SQL Server Compact Edition) I get a "Row not found or changed." ChangeConflictException. var ctx = new Data.MobileServerDataDataContext(Common.DatabasePath); var deviceSessionRecord = ctx.Sessions.First(sess => sess.SessionRecId == args.DeviceSessionId);
deviceSessionRecord.IsActive = false; deviceSessionRecord.Disconnected = DateTime.Now;
ctx.SubmitChanges(); The query generates the following SQL: UPDATE [Sessions] SET [Is_Active] = @p0, [Disconnected] = @p1 WHERE 0 = 1 -- @p0: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False] -- @p1: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:12:02 PM] -- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8 The obvious problem is the WHERE 0=1, After the record was loaded, I've confirmed that all the properties in the "deviceSessionRecord" are correct to include the primary key. Also when catching the "ChangeConflictException" there is no additional information about why this failed. I've also confirmed that this exception get's thrown with exactly one record in the database (the record I'm attempting to update) What's strange is that I have a very similar update statement in a different section of code and it generates the following SQL and does indeed update my SQL Server Compact Edition database. UPDATE [Sessions] SET [Is_Active] = @p4, [Disconnected] = @p5 WHERE ([Session_RecId] = @p0) AND ([App_RecId] = @p1) AND ([Is_Active] = 1) AND ([Established] = @p2) AND ([Disconnected] IS NULL) AND ([Member_Id] IS NULL) AND ([Company_Id] IS NULL) AND ([Site] IS NULL) AND (NOT ([Is_Device] = 1)) AND ([Machine_Name] = @p3) -- @p0: Input Guid (Size = 0; Prec = 0; Scale = 0) [0fbbee53-cf4c-4643-9045-e0a284ad131b] -- @p1: Input Guid (Size = 0; Prec = 0; Scale = 0) [7a174954-dd18-406e-833d-8da650207d3d] -- @p2: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:50 PM] -- @p3: Input String (Size = 0; Prec = 0; Scale = 0) [CWMOBILEDEV] -- @p4: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False] -- @p5: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:52 PM] -- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8 I have confirmed that the proper primary fields values have been identified in both the Database Schema and the DBML that generates the LINQ classes. I guess this is almost a two part question: Why is the exception being thrown? After reviewing the second set of generated SQL, it seems like for detecting conflicts it would be nice to check all the fields, but I imagine this would be fairly inefficient. Is this the way this always works? Is there a setting to just check the primary key? I've been fighting with this for the past two hours so any help would be appreciated. | Thats nasty, but simple: Check if the data types for all fields in the O/R-Designer match the data types in your SQL table. Double check for nullable! A column should be either nullable in both the O/R-Designer and SQL, or not nullable in both. For example, a NVARCHAR column "title" is marked as NULLable in your database, and contains the value NULL. Even though the column is marked as NOT NULLable in your O/R-Mapping, LINQ will load it successfully and set the column-String to null. Now you change something and call SubmitChanges(). LINQ will generate a SQL query containing "WHERE [title] IS NULL", to make sure the title has not been changed by someone else. LINQ looks up the properties of [title] in the mapping. LINQ will find [title] NOT NULLable. Since [title] is NOT NULLable, by logic it never could be NULL! So, optimizing the query, LINQ replaces it with "where 0 = 1", the SQL equivalent of "never". The same symptom will appear when the data types of a field does not match the data type in SQL, or if fields are missing, since LINQ will not be able to make sure the SQL data has not changed since reading the data. | What can I do to resolve a "Row not found or changed" Exception in LINQ to SQL on a SQL Server Compact Edition Database? When executing SubmitChanges to the DataContext after updating a couple properties with a LINQ to SQL connection (against SQL Server Compact Edition) I get a "Row not found or changed." ChangeConflictException. var ctx = new Data.MobileServerDataDataContext(Common.DatabasePath); var deviceSessionRecord = ctx.Sessions.First(sess => sess.SessionRecId == args.DeviceSessionId);
deviceSessionRecord.IsActive = false; deviceSessionRecord.Disconnected = DateTime.Now;
ctx.SubmitChanges(); The query generates the following SQL: UPDATE [Sessions] SET [Is_Active] = @p0, [Disconnected] = @p1 WHERE 0 = 1 -- @p0: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False] -- @p1: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:12:02 PM] -- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8 The obvious problem is the WHERE 0=1, After the record was loaded, I've confirmed that all the properties in the "deviceSessionRecord" are correct to include the primary key. Also when catching the "ChangeConflictException" there is no additional information about why this failed. I've also confirmed that this exception get's thrown with exactly one record in the database (the record I'm attempting to update) What's strange is that I have a very similar update statement in a different section of code and it generates the following SQL and does indeed update my SQL Server Compact Edition database. UPDATE [Sessions] SET [Is_Active] = @p4, [Disconnected] = @p5 WHERE ([Session_RecId] = @p0) AND ([App_RecId] = @p1) AND ([Is_Active] = 1) AND ([Established] = @p2) AND ([Disconnected] IS NULL) AND ([Member_Id] IS NULL) AND ([Company_Id] IS NULL) AND ([Site] IS NULL) AND (NOT ([Is_Device] = 1)) AND ([Machine_Name] = @p3) -- @p0: Input Guid (Size = 0; Prec = 0; Scale = 0) [0fbbee53-cf4c-4643-9045-e0a284ad131b] -- @p1: Input Guid (Size = 0; Prec = 0; Scale = 0) [7a174954-dd18-406e-833d-8da650207d3d] -- @p2: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:50 PM] -- @p3: Input String (Size = 0; Prec = 0; Scale = 0) [CWMOBILEDEV] -- @p4: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False] -- @p5: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:52 PM] -- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8 I have confirmed that the proper primary fields values have been identified in both the Database Schema and the DBML that generates the LINQ classes. I guess this is almost a two part question: Why is the exception being thrown? After reviewing the second set of generated SQL, it seems like for detecting conflicts it would be nice to check all the fields, but I imagine this would be fairly inefficient. Is this the way this always works? Is there a setting to just check the primary key? I've been fighting with this for the past two hours so any help would be appreciated. | TITLE:
What can I do to resolve a "Row not found or changed" Exception in LINQ to SQL on a SQL Server Compact Edition Database?
QUESTION:
When executing SubmitChanges to the DataContext after updating a couple properties with a LINQ to SQL connection (against SQL Server Compact Edition) I get a "Row not found or changed." ChangeConflictException. var ctx = new Data.MobileServerDataDataContext(Common.DatabasePath); var deviceSessionRecord = ctx.Sessions.First(sess => sess.SessionRecId == args.DeviceSessionId);
deviceSessionRecord.IsActive = false; deviceSessionRecord.Disconnected = DateTime.Now;
ctx.SubmitChanges(); The query generates the following SQL: UPDATE [Sessions] SET [Is_Active] = @p0, [Disconnected] = @p1 WHERE 0 = 1 -- @p0: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False] -- @p1: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:12:02 PM] -- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8 The obvious problem is the WHERE 0=1, After the record was loaded, I've confirmed that all the properties in the "deviceSessionRecord" are correct to include the primary key. Also when catching the "ChangeConflictException" there is no additional information about why this failed. I've also confirmed that this exception get's thrown with exactly one record in the database (the record I'm attempting to update) What's strange is that I have a very similar update statement in a different section of code and it generates the following SQL and does indeed update my SQL Server Compact Edition database. UPDATE [Sessions] SET [Is_Active] = @p4, [Disconnected] = @p5 WHERE ([Session_RecId] = @p0) AND ([App_RecId] = @p1) AND ([Is_Active] = 1) AND ([Established] = @p2) AND ([Disconnected] IS NULL) AND ([Member_Id] IS NULL) AND ([Company_Id] IS NULL) AND ([Site] IS NULL) AND (NOT ([Is_Device] = 1)) AND ([Machine_Name] = @p3) -- @p0: Input Guid (Size = 0; Prec = 0; Scale = 0) [0fbbee53-cf4c-4643-9045-e0a284ad131b] -- @p1: Input Guid (Size = 0; Prec = 0; Scale = 0) [7a174954-dd18-406e-833d-8da650207d3d] -- @p2: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:50 PM] -- @p3: Input String (Size = 0; Prec = 0; Scale = 0) [CWMOBILEDEV] -- @p4: Input Boolean (Size = 0; Prec = 0; Scale = 0) [False] -- @p5: Input DateTime (Size = 0; Prec = 0; Scale = 0) [9/4/2008 5:20:52 PM] -- Context: SqlProvider(SqlCE) Model: AttributedMetaModel Build: 3.5.21022.8 I have confirmed that the proper primary fields values have been identified in both the Database Schema and the DBML that generates the LINQ classes. I guess this is almost a two part question: Why is the exception being thrown? After reviewing the second set of generated SQL, it seems like for detecting conflicts it would be nice to check all the fields, but I imagine this would be fairly inefficient. Is this the way this always works? Is there a setting to just check the primary key? I've been fighting with this for the past two hours so any help would be appreciated.
ANSWER:
Thats nasty, but simple: Check if the data types for all fields in the O/R-Designer match the data types in your SQL table. Double check for nullable! A column should be either nullable in both the O/R-Designer and SQL, or not nullable in both. For example, a NVARCHAR column "title" is marked as NULLable in your database, and contains the value NULL. Even though the column is marked as NOT NULLable in your O/R-Mapping, LINQ will load it successfully and set the column-String to null. Now you change something and call SubmitChanges(). LINQ will generate a SQL query containing "WHERE [title] IS NULL", to make sure the title has not been changed by someone else. LINQ looks up the properties of [title] in the mapping. LINQ will find [title] NOT NULLable. Since [title] is NOT NULLable, by logic it never could be NULL! So, optimizing the query, LINQ replaces it with "where 0 = 1", the SQL equivalent of "never". The same symptom will appear when the data types of a field does not match the data type in SQL, or if fields are missing, since LINQ will not be able to make sure the SQL data has not changed since reading the data. | [
".net",
"linq",
"linq-to-sql"
] | 107 | 203 | 77,202 | 16 | 0 | 2008-09-05T00:39:31.707000 | 2008-09-17T14:44:57.607000 |
45,062 | 45,065 | LINQ to SQL Association - "Properties do not have matching types" | I am trying to link two fields of a given table to the same field in another table. I have done this before so I can't work out what is wrong this time. Anyway: Table1 - Id (Primary) - FK-Table2a (Nullable, foreign key relationship in DB to Table2.Id) - FK-Table2b (Nullable, foreign key relationship in DB to Table2.Id)
Table2 - Id (Primary) The association works for FK-Table2a but not FK-Table2b. In fact, when I load into LINQ to SQL, it shows Table2.Id as associated to Table1.Id. If I try and change this, or add a new association for FK-Table2b to Table2.Id it says: "Properties do not have matching types". This also works in other projects - maybe I should just copy over the.dbml? Any ideas? | No idea on the cause, but I just reconstructed my.dbml from scratch and it fixed itself. Oh for a "refresh" feature... | LINQ to SQL Association - "Properties do not have matching types" I am trying to link two fields of a given table to the same field in another table. I have done this before so I can't work out what is wrong this time. Anyway: Table1 - Id (Primary) - FK-Table2a (Nullable, foreign key relationship in DB to Table2.Id) - FK-Table2b (Nullable, foreign key relationship in DB to Table2.Id)
Table2 - Id (Primary) The association works for FK-Table2a but not FK-Table2b. In fact, when I load into LINQ to SQL, it shows Table2.Id as associated to Table1.Id. If I try and change this, or add a new association for FK-Table2b to Table2.Id it says: "Properties do not have matching types". This also works in other projects - maybe I should just copy over the.dbml? Any ideas? | TITLE:
LINQ to SQL Association - "Properties do not have matching types"
QUESTION:
I am trying to link two fields of a given table to the same field in another table. I have done this before so I can't work out what is wrong this time. Anyway: Table1 - Id (Primary) - FK-Table2a (Nullable, foreign key relationship in DB to Table2.Id) - FK-Table2b (Nullable, foreign key relationship in DB to Table2.Id)
Table2 - Id (Primary) The association works for FK-Table2a but not FK-Table2b. In fact, when I load into LINQ to SQL, it shows Table2.Id as associated to Table1.Id. If I try and change this, or add a new association for FK-Table2b to Table2.Id it says: "Properties do not have matching types". This also works in other projects - maybe I should just copy over the.dbml? Any ideas?
ANSWER:
No idea on the cause, but I just reconstructed my.dbml from scratch and it fixed itself. Oh for a "refresh" feature... | [
"c#",
"asp.net",
"linq-to-sql",
"dynamic-data"
] | 1 | 2 | 2,144 | 3 | 0 | 2008-09-05T00:58:59.740000 | 2008-09-05T01:12:58.910000 |
45,075 | 45,248 | Java: Flash a window to grab user's attention | Is there a better way to flash a window in Java than this: public static void flashWindow(JFrame frame) throws InterruptedException { int sleepTime = 50; frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); Thread.sleep(sleepTime); frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); Thread.sleep(sleepTime); frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); } I know that this code is scary...But it works alright. (I should implement a loop...) | There are two common ways to do this: use JNI to set urgency hints on the taskbar's window, and create a notification icon/message. I prefer the second way, since it's cross-platform and less annoying. See documentation on the TrayIcon class, particularly the displayMessage() method. The following links may be of interest: New System Tray Functionality in Java SE 6 Java Programming - Iconified window blinking TrayIcon for earlier versions of Java | Java: Flash a window to grab user's attention Is there a better way to flash a window in Java than this: public static void flashWindow(JFrame frame) throws InterruptedException { int sleepTime = 50; frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); Thread.sleep(sleepTime); frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); Thread.sleep(sleepTime); frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); } I know that this code is scary...But it works alright. (I should implement a loop...) | TITLE:
Java: Flash a window to grab user's attention
QUESTION:
Is there a better way to flash a window in Java than this: public static void flashWindow(JFrame frame) throws InterruptedException { int sleepTime = 50; frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); Thread.sleep(sleepTime); frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); Thread.sleep(sleepTime); frame.setVisible(false); Thread.sleep(sleepTime); frame.setVisible(true); } I know that this code is scary...But it works alright. (I should implement a loop...)
ANSWER:
There are two common ways to do this: use JNI to set urgency hints on the taskbar's window, and create a notification icon/message. I prefer the second way, since it's cross-platform and less annoying. See documentation on the TrayIcon class, particularly the displayMessage() method. The following links may be of interest: New System Tray Functionality in Java SE 6 Java Programming - Iconified window blinking TrayIcon for earlier versions of Java | [
"java",
"user-interface"
] | 3 | 6 | 7,664 | 2 | 0 | 2008-09-05T01:29:03.007000 | 2008-09-05T04:56:17.533000 |
45,078 | 45,094 | Flex and .NET - What's a good way to get data into Flex, WebORB? Web Services? | Ok, I asked a question earlier about Flex and ADO.NET Data Services but didn't get much response so I thought I'd rephrase. Does anyone have any experience building Adobe Flex applications with a.NET back-end? If so, what architecture did you use and what third-party tools if any did you employ. I've read a little about doing Flex remoting with WebORB but it seems more complicated than it should be, are web services an adequate alternative? | I've mainly used plain ASP.NET pages that return XML for situations that are mainly one-way (data from ASP.NET --> Flex/Flash) communication. The Flex side just uses a URLLoader to hit the ASP.NET page and loads the result as XML. If the communication needs to be a little more two-sided (sending more than a couple parameters to ASP.NET lets say), I have used standard ASP.NET webservices. I've never used WebOrb or Flex remoting because I've never really needed that type of interaction between the server and the SWF. Hope that helps. | Flex and .NET - What's a good way to get data into Flex, WebORB? Web Services? Ok, I asked a question earlier about Flex and ADO.NET Data Services but didn't get much response so I thought I'd rephrase. Does anyone have any experience building Adobe Flex applications with a.NET back-end? If so, what architecture did you use and what third-party tools if any did you employ. I've read a little about doing Flex remoting with WebORB but it seems more complicated than it should be, are web services an adequate alternative? | TITLE:
Flex and .NET - What's a good way to get data into Flex, WebORB? Web Services?
QUESTION:
Ok, I asked a question earlier about Flex and ADO.NET Data Services but didn't get much response so I thought I'd rephrase. Does anyone have any experience building Adobe Flex applications with a.NET back-end? If so, what architecture did you use and what third-party tools if any did you employ. I've read a little about doing Flex remoting with WebORB but it seems more complicated than it should be, are web services an adequate alternative?
ANSWER:
I've mainly used plain ASP.NET pages that return XML for situations that are mainly one-way (data from ASP.NET --> Flex/Flash) communication. The Flex side just uses a URLLoader to hit the ASP.NET page and loads the result as XML. If the communication needs to be a little more two-sided (sending more than a couple parameters to ASP.NET lets say), I have used standard ASP.NET webservices. I've never used WebOrb or Flex remoting because I've never really needed that type of interaction between the server and the SWF. Hope that helps. | [
".net",
"apache-flex"
] | 2 | 1 | 1,652 | 2 | 0 | 2008-09-05T01:31:19.770000 | 2008-09-05T02:00:34.570000 |
45,093 | 45,096 | RegEx to Detect SQL Injection | Is there a Regular Expression that can detect SQL in a string? Does anyone have a sample of something that they have used before to share? | Don't do it. You're practically guaranteed to fail. Use PreparedStatement (or its equivalent) instead. | RegEx to Detect SQL Injection Is there a Regular Expression that can detect SQL in a string? Does anyone have a sample of something that they have used before to share? | TITLE:
RegEx to Detect SQL Injection
QUESTION:
Is there a Regular Expression that can detect SQL in a string? Does anyone have a sample of something that they have used before to share?
ANSWER:
Don't do it. You're practically guaranteed to fail. Use PreparedStatement (or its equivalent) instead. | [
"sql",
"regex",
"sql-injection"
] | 7 | 41 | 25,517 | 5 | 0 | 2008-09-05T02:00:32.993000 | 2008-09-05T02:02:34.377000 |
45,097 | 45,133 | How do I know if Javascript has been turned off inside browser? | I assume that you can't use a JavaScript code snippet to validate if the browser user has turned off JavaScript. So what can I use instead? Can someone offer a code sample? I'm looking to wrap an if/then statement around it. I often code in CFML, if that helps. | Are we talking about something like this: JavaScript:...... Your browser does not support JavaScript!...... | How do I know if Javascript has been turned off inside browser? I assume that you can't use a JavaScript code snippet to validate if the browser user has turned off JavaScript. So what can I use instead? Can someone offer a code sample? I'm looking to wrap an if/then statement around it. I often code in CFML, if that helps. | TITLE:
How do I know if Javascript has been turned off inside browser?
QUESTION:
I assume that you can't use a JavaScript code snippet to validate if the browser user has turned off JavaScript. So what can I use instead? Can someone offer a code sample? I'm looking to wrap an if/then statement around it. I often code in CFML, if that helps.
ANSWER:
Are we talking about something like this: JavaScript:...... Your browser does not support JavaScript!...... | [
"javascript",
"browser"
] | 5 | 4 | 4,780 | 16 | 0 | 2008-09-05T02:04:13.077000 | 2008-09-05T02:22:35.343000 |
45,122 | 45,126 | Python packages - import by class, not file | Say I have the following file structure: app/ app.py controllers/ __init__.py project.py plugin.py If app/controllers/project.py defines a class Project, app.py would import it like this: from app.controllers.project import Project I'd like to just be able to do: from app.controllers import Project How would this be done? | You need to put from project import Project in controllers/__init__.py. Note that when Absolute imports become the default (Python 2.7?), you will want to add a dot before the module name (to avoid collisions with a top-level model named project ), i.e., from.project import Project | Python packages - import by class, not file Say I have the following file structure: app/ app.py controllers/ __init__.py project.py plugin.py If app/controllers/project.py defines a class Project, app.py would import it like this: from app.controllers.project import Project I'd like to just be able to do: from app.controllers import Project How would this be done? | TITLE:
Python packages - import by class, not file
QUESTION:
Say I have the following file structure: app/ app.py controllers/ __init__.py project.py plugin.py If app/controllers/project.py defines a class Project, app.py would import it like this: from app.controllers.project import Project I'd like to just be able to do: from app.controllers import Project How would this be done?
ANSWER:
You need to put from project import Project in controllers/__init__.py. Note that when Absolute imports become the default (Python 2.7?), you will want to add a dot before the module name (to avoid collisions with a top-level model named project ), i.e., from.project import Project | [
"python",
"package"
] | 61 | 104 | 56,142 | 1 | 0 | 2008-09-05T02:15:33.707000 | 2008-09-05T02:18:21.080000 |
45,123 | 45,138 | Interfaces and Versioning | I am designing a new System and I have a lot of Interfaces that will grow over time with the system. What is the best practice to name this interfaces ISomethingV01 ISomethingV02 etc and I do this public interface ISomething{ void method(); } then I have to add method 2 so now what I do? public interface ISomethingV2:ISomething{ void method2(); } or same other way? | Ideally, you shouldn't be changing your interfaces very often (if at all). If you do need to change an interface, you should reconsider its purpose and see if the original name still applies to it. If you still feel that the interfaces will change, and the interfaces changes are small (adding items) and you have control of the whole code base, then you should just modify the interface and fix all the compilation errors. If your change is a change in how the interface is to be used, then you need to create a separate interface (most likely with a different name) to support that alternative usage pattern. Even if you end up creating ISomething, ISomething2 and ISomething3, the consumers of your interfaces will have a hard time figuring out what the differences are between the interfaces. When should they use ISomething2 and when should they use ISomething3? Then you have to go about the process of obsoleting ISomething and ISomething2. | Interfaces and Versioning I am designing a new System and I have a lot of Interfaces that will grow over time with the system. What is the best practice to name this interfaces ISomethingV01 ISomethingV02 etc and I do this public interface ISomething{ void method(); } then I have to add method 2 so now what I do? public interface ISomethingV2:ISomething{ void method2(); } or same other way? | TITLE:
Interfaces and Versioning
QUESTION:
I am designing a new System and I have a lot of Interfaces that will grow over time with the system. What is the best practice to name this interfaces ISomethingV01 ISomethingV02 etc and I do this public interface ISomething{ void method(); } then I have to add method 2 so now what I do? public interface ISomethingV2:ISomething{ void method2(); } or same other way?
ANSWER:
Ideally, you shouldn't be changing your interfaces very often (if at all). If you do need to change an interface, you should reconsider its purpose and see if the original name still applies to it. If you still feel that the interfaces will change, and the interfaces changes are small (adding items) and you have control of the whole code base, then you should just modify the interface and fix all the compilation errors. If your change is a change in how the interface is to be used, then you need to create a separate interface (most likely with a different name) to support that alternative usage pattern. Even if you end up creating ISomething, ISomething2 and ISomething3, the consumers of your interfaces will have a hard time figuring out what the differences are between the interfaces. When should they use ISomething2 and when should they use ISomething3? Then you have to go about the process of obsoleting ISomething and ISomething2. | [
"naming-conventions",
"interface",
"versioning"
] | 12 | 5 | 3,071 | 5 | 0 | 2008-09-05T02:15:49.040000 | 2008-09-05T02:29:49.770000 |
45,163 | 45,429 | How do I convert a list with graphical links to an inline list? | Given this HTML: Galleries Information And this CSS: #topnav_galleries a, #topnav_information a { background-repeat: no-repeat; text-indent: -9000px; padding: 0; margin: 0 0; overflow: hidden; height: 46px; width: 136px; display: block; } #topnav { list-style-type: none; } #topnav_galleries a { background-image: url('image1.jpg'); } #topnav_information a { background-image: url('image2.jpg'); } How would I go about turning the topnav list into an inline list? | Try this: #topnav { overflow:hidden; } #topnav li { float:left; } And for IE you will need to add the following: #topnav { zoom:1; } Otherwise your floated < li > tags will spill out of the containing < ul >. | How do I convert a list with graphical links to an inline list? Given this HTML: Galleries Information And this CSS: #topnav_galleries a, #topnav_information a { background-repeat: no-repeat; text-indent: -9000px; padding: 0; margin: 0 0; overflow: hidden; height: 46px; width: 136px; display: block; } #topnav { list-style-type: none; } #topnav_galleries a { background-image: url('image1.jpg'); } #topnav_information a { background-image: url('image2.jpg'); } How would I go about turning the topnav list into an inline list? | TITLE:
How do I convert a list with graphical links to an inline list?
QUESTION:
Given this HTML: Galleries Information And this CSS: #topnav_galleries a, #topnav_information a { background-repeat: no-repeat; text-indent: -9000px; padding: 0; margin: 0 0; overflow: hidden; height: 46px; width: 136px; display: block; } #topnav { list-style-type: none; } #topnav_galleries a { background-image: url('image1.jpg'); } #topnav_information a { background-image: url('image2.jpg'); } How would I go about turning the topnav list into an inline list?
ANSWER:
Try this: #topnav { overflow:hidden; } #topnav li { float:left; } And for IE you will need to add the following: #topnav { zoom:1; } Otherwise your floated < li > tags will spill out of the containing < ul >. | [
"html",
"css"
] | 1 | 4 | 795 | 3 | 0 | 2008-09-05T03:03:22.873000 | 2008-09-05T08:26:22.160000 |
45,169 | 45,211 | How do I return an array of strings from an ActiveX object to JScript | I need to call into a Win32 API to get a series of strings, and I would like to return an array of those strings to JavaScript. This is for script that runs on local machine for administration scripts, not for the web browser. My IDL file for the COM object has the interface that I am calling into as: HRESULT GetArrayOfStrings([out, retval] SAFEARRAY(BSTR) * rgBstrStringArray); The function returns correctly, but the strings are getting 'lost' when they are being assigned to a variable in JavaScript. The question is: What is the proper way to get the array of strings returned to a JavaScript variable? | If i recall correctly, you'll need to wrap the SAFEARRAY in a VARIANT in order for it to get through, and then use a VBArray object to unpack it on the JS side of things: HRESULT GetArrayOfStrings(/*[out, retval]*/ VARIANT* pvarBstrStringArray) { //...
_variant_t ret; ret.vt = VT_ARRAY|VT_VARIANT; ret.parray = rgBstrStringArray; *pvarBstrStringArray = ret.Detach(); return S_OK; } then var jsFriendlyStrings = new VBArray( axOb.GetArrayOfStrings() ).toArray(); | How do I return an array of strings from an ActiveX object to JScript I need to call into a Win32 API to get a series of strings, and I would like to return an array of those strings to JavaScript. This is for script that runs on local machine for administration scripts, not for the web browser. My IDL file for the COM object has the interface that I am calling into as: HRESULT GetArrayOfStrings([out, retval] SAFEARRAY(BSTR) * rgBstrStringArray); The function returns correctly, but the strings are getting 'lost' when they are being assigned to a variable in JavaScript. The question is: What is the proper way to get the array of strings returned to a JavaScript variable? | TITLE:
How do I return an array of strings from an ActiveX object to JScript
QUESTION:
I need to call into a Win32 API to get a series of strings, and I would like to return an array of those strings to JavaScript. This is for script that runs on local machine for administration scripts, not for the web browser. My IDL file for the COM object has the interface that I am calling into as: HRESULT GetArrayOfStrings([out, retval] SAFEARRAY(BSTR) * rgBstrStringArray); The function returns correctly, but the strings are getting 'lost' when they are being assigned to a variable in JavaScript. The question is: What is the proper way to get the array of strings returned to a JavaScript variable?
ANSWER:
If i recall correctly, you'll need to wrap the SAFEARRAY in a VARIANT in order for it to get through, and then use a VBArray object to unpack it on the JS side of things: HRESULT GetArrayOfStrings(/*[out, retval]*/ VARIANT* pvarBstrStringArray) { //...
_variant_t ret; ret.vt = VT_ARRAY|VT_VARIANT; ret.parray = rgBstrStringArray; *pvarBstrStringArray = ret.Detach(); return S_OK; } then var jsFriendlyStrings = new VBArray( axOb.GetArrayOfStrings() ).toArray(); | [
"javascript",
"com",
"activex"
] | 5 | 6 | 4,460 | 2 | 0 | 2008-09-05T03:07:46.217000 | 2008-09-05T04:04:12.930000 |
45,179 | 45,186 | Are there benefits to Classic ASP over ASP.net | Having worked with Classic ASP for about 2 years now by creating a few 100 simple web forms I can't see a good reason for switching to.net; however, I'm not that versed in.net so I'm sure I could be missing a few things. Some points that I often hear around work can be found here: http://www.packtpub.com/article/Classic-ASP (not that I share all of these thoughts, but it's a good jumping off point) I'm very interested to hear what others have to say on this matter. | You're missing more than a few things! ASP.NET is orders of magnitudes more productive, robust, and maintainable than old-school ASP ever thought about being. Server side controls, third-party controls, master pages, forms authentication, forms validation, an OO model than encourages appropriate application partitioning, easy deployment, built-in debugging and tracing, state management. You even have the choice of WebForms or MVC. It's not an understatement to say that you are simply out of your mind if you don't thoroughly investigate what you're missing. | Are there benefits to Classic ASP over ASP.net Having worked with Classic ASP for about 2 years now by creating a few 100 simple web forms I can't see a good reason for switching to.net; however, I'm not that versed in.net so I'm sure I could be missing a few things. Some points that I often hear around work can be found here: http://www.packtpub.com/article/Classic-ASP (not that I share all of these thoughts, but it's a good jumping off point) I'm very interested to hear what others have to say on this matter. | TITLE:
Are there benefits to Classic ASP over ASP.net
QUESTION:
Having worked with Classic ASP for about 2 years now by creating a few 100 simple web forms I can't see a good reason for switching to.net; however, I'm not that versed in.net so I'm sure I could be missing a few things. Some points that I often hear around work can be found here: http://www.packtpub.com/article/Classic-ASP (not that I share all of these thoughts, but it's a good jumping off point) I'm very interested to hear what others have to say on this matter.
ANSWER:
You're missing more than a few things! ASP.NET is orders of magnitudes more productive, robust, and maintainable than old-school ASP ever thought about being. Server side controls, third-party controls, master pages, forms authentication, forms validation, an OO model than encourages appropriate application partitioning, easy deployment, built-in debugging and tracing, state management. You even have the choice of WebForms or MVC. It's not an understatement to say that you are simply out of your mind if you don't thoroughly investigate what you're missing. | [
"asp.net",
"asp-classic"
] | 53 | 74 | 11,882 | 19 | 0 | 2008-09-05T03:19:57.747000 | 2008-09-05T03:27:57.103000 |
45,180 | 45,187 | Problems with disabling IIS shutdown of idle worker process? | I ran into an issue with an IIS web app shutting down an idle worker process! The next request would then have to re-initialize the application, leading to delays. I disabled the IIS shutdown of idle worker processes on the application pool to resolve this. Are there any issues associated with turning this off? If the process is leaking memory, I imagine it is nice to recycle the process every now and then. Are there any other benefits to having this process shutdown? | I'm assuming that you're referring to IIS 6. Instead of disabling shutdown altogether, maybe you can just increase the amount of time it waits before killing the process. The server is essentially conserving resources - if your server can stand the resource allocation for a process that mostly sits around doing nothing, then there isn't any harm in letting it be. As you mentioned, setting the auto-recycling of the process on a memory limit would be a good idea, if the possibility of a memory leak is there. | Problems with disabling IIS shutdown of idle worker process? I ran into an issue with an IIS web app shutting down an idle worker process! The next request would then have to re-initialize the application, leading to delays. I disabled the IIS shutdown of idle worker processes on the application pool to resolve this. Are there any issues associated with turning this off? If the process is leaking memory, I imagine it is nice to recycle the process every now and then. Are there any other benefits to having this process shutdown? | TITLE:
Problems with disabling IIS shutdown of idle worker process?
QUESTION:
I ran into an issue with an IIS web app shutting down an idle worker process! The next request would then have to re-initialize the application, leading to delays. I disabled the IIS shutdown of idle worker processes on the application pool to resolve this. Are there any issues associated with turning this off? If the process is leaking memory, I imagine it is nice to recycle the process every now and then. Are there any other benefits to having this process shutdown?
ANSWER:
I'm assuming that you're referring to IIS 6. Instead of disabling shutdown altogether, maybe you can just increase the amount of time it waits before killing the process. The server is essentially conserving resources - if your server can stand the resource allocation for a process that mostly sits around doing nothing, then there isn't any harm in letting it be. As you mentioned, setting the auto-recycling of the process on a memory limit would be a good idea, if the possibility of a memory leak is there. | [
"iis"
] | 5 | 1 | 2,227 | 1 | 0 | 2008-09-05T03:20:56.247000 | 2008-09-05T03:28:07.993000 |
45,202 | 45,699 | IoC Container Configuration/Registration | I absolutely need to use an IoC container for decoupling dependencies in an ever increasingly complex system of enterprise services. The issue I am facing is one related to configuration (a.k.a. registration). We currently have 4 different environments -- development to production and in between. These environments have numerous configurations that slightly vary from environment to environment; however, in all cases that I can currently think of, dependencies between components do not differ from environment to environment, though I could have missed something and/or this could obviously change. So, the ultimate question is, does anybody have a similar experience using an IoC framework? Or, can anybody recommend one framework over another that would provide flexible registration be it through some sort of convention or simplified configuration information? Would I still be able to benefit from a fluent interface or am I stuck with XML -- I'd like to avoid XML-hell. Edit: This is a.Net environment and I have been looking at Windsor, Ninject and Autofac. They all seem to now support both methods of registration (fluent and XML), though Autofac's support for lambda expressions seems to be a little different than the others. Anybody use that in a similar multi-deployment environment? | I use Ninject. I like the fact that I don't have to use Xml to configure the dependencies. I can just use straight up C# code. There are multiple ways of doing it also. I know other libraries have that feature, but Ninject offers fast instantiation, it is pretty lightweight, it has conditional binding, supports compact framework, and it supports Silverlight, 2.0. I also use a wrapper on top of it, in case I do switch it out for another framework in the future. You should definitely try Ninject when deciding on a framework. | IoC Container Configuration/Registration I absolutely need to use an IoC container for decoupling dependencies in an ever increasingly complex system of enterprise services. The issue I am facing is one related to configuration (a.k.a. registration). We currently have 4 different environments -- development to production and in between. These environments have numerous configurations that slightly vary from environment to environment; however, in all cases that I can currently think of, dependencies between components do not differ from environment to environment, though I could have missed something and/or this could obviously change. So, the ultimate question is, does anybody have a similar experience using an IoC framework? Or, can anybody recommend one framework over another that would provide flexible registration be it through some sort of convention or simplified configuration information? Would I still be able to benefit from a fluent interface or am I stuck with XML -- I'd like to avoid XML-hell. Edit: This is a.Net environment and I have been looking at Windsor, Ninject and Autofac. They all seem to now support both methods of registration (fluent and XML), though Autofac's support for lambda expressions seems to be a little different than the others. Anybody use that in a similar multi-deployment environment? | TITLE:
IoC Container Configuration/Registration
QUESTION:
I absolutely need to use an IoC container for decoupling dependencies in an ever increasingly complex system of enterprise services. The issue I am facing is one related to configuration (a.k.a. registration). We currently have 4 different environments -- development to production and in between. These environments have numerous configurations that slightly vary from environment to environment; however, in all cases that I can currently think of, dependencies between components do not differ from environment to environment, though I could have missed something and/or this could obviously change. So, the ultimate question is, does anybody have a similar experience using an IoC framework? Or, can anybody recommend one framework over another that would provide flexible registration be it through some sort of convention or simplified configuration information? Would I still be able to benefit from a fluent interface or am I stuck with XML -- I'd like to avoid XML-hell. Edit: This is a.Net environment and I have been looking at Windsor, Ninject and Autofac. They all seem to now support both methods of registration (fluent and XML), though Autofac's support for lambda expressions seems to be a little different than the others. Anybody use that in a similar multi-deployment environment?
ANSWER:
I use Ninject. I like the fact that I don't have to use Xml to configure the dependencies. I can just use straight up C# code. There are multiple ways of doing it also. I know other libraries have that feature, but Ninject offers fast instantiation, it is pretty lightweight, it has conditional binding, supports compact framework, and it supports Silverlight, 2.0. I also use a wrapper on top of it, in case I do switch it out for another framework in the future. You should definitely try Ninject when deciding on a framework. | [
"dependency-injection",
"inversion-of-control"
] | 1 | 2 | 1,850 | 4 | 0 | 2008-09-05T03:51:57.547000 | 2008-09-05T12:44:47.577000 |
45,227 | 45,233 | List operations in Lisp | I have been searching everywhere for the following functionality in Lisp, and have gotten nowhere: find the index of something in a list. example: (index-of item InThisList) replace something at a specific spot in a list. example: (replace item InThisList AtThisIndex);i think this can be done with 'setf'? return an item at a specific index. example: (return InThisList ItemAtThisIndex) Up until this point, I've been faking it with my own functions. I'm wondering if I'm just creating more work for myself. This is how I've been faking number 1: (defun my-index (findMe mylist) (let ((counter 0) (found 1)) (dolist (item mylist) (cond ((eq item findMe);this works because 'eq' checks place in memory,;and as long as 'findMe' was from the original list, this will work. (setq found nil) (found (incf counter)))) counter)) | You can use setf and nth to replace and retrieve values by index. (let ((myList '(1 2 3 4 5 6))) (setf (nth 4 myList) 101); <---- myList)
(1 2 3 4 101 6) To find by index you can use the position function. (let ((myList '(1 2 3 4 5 6))) (setf (nth 4 myList) 101) (list myList (position 101 myList)))
((1 2 3 4 101 6) 4) I found these all in this index of functions. | List operations in Lisp I have been searching everywhere for the following functionality in Lisp, and have gotten nowhere: find the index of something in a list. example: (index-of item InThisList) replace something at a specific spot in a list. example: (replace item InThisList AtThisIndex);i think this can be done with 'setf'? return an item at a specific index. example: (return InThisList ItemAtThisIndex) Up until this point, I've been faking it with my own functions. I'm wondering if I'm just creating more work for myself. This is how I've been faking number 1: (defun my-index (findMe mylist) (let ((counter 0) (found 1)) (dolist (item mylist) (cond ((eq item findMe);this works because 'eq' checks place in memory,;and as long as 'findMe' was from the original list, this will work. (setq found nil) (found (incf counter)))) counter)) | TITLE:
List operations in Lisp
QUESTION:
I have been searching everywhere for the following functionality in Lisp, and have gotten nowhere: find the index of something in a list. example: (index-of item InThisList) replace something at a specific spot in a list. example: (replace item InThisList AtThisIndex);i think this can be done with 'setf'? return an item at a specific index. example: (return InThisList ItemAtThisIndex) Up until this point, I've been faking it with my own functions. I'm wondering if I'm just creating more work for myself. This is how I've been faking number 1: (defun my-index (findMe mylist) (let ((counter 0) (found 1)) (dolist (item mylist) (cond ((eq item findMe);this works because 'eq' checks place in memory,;and as long as 'findMe' was from the original list, this will work. (setq found nil) (found (incf counter)))) counter))
ANSWER:
You can use setf and nth to replace and retrieve values by index. (let ((myList '(1 2 3 4 5 6))) (setf (nth 4 myList) 101); <---- myList)
(1 2 3 4 101 6) To find by index you can use the position function. (let ((myList '(1 2 3 4 5 6))) (setf (nth 4 myList) 101) (list myList (position 101 myList)))
((1 2 3 4 101 6) 4) I found these all in this index of functions. | [
"functional-programming",
"lisp",
"list"
] | 7 | 23 | 8,449 | 6 | 0 | 2008-09-05T04:26:49.803000 | 2008-09-05T04:33:41.173000 |
45,228 | 46,201 | Where can I find the time and space complexity of the built-in sequence types in Python | I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online? | Checkout the TimeComplexity page on the py dot org wiki. It covers set/dicts/lists/etc at least as far as time complexity goes. | Where can I find the time and space complexity of the built-in sequence types in Python I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online? | TITLE:
Where can I find the time and space complexity of the built-in sequence types in Python
QUESTION:
I've been unable to find a source for this information, short of looking through the Python source code myself to determine how the objects work. Does anyone know where I could find this online?
ANSWER:
Checkout the TimeComplexity page on the py dot org wiki. It covers set/dicts/lists/etc at least as far as time complexity goes. | [
"python",
"performance",
"complexity-theory",
"big-o",
"sequences"
] | 19 | 19 | 4,042 | 3 | 0 | 2008-09-05T04:27:46.557000 | 2008-09-05T16:19:03.537000 |
45,230 | 45,237 | Is it possible to forward ssh requests that come in over a certain port to another machine? | I have a small local network. Only one of the machines is available to the outside world (this is not easily changeable). I'd like to be able to set it up such that ssh requests that don't come in on the standard port go to another machine. Is this possible? If so, how? Oh and all of these machines are running either Ubuntu or OS X. | Another way to go would be to use ssh tunneling (which happens on the client side). You'd do an ssh command like this: ssh -L 8022:myinsideserver:22 paul@myoutsideserver That connects you to the machine that's accessible from the outside (myoutsideserver) and creates a tunnel through that ssh connection to port 22 (the standard ssh port) on the server that's only accessible from the inside. Then you'd do another ssh command like this (leaving the first one still connected): ssh -p 8022 paul@localhost That connection to port 8022 on your localhost will then get tunneled through the first ssh connection taking you over myinsideserver. There may be something you have to do on myoutsideserver to allow forwarding of the ssh port. I'm double-checking that now. Edit Hmmm. The ssh manpage says this: **Only the superuser can forward privileged ports. ** That sort of implies to me that the first ssh connection has to be as root. Maybe somebody else can clarify that. It looks like superuser privileges aren't required as long as the forwarded port (in this case, 8022) isn't a privileged port (like 22). Thanks for the clarification Mike Stone. | Is it possible to forward ssh requests that come in over a certain port to another machine? I have a small local network. Only one of the machines is available to the outside world (this is not easily changeable). I'd like to be able to set it up such that ssh requests that don't come in on the standard port go to another machine. Is this possible? If so, how? Oh and all of these machines are running either Ubuntu or OS X. | TITLE:
Is it possible to forward ssh requests that come in over a certain port to another machine?
QUESTION:
I have a small local network. Only one of the machines is available to the outside world (this is not easily changeable). I'd like to be able to set it up such that ssh requests that don't come in on the standard port go to another machine. Is this possible? If so, how? Oh and all of these machines are running either Ubuntu or OS X.
ANSWER:
Another way to go would be to use ssh tunneling (which happens on the client side). You'd do an ssh command like this: ssh -L 8022:myinsideserver:22 paul@myoutsideserver That connects you to the machine that's accessible from the outside (myoutsideserver) and creates a tunnel through that ssh connection to port 22 (the standard ssh port) on the server that's only accessible from the inside. Then you'd do another ssh command like this (leaving the first one still connected): ssh -p 8022 paul@localhost That connection to port 8022 on your localhost will then get tunneled through the first ssh connection taking you over myinsideserver. There may be something you have to do on myoutsideserver to allow forwarding of the ssh port. I'm double-checking that now. Edit Hmmm. The ssh manpage says this: **Only the superuser can forward privileged ports. ** That sort of implies to me that the first ssh connection has to be as root. Maybe somebody else can clarify that. It looks like superuser privileges aren't required as long as the forwarded port (in this case, 8022) isn't a privileged port (like 22). Thanks for the clarification Mike Stone. | [
"macos",
"ubuntu",
"ssh",
"port"
] | 6 | 12 | 4,081 | 6 | 0 | 2008-09-05T04:30:19.980000 | 2008-09-05T04:40:18.740000 |
45,239 | 679,997 | What is the best technique for consistent form, function between all web browsers (including Google Chrome)? | Short version: What is the cleanest and most maintainable technique for consistant presentation and AJAX function across all browsers used by both web developers and web developers' end-users? IE 6, 7, 8 Firefox 2, 3 Safari Google Chrome Opera Long version: I wrote a web app aimed at other web developers. I want my app to support the major web browsers (plus Google Chrome) in both presentation and AJAX behavior. I began on Firefox/Firebug, then added conditional comments for a consistent styling under IE 6 and 7. Next, to my amazement, I discovered that jQuery does not behave identically in IE; so I changed my Javascript to be portable on FF and IE using conditionals and less pure jQuery. Today, I started testing on Webkit and Google Chrome and discovered that, not only are the styles inconsistant with both FF and IE, but Javascript is not executing at all, probably due to a syntax or parse error. I expected some CSS work, but now I have more Javascript debugging to do! At this point, I want to step back and think before writing piles of special cases for all situations. I am not looking for a silver bullet, just best practices to keep things as understandable and maintainable as possible. I prefer if this works with no server-side intelligence; however if there is a advantage to, for example, check the user-agent and then return different files to different browsers, that is fine if the total comprehensibility and maintainability of the web app is lower. Thank you all very much! | I am in a similar situation, working on a web app that is targeted at IT professionals, and required to support the same set of browsers, minus Opera. Some general things I've learned so far: Test often, in as many of your target browsers as you can. Make sure you have time for this in your development schedule. Toolkits can get you part of the way to cross-browser support, but will eventually miss something on some browser. Plan some time for debugging and researching fixes for specific browsers. If you need something that's not in a toolkit and can't find a free code snippet, invest some time to write utility functions that encapsulate the browser-dependent behavior. Educate yourself about known browser bugs, so that you can steer your implementation around them. A few more-specific things I've learned: Use conditional code based on the user-agent only as a last resort, because different generations of the "same" browser may have different features. Instead, test for standards-compliant behavior first — e.g., if(node.addEventListener)..., then common non-standard functions — e.g., if(window.attachEvent)..., and then, if you must, look at the user-agent for a specific browser type & version number. Knowing when the DOM is 'ready' for script access is different in just about every browser. A good toolkit will abstract this for you. Event handlers are different in just about every browser. A good toolkit will abstract this for you. Creating DOM elements, particularly form controls or elements with attributes, can be tricky with document.createElement and element.setAttribute. While not standard (and kinda yucky), using node.innerHTML with strings that contain bits of HTML seems to be more reliable across browser types. I have yet to find a toolkit that will let you use element.setAttribute to add a 'name' to a form element in IE. CSS differences (and bugs) are just as important as JS differences. The 'core' Javascript features (String, Date, RegExp, Array functions) seem to be pretty reliable and consistent across browsers, especially relative to the DOM/CSS/Window functions. There's some small joy in the fact that the language isn't entirely different on every platform.:-) I haven't really run into any Chrome-specific JS bugs, but it's always one of the first browsers I test. HTH | What is the best technique for consistent form, function between all web browsers (including Google Chrome)? Short version: What is the cleanest and most maintainable technique for consistant presentation and AJAX function across all browsers used by both web developers and web developers' end-users? IE 6, 7, 8 Firefox 2, 3 Safari Google Chrome Opera Long version: I wrote a web app aimed at other web developers. I want my app to support the major web browsers (plus Google Chrome) in both presentation and AJAX behavior. I began on Firefox/Firebug, then added conditional comments for a consistent styling under IE 6 and 7. Next, to my amazement, I discovered that jQuery does not behave identically in IE; so I changed my Javascript to be portable on FF and IE using conditionals and less pure jQuery. Today, I started testing on Webkit and Google Chrome and discovered that, not only are the styles inconsistant with both FF and IE, but Javascript is not executing at all, probably due to a syntax or parse error. I expected some CSS work, but now I have more Javascript debugging to do! At this point, I want to step back and think before writing piles of special cases for all situations. I am not looking for a silver bullet, just best practices to keep things as understandable and maintainable as possible. I prefer if this works with no server-side intelligence; however if there is a advantage to, for example, check the user-agent and then return different files to different browsers, that is fine if the total comprehensibility and maintainability of the web app is lower. Thank you all very much! | TITLE:
What is the best technique for consistent form, function between all web browsers (including Google Chrome)?
QUESTION:
Short version: What is the cleanest and most maintainable technique for consistant presentation and AJAX function across all browsers used by both web developers and web developers' end-users? IE 6, 7, 8 Firefox 2, 3 Safari Google Chrome Opera Long version: I wrote a web app aimed at other web developers. I want my app to support the major web browsers (plus Google Chrome) in both presentation and AJAX behavior. I began on Firefox/Firebug, then added conditional comments for a consistent styling under IE 6 and 7. Next, to my amazement, I discovered that jQuery does not behave identically in IE; so I changed my Javascript to be portable on FF and IE using conditionals and less pure jQuery. Today, I started testing on Webkit and Google Chrome and discovered that, not only are the styles inconsistant with both FF and IE, but Javascript is not executing at all, probably due to a syntax or parse error. I expected some CSS work, but now I have more Javascript debugging to do! At this point, I want to step back and think before writing piles of special cases for all situations. I am not looking for a silver bullet, just best practices to keep things as understandable and maintainable as possible. I prefer if this works with no server-side intelligence; however if there is a advantage to, for example, check the user-agent and then return different files to different browsers, that is fine if the total comprehensibility and maintainability of the web app is lower. Thank you all very much!
ANSWER:
I am in a similar situation, working on a web app that is targeted at IT professionals, and required to support the same set of browsers, minus Opera. Some general things I've learned so far: Test often, in as many of your target browsers as you can. Make sure you have time for this in your development schedule. Toolkits can get you part of the way to cross-browser support, but will eventually miss something on some browser. Plan some time for debugging and researching fixes for specific browsers. If you need something that's not in a toolkit and can't find a free code snippet, invest some time to write utility functions that encapsulate the browser-dependent behavior. Educate yourself about known browser bugs, so that you can steer your implementation around them. A few more-specific things I've learned: Use conditional code based on the user-agent only as a last resort, because different generations of the "same" browser may have different features. Instead, test for standards-compliant behavior first — e.g., if(node.addEventListener)..., then common non-standard functions — e.g., if(window.attachEvent)..., and then, if you must, look at the user-agent for a specific browser type & version number. Knowing when the DOM is 'ready' for script access is different in just about every browser. A good toolkit will abstract this for you. Event handlers are different in just about every browser. A good toolkit will abstract this for you. Creating DOM elements, particularly form controls or elements with attributes, can be tricky with document.createElement and element.setAttribute. While not standard (and kinda yucky), using node.innerHTML with strings that contain bits of HTML seems to be more reliable across browser types. I have yet to find a toolkit that will let you use element.setAttribute to add a 'name' to a form element in IE. CSS differences (and bugs) are just as important as JS differences. The 'core' Javascript features (String, Date, RegExp, Array functions) seem to be pretty reliable and consistent across browsers, especially relative to the DOM/CSS/Window functions. There's some small joy in the fact that the language isn't entirely different on every platform.:-) I haven't really run into any Chrome-specific JS bugs, but it's always one of the first browsers I test. HTH | [
"css",
"google-chrome",
"portability"
] | 10 | 14 | 1,452 | 11 | 0 | 2008-09-05T04:43:43.350000 | 2009-03-25T02:19:42.190000 |
45,252 | 45,370 | Load Balancing of Process in 1 Server | I have 1 process that receives incoming connection from port 1000 in 1 linux server. However, 1 process is not fast enough to handle all the incoming request. I want to run multiple processes in the server but with 1 end-point. In this way, the client will only see 1 end-point/process not multiple. I have checked LVS and other Load Balancing Solution. Those solutions seem geared towards multiple servers load-balancing. Any other solution to help on my case? i am looking something more like nginx where i will need to run multiple copies of my app. Let me try it out. Thanks for the help. | You also may want to go with a web server like nginx. It can load balance your app against multiple ports of the same app, and is commonly used to load balance Ruby on Rails apps (which are single threaded). The downside is that you need to run multiple copies of your app (one on each port) for this load balancing to work. | Load Balancing of Process in 1 Server I have 1 process that receives incoming connection from port 1000 in 1 linux server. However, 1 process is not fast enough to handle all the incoming request. I want to run multiple processes in the server but with 1 end-point. In this way, the client will only see 1 end-point/process not multiple. I have checked LVS and other Load Balancing Solution. Those solutions seem geared towards multiple servers load-balancing. Any other solution to help on my case? i am looking something more like nginx where i will need to run multiple copies of my app. Let me try it out. Thanks for the help. | TITLE:
Load Balancing of Process in 1 Server
QUESTION:
I have 1 process that receives incoming connection from port 1000 in 1 linux server. However, 1 process is not fast enough to handle all the incoming request. I want to run multiple processes in the server but with 1 end-point. In this way, the client will only see 1 end-point/process not multiple. I have checked LVS and other Load Balancing Solution. Those solutions seem geared towards multiple servers load-balancing. Any other solution to help on my case? i am looking something more like nginx where i will need to run multiple copies of my app. Let me try it out. Thanks for the help.
ANSWER:
You also may want to go with a web server like nginx. It can load balance your app against multiple ports of the same app, and is commonly used to load balance Ruby on Rails apps (which are single threaded). The downside is that you need to run multiple copies of your app (one on each port) for this load balancing to work. | [
"linux",
"load-balancing"
] | 1 | 2 | 2,252 | 7 | 0 | 2008-09-05T05:06:23.437000 | 2008-09-05T07:13:01.993000 |
45,253 | 45,261 | Adding functionality to Rails | I'm working on a Rails app and am looking to include some functionality from " Getting the Hostname or IP in Ruby on Rails " that I asked. I'm having problems getting it to work. I was under the impression that I should just make a file in the lib directory, so I named it 'get_ip.rb', with the contents: require 'socket'
module GetIP def local_ip orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s| s.connect '64.233.187.99', 1 s.addr.last end ensure Socket.do_not_reverse_lookup = orig end end I had also tried defining GetIP as a class but when I do the usual ruby script/console, I'm not able to use the local_ip method at all. Any ideas? | You haven't described how you're trying to use the method, so I apologize in advance if this is stuff you already know. The methods on a module never come into use unless the module is included into a class. Instance methods on a class require there to be an instance of the class. You probably want a class method instead. And the file itself should be loaded, generally through the require statement. If the following code is in the file getip.rb, require 'socket'
class GetIP def self.local_ip orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true
UDPSocket.open do |s| s.connect '64.233.187.99', 1 s.addr.last end ensure Socket.do_not_reverse_lookup = orig end end Then you should be able to run it by saying, require 'getip' GetIP.local_ip | Adding functionality to Rails I'm working on a Rails app and am looking to include some functionality from " Getting the Hostname or IP in Ruby on Rails " that I asked. I'm having problems getting it to work. I was under the impression that I should just make a file in the lib directory, so I named it 'get_ip.rb', with the contents: require 'socket'
module GetIP def local_ip orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s| s.connect '64.233.187.99', 1 s.addr.last end ensure Socket.do_not_reverse_lookup = orig end end I had also tried defining GetIP as a class but when I do the usual ruby script/console, I'm not able to use the local_ip method at all. Any ideas? | TITLE:
Adding functionality to Rails
QUESTION:
I'm working on a Rails app and am looking to include some functionality from " Getting the Hostname or IP in Ruby on Rails " that I asked. I'm having problems getting it to work. I was under the impression that I should just make a file in the lib directory, so I named it 'get_ip.rb', with the contents: require 'socket'
module GetIP def local_ip orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true # turn off reverse DNS resolution temporarily
UDPSocket.open do |s| s.connect '64.233.187.99', 1 s.addr.last end ensure Socket.do_not_reverse_lookup = orig end end I had also tried defining GetIP as a class but when I do the usual ruby script/console, I'm not able to use the local_ip method at all. Any ideas?
ANSWER:
You haven't described how you're trying to use the method, so I apologize in advance if this is stuff you already know. The methods on a module never come into use unless the module is included into a class. Instance methods on a class require there to be an instance of the class. You probably want a class method instead. And the file itself should be loaded, generally through the require statement. If the following code is in the file getip.rb, require 'socket'
class GetIP def self.local_ip orig, Socket.do_not_reverse_lookup = Socket.do_not_reverse_lookup, true
UDPSocket.open do |s| s.connect '64.233.187.99', 1 s.addr.last end ensure Socket.do_not_reverse_lookup = orig end end Then you should be able to run it by saying, require 'getip' GetIP.local_ip | [
"ruby-on-rails",
"ruby"
] | 2 | 4 | 1,026 | 3 | 0 | 2008-09-05T05:07:38.333000 | 2008-09-05T05:19:10.490000 |
45,264 | 45,271 | Django Calendar Widget? | Does anyone know of any existing packages or libraries that can be used to build a calendar in a django app? | A quick google search reveals django-gencal, which looks like exactly what you need. It would also be worth looking at the snippets under the calendar tag on Django Snippets at http://www.djangosnippets.org/tags/calendar/. | Django Calendar Widget? Does anyone know of any existing packages or libraries that can be used to build a calendar in a django app? | TITLE:
Django Calendar Widget?
QUESTION:
Does anyone know of any existing packages or libraries that can be used to build a calendar in a django app?
ANSWER:
A quick google search reveals django-gencal, which looks like exactly what you need. It would also be worth looking at the snippets under the calendar tag on Django Snippets at http://www.djangosnippets.org/tags/calendar/. | [
"django",
"calendar"
] | 34 | 17 | 32,197 | 8 | 0 | 2008-09-05T05:20:57.443000 | 2008-09-05T05:27:26.397000 |
45,267 | 46,158 | How do I make AutoCompleteExtender render above select controls in IE6 | When an AutoCompleteExtender is displayed in IE6 it seems to ignore z-index and renders below any select controls (like dropdownlists ) in IE6. How do I make it render above dropdownlists? | @Orion has this partially correct - there is one other way to deal with these, and that is to cover the offending select lists with an iframe. This technique is used in Cody Lindley's ThickBox (written for jQuery). See the code for details on how to do it. | How do I make AutoCompleteExtender render above select controls in IE6 When an AutoCompleteExtender is displayed in IE6 it seems to ignore z-index and renders below any select controls (like dropdownlists ) in IE6. How do I make it render above dropdownlists? | TITLE:
How do I make AutoCompleteExtender render above select controls in IE6
QUESTION:
When an AutoCompleteExtender is displayed in IE6 it seems to ignore z-index and renders below any select controls (like dropdownlists ) in IE6. How do I make it render above dropdownlists?
ANSWER:
@Orion has this partially correct - there is one other way to deal with these, and that is to cover the offending select lists with an iframe. This technique is used in Cody Lindley's ThickBox (written for jQuery). See the code for details on how to do it. | [
"asp.net",
"internet-explorer-6",
"autocompleteextender"
] | 0 | 0 | 2,516 | 2 | 0 | 2008-09-05T05:24:55.263000 | 2008-09-05T16:10:38.970000 |
45,286 | 45,316 | How can I overwrite the same portion of the console in a Windows native C++ console app, without using a 3rd Party library? | I have a console app that needs to display the state of items, but rather than having text scroll by like mad I'd rather see the current status keep showing up on the same lines. For the sake of example: Running... nn% complete Buffer size: bbbb bytes should be the output, where 'nn' is the current percentage complete, and 'bbbb' is a buffer size, updated periodically on the same lines of the console. The first approach I took simply printed the correct number of backspaces to the console before printing the new state, but this has an obnoxious flicker that I want to get rid of. I also want to stick to either standard library or MS-provided functionality (VC 8) so as not to introduce another dependency for this one simple need. | You can use SetConsoleCursorPosition. You'll need to call GetStdHandle to get a handle to the output buffer. | How can I overwrite the same portion of the console in a Windows native C++ console app, without using a 3rd Party library? I have a console app that needs to display the state of items, but rather than having text scroll by like mad I'd rather see the current status keep showing up on the same lines. For the sake of example: Running... nn% complete Buffer size: bbbb bytes should be the output, where 'nn' is the current percentage complete, and 'bbbb' is a buffer size, updated periodically on the same lines of the console. The first approach I took simply printed the correct number of backspaces to the console before printing the new state, but this has an obnoxious flicker that I want to get rid of. I also want to stick to either standard library or MS-provided functionality (VC 8) so as not to introduce another dependency for this one simple need. | TITLE:
How can I overwrite the same portion of the console in a Windows native C++ console app, without using a 3rd Party library?
QUESTION:
I have a console app that needs to display the state of items, but rather than having text scroll by like mad I'd rather see the current status keep showing up on the same lines. For the sake of example: Running... nn% complete Buffer size: bbbb bytes should be the output, where 'nn' is the current percentage complete, and 'bbbb' is a buffer size, updated periodically on the same lines of the console. The first approach I took simply printed the correct number of backspaces to the console before printing the new state, but this has an obnoxious flicker that I want to get rid of. I also want to stick to either standard library or MS-provided functionality (VC 8) so as not to introduce another dependency for this one simple need.
ANSWER:
You can use SetConsoleCursorPosition. You'll need to call GetStdHandle to get a handle to the output buffer. | [
"c++",
"windows",
"console"
] | 15 | 9 | 13,881 | 5 | 0 | 2008-09-05T05:42:57.217000 | 2008-09-05T06:12:27.007000 |
45,325 | 45,327 | How do you force Visual Studio to regenerate the .designer files for aspx/ascx files? | Sometimes when I'm editing page or control the.designer files stop being updated with the new controls I'm putting on the page. I'm not sure what's causing this to happen, but I'm wondering if there's any way of forcing Visual Studio to regenerate the.designer file. I'm using Visual Studio 2008 EDIT: Sorry I should have noted I've already tried: Closing & re-opening all the files & Visual Studio Making a change to a runat="server" control on the page Deleting & re-adding the page directive | If you open the.aspx file and switch between design view and html view and back it will prompt VS to check the controls and add any that are missing to the designer file. In VS2013-15 there is a Convert to Web Application command under the Project menu. Prior to VS2013 this option was available in the right-click context menu for as(c/p)x files. When this is done you should see that you now have a *.Designer.cs file available and your controls within the Design HTML will be available for your control. PS: This should not be done in debug mode, as not everything is "recompiled" when debugging. Some people have also reported success by (making a backup copy of your.designer.cs file and then) deleting the.designer.cs file. Re-create an empty file with the same name. There are many comments to this answer that add tips on how best to re-create the designer.cs file. | How do you force Visual Studio to regenerate the .designer files for aspx/ascx files? Sometimes when I'm editing page or control the.designer files stop being updated with the new controls I'm putting on the page. I'm not sure what's causing this to happen, but I'm wondering if there's any way of forcing Visual Studio to regenerate the.designer file. I'm using Visual Studio 2008 EDIT: Sorry I should have noted I've already tried: Closing & re-opening all the files & Visual Studio Making a change to a runat="server" control on the page Deleting & re-adding the page directive | TITLE:
How do you force Visual Studio to regenerate the .designer files for aspx/ascx files?
QUESTION:
Sometimes when I'm editing page or control the.designer files stop being updated with the new controls I'm putting on the page. I'm not sure what's causing this to happen, but I'm wondering if there's any way of forcing Visual Studio to regenerate the.designer file. I'm using Visual Studio 2008 EDIT: Sorry I should have noted I've already tried: Closing & re-opening all the files & Visual Studio Making a change to a runat="server" control on the page Deleting & re-adding the page directive
ANSWER:
If you open the.aspx file and switch between design view and html view and back it will prompt VS to check the controls and add any that are missing to the designer file. In VS2013-15 there is a Convert to Web Application command under the Project menu. Prior to VS2013 this option was available in the right-click context menu for as(c/p)x files. When this is done you should see that you now have a *.Designer.cs file available and your controls within the Design HTML will be available for your control. PS: This should not be done in debug mode, as not everything is "recompiled" when debugging. Some people have also reported success by (making a backup copy of your.designer.cs file and then) deleting the.designer.cs file. Re-create an empty file with the same name. There are many comments to this answer that add tips on how best to re-create the designer.cs file. | [
"asp.net",
"visual-studio",
"visual-studio-2008"
] | 432 | 388 | 351,759 | 50 | 0 | 2008-09-05T06:21:06.517000 | 2008-09-05T06:25:29.457000 |
45,331 | 63,710 | MS Visual Studio "Package Load Failure" error | I'm receiving "Package Load Failure" error when I open VS 2005 after I installed the latest VisualSVN (v. 1.5.2). Anyone facing this error? Is there any tool out there to help identify which package didn't load and/or help unload a specific package? | Installing the Visual Studio SDK will install the "Package Load Analyzer" package. This allows you to see what package failed to load and why. | MS Visual Studio "Package Load Failure" error I'm receiving "Package Load Failure" error when I open VS 2005 after I installed the latest VisualSVN (v. 1.5.2). Anyone facing this error? Is there any tool out there to help identify which package didn't load and/or help unload a specific package? | TITLE:
MS Visual Studio "Package Load Failure" error
QUESTION:
I'm receiving "Package Load Failure" error when I open VS 2005 after I installed the latest VisualSVN (v. 1.5.2). Anyone facing this error? Is there any tool out there to help identify which package didn't load and/or help unload a specific package?
ANSWER:
Installing the Visual Studio SDK will install the "Package Load Analyzer" package. This allows you to see what package failed to load and why. | [
"visual-studio-2005",
"visualsvn"
] | 0 | 1 | 2,163 | 2 | 0 | 2008-09-05T06:28:41.397000 | 2008-09-15T15:04:04.660000 |
45,339 | 45,371 | Why is my web control null? | I have a web site in asp.net that uses a master page. In this master page I have a multiview control with one view that has all the content for the content pages and one view that has some local content to the master page where I show error messages from all content pages. In this error view I have a asp.net Label control that displays the error messages. Usually the label works fine, but in some few cases the label is null, which renders a NullReferenceException. Now I have handled this case by checking if the label is null before using it, but still my question is: Why is this label null? What are the circumstances that can generate this? EDIT: In the master page I have a method called SetErrorText that takes a string and sets the label. I'm calling this method from the content pages' Page_Load method, and this generally works fine. In all but two cases (that I've discovered so far) the label is initialised, and nothing separates these two cases from all the ones that work. Also, all other controls in the master page are initialised, such as the View-control that houses the label. When the Page_Load of a content page rolls around, the master page should be populated. | It seems that the problem was one of sloppiness. Someone had forgotten to delete the auto-generated Content-controls that Visual Studio throws in on all content pages where the master page has a ContentPlaceHolder-control. If a content page has a Content-control, all controls that are placed in the ContentPlaceHolder-control on the master page will be null, it seems. | Why is my web control null? I have a web site in asp.net that uses a master page. In this master page I have a multiview control with one view that has all the content for the content pages and one view that has some local content to the master page where I show error messages from all content pages. In this error view I have a asp.net Label control that displays the error messages. Usually the label works fine, but in some few cases the label is null, which renders a NullReferenceException. Now I have handled this case by checking if the label is null before using it, but still my question is: Why is this label null? What are the circumstances that can generate this? EDIT: In the master page I have a method called SetErrorText that takes a string and sets the label. I'm calling this method from the content pages' Page_Load method, and this generally works fine. In all but two cases (that I've discovered so far) the label is initialised, and nothing separates these two cases from all the ones that work. Also, all other controls in the master page are initialised, such as the View-control that houses the label. When the Page_Load of a content page rolls around, the master page should be populated. | TITLE:
Why is my web control null?
QUESTION:
I have a web site in asp.net that uses a master page. In this master page I have a multiview control with one view that has all the content for the content pages and one view that has some local content to the master page where I show error messages from all content pages. In this error view I have a asp.net Label control that displays the error messages. Usually the label works fine, but in some few cases the label is null, which renders a NullReferenceException. Now I have handled this case by checking if the label is null before using it, but still my question is: Why is this label null? What are the circumstances that can generate this? EDIT: In the master page I have a method called SetErrorText that takes a string and sets the label. I'm calling this method from the content pages' Page_Load method, and this generally works fine. In all but two cases (that I've discovered so far) the label is initialised, and nothing separates these two cases from all the ones that work. Also, all other controls in the master page are initialised, such as the View-control that houses the label. When the Page_Load of a content page rolls around, the master page should be populated.
ANSWER:
It seems that the problem was one of sloppiness. Someone had forgotten to delete the auto-generated Content-controls that Visual Studio throws in on all content pages where the master page has a ContentPlaceHolder-control. If a content page has a Content-control, all controls that are placed in the ContentPlaceHolder-control on the master page will be null, it seems. | [
"asp.net",
"master-pages"
] | 3 | 4 | 6,255 | 4 | 0 | 2008-09-05T06:36:03.143000 | 2008-09-05T07:15:19.057000 |
45,361 | 46,330 | Tomcat doFilter() invoked with committed response | I have a Tomcat Filter that delegates requests to the a handling object depending on the URL. This is the only filter in the FilterChain. I have an Ajax app that hammers this filter with lots of requests. Recently I noticed an issue where the filter's doFilter method is often called with a committed response as a parameter (Internally, it is the coyote response that is marked committed). It seems to me that the only way that this can happen is if the recycle() method is not called on this coyote response. I have checked to make sure that I am not keeping references to any of the request, response, outputStream, or writer objects. Additionally, I made sure to close the outputStream in a finally block. However, this doesn't resolve this issue. This sounds like I am doing something to abuse the servlet container but I am having trouble tracking it down. | I have tried using Tomcat 6.16 and 6.18. This is definitely is the only filter in the chain. It seems that something is keeping a reference to the servlet outputStream. I wrapped the ServletOutputStream in my own OutputStream and then made sure the reference is destroyed. This fixed the issue so that I no longer see a committed response passed in. This is an odd side effect of holding a reference. But I don't think it qualifies as a Tomcat bug. More likely a bug in ImageIO.createImageOutputStream() that I suspect is holding the reference. | Tomcat doFilter() invoked with committed response I have a Tomcat Filter that delegates requests to the a handling object depending on the URL. This is the only filter in the FilterChain. I have an Ajax app that hammers this filter with lots of requests. Recently I noticed an issue where the filter's doFilter method is often called with a committed response as a parameter (Internally, it is the coyote response that is marked committed). It seems to me that the only way that this can happen is if the recycle() method is not called on this coyote response. I have checked to make sure that I am not keeping references to any of the request, response, outputStream, or writer objects. Additionally, I made sure to close the outputStream in a finally block. However, this doesn't resolve this issue. This sounds like I am doing something to abuse the servlet container but I am having trouble tracking it down. | TITLE:
Tomcat doFilter() invoked with committed response
QUESTION:
I have a Tomcat Filter that delegates requests to the a handling object depending on the URL. This is the only filter in the FilterChain. I have an Ajax app that hammers this filter with lots of requests. Recently I noticed an issue where the filter's doFilter method is often called with a committed response as a parameter (Internally, it is the coyote response that is marked committed). It seems to me that the only way that this can happen is if the recycle() method is not called on this coyote response. I have checked to make sure that I am not keeping references to any of the request, response, outputStream, or writer objects. Additionally, I made sure to close the outputStream in a finally block. However, this doesn't resolve this issue. This sounds like I am doing something to abuse the servlet container but I am having trouble tracking it down.
ANSWER:
I have tried using Tomcat 6.16 and 6.18. This is definitely is the only filter in the chain. It seems that something is keeping a reference to the servlet outputStream. I wrapped the ServletOutputStream in my own OutputStream and then made sure the reference is destroyed. This fixed the issue so that I no longer see a committed response passed in. This is an odd side effect of holding a reference. But I don't think it qualifies as a Tomcat bug. More likely a bug in ImageIO.createImageOutputStream() that I suspect is holding the reference. | [
"java",
"tomcat",
"servlets"
] | 8 | 4 | 1,765 | 2 | 0 | 2008-09-05T07:07:06.593000 | 2008-09-05T17:14:40.767000 |
45,372 | 61,050 | Calculated columns in mysql on INSERT statements | Let's say that I want to have a table that logs the date and the number of columns in some other table (or really any sort of math / string concat etc). CREATE TABLE `log` ( `id` INTEGER NOT NULL AUTO_INCREMENT, `date` DATETIME NOT NULL, `count` INTEGER NOT NULL, PRIMARY KEY (`id`) ); Is it possible to have the count column calculated for me whenever I do an insert? e.g. do something like: INSERT INTO log (date='foo'); and have count calculated by mysql. Obviously I could do it myself by doing a query to get the count and inserting it, but this would be better. | Triggers are the best tool for annotating data when a table is changed by insert, update or delete. To automatically set the date column of a new row in the log with the current date, you'd create a trigger that looked something like this: create trigger log_date before insert on log for each row begin set new.date = current_date() end; | Calculated columns in mysql on INSERT statements Let's say that I want to have a table that logs the date and the number of columns in some other table (or really any sort of math / string concat etc). CREATE TABLE `log` ( `id` INTEGER NOT NULL AUTO_INCREMENT, `date` DATETIME NOT NULL, `count` INTEGER NOT NULL, PRIMARY KEY (`id`) ); Is it possible to have the count column calculated for me whenever I do an insert? e.g. do something like: INSERT INTO log (date='foo'); and have count calculated by mysql. Obviously I could do it myself by doing a query to get the count and inserting it, but this would be better. | TITLE:
Calculated columns in mysql on INSERT statements
QUESTION:
Let's say that I want to have a table that logs the date and the number of columns in some other table (or really any sort of math / string concat etc). CREATE TABLE `log` ( `id` INTEGER NOT NULL AUTO_INCREMENT, `date` DATETIME NOT NULL, `count` INTEGER NOT NULL, PRIMARY KEY (`id`) ); Is it possible to have the count column calculated for me whenever I do an insert? e.g. do something like: INSERT INTO log (date='foo'); and have count calculated by mysql. Obviously I could do it myself by doing a query to get the count and inserting it, but this would be better.
ANSWER:
Triggers are the best tool for annotating data when a table is changed by insert, update or delete. To automatically set the date column of a new row in the log with the current date, you'd create a trigger that looked something like this: create trigger log_date before insert on log for each row begin set new.date = current_date() end; | [
"sql",
"mysql",
"database"
] | 3 | 6 | 4,134 | 3 | 0 | 2008-09-05T07:15:27.807000 | 2008-09-14T01:46:27.893000 |
45,385 | 45,392 | Good python library for generating audio files? | Can anyone recommend a good library for generating an audio file, such as mp3, wav, or even midi, from python? I've seen recommendations for working with the id tags (song name, artist, etc) in mp3 files, but this is not my goal. | See http://wiki.python.org/moin/Audio/ and http://wiki.python.org/moin/PythonInMusic, maybe some of the projects listed there can be of help. Also, Google is your friend. | Good python library for generating audio files? Can anyone recommend a good library for generating an audio file, such as mp3, wav, or even midi, from python? I've seen recommendations for working with the id tags (song name, artist, etc) in mp3 files, but this is not my goal. | TITLE:
Good python library for generating audio files?
QUESTION:
Can anyone recommend a good library for generating an audio file, such as mp3, wav, or even midi, from python? I've seen recommendations for working with the id tags (song name, artist, etc) in mp3 files, but this is not my goal.
ANSWER:
See http://wiki.python.org/moin/Audio/ and http://wiki.python.org/moin/PythonInMusic, maybe some of the projects listed there can be of help. Also, Google is your friend. | [
"python",
"audio",
"mp3"
] | 7 | 10 | 4,456 | 2 | 0 | 2008-09-05T07:33:43.783000 | 2008-09-05T07:44:45.413000 |
45,387 | 45,397 | Accessible controls for ASP.NET | In my last job we ended up rewriting the complete ASP.NET stack (forms, controls, validation, postback handling, ajax library etc...) - the reason I was given was that the ASP.NET controls were not accessible enough, not were any of the third party controls that were assessed for the project. Can anyone point me to good accessible ASP.NET controls that do ajax as well? Failing that, how would you approach creating accessible, ajax enabled controls? | You could take a look at the 'App_Browsers' feature in.NET. It gives you the opportunity to hook into the rendering engine for each control. The original intention for this was to be able to alter the HTML output of controls depending on the user's browser - but you can also do it for all browsers. You could also take a look at these control adapters, which make the normal ASP.NET controls 'CSS Friendly'. | Accessible controls for ASP.NET In my last job we ended up rewriting the complete ASP.NET stack (forms, controls, validation, postback handling, ajax library etc...) - the reason I was given was that the ASP.NET controls were not accessible enough, not were any of the third party controls that were assessed for the project. Can anyone point me to good accessible ASP.NET controls that do ajax as well? Failing that, how would you approach creating accessible, ajax enabled controls? | TITLE:
Accessible controls for ASP.NET
QUESTION:
In my last job we ended up rewriting the complete ASP.NET stack (forms, controls, validation, postback handling, ajax library etc...) - the reason I was given was that the ASP.NET controls were not accessible enough, not were any of the third party controls that were assessed for the project. Can anyone point me to good accessible ASP.NET controls that do ajax as well? Failing that, how would you approach creating accessible, ajax enabled controls?
ANSWER:
You could take a look at the 'App_Browsers' feature in.NET. It gives you the opportunity to hook into the rendering engine for each control. The original intention for this was to be able to alter the HTML output of controls depending on the user's browser - but you can also do it for all browsers. You could also take a look at these control adapters, which make the normal ASP.NET controls 'CSS Friendly'. | [
"asp.net",
"ajax",
"accessibility"
] | 0 | 1 | 273 | 1 | 0 | 2008-09-05T07:40:27.530000 | 2008-09-05T07:47:01.880000 |
45,399 | 45,479 | Advantages and disadvantages of GUID / UUID database keys | I've worked on a number of database systems in the past where moving entries between databases would have been made a lot easier if all the database keys had been GUID / UUID values. I've considered going down this path a few times, but there's always a bit of uncertainty, especially around performance and un-read-out-over-the-phone-able URLs. Has anyone worked extensively with GUIDs in a database? What advantages would I get by going that way, and what are the likely pitfalls? | Advantages: Can generate them offline. Makes replication trivial (as opposed to int's, which makes it REALLY hard) ORM's usually like them Unique across applications. So We can use the PK's from our CMS (guid) in our app (also guid) and know we are NEVER going to get a clash. Disadvantages: Larger space use, but space is cheap(er) Can't order by ID to get the insert order. Can look ugly in a URL, but really, WTF are you doing putting a REAL DB key in a URL!? (This point disputed in comments below) Harder to do manual debugging, but not that hard. Personally, I use them for most PK's in any system of a decent size, but I got "trained" on a system which was replicated all over the place, so we HAD to have them. YMMV. I think the duplicate data thing is rubbish - you can get duplicate data however you do it. Surrogate keys are usually frowned upon where ever I've been working. We DO use the WordPress-like system though: unique ID for the row (GUID/whatever). Never visible to the user. public ID is generated ONCE from some field (e.g. the title - make it the-title-of-the-article) UPDATE: So this one gets +1'ed a lot, and I thought I should point out a big downside of GUID PK's: Clustered Indexes. If you have a lot of records, and a clustered index on a GUID, your insert performance will SUCK, as you get inserts in random places in the list of items (that's the point), not at the end (which is quick). So if you need insert performance, maybe use a auto-inc INT, and generate a GUID if you want to share it with someone else (e.g., showing it to a user in a URL). | Advantages and disadvantages of GUID / UUID database keys I've worked on a number of database systems in the past where moving entries between databases would have been made a lot easier if all the database keys had been GUID / UUID values. I've considered going down this path a few times, but there's always a bit of uncertainty, especially around performance and un-read-out-over-the-phone-able URLs. Has anyone worked extensively with GUIDs in a database? What advantages would I get by going that way, and what are the likely pitfalls? | TITLE:
Advantages and disadvantages of GUID / UUID database keys
QUESTION:
I've worked on a number of database systems in the past where moving entries between databases would have been made a lot easier if all the database keys had been GUID / UUID values. I've considered going down this path a few times, but there's always a bit of uncertainty, especially around performance and un-read-out-over-the-phone-able URLs. Has anyone worked extensively with GUIDs in a database? What advantages would I get by going that way, and what are the likely pitfalls?
ANSWER:
Advantages: Can generate them offline. Makes replication trivial (as opposed to int's, which makes it REALLY hard) ORM's usually like them Unique across applications. So We can use the PK's from our CMS (guid) in our app (also guid) and know we are NEVER going to get a clash. Disadvantages: Larger space use, but space is cheap(er) Can't order by ID to get the insert order. Can look ugly in a URL, but really, WTF are you doing putting a REAL DB key in a URL!? (This point disputed in comments below) Harder to do manual debugging, but not that hard. Personally, I use them for most PK's in any system of a decent size, but I got "trained" on a system which was replicated all over the place, so we HAD to have them. YMMV. I think the duplicate data thing is rubbish - you can get duplicate data however you do it. Surrogate keys are usually frowned upon where ever I've been working. We DO use the WordPress-like system though: unique ID for the row (GUID/whatever). Never visible to the user. public ID is generated ONCE from some field (e.g. the title - make it the-title-of-the-article) UPDATE: So this one gets +1'ed a lot, and I thought I should point out a big downside of GUID PK's: Clustered Indexes. If you have a lot of records, and a clustered index on a GUID, your insert performance will SUCK, as you get inserts in random places in the list of items (that's the point), not at the end (which is quick). So if you need insert performance, maybe use a auto-inc INT, and generate a GUID if you want to share it with someone else (e.g., showing it to a user in a URL). | [
"database",
"guid",
"uuid"
] | 277 | 291 | 113,162 | 10 | 0 | 2008-09-05T08:00:50.380000 | 2008-09-05T09:44:55.717000 |
45,400 | 45,440 | Source control system for single developer | What's the recommended source control system for a very small team (one developer)? Price does not matter. Customer would pay:-) I'm working on Vista32 with VS 2008 in C++ and later in C# and with WPF. Setting up an extra (physical) server for this seems overkill to me. Any opinions? | I would use Subversion (in fact I use it) [ update: Jul 2014 -- I use Git -- see end of the answer]. SVN is: free, good enough (see disadvantages below), simple, works fine on Windows (and Linux too), a lot of people use it so it's easy to get help, can integrate with most of IDEs i.e. Visual Studio (i.e. ankhsvn or VisualSVN -- more info ) or Eclipse (i.e. Subclipse -- here someone asked about that). I would strongly recommended separate machine to source control server. At best somewhere on the cloud. Advantages: You don't lost your source control repositories if your development box dies. You don't have to worry about maintenance of one more box. There are companies which host SVN repositories. Here are links to SVN (client and server) packages for various operating systems. Disadvantages of SVN I am using SVN on Windows machine for about 5 years and found that SVN has a few disadvantages:). It is slow on large repositories SVN (or its client -- TortoiseSVN) has one big disadvantage -- it terrible slow (while updating or committing) on large (thousands of files) repositories unless you have SSD drive. Merging can be difficult Many people complain about how hard merging is with SVN. I do merging for about 4 years (including about 2 years in CVS -- that was terrible, but doable) and about 2 years with SVN. And personally I don't find it hard -- on the other hand -- any merge is easy after merging branches in CVS:). I do merge of large repository (two repositories in fact) once a week and rarely I have conflicts which are hard to solve (most of conflicts are solved automatically with diff software which I use). However in case of project of a few developers merging should not be problem at all if you keep a few simple rules: merge changes often, avoid active development in various branches simultaneously. Added in July 2011 Many devs recommended Distributed Version Control like Git or Mercurial. From single developer perspective there are only a few important advantages of DVCS over SVN: DVCS can be faster. You can commit to local repository without access to central one. DVCS is hot thing and fancy to use/learn (if someone pay for your learning). And I don't think merging is a problem in case of single developer. Joel Spolsky wrote tutorial about Mercurial which is definitively worth to read. So, despite of many advantages of DVCS I would stay with SVN if merging or speed is not a problem. Or try Mercurial, which according to this and this SO questions, is better supported (in July 2011) on Windows. Added in July 2014 For about a year I use Git (Git Bash mainly) for my pet-projects (i.e. solving Euler problems) and local branches for each Euler problem are really nice feature -- exactly as it is described as advantage of DVCS. Today Git tooling on Windows is much, much better then 2 or more years ago. You can use remote repo (like GitHub or ProjectLocker and many others) to keep copy of your project away from your workstation with no extra effort/money. However I use GUI client only to looks at diffs (and sometimes to choose files to commit), so it's better to not afraid of command line -- it's really nice. So as of today I would go with Git. | Source control system for single developer What's the recommended source control system for a very small team (one developer)? Price does not matter. Customer would pay:-) I'm working on Vista32 with VS 2008 in C++ and later in C# and with WPF. Setting up an extra (physical) server for this seems overkill to me. Any opinions? | TITLE:
Source control system for single developer
QUESTION:
What's the recommended source control system for a very small team (one developer)? Price does not matter. Customer would pay:-) I'm working on Vista32 with VS 2008 in C++ and later in C# and with WPF. Setting up an extra (physical) server for this seems overkill to me. Any opinions?
ANSWER:
I would use Subversion (in fact I use it) [ update: Jul 2014 -- I use Git -- see end of the answer]. SVN is: free, good enough (see disadvantages below), simple, works fine on Windows (and Linux too), a lot of people use it so it's easy to get help, can integrate with most of IDEs i.e. Visual Studio (i.e. ankhsvn or VisualSVN -- more info ) or Eclipse (i.e. Subclipse -- here someone asked about that). I would strongly recommended separate machine to source control server. At best somewhere on the cloud. Advantages: You don't lost your source control repositories if your development box dies. You don't have to worry about maintenance of one more box. There are companies which host SVN repositories. Here are links to SVN (client and server) packages for various operating systems. Disadvantages of SVN I am using SVN on Windows machine for about 5 years and found that SVN has a few disadvantages:). It is slow on large repositories SVN (or its client -- TortoiseSVN) has one big disadvantage -- it terrible slow (while updating or committing) on large (thousands of files) repositories unless you have SSD drive. Merging can be difficult Many people complain about how hard merging is with SVN. I do merging for about 4 years (including about 2 years in CVS -- that was terrible, but doable) and about 2 years with SVN. And personally I don't find it hard -- on the other hand -- any merge is easy after merging branches in CVS:). I do merge of large repository (two repositories in fact) once a week and rarely I have conflicts which are hard to solve (most of conflicts are solved automatically with diff software which I use). However in case of project of a few developers merging should not be problem at all if you keep a few simple rules: merge changes often, avoid active development in various branches simultaneously. Added in July 2011 Many devs recommended Distributed Version Control like Git or Mercurial. From single developer perspective there are only a few important advantages of DVCS over SVN: DVCS can be faster. You can commit to local repository without access to central one. DVCS is hot thing and fancy to use/learn (if someone pay for your learning). And I don't think merging is a problem in case of single developer. Joel Spolsky wrote tutorial about Mercurial which is definitively worth to read. So, despite of many advantages of DVCS I would stay with SVN if merging or speed is not a problem. Or try Mercurial, which according to this and this SO questions, is better supported (in July 2011) on Windows. Added in July 2014 For about a year I use Git (Git Bash mainly) for my pet-projects (i.e. solving Euler problems) and local branches for each Euler problem are really nice feature -- exactly as it is described as advantage of DVCS. Today Git tooling on Windows is much, much better then 2 or more years ago. You can use remote repo (like GitHub or ProjectLocker and many others) to keep copy of your project away from your workstation with no extra effort/money. However I use GUI client only to looks at diffs (and sometimes to choose files to commit), so it's better to not afraid of command line -- it's really nice. So as of today I would go with Git. | [
"version-control"
] | 57 | 63 | 22,498 | 26 | 0 | 2008-09-05T08:01:17.447000 | 2008-09-05T08:45:23.520000 |
45,401 | 45,421 | Lightweight 3D Graphics Engine .NET (Compact and Full Framework) | I am creating a GUI for a machine that runs remote (WinXP) or on the machine itself (Windows CE 6.0). Right now I've created a fast visualisation (read: very simple) of the machine itself. The goal is to make a bit more complex visualisation of the machine and for that I would need a lightweight 3d engine. The engine should run on both full and compact.net framework (I am prepared to do some porting:). What I mean with lightweigt is that it doesn't need shading, lighting, advanced camera's. The Idea is that the whole scene is shown in Isometric perspective. So what I was wondering is that anyone knows a good engine (open source?) or has some helpfull resources you could share with me. | Did you try Irrlicht. Recently Irrlicht has acquired official.NET bindings, allowing users to develop in.Net languages such as VB.NET, C# and Boo. There is also Ogre 3D and also Axiom Engine | Lightweight 3D Graphics Engine .NET (Compact and Full Framework) I am creating a GUI for a machine that runs remote (WinXP) or on the machine itself (Windows CE 6.0). Right now I've created a fast visualisation (read: very simple) of the machine itself. The goal is to make a bit more complex visualisation of the machine and for that I would need a lightweight 3d engine. The engine should run on both full and compact.net framework (I am prepared to do some porting:). What I mean with lightweigt is that it doesn't need shading, lighting, advanced camera's. The Idea is that the whole scene is shown in Isometric perspective. So what I was wondering is that anyone knows a good engine (open source?) or has some helpfull resources you could share with me. | TITLE:
Lightweight 3D Graphics Engine .NET (Compact and Full Framework)
QUESTION:
I am creating a GUI for a machine that runs remote (WinXP) or on the machine itself (Windows CE 6.0). Right now I've created a fast visualisation (read: very simple) of the machine itself. The goal is to make a bit more complex visualisation of the machine and for that I would need a lightweight 3d engine. The engine should run on both full and compact.net framework (I am prepared to do some porting:). What I mean with lightweigt is that it doesn't need shading, lighting, advanced camera's. The Idea is that the whole scene is shown in Isometric perspective. So what I was wondering is that anyone knows a good engine (open source?) or has some helpfull resources you could share with me.
ANSWER:
Did you try Irrlicht. Recently Irrlicht has acquired official.NET bindings, allowing users to develop in.Net languages such as VB.NET, C# and Boo. There is also Ogre 3D and also Axiom Engine | [
"c#",
"3d-engine"
] | 3 | 3 | 4,670 | 4 | 0 | 2008-09-05T08:02:39.160000 | 2008-09-05T08:16:41.560000 |
45,407 | 45,448 | Is there any difference between the box models of IE8 and Firefox3? | What are the main differences (if any) between the box models of IE8 and Firefox3? Are they the same now? What are the other main differences between these two browsers? Can a web developer assume that these two browsers as the same since they (seem to) support the latest web standards? | The Internet Explorer box model has been "fixed" since Internet Explorer 6 so long as your pages are in standard compliants mode. See: Quirks mode and Internet Explorer box model bug. Until I learnt about doctype declerations getting IE to work properly was a real PAIN, because IE runs in "quirks mode" by default. So having a standards mode doctype will eliminate a whole bunch of the most painful CSS problems. | Is there any difference between the box models of IE8 and Firefox3? What are the main differences (if any) between the box models of IE8 and Firefox3? Are they the same now? What are the other main differences between these two browsers? Can a web developer assume that these two browsers as the same since they (seem to) support the latest web standards? | TITLE:
Is there any difference between the box models of IE8 and Firefox3?
QUESTION:
What are the main differences (if any) between the box models of IE8 and Firefox3? Are they the same now? What are the other main differences between these two browsers? Can a web developer assume that these two browsers as the same since they (seem to) support the latest web standards?
ANSWER:
The Internet Explorer box model has been "fixed" since Internet Explorer 6 so long as your pages are in standard compliants mode. See: Quirks mode and Internet Explorer box model bug. Until I learnt about doctype declerations getting IE to work properly was a real PAIN, because IE runs in "quirks mode" by default. So having a standards mode doctype will eliminate a whole bunch of the most painful CSS problems. | [
"firefox",
"browser",
"internet-explorer-8"
] | 18 | 13 | 4,075 | 3 | 0 | 2008-09-05T08:06:32.740000 | 2008-09-05T09:07:55.993000 |
45,408 | 45,417 | JIT code generation techniques | How does a virtual machine generate native machine code on the fly and execute it? Assuming you can figure out what are the native machine op-codes you want to emit, how do you go about actually running it? Is it something as hacky as mapping the mnemonic instructions to binary codes, stuffing it into an char* pointer and casting it as a function and executing? Or would you generate a temporary shared library (.dll or.so or whatever) and load it into memory using standard functions like LoadLibrary? | You can just make the program counter point to the code you want to execute. Remember that data can be data or code. On x86 the program counter is the EIP register. The IP part of EIP stands for instruction pointer. The JMP instruction is called to jump to an address. After the jump EIP will contain this address. Is it something as hacky as mapping the mnemonic instructions to binary codes, stuffing it into an char* pointer and casting it as a function and executing? Yes. This is one way of doing it. The resulting code would be cast to a pointer to function in C. | JIT code generation techniques How does a virtual machine generate native machine code on the fly and execute it? Assuming you can figure out what are the native machine op-codes you want to emit, how do you go about actually running it? Is it something as hacky as mapping the mnemonic instructions to binary codes, stuffing it into an char* pointer and casting it as a function and executing? Or would you generate a temporary shared library (.dll or.so or whatever) and load it into memory using standard functions like LoadLibrary? | TITLE:
JIT code generation techniques
QUESTION:
How does a virtual machine generate native machine code on the fly and execute it? Assuming you can figure out what are the native machine op-codes you want to emit, how do you go about actually running it? Is it something as hacky as mapping the mnemonic instructions to binary codes, stuffing it into an char* pointer and casting it as a function and executing? Or would you generate a temporary shared library (.dll or.so or whatever) and load it into memory using standard functions like LoadLibrary?
ANSWER:
You can just make the program counter point to the code you want to execute. Remember that data can be data or code. On x86 the program counter is the EIP register. The IP part of EIP stands for instruction pointer. The JMP instruction is called to jump to an address. After the jump EIP will contain this address. Is it something as hacky as mapping the mnemonic instructions to binary codes, stuffing it into an char* pointer and casting it as a function and executing? Yes. This is one way of doing it. The resulting code would be cast to a pointer to function in C. | [
"interpreter",
"jit",
".net-assembly"
] | 19 | 8 | 1,680 | 7 | 0 | 2008-09-05T08:07:00.273000 | 2008-09-05T08:15:05.247000 |
45,414 | 45,550 | Why does the Eclipse code formatter break </a> in a Javadoc @see tag? | I'm using Eclipse 3.4 and have configured the Java code formatter with all of the options on the Comments tab enabled. The problem is that when I format a document comment that contains: * @see test the code formatter inserts a space in the closing HTML, breaking it: * @see test< /a> Why? How do I stop this happening? This is not fixed by disabling any of the options on the Comments tab, such as Format HTML tags. The only work-around I found is to disable Javadoc formatting completely by disabling both the Enable Javadoc comment formatting and Enable block comment formatting options, which means I then have to format comment blocks manually. | I can only assume it's a bug in Eclipse. It only happens with @see tags, it happens also for all 3 builtin code formatter settings. There are some interesting bugs reported already in the neighbourhood, but I couldn't find this specific one. See for example a search for @see in the Eclipse Bugzilla. | Why does the Eclipse code formatter break </a> in a Javadoc @see tag? I'm using Eclipse 3.4 and have configured the Java code formatter with all of the options on the Comments tab enabled. The problem is that when I format a document comment that contains: * @see test the code formatter inserts a space in the closing HTML, breaking it: * @see test< /a> Why? How do I stop this happening? This is not fixed by disabling any of the options on the Comments tab, such as Format HTML tags. The only work-around I found is to disable Javadoc formatting completely by disabling both the Enable Javadoc comment formatting and Enable block comment formatting options, which means I then have to format comment blocks manually. | TITLE:
Why does the Eclipse code formatter break </a> in a Javadoc @see tag?
QUESTION:
I'm using Eclipse 3.4 and have configured the Java code formatter with all of the options on the Comments tab enabled. The problem is that when I format a document comment that contains: * @see test the code formatter inserts a space in the closing HTML, breaking it: * @see test< /a> Why? How do I stop this happening? This is not fixed by disabling any of the options on the Comments tab, such as Format HTML tags. The only work-around I found is to disable Javadoc formatting completely by disabling both the Enable Javadoc comment formatting and Enable block comment formatting options, which means I then have to format comment blocks manually.
ANSWER:
I can only assume it's a bug in Eclipse. It only happens with @see tags, it happens also for all 3 builtin code formatter settings. There are some interesting bugs reported already in the neighbourhood, but I couldn't find this specific one. See for example a search for @see in the Eclipse Bugzilla. | [
"java",
"eclipse",
"javadoc",
"eclipse-3.4"
] | 4 | 4 | 1,698 | 3 | 0 | 2008-09-05T08:12:44.627000 | 2008-09-05T11:13:21.853000 |
45,415 | 159,437 | How to run NUnit v2.4.8 tests with NAnt 0.86 beta? | I tried recently to use NAnt (beta 0.86.2962.0) to run some unit tests compiled with the last stable version of NUnit (v2.4.8) without any success. The error I get is the following: [nunit2] Assembly "C:\Dev\MySample\bin\tests\My.Sample.Tests.dll" contains no tests. Of course, the assembly contains tests that I can run from any runner, like NUnit one, TestDriven or Resharper. I would like to use task, and not directly the one, but I'm wondering if it is still possible, even using app.config files to bind assembly versions. | I can't remember why, but I gave up on using the task and I've been using the task and nunit-console.exe happily. If it helps, here's my test target that runs NUnit and FxCop. Note that it skips them if the executables aren't in the Windows path. | How to run NUnit v2.4.8 tests with NAnt 0.86 beta? I tried recently to use NAnt (beta 0.86.2962.0) to run some unit tests compiled with the last stable version of NUnit (v2.4.8) without any success. The error I get is the following: [nunit2] Assembly "C:\Dev\MySample\bin\tests\My.Sample.Tests.dll" contains no tests. Of course, the assembly contains tests that I can run from any runner, like NUnit one, TestDriven or Resharper. I would like to use task, and not directly the one, but I'm wondering if it is still possible, even using app.config files to bind assembly versions. | TITLE:
How to run NUnit v2.4.8 tests with NAnt 0.86 beta?
QUESTION:
I tried recently to use NAnt (beta 0.86.2962.0) to run some unit tests compiled with the last stable version of NUnit (v2.4.8) without any success. The error I get is the following: [nunit2] Assembly "C:\Dev\MySample\bin\tests\My.Sample.Tests.dll" contains no tests. Of course, the assembly contains tests that I can run from any runner, like NUnit one, TestDriven or Resharper. I would like to use task, and not directly the one, but I'm wondering if it is still possible, even using app.config files to bind assembly versions.
ANSWER:
I can't remember why, but I gave up on using the task and I've been using the task and nunit-console.exe happily. If it helps, here's my test target that runs NUnit and FxCop. Note that it skips them if the executables aren't in the Windows path. | [
".net",
"unit-testing",
"nunit",
"nant"
] | 6 | 10 | 2,264 | 1 | 0 | 2008-09-05T08:14:39.567000 | 2008-10-01T19:58:47.590000 |
45,424 | 202,693 | Struts 2: return to calling page | I'm using Struts 2. I'd like to return from an Action to the page which invoked it. Say I'm in page x.jsp, I invoke Visual action to change CSS preferences in the session; I want to return to x.jsp rather than to a fixed page (i.e. home.jsp ) Here's the relevant struts.xml fragment: /pages/home.jsp Of course my VisualizationAction.execute() returns home. Is there any "magic" constant (like, say, INPUT_PAGE) that I may return to do the trick? Must I use a more involved method (i.e. extracting the request page and forwarding to it)? T.I.A. | You can use a dynamic result in struts.xml. For instance: ${next} Then in your action, you create a field called next. So to invoke the action you will pass the name of the page that you want to forward to next. The action then returns "next" and struts will know which page to go to. There is a nicer explanation on this post: Stack Overflow | Struts 2: return to calling page I'm using Struts 2. I'd like to return from an Action to the page which invoked it. Say I'm in page x.jsp, I invoke Visual action to change CSS preferences in the session; I want to return to x.jsp rather than to a fixed page (i.e. home.jsp ) Here's the relevant struts.xml fragment: /pages/home.jsp Of course my VisualizationAction.execute() returns home. Is there any "magic" constant (like, say, INPUT_PAGE) that I may return to do the trick? Must I use a more involved method (i.e. extracting the request page and forwarding to it)? T.I.A. | TITLE:
Struts 2: return to calling page
QUESTION:
I'm using Struts 2. I'd like to return from an Action to the page which invoked it. Say I'm in page x.jsp, I invoke Visual action to change CSS preferences in the session; I want to return to x.jsp rather than to a fixed page (i.e. home.jsp ) Here's the relevant struts.xml fragment: /pages/home.jsp Of course my VisualizationAction.execute() returns home. Is there any "magic" constant (like, say, INPUT_PAGE) that I may return to do the trick? Must I use a more involved method (i.e. extracting the request page and forwarding to it)? T.I.A.
ANSWER:
You can use a dynamic result in struts.xml. For instance: ${next} Then in your action, you create a field called next. So to invoke the action you will pass the name of the page that you want to forward to next. The action then returns "next" and struts will know which page to go to. There is a nicer explanation on this post: Stack Overflow | [
"java",
"struts2",
"struts"
] | 2 | 4 | 22,944 | 4 | 0 | 2008-09-05T08:18:52.443000 | 2008-10-14T20:36:06.363000 |
45,426 | 45,466 | SQL file encoding in Visual Studio | When we create stored procedures in Visual Studio (with the extension.sql) the file encoding is automatically set to 'Unicode (UTF-8 with signature) - Codepage 65001'. This causes ours DBA's problems as their scripts don't like it. We have to manually go in and change them to 'Western European (windows) - Codepage 1252'. This only seems to be happening since we upgraded to VS 2008 from 2005. Can anyone explain whats going on and how to stop it? | I think somebody faced a similar problem like yours and had the following workaround which is posted at http://connect.microsoft.com/VisualStudio/feedback/Workaround.aspx?FeedbackID=319830 | SQL file encoding in Visual Studio When we create stored procedures in Visual Studio (with the extension.sql) the file encoding is automatically set to 'Unicode (UTF-8 with signature) - Codepage 65001'. This causes ours DBA's problems as their scripts don't like it. We have to manually go in and change them to 'Western European (windows) - Codepage 1252'. This only seems to be happening since we upgraded to VS 2008 from 2005. Can anyone explain whats going on and how to stop it? | TITLE:
SQL file encoding in Visual Studio
QUESTION:
When we create stored procedures in Visual Studio (with the extension.sql) the file encoding is automatically set to 'Unicode (UTF-8 with signature) - Codepage 65001'. This causes ours DBA's problems as their scripts don't like it. We have to manually go in and change them to 'Western European (windows) - Codepage 1252'. This only seems to be happening since we upgraded to VS 2008 from 2005. Can anyone explain whats going on and how to stop it?
ANSWER:
I think somebody faced a similar problem like yours and had the following workaround which is posted at http://connect.microsoft.com/VisualStudio/feedback/Workaround.aspx?FeedbackID=319830 | [
"sql",
"visual-studio",
"stored-procedures"
] | 5 | 3 | 6,261 | 3 | 0 | 2008-09-05T08:20:13.890000 | 2008-09-05T09:28:35.897000 |
45,431 | 590,946 | NCover, TypeMock and MSTest | has anyone got NCover, TypeMock and MSTest to work together? and if so how. I've had 2 or 3 serious tries at this now and just can't get it to work. I'm using MSTest 9, NCover 2.1 and TypeMock 4.1. Ideally I would like to run them from an MSBuild task. Cheers Mat | Well its a bit late but here is the answer for future generations... Few key points: In older version of Typemock (like 4.1) you need an enterprise license in order to run Typemock with NCover. In the current version all licenses have the same features list. In order to run Typemock with other profilers you need to use the link feature of Typemock. In your case you can do it with Typemock MSBuild task. You need to run MSTest with the /noisolation argument. This will prevent MSTest to spawn VSTestHost.exe process that will actually run your tests. This creates a problem enabling the environment variables that are needed in order to let the profilers work In the example below I'm running the tests in Tests.dll and asking for coverage report about ClassLibrary.dll "E:\src\TypeMock\Build\Binaries\NCover\NCover 2.0\NCover.Console.exe" "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\MSTest.exe" | NCover, TypeMock and MSTest has anyone got NCover, TypeMock and MSTest to work together? and if so how. I've had 2 or 3 serious tries at this now and just can't get it to work. I'm using MSTest 9, NCover 2.1 and TypeMock 4.1. Ideally I would like to run them from an MSBuild task. Cheers Mat | TITLE:
NCover, TypeMock and MSTest
QUESTION:
has anyone got NCover, TypeMock and MSTest to work together? and if so how. I've had 2 or 3 serious tries at this now and just can't get it to work. I'm using MSTest 9, NCover 2.1 and TypeMock 4.1. Ideally I would like to run them from an MSBuild task. Cheers Mat
ANSWER:
Well its a bit late but here is the answer for future generations... Few key points: In older version of Typemock (like 4.1) you need an enterprise license in order to run Typemock with NCover. In the current version all licenses have the same features list. In order to run Typemock with other profilers you need to use the link feature of Typemock. In your case you can do it with Typemock MSBuild task. You need to run MSTest with the /noisolation argument. This will prevent MSTest to spawn VSTestHost.exe process that will actually run your tests. This creates a problem enabling the environment variables that are needed in order to let the profilers work In the example below I'm running the tests in Tests.dll and asking for coverage report about ClassLibrary.dll "E:\src\TypeMock\Build\Binaries\NCover\NCover 2.0\NCover.Console.exe" "C:\Program Files (x86)\Microsoft Visual Studio 9.0\Common7\IDE\MSTest.exe" | [
"ncover",
"typemock"
] | 0 | 2 | 1,257 | 1 | 0 | 2008-09-05T08:29:08.957000 | 2009-02-26T15:13:12.747000 |
45,453 | 45,969 | ICalendar and event updates not working in Outlook | I'm generating ICalendar (.ics) files. Using the UID and SEQUENCE fields I can update existing events in Google Calendar and in Windows Calendar BUT NOT in MS Outlook 2007 - it just creates a second event How do I get them to work for Outlook? Thanks Tom | I've continued to do some testing and have now managed to get Outlook to update and cancel events based on the.cs file. Outlook in fact seems to respond to the rules defined in RFC 2446 In summary you have to specify METHOD:REQUEST and ORGANIZER:xxxxxxxx in addition to UID: and SEQUENCE: For a cancellation you have to specify METHOD:CANCEL Request/Update Example BEGIN:VCALENDAR VERSION:2.0 PRODID:-//SYFADIS//PORTAIL FORMATION//FR METHOD:REQUEST BEGIN:VEVENT UID:TS_229377_MS_262145@syfadis.com SEQUENCE:5 DTSTAMP:20081106T154911Z ORGANIZER:catalog@syfadis.com DTSTART:20081113T164907 DTEND:20081115T170000 SUMMARY:TestTraining STATUS:CONFIRMED END:VEVENT END:VCALENDAR Cancel Example; BEGIN:VCALENDAR VERSION:2.0 PRODID:-//SYFADIS//PORTAIL FORMATION//FR METHOD:CANCEL BEGIN:VEVENT UID:TS_229377_MS_262145@syfadis.com SEQUENCE:7 DTSTAMP:20081106T154916Z ORGANIZER:catalog@syfadis.com DTSTART:20081113T164907 SUMMARY:TestTraining STATUS:CANCELLED END:VEVENT END:VCALENDAR | ICalendar and event updates not working in Outlook I'm generating ICalendar (.ics) files. Using the UID and SEQUENCE fields I can update existing events in Google Calendar and in Windows Calendar BUT NOT in MS Outlook 2007 - it just creates a second event How do I get them to work for Outlook? Thanks Tom | TITLE:
ICalendar and event updates not working in Outlook
QUESTION:
I'm generating ICalendar (.ics) files. Using the UID and SEQUENCE fields I can update existing events in Google Calendar and in Windows Calendar BUT NOT in MS Outlook 2007 - it just creates a second event How do I get them to work for Outlook? Thanks Tom
ANSWER:
I've continued to do some testing and have now managed to get Outlook to update and cancel events based on the.cs file. Outlook in fact seems to respond to the rules defined in RFC 2446 In summary you have to specify METHOD:REQUEST and ORGANIZER:xxxxxxxx in addition to UID: and SEQUENCE: For a cancellation you have to specify METHOD:CANCEL Request/Update Example BEGIN:VCALENDAR VERSION:2.0 PRODID:-//SYFADIS//PORTAIL FORMATION//FR METHOD:REQUEST BEGIN:VEVENT UID:TS_229377_MS_262145@syfadis.com SEQUENCE:5 DTSTAMP:20081106T154911Z ORGANIZER:catalog@syfadis.com DTSTART:20081113T164907 DTEND:20081115T170000 SUMMARY:TestTraining STATUS:CONFIRMED END:VEVENT END:VCALENDAR Cancel Example; BEGIN:VCALENDAR VERSION:2.0 PRODID:-//SYFADIS//PORTAIL FORMATION//FR METHOD:CANCEL BEGIN:VEVENT UID:TS_229377_MS_262145@syfadis.com SEQUENCE:7 DTSTAMP:20081106T154916Z ORGANIZER:catalog@syfadis.com DTSTART:20081113T164907 SUMMARY:TestTraining STATUS:CANCELLED END:VEVENT END:VCALENDAR | [
"language-agnostic",
"icalendar",
"rfc2445",
"rfc5545"
] | 27 | 26 | 29,750 | 5 | 0 | 2008-09-05T09:14:03.747000 | 2008-09-05T14:52:00.670000 |
45,470 | 45,474 | Suggest some good MVC framework in perl | Can you suggest some good MVC framework for perl -- one I am aware of is catalyst The need is to be able to expose services on the perl infrastructure which can be called by Java/.Net applications seamlessly. | I'll tell you right now that Catalyst has by far the best reputation amongst Perl developers in terms of a rapid application development MVC framework. In terms of "pure" MVC I'm not sure there are even that many "mature" or at least production-ready alternatives. If Catalyst doesn't seem right to you, then you could build upon the lightweight framework CGI::Application to suit your needs or take a look at some of the lesser known MVC frameworks like PageKit and Maypole. | Suggest some good MVC framework in perl Can you suggest some good MVC framework for perl -- one I am aware of is catalyst The need is to be able to expose services on the perl infrastructure which can be called by Java/.Net applications seamlessly. | TITLE:
Suggest some good MVC framework in perl
QUESTION:
Can you suggest some good MVC framework for perl -- one I am aware of is catalyst The need is to be able to expose services on the perl infrastructure which can be called by Java/.Net applications seamlessly.
ANSWER:
I'll tell you right now that Catalyst has by far the best reputation amongst Perl developers in terms of a rapid application development MVC framework. In terms of "pure" MVC I'm not sure there are even that many "mature" or at least production-ready alternatives. If Catalyst doesn't seem right to you, then you could build upon the lightweight framework CGI::Application to suit your needs or take a look at some of the lesser known MVC frameworks like PageKit and Maypole. | [
"perl",
"model-view-controller"
] | 16 | 21 | 9,281 | 12 | 0 | 2008-09-05T09:36:30.493000 | 2008-09-05T09:41:31.060000 |
45,481 | 45,493 | How to do streaming read of a large XML file in C# 3.5 | How can you do a streaming read on a large XML file that contains a xs:sequence just below root element, without loading the whole file into a XDocument instance in memory? | Going with a SAX-style element parser and the XmlTextReader class created with XmlReader.Create would be a good idea, yes. Here's a slightly-modified code example from CodeGuru: void ParseURL(string strUrl) { try { using (var reader = XmlReader.Create(strUrl)) { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: var attributes = new Hashtable(); var strURI = reader.NamespaceURI; var strName = reader.Name; if (reader.HasAttributes) { for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); attributes.Add(reader.Name,reader.Value); } } StartElement(strURI,strName,strName,attributes); break; // //you can handle other cases here // //case XmlNodeType.EndElement: // Todo //case XmlNodeType.Text: // Todo default: break; } } } catch (XmlException e) { Console.WriteLine("error occured: " + e.Message); } } } } | How to do streaming read of a large XML file in C# 3.5 How can you do a streaming read on a large XML file that contains a xs:sequence just below root element, without loading the whole file into a XDocument instance in memory? | TITLE:
How to do streaming read of a large XML file in C# 3.5
QUESTION:
How can you do a streaming read on a large XML file that contains a xs:sequence just below root element, without loading the whole file into a XDocument instance in memory?
ANSWER:
Going with a SAX-style element parser and the XmlTextReader class created with XmlReader.Create would be a good idea, yes. Here's a slightly-modified code example from CodeGuru: void ParseURL(string strUrl) { try { using (var reader = XmlReader.Create(strUrl)) { while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: var attributes = new Hashtable(); var strURI = reader.NamespaceURI; var strName = reader.Name; if (reader.HasAttributes) { for (int i = 0; i < reader.AttributeCount; i++) { reader.MoveToAttribute(i); attributes.Add(reader.Name,reader.Value); } } StartElement(strURI,strName,strName,attributes); break; // //you can handle other cases here // //case XmlNodeType.EndElement: // Todo //case XmlNodeType.Text: // Todo default: break; } } } catch (XmlException e) { Console.WriteLine("error occured: " + e.Message); } } } } | [
"c#",
".net",
"xml",
".net-3.5",
"streaming"
] | 11 | 9 | 9,972 | 6 | 0 | 2008-09-05T09:45:59.397000 | 2008-09-05T10:02:45.580000 |
45,485 | 45,542 | Are there conventions for function names when using the Perl Test::More? | Are there conventions for function names when using the Perl Test::More or Test::Simple modules? I'm specifically asking about the names of functions that are used to set up a test environment before the test and to tear down the environment after successful completion of the test(s). cheers, Rob | I dont think there are any such conventions out there. The only way you can do it is perhaps use BEGIN/END blocks, if the resources are to be used over the whole file. The general approach I take is to put related tests in one code block and then initialize the variables/resource etc there. You can perhaps keep an easy count of how many tests you have for each function. Something like... BEGIN { # If you want to set some global db setting/file setting/INC changes etc }
# Tests functionality 1... { # have fun.... }
# Tests functionality 2... { # have more fun.... }
END { # Clean up the BEGIN changes } On other note, you may want to read this for testing in perl... http://perlandmac.blogspot.com/2007/08/using-perl-testsimple-and-testmore.html | Are there conventions for function names when using the Perl Test::More? Are there conventions for function names when using the Perl Test::More or Test::Simple modules? I'm specifically asking about the names of functions that are used to set up a test environment before the test and to tear down the environment after successful completion of the test(s). cheers, Rob | TITLE:
Are there conventions for function names when using the Perl Test::More?
QUESTION:
Are there conventions for function names when using the Perl Test::More or Test::Simple modules? I'm specifically asking about the names of functions that are used to set up a test environment before the test and to tear down the environment after successful completion of the test(s). cheers, Rob
ANSWER:
I dont think there are any such conventions out there. The only way you can do it is perhaps use BEGIN/END blocks, if the resources are to be used over the whole file. The general approach I take is to put related tests in one code block and then initialize the variables/resource etc there. You can perhaps keep an easy count of how many tests you have for each function. Something like... BEGIN { # If you want to set some global db setting/file setting/INC changes etc }
# Tests functionality 1... { # have fun.... }
# Tests functionality 2... { # have more fun.... }
END { # Clean up the BEGIN changes } On other note, you may want to read this for testing in perl... http://perlandmac.blogspot.com/2007/08/using-perl-testsimple-and-testmore.html | [
"perl",
"testing",
"frameworks"
] | 3 | 3 | 1,177 | 8 | 0 | 2008-09-05T09:51:43.203000 | 2008-09-05T11:07:25.627000 |
45,494 | 45,498 | MySQL Error 1093 - Can't specify target table for update in FROM clause | I have a table story_category in my database with corrupt entries. The next query returns the corrupt entries: SELECT * FROM story_category WHERE category_id NOT IN ( SELECT DISTINCT category.id FROM category INNER JOIN story_category ON category_id=category.id); I tried to delete them executing: DELETE FROM story_category WHERE category_id NOT IN ( SELECT DISTINCT category.id FROM category INNER JOIN story_category ON category_id=category.id); But I get the next error: #1093 - You can't specify target table 'story_category' for update in FROM clause How can I overcome this? | Update: This answer covers the general error classification. For a more specific answer about how to best handle the OP's exact query, please see other answers to this question In MySQL, you can't modify the same table which you use in the SELECT part. This behaviour is documented at: http://dev.mysql.com/doc/refman/5.6/en/update.html Maybe you can just join the table to itself If the logic is simple enough to re-shape the query, lose the subquery and join the table to itself, employing appropriate selection criteria. This will cause MySQL to see the table as two different things, allowing destructive changes to go ahead. UPDATE tbl AS a INNER JOIN tbl AS b ON.... SET a.col = b.col Alternatively, try nesting the subquery deeper into a from clause... If you absolutely need the subquery, there's a workaround, but it's ugly for several reasons, including performance: UPDATE tbl SET col = ( SELECT... FROM (SELECT.... FROM) AS x); The nested subquery in the FROM clause creates an implicit temporary table, so it doesn't count as the same table you're updating.... but watch out for the query optimiser However, beware that from MySQL 5.7.6 and onward, the optimiser may optimise out the subquery, and still give you the error. Luckily, the optimizer_switch variable can be used to switch off this behaviour; although I couldn't recommend doing this as anything more than a short term fix, or for small one-off tasks. SET optimizer_switch = 'derived_merge=off'; Thanks to Peter V. Mørch for this advice in the comments. Example technique was from Baron Schwartz, originally published at Nabble, paraphrased and extended here. | MySQL Error 1093 - Can't specify target table for update in FROM clause I have a table story_category in my database with corrupt entries. The next query returns the corrupt entries: SELECT * FROM story_category WHERE category_id NOT IN ( SELECT DISTINCT category.id FROM category INNER JOIN story_category ON category_id=category.id); I tried to delete them executing: DELETE FROM story_category WHERE category_id NOT IN ( SELECT DISTINCT category.id FROM category INNER JOIN story_category ON category_id=category.id); But I get the next error: #1093 - You can't specify target table 'story_category' for update in FROM clause How can I overcome this? | TITLE:
MySQL Error 1093 - Can't specify target table for update in FROM clause
QUESTION:
I have a table story_category in my database with corrupt entries. The next query returns the corrupt entries: SELECT * FROM story_category WHERE category_id NOT IN ( SELECT DISTINCT category.id FROM category INNER JOIN story_category ON category_id=category.id); I tried to delete them executing: DELETE FROM story_category WHERE category_id NOT IN ( SELECT DISTINCT category.id FROM category INNER JOIN story_category ON category_id=category.id); But I get the next error: #1093 - You can't specify target table 'story_category' for update in FROM clause How can I overcome this?
ANSWER:
Update: This answer covers the general error classification. For a more specific answer about how to best handle the OP's exact query, please see other answers to this question In MySQL, you can't modify the same table which you use in the SELECT part. This behaviour is documented at: http://dev.mysql.com/doc/refman/5.6/en/update.html Maybe you can just join the table to itself If the logic is simple enough to re-shape the query, lose the subquery and join the table to itself, employing appropriate selection criteria. This will cause MySQL to see the table as two different things, allowing destructive changes to go ahead. UPDATE tbl AS a INNER JOIN tbl AS b ON.... SET a.col = b.col Alternatively, try nesting the subquery deeper into a from clause... If you absolutely need the subquery, there's a workaround, but it's ugly for several reasons, including performance: UPDATE tbl SET col = ( SELECT... FROM (SELECT.... FROM) AS x); The nested subquery in the FROM clause creates an implicit temporary table, so it doesn't count as the same table you're updating.... but watch out for the query optimiser However, beware that from MySQL 5.7.6 and onward, the optimiser may optimise out the subquery, and still give you the error. Luckily, the optimizer_switch variable can be used to switch off this behaviour; although I couldn't recommend doing this as anything more than a short term fix, or for small one-off tasks. SET optimizer_switch = 'derived_merge=off'; Thanks to Peter V. Mørch for this advice in the comments. Example technique was from Baron Schwartz, originally published at Nabble, paraphrased and extended here. | [
"mysql",
"subquery",
"sql-delete",
"mysql-error-1093"
] | 837 | 960 | 757,141 | 18 | 0 | 2008-09-05T10:03:46.590000 | 2008-09-05T10:07:48.143000 |
45,507 | 45,832 | Is there a Python library for generating .ico files? | I'm looking to create favicon.ico files programatically from Python, but PIL only has support for reading ico files. | According to Wikipedia modern browsers can handle favicons in PNG format, so maybe you could just generate that? Alternatively the ICO article describes the format... | Is there a Python library for generating .ico files? I'm looking to create favicon.ico files programatically from Python, but PIL only has support for reading ico files. | TITLE:
Is there a Python library for generating .ico files?
QUESTION:
I'm looking to create favicon.ico files programatically from Python, but PIL only has support for reading ico files.
ANSWER:
According to Wikipedia modern browsers can handle favicons in PNG format, so maybe you could just generate that? Alternatively the ICO article describes the format... | [
"python",
"favicon"
] | 36 | 7 | 33,631 | 7 | 0 | 2008-09-05T10:26:47.223000 | 2008-09-05T13:35:32.900000 |
45,510 | 45,537 | How can I call a .NET DLL from an Inno Setup script? | I want to call a function from a.NET DLL (coded in C#) from an Inno Setup script. I have: marked the Register for COM interop option in the project properties, changed the ComVisible setting in the AssemblyInfo.cs file, added these lines to the ISS script: [Files] Source: c:\temp\1\MyDLL.dll; Flags: dontcopy [Code] function MyFunction(): string; external 'MyFunction@files:MyDLL.dll stdcall setuponly'; But I still get the following error: Runtime Error (at -1:0): Cannot Import dll:C:\DOCUME~1\foo\LOCALS~1\Temp\is-LRL3E.tmp\MyDLL.dll. What am I doing wrong? | Oops, my bad, it's been too long since I've read pascal! So, if you need to get the value then there are a couple of possibilities: Write the functionality in C/C++ and export the function, that's definitely supported. Use a Managed C++ dll to shim to your.NET dll, and expose the call as a C interface point (this should work, but it's getting messy) Use an.exe to store the result of your code in a.INI file or the registry or in a temp file and read the result in the setup code section (this is now properly nasty) When I last worked with InnoSetup it didn't support your scenario directly (calling.NET code from setup). | How can I call a .NET DLL from an Inno Setup script? I want to call a function from a.NET DLL (coded in C#) from an Inno Setup script. I have: marked the Register for COM interop option in the project properties, changed the ComVisible setting in the AssemblyInfo.cs file, added these lines to the ISS script: [Files] Source: c:\temp\1\MyDLL.dll; Flags: dontcopy [Code] function MyFunction(): string; external 'MyFunction@files:MyDLL.dll stdcall setuponly'; But I still get the following error: Runtime Error (at -1:0): Cannot Import dll:C:\DOCUME~1\foo\LOCALS~1\Temp\is-LRL3E.tmp\MyDLL.dll. What am I doing wrong? | TITLE:
How can I call a .NET DLL from an Inno Setup script?
QUESTION:
I want to call a function from a.NET DLL (coded in C#) from an Inno Setup script. I have: marked the Register for COM interop option in the project properties, changed the ComVisible setting in the AssemblyInfo.cs file, added these lines to the ISS script: [Files] Source: c:\temp\1\MyDLL.dll; Flags: dontcopy [Code] function MyFunction(): string; external 'MyFunction@files:MyDLL.dll stdcall setuponly'; But I still get the following error: Runtime Error (at -1:0): Cannot Import dll:C:\DOCUME~1\foo\LOCALS~1\Temp\is-LRL3E.tmp\MyDLL.dll. What am I doing wrong?
ANSWER:
Oops, my bad, it's been too long since I've read pascal! So, if you need to get the value then there are a couple of possibilities: Write the functionality in C/C++ and export the function, that's definitely supported. Use a Managed C++ dll to shim to your.NET dll, and expose the call as a C interface point (this should work, but it's getting messy) Use an.exe to store the result of your code in a.INI file or the registry or in a temp file and read the result in the setup code section (this is now properly nasty) When I last worked with InnoSetup it didn't support your scenario directly (calling.NET code from setup). | [
".net",
"installation",
"inno-setup",
"pascalscript"
] | 12 | 5 | 9,983 | 7 | 0 | 2008-09-05T10:28:46.813000 | 2008-09-05T11:03:44.623000 |
45,528 | 45,587 | Simplest way to change listview and treeview colours | I'm trying to find a simple way to change the colour of the text and background in listview and treeview controls in WTL or plain Win32 code. I really don't want to have to implement full owner drawing for these controls, simply change the colours used. I want to make sure that the images are still drawn with proper transparency. Any suggestions? | Have a look at the following macros: ListView_SetBkColor ListView_SetTextColor TreeView_SetBkColor TreeView_SetTextColor | Simplest way to change listview and treeview colours I'm trying to find a simple way to change the colour of the text and background in listview and treeview controls in WTL or plain Win32 code. I really don't want to have to implement full owner drawing for these controls, simply change the colours used. I want to make sure that the images are still drawn with proper transparency. Any suggestions? | TITLE:
Simplest way to change listview and treeview colours
QUESTION:
I'm trying to find a simple way to change the colour of the text and background in listview and treeview controls in WTL or plain Win32 code. I really don't want to have to implement full owner drawing for these controls, simply change the colours used. I want to make sure that the images are still drawn with proper transparency. Any suggestions?
ANSWER:
Have a look at the following macros: ListView_SetBkColor ListView_SetTextColor TreeView_SetBkColor TreeView_SetTextColor | [
"c++",
"winapi",
"wtl"
] | 5 | 3 | 2,882 | 4 | 0 | 2008-09-05T10:54:12.460000 | 2008-09-05T11:38:06.083000 |
45,535 | 45,548 | Get month and year from a datetime in SQL Server 2005 | I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this? | If you mean you want them back as a string, in that format; SELECT CONVERT(CHAR(4), date_of_birth, 100) + CONVERT(CHAR(4), date_of_birth, 120) FROM customers Here are the other format options | Get month and year from a datetime in SQL Server 2005 I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this? | TITLE:
Get month and year from a datetime in SQL Server 2005
QUESTION:
I need the month+year from the datetime in SQL Server like 'Jan 2008'. I'm grouping the query by month, year. I've searched and found functions like datepart, convert, etc., but none of them seem useful for this. Am I missing something here? Is there a function for this?
ANSWER:
If you mean you want them back as a string, in that format; SELECT CONVERT(CHAR(4), date_of_birth, 100) + CONVERT(CHAR(4), date_of_birth, 120) FROM customers Here are the other format options | [
"sql",
"sql-server"
] | 97 | 81 | 846,972 | 20 | 0 | 2008-09-05T11:02:44.640000 | 2008-09-05T11:12:32.667000 |
45,546 | 45,585 | How do I return a 403 Forbidden in Spring MVC? | I want my controller to return the right HTTP response code when the user lacks permission to view a particular page. | Quickie If you are using plain JSP views (as is most common), then simply add <% response.setStatus( 403 ); %> somewhere in your view file. At the top is a nice place. Detail In MVC, i would always set this in the view, and in most cases with Spring-MVC, use the SimpleMappingExceptionResolver to present the correct view in response to a thrown runtime Exception. For example: create and throw a PermissionDeniedException in your controller or service layer and have the exception resolver point to a view file permissionDenied.jsp. This view file sets the 403 status and shows the user an appropriate message. In your Spring bean XML file: rescues/permissionDenied... set other exception/view mappings as s here... If you need to implement a user login mechanism, take a look at Spring Security (formerly Acegi Security). | How do I return a 403 Forbidden in Spring MVC? I want my controller to return the right HTTP response code when the user lacks permission to view a particular page. | TITLE:
How do I return a 403 Forbidden in Spring MVC?
QUESTION:
I want my controller to return the right HTTP response code when the user lacks permission to view a particular page.
ANSWER:
Quickie If you are using plain JSP views (as is most common), then simply add <% response.setStatus( 403 ); %> somewhere in your view file. At the top is a nice place. Detail In MVC, i would always set this in the view, and in most cases with Spring-MVC, use the SimpleMappingExceptionResolver to present the correct view in response to a thrown runtime Exception. For example: create and throw a PermissionDeniedException in your controller or service layer and have the exception resolver point to a view file permissionDenied.jsp. This view file sets the 403 status and shows the user an appropriate message. In your Spring bean XML file: rescues/permissionDenied... set other exception/view mappings as s here... If you need to implement a user login mechanism, take a look at Spring Security (formerly Acegi Security). | [
"java",
"spring",
"http-status-code-403",
"httpforbiddenhandler"
] | 40 | 13 | 90,768 | 6 | 0 | 2008-09-05T11:11:21.203000 | 2008-09-05T11:35:15.937000 |
45,553 | 45,641 | How to get browser IP or hostname? | I have a web application that should behave differently for internal users than external ones. The web application is available over the Internet, and therefore obviously to the internal users as well. All the users are anonymous, not authenticated, but the page should render differently for internal users than external. What I'm doing in my code is use Request.UserHostName and then Dns.GetHostEntry. The result is then compared to a setting in my web.config (that holds something like *.mydomain.local ). If the comparison gives a positive result then I render the HTML that the internal user should see otherwise I render the HTML the external user should see. However, my problem is that I don't always get the expected value from Request.UserHostName. on the development site I get the IP-number (?) of the machine running the browser but on the customer site I don't get the IP-number of the user machine, I get some other IP-number. The browsers don't have any proxies set or anything like that. Should I be using something else than Request.UserHostName? | I recommend using IP addresses as well. I'm dealing with this exact same situation setting up an authentication system right now as well and the conditions described by Epso and Robin M are exactly what is happening. External users coming to the site give me their actual IP address while all internal users provide the IP of the gateway machine(router) on to the private subnet the webservers sit on. To deal with it I just check for that one IP. If I get the IP of the gateway, I provide the internal access. If I get anything else they get the external one which requires additional authentication in my case. In yours, it would just mean a different interface. | How to get browser IP or hostname? I have a web application that should behave differently for internal users than external ones. The web application is available over the Internet, and therefore obviously to the internal users as well. All the users are anonymous, not authenticated, but the page should render differently for internal users than external. What I'm doing in my code is use Request.UserHostName and then Dns.GetHostEntry. The result is then compared to a setting in my web.config (that holds something like *.mydomain.local ). If the comparison gives a positive result then I render the HTML that the internal user should see otherwise I render the HTML the external user should see. However, my problem is that I don't always get the expected value from Request.UserHostName. on the development site I get the IP-number (?) of the machine running the browser but on the customer site I don't get the IP-number of the user machine, I get some other IP-number. The browsers don't have any proxies set or anything like that. Should I be using something else than Request.UserHostName? | TITLE:
How to get browser IP or hostname?
QUESTION:
I have a web application that should behave differently for internal users than external ones. The web application is available over the Internet, and therefore obviously to the internal users as well. All the users are anonymous, not authenticated, but the page should render differently for internal users than external. What I'm doing in my code is use Request.UserHostName and then Dns.GetHostEntry. The result is then compared to a setting in my web.config (that holds something like *.mydomain.local ). If the comparison gives a positive result then I render the HTML that the internal user should see otherwise I render the HTML the external user should see. However, my problem is that I don't always get the expected value from Request.UserHostName. on the development site I get the IP-number (?) of the machine running the browser but on the customer site I don't get the IP-number of the user machine, I get some other IP-number. The browsers don't have any proxies set or anything like that. Should I be using something else than Request.UserHostName?
ANSWER:
I recommend using IP addresses as well. I'm dealing with this exact same situation setting up an authentication system right now as well and the conditions described by Epso and Robin M are exactly what is happening. External users coming to the site give me their actual IP address while all internal users provide the IP of the gateway machine(router) on to the private subnet the webservers sit on. To deal with it I just check for that one IP. If I get the IP of the gateway, I provide the internal access. If I get anything else they get the external one which requires additional authentication in my case. In yours, it would just mean a different interface. | [
"asp.net",
"visual-studio"
] | 1 | 3 | 3,967 | 5 | 0 | 2008-09-05T11:15:25.763000 | 2008-09-05T12:24:35.033000 |
45,571 | 45,573 | fprintf returns success but can't write to an existing file | In my code fprintf returns successfully by returning the number of bytes written in STREAM, but in the actual file the string I wrote is not there. | The output is probably just buffered. Try closing the file using close() or call fflush() on the stream to force the string to the file. | fprintf returns success but can't write to an existing file In my code fprintf returns successfully by returning the number of bytes written in STREAM, but in the actual file the string I wrote is not there. | TITLE:
fprintf returns success but can't write to an existing file
QUESTION:
In my code fprintf returns successfully by returning the number of bytes written in STREAM, but in the actual file the string I wrote is not there.
ANSWER:
The output is probably just buffered. Try closing the file using close() or call fflush() on the stream to force the string to the file. | [
"c",
"file",
"io",
"stream",
"printf"
] | 3 | 5 | 1,081 | 1 | 0 | 2008-09-05T11:24:39.627000 | 2008-09-05T11:27:31.087000 |
45,577 | 942,103 | Syntax highlighting for html markup disappears in Visual Studio 2008 | This happened to me in Visual Studio 2008 pre and post 2008 sp1 on more than one computer and to someone else I know, so it can't be an isolated incident. Seemingly random, every so often I lose all syntax highlighting in my aspx page (the html) so that Visual Studio now looks like a really expensive version of notepad. Does anyone know why does happens? Better yet, anyone know how to fix it? | it happened to me after an uninstall of visual studio using a removal tool at http://msdn.microsoft.com/en-us/vstudio/bb968856.aspx I had to run this before upgrading sql server management studio to 2008 version syntax highlighting has disappeared since because of package loading failures. I didn't find the fix yet so if anybody has an idea... | Syntax highlighting for html markup disappears in Visual Studio 2008 This happened to me in Visual Studio 2008 pre and post 2008 sp1 on more than one computer and to someone else I know, so it can't be an isolated incident. Seemingly random, every so often I lose all syntax highlighting in my aspx page (the html) so that Visual Studio now looks like a really expensive version of notepad. Does anyone know why does happens? Better yet, anyone know how to fix it? | TITLE:
Syntax highlighting for html markup disappears in Visual Studio 2008
QUESTION:
This happened to me in Visual Studio 2008 pre and post 2008 sp1 on more than one computer and to someone else I know, so it can't be an isolated incident. Seemingly random, every so often I lose all syntax highlighting in my aspx page (the html) so that Visual Studio now looks like a really expensive version of notepad. Does anyone know why does happens? Better yet, anyone know how to fix it?
ANSWER:
it happened to me after an uninstall of visual studio using a removal tool at http://msdn.microsoft.com/en-us/vstudio/bb968856.aspx I had to run this before upgrading sql server management studio to 2008 version syntax highlighting has disappeared since because of package loading failures. I didn't find the fix yet so if anybody has an idea... | [
"asp.net",
"html",
"visual-studio",
"visual-studio-2008"
] | 2 | 3 | 2,593 | 7 | 0 | 2008-09-05T11:29:22.970000 | 2009-06-02T21:56:11.567000 |
45,582 | 1,380,478 | How can I convince GroovyShell to maintain state over eval() calls? | I'm trying to use Groovy to create an interactive scripting / macro mode for my application. The application is OSGi and much of the information the scripts may need is not know up front. I figured I could use GroovyShell and call eval() multiple times continually appending to the namespace as OSGi bundles are loaded. GroovyShell maintains variable state over multiple eval calls, but not class definitions or methods. goal: Create a base class during startup. As OSGi bundles load, create derived classes as needed. | Ended up injecting code before each script compilation. End goal is that the user written script has a domain-specific-language available for use. | How can I convince GroovyShell to maintain state over eval() calls? I'm trying to use Groovy to create an interactive scripting / macro mode for my application. The application is OSGi and much of the information the scripts may need is not know up front. I figured I could use GroovyShell and call eval() multiple times continually appending to the namespace as OSGi bundles are loaded. GroovyShell maintains variable state over multiple eval calls, but not class definitions or methods. goal: Create a base class during startup. As OSGi bundles load, create derived classes as needed. | TITLE:
How can I convince GroovyShell to maintain state over eval() calls?
QUESTION:
I'm trying to use Groovy to create an interactive scripting / macro mode for my application. The application is OSGi and much of the information the scripts may need is not know up front. I figured I could use GroovyShell and call eval() multiple times continually appending to the namespace as OSGi bundles are loaded. GroovyShell maintains variable state over multiple eval calls, but not class definitions or methods. goal: Create a base class during startup. As OSGi bundles load, create derived classes as needed.
ANSWER:
Ended up injecting code before each script compilation. End goal is that the user written script has a domain-specific-language available for use. | [
"java",
"groovy",
"scripting",
"groovyshell"
] | 3 | 1 | 1,829 | 3 | 0 | 2008-09-05T11:33:04.957000 | 2009-09-04T17:08:35.407000 |
45,593 | 45,692 | Is there a way to perform a "Refresh Dependencies" in a setup project outside VS2008? | I have a solution with several projects. One of them is a setup project. If you expand the setup project in the Solution Explorer, you see a Detected Dependencies node. If you right click on it, you get a menu item called Refresh Dependencies. This refreshes any dependencies based on the files included in the setup. I am asking if I can execute this action outside Visual Studio, using either devenv.com or MSBuild. I want this because I am using CruiseControl.NET for continuous integration and in some solutions I found that the setup output is missing some dependencies because of the way I automatically build the projects. Update: It turned out that my setup is not very friendly to how Setup projects work in Visual Studio. I ended up using Post Build Events in order to create the whole application structure ready to just be copied to a computer and work out of the box. I am not using setup projects in Visual Studio anymore, unless I really have to. | Record or create a macro: Option Strict Off Option Explicit Off Imports System Imports EnvDTE Imports EnvDTE80 Imports EnvDTE90 Imports System.Diagnostics
Public Module RefreshDependencies Sub TemporaryMacro() DTE.ActiveWindow.Object.GetItem("Project\Setup1\Setup1").Select(vsUISelectionType.vsUISelectionTypeSelect) DTE.ExecuteCommand("Build.RefreshDependencies") End Sub End Module Then just call the macro in the command line: devenv /command "Macros.MyMacros.RefreshDependencies C:\MyProjects\MyApp\" | Is there a way to perform a "Refresh Dependencies" in a setup project outside VS2008? I have a solution with several projects. One of them is a setup project. If you expand the setup project in the Solution Explorer, you see a Detected Dependencies node. If you right click on it, you get a menu item called Refresh Dependencies. This refreshes any dependencies based on the files included in the setup. I am asking if I can execute this action outside Visual Studio, using either devenv.com or MSBuild. I want this because I am using CruiseControl.NET for continuous integration and in some solutions I found that the setup output is missing some dependencies because of the way I automatically build the projects. Update: It turned out that my setup is not very friendly to how Setup projects work in Visual Studio. I ended up using Post Build Events in order to create the whole application structure ready to just be copied to a computer and work out of the box. I am not using setup projects in Visual Studio anymore, unless I really have to. | TITLE:
Is there a way to perform a "Refresh Dependencies" in a setup project outside VS2008?
QUESTION:
I have a solution with several projects. One of them is a setup project. If you expand the setup project in the Solution Explorer, you see a Detected Dependencies node. If you right click on it, you get a menu item called Refresh Dependencies. This refreshes any dependencies based on the files included in the setup. I am asking if I can execute this action outside Visual Studio, using either devenv.com or MSBuild. I want this because I am using CruiseControl.NET for continuous integration and in some solutions I found that the setup output is missing some dependencies because of the way I automatically build the projects. Update: It turned out that my setup is not very friendly to how Setup projects work in Visual Studio. I ended up using Post Build Events in order to create the whole application structure ready to just be copied to a computer and work out of the box. I am not using setup projects in Visual Studio anymore, unless I really have to.
ANSWER:
Record or create a macro: Option Strict Off Option Explicit Off Imports System Imports EnvDTE Imports EnvDTE80 Imports EnvDTE90 Imports System.Diagnostics
Public Module RefreshDependencies Sub TemporaryMacro() DTE.ActiveWindow.Object.GetItem("Project\Setup1\Setup1").Select(vsUISelectionType.vsUISelectionTypeSelect) DTE.ExecuteCommand("Build.RefreshDependencies") End Sub End Module Then just call the macro in the command line: devenv /command "Macros.MyMacros.RefreshDependencies C:\MyProjects\MyApp\" | [
"c#",
"visual-studio-2008",
"msbuild",
"installation",
"cruisecontrol.net"
] | 7 | 2 | 5,748 | 1 | 0 | 2008-09-05T11:49:02.483000 | 2008-09-05T12:42:37.597000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.