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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
38,288 | 38,289 | How do I add a user in Ubuntu? | Specifically, what commands do I run from the terminal? | Without a home directory sudo useradd myuser With home directory sudo useradd -m myuser Then set the password sudo passwd myuser Then set the shell sudo usermod -s /bin/bash myuser | How do I add a user in Ubuntu? Specifically, what commands do I run from the terminal? | TITLE:
How do I add a user in Ubuntu?
QUESTION:
Specifically, what commands do I run from the terminal?
ANSWER:
Without a home directory sudo useradd myuser With home directory sudo useradd -m myuser Then set the password sudo passwd myuser Then set the shell sudo usermod -s /bin/bash myuser | [
"linux",
"ubuntu",
"system-administration",
"user-management"
] | 68 | 141 | 79,029 | 3 | 0 | 2008-09-01T18:59:14.590000 | 2008-09-01T18:59:20.970000 |
38,295 | 38,396 | Apply an ICC Color Profile to an image in C# (Dotnet) | How does one convert an image from one color profile to another (screen to printer, or scanner to screen). In Visual C++ you would use the function in ICM.h, is there a managed way to do this with GDI+? I need to use GDI+, not WPF. I'd prefer to have a managed solution, but if it is not available, I guess PInkvoke will have to suffice. | There are a number of solutions. For GDI+, check out this article at MSDN (HOW TO: Use GDI+ and Image Color Management to Adjust Image Colors). For WPF (.NET 3.0), see the System.Windows.Media namespace. There are a number of different classes, such as the BitmapEncoder, that have the concept of a ColorContext, which "Represents the International Color Consortium (ICC) or Image Color Management (ICM) color profile that is associated with a bitmap image." Both of these seem pretty complex, so there's always the option of buying somebody else's code. Atalasoft's DotImage Photo Pro has ICC profile setting capabilities built in. The code is expensive; a dev license is almost 2k. But based on their participation in the dotnet community, I'd give them a whirl. | Apply an ICC Color Profile to an image in C# (Dotnet) How does one convert an image from one color profile to another (screen to printer, or scanner to screen). In Visual C++ you would use the function in ICM.h, is there a managed way to do this with GDI+? I need to use GDI+, not WPF. I'd prefer to have a managed solution, but if it is not available, I guess PInkvoke will have to suffice. | TITLE:
Apply an ICC Color Profile to an image in C# (Dotnet)
QUESTION:
How does one convert an image from one color profile to another (screen to printer, or scanner to screen). In Visual C++ you would use the function in ICM.h, is there a managed way to do this with GDI+? I need to use GDI+, not WPF. I'd prefer to have a managed solution, but if it is not available, I guess PInkvoke will have to suffice.
ANSWER:
There are a number of solutions. For GDI+, check out this article at MSDN (HOW TO: Use GDI+ and Image Color Management to Adjust Image Colors). For WPF (.NET 3.0), see the System.Windows.Media namespace. There are a number of different classes, such as the BitmapEncoder, that have the concept of a ColorContext, which "Represents the International Color Consortium (ICC) or Image Color Management (ICM) color profile that is associated with a bitmap image." Both of these seem pretty complex, so there's always the option of buying somebody else's code. Atalasoft's DotImage Photo Pro has ICC profile setting capabilities built in. The code is expensive; a dev license is almost 2k. But based on their participation in the dotnet community, I'd give them a whirl. | [
"c#",
".net",
"gdi+",
"color-management"
] | 4 | 4 | 9,552 | 2 | 0 | 2008-09-01T19:02:13.883000 | 2008-09-01T20:37:04.840000 |
38,299 | 38,568 | Tutorial on understanding strings in Symbian | I have Carbide.c++ Developer from Nokia and I want to create applications for my S60 phone. I've looked at the samples that goes with the different SDK's for S60 but I haven't found any simple explanation on how strings, called descriptors, are used in Symbian. One of the problems are that I'm visually impaired and therefore it takes quite some time to read through large documents that has page up and page down with lots of unuseful info and I've given up. I'm willing to give it another try. Can anyone help me? | Here are a few sites on blogspot that may help. They have RSS feeds that will hopefully be easier to consume than paging through PDFs. http://descriptor-tips.blogspot.com/ http://descriptors.blogspot.com/ | Tutorial on understanding strings in Symbian I have Carbide.c++ Developer from Nokia and I want to create applications for my S60 phone. I've looked at the samples that goes with the different SDK's for S60 but I haven't found any simple explanation on how strings, called descriptors, are used in Symbian. One of the problems are that I'm visually impaired and therefore it takes quite some time to read through large documents that has page up and page down with lots of unuseful info and I've given up. I'm willing to give it another try. Can anyone help me? | TITLE:
Tutorial on understanding strings in Symbian
QUESTION:
I have Carbide.c++ Developer from Nokia and I want to create applications for my S60 phone. I've looked at the samples that goes with the different SDK's for S60 but I haven't found any simple explanation on how strings, called descriptors, are used in Symbian. One of the problems are that I'm visually impaired and therefore it takes quite some time to read through large documents that has page up and page down with lots of unuseful info and I've given up. I'm willing to give it another try. Can anyone help me?
ANSWER:
Here are a few sites on blogspot that may help. They have RSS feeds that will hopefully be easier to consume than paging through PDFs. http://descriptor-tips.blogspot.com/ http://descriptors.blogspot.com/ | [
"c++",
"symbian",
"carbide"
] | 7 | 7 | 2,695 | 4 | 0 | 2008-09-01T19:04:06.170000 | 2008-09-01T22:49:31.683000 |
38,302 | 38,311 | Pinning pointer arrays in memory | I'm currently working on a ray-tracer in C# as a hobby project. I'm trying to achieve a decent rendering speed by implementing some tricks from a c++ implementation and have run into a spot of trouble. The objects in the scenes which the ray-tracer renders are stored in a KdTree structure and the tree's nodes are, in turn, stored in an array. The optimization I'm having problems with is while trying to fit as many tree nodes as possible into a cache line. One means of doing this is for nodes to contain a pointer to the left child node only. It is then implicit that the right child follows directly after the left one in the array. The nodes are structs and during tree construction they are succesfully put into the array by a static memory manager class. When I begin to traverse the tree it, at first, seems to work just fine. Then at a point early in the rendering (about the same place each time), the left child pointer of the root node is suddenly pointing at a null pointer. I have come to the conclusion that the garbage collecter has moved the structs as the array lies on the heap. I've tried several things to pin the addresses in memory but none of them seems to last for the entire application lifetime as I need. The 'fixed' keyword only seems to help during single method calls and declaring 'fixed' arrays can only be done on simple types which a node isn't. Is there a good way to do this or am I just too far down the path of stuff C# wasn't meant for. Btw, changing to c++, while perhaps the better choice for a high performance program, is not an option. | Firstly, if you're using C# normally, you can't suddenly get a null reference due to the garbage collector moving stuff, because the garbage collector also updates all references, so you don't need to worry about it moving stuff around. You can pin things in memory but this may cause more problems than it solves. For one thing, it prevents the garbage collector from compacting memory properly, and may impact performance in that way. One thing I would say from your post is that using structs may not help performance as you hope. C# fails to inline any method calls involving structs, and even though they've fixed this in their latest runtime beta, structs frequently don't perform that well. Personally, I would say C++ tricks like this don't generally tend to carry over too well into C#. You may have to learn to let go a bit; there can be other more subtle ways to improve performance;) | Pinning pointer arrays in memory I'm currently working on a ray-tracer in C# as a hobby project. I'm trying to achieve a decent rendering speed by implementing some tricks from a c++ implementation and have run into a spot of trouble. The objects in the scenes which the ray-tracer renders are stored in a KdTree structure and the tree's nodes are, in turn, stored in an array. The optimization I'm having problems with is while trying to fit as many tree nodes as possible into a cache line. One means of doing this is for nodes to contain a pointer to the left child node only. It is then implicit that the right child follows directly after the left one in the array. The nodes are structs and during tree construction they are succesfully put into the array by a static memory manager class. When I begin to traverse the tree it, at first, seems to work just fine. Then at a point early in the rendering (about the same place each time), the left child pointer of the root node is suddenly pointing at a null pointer. I have come to the conclusion that the garbage collecter has moved the structs as the array lies on the heap. I've tried several things to pin the addresses in memory but none of them seems to last for the entire application lifetime as I need. The 'fixed' keyword only seems to help during single method calls and declaring 'fixed' arrays can only be done on simple types which a node isn't. Is there a good way to do this or am I just too far down the path of stuff C# wasn't meant for. Btw, changing to c++, while perhaps the better choice for a high performance program, is not an option. | TITLE:
Pinning pointer arrays in memory
QUESTION:
I'm currently working on a ray-tracer in C# as a hobby project. I'm trying to achieve a decent rendering speed by implementing some tricks from a c++ implementation and have run into a spot of trouble. The objects in the scenes which the ray-tracer renders are stored in a KdTree structure and the tree's nodes are, in turn, stored in an array. The optimization I'm having problems with is while trying to fit as many tree nodes as possible into a cache line. One means of doing this is for nodes to contain a pointer to the left child node only. It is then implicit that the right child follows directly after the left one in the array. The nodes are structs and during tree construction they are succesfully put into the array by a static memory manager class. When I begin to traverse the tree it, at first, seems to work just fine. Then at a point early in the rendering (about the same place each time), the left child pointer of the root node is suddenly pointing at a null pointer. I have come to the conclusion that the garbage collecter has moved the structs as the array lies on the heap. I've tried several things to pin the addresses in memory but none of them seems to last for the entire application lifetime as I need. The 'fixed' keyword only seems to help during single method calls and declaring 'fixed' arrays can only be done on simple types which a node isn't. Is there a good way to do this or am I just too far down the path of stuff C# wasn't meant for. Btw, changing to c++, while perhaps the better choice for a high performance program, is not an option.
ANSWER:
Firstly, if you're using C# normally, you can't suddenly get a null reference due to the garbage collector moving stuff, because the garbage collector also updates all references, so you don't need to worry about it moving stuff around. You can pin things in memory but this may cause more problems than it solves. For one thing, it prevents the garbage collector from compacting memory properly, and may impact performance in that way. One thing I would say from your post is that using structs may not help performance as you hope. C# fails to inline any method calls involving structs, and even though they've fixed this in their latest runtime beta, structs frequently don't perform that well. Personally, I would say C++ tricks like this don't generally tend to carry over too well into C#. You may have to learn to let go a bit; there can be other more subtle ways to improve performance;) | [
"c#",
"optimization",
"unsafe",
"raytracing"
] | 1 | 4 | 2,878 | 5 | 0 | 2008-09-01T19:06:01.003000 | 2008-09-01T19:14:11.233000 |
38,305 | 38,591 | How do I strip the fluff out of a third party library? | It may not be best practice but are there ways of removing unsused classes from a third party's jar files. Something that looks at the way in which my classes are using the library and does some kind of coverage analysis, then spits out another jar with all of the untouched classes removed. Obviously there are issues with this. Specifically, the usage scenario I put it though may not use all classes all the time. But neglecting these problems, can it be done in principle? | There is a way. The JarJar project does this AFAIR. The first goal of the JarJar project is to allow one to embed third party libraries in your own jar, changing the package structure if necessary. Doing so it can strip out the classes that are not needed. Check it out at http://code.google.com/p/jarjar/. Here is a link about shrinking jars: http://sixlegs.com/blog/java/jarjar-keep.html | How do I strip the fluff out of a third party library? It may not be best practice but are there ways of removing unsused classes from a third party's jar files. Something that looks at the way in which my classes are using the library and does some kind of coverage analysis, then spits out another jar with all of the untouched classes removed. Obviously there are issues with this. Specifically, the usage scenario I put it though may not use all classes all the time. But neglecting these problems, can it be done in principle? | TITLE:
How do I strip the fluff out of a third party library?
QUESTION:
It may not be best practice but are there ways of removing unsused classes from a third party's jar files. Something that looks at the way in which my classes are using the library and does some kind of coverage analysis, then spits out another jar with all of the untouched classes removed. Obviously there are issues with this. Specifically, the usage scenario I put it though may not use all classes all the time. But neglecting these problems, can it be done in principle?
ANSWER:
There is a way. The JarJar project does this AFAIR. The first goal of the JarJar project is to allow one to embed third party libraries in your own jar, changing the package structure if necessary. Doing so it can strip out the classes that are not needed. Check it out at http://code.google.com/p/jarjar/. Here is a link about shrinking jars: http://sixlegs.com/blog/java/jarjar-keep.html | [
"java",
"optimization",
"size"
] | 4 | 8 | 2,191 | 7 | 0 | 2008-09-01T19:09:19.917000 | 2008-09-01T23:14:40.343000 |
38,323 | 38,332 | VMware or Hyper-V for Developers | I'm looking to replace a couple of machines in the office with a more powerful multi-processor machine running either VMware or Microsoft's Hyper-V with a view to hosting a mix of Windows Server 2003, Windows Server 2008 and Linux operating systems. The machines are used mainly for testing ASP.Net or Perl web sites. I don't need advanced features like live migration of running systems but it would be useful to be able to restore a machine to a known state. Performance is not really a big issue either unless one is noticeable faster than the other. My question is: Should I play safe and go with VMware or is Hyper-V mature enough to be a candidate? | VMware did recently release a free version of ESXi recently. VMware has a few advantages: 1. VMware virtual machines are portable across different types of hardware. IIRC, Hyper-V uses the drivers from the Host OS. 2. VMware virtual machines are portable across different VMware products (although you may need to use their converter tool to go from some hosted virtual machines to ESX or ESXi). 3. The VMware platforms have been in use much longer, and are quite mature products and generally better-known for troubleshooting. With VMware, you could develop and test a virtual machine on your local system using VMware Workstation, Fusion, Server, or Player, and then deploy it to a production server later. With Hyper-V, I believe you would have to build the virtual machine on the target box for best results. If performance isn't really that big of an issue, then VMware Server may be the best option, for it can run most.vmx machines directly and is generally a bit easier to manage; if performance becomes critical, you still have the ESX or ESXi upgrade option that you can use those same virtual machines with. This entry talks about how Virtual Server machines will not run on Hyper-V: http://blogs.technet.com/jhoward/archive/2008/02/28/are-vhds-compatible-between-hyper-v-and-virtual-server-and-virtual-pc.aspx | VMware or Hyper-V for Developers I'm looking to replace a couple of machines in the office with a more powerful multi-processor machine running either VMware or Microsoft's Hyper-V with a view to hosting a mix of Windows Server 2003, Windows Server 2008 and Linux operating systems. The machines are used mainly for testing ASP.Net or Perl web sites. I don't need advanced features like live migration of running systems but it would be useful to be able to restore a machine to a known state. Performance is not really a big issue either unless one is noticeable faster than the other. My question is: Should I play safe and go with VMware or is Hyper-V mature enough to be a candidate? | TITLE:
VMware or Hyper-V for Developers
QUESTION:
I'm looking to replace a couple of machines in the office with a more powerful multi-processor machine running either VMware or Microsoft's Hyper-V with a view to hosting a mix of Windows Server 2003, Windows Server 2008 and Linux operating systems. The machines are used mainly for testing ASP.Net or Perl web sites. I don't need advanced features like live migration of running systems but it would be useful to be able to restore a machine to a known state. Performance is not really a big issue either unless one is noticeable faster than the other. My question is: Should I play safe and go with VMware or is Hyper-V mature enough to be a candidate?
ANSWER:
VMware did recently release a free version of ESXi recently. VMware has a few advantages: 1. VMware virtual machines are portable across different types of hardware. IIRC, Hyper-V uses the drivers from the Host OS. 2. VMware virtual machines are portable across different VMware products (although you may need to use their converter tool to go from some hosted virtual machines to ESX or ESXi). 3. The VMware platforms have been in use much longer, and are quite mature products and generally better-known for troubleshooting. With VMware, you could develop and test a virtual machine on your local system using VMware Workstation, Fusion, Server, or Player, and then deploy it to a production server later. With Hyper-V, I believe you would have to build the virtual machine on the target box for best results. If performance isn't really that big of an issue, then VMware Server may be the best option, for it can run most.vmx machines directly and is generally a bit easier to manage; if performance becomes critical, you still have the ESX or ESXi upgrade option that you can use those same virtual machines with. This entry talks about how Virtual Server machines will not run on Hyper-V: http://blogs.technet.com/jhoward/archive/2008/02/28/are-vhds-compatible-between-hyper-v-and-virtual-server-and-virtual-pc.aspx | [
"vmware",
"virtualization",
"hyper-v"
] | 9 | 17 | 4,504 | 6 | 0 | 2008-09-01T19:26:42.217000 | 2008-09-01T19:41:48.467000 |
38,336 | 39,692 | On the web, what fonts should I use to create an equivalent experience cross-platform? | Because Linux (and its variants) have a completely different set of fonts than Windows and Mac OS X, is there anyone with any experience of creating cross-platform font families - ideally finding equivalents to the common fonts found on the aforementioned operating systems? If so, what is the best route to take? | Here are some good up-to-date listings of the most-installed fonts for PC, Mac, and Linux: Sans serif font sampler and survey results Serif font sampler and survey results Hope this helps your decision! | On the web, what fonts should I use to create an equivalent experience cross-platform? Because Linux (and its variants) have a completely different set of fonts than Windows and Mac OS X, is there anyone with any experience of creating cross-platform font families - ideally finding equivalents to the common fonts found on the aforementioned operating systems? If so, what is the best route to take? | TITLE:
On the web, what fonts should I use to create an equivalent experience cross-platform?
QUESTION:
Because Linux (and its variants) have a completely different set of fonts than Windows and Mac OS X, is there anyone with any experience of creating cross-platform font families - ideally finding equivalents to the common fonts found on the aforementioned operating systems? If so, what is the best route to take?
ANSWER:
Here are some good up-to-date listings of the most-installed fonts for PC, Mac, and Linux: Sans serif font sampler and survey results Serif font sampler and survey results Hope this helps your decision! | [
"css",
"linux",
"fonts",
"cross-platform"
] | 28 | 15 | 1,775 | 9 | 0 | 2008-09-01T19:48:10.013000 | 2008-09-02T14:41:31.410000 |
38,345 | 71,895 | Is there an elegant zip to interleave two lists in Perl 5? | I recently "needed" a zip function in Perl 5 (while I was thinking about How do I calculate relative time? ), i.e. a function that takes two lists and "zips" them together to one list, interleaving the elements. (Pseudo)example: @a=(1, 2, 3); @b=('apple', 'orange', 'grape'); zip @a, @b; # (1, 'apple', 2, 'orange', 3, 'grape'); Haskell has zip in the Prelude and Perl 6 has a zip operator built in, but how do you do it in an elegant way in Perl 5? | Assuming you have exactly two lists and they are exactly the same length, here is a solution originally by merlyn (Randal Schwartz), who called it perversely perlish: sub zip2 { my $p = @_ / 2; return @_[ map { $_, $_ + $p } 0.. $p - 1 ]; } What happens here is that for a 10-element list, first, we find the pivot point in the middle, in this case 5, and save it in $p. Then we make a list of indices up to that point, in this case 0 1 2 3 4. Next we use map to pair each index with another index that’s at the same distance from the pivot point as the first index is from the start, giving us (in this case) 0 5 1 6 2 7 3 8 4 9. Then we take a slice from @_ using that as the list of indices. This means that if 'a', 'b', 'c', 1, 2, 3 is passed to zip2, it will return that list rearranged into 'a', 1, 'b', 2, 'c', 3. This can be written in a single expression along ysth’s lines like so: sub zip2 { @_[map { $_, $_ + @_/2 } 0..(@_/2 - 1)] } Whether you’d want to use either variation depends on whether you can see yourself remembering how they work, but for me, it was a mind expander. | Is there an elegant zip to interleave two lists in Perl 5? I recently "needed" a zip function in Perl 5 (while I was thinking about How do I calculate relative time? ), i.e. a function that takes two lists and "zips" them together to one list, interleaving the elements. (Pseudo)example: @a=(1, 2, 3); @b=('apple', 'orange', 'grape'); zip @a, @b; # (1, 'apple', 2, 'orange', 3, 'grape'); Haskell has zip in the Prelude and Perl 6 has a zip operator built in, but how do you do it in an elegant way in Perl 5? | TITLE:
Is there an elegant zip to interleave two lists in Perl 5?
QUESTION:
I recently "needed" a zip function in Perl 5 (while I was thinking about How do I calculate relative time? ), i.e. a function that takes two lists and "zips" them together to one list, interleaving the elements. (Pseudo)example: @a=(1, 2, 3); @b=('apple', 'orange', 'grape'); zip @a, @b; # (1, 'apple', 2, 'orange', 3, 'grape'); Haskell has zip in the Prelude and Perl 6 has a zip operator built in, but how do you do it in an elegant way in Perl 5?
ANSWER:
Assuming you have exactly two lists and they are exactly the same length, here is a solution originally by merlyn (Randal Schwartz), who called it perversely perlish: sub zip2 { my $p = @_ / 2; return @_[ map { $_, $_ + $p } 0.. $p - 1 ]; } What happens here is that for a 10-element list, first, we find the pivot point in the middle, in this case 5, and save it in $p. Then we make a list of indices up to that point, in this case 0 1 2 3 4. Next we use map to pair each index with another index that’s at the same distance from the pivot point as the first index is from the start, giving us (in this case) 0 5 1 6 2 7 3 8 4 9. Then we take a slice from @_ using that as the list of indices. This means that if 'a', 'b', 'c', 1, 2, 3 is passed to zip2, it will return that list rearranged into 'a', 1, 'b', 2, 'c', 3. This can be written in a single expression along ysth’s lines like so: sub zip2 { @_[map { $_, $_ + @_/2 } 0..(@_/2 - 1)] } Whether you’d want to use either variation depends on whether you can see yourself remembering how they work, but for me, it was a mind expander. | [
"perl",
"zip"
] | 28 | 38 | 12,152 | 7 | 0 | 2008-09-01T19:59:37.287000 | 2008-09-16T12:56:05.490000 |
38,352 | 61,103 | Address book DB schema | I need to store contact information for users. I want to present this data on the page as an hCard and downloadable as a vCard. I'd also like to be able to search the database by phone number, email, etc. What do you think is the best way to store this data? Since users could have multiple addresses, etc complete normalization would be a mess. I'm thinking about using XML, but I'm not familiar with querying XML db fields. Would I still be able to search for users by contact info? I'm using SQL Server 2005, if that matters. | Consider two tables for People and their addresses: People (pid, prefix, firstName, lastName, suffix, DOB,... primaryAddressTag )
AddressBook (pid, tag, address1, address2, city, stateProv, postalCode,... ) The Primary Key (that uniquely identifies each and every row) of People is pid. The PK of AddressBook is the composition of pid and tag (pid, tag). Some example data: People 1, Kirk
2, Spock AddressBook 1, home, '123 Main Street', Iowa
1, work, 'USS Enterprise NCC-1701'
2, other, 'Mt. Selaya, Vulcan' In this example, Kirk has two addresses: one 'home' and one 'work'. One of those two can (and should) be noted as a foreign key (like a cross-reference) in People in the primaryAddressTag column. Spock has a single address with the tag 'other'. Since that is Spock's only address, the value 'other' ought to go in the primaryAddressTag column for pid=2. This schema has the nice effect of preventing the same person from duplicating any of their own addresses by accidentally reusing tags while at the same time allowing all other people use any address tags they like. Further, with FK references in primaryAddressTag, the database system itself will enforce the validity of the primary address tag (via something we database geeks call referential integrity) so that your -- or any -- application need not worry about it. | Address book DB schema I need to store contact information for users. I want to present this data on the page as an hCard and downloadable as a vCard. I'd also like to be able to search the database by phone number, email, etc. What do you think is the best way to store this data? Since users could have multiple addresses, etc complete normalization would be a mess. I'm thinking about using XML, but I'm not familiar with querying XML db fields. Would I still be able to search for users by contact info? I'm using SQL Server 2005, if that matters. | TITLE:
Address book DB schema
QUESTION:
I need to store contact information for users. I want to present this data on the page as an hCard and downloadable as a vCard. I'd also like to be able to search the database by phone number, email, etc. What do you think is the best way to store this data? Since users could have multiple addresses, etc complete normalization would be a mess. I'm thinking about using XML, but I'm not familiar with querying XML db fields. Would I still be able to search for users by contact info? I'm using SQL Server 2005, if that matters.
ANSWER:
Consider two tables for People and their addresses: People (pid, prefix, firstName, lastName, suffix, DOB,... primaryAddressTag )
AddressBook (pid, tag, address1, address2, city, stateProv, postalCode,... ) The Primary Key (that uniquely identifies each and every row) of People is pid. The PK of AddressBook is the composition of pid and tag (pid, tag). Some example data: People 1, Kirk
2, Spock AddressBook 1, home, '123 Main Street', Iowa
1, work, 'USS Enterprise NCC-1701'
2, other, 'Mt. Selaya, Vulcan' In this example, Kirk has two addresses: one 'home' and one 'work'. One of those two can (and should) be noted as a foreign key (like a cross-reference) in People in the primaryAddressTag column. Spock has a single address with the tag 'other'. Since that is Spock's only address, the value 'other' ought to go in the primaryAddressTag column for pid=2. This schema has the nice effect of preventing the same person from duplicating any of their own addresses by accidentally reusing tags while at the same time allowing all other people use any address tags they like. Further, with FK references in primaryAddressTag, the database system itself will enforce the validity of the primary address tag (via something we database geeks call referential integrity) so that your -- or any -- application need not worry about it. | [
"schema",
"microformats",
"vcf-vcard",
"normalizing",
"hcard"
] | 3 | 7 | 5,101 | 7 | 0 | 2008-09-01T20:02:15.127000 | 2008-09-14T03:34:11.817000 |
38,357 | 38,497 | Error Code Reference for OSX/Cocoa | If I get an error code result from a Cocoa function, is there any easy way to figure out what it means (other than by grepping through all the.h files in the framework bundles)? | You should look at the header for whatever framework the method you're using that's returning an error comes from. For example, an NSError in the Cocoa domain that you get from a method in the Foundation framework will have its code property described in the header. Similarly with AppKit and and Core Data and. Also, if you print the description of the NSError in the debugger, it should include not only the error domain and code, but also the name of the actual error code constant so you can look it up in the API reference. | Error Code Reference for OSX/Cocoa If I get an error code result from a Cocoa function, is there any easy way to figure out what it means (other than by grepping through all the.h files in the framework bundles)? | TITLE:
Error Code Reference for OSX/Cocoa
QUESTION:
If I get an error code result from a Cocoa function, is there any easy way to figure out what it means (other than by grepping through all the.h files in the framework bundles)?
ANSWER:
You should look at the header for whatever framework the method you're using that's returning an error comes from. For example, an NSError in the Cocoa domain that you get from a method in the Foundation framework will have its code property described in the header. Similarly with AppKit and and Core Data and. Also, if you print the description of the NSError in the debugger, it should include not only the error domain and code, but also the name of the actual error code constant so you can look it up in the API reference. | [
"cocoa",
"xcode",
"macos"
] | 17 | 23 | 7,816 | 4 | 0 | 2008-09-01T20:04:49.973000 | 2008-09-01T21:54:46.823000 |
38,362 | 38,381 | Best version control system for managing home directories | I have 3 Linux machines, and want some way to keep the dotfiles in their home directories in sync. Some files, like.vimrc, are the same across all 3 machines, and some are unique to each machine. I've used SVN before, but all the buzz about DVCSs makes me think I should try one - is there a particular one that would work best with this? Or should I stick with SVN? | I've had the same problem, and built a tool on top of Subversion that adds permission, ownership and secontext tracking, keeps the.svn directories out of the actually versioned trees, and adds a concept of layers so you can for example track all your config related to development, which you then only check out on machines you use for developing. This has helped me organize my settings much better across the 50+ machines I log into. Here's the project page. It's still a little rough around the edges, but we also use it at work to version system configuration for our 60+ servers. In general, any version control system that uses some sort of metadata files to track stuff is going to cause you pain as is when actually using it. | Best version control system for managing home directories I have 3 Linux machines, and want some way to keep the dotfiles in their home directories in sync. Some files, like.vimrc, are the same across all 3 machines, and some are unique to each machine. I've used SVN before, but all the buzz about DVCSs makes me think I should try one - is there a particular one that would work best with this? Or should I stick with SVN? | TITLE:
Best version control system for managing home directories
QUESTION:
I have 3 Linux machines, and want some way to keep the dotfiles in their home directories in sync. Some files, like.vimrc, are the same across all 3 machines, and some are unique to each machine. I've used SVN before, but all the buzz about DVCSs makes me think I should try one - is there a particular one that would work best with this? Or should I stick with SVN?
ANSWER:
I've had the same problem, and built a tool on top of Subversion that adds permission, ownership and secontext tracking, keeps the.svn directories out of the actually versioned trees, and adds a concept of layers so you can for example track all your config related to development, which you then only check out on machines you use for developing. This has helped me organize my settings much better across the 50+ machines I log into. Here's the project page. It's still a little rough around the edges, but we also use it at work to version system configuration for our 60+ servers. In general, any version control system that uses some sort of metadata files to track stuff is going to cause you pain as is when actually using it. | [
"linux",
"version-control"
] | 12 | 2 | 3,764 | 10 | 0 | 2008-09-01T20:12:08.427000 | 2008-09-01T20:25:04.870000 |
38,370 | 38,924 | PHP : session variable aren't usable when site is redirected | I've to admin a small website for my alumni group which is hosted by my ISV. The url is something like www.myIsv.com/myWebSite/ which is quite ugly and very forgetable. The main admin of the webserver has registered a domain name www.mysmallwebsite.com and put a index.html with this content: www.mysmallwebsite.com Original location: http://www.myIsv.com/myWebSite/ It works fine, but some features like PHP Session variables doesn't work anymore! Anyone has a suggestion for correcting that? Edit: This doesn't work both on IE and on Firefox (no plugins) Thanks | Sessions are tied to the server AND the domain. Using frameset across domain will cause all kind of breakage because that's just not how it was designed to do. Try using apache mod rewrite to create a "passthrough redirection", the " proxy " flag ([P]) in the rule is the magic flag that you need Documentation at http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html | PHP : session variable aren't usable when site is redirected I've to admin a small website for my alumni group which is hosted by my ISV. The url is something like www.myIsv.com/myWebSite/ which is quite ugly and very forgetable. The main admin of the webserver has registered a domain name www.mysmallwebsite.com and put a index.html with this content: www.mysmallwebsite.com Original location: http://www.myIsv.com/myWebSite/ It works fine, but some features like PHP Session variables doesn't work anymore! Anyone has a suggestion for correcting that? Edit: This doesn't work both on IE and on Firefox (no plugins) Thanks | TITLE:
PHP : session variable aren't usable when site is redirected
QUESTION:
I've to admin a small website for my alumni group which is hosted by my ISV. The url is something like www.myIsv.com/myWebSite/ which is quite ugly and very forgetable. The main admin of the webserver has registered a domain name www.mysmallwebsite.com and put a index.html with this content: www.mysmallwebsite.com Original location: http://www.myIsv.com/myWebSite/ It works fine, but some features like PHP Session variables doesn't work anymore! Anyone has a suggestion for correcting that? Edit: This doesn't work both on IE and on Firefox (no plugins) Thanks
ANSWER:
Sessions are tied to the server AND the domain. Using frameset across domain will cause all kind of breakage because that's just not how it was designed to do. Try using apache mod rewrite to create a "passthrough redirection", the " proxy " flag ([P]) in the rule is the magic flag that you need Documentation at http://httpd.apache.org/docs/1.3/mod/mod_rewrite.html | [
"php",
"session",
"session-variables"
] | 6 | 4 | 3,607 | 10 | 0 | 2008-09-01T20:17:28.443000 | 2008-09-02T06:18:34.380000 |
38,378 | 38,415 | Clone a control in silverlight | What's the best way to clone a control in Silverlight (including it's children)? UPDATE Is there a better way in Silverlight 2? | Here's a great thread about serializing and deserializing objects in Silverlight 1.1. As for a "best way," I'd say it would definitely be caching the xaml for the control and calling createFromXaml on it. | Clone a control in silverlight What's the best way to clone a control in Silverlight (including it's children)? UPDATE Is there a better way in Silverlight 2? | TITLE:
Clone a control in silverlight
QUESTION:
What's the best way to clone a control in Silverlight (including it's children)? UPDATE Is there a better way in Silverlight 2?
ANSWER:
Here's a great thread about serializing and deserializing objects in Silverlight 1.1. As for a "best way," I'd say it would definitely be caching the xaml for the control and calling createFromXaml on it. | [
"silverlight"
] | 1 | 1 | 2,582 | 1 | 0 | 2008-09-01T20:21:50.307000 | 2008-09-01T20:53:54.160000 |
38,408 | 38,529 | How can I make flash cs3, actionscript send events to javascript? | I'm using Flash to play an.flv movieclip on my site, but I want to have the.swf send trigger an event in my javascript when it start loading, starts playing and ends playing. What is the best way to do that in Flash CS3 using Actionscript 3.0? | You need to use the "allowScriptAccess" flash variable in the HTML. You probably want to use "sameDomain" as the type. Note that if you go cross-domain, you also need to host a special file on the server called 'crossdomain.xml' which enables such scripting (the flash player will check for this. More info at http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_14213&sliceId=2 The call is the easy part.:-) In the Flash code, you'll use the ExternalInterface to do the call, as documented here: http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001655.html Short version: you say ExternalInterface.call("javascriptFunction", "argument") | How can I make flash cs3, actionscript send events to javascript? I'm using Flash to play an.flv movieclip on my site, but I want to have the.swf send trigger an event in my javascript when it start loading, starts playing and ends playing. What is the best way to do that in Flash CS3 using Actionscript 3.0? | TITLE:
How can I make flash cs3, actionscript send events to javascript?
QUESTION:
I'm using Flash to play an.flv movieclip on my site, but I want to have the.swf send trigger an event in my javascript when it start loading, starts playing and ends playing. What is the best way to do that in Flash CS3 using Actionscript 3.0?
ANSWER:
You need to use the "allowScriptAccess" flash variable in the HTML. You probably want to use "sameDomain" as the type. Note that if you go cross-domain, you also need to host a special file on the server called 'crossdomain.xml' which enables such scripting (the flash player will check for this. More info at http://kb.adobe.com/selfservice/viewContent.do?externalId=tn_14213&sliceId=2 The call is the easy part.:-) In the Flash code, you'll use the ExternalInterface to do the call, as documented here: http://livedocs.adobe.com/flash/9.0/main/wwhelp/wwhimpl/common/html/wwhelp.htm?context=LiveDocs_Parts&file=00001655.html Short version: you say ExternalInterface.call("javascriptFunction", "argument") | [
"javascript",
"flash",
"actionscript"
] | 5 | 5 | 3,537 | 3 | 0 | 2008-09-01T20:44:37.723000 | 2008-09-01T22:11:32.540000 |
38,409 | 40,849 | How do I convert a Ruby string with brackets to an array? | I would like to convert the following string into an array/nested array: str = "[[this, is],[a, nested],[array]]"
newarray = # this is what I need help with!
newarray.inspect # => [['this','is'],['a','nested'],['array']] | You'll get what you want with YAML. But there is a little problem with your string. YAML expects that there's a space behind the comma. So we need this str = "[[this, is], [a, nested], [array]]" Code: require 'yaml' str = "[[this, is],[a, nested],[array]]" ### transform your string in a valid YAML-String str.gsub!(/(\,)(\S)/, "\\1 \\2") YAML::load(str) # => [["this", "is"], ["a", "nested"], ["array"]] | How do I convert a Ruby string with brackets to an array? I would like to convert the following string into an array/nested array: str = "[[this, is],[a, nested],[array]]"
newarray = # this is what I need help with!
newarray.inspect # => [['this','is'],['a','nested'],['array']] | TITLE:
How do I convert a Ruby string with brackets to an array?
QUESTION:
I would like to convert the following string into an array/nested array: str = "[[this, is],[a, nested],[array]]"
newarray = # this is what I need help with!
newarray.inspect # => [['this','is'],['a','nested'],['array']]
ANSWER:
You'll get what you want with YAML. But there is a little problem with your string. YAML expects that there's a space behind the comma. So we need this str = "[[this, is], [a, nested], [array]]" Code: require 'yaml' str = "[[this, is],[a, nested],[array]]" ### transform your string in a valid YAML-String str.gsub!(/(\,)(\S)/, "\\1 \\2") YAML::load(str) # => [["this", "is"], ["a", "nested"], ["array"]] | [
"ruby",
"arrays"
] | 9 | 11 | 10,531 | 5 | 0 | 2008-09-01T20:44:47.007000 | 2008-09-02T22:39:27.503000 |
38,421 | 38,446 | Security advice for jquery ajax data post? | I'm using jquery ajax to post updates back to my server. I'm concerned about making sure I have put in place appropriate measures so that only my AJAX calls can post data. My stack is PHP on Apache against a MySQL backend. Advice greatly appreciated! | Any request that the AJAX calls in your pages can make can also be made by someone outside of the application. If done right, you will not be able to tell if they were made as part of an AJAX call from your webapp or by hand/other means. There are two scenarios I can think of which you might be talking about when you say you want to make sure that only your AJAX calls can post data: either you don't want a malicious user to be able to post data that interferes with another user's data or you actually want to restrict the posts to being in the "flow" of a multi-request operation. If you are concerned with the first case (someone posting malicious data to/as another user) the solution is the same whether you are using AJAX or not -- you just have to authenticate the user through whatever means is necessary -- usually via session cookie. If you are concerned with the second case, then you are going to have to do something like issue a unique token at each step of the process, and store the expected token on the server side. Then when a request is made, check that there is a corresponding entry on the server side for the action that is being taken and that the expected tokens match and that that token has not been used yet. If there is no, you reject the request, if there is, then you mark that token as used and process the request. If what you are concerned about is something other than one of these two scenarios then the answer will depend on more specifics than you have provided. | Security advice for jquery ajax data post? I'm using jquery ajax to post updates back to my server. I'm concerned about making sure I have put in place appropriate measures so that only my AJAX calls can post data. My stack is PHP on Apache against a MySQL backend. Advice greatly appreciated! | TITLE:
Security advice for jquery ajax data post?
QUESTION:
I'm using jquery ajax to post updates back to my server. I'm concerned about making sure I have put in place appropriate measures so that only my AJAX calls can post data. My stack is PHP on Apache against a MySQL backend. Advice greatly appreciated!
ANSWER:
Any request that the AJAX calls in your pages can make can also be made by someone outside of the application. If done right, you will not be able to tell if they were made as part of an AJAX call from your webapp or by hand/other means. There are two scenarios I can think of which you might be talking about when you say you want to make sure that only your AJAX calls can post data: either you don't want a malicious user to be able to post data that interferes with another user's data or you actually want to restrict the posts to being in the "flow" of a multi-request operation. If you are concerned with the first case (someone posting malicious data to/as another user) the solution is the same whether you are using AJAX or not -- you just have to authenticate the user through whatever means is necessary -- usually via session cookie. If you are concerned with the second case, then you are going to have to do something like issue a unique token at each step of the process, and store the expected token on the server side. Then when a request is made, check that there is a corresponding entry on the server side for the action that is being taken and that the expected tokens match and that that token has not been used yet. If there is no, you reject the request, if there is, then you mark that token as used and process the request. If what you are concerned about is something other than one of these two scenarios then the answer will depend on more specifics than you have provided. | [
"jquery",
"ajax",
"security",
"post"
] | 21 | 28 | 13,995 | 2 | 0 | 2008-09-01T20:57:12.093000 | 2008-09-01T21:16:52.590000 |
38,428 | 38,440 | Positioning controls in the middle of a CheckBox | THis is a followup to my previous question " Font-dependent control positioning. " It's an attempt to solve the real problem behind that question, perhaps in ways different than the one I was asking about. Example of the problem statement: I want a checkbox that says "Adjust prices by after loading," where is a number---adjustable with a NumericUpDown ---and is either "percent" or "dollars," with the choices being made by a ComboBox. This will be on a single line. The complication: I want to be able to change my fonts for all these controls (basically setting them to System.Drawing.Fonts.MessageBoxFont, which is Tahoma 8 pt on Windows XP/etc. and Segoe UI 9 pt on Vista), without messing up my layout, which with my current Position -property--setting paradigm does not work. More generally, I'd like the controls to be dynamically laid out in a font-independent way, so that the NumericUpDown fits snugly into the space between "by " and the ComboBox, and similarly the ComboBox fits in with respect to the CheckBox and the string " after loading" to its right. The part everyone seems to miss: This is all nested within a CheckBox. So, ideally, clicking on the words "after loading" should check/uncheck the checkbox, and draw that little highlight rectangle around "Adjust prices by after loading." So just slapping an extra Label on the end doesn't work, because then it doesn't toggle the CheckBox; similarly, trying to band-aid things by hooking up such a Label 's Click event won't produce the desired highlight-rectangle. Solutions? At this point I'm thinking either: Rethink the problem, somehow, maybe with an ugly solution like two separate lines of text: "Adjust found prices after loading" ( CheckBox ), "Adjustment amount:" ( NumericUpDown and ComboBox ). This is really bad because my options box is absolutely full of options of this type (i.e. the type in the example), so it would at least double in vertical size. Some sort of custom control? SplittableCheckBox? Some kind of magic with a TableLayout control? (Pretty sure this fails at "the part everyone seems to miss.) Give up and either go back to MS Sans Serif, or use Tahoma uniformly, or package Segoe UI with my application, thus disrespecting the system default fonts. (New, via edit) Switch to WPF, if someone can convince me that it supports this scenario exactly. | If you have several options that follow this layout, why not create a user control? The user control will contain the CheckBox, a NumericUpDown, a ComboBox and a label for the "after loading". You can override OnFontChanged to adjust the location of the controls based on the rendering of the text with the given font. Add an EventHandler to the Label to check/uncheck the CheckBox. As for having the focus rectangle surround all of the controls, you should be able to give the user control focus when one of its inner controls is clicked. | Positioning controls in the middle of a CheckBox THis is a followup to my previous question " Font-dependent control positioning. " It's an attempt to solve the real problem behind that question, perhaps in ways different than the one I was asking about. Example of the problem statement: I want a checkbox that says "Adjust prices by after loading," where is a number---adjustable with a NumericUpDown ---and is either "percent" or "dollars," with the choices being made by a ComboBox. This will be on a single line. The complication: I want to be able to change my fonts for all these controls (basically setting them to System.Drawing.Fonts.MessageBoxFont, which is Tahoma 8 pt on Windows XP/etc. and Segoe UI 9 pt on Vista), without messing up my layout, which with my current Position -property--setting paradigm does not work. More generally, I'd like the controls to be dynamically laid out in a font-independent way, so that the NumericUpDown fits snugly into the space between "by " and the ComboBox, and similarly the ComboBox fits in with respect to the CheckBox and the string " after loading" to its right. The part everyone seems to miss: This is all nested within a CheckBox. So, ideally, clicking on the words "after loading" should check/uncheck the checkbox, and draw that little highlight rectangle around "Adjust prices by after loading." So just slapping an extra Label on the end doesn't work, because then it doesn't toggle the CheckBox; similarly, trying to band-aid things by hooking up such a Label 's Click event won't produce the desired highlight-rectangle. Solutions? At this point I'm thinking either: Rethink the problem, somehow, maybe with an ugly solution like two separate lines of text: "Adjust found prices after loading" ( CheckBox ), "Adjustment amount:" ( NumericUpDown and ComboBox ). This is really bad because my options box is absolutely full of options of this type (i.e. the type in the example), so it would at least double in vertical size. Some sort of custom control? SplittableCheckBox? Some kind of magic with a TableLayout control? (Pretty sure this fails at "the part everyone seems to miss.) Give up and either go back to MS Sans Serif, or use Tahoma uniformly, or package Segoe UI with my application, thus disrespecting the system default fonts. (New, via edit) Switch to WPF, if someone can convince me that it supports this scenario exactly. | TITLE:
Positioning controls in the middle of a CheckBox
QUESTION:
THis is a followup to my previous question " Font-dependent control positioning. " It's an attempt to solve the real problem behind that question, perhaps in ways different than the one I was asking about. Example of the problem statement: I want a checkbox that says "Adjust prices by after loading," where is a number---adjustable with a NumericUpDown ---and is either "percent" or "dollars," with the choices being made by a ComboBox. This will be on a single line. The complication: I want to be able to change my fonts for all these controls (basically setting them to System.Drawing.Fonts.MessageBoxFont, which is Tahoma 8 pt on Windows XP/etc. and Segoe UI 9 pt on Vista), without messing up my layout, which with my current Position -property--setting paradigm does not work. More generally, I'd like the controls to be dynamically laid out in a font-independent way, so that the NumericUpDown fits snugly into the space between "by " and the ComboBox, and similarly the ComboBox fits in with respect to the CheckBox and the string " after loading" to its right. The part everyone seems to miss: This is all nested within a CheckBox. So, ideally, clicking on the words "after loading" should check/uncheck the checkbox, and draw that little highlight rectangle around "Adjust prices by after loading." So just slapping an extra Label on the end doesn't work, because then it doesn't toggle the CheckBox; similarly, trying to band-aid things by hooking up such a Label 's Click event won't produce the desired highlight-rectangle. Solutions? At this point I'm thinking either: Rethink the problem, somehow, maybe with an ugly solution like two separate lines of text: "Adjust found prices after loading" ( CheckBox ), "Adjustment amount:" ( NumericUpDown and ComboBox ). This is really bad because my options box is absolutely full of options of this type (i.e. the type in the example), so it would at least double in vertical size. Some sort of custom control? SplittableCheckBox? Some kind of magic with a TableLayout control? (Pretty sure this fails at "the part everyone seems to miss.) Give up and either go back to MS Sans Serif, or use Tahoma uniformly, or package Segoe UI with my application, thus disrespecting the system default fonts. (New, via edit) Switch to WPF, if someone can convince me that it supports this scenario exactly.
ANSWER:
If you have several options that follow this layout, why not create a user control? The user control will contain the CheckBox, a NumericUpDown, a ComboBox and a label for the "after loading". You can override OnFontChanged to adjust the location of the controls based on the rendering of the text with the given font. Add an EventHandler to the Label to check/uncheck the CheckBox. As for having the focus rectangle surround all of the controls, you should be able to give the user control focus when one of its inner controls is clicked. | [
"winforms",
"layout",
"fonts"
] | 3 | 0 | 313 | 1 | 0 | 2008-09-01T21:00:05.940000 | 2008-09-01T21:13:01.993000 |
38,435 | 38,718 | Retrieving an Oracle timestamp using Python's Win32 ODBC module | Given an Oracle table created using the following: CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE); Using the Python ODBC module from its Win32 extensions (from the win32all package), I tried the following: import dbi, odbc
connection = odbc.odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD")
cursor = connection.cursor() cursor.execute("SELECT WhenAdded FROM Log")
results = cursor.fetchall() When I run this, I get the following: Traceback (most recent call last):... results = cursor.fetchall() dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s in FETCH The other data types I've tried (VARCHAR2, BLOB) do not cause this problem. Is there a way of retrieving timestamps? | I believe this is a bug in the Oracle ODBC driver. Basically, the Oracle ODBC driver does not support the TIMESTAMP WITH (LOCAL) TIME ZONE data types, only the TIMESTAMP data type. As you have discovered, one workaround is in fact to use the TO_CHAR method. In your example you are not actually reading the time zone information. If you have control of the table you could convert it to a straight TIMESTAMP column. If you don't have control over the table, another solution may be to create a view that converts from TIMESTAMP WITH TIME ZONE to TIMESTAMP via a string - sorry, I don't know if there is a way to convert directly from TIMESTAMP WITH TIME ZONE to TIMESTAMP. | Retrieving an Oracle timestamp using Python's Win32 ODBC module Given an Oracle table created using the following: CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE); Using the Python ODBC module from its Win32 extensions (from the win32all package), I tried the following: import dbi, odbc
connection = odbc.odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD")
cursor = connection.cursor() cursor.execute("SELECT WhenAdded FROM Log")
results = cursor.fetchall() When I run this, I get the following: Traceback (most recent call last):... results = cursor.fetchall() dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s in FETCH The other data types I've tried (VARCHAR2, BLOB) do not cause this problem. Is there a way of retrieving timestamps? | TITLE:
Retrieving an Oracle timestamp using Python's Win32 ODBC module
QUESTION:
Given an Oracle table created using the following: CREATE TABLE Log(WhenAdded TIMESTAMP(6) WITH TIME ZONE); Using the Python ODBC module from its Win32 extensions (from the win32all package), I tried the following: import dbi, odbc
connection = odbc.odbc("Driver=Oracle in OraHome92;Dbq=SERVER;Uid=USER;Pwd=PASSWD")
cursor = connection.cursor() cursor.execute("SELECT WhenAdded FROM Log")
results = cursor.fetchall() When I run this, I get the following: Traceback (most recent call last):... results = cursor.fetchall() dbi.operation-error: [Oracle][ODBC][Ora]ORA-00932: inconsistent datatypes: expected %s got %s in FETCH The other data types I've tried (VARCHAR2, BLOB) do not cause this problem. Is there a way of retrieving timestamps?
ANSWER:
I believe this is a bug in the Oracle ODBC driver. Basically, the Oracle ODBC driver does not support the TIMESTAMP WITH (LOCAL) TIME ZONE data types, only the TIMESTAMP data type. As you have discovered, one workaround is in fact to use the TO_CHAR method. In your example you are not actually reading the time zone information. If you have control of the table you could convert it to a straight TIMESTAMP column. If you don't have control over the table, another solution may be to create a view that converts from TIMESTAMP WITH TIME ZONE to TIMESTAMP via a string - sorry, I don't know if there is a way to convert directly from TIMESTAMP WITH TIME ZONE to TIMESTAMP. | [
"python",
"oracle",
"ora-00932"
] | 3 | 2 | 2,114 | 2 | 0 | 2008-09-01T21:06:07.517000 | 2008-09-02T02:33:57.807000 |
38,437 | 38,453 | How to track data changes in a database table | What is the best way to track changes in a database table? Imagine you got an application in which users (in the context of the application not DB users ) are able to change data which are store in some database table. What's the best way to track a history of all changes, so that you can show which user at what time change which data how? | In general, if your application is structured into layers, have the data access tier call a stored procedure on your database server to write a log of the database changes. In languages that support such a thing aspect-oriented programming can be a good technique to use for this kind of application. Auditing database table changes is the kind of operation that you'll typically want to log for all operations, so AOP can work very nicely. Bear in mind that logging database changes will create lots of data and will slow the system down. It may be sensible to use a message-queue solution and a separate database to perform the audit log, depending on the size of the application. It's also perfectly feasible to use stored procedures to handle this, although there may be a bit of work involved passing user credentials through to the database itself. | How to track data changes in a database table What is the best way to track changes in a database table? Imagine you got an application in which users (in the context of the application not DB users ) are able to change data which are store in some database table. What's the best way to track a history of all changes, so that you can show which user at what time change which data how? | TITLE:
How to track data changes in a database table
QUESTION:
What is the best way to track changes in a database table? Imagine you got an application in which users (in the context of the application not DB users ) are able to change data which are store in some database table. What's the best way to track a history of all changes, so that you can show which user at what time change which data how?
ANSWER:
In general, if your application is structured into layers, have the data access tier call a stored procedure on your database server to write a log of the database changes. In languages that support such a thing aspect-oriented programming can be a good technique to use for this kind of application. Auditing database table changes is the kind of operation that you'll typically want to log for all operations, so AOP can work very nicely. Bear in mind that logging database changes will create lots of data and will slow the system down. It may be sensible to use a message-queue solution and a separate database to perform the audit log, depending on the size of the application. It's also perfectly feasible to use stored procedures to handle this, although there may be a bit of work involved passing user credentials through to the database itself. | [
"database"
] | 50 | 13 | 95,523 | 8 | 0 | 2008-09-01T21:10:14.340000 | 2008-09-01T21:19:50.400000 |
38,501 | 40,291 | Thread pool for executing arbitrary tasks with different priorities | I'm trying to come up with a design for a thread pool with a lot of design requirements for my job. This is a real problem for working software, and it's a difficult task. I have a working implementation but I'd like to throw this out to SO and see what interesting ideas people can come up with, so that I can compare to my implementation and see how it stacks up. I've tried to be as specific to the requirements as I can. The thread pool needs to execute a series of tasks. The tasks can be short running (<1sec) or long running (hours or days). Each task has an associated priority (from 1 = very low to 5 = very high). Tasks can arrive at any time while the other tasks are running, so as they arrive the thread pool needs to pick these up and schedule them as threads become available. The task priority is completely independant of the task length. In fact it is impossible to tell how long a task could take to run without just running it. Some tasks are CPU bound while some are greatly IO bound. It is impossible to tell beforehand what a given task would be (although I guess it might be possible to detect while the tasks are running). The primary goal of the thread pool is to maximise throughput. The thread pool should effectively use the resources of the computer. Ideally, for CPU bound tasks, the number of active threads would be equal to the number of CPUs. For IO bound tasks, more threads should be allocated than there are CPUs so that blocking does not overly affect throughput. Minimising the use of locks and using thread safe/fast containers is important. In general, you should run higher priority tasks with a higher CPU priority (ref: SetThreadPriority). Lower priority tasks should not "block" higher priority tasks from running, so if a higher priority task comes along while all low priority tasks are running, the higher priority task will get to run. The tasks have a "max running tasks" parameter associated with them. Each type of task is only allowed to run at most this many concurrent instances of the task at a time. For example, we might have the following tasks in the queue: A - 1000 instances - low priority - max tasks 1 B - 1000 instances - low priority - max tasks 1 C - 1000 instances - low priority - max tasks 1 A working implementation could only run (at most) 1 A, 1 B and 1 C at the same time. It needs to run on Windows XP, Server 2003, Vista and Server 2008 (latest service packs). For reference, we might use the following interface: namespace ThreadPool { class Task { public: Task(); void run(); };
class ThreadPool { public: ThreadPool(); ~ThreadPool();
void run(Task *inst); void stop(); }; } | So what are we going to pick as the basic building block for this. Windows has two building blocks that look promising:- I/O Completion Ports (IOCPs) and Asynchronous Procedure Calls (APCs). Both of these give us FIFO queuing without having to perform explicit locking, and with a certain amount of built-in OS support in places like the scheduler (for example, IOCPs can avoid some context switches). APCs are perhaps a slightly better fit, but we will have to be slightly careful with them, because they are not quite "transparent". If the work item performs an alertable wait (::SleepEx,::WaitForXxxObjectEx, etc.) and we accidentally dispatch an APC to the thread then the newly dispatched APC will take over the thread, suspending the previously executing APC until the new APC is finished. This is bad for our concurrency requirements and can make stack overflows more likely. | Thread pool for executing arbitrary tasks with different priorities I'm trying to come up with a design for a thread pool with a lot of design requirements for my job. This is a real problem for working software, and it's a difficult task. I have a working implementation but I'd like to throw this out to SO and see what interesting ideas people can come up with, so that I can compare to my implementation and see how it stacks up. I've tried to be as specific to the requirements as I can. The thread pool needs to execute a series of tasks. The tasks can be short running (<1sec) or long running (hours or days). Each task has an associated priority (from 1 = very low to 5 = very high). Tasks can arrive at any time while the other tasks are running, so as they arrive the thread pool needs to pick these up and schedule them as threads become available. The task priority is completely independant of the task length. In fact it is impossible to tell how long a task could take to run without just running it. Some tasks are CPU bound while some are greatly IO bound. It is impossible to tell beforehand what a given task would be (although I guess it might be possible to detect while the tasks are running). The primary goal of the thread pool is to maximise throughput. The thread pool should effectively use the resources of the computer. Ideally, for CPU bound tasks, the number of active threads would be equal to the number of CPUs. For IO bound tasks, more threads should be allocated than there are CPUs so that blocking does not overly affect throughput. Minimising the use of locks and using thread safe/fast containers is important. In general, you should run higher priority tasks with a higher CPU priority (ref: SetThreadPriority). Lower priority tasks should not "block" higher priority tasks from running, so if a higher priority task comes along while all low priority tasks are running, the higher priority task will get to run. The tasks have a "max running tasks" parameter associated with them. Each type of task is only allowed to run at most this many concurrent instances of the task at a time. For example, we might have the following tasks in the queue: A - 1000 instances - low priority - max tasks 1 B - 1000 instances - low priority - max tasks 1 C - 1000 instances - low priority - max tasks 1 A working implementation could only run (at most) 1 A, 1 B and 1 C at the same time. It needs to run on Windows XP, Server 2003, Vista and Server 2008 (latest service packs). For reference, we might use the following interface: namespace ThreadPool { class Task { public: Task(); void run(); };
class ThreadPool { public: ThreadPool(); ~ThreadPool();
void run(Task *inst); void stop(); }; } | TITLE:
Thread pool for executing arbitrary tasks with different priorities
QUESTION:
I'm trying to come up with a design for a thread pool with a lot of design requirements for my job. This is a real problem for working software, and it's a difficult task. I have a working implementation but I'd like to throw this out to SO and see what interesting ideas people can come up with, so that I can compare to my implementation and see how it stacks up. I've tried to be as specific to the requirements as I can. The thread pool needs to execute a series of tasks. The tasks can be short running (<1sec) or long running (hours or days). Each task has an associated priority (from 1 = very low to 5 = very high). Tasks can arrive at any time while the other tasks are running, so as they arrive the thread pool needs to pick these up and schedule them as threads become available. The task priority is completely independant of the task length. In fact it is impossible to tell how long a task could take to run without just running it. Some tasks are CPU bound while some are greatly IO bound. It is impossible to tell beforehand what a given task would be (although I guess it might be possible to detect while the tasks are running). The primary goal of the thread pool is to maximise throughput. The thread pool should effectively use the resources of the computer. Ideally, for CPU bound tasks, the number of active threads would be equal to the number of CPUs. For IO bound tasks, more threads should be allocated than there are CPUs so that blocking does not overly affect throughput. Minimising the use of locks and using thread safe/fast containers is important. In general, you should run higher priority tasks with a higher CPU priority (ref: SetThreadPriority). Lower priority tasks should not "block" higher priority tasks from running, so if a higher priority task comes along while all low priority tasks are running, the higher priority task will get to run. The tasks have a "max running tasks" parameter associated with them. Each type of task is only allowed to run at most this many concurrent instances of the task at a time. For example, we might have the following tasks in the queue: A - 1000 instances - low priority - max tasks 1 B - 1000 instances - low priority - max tasks 1 C - 1000 instances - low priority - max tasks 1 A working implementation could only run (at most) 1 A, 1 B and 1 C at the same time. It needs to run on Windows XP, Server 2003, Vista and Server 2008 (latest service packs). For reference, we might use the following interface: namespace ThreadPool { class Task { public: Task(); void run(); };
class ThreadPool { public: ThreadPool(); ~ThreadPool();
void run(Task *inst); void stop(); }; }
ANSWER:
So what are we going to pick as the basic building block for this. Windows has two building blocks that look promising:- I/O Completion Ports (IOCPs) and Asynchronous Procedure Calls (APCs). Both of these give us FIFO queuing without having to perform explicit locking, and with a certain amount of built-in OS support in places like the scheduler (for example, IOCPs can avoid some context switches). APCs are perhaps a slightly better fit, but we will have to be slightly careful with them, because they are not quite "transparent". If the work item performs an alertable wait (::SleepEx,::WaitForXxxObjectEx, etc.) and we accidentally dispatch an APC to the thread then the newly dispatched APC will take over the thread, suspending the previously executing APC until the new APC is finished. This is bad for our concurrency requirements and can make stack overflows more likely. | [
"c++",
"windows",
"multithreading"
] | 11 | 5 | 3,007 | 5 | 0 | 2008-09-01T21:57:16.347000 | 2008-09-02T18:51:57.673000 |
38,502 | 38,517 | What's a good algorithm to generate a maze? | Say you want a simple maze on an N by M grid, with one path through, and a good number of dead ends, but that looks "right" (i.e. like someone made it by hand without too many little tiny dead ends and all that). Is there a known way to do this? | From http://www.astrolog.org/labyrnth/algrithm.htm Recursive backtracker: This is somewhat related to the recursive backtracker solving method described below, and requires stack up to the size of the Maze. When carving, be as greedy as possible, and always carve into an unmade section if one is next to the current cell. Each time you move to a new cell, push the former cell on the stack. If there are no unmade cells next to the current position, pop the stack to the previous position. The Maze is done when you pop everything off the stack. This algorithm results in Mazes with about as high a "river" factor as possible, with fewer but longer dead ends, and usually a very long and twisty solution. It runs quite fast, although Prim's algorithm is a bit faster. Recursive backtracking doesn't work as a wall adder, because doing so tends to result in a solution path that follows the outside edge, where the entire interior of the Maze is attached to the boundary by a single stem. They produce only 10% dead ends is an example of a maze generated by that method. | What's a good algorithm to generate a maze? Say you want a simple maze on an N by M grid, with one path through, and a good number of dead ends, but that looks "right" (i.e. like someone made it by hand without too many little tiny dead ends and all that). Is there a known way to do this? | TITLE:
What's a good algorithm to generate a maze?
QUESTION:
Say you want a simple maze on an N by M grid, with one path through, and a good number of dead ends, but that looks "right" (i.e. like someone made it by hand without too many little tiny dead ends and all that). Is there a known way to do this?
ANSWER:
From http://www.astrolog.org/labyrnth/algrithm.htm Recursive backtracker: This is somewhat related to the recursive backtracker solving method described below, and requires stack up to the size of the Maze. When carving, be as greedy as possible, and always carve into an unmade section if one is next to the current cell. Each time you move to a new cell, push the former cell on the stack. If there are no unmade cells next to the current position, pop the stack to the previous position. The Maze is done when you pop everything off the stack. This algorithm results in Mazes with about as high a "river" factor as possible, with fewer but longer dead ends, and usually a very long and twisty solution. It runs quite fast, although Prim's algorithm is a bit faster. Recursive backtracking doesn't work as a wall adder, because doing so tends to result in a solution path that follows the outside edge, where the entire interior of the Maze is attached to the boundary by a single stem. They produce only 10% dead ends is an example of a maze generated by that method. | [
"algorithm",
"maze"
] | 81 | 50 | 104,713 | 9 | 0 | 2008-09-01T21:57:45.490000 | 2008-09-01T22:04:39.747000 |
38,508 | 38,516 | What's the best way to return multiple values from a function? | I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string. Related question: Is it pythonic for a function to return multiple values? | def f(in_str): out_str = in_str.upper() return True, out_str # Creates tuple automatically
succeeded, b = f("a") # Automatic tuple unpacking | What's the best way to return multiple values from a function? I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string. Related question: Is it pythonic for a function to return multiple values? | TITLE:
What's the best way to return multiple values from a function?
QUESTION:
I have a function where I need to do something to a string. I need the function to return a boolean indicating whether or not the operation succeeded, and I also need to return the modified string. In C#, I would use an out parameter for the string, but there is no equivalent in Python. I'm still very new to Python and the only thing I can think of is to return a tuple with the boolean and modified string. Related question: Is it pythonic for a function to return multiple values?
ANSWER:
def f(in_str): out_str = in_str.upper() return True, out_str # Creates tuple automatically
succeeded, b = f("a") # Automatic tuple unpacking | [
"python",
"variables",
"return"
] | 78 | 136 | 81,568 | 6 | 0 | 2008-09-01T22:01:02.143000 | 2008-09-01T22:04:02.510000 |
38,510 | 38,532 | C# WinForms - DataGridView/SQL Compact - Negative integer in primary key column | I'm just getting dirty in WinForms, and I've discovered, through a lovely tutorial, the magic of dragging a database table onto the design view of my main form. So, all is lovely, I've got my DataGridView with all of the columns represented beautifully. BUT... When I run my application against this brand new, empty.sdf (empty save for the two tables I've created, which are themselves empty), I get a -1 in the column corresponding to my primary key/identity column whenever I try to create that first record. Any idea why this might be happening? If it helps, the column is an int. | Since it is an Identity column and you haven't saved it to the database yet it is -1. I am assuming here that this is before you save the table back to the database, correct? You need to perform the insert before that value will be set correctly. | C# WinForms - DataGridView/SQL Compact - Negative integer in primary key column I'm just getting dirty in WinForms, and I've discovered, through a lovely tutorial, the magic of dragging a database table onto the design view of my main form. So, all is lovely, I've got my DataGridView with all of the columns represented beautifully. BUT... When I run my application against this brand new, empty.sdf (empty save for the two tables I've created, which are themselves empty), I get a -1 in the column corresponding to my primary key/identity column whenever I try to create that first record. Any idea why this might be happening? If it helps, the column is an int. | TITLE:
C# WinForms - DataGridView/SQL Compact - Negative integer in primary key column
QUESTION:
I'm just getting dirty in WinForms, and I've discovered, through a lovely tutorial, the magic of dragging a database table onto the design view of my main form. So, all is lovely, I've got my DataGridView with all of the columns represented beautifully. BUT... When I run my application against this brand new, empty.sdf (empty save for the two tables I've created, which are themselves empty), I get a -1 in the column corresponding to my primary key/identity column whenever I try to create that first record. Any idea why this might be happening? If it helps, the column is an int.
ANSWER:
Since it is an Identity column and you haven't saved it to the database yet it is -1. I am assuming here that this is before you save the table back to the database, correct? You need to perform the insert before that value will be set correctly. | [
"c#",
"sql-server",
"winforms",
"data-binding",
"sql-server-ce"
] | 3 | 3 | 4,145 | 2 | 0 | 2008-09-01T22:01:25.993000 | 2008-09-01T22:14:53.187000 |
38,549 | 38,578 | What is the difference between "INNER JOIN" and "OUTER JOIN"? | Also, how do LEFT OUTER JOIN, RIGHT OUTER JOIN, and FULL OUTER JOIN fit in? | Assuming you're joining on columns with no duplicates, which is a very common case: An inner join of A and B gives the result of A intersect B, i.e. the inner part of a Venn diagram intersection. An outer join of A and B gives the results of A union B, i.e. the outer parts of a Venn diagram union. Examples Suppose you have two tables, with a single column each, and data as follows: A B - - 1 3 2 4 3 5 4 6 Note that (1,2) are unique to A, (3,4) are common, and (5,6) are unique to B. Inner join An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common. select * from a INNER JOIN b on a.a = b.b; select a.*, b.* from a,b where a.a = b.b;
a | b --+-- 3 | 3 4 | 4 Left outer join A left outer join will give all rows in A, plus any common rows in B. select * from a LEFT OUTER JOIN b on a.a = b.b; select a.*, b.* from a,b where a.a = b.b(+);
a | b --+----- 1 | null 2 | null 3 | 3 4 | 4 Right outer join A right outer join will give all rows in B, plus any common rows in A. select * from a RIGHT OUTER JOIN b on a.a = b.b; select a.*, b.* from a,b where a.a(+) = b.b;
a | b -----+---- 3 | 3 4 | 4 null | 5 null | 6 Full outer join A full outer join will give you the union of A and B, i.e. all the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa. select * from a FULL OUTER JOIN b on a.a = b.b;
a | b -----+----- 1 | null 2 | null 3 | 3 4 | 4 null | 6 null | 5 | What is the difference between "INNER JOIN" and "OUTER JOIN"? Also, how do LEFT OUTER JOIN, RIGHT OUTER JOIN, and FULL OUTER JOIN fit in? | TITLE:
What is the difference between "INNER JOIN" and "OUTER JOIN"?
QUESTION:
Also, how do LEFT OUTER JOIN, RIGHT OUTER JOIN, and FULL OUTER JOIN fit in?
ANSWER:
Assuming you're joining on columns with no duplicates, which is a very common case: An inner join of A and B gives the result of A intersect B, i.e. the inner part of a Venn diagram intersection. An outer join of A and B gives the results of A union B, i.e. the outer parts of a Venn diagram union. Examples Suppose you have two tables, with a single column each, and data as follows: A B - - 1 3 2 4 3 5 4 6 Note that (1,2) are unique to A, (3,4) are common, and (5,6) are unique to B. Inner join An inner join using either of the equivalent queries gives the intersection of the two tables, i.e. the two rows they have in common. select * from a INNER JOIN b on a.a = b.b; select a.*, b.* from a,b where a.a = b.b;
a | b --+-- 3 | 3 4 | 4 Left outer join A left outer join will give all rows in A, plus any common rows in B. select * from a LEFT OUTER JOIN b on a.a = b.b; select a.*, b.* from a,b where a.a = b.b(+);
a | b --+----- 1 | null 2 | null 3 | 3 4 | 4 Right outer join A right outer join will give all rows in B, plus any common rows in A. select * from a RIGHT OUTER JOIN b on a.a = b.b; select a.*, b.* from a,b where a.a(+) = b.b;
a | b -----+---- 3 | 3 4 | 4 null | 5 null | 6 Full outer join A full outer join will give you the union of A and B, i.e. all the rows in A and all the rows in B. If something in A doesn't have a corresponding datum in B, then the B portion is null, and vice versa. select * from a FULL OUTER JOIN b on a.a = b.b;
a | b -----+----- 1 | null 2 | null 3 | 3 4 | 4 null | 6 null | 5 | [
"sql",
"join",
"inner-join",
"outer-join"
] | 5,231 | 6,702 | 2,628,917 | 28 | 0 | 2008-09-01T22:36:06.940000 | 2008-09-01T22:59:34.840000 |
38,561 | 38,570 | What is the conversion specifier for printf that formats a long? | The printf function takes an argument type, such as %d or %i for a signed int. However, I don't see anything for a long value. | Put an l (lowercased letter L) directly before the specifier. unsigned long n; long m;
printf("%lu %ld", n, m); | What is the conversion specifier for printf that formats a long? The printf function takes an argument type, such as %d or %i for a signed int. However, I don't see anything for a long value. | TITLE:
What is the conversion specifier for printf that formats a long?
QUESTION:
The printf function takes an argument type, such as %d or %i for a signed int. However, I don't see anything for a long value.
ANSWER:
Put an l (lowercased letter L) directly before the specifier. unsigned long n; long m;
printf("%lu %ld", n, m); | [
"c",
"printf",
"long-integer"
] | 615 | 794 | 1,112,843 | 7 | 0 | 2008-09-01T22:45:25.903000 | 2008-09-01T22:50:23.023000 |
38,571 | 38,823 | Common lisp idiom - is there a better way? | I find myself doing this sort of thing all the time. I've been considering writing a macro/function to make this sort of thing easier, but it occurs to me that I'm probably reinventing the wheel. Is there an existing function that will let me accomplish this same sort of thing more succinctly? (defun remove-low-words (word-list) "Return a list with words of insufficient score removed." (let ((result nil)) (dolist (word word-list) (when (good-enough-score-p word) (push word result))) result)) | There are several built-in ways of doing this. One way would be: (remove-if-not 'good-enough-score-p word-list) And another: (loop for word in word-list when (good-enough-score-p word) collect word) And yet another: (mapcan (lambda (word) (when (good-enough-score-p word) (list word))) word-list) Etc... There's also SERIES and Iterate. The Iterate version is identical to the LOOP version, but the SERIES version is interesting: (collect (choose-if 'good-enough-score-p (scan word-list)))) So, yes, you're very likely to reinvent some wheel.:-) | Common lisp idiom - is there a better way? I find myself doing this sort of thing all the time. I've been considering writing a macro/function to make this sort of thing easier, but it occurs to me that I'm probably reinventing the wheel. Is there an existing function that will let me accomplish this same sort of thing more succinctly? (defun remove-low-words (word-list) "Return a list with words of insufficient score removed." (let ((result nil)) (dolist (word word-list) (when (good-enough-score-p word) (push word result))) result)) | TITLE:
Common lisp idiom - is there a better way?
QUESTION:
I find myself doing this sort of thing all the time. I've been considering writing a macro/function to make this sort of thing easier, but it occurs to me that I'm probably reinventing the wheel. Is there an existing function that will let me accomplish this same sort of thing more succinctly? (defun remove-low-words (word-list) "Return a list with words of insufficient score removed." (let ((result nil)) (dolist (word word-list) (when (good-enough-score-p word) (push word result))) result))
ANSWER:
There are several built-in ways of doing this. One way would be: (remove-if-not 'good-enough-score-p word-list) And another: (loop for word in word-list when (good-enough-score-p word) collect word) And yet another: (mapcan (lambda (word) (when (good-enough-score-p word) (list word))) word-list) Etc... There's also SERIES and Iterate. The Iterate version is identical to the LOOP version, but the SERIES version is interesting: (collect (choose-if 'good-enough-score-p (scan word-list)))) So, yes, you're very likely to reinvent some wheel.:-) | [
"common-lisp"
] | 7 | 22 | 2,098 | 3 | 0 | 2008-09-01T22:50:52.693000 | 2008-09-02T04:37:55.650000 |
38,572 | 38,573 | Is .NET 3.5 SP1 Required on the server to use Dynamic Data? | Is.NET 3.5 SP1 Required on the server to use Dynamic Data? It looks like it generates a lot of code and therefore wouldn't require anything special on the server side. I ask because I would like to use it but the shared hosting provider my client is using only have 3.5 installed and not 3.5 SP1. | Yes, SP1 is required. There are several bits of SP1 that Dynamic Data uses, notably the ASP.NET routing extensions and the new data annotation classes in System.ComponentModel. | Is .NET 3.5 SP1 Required on the server to use Dynamic Data? Is.NET 3.5 SP1 Required on the server to use Dynamic Data? It looks like it generates a lot of code and therefore wouldn't require anything special on the server side. I ask because I would like to use it but the shared hosting provider my client is using only have 3.5 installed and not 3.5 SP1. | TITLE:
Is .NET 3.5 SP1 Required on the server to use Dynamic Data?
QUESTION:
Is.NET 3.5 SP1 Required on the server to use Dynamic Data? It looks like it generates a lot of code and therefore wouldn't require anything special on the server side. I ask because I would like to use it but the shared hosting provider my client is using only have 3.5 installed and not 3.5 SP1.
ANSWER:
Yes, SP1 is required. There are several bits of SP1 that Dynamic Data uses, notably the ASP.NET routing extensions and the new data annotation classes in System.ComponentModel. | [
"asp.net",
"deployment",
"dynamic-data"
] | 1 | 2 | 176 | 1 | 0 | 2008-09-01T22:51:45.610000 | 2008-09-01T22:52:52.220000 |
38,592 | 38,599 | How do I make persistent network sockets on Unix in Ruby? | I'd like to be able to write a ruby program that can restart without dropping it's socket connections. | This program gets Google's homepage and then when you pass it SIG_INT via Ctrl - C it restarts the program and reads the output of the homepage from the open socket with Google. #!/usr/bin/ruby #simple_connector.rb require 'socket'
puts "Started."
if ARGV[0] == "restart" sock = IO.open(ARGV[1].to_i) puts sock.read exit else sock = TCPSocket.new('google.com', 80) sock.write("GET /\n") end
Signal.trap("INT") do puts "Restarting..." exec("ruby simple_connector.rb restart #{sock.fileno}") end
while true sleep 1 end | How do I make persistent network sockets on Unix in Ruby? I'd like to be able to write a ruby program that can restart without dropping it's socket connections. | TITLE:
How do I make persistent network sockets on Unix in Ruby?
QUESTION:
I'd like to be able to write a ruby program that can restart without dropping it's socket connections.
ANSWER:
This program gets Google's homepage and then when you pass it SIG_INT via Ctrl - C it restarts the program and reads the output of the homepage from the open socket with Google. #!/usr/bin/ruby #simple_connector.rb require 'socket'
puts "Started."
if ARGV[0] == "restart" sock = IO.open(ARGV[1].to_i) puts sock.read exit else sock = TCPSocket.new('google.com', 80) sock.write("GET /\n") end
Signal.trap("INT") do puts "Restarting..." exec("ruby simple_connector.rb restart #{sock.fileno}") end
while true sleep 1 end | [
"ruby",
"sockets"
] | 0 | 1 | 855 | 2 | 0 | 2008-09-01T23:19:03.717000 | 2008-09-01T23:21:48.203000 |
38,596 | 38,608 | What's the best way to keep a PHP script running as a daemon? | What is the best way to keep a PHP script running as a daemon, and what's the best way to check if needs restarting. I have some scripts that need to run 24/7 and for the most part I can run them using nohup. But if they go down, what's the best way to monitor it so it can be automatically restarted? | If you can't use the (proper) init structure to do this (you're on shared hosting, etc.), use cron to run a script (it can be written in whatever language you like) every few minutes that checks to see if they're running, and restarts them if necessary. | What's the best way to keep a PHP script running as a daemon? What is the best way to keep a PHP script running as a daemon, and what's the best way to check if needs restarting. I have some scripts that need to run 24/7 and for the most part I can run them using nohup. But if they go down, what's the best way to monitor it so it can be automatically restarted? | TITLE:
What's the best way to keep a PHP script running as a daemon?
QUESTION:
What is the best way to keep a PHP script running as a daemon, and what's the best way to check if needs restarting. I have some scripts that need to run 24/7 and for the most part I can run them using nohup. But if they go down, what's the best way to monitor it so it can be automatically restarted?
ANSWER:
If you can't use the (proper) init structure to do this (you're on shared hosting, etc.), use cron to run a script (it can be written in whatever language you like) every few minutes that checks to see if they're running, and restarts them if necessary. | [
"php",
"daemon"
] | 9 | 4 | 8,225 | 8 | 0 | 2008-09-01T23:20:59.033000 | 2008-09-01T23:26:35.400000 |
38,598 | 38,636 | How do you unit test business applications? | How are people unit testing their business applications? I've seen a lot of examples of unit testing with "simple to test" examples. Ex. a calculator. How are people unit testing data-heavy applications? How are you putting together your sample data? In many cases, data for one test may not work at all for another test which makes it hard to just have one test database? Testing the data access portion of the code is fairly straightforward. It's testing out all the methods that work against the data that seem to be hard to test. For example, imagine a posting process where there is heavy data access to determine what is posted, numbers are adjusted, etc. There are a number of interim steps that occur (and need to be tested) along with tests afterwards that ensure the posting was successful. Some of those steps may actually be stored procedures. In the past I've tried inserting the test data in a test database, then running the test, but honestly it's pretty painful to write this kind of code (and error prone). I've also tried just building a test database up front and rolling back the changes. That works OK but in a number of places you can't easily do this either (and many people would say that's integration testing; so be it, I still need to be able to test this somehow). If the answer is that there isn't a nice way of handling this and it currently just sort of sucks, that would be useful to know as well. Any thoughts, ideas, suggestions, or tips are appreciated. | I have to second the comment by @Phil Bennett as I try to approach these integration tests with a rollback solution. I have a very detailed post about integration testing your data access layer here I show not only the sample data access class, base class, and sample DB transaction fixture class, but a full CRUD integration test w/ sample data shown. With this approach you don't need multiple test databases as you can control the data going in with each test and after the test is complete the transactions are all rolledback so your DB is clean. About unit testing business logic inside your app, I would also second the comments by @Phil and @Mark because if you mock out all the dependencies your business object has, it becomes very simple to test your application logic one entity at a time;) Edit: So are you looking for one huge integration test that will verify everything from logic pre-data base / stored procedure run w/ logic and finally a verification on the way back? If so you could break this out into 2 steps: 1 - Unit test the logic that happens before the data is pushed into your data access code. For example, if you have some code that calculates some numbers based on some properties -- write a test that only checks to see if the logic for this 1 function does what you asked it to do. Mock out any dependancy on the data access class so you can ignore it for this test of the application logic alone. 2 - Integration test the logic that happens once you take your manipulated data (from the previous method we unit tested) and call the appropriate stored procedure. Do this inside a data specific testing class so you can rollback after it's completed. After your stored procedure has run, do a query against the database to get your object now that we have done some logic against the data and verify it has the values you expected (post-stored procedure logic /etc ) If you need an entry in your database for the stored procedure to run, simply insert that data before you run the sproc that has your logic inside it. For example, if you have a product that you need to test, it might require a supplier and category entry to insert so before you insert your product do a quick and dirty insert for a supplier and category so your product insert works as planned. | How do you unit test business applications? How are people unit testing their business applications? I've seen a lot of examples of unit testing with "simple to test" examples. Ex. a calculator. How are people unit testing data-heavy applications? How are you putting together your sample data? In many cases, data for one test may not work at all for another test which makes it hard to just have one test database? Testing the data access portion of the code is fairly straightforward. It's testing out all the methods that work against the data that seem to be hard to test. For example, imagine a posting process where there is heavy data access to determine what is posted, numbers are adjusted, etc. There are a number of interim steps that occur (and need to be tested) along with tests afterwards that ensure the posting was successful. Some of those steps may actually be stored procedures. In the past I've tried inserting the test data in a test database, then running the test, but honestly it's pretty painful to write this kind of code (and error prone). I've also tried just building a test database up front and rolling back the changes. That works OK but in a number of places you can't easily do this either (and many people would say that's integration testing; so be it, I still need to be able to test this somehow). If the answer is that there isn't a nice way of handling this and it currently just sort of sucks, that would be useful to know as well. Any thoughts, ideas, suggestions, or tips are appreciated. | TITLE:
How do you unit test business applications?
QUESTION:
How are people unit testing their business applications? I've seen a lot of examples of unit testing with "simple to test" examples. Ex. a calculator. How are people unit testing data-heavy applications? How are you putting together your sample data? In many cases, data for one test may not work at all for another test which makes it hard to just have one test database? Testing the data access portion of the code is fairly straightforward. It's testing out all the methods that work against the data that seem to be hard to test. For example, imagine a posting process where there is heavy data access to determine what is posted, numbers are adjusted, etc. There are a number of interim steps that occur (and need to be tested) along with tests afterwards that ensure the posting was successful. Some of those steps may actually be stored procedures. In the past I've tried inserting the test data in a test database, then running the test, but honestly it's pretty painful to write this kind of code (and error prone). I've also tried just building a test database up front and rolling back the changes. That works OK but in a number of places you can't easily do this either (and many people would say that's integration testing; so be it, I still need to be able to test this somehow). If the answer is that there isn't a nice way of handling this and it currently just sort of sucks, that would be useful to know as well. Any thoughts, ideas, suggestions, or tips are appreciated.
ANSWER:
I have to second the comment by @Phil Bennett as I try to approach these integration tests with a rollback solution. I have a very detailed post about integration testing your data access layer here I show not only the sample data access class, base class, and sample DB transaction fixture class, but a full CRUD integration test w/ sample data shown. With this approach you don't need multiple test databases as you can control the data going in with each test and after the test is complete the transactions are all rolledback so your DB is clean. About unit testing business logic inside your app, I would also second the comments by @Phil and @Mark because if you mock out all the dependencies your business object has, it becomes very simple to test your application logic one entity at a time;) Edit: So are you looking for one huge integration test that will verify everything from logic pre-data base / stored procedure run w/ logic and finally a verification on the way back? If so you could break this out into 2 steps: 1 - Unit test the logic that happens before the data is pushed into your data access code. For example, if you have some code that calculates some numbers based on some properties -- write a test that only checks to see if the logic for this 1 function does what you asked it to do. Mock out any dependancy on the data access class so you can ignore it for this test of the application logic alone. 2 - Integration test the logic that happens once you take your manipulated data (from the previous method we unit tested) and call the appropriate stored procedure. Do this inside a data specific testing class so you can rollback after it's completed. After your stored procedure has run, do a query against the database to get your object now that we have done some logic against the data and verify it has the values you expected (post-stored procedure logic /etc ) If you need an entry in your database for the stored procedure to run, simply insert that data before you run the sproc that has your logic inside it. For example, if you have a product that you need to test, it might require a supplier and category entry to insert so before you insert your product do a quick and dirty insert for a supplier and category so your product insert works as planned. | [
"unit-testing"
] | 14 | 2 | 2,267 | 6 | 0 | 2008-09-01T23:21:33.713000 | 2008-09-01T23:54:30.933000 |
38,601 | 38,916 | Using Django time/date widgets in custom form | How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view? I have looked through the Django forms documentation, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it? Here is my template that I want it applied on. {% for f in form %} {{ f.name }} {{ f }} {% endfor %} Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py: (r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy... | The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doing this at all. It's relying on undocumented internal implementation details of the admin, is likely to break again in future versions of Django, and is no easier to implement than just finding another JS calendar widget and using that. That said, here's what you have to do if you're determined to make this work: Define your own ModelForm subclass for your model (best to put it in forms.py in your app), and tell it to use the AdminDateWidget / AdminTimeWidget / AdminSplitDateTime (replace 'mydate' etc with the proper field names from your model): from django import forms from my_app.models import Product from django.contrib.admin import widgets
class ProductForm(forms.ModelForm): class Meta: model = Product def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.fields['mydate'].widget = widgets.AdminDateWidget() self.fields['mytime'].widget = widgets.AdminTimeWidget() self.fields['mydatetime'].widget = widgets.AdminSplitDateTime() Change your URLconf to pass 'form_class': ProductForm instead of 'model': Product to the generic create_object view (that'll mean from my_app.forms import ProductForm instead of from my_app.models import Product, of course). In the head of your template, include {{ form.media }} to output the links to the Javascript files. And the hacky part: the admin date/time widgets presume that the i18n JS stuff has been loaded, and also require core.js, but don't provide either one automatically. So in your template above {{ form.media }} you'll need: You may also wish to use the following admin CSS (thanks Alex for mentioning this): This implies that Django's admin media ( ADMIN_MEDIA_PREFIX ) is at /media/admin/ - you can change that for your setup. Ideally you'd use a context processor to pass this values to your template instead of hardcoding it, but that's beyond the scope of this question. This also requires that the URL /my_admin/jsi18n/ be manually wired up to the django.views.i18n.javascript_catalog view (or null_javascript_catalog if you aren't using I18N). You have to do this yourself instead of going through the admin application so it's accessible regardless of whether you're logged into the admin (thanks Jeremy for pointing this out). Sample code for your URLconf: (r'^my_admin/jsi18n', 'django.views.i18n.javascript_catalog'), Lastly, if you are using Django 1.2 or later, you need some additional code in your template to help the widgets find their media: {% load adminmedia %} /* At the top of the template. */
/* In the head section of the template. */ Thanks lupefiasco for this addition. | Using Django time/date widgets in custom form How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view? I have looked through the Django forms documentation, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it? Here is my template that I want it applied on. {% for f in form %} {{ f.name }} {{ f }} {% endfor %} Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py: (r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy... | TITLE:
Using Django time/date widgets in custom form
QUESTION:
How can I use the nifty JavaScript date and time widgets that the default admin uses with my custom view? I have looked through the Django forms documentation, and it briefly mentions django.contrib.admin.widgets, but I don't know how to use it? Here is my template that I want it applied on. {% for f in form %} {{ f.name }} {{ f }} {% endfor %} Also, I think it should be noted that I haven't really written a view up myself for this form, I am using a generic view. Here is the entry from the url.py: (r'^admin/products/add/$', create_object, {'model': Product, 'post_save_redirect': ''}), And I am relevantly new to the whole Django/MVC/MTV thing, so please go easy...
ANSWER:
The growing complexity of this answer over time, and the many hacks required, probably ought to caution you against doing this at all. It's relying on undocumented internal implementation details of the admin, is likely to break again in future versions of Django, and is no easier to implement than just finding another JS calendar widget and using that. That said, here's what you have to do if you're determined to make this work: Define your own ModelForm subclass for your model (best to put it in forms.py in your app), and tell it to use the AdminDateWidget / AdminTimeWidget / AdminSplitDateTime (replace 'mydate' etc with the proper field names from your model): from django import forms from my_app.models import Product from django.contrib.admin import widgets
class ProductForm(forms.ModelForm): class Meta: model = Product def __init__(self, *args, **kwargs): super(ProductForm, self).__init__(*args, **kwargs) self.fields['mydate'].widget = widgets.AdminDateWidget() self.fields['mytime'].widget = widgets.AdminTimeWidget() self.fields['mydatetime'].widget = widgets.AdminSplitDateTime() Change your URLconf to pass 'form_class': ProductForm instead of 'model': Product to the generic create_object view (that'll mean from my_app.forms import ProductForm instead of from my_app.models import Product, of course). In the head of your template, include {{ form.media }} to output the links to the Javascript files. And the hacky part: the admin date/time widgets presume that the i18n JS stuff has been loaded, and also require core.js, but don't provide either one automatically. So in your template above {{ form.media }} you'll need: You may also wish to use the following admin CSS (thanks Alex for mentioning this): This implies that Django's admin media ( ADMIN_MEDIA_PREFIX ) is at /media/admin/ - you can change that for your setup. Ideally you'd use a context processor to pass this values to your template instead of hardcoding it, but that's beyond the scope of this question. This also requires that the URL /my_admin/jsi18n/ be manually wired up to the django.views.i18n.javascript_catalog view (or null_javascript_catalog if you aren't using I18N). You have to do this yourself instead of going through the admin application so it's accessible regardless of whether you're logged into the admin (thanks Jeremy for pointing this out). Sample code for your URLconf: (r'^my_admin/jsi18n', 'django.views.i18n.javascript_catalog'), Lastly, if you are using Django 1.2 or later, you need some additional code in your template to help the widgets find their media: {% load adminmedia %} /* At the top of the template. */
/* In the head section of the template. */ Thanks lupefiasco for this addition. | [
"python",
"django"
] | 184 | 169 | 139,017 | 18 | 0 | 2008-09-01T23:22:55.207000 | 2008-09-02T06:10:58.127000 |
38,602 | 38,611 | Best way to display/format SQL 2005 money data type in ASP.Net | I am attempting to set an asp.net textbox to a SQL 2005 money data type field, the initial result displayed to the user is 40.0000 instead of 40.00. In my asp.net textbox control I would like to only display the first 2 numbers after the decimal point e.g. 40.00 What would be the best way to do this? My code is below: this.txtPayment.Text = dr["Payment"].ToString(); | this.txtPayment.Text = string.Format("{0:c}", dr[Payment"].ToString()); | Best way to display/format SQL 2005 money data type in ASP.Net I am attempting to set an asp.net textbox to a SQL 2005 money data type field, the initial result displayed to the user is 40.0000 instead of 40.00. In my asp.net textbox control I would like to only display the first 2 numbers after the decimal point e.g. 40.00 What would be the best way to do this? My code is below: this.txtPayment.Text = dr["Payment"].ToString(); | TITLE:
Best way to display/format SQL 2005 money data type in ASP.Net
QUESTION:
I am attempting to set an asp.net textbox to a SQL 2005 money data type field, the initial result displayed to the user is 40.0000 instead of 40.00. In my asp.net textbox control I would like to only display the first 2 numbers after the decimal point e.g. 40.00 What would be the best way to do this? My code is below: this.txtPayment.Text = dr["Payment"].ToString();
ANSWER:
this.txtPayment.Text = string.Format("{0:c}", dr[Payment"].ToString()); | [
"asp.net"
] | 2 | 2 | 3,026 | 5 | 0 | 2008-09-01T23:23:26.047000 | 2008-09-01T23:29:54.910000 |
38,612 | 38,684 | asp:DropDownList Error: 'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items | I have a asp.net 2.0 web site with numerous asp:DropDownList controls. The DropDownList control contains the standard info city, state, county etc... info. In addition to the standard codes the site also has custom codes that the users can configure themselves. For example a animal dropdown may contain the values Dog, Cat, Fish, ect... I am popluating the DropDownList from a SQL 2005 table that I created e.g. tblCodes Everything works great and users are able to add orders using the numerous DropDownList controls to choose items from the list. The problem occurrs if a user wants to change one of their custom dropdowns. For example a user would like to change the verbage on a animal type control from Dog to K9. This is where the problem starts. For all new orders the drop down works fine. When the user retrieved an old order I get the following error in the C# codebehind "'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items." What's happening is the old order has a database field value of Dog and the DropDownList no longer has Dog in its list since the user changed it to K9. Any ideas on a workaround? Is there a way to make the asp:DropDownList accept items not seeded in its list? Is there another control I could use? | I'm not sure it's the same issue, but I had a similar sounding issue with trying to bind a DropDownList that I wanted to contain in a GridView. When I looked around I found a lot of people asking similar questions, but no robust solutions. I did read conflicting reports about whether you could intercept databinding, etc events. I tried most of them but I couldn'f find a way of intercepting or pre-empting the error. I ended up creating a subclass of the ddl, intercepting the error from there hacking a fix. Not tidy but it worked for my needs. I put the code up on my blog in case it's of help. link text | asp:DropDownList Error: 'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items I have a asp.net 2.0 web site with numerous asp:DropDownList controls. The DropDownList control contains the standard info city, state, county etc... info. In addition to the standard codes the site also has custom codes that the users can configure themselves. For example a animal dropdown may contain the values Dog, Cat, Fish, ect... I am popluating the DropDownList from a SQL 2005 table that I created e.g. tblCodes Everything works great and users are able to add orders using the numerous DropDownList controls to choose items from the list. The problem occurrs if a user wants to change one of their custom dropdowns. For example a user would like to change the verbage on a animal type control from Dog to K9. This is where the problem starts. For all new orders the drop down works fine. When the user retrieved an old order I get the following error in the C# codebehind "'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items." What's happening is the old order has a database field value of Dog and the DropDownList no longer has Dog in its list since the user changed it to K9. Any ideas on a workaround? Is there a way to make the asp:DropDownList accept items not seeded in its list? Is there another control I could use? | TITLE:
asp:DropDownList Error: 'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items
QUESTION:
I have a asp.net 2.0 web site with numerous asp:DropDownList controls. The DropDownList control contains the standard info city, state, county etc... info. In addition to the standard codes the site also has custom codes that the users can configure themselves. For example a animal dropdown may contain the values Dog, Cat, Fish, ect... I am popluating the DropDownList from a SQL 2005 table that I created e.g. tblCodes Everything works great and users are able to add orders using the numerous DropDownList controls to choose items from the list. The problem occurrs if a user wants to change one of their custom dropdowns. For example a user would like to change the verbage on a animal type control from Dog to K9. This is where the problem starts. For all new orders the drop down works fine. When the user retrieved an old order I get the following error in the C# codebehind "'DropDownList1' has a SelectedValue which is invalid because it does not exist in the list of items." What's happening is the old order has a database field value of Dog and the DropDownList no longer has Dog in its list since the user changed it to K9. Any ideas on a workaround? Is there a way to make the asp:DropDownList accept items not seeded in its list? Is there another control I could use?
ANSWER:
I'm not sure it's the same issue, but I had a similar sounding issue with trying to bind a DropDownList that I wanted to contain in a GridView. When I looked around I found a lot of people asking similar questions, but no robust solutions. I did read conflicting reports about whether you could intercept databinding, etc events. I tried most of them but I couldn'f find a way of intercepting or pre-empting the error. I ended up creating a subclass of the ddl, intercepting the error from there hacking a fix. Not tidy but it worked for my needs. I put the code up on my blog in case it's of help. link text | [
"asp.net"
] | 2 | 2 | 17,387 | 8 | 0 | 2008-09-01T23:30:10.930000 | 2008-09-02T01:28:28.447000 |
38,618 | 38,620 | LSP in OO programming? | Am I right in thinking the full name of the LSP is the Liskoff Substitution Principle? I'm having trouble finding an [online] source to cite for any information on this... it seems to be a cornerstone of OOP, and yet I'm having trouble finding definitions. | Yes, you are right. It's spelled Liskov which is probably why you can't find a citation. Here's the link. One of the better resources regarding this is Robert C. Martin's Agile Software Development Principles Patterns and practices book. | LSP in OO programming? Am I right in thinking the full name of the LSP is the Liskoff Substitution Principle? I'm having trouble finding an [online] source to cite for any information on this... it seems to be a cornerstone of OOP, and yet I'm having trouble finding definitions. | TITLE:
LSP in OO programming?
QUESTION:
Am I right in thinking the full name of the LSP is the Liskoff Substitution Principle? I'm having trouble finding an [online] source to cite for any information on this... it seems to be a cornerstone of OOP, and yet I'm having trouble finding definitions.
ANSWER:
Yes, you are right. It's spelled Liskov which is probably why you can't find a citation. Here's the link. One of the better resources regarding this is Robert C. Martin's Agile Software Development Principles Patterns and practices book. | [
"oop"
] | 0 | 4 | 1,020 | 2 | 0 | 2008-09-01T23:34:35.490000 | 2008-09-01T23:37:05.797000 |
38,635 | 100,350 | What static analysis tools are available for C#? | What tools are there available for static analysis against C# code? I know about FxCop and StyleCop. Are there others? I've run across NStatic before but it's been in development for what seems like forever - it's looking pretty slick from what little I've seen of it, so it would be nice if it would ever see the light of day. Along these same lines (this is primarily my interest for static analysis), tools for testing code for multithreading issues (deadlocks, race conditions, etc.) also seem a bit scarce. Typemock Racer just popped up so I'll be looking at that. Anything beyond this? Real-life opinions about tools you've used are appreciated. | Code violation detection Tools: FxCop, excellent tool by Microsoft. Check compliance with.NET framework guidelines. Edit October 2010: No longer available as a standalone download. It is now included in the Windows SDK and after installation can be found in Program Files\Microsoft SDKs\Windows\ [v7.1] \Bin\FXCop\FxCopSetup.exe Edit February 2018: This functionality has now been integrated into Visual Studio 2012 and later as Code Analysis Clocksharp, based on code source analysis (to C# 2.0) Mono.Gendarme, similar to FxCop but with an open source licence (based on Mono.Cecil ) Smokey, similar to FxCop and Gendarme, based on Mono.Cecil. No longer on development, the main developer works with Gendarme team now. Coverity Prevent™ for C#, commercial product PRQA QA·C#, commercial product PVS-Studio, commercial product CAT.NET, visual studio addin that helps identification of security flaws Edit November 2019: Link is dead. CodeIt.Right Spec# Pex SonarQube, FOSS & Commercial options to support writing cleaner and safer code. Quality Metric Tools: NDepend, great visual tool. Useful for code metrics, rules, diff, coupling and dependency studies. Nitriq, free, can easily write your own metrics/constraints, nice visualizations. Edit February 2018: download links now dead. Edit June 17, 2019: Links not dead. RSM Squared, based on code source analysis C# Metrics, using a full parse of C# SourceMonitor, an old tool that occasionally gets updates Code Metrics, a Reflector add-in Vil, old tool that doesn't support.NET 2.0. Edit January 2018: Link now dead Checking Style Tools: StyleCop, Microsoft tool ( run from inside of Visual Studio or integrated into an MSBuild project). Also available as an extension for Visual Studio 2015 and C#6.0 Agent Smith, code style validation plugin for ReSharper Duplication Detection: Simian, based on source code. Works with plenty languages. CloneDR, detects parameterized clones only on language boundaries (also handles many languages other than C#) Clone Detective a Visual Studio plugin (which uses ConQAT internally) Atomiq, based on source code, plenty of languages, cool "wheel" visualization General Refactoring tools ReSharper - Majorly cool C# code analysis and refactoring features | What static analysis tools are available for C#? What tools are there available for static analysis against C# code? I know about FxCop and StyleCop. Are there others? I've run across NStatic before but it's been in development for what seems like forever - it's looking pretty slick from what little I've seen of it, so it would be nice if it would ever see the light of day. Along these same lines (this is primarily my interest for static analysis), tools for testing code for multithreading issues (deadlocks, race conditions, etc.) also seem a bit scarce. Typemock Racer just popped up so I'll be looking at that. Anything beyond this? Real-life opinions about tools you've used are appreciated. | TITLE:
What static analysis tools are available for C#?
QUESTION:
What tools are there available for static analysis against C# code? I know about FxCop and StyleCop. Are there others? I've run across NStatic before but it's been in development for what seems like forever - it's looking pretty slick from what little I've seen of it, so it would be nice if it would ever see the light of day. Along these same lines (this is primarily my interest for static analysis), tools for testing code for multithreading issues (deadlocks, race conditions, etc.) also seem a bit scarce. Typemock Racer just popped up so I'll be looking at that. Anything beyond this? Real-life opinions about tools you've used are appreciated.
ANSWER:
Code violation detection Tools: FxCop, excellent tool by Microsoft. Check compliance with.NET framework guidelines. Edit October 2010: No longer available as a standalone download. It is now included in the Windows SDK and after installation can be found in Program Files\Microsoft SDKs\Windows\ [v7.1] \Bin\FXCop\FxCopSetup.exe Edit February 2018: This functionality has now been integrated into Visual Studio 2012 and later as Code Analysis Clocksharp, based on code source analysis (to C# 2.0) Mono.Gendarme, similar to FxCop but with an open source licence (based on Mono.Cecil ) Smokey, similar to FxCop and Gendarme, based on Mono.Cecil. No longer on development, the main developer works with Gendarme team now. Coverity Prevent™ for C#, commercial product PRQA QA·C#, commercial product PVS-Studio, commercial product CAT.NET, visual studio addin that helps identification of security flaws Edit November 2019: Link is dead. CodeIt.Right Spec# Pex SonarQube, FOSS & Commercial options to support writing cleaner and safer code. Quality Metric Tools: NDepend, great visual tool. Useful for code metrics, rules, diff, coupling and dependency studies. Nitriq, free, can easily write your own metrics/constraints, nice visualizations. Edit February 2018: download links now dead. Edit June 17, 2019: Links not dead. RSM Squared, based on code source analysis C# Metrics, using a full parse of C# SourceMonitor, an old tool that occasionally gets updates Code Metrics, a Reflector add-in Vil, old tool that doesn't support.NET 2.0. Edit January 2018: Link now dead Checking Style Tools: StyleCop, Microsoft tool ( run from inside of Visual Studio or integrated into an MSBuild project). Also available as an extension for Visual Studio 2015 and C#6.0 Agent Smith, code style validation plugin for ReSharper Duplication Detection: Simian, based on source code. Works with plenty languages. CloneDR, detects parameterized clones only on language boundaries (also handles many languages other than C#) Clone Detective a Visual Studio plugin (which uses ConQAT internally) Atomiq, based on source code, plenty of languages, cool "wheel" visualization General Refactoring tools ReSharper - Majorly cool C# code analysis and refactoring features | [
"c#",
"code-analysis",
"static-analysis"
] | 174 | 361 | 173,688 | 9 | 0 | 2008-09-01T23:54:02.620000 | 2008-09-19T07:55:39.417000 |
38,645 | 39,678 | What are some efficient ways to combine two structures in MATLAB? | I want to combine two structures with differing fields names. For example, starting with: A.field1 = 1; A.field2 = 'a';
B.field3 = 2; B.field4 = 'b'; I would like to have: C.field1 = 1; C.field2 = 'a'; C.field3 = 2; C.field4 = 'b'; Is there a more efficient way than using "fieldnames" and a for loop? EDIT: Let's assume that in the case of field name conflicts we give preference to A. | Without collisions, you can do M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)']; C=struct(M{:}); And this is reasonably efficient. However, struct errors on duplicate fieldnames, and pre-checking for them using unique kills performance to the point that a loop is better. But here's what it would look like: M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)'];
[tmp, rows] = unique(M(1,:), 'last'); M=M(:, rows);
C=struct(M{:}); You might be able to make a hybrid solution by assuming no conflicts and using a try/catch around the call to struct to gracefully degrade to the conflict handling case. | What are some efficient ways to combine two structures in MATLAB? I want to combine two structures with differing fields names. For example, starting with: A.field1 = 1; A.field2 = 'a';
B.field3 = 2; B.field4 = 'b'; I would like to have: C.field1 = 1; C.field2 = 'a'; C.field3 = 2; C.field4 = 'b'; Is there a more efficient way than using "fieldnames" and a for loop? EDIT: Let's assume that in the case of field name conflicts we give preference to A. | TITLE:
What are some efficient ways to combine two structures in MATLAB?
QUESTION:
I want to combine two structures with differing fields names. For example, starting with: A.field1 = 1; A.field2 = 'a';
B.field3 = 2; B.field4 = 'b'; I would like to have: C.field1 = 1; C.field2 = 'a'; C.field3 = 2; C.field4 = 'b'; Is there a more efficient way than using "fieldnames" and a for loop? EDIT: Let's assume that in the case of field name conflicts we give preference to A.
ANSWER:
Without collisions, you can do M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)']; C=struct(M{:}); And this is reasonably efficient. However, struct errors on duplicate fieldnames, and pre-checking for them using unique kills performance to the point that a loop is better. But here's what it would look like: M = [fieldnames(A)' fieldnames(B)'; struct2cell(A)' struct2cell(B)'];
[tmp, rows] = unique(M(1,:), 'last'); M=M(:, rows);
C=struct(M{:}); You might be able to make a hybrid solution by assuming no conflicts and using a try/catch around the call to struct to gracefully degrade to the conflict handling case. | [
"matlab",
"merge",
"structure",
"field"
] | 24 | 19 | 19,847 | 5 | 0 | 2008-09-02T00:10:44.843000 | 2008-09-02T14:36:20.563000 |
38,647 | 356,511 | Performance of Linq to Entities vs ESQL | When using the Entity Framework, does ESQL perform better than Linq to Entities? I'd prefer to use Linq to Entities (mainly because of the strong-type checking), but some of my other team members are citing performance as a reason to use ESQL. I would like to get a full idea of the pro's/con's of using either method. | The most obvious differences are: Linq to Entities is strongly typed code including nice query comprehension syntax. The fact that the “from” comes before the “select” allows IntelliSense to help you. Entity SQL uses traditional string based queries with a more familiar SQL like syntax where the SELECT statement comes before the FROM. Because eSQL is string based, dynamic queries may be composed in a traditional way at run time using string manipulation. The less obvious key difference is: Linq to Entities allows you to change the shape or "project" the results of your query into any shape you require with the “select new{... }” syntax. Anonymous types, new to C# 3.0, has allowed this. Projection is not possible using Entity SQL as you must always return an ObjectQuery. In some scenarios it is possible use ObjectQuery however you must work around the fact that.Select always returns ObjectQuery. See code below... ObjectQuery query = DynamicQuery(context, "Products", "it.ProductName = 'Chai'", "it.ProductName, it.QuantityPerUnit");
public static ObjectQuery DynamicQuery(MyContext context, string root, string selection, string projection) { ObjectQuery rootQuery = context.CreateQuery (root); ObjectQuery filteredQuery = rootQuery.Where(selection); ObjectQuery result = filteredQuery.Select(projection); return result; } There are other more subtle differences described by one of the team members in detail here and here. | Performance of Linq to Entities vs ESQL When using the Entity Framework, does ESQL perform better than Linq to Entities? I'd prefer to use Linq to Entities (mainly because of the strong-type checking), but some of my other team members are citing performance as a reason to use ESQL. I would like to get a full idea of the pro's/con's of using either method. | TITLE:
Performance of Linq to Entities vs ESQL
QUESTION:
When using the Entity Framework, does ESQL perform better than Linq to Entities? I'd prefer to use Linq to Entities (mainly because of the strong-type checking), but some of my other team members are citing performance as a reason to use ESQL. I would like to get a full idea of the pro's/con's of using either method.
ANSWER:
The most obvious differences are: Linq to Entities is strongly typed code including nice query comprehension syntax. The fact that the “from” comes before the “select” allows IntelliSense to help you. Entity SQL uses traditional string based queries with a more familiar SQL like syntax where the SELECT statement comes before the FROM. Because eSQL is string based, dynamic queries may be composed in a traditional way at run time using string manipulation. The less obvious key difference is: Linq to Entities allows you to change the shape or "project" the results of your query into any shape you require with the “select new{... }” syntax. Anonymous types, new to C# 3.0, has allowed this. Projection is not possible using Entity SQL as you must always return an ObjectQuery. In some scenarios it is possible use ObjectQuery however you must work around the fact that.Select always returns ObjectQuery. See code below... ObjectQuery query = DynamicQuery(context, "Products", "it.ProductName = 'Chai'", "it.ProductName, it.QuantityPerUnit");
public static ObjectQuery DynamicQuery(MyContext context, string root, string selection, string projection) { ObjectQuery rootQuery = context.CreateQuery (root); ObjectQuery filteredQuery = rootQuery.Where(selection); ObjectQuery result = filteredQuery.Select(projection); return result; } There are other more subtle differences described by one of the team members in detail here and here. | [
"entity-framework",
"linq-to-entities",
"entity-sql"
] | 18 | 17 | 12,147 | 6 | 0 | 2008-09-02T00:14:56.690000 | 2008-12-10T15:41:19.460000 |
38,651 | 528,831 | Any way to have an ActionScript 3 (Flex/AIR) project print to standard output? | Is there any way to have a binary compiled from an ActionScript 3 project print stuff to stdout when executed? From what I've gathered, people have been going around this limitation by writing hacks that rely on local socket connections and AIR apps that write to files in the local filesystem, but that's pretty much it -- it's obviously not possible with the Flash Player and AIR runtimes from Adobe. Is there any project (e.g. based on the Tamarin code) that is attempting to implement something that would provide this kind of functionality? | With AIR on Linux, it is easy to write to stdout, since the process can see its own file descriptors as files in /dev. For stdout, open /dev/fd/1 or /dev/stdout as a FileStream, then write to that. Example: var stdout: FileStream = new FileStream(); stdout.open(new File("/dev/fd/1"), FileMode.WRITE); stdout.writeUTFBytes("test\n"); stdout.close(); Note: See this answer for the difference between writeUTF() and writeUTFBytes() - the latter will avoid garbled output on stdout. | Any way to have an ActionScript 3 (Flex/AIR) project print to standard output? Is there any way to have a binary compiled from an ActionScript 3 project print stuff to stdout when executed? From what I've gathered, people have been going around this limitation by writing hacks that rely on local socket connections and AIR apps that write to files in the local filesystem, but that's pretty much it -- it's obviously not possible with the Flash Player and AIR runtimes from Adobe. Is there any project (e.g. based on the Tamarin code) that is attempting to implement something that would provide this kind of functionality? | TITLE:
Any way to have an ActionScript 3 (Flex/AIR) project print to standard output?
QUESTION:
Is there any way to have a binary compiled from an ActionScript 3 project print stuff to stdout when executed? From what I've gathered, people have been going around this limitation by writing hacks that rely on local socket connections and AIR apps that write to files in the local filesystem, but that's pretty much it -- it's obviously not possible with the Flash Player and AIR runtimes from Adobe. Is there any project (e.g. based on the Tamarin code) that is attempting to implement something that would provide this kind of functionality?
ANSWER:
With AIR on Linux, it is easy to write to stdout, since the process can see its own file descriptors as files in /dev. For stdout, open /dev/fd/1 or /dev/stdout as a FileStream, then write to that. Example: var stdout: FileStream = new FileStream(); stdout.open(new File("/dev/fd/1"), FileMode.WRITE); stdout.writeUTFBytes("test\n"); stdout.close(); Note: See this answer for the difference between writeUTF() and writeUTFBytes() - the latter will avoid garbled output on stdout. | [
"apache-flex",
"flash",
"actionscript-3",
"adobe"
] | 7 | 9 | 3,708 | 4 | 0 | 2008-09-02T00:27:49.823000 | 2009-02-09T16:24:49.427000 |
38,654 | 38,685 | Automatically floating all fields in a VFP report? | I want to set all the fields and labels on a VFP7 report to Float and Stretch with overflow. I tried Using the.frx file and doing the following REPLACE but it didn't work. Is there some other field I need to change too? REPLACE float WITH.T. FOR objtype = 8 | It turns out you have to set top to.F. for float to take effect, this worked: USE report.frx REPLACE float with.T., stretch with.T., top with.F. for objtype = 8 | Automatically floating all fields in a VFP report? I want to set all the fields and labels on a VFP7 report to Float and Stretch with overflow. I tried Using the.frx file and doing the following REPLACE but it didn't work. Is there some other field I need to change too? REPLACE float WITH.T. FOR objtype = 8 | TITLE:
Automatically floating all fields in a VFP report?
QUESTION:
I want to set all the fields and labels on a VFP7 report to Float and Stretch with overflow. I tried Using the.frx file and doing the following REPLACE but it didn't work. Is there some other field I need to change too? REPLACE float WITH.T. FOR objtype = 8
ANSWER:
It turns out you have to set top to.F. for float to take effect, this worked: USE report.frx REPLACE float with.T., stretch with.T., top with.F. for objtype = 8 | [
"report",
"foxpro",
"visual-foxpro"
] | 2 | 2 | 1,298 | 1 | 0 | 2008-09-02T00:33:09.517000 | 2008-09-02T01:29:23.653000 |
38,661 | 39,535 | Can IIS 6 serve requests for pages with no extensions? | Is there any way in IIS to map requests to a particular URL with no extension to a given application. For example, in trying to port something from a Java servlet, you might have a URL like this... http://[server]/MyApp/HomePage?some=parameter Ideally I'd like to be able to map everything under MyApp to a particular application, but failing that, any suggestions about how to achieve the same effect would be really helpful. | You can set the IIS6 to handle all requests, but the key to handle files without extensions is to tell the IIS not to look for the file. http://weblogs.asp.net/scottgu/archive/2007/03/04/tip-trick-integrating-asp-net-security-with-classic-asp-and-non-asp-net-urls.aspx | Can IIS 6 serve requests for pages with no extensions? Is there any way in IIS to map requests to a particular URL with no extension to a given application. For example, in trying to port something from a Java servlet, you might have a URL like this... http://[server]/MyApp/HomePage?some=parameter Ideally I'd like to be able to map everything under MyApp to a particular application, but failing that, any suggestions about how to achieve the same effect would be really helpful. | TITLE:
Can IIS 6 serve requests for pages with no extensions?
QUESTION:
Is there any way in IIS to map requests to a particular URL with no extension to a given application. For example, in trying to port something from a Java servlet, you might have a URL like this... http://[server]/MyApp/HomePage?some=parameter Ideally I'd like to be able to map everything under MyApp to a particular application, but failing that, any suggestions about how to achieve the same effect would be really helpful.
ANSWER:
You can set the IIS6 to handle all requests, but the key to handle files without extensions is to tell the IIS not to look for the file. http://weblogs.asp.net/scottgu/archive/2007/03/04/tip-trick-integrating-asp-net-security-with-classic-asp-and-non-asp-net-urls.aspx | [
"iis",
"iis-6"
] | 1 | 1 | 3,525 | 2 | 0 | 2008-09-02T00:52:31.840000 | 2008-09-02T13:42:09.337000 |
38,664 | 38,666 | Can you modify text files when committing to subversion? | I want to ran the following script on text files that are being committed: # Send the commands H and w to ed # ed will append newline if the file does not end in one printf "%s\n" H w | ed -s $1
# Strip trailing whitespace sed -i 's/[ \t]*$//g' $1
# Convert tabs to 4 spaces sed -i -r "s/\t/ /g" $1 I see subversion has a start-commit and pre-commit hooks but I can't follow the documentation about how I could process the text files with the above script. | You mean change the text file before it's committed? You can (I'm not sure how), but it's generally not a good idea, as it doesn't tell the client about the change, so the local copies become void on a commit. What I would do is block the commit (non zero exit), and give an error message as to why you don't want that revision to go through. | Can you modify text files when committing to subversion? I want to ran the following script on text files that are being committed: # Send the commands H and w to ed # ed will append newline if the file does not end in one printf "%s\n" H w | ed -s $1
# Strip trailing whitespace sed -i 's/[ \t]*$//g' $1
# Convert tabs to 4 spaces sed -i -r "s/\t/ /g" $1 I see subversion has a start-commit and pre-commit hooks but I can't follow the documentation about how I could process the text files with the above script. | TITLE:
Can you modify text files when committing to subversion?
QUESTION:
I want to ran the following script on text files that are being committed: # Send the commands H and w to ed # ed will append newline if the file does not end in one printf "%s\n" H w | ed -s $1
# Strip trailing whitespace sed -i 's/[ \t]*$//g' $1
# Convert tabs to 4 spaces sed -i -r "s/\t/ /g" $1 I see subversion has a start-commit and pre-commit hooks but I can't follow the documentation about how I could process the text files with the above script.
ANSWER:
You mean change the text file before it's committed? You can (I'm not sure how), but it's generally not a good idea, as it doesn't tell the client about the change, so the local copies become void on a commit. What I would do is block the commit (non zero exit), and give an error message as to why you don't want that revision to go through. | [
"svn",
"hook"
] | 3 | 7 | 668 | 1 | 0 | 2008-09-02T01:01:56.310000 | 2008-09-02T01:04:55.243000 |
38,669 | 580,095 | Does the PHP mail() function work if I don't own the MX record | I'm not sure I'm using all the correct terminology here so be forgiving. I just put up a site with a contact form that sends an email using the PHP mail() function. Simple enough. However the live site doesn't actually send the email, the test site does. So it's not my code. It's a shared host and we have another site that has the same function that works perfectly, so it's not the server. The only difference between the two is that the site that doesn't work just has the name server pointing to us and so the MX record never touches our server. So my question is, could some one please confirm that the mail() function wont work if we don't have the MX record pointing to our server. Thanks | Hey guys thanks for the answers, it is really appreciated. After ignoring the issue for a few months it has come up again, I did however find the answer to my problems. Firstly, as you answers suggested, PHP and the mail() function were working as expected. The mail was getting sent. The problem lies when the email is sent, it simply presumes that because its being sent from mydomain.com to *@mydomain.com email that the email itself is hosted on the same server, so it gets sent there instead and ignores the MX record. OK it's a bit more complicated than that, but that is the general jist. Edit: Found a better version of the topic sendmail and MX records when mail server is not on web host. | Does the PHP mail() function work if I don't own the MX record I'm not sure I'm using all the correct terminology here so be forgiving. I just put up a site with a contact form that sends an email using the PHP mail() function. Simple enough. However the live site doesn't actually send the email, the test site does. So it's not my code. It's a shared host and we have another site that has the same function that works perfectly, so it's not the server. The only difference between the two is that the site that doesn't work just has the name server pointing to us and so the MX record never touches our server. So my question is, could some one please confirm that the mail() function wont work if we don't have the MX record pointing to our server. Thanks | TITLE:
Does the PHP mail() function work if I don't own the MX record
QUESTION:
I'm not sure I'm using all the correct terminology here so be forgiving. I just put up a site with a contact form that sends an email using the PHP mail() function. Simple enough. However the live site doesn't actually send the email, the test site does. So it's not my code. It's a shared host and we have another site that has the same function that works perfectly, so it's not the server. The only difference between the two is that the site that doesn't work just has the name server pointing to us and so the MX record never touches our server. So my question is, could some one please confirm that the mail() function wont work if we don't have the MX record pointing to our server. Thanks
ANSWER:
Hey guys thanks for the answers, it is really appreciated. After ignoring the issue for a few months it has come up again, I did however find the answer to my problems. Firstly, as you answers suggested, PHP and the mail() function were working as expected. The mail was getting sent. The problem lies when the email is sent, it simply presumes that because its being sent from mydomain.com to *@mydomain.com email that the email itself is hosted on the same server, so it gets sent there instead and ignores the MX record. OK it's a bit more complicated than that, but that is the general jist. Edit: Found a better version of the topic sendmail and MX records when mail server is not on web host. | [
"php",
"dns"
] | 7 | 2 | 9,961 | 6 | 0 | 2008-09-02T01:10:54.090000 | 2009-02-24T01:09:17.330000 |
38,670 | 38,704 | ASP.NET controls cannot be referenced in code-behind in Visual Studio 2008 | Ok, so, my visual studio is broken. I say this NOT prematurely, as it was my first response to see where I had messed up in my code. When I add controls to the page I can't reference all of them in the code behind. Some of them I can, it seems that the first few I put on a page work, then it just stops. I first thought it may be the type of control as initially I was trying to reference a repeater inside an update panel. I know I am correctly referencing the code behind in my aspx page. But just in case it was a screw up on my part I started to recreate the page from scratch and this time got a few more controls down before VS stopped recognizing my controls. After creating my page twice and getting stuck I thought maybe it was still the type of controls. I created a new page and just threw some labels on it. No dice, build fails when referencing the control from the code behind. In a possibly unrelated note when I switch to the dreaded "design" mode of the aspx pages VS 2008 errors out and restarts. I have already put a trouble ticket in to Microsoft. I uninstalled all add-ins, I reinstalled visual studio. Anyone that wants to see my code just ask, but I am using the straight WYSIWYG visual studio "new aspx page" nothing fancy. I doubt anyone has run into this, but have you? Has anyone had success trouble shooting these things with Microsoft? Any way to expedite this ticket without paying??? I have been talking to a rep from Microsoft for days with no luck yet and I am dead in the water. Jon Limjap: I edited the title to both make it clear and descriptive and make sure that nobody sees it as offensive. "Foo-barred" doesn't exactly constitute a proper question title, although your question is clearly a valid one. | try clearing your local VS cache. find your project and delete the folder. the folder is created by VS for what reason I honestly don't understand. but I've had several occasions where clearing it and doing a re-build fixes things... hope this is all that you need as well. here %Temp%\VWDWebCache and possibly here %LocalAppData%\Microsoft\WebsiteCache | ASP.NET controls cannot be referenced in code-behind in Visual Studio 2008 Ok, so, my visual studio is broken. I say this NOT prematurely, as it was my first response to see where I had messed up in my code. When I add controls to the page I can't reference all of them in the code behind. Some of them I can, it seems that the first few I put on a page work, then it just stops. I first thought it may be the type of control as initially I was trying to reference a repeater inside an update panel. I know I am correctly referencing the code behind in my aspx page. But just in case it was a screw up on my part I started to recreate the page from scratch and this time got a few more controls down before VS stopped recognizing my controls. After creating my page twice and getting stuck I thought maybe it was still the type of controls. I created a new page and just threw some labels on it. No dice, build fails when referencing the control from the code behind. In a possibly unrelated note when I switch to the dreaded "design" mode of the aspx pages VS 2008 errors out and restarts. I have already put a trouble ticket in to Microsoft. I uninstalled all add-ins, I reinstalled visual studio. Anyone that wants to see my code just ask, but I am using the straight WYSIWYG visual studio "new aspx page" nothing fancy. I doubt anyone has run into this, but have you? Has anyone had success trouble shooting these things with Microsoft? Any way to expedite this ticket without paying??? I have been talking to a rep from Microsoft for days with no luck yet and I am dead in the water. Jon Limjap: I edited the title to both make it clear and descriptive and make sure that nobody sees it as offensive. "Foo-barred" doesn't exactly constitute a proper question title, although your question is clearly a valid one. | TITLE:
ASP.NET controls cannot be referenced in code-behind in Visual Studio 2008
QUESTION:
Ok, so, my visual studio is broken. I say this NOT prematurely, as it was my first response to see where I had messed up in my code. When I add controls to the page I can't reference all of them in the code behind. Some of them I can, it seems that the first few I put on a page work, then it just stops. I first thought it may be the type of control as initially I was trying to reference a repeater inside an update panel. I know I am correctly referencing the code behind in my aspx page. But just in case it was a screw up on my part I started to recreate the page from scratch and this time got a few more controls down before VS stopped recognizing my controls. After creating my page twice and getting stuck I thought maybe it was still the type of controls. I created a new page and just threw some labels on it. No dice, build fails when referencing the control from the code behind. In a possibly unrelated note when I switch to the dreaded "design" mode of the aspx pages VS 2008 errors out and restarts. I have already put a trouble ticket in to Microsoft. I uninstalled all add-ins, I reinstalled visual studio. Anyone that wants to see my code just ask, but I am using the straight WYSIWYG visual studio "new aspx page" nothing fancy. I doubt anyone has run into this, but have you? Has anyone had success trouble shooting these things with Microsoft? Any way to expedite this ticket without paying??? I have been talking to a rep from Microsoft for days with no luck yet and I am dead in the water. Jon Limjap: I edited the title to both make it clear and descriptive and make sure that nobody sees it as offensive. "Foo-barred" doesn't exactly constitute a proper question title, although your question is clearly a valid one.
ANSWER:
try clearing your local VS cache. find your project and delete the folder. the folder is created by VS for what reason I honestly don't understand. but I've had several occasions where clearing it and doing a re-build fixes things... hope this is all that you need as well. here %Temp%\VWDWebCache and possibly here %LocalAppData%\Microsoft\WebsiteCache | [
"c#",
"asp.net",
"visual-studio"
] | 32 | 17 | 56,187 | 16 | 0 | 2008-09-02T01:10:54.307000 | 2008-09-02T02:12:06.830000 |
38,674 | 39,266 | Does Adobe Flash support databases? | Which databases does Adobe Flash support, if any? | None, really. As others have said, the best solution is to have something in between. I personally prefer amfphp for larger datasets and plain xml for smaller stuff, especially since they introduced E4X (way better XML handling) in ActionScript 3. However, since Flash can do socket communication, it is possible to talk directly to a server. This is very fast, but you're basically opening up your database to the world. I've never used any of these, but the major ones seem to be asql and assql. Also, flash running in Adobe AIR has support for sqlite databases. | Does Adobe Flash support databases? Which databases does Adobe Flash support, if any? | TITLE:
Does Adobe Flash support databases?
QUESTION:
Which databases does Adobe Flash support, if any?
ANSWER:
None, really. As others have said, the best solution is to have something in between. I personally prefer amfphp for larger datasets and plain xml for smaller stuff, especially since they introduced E4X (way better XML handling) in ActionScript 3. However, since Flash can do socket communication, it is possible to talk directly to a server. This is very fast, but you're basically opening up your database to the world. I've never used any of these, but the major ones seem to be asql and assql. Also, flash running in Adobe AIR has support for sqlite databases. | [
"database",
"flash",
"adobe"
] | 1 | 4 | 5,317 | 8 | 0 | 2008-09-02T01:15:47.383000 | 2008-09-02T11:30:25.473000 |
38,680 | 153,943 | How to provide next page of updated content? | Feel free to edit the title if you know how to formulate the question better. (Tagging is a problem as well.) The problem may be too difficult in this general form, so let us consider a concrete example. You get a screenful of stackoverflow questions by requesting /questions?sort=newest page. Next page link leads to /questions?page=2 &sort=newest. I suppose that at server side, the request is translated into an SQL query with LIMIT clause. Problem with this approach is, that if new question were added while user browses first page, his second page will start with some questions he already saw. (If he has 10 question per page, and 10 new questions happened to be added, he’ll get exactly the same content second time!) Is there an elegant way to solve this common problem? I realize that it is not that big a problem, at least not for stackoverflow, but still. The best idea I have (apart from storing request history per client) is to use /questions?answer_id=NNN format. Server returns a page that starts with the requested answer, and puts the id of the first answer on the next page into next page link. There must be a way to write SQL for that, right? Is it how it usually done? Or there is a better way? | This can't be done an easy way. For instance, the "Unanswered" list here at stackoverflow is sorted by number of votes. So if you'd save the last ID of the page you're viewing (in a cookie, request, session, whereever) and someone upvotes a post while you're browsing page 2, page 3 isn't complete since the recently upvoted post could have been moved to page 1 or 2. Only way to do it is to load the complete list in someones session. Please don't... As already mentioned, let's hope people are used to this by now. | How to provide next page of updated content? Feel free to edit the title if you know how to formulate the question better. (Tagging is a problem as well.) The problem may be too difficult in this general form, so let us consider a concrete example. You get a screenful of stackoverflow questions by requesting /questions?sort=newest page. Next page link leads to /questions?page=2 &sort=newest. I suppose that at server side, the request is translated into an SQL query with LIMIT clause. Problem with this approach is, that if new question were added while user browses first page, his second page will start with some questions he already saw. (If he has 10 question per page, and 10 new questions happened to be added, he’ll get exactly the same content second time!) Is there an elegant way to solve this common problem? I realize that it is not that big a problem, at least not for stackoverflow, but still. The best idea I have (apart from storing request history per client) is to use /questions?answer_id=NNN format. Server returns a page that starts with the requested answer, and puts the id of the first answer on the next page into next page link. There must be a way to write SQL for that, right? Is it how it usually done? Or there is a better way? | TITLE:
How to provide next page of updated content?
QUESTION:
Feel free to edit the title if you know how to formulate the question better. (Tagging is a problem as well.) The problem may be too difficult in this general form, so let us consider a concrete example. You get a screenful of stackoverflow questions by requesting /questions?sort=newest page. Next page link leads to /questions?page=2 &sort=newest. I suppose that at server side, the request is translated into an SQL query with LIMIT clause. Problem with this approach is, that if new question were added while user browses first page, his second page will start with some questions he already saw. (If he has 10 question per page, and 10 new questions happened to be added, he’ll get exactly the same content second time!) Is there an elegant way to solve this common problem? I realize that it is not that big a problem, at least not for stackoverflow, but still. The best idea I have (apart from storing request history per client) is to use /questions?answer_id=NNN format. Server returns a page that starts with the requested answer, and puts the id of the first answer on the next page into next page link. There must be a way to write SQL for that, right? Is it how it usually done? Or there is a better way?
ANSWER:
This can't be done an easy way. For instance, the "Unanswered" list here at stackoverflow is sorted by number of votes. So if you'd save the last ID of the page you're viewing (in a cookie, request, session, whereever) and someone upvotes a post while you're browsing page 2, page 3 isn't complete since the recently upvoted post could have been moved to page 1 or 2. Only way to do it is to load the complete list in someones session. Please don't... As already mentioned, let's hope people are used to this by now. | [
"sql",
"paging"
] | 3 | 1 | 354 | 4 | 0 | 2008-09-02T01:25:18.127000 | 2008-09-30T16:48:56.963000 |
38,691 | 38,697 | How to grab the contents of HTML tags? | Hey so what I want to do is snag the content for the first paragraph. The string $blog_post contains a lot of paragraphs in the following format: Paragraph 1 Paragraph 2 Paragraph 3 The problem I'm running into is that I am writing a regex to grab everything between the first tag and the first closing tag. However, it is grabbing the first tag and the last closing tag which results in me grabbing everything. Here is my current code: if (preg_match("/[\\s]* [\\s]*(? [\\s\\S]+)[\\s]*<\\/p>[\\s\\S]*/",$blog_post,$blog_paragraph)) echo " ". $blog_paragraph["firstparagraph"]. " "; else echo $blog_post; | Well, sysrqb will let you match anything in the first paragraph assuming there's no other html in the paragraph. You might want something more like this.*? Placing the? after your * makes it non-greedy, meaning it will only match as little text as necessary before matching the. | How to grab the contents of HTML tags? Hey so what I want to do is snag the content for the first paragraph. The string $blog_post contains a lot of paragraphs in the following format: Paragraph 1 Paragraph 2 Paragraph 3 The problem I'm running into is that I am writing a regex to grab everything between the first tag and the first closing tag. However, it is grabbing the first tag and the last closing tag which results in me grabbing everything. Here is my current code: if (preg_match("/[\\s]* [\\s]*(? [\\s\\S]+)[\\s]*<\\/p>[\\s\\S]*/",$blog_post,$blog_paragraph)) echo " ". $blog_paragraph["firstparagraph"]. " "; else echo $blog_post; | TITLE:
How to grab the contents of HTML tags?
QUESTION:
Hey so what I want to do is snag the content for the first paragraph. The string $blog_post contains a lot of paragraphs in the following format: Paragraph 1 Paragraph 2 Paragraph 3 The problem I'm running into is that I am writing a regex to grab everything between the first tag and the first closing tag. However, it is grabbing the first tag and the last closing tag which results in me grabbing everything. Here is my current code: if (preg_match("/[\\s]* [\\s]*(? [\\s\\S]+)[\\s]*<\\/p>[\\s\\S]*/",$blog_post,$blog_paragraph)) echo " ". $blog_paragraph["firstparagraph"]. " "; else echo $blog_post;
ANSWER:
Well, sysrqb will let you match anything in the first paragraph assuming there's no other html in the paragraph. You might want something more like this.*? Placing the? after your * makes it non-greedy, meaning it will only match as little text as necessary before matching the. | [
"php",
"html",
"regex",
"html-parsing"
] | 7 | 18 | 1,318 | 4 | 0 | 2008-09-02T01:41:59.537000 | 2008-09-02T01:48:04.593000 |
38,713 | 41,033 | ruby idioms for using command-line options | I'm trying to pick up ruby by porting a medium-sized (non-OO) perl program. One of my personal idioms is to set options like this: use Getopt::Std; our $opt_v; # be verbose getopts('v'); # and later... $opt_v && print "something interesting\n"; In perl, I kind of grit my teeth and let $opt_v be (effectively) a global. In ruby,the more-or-less exact equivalent would be require 'optparse' opts.on("-v", "--[no-]verbose", TrueClass, "Run verbosely") { |$opt_verbose| } opts.parse! end where $opt_verbose is a global that classes could access. Having classes know about global flags like that seems... er... wrong. What's the OO-idiomatic way of doing this? Let the main routine take care of all option-related stuff and have the classes just return things to it that it decides how to deal with? Have classes implement optional behaviour (e.g., know how to be verbose) and set a mode via an attr_writer sort of thing? updated: Thanks for the answers suggesting optparse, but I should have been clearer that it's not how to process command-line options I'm asking about, but more the relationship between command-line options that effectively set a global program state and classes that should ideally be independent of that sort of thing. | A while back I ran across this blog post (by Todd Werth) which presented a rather lengthy skeleton for command-line scripts in Ruby. His skeleton uses a hybrid approach in which the application code is encapsulated in an application class which is instantiated, then executed by calling a "run" method on the application object. This allowed the options to be stored in a class-wide instance variable so that all methods in the application object can access them without exposing them to any other objects that might be used in the script. I would lean toward using this technique, where the options are contained in one object and use either attr_writers or option parameters on method calls to pass relevant options to any additional objects. This way, any code contained in external classes can be isolated from the options themselves -- no need to worry about the naming of the variables in the main routine from within the thingy class if your options are set with a thingy.verbose=true attr_writer or thingy.process(true) call. | ruby idioms for using command-line options I'm trying to pick up ruby by porting a medium-sized (non-OO) perl program. One of my personal idioms is to set options like this: use Getopt::Std; our $opt_v; # be verbose getopts('v'); # and later... $opt_v && print "something interesting\n"; In perl, I kind of grit my teeth and let $opt_v be (effectively) a global. In ruby,the more-or-less exact equivalent would be require 'optparse' opts.on("-v", "--[no-]verbose", TrueClass, "Run verbosely") { |$opt_verbose| } opts.parse! end where $opt_verbose is a global that classes could access. Having classes know about global flags like that seems... er... wrong. What's the OO-idiomatic way of doing this? Let the main routine take care of all option-related stuff and have the classes just return things to it that it decides how to deal with? Have classes implement optional behaviour (e.g., know how to be verbose) and set a mode via an attr_writer sort of thing? updated: Thanks for the answers suggesting optparse, but I should have been clearer that it's not how to process command-line options I'm asking about, but more the relationship between command-line options that effectively set a global program state and classes that should ideally be independent of that sort of thing. | TITLE:
ruby idioms for using command-line options
QUESTION:
I'm trying to pick up ruby by porting a medium-sized (non-OO) perl program. One of my personal idioms is to set options like this: use Getopt::Std; our $opt_v; # be verbose getopts('v'); # and later... $opt_v && print "something interesting\n"; In perl, I kind of grit my teeth and let $opt_v be (effectively) a global. In ruby,the more-or-less exact equivalent would be require 'optparse' opts.on("-v", "--[no-]verbose", TrueClass, "Run verbosely") { |$opt_verbose| } opts.parse! end where $opt_verbose is a global that classes could access. Having classes know about global flags like that seems... er... wrong. What's the OO-idiomatic way of doing this? Let the main routine take care of all option-related stuff and have the classes just return things to it that it decides how to deal with? Have classes implement optional behaviour (e.g., know how to be verbose) and set a mode via an attr_writer sort of thing? updated: Thanks for the answers suggesting optparse, but I should have been clearer that it's not how to process command-line options I'm asking about, but more the relationship between command-line options that effectively set a global program state and classes that should ideally be independent of that sort of thing.
ANSWER:
A while back I ran across this blog post (by Todd Werth) which presented a rather lengthy skeleton for command-line scripts in Ruby. His skeleton uses a hybrid approach in which the application code is encapsulated in an application class which is instantiated, then executed by calling a "run" method on the application object. This allowed the options to be stored in a class-wide instance variable so that all methods in the application object can access them without exposing them to any other objects that might be used in the script. I would lean toward using this technique, where the options are contained in one object and use either attr_writers or option parameters on method calls to pass relevant options to any additional objects. This way, any code contained in external classes can be isolated from the options themselves -- no need to worry about the naming of the variables in the main routine from within the thingy class if your options are set with a thingy.verbose=true attr_writer or thingy.process(true) call. | [
"ruby",
"idioms"
] | 4 | 3 | 2,696 | 3 | 0 | 2008-09-02T02:29:06.617000 | 2008-09-03T01:41:55.677000 |
38,719 | 38,980 | What is the best way to create a wizard in C# 2.0? | I have a winforms application where users will be creating stock items, and a time of creation there are a number of different things that need to happen. I think the UI for this should probably be a wizard of some kind, but I'm unsure as to the best way to achieve this. I have seen a couple of 3rd party Wizard controls, and I have also seen manual implementations of making panel visible/invisible. What are the best ways that people have used in the past, that are easy to implement, and also make it easy to add "pages" to the wizard later on if needed? | Here are a few more resources you should check out: This DevExpress WinForms control: http://www.devexpress.com/Products/NET/Controls/WinForms/Wizard/ A home-grown wizards framework: http://weblogs.asp.net/justin_rogers/articles/60155.aspx A wizard framework by Shawn Wildermut part of the Chris Sells's Genghis framework: http://www.sellsbrothers.com/tools/genghis/ | What is the best way to create a wizard in C# 2.0? I have a winforms application where users will be creating stock items, and a time of creation there are a number of different things that need to happen. I think the UI for this should probably be a wizard of some kind, but I'm unsure as to the best way to achieve this. I have seen a couple of 3rd party Wizard controls, and I have also seen manual implementations of making panel visible/invisible. What are the best ways that people have used in the past, that are easy to implement, and also make it easy to add "pages" to the wizard later on if needed? | TITLE:
What is the best way to create a wizard in C# 2.0?
QUESTION:
I have a winforms application where users will be creating stock items, and a time of creation there are a number of different things that need to happen. I think the UI for this should probably be a wizard of some kind, but I'm unsure as to the best way to achieve this. I have seen a couple of 3rd party Wizard controls, and I have also seen manual implementations of making panel visible/invisible. What are the best ways that people have used in the past, that are easy to implement, and also make it easy to add "pages" to the wizard later on if needed?
ANSWER:
Here are a few more resources you should check out: This DevExpress WinForms control: http://www.devexpress.com/Products/NET/Controls/WinForms/Wizard/ A home-grown wizards framework: http://weblogs.asp.net/justin_rogers/articles/60155.aspx A wizard framework by Shawn Wildermut part of the Chris Sells's Genghis framework: http://www.sellsbrothers.com/tools/genghis/ | [
"c#",
"visual-studio",
"winforms",
"user-interface",
"wizard"
] | 26 | 4 | 14,699 | 5 | 0 | 2008-09-02T02:34:13.327000 | 2008-09-02T07:33:19.630000 |
38,726 | 92,670 | WebClient.DownloadFileAsync fails to raise exception | An odd issue that I have been trying to address in a project - my calls to WebClient.DownloadFileAsync seem to be getting ignored and no exceptions are being raised. So far I have been able to determine this might be due to destination folder not existing, but from the looks of the MSDN documentation for Webclient.DownloadFileAsync this should still cause an exception to be raised. I did find one MSDN forum thread that seems to imply that this has been known to happen, but there doesn't seem to be any resolution for it. Any ideas what might be going on? | This issue was resolved after reviewing MSDN and the source code involved. Previously the application was only implementing the DownloadProgressChangedEventHandler to track how much of a download remained. This turned out to be the root cause of the issue as AsyncCompletedEventHandler is what is invoked when an exception occurs and not implementing this event handler leaves you with no notification of errors. | WebClient.DownloadFileAsync fails to raise exception An odd issue that I have been trying to address in a project - my calls to WebClient.DownloadFileAsync seem to be getting ignored and no exceptions are being raised. So far I have been able to determine this might be due to destination folder not existing, but from the looks of the MSDN documentation for Webclient.DownloadFileAsync this should still cause an exception to be raised. I did find one MSDN forum thread that seems to imply that this has been known to happen, but there doesn't seem to be any resolution for it. Any ideas what might be going on? | TITLE:
WebClient.DownloadFileAsync fails to raise exception
QUESTION:
An odd issue that I have been trying to address in a project - my calls to WebClient.DownloadFileAsync seem to be getting ignored and no exceptions are being raised. So far I have been able to determine this might be due to destination folder not existing, but from the looks of the MSDN documentation for Webclient.DownloadFileAsync this should still cause an exception to be raised. I did find one MSDN forum thread that seems to imply that this has been known to happen, but there doesn't seem to be any resolution for it. Any ideas what might be going on?
ANSWER:
This issue was resolved after reviewing MSDN and the source code involved. Previously the application was only implementing the DownloadProgressChangedEventHandler to track how much of a download remained. This turned out to be the root cause of the issue as AsyncCompletedEventHandler is what is invoked when an exception occurs and not implementing this event handler leaves you with no notification of errors. | [
".net",
"webclient"
] | 2 | 2 | 3,769 | 2 | 0 | 2008-09-02T02:38:15.657000 | 2008-09-18T13:47:02.357000 |
38,729 | 38,737 | Do you know how to implement transactions in Castle ActiveRecord? | I decided to make a system for a client using Castle ActiveRecord, everything went well until I found that the transactions do not work, for instance; TransactionScope t = new TransactionScope();
try { member.Save();
//This is just to see transaction working throw new Exception("Exception");
foreach (qfh.Beneficiary b1 in l) { b1.Create(); }
} catch (Exception ex) {
t.VoteRollBack(); MessageBox.Show(ex.Message); } finally { t.Dispose(); } But it doesn't work, I throw an Exception just to try the transaction rolls back, but for my surprise I see that the first [Save] records into the database. What is happening? I'm new on Castle and NHibernate, firstly I saw it very attractive and I decided to go on with it and MySQL (I've never worked with this DB), I tried ActiveWriter and it seemed very promising but after a long and effortly week I see this issue and now I feel like I'm stuck and like I've wasted my time. It is supposed to be easy but right now I'm feeling a frustated cause I cannot find enough information to make this workout, can you help me? | Ben's got it. That doc is a little confusing. Refer to the last block on the page, "Nested transactions". | Do you know how to implement transactions in Castle ActiveRecord? I decided to make a system for a client using Castle ActiveRecord, everything went well until I found that the transactions do not work, for instance; TransactionScope t = new TransactionScope();
try { member.Save();
//This is just to see transaction working throw new Exception("Exception");
foreach (qfh.Beneficiary b1 in l) { b1.Create(); }
} catch (Exception ex) {
t.VoteRollBack(); MessageBox.Show(ex.Message); } finally { t.Dispose(); } But it doesn't work, I throw an Exception just to try the transaction rolls back, but for my surprise I see that the first [Save] records into the database. What is happening? I'm new on Castle and NHibernate, firstly I saw it very attractive and I decided to go on with it and MySQL (I've never worked with this DB), I tried ActiveWriter and it seemed very promising but after a long and effortly week I see this issue and now I feel like I'm stuck and like I've wasted my time. It is supposed to be easy but right now I'm feeling a frustated cause I cannot find enough information to make this workout, can you help me? | TITLE:
Do you know how to implement transactions in Castle ActiveRecord?
QUESTION:
I decided to make a system for a client using Castle ActiveRecord, everything went well until I found that the transactions do not work, for instance; TransactionScope t = new TransactionScope();
try { member.Save();
//This is just to see transaction working throw new Exception("Exception");
foreach (qfh.Beneficiary b1 in l) { b1.Create(); }
} catch (Exception ex) {
t.VoteRollBack(); MessageBox.Show(ex.Message); } finally { t.Dispose(); } But it doesn't work, I throw an Exception just to try the transaction rolls back, but for my surprise I see that the first [Save] records into the database. What is happening? I'm new on Castle and NHibernate, firstly I saw it very attractive and I decided to go on with it and MySQL (I've never worked with this DB), I tried ActiveWriter and it seemed very promising but after a long and effortly week I see this issue and now I feel like I'm stuck and like I've wasted my time. It is supposed to be easy but right now I'm feeling a frustated cause I cannot find enough information to make this workout, can you help me?
ANSWER:
Ben's got it. That doc is a little confusing. Refer to the last block on the page, "Nested transactions". | [
"activerecord",
"castle"
] | 4 | 3 | 2,887 | 3 | 0 | 2008-09-02T02:40:47.820000 | 2008-09-02T02:49:15.133000 |
38,746 | 40,919 | How to detect file ends in newline? | Over at Can you modify text files when committing to subversion? Grant suggested that I block commits instead. However I don't know how to check a file ends with a newline. How can you detect that the file ends with a newline? | @Konrad: tail does not return an empty line. I made a file that has some text that doesn't end in newline and a file that does. Here is the output from tail: $ cat test_no_newline.txt this file doesn't end in newline$
$ cat test_with_newline.txt this file ends in newline $ Though I found that tail has get last byte option. So I modified your script to: #!/bin/sh c=`tail -c 1 $1` if [ "$c"!= "" ]; then echo "no newline" fi | How to detect file ends in newline? Over at Can you modify text files when committing to subversion? Grant suggested that I block commits instead. However I don't know how to check a file ends with a newline. How can you detect that the file ends with a newline? | TITLE:
How to detect file ends in newline?
QUESTION:
Over at Can you modify text files when committing to subversion? Grant suggested that I block commits instead. However I don't know how to check a file ends with a newline. How can you detect that the file ends with a newline?
ANSWER:
@Konrad: tail does not return an empty line. I made a file that has some text that doesn't end in newline and a file that does. Here is the output from tail: $ cat test_no_newline.txt this file doesn't end in newline$
$ cat test_with_newline.txt this file ends in newline $ Though I found that tail has get last byte option. So I modified your script to: #!/bin/sh c=`tail -c 1 $1` if [ "$c"!= "" ]; then echo "no newline" fi | [
"svn",
"bash",
"text-files"
] | 31 | 23 | 28,332 | 10 | 0 | 2008-09-02T02:58:03.613000 | 2008-09-02T23:35:22.377000 |
38,756 | 38,765 | Concurrent collections in C# | I'm looking for a way of getting a concurrent collection in C# or at least a collection which supports a concurrent enumerator. Right now I'm getting an InvalidOperationException when the collection over which I'm iterating changes. I could just deep copy the collection and work with a private copy but I'm wondering if there is perhaps a better way Code snippet: foreach (String s in (List ) callingForm.Invoke(callingForm.delegateGetKillStrings)) { //do some jazz } --edit-- I took the answer but also found that I needed to ensure that the code which was writing to the collection needed to attempt to get a lock as well. private void addKillString(String s) { lock (killStrings) { killStrings.Add(s); } } | Other than doing a deep-copy your best bet might be to lock the collection: List theList = (List )callingForm.Invoke(callingForm.delegateGetKillStrings); lock(theList.SyncRoot) { foreach(string s in theList) { // Do some Jazz } } | Concurrent collections in C# I'm looking for a way of getting a concurrent collection in C# or at least a collection which supports a concurrent enumerator. Right now I'm getting an InvalidOperationException when the collection over which I'm iterating changes. I could just deep copy the collection and work with a private copy but I'm wondering if there is perhaps a better way Code snippet: foreach (String s in (List ) callingForm.Invoke(callingForm.delegateGetKillStrings)) { //do some jazz } --edit-- I took the answer but also found that I needed to ensure that the code which was writing to the collection needed to attempt to get a lock as well. private void addKillString(String s) { lock (killStrings) { killStrings.Add(s); } } | TITLE:
Concurrent collections in C#
QUESTION:
I'm looking for a way of getting a concurrent collection in C# or at least a collection which supports a concurrent enumerator. Right now I'm getting an InvalidOperationException when the collection over which I'm iterating changes. I could just deep copy the collection and work with a private copy but I'm wondering if there is perhaps a better way Code snippet: foreach (String s in (List ) callingForm.Invoke(callingForm.delegateGetKillStrings)) { //do some jazz } --edit-- I took the answer but also found that I needed to ensure that the code which was writing to the collection needed to attempt to get a lock as well. private void addKillString(String s) { lock (killStrings) { killStrings.Add(s); } }
ANSWER:
Other than doing a deep-copy your best bet might be to lock the collection: List theList = (List )callingForm.Invoke(callingForm.delegateGetKillStrings); lock(theList.SyncRoot) { foreach(string s in theList) { // Do some Jazz } } | [
"c#",
"concurrency"
] | 3 | 5 | 9,056 | 3 | 0 | 2008-09-02T03:09:38.517000 | 2008-09-02T03:25:49.087000 |
38,763 | 38,802 | What design pattern is PEAR DB_DataObject implementing? | DB_DataObject does not appear to be ActiveRecord because you do not necessarily store business logic in the "table" classes. It seems more like Table Data Gateway or Row Data Gateway, but I really cannot tell. What I need is good ORM layer that we can use with DataMapper and a DomainModel. Any ideas? | Follow this link to read what DB_DO is. In a nutshell, it doesn't implement a specific pattern, it just aims to provide a common interface. The idea is to not rebuild the same basic code in each project. As for an ORM, I'd recommend Doctrine. It implements ActiveRecord. | What design pattern is PEAR DB_DataObject implementing? DB_DataObject does not appear to be ActiveRecord because you do not necessarily store business logic in the "table" classes. It seems more like Table Data Gateway or Row Data Gateway, but I really cannot tell. What I need is good ORM layer that we can use with DataMapper and a DomainModel. Any ideas? | TITLE:
What design pattern is PEAR DB_DataObject implementing?
QUESTION:
DB_DataObject does not appear to be ActiveRecord because you do not necessarily store business logic in the "table" classes. It seems more like Table Data Gateway or Row Data Gateway, but I really cannot tell. What I need is good ORM layer that we can use with DataMapper and a DomainModel. Any ideas?
ANSWER:
Follow this link to read what DB_DO is. In a nutshell, it doesn't implement a specific pattern, it just aims to provide a common interface. The idea is to not rebuild the same basic code in each project. As for an ORM, I'd recommend Doctrine. It implements ActiveRecord. | [
"php",
"database",
"design-patterns",
"pear"
] | 2 | 2 | 722 | 2 | 0 | 2008-09-02T03:24:33.720000 | 2008-09-02T04:12:00.427000 |
38,766 | 38,909 | How do I use a different database connection for package configuration? | I have an SSIS Package that sets some variable data from a SQL Server Package Configuration Table. (Selecting the "Specify configuration setings directly" option) This works well when I'm using the Database connection that I specified when developing the package. However when I run it on a server (64 bit) in the testing environment (either as an Agent job or running the package directly) and I Specify the new connection string in the Connection managers, the package still reads the settings from the DB server that I specified in development. All the other Connections take up the correct connection strings, it only seems to be the Package Configuration that reads from the wrong place. Any ideas or am I doing something really wrong? | The only way I was able to do this was to use Windows Environment Variables. You can specify things like connection strings and user preferences in environment variables, and then pick up those environment variables from your SSIS Task. | How do I use a different database connection for package configuration? I have an SSIS Package that sets some variable data from a SQL Server Package Configuration Table. (Selecting the "Specify configuration setings directly" option) This works well when I'm using the Database connection that I specified when developing the package. However when I run it on a server (64 bit) in the testing environment (either as an Agent job or running the package directly) and I Specify the new connection string in the Connection managers, the package still reads the settings from the DB server that I specified in development. All the other Connections take up the correct connection strings, it only seems to be the Package Configuration that reads from the wrong place. Any ideas or am I doing something really wrong? | TITLE:
How do I use a different database connection for package configuration?
QUESTION:
I have an SSIS Package that sets some variable data from a SQL Server Package Configuration Table. (Selecting the "Specify configuration setings directly" option) This works well when I'm using the Database connection that I specified when developing the package. However when I run it on a server (64 bit) in the testing environment (either as an Agent job or running the package directly) and I Specify the new connection string in the Connection managers, the package still reads the settings from the DB server that I specified in development. All the other Connections take up the correct connection strings, it only seems to be the Package Configuration that reads from the wrong place. Any ideas or am I doing something really wrong?
ANSWER:
The only way I was able to do this was to use Windows Environment Variables. You can specify things like connection strings and user preferences in environment variables, and then pick up those environment variables from your SSIS Task. | [
"sql-server",
"ssis"
] | 2 | 1 | 6,024 | 9 | 0 | 2008-09-02T03:26:09.100000 | 2008-09-02T05:49:34.997000 |
38,769 | 208,639 | How would you extract data from a MS Project .mpp file? | I need to extract data from a.mpp file on the network and combine it with other data from several different databases. The application can be written in Perl, VB6, VB.net or C# but must be easily scheduled from a Windows based server. What would you recommend to extract the MS Project data with no user intervention? Is there any ODBC drivers available for MS Project? Are there any modules (for Perl, VB, VB.net or C#) for opening a.mpp and reading activity data? | I would recommend using MPXJ ( mpxj.sf.net ) to extract data from Microsoft Project files. Don't be put off by the fact that it was originally a Java library - the current release of MPXJ includes native.net dlls as well as the original Java JAR file, thanks to the magic of IKVM. Disclaimer: I maintain MPXJ. | How would you extract data from a MS Project .mpp file? I need to extract data from a.mpp file on the network and combine it with other data from several different databases. The application can be written in Perl, VB6, VB.net or C# but must be easily scheduled from a Windows based server. What would you recommend to extract the MS Project data with no user intervention? Is there any ODBC drivers available for MS Project? Are there any modules (for Perl, VB, VB.net or C#) for opening a.mpp and reading activity data? | TITLE:
How would you extract data from a MS Project .mpp file?
QUESTION:
I need to extract data from a.mpp file on the network and combine it with other data from several different databases. The application can be written in Perl, VB6, VB.net or C# but must be easily scheduled from a Windows based server. What would you recommend to extract the MS Project data with no user intervention? Is there any ODBC drivers available for MS Project? Are there any modules (for Perl, VB, VB.net or C#) for opening a.mpp and reading activity data?
ANSWER:
I would recommend using MPXJ ( mpxj.sf.net ) to extract data from Microsoft Project files. Don't be put off by the fact that it was originally a Java library - the current release of MPXJ includes native.net dlls as well as the original Java JAR file, thanks to the magic of IKVM. Disclaimer: I maintain MPXJ. | [
"c#",
"vb.net",
"perl",
"vb6",
"project-management"
] | 5 | 4 | 17,837 | 5 | 0 | 2008-09-02T03:29:57.140000 | 2008-10-16T13:49:23.610000 |
38,779 | 40,472 | What SPN do I need to set for a net.tcp service? | I have a wcf application hosted in a windows service running a local windows account. Do I need to set an SPN for this account? If so, what's the protocol the SPN needs to be set under? I know how to do this for services over HTTP, but have never done it for net.tcp. | By default (i.e. out of the box) net.tcp services are unsecured and don't perform any authentication at all. So you won't need (and in fact can't) set a service principal name. If you need to authenticate, then check the net.tcp security modes on MSDN. The best way to understand the different combinations is to experiment! | What SPN do I need to set for a net.tcp service? I have a wcf application hosted in a windows service running a local windows account. Do I need to set an SPN for this account? If so, what's the protocol the SPN needs to be set under? I know how to do this for services over HTTP, but have never done it for net.tcp. | TITLE:
What SPN do I need to set for a net.tcp service?
QUESTION:
I have a wcf application hosted in a windows service running a local windows account. Do I need to set an SPN for this account? If so, what's the protocol the SPN needs to be set under? I know how to do this for services over HTTP, but have never done it for net.tcp.
ANSWER:
By default (i.e. out of the box) net.tcp services are unsecured and don't perform any authentication at all. So you won't need (and in fact can't) set a service principal name. If you need to authenticate, then check the net.tcp security modes on MSDN. The best way to understand the different combinations is to experiment! | [
"wcf",
"security",
"spn"
] | 6 | 3 | 6,282 | 2 | 0 | 2008-09-02T03:41:06.880000 | 2008-09-02T20:12:02.473000 |
38,789 | 38,792 | Web Service Namespace Dynamic Naming | I have a web-service that I will be deploying to dev, staging and production. Along with this will be an ASP.net application that will be deploying separately but also in those three stages. What is the most pragmatic way to change the following line in the web-service to match the current environment? [WebService(Namespace = "http://dev.mycompany.com/MyAppsWebService")] [WebService(Namespace = "http://stage.mycompany.com/MyAppsWebService")] [WebService(Namespace = "http://mycompany.com/MyAppsWebService")] | Your webservice object has a "URL" property on it which can be set via the web.config file. There's a config file that gets created when you add the web reference to your application that you should copy the contents of to your web.config or app.config file. You can then deploy the config file and not have to manage any code changes to accomodate the change in url. | Web Service Namespace Dynamic Naming I have a web-service that I will be deploying to dev, staging and production. Along with this will be an ASP.net application that will be deploying separately but also in those three stages. What is the most pragmatic way to change the following line in the web-service to match the current environment? [WebService(Namespace = "http://dev.mycompany.com/MyAppsWebService")] [WebService(Namespace = "http://stage.mycompany.com/MyAppsWebService")] [WebService(Namespace = "http://mycompany.com/MyAppsWebService")] | TITLE:
Web Service Namespace Dynamic Naming
QUESTION:
I have a web-service that I will be deploying to dev, staging and production. Along with this will be an ASP.net application that will be deploying separately but also in those three stages. What is the most pragmatic way to change the following line in the web-service to match the current environment? [WebService(Namespace = "http://dev.mycompany.com/MyAppsWebService")] [WebService(Namespace = "http://stage.mycompany.com/MyAppsWebService")] [WebService(Namespace = "http://mycompany.com/MyAppsWebService")]
ANSWER:
Your webservice object has a "URL" property on it which can be set via the web.config file. There's a config file that gets created when you add the web reference to your application that you should copy the contents of to your web.config or app.config file. You can then deploy the config file and not have to manage any code changes to accomodate the change in url. | [
"c#",
"asp.net",
"web-services"
] | 4 | 2 | 4,406 | 1 | 0 | 2008-09-02T03:59:44.417000 | 2008-09-02T04:02:40.307000 |
38,791 | 38,793 | Which database table Schema is more efficient? | Which Database table Schema is more efficient and why? "Users (UserID, UserName, CompamyId)" "Companies (CompamyId, CompanyName)" OR "Users (UserID, UserName)" "Companies (CompamyId, CompanyName)" "UserCompanies (UserID, CompamyId)" Given the fact that user and company have one-to-one relation. | For sure, the earlier one is more efficient given that constraint. For getting the same information, you will have less number of joins in your queries. | Which database table Schema is more efficient? Which Database table Schema is more efficient and why? "Users (UserID, UserName, CompamyId)" "Companies (CompamyId, CompanyName)" OR "Users (UserID, UserName)" "Companies (CompamyId, CompanyName)" "UserCompanies (UserID, CompamyId)" Given the fact that user and company have one-to-one relation. | TITLE:
Which database table Schema is more efficient?
QUESTION:
Which Database table Schema is more efficient and why? "Users (UserID, UserName, CompamyId)" "Companies (CompamyId, CompanyName)" OR "Users (UserID, UserName)" "Companies (CompamyId, CompanyName)" "UserCompanies (UserID, CompamyId)" Given the fact that user and company have one-to-one relation.
ANSWER:
For sure, the earlier one is more efficient given that constraint. For getting the same information, you will have less number of joins in your queries. | [
"database-design"
] | 4 | 6 | 2,483 | 6 | 0 | 2008-09-02T04:01:09.827000 | 2008-09-02T04:05:56.213000 |
38,801 | 48,298 | SQL - How to store and navigate hierarchies? | What are the ways that you use to model and retrieve hierarchical info in a database? | The definitive pieces on this subject have been written by Joe Celko, and he has worked a number of them into a book called Joe Celko's Trees and Hierarchies in SQL for Smarties. He favours a technique called directed graphs. An introduction to his work on this subject can be found here | SQL - How to store and navigate hierarchies? What are the ways that you use to model and retrieve hierarchical info in a database? | TITLE:
SQL - How to store and navigate hierarchies?
QUESTION:
What are the ways that you use to model and retrieve hierarchical info in a database?
ANSWER:
The definitive pieces on this subject have been written by Joe Celko, and he has worked a number of them into a book called Joe Celko's Trees and Hierarchies in SQL for Smarties. He favours a technique called directed graphs. An introduction to his work on this subject can be found here | [
"sql",
"sql-server",
"oracle",
"database-design",
"hierarchy"
] | 48 | 15 | 28,274 | 9 | 0 | 2008-09-02T04:10:50.413000 | 2008-09-07T10:33:21.527000 |
38,820 | 38,829 | Which class design is better? | Which class design is better and why? public class User { public String UserName; public String Password; public String FirstName; public String LastName; }
public class Employee: User { public String EmployeeId; public String EmployeeCode; public String DepartmentId; }
public class Member: User { public String MemberId; public String JoinDate; public String ExpiryDate; } OR public class User { public String UserId; public String UserName; public String Password; public String FirstName; public String LastName; }
public class Employee { public User UserInfo; public String EmployeeId; public String EmployeeCode; public String DepartmentId; }
public class Member { public User UserInfo; public String MemberId; public String JoinDate; public String ExpiryDate; } | The question is simply answered by recognising that inheritance models an "IS-A" relationship, while membership models a "HAS-A" relationship. An employee IS A user An employee HAS A userinfo Which one is correct? This is your answer. | Which class design is better? Which class design is better and why? public class User { public String UserName; public String Password; public String FirstName; public String LastName; }
public class Employee: User { public String EmployeeId; public String EmployeeCode; public String DepartmentId; }
public class Member: User { public String MemberId; public String JoinDate; public String ExpiryDate; } OR public class User { public String UserId; public String UserName; public String Password; public String FirstName; public String LastName; }
public class Employee { public User UserInfo; public String EmployeeId; public String EmployeeCode; public String DepartmentId; }
public class Member { public User UserInfo; public String MemberId; public String JoinDate; public String ExpiryDate; } | TITLE:
Which class design is better?
QUESTION:
Which class design is better and why? public class User { public String UserName; public String Password; public String FirstName; public String LastName; }
public class Employee: User { public String EmployeeId; public String EmployeeCode; public String DepartmentId; }
public class Member: User { public String MemberId; public String JoinDate; public String ExpiryDate; } OR public class User { public String UserId; public String UserName; public String Password; public String FirstName; public String LastName; }
public class Employee { public User UserInfo; public String EmployeeId; public String EmployeeCode; public String DepartmentId; }
public class Member { public User UserInfo; public String MemberId; public String JoinDate; public String ExpiryDate; }
ANSWER:
The question is simply answered by recognising that inheritance models an "IS-A" relationship, while membership models a "HAS-A" relationship. An employee IS A user An employee HAS A userinfo Which one is correct? This is your answer. | [
"oop",
"class-design"
] | 46 | 63 | 16,483 | 11 | 0 | 2008-09-02T04:34:20.963000 | 2008-09-02T04:41:11.573000 |
38,822 | 49,780 | Best full text search alternative to MS SQL, C++ solution | What is the best full text search alternative to Microsoft SQL? (which works with MS SQL) I'm looking for something similar to Lucene and Lucene.NET but without the.NET and Java requirements. I would also like to find a solution that is usable in commercial applications. | Take a look at CLucene - It's a well maintained C++ port of java Lucene. It's currently licenced under LGPL and we use it in our commercial application. Performance is incredible, however you do have to get your head around some of the strange API conventions. | Best full text search alternative to MS SQL, C++ solution What is the best full text search alternative to Microsoft SQL? (which works with MS SQL) I'm looking for something similar to Lucene and Lucene.NET but without the.NET and Java requirements. I would also like to find a solution that is usable in commercial applications. | TITLE:
Best full text search alternative to MS SQL, C++ solution
QUESTION:
What is the best full text search alternative to Microsoft SQL? (which works with MS SQL) I'm looking for something similar to Lucene and Lucene.NET but without the.NET and Java requirements. I would also like to find a solution that is usable in commercial applications.
ANSWER:
Take a look at CLucene - It's a well maintained C++ port of java Lucene. It's currently licenced under LGPL and we use it in our commercial application. Performance is incredible, however you do have to get your head around some of the strange API conventions. | [
"c++",
"sql-server",
"full-text-search",
"lucene",
"lucene.net"
] | 4 | 3 | 4,430 | 5 | 0 | 2008-09-02T04:36:54.623000 | 2008-09-08T14:13:20.957000 |
38,824 | 38,851 | Is Wiki Content Portable? | I'm thinking of starting a wiki, probably on a low cost LAMP hosting account. I'd like the option of exporting my content later in case I want to run it on IIS/ASP.NET down the line. I know in the weblog world, there's an open standard called BlogML which will let you export your blog content to an XML based format on one site and import it into another. Is there something similar with wikis? | The correct answer is... "it depends". It depends on which wiki you're using or planning to use. I've used various over the years MoinMoin was ok, used files rather than database, Ubuntu seem to like it. MediaWiki, everyone knows about and JAMWiki is a java clone(ish) of MediaWiki with the aim to be markup compatible with MediaWiki, both use databases and you can generally connect whichever database you want, JAMWiki is pre-configured to use an internal HSQLDB instance. I recently converted about 80 pages from a MoinMoin wiki into JAMWiki pages and this was probably 90% handled by a tiny perl script I found somewhere (I'll provide a link if I can find it again). The other 10% was unfortunately a by-hand experience (they were of the utmost importance with them being recipies for the missus);-) I also recently setup a Mediawiki instance for work and that took all of about 8 minutes to do. So that'd be my choice. | Is Wiki Content Portable? I'm thinking of starting a wiki, probably on a low cost LAMP hosting account. I'd like the option of exporting my content later in case I want to run it on IIS/ASP.NET down the line. I know in the weblog world, there's an open standard called BlogML which will let you export your blog content to an XML based format on one site and import it into another. Is there something similar with wikis? | TITLE:
Is Wiki Content Portable?
QUESTION:
I'm thinking of starting a wiki, probably on a low cost LAMP hosting account. I'd like the option of exporting my content later in case I want to run it on IIS/ASP.NET down the line. I know in the weblog world, there's an open standard called BlogML which will let you export your blog content to an XML based format on one site and import it into another. Is there something similar with wikis?
ANSWER:
The correct answer is... "it depends". It depends on which wiki you're using or planning to use. I've used various over the years MoinMoin was ok, used files rather than database, Ubuntu seem to like it. MediaWiki, everyone knows about and JAMWiki is a java clone(ish) of MediaWiki with the aim to be markup compatible with MediaWiki, both use databases and you can generally connect whichever database you want, JAMWiki is pre-configured to use an internal HSQLDB instance. I recently converted about 80 pages from a MoinMoin wiki into JAMWiki pages and this was probably 90% handled by a tiny perl script I found somewhere (I'll provide a link if I can find it again). The other 10% was unfortunately a by-hand experience (they were of the utmost importance with them being recipies for the missus);-) I also recently setup a Mediawiki instance for work and that took all of about 8 minutes to do. So that'd be my choice. | [
"asp.net",
"iis",
"wiki"
] | 7 | 6 | 1,181 | 3 | 0 | 2008-09-02T04:38:06.430000 | 2008-09-02T05:03:06.653000 |
38,842 | 42,760 | How to do a simple mail merge in OpenOffice | I need to do a simple mail merge in OpenOffice using C++, VBScript, VB.Net or C# via OLE or native API. Are there any good examples available? | I haven't come up with a solution I'm really happy with but here are some notes: Q. What is the OO API for mail merge? A. http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html Q. What support groups? A. http://user.services.openoffice.org/en/forum/viewforum.php?f=20 Q. Sample code? A. http://user.services.openoffice.org/en/forum/viewtopic.php?f=20&t=946&p=3778&hilit=mail+merge#p3778 http://user.services.openoffice.org/en/forum/viewtopic.php?f=20&t=8088&p=38017&hilit=mail+merge#p38017 Q. Any more examples? A. file:///C:/Program%20Files/OpenOffice.org_2.4_SDK/examples/examples.html (comes with the SDK) http://www.oooforum.org/forum/viewtopic.phtml?p=94970 Q. How do I build the examples? A. e.g., for WriterDemo (C:\Program Files\OpenOffice.org_2.4_SDK\examples\CLI\VB.NET\WriterDemo) Add references to everything in here: C:\Program Files\OpenOffice.org 2.4\program\assembly That is cli_basetypes, cli_cppuhelper, cli_types, cli_ure Q. Does OO use the same separate data/document file for mail merge? A. It allows for a range of data sources including csv files Q. Does OO allow you to merge to all the different types (fax, email, new document printer)? A. You can merge to a new document, print and email Q. Can you add custom fields? A. Yes Q. How do you create a new document in VB.Net? A. Dim xContext As XComponentContext
xContext = Bootstrap.bootstrap()
Dim xFactory As XMultiServiceFactory xFactory = DirectCast(xContext.getServiceManager(), _ XMultiServiceFactory)
'Create the Desktop Dim xDesktop As unoidl.com.sun.star.frame.XDesktop xDesktop = DirectCast(xFactory.createInstance("com.sun.star.frame.Desktop"), _ unoidl.com.sun.star.frame.XDesktop)
'Open a new empty writer document Dim xComponentLoader As unoidl.com.sun.star.frame.XComponentLoader xComponentLoader = DirectCast(xDesktop, unoidl.com.sun.star.frame.XComponentLoader) Dim arProps() As unoidl.com.sun.star.beans.PropertyValue = _ New unoidl.com.sun.star.beans.PropertyValue() {} Dim xComponent As unoidl.com.sun.star.lang.XComponent xComponent = xComponentLoader.loadComponentFromURL( _ "private:factory/swriter", "_blank", 0, arProps) Dim xTextDocument As unoidl.com.sun.star.text.XTextDocument xTextDocument = DirectCast(xComponent, unoidl.com.sun.star.text.XTextDocument) Q. How do you save the document? A. Dim storer As unoidl.com.sun.star.frame.XStorable = DirectCast(xTextDocument, unoidl.com.sun.star.frame.XStorable) arProps = New unoidl.com.sun.star.beans.PropertyValue() {} storer.storeToURL("file:///C:/Users/me/Desktop/OpenOffice Investigation/saved doc.odt", arProps) Q. How do you Open the document? A. Dim xComponent As unoidl.com.sun.star.lang.XComponent xComponent = xComponentLoader.loadComponentFromURL( _ "file:///C:/Users/me/Desktop/OpenOffice Investigation/saved doc.odt", "_blank", 0, arProps) Q. How do you initiate a mail merge in VB.Net? A. Don't know. This functionality is in the API reference but is missing from the IDL. We may be slightly screwed. Assuming the API was working, it looks like running a merge is fairly simple. In VBScript: Set objServiceManager = WScript.CreateObject("com.sun.star.ServiceManager") 'Now set up a new MailMerge using the settings extracted from that doc Set oMailMerge = objServiceManager.createInstance("com.sun.star.text.MailMerge") oMailMerge.DocumentURL = "file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt" oMailMerge.DataSourceName = "adds" oMailMerge.CommandType = 0 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#CommandType oMailMerge.Command = "adds" oMailMerge.OutputType = 2 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#OutputType oMailMerge.execute(Array()) In VB.Net (Option Strict Off) Dim t_OOo As Type t_OOo = Type.GetTypeFromProgID("com.sun.star.ServiceManager") Dim objServiceManager As Object objServiceManager = System.Activator.CreateInstance(t_OOo)
Dim oMailMerge As Object oMailMerge = t_OOo.InvokeMember("createInstance", _ BindingFlags.InvokeMethod, Nothing, _ objServiceManager, New [Object]() {"com.sun.star.text.MailMerge"})
'Now set up a new MailMerge using the settings extracted from that doc oMailMerge.DocumentURL = "file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt" oMailMerge.DataSourceName = "adds" oMailMerge.CommandType = 0 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#CommandType oMailMerge.Command = "adds" oMailMerge.OutputType = 2 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#OutputType oMailMerge.execute(New [Object]() {}) The same thing but with Option Strict On (doesn't work) Dim t_OOo As Type t_OOo = Type.GetTypeFromProgID("com.sun.star.ServiceManager") Dim objServiceManager As Object objServiceManager = System.Activator.CreateInstance(t_OOo)
Dim oMailMerge As Object oMailMerge = t_OOo.InvokeMember("createInstance", _ BindingFlags.InvokeMethod, Nothing, _ objServiceManager, New [Object]() {"com.sun.star.text.MailMerge"})
'Now set up a new MailMerge using the settings extracted from that doc oMailMerge.GetType().InvokeMember("DocumentURL", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {"file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt"}) oMailMerge.GetType().InvokeMember("DataSourceName", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {"adds"}) oMailMerge.GetType().InvokeMember("CommandType", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {0}) oMailMerge.GetType().InvokeMember("Command", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {"adds"}) oMailMerge.GetType().InvokeMember("OutputType", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {2}) oMailMerge.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod Or BindingFlags.IgnoreReturn, Nothing, oMailMerge, New [Object]() {}) ' this line fails with a type mismatch error | How to do a simple mail merge in OpenOffice I need to do a simple mail merge in OpenOffice using C++, VBScript, VB.Net or C# via OLE or native API. Are there any good examples available? | TITLE:
How to do a simple mail merge in OpenOffice
QUESTION:
I need to do a simple mail merge in OpenOffice using C++, VBScript, VB.Net or C# via OLE or native API. Are there any good examples available?
ANSWER:
I haven't come up with a solution I'm really happy with but here are some notes: Q. What is the OO API for mail merge? A. http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html Q. What support groups? A. http://user.services.openoffice.org/en/forum/viewforum.php?f=20 Q. Sample code? A. http://user.services.openoffice.org/en/forum/viewtopic.php?f=20&t=946&p=3778&hilit=mail+merge#p3778 http://user.services.openoffice.org/en/forum/viewtopic.php?f=20&t=8088&p=38017&hilit=mail+merge#p38017 Q. Any more examples? A. file:///C:/Program%20Files/OpenOffice.org_2.4_SDK/examples/examples.html (comes with the SDK) http://www.oooforum.org/forum/viewtopic.phtml?p=94970 Q. How do I build the examples? A. e.g., for WriterDemo (C:\Program Files\OpenOffice.org_2.4_SDK\examples\CLI\VB.NET\WriterDemo) Add references to everything in here: C:\Program Files\OpenOffice.org 2.4\program\assembly That is cli_basetypes, cli_cppuhelper, cli_types, cli_ure Q. Does OO use the same separate data/document file for mail merge? A. It allows for a range of data sources including csv files Q. Does OO allow you to merge to all the different types (fax, email, new document printer)? A. You can merge to a new document, print and email Q. Can you add custom fields? A. Yes Q. How do you create a new document in VB.Net? A. Dim xContext As XComponentContext
xContext = Bootstrap.bootstrap()
Dim xFactory As XMultiServiceFactory xFactory = DirectCast(xContext.getServiceManager(), _ XMultiServiceFactory)
'Create the Desktop Dim xDesktop As unoidl.com.sun.star.frame.XDesktop xDesktop = DirectCast(xFactory.createInstance("com.sun.star.frame.Desktop"), _ unoidl.com.sun.star.frame.XDesktop)
'Open a new empty writer document Dim xComponentLoader As unoidl.com.sun.star.frame.XComponentLoader xComponentLoader = DirectCast(xDesktop, unoidl.com.sun.star.frame.XComponentLoader) Dim arProps() As unoidl.com.sun.star.beans.PropertyValue = _ New unoidl.com.sun.star.beans.PropertyValue() {} Dim xComponent As unoidl.com.sun.star.lang.XComponent xComponent = xComponentLoader.loadComponentFromURL( _ "private:factory/swriter", "_blank", 0, arProps) Dim xTextDocument As unoidl.com.sun.star.text.XTextDocument xTextDocument = DirectCast(xComponent, unoidl.com.sun.star.text.XTextDocument) Q. How do you save the document? A. Dim storer As unoidl.com.sun.star.frame.XStorable = DirectCast(xTextDocument, unoidl.com.sun.star.frame.XStorable) arProps = New unoidl.com.sun.star.beans.PropertyValue() {} storer.storeToURL("file:///C:/Users/me/Desktop/OpenOffice Investigation/saved doc.odt", arProps) Q. How do you Open the document? A. Dim xComponent As unoidl.com.sun.star.lang.XComponent xComponent = xComponentLoader.loadComponentFromURL( _ "file:///C:/Users/me/Desktop/OpenOffice Investigation/saved doc.odt", "_blank", 0, arProps) Q. How do you initiate a mail merge in VB.Net? A. Don't know. This functionality is in the API reference but is missing from the IDL. We may be slightly screwed. Assuming the API was working, it looks like running a merge is fairly simple. In VBScript: Set objServiceManager = WScript.CreateObject("com.sun.star.ServiceManager") 'Now set up a new MailMerge using the settings extracted from that doc Set oMailMerge = objServiceManager.createInstance("com.sun.star.text.MailMerge") oMailMerge.DocumentURL = "file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt" oMailMerge.DataSourceName = "adds" oMailMerge.CommandType = 0 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#CommandType oMailMerge.Command = "adds" oMailMerge.OutputType = 2 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#OutputType oMailMerge.execute(Array()) In VB.Net (Option Strict Off) Dim t_OOo As Type t_OOo = Type.GetTypeFromProgID("com.sun.star.ServiceManager") Dim objServiceManager As Object objServiceManager = System.Activator.CreateInstance(t_OOo)
Dim oMailMerge As Object oMailMerge = t_OOo.InvokeMember("createInstance", _ BindingFlags.InvokeMethod, Nothing, _ objServiceManager, New [Object]() {"com.sun.star.text.MailMerge"})
'Now set up a new MailMerge using the settings extracted from that doc oMailMerge.DocumentURL = "file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt" oMailMerge.DataSourceName = "adds" oMailMerge.CommandType = 0 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#CommandType oMailMerge.Command = "adds" oMailMerge.OutputType = 2 ' http://api.openoffice.org/docs/common/ref/com/sun/star/text/MailMerge.html#OutputType oMailMerge.execute(New [Object]() {}) The same thing but with Option Strict On (doesn't work) Dim t_OOo As Type t_OOo = Type.GetTypeFromProgID("com.sun.star.ServiceManager") Dim objServiceManager As Object objServiceManager = System.Activator.CreateInstance(t_OOo)
Dim oMailMerge As Object oMailMerge = t_OOo.InvokeMember("createInstance", _ BindingFlags.InvokeMethod, Nothing, _ objServiceManager, New [Object]() {"com.sun.star.text.MailMerge"})
'Now set up a new MailMerge using the settings extracted from that doc oMailMerge.GetType().InvokeMember("DocumentURL", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {"file:///C:/Users/me/Desktop/OpenOffice Investigation/mail merged.odt"}) oMailMerge.GetType().InvokeMember("DataSourceName", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {"adds"}) oMailMerge.GetType().InvokeMember("CommandType", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {0}) oMailMerge.GetType().InvokeMember("Command", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {"adds"}) oMailMerge.GetType().InvokeMember("OutputType", BindingFlags.SetProperty, Nothing, oMailMerge, New [Object]() {2}) oMailMerge.GetType().InvokeMember("Execute", BindingFlags.InvokeMethod Or BindingFlags.IgnoreReturn, Nothing, oMailMerge, New [Object]() {}) ' this line fails with a type mismatch error | [
"c#",
"c++",
"com",
"openoffice.org",
"ole"
] | 4 | 9 | 9,077 | 2 | 0 | 2008-09-02T04:52:52.027000 | 2008-09-03T22:34:34.027000 |
38,846 | 38,853 | How to encrypt one message for multiple recipients? | What are the fundamentals to accomplish data encryption with exactly two keys (which could be password-based), but needing only one (either one) of the two keys to decrypt the data? For example, data is encrypted with a user's password and his company's password, and then he or his company can decrypt the data. Neither of them know the other password. Only one copy of the encrypted data is stored. I don't mean public/private key. Probably via symmetric key cryptography and maybe it involves something like XORing the keys together to use them for encrypting. Update: I would also like to find a solution that does not involve storing the keys at all. | The way this is customarily done is to generate a single symmetric key to encrypt the data. Then you encrypt the symmetric key with each recipient's key or password to that they can decrypt it on their own. S/MIME (actually the Cryptographic Message Syntax on which S/MIME is based) uses this technique. This way, you only have to store one copy of the encrypted message, but multiple copies of its key. | How to encrypt one message for multiple recipients? What are the fundamentals to accomplish data encryption with exactly two keys (which could be password-based), but needing only one (either one) of the two keys to decrypt the data? For example, data is encrypted with a user's password and his company's password, and then he or his company can decrypt the data. Neither of them know the other password. Only one copy of the encrypted data is stored. I don't mean public/private key. Probably via symmetric key cryptography and maybe it involves something like XORing the keys together to use them for encrypting. Update: I would also like to find a solution that does not involve storing the keys at all. | TITLE:
How to encrypt one message for multiple recipients?
QUESTION:
What are the fundamentals to accomplish data encryption with exactly two keys (which could be password-based), but needing only one (either one) of the two keys to decrypt the data? For example, data is encrypted with a user's password and his company's password, and then he or his company can decrypt the data. Neither of them know the other password. Only one copy of the encrypted data is stored. I don't mean public/private key. Probably via symmetric key cryptography and maybe it involves something like XORing the keys together to use them for encrypting. Update: I would also like to find a solution that does not involve storing the keys at all.
ANSWER:
The way this is customarily done is to generate a single symmetric key to encrypt the data. Then you encrypt the symmetric key with each recipient's key or password to that they can decrypt it on their own. S/MIME (actually the Cryptographic Message Syntax on which S/MIME is based) uses this technique. This way, you only have to store one copy of the encrypted message, but multiple copies of its key. | [
"security",
"encryption",
"cryptography"
] | 9 | 21 | 10,463 | 5 | 0 | 2008-09-02T04:58:46.320000 | 2008-09-02T05:04:02.670000 |
38,861 | 38,921 | Will this hardware be 64bit Windows Server 2008 compatible? | I recently printed out Jeff Atwood's Understanding The Hardware blog post and plan on taking it to Fry's Electronics and saying to them "Give me all the parts on these sheets so I can put this together." However, I'm going to be installing 64bit Windows Server 2008 on this machine so before I get all the parts: Will all this hardware be 64bit Server 2008 compatible? - i.e. all drivers available for this hardware for this OS? | Hardware's generally pretty OS-agnostic (at least in terms of Windows flavors) these days. Your only concern is getting drivers for other devices (scanners, printers, IR remotes) that won't work on 64bit and/or won't work on "Server" OSes. Online backup software like Mozy generally won't even install on a Server OS, so it depends on what you're going to use it for. That said, if you're just going to use it for a home machine, then without even looking at the hardware list Jeff put together, I'd be confident in saying it'll probably work just fine. | Will this hardware be 64bit Windows Server 2008 compatible? I recently printed out Jeff Atwood's Understanding The Hardware blog post and plan on taking it to Fry's Electronics and saying to them "Give me all the parts on these sheets so I can put this together." However, I'm going to be installing 64bit Windows Server 2008 on this machine so before I get all the parts: Will all this hardware be 64bit Server 2008 compatible? - i.e. all drivers available for this hardware for this OS? | TITLE:
Will this hardware be 64bit Windows Server 2008 compatible?
QUESTION:
I recently printed out Jeff Atwood's Understanding The Hardware blog post and plan on taking it to Fry's Electronics and saying to them "Give me all the parts on these sheets so I can put this together." However, I'm going to be installing 64bit Windows Server 2008 on this machine so before I get all the parts: Will all this hardware be 64bit Server 2008 compatible? - i.e. all drivers available for this hardware for this OS?
ANSWER:
Hardware's generally pretty OS-agnostic (at least in terms of Windows flavors) these days. Your only concern is getting drivers for other devices (scanners, printers, IR remotes) that won't work on 64bit and/or won't work on "Server" OSes. Online backup software like Mozy generally won't even install on a Server OS, so it depends on what you're going to use it for. That said, if you're just going to use it for a home machine, then without even looking at the hardware list Jeff put together, I'd be confident in saying it'll probably work just fine. | [
"hardware",
"windows-server-2008"
] | 0 | 2 | 971 | 3 | 0 | 2008-09-02T05:14:49.587000 | 2008-09-02T06:16:07.240000 |
38,864 | 39,209 | How do you find out which NIC is connected to the internet? | Consider the following setup: A windows PC with a LAN interface and a WiFi interface (the standard for any new laptop). Each of the interfaces might be connected or disconnected from a network. I need a way to determine which one of the adapters is the one connected to the internet - specifically, in case they are both connected to different networks, one with connection to the internet and one without. My current solution involves using IPHelper's " GetBestInterface " function and supplying it with the IP address "0.0.0.0". Do you have any other solutions you might suggest to this problem? Following some of the answers, let me elaborate: I need this because I have a product that has to choose which adapter to bind to. I have no way of controlling the setup of the network or the host where the product will run and so I need a solution that is as robust as possible, with as few assumptions as possible. I need to do this in code, since this is part of a product. @Chris Upchurch: This makes me dependent on google.com being up (usually not a problem) and on any personal firewall that might be installed to allow pinging. @Till: Like Steve Moon said, relying on the adapter's address is kind of risky because you make a lot of assumptions on the internal network setup. @Steve Moon: Looking at the routing table sounds like a good idea, but instead of applying the routing logic myself, I am trying to use "GetBestInterface" as described above. I believe what it should do is exactly what you outlined in your answer, but I am not really sure. The reason I'm reluctant to implement my own "routing logic" is that there's a better chance that I'll get it wrong than if I use a library/API written and tested by more "hard-core" network people. | Technically, there is no "connected to the Internet". The real question is, which interface is routeable to a desired address. Right now, you're querying for the "default route" - the one that applies if no specific route to destination exists. But, you're ignoring any specific routes. Fortunately, for 99.9% of home users, that'll do the trick. They're not likely to have much of a routing table, and GetBestInterface will automatically prefer wired over wireless - so you should be good. Throw in an override option for the.1% of cases you screw up, and call it a day. But, for corporate use, you should be using GetBestInterface for a specific destination - otherwise, you'll have issues if someone is on the same LAN as your destination (which means you should take the "internal" interface, not the "external") or has a specific route to your destination (my internal network could peer with your destination's network, for instance). Then again, I'm not sure what you plan to do with this adapter "connected to the Internet", so it might not be a big deal. | How do you find out which NIC is connected to the internet? Consider the following setup: A windows PC with a LAN interface and a WiFi interface (the standard for any new laptop). Each of the interfaces might be connected or disconnected from a network. I need a way to determine which one of the adapters is the one connected to the internet - specifically, in case they are both connected to different networks, one with connection to the internet and one without. My current solution involves using IPHelper's " GetBestInterface " function and supplying it with the IP address "0.0.0.0". Do you have any other solutions you might suggest to this problem? Following some of the answers, let me elaborate: I need this because I have a product that has to choose which adapter to bind to. I have no way of controlling the setup of the network or the host where the product will run and so I need a solution that is as robust as possible, with as few assumptions as possible. I need to do this in code, since this is part of a product. @Chris Upchurch: This makes me dependent on google.com being up (usually not a problem) and on any personal firewall that might be installed to allow pinging. @Till: Like Steve Moon said, relying on the adapter's address is kind of risky because you make a lot of assumptions on the internal network setup. @Steve Moon: Looking at the routing table sounds like a good idea, but instead of applying the routing logic myself, I am trying to use "GetBestInterface" as described above. I believe what it should do is exactly what you outlined in your answer, but I am not really sure. The reason I'm reluctant to implement my own "routing logic" is that there's a better chance that I'll get it wrong than if I use a library/API written and tested by more "hard-core" network people. | TITLE:
How do you find out which NIC is connected to the internet?
QUESTION:
Consider the following setup: A windows PC with a LAN interface and a WiFi interface (the standard for any new laptop). Each of the interfaces might be connected or disconnected from a network. I need a way to determine which one of the adapters is the one connected to the internet - specifically, in case they are both connected to different networks, one with connection to the internet and one without. My current solution involves using IPHelper's " GetBestInterface " function and supplying it with the IP address "0.0.0.0". Do you have any other solutions you might suggest to this problem? Following some of the answers, let me elaborate: I need this because I have a product that has to choose which adapter to bind to. I have no way of controlling the setup of the network or the host where the product will run and so I need a solution that is as robust as possible, with as few assumptions as possible. I need to do this in code, since this is part of a product. @Chris Upchurch: This makes me dependent on google.com being up (usually not a problem) and on any personal firewall that might be installed to allow pinging. @Till: Like Steve Moon said, relying on the adapter's address is kind of risky because you make a lot of assumptions on the internal network setup. @Steve Moon: Looking at the routing table sounds like a good idea, but instead of applying the routing logic myself, I am trying to use "GetBestInterface" as described above. I believe what it should do is exactly what you outlined in your answer, but I am not really sure. The reason I'm reluctant to implement my own "routing logic" is that there's a better chance that I'll get it wrong than if I use a library/API written and tested by more "hard-core" network people.
ANSWER:
Technically, there is no "connected to the Internet". The real question is, which interface is routeable to a desired address. Right now, you're querying for the "default route" - the one that applies if no specific route to destination exists. But, you're ignoring any specific routes. Fortunately, for 99.9% of home users, that'll do the trick. They're not likely to have much of a routing table, and GetBestInterface will automatically prefer wired over wireless - so you should be good. Throw in an override option for the.1% of cases you screw up, and call it a day. But, for corporate use, you should be using GetBestInterface for a specific destination - otherwise, you'll have issues if someone is on the same LAN as your destination (which means you should take the "internal" interface, not the "external") or has a specific route to your destination (my internal network could peer with your destination's network, for instance). Then again, I'm not sure what you plan to do with this adapter "connected to the Internet", so it might not be a big deal. | [
"windows",
"networking",
"iphelper"
] | 5 | 5 | 6,371 | 8 | 0 | 2008-09-02T05:16:23.360000 | 2008-09-02T10:46:50.633000 |
38,870 | 38,882 | One or Two Primary Keys in Many-to-Many Table? | I have the following tables in my database that have a many-to-many relationship, which is expressed by a connecting table that has foreign keys to the primary keys of each of the main tables: Widget: WidgetID (PK), Title, Price User: UserID (PK), FirstName, LastName Assume that each User-Widget combination is unique. I can see two options for how to structure the connecting table that defines the data relationship: UserWidgets1: UserWidgetID (PK), WidgetID (FK), UserID (FK) UserWidgets2: WidgetID (PK, FK), UserID (PK, FK) Option 1 has a single column for the Primary Key. However, this seems unnecessary since the only data being stored in the table is the relationship between the two primary tables, and this relationship itself can form a unique key. Thus leading to option 2, which has a two-column primary key, but loses the one-column unique identifier that option 1 has. I could also optionally add a two-column unique index (WidgetID, UserID) to the first table. Is there any real difference between the two performance-wise, or any reason to prefer one approach over the other for structuring the UserWidgets many-to-many table? | You only have one primary key in either case. The second one is what's called a compound key. There's no good reason for introducing a new column. In practise, you will have to keep a unique index on all candidate keys. Adding a new column buys you nothing but maintenance overhead. Go with option 2. | One or Two Primary Keys in Many-to-Many Table? I have the following tables in my database that have a many-to-many relationship, which is expressed by a connecting table that has foreign keys to the primary keys of each of the main tables: Widget: WidgetID (PK), Title, Price User: UserID (PK), FirstName, LastName Assume that each User-Widget combination is unique. I can see two options for how to structure the connecting table that defines the data relationship: UserWidgets1: UserWidgetID (PK), WidgetID (FK), UserID (FK) UserWidgets2: WidgetID (PK, FK), UserID (PK, FK) Option 1 has a single column for the Primary Key. However, this seems unnecessary since the only data being stored in the table is the relationship between the two primary tables, and this relationship itself can form a unique key. Thus leading to option 2, which has a two-column primary key, but loses the one-column unique identifier that option 1 has. I could also optionally add a two-column unique index (WidgetID, UserID) to the first table. Is there any real difference between the two performance-wise, or any reason to prefer one approach over the other for structuring the UserWidgets many-to-many table? | TITLE:
One or Two Primary Keys in Many-to-Many Table?
QUESTION:
I have the following tables in my database that have a many-to-many relationship, which is expressed by a connecting table that has foreign keys to the primary keys of each of the main tables: Widget: WidgetID (PK), Title, Price User: UserID (PK), FirstName, LastName Assume that each User-Widget combination is unique. I can see two options for how to structure the connecting table that defines the data relationship: UserWidgets1: UserWidgetID (PK), WidgetID (FK), UserID (FK) UserWidgets2: WidgetID (PK, FK), UserID (PK, FK) Option 1 has a single column for the Primary Key. However, this seems unnecessary since the only data being stored in the table is the relationship between the two primary tables, and this relationship itself can form a unique key. Thus leading to option 2, which has a two-column primary key, but loses the one-column unique identifier that option 1 has. I could also optionally add a two-column unique index (WidgetID, UserID) to the first table. Is there any real difference between the two performance-wise, or any reason to prefer one approach over the other for structuring the UserWidgets many-to-many table?
ANSWER:
You only have one primary key in either case. The second one is what's called a compound key. There's no good reason for introducing a new column. In practise, you will have to keep a unique index on all candidate keys. Adding a new column buys you nothing but maintenance overhead. Go with option 2. | [
"database",
"data-structures",
"indexing",
"schema"
] | 16 | 24 | 14,331 | 9 | 0 | 2008-09-02T05:21:36.203000 | 2008-09-02T05:28:28.573000 |
38,875 | 38,886 | Best way to avoid code injection in PHP | My website was recently attacked by, what seemed to me as, an innocent code: There where no SQL calls, so I wasn't afraid for SQL Injection. But, apparently, SQL isn't the only kind of injection. This website has an explanation and a few examples of avoiding code injection: http://www.theserverpages.com/articles/webmasters/php/security/Code_Injection_Vulnerabilities_Explained.html How would you protect this code from code injection? | Use a whitelist and make sure the page is in the whitelist: $whitelist = array('home', 'page');
if (in_array($_GET['page'], $whitelist)) { include($_GET['page'].'.php'); } else { include('home.php'); } | Best way to avoid code injection in PHP My website was recently attacked by, what seemed to me as, an innocent code: There where no SQL calls, so I wasn't afraid for SQL Injection. But, apparently, SQL isn't the only kind of injection. This website has an explanation and a few examples of avoiding code injection: http://www.theserverpages.com/articles/webmasters/php/security/Code_Injection_Vulnerabilities_Explained.html How would you protect this code from code injection? | TITLE:
Best way to avoid code injection in PHP
QUESTION:
My website was recently attacked by, what seemed to me as, an innocent code: There where no SQL calls, so I wasn't afraid for SQL Injection. But, apparently, SQL isn't the only kind of injection. This website has an explanation and a few examples of avoiding code injection: http://www.theserverpages.com/articles/webmasters/php/security/Code_Injection_Vulnerabilities_Explained.html How would you protect this code from code injection?
ANSWER:
Use a whitelist and make sure the page is in the whitelist: $whitelist = array('home', 'page');
if (in_array($_GET['page'], $whitelist)) { include($_GET['page'].'.php'); } else { include('home.php'); } | [
"php",
"security",
"code-injection"
] | 24 | 40 | 26,698 | 10 | 0 | 2008-09-02T05:24:28.893000 | 2008-09-02T05:30:06.120000 |
38,890 | 38,897 | Enforce constraint checking only when inserting rows in MSSQL? | Is there a way to enforce constraint checking in MSSQL only when inserting new rows? I.e. allow the constraints to be violated when removing/updating rows? Update: I mean FK constraint. | You could create an INSERT TRIGGER that checks that the conditions are met. That way all updates will go straight through. CREATE TRIGGER employee_insupd ON employee FOR INSERT AS /* Get the range of level for this job type from the jobs table. */ DECLARE @min_lvl tinyint, @max_lvl tinyint, @emp_lvl tinyint, @job_id smallint SELECT @min_lvl = min_lvl, @max_lvl = max_lvl, @emp_lvl = i.job_lvl, @job_id = i.job_id FROM employee e INNER JOIN inserted i ON e.emp_id = i.emp_id JOIN jobs j ON j.job_id = i.job_id IF (@job_id = 1) and (@emp_lvl <> 10) BEGIN RAISERROR ('Job id 1 expects the default level of 10.', 16, 1) ROLLBACK TRANSACTION END ELSE IF NOT (@emp_lvl BETWEEN @min_lvl AND @max_lvl) BEGIN RAISERROR ('The level for job_id:%d should be between %d and %d.', 16, 1, @job_id, @min_lvl, @max_lvl) ROLLBACK TRANSACTION END | Enforce constraint checking only when inserting rows in MSSQL? Is there a way to enforce constraint checking in MSSQL only when inserting new rows? I.e. allow the constraints to be violated when removing/updating rows? Update: I mean FK constraint. | TITLE:
Enforce constraint checking only when inserting rows in MSSQL?
QUESTION:
Is there a way to enforce constraint checking in MSSQL only when inserting new rows? I.e. allow the constraints to be violated when removing/updating rows? Update: I mean FK constraint.
ANSWER:
You could create an INSERT TRIGGER that checks that the conditions are met. That way all updates will go straight through. CREATE TRIGGER employee_insupd ON employee FOR INSERT AS /* Get the range of level for this job type from the jobs table. */ DECLARE @min_lvl tinyint, @max_lvl tinyint, @emp_lvl tinyint, @job_id smallint SELECT @min_lvl = min_lvl, @max_lvl = max_lvl, @emp_lvl = i.job_lvl, @job_id = i.job_id FROM employee e INNER JOIN inserted i ON e.emp_id = i.emp_id JOIN jobs j ON j.job_id = i.job_id IF (@job_id = 1) and (@emp_lvl <> 10) BEGIN RAISERROR ('Job id 1 expects the default level of 10.', 16, 1) ROLLBACK TRANSACTION END ELSE IF NOT (@emp_lvl BETWEEN @min_lvl AND @max_lvl) BEGIN RAISERROR ('The level for job_id:%d should be between %d and %d.', 16, 1, @job_id, @min_lvl, @max_lvl) ROLLBACK TRANSACTION END | [
"sql-server",
"database"
] | 1 | 7 | 1,890 | 3 | 0 | 2008-09-02T05:34:35.720000 | 2008-09-02T05:42:55.557000 |
38,901 | 38,915 | Strange Rails Authentication Issue | I'm using the RESTful authentication Rails plugin for an app I'm developing. I'm having a strange issue I can't get to the bottom of. Essentially, the first time I log into the app after a period of inactivity (the app is deployed in production, but only being used by me), I will be brought to a 404 page, but if I go back to the home page and log in again, everything works according to plan. Any ideas? | Please check your routes. Not all routes are created equally. Routes have priority defined by the order of appearance of the routes in the config/routes.rb file. The priority goes from top to bottom. The last route in that file is at the lowest priority and will be applied last. If no route matches, 404 is returned. More info: http://api.rubyonrails.org/classes/ActionController/Routing.html | Strange Rails Authentication Issue I'm using the RESTful authentication Rails plugin for an app I'm developing. I'm having a strange issue I can't get to the bottom of. Essentially, the first time I log into the app after a period of inactivity (the app is deployed in production, but only being used by me), I will be brought to a 404 page, but if I go back to the home page and log in again, everything works according to plan. Any ideas? | TITLE:
Strange Rails Authentication Issue
QUESTION:
I'm using the RESTful authentication Rails plugin for an app I'm developing. I'm having a strange issue I can't get to the bottom of. Essentially, the first time I log into the app after a period of inactivity (the app is deployed in production, but only being used by me), I will be brought to a 404 page, but if I go back to the home page and log in again, everything works according to plan. Any ideas?
ANSWER:
Please check your routes. Not all routes are created equally. Routes have priority defined by the order of appearance of the routes in the config/routes.rb file. The priority goes from top to bottom. The last route in that file is at the lowest priority and will be applied last. If no route matches, 404 is returned. More info: http://api.rubyonrails.org/classes/ActionController/Routing.html | [
"ruby-on-rails",
"ruby",
"authentication",
"rest",
"plugins"
] | 2 | 2 | 290 | 2 | 0 | 2008-09-02T05:43:40.470000 | 2008-09-02T06:09:25.010000 |
38,907 | 39,022 | Developing on Eclipse 3.4, running on Eclipse 3.3 | I'm developing an Eclipse plug-in, based on a bunch of core Eclipse plug-ins like SWT, JDT, GEF and others. I need my plug-in to be compatible with Eclipse 3.3, since many potential customers are still using it. However, personally I like the new features in Eclipse 3.4 and would like to use it for my development. This means I need PDE to reference 3.3 code and, when debug, execute a 3.3 instance. Any tips on how this can be achieved? Thanks. | You can change the 'Target platform' setting to point to the location of an existing set of eclipse 3.3 plugins. This will compile your code against the 3.3 plugins, making sure that they stay compatible no matter which version of eclipse you are using to develop the application. The setting is under Window->Preferences->Plug-in development->Target Platform | Developing on Eclipse 3.4, running on Eclipse 3.3 I'm developing an Eclipse plug-in, based on a bunch of core Eclipse plug-ins like SWT, JDT, GEF and others. I need my plug-in to be compatible with Eclipse 3.3, since many potential customers are still using it. However, personally I like the new features in Eclipse 3.4 and would like to use it for my development. This means I need PDE to reference 3.3 code and, when debug, execute a 3.3 instance. Any tips on how this can be achieved? Thanks. | TITLE:
Developing on Eclipse 3.4, running on Eclipse 3.3
QUESTION:
I'm developing an Eclipse plug-in, based on a bunch of core Eclipse plug-ins like SWT, JDT, GEF and others. I need my plug-in to be compatible with Eclipse 3.3, since many potential customers are still using it. However, personally I like the new features in Eclipse 3.4 and would like to use it for my development. This means I need PDE to reference 3.3 code and, when debug, execute a 3.3 instance. Any tips on how this can be achieved? Thanks.
ANSWER:
You can change the 'Target platform' setting to point to the location of an existing set of eclipse 3.3 plugins. This will compile your code against the 3.3 plugins, making sure that they stay compatible no matter which version of eclipse you are using to develop the application. The setting is under Window->Preferences->Plug-in development->Target Platform | [
"eclipse",
"eclipse-pde",
"eclipse-3.4",
"eclipse-3.3"
] | 6 | 11 | 533 | 3 | 0 | 2008-09-02T05:46:42.927000 | 2008-09-02T08:27:01.217000 |
38,920 | 38,978 | php mail() not working windows 2003, IIS SMTP | I'm getting this problem: PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay for chris.mahan@gmail.com in c:\inetpub\wwwroot\mailtest.php on line 12 from this script: section from php.ini on the server: [mail function]; For Win32 only. SMTP = server.domain.com; for Win32 only smtp_port = 25; For Win32 only. sendmail_from = support@domain.com; For Unix only. You may supply arguments as well (default: "sendmail -t -i").;sendmail_path = (note that "server" and "domain" refer accurately to the actual server and domain name) In IIS, SMTP is running. Under "Access" tab, "Relay" button, the Select which computers may relay through this virtual server is set to checkbox "only the list below" and on the list is "127.0.0.1(xxx.xxx.xxx.xxx)" (x's representing actual server IP address). Server is running Windows Server 2003 Service Pack 2, fully patched as of 5 PM Sept 1st 2008. I assume it is running IIS7 (how to check?). Any ideas? In reponse to Espo: This machine is hosted at a datacenter. We do not want to use a gmail account (were doing it, want to move away from that). Windows server 2003 comes with its own SMTP server. Update: Per Yaakov Ellis' advice, I dropped all relay restrictions and added the server IP to the allowed list (using the reverse DNS button provided) and the thing started working. Thanks to both Espo and Yaakov for helping me out. | Try removing the IP restrictions for Relaying in the SMTP server, and opening it up to all relays. If it works when this is set, then you know that the problem has to do with the original restrictions. In this case, it may be a DNS issue, or perhaps you had the wrong IP address listed. | php mail() not working windows 2003, IIS SMTP I'm getting this problem: PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay for chris.mahan@gmail.com in c:\inetpub\wwwroot\mailtest.php on line 12 from this script: section from php.ini on the server: [mail function]; For Win32 only. SMTP = server.domain.com; for Win32 only smtp_port = 25; For Win32 only. sendmail_from = support@domain.com; For Unix only. You may supply arguments as well (default: "sendmail -t -i").;sendmail_path = (note that "server" and "domain" refer accurately to the actual server and domain name) In IIS, SMTP is running. Under "Access" tab, "Relay" button, the Select which computers may relay through this virtual server is set to checkbox "only the list below" and on the list is "127.0.0.1(xxx.xxx.xxx.xxx)" (x's representing actual server IP address). Server is running Windows Server 2003 Service Pack 2, fully patched as of 5 PM Sept 1st 2008. I assume it is running IIS7 (how to check?). Any ideas? In reponse to Espo: This machine is hosted at a datacenter. We do not want to use a gmail account (were doing it, want to move away from that). Windows server 2003 comes with its own SMTP server. Update: Per Yaakov Ellis' advice, I dropped all relay restrictions and added the server IP to the allowed list (using the reverse DNS button provided) and the thing started working. Thanks to both Espo and Yaakov for helping me out. | TITLE:
php mail() not working windows 2003, IIS SMTP
QUESTION:
I'm getting this problem: PHP Warning: mail() [function.mail]: SMTP server response: 550 5.7.1 Unable to relay for chris.mahan@gmail.com in c:\inetpub\wwwroot\mailtest.php on line 12 from this script: section from php.ini on the server: [mail function]; For Win32 only. SMTP = server.domain.com; for Win32 only smtp_port = 25; For Win32 only. sendmail_from = support@domain.com; For Unix only. You may supply arguments as well (default: "sendmail -t -i").;sendmail_path = (note that "server" and "domain" refer accurately to the actual server and domain name) In IIS, SMTP is running. Under "Access" tab, "Relay" button, the Select which computers may relay through this virtual server is set to checkbox "only the list below" and on the list is "127.0.0.1(xxx.xxx.xxx.xxx)" (x's representing actual server IP address). Server is running Windows Server 2003 Service Pack 2, fully patched as of 5 PM Sept 1st 2008. I assume it is running IIS7 (how to check?). Any ideas? In reponse to Espo: This machine is hosted at a datacenter. We do not want to use a gmail account (were doing it, want to move away from that). Windows server 2003 comes with its own SMTP server. Update: Per Yaakov Ellis' advice, I dropped all relay restrictions and added the server IP to the allowed list (using the reverse DNS button provided) and the thing started working. Thanks to both Espo and Yaakov for helping me out.
ANSWER:
Try removing the IP restrictions for Relaying in the SMTP server, and opening it up to all relays. If it works when this is set, then you know that the problem has to do with the original restrictions. In this case, it may be a DNS issue, or perhaps you had the wrong IP address listed. | [
"php",
"iis",
"smtp"
] | 2 | 4 | 13,531 | 5 | 0 | 2008-09-02T06:15:57.210000 | 2008-09-02T07:30:53.520000 |
38,922 | 40,015 | Running DB Migrations from application | I have a rails application where each user has a separate database. (taking Joel Spolsky's advice on this). I want to run DB migrations from the rails application to create a new database and tables for this user. What is the easiest way to do this? Maybe the db migration is not the best for this type of thing. Thanks! It would be nice if it could be a completely automated process. The following process would be ideal. A user signs up on our site to use this web app Migrations are run to create this users database and get tables setup correctly Is there a way of calling a rake task from a ruby application? | To answer part of your question, here's how you'd run a rake task from inside Rails code: require 'rake' load 'path/to/task.rake'
Rake::Task['foo:bar:baz'].invoke Mind you, I have no idea how (or why) you could have one database per user. | Running DB Migrations from application I have a rails application where each user has a separate database. (taking Joel Spolsky's advice on this). I want to run DB migrations from the rails application to create a new database and tables for this user. What is the easiest way to do this? Maybe the db migration is not the best for this type of thing. Thanks! It would be nice if it could be a completely automated process. The following process would be ideal. A user signs up on our site to use this web app Migrations are run to create this users database and get tables setup correctly Is there a way of calling a rake task from a ruby application? | TITLE:
Running DB Migrations from application
QUESTION:
I have a rails application where each user has a separate database. (taking Joel Spolsky's advice on this). I want to run DB migrations from the rails application to create a new database and tables for this user. What is the easiest way to do this? Maybe the db migration is not the best for this type of thing. Thanks! It would be nice if it could be a completely automated process. The following process would be ideal. A user signs up on our site to use this web app Migrations are run to create this users database and get tables setup correctly Is there a way of calling a rake task from a ruby application?
ANSWER:
To answer part of your question, here's how you'd run a rake task from inside Rails code: require 'rake' load 'path/to/task.rake'
Rake::Task['foo:bar:baz'].invoke Mind you, I have no idea how (or why) you could have one database per user. | [
"ruby-on-rails"
] | 0 | 1 | 279 | 3 | 0 | 2008-09-02T06:17:20.310000 | 2008-09-02T16:51:01.660000 |
38,940 | 38,942 | Generate field in MySQL SELECT | If I've got a table containing Field1 and Field2 can I generate a new field in the select statement? For example, a normal query would be: SELECT Field1, Field2 FROM Table And I want to also create Field3 and have that returned in the resultset... something along the lines of this would be ideal: SELECT Field1, Field2, Field3 = 'Value' FROM Table Is this possible at all? | SELECT Field1, Field2, 'Value' Field3 FROM Table or for clarity SELECT Field1, Field2, 'Value' AS Field3 FROM Table | Generate field in MySQL SELECT If I've got a table containing Field1 and Field2 can I generate a new field in the select statement? For example, a normal query would be: SELECT Field1, Field2 FROM Table And I want to also create Field3 and have that returned in the resultset... something along the lines of this would be ideal: SELECT Field1, Field2, Field3 = 'Value' FROM Table Is this possible at all? | TITLE:
Generate field in MySQL SELECT
QUESTION:
If I've got a table containing Field1 and Field2 can I generate a new field in the select statement? For example, a normal query would be: SELECT Field1, Field2 FROM Table And I want to also create Field3 and have that returned in the resultset... something along the lines of this would be ideal: SELECT Field1, Field2, Field3 = 'Value' FROM Table Is this possible at all?
ANSWER:
SELECT Field1, Field2, 'Value' Field3 FROM Table or for clarity SELECT Field1, Field2, 'Value' AS Field3 FROM Table | [
"sql",
"mysql"
] | 4 | 12 | 2,032 | 2 | 0 | 2008-09-02T06:50:58.233000 | 2008-09-02T06:53:23.487000 |
38,955 | 38,981 | Is it possible to get the maximum supported resolution of a connected display in os x from java? | Assume java 1.6 and leopard. Ideally, it would also be nice to get a list of all supported resolutions and the current resolution. If this isn't possible in java, is there some way to do it that could be called from java? | GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); for (int i = 0; i < devices.length; i++) { GraphicsDevice dev = devices[i]; System.out.println("device " + i); DisplayMode[] modes = dev.getDisplayModes(); for (int j = 0; j < modes.length; j++) { DisplayMode m = modes[j]; System.out.println(" " + j + ": " + m.getWidth() + " x " + m.getHeight()); } } With this code you can determine the current resolution. On my system (SuSE linux) it does NOT output the possible resolutions. Seems to work an Mac and Windows. | Is it possible to get the maximum supported resolution of a connected display in os x from java? Assume java 1.6 and leopard. Ideally, it would also be nice to get a list of all supported resolutions and the current resolution. If this isn't possible in java, is there some way to do it that could be called from java? | TITLE:
Is it possible to get the maximum supported resolution of a connected display in os x from java?
QUESTION:
Assume java 1.6 and leopard. Ideally, it would also be nice to get a list of all supported resolutions and the current resolution. If this isn't possible in java, is there some way to do it that could be called from java?
ANSWER:
GraphicsDevice[] devices = GraphicsEnvironment.getLocalGraphicsEnvironment().getScreenDevices(); for (int i = 0; i < devices.length; i++) { GraphicsDevice dev = devices[i]; System.out.println("device " + i); DisplayMode[] modes = dev.getDisplayModes(); for (int j = 0; j < modes.length; j++) { DisplayMode m = modes[j]; System.out.println(" " + j + ": " + m.getWidth() + " x " + m.getHeight()); } } With this code you can determine the current resolution. On my system (SuSE linux) it does NOT output the possible resolutions. Seems to work an Mac and Windows. | [
"java",
"macos",
"osx-leopard",
"resolutions"
] | 1 | 6 | 836 | 1 | 0 | 2008-09-02T07:11:40.867000 | 2008-09-02T07:33:22.093000 |
38,960 | 38,962 | How to find out if a file exists in C# / .NET? | I would like to test a string containing a path to a file for existence of that file (something like the -e test in Perl or the os.path.exists() in Python) in C#. | Use: File.Exists(path) MSDN: http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx Edit: In System.IO | How to find out if a file exists in C# / .NET? I would like to test a string containing a path to a file for existence of that file (something like the -e test in Perl or the os.path.exists() in Python) in C#. | TITLE:
How to find out if a file exists in C# / .NET?
QUESTION:
I would like to test a string containing a path to a file for existence of that file (something like the -e test in Perl or the os.path.exists() in Python) in C#.
ANSWER:
Use: File.Exists(path) MSDN: http://msdn.microsoft.com/en-us/library/system.io.file.exists.aspx Edit: In System.IO | [
"c#",
".net",
"io"
] | 242 | 370 | 343,780 | 6 | 0 | 2008-09-02T07:18:48.120000 | 2008-09-02T07:19:51.190000 |
38,993 | 39,004 | Regex to match unique substrings | Here's a basic regex technique that I've never managed to remember. Let's say I'm using a fairly generic regex implementation (e.g., grep or grep -E). If I were to do a list of files and match any that end in either.sty or.cls, how would I do that? | ls | grep -E "\.(sty|cls)$" \. matches literally a "." - an unescaped. matches any character (sty|cls) - match "sty" or "cls" - the | is an or and the brackets limit the expression. $ forces the match to be at the end of the line Note, you want grep -E or egrep, not grep -e as that's a different option for lists of patterns. | Regex to match unique substrings Here's a basic regex technique that I've never managed to remember. Let's say I'm using a fairly generic regex implementation (e.g., grep or grep -E). If I were to do a list of files and match any that end in either.sty or.cls, how would I do that? | TITLE:
Regex to match unique substrings
QUESTION:
Here's a basic regex technique that I've never managed to remember. Let's say I'm using a fairly generic regex implementation (e.g., grep or grep -E). If I were to do a list of files and match any that end in either.sty or.cls, how would I do that?
ANSWER:
ls | grep -E "\.(sty|cls)$" \. matches literally a "." - an unescaped. matches any character (sty|cls) - match "sty" or "cls" - the | is an or and the brackets limit the expression. $ forces the match to be at the end of the line Note, you want grep -E or egrep, not grep -e as that's a different option for lists of patterns. | [
"regex",
"grep"
] | 4 | 4 | 2,689 | 3 | 0 | 2008-09-02T08:05:43.420000 | 2008-09-02T08:14:22.183000 |
38,998 | 39,015 | Can I stop .NET eating IDs? | I'm an Information Architect and JavaScript developer by trade nowadays, but recently I've been getting back into back-end coding again. And, whilst trying to get an HTML prototype integrated and working with our C#-based CMS, I've come to blows with our programmers over the HTML ID attributes being arbitrarily rewritten by.NET for form elements. I can understand the code-behind reasoning for.NET changing IDs, but the fact you can no longer use IDs when trying to develop e.g. jQuery enhanced interfaces is causing some friction. What can I do to work around this? I've tried using the class attribute instead, but that's really crappy, not what it's meant for and doesn't get around that problem of.NET effectively changing rendered source on the fly. It also means that CSS is less useful now and less efficient to create and maintain. Any tips or advice greatly appreciated--anything for a few less sleepless nights... | The short answer is no, with webforms the id can always be rewritten depending on the nesting of the element. You can get access to the id through the ClientID property, so you could set the ids into variables in a script at the end of the page/control then put them into jQuery. something like this: Click Me It's a hack I know, but it will work. (I should note for the un-initiated, I'm using the Prototype $ get by id method there) | Can I stop .NET eating IDs? I'm an Information Architect and JavaScript developer by trade nowadays, but recently I've been getting back into back-end coding again. And, whilst trying to get an HTML prototype integrated and working with our C#-based CMS, I've come to blows with our programmers over the HTML ID attributes being arbitrarily rewritten by.NET for form elements. I can understand the code-behind reasoning for.NET changing IDs, but the fact you can no longer use IDs when trying to develop e.g. jQuery enhanced interfaces is causing some friction. What can I do to work around this? I've tried using the class attribute instead, but that's really crappy, not what it's meant for and doesn't get around that problem of.NET effectively changing rendered source on the fly. It also means that CSS is less useful now and less efficient to create and maintain. Any tips or advice greatly appreciated--anything for a few less sleepless nights... | TITLE:
Can I stop .NET eating IDs?
QUESTION:
I'm an Information Architect and JavaScript developer by trade nowadays, but recently I've been getting back into back-end coding again. And, whilst trying to get an HTML prototype integrated and working with our C#-based CMS, I've come to blows with our programmers over the HTML ID attributes being arbitrarily rewritten by.NET for form elements. I can understand the code-behind reasoning for.NET changing IDs, but the fact you can no longer use IDs when trying to develop e.g. jQuery enhanced interfaces is causing some friction. What can I do to work around this? I've tried using the class attribute instead, but that's really crappy, not what it's meant for and doesn't get around that problem of.NET effectively changing rendered source on the fly. It also means that CSS is less useful now and less efficient to create and maintain. Any tips or advice greatly appreciated--anything for a few less sleepless nights...
ANSWER:
The short answer is no, with webforms the id can always be rewritten depending on the nesting of the element. You can get access to the id through the ClientID property, so you could set the ids into variables in a script at the end of the page/control then put them into jQuery. something like this: Click Me It's a hack I know, but it will work. (I should note for the un-initiated, I'm using the Prototype $ get by id method there) | [
"c#",
".net",
"javascript",
"html",
"css"
] | 21 | 25 | 1,968 | 10 | 0 | 2008-09-02T08:09:24.253000 | 2008-09-02T08:20:29.283000 |
39,003 | 39,034 | NUnit - How to test all classes that implement a particular interface | If I have interface IFoo, and have several classes that implement it, what is the best/most elegant/cleverest way to test all those classes against the interface? I'd like to reduce test code duplication, but still 'stay true' to the principles of Unit testing. What would you consider best practice? I'm using NUnit, but I suppose examples from any Unit testing framework would be valid | If you have classes implement any one interface then they all need to implement the methods in that interface. In order to test these classes you need to create a unit test class for each of the classes. Lets go with a smarter route instead; if your goal is to avoid code and test code duplication you might want to create an abstract class instead that handles the recurring code. E.g. you have the following interface: public interface IFoo {
public void CommonCode();
public void SpecificCode();
} You might want to create an abstract class: public abstract class AbstractFoo: IFoo {
public void CommonCode() { SpecificCode(); }
public abstract void SpecificCode();
} Testing that is easy; implement the abstract class in the test class either as an inner class: [TestFixture] public void TestClass {
private class TestFoo: AbstractFoo { boolean hasCalledSpecificCode = false; public void SpecificCode() { hasCalledSpecificCode = true; } }
[Test] public void testCommonCallsSpecificCode() { TestFoo fooFighter = new TestFoo(); fooFighter.CommonCode(); Assert.That(fooFighter.hasCalledSpecificCode, Is.True()); } }...or let the test class extend the abstract class itself if that fits your fancy. [TestFixture] public void TestClass: AbstractFoo {
boolean hasCalledSpecificCode; public void specificCode() { hasCalledSpecificCode = true; }
[Test] public void testCommonCallsSpecificCode() { AbstractFoo fooFighter = this; hasCalledSpecificCode = false; fooFighter.CommonCode(); Assert.That(fooFighter.hasCalledSpecificCode, Is.True()); }
} Having an abstract class take care of common code that an interface implies gives a much cleaner code design. I hope this makes sense to you. As a side note, this is a common design pattern called the Template Method pattern. In the above example, the template method is the CommonCode method and SpecificCode is called a stub or a hook. The idea is that anyone can extend behavior without the need to know the behind the scenes stuff. A lot of frameworks rely on this behavioral pattern, e.g. ASP.NET where you have to implement the hooks in a page or a user controls such as the generated Page_Load method which is called by the Load event, the template method calls the hooks behind the scenes. There are a lot more examples of this. Basically anything that you have to implement that is using the words "load", "init", or "render" is called by a template method. | NUnit - How to test all classes that implement a particular interface If I have interface IFoo, and have several classes that implement it, what is the best/most elegant/cleverest way to test all those classes against the interface? I'd like to reduce test code duplication, but still 'stay true' to the principles of Unit testing. What would you consider best practice? I'm using NUnit, but I suppose examples from any Unit testing framework would be valid | TITLE:
NUnit - How to test all classes that implement a particular interface
QUESTION:
If I have interface IFoo, and have several classes that implement it, what is the best/most elegant/cleverest way to test all those classes against the interface? I'd like to reduce test code duplication, but still 'stay true' to the principles of Unit testing. What would you consider best practice? I'm using NUnit, but I suppose examples from any Unit testing framework would be valid
ANSWER:
If you have classes implement any one interface then they all need to implement the methods in that interface. In order to test these classes you need to create a unit test class for each of the classes. Lets go with a smarter route instead; if your goal is to avoid code and test code duplication you might want to create an abstract class instead that handles the recurring code. E.g. you have the following interface: public interface IFoo {
public void CommonCode();
public void SpecificCode();
} You might want to create an abstract class: public abstract class AbstractFoo: IFoo {
public void CommonCode() { SpecificCode(); }
public abstract void SpecificCode();
} Testing that is easy; implement the abstract class in the test class either as an inner class: [TestFixture] public void TestClass {
private class TestFoo: AbstractFoo { boolean hasCalledSpecificCode = false; public void SpecificCode() { hasCalledSpecificCode = true; } }
[Test] public void testCommonCallsSpecificCode() { TestFoo fooFighter = new TestFoo(); fooFighter.CommonCode(); Assert.That(fooFighter.hasCalledSpecificCode, Is.True()); } }...or let the test class extend the abstract class itself if that fits your fancy. [TestFixture] public void TestClass: AbstractFoo {
boolean hasCalledSpecificCode; public void specificCode() { hasCalledSpecificCode = true; }
[Test] public void testCommonCallsSpecificCode() { AbstractFoo fooFighter = this; hasCalledSpecificCode = false; fooFighter.CommonCode(); Assert.That(fooFighter.hasCalledSpecificCode, Is.True()); }
} Having an abstract class take care of common code that an interface implies gives a much cleaner code design. I hope this makes sense to you. As a side note, this is a common design pattern called the Template Method pattern. In the above example, the template method is the CommonCode method and SpecificCode is called a stub or a hook. The idea is that anyone can extend behavior without the need to know the behind the scenes stuff. A lot of frameworks rely on this behavioral pattern, e.g. ASP.NET where you have to implement the hooks in a page or a user controls such as the generated Page_Load method which is called by the Load event, the template method calls the hooks behind the scenes. There are a lot more examples of this. Basically anything that you have to implement that is using the words "load", "init", or "render" is called by a template method. | [
"c#",
".net",
"unit-testing",
"nunit"
] | 33 | 15 | 11,786 | 6 | 0 | 2008-09-02T08:13:58.050000 | 2008-09-02T08:39:09.847000 |
39,006 | 39,321 | Error: "VirtualHost *:80 -- mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results" | I'm running WAMP v2.0 on WindowsXP and I've got a bunch of virtual hosts setup in the http-vhosts.conf file. This was working, but in the last week whenever I try & start WAMP I get this error in the event logs: VirtualHost *:80 -- mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results. and the server won't start. I can't think of what's changed. I've copied the conf file below. NameVirtualHost * ServerName dev.blog.slaven.net.au ServerAlias dev.blog.slaven.net.au ServerAdmin user@host.com DocumentRoot "c:/Project Data/OtherProjects/slaven.net.au/blog/" ErrorLog "logs/blog.slaven.localhost-error.log" CustomLog "logs/blog.slaven.localhost-access.log" common Options Indexes FollowSymLinks MultiViews AllowOverride all Order allow,deny Allow from all EDIT: I meant to add, if I change the NameVirtualHosts directive to specify a port, i.e NameVirtualHost *:80 I get this error: Only one usage of each socket address (protocol/network address/port) is normally permitted.: make_sock: could not bind to address 0.0.0.0:80 | NameVirtualHost *:80 I get this error: Only one usage of each socket address (protocol/network address/port) is normally >permitted.: make_sock: could not bind to address 0.0.0.0:80 I think this might be because you have somthing else listening to port 80. Do you have any other servers (or for example Skype) running? (If it was Skype: untick "Tools > Options > Advanced > Connection > Use port 80 and 443 as alternatives for incoming connections") | Error: "VirtualHost *:80 -- mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results" I'm running WAMP v2.0 on WindowsXP and I've got a bunch of virtual hosts setup in the http-vhosts.conf file. This was working, but in the last week whenever I try & start WAMP I get this error in the event logs: VirtualHost *:80 -- mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results. and the server won't start. I can't think of what's changed. I've copied the conf file below. NameVirtualHost * ServerName dev.blog.slaven.net.au ServerAlias dev.blog.slaven.net.au ServerAdmin user@host.com DocumentRoot "c:/Project Data/OtherProjects/slaven.net.au/blog/" ErrorLog "logs/blog.slaven.localhost-error.log" CustomLog "logs/blog.slaven.localhost-access.log" common Options Indexes FollowSymLinks MultiViews AllowOverride all Order allow,deny Allow from all EDIT: I meant to add, if I change the NameVirtualHosts directive to specify a port, i.e NameVirtualHost *:80 I get this error: Only one usage of each socket address (protocol/network address/port) is normally permitted.: make_sock: could not bind to address 0.0.0.0:80 | TITLE:
Error: "VirtualHost *:80 -- mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results"
QUESTION:
I'm running WAMP v2.0 on WindowsXP and I've got a bunch of virtual hosts setup in the http-vhosts.conf file. This was working, but in the last week whenever I try & start WAMP I get this error in the event logs: VirtualHost *:80 -- mixing * ports and non-* ports with a NameVirtualHost address is not supported, proceeding with undefined results. and the server won't start. I can't think of what's changed. I've copied the conf file below. NameVirtualHost * ServerName dev.blog.slaven.net.au ServerAlias dev.blog.slaven.net.au ServerAdmin user@host.com DocumentRoot "c:/Project Data/OtherProjects/slaven.net.au/blog/" ErrorLog "logs/blog.slaven.localhost-error.log" CustomLog "logs/blog.slaven.localhost-access.log" common Options Indexes FollowSymLinks MultiViews AllowOverride all Order allow,deny Allow from all EDIT: I meant to add, if I change the NameVirtualHosts directive to specify a port, i.e NameVirtualHost *:80 I get this error: Only one usage of each socket address (protocol/network address/port) is normally permitted.: make_sock: could not bind to address 0.0.0.0:80
ANSWER:
NameVirtualHost *:80 I get this error: Only one usage of each socket address (protocol/network address/port) is normally >permitted.: make_sock: could not bind to address 0.0.0.0:80 I think this might be because you have somthing else listening to port 80. Do you have any other servers (or for example Skype) running? (If it was Skype: untick "Tools > Options > Advanced > Connection > Use port 80 and 443 as alternatives for incoming connections") | [
"windows",
"apache",
"wamp"
] | 1 | 4 | 5,952 | 2 | 0 | 2008-09-02T08:14:54.833000 | 2008-09-02T11:56:29.810000 |
39,007 | 39,290 | Speeding up XAML editing in VS2008 | When editing XAML in VS2008 SP1, the editor is really slow. devenv process seems to be around at 40% CPU (the machine I’m using at the moment is only dual core, so that’s almost maxing out one core) most of the time. It spikes up a bit more when I switch to another XAML file. I do also have ReSharper installed, but I think I’d rather put up with the slowness than remove that:) Any suggestions on how I can speed things up a bit? Edited to add: I'm already using the Xaml only view, which did speed it up from what I remember - but it's still to sluggish. Also, the Xaml files aren't massive - only 100 to 200 lines. | It looks like the slowdown is due to ReSharper. From a bit more Googling I found that pressing Ctrl + 8 will turn ReSharper off for the current file ( Ctrl + 8 again to turn it back on). If I do this for the slow Xaml files, my problems pretty much go away (and I don’t mind not having ReSharper for Xaml) Update: The 4.1 release of ReSharper seems to have fixed the performance problem, so I no longer need to use the Ctrl + 8 shortcut. | Speeding up XAML editing in VS2008 When editing XAML in VS2008 SP1, the editor is really slow. devenv process seems to be around at 40% CPU (the machine I’m using at the moment is only dual core, so that’s almost maxing out one core) most of the time. It spikes up a bit more when I switch to another XAML file. I do also have ReSharper installed, but I think I’d rather put up with the slowness than remove that:) Any suggestions on how I can speed things up a bit? Edited to add: I'm already using the Xaml only view, which did speed it up from what I remember - but it's still to sluggish. Also, the Xaml files aren't massive - only 100 to 200 lines. | TITLE:
Speeding up XAML editing in VS2008
QUESTION:
When editing XAML in VS2008 SP1, the editor is really slow. devenv process seems to be around at 40% CPU (the machine I’m using at the moment is only dual core, so that’s almost maxing out one core) most of the time. It spikes up a bit more when I switch to another XAML file. I do also have ReSharper installed, but I think I’d rather put up with the slowness than remove that:) Any suggestions on how I can speed things up a bit? Edited to add: I'm already using the Xaml only view, which did speed it up from what I remember - but it's still to sluggish. Also, the Xaml files aren't massive - only 100 to 200 lines.
ANSWER:
It looks like the slowdown is due to ReSharper. From a bit more Googling I found that pressing Ctrl + 8 will turn ReSharper off for the current file ( Ctrl + 8 again to turn it back on). If I do this for the slow Xaml files, my problems pretty much go away (and I don’t mind not having ReSharper for Xaml) Update: The 4.1 release of ReSharper seems to have fixed the performance problem, so I no longer need to use the Ctrl + 8 shortcut. | [
"visual-studio-2008",
"xaml"
] | 4 | 1 | 1,352 | 4 | 0 | 2008-09-02T08:15:20.793000 | 2008-09-02T11:41:55.087000 |
39,037 | 39,139 | How to convert Word and Excel documents to PDF programmatically? | We are developing a little application that given a directory with PDF files creates a unique PDF file containing all the PDF files in the directory. This is a simple task using iTextSharp. The problem appears if in the directory exist some files like Word documents, or Excel documents. My question is, is there a way to convert word, excel documents into PDF programmatically? And even better, is this possible without having the office suite installed on the computer running the application? | Office 2007 allows for this. I have found PDFCreator to be good, the VBA is included in sample files, and have heard that CutePDF is also good. PDFCreator and CutePDF are free. To work without Office, you would need viewers, as far as I know: http://www.microsoft.com/downloads/details.aspx?FamilyID=c8378bf4-996c-4569-b547-75edbd03aaf0&displaylang=EN http://www.microsoft.com/downloads/details.aspx?familyid=95E24C87-8732-48D5-8689-AB826E7B8FDF&displaylang=en | How to convert Word and Excel documents to PDF programmatically? We are developing a little application that given a directory with PDF files creates a unique PDF file containing all the PDF files in the directory. This is a simple task using iTextSharp. The problem appears if in the directory exist some files like Word documents, or Excel documents. My question is, is there a way to convert word, excel documents into PDF programmatically? And even better, is this possible without having the office suite installed on the computer running the application? | TITLE:
How to convert Word and Excel documents to PDF programmatically?
QUESTION:
We are developing a little application that given a directory with PDF files creates a unique PDF file containing all the PDF files in the directory. This is a simple task using iTextSharp. The problem appears if in the directory exist some files like Word documents, or Excel documents. My question is, is there a way to convert word, excel documents into PDF programmatically? And even better, is this possible without having the office suite installed on the computer running the application?
ANSWER:
Office 2007 allows for this. I have found PDFCreator to be good, the VBA is included in sample files, and have heard that CutePDF is also good. PDFCreator and CutePDF are free. To work without Office, you would need viewers, as far as I know: http://www.microsoft.com/downloads/details.aspx?FamilyID=c8378bf4-996c-4569-b547-75edbd03aaf0&displaylang=EN http://www.microsoft.com/downloads/details.aspx?familyid=95E24C87-8732-48D5-8689-AB826E7B8FDF&displaylang=en | [
"automation",
"ms-office"
] | 7 | 2 | 18,686 | 8 | 0 | 2008-09-02T08:42:22.820000 | 2008-09-02T09:58:17.707000 |
39,059 | 39,235 | How do I run my app with large pages in Windows? | Large pages are available in Windows Server 2003 and Windows Vista. But how do I enable large pages for my application? | Martin's answer is correct on Windows Server 2003: You will have to assign the "Lock pages in memory" privilege to any user that runs your > application. This includes administrators Select Control Panel -> Administrative Tools -> Local Security Policy Select Local Policies -> User Rights Assignment Double click "Lock pages in memory", add users and/or groups Reboot the machine On Windows Vista you need also make sure that the application is run as Administrator (by right-clicking on the application or the shell and choosing "Run as adminstrator". In addition, it helps to have a freshly booted machine since the large pages can "run out" due to fragmentation of the heap. | How do I run my app with large pages in Windows? Large pages are available in Windows Server 2003 and Windows Vista. But how do I enable large pages for my application? | TITLE:
How do I run my app with large pages in Windows?
QUESTION:
Large pages are available in Windows Server 2003 and Windows Vista. But how do I enable large pages for my application?
ANSWER:
Martin's answer is correct on Windows Server 2003: You will have to assign the "Lock pages in memory" privilege to any user that runs your > application. This includes administrators Select Control Panel -> Administrative Tools -> Local Security Policy Select Local Policies -> User Rights Assignment Double click "Lock pages in memory", add users and/or groups Reboot the machine On Windows Vista you need also make sure that the application is run as Administrator (by right-clicking on the application or the shell and choosing "Run as adminstrator". In addition, it helps to have a freshly booted machine since the large pages can "run out" due to fragmentation of the heap. | [
"windows",
"windows-server-2003"
] | 2 | 3 | 9,648 | 2 | 0 | 2008-09-02T09:00:58.093000 | 2008-09-02T11:10:10.670000 |
39,061 | 39,072 | Can all RPN expressions be represented such that all operators appear on the left and all operands appear on the right? | I've convinced myself that they can't. Take for example: 4 4 + 4 / stack: 4 stack: 4 4 4 + 4 = 8 stack: 8 stack: 8 4 8 / 4 = 2 stack: 2 There are two ways that you could write the above expression with the same operators and operands such that the operands all come first: "4 4 4 + /" and "4 4 4 / +", neither of which evaluate to 2. "4 4 4 + /" stack: 4 stack: 4 4 stack: 4 4 4 4 + 4 = 8 stack: 4 8 4 / 8 = 0.5 stack: 0.5 "4 4 4 / +" stack: 4 stack: 4 4 stack: 4 4 4 4 / 4 = 1 stack: 4 1 4 + 1 = 5 stack: 5 If you have the ability to swap items on the stack then yes, it's possible, otherwise, no. Thoughts? | Consider the algebraic expression: (a + b) * (c + d) The obvious translation to RPN would be: a b + c d + * Even with a swap operation available, I don't think there is a way to collect all the operators on the right: a b c d + a b S where S is the sum of c and d. At this point, you couldn't use a single swap operation to get both a and b in place for a + operation. Instead, you would need a more sophisticated stack operation (such as roll) to get a and b in the right spot. I don't know whether a roll operation would be sufficient for all cases, either. | Can all RPN expressions be represented such that all operators appear on the left and all operands appear on the right? I've convinced myself that they can't. Take for example: 4 4 + 4 / stack: 4 stack: 4 4 4 + 4 = 8 stack: 8 stack: 8 4 8 / 4 = 2 stack: 2 There are two ways that you could write the above expression with the same operators and operands such that the operands all come first: "4 4 4 + /" and "4 4 4 / +", neither of which evaluate to 2. "4 4 4 + /" stack: 4 stack: 4 4 stack: 4 4 4 4 + 4 = 8 stack: 4 8 4 / 8 = 0.5 stack: 0.5 "4 4 4 / +" stack: 4 stack: 4 4 stack: 4 4 4 4 / 4 = 1 stack: 4 1 4 + 1 = 5 stack: 5 If you have the ability to swap items on the stack then yes, it's possible, otherwise, no. Thoughts? | TITLE:
Can all RPN expressions be represented such that all operators appear on the left and all operands appear on the right?
QUESTION:
I've convinced myself that they can't. Take for example: 4 4 + 4 / stack: 4 stack: 4 4 4 + 4 = 8 stack: 8 stack: 8 4 8 / 4 = 2 stack: 2 There are two ways that you could write the above expression with the same operators and operands such that the operands all come first: "4 4 4 + /" and "4 4 4 / +", neither of which evaluate to 2. "4 4 4 + /" stack: 4 stack: 4 4 stack: 4 4 4 4 + 4 = 8 stack: 4 8 4 / 8 = 0.5 stack: 0.5 "4 4 4 / +" stack: 4 stack: 4 4 stack: 4 4 4 4 / 4 = 1 stack: 4 1 4 + 1 = 5 stack: 5 If you have the ability to swap items on the stack then yes, it's possible, otherwise, no. Thoughts?
ANSWER:
Consider the algebraic expression: (a + b) * (c + d) The obvious translation to RPN would be: a b + c d + * Even with a swap operation available, I don't think there is a way to collect all the operators on the right: a b c d + a b S where S is the sum of c and d. At this point, you couldn't use a single swap operation to get both a and b in place for a + operation. Instead, you would need a more sophisticated stack operation (such as roll) to get a and b in the right spot. I don't know whether a roll operation would be sufficient for all cases, either. | [
"rpn"
] | 1 | 2 | 496 | 4 | 0 | 2008-09-02T09:01:50.137000 | 2008-09-02T09:08:08.793000 |
39,065 | 39,083 | Referencing resource files from multiple projects in a solution | I am working on localization for a asp.net application that consists of several projects. For this, there are some strings that are used in several of these projects. Naturally, I would prefer to have only one copy of the resource file in each project. Since the resource files don't have an namespace (at least as far as I can tell), they can't be accessed like regular classes. Is there any way to reference resx files in another project, within the same solution? | You can just create a class library project, add a resource file there, and then refer to that assembly for common resources. | Referencing resource files from multiple projects in a solution I am working on localization for a asp.net application that consists of several projects. For this, there are some strings that are used in several of these projects. Naturally, I would prefer to have only one copy of the resource file in each project. Since the resource files don't have an namespace (at least as far as I can tell), they can't be accessed like regular classes. Is there any way to reference resx files in another project, within the same solution? | TITLE:
Referencing resource files from multiple projects in a solution
QUESTION:
I am working on localization for a asp.net application that consists of several projects. For this, there are some strings that are used in several of these projects. Naturally, I would prefer to have only one copy of the resource file in each project. Since the resource files don't have an namespace (at least as far as I can tell), they can't be accessed like regular classes. Is there any way to reference resx files in another project, within the same solution?
ANSWER:
You can just create a class library project, add a resource file there, and then refer to that assembly for common resources. | [
"c#",
"localization",
"resx"
] | 11 | 15 | 22,299 | 3 | 0 | 2008-09-02T09:05:04.433000 | 2008-09-02T09:16:56.497000 |
39,070 | 84,138 | Programmable, secure FTP replacement | We need to move off traditional FTP for security purposes (it transmits it's passwords unencrypted). I am hearing SSH touted as the obvious alternative. However I have been driving FTP from an ASP.NET program interface to automate my web-site development, which is now quite a highly web-enabled process. Can anyone recommend a secure way to transfer files around which has a program interface that I can drive from ASP.NET? | the question has three subquestions: 1) choosing the secure transfer protocol The secure version of old FTP exists - it's called FTP/SSL (plain old FTP over SSL encrypted channel). Maybe you can still use your old deployment infrastructure - just check whether it supports the FTPS or FTP/SSL. You can check details about FTP, FTP/SSL and SFTP differences at http://www.rebex.net/secure-ftp.net/ page. 2) SFTP or FTP/SSL server for Windows When you choose whether to use SFTP or FTPS you have to deploy the proper server. For FTP/SSL we use the Gene6 ( http://www.g6ftpserver.com/ ) on several servers without problems. There is plenty of FTP/SSL Windows servers so use whatever you want. The situation is a bit more complicated with SFTP server for Windows - there is only a few working implementations. The Bitvise WinHTTPD looks quite promising ( http://www.bitvise.com/winsshd ). 3) Internet File Transfer Component for ASP.NET Last part of the solution is secure file transfer from asp.net. There is several components on the market. I would recommend the Rebex File Transfer Pack - it supports both FTP (and FTP/SSL) and SFTP (SSH File Transfer). Following code shows how to upload a file to the server via SFTP. The code is taken from our Rebex SFTP tutorial page. // create client, connect and log in Sftp client = new Sftp(); client.Connect(hostname); client.Login(username, password);
// upload the 'test.zip' file to the current directory at the server client.PutFile(@"c:\data\test.zip", "test.zip");
// upload the 'index.html' file to the specified directory at the server client.PutFile(@"c:\data\index.html", "/wwwroot/index.html");
// download the 'test.zip' file from the current directory at the server client.GetFile("test.zip", @"c:\data\test.zip");
// download the 'index.html' file from the specified directory at the server client.GetFile("/wwwroot/index.html", @"c:\data\index.html");
// upload a text using a MemoryStream string message = "Hello from Rebex SFTP for.NET!"; byte[] data = System.Text.Encoding.Default.GetBytes(message); System.IO.MemoryStream ms = new System.IO.MemoryStream(data); client.PutFile(ms, "message.txt"); Martin | Programmable, secure FTP replacement We need to move off traditional FTP for security purposes (it transmits it's passwords unencrypted). I am hearing SSH touted as the obvious alternative. However I have been driving FTP from an ASP.NET program interface to automate my web-site development, which is now quite a highly web-enabled process. Can anyone recommend a secure way to transfer files around which has a program interface that I can drive from ASP.NET? | TITLE:
Programmable, secure FTP replacement
QUESTION:
We need to move off traditional FTP for security purposes (it transmits it's passwords unencrypted). I am hearing SSH touted as the obvious alternative. However I have been driving FTP from an ASP.NET program interface to automate my web-site development, which is now quite a highly web-enabled process. Can anyone recommend a secure way to transfer files around which has a program interface that I can drive from ASP.NET?
ANSWER:
the question has three subquestions: 1) choosing the secure transfer protocol The secure version of old FTP exists - it's called FTP/SSL (plain old FTP over SSL encrypted channel). Maybe you can still use your old deployment infrastructure - just check whether it supports the FTPS or FTP/SSL. You can check details about FTP, FTP/SSL and SFTP differences at http://www.rebex.net/secure-ftp.net/ page. 2) SFTP or FTP/SSL server for Windows When you choose whether to use SFTP or FTPS you have to deploy the proper server. For FTP/SSL we use the Gene6 ( http://www.g6ftpserver.com/ ) on several servers without problems. There is plenty of FTP/SSL Windows servers so use whatever you want. The situation is a bit more complicated with SFTP server for Windows - there is only a few working implementations. The Bitvise WinHTTPD looks quite promising ( http://www.bitvise.com/winsshd ). 3) Internet File Transfer Component for ASP.NET Last part of the solution is secure file transfer from asp.net. There is several components on the market. I would recommend the Rebex File Transfer Pack - it supports both FTP (and FTP/SSL) and SFTP (SSH File Transfer). Following code shows how to upload a file to the server via SFTP. The code is taken from our Rebex SFTP tutorial page. // create client, connect and log in Sftp client = new Sftp(); client.Connect(hostname); client.Login(username, password);
// upload the 'test.zip' file to the current directory at the server client.PutFile(@"c:\data\test.zip", "test.zip");
// upload the 'index.html' file to the specified directory at the server client.PutFile(@"c:\data\index.html", "/wwwroot/index.html");
// download the 'test.zip' file from the current directory at the server client.GetFile("test.zip", @"c:\data\test.zip");
// download the 'index.html' file from the specified directory at the server client.GetFile("/wwwroot/index.html", @"c:\data\index.html");
// upload a text using a MemoryStream string message = "Hello from Rebex SFTP for.NET!"; byte[] data = System.Text.Encoding.Default.GetBytes(message); System.IO.MemoryStream ms = new System.IO.MemoryStream(data); client.PutFile(ms, "message.txt"); Martin | [
"asp.net",
"ftp"
] | 2 | 3 | 3,033 | 5 | 0 | 2008-09-02T09:06:04.260000 | 2008-09-17T14:57:24.537000 |
39,086 | 39,110 | Search and replace a line in a file in Python | I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it. What is the best way to do this, within the following code? f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file | I guess something like this should do it. It basically writes the content to a new file and replaces the old file with the new file: from tempfile import mkstemp from shutil import move, copymode from os import fdopen, remove
def replace(file_path, pattern, subst): #Create temp file fh, abs_path = mkstemp() with fdopen(fh,'w') as new_file: with open(file_path) as old_file: for line in old_file: new_file.write(line.replace(pattern, subst)) #Copy the file permissions from the old file to the new file copymode(file_path, abs_path) #Remove original file remove(file_path) #Move new file move(abs_path, file_path) | Search and replace a line in a file in Python I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it. What is the best way to do this, within the following code? f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file | TITLE:
Search and replace a line in a file in Python
QUESTION:
I want to loop over the contents of a text file and do a search and replace on some lines and write the result back to the file. I could first load the whole file in memory and then write it back, but that probably is not the best way to do it. What is the best way to do this, within the following code? f = open(file) for line in f: if line.contains('foo'): newline = line.replace('foo', 'bar') # how to write this newline back to the file
ANSWER:
I guess something like this should do it. It basically writes the content to a new file and replaces the old file with the new file: from tempfile import mkstemp from shutil import move, copymode from os import fdopen, remove
def replace(file_path, pattern, subst): #Create temp file fh, abs_path = mkstemp() with fdopen(fh,'w') as new_file: with open(file_path) as old_file: for line in old_file: new_file.write(line.replace(pattern, subst)) #Copy the file permissions from the old file to the new file copymode(file_path, abs_path) #Remove original file remove(file_path) #Move new file move(abs_path, file_path) | [
"python",
"file"
] | 377 | 235 | 630,471 | 13 | 0 | 2008-09-02T09:19:04.417000 | 2008-09-02T09:42:21.037000 |
39,107 | 39,875 | Tools for degrading my network connection? | I've written some applications than heavily use network, and I would like to test it over a slow network. I'm looking for a tool to simulate these kind of connections. I'm only interested in Windows tools. | I've used Traffic Shaper XP on my XP dev box at work. It seems to handle any connection (not just HTTP). It wasn't perfect, but worked well enough for the tests I was doing. If you're on Windows maybe it'll do enough for you. | Tools for degrading my network connection? I've written some applications than heavily use network, and I would like to test it over a slow network. I'm looking for a tool to simulate these kind of connections. I'm only interested in Windows tools. | TITLE:
Tools for degrading my network connection?
QUESTION:
I've written some applications than heavily use network, and I would like to test it over a slow network. I'm looking for a tool to simulate these kind of connections. I'm only interested in Windows tools.
ANSWER:
I've used Traffic Shaper XP on my XP dev box at work. It seems to handle any connection (not just HTTP). It wasn't perfect, but worked well enough for the tests I was doing. If you're on Windows maybe it'll do enough for you. | [
"networking",
"bandwidth",
"throttling"
] | 18 | 9 | 13,742 | 10 | 0 | 2008-09-02T09:41:23.410000 | 2008-09-02T16:02:18.097000 |
39,112 | 40,065 | What is the best way to lock cache in asp.net? | I know in certain circumstances, such as long running processes, it is important to lock ASP.NET cache in order to avoid subsequent requests by another user for that resource from executing the long process again instead of hitting the cache. What is the best way in c# to implement cache locking in ASP.NET? | Here's the basic pattern: Check the cache for the value, return if its available If the value is not in the cache, then implement a lock Inside the lock, check the cache again, you might have been blocked Perform the value look up and cache it Release the lock In code, it looks like this: private static object ThisLock = new object();
public string GetFoo() {
// try to pull from cache here
lock (ThisLock) { // cache was empty before we got the lock, check again inside the lock
// cache is still empty, so retreive the value here
// store the value in the cache here }
// return the cached value here
} | What is the best way to lock cache in asp.net? I know in certain circumstances, such as long running processes, it is important to lock ASP.NET cache in order to avoid subsequent requests by another user for that resource from executing the long process again instead of hitting the cache. What is the best way in c# to implement cache locking in ASP.NET? | TITLE:
What is the best way to lock cache in asp.net?
QUESTION:
I know in certain circumstances, such as long running processes, it is important to lock ASP.NET cache in order to avoid subsequent requests by another user for that resource from executing the long process again instead of hitting the cache. What is the best way in c# to implement cache locking in ASP.NET?
ANSWER:
Here's the basic pattern: Check the cache for the value, return if its available If the value is not in the cache, then implement a lock Inside the lock, check the cache again, you might have been blocked Perform the value look up and cache it Release the lock In code, it looks like this: private static object ThisLock = new object();
public string GetFoo() {
// try to pull from cache here
lock (ThisLock) { // cache was empty before we got the lock, check again inside the lock
// cache is still empty, so retreive the value here
// store the value in the cache here }
// return the cached value here
} | [
"c#",
".net",
"asp.net",
"caching"
] | 81 | 117 | 42,690 | 9 | 0 | 2008-09-02T09:42:44.373000 | 2008-09-02T17:12:26.023000 |
39,116 | 39,147 | Linking statically in C# | I'm working on a module for a CMS. This module is distributed as a class library DLL. I have several utility libraries I'd like to use in this module. Is there anyway I can link these libraries statically so I won't have to distribute several DLL's (thereby distributing my utility libraries separately)? I would like to have only one DLL. | You can merge your many DLLs with ILMERGE: http://research.microsoft.com/~mbarnett/ILMerge.aspx Haven't tried it myself. Hope it helps. Download here: http://www.microsoft.com/downloads/details.aspx?familyid=22914587-B4AD-4EAE-87CF-B14AE6A939B0&displaylang=en Brief Description (from download-page) ILMerge is a utility for merging multiple.NET assemblies into a single.NET assembly. It works on executables and DLLs alike and comes with several options for controlling the processing and format of the output. See the accompanying documentation for details. | Linking statically in C# I'm working on a module for a CMS. This module is distributed as a class library DLL. I have several utility libraries I'd like to use in this module. Is there anyway I can link these libraries statically so I won't have to distribute several DLL's (thereby distributing my utility libraries separately)? I would like to have only one DLL. | TITLE:
Linking statically in C#
QUESTION:
I'm working on a module for a CMS. This module is distributed as a class library DLL. I have several utility libraries I'd like to use in this module. Is there anyway I can link these libraries statically so I won't have to distribute several DLL's (thereby distributing my utility libraries separately)? I would like to have only one DLL.
ANSWER:
You can merge your many DLLs with ILMERGE: http://research.microsoft.com/~mbarnett/ILMerge.aspx Haven't tried it myself. Hope it helps. Download here: http://www.microsoft.com/downloads/details.aspx?familyid=22914587-B4AD-4EAE-87CF-B14AE6A939B0&displaylang=en Brief Description (from download-page) ILMerge is a utility for merging multiple.NET assemblies into a single.NET assembly. It works on executables and DLLs alike and comes with several options for controlling the processing and format of the output. See the accompanying documentation for details. | [
"c#",
"visual-studio-2008",
"linker"
] | 17 | 24 | 15,787 | 3 | 0 | 2008-09-02T09:44:16.400000 | 2008-09-02T10:01:43.110000 |
39,119 | 39,156 | How can I control checkboxes in a .Net Forms.TreeView? | I have a.Net desktop application with a TreeView as one of the UI elements. I want to be able to multi-select that TreeView, only that isn't supported at all. So I'm adding check-boxes to the tree, My problem is that only some items are selectable, and those that aren't can't consistently cascade selections. Is there any way to disable or hide some check-boxes while displaying others? | The default behavior of TreeView is that when the Checkboxes property is set to true, that checkboxes will be shown for all TreeNodes. The behavior that you are looking for - to disable or hide some checkboxes - is a custom modification of the normal behavior. You can create a custom implementation of TreeView or TreeNode that overrides the default behavior. One other thing to try would be to use the TreeView. StateImageList property. Some sites to check out for more info: See this post to the MSDN forums that goes through an implementation similar to what you are attempting. CodeProject: Tri-State TreeView CodeProject: How to handle custom node state images in a TreeView (e.g. tristate checkboxes) | How can I control checkboxes in a .Net Forms.TreeView? I have a.Net desktop application with a TreeView as one of the UI elements. I want to be able to multi-select that TreeView, only that isn't supported at all. So I'm adding check-boxes to the tree, My problem is that only some items are selectable, and those that aren't can't consistently cascade selections. Is there any way to disable or hide some check-boxes while displaying others? | TITLE:
How can I control checkboxes in a .Net Forms.TreeView?
QUESTION:
I have a.Net desktop application with a TreeView as one of the UI elements. I want to be able to multi-select that TreeView, only that isn't supported at all. So I'm adding check-boxes to the tree, My problem is that only some items are selectable, and those that aren't can't consistently cascade selections. Is there any way to disable or hide some check-boxes while displaying others?
ANSWER:
The default behavior of TreeView is that when the Checkboxes property is set to true, that checkboxes will be shown for all TreeNodes. The behavior that you are looking for - to disable or hide some checkboxes - is a custom modification of the normal behavior. You can create a custom implementation of TreeView or TreeNode that overrides the default behavior. One other thing to try would be to use the TreeView. StateImageList property. Some sites to check out for more info: See this post to the MSDN forums that goes through an implementation similar to what you are attempting. CodeProject: Tri-State TreeView CodeProject: How to handle custom node state images in a TreeView (e.g. tristate checkboxes) | [
".net",
"winforms",
"treeview",
"treenode"
] | 3 | 4 | 6,247 | 3 | 0 | 2008-09-02T09:46:16.940000 | 2008-09-02T10:08:44.827000 |
39,121 | 39,828 | How do I begin beta testing? | I have a project that I would like to start beta testing soon, it is a PHP/MySQL site for programmers. I have beta tested sites before however it was always in-house, and I have never done betas that could/should be seen by someone other then those associated with the project. How should I go about starting the beta, and what problems, aside from those the beta is supposed to expose, should I be prepared for? | First, accept the fact that problems with your app (code, usability, etc.) will be discovered. Then, make sure you have a clear way for users to communicate with you (form mail, email, uservoice, etc.). The easier you make this the better. For example, there is a uservoice link on every page of SO. One philosophy I strongly believe in: if it's confusing to your users, it's broken. Be willing to change your app (no matter how "beautiful" the design may be) if your users are confused or not liking it. This doesn't mean you have to cave on your decisions, just that you need to consider revisions to improve the user experience. | How do I begin beta testing? I have a project that I would like to start beta testing soon, it is a PHP/MySQL site for programmers. I have beta tested sites before however it was always in-house, and I have never done betas that could/should be seen by someone other then those associated with the project. How should I go about starting the beta, and what problems, aside from those the beta is supposed to expose, should I be prepared for? | TITLE:
How do I begin beta testing?
QUESTION:
I have a project that I would like to start beta testing soon, it is a PHP/MySQL site for programmers. I have beta tested sites before however it was always in-house, and I have never done betas that could/should be seen by someone other then those associated with the project. How should I go about starting the beta, and what problems, aside from those the beta is supposed to expose, should I be prepared for?
ANSWER:
First, accept the fact that problems with your app (code, usability, etc.) will be discovered. Then, make sure you have a clear way for users to communicate with you (form mail, email, uservoice, etc.). The easier you make this the better. For example, there is a uservoice link on every page of SO. One philosophy I strongly believe in: if it's confusing to your users, it's broken. Be willing to change your app (no matter how "beautiful" the design may be) if your users are confused or not liking it. This doesn't mean you have to cave on your decisions, just that you need to consider revisions to improve the user experience. | [
"testing",
"beta"
] | 4 | 7 | 586 | 4 | 0 | 2008-09-02T09:46:36.907000 | 2008-09-02T15:40:08.993000 |
39,154 | 39,179 | Do you version "derived" files? | Using online interfaces to a version control system is a nice way to have a published location for the most recent versions of code. For example, I have a LaTeX package here (which is released to CTAN whenever changes are verified to actually work): http://github.com/wspr/pstool/tree/master The package itself is derived from a single file (in this case, pstool.tex) which, when processed, produces the documentation, the readme, the installer file, and the actual files that make up the package as it is used by LaTeX. In order to make it easy for users who want to download this stuff, I include all of the derived files mentioned above in the repository itself as well as the master file pstool.tex. This means that I'll have double the number of changes every time I commit because the package file pstool.sty is a generated subset of the master file. Is this a perversion of version control? @ Jon Limjap raised a good point: Is there another way for you to publish your generated files elsewhere for download, instead of relying on your version control to be your download server? That's really the crux of the matter in this case. Yes, released versions of the package can be obtained from elsewhere. So it does really make more sense to only version the non-generated files. On the other hand, @ Madir 's comment that: the convenience, which is real and repeated, outweighs cost, which is borne behind the scenes is also rather pertinent in that if a user finds a bug and I fix it immediately, they can then head over to the repository and grab the file that's necessary for them to continue working without having to run any "installation" steps. And this, I think, is the more important use case for my particular set of projects. | I am using Tortoise SVN for small system ASP.NET development. Most code is interpreted ASPX, but there are around a dozen binary DLLs generated by a manual compile step. Whilst it doesn't make a lot of sense to have these source-code versioned in theory, it certainly makes it convenient to ensure they are correctly mirrored from the development environment onto the production system (one click). Also - in case of disaster - the rollback to the previous step is again one click in SVN. So I bit the bullet and included them in the SVN archive - the convenience, which is real and repeated, outweighs cost, which is borne behind the scenes. | Do you version "derived" files? Using online interfaces to a version control system is a nice way to have a published location for the most recent versions of code. For example, I have a LaTeX package here (which is released to CTAN whenever changes are verified to actually work): http://github.com/wspr/pstool/tree/master The package itself is derived from a single file (in this case, pstool.tex) which, when processed, produces the documentation, the readme, the installer file, and the actual files that make up the package as it is used by LaTeX. In order to make it easy for users who want to download this stuff, I include all of the derived files mentioned above in the repository itself as well as the master file pstool.tex. This means that I'll have double the number of changes every time I commit because the package file pstool.sty is a generated subset of the master file. Is this a perversion of version control? @ Jon Limjap raised a good point: Is there another way for you to publish your generated files elsewhere for download, instead of relying on your version control to be your download server? That's really the crux of the matter in this case. Yes, released versions of the package can be obtained from elsewhere. So it does really make more sense to only version the non-generated files. On the other hand, @ Madir 's comment that: the convenience, which is real and repeated, outweighs cost, which is borne behind the scenes is also rather pertinent in that if a user finds a bug and I fix it immediately, they can then head over to the repository and grab the file that's necessary for them to continue working without having to run any "installation" steps. And this, I think, is the more important use case for my particular set of projects. | TITLE:
Do you version "derived" files?
QUESTION:
Using online interfaces to a version control system is a nice way to have a published location for the most recent versions of code. For example, I have a LaTeX package here (which is released to CTAN whenever changes are verified to actually work): http://github.com/wspr/pstool/tree/master The package itself is derived from a single file (in this case, pstool.tex) which, when processed, produces the documentation, the readme, the installer file, and the actual files that make up the package as it is used by LaTeX. In order to make it easy for users who want to download this stuff, I include all of the derived files mentioned above in the repository itself as well as the master file pstool.tex. This means that I'll have double the number of changes every time I commit because the package file pstool.sty is a generated subset of the master file. Is this a perversion of version control? @ Jon Limjap raised a good point: Is there another way for you to publish your generated files elsewhere for download, instead of relying on your version control to be your download server? That's really the crux of the matter in this case. Yes, released versions of the package can be obtained from elsewhere. So it does really make more sense to only version the non-generated files. On the other hand, @ Madir 's comment that: the convenience, which is real and repeated, outweighs cost, which is borne behind the scenes is also rather pertinent in that if a user finds a bug and I fix it immediately, they can then head over to the repository and grab the file that's necessary for them to continue working without having to run any "installation" steps. And this, I think, is the more important use case for my particular set of projects.
ANSWER:
I am using Tortoise SVN for small system ASP.NET development. Most code is interpreted ASPX, but there are around a dozen binary DLLs generated by a manual compile step. Whilst it doesn't make a lot of sense to have these source-code versioned in theory, it certainly makes it convenient to ensure they are correctly mirrored from the development environment onto the production system (one click). Also - in case of disaster - the rollback to the previous step is again one click in SVN. So I bit the bullet and included them in the SVN archive - the convenience, which is real and repeated, outweighs cost, which is borne behind the scenes. | [
"version-control",
"versioning",
"revision-history",
"revisions"
] | 2 | 2 | 255 | 5 | 0 | 2008-09-02T10:06:25.487000 | 2008-09-02T10:25:26.237000 |
39,187 | 280,699 | How do I install a color theme for IntelliJ IDEA 7.0.x | I prefer dark backgrounds for coding, and I've downloaded a jar file containing an IntelliJ IDEA color theme that has a dark background. How do I tell IntelliJ about it? | Go to File->Import Settings... and select the jar settings file Update as of IntelliJ 2020: Go to File -> Manage IDE Settings -> Import Settings... | How do I install a color theme for IntelliJ IDEA 7.0.x I prefer dark backgrounds for coding, and I've downloaded a jar file containing an IntelliJ IDEA color theme that has a dark background. How do I tell IntelliJ about it? | TITLE:
How do I install a color theme for IntelliJ IDEA 7.0.x
QUESTION:
I prefer dark backgrounds for coding, and I've downloaded a jar file containing an IntelliJ IDEA color theme that has a dark background. How do I tell IntelliJ about it?
ANSWER:
Go to File->Import Settings... and select the jar settings file Update as of IntelliJ 2020: Go to File -> Manage IDE Settings -> Import Settings... | [
"intellij-idea",
"color-scheme"
] | 77 | 127 | 153,092 | 9 | 0 | 2008-09-02T10:31:38.813000 | 2008-11-11T11:54:04.883000 |
39,194 | 39,309 | Do I need a Mac to make a Java application bundle? | I want to create a Java application bundle for Mac without using Mac. According to Java Deployment Options for Mac OS X, I can do this by using Xcode, Jar Bundler, or from the command line. Once the files and folders are set up, all I need for the command line method is to call /Developer/Tools/SetFile. Is there a SetFile clone on Linux or Windows? If not, do I have to get a Mac? | A Java application bundle on OS X is nothing more than a directory containing your.jars and a number of configuration files. The SetFile tool sets a custom HFS filesystem property on the directory to tell finder that it is an app, but giving it a ".app" extension serves the same purpose. I don't think there's anything stopping you from building one on, say, Windows, though of course you have no way of testing that it works, but if you are able to test it at least once on a real Mac, you could then conceivably update the.jars within it on Windows to reflect code changes without too much difficulty. Have a look at the Bundle Programming Guide for more info. | Do I need a Mac to make a Java application bundle? I want to create a Java application bundle for Mac without using Mac. According to Java Deployment Options for Mac OS X, I can do this by using Xcode, Jar Bundler, or from the command line. Once the files and folders are set up, all I need for the command line method is to call /Developer/Tools/SetFile. Is there a SetFile clone on Linux or Windows? If not, do I have to get a Mac? | TITLE:
Do I need a Mac to make a Java application bundle?
QUESTION:
I want to create a Java application bundle for Mac without using Mac. According to Java Deployment Options for Mac OS X, I can do this by using Xcode, Jar Bundler, or from the command line. Once the files and folders are set up, all I need for the command line method is to call /Developer/Tools/SetFile. Is there a SetFile clone on Linux or Windows? If not, do I have to get a Mac?
ANSWER:
A Java application bundle on OS X is nothing more than a directory containing your.jars and a number of configuration files. The SetFile tool sets a custom HFS filesystem property on the directory to tell finder that it is an app, but giving it a ".app" extension serves the same purpose. I don't think there's anything stopping you from building one on, say, Windows, though of course you have no way of testing that it works, but if you are able to test it at least once on a real Mac, you could then conceivably update the.jars within it on Windows to reflect code changes without too much difficulty. Have a look at the Bundle Programming Guide for more info. | [
"java",
"macos",
"deployment"
] | 8 | 6 | 2,377 | 4 | 0 | 2008-09-02T10:37:06.333000 | 2008-09-02T11:48:56.990000 |
39,222 | 39,238 | Portably handle exceptional errors in C++ | I'm working on porting a Visual C++ application to GCC (should build on MingW and Linux). The existing code uses __try {... } __except(1) {... } blocks in a few places so that almost nothing (short of maybe out of memory type errors?) would make the program exit without doing some minimal logging. What are the options for doing something similar with GCC? Edit: Thanks for the pointer to /EH options in Visual Studio, what I need now is some examples on how to handle signals on Linux. I've found this message from 2002. What other signals besides SIGFPE and SIGSEVG should I watch out for? (Mostly care about ones that might be raised from me doing something wrong) Bounty Information: I want my application to be able to self-log as many error conditions as possible before it exits. What signals might I get and which would generally be impossible to log an error message after? (Out of memory, what else?) How can I handle exceptions and (most importantly) signals in a portable way that the code at least works the same on Linux and MingW. #ifdef is OK. The reason I don't just have a wrapper process that logs the failure is that for performance reasons I save writing some data to disk till the last minute, so if something goes wrong I want to make all possible attempts to write the data out before exiting. | try { xxx } catch(...) { xxx } would be more portable but might not catch as much. It depends on compiler settings and environments. Using the default VC++ settings, asynchronous (SEH) errors are not delivered to the C++ EH infrastructure; to catch them you need to use SEH handlers (__try/__except) instead. VC++ allows you to route SEH errors through C++ error-handling, which allows a catch(...) to trap SEH errors; this includes memory errors such as null pointer dereferences. Details. On Linux, however, many of the errors that Windows uses SEH for are indicated through signals. These are not ever caught by try/catch; to handle them you need a signal handler. | Portably handle exceptional errors in C++ I'm working on porting a Visual C++ application to GCC (should build on MingW and Linux). The existing code uses __try {... } __except(1) {... } blocks in a few places so that almost nothing (short of maybe out of memory type errors?) would make the program exit without doing some minimal logging. What are the options for doing something similar with GCC? Edit: Thanks for the pointer to /EH options in Visual Studio, what I need now is some examples on how to handle signals on Linux. I've found this message from 2002. What other signals besides SIGFPE and SIGSEVG should I watch out for? (Mostly care about ones that might be raised from me doing something wrong) Bounty Information: I want my application to be able to self-log as many error conditions as possible before it exits. What signals might I get and which would generally be impossible to log an error message after? (Out of memory, what else?) How can I handle exceptions and (most importantly) signals in a portable way that the code at least works the same on Linux and MingW. #ifdef is OK. The reason I don't just have a wrapper process that logs the failure is that for performance reasons I save writing some data to disk till the last minute, so if something goes wrong I want to make all possible attempts to write the data out before exiting. | TITLE:
Portably handle exceptional errors in C++
QUESTION:
I'm working on porting a Visual C++ application to GCC (should build on MingW and Linux). The existing code uses __try {... } __except(1) {... } blocks in a few places so that almost nothing (short of maybe out of memory type errors?) would make the program exit without doing some minimal logging. What are the options for doing something similar with GCC? Edit: Thanks for the pointer to /EH options in Visual Studio, what I need now is some examples on how to handle signals on Linux. I've found this message from 2002. What other signals besides SIGFPE and SIGSEVG should I watch out for? (Mostly care about ones that might be raised from me doing something wrong) Bounty Information: I want my application to be able to self-log as many error conditions as possible before it exits. What signals might I get and which would generally be impossible to log an error message after? (Out of memory, what else?) How can I handle exceptions and (most importantly) signals in a portable way that the code at least works the same on Linux and MingW. #ifdef is OK. The reason I don't just have a wrapper process that logs the failure is that for performance reasons I save writing some data to disk till the last minute, so if something goes wrong I want to make all possible attempts to write the data out before exiting.
ANSWER:
try { xxx } catch(...) { xxx } would be more portable but might not catch as much. It depends on compiler settings and environments. Using the default VC++ settings, asynchronous (SEH) errors are not delivered to the C++ EH infrastructure; to catch them you need to use SEH handlers (__try/__except) instead. VC++ allows you to route SEH errors through C++ error-handling, which allows a catch(...) to trap SEH errors; this includes memory errors such as null pointer dereferences. Details. On Linux, however, many of the errors that Windows uses SEH for are indicated through signals. These are not ever caught by try/catch; to handle them you need a signal handler. | [
"exception",
"visual-c++",
"gcc",
"cross-platform",
"portability"
] | 7 | 12 | 3,032 | 5 | 0 | 2008-09-02T10:57:10.873000 | 2008-09-02T11:11:01.103000 |
39,229 | 39,232 | Can I use other IDEs other than Visual Studio for coding in .net? | What are the options? How popular are they? Do these IDEs give similar/better functionality compared to visual studio? | Yes - you can try using SharpDevelop: http://www.icsharpcode.net/OpenSource/SD/ Or you can just use notepad, or notepad++ http://notepad-plus.sourceforge.net/ Then compile on the command line. Edit: If you're looking for a free solution - try Visual Studio C# Express Edition: http://www.microsoft.com/express/vcsharp/ | Can I use other IDEs other than Visual Studio for coding in .net? What are the options? How popular are they? Do these IDEs give similar/better functionality compared to visual studio? | TITLE:
Can I use other IDEs other than Visual Studio for coding in .net?
QUESTION:
What are the options? How popular are they? Do these IDEs give similar/better functionality compared to visual studio?
ANSWER:
Yes - you can try using SharpDevelop: http://www.icsharpcode.net/OpenSource/SD/ Or you can just use notepad, or notepad++ http://notepad-plus.sourceforge.net/ Then compile on the command line. Edit: If you're looking for a free solution - try Visual Studio C# Express Edition: http://www.microsoft.com/express/vcsharp/ | [
".net",
"visual-studio"
] | 5 | 5 | 1,201 | 5 | 0 | 2008-09-02T11:07:23.250000 | 2008-09-02T11:08:14.030000 |
39,240 | 39,316 | "Similar Posts" like functionality using MS SQL Server? | I have lots of article store in MS SQL server 2005 database in a table called Articles- "Articles (ArticleID, ArticleTitle, ArticleContent)" Now I want some SP or SQL query which could return me similar Article against any user's input (very much like "Similar Posts" in blogs OR "Related Questions" in stackoverflow). The matching should work on both ArticleTitle and ArticleContent. The query should be intelligent enough to sort the result on the basis on their relevancy. Is it possible to do this in MS SQL Server 2005? | Something like this might work, a kind of ranking system. You would probably have to split the string in your application to build a SQL string, but I have used similar to build an effective site search. Select Top 10 ArticleID, ArticleTitle, ArticleContent From Articles Order By (Case When ArticleTitle = 'Article Title' Then 1 Else 0 End) Desc, (Case When ArticleTitle = 'Article' Then 1 Else 0 End) Desc, (Case When ArticleTitle = 'Title' Then 1 Else 0 End) Desc, (Case When Soundex('Article Title') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc, (Case When Soundex('Article') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc, (Case When Soundex('Title') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc, (Case When PatIndex('%Article%Title%', ArticleTitle) > 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Article%', ArticleTitle) > 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Title%', ArticleTitle) > 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Article%Title%', ArticleContent) > 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Article%', ArticleContent) > 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Title%', ArticleContent) > 0 Then 1 Else 0 End) Desc You can then add/remove case statements from the order by clause to improve the list based on your data. | "Similar Posts" like functionality using MS SQL Server? I have lots of article store in MS SQL server 2005 database in a table called Articles- "Articles (ArticleID, ArticleTitle, ArticleContent)" Now I want some SP or SQL query which could return me similar Article against any user's input (very much like "Similar Posts" in blogs OR "Related Questions" in stackoverflow). The matching should work on both ArticleTitle and ArticleContent. The query should be intelligent enough to sort the result on the basis on their relevancy. Is it possible to do this in MS SQL Server 2005? | TITLE:
"Similar Posts" like functionality using MS SQL Server?
QUESTION:
I have lots of article store in MS SQL server 2005 database in a table called Articles- "Articles (ArticleID, ArticleTitle, ArticleContent)" Now I want some SP or SQL query which could return me similar Article against any user's input (very much like "Similar Posts" in blogs OR "Related Questions" in stackoverflow). The matching should work on both ArticleTitle and ArticleContent. The query should be intelligent enough to sort the result on the basis on their relevancy. Is it possible to do this in MS SQL Server 2005?
ANSWER:
Something like this might work, a kind of ranking system. You would probably have to split the string in your application to build a SQL string, but I have used similar to build an effective site search. Select Top 10 ArticleID, ArticleTitle, ArticleContent From Articles Order By (Case When ArticleTitle = 'Article Title' Then 1 Else 0 End) Desc, (Case When ArticleTitle = 'Article' Then 1 Else 0 End) Desc, (Case When ArticleTitle = 'Title' Then 1 Else 0 End) Desc, (Case When Soundex('Article Title') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc, (Case When Soundex('Article') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc, (Case When Soundex('Title') = Soundex(ArticleTitle) Then 1 Else 0 End) Desc, (Case When PatIndex('%Article%Title%', ArticleTitle) > 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Article%', ArticleTitle) > 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Title%', ArticleTitle) > 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Article%Title%', ArticleContent) > 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Article%', ArticleContent) > 0 Then 1 Else 0 End) Desc, (Case When PatIndex('%Title%', ArticleContent) > 0 Then 1 Else 0 End) Desc You can then add/remove case statements from the order by clause to improve the list based on your data. | [
"sql",
"sql-server",
"database"
] | 2 | 1 | 1,509 | 3 | 0 | 2008-09-02T11:12:35 | 2008-09-02T11:52:02.130000 |
39,243 | 39,311 | Query to identify the number of revisions made to a table | Is there any query which can return me the number of revisions made to the structure of a database table? Secondly, how can I determine the number of pages (in terms of size) present in mdf or ldf files? | You can get last modify date or creation date of object in SQL Server. For examle info on tables: SELECT * FROM sys.objects WHERE type='U' More info on msdn Number of pages can be fetched from sys.database_files. Check documentation | Query to identify the number of revisions made to a table Is there any query which can return me the number of revisions made to the structure of a database table? Secondly, how can I determine the number of pages (in terms of size) present in mdf or ldf files? | TITLE:
Query to identify the number of revisions made to a table
QUESTION:
Is there any query which can return me the number of revisions made to the structure of a database table? Secondly, how can I determine the number of pages (in terms of size) present in mdf or ldf files?
ANSWER:
You can get last modify date or creation date of object in SQL Server. For examle info on tables: SELECT * FROM sys.objects WHERE type='U' More info on msdn Number of pages can be fetched from sys.database_files. Check documentation | [
"sql-server"
] | 0 | 1 | 142 | 3 | 0 | 2008-09-02T11:14:36.133000 | 2008-09-02T11:49:20.857000 |
39,281 | 39,360 | Database Design for Revisions? | We have a requirement in project to store all the revisions(Change History) for the entities in the database. Currently we have 2 designed proposals for this: e.g. for "Employee" Entity Design 1: -- Holds Employee Entity "Employees (EmployeeId, FirstName, LastName, DepartmentId,..,..)"
-- Holds the Employee Revisions in Xml. The RevisionXML will contain -- all data of that particular EmployeeId "EmployeeHistories (EmployeeId, DateModified, RevisionXML)" Design 2: -- Holds Employee Entity "Employees (EmployeeId, FirstName, LastName, DepartmentId,..,..)"
-- In this approach we have basically duplicated all the fields on Employees -- in the EmployeeHistories and storing the revision data. "EmployeeHistories (EmployeeId, RevisionId, DateModified, FirstName, LastName, DepartmentId,..,..)" Is there any other way of doing this thing? The problem with the "Design 1" is that we have to parse XML each time when you need to access data. This will slow the process and also add some limitations like we cannot add joins on the revisions data fields. And the problem with the "Design 2" is that we have to duplicate each and every field on all entities (We have around 70-80 entities for which we want to maintain revisions). | Do not put it all in one table with an IsCurrent discriminator attribute. This just causes problems down the line, requires surrogate keys and all sorts of other problems. Design 2 does have problems with schema changes. If you change the Employees table you have to change the EmployeeHistories table and all the related sprocs that go with it. Potentially doubles you schema change effort. Design 1 works well and if done properly does not cost much in terms of a performance hit. You could use an xml schema and even indexes to get over possible performance problems. Your comment about parsing the xml is valid but you could easily create a view using xquery - which you can include in queries and join to. Something like this... CREATE VIEW EmployeeHistory AS, FirstName,, DepartmentId
SELECT EmployeeId, RevisionXML.value('(/employee/FirstName)[1]', 'varchar(50)') AS FirstName,
RevisionXML.value('(/employee/LastName)[1]', 'varchar(100)') AS LastName,
RevisionXML.value('(/employee/DepartmentId)[1]', 'integer') AS DepartmentId,
FROM EmployeeHistories | Database Design for Revisions? We have a requirement in project to store all the revisions(Change History) for the entities in the database. Currently we have 2 designed proposals for this: e.g. for "Employee" Entity Design 1: -- Holds Employee Entity "Employees (EmployeeId, FirstName, LastName, DepartmentId,..,..)"
-- Holds the Employee Revisions in Xml. The RevisionXML will contain -- all data of that particular EmployeeId "EmployeeHistories (EmployeeId, DateModified, RevisionXML)" Design 2: -- Holds Employee Entity "Employees (EmployeeId, FirstName, LastName, DepartmentId,..,..)"
-- In this approach we have basically duplicated all the fields on Employees -- in the EmployeeHistories and storing the revision data. "EmployeeHistories (EmployeeId, RevisionId, DateModified, FirstName, LastName, DepartmentId,..,..)" Is there any other way of doing this thing? The problem with the "Design 1" is that we have to parse XML each time when you need to access data. This will slow the process and also add some limitations like we cannot add joins on the revisions data fields. And the problem with the "Design 2" is that we have to duplicate each and every field on all entities (We have around 70-80 entities for which we want to maintain revisions). | TITLE:
Database Design for Revisions?
QUESTION:
We have a requirement in project to store all the revisions(Change History) for the entities in the database. Currently we have 2 designed proposals for this: e.g. for "Employee" Entity Design 1: -- Holds Employee Entity "Employees (EmployeeId, FirstName, LastName, DepartmentId,..,..)"
-- Holds the Employee Revisions in Xml. The RevisionXML will contain -- all data of that particular EmployeeId "EmployeeHistories (EmployeeId, DateModified, RevisionXML)" Design 2: -- Holds Employee Entity "Employees (EmployeeId, FirstName, LastName, DepartmentId,..,..)"
-- In this approach we have basically duplicated all the fields on Employees -- in the EmployeeHistories and storing the revision data. "EmployeeHistories (EmployeeId, RevisionId, DateModified, FirstName, LastName, DepartmentId,..,..)" Is there any other way of doing this thing? The problem with the "Design 1" is that we have to parse XML each time when you need to access data. This will slow the process and also add some limitations like we cannot add joins on the revisions data fields. And the problem with the "Design 2" is that we have to duplicate each and every field on all entities (We have around 70-80 entities for which we want to maintain revisions).
ANSWER:
Do not put it all in one table with an IsCurrent discriminator attribute. This just causes problems down the line, requires surrogate keys and all sorts of other problems. Design 2 does have problems with schema changes. If you change the Employees table you have to change the EmployeeHistories table and all the related sprocs that go with it. Potentially doubles you schema change effort. Design 1 works well and if done properly does not cost much in terms of a performance hit. You could use an xml schema and even indexes to get over possible performance problems. Your comment about parsing the xml is valid but you could easily create a view using xquery - which you can include in queries and join to. Something like this... CREATE VIEW EmployeeHistory AS, FirstName,, DepartmentId
SELECT EmployeeId, RevisionXML.value('(/employee/FirstName)[1]', 'varchar(50)') AS FirstName,
RevisionXML.value('(/employee/LastName)[1]', 'varchar(100)') AS LastName,
RevisionXML.value('(/employee/DepartmentId)[1]', 'integer') AS DepartmentId,
FROM EmployeeHistories | [
"sql",
"database",
"database-design",
"versioning"
] | 132 | 42 | 46,030 | 16 | 0 | 2008-09-02T11:36:38.517000 | 2008-09-02T12:13:47.380000 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.