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
22,903
22,911
How do I stop Windows applications from stealing focus
I know this isn't strictly a programming question but y'all must have experienced this. So...you have four or five RDP sessions open over the corp VPN, you're bashing away inside your favourite IDE, your VPN to the data centre bounces briefly then recovers, all your RDP sessions start re-establishing their connections and whilst doing so sequentially keep grabbing focus, one after the other. Pretty bloody annoying and downright rude. Any idea how to prevent this behaviour and just make the RDP client flash it's taskbar button instead of totally grabbing focus away from whatever you were doing? @ Jason - thanks for the reply, I'm running 64 bit Vista and 64 Bit Windows 2008. Any ideas how well it plays? @ Jason - good idea. Done. @ Ryan - thanks also for the answer. I tried Terminals a few times before, but quite often I need to see two or three sessions side by side which the tabbing doesn't really facilitate too well, would've been nice to have a 'pop out in own window' button. I did once grab the source code to fix stuff like that, but never got the time. I also found it behaved oddly whenever there was a brief network disconnect (e.g. xDSL flapping) and it would reconnect to the wrong session (usually a new one) and leave the session I had opened in a disconnected state on the server. Otherwise Terminals would've been really cool, we have 200+ windows servers, and organising all those.rdp files can be a pain.
I use Tweak UI to configure explorer so that apps don't steal focus; you can also configure how many times they flash in the taskbar as well. EDIT: Once you are within Tweak UI, these options are found under General > Focus. EDIT: @Kev, apparently there is a 64-bit version (not MS approved, apparently, I would scan it for viruses of course) that works successfully with the 64-bit version of XP. From what I understand, you download that and then run it in XP compatibility mode as administrator and it will do the trick. Tweak UI is basically a nice wrapper around a collection of registry hacks, so I imagine you could find the hacks themselves if you didn't care for running Tweak UI in this manner. Hope that works for you!
How do I stop Windows applications from stealing focus I know this isn't strictly a programming question but y'all must have experienced this. So...you have four or five RDP sessions open over the corp VPN, you're bashing away inside your favourite IDE, your VPN to the data centre bounces briefly then recovers, all your RDP sessions start re-establishing their connections and whilst doing so sequentially keep grabbing focus, one after the other. Pretty bloody annoying and downright rude. Any idea how to prevent this behaviour and just make the RDP client flash it's taskbar button instead of totally grabbing focus away from whatever you were doing? @ Jason - thanks for the reply, I'm running 64 bit Vista and 64 Bit Windows 2008. Any ideas how well it plays? @ Jason - good idea. Done. @ Ryan - thanks also for the answer. I tried Terminals a few times before, but quite often I need to see two or three sessions side by side which the tabbing doesn't really facilitate too well, would've been nice to have a 'pop out in own window' button. I did once grab the source code to fix stuff like that, but never got the time. I also found it behaved oddly whenever there was a brief network disconnect (e.g. xDSL flapping) and it would reconnect to the wrong session (usually a new one) and leave the session I had opened in a disconnected state on the server. Otherwise Terminals would've been really cool, we have 200+ windows servers, and organising all those.rdp files can be a pain.
TITLE: How do I stop Windows applications from stealing focus QUESTION: I know this isn't strictly a programming question but y'all must have experienced this. So...you have four or five RDP sessions open over the corp VPN, you're bashing away inside your favourite IDE, your VPN to the data centre bounces briefly then recovers, all your RDP sessions start re-establishing their connections and whilst doing so sequentially keep grabbing focus, one after the other. Pretty bloody annoying and downright rude. Any idea how to prevent this behaviour and just make the RDP client flash it's taskbar button instead of totally grabbing focus away from whatever you were doing? @ Jason - thanks for the reply, I'm running 64 bit Vista and 64 Bit Windows 2008. Any ideas how well it plays? @ Jason - good idea. Done. @ Ryan - thanks also for the answer. I tried Terminals a few times before, but quite often I need to see two or three sessions side by side which the tabbing doesn't really facilitate too well, would've been nice to have a 'pop out in own window' button. I did once grab the source code to fix stuff like that, but never got the time. I also found it behaved oddly whenever there was a brief network disconnect (e.g. xDSL flapping) and it would reconnect to the wrong session (usually a new one) and leave the session I had opened in a disconnected state on the server. Otherwise Terminals would've been really cool, we have 200+ windows servers, and organising all those.rdp files can be a pain. ANSWER: I use Tweak UI to configure explorer so that apps don't steal focus; you can also configure how many times they flash in the taskbar as well. EDIT: Once you are within Tweak UI, these options are found under General > Focus. EDIT: @Kev, apparently there is a 64-bit version (not MS approved, apparently, I would scan it for viruses of course) that works successfully with the 64-bit version of XP. From what I understand, you download that and then run it in XP compatibility mode as administrator and it will do the trick. Tweak UI is basically a nice wrapper around a collection of registry hacks, so I imagine you could find the hacks themselves if you didn't care for running Tweak UI in this manner. Hope that works for you!
[ "terminal-services", "rdp" ]
7
6
8,586
3
0
2008-08-22T17:09:14.593000
2008-08-22T17:11:21.500000
22,907
22,970
Which is better: Ad hoc queries or stored procedures?
Assuming you can't use LINQ for whatever reason, is it a better practice to place your queries in stored procedures, or is it just as good a practice to execute ad hoc queries against the database (say, SQL Server for argument's sake)?
In my experience writing mostly WinForms Client/Server apps these are the simple conclusions I've come to: Use Stored Procedures: For any complex data work. If you're going to be doing something truly requiring a cursor or temp tables it's usually fastest to do it within SQL Server. When you need to lock down access to the data. If you don't give table access to users (or role or whatever) you can be sure that the only way to interact with the data is through the SP's you create. Use ad-hoc queries: For CRUD when you don't need to restrict data access (or are doing so in another manner). For simple searches. Creating SP's for a bunch of search criteria is a pain and difficult to maintain. If you can generate a reasonably fast search query use that. In most of my applications I've used both SP's and ad-hoc sql, though I find I'm using SP's less and less as they end up being code just like C#, only harder to version control, test, and maintain. I would recommend using ad-hoc sql unless you can find a specific reason not to.
Which is better: Ad hoc queries or stored procedures? Assuming you can't use LINQ for whatever reason, is it a better practice to place your queries in stored procedures, or is it just as good a practice to execute ad hoc queries against the database (say, SQL Server for argument's sake)?
TITLE: Which is better: Ad hoc queries or stored procedures? QUESTION: Assuming you can't use LINQ for whatever reason, is it a better practice to place your queries in stored procedures, or is it just as good a practice to execute ad hoc queries against the database (say, SQL Server for argument's sake)? ANSWER: In my experience writing mostly WinForms Client/Server apps these are the simple conclusions I've come to: Use Stored Procedures: For any complex data work. If you're going to be doing something truly requiring a cursor or temp tables it's usually fastest to do it within SQL Server. When you need to lock down access to the data. If you don't give table access to users (or role or whatever) you can be sure that the only way to interact with the data is through the SP's you create. Use ad-hoc queries: For CRUD when you don't need to restrict data access (or are doing so in another manner). For simple searches. Creating SP's for a bunch of search criteria is a pain and difficult to maintain. If you can generate a reasonably fast search query use that. In most of my applications I've used both SP's and ad-hoc sql, though I find I'm using SP's less and less as they end up being code just like C#, only harder to version control, test, and maintain. I would recommend using ad-hoc sql unless you can find a specific reason not to.
[ "sql", "stored-procedures" ]
55
109
59,680
22
0
2008-08-22T17:10:30.440000
2008-08-22T17:32:28
22,909
22,930
Is there some way to show HTML content inside Flash?
I want to show HTML content inside Flash. Is there some way to do this? I am talking about full blown HTML (with JavaScript if possible).
Here is a decent article on how to accomplish that. @Flubba: I didn't say " great " article, I said " decent " - there is a big difference. Besides, no one else had answered and it had been around a while. I figured a "decent" answer was better than none. I am no Flash expert, so...
Is there some way to show HTML content inside Flash? I want to show HTML content inside Flash. Is there some way to do this? I am talking about full blown HTML (with JavaScript if possible).
TITLE: Is there some way to show HTML content inside Flash? QUESTION: I want to show HTML content inside Flash. Is there some way to do this? I am talking about full blown HTML (with JavaScript if possible). ANSWER: Here is a decent article on how to accomplish that. @Flubba: I didn't say " great " article, I said " decent " - there is a big difference. Besides, no one else had answered and it had been around a while. I figured a "decent" answer was better than none. I am no Flash expert, so...
[ "javascript", "html", "flash", "adobe" ]
13
1
14,843
6
0
2008-08-22T17:10:59.567000
2008-08-22T17:18:39.983000
22,935
22,948
CSV (or sheet in XLS) to SQL create (and insert) statements with .Net?
Does anyone have a technique for generating SQL table create (and data insert) commands pragmatically from a CSV (or sheet in a.xls) file? I've got a third party database system which I'd like to populate with data from a csv file (or sheet in a xls file) but the importer supplied can't create the table structure automatically as it does the import. My csv file has lots of tables with lots of columns so I'd like to automate the table creation process as well as the data importing if possible but I'm unsure about how to go about generating the create statement...
In SQL server it is as easy as SELECT * INTO NewTablenNmeHere FROM OPENROWSET( 'Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=C:\testing.xls','SELECT * FROM [Sheet1$]')
CSV (or sheet in XLS) to SQL create (and insert) statements with .Net? Does anyone have a technique for generating SQL table create (and data insert) commands pragmatically from a CSV (or sheet in a.xls) file? I've got a third party database system which I'd like to populate with data from a csv file (or sheet in a xls file) but the importer supplied can't create the table structure automatically as it does the import. My csv file has lots of tables with lots of columns so I'd like to automate the table creation process as well as the data importing if possible but I'm unsure about how to go about generating the create statement...
TITLE: CSV (or sheet in XLS) to SQL create (and insert) statements with .Net? QUESTION: Does anyone have a technique for generating SQL table create (and data insert) commands pragmatically from a CSV (or sheet in a.xls) file? I've got a third party database system which I'd like to populate with data from a csv file (or sheet in a xls file) but the importer supplied can't create the table structure automatically as it does the import. My csv file has lots of tables with lots of columns so I'd like to automate the table creation process as well as the data importing if possible but I'm unsure about how to go about generating the create statement... ANSWER: In SQL server it is as easy as SELECT * INTO NewTablenNmeHere FROM OPENROWSET( 'Microsoft.Jet.OLEDB.4.0', 'Excel 8.0;Database=C:\testing.xls','SELECT * FROM [Sheet1$]')
[ ".net", "sql", "csv", "xls" ]
3
1
5,234
4
0
2008-08-22T17:19:24.130000
2008-08-22T17:23:06.040000
22,943
23,038
Does anybody know of existing code to read a mork file (Thunderbird Address Book)?
I have the need to read the Thunderbird address book on the fly. It is stored in a file format called Mork. Not a pleasant file format to read. I found a 1999 article explaining the file format. I would love to know if someone already has gone through this process and could make the code available. I found mork.pl by Jamie Zawinski (he worked on Netscape Navigator), but I was hoping for a.NET solution. I'm hoping StackOverflow will come to the rescue, because this just seems like a waste of my time to write something to read this file format when it should be so simple. I love the comments that Jamie put in his perl script. Here is my favorite part: # Let me make it clear that McCusker is a complete barking lunatic. # This is just about the stupidest file format I've ever seen.
The Beagle search engine had code to parse Mork files. It's not the most memory efficient solution, but it worked and could be a useful starting point. Here's a link to the file: http://svn.gnome.org/viewvc/beagle/tags/BEAGLE_0_2_18/Util/Mork.cs?view=markup (These days Beagle doesn't use this parser anymore; we took the easier (and supported) path of writing a Thunderbird extension which just sent the data to Beagle itself. Has the disadvantage of not working while Thunderbird is closed, but has the advantage of not instilling the desire to bash your head in with the nearest blunt instrument.)
Does anybody know of existing code to read a mork file (Thunderbird Address Book)? I have the need to read the Thunderbird address book on the fly. It is stored in a file format called Mork. Not a pleasant file format to read. I found a 1999 article explaining the file format. I would love to know if someone already has gone through this process and could make the code available. I found mork.pl by Jamie Zawinski (he worked on Netscape Navigator), but I was hoping for a.NET solution. I'm hoping StackOverflow will come to the rescue, because this just seems like a waste of my time to write something to read this file format when it should be so simple. I love the comments that Jamie put in his perl script. Here is my favorite part: # Let me make it clear that McCusker is a complete barking lunatic. # This is just about the stupidest file format I've ever seen.
TITLE: Does anybody know of existing code to read a mork file (Thunderbird Address Book)? QUESTION: I have the need to read the Thunderbird address book on the fly. It is stored in a file format called Mork. Not a pleasant file format to read. I found a 1999 article explaining the file format. I would love to know if someone already has gone through this process and could make the code available. I found mork.pl by Jamie Zawinski (he worked on Netscape Navigator), but I was hoping for a.NET solution. I'm hoping StackOverflow will come to the rescue, because this just seems like a waste of my time to write something to read this file format when it should be so simple. I love the comments that Jamie put in his perl script. Here is my favorite part: # Let me make it clear that McCusker is a complete barking lunatic. # This is just about the stupidest file format I've ever seen. ANSWER: The Beagle search engine had code to parse Mork files. It's not the most memory efficient solution, but it worked and could be a useful starting point. Here's a link to the file: http://svn.gnome.org/viewvc/beagle/tags/BEAGLE_0_2_18/Util/Mork.cs?view=markup (These days Beagle doesn't use this parser anymore; we took the easier (and supported) path of writing a Thunderbird extension which just sent the data to Beagle itself. Has the disadvantage of not working while Thunderbird is closed, but has the advantage of not instilling the desire to bash your head in with the nearest blunt instrument.)
[ ".net", "file-format", "thunderbird", "mork" ]
3
4
1,149
1
0
2008-08-22T17:19:52.210000
2008-08-22T17:57:14.510000
22,968
23,148
How to process Excel files stored in an image data type column using SSIS package?
I have a.NET webforms front end that allows admin users to upload two.xls files for offline processing. As these files will be used for validation (and aggregation) I store these in an image field in a table. My ultimate goal is to create an SSIS package that will process these files offline. Does anyone know how to use SSIS to read a blob from a table into its native (in this case.xls) format for use in a Data Flow task?
In my (admittedly limited) experience with SSIS, it is quite good at rapidly getting something up and running, but frusteratingly limited in getting something that "feels" like the most elegant, efficient solution to a programmer. Since the Excel Source Editor seems to take only files as input, you need to give it a file or reimplement its functionality in code that can take a blob. I understand that this is unsatisfying, but in the end, this is a time saving tool.
How to process Excel files stored in an image data type column using SSIS package? I have a.NET webforms front end that allows admin users to upload two.xls files for offline processing. As these files will be used for validation (and aggregation) I store these in an image field in a table. My ultimate goal is to create an SSIS package that will process these files offline. Does anyone know how to use SSIS to read a blob from a table into its native (in this case.xls) format for use in a Data Flow task?
TITLE: How to process Excel files stored in an image data type column using SSIS package? QUESTION: I have a.NET webforms front end that allows admin users to upload two.xls files for offline processing. As these files will be used for validation (and aggregation) I store these in an image field in a table. My ultimate goal is to create an SSIS package that will process these files offline. Does anyone know how to use SSIS to read a blob from a table into its native (in this case.xls) format for use in a Data Flow task? ANSWER: In my (admittedly limited) experience with SSIS, it is quite good at rapidly getting something up and running, but frusteratingly limited in getting something that "feels" like the most elegant, efficient solution to a programmer. Since the Excel Source Editor seems to take only files as input, you need to give it a file or reimplement its functionality in code that can take a blob. I understand that this is unsatisfying, but in the end, this is a time saving tool.
[ "ssis" ]
3
1
2,143
1
0
2008-08-22T17:32:11.993000
2008-08-22T18:37:53.803000
22,976
23,089
How to provide namespaces in JavaScript with instanced objects
I've got a JavaScript "object", built this way: function foo() { this.length = 0; } foo.prototype.getLength = function() { return this.length; }... I know how to emulate namespaces with singleton JavaScript objects, but what is the best way to "namepace" an object such as that above that will intanced? I know that several JavaScript libraries have namepacing capabilities, but I'm using jQuery and would rather not add another library to the mix. I'd like to be able to provide my own, perhaps by exploiting jQuery, intrinsic namespacing scheme for the JS objects of mine that need to be instanced. Thanks rp
Simple: if(!MyNamespace) MyNamespace = {}; MyNamespace.foo = function() { this.length = 0; }; MyNamespace.foo.prototype.getLength = function() { return this.length; };
How to provide namespaces in JavaScript with instanced objects I've got a JavaScript "object", built this way: function foo() { this.length = 0; } foo.prototype.getLength = function() { return this.length; }... I know how to emulate namespaces with singleton JavaScript objects, but what is the best way to "namepace" an object such as that above that will intanced? I know that several JavaScript libraries have namepacing capabilities, but I'm using jQuery and would rather not add another library to the mix. I'd like to be able to provide my own, perhaps by exploiting jQuery, intrinsic namespacing scheme for the JS objects of mine that need to be instanced. Thanks rp
TITLE: How to provide namespaces in JavaScript with instanced objects QUESTION: I've got a JavaScript "object", built this way: function foo() { this.length = 0; } foo.prototype.getLength = function() { return this.length; }... I know how to emulate namespaces with singleton JavaScript objects, but what is the best way to "namepace" an object such as that above that will intanced? I know that several JavaScript libraries have namepacing capabilities, but I'm using jQuery and would rather not add another library to the mix. I'd like to be able to provide my own, perhaps by exploiting jQuery, intrinsic namespacing scheme for the JS objects of mine that need to be instanced. Thanks rp ANSWER: Simple: if(!MyNamespace) MyNamespace = {}; MyNamespace.foo = function() { this.length = 0; }; MyNamespace.foo.prototype.getLength = function() { return this.length; };
[ "javascript", "namespaces" ]
11
12
9,935
5
0
2008-08-22T17:37:07.303000
2008-08-22T18:18:30.947000
22,979
22,991
Detecting if SQL server is running
I'm looking for a way to poll different servers and check that SQL server is up and running. I'm writing my code in C#. I don't particularly care about individual databases, just that SQL server is running and responsive. Any ideas?
Well, the brute force solution is to attempt to initiate a connection with the database on each server. That will tell you whether it's running, though you could have timeout issues. The more elegant (but more difficult... isn't that always the way?) solution would be to use WMI to connect to the remote machine and find out if the SQL server process is running.
Detecting if SQL server is running I'm looking for a way to poll different servers and check that SQL server is up and running. I'm writing my code in C#. I don't particularly care about individual databases, just that SQL server is running and responsive. Any ideas?
TITLE: Detecting if SQL server is running QUESTION: I'm looking for a way to poll different servers and check that SQL server is up and running. I'm writing my code in C#. I don't particularly care about individual databases, just that SQL server is running and responsive. Any ideas? ANSWER: Well, the brute force solution is to attempt to initiate a connection with the database on each server. That will tell you whether it's running, though you could have timeout issues. The more elegant (but more difficult... isn't that always the way?) solution would be to use WMI to connect to the remote machine and find out if the SQL server process is running.
[ "c#", "sql-server" ]
8
5
14,273
6
0
2008-08-22T17:37:48.707000
2008-08-22T17:41:22.050000
22,980
23,137
Acts-as-readable Rails plugin Issue
I'm using Intridea's Acts as Readable Rails plugin for a messaging system I'm currently building. I've defined my message class accordingly: class Post < ActiveRecord::Base acts-as-readable end And everything seems to be working according to plan, but when trying to make the app show unread messages in my message view, I run into problems. Their example: (I've changed underscores to hyphens due to formatting issues) bob = User.find_by_name("bob") bob.readings # => [] Post.find_unread_by(bob) # => [,,...] Post.find_read_by(bob) # => [] Post.find(1).read_by?(bob) # => false Post.find(1).read_by!(bob) # => Post.find(1).read_by?(bob) # => true Post.find(1).users_who_read # => [ ] Post.find_unread_by(bob) # => [,...] Post.find_read_by(bob) # => [ ] bob.readings # => [ ] So it seems that if I wanted to list the number of unread messages sitting in a mailbox (for example Inbox (39) ), I should be able to do something like: <%= Post.find_unread_by(current-user).count %> But to no avail. I always seem to get stuck on the simple view issues after everything's set. Any ideas?
The following will work <%= Post.find_unread_by(current_user).size %> or <%= Post.find_unread_by(current_user).length %> However if you check your development.log you should see that it gets the unread count by Retrieving all the posts Retrieving all the posts read by the user Removing all of 2. from 1. in ruby This will be very bad performance wise with lots of posts. A better way would be to retrieve the posts read by the current user and then use ActiveRecord::Calculations to get a count without retrieving all the posts in the database Post.count(:conditions => [ "id NOT IN (?)", Post.find_read_by(current_user)]) This should go into your Post model to follow best practices of not having finders in the view or controller Post.rb def self.unread_post_count_for_user(user) count(:conditions => [ "id NOT IN (?)", Post.find_read_by(user)]) end Then your view will just be <%= Post.unread_post_count_for_user(current-user) %>
Acts-as-readable Rails plugin Issue I'm using Intridea's Acts as Readable Rails plugin for a messaging system I'm currently building. I've defined my message class accordingly: class Post < ActiveRecord::Base acts-as-readable end And everything seems to be working according to plan, but when trying to make the app show unread messages in my message view, I run into problems. Their example: (I've changed underscores to hyphens due to formatting issues) bob = User.find_by_name("bob") bob.readings # => [] Post.find_unread_by(bob) # => [,,...] Post.find_read_by(bob) # => [] Post.find(1).read_by?(bob) # => false Post.find(1).read_by!(bob) # => Post.find(1).read_by?(bob) # => true Post.find(1).users_who_read # => [ ] Post.find_unread_by(bob) # => [,...] Post.find_read_by(bob) # => [ ] bob.readings # => [ ] So it seems that if I wanted to list the number of unread messages sitting in a mailbox (for example Inbox (39) ), I should be able to do something like: <%= Post.find_unread_by(current-user).count %> But to no avail. I always seem to get stuck on the simple view issues after everything's set. Any ideas?
TITLE: Acts-as-readable Rails plugin Issue QUESTION: I'm using Intridea's Acts as Readable Rails plugin for a messaging system I'm currently building. I've defined my message class accordingly: class Post < ActiveRecord::Base acts-as-readable end And everything seems to be working according to plan, but when trying to make the app show unread messages in my message view, I run into problems. Their example: (I've changed underscores to hyphens due to formatting issues) bob = User.find_by_name("bob") bob.readings # => [] Post.find_unread_by(bob) # => [,,...] Post.find_read_by(bob) # => [] Post.find(1).read_by?(bob) # => false Post.find(1).read_by!(bob) # => Post.find(1).read_by?(bob) # => true Post.find(1).users_who_read # => [ ] Post.find_unread_by(bob) # => [,...] Post.find_read_by(bob) # => [ ] bob.readings # => [ ] So it seems that if I wanted to list the number of unread messages sitting in a mailbox (for example Inbox (39) ), I should be able to do something like: <%= Post.find_unread_by(current-user).count %> But to no avail. I always seem to get stuck on the simple view issues after everything's set. Any ideas? ANSWER: The following will work <%= Post.find_unread_by(current_user).size %> or <%= Post.find_unread_by(current_user).length %> However if you check your development.log you should see that it gets the unread count by Retrieving all the posts Retrieving all the posts read by the user Removing all of 2. from 1. in ruby This will be very bad performance wise with lots of posts. A better way would be to retrieve the posts read by the current user and then use ActiveRecord::Calculations to get a count without retrieving all the posts in the database Post.count(:conditions => [ "id NOT IN (?)", Post.find_read_by(current_user)]) This should go into your Post model to follow best practices of not having finders in the view or controller Post.rb def self.unread_post_count_for_user(user) count(:conditions => [ "id NOT IN (?)", Post.find_read_by(user)]) end Then your view will just be <%= Post.unread_post_count_for_user(current-user) %>
[ "ruby-on-rails", "ruby", "plugins" ]
9
11
637
1
0
2008-08-22T17:37:51.403000
2008-08-22T18:33:33.890000
22,981
22,992
ASP.Net: How to do pagination with a Repeater?
I'm using the Repeater control on my site to display data from the database. I need to do pagination ("now displaying page 1 of 10", 10 items per page, etc) but I'm not sure I'm going about it the best way possible. I know the Repeater control doesn't have any built-in pagination, so I'll have to make my own. Is there a way to tell the DataSource control to return rows 10-20 of a much larger result set? If not, how do I write that into a query (SQL Server 2005)? I'm currently using the TOP keyword to only return the first 10 rows, but I'm not sure how to display rows 10-20.
This isn't a way to page the data, but have you looked into the ListView control? It gives the flexibility of repeater / data list but with built in paging like the grid view. And for paging in sql, you would want to do something like this
ASP.Net: How to do pagination with a Repeater? I'm using the Repeater control on my site to display data from the database. I need to do pagination ("now displaying page 1 of 10", 10 items per page, etc) but I'm not sure I'm going about it the best way possible. I know the Repeater control doesn't have any built-in pagination, so I'll have to make my own. Is there a way to tell the DataSource control to return rows 10-20 of a much larger result set? If not, how do I write that into a query (SQL Server 2005)? I'm currently using the TOP keyword to only return the first 10 rows, but I'm not sure how to display rows 10-20.
TITLE: ASP.Net: How to do pagination with a Repeater? QUESTION: I'm using the Repeater control on my site to display data from the database. I need to do pagination ("now displaying page 1 of 10", 10 items per page, etc) but I'm not sure I'm going about it the best way possible. I know the Repeater control doesn't have any built-in pagination, so I'll have to make my own. Is there a way to tell the DataSource control to return rows 10-20 of a much larger result set? If not, how do I write that into a query (SQL Server 2005)? I'm currently using the TOP keyword to only return the first 10 rows, but I'm not sure how to display rows 10-20. ANSWER: This isn't a way to page the data, but have you looked into the ListView control? It gives the flexibility of repeater / data list but with built in paging like the grid view. And for paging in sql, you would want to do something like this
[ "asp.net", "sql-server" ]
0
2
2,013
3
0
2008-08-22T17:37:54.617000
2008-08-22T17:41:23.127000
22,988
23,007
Form post doesn't contain textbox data [ASP.NET C#]
I have several "ASP:TextBox" controls on a form (about 20). When the form loads, the text boxes are populated from a database. The user can change the populated values, and when they submit the form, I take the values posted to the server and conditionally save them (determined by some business logic). All but 1 of the text boxes work as intended. The odd box out, upon postback, does not contain the updated value that the user typed into the box. When debugging the application, it is clear that myTextBox.Text reflects the old, pre-populated value, not the new, user-supplied value. Every other box properly shows their respective user-supplied values. I did find a workaround. My solution was to basically extract the text box's value out of the Request.Form object: Request.Form[myTextBox.UniqueID], which does contain the user-supplied value. What could be going on, here? As I mentioned, the other text boxes receive the user-supplied values just fine, and this particular problematic text box doesn't have any logic associated to it -- it just takes the value and saves it. The main difference between this text box and the others is that this is a multi-line box (for inputting notes), which I believe is rendered as an HTML "textarea" tag instead of an "input" tag in ASP.NET.
Are you initially loading the data only when!Page.IsPostBack? Also, is view state enabled for the text box?
Form post doesn't contain textbox data [ASP.NET C#] I have several "ASP:TextBox" controls on a form (about 20). When the form loads, the text boxes are populated from a database. The user can change the populated values, and when they submit the form, I take the values posted to the server and conditionally save them (determined by some business logic). All but 1 of the text boxes work as intended. The odd box out, upon postback, does not contain the updated value that the user typed into the box. When debugging the application, it is clear that myTextBox.Text reflects the old, pre-populated value, not the new, user-supplied value. Every other box properly shows their respective user-supplied values. I did find a workaround. My solution was to basically extract the text box's value out of the Request.Form object: Request.Form[myTextBox.UniqueID], which does contain the user-supplied value. What could be going on, here? As I mentioned, the other text boxes receive the user-supplied values just fine, and this particular problematic text box doesn't have any logic associated to it -- it just takes the value and saves it. The main difference between this text box and the others is that this is a multi-line box (for inputting notes), which I believe is rendered as an HTML "textarea" tag instead of an "input" tag in ASP.NET.
TITLE: Form post doesn't contain textbox data [ASP.NET C#] QUESTION: I have several "ASP:TextBox" controls on a form (about 20). When the form loads, the text boxes are populated from a database. The user can change the populated values, and when they submit the form, I take the values posted to the server and conditionally save them (determined by some business logic). All but 1 of the text boxes work as intended. The odd box out, upon postback, does not contain the updated value that the user typed into the box. When debugging the application, it is clear that myTextBox.Text reflects the old, pre-populated value, not the new, user-supplied value. Every other box properly shows their respective user-supplied values. I did find a workaround. My solution was to basically extract the text box's value out of the Request.Form object: Request.Form[myTextBox.UniqueID], which does contain the user-supplied value. What could be going on, here? As I mentioned, the other text boxes receive the user-supplied values just fine, and this particular problematic text box doesn't have any logic associated to it -- it just takes the value and saves it. The main difference between this text box and the others is that this is a multi-line box (for inputting notes), which I believe is rendered as an HTML "textarea" tag instead of an "input" tag in ASP.NET. ANSWER: Are you initially loading the data only when!Page.IsPostBack? Also, is view state enabled for the text box?
[ "c#", "asp.net" ]
6
9
6,511
5
0
2008-08-22T17:40:23.893000
2008-08-22T17:43:41.560000
23,001
23,069
Any good tools to automate SQL Server management tasks?
I know I could write scripts and create jobs to run them, but at least some of what I'm wanting it to do is beyond my programming abilities for that to be an option. What I'm imagining is something that can run on a regular schedule that will examine all the databases on a server and automatically shrink data and log files (after a backup, of course) when they've reached a file size that contains too much free space. It would be nice if it could defrag index files when they've become too fragmented as well. I guess what I'm probably looking for is a DBA in a box! Or it could just be that I need better performance monitoring tools instead. I know how to take care of both of those issues, but it's more that I forget to check for those issues until I start seeing performance issues with my apps.
If you are using SQL Server 2005. Fire up the Management Studio and look at the Maintenance Plan section. See http://msdn.microsoft.com/en-us/library/ms187658.aspx for an overview and http://msdn.microsoft.com/en-us/library/ms189036.aspx for details on the Maintenance plan wizard. Finally, http://msdn.microsoft.com/en-us/library/ms140255.aspx is a list of all the maintenance tasks available. I am pretty sure this is all available even in the Express Edition. I can't speak to if anything has changed in 2008, I haven't used it yet.
Any good tools to automate SQL Server management tasks? I know I could write scripts and create jobs to run them, but at least some of what I'm wanting it to do is beyond my programming abilities for that to be an option. What I'm imagining is something that can run on a regular schedule that will examine all the databases on a server and automatically shrink data and log files (after a backup, of course) when they've reached a file size that contains too much free space. It would be nice if it could defrag index files when they've become too fragmented as well. I guess what I'm probably looking for is a DBA in a box! Or it could just be that I need better performance monitoring tools instead. I know how to take care of both of those issues, but it's more that I forget to check for those issues until I start seeing performance issues with my apps.
TITLE: Any good tools to automate SQL Server management tasks? QUESTION: I know I could write scripts and create jobs to run them, but at least some of what I'm wanting it to do is beyond my programming abilities for that to be an option. What I'm imagining is something that can run on a regular schedule that will examine all the databases on a server and automatically shrink data and log files (after a backup, of course) when they've reached a file size that contains too much free space. It would be nice if it could defrag index files when they've become too fragmented as well. I guess what I'm probably looking for is a DBA in a box! Or it could just be that I need better performance monitoring tools instead. I know how to take care of both of those issues, but it's more that I forget to check for those issues until I start seeing performance issues with my apps. ANSWER: If you are using SQL Server 2005. Fire up the Management Studio and look at the Maintenance Plan section. See http://msdn.microsoft.com/en-us/library/ms187658.aspx for an overview and http://msdn.microsoft.com/en-us/library/ms189036.aspx for details on the Maintenance plan wizard. Finally, http://msdn.microsoft.com/en-us/library/ms140255.aspx is a list of all the maintenance tasks available. I am pretty sure this is all available even in the Express Edition. I can't speak to if anything has changed in 2008, I haven't used it yet.
[ "sql-server" ]
1
2
200
4
0
2008-08-22T17:42:24.077000
2008-08-22T18:10:12.123000
23,016
23,220
Checklist for testing a new site
What are the most common things to test in a new site? For instance to prevent exploits by bots, malicious users, massive load, etc.? And just as importantly, what tools and approaches should you use? (some stress test tools are really expensive/had to use, do you write your own? etc) Common exploits that should be checked for. Edit: the reason for this question is partially from being in SO beta, however please refrain from SO beta discussion, SO beta got me thinking about my own site and good thing too. This is meant to be a checklist for things that I, you, or someone else hasn't thought of before.
Try and break your own site before someone else does. Your web site is basically a publicly accessible API that allows access to a database and other backend systems. Test the URLs as if they were any other API. I like to start by cataloging all URLs that have some sort of permenant affect on the state of the system - this is easy if you are doing Ruby on Rails development or trying to follow a RESTful design pattern. For each of those URLs, try running a GET, POST, PUT or DELETE HTTP methods with different parameters so that you can ensure that you're only giving access to what you want to give access to. This of course is in addition to obvious: Functional testing, Load Testing, SQL Injection, XSS etc.
Checklist for testing a new site What are the most common things to test in a new site? For instance to prevent exploits by bots, malicious users, massive load, etc.? And just as importantly, what tools and approaches should you use? (some stress test tools are really expensive/had to use, do you write your own? etc) Common exploits that should be checked for. Edit: the reason for this question is partially from being in SO beta, however please refrain from SO beta discussion, SO beta got me thinking about my own site and good thing too. This is meant to be a checklist for things that I, you, or someone else hasn't thought of before.
TITLE: Checklist for testing a new site QUESTION: What are the most common things to test in a new site? For instance to prevent exploits by bots, malicious users, massive load, etc.? And just as importantly, what tools and approaches should you use? (some stress test tools are really expensive/had to use, do you write your own? etc) Common exploits that should be checked for. Edit: the reason for this question is partially from being in SO beta, however please refrain from SO beta discussion, SO beta got me thinking about my own site and good thing too. This is meant to be a checklist for things that I, you, or someone else hasn't thought of before. ANSWER: Try and break your own site before someone else does. Your web site is basically a publicly accessible API that allows access to a database and other backend systems. Test the URLs as if they were any other API. I like to start by cataloging all URLs that have some sort of permenant affect on the state of the system - this is easy if you are doing Ruby on Rails development or trying to follow a RESTful design pattern. For each of those URLs, try running a GET, POST, PUT or DELETE HTTP methods with different parameters so that you can ensure that you're only giving access to what you want to give access to. This of course is in addition to obvious: Functional testing, Load Testing, SQL Injection, XSS etc.
[ "testing" ]
5
4
824
7
0
2008-08-22T17:47:27.933000
2008-08-22T19:11:46.203000
23,027
23,060
CruiseControl.Net Build Publisher - Only publish compiled files
While setting up CruiseControl, I added a buildpublisher block to the publisher tasks: C:\MyBuild\ C:\MyBuildPublished\ false This works, but it copies the entire file contents of the build, I only want to copy the DLL's and.aspx pages, I don't need the source code to get published. Does anyone know of a way to filter this, or do I need to setup a task to run a RoboCopy script instead?
I set up a task to do this. I'm not aware of any way to make CruiseControl be that specific. I usually just chain a batch file to do the copy to the CC.net task.
CruiseControl.Net Build Publisher - Only publish compiled files While setting up CruiseControl, I added a buildpublisher block to the publisher tasks: C:\MyBuild\ C:\MyBuildPublished\ false This works, but it copies the entire file contents of the build, I only want to copy the DLL's and.aspx pages, I don't need the source code to get published. Does anyone know of a way to filter this, or do I need to setup a task to run a RoboCopy script instead?
TITLE: CruiseControl.Net Build Publisher - Only publish compiled files QUESTION: While setting up CruiseControl, I added a buildpublisher block to the publisher tasks: C:\MyBuild\ C:\MyBuildPublished\ false This works, but it copies the entire file contents of the build, I only want to copy the DLL's and.aspx pages, I don't need the source code to get published. Does anyone know of a way to filter this, or do I need to setup a task to run a RoboCopy script instead? ANSWER: I set up a task to do this. I'm not aware of any way to make CruiseControl be that specific. I usually just chain a batch file to do the copy to the CC.net task.
[ ".net", "build-process", "cruisecontrol.net" ]
9
3
4,977
4
0
2008-08-22T17:53:24.143000
2008-08-22T18:05:24.583000
23,031
23,040
When/how frequently should I test?
As a novice developer who is getting into the rhythm of my first professional project, I'm trying to develop good habits as soon as possible. However, I've found that I often forget to test, put it off, or do a whole bunch of tests at the end of a build instead of one at a time. My question is what rhythm do you like to get into when working on large projects, and where testing fits into it.
Well, if you want to follow the TDD guys, before you start to code;) I am very much in the same position as you. I want to get more into testing, but I am currently in a position where we are working to "get the code out" rather than "get the code out right" which scares the crap out of me. So I am slowly trying to integrate testing processes in my development cycle. Currently, I test as I code, trying to bust the code as I write it. I do find it hard to get into the TDD mindset.. Its taking time, but that is the way I would want to work.. EDIT: I thought I should probably expand on this, this is my basic "working process"... Plan what I want from the code, possible object design, whatever. Create my first class, add a huge comment to the top outlining what my "vision" for the class is. Outline the basic test scenarios.. These will basically become the unit tests. Create my first method.. Also writing a short comment explaining how it is expected to work. Write an automated test to see if it does what I expect. Repeat steps 4-6 for each method (note the automated tests are in a huge list that runs on F5). I then create some beefy tests to emulate the class in the working environment, obviously fixing any issues. If any new bugs come to light following this, I then go back and write the new test in, make sure it fails (this also serves as proof-of-concept for the bug) then fix it.. I hope that helps.. Open to comments on how to improve this, as I said it is a concern of mine..
When/how frequently should I test? As a novice developer who is getting into the rhythm of my first professional project, I'm trying to develop good habits as soon as possible. However, I've found that I often forget to test, put it off, or do a whole bunch of tests at the end of a build instead of one at a time. My question is what rhythm do you like to get into when working on large projects, and where testing fits into it.
TITLE: When/how frequently should I test? QUESTION: As a novice developer who is getting into the rhythm of my first professional project, I'm trying to develop good habits as soon as possible. However, I've found that I often forget to test, put it off, or do a whole bunch of tests at the end of a build instead of one at a time. My question is what rhythm do you like to get into when working on large projects, and where testing fits into it. ANSWER: Well, if you want to follow the TDD guys, before you start to code;) I am very much in the same position as you. I want to get more into testing, but I am currently in a position where we are working to "get the code out" rather than "get the code out right" which scares the crap out of me. So I am slowly trying to integrate testing processes in my development cycle. Currently, I test as I code, trying to bust the code as I write it. I do find it hard to get into the TDD mindset.. Its taking time, but that is the way I would want to work.. EDIT: I thought I should probably expand on this, this is my basic "working process"... Plan what I want from the code, possible object design, whatever. Create my first class, add a huge comment to the top outlining what my "vision" for the class is. Outline the basic test scenarios.. These will basically become the unit tests. Create my first method.. Also writing a short comment explaining how it is expected to work. Write an automated test to see if it does what I expect. Repeat steps 4-6 for each method (note the automated tests are in a huge list that runs on F5). I then create some beefy tests to emulate the class in the working environment, obviously fixing any issues. If any new bugs come to light following this, I then go back and write the new test in, make sure it fails (this also serves as proof-of-concept for the bug) then fix it.. I hope that helps.. Open to comments on how to improve this, as I said it is a concern of mine..
[ "testing" ]
4
6
801
12
0
2008-08-22T17:54:10.787000
2008-08-22T17:57:37.160000
23,064
23,067
XML Collection Best Practices
I'm creating an application that will store a hierarchical collection of items in an XML file and I'm wondering about the industry standard for storing collections in XML. Which of the following two formats is preferred? (If there is another option I'm not seeing, please advise.) Option A Option B
I'm no XML expert, but I find Option B to be more human readable, and I think it's just as machine readable as Option A. I believe that XML is designed to be both human and machine readable, so I would go for Option B myself. I just realized something else after Ryan Farley's post. If the Students or Classes section becomes too big and must be moved to another XML file, it seems like it would be easier to copy the node and create a new XML file out of that node with Option B.
XML Collection Best Practices I'm creating an application that will store a hierarchical collection of items in an XML file and I'm wondering about the industry standard for storing collections in XML. Which of the following two formats is preferred? (If there is another option I'm not seeing, please advise.) Option A Option B
TITLE: XML Collection Best Practices QUESTION: I'm creating an application that will store a hierarchical collection of items in an XML file and I'm wondering about the industry standard for storing collections in XML. Which of the following two formats is preferred? (If there is another option I'm not seeing, please advise.) Option A Option B ANSWER: I'm no XML expert, but I find Option B to be more human readable, and I think it's just as machine readable as Option A. I believe that XML is designed to be both human and machine readable, so I would go for Option B myself. I just realized something else after Ryan Farley's post. If the Students or Classes section becomes too big and must be moved to another XML file, it seems like it would be easier to copy the node and create a new XML file out of that node with Option B.
[ "xml" ]
4
4
4,741
4
0
2008-08-22T18:07:56.917000
2008-08-22T18:09:36.507000
23,082
23,676
How Did You Decide Between WISA and LAMP?
Did you ever have to choose between WISA or LAMP at the beginning of a web project? While pros and cons are littered around the net, it would be helpful to know about your real experience in coming up w/ criteria, evaluating, deciding, and reflecting upon your decision to go w/ either platform.
I think the first part is your Application. If you decide to go PHP, you almost automatically end up with LAMP, as WIMP or WISP stacks are quite rare (I think blog.stackoverflow.com runs on WIMP), and with.net you definitely want to go WISA. So normally, it boils down to.net vs. PHP. (Ignoring Ruby, Python and all the other stuff for a moment). When you made that decision, the rest comes naturally or adapts into your environment (i.e. if all your admins in the company are windows admins, maybe WAMP works better for you) I switched from PHP to.net about a year ago and I never looked back at PHP, but I never had to look at the bill for Windows and SQL Server licenses to be fair. Deployment on WISA has a much higher initial cost due to the licenses involved, whereas a LAMP Stack is free (Yes, MySQL is also free for commercial use). Addendum: All the funny acronyms stand for the combination of technologies: (L)inux or (W)indows, (A)pache or (I)IS, (M)ySQL or (S)QL Server, (P)hp or (A)SP.net.
How Did You Decide Between WISA and LAMP? Did you ever have to choose between WISA or LAMP at the beginning of a web project? While pros and cons are littered around the net, it would be helpful to know about your real experience in coming up w/ criteria, evaluating, deciding, and reflecting upon your decision to go w/ either platform.
TITLE: How Did You Decide Between WISA and LAMP? QUESTION: Did you ever have to choose between WISA or LAMP at the beginning of a web project? While pros and cons are littered around the net, it would be helpful to know about your real experience in coming up w/ criteria, evaluating, deciding, and reflecting upon your decision to go w/ either platform. ANSWER: I think the first part is your Application. If you decide to go PHP, you almost automatically end up with LAMP, as WIMP or WISP stacks are quite rare (I think blog.stackoverflow.com runs on WIMP), and with.net you definitely want to go WISA. So normally, it boils down to.net vs. PHP. (Ignoring Ruby, Python and all the other stuff for a moment). When you made that decision, the rest comes naturally or adapts into your environment (i.e. if all your admins in the company are windows admins, maybe WAMP works better for you) I switched from PHP to.net about a year ago and I never looked back at PHP, but I never had to look at the bill for Windows and SQL Server licenses to be fair. Deployment on WISA has a much higher initial cost due to the licenses involved, whereas a LAMP Stack is free (Yes, MySQL is also free for commercial use). Addendum: All the funny acronyms stand for the combination of technologies: (L)inux or (W)indows, (A)pache or (I)IS, (M)ySQL or (S)QL Server, (P)hp or (A)SP.net.
[ "architecture", "web-applications", "lamp", "platform", "wisa" ]
11
11
9,066
13
0
2008-08-22T18:16:39.547000
2008-08-22T22:35:32.267000
23,083
23,101
What's an alternative to GWL_USERDATA for storing an object pointer?
In the Windows applications I work on, we have a custom framework that sits directly above Win32 (don't ask). When we create a window, our normal practice is to put this in the window's user data area via SetWindowLong(hwnd, GWL_USERDATA, this), which allows us to have an MFC-like callback or a tightly integrated WndProc, depending. The problem is that this will not work on 64-bit Windows, since LONG is only 32-bits wide. What's a better solution to this problem that works on both 32- and 64-bit systems?
SetWindowLongPtr was created to replace SetWindowLong in these instances. It's LONG_PTR parameter allows you to store a pointer for 32-bit or 64-bit compilations. LONG_PTR SetWindowLongPtr( HWND hWnd, int nIndex, LONG_PTR dwNewLong ); Remember that the constants have changed too, so usage now looks like: SetWindowLongPtr(hWnd, GWLP_USERDATA, this); Also don't forget that now to retrieve the pointer, you must use GetWindowLongPtr: LONG_PTR GetWindowLongPtr( HWND hWnd, int nIndex ); And usage would look like (again, with changed constants): LONG_PTR lpUserData = GetWindowLongPtr(hWnd, GWLP_USERDATA); MyObject* pMyObject = (MyObject*)lpUserData;
What's an alternative to GWL_USERDATA for storing an object pointer? In the Windows applications I work on, we have a custom framework that sits directly above Win32 (don't ask). When we create a window, our normal practice is to put this in the window's user data area via SetWindowLong(hwnd, GWL_USERDATA, this), which allows us to have an MFC-like callback or a tightly integrated WndProc, depending. The problem is that this will not work on 64-bit Windows, since LONG is only 32-bits wide. What's a better solution to this problem that works on both 32- and 64-bit systems?
TITLE: What's an alternative to GWL_USERDATA for storing an object pointer? QUESTION: In the Windows applications I work on, we have a custom framework that sits directly above Win32 (don't ask). When we create a window, our normal practice is to put this in the window's user data area via SetWindowLong(hwnd, GWL_USERDATA, this), which allows us to have an MFC-like callback or a tightly integrated WndProc, depending. The problem is that this will not work on 64-bit Windows, since LONG is only 32-bits wide. What's a better solution to this problem that works on both 32- and 64-bit systems? ANSWER: SetWindowLongPtr was created to replace SetWindowLong in these instances. It's LONG_PTR parameter allows you to store a pointer for 32-bit or 64-bit compilations. LONG_PTR SetWindowLongPtr( HWND hWnd, int nIndex, LONG_PTR dwNewLong ); Remember that the constants have changed too, so usage now looks like: SetWindowLongPtr(hWnd, GWLP_USERDATA, this); Also don't forget that now to retrieve the pointer, you must use GetWindowLongPtr: LONG_PTR GetWindowLongPtr( HWND hWnd, int nIndex ); And usage would look like (again, with changed constants): LONG_PTR lpUserData = GetWindowLongPtr(hWnd, GWLP_USERDATA); MyObject* pMyObject = (MyObject*)lpUserData;
[ "windows", "winapi", "32bit-64bit" ]
31
45
22,026
2
0
2008-08-22T18:16:51.653000
2008-08-22T18:21:41.783000
23,094
24,334
What's the best way to deal with cache and the browser back button?
What's the best way to handle a user going back to a page that had cached items in an asp.net app? Is there a good way to capture the back button (event?) and handle the cache that way?
You can try using the HttpResponse.Cache property if that would help: Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.SetValidUntilExpires(false); Response.Cache.VaryByParams["Category"] = true; if (Response.Cache.VaryByParams["Category"]) { //... } Or could could block caching of the page altogether with HttpResponse.CacheControl, but its been deprecated in favor of the Cache property above: Response.CacheControl = "No-Cache"; Edit: OR you could really go nuts and do it all by hand: Response.ClearHeaders(); Response.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1 Response.AppendHeader("Cache-Control", "private"); // HTTP 1.1 Response.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1 Response.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1 Response.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1 Response.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1 Response.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1 Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.1 Response.AppendHeader("Keep-Alive", "timeout=3, max=993"); // HTTP 1.1 Response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.1
What's the best way to deal with cache and the browser back button? What's the best way to handle a user going back to a page that had cached items in an asp.net app? Is there a good way to capture the back button (event?) and handle the cache that way?
TITLE: What's the best way to deal with cache and the browser back button? QUESTION: What's the best way to handle a user going back to a page that had cached items in an asp.net app? Is there a good way to capture the back button (event?) and handle the cache that way? ANSWER: You can try using the HttpResponse.Cache property if that would help: Response.Cache.SetExpires(DateTime.Now.AddSeconds(60)); Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.SetValidUntilExpires(false); Response.Cache.VaryByParams["Category"] = true; if (Response.Cache.VaryByParams["Category"]) { //... } Or could could block caching of the page altogether with HttpResponse.CacheControl, but its been deprecated in favor of the Cache property above: Response.CacheControl = "No-Cache"; Edit: OR you could really go nuts and do it all by hand: Response.ClearHeaders(); Response.AppendHeader("Cache-Control", "no-cache"); //HTTP 1.1 Response.AppendHeader("Cache-Control", "private"); // HTTP 1.1 Response.AppendHeader("Cache-Control", "no-store"); // HTTP 1.1 Response.AppendHeader("Cache-Control", "must-revalidate"); // HTTP 1.1 Response.AppendHeader("Cache-Control", "max-stale=0"); // HTTP 1.1 Response.AppendHeader("Cache-Control", "post-check=0"); // HTTP 1.1 Response.AppendHeader("Cache-Control", "pre-check=0"); // HTTP 1.1 Response.AppendHeader("Pragma", "no-cache"); // HTTP 1.1 Response.AppendHeader("Keep-Alive", "timeout=3, max=993"); // HTTP 1.1 Response.AppendHeader("Expires", "Mon, 26 Jul 1997 05:00:00 GMT"); // HTTP 1.1
[ "asp.net", "caching", "back-button" ]
9
7
8,214
5
0
2008-08-22T18:19:10.447000
2008-08-23T16:10:11.200000
23,102
23,206
What common web exploits should I know about?
I'm pretty green still when it comes to web programming, I've spent most of my time on client applications. So I'm curious about the common exploits I should fear/test for in my site.
OWASP keeps a list of the Top 10 web attacks to watch our for, in addition to a ton of other useful security information for web development.
What common web exploits should I know about? I'm pretty green still when it comes to web programming, I've spent most of my time on client applications. So I'm curious about the common exploits I should fear/test for in my site.
TITLE: What common web exploits should I know about? QUESTION: I'm pretty green still when it comes to web programming, I've spent most of my time on client applications. So I'm curious about the common exploits I should fear/test for in my site. ANSWER: OWASP keeps a list of the Top 10 web attacks to watch our for, in addition to a ton of other useful security information for web development.
[ "security", "testing" ]
54
29
12,608
13
0
2008-08-22T18:22:09.207000
2008-08-22T19:03:40.027000
23,106
23,300
Best method to parse various custom XML documents in Java
What is the best method to parse multiple, discrete, custom XML documents with Java?
I would use Stax to parse XML, it's fast and easy to use. I've been using it on my last project to parse XML files up to 24MB. There's a nice introduction on java.net, which tells you everything you need to know to get started.
Best method to parse various custom XML documents in Java What is the best method to parse multiple, discrete, custom XML documents with Java?
TITLE: Best method to parse various custom XML documents in Java QUESTION: What is the best method to parse multiple, discrete, custom XML documents with Java? ANSWER: I would use Stax to parse XML, it's fast and easy to use. I've been using it on my last project to parse XML files up to 24MB. There's a nice introduction on java.net, which tells you everything you need to know to get started.
[ "java", "xml" ]
10
6
8,454
6
0
2008-08-22T18:22:39.860000
2008-08-22T19:45:47.540000
23,124
23,227
Need to test an ajax timeout condition
As the title mentions, I have a timeout callback handler on an ajax call, and I want to be able to test that condition but nothing is coming to mind immediately on ways I can force my application to hit that state, any suggestions?
First off, I think you need to be clearer in your question - what technology are you using and where is this process that is timing out - server-side or client-side? If you want to have the server-side code take a long time and you are using.NET, place this line in the method you call server-side: System.Threading.Thread.Sleep(timeoutMilliseconds); As long as you use a number sufficient so that your client-side code assumes the server has timed out, you should be good.
Need to test an ajax timeout condition As the title mentions, I have a timeout callback handler on an ajax call, and I want to be able to test that condition but nothing is coming to mind immediately on ways I can force my application to hit that state, any suggestions?
TITLE: Need to test an ajax timeout condition QUESTION: As the title mentions, I have a timeout callback handler on an ajax call, and I want to be able to test that condition but nothing is coming to mind immediately on ways I can force my application to hit that state, any suggestions? ANSWER: First off, I think you need to be clearer in your question - what technology are you using and where is this process that is timing out - server-side or client-side? If you want to have the server-side code take a long time and you are using.NET, place this line in the method you call server-side: System.Threading.Thread.Sleep(timeoutMilliseconds); As long as you use a number sufficient so that your client-side code assumes the server has timed out, you should be good.
[ "asp.net", "ajax", "testing" ]
1
2
1,789
3
0
2008-08-22T18:27:59.147000
2008-08-22T19:14:36.600000
23,166
23,179
What's a good beginning text on functional programming?
I like to study languages outside my comfort zone, but I've had a hard time finding a place to start for functional languages. I heard a lot of good things about Structure and Interpretations of Computer Programs, but when I tried to read through it a couple of years ago it just seemed to whiz over my head. I do way better with books than web sites, but when I visit the local book store the books on LISP look kind of scary. So what's a good starting point? My goal is to be able to use a functional programming language to solve simple problems in 6 months or so, and the ability to move to more advanced topics, recognize when a functional language is the right tool for the job, and use the language to solve more problems over the course of 2-3 years. I like books that are heavy on examples but also include challenges to work through. Does such a thing exist for functional languages?
The Little Schemer teaches recursion really well, and it's fun and simple to read. I also liked The Scheme Programming Language for a broader introduction into the language.
What's a good beginning text on functional programming? I like to study languages outside my comfort zone, but I've had a hard time finding a place to start for functional languages. I heard a lot of good things about Structure and Interpretations of Computer Programs, but when I tried to read through it a couple of years ago it just seemed to whiz over my head. I do way better with books than web sites, but when I visit the local book store the books on LISP look kind of scary. So what's a good starting point? My goal is to be able to use a functional programming language to solve simple problems in 6 months or so, and the ability to move to more advanced topics, recognize when a functional language is the right tool for the job, and use the language to solve more problems over the course of 2-3 years. I like books that are heavy on examples but also include challenges to work through. Does such a thing exist for functional languages?
TITLE: What's a good beginning text on functional programming? QUESTION: I like to study languages outside my comfort zone, but I've had a hard time finding a place to start for functional languages. I heard a lot of good things about Structure and Interpretations of Computer Programs, but when I tried to read through it a couple of years ago it just seemed to whiz over my head. I do way better with books than web sites, but when I visit the local book store the books on LISP look kind of scary. So what's a good starting point? My goal is to be able to use a functional programming language to solve simple problems in 6 months or so, and the ability to move to more advanced topics, recognize when a functional language is the right tool for the job, and use the language to solve more problems over the course of 2-3 years. I like books that are heavy on examples but also include challenges to work through. Does such a thing exist for functional languages? ANSWER: The Little Schemer teaches recursion really well, and it's fun and simple to read. I also liked The Scheme Programming Language for a broader introduction into the language.
[ "functional-programming", "lisp", "scheme" ]
54
29
6,691
15
0
2008-08-22T18:46:09.010000
2008-08-22T18:52:28.230000
23,176
23,181
Suggestions on Ajax development environment for PHP
I am a C/C++ programmer professionally, but I've created a couple of personal web sites using PHP and MySQL. They're pretty basic, and I'd like to jazz them up using Ajax, but I've never done any Ajax. I've done all the development so far manually, i.e. no IDE or anything like that. Does anyone have suggestions on Ajax development environments that can help me? Shareware or freeware would be preferable as I'd find it hard to justify spending more than a minimal amount of money on this...
As T.O. says, try Aptana. There's a very good free version, and they really push the AJAX. They even have Jaxer, an "AJAX Server" that they're working on. If nothing else, the plugins are great, and, other than a few quirks, I really like working in it.
Suggestions on Ajax development environment for PHP I am a C/C++ programmer professionally, but I've created a couple of personal web sites using PHP and MySQL. They're pretty basic, and I'd like to jazz them up using Ajax, but I've never done any Ajax. I've done all the development so far manually, i.e. no IDE or anything like that. Does anyone have suggestions on Ajax development environments that can help me? Shareware or freeware would be preferable as I'd find it hard to justify spending more than a minimal amount of money on this...
TITLE: Suggestions on Ajax development environment for PHP QUESTION: I am a C/C++ programmer professionally, but I've created a couple of personal web sites using PHP and MySQL. They're pretty basic, and I'd like to jazz them up using Ajax, but I've never done any Ajax. I've done all the development so far manually, i.e. no IDE or anything like that. Does anyone have suggestions on Ajax development environments that can help me? Shareware or freeware would be preferable as I'd find it hard to justify spending more than a minimal amount of money on this... ANSWER: As T.O. says, try Aptana. There's a very good free version, and they really push the AJAX. They even have Jaxer, an "AJAX Server" that they're working on. If nothing else, the plugins are great, and, other than a few quirks, I really like working in it.
[ "php", "javascript", "ajax", "ide" ]
5
2
1,280
6
0
2008-08-22T18:50:54.660000
2008-08-22T18:54:07.353000
23,178
23,194
"All Users" Folder
Is there a.NET variable that returns the "All Users" directory?
You'll want to use the system.environment variables. Most of the predefined ones are shown here. For the " All Users " you would use: System.Environment.GetEnvironmentVariable("ALLUSERSPROFILE") I know I got a lot of upmods and a correct answer for my other stuff, but this actually works. where as the other environment variables I linked to previously don't seem to work with that function call.
"All Users" Folder Is there a.NET variable that returns the "All Users" directory?
TITLE: "All Users" Folder QUESTION: Is there a.NET variable that returns the "All Users" directory? ANSWER: You'll want to use the system.environment variables. Most of the predefined ones are shown here. For the " All Users " you would use: System.Environment.GetEnvironmentVariable("ALLUSERSPROFILE") I know I got a lot of upmods and a correct answer for my other stuff, but this actually works. where as the other environment variables I linked to previously don't seem to work with that function call.
[ ".net", "io" ]
1
7
1,296
3
0
2008-08-22T18:52:14.690000
2008-08-22T18:57:25.753000
23,190
25,002
How Does One Sum Dimensions of an Array Specified at Run-Time?
I am working on a function to establish the entropy of a distribution. It uses a copula, if any are familiar with that. I need to sum up the values in the array based on which dimensions are "cared about." Example: Consider the following example... Dimension 0 (across) _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 0 _|_ 0 _|_ 0 _|_ 2 _| Dimension 1 |_ 1 _|_ 0 _|_ 2 _|_ 0 _| (down) |_ 0 _|_ 3 _|_ 0 _|_ 6 _| |_ 0 _|_ 0 _|_ 0 _|_ 0 _| I "care about" dimension 0 only, and "don't care" about the rest (dim 1). Summing this array with the above specifications will "collapse" the "stacks" of dimension 1 down to a single 4 x 1 array: _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 1 _|_ 3 _|_ 2 _|_ 8 _| This can then be summed, or have any operation performed. I need to do this with an array of 'n' dimensions, which could feasibly be 20. Also, I need to be able to do this, caring about certain dimensions, and collapsing the rest. I am having an especially hard time with this because I cant visualize 20 dimensions:p. If anyone could help me set up some c/c++ code to collapse/sum, I would be very very grateful. Update: Just got home. Here is some info to answer your questions: Sorry for rolling back the edits, I was hoping when I clicked roll-back it would show me the changes so I could see what I messed up, a bit like wikipedia. This wasn't the case, as I found out. @jeff - What doesnt make sense? I am using this great service for (what I think is) a legit reason. I want to get better at my hobby, which is all it is, as I am in high school. Many of my posts regard implementing a genetic algorithm (This post, sparsearray, rank an array, pointer manipulation). I am using a sparse array representation, as it is possible to exceed the number of molecules in the universe using a traditional (dense) array. For now, the implementation of the sparsearray itself doesnt matter a whole lot, as I am working to make it work with a standard array before going to a sparse representation. For those who havent seen my previous questions, I am using a binary search tree as the structure to contain the sparse array points, and a "driver" function to traverse the tree as necessary, returning whatever the function is designed to do. This is flexible, so I can accomodate a lot of different methods of accessing the array. The structure is a hypercube, and the number of dimensions is specified at run time, as well as the length of each dimension (which are all the same, as it is a hypercube). Thanks everyone for your imput.
This could have applications. Lets say you implemented a 2D Conway's Game of Life (which defines a 2D plane, 1 for 'alive', 0 for 'dead') and you stored the Games history for every iteration (which then defines a 3D cube). If you wanted to know how many bacteria there was alive over history, you would use the above algorithm. You could use the same algorithm for a 3D, (and 4D, 5D etc.) version of Game of Life grid. I'd say this was a question for recursion, I'm not yet a C programmer but I know it is possible in C. In python, def iter_arr(array): sum = 0 for i in array: if type(i) == type(list()): sum = sum + iter_arr(i) else: sum = sum + i return sum Iterate over each element in array If element is another array, call the function again If element is not array, add it to the sum Return sum You would then apply this to each element in the 'cared about' dimension. This is easier in python due to duck-typing though...
How Does One Sum Dimensions of an Array Specified at Run-Time? I am working on a function to establish the entropy of a distribution. It uses a copula, if any are familiar with that. I need to sum up the values in the array based on which dimensions are "cared about." Example: Consider the following example... Dimension 0 (across) _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 0 _|_ 0 _|_ 0 _|_ 2 _| Dimension 1 |_ 1 _|_ 0 _|_ 2 _|_ 0 _| (down) |_ 0 _|_ 3 _|_ 0 _|_ 6 _| |_ 0 _|_ 0 _|_ 0 _|_ 0 _| I "care about" dimension 0 only, and "don't care" about the rest (dim 1). Summing this array with the above specifications will "collapse" the "stacks" of dimension 1 down to a single 4 x 1 array: _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 1 _|_ 3 _|_ 2 _|_ 8 _| This can then be summed, or have any operation performed. I need to do this with an array of 'n' dimensions, which could feasibly be 20. Also, I need to be able to do this, caring about certain dimensions, and collapsing the rest. I am having an especially hard time with this because I cant visualize 20 dimensions:p. If anyone could help me set up some c/c++ code to collapse/sum, I would be very very grateful. Update: Just got home. Here is some info to answer your questions: Sorry for rolling back the edits, I was hoping when I clicked roll-back it would show me the changes so I could see what I messed up, a bit like wikipedia. This wasn't the case, as I found out. @jeff - What doesnt make sense? I am using this great service for (what I think is) a legit reason. I want to get better at my hobby, which is all it is, as I am in high school. Many of my posts regard implementing a genetic algorithm (This post, sparsearray, rank an array, pointer manipulation). I am using a sparse array representation, as it is possible to exceed the number of molecules in the universe using a traditional (dense) array. For now, the implementation of the sparsearray itself doesnt matter a whole lot, as I am working to make it work with a standard array before going to a sparse representation. For those who havent seen my previous questions, I am using a binary search tree as the structure to contain the sparse array points, and a "driver" function to traverse the tree as necessary, returning whatever the function is designed to do. This is flexible, so I can accomodate a lot of different methods of accessing the array. The structure is a hypercube, and the number of dimensions is specified at run time, as well as the length of each dimension (which are all the same, as it is a hypercube). Thanks everyone for your imput.
TITLE: How Does One Sum Dimensions of an Array Specified at Run-Time? QUESTION: I am working on a function to establish the entropy of a distribution. It uses a copula, if any are familiar with that. I need to sum up the values in the array based on which dimensions are "cared about." Example: Consider the following example... Dimension 0 (across) _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 0 _|_ 0 _|_ 0 _|_ 2 _| Dimension 1 |_ 1 _|_ 0 _|_ 2 _|_ 0 _| (down) |_ 0 _|_ 3 _|_ 0 _|_ 6 _| |_ 0 _|_ 0 _|_ 0 _|_ 0 _| I "care about" dimension 0 only, and "don't care" about the rest (dim 1). Summing this array with the above specifications will "collapse" the "stacks" of dimension 1 down to a single 4 x 1 array: _ _ _ _ _ _ _ _ _ _ _ _ _ |_ 1 _|_ 3 _|_ 2 _|_ 8 _| This can then be summed, or have any operation performed. I need to do this with an array of 'n' dimensions, which could feasibly be 20. Also, I need to be able to do this, caring about certain dimensions, and collapsing the rest. I am having an especially hard time with this because I cant visualize 20 dimensions:p. If anyone could help me set up some c/c++ code to collapse/sum, I would be very very grateful. Update: Just got home. Here is some info to answer your questions: Sorry for rolling back the edits, I was hoping when I clicked roll-back it would show me the changes so I could see what I messed up, a bit like wikipedia. This wasn't the case, as I found out. @jeff - What doesnt make sense? I am using this great service for (what I think is) a legit reason. I want to get better at my hobby, which is all it is, as I am in high school. Many of my posts regard implementing a genetic algorithm (This post, sparsearray, rank an array, pointer manipulation). I am using a sparse array representation, as it is possible to exceed the number of molecules in the universe using a traditional (dense) array. For now, the implementation of the sparsearray itself doesnt matter a whole lot, as I am working to make it work with a standard array before going to a sparse representation. For those who havent seen my previous questions, I am using a binary search tree as the structure to contain the sparse array points, and a "driver" function to traverse the tree as necessary, returning whatever the function is designed to do. This is flexible, so I can accomodate a lot of different methods of accessing the array. The structure is a hypercube, and the number of dimensions is specified at run time, as well as the length of each dimension (which are all the same, as it is a hypercube). Thanks everyone for your imput. ANSWER: This could have applications. Lets say you implemented a 2D Conway's Game of Life (which defines a 2D plane, 1 for 'alive', 0 for 'dead') and you stored the Games history for every iteration (which then defines a 3D cube). If you wanted to know how many bacteria there was alive over history, you would use the above algorithm. You could use the same algorithm for a 3D, (and 4D, 5D etc.) version of Game of Life grid. I'd say this was a question for recursion, I'm not yet a C programmer but I know it is possible in C. In python, def iter_arr(array): sum = 0 for i in array: if type(i) == type(list()): sum = sum + iter_arr(i) else: sum = sum + i return sum Iterate over each element in array If element is another array, call the function again If element is not array, add it to the sum Return sum You would then apply this to each element in the 'cared about' dimension. This is easier in python due to duck-typing though...
[ "c++", "c", "arrays", "microsoft-dynamics" ]
4
2
1,306
10
0
2008-08-22T18:56:04.850000
2008-08-24T12:27:40.617000
23,216
23,229
Summary of differences in regular expression syntax for various tools and languages?
I can never remember the differences in regular expression syntax used by tools like grep and AWK, or languages like Python and PHP. Generally, Perl has the most expansive syntax, but I'm often hamstrung by the limitations of even egrep ("extended" grep ). Is there a site that lists the differences in a concise and easy-to-read fashion?
Mastering Regular Expressions, devotes the last four chapters to Java, PHP, Perl, and.NET. One chapter for each. From what I know, the pocket edition contains just those final four chapters.
Summary of differences in regular expression syntax for various tools and languages? I can never remember the differences in regular expression syntax used by tools like grep and AWK, or languages like Python and PHP. Generally, Perl has the most expansive syntax, but I'm often hamstrung by the limitations of even egrep ("extended" grep ). Is there a site that lists the differences in a concise and easy-to-read fashion?
TITLE: Summary of differences in regular expression syntax for various tools and languages? QUESTION: I can never remember the differences in regular expression syntax used by tools like grep and AWK, or languages like Python and PHP. Generally, Perl has the most expansive syntax, but I'm often hamstrung by the limitations of even egrep ("extended" grep ). Is there a site that lists the differences in a concise and easy-to-read fashion? ANSWER: Mastering Regular Expressions, devotes the last four chapters to Java, PHP, Perl, and.NET. One chapter for each. From what I know, the pocket edition contains just those final four chapters.
[ "regex", "grep" ]
8
7
4,567
3
0
2008-08-22T19:10:51.150000
2008-08-22T19:15:44.633000
23,217
23,222
What's the purpose (if any) of "javascript:" in event handler tags?
I've been making a concerted effort to improve my javascript skills lately by reading as much javascript code as I can. In doing this I've sometimes seen the javascript: prefix appended to the front of event handler attributes in HTML element tags. What's the purpose of this prefix? Basically, is there any appreciable difference between: onchange="javascript: myFunction(this)" and onchange="myFunction(this)"?
Probably nothing in your example. My understanding is that javascript: is for anchor tags (in place of an actual href ). You'd use it so that your script can execute when the user clicks the link, but without initiating a navigation back to the page (which a blank href coupled with an onclick will do). For example: Blah Rather than: Blah
What's the purpose (if any) of "javascript:" in event handler tags? I've been making a concerted effort to improve my javascript skills lately by reading as much javascript code as I can. In doing this I've sometimes seen the javascript: prefix appended to the front of event handler attributes in HTML element tags. What's the purpose of this prefix? Basically, is there any appreciable difference between: onchange="javascript: myFunction(this)" and onchange="myFunction(this)"?
TITLE: What's the purpose (if any) of "javascript:" in event handler tags? QUESTION: I've been making a concerted effort to improve my javascript skills lately by reading as much javascript code as I can. In doing this I've sometimes seen the javascript: prefix appended to the front of event handler attributes in HTML element tags. What's the purpose of this prefix? Basically, is there any appreciable difference between: onchange="javascript: myFunction(this)" and onchange="myFunction(this)"? ANSWER: Probably nothing in your example. My understanding is that javascript: is for anchor tags (in place of an actual href ). You'd use it so that your script can execute when the user clicks the link, but without initiating a navigation back to the page (which a blank href coupled with an onclick will do). For example: Blah Rather than: Blah
[ "javascript" ]
18
19
1,830
10
0
2008-08-22T19:10:56.250000
2008-08-22T19:12:17.213000
23,228
24,143
Why is String.Format static?
Compare String.Format("Hello {0}", "World"); with "Hello {0}".Format("World"); Why did the.Net designers choose a static method over an instance method? What do you think?
I don't actually know the answer but I suspect that it has something to do with the aspect of invoking methods on string literals directly. If I recall correctly (I didn't actually verify this because I don't have an old IDE handy), early versions of the C# IDE had trouble detecting method calls against string literals in IntelliSense, and that has a big impact on the discoverability of the API. If that was the case, typing the following wouldn't give you any help: "{0}".Format(12); If you were forced to type new String("{0}").Format(12); It would be clear that there was no advantage to making the Format method an instance method rather than a static method. The.NET libraries were designed by a lot of the same people that gave us MFC, and the String class in particular bears a strong resemblance to the CString class in MFC. MFC does have an instance Format method (that uses printf style formatting codes rather than the curly-brace style of.NET) which is painful because there's no such thing as a CString literal. So in a MFC codebase that I worked on I see a lot of this: CString csTemp = ""; csTemp.Format("Some string: %s", szFoo); which is painful. (I'm not saying that the code above is a great way to do things even in MFC, but that does seem to be the way that most of the developers on the project learned how to use CString::Format). Coming from that heritage, I can imagine that the API designers were trying to avoid that sort of situation again.
Why is String.Format static? Compare String.Format("Hello {0}", "World"); with "Hello {0}".Format("World"); Why did the.Net designers choose a static method over an instance method? What do you think?
TITLE: Why is String.Format static? QUESTION: Compare String.Format("Hello {0}", "World"); with "Hello {0}".Format("World"); Why did the.Net designers choose a static method over an instance method? What do you think? ANSWER: I don't actually know the answer but I suspect that it has something to do with the aspect of invoking methods on string literals directly. If I recall correctly (I didn't actually verify this because I don't have an old IDE handy), early versions of the C# IDE had trouble detecting method calls against string literals in IntelliSense, and that has a big impact on the discoverability of the API. If that was the case, typing the following wouldn't give you any help: "{0}".Format(12); If you were forced to type new String("{0}").Format(12); It would be clear that there was no advantage to making the Format method an instance method rather than a static method. The.NET libraries were designed by a lot of the same people that gave us MFC, and the String class in particular bears a strong resemblance to the CString class in MFC. MFC does have an instance Format method (that uses printf style formatting codes rather than the curly-brace style of.NET) which is painful because there's no such thing as a CString literal. So in a MFC codebase that I worked on I see a lot of this: CString csTemp = ""; csTemp.Format("Some string: %s", szFoo); which is painful. (I'm not saying that the code above is a great way to do things even in MFC, but that does seem to be the way that most of the developers on the project learned how to use CString::Format). Coming from that heritage, I can imagine that the API designers were trying to avoid that sort of situation again.
[ ".net", "string" ]
41
31
5,986
22
0
2008-08-22T19:15:08.533000
2008-08-23T11:05:01.653000
23,250
23,502
When do you use the "this" keyword?
I was curious about how other people use the this keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples: In a constructor: public Light(Vector v) { this.dir = new Vector(v); } Elsewhere public void SomeMethod() { Vector vec = new Vector(); double d = (vec * vec) - (this.radius * this.radius); }
There are several usages of this keyword in C#. To qualify members hidden by similar name To have an object pass itself as a parameter to other methods To have an object return itself from a method To declare indexers To declare extension methods To pass parameters between constructors To internally reassign value type (struct) value. To invoke an extension method on the current instance To cast itself to another type To chain constructors defined in the same class You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using auto-implemented properties.
When do you use the "this" keyword? I was curious about how other people use the this keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples: In a constructor: public Light(Vector v) { this.dir = new Vector(v); } Elsewhere public void SomeMethod() { Vector vec = new Vector(); double d = (vec * vec) - (this.radius * this.radius); }
TITLE: When do you use the "this" keyword? QUESTION: I was curious about how other people use the this keyword. I tend to use it in constructors, but I may also use it throughout the class in other methods. Some examples: In a constructor: public Light(Vector v) { this.dir = new Vector(v); } Elsewhere public void SomeMethod() { Vector vec = new Vector(); double d = (vec * vec) - (this.radius * this.radius); } ANSWER: There are several usages of this keyword in C#. To qualify members hidden by similar name To have an object pass itself as a parameter to other methods To have an object return itself from a method To declare indexers To declare extension methods To pass parameters between constructors To internally reassign value type (struct) value. To invoke an extension method on the current instance To cast itself to another type To chain constructors defined in the same class You can avoid the first usage by not having member and local variables with the same name in scope, for example by following common naming conventions and using properties (Pascal case) instead of fields (camel case) to avoid colliding with local variables (also camel case). In C# 3.0 fields can be converted to properties easily by using auto-implemented properties.
[ "c#", "coding-style", "this" ]
248
217
229,981
31
0
2008-08-22T19:21:25.227000
2008-08-22T21:12:48.937000
23,270
36,667
How IE7 determines a site's Security Zone
Does anyone know how IE7 determines what Security Zone to use for a site? I see the basics for IE6 here, but I can't find the equivalent for IE7.
I could use a little more information to narrow down my answer, but here is what I have: Internet Explorer has 5 different security zones be default: Local Machine Zone, Intranet, Internet, Trusted, and Restricted These are determined in urlmon.dll (Url Moniker) More information here: http://msdn.microsoft.com/en-us/library/ms537183(VS.85).aspx But you can also implement your own custom security zone: http://msdn.microsoft.com/en-us/library/ms537182(VS.85).aspx The way that IE determines the security zones should not have changes between IE6 and IE7 (or IE8 for that matter) Intranet sites are determined: 1. By url host names do not have any dots ( http://stackoverflow vs http://stackoverflow.com ) Sites from the file:// scheme where the resource is collected from UNC
How IE7 determines a site's Security Zone Does anyone know how IE7 determines what Security Zone to use for a site? I see the basics for IE6 here, but I can't find the equivalent for IE7.
TITLE: How IE7 determines a site's Security Zone QUESTION: Does anyone know how IE7 determines what Security Zone to use for a site? I see the basics for IE6 here, but I can't find the equivalent for IE7. ANSWER: I could use a little more information to narrow down my answer, but here is what I have: Internet Explorer has 5 different security zones be default: Local Machine Zone, Intranet, Internet, Trusted, and Restricted These are determined in urlmon.dll (Url Moniker) More information here: http://msdn.microsoft.com/en-us/library/ms537183(VS.85).aspx But you can also implement your own custom security zone: http://msdn.microsoft.com/en-us/library/ms537182(VS.85).aspx The way that IE determines the security zones should not have changes between IE6 and IE7 (or IE8 for that matter) Intranet sites are determined: 1. By url host names do not have any dots ( http://stackoverflow vs http://stackoverflow.com ) Sites from the file:// scheme where the resource is collected from UNC
[ "security", "internet-explorer-7", "security-zone" ]
4
2
1,532
4
0
2008-08-22T19:28:00.140000
2008-08-31T06:29:06.977000
23,277
23,290
What is the difference between procedural programming and functional programming?
I've read the Wikipedia articles for both procedural programming and functional programming, but I'm still slightly confused. Could someone boil it down to the core?
A functional language (ideally) allows you to write a mathematical function, i.e. a function that takes n arguments and returns a value. If the program is executed, this function is logically evaluated as needed. 1 A procedural language, on the other hand, performs a series of sequential steps. (There's a way of transforming sequential logic into functional logic called continuation passing style.) As a consequence, a purely functional program always yields the same value for an input, and the order of evaluation is not well-defined; which means that uncertain values like user input or random values are hard to model in purely functional languages. 1 As everything else in this answer, that’s a generalisation. This property, evaluating a computation when its result is needed rather than sequentially where it’s called, is known as “laziness”. Not all functional languages are actually universally lazy, nor is laziness restricted to functional programming. Rather, the description given here provides a “mental framework” to think about different programming styles that are not distinct and opposite categories but rather fluid ideas.
What is the difference between procedural programming and functional programming? I've read the Wikipedia articles for both procedural programming and functional programming, but I'm still slightly confused. Could someone boil it down to the core?
TITLE: What is the difference between procedural programming and functional programming? QUESTION: I've read the Wikipedia articles for both procedural programming and functional programming, but I'm still slightly confused. Could someone boil it down to the core? ANSWER: A functional language (ideally) allows you to write a mathematical function, i.e. a function that takes n arguments and returns a value. If the program is executed, this function is logically evaluated as needed. 1 A procedural language, on the other hand, performs a series of sequential steps. (There's a way of transforming sequential logic into functional logic called continuation passing style.) As a consequence, a purely functional program always yields the same value for an input, and the order of evaluation is not well-defined; which means that uncertain values like user input or random values are hard to model in purely functional languages. 1 As everything else in this answer, that’s a generalisation. This property, evaluating a computation when its result is needed rather than sequentially where it’s called, is known as “laziness”. Not all functional languages are actually universally lazy, nor is laziness restricted to functional programming. Rather, the description given here provides a “mental framework” to think about different programming styles that are not distinct and opposite categories but rather fluid ideas.
[ "functional-programming", "glossary", "paradigms", "procedural-programming" ]
327
185
180,814
17
0
2008-08-22T19:29:45.253000
2008-08-22T19:37:53.580000
23,287
242,189
Algorithm to find Largest prime factor of a number
What is the best approach to calculating the largest prime factor of a number? I'm thinking the most efficient would be the following: Find lowest prime number that divides cleanly Check if result of division is prime If not, find next lowest Go to 2. I'm basing this assumption on it being easier to calculate the small prime factors. Is this about right? What other approaches should I look into? Edit: I've now realised that my approach is futile if there are more than 2 prime factors in play, since step 2 fails when the result is a product of two other primes, therefore a recursive algorithm is needed. Edit again: And now I've realised that this does still work, because the last found prime number has to be the highest one, therefore any further testing of the non-prime result from step 2 would result in a smaller prime.
Actually there are several more efficient ways to find factors of big numbers (for smaller ones trial division works reasonably well). One method which is very fast if the input number has two factors very close to its square root is known as Fermat factorisation. It makes use of the identity N = (a + b)(a - b) = a^2 - b^2 and is easy to understand and implement. Unfortunately it's not very fast in general. The best known method for factoring numbers up to 100 digits long is the Quadratic sieve. As a bonus, part of the algorithm is easily done with parallel processing. Yet another algorithm I've heard of is Pollard's Rho algorithm. It's not as efficient as the Quadratic Sieve in general but seems to be easier to implement. Once you've decided on how to split a number into two factors, here is the fastest algorithm I can think of to find the largest prime factor of a number: Create a priority queue which initially stores the number itself. Each iteration, you remove the highest number from the queue, and attempt to split it into two factors (not allowing 1 to be one of those factors, of course). If this step fails, the number is prime and you have your answer! Otherwise you add the two factors into the queue and repeat.
Algorithm to find Largest prime factor of a number What is the best approach to calculating the largest prime factor of a number? I'm thinking the most efficient would be the following: Find lowest prime number that divides cleanly Check if result of division is prime If not, find next lowest Go to 2. I'm basing this assumption on it being easier to calculate the small prime factors. Is this about right? What other approaches should I look into? Edit: I've now realised that my approach is futile if there are more than 2 prime factors in play, since step 2 fails when the result is a product of two other primes, therefore a recursive algorithm is needed. Edit again: And now I've realised that this does still work, because the last found prime number has to be the highest one, therefore any further testing of the non-prime result from step 2 would result in a smaller prime.
TITLE: Algorithm to find Largest prime factor of a number QUESTION: What is the best approach to calculating the largest prime factor of a number? I'm thinking the most efficient would be the following: Find lowest prime number that divides cleanly Check if result of division is prime If not, find next lowest Go to 2. I'm basing this assumption on it being easier to calculate the small prime factors. Is this about right? What other approaches should I look into? Edit: I've now realised that my approach is futile if there are more than 2 prime factors in play, since step 2 fails when the result is a product of two other primes, therefore a recursive algorithm is needed. Edit again: And now I've realised that this does still work, because the last found prime number has to be the highest one, therefore any further testing of the non-prime result from step 2 would result in a smaller prime. ANSWER: Actually there are several more efficient ways to find factors of big numbers (for smaller ones trial division works reasonably well). One method which is very fast if the input number has two factors very close to its square root is known as Fermat factorisation. It makes use of the identity N = (a + b)(a - b) = a^2 - b^2 and is easy to understand and implement. Unfortunately it's not very fast in general. The best known method for factoring numbers up to 100 digits long is the Quadratic sieve. As a bonus, part of the algorithm is easily done with parallel processing. Yet another algorithm I've heard of is Pollard's Rho algorithm. It's not as efficient as the Quadratic Sieve in general but seems to be easier to implement. Once you've decided on how to split a number into two factors, here is the fastest algorithm I can think of to find the largest prime factor of a number: Create a priority queue which initially stores the number itself. Each iteration, you remove the highest number from the queue, and attempt to split it into two factors (not allowing 1 to be one of those factors, of course). If this step fails, the number is prime and you have your answer! Otherwise you add the two factors into the queue and repeat.
[ "algorithm", "math", "prime-factoring" ]
203
147
240,765
30
0
2008-08-22T19:35:50.513000
2008-10-28T03:44:38.280000
23,288
23,292
Free ASP.Net and/or CSS Themes
Where can I get some decent looking free ASP.Net or CSS themes?
I wouldn't bother looking for ASP.NET stuff specifically (probably won't find any anyways). Finding a good CSS theme easily can be used in ASP.NET. Here's some sites that I love for CSS goodness: http://www.freecsstemplates.org/ http://www.oswd.org/ http://www.openwebdesign.org/ http://www.styleshout.com/ http://www.freelayouts.com/
Free ASP.Net and/or CSS Themes Where can I get some decent looking free ASP.Net or CSS themes?
TITLE: Free ASP.Net and/or CSS Themes QUESTION: Where can I get some decent looking free ASP.Net or CSS themes? ANSWER: I wouldn't bother looking for ASP.NET stuff specifically (probably won't find any anyways). Finding a good CSS theme easily can be used in ASP.NET. Here's some sites that I love for CSS goodness: http://www.freecsstemplates.org/ http://www.oswd.org/ http://www.openwebdesign.org/ http://www.styleshout.com/ http://www.freelayouts.com/
[ "css", "asp.net", "themes" ]
36
33
132,443
4
0
2008-08-22T19:36:06.033000
2008-08-22T19:39:11.143000
23,310
23,353
Source Control Beginners
What would be the best version control system to learn as a beginner to source control?
Anything but Visual Source Safe; preferably one which supports the concepts of branching and merging. As others have said, Subversion is a great choice, especially with the TortoiseSVN client. Be sure to check out (pardon the pun) Eric Sink's classic series of Source Control HOWTO articles.
Source Control Beginners What would be the best version control system to learn as a beginner to source control?
TITLE: Source Control Beginners QUESTION: What would be the best version control system to learn as a beginner to source control? ANSWER: Anything but Visual Source Safe; preferably one which supports the concepts of branching and merging. As others have said, Subversion is a great choice, especially with the TortoiseSVN client. Be sure to check out (pardon the pun) Eric Sink's classic series of Source Control HOWTO articles.
[ "version-control" ]
6
24
2,573
16
0
2008-08-22T19:49:05.457000
2008-08-22T20:09:20.993000
23,373
23,406
Create an EXE from a SWF using Flex 3 without requiring AIR?
I have a simple little test app written in Flex 3 (MXML and some AS3). I can compile it to a SWF just fine, but I'd like to make it into an EXE so I can give it to a couple of my coworkers who might find it useful. With Flash 8, I could just target an EXE instead of a SWF and it would wrap the SWF in a projector, and everything worked fine. Is there an equivalent to that using the Flex 3 SDK that doesn't end up requiring AIR? Note: I don't have Flex Builder, I'm just using the free Flex 3 SDK.
In your Flex SDK folders you should see a 'runtimes\player\win\FlashPlayer.exe' which is a stand alone Flash player. Open your SWF with that and you'll see a 'Create Projector...' menu item in the File menu which will create the stand-alone EXE.
Create an EXE from a SWF using Flex 3 without requiring AIR? I have a simple little test app written in Flex 3 (MXML and some AS3). I can compile it to a SWF just fine, but I'd like to make it into an EXE so I can give it to a couple of my coworkers who might find it useful. With Flash 8, I could just target an EXE instead of a SWF and it would wrap the SWF in a projector, and everything worked fine. Is there an equivalent to that using the Flex 3 SDK that doesn't end up requiring AIR? Note: I don't have Flex Builder, I'm just using the free Flex 3 SDK.
TITLE: Create an EXE from a SWF using Flex 3 without requiring AIR? QUESTION: I have a simple little test app written in Flex 3 (MXML and some AS3). I can compile it to a SWF just fine, but I'd like to make it into an EXE so I can give it to a couple of my coworkers who might find it useful. With Flash 8, I could just target an EXE instead of a SWF and it would wrap the SWF in a projector, and everything worked fine. Is there an equivalent to that using the Flex 3 SDK that doesn't end up requiring AIR? Note: I don't have Flex Builder, I'm just using the free Flex 3 SDK. ANSWER: In your Flex SDK folders you should see a 'runtimes\player\win\FlashPlayer.exe' which is a stand alone Flash player. Open your SWF with that and you'll see a 'Create Projector...' menu item in the File menu which will create the stand-alone EXE.
[ "apache-flex", "actionscript-3", "flash" ]
9
22
14,060
3
0
2008-08-22T20:18:12.610000
2008-08-22T20:31:22.390000
23,382
23,441
Scheduled Tasks for Web Applications
What are the different approaches for creating scheduled tasks for web applications, with or without a separate web/desktop application?
If we're talking Microsoft platform, then I'd always develop a separate Windows Service to handle such batch tasks. You can always reference the same assemblies that are being used by your web application to avoid any nasty code duplication.
Scheduled Tasks for Web Applications What are the different approaches for creating scheduled tasks for web applications, with or without a separate web/desktop application?
TITLE: Scheduled Tasks for Web Applications QUESTION: What are the different approaches for creating scheduled tasks for web applications, with or without a separate web/desktop application? ANSWER: If we're talking Microsoft platform, then I'd always develop a separate Windows Service to handle such batch tasks. You can always reference the same assemblies that are being used by your web application to avoid any nasty code duplication.
[ "scheduled-tasks" ]
4
4
11,949
12
0
2008-08-22T20:22:47.420000
2008-08-22T20:46:18.347000
23,391
23,505
What should I learn to increase my skills?
My path to a 'fulltime'- developer stated as a analyst using VBA with Excel, Access, and then onto C#. I went to college part time once I discovered I had a passion for coding not business. I do about most of my coding in C#, but being an ASP.NET developer I also write in HTML, JavaScript, SQL etc... the usual suspects. I like to keep moving forward find the edge that will get me to the next level, the next job, and of course more money. Most importantly I just want to learning something new and challenge me. I have spent time recently learning LINQ, but was wondering what should I learn next? Something on the.NET Framework or a new language technology?
If you want to be one of the best you need to specialise. If you become very good in many skills then you may never become truly excellent in one. I know because I have taken this route myself and have found it difficult to get employment at times. After all, who wants someone who is capable at many languages when there is someone who excels at the specific thing they need. If a company develops in C# then who would want someone who is OK at C# but also is good at C, Visual Basic, Perl and Cobol, when all they really want is the best possible C# developer for the money they can afford. After all, you will only ever be employed for one, maybe two of your skills. There are very few jobs for people who are good in 10 or 15 skills. If you are looking to a new skill then maybe check out the job boards and find which skills are particularly in need, but be aware that what is the flavour of the month this year may not even be on the scene next year, which will make all of that effort to learn the skill futile and wasted. What I would say is: do one thing, and do it well. This may include supporting skills (C#, ASP.Net, SQL, LINQ etc). If you want to choose something else, then choose something complementary. Possibly most importantly, choose something you will enjoy. Maybe Ruby on Rails is the current flavour of the month, but if you don't enjoy doing it, then don't do it. Really, it's not worth it. You will never wish, on your death bed, that you had worked more in something you didn't enjoy. Another direction you could look at is maybe not for a particular development skill, but look for something else, maybe soft skills like people management, better business understanding or even look to something like literary skills to help improve your communications skills. All of these will help to allow you to do what you want to do more, and cut down on the stuff you really don't enjoy, thus helping to make your job more enjoyable. Apologies for the waffling here. Hope you are still awake:)
What should I learn to increase my skills? My path to a 'fulltime'- developer stated as a analyst using VBA with Excel, Access, and then onto C#. I went to college part time once I discovered I had a passion for coding not business. I do about most of my coding in C#, but being an ASP.NET developer I also write in HTML, JavaScript, SQL etc... the usual suspects. I like to keep moving forward find the edge that will get me to the next level, the next job, and of course more money. Most importantly I just want to learning something new and challenge me. I have spent time recently learning LINQ, but was wondering what should I learn next? Something on the.NET Framework or a new language technology?
TITLE: What should I learn to increase my skills? QUESTION: My path to a 'fulltime'- developer stated as a analyst using VBA with Excel, Access, and then onto C#. I went to college part time once I discovered I had a passion for coding not business. I do about most of my coding in C#, but being an ASP.NET developer I also write in HTML, JavaScript, SQL etc... the usual suspects. I like to keep moving forward find the edge that will get me to the next level, the next job, and of course more money. Most importantly I just want to learning something new and challenge me. I have spent time recently learning LINQ, but was wondering what should I learn next? Something on the.NET Framework or a new language technology? ANSWER: If you want to be one of the best you need to specialise. If you become very good in many skills then you may never become truly excellent in one. I know because I have taken this route myself and have found it difficult to get employment at times. After all, who wants someone who is capable at many languages when there is someone who excels at the specific thing they need. If a company develops in C# then who would want someone who is OK at C# but also is good at C, Visual Basic, Perl and Cobol, when all they really want is the best possible C# developer for the money they can afford. After all, you will only ever be employed for one, maybe two of your skills. There are very few jobs for people who are good in 10 or 15 skills. If you are looking to a new skill then maybe check out the job boards and find which skills are particularly in need, but be aware that what is the flavour of the month this year may not even be on the scene next year, which will make all of that effort to learn the skill futile and wasted. What I would say is: do one thing, and do it well. This may include supporting skills (C#, ASP.Net, SQL, LINQ etc). If you want to choose something else, then choose something complementary. Possibly most importantly, choose something you will enjoy. Maybe Ruby on Rails is the current flavour of the month, but if you don't enjoy doing it, then don't do it. Really, it's not worth it. You will never wish, on your death bed, that you had worked more in something you didn't enjoy. Another direction you could look at is maybe not for a particular development skill, but look for something else, maybe soft skills like people management, better business understanding or even look to something like literary skills to help improve your communications skills. All of these will help to allow you to do what you want to do more, and cut down on the stuff you really don't enjoy, thus helping to make your job more enjoyable. Apologies for the waffling here. Hope you are still awake:)
[ "c#", ".net" ]
9
6
2,367
9
0
2008-08-22T20:25:46.103000
2008-08-22T21:13:22.213000
23,399
23,432
Is it better to structure an SQL table to have a match, or return no result
I've got an interesting design question. I'm designing the security side of our project, to allow us to have different versions of the program for different costs and also to allow Manager-type users to grant or deny access to parts of the program to other users. Its going to web-based and hosted on our servers. I'm using a simple Allow or Deny option for each 'Resource' or screen. We're going to have a large number of resources, and the user will be able to set up many different groups to put users in to control access. Each user can only belong to a single group. I've got two approaches to this in mind, and was curious which would be better for the SQL server in terms of performance. Option A The presence of an entry in the access table means access is allowed. This will not need a column in the database to store information. If no results are returned, then access is denied. I think this will mean a smaller table, but would queries search the whole table to determine there is no match? Option B A bit column is included in the database that controls the Allow/Deny. This will mean there is always a result to be found, and makes for a larger table. Thoughts?
If it's only going to be Allow/Deny, then a simple linking table between Users and Resources would work fine. If there is an entry keyed to the User-Resource in the linking table, allow access. UserResources ------------- UserId FK->Users ResourceId FK->Resources and the sql would be something like if exists (select 1 from UserResources where UserId = @uid and ResourceId=@rid) set @allow=1; With a clustered index on (UserId and ResourceId), the query would be blindingly fast even with millions of records.
Is it better to structure an SQL table to have a match, or return no result I've got an interesting design question. I'm designing the security side of our project, to allow us to have different versions of the program for different costs and also to allow Manager-type users to grant or deny access to parts of the program to other users. Its going to web-based and hosted on our servers. I'm using a simple Allow or Deny option for each 'Resource' or screen. We're going to have a large number of resources, and the user will be able to set up many different groups to put users in to control access. Each user can only belong to a single group. I've got two approaches to this in mind, and was curious which would be better for the SQL server in terms of performance. Option A The presence of an entry in the access table means access is allowed. This will not need a column in the database to store information. If no results are returned, then access is denied. I think this will mean a smaller table, but would queries search the whole table to determine there is no match? Option B A bit column is included in the database that controls the Allow/Deny. This will mean there is always a result to be found, and makes for a larger table. Thoughts?
TITLE: Is it better to structure an SQL table to have a match, or return no result QUESTION: I've got an interesting design question. I'm designing the security side of our project, to allow us to have different versions of the program for different costs and also to allow Manager-type users to grant or deny access to parts of the program to other users. Its going to web-based and hosted on our servers. I'm using a simple Allow or Deny option for each 'Resource' or screen. We're going to have a large number of resources, and the user will be able to set up many different groups to put users in to control access. Each user can only belong to a single group. I've got two approaches to this in mind, and was curious which would be better for the SQL server in terms of performance. Option A The presence of an entry in the access table means access is allowed. This will not need a column in the database to store information. If no results are returned, then access is denied. I think this will mean a smaller table, but would queries search the whole table to determine there is no match? Option B A bit column is included in the database that controls the Allow/Deny. This will mean there is always a result to be found, and makes for a larger table. Thoughts? ANSWER: If it's only going to be Allow/Deny, then a simple linking table between Users and Resources would work fine. If there is an entry keyed to the User-Resource in the linking table, allow access. UserResources ------------- UserId FK->Users ResourceId FK->Resources and the sql would be something like if exists (select 1 from UserResources where UserId = @uid and ResourceId=@rid) set @allow=1; With a clustered index on (UserId and ResourceId), the query would be blindingly fast even with millions of records.
[ "sql", "sql-server", "optimization" ]
0
4
258
4
0
2008-08-22T20:28:38.887000
2008-08-22T20:41:25.190000
23,402
23,417
Are there any alternatives to Gigaspaces?
Anything thats as good and as stable and as feature-rich as gigaspaces?
Gigaspaces is top notch as far as a Javaspaces implementation goes for scalability and performance. Are you restricted to a Javaspaces implementation? Blitz Javaspaces is top notch for a free product.
Are there any alternatives to Gigaspaces? Anything thats as good and as stable and as feature-rich as gigaspaces?
TITLE: Are there any alternatives to Gigaspaces? QUESTION: Anything thats as good and as stable and as feature-rich as gigaspaces? ANSWER: Gigaspaces is top notch as far as a Javaspaces implementation goes for scalability and performance. Are you restricted to a Javaspaces implementation? Blitz Javaspaces is top notch for a free product.
[ "java", "jakarta-ee", "gigaspaces" ]
10
8
4,365
4
0
2008-08-22T20:30:04.017000
2008-08-22T20:35:55.970000
23,439
25,899
FLVPlayback component memory issues
My website is entirely flash based, it moves around a 3D model which was given to me as chunks of video that I've converted to FLV files. I'm using the FLVPlayback component to control the video inside of my program. While running memory checks using System.totalMemory I've noticed that whenever a video is loaded, it will eat up a chunk of memory and even when I remove all the event listeners from it(they are all weakly referenced), remove the component from its parent, stop the video and null the component instance, it still will not give that memory back. This has been bothering me since I started working on this project because of the huge amount of video a user can potentially instantiate and load. Currently every video is loaded into a new FLVPlayback instance whenever it is required, but I have read that perhaps the best way to go about this problem is to simply have a global FLVPlayback instance and just reload the new video into the old instance, that way there would only be one FLVPlayback component in the application's memory. Has anyone else run into this problem as well? Have you found a better solution than using a global instance that you just re-use for every new video?
You can't help the memory problems much until Flash adds destructors and explicit object deletion, unfortunately. See this thread: Unloading a ByteArray in Actionscript 3 There's a limit to how much memory Flash applets can use; the GC seems to fire upon reaching that limit. I've seen my memory-easy applets use as much as ~200MB, just because they run for hours on end and the GC doesn't want to kick in. Oh, and I don't think using a single instance is an elegant solution, either. Currently I just write a dispose() function for my custom classes, waiting for some day when it can be turned into a proper destructor.
FLVPlayback component memory issues My website is entirely flash based, it moves around a 3D model which was given to me as chunks of video that I've converted to FLV files. I'm using the FLVPlayback component to control the video inside of my program. While running memory checks using System.totalMemory I've noticed that whenever a video is loaded, it will eat up a chunk of memory and even when I remove all the event listeners from it(they are all weakly referenced), remove the component from its parent, stop the video and null the component instance, it still will not give that memory back. This has been bothering me since I started working on this project because of the huge amount of video a user can potentially instantiate and load. Currently every video is loaded into a new FLVPlayback instance whenever it is required, but I have read that perhaps the best way to go about this problem is to simply have a global FLVPlayback instance and just reload the new video into the old instance, that way there would only be one FLVPlayback component in the application's memory. Has anyone else run into this problem as well? Have you found a better solution than using a global instance that you just re-use for every new video?
TITLE: FLVPlayback component memory issues QUESTION: My website is entirely flash based, it moves around a 3D model which was given to me as chunks of video that I've converted to FLV files. I'm using the FLVPlayback component to control the video inside of my program. While running memory checks using System.totalMemory I've noticed that whenever a video is loaded, it will eat up a chunk of memory and even when I remove all the event listeners from it(they are all weakly referenced), remove the component from its parent, stop the video and null the component instance, it still will not give that memory back. This has been bothering me since I started working on this project because of the huge amount of video a user can potentially instantiate and load. Currently every video is loaded into a new FLVPlayback instance whenever it is required, but I have read that perhaps the best way to go about this problem is to simply have a global FLVPlayback instance and just reload the new video into the old instance, that way there would only be one FLVPlayback component in the application's memory. Has anyone else run into this problem as well? Have you found a better solution than using a global instance that you just re-use for every new video? ANSWER: You can't help the memory problems much until Flash adds destructors and explicit object deletion, unfortunately. See this thread: Unloading a ByteArray in Actionscript 3 There's a limit to how much memory Flash applets can use; the GC seems to fire upon reaching that limit. I've seen my memory-easy applets use as much as ~200MB, just because they run for hours on end and the GC doesn't want to kick in. Oh, and I don't think using a single instance is an elegant solution, either. Currently I just write a dispose() function for my custom classes, waiting for some day when it can be turned into a proper destructor.
[ "actionscript-3", "memory", "video", "flash" ]
1
1
2,612
5
0
2008-08-22T20:44:55.150000
2008-08-25T11:52:04.143000
23,446
23,473
How do I format Visual Studio Test results file (.trx) into a more readable format?
Have just started using Visual Studio Professional's built-in unit testing features, which as I understand, uses MS Test to run the tests. The.trx file that the tests produce is xml, but was wondering if there was an easy way to convert this file into a more "manager-friendly" format? My ultimate goal is to be able to automate the unit-testing and be able to produce a nice looking document that shows the tests run and how 100% of them passed:)
Since this file is XML you could and should use xsl to transform it to another format. The IAmUnkown - blog has an entry about decoding/transforming the trx file into html. You can also use.NetSpecExporter from Bekk to create nice reports. Their product also uses XSL, so you could probably steal it from the downloaded file and apply it with whatever xsl-application you want.
How do I format Visual Studio Test results file (.trx) into a more readable format? Have just started using Visual Studio Professional's built-in unit testing features, which as I understand, uses MS Test to run the tests. The.trx file that the tests produce is xml, but was wondering if there was an easy way to convert this file into a more "manager-friendly" format? My ultimate goal is to be able to automate the unit-testing and be able to produce a nice looking document that shows the tests run and how 100% of them passed:)
TITLE: How do I format Visual Studio Test results file (.trx) into a more readable format? QUESTION: Have just started using Visual Studio Professional's built-in unit testing features, which as I understand, uses MS Test to run the tests. The.trx file that the tests produce is xml, but was wondering if there was an easy way to convert this file into a more "manager-friendly" format? My ultimate goal is to be able to automate the unit-testing and be able to produce a nice looking document that shows the tests run and how 100% of them passed:) ANSWER: Since this file is XML you could and should use xsl to transform it to another format. The IAmUnkown - blog has an entry about decoding/transforming the trx file into html. You can also use.NetSpecExporter from Bekk to create nice reports. Their product also uses XSL, so you could probably steal it from the downloaded file and apply it with whatever xsl-application you want.
[ "visual-studio-2008", "unit-testing" ]
18
9
37,770
5
0
2008-08-22T20:48:03.897000
2008-08-22T20:58:42.123000
23,448
24,167
DSLs (Domain Specific Languages) in Finance
Has anyone worked with DSLs (Domain Specific Languages) in the finance domain? I am planning to introduce some kind of DSL support in the application that I am working on and would like to share some ideas. I am in a stage of identifying which are the most stable domain elements and selecting the features which would be better implemented with the DSL. I have not yet defined the syntax for this first feature.
Jay Fields and Obie Fernandez have written and talked extensively on the subject. Jay Fields intro on Domain Specific Languages Jay Fields' series on Business Natural Language Obie Fernandez Expressing Contract Terms in a DSL A very good presentation on infoQ by Jay Fields You'll also find general stuff on implementing DSL in Martin Fowler's writings (but not specific to finance). DSL
DSLs (Domain Specific Languages) in Finance Has anyone worked with DSLs (Domain Specific Languages) in the finance domain? I am planning to introduce some kind of DSL support in the application that I am working on and would like to share some ideas. I am in a stage of identifying which are the most stable domain elements and selecting the features which would be better implemented with the DSL. I have not yet defined the syntax for this first feature.
TITLE: DSLs (Domain Specific Languages) in Finance QUESTION: Has anyone worked with DSLs (Domain Specific Languages) in the finance domain? I am planning to introduce some kind of DSL support in the application that I am working on and would like to share some ideas. I am in a stage of identifying which are the most stable domain elements and selecting the features which would be better implemented with the DSL. I have not yet defined the syntax for this first feature. ANSWER: Jay Fields and Obie Fernandez have written and talked extensively on the subject. Jay Fields intro on Domain Specific Languages Jay Fields' series on Business Natural Language Obie Fernandez Expressing Contract Terms in a DSL A very good presentation on infoQ by Jay Fields You'll also find general stuff on implementing DSL in Martin Fowler's writings (but not specific to finance). DSL
[ "dsl", "finance" ]
19
9
6,111
5
0
2008-08-22T20:48:14.003000
2008-08-23T12:04:32.493000
23,472
23,533
Resources for an Oracle beginner
Can anyone recommend some good resources that highlight the differences between Oracle and the AS/400 database? I am trying to help someone with a lot of AS/400 experience implement an Oracle installation, and they need some guidance. A book or online resource would be ideal.
I've done this a fair few times and the solutions out there really depend on the environment (enterprise / mission critical or development). The BEST way would be the Oracle AS/400 Gateway. Here are some important links in that area: Allow AS/400 apps to access oracle with the Oracle Access Manager: Installation Guide for the AS/400 Oracle Access Manager Allow your Oracle apps to access AS/400 tables and be queried using Oracle: Oracle Transparent Gateway for DB/2 ^^^Those products are fairly expensive but super powerful.^^^ Alternately, here are some more academic approaches to the situation: Here's a technical comparison of the two technologies... It's a little propagandaish*. Technical comparisons of Oracle and DB/2 Here's a document written from the opposite point of view - Someone moving from Oracle to DB2. I still find it's useful information: Leverage your Oracle 10g skills to learn DB2... And another IBM link that has some really great information all around: IBM Developer Network Search Results Hope this helps! *Yes, I know propagandaish is not a real word.
Resources for an Oracle beginner Can anyone recommend some good resources that highlight the differences between Oracle and the AS/400 database? I am trying to help someone with a lot of AS/400 experience implement an Oracle installation, and they need some guidance. A book or online resource would be ideal.
TITLE: Resources for an Oracle beginner QUESTION: Can anyone recommend some good resources that highlight the differences between Oracle and the AS/400 database? I am trying to help someone with a lot of AS/400 experience implement an Oracle installation, and they need some guidance. A book or online resource would be ideal. ANSWER: I've done this a fair few times and the solutions out there really depend on the environment (enterprise / mission critical or development). The BEST way would be the Oracle AS/400 Gateway. Here are some important links in that area: Allow AS/400 apps to access oracle with the Oracle Access Manager: Installation Guide for the AS/400 Oracle Access Manager Allow your Oracle apps to access AS/400 tables and be queried using Oracle: Oracle Transparent Gateway for DB/2 ^^^Those products are fairly expensive but super powerful.^^^ Alternately, here are some more academic approaches to the situation: Here's a technical comparison of the two technologies... It's a little propagandaish*. Technical comparisons of Oracle and DB/2 Here's a document written from the opposite point of view - Someone moving from Oracle to DB2. I still find it's useful information: Leverage your Oracle 10g skills to learn DB2... And another IBM link that has some really great information all around: IBM Developer Network Search Results Hope this helps! *Yes, I know propagandaish is not a real word.
[ "oracle", "ibm-midrange" ]
1
2
369
3
0
2008-08-22T20:58:21.703000
2008-08-22T21:23:11.783000
23,511
5,009,525
Algorithm behind MD5Crypt
I'm working with Subversion based on Windows and would like to write an easy utility in.NET for working with the Apache password file. I understand that it uses a function referred to as MD5Crypt, but I can't seem to find a description of the algorithm beyond that at some point it uses MD5 to create a hash. Can someone describe the MD5Crypt algorithm and password line format?
A precise textual description of the crypt algorithm updated for use with sha256 and sha512 is at http://www.akkadia.org/drepper/SHA-crypt.txt It includes contrasts with the MD5 algorithm, so it should give you what you're looking for.
Algorithm behind MD5Crypt I'm working with Subversion based on Windows and would like to write an easy utility in.NET for working with the Apache password file. I understand that it uses a function referred to as MD5Crypt, but I can't seem to find a description of the algorithm beyond that at some point it uses MD5 to create a hash. Can someone describe the MD5Crypt algorithm and password line format?
TITLE: Algorithm behind MD5Crypt QUESTION: I'm working with Subversion based on Windows and would like to write an easy utility in.NET for working with the Apache password file. I understand that it uses a function referred to as MD5Crypt, but I can't seem to find a description of the algorithm beyond that at some point it uses MD5 to create a hash. Can someone describe the MD5Crypt algorithm and password line format? ANSWER: A precise textual description of the crypt algorithm updated for use with sha256 and sha512 is at http://www.akkadia.org/drepper/SHA-crypt.txt It includes contrasts with the MD5 algorithm, so it should give you what you're looking for.
[ ".net", "svn", "apache", "md5", "crypt" ]
3
4
4,319
4
0
2008-08-22T21:16:45.170000
2011-02-15T21:09:46.357000
23,564
23,643
What WCF best practices do you follow in object model design?
I've noticed that a handful of WCF applications choose to "break" their objects apart; that is, a project might have a DataObjects assembly that contains DataContracts/Members in addition to a meaningful class library that performs business logic. Is this an unnecessary level of abstraction? Is there any inherent evil associated with going through and tagging existing class libraries with DataContract information? Also, as an aside, how do you handle error conditions? Are thrown exceptions from the service (InvalidOperation, ArgumentException and so on) generally accepted, or is there usually a level around that?
The key reason to separating internal business objects from the data contracts/message contracts is that you don't want internal changes to your app to necessarily change the service contract. If you're creating versioned web services (with more than 1 version of the implemented interfaces) then you often have a single version of your apps business objects with more than 1 version of the data contract/message contract objects. In addition, in complex Enterprise Integration situations you often have a canonical data format (Data and Message contracts) which is shared by a number of applications, which forces each application to map the canonical data format to its internal object model. If you want a tool to help with the nitty gritty of separating data contract/message contract etc. then check out Microsoft's Web Services Software Factory http://msdn.microsoft.com/en-us/library/cc487895.aspx which has some good recipes for solving the WCF plumbing. In regards to excpetions, WCF automatically wraps all exceptions in FaultExceptions, which are serialized as wire-format faults. It's also possible to throw generic Fault Exceptions which allows you to specify additional details to be included with the serialized fault. Since the faults thrown by a web service operation are part of its contract it's a good idea to declare the faults on the operation declaration: [FaultContract(typeof(AuthenticationFault))] [FaultContract(typeof(AuthorizationFault))] StoreLocationResponse StoreLocation(StoreLocationRequest request); Both the AuthenticationFault and AuthorizationFault types represent the additional details to be serialized and sent over the wire and can be thrown as follows: throw new FaultException (new AuthenticationFault()); If you want more details then shout; I've been living and breathing this stuff for so long I almost making a living doing it;)
What WCF best practices do you follow in object model design? I've noticed that a handful of WCF applications choose to "break" their objects apart; that is, a project might have a DataObjects assembly that contains DataContracts/Members in addition to a meaningful class library that performs business logic. Is this an unnecessary level of abstraction? Is there any inherent evil associated with going through and tagging existing class libraries with DataContract information? Also, as an aside, how do you handle error conditions? Are thrown exceptions from the service (InvalidOperation, ArgumentException and so on) generally accepted, or is there usually a level around that?
TITLE: What WCF best practices do you follow in object model design? QUESTION: I've noticed that a handful of WCF applications choose to "break" their objects apart; that is, a project might have a DataObjects assembly that contains DataContracts/Members in addition to a meaningful class library that performs business logic. Is this an unnecessary level of abstraction? Is there any inherent evil associated with going through and tagging existing class libraries with DataContract information? Also, as an aside, how do you handle error conditions? Are thrown exceptions from the service (InvalidOperation, ArgumentException and so on) generally accepted, or is there usually a level around that? ANSWER: The key reason to separating internal business objects from the data contracts/message contracts is that you don't want internal changes to your app to necessarily change the service contract. If you're creating versioned web services (with more than 1 version of the implemented interfaces) then you often have a single version of your apps business objects with more than 1 version of the data contract/message contract objects. In addition, in complex Enterprise Integration situations you often have a canonical data format (Data and Message contracts) which is shared by a number of applications, which forces each application to map the canonical data format to its internal object model. If you want a tool to help with the nitty gritty of separating data contract/message contract etc. then check out Microsoft's Web Services Software Factory http://msdn.microsoft.com/en-us/library/cc487895.aspx which has some good recipes for solving the WCF plumbing. In regards to excpetions, WCF automatically wraps all exceptions in FaultExceptions, which are serialized as wire-format faults. It's also possible to throw generic Fault Exceptions which allows you to specify additional details to be included with the serialized fault. Since the faults thrown by a web service operation are part of its contract it's a good idea to declare the faults on the operation declaration: [FaultContract(typeof(AuthenticationFault))] [FaultContract(typeof(AuthorizationFault))] StoreLocationResponse StoreLocation(StoreLocationRequest request); Both the AuthenticationFault and AuthorizationFault types represent the additional details to be serialized and sent over the wire and can be thrown as follows: throw new FaultException (new AuthenticationFault()); If you want more details then shout; I've been living and breathing this stuff for so long I almost making a living doing it;)
[ "wcf" ]
12
17
6,012
1
0
2008-08-22T21:36:55.807000
2008-08-22T22:14:41.550000
23,566
23,571
What does 'IISReset' do?
On IIS 6, what does an IIS reset do? Please compare to recycling an app pool and stopping and starting an ASP.NET web site. If you replace a DLL or edit/replace the web.config on an ASP.NET web site is that the same as stopping and starting that web site?
IISReset stops and restarts the entire web server (including non-ASP.NET apps) Recycling an app pool will only affect applications running in that app pool. Editing the web.config in a web application only affects that web application (recycles just that app). Editing the machine.config on the machine will recycle all app pools running. IIS will monitor the /bin directory of your application. Whenever a change is detected in those dlls, it will recycle the app and re-load those new dlls. It also monitors the web.config & machine.config in the same way and performs the same action for the applicable apps.
What does 'IISReset' do? On IIS 6, what does an IIS reset do? Please compare to recycling an app pool and stopping and starting an ASP.NET web site. If you replace a DLL or edit/replace the web.config on an ASP.NET web site is that the same as stopping and starting that web site?
TITLE: What does 'IISReset' do? QUESTION: On IIS 6, what does an IIS reset do? Please compare to recycling an app pool and stopping and starting an ASP.NET web site. If you replace a DLL or edit/replace the web.config on an ASP.NET web site is that the same as stopping and starting that web site? ANSWER: IISReset stops and restarts the entire web server (including non-ASP.NET apps) Recycling an app pool will only affect applications running in that app pool. Editing the web.config in a web application only affects that web application (recycles just that app). Editing the machine.config on the machine will recycle all app pools running. IIS will monitor the /bin directory of your application. Whenever a change is detected in those dlls, it will recycle the app and re-load those new dlls. It also monitors the web.config & machine.config in the same way and performs the same action for the applicable apps.
[ "asp.net", "iis", "iis-7", "iis-6", "iis-8" ]
74
81
125,535
9
0
2008-08-22T21:37:35.900000
2008-08-22T21:40:26.767000
23,569
23,700
Calculating Distance Between 2 Cities
How do you calculate the distance between 2 cities?
If you need to take the curvature of the earth into account, the Great-Circle distance is what you're looking for. The Wikipedia article probably does a better job of explaining how the formula works than me, and there's also this aviation formulary page that covers that goes into more detail. The formulas are only the first part of the puzzle though, if you need to make this work for arbitrary cities, you'll need a location database to get the lat/long from. Luckily you can get this for free from Geonames.org, although there are commercial db's available (ask google). So, in general, look up the two cities you want, get the lat/long co-orinates and plug them into the formula as in the Wikipedia Worked Example. Other suggestions: For a full commercial solution, there's PC Miler which is used by many trucking companies to calculate shipping rates. Make calls to the Google Maps (or other) api. If you need to do many requests per day, consider caching the results on the server. Also very important is to consider building an equivalence database for cities, suburbs, towns etc. if you think you'll ever need to group your data. This gets really complicated though, and you may not find a one-size-fits-all solution for your problem. Last but not least, Joel wrote an article about this problem a while back, so here you go: New Feature: Job Search
Calculating Distance Between 2 Cities How do you calculate the distance between 2 cities?
TITLE: Calculating Distance Between 2 Cities QUESTION: How do you calculate the distance between 2 cities? ANSWER: If you need to take the curvature of the earth into account, the Great-Circle distance is what you're looking for. The Wikipedia article probably does a better job of explaining how the formula works than me, and there's also this aviation formulary page that covers that goes into more detail. The formulas are only the first part of the puzzle though, if you need to make this work for arbitrary cities, you'll need a location database to get the lat/long from. Luckily you can get this for free from Geonames.org, although there are commercial db's available (ask google). So, in general, look up the two cities you want, get the lat/long co-orinates and plug them into the formula as in the Wikipedia Worked Example. Other suggestions: For a full commercial solution, there's PC Miler which is used by many trucking companies to calculate shipping rates. Make calls to the Google Maps (or other) api. If you need to do many requests per day, consider caching the results on the server. Also very important is to consider building an equivalence database for cities, suburbs, towns etc. if you think you'll ever need to group your data. This gets really complicated though, and you may not find a one-size-fits-all solution for your problem. Last but not least, Joel wrote an article about this problem a while back, so here you go: New Feature: Job Search
[ "algorithm", "math", "trigonometry", "geography" ]
16
33
16,542
14
0
2008-08-22T21:39:41.917000
2008-08-22T22:53:00.587000
23,614
23,669
Reporting Systems for ASP.NET
What are the best open source (open source and commercial) reporting tools for ASP.NET similar to Crystal Reports for ASP.NET?
Microsoft Reporting Services, free and included with SQL Server 2005 and 2008. Of course, this is great if you need a separation of report design and application, which for Enterprise applications is a huge plus. However, if what you want is to be able to create "in application" dashboards, where "you" design the reports and have limited parameters you expose to the user, then I suggest looking into "control" based charting vendors like TeeChart. Pros/cons of each strategy: Crystal/Microsoft Reporting services will give you out of the box handling of things like report scheduling, export to excel and pdf, and separation between application and report design. The independent charting tools you can get give you better control, they render better on any size you need, easier to grammatically manipulate and can handle eye candy such as flash based (no flash charts in MS SSRS)
Reporting Systems for ASP.NET What are the best open source (open source and commercial) reporting tools for ASP.NET similar to Crystal Reports for ASP.NET?
TITLE: Reporting Systems for ASP.NET QUESTION: What are the best open source (open source and commercial) reporting tools for ASP.NET similar to Crystal Reports for ASP.NET? ANSWER: Microsoft Reporting Services, free and included with SQL Server 2005 and 2008. Of course, this is great if you need a separation of report design and application, which for Enterprise applications is a huge plus. However, if what you want is to be able to create "in application" dashboards, where "you" design the reports and have limited parameters you expose to the user, then I suggest looking into "control" based charting vendors like TeeChart. Pros/cons of each strategy: Crystal/Microsoft Reporting services will give you out of the box handling of things like report scheduling, export to excel and pdf, and separation between application and report design. The independent charting tools you can get give you better control, they render better on any size you need, easier to grammatically manipulate and can handle eye candy such as flash based (no flash charts in MS SSRS)
[ "asp.net", "report" ]
6
8
8,874
6
0
2008-08-22T22:00:07.593000
2008-08-22T22:33:18.870000
23,640
23,692
Free or Open Source Collaboration/eLearning Software
I am looking for open source or free data collaboration software. Specifically this is for a non-profit organization that wants to teach remote students how a foreign language. The idea is that an instructor would teach a class and there would be up to 10 students in the class at a time. The instructor would be able to post slides or other teaching material and the students would be able to see it on their computers remotely. Video is not required but audio is a must. Any recommendations? Also if there have been any reviews or feature comparison amongst these products, I would be interested in hearing about them.
The BlindSide site also listed these other projects: ePresence OpenMeetings DimDim WebHuddle All opensource as well.
Free or Open Source Collaboration/eLearning Software I am looking for open source or free data collaboration software. Specifically this is for a non-profit organization that wants to teach remote students how a foreign language. The idea is that an instructor would teach a class and there would be up to 10 students in the class at a time. The instructor would be able to post slides or other teaching material and the students would be able to see it on their computers remotely. Video is not required but audio is a must. Any recommendations? Also if there have been any reviews or feature comparison amongst these products, I would be interested in hearing about them.
TITLE: Free or Open Source Collaboration/eLearning Software QUESTION: I am looking for open source or free data collaboration software. Specifically this is for a non-profit organization that wants to teach remote students how a foreign language. The idea is that an instructor would teach a class and there would be up to 10 students in the class at a time. The instructor would be able to post slides or other teaching material and the students would be able to see it on their computers remotely. Video is not required but audio is a must. Any recommendations? Also if there have been any reviews or feature comparison amongst these products, I would be interested in hearing about them. ANSWER: The BlindSide site also listed these other projects: ePresence OpenMeetings DimDim WebHuddle All opensource as well.
[ "product" ]
3
3
1,260
8
0
2008-08-22T22:13:06.017000
2008-08-22T22:46:06.250000
23,689
631,134
Natural language date/time parser for .NET?
Does anyone know of a.NET date/time parser similar to Chronic for Ruby (handles stuff like "tomorrow" or "3pm next thursday")? Note: I do write Ruby (which is how I know about Chronic) but this project must use.NET.
We developed exactly what you are looking for on an internal project. We are thinking of making this public if there is sufficient need for it. Take a look at this blog for more details: http://precisionsoftwaredesign.com/blog.php. Feel free to contact me if you are interested: contact@precisionsoftware.us This library is now a SourceForge project. The page is at: http://www.SourceForge.net/p/naturaldate The assembly is in the downloads section, and the source is available with Mercurial.
Natural language date/time parser for .NET? Does anyone know of a.NET date/time parser similar to Chronic for Ruby (handles stuff like "tomorrow" or "3pm next thursday")? Note: I do write Ruby (which is how I know about Chronic) but this project must use.NET.
TITLE: Natural language date/time parser for .NET? QUESTION: Does anyone know of a.NET date/time parser similar to Chronic for Ruby (handles stuff like "tomorrow" or "3pm next thursday")? Note: I do write Ruby (which is how I know about Chronic) but this project must use.NET. ANSWER: We developed exactly what you are looking for on an internal project. We are thinking of making this public if there is sufficient need for it. Take a look at this blog for more details: http://precisionsoftwaredesign.com/blog.php. Feel free to contact me if you are interested: contact@precisionsoftware.us This library is now a SourceForge project. The page is at: http://www.SourceForge.net/p/naturaldate The assembly is in the downloads section, and the source is available with Mercurial.
[ ".net", "datetime", "nlp" ]
27
12
6,270
9
0
2008-08-22T22:45:10.790000
2009-03-10T16:36:12.697000
23,713
23,929
.NET Security Policy change by standard users?
The.NET Security Policy can be changed from a script by using CasPol.exe. Say I will be distributing an application to several users on a local network. Most of those users will be unprivileged, standard accounts, so they will not have necessary permissions for the relevant command. I think I shall be looking into domain logon scripts. Is there any alternative scenarios? Any solutions for networks without a domain? Edit: I'm bound to use Framework version 2.0
The latest version of.Net 3.5 SP1 now allows you to run managed executables over a network share without using CasPol. See this post
.NET Security Policy change by standard users? The.NET Security Policy can be changed from a script by using CasPol.exe. Say I will be distributing an application to several users on a local network. Most of those users will be unprivileged, standard accounts, so they will not have necessary permissions for the relevant command. I think I shall be looking into domain logon scripts. Is there any alternative scenarios? Any solutions for networks without a domain? Edit: I'm bound to use Framework version 2.0
TITLE: .NET Security Policy change by standard users? QUESTION: The.NET Security Policy can be changed from a script by using CasPol.exe. Say I will be distributing an application to several users on a local network. Most of those users will be unprivileged, standard accounts, so they will not have necessary permissions for the relevant command. I think I shall be looking into domain logon scripts. Is there any alternative scenarios? Any solutions for networks without a domain? Edit: I'm bound to use Framework version 2.0 ANSWER: The latest version of.Net 3.5 SP1 now allows you to run managed executables over a network share without using CasPol. See this post
[ ".net", "windows", "security" ]
1
1
297
1
0
2008-08-22T23:06:00.490000
2008-08-23T03:46:01.147000
23,715
23,732
Running Apache alongside another web server?
Has anyone had any success running two different web servers -- such as Apache and CherryPy -- alongside each other on the same machine? I am experimenting with other web servers right now, and I'd like to see if I can do my experiments while keeping my other sites up and running. You could say that this isn't so much a specific-software question as it is a general networking question. I know it's possible to run two web servers on different ports; but is there any way to configure them so that they can run on the same port (ie, they both run on port 80)? The web servers would not be serving files from the same domains. For example, Apache might serve up documents from foo.domain.com, and the other web server would serve from bar.domain.com. I do know that this is not an ideal configuration. I'd just like to see if it can be done before I go sprinting down the rabbit hole.:)
You can't have two processes bound to the same port on the same IP address. You can add another IP address to the box and have each server listen on one. Another option is to proxy pass one server to the other. With Apache, you could do something like: NameVirtualHost * ServerName other.site.com # assumes CherryPy listens on port 8080 ProxyPass / http://127.0.0.1:8080/ ProxyPassReverse / http://127.0.0.1:8080/ That's a pretty quick example, but you can always check the ProxyPass documentation. Remember though, the application being proxyed to will get 127.0.0.1 in it's logs instead of the requester's IP address. Some web servers (apache does with mod_rpaf ) can substitute the X-Forwarded-For header in place of the wrong IP address. Possibly CherryPy has this?
Running Apache alongside another web server? Has anyone had any success running two different web servers -- such as Apache and CherryPy -- alongside each other on the same machine? I am experimenting with other web servers right now, and I'd like to see if I can do my experiments while keeping my other sites up and running. You could say that this isn't so much a specific-software question as it is a general networking question. I know it's possible to run two web servers on different ports; but is there any way to configure them so that they can run on the same port (ie, they both run on port 80)? The web servers would not be serving files from the same domains. For example, Apache might serve up documents from foo.domain.com, and the other web server would serve from bar.domain.com. I do know that this is not an ideal configuration. I'd just like to see if it can be done before I go sprinting down the rabbit hole.:)
TITLE: Running Apache alongside another web server? QUESTION: Has anyone had any success running two different web servers -- such as Apache and CherryPy -- alongside each other on the same machine? I am experimenting with other web servers right now, and I'd like to see if I can do my experiments while keeping my other sites up and running. You could say that this isn't so much a specific-software question as it is a general networking question. I know it's possible to run two web servers on different ports; but is there any way to configure them so that they can run on the same port (ie, they both run on port 80)? The web servers would not be serving files from the same domains. For example, Apache might serve up documents from foo.domain.com, and the other web server would serve from bar.domain.com. I do know that this is not an ideal configuration. I'd just like to see if it can be done before I go sprinting down the rabbit hole.:) ANSWER: You can't have two processes bound to the same port on the same IP address. You can add another IP address to the box and have each server listen on one. Another option is to proxy pass one server to the other. With Apache, you could do something like: NameVirtualHost * ServerName other.site.com # assumes CherryPy listens on port 8080 ProxyPass / http://127.0.0.1:8080/ ProxyPassReverse / http://127.0.0.1:8080/ That's a pretty quick example, but you can always check the ProxyPass documentation. Remember though, the application being proxyed to will get 127.0.0.1 in it's logs instead of the requester's IP address. Some web servers (apache does with mod_rpaf ) can substitute the X-Forwarded-For header in place of the wrong IP address. Possibly CherryPy has this?
[ "linux", "apache" ]
3
7
1,620
3
0
2008-08-22T23:06:43.437000
2008-08-22T23:24:25.377000
23,737
23,768
Do you have any tips to improve ReSharper and/or Visual Studio performance?
I'm using visual studio 2008 and ReSharper 4 and it's kind of slow. My machine has 2 GB of RAM, dual core processor and a 7200 rpm hard disk. I know more RAM and a faster hard disk could improve performance, but do you have any tips to improve ReSharper/Visual Studio performance?
Turn off the annoying RSS reader Tools, Options, Environment, Startup Turn off all the animations Tools, Options, Environment, Animate Environment Tools Install the recent Service Pack Clean out your WebCache AppData\Local\Microsoft\WebSiteCache
Do you have any tips to improve ReSharper and/or Visual Studio performance? I'm using visual studio 2008 and ReSharper 4 and it's kind of slow. My machine has 2 GB of RAM, dual core processor and a 7200 rpm hard disk. I know more RAM and a faster hard disk could improve performance, but do you have any tips to improve ReSharper/Visual Studio performance?
TITLE: Do you have any tips to improve ReSharper and/or Visual Studio performance? QUESTION: I'm using visual studio 2008 and ReSharper 4 and it's kind of slow. My machine has 2 GB of RAM, dual core processor and a 7200 rpm hard disk. I know more RAM and a faster hard disk could improve performance, but do you have any tips to improve ReSharper/Visual Studio performance? ANSWER: Turn off the annoying RSS reader Tools, Options, Environment, Startup Turn off all the animations Tools, Options, Environment, Animate Environment Tools Install the recent Service Pack Clean out your WebCache AppData\Local\Microsoft\WebSiteCache
[ ".net", "visual-studio", "performance", "resharper" ]
14
8
11,780
6
0
2008-08-22T23:27:21.050000
2008-08-23T00:03:13.770000
23,738
23,754
Why is Peer-to-Peer programming a hard topic to obtain good research for?
After reading a bit more about how Gnutella and other P2P networks function, I wanted to start my own peer-to-peer system. I went in thinking that I would find plenty of tutorials and language-agnostic guidelines which could be applied, however I was met with a vague simplistic overview. I could only find very small, precise P2P code which didn't do much more than use client/server architecture on all users, which wasn't really what I was looking for. I wanted something like Gnutella, but there doesn't seem to be any articles out in the open for joining the network.
I had to write a basic Gnutella client in C# using Web Services and I think the class notes on the P2P stuff are still available here and here.
Why is Peer-to-Peer programming a hard topic to obtain good research for? After reading a bit more about how Gnutella and other P2P networks function, I wanted to start my own peer-to-peer system. I went in thinking that I would find plenty of tutorials and language-agnostic guidelines which could be applied, however I was met with a vague simplistic overview. I could only find very small, precise P2P code which didn't do much more than use client/server architecture on all users, which wasn't really what I was looking for. I wanted something like Gnutella, but there doesn't seem to be any articles out in the open for joining the network.
TITLE: Why is Peer-to-Peer programming a hard topic to obtain good research for? QUESTION: After reading a bit more about how Gnutella and other P2P networks function, I wanted to start my own peer-to-peer system. I went in thinking that I would find plenty of tutorials and language-agnostic guidelines which could be applied, however I was met with a vague simplistic overview. I could only find very small, precise P2P code which didn't do much more than use client/server architecture on all users, which wasn't really what I was looking for. I wanted something like Gnutella, but there doesn't seem to be any articles out in the open for joining the network. ANSWER: I had to write a basic Gnutella client in C# using Web Services and I think the class notes on the P2P stuff are still available here and here.
[ "networking", "language-agnostic", "p2p" ]
2
1
3,432
7
0
2008-08-22T23:28:23.200000
2008-08-22T23:48:40.013000
23,755
23,769
How do you find a needle in a haystack?
When implementing a needle search of a haystack in an object-oriented way, you essentially have three alternatives: 1. needle.find(haystack) 2. haystack.find(needle) 3. searcher.find(needle, haystack) Which do you prefer, and why? I know some people prefer the second alternative because it avoids introducing a third object. However, I can't help feeling that the third approach is more conceptually "correct", at least if your goal is to model "the real world". In which cases do you think it is justified to introduce helper objects, such as the searcher in this example, and when should they be avoided?
Usually actions should be applied to what you are doing the action on... in this case the haystack, so I think option 2 is the most appropriate. You also have a fourth alternative that I think would be better than alternative 3: haystack.find(needle, searcher) In this case, it allows you to provide the manner in which you want to search as part of the action, and so you can keep the action with the object that is being operated on.
How do you find a needle in a haystack? When implementing a needle search of a haystack in an object-oriented way, you essentially have three alternatives: 1. needle.find(haystack) 2. haystack.find(needle) 3. searcher.find(needle, haystack) Which do you prefer, and why? I know some people prefer the second alternative because it avoids introducing a third object. However, I can't help feeling that the third approach is more conceptually "correct", at least if your goal is to model "the real world". In which cases do you think it is justified to introduce helper objects, such as the searcher in this example, and when should they be avoided?
TITLE: How do you find a needle in a haystack? QUESTION: When implementing a needle search of a haystack in an object-oriented way, you essentially have three alternatives: 1. needle.find(haystack) 2. haystack.find(needle) 3. searcher.find(needle, haystack) Which do you prefer, and why? I know some people prefer the second alternative because it avoids introducing a third object. However, I can't help feeling that the third approach is more conceptually "correct", at least if your goal is to model "the real world". In which cases do you think it is justified to introduce helper objects, such as the searcher in this example, and when should they be avoided? ANSWER: Usually actions should be applied to what you are doing the action on... in this case the haystack, so I think option 2 is the most appropriate. You also have a fourth alternative that I think would be better than alternative 3: haystack.find(needle, searcher) In this case, it allows you to provide the manner in which you want to search as part of the action, and so you can keep the action with the object that is being operated on.
[ "oop", "class-design", "program-structure" ]
76
53
13,100
29
0
2008-08-22T23:49:32.697000
2008-08-23T00:05:20.397000
23,763
27,185
Colorizing images in Java
I'm working on some code to colorize an image in Java. Basically what I'd like to do is something along the lines of GIMP's colorize command, so that if I have a BufferedImage and a Color, I can colorize the Image with the given color. Anyone got any ideas? My current best guess at doing something like this is to get the rgb value of each pixel in the BufferedImage and add the RGB value of the Color to it with some scaling factor.
I have never used GIMP's colorize command. However, if your getting the RGB value of each pixel and adding RGB value to it you should really use a LookupOp. Here is some code that I wrote to apply a BufferedImageOp to a BufferedImage. Using Nicks example from above heres how I would do it. Let Y = 0.3*R + 0.59*G + 0.11*B for each pixel (R1,G1,B1) is what you are colorizing with protected LookupOp createColorizeOp(short R1, short G1, short B1) { short[] alpha = new short[256]; short[] red = new short[256]; short[] green = new short[256]; short[] blue = new short[256]; int Y = 0.3*R + 0.59*G + 0.11*B for (short i = 0; i < 256; i++) { alpha[i] = i; red[i] = (R1 + i*.3)/2; green[i] = (G1 + i*.59)/2; blue[i] = (B1 + i*.11)/2; } short[][] data = new short[][] { red, green, blue, alpha }; LookupTable lookupTable = new ShortLookupTable(0, data); return new LookupOp(lookupTable, null); } It creates a BufferedImageOp that will mask out each color if the mask boolean is true. Its simple to call too. BufferedImageOp colorizeFilter = createColorizeOp(R1, G1, B1); BufferedImage targetImage = colorizeFilter.filter(sourceImage, null); If this is not what your looking for I suggest you look more into BufferedImageOp's. This is would also be more efficient since you would not need to do the calculations multiple times on different images. Or do the calculations over again on different BufferedImages as long as the R1,G1,B1 values don't change.
Colorizing images in Java I'm working on some code to colorize an image in Java. Basically what I'd like to do is something along the lines of GIMP's colorize command, so that if I have a BufferedImage and a Color, I can colorize the Image with the given color. Anyone got any ideas? My current best guess at doing something like this is to get the rgb value of each pixel in the BufferedImage and add the RGB value of the Color to it with some scaling factor.
TITLE: Colorizing images in Java QUESTION: I'm working on some code to colorize an image in Java. Basically what I'd like to do is something along the lines of GIMP's colorize command, so that if I have a BufferedImage and a Color, I can colorize the Image with the given color. Anyone got any ideas? My current best guess at doing something like this is to get the rgb value of each pixel in the BufferedImage and add the RGB value of the Color to it with some scaling factor. ANSWER: I have never used GIMP's colorize command. However, if your getting the RGB value of each pixel and adding RGB value to it you should really use a LookupOp. Here is some code that I wrote to apply a BufferedImageOp to a BufferedImage. Using Nicks example from above heres how I would do it. Let Y = 0.3*R + 0.59*G + 0.11*B for each pixel (R1,G1,B1) is what you are colorizing with protected LookupOp createColorizeOp(short R1, short G1, short B1) { short[] alpha = new short[256]; short[] red = new short[256]; short[] green = new short[256]; short[] blue = new short[256]; int Y = 0.3*R + 0.59*G + 0.11*B for (short i = 0; i < 256; i++) { alpha[i] = i; red[i] = (R1 + i*.3)/2; green[i] = (G1 + i*.59)/2; blue[i] = (B1 + i*.11)/2; } short[][] data = new short[][] { red, green, blue, alpha }; LookupTable lookupTable = new ShortLookupTable(0, data); return new LookupOp(lookupTable, null); } It creates a BufferedImageOp that will mask out each color if the mask boolean is true. Its simple to call too. BufferedImageOp colorizeFilter = createColorizeOp(R1, G1, B1); BufferedImage targetImage = colorizeFilter.filter(sourceImage, null); If this is not what your looking for I suggest you look more into BufferedImageOp's. This is would also be more efficient since you would not need to do the calculations multiple times on different images. Or do the calculations over again on different BufferedImages as long as the R1,G1,B1 values don't change.
[ "java", "colors", "bufferedimage", "colorize" ]
5
4
10,747
4
0
2008-08-22T23:57:13.863000
2008-08-26T01:02:32.793000
23,770
23,777
Effective strategy for leaving an audit trail/change history for DB applications?
What are some strategies that people have had success with for maintaining a change history for data in a fairly complex database. One of the applications that I frequently use and develop for could really benefit from a more comprehensive way of tracking how records have changed over time. For instance, right now records can have a number of timestamp and modified user fields, but we currently don't have a scheme for logging multiple change, for instance if an operation is rolled back. In a perfect world, it would be possible to reconstruct the record as it was after each save, etc. Some info on the DB: Needs to have the capacity to grow by thousands of records per week 50-60 Tables Main revisioned tables may have several million records each Reasonable amount of foreign keys and indexes set Using PostgreSQL 8.x
In the past I have used triggers to construct db update/insert/delete logging. You could insert a record each time one of the above actions is done on a specific table into a logging table that keeps track of the action, what db user did it, timestamp, table it was performed on, and previous value. There is probably a better answer though as this would require you to cache the value before the actual delete or update was performed I think. But you could use this to do rollbacks.
Effective strategy for leaving an audit trail/change history for DB applications? What are some strategies that people have had success with for maintaining a change history for data in a fairly complex database. One of the applications that I frequently use and develop for could really benefit from a more comprehensive way of tracking how records have changed over time. For instance, right now records can have a number of timestamp and modified user fields, but we currently don't have a scheme for logging multiple change, for instance if an operation is rolled back. In a perfect world, it would be possible to reconstruct the record as it was after each save, etc. Some info on the DB: Needs to have the capacity to grow by thousands of records per week 50-60 Tables Main revisioned tables may have several million records each Reasonable amount of foreign keys and indexes set Using PostgreSQL 8.x
TITLE: Effective strategy for leaving an audit trail/change history for DB applications? QUESTION: What are some strategies that people have had success with for maintaining a change history for data in a fairly complex database. One of the applications that I frequently use and develop for could really benefit from a more comprehensive way of tracking how records have changed over time. For instance, right now records can have a number of timestamp and modified user fields, but we currently don't have a scheme for logging multiple change, for instance if an operation is rolled back. In a perfect world, it would be possible to reconstruct the record as it was after each save, etc. Some info on the DB: Needs to have the capacity to grow by thousands of records per week 50-60 Tables Main revisioned tables may have several million records each Reasonable amount of foreign keys and indexes set Using PostgreSQL 8.x ANSWER: In the past I have used triggers to construct db update/insert/delete logging. You could insert a record each time one of the above actions is done on a specific table into a logging table that keeps track of the action, what db user did it, timestamp, table it was performed on, and previous value. There is probably a better answer though as this would require you to cache the value before the actual delete or update was performed I think. But you could use this to do rollbacks.
[ "database", "postgresql", "database-design", "crud", "audit-trail" ]
26
11
19,244
6
0
2008-08-23T00:05:58.210000
2008-08-23T00:12:10.443000
23,787
23,799
Cleanest Way to Find a Match In a List
What is the best way to find something in a list? I know LINQ has some nice tricks, but let's also get suggestions for C# 2.0. Lets get the best refactorings for this common code pattern. Currently I use code like this: // mObjList is a List MyObject match = null; foreach (MyObject mo in mObjList) { if (Criteria(mo)) { match = mo; break; } } or // mObjList is a List bool foundIt = false; foreach (MyObject mo in mObjList) { if (Criteria(mo)) { foundIt = true; break; } }
@ Konrad: So how do you use it? Let's say I want to match mo.ID to magicNumber. In C# 2.0 you'd write: result = mObjList.Find(delegate(int x) { return x.ID == magicNumber; }); 3.0 knows lambdas: result = mObjList.Find(x => x.ID == magicNumber);
Cleanest Way to Find a Match In a List What is the best way to find something in a list? I know LINQ has some nice tricks, but let's also get suggestions for C# 2.0. Lets get the best refactorings for this common code pattern. Currently I use code like this: // mObjList is a List MyObject match = null; foreach (MyObject mo in mObjList) { if (Criteria(mo)) { match = mo; break; } } or // mObjList is a List bool foundIt = false; foreach (MyObject mo in mObjList) { if (Criteria(mo)) { foundIt = true; break; } }
TITLE: Cleanest Way to Find a Match In a List QUESTION: What is the best way to find something in a list? I know LINQ has some nice tricks, but let's also get suggestions for C# 2.0. Lets get the best refactorings for this common code pattern. Currently I use code like this: // mObjList is a List MyObject match = null; foreach (MyObject mo in mObjList) { if (Criteria(mo)) { match = mo; break; } } or // mObjList is a List bool foundIt = false; foreach (MyObject mo in mObjList) { if (Criteria(mo)) { foundIt = true; break; } } ANSWER: @ Konrad: So how do you use it? Let's say I want to match mo.ID to magicNumber. In C# 2.0 you'd write: result = mObjList.Find(delegate(int x) { return x.ID == magicNumber; }); 3.0 knows lambdas: result = mObjList.Find(x => x.ID == magicNumber);
[ "c#", "refactoring" ]
12
18
27,561
4
0
2008-08-23T00:22:24.910000
2008-08-23T00:41:01.387000
23,802
24,106
How to handle including needed classes in PHP
I'm wondering what the best practice is for handling the problem with having to "include" so many files in my PHP scripts in order to ensure that all the classes I need to use are accessible to my script. Currently, I'm just using include_once to include the classes I access directly. Each of those would include_once the classes that they access. I've looked into using the __autoload function, but hat doesn't seem to work well if you plan to have your class files organized in a directory tree. If you did this, it seems like you'd end up walking the directory tree until you found the class you were looking for. Also, I'm not sure how this effects classes with the same name in different namespaces. Is there an easier way to handle this? Or is PHP just not suited to " enterprisey " type applications with lots of different objects all located in separate files that can be in many different directories.
I my applications I usually have setup.php file that includes all core classes (i.e. framework and accompanying libraries). My custom classes are loaded using autoloader aided by directory layout map. Each time new class is added I run command line builder script that scans whole directory tree in search for model classes then builds associative array with class names as keys and paths as values. Then, __autoload function looks up class name in that array and gets include path. Here's the code: autobuild.php define('MAP', 'var/cache/autoload.map'); error_reporting(E_ALL); require 'setup.php'; print(buildAutoloaderMap(). " classes mapped\n"); function buildAutoloaderMap() { $dirs = array('lib', 'view', 'model'); $cache = array(); $n = 0; foreach ($dirs as $dir) { foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $entry) { $fn = $entry->getFilename(); if (!preg_match('/\.class\.php$/', $fn)) continue; $c = str_replace('.class.php', '', $fn); if (!class_exists($c)) { $cache[$c] = ($pn = $entry->getPathname()); ++$n; } } } ksort($cache); file_put_contents(MAP, serialize($cache)); return $n; } autoload.php define('MAP', 'var/cache/autoload.map'); function __autoload($className) { static $map; $map or ($map = unserialize(file_get_contents(MAP))); $fn = array_key_exists($className, $map)? $map[$className]: null; if ($fn and file_exists($fn)) { include $fn; unset($map[$className]); } } Note that file naming convention must be [class_name].class.php. Alter the directories classes will be looked in autobuild.php. You can also run autobuilder from autoload function when class not found, but that may get your program into infinite loop. Serialized arrays are darn fast. @JasonMichael: PHP 4 is dead. Get over it.
How to handle including needed classes in PHP I'm wondering what the best practice is for handling the problem with having to "include" so many files in my PHP scripts in order to ensure that all the classes I need to use are accessible to my script. Currently, I'm just using include_once to include the classes I access directly. Each of those would include_once the classes that they access. I've looked into using the __autoload function, but hat doesn't seem to work well if you plan to have your class files organized in a directory tree. If you did this, it seems like you'd end up walking the directory tree until you found the class you were looking for. Also, I'm not sure how this effects classes with the same name in different namespaces. Is there an easier way to handle this? Or is PHP just not suited to " enterprisey " type applications with lots of different objects all located in separate files that can be in many different directories.
TITLE: How to handle including needed classes in PHP QUESTION: I'm wondering what the best practice is for handling the problem with having to "include" so many files in my PHP scripts in order to ensure that all the classes I need to use are accessible to my script. Currently, I'm just using include_once to include the classes I access directly. Each of those would include_once the classes that they access. I've looked into using the __autoload function, but hat doesn't seem to work well if you plan to have your class files organized in a directory tree. If you did this, it seems like you'd end up walking the directory tree until you found the class you were looking for. Also, I'm not sure how this effects classes with the same name in different namespaces. Is there an easier way to handle this? Or is PHP just not suited to " enterprisey " type applications with lots of different objects all located in separate files that can be in many different directories. ANSWER: I my applications I usually have setup.php file that includes all core classes (i.e. framework and accompanying libraries). My custom classes are loaded using autoloader aided by directory layout map. Each time new class is added I run command line builder script that scans whole directory tree in search for model classes then builds associative array with class names as keys and paths as values. Then, __autoload function looks up class name in that array and gets include path. Here's the code: autobuild.php define('MAP', 'var/cache/autoload.map'); error_reporting(E_ALL); require 'setup.php'; print(buildAutoloaderMap(). " classes mapped\n"); function buildAutoloaderMap() { $dirs = array('lib', 'view', 'model'); $cache = array(); $n = 0; foreach ($dirs as $dir) { foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dir)) as $entry) { $fn = $entry->getFilename(); if (!preg_match('/\.class\.php$/', $fn)) continue; $c = str_replace('.class.php', '', $fn); if (!class_exists($c)) { $cache[$c] = ($pn = $entry->getPathname()); ++$n; } } } ksort($cache); file_put_contents(MAP, serialize($cache)); return $n; } autoload.php define('MAP', 'var/cache/autoload.map'); function __autoload($className) { static $map; $map or ($map = unserialize(file_get_contents(MAP))); $fn = array_key_exists($className, $map)? $map[$className]: null; if ($fn and file_exists($fn)) { include $fn; unset($map[$className]); } } Note that file naming convention must be [class_name].class.php. Alter the directories classes will be looked in autobuild.php. You can also run autobuilder from autoload function when class not found, but that may get your program into infinite loop. Serialized arrays are darn fast. @JasonMichael: PHP 4 is dead. Get over it.
[ "php", "class", "include", "autoload" ]
3
6
3,089
7
0
2008-08-23T00:43:18.090000
2008-08-23T09:37:32.237000
23,836
23,857
How to create a simple install system for VB6 on XP/Vista and newer?
Heavy emphasis on simple. I've never made an installer and I'd rather not have to learn much. A system that I could hand a pile of files to and it would make some smart guesses about where to put them would be ideal. Go ahead and answer the general question. However In my cases I'm stuck with some extra constraints. The program to be installed is written in VB6 (or is it 5?) and a few previous versions of VB, so it's not going to be updated any time soon. I have a running install and will have a Clean VM to play with So I'll be doing a loop of: run the install, find where it's broken, fix it, add that to the installer, revert the VM, try again. If anyone has a better approach I'm open to suggestions. I MUST get it working on XP and I'd really like to also have something that will work on newer versions of Windows as well.
InnoSetup or NSIS, whichever seems easier to you. ISTool is a nice GUI tool for InnoSetup which makes creating setup scripts even easier.
How to create a simple install system for VB6 on XP/Vista and newer? Heavy emphasis on simple. I've never made an installer and I'd rather not have to learn much. A system that I could hand a pile of files to and it would make some smart guesses about where to put them would be ideal. Go ahead and answer the general question. However In my cases I'm stuck with some extra constraints. The program to be installed is written in VB6 (or is it 5?) and a few previous versions of VB, so it's not going to be updated any time soon. I have a running install and will have a Clean VM to play with So I'll be doing a loop of: run the install, find where it's broken, fix it, add that to the installer, revert the VM, try again. If anyone has a better approach I'm open to suggestions. I MUST get it working on XP and I'd really like to also have something that will work on newer versions of Windows as well.
TITLE: How to create a simple install system for VB6 on XP/Vista and newer? QUESTION: Heavy emphasis on simple. I've never made an installer and I'd rather not have to learn much. A system that I could hand a pile of files to and it would make some smart guesses about where to put them would be ideal. Go ahead and answer the general question. However In my cases I'm stuck with some extra constraints. The program to be installed is written in VB6 (or is it 5?) and a few previous versions of VB, so it's not going to be updated any time soon. I have a running install and will have a Clean VM to play with So I'll be doing a loop of: run the install, find where it's broken, fix it, add that to the installer, revert the VM, try again. If anyone has a better approach I'm open to suggestions. I MUST get it working on XP and I'd really like to also have something that will work on newer versions of Windows as well. ANSWER: InnoSetup or NSIS, whichever seems easier to you. ISTool is a nice GUI tool for InnoSetup which makes creating setup scripts even easier.
[ "windows", "vb6", "installation" ]
7
11
5,438
7
0
2008-08-23T01:50:44.340000
2008-08-23T02:16:37.897000
23,853
23,879
How I hide empty Velocity variable names?
I am using Struts + Velocity in a Java application, but after I submit a form, the confirmation page (Velocity template) shows the variable names instead an empty label, like the Age in following example: Name: Fernando Age: {person.age} Sex: Male I would like to know how to hide it!
You can mark variables as " silent " like this: $!variable If $variable is null, nothing will be rendered. If it is not null, its value will render as it normally would.
How I hide empty Velocity variable names? I am using Struts + Velocity in a Java application, but after I submit a form, the confirmation page (Velocity template) shows the variable names instead an empty label, like the Age in following example: Name: Fernando Age: {person.age} Sex: Male I would like to know how to hide it!
TITLE: How I hide empty Velocity variable names? QUESTION: I am using Struts + Velocity in a Java application, but after I submit a form, the confirmation page (Velocity template) shows the variable names instead an empty label, like the Age in following example: Name: Fernando Age: {person.age} Sex: Male I would like to know how to hide it! ANSWER: You can mark variables as " silent " like this: $!variable If $variable is null, nothing will be rendered. If it is not null, its value will render as it normally would.
[ "java", "templates", "struts", "velocity" ]
46
78
17,085
2
0
2008-08-23T02:09:25.167000
2008-08-23T02:37:43.103000
23,867
24,337
Closing and Disposing a WCF Service
The Close method on an ICommunicationObject can throw two types of exceptions as MSDN outlines here. I understand why the Close method can throw those exceptions, but what I don't understand is why the Dispose method on a service proxy calls the Close method without a try around it. Isn't your Dispose method the one place where you want make sure you don't throw any exceptions?
It seems to be a common design pattern in.NET code. Here is a citation from Framework design guidelines Consider providing method Close(), in addition to the Dispose(), if close is standard terminology in the area. When doing so, it is important that you make the Close implementation identical to Dispose... Here is a blog post in which you can find workaround for this System.ServiceModel.ClientBase design problem
Closing and Disposing a WCF Service The Close method on an ICommunicationObject can throw two types of exceptions as MSDN outlines here. I understand why the Close method can throw those exceptions, but what I don't understand is why the Dispose method on a service proxy calls the Close method without a try around it. Isn't your Dispose method the one place where you want make sure you don't throw any exceptions?
TITLE: Closing and Disposing a WCF Service QUESTION: The Close method on an ICommunicationObject can throw two types of exceptions as MSDN outlines here. I understand why the Close method can throw those exceptions, but what I don't understand is why the Dispose method on a service proxy calls the Close method without a try around it. Isn't your Dispose method the one place where you want make sure you don't throw any exceptions? ANSWER: It seems to be a common design pattern in.NET code. Here is a citation from Framework design guidelines Consider providing method Close(), in addition to the Dispose(), if close is standard terminology in the area. When doing so, it is important that you make the Close implementation identical to Dispose... Here is a blog post in which you can find workaround for this System.ServiceModel.ClientBase design problem
[ "wcf", "web-services" ]
15
10
10,018
2
0
2008-08-23T02:29:18.070000
2008-08-23T16:19:56.747000
23,899
60,404
Best practices for refactoring classic ASP?
I've got to do some significant development in a large, old, spaghetti-ridden ASP system. I've been away from ASP for a long time, focusing my energies on Rails development. One basic step I've taken is to refactor pages into subs and functions with meaningful names, so that at least it's easy to understand @ the top of the file what's generally going on. Is there a worthwhile MVC framework for ASP? Or a best practice at how to at least get business logic out of the views? (I remember doing a lot of includes back in the day -- is that still the way to do it?) I'd love to get some unit testing going for business logic too, but maybe I'm asking too much? Update: There are over 200 ASP scripts in the project, some thousands of lines long;) UGH! We may opt for the "big rewrite" but until then, when I'm in changing a page, I want to spend a little extra time cleaning up the spaghetti.
Assumptions The documentation for the Classic ASP system is rather light. Management is not looking for a rewrite. Since you have been doing ruby on rails, your (VB/C#) ASP.NET is passable at best. My experience I too inherited a classic ASP system that was slapped together willy-nilly by ex excel-vba types. There was a lot of this stuff crap (and sometimes missing closing tags; Argggh!). Over the course of 2.5 years I added a security system, a common library, CSS+XHTML and was able to coerce the thing to validate xhtml1.1 (sans proper mime type, unfortunately) and built a fairly robust and ajaxy reporting system that's being used daily by 80 users. I used jEdit, with cTags (as mentioned by jamting above), and a bunch of other plugins. My Advice Try to create a master include file from which to import all the stuff that's commonly used. Stuff like login/logout, database access, web services, javascript libs, etc. Do use classes. They are ultra-primitive (no inheritance) but as jamting said, they can be convenient. Indent the scripts properly. Comment Write an external architecture document. I personally use LyX, because it's brain-dead to produce a nicely formatted pdf, but you can use whatever you like. If you use a wiki, get the graphviz add-in installed and use it. It's super easy to make quick diagrams that can be easily modified. Since I have no idea how substantial the enhancements need to be, I suggest having a good high-level to mid-level architecture document will be quite useful in planning the enhancements. On the business logic unit tests, the only thing I found that works is setting up an xml-rpc listener in asp that imports the main library and exposes the functions (not subroutines though) in any of the main library's sub-includes, and then build, separately, a unit test system in a language with better support for the stuff that calls the ASP functions through xml-rpc. I use python, but I think Ruby should do the trick. (Does that make sense?). The cool thing is that the person writing the unit-test part of the software does not need to even look at the ASP code, as long as they have decent descriptions of the functions to call, so they can be someone beside you. There is a project called aspunit at sourceforge but the last release was in 2004 and it's marked as inactive. Never used it but it's pure vbscript. A cursory look at the code tells me it looks like the authors knew what they were doing. Finally, if you need help, I have some availability to do contract telecommuting work (maybe 8 hours/week max). Follow the link trail for contact info. Good luck! HTH.
Best practices for refactoring classic ASP? I've got to do some significant development in a large, old, spaghetti-ridden ASP system. I've been away from ASP for a long time, focusing my energies on Rails development. One basic step I've taken is to refactor pages into subs and functions with meaningful names, so that at least it's easy to understand @ the top of the file what's generally going on. Is there a worthwhile MVC framework for ASP? Or a best practice at how to at least get business logic out of the views? (I remember doing a lot of includes back in the day -- is that still the way to do it?) I'd love to get some unit testing going for business logic too, but maybe I'm asking too much? Update: There are over 200 ASP scripts in the project, some thousands of lines long;) UGH! We may opt for the "big rewrite" but until then, when I'm in changing a page, I want to spend a little extra time cleaning up the spaghetti.
TITLE: Best practices for refactoring classic ASP? QUESTION: I've got to do some significant development in a large, old, spaghetti-ridden ASP system. I've been away from ASP for a long time, focusing my energies on Rails development. One basic step I've taken is to refactor pages into subs and functions with meaningful names, so that at least it's easy to understand @ the top of the file what's generally going on. Is there a worthwhile MVC framework for ASP? Or a best practice at how to at least get business logic out of the views? (I remember doing a lot of includes back in the day -- is that still the way to do it?) I'd love to get some unit testing going for business logic too, but maybe I'm asking too much? Update: There are over 200 ASP scripts in the project, some thousands of lines long;) UGH! We may opt for the "big rewrite" but until then, when I'm in changing a page, I want to spend a little extra time cleaning up the spaghetti. ANSWER: Assumptions The documentation for the Classic ASP system is rather light. Management is not looking for a rewrite. Since you have been doing ruby on rails, your (VB/C#) ASP.NET is passable at best. My experience I too inherited a classic ASP system that was slapped together willy-nilly by ex excel-vba types. There was a lot of this stuff crap (and sometimes missing closing tags; Argggh!). Over the course of 2.5 years I added a security system, a common library, CSS+XHTML and was able to coerce the thing to validate xhtml1.1 (sans proper mime type, unfortunately) and built a fairly robust and ajaxy reporting system that's being used daily by 80 users. I used jEdit, with cTags (as mentioned by jamting above), and a bunch of other plugins. My Advice Try to create a master include file from which to import all the stuff that's commonly used. Stuff like login/logout, database access, web services, javascript libs, etc. Do use classes. They are ultra-primitive (no inheritance) but as jamting said, they can be convenient. Indent the scripts properly. Comment Write an external architecture document. I personally use LyX, because it's brain-dead to produce a nicely formatted pdf, but you can use whatever you like. If you use a wiki, get the graphviz add-in installed and use it. It's super easy to make quick diagrams that can be easily modified. Since I have no idea how substantial the enhancements need to be, I suggest having a good high-level to mid-level architecture document will be quite useful in planning the enhancements. On the business logic unit tests, the only thing I found that works is setting up an xml-rpc listener in asp that imports the main library and exposes the functions (not subroutines though) in any of the main library's sub-includes, and then build, separately, a unit test system in a language with better support for the stuff that calls the ASP functions through xml-rpc. I use python, but I think Ruby should do the trick. (Does that make sense?). The cool thing is that the person writing the unit-test part of the software does not need to even look at the ASP code, as long as they have decent descriptions of the functions to call, so they can be someone beside you. There is a project called aspunit at sourceforge but the last release was in 2004 and it's marked as inactive. Never used it but it's pure vbscript. A cursory look at the code tells me it looks like the authors knew what they were doing. Finally, if you need help, I have some availability to do contract telecommuting work (maybe 8 hours/week max). Follow the link trail for contact info. Good luck! HTH.
[ "asp.net-mvc", "coding-style", "refactoring" ]
16
13
4,896
8
0
2008-08-23T02:56:37.833000
2008-09-13T08:13:51.920000
23,907
2,854,506
How can I graph the Lines of Code history for git repo?
Basically I want to get the number of lines-of-code in the repository after each commit. The only (really crappy) ways I have found is to use git filter-branch to run wc -l *, and a script that runs git reset --hard on each commit, then runs wc -l To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on. This is what I want the tool to output (as an example): me@something:~/$ gitsloc --branch master 10 48 153 450 1734 1542 I've played around with the ruby 'git' library, but the closest I found was using the.lines() method on a diff, which seems like it should give the added lines (but does not: it returns 0 when you delete lines for example) require 'rubygems' require 'git' total = 0 g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api') last = nil g.log.each do |cur| diff = g.diff(last, cur) total = total + diff.lines puts total last = cur end
You might also consider gitstats, which generates this graph as an html file.
How can I graph the Lines of Code history for git repo? Basically I want to get the number of lines-of-code in the repository after each commit. The only (really crappy) ways I have found is to use git filter-branch to run wc -l *, and a script that runs git reset --hard on each commit, then runs wc -l To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on. This is what I want the tool to output (as an example): me@something:~/$ gitsloc --branch master 10 48 153 450 1734 1542 I've played around with the ruby 'git' library, but the closest I found was using the.lines() method on a diff, which seems like it should give the added lines (but does not: it returns 0 when you delete lines for example) require 'rubygems' require 'git' total = 0 g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api') last = nil g.log.each do |cur| diff = g.diff(last, cur) total = total + diff.lines puts total last = cur end
TITLE: How can I graph the Lines of Code history for git repo? QUESTION: Basically I want to get the number of lines-of-code in the repository after each commit. The only (really crappy) ways I have found is to use git filter-branch to run wc -l *, and a script that runs git reset --hard on each commit, then runs wc -l To make it a bit clearer, when the tool is run, it would output the lines of code of the very first commit, then the second and so on. This is what I want the tool to output (as an example): me@something:~/$ gitsloc --branch master 10 48 153 450 1734 1542 I've played around with the ruby 'git' library, but the closest I found was using the.lines() method on a diff, which seems like it should give the added lines (but does not: it returns 0 when you delete lines for example) require 'rubygems' require 'git' total = 0 g = Git.open(working_dir = '/Users/dbr/Desktop/code_projects/tvdb_api') last = nil g.log.each do |cur| diff = g.diff(last, cur) total = total + diff.lines puts total last = cur end ANSWER: You might also consider gitstats, which generates this graph as an html file.
[ "git" ]
52
29
22,621
4
0
2008-08-23T03:00:46.277000
2010-05-18T04:09:01.977000
23,918
23,926
OpenGL Rotation
I'm trying to do a simple rotation in OpenGL but must be missing the point. I'm not looking for a specific fix so much as a quick explanation or link that explains OpenGL rotation more generally. At the moment I have code like this: glPushMatrix(); glRotatef(90.0, 0.0, 1.0, 0.0); glBegin(GL_TRIANGLES); glVertex3f( 1.0, 1.0, 0.0 ); glVertex3f( 3.0, 2.0, 0.0 ); glVertex3f( 3.0, 1.0, 0.0 ); glEnd(); glPopMatrix(); But the result is not a triangle rotated 90 degrees. Edit Hmm thanks to Mike Haboustak - it appeared my code was calling a SetCamera function that use glOrtho. I'm too new to OpenGL to have any idea of what this meant but disabling this and rotating in the Z-axis produced the desired result.
Do you get a 1 unit straight line? It seems that 90deg rot. around Y is going to have you looking at the side of a triangle with no depth. You should try rotating around the Z axis instead and see if you get something that makes more sense. OpenGL has two matrices related to the display of geometry, the ModelView and the Projection. Both are applied to coordinates before the data becomes visible on the screen. First the ModelView matrix is applied, transforming the data from model space into view space. Then the Projection matrix is applied with transforms the data from view space for "projection" on your 2D monitor. ModelView is used to position multiple objects to their locations in the "world", Projection is used to position the objects onto the screen. Your code seems fine, so I assume from reading the documentation you know what the nature of functions like glPushMatrix() is. If rotating around Z still doesn't make sense, verify that you're editing the ModelView matrix by calling glMatrixMode.
OpenGL Rotation I'm trying to do a simple rotation in OpenGL but must be missing the point. I'm not looking for a specific fix so much as a quick explanation or link that explains OpenGL rotation more generally. At the moment I have code like this: glPushMatrix(); glRotatef(90.0, 0.0, 1.0, 0.0); glBegin(GL_TRIANGLES); glVertex3f( 1.0, 1.0, 0.0 ); glVertex3f( 3.0, 2.0, 0.0 ); glVertex3f( 3.0, 1.0, 0.0 ); glEnd(); glPopMatrix(); But the result is not a triangle rotated 90 degrees. Edit Hmm thanks to Mike Haboustak - it appeared my code was calling a SetCamera function that use glOrtho. I'm too new to OpenGL to have any idea of what this meant but disabling this and rotating in the Z-axis produced the desired result.
TITLE: OpenGL Rotation QUESTION: I'm trying to do a simple rotation in OpenGL but must be missing the point. I'm not looking for a specific fix so much as a quick explanation or link that explains OpenGL rotation more generally. At the moment I have code like this: glPushMatrix(); glRotatef(90.0, 0.0, 1.0, 0.0); glBegin(GL_TRIANGLES); glVertex3f( 1.0, 1.0, 0.0 ); glVertex3f( 3.0, 2.0, 0.0 ); glVertex3f( 3.0, 1.0, 0.0 ); glEnd(); glPopMatrix(); But the result is not a triangle rotated 90 degrees. Edit Hmm thanks to Mike Haboustak - it appeared my code was calling a SetCamera function that use glOrtho. I'm too new to OpenGL to have any idea of what this meant but disabling this and rotating in the Z-axis produced the desired result. ANSWER: Do you get a 1 unit straight line? It seems that 90deg rot. around Y is going to have you looking at the side of a triangle with no depth. You should try rotating around the Z axis instead and see if you get something that makes more sense. OpenGL has two matrices related to the display of geometry, the ModelView and the Projection. Both are applied to coordinates before the data becomes visible on the screen. First the ModelView matrix is applied, transforming the data from model space into view space. Then the Projection matrix is applied with transforms the data from view space for "projection" on your 2D monitor. ModelView is used to position multiple objects to their locations in the "world", Projection is used to position the objects onto the screen. Your code seems fine, so I assume from reading the documentation you know what the nature of functions like glPushMatrix() is. If rotating around Z still doesn't make sense, verify that you're editing the ModelView matrix by calling glMatrixMode.
[ "c++", "opengl", "glut" ]
11
7
33,936
4
0
2008-08-23T03:23:44.350000
2008-08-23T03:40:29.037000
23,930
441,229
Factorial Algorithms in different languages
I want to see all the different ways you can come up with, for a factorial subroutine, or program. The hope is that anyone can come here and see if they might want to learn a new language. Ideas: Procedural Functional Object Oriented One liners Obfuscated Oddball Bad Code Polyglot Basically I want to see an example, of different ways of writing an algorithm, and what they would look like in different languages. Please limit it to one example per entry. I will allow you to have more than one example per answer, if you are trying to highlight a specific style, language, or just a well thought out idea that lends itself to being in one post. The only real requirement is it must find the factorial of a given argument, in all languages represented. Be Creative! Recommended Guideline: # Language Name: Optional Style type - Optional bullet points Code Goes Here Other informational text goes here I will ocasionally go along and edit any answer that does not have decent formatting.
Polyglot: 5 languages, all using bignums So, I wrote a polyglot which works in the three languages I often write in, as well as one from my other answer to this question and one I just learned today. It's a standalone program, which reads a single line containing a nonnegative integer and prints a single line containing its factorial. Bignums are used in all languages, so the maximum computable factorial depends only on your computer's resources. Perl: uses built-in bignum package. Run with perl FILENAME. Haskell: uses built-in bignums. Run with runhugs FILENAME or your favorite compiler's equivalent. C++: requires GMP for bignum support. To compile with g++, use g++ -lgmpxx -lgmp -x c++ FILENAME to link against the right libraries. After compiling, run./a.out. Or use your favorite compiler's equivalent. brainf*ck: I wrote some bignum support in this post. Using Muller's classic distribution, compile with bf < FILENAME > EXECUTABLE. Make the output executable and run it. Or use your favorite distribution. Whitespace: uses built-in bignum support. Run with wspace FILENAME. Edit: added Whitespace as a fifth language. Incidentally, do not wrap the code with tags; it breaks the Whitespace. Also, the code looks much nicer in fixed-width. char //# b=0+0{- |0*/; #>>>>,----------[>>>>,-------- #define a/*#--]>>>>++<<<<<<<<[>++++++[<------>-]<-<<< #Perl ><><><> <> <> <<]>>>>[[>>+<<-]>>[<<+>+>-]<-> #C++ --><><> <><><>< > < > < +<[>>>>+<<<-<[-]]>[-] #Haskell >>]>[-<<<<<[<<<<]>>>>[[>>+<<-]>>[<<+>+>-]>>] #Whitespace >>>>[-[>+<-]+>>>>]<<<<[<<<<]<<<<[<<<< #brainf*ck > < ]>>>>>[>>>[>>>>]>>>>[>>>>]<<<<[[>>>>*/ exp;;//;#+<<<<-]<<<<]>>>>+<<<<<<<[<<<<][.POLYGLOT^5. #include //]>>>>-[>>>[>>>>]>>>>[>>>>]<<<<[>> #define eval int main()//>+<<<-]>>>[<<<+>>+>-> #include //<]<-[>>+<<[-]]<<[<<<<]>>>>[>[>>> #define print std::cout << // > <+<-]>[<<+>+>-]<<[>>> #define z std::cin>>//<< +<<<-]>>>[<<<+>>+>-]<->+++++ #define c/*++++[-<[-[>>>>+<<<<-]]>>>>[<<<<+>>>>-]<<*/ #define abs int $n //>< <]<[>>+<<<<[-]>>[<<+>>-]]>>]< #define uc mpz_class fact(int $n){/*<<<[<<<<]<<<[<< use bignum;sub#<<]>>>>-]>>>>]>>>[>[-]>>>]<<<<[>>+<<-] z{$_[0+0]=readline(*STDIN);}sub fact{my($n)=shift;#>> #[<<+>+>-]<->+<[>-<[-]]>[-<<-<<<<[>>+<<-]>>[<<+>+>+*/ uc;if($n==0){return 1;}return $n*fact($n-1); }//;# eval{abs;z($n);print fact($n);print("\n")/*2;};#-]<-> '+<[>-<[-]]>]<<[<<<<]<<<<-[>>+<<-]>>[<<+>+>-]+<[>-+++ -}-- <[-]]>[-<<++++++++++<<<<-[>>+<<-]>>[<<+>+>-++ fact 0 = 1 -- ><><><>< > <><>< ]+<[>-<[-]]>]<<[<<+ + fact n=n*fact(n-1){-<<]>>>>[[>>+<<-]>>[<<+>+++>+-} main=do{n<-readLn;print(fact n)}-- +>-]<->+<[>>>>+<<+ {-x<-<[-]]>[-]>>]>]>>>[>>>>]<<<<[>+++++++[<+++++++>-] <--.<<<<]+written+by+++A+Rex+++2009+.';#+++x-}--x*/;}
Factorial Algorithms in different languages I want to see all the different ways you can come up with, for a factorial subroutine, or program. The hope is that anyone can come here and see if they might want to learn a new language. Ideas: Procedural Functional Object Oriented One liners Obfuscated Oddball Bad Code Polyglot Basically I want to see an example, of different ways of writing an algorithm, and what they would look like in different languages. Please limit it to one example per entry. I will allow you to have more than one example per answer, if you are trying to highlight a specific style, language, or just a well thought out idea that lends itself to being in one post. The only real requirement is it must find the factorial of a given argument, in all languages represented. Be Creative! Recommended Guideline: # Language Name: Optional Style type - Optional bullet points Code Goes Here Other informational text goes here I will ocasionally go along and edit any answer that does not have decent formatting.
TITLE: Factorial Algorithms in different languages QUESTION: I want to see all the different ways you can come up with, for a factorial subroutine, or program. The hope is that anyone can come here and see if they might want to learn a new language. Ideas: Procedural Functional Object Oriented One liners Obfuscated Oddball Bad Code Polyglot Basically I want to see an example, of different ways of writing an algorithm, and what they would look like in different languages. Please limit it to one example per entry. I will allow you to have more than one example per answer, if you are trying to highlight a specific style, language, or just a well thought out idea that lends itself to being in one post. The only real requirement is it must find the factorial of a given argument, in all languages represented. Be Creative! Recommended Guideline: # Language Name: Optional Style type - Optional bullet points Code Goes Here Other informational text goes here I will ocasionally go along and edit any answer that does not have decent formatting. ANSWER: Polyglot: 5 languages, all using bignums So, I wrote a polyglot which works in the three languages I often write in, as well as one from my other answer to this question and one I just learned today. It's a standalone program, which reads a single line containing a nonnegative integer and prints a single line containing its factorial. Bignums are used in all languages, so the maximum computable factorial depends only on your computer's resources. Perl: uses built-in bignum package. Run with perl FILENAME. Haskell: uses built-in bignums. Run with runhugs FILENAME or your favorite compiler's equivalent. C++: requires GMP for bignum support. To compile with g++, use g++ -lgmpxx -lgmp -x c++ FILENAME to link against the right libraries. After compiling, run./a.out. Or use your favorite compiler's equivalent. brainf*ck: I wrote some bignum support in this post. Using Muller's classic distribution, compile with bf < FILENAME > EXECUTABLE. Make the output executable and run it. Or use your favorite distribution. Whitespace: uses built-in bignum support. Run with wspace FILENAME. Edit: added Whitespace as a fifth language. Incidentally, do not wrap the code with tags; it breaks the Whitespace. Also, the code looks much nicer in fixed-width. char //# b=0+0{- |0*/; #>>>>,----------[>>>>,-------- #define a/*#--]>>>>++<<<<<<<<[>++++++[<------>-]<-<<< #Perl ><><><> <> <> <<]>>>>[[>>+<<-]>>[<<+>+>-]<-> #C++ --><><> <><><>< > < > < +<[>>>>+<<<-<[-]]>[-] #Haskell >>]>[-<<<<<[<<<<]>>>>[[>>+<<-]>>[<<+>+>-]>>] #Whitespace >>>>[-[>+<-]+>>>>]<<<<[<<<<]<<<<[<<<< #brainf*ck > < ]>>>>>[>>>[>>>>]>>>>[>>>>]<<<<[[>>>>*/ exp;;//;#+<<<<-]<<<<]>>>>+<<<<<<<[<<<<][.POLYGLOT^5. #include //]>>>>-[>>>[>>>>]>>>>[>>>>]<<<<[>> #define eval int main()//>+<<<-]>>>[<<<+>>+>-> #include //<]<-[>>+<<[-]]<<[<<<<]>>>>[>[>>> #define print std::cout << // > <+<-]>[<<+>+>-]<<[>>> #define z std::cin>>//<< +<<<-]>>>[<<<+>>+>-]<->+++++ #define c/*++++[-<[-[>>>>+<<<<-]]>>>>[<<<<+>>>>-]<<*/ #define abs int $n //>< <]<[>>+<<<<[-]>>[<<+>>-]]>>]< #define uc mpz_class fact(int $n){/*<<<[<<<<]<<<[<< use bignum;sub#<<]>>>>-]>>>>]>>>[>[-]>>>]<<<<[>>+<<-] z{$_[0+0]=readline(*STDIN);}sub fact{my($n)=shift;#>> #[<<+>+>-]<->+<[>-<[-]]>[-<<-<<<<[>>+<<-]>>[<<+>+>+*/ uc;if($n==0){return 1;}return $n*fact($n-1); }//;# eval{abs;z($n);print fact($n);print("\n")/*2;};#-]<-> '+<[>-<[-]]>]<<[<<<<]<<<<-[>>+<<-]>>[<<+>+>-]+<[>-+++ -}-- <[-]]>[-<<++++++++++<<<<-[>>+<<-]>>[<<+>+>-++ fact 0 = 1 -- ><><><>< > <><>< ]+<[>-<[-]]>]<<[<<+ + fact n=n*fact(n-1){-<<]>>>>[[>>+<<-]>>[<<+>+++>+-} main=do{n<-readLn;print(fact n)}-- +>-]<->+<[>>>>+<<+ {-x<-<[-]]>[-]>>]>]>>>[>>>>]<<<<[>+++++++[<+++++++>-] <--.<<<<]+written+by+++A+Rex+++2009+.';#+++x-}--x*/;}
[ "algorithm", "language-agnostic" ]
64
184
29,592
129
0
2008-08-23T03:46:32.750000
2009-01-13T23:02:32.120000
23,950
24,023
Best method to get objects from a BlockingQueue in a concurrent program?
What is the best method to get objects out of a BlockingQueue, in a concurrent program, without hitting a race condition? I'm currently doing the following and I'm not convinced it is the best method: BlockingQueue vQueue; /* in the constructor I pass in a BlockingQueue object full of violations that need to be processed - cut out for brevity */ Violation v; while ( ( v = vQueue.poll(500, TimeUnit.MILLISECONDS) )!= null ) { // do stuff with the violation } I have yet to hit a race condition... but, I'm none too sure if this is truly safe.
class Producer implements Runnable { private final BlockingQueue queue; Producer(BlockingQueue q) { queue = q; } public void run() { try { while (true) { queue.put(produce()); } } catch (InterruptedException ex) {... handle...} } Object produce() {... } } class Consumer implements Runnable { private final BlockingQueue queue; Consumer(BlockingQueue q) { queue = q; } public void run() { try { while (true) { consume(queue.take()); } } catch (InterruptedException ex) {... handle...} } void consume(Object x) {... } } class Setup { void main() { BlockingQueue q = new SomeQueueImplementation(); Producer p = new Producer(q); Consumer c1 = new Consumer(q); Consumer c2 = new Consumer(q); new Thread(p).start(); new Thread(c1).start(); new Thread(c2).start(); } } This example was taken from the JDK 1.6 docs of BlockingQueue. So You can see that you are doing it the right way. Here's the quote which tells you that it have to work: Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a BlockingQueue happen-before actions subsequent to the access or removal of that element from the BlockingQueue in another thread.
Best method to get objects from a BlockingQueue in a concurrent program? What is the best method to get objects out of a BlockingQueue, in a concurrent program, without hitting a race condition? I'm currently doing the following and I'm not convinced it is the best method: BlockingQueue vQueue; /* in the constructor I pass in a BlockingQueue object full of violations that need to be processed - cut out for brevity */ Violation v; while ( ( v = vQueue.poll(500, TimeUnit.MILLISECONDS) )!= null ) { // do stuff with the violation } I have yet to hit a race condition... but, I'm none too sure if this is truly safe.
TITLE: Best method to get objects from a BlockingQueue in a concurrent program? QUESTION: What is the best method to get objects out of a BlockingQueue, in a concurrent program, without hitting a race condition? I'm currently doing the following and I'm not convinced it is the best method: BlockingQueue vQueue; /* in the constructor I pass in a BlockingQueue object full of violations that need to be processed - cut out for brevity */ Violation v; while ( ( v = vQueue.poll(500, TimeUnit.MILLISECONDS) )!= null ) { // do stuff with the violation } I have yet to hit a race condition... but, I'm none too sure if this is truly safe. ANSWER: class Producer implements Runnable { private final BlockingQueue queue; Producer(BlockingQueue q) { queue = q; } public void run() { try { while (true) { queue.put(produce()); } } catch (InterruptedException ex) {... handle...} } Object produce() {... } } class Consumer implements Runnable { private final BlockingQueue queue; Consumer(BlockingQueue q) { queue = q; } public void run() { try { while (true) { consume(queue.take()); } } catch (InterruptedException ex) {... handle...} } void consume(Object x) {... } } class Setup { void main() { BlockingQueue q = new SomeQueueImplementation(); Producer p = new Producer(q); Consumer c1 = new Consumer(q); Consumer c2 = new Consumer(q); new Thread(p).start(); new Thread(c1).start(); new Thread(c2).start(); } } This example was taken from the JDK 1.6 docs of BlockingQueue. So You can see that you are doing it the right way. Here's the quote which tells you that it have to work: Memory consistency effects: As with other concurrent collections, actions in a thread prior to placing an object into a BlockingQueue happen-before actions subsequent to the access or removal of that element from the BlockingQueue in another thread.
[ "java", "concurrency" ]
4
6
7,955
1
0
2008-08-23T04:03:18.997000
2008-08-23T05:39:15.197000
23,961
24,097
What to do about ScanAlert?
One of my clients uses McAfee ScanAlert (i.e., HackerSafe). It basically hits the site with about 1500 bad requests a day looking for security holes. Since it demonstrates malicious behavior it is tempting to just block it after a couple bad requests, but maybe I should let it exercise the UI. Is it a true test if I don't let it finish?
Isn't it a security flaw of the site to let hackers throw everything in their arsenal against the site? Well, you should focus on closing holes, rather than trying to thwart scanners (which is a futile battle). Consider running such tests yourself.
What to do about ScanAlert? One of my clients uses McAfee ScanAlert (i.e., HackerSafe). It basically hits the site with about 1500 bad requests a day looking for security holes. Since it demonstrates malicious behavior it is tempting to just block it after a couple bad requests, but maybe I should let it exercise the UI. Is it a true test if I don't let it finish?
TITLE: What to do about ScanAlert? QUESTION: One of my clients uses McAfee ScanAlert (i.e., HackerSafe). It basically hits the site with about 1500 bad requests a day looking for security holes. Since it demonstrates malicious behavior it is tempting to just block it after a couple bad requests, but maybe I should let it exercise the UI. Is it a true test if I don't let it finish? ANSWER: Isn't it a security flaw of the site to let hackers throw everything in their arsenal against the site? Well, you should focus on closing holes, rather than trying to thwart scanners (which is a futile battle). Consider running such tests yourself.
[ "performance", "security" ]
3
2
468
4
0
2008-08-23T04:11:36.047000
2008-08-23T09:17:00.227000
23,962
23,975
Is there some way to speed up recursion by remembering child nodes?
For example, Look at the code that calculates the n-th Fibonacci number: fib(int n) { if(n==0 || n==1) return 1; return fib(n-1) + fib(n-2); } The problem with this code is that it will generate stack overflow error for any number greater than 15 (in most computers). Assume that we are calculating fib(10). In this process, say fib(5) is calculated a lot of times. Is there some way to store this in memory for fast retrieval and thereby increase the speed of recursion? I am looking for a generic technique that can be used in almost all problems.
Yes your insight is correct. This is called dynamic programming. It is usually a common memory runtime trade-off. In the case of fibo, you don't even need to cache everything: [edit] The author of the question seems to be looking for a general method to cache rather than a method to compute Fibonacci. Search wikipedia or look at the code of the other poster to get this answer. Those answers are linear in time and memory. **Here is a linear-time algorithm O(n), constant in memory ** in OCaml: let rec fibo n = let rec aux = fun | 0 -> (1,1) | n -> let (cur, prec) = aux (n-1) in (cur+prec, cur) let (cur,prec) = aux n in prec;; in C++: int fibo(int n) { if (n == 0 ) return 1; if (n == 1 ) return 1; int p = fibo(0); int c = fibo(1); int buff = 0; for (int i=1; i < n; ++i) { buff = c; c = p+c; p = buff; }; return c; }; This perform in linear time. But log is actually possible!!! Roo's program is linear too, but way slower, and use memory. Here is the log algorithm O(log(n)) Now for the log-time algorithm (way way way faster), here is a method: If you know u(n), u(n-1), computing u(n+1), u(n) can be done by applying a matrix: | u(n+1) | = | 1 1 | | u(n) | | u(n) | | 1 0 | | u(n-1) | So that you have: | u(n) | = | 1 1 |^(n-1) | u(1) | = | 1 1 |^(n-1) | 1 | | u(n-1) | | 1 0 | | u(0) | | 1 0 | | 1 | Computing the exponential of the matrix has a logarithmic complexity. Just implement recursively the idea: M^(0) = Id M^(2p+1) = (M^2p) * M M^(2p) = (M^p) * (M^p) // of course don't compute M^p twice here. You can also just diagonalize it (not to difficult), you will find the gold number and its conjugate in its eigenvalue, and the result will give you an EXACT mathematical formula for u(n). It contains powers of those eigenvalues, so that the complexity will still be logarithmic. Fibo is often taken as an example to illustrate Dynamic Programming, but as you see, it is not really pertinent. @John: I don't think it has anything to do with do with hash. @John2: A map is a bit general don't you think? For Fibonacci case, all the keys are contiguous so that a vector is appropriate, once again there are much faster ways to compute fibo sequence, see my code sample over there.
Is there some way to speed up recursion by remembering child nodes? For example, Look at the code that calculates the n-th Fibonacci number: fib(int n) { if(n==0 || n==1) return 1; return fib(n-1) + fib(n-2); } The problem with this code is that it will generate stack overflow error for any number greater than 15 (in most computers). Assume that we are calculating fib(10). In this process, say fib(5) is calculated a lot of times. Is there some way to store this in memory for fast retrieval and thereby increase the speed of recursion? I am looking for a generic technique that can be used in almost all problems.
TITLE: Is there some way to speed up recursion by remembering child nodes? QUESTION: For example, Look at the code that calculates the n-th Fibonacci number: fib(int n) { if(n==0 || n==1) return 1; return fib(n-1) + fib(n-2); } The problem with this code is that it will generate stack overflow error for any number greater than 15 (in most computers). Assume that we are calculating fib(10). In this process, say fib(5) is calculated a lot of times. Is there some way to store this in memory for fast retrieval and thereby increase the speed of recursion? I am looking for a generic technique that can be used in almost all problems. ANSWER: Yes your insight is correct. This is called dynamic programming. It is usually a common memory runtime trade-off. In the case of fibo, you don't even need to cache everything: [edit] The author of the question seems to be looking for a general method to cache rather than a method to compute Fibonacci. Search wikipedia or look at the code of the other poster to get this answer. Those answers are linear in time and memory. **Here is a linear-time algorithm O(n), constant in memory ** in OCaml: let rec fibo n = let rec aux = fun | 0 -> (1,1) | n -> let (cur, prec) = aux (n-1) in (cur+prec, cur) let (cur,prec) = aux n in prec;; in C++: int fibo(int n) { if (n == 0 ) return 1; if (n == 1 ) return 1; int p = fibo(0); int c = fibo(1); int buff = 0; for (int i=1; i < n; ++i) { buff = c; c = p+c; p = buff; }; return c; }; This perform in linear time. But log is actually possible!!! Roo's program is linear too, but way slower, and use memory. Here is the log algorithm O(log(n)) Now for the log-time algorithm (way way way faster), here is a method: If you know u(n), u(n-1), computing u(n+1), u(n) can be done by applying a matrix: | u(n+1) | = | 1 1 | | u(n) | | u(n) | | 1 0 | | u(n-1) | So that you have: | u(n) | = | 1 1 |^(n-1) | u(1) | = | 1 1 |^(n-1) | 1 | | u(n-1) | | 1 0 | | u(0) | | 1 0 | | 1 | Computing the exponential of the matrix has a logarithmic complexity. Just implement recursively the idea: M^(0) = Id M^(2p+1) = (M^2p) * M M^(2p) = (M^p) * (M^p) // of course don't compute M^p twice here. You can also just diagonalize it (not to difficult), you will find the gold number and its conjugate in its eigenvalue, and the result will give you an EXACT mathematical formula for u(n). It contains powers of those eigenvalues, so that the complexity will still be logarithmic. Fibo is often taken as an example to illustrate Dynamic Programming, but as you see, it is not really pertinent. @John: I don't think it has anything to do with do with hash. @John2: A map is a bit general don't you think? For Fibonacci case, all the keys are contiguous so that a vector is appropriate, once again there are much faster ways to compute fibo sequence, see my code sample over there.
[ "performance", "recursion" ]
18
17
7,276
18
0
2008-08-23T04:12:29.240000
2008-08-23T04:24:57.807000
23,963
23,971
RESTful web services and HTTP verbs
What is the minimum set of HTTP verbs that a server should allow for a web service to be classed as RESTful? What if my hoster doesn't permit PUT and DELETE? Is this actually important, can I live happily ever after with just GET and POST? Update: Thanks for the answers folks, Roger's answer was probably best because of the link to the Bill Venners and Elliotte Rusty Harold interview. I now get it.
Yes, you can live without PUT and DELETE. This article tells you why: http://www.artima.com/lejava/articles/why_put_and_delete.html While to true RESTafrians this may be heresy, in the real world you do what you can, with what you have. Be as rational as you can and as consistent with your own convention as you can, but you can definitely build a good RESTful system without P and D. rp
RESTful web services and HTTP verbs What is the minimum set of HTTP verbs that a server should allow for a web service to be classed as RESTful? What if my hoster doesn't permit PUT and DELETE? Is this actually important, can I live happily ever after with just GET and POST? Update: Thanks for the answers folks, Roger's answer was probably best because of the link to the Bill Venners and Elliotte Rusty Harold interview. I now get it.
TITLE: RESTful web services and HTTP verbs QUESTION: What is the minimum set of HTTP verbs that a server should allow for a web service to be classed as RESTful? What if my hoster doesn't permit PUT and DELETE? Is this actually important, can I live happily ever after with just GET and POST? Update: Thanks for the answers folks, Roger's answer was probably best because of the link to the Bill Venners and Elliotte Rusty Harold interview. I now get it. ANSWER: Yes, you can live without PUT and DELETE. This article tells you why: http://www.artima.com/lejava/articles/why_put_and_delete.html While to true RESTafrians this may be heresy, in the real world you do what you can, with what you have. Be as rational as you can and as consistent with your own convention as you can, but you can definitely build a good RESTful system without P and D. rp
[ "web-services", "rest" ]
14
22
16,862
5
0
2008-08-23T04:14:17.257000
2008-08-23T04:23:10.713000
23,970
38,588
How do I marshal a lambda (Proc) in Ruby?
Joe Van Dyk asked the Ruby mailing list: Hi, In Ruby, I guess you can't marshal a lambda/proc object, right? Is that possible in lisp or other languages? What I was trying to do: l = lamda {... } Bj.submit "/path/to/ruby/program",:stdin => Marshal.dump(l) So, I'm sending BackgroundJob a lambda object, which contains the context/code for what to do. But, guess that wasn't possible. I ended up marshaling a normal ruby object that contained instructions for what to do after the program ran. Joe
You cannot marshal a Lambda or Proc. This is because both of them are considered closures, which means they close around the memory on which they were defined and can reference it. (In order to marshal them you'd have to Marshal all of the memory they could access at the time they were created.) As Gaius pointed out though, you can use ruby2ruby to get a hold of the string of the program. That is, you can marshal the string that represents the ruby code and then reevaluate it later.
How do I marshal a lambda (Proc) in Ruby? Joe Van Dyk asked the Ruby mailing list: Hi, In Ruby, I guess you can't marshal a lambda/proc object, right? Is that possible in lisp or other languages? What I was trying to do: l = lamda {... } Bj.submit "/path/to/ruby/program",:stdin => Marshal.dump(l) So, I'm sending BackgroundJob a lambda object, which contains the context/code for what to do. But, guess that wasn't possible. I ended up marshaling a normal ruby object that contained instructions for what to do after the program ran. Joe
TITLE: How do I marshal a lambda (Proc) in Ruby? QUESTION: Joe Van Dyk asked the Ruby mailing list: Hi, In Ruby, I guess you can't marshal a lambda/proc object, right? Is that possible in lisp or other languages? What I was trying to do: l = lamda {... } Bj.submit "/path/to/ruby/program",:stdin => Marshal.dump(l) So, I'm sending BackgroundJob a lambda object, which contains the context/code for what to do. But, guess that wasn't possible. I ended up marshaling a normal ruby object that contained instructions for what to do after the program ran. Joe ANSWER: You cannot marshal a Lambda or Proc. This is because both of them are considered closures, which means they close around the memory on which they were defined and can reference it. (In order to marshal them you'd have to Marshal all of the memory they could access at the time they were created.) As Gaius pointed out though, you can use ruby2ruby to get a hold of the string of the program. That is, you can marshal the string that represents the ruby code and then reevaluate it later.
[ "ruby", "serialization", "lambda", "proc-object" ]
21
21
9,295
7
0
2008-08-23T04:22:44.880000
2008-09-01T23:10:45.360000
23,988
23,997
Why is an s-box input longer than its output?
I don't understand where the extra bits are coming from in this article about s-boxes. Why doesn't the s-box take in the same number of bits for input as output?
It is the way s-boxes work. They can be m * n ==> m bit input, n bit output. For example, in the AES S-box the number of bits in input is equal to the number of bits in output. In DES, m=6 and n=4. The input is expanded from 32 to 48 bits in the first stages of DES. So it is be reduced to 32 bits again by applying one round of S-box substitution. Thus no information is lost here. The Wikipedia article on itself can be a bit confusing. It will make people think that information is lost. You should read the article in conjuncture with implementation details of some encryption algorithm using s-boxes.
Why is an s-box input longer than its output? I don't understand where the extra bits are coming from in this article about s-boxes. Why doesn't the s-box take in the same number of bits for input as output?
TITLE: Why is an s-box input longer than its output? QUESTION: I don't understand where the extra bits are coming from in this article about s-boxes. Why doesn't the s-box take in the same number of bits for input as output? ANSWER: It is the way s-boxes work. They can be m * n ==> m bit input, n bit output. For example, in the AES S-box the number of bits in input is equal to the number of bits in output. In DES, m=6 and n=4. The input is expanded from 32 to 48 bits in the first stages of DES. So it is be reduced to 32 bits again by applying one round of S-box substitution. Thus no information is lost here. The Wikipedia article on itself can be a bit confusing. It will make people think that information is lost. You should read the article in conjuncture with implementation details of some encryption algorithm using s-boxes.
[ "cryptography" ]
2
3
1,132
2
0
2008-08-23T04:37:51.270000
2008-08-23T04:55:28.217000
23,994
24,005
Experiences Using ASP.NET MVC Framework
I am wondering what experiences people are having using the ASP.NET MVC Framework? In particular I am looking for feedback on the type of experience folks are having using the framework. What are people using for their view engine? What about the db layer, NHibernate, LINQ to SQL or something else? I know stackoverflow uses MVC, so please say this site. Thank you. Why the choice of NHibernate over anything else? I am not against NHibernate, just wondering the rational.
I've just been recently turned on to MVC and Linq to Sql for Asp.Net. I'm still learning both, and I'm really enjoying them both. There are quite a few screen casts on http://www.asp.net/learn/.
Experiences Using ASP.NET MVC Framework I am wondering what experiences people are having using the ASP.NET MVC Framework? In particular I am looking for feedback on the type of experience folks are having using the framework. What are people using for their view engine? What about the db layer, NHibernate, LINQ to SQL or something else? I know stackoverflow uses MVC, so please say this site. Thank you. Why the choice of NHibernate over anything else? I am not against NHibernate, just wondering the rational.
TITLE: Experiences Using ASP.NET MVC Framework QUESTION: I am wondering what experiences people are having using the ASP.NET MVC Framework? In particular I am looking for feedback on the type of experience folks are having using the framework. What are people using for their view engine? What about the db layer, NHibernate, LINQ to SQL or something else? I know stackoverflow uses MVC, so please say this site. Thank you. Why the choice of NHibernate over anything else? I am not against NHibernate, just wondering the rational. ANSWER: I've just been recently turned on to MVC and Linq to Sql for Asp.Net. I'm still learning both, and I'm really enjoying them both. There are quite a few screen casts on http://www.asp.net/learn/.
[ ".net", "asp.net", "asp.net-mvc" ]
4
0
714
6
0
2008-08-23T04:51:32.597000
2008-08-23T05:07:21.997000
23,996
26,243
Setting Attributes in Webby Layouts
I'm working with Webby and am looking for some clarification. Can I define attributes like title or author in my layout?
Not really. The layout has access to the page attributes rather than the other way. The easiest way to do what you want is to populate the SITE.page_defaults hash in your site's Rakefile (probably build.rake). Add something like the following: SITE.page_defaults['title'] = "My awesome title" SITE.page_defaults['author'] = "Shazbug" SITE.page_defaults['is_mando_awesome'] = "very yes" You can now access those hash members in your template: Written by <%= @page.author %> You can find more info about Webby's page default stuff on the Google Group, specifically here: http://groups.google.com/group/webby-forum/browse_thread/thread/f3dc1f4187959634/c30d7883705f6218?lnk=gst&q=SITE#c30d7883705f6218
Setting Attributes in Webby Layouts I'm working with Webby and am looking for some clarification. Can I define attributes like title or author in my layout?
TITLE: Setting Attributes in Webby Layouts QUESTION: I'm working with Webby and am looking for some clarification. Can I define attributes like title or author in my layout? ANSWER: Not really. The layout has access to the page attributes rather than the other way. The easiest way to do what you want is to populate the SITE.page_defaults hash in your site's Rakefile (probably build.rake). Add something like the following: SITE.page_defaults['title'] = "My awesome title" SITE.page_defaults['author'] = "Shazbug" SITE.page_defaults['is_mando_awesome'] = "very yes" You can now access those hash members in your template: Written by <%= @page.author %> You can find more info about Webby's page default stuff on the Google Group, specifically here: http://groups.google.com/group/webby-forum/browse_thread/thread/f3dc1f4187959634/c30d7883705f6218?lnk=gst&q=SITE#c30d7883705f6218
[ "ruby", "webby" ]
2
1
376
2
0
2008-08-23T04:53:47.863000
2008-08-25T15:25:59.247000
24,041
24,044
Markdown vs markup - are they related?
I'm using markdown to edit this question right now. In some wikis I used wiki markup. Are they the same thing? Are they related? Please explain. If I want to implement one or the other in a web project (like stackoverflow) what do I need to use?
Markup is a generic term for a language that describes a document's formatting Markdown is a specific markup library: http://daringfireball.net/projects/markdown/ These days the term is more commonly used to refer to markup languages that mimic the style of the library. See: https://en.wikipedia.org/wiki/Markdown
Markdown vs markup - are they related? I'm using markdown to edit this question right now. In some wikis I used wiki markup. Are they the same thing? Are they related? Please explain. If I want to implement one or the other in a web project (like stackoverflow) what do I need to use?
TITLE: Markdown vs markup - are they related? QUESTION: I'm using markdown to edit this question right now. In some wikis I used wiki markup. Are they the same thing? Are they related? Please explain. If I want to implement one or the other in a web project (like stackoverflow) what do I need to use? ANSWER: Markup is a generic term for a language that describes a document's formatting Markdown is a specific markup library: http://daringfireball.net/projects/markdown/ These days the term is more commonly used to refer to markup languages that mimic the style of the library. See: https://en.wikipedia.org/wiki/Markdown
[ "markdown", "markup", "glossary" ]
285
313
121,243
6
0
2008-08-23T06:34:09.493000
2008-08-23T06:40:08.683000
24,045
24,062
AnkhSVN versus VisualSVN
I currently use AnkhSVN to integrate subversion into Visual Studio. Is there any reason I should switch to VisualSVN? AnkhSVN is free (in more than one sense of the word) while VisualSVN costs $50. So right there unless I'm missing some great feature of VisualSVN I don't see any reason to switch.
I used VisualSVN until Ankh hit 2.0, and ever since, I've abandoned VisualSVN. Ankh has surpassed VisualSVN in functionality, in my mind, and all the 1.x perf and integration issues are gone.
AnkhSVN versus VisualSVN I currently use AnkhSVN to integrate subversion into Visual Studio. Is there any reason I should switch to VisualSVN? AnkhSVN is free (in more than one sense of the word) while VisualSVN costs $50. So right there unless I'm missing some great feature of VisualSVN I don't see any reason to switch.
TITLE: AnkhSVN versus VisualSVN QUESTION: I currently use AnkhSVN to integrate subversion into Visual Studio. Is there any reason I should switch to VisualSVN? AnkhSVN is free (in more than one sense of the word) while VisualSVN costs $50. So right there unless I'm missing some great feature of VisualSVN I don't see any reason to switch. ANSWER: I used VisualSVN until Ankh hit 2.0, and ever since, I've abandoned VisualSVN. Ankh has surpassed VisualSVN in functionality, in my mind, and all the 1.x perf and integration issues are gone.
[ "visual-studio", "svn", "version-control", "visualsvn", "ankhsvn" ]
59
48
27,608
4
0
2008-08-23T06:42:01.067000
2008-08-23T07:44:29.870000
24,099
24,140
Best way to license Microsoft software as an independent developer
I've recently switched from being an employee of a small consulting company to being an independent consultant and as time goes on I will need to upgrade Windows and Visual Studio. So what is the most affordable way to go about this for a small time developer? My previous boss suggested I get a TechNet Plus subscription for OS licenses, I've done that and appears to be what I need, but open to other options for the future. Visual Studio I'm having a hard time figuring out exactly what is the difference between Professional and Standard. Also I'd really like a digital version, but seems that expensive MSDN subscription is the only way? Visual Studio 2008 Professional with MSDN Professional listed here appears to be semi-reasonably priced at $1,199. That would make the TechNet Plus subscription unneeded.
I recommend that if VS Express is not good enough, use Professional. Standard is missing some really useful features, like a Remote Debugger. Here is a detailed comparison: http://msdn.microsoft.com/en-us/vs2008/products/cc149003.aspx I'd say cancel TechNet and get one of the bottom two MSDN Subscriptions, Visual Studio Professional with either MSDN Professional or with MSDN Premium.
Best way to license Microsoft software as an independent developer I've recently switched from being an employee of a small consulting company to being an independent consultant and as time goes on I will need to upgrade Windows and Visual Studio. So what is the most affordable way to go about this for a small time developer? My previous boss suggested I get a TechNet Plus subscription for OS licenses, I've done that and appears to be what I need, but open to other options for the future. Visual Studio I'm having a hard time figuring out exactly what is the difference between Professional and Standard. Also I'd really like a digital version, but seems that expensive MSDN subscription is the only way? Visual Studio 2008 Professional with MSDN Professional listed here appears to be semi-reasonably priced at $1,199. That would make the TechNet Plus subscription unneeded.
TITLE: Best way to license Microsoft software as an independent developer QUESTION: I've recently switched from being an employee of a small consulting company to being an independent consultant and as time goes on I will need to upgrade Windows and Visual Studio. So what is the most affordable way to go about this for a small time developer? My previous boss suggested I get a TechNet Plus subscription for OS licenses, I've done that and appears to be what I need, but open to other options for the future. Visual Studio I'm having a hard time figuring out exactly what is the difference between Professional and Standard. Also I'd really like a digital version, but seems that expensive MSDN subscription is the only way? Visual Studio 2008 Professional with MSDN Professional listed here appears to be semi-reasonably priced at $1,199. That would make the TechNet Plus subscription unneeded. ANSWER: I recommend that if VS Express is not good enough, use Professional. Standard is missing some really useful features, like a Remote Debugger. Here is a detailed comparison: http://msdn.microsoft.com/en-us/vs2008/products/cc149003.aspx I'd say cancel TechNet and get one of the bottom two MSDN Subscriptions, Visual Studio Professional with either MSDN Professional or with MSDN Premium.
[ "windows", "visual-studio", "licensing" ]
16
5
4,876
5
0
2008-08-23T09:19:54.883000
2008-08-23T11:02:29.800000
24,109
24,119
C++ IDE for Linux?
I want to expand my programming horizons to Linux. A good, dependable basic toolset is important, and what is more basic than an IDE? I could find these SO topics: Lightweight IDE for linux and What tools do you use to develop C++ applications on Linux? I'm not looking for a lightweight IDE. If an IDE is worth the money, then I will pay for it, so it need not be free. My question, then: What good, C++ programming IDE is available for Linux? The minimums are fairly standard: syntax highlighting, code completion (like intellisense or its Eclipse counterpart) and integrated debugging (e.g., basic breakpoints). I have searched for it myself, but there are so many that it is almost impossible to separate the good from the bads by hand, especially for someone like me who has little C++ coding experience in Linux. I know that Eclipse supports C++, and I really like that IDE for Java, but is it any good for C++ and is there something better? The second post actually has some good suggestions, but what I am missing is what exactly makes the sugested IDE so good for the user, what are its (dis)advantages? Maybe my question should therefore be: What IDE do you propose (given your experiences), and why?
Initially: confusion When originally writing this answer, I had recently made the switch from Visual Studio (with years of experience) to Linux and the first thing I did was try to find a reasonable IDE. At the time this was impossible: no good IDE existed. Epiphany: UNIX is an IDE. All of it. 1 And then I realised that the IDE in Linux is the command line with its tools: First you set up your shell Bash, in my case, but many people prefer fish or (Oh My) Zsh; and your editor; pick your poison — both are state of the art: Neovim 2 or Emacs. Depending on your needs, you will then have to install and configure several plugins to make the editor work nicely (that’s the one annoying part). For example, most programmers on Vim will benefit from the YouCompleteMe plugin for smart autocompletion. Once that’s done, the shell is your command interface to interact with the various tools — Debuggers (gdb), Profilers (gprof, valgrind), etc. You set up your project/build environment using Make, CMake, SnakeMake or any of the various alternatives. And you manage your code with a version control system (most people use Git ). You also use tmux (previously also screen) to multiplex (= think multiple windows/tabs/panels) and persist your terminal session. The point is that, thanks to the shell and a few tool writing conventions, these all integrate with each other. And that way the Linux shell is a truly integrated development environment, completely on par with other modern IDEs. (This doesn’t mean that individual IDEs don’t have features that the command line may be lacking, but the inverse is also true.) To each their own I cannot overstate how well the above workflow functions once you’ve gotten into the habit. But some people simply prefer graphical editors, and in the years since this answer was originally written, Linux has gained a suite of excellent graphical IDEs for several different programming languages (but not, as far as I’m aware, for C++). Do give them a try even if — like me — you end up not using them. Here’s just a small and biased selection: For Python development, there’s PyCharm For R, there’s RStudio For JavaScript and TypeScript, there’s Visual Studio Code (which is also a good all-round editor) And finally, many people love the Sublime Text editor for general code editing. Keep in mind that this list is far from complete. 1 I stole that title from dsm’s comment. 2 I used to refer to Vim here. And while plain Vim is still more than capable, Neovim is a promising restart, and it’s modernised a few old warts.
C++ IDE for Linux? I want to expand my programming horizons to Linux. A good, dependable basic toolset is important, and what is more basic than an IDE? I could find these SO topics: Lightweight IDE for linux and What tools do you use to develop C++ applications on Linux? I'm not looking for a lightweight IDE. If an IDE is worth the money, then I will pay for it, so it need not be free. My question, then: What good, C++ programming IDE is available for Linux? The minimums are fairly standard: syntax highlighting, code completion (like intellisense or its Eclipse counterpart) and integrated debugging (e.g., basic breakpoints). I have searched for it myself, but there are so many that it is almost impossible to separate the good from the bads by hand, especially for someone like me who has little C++ coding experience in Linux. I know that Eclipse supports C++, and I really like that IDE for Java, but is it any good for C++ and is there something better? The second post actually has some good suggestions, but what I am missing is what exactly makes the sugested IDE so good for the user, what are its (dis)advantages? Maybe my question should therefore be: What IDE do you propose (given your experiences), and why?
TITLE: C++ IDE for Linux? QUESTION: I want to expand my programming horizons to Linux. A good, dependable basic toolset is important, and what is more basic than an IDE? I could find these SO topics: Lightweight IDE for linux and What tools do you use to develop C++ applications on Linux? I'm not looking for a lightweight IDE. If an IDE is worth the money, then I will pay for it, so it need not be free. My question, then: What good, C++ programming IDE is available for Linux? The minimums are fairly standard: syntax highlighting, code completion (like intellisense or its Eclipse counterpart) and integrated debugging (e.g., basic breakpoints). I have searched for it myself, but there are so many that it is almost impossible to separate the good from the bads by hand, especially for someone like me who has little C++ coding experience in Linux. I know that Eclipse supports C++, and I really like that IDE for Java, but is it any good for C++ and is there something better? The second post actually has some good suggestions, but what I am missing is what exactly makes the sugested IDE so good for the user, what are its (dis)advantages? Maybe my question should therefore be: What IDE do you propose (given your experiences), and why? ANSWER: Initially: confusion When originally writing this answer, I had recently made the switch from Visual Studio (with years of experience) to Linux and the first thing I did was try to find a reasonable IDE. At the time this was impossible: no good IDE existed. Epiphany: UNIX is an IDE. All of it. 1 And then I realised that the IDE in Linux is the command line with its tools: First you set up your shell Bash, in my case, but many people prefer fish or (Oh My) Zsh; and your editor; pick your poison — both are state of the art: Neovim 2 or Emacs. Depending on your needs, you will then have to install and configure several plugins to make the editor work nicely (that’s the one annoying part). For example, most programmers on Vim will benefit from the YouCompleteMe plugin for smart autocompletion. Once that’s done, the shell is your command interface to interact with the various tools — Debuggers (gdb), Profilers (gprof, valgrind), etc. You set up your project/build environment using Make, CMake, SnakeMake or any of the various alternatives. And you manage your code with a version control system (most people use Git ). You also use tmux (previously also screen) to multiplex (= think multiple windows/tabs/panels) and persist your terminal session. The point is that, thanks to the shell and a few tool writing conventions, these all integrate with each other. And that way the Linux shell is a truly integrated development environment, completely on par with other modern IDEs. (This doesn’t mean that individual IDEs don’t have features that the command line may be lacking, but the inverse is also true.) To each their own I cannot overstate how well the above workflow functions once you’ve gotten into the habit. But some people simply prefer graphical editors, and in the years since this answer was originally written, Linux has gained a suite of excellent graphical IDEs for several different programming languages (but not, as far as I’m aware, for C++). Do give them a try even if — like me — you end up not using them. Here’s just a small and biased selection: For Python development, there’s PyCharm For R, there’s RStudio For JavaScript and TypeScript, there’s Visual Studio Code (which is also a good all-round editor) And finally, many people love the Sublime Text editor for general code editing. Keep in mind that this list is far from complete. 1 I stole that title from dsm’s comment. 2 I used to refer to Vim here. And while plain Vim is still more than capable, Neovim is a promising restart, and it’s modernised a few old warts.
[ "c++", "linux", "ide" ]
209
258
1,031,427
45
0
2008-08-23T09:52:59.517000
2008-08-23T10:06:09.157000
24,130
24,134
Classes vs 2D arrays
Which is better to use in PHP, a 2D array or a class? I've included an example of what I mean by this. // Using a class class someClass { public $name; public $height; public $weight; function __construct($name, $height, $weight) { $this -> name = $name; $this -> height = $height; $this -> weight = $weight; } } $classArray[1] = new someClass('Bob', 10, 20); $classArray[2] = new someClass('Fred', 15, 10); $classArray[3] = new someClass('Ned', 25, 30); // Using a 2D array $normalArray[1]['name'] = 'Bob'; $normalArray[1]['height'] = 10; $normalArray[1]['weight'] = 20; $normalArray[2]['name'] = 'Fred'; $normalArray[2]['height'] = 15; $normalArray[2]['weight'] = 10; $normalArray[3]['name'] = 'Ned'; $normalArray[3]['height'] = 25; $normalArray[3]['weight'] = 30; Assuming that somebody doesn't come out and show that classes are too slow, it looks like class wins. I've not idea which answer I should accept to I've just upvoted all of them. And I have now written two near identical pages, one using the 2D array (written before this question was posted) and now one using a class and I must say that the class produces much nicer code. I have no idea how much overhead is going to be generated but I doubt it will rival the improvement to the code itself. Thank you for helping to make me a better programmer.
The "class" that you've constructed above is what most people would use a struct for in other languages. I'm not sure what the performance implications are in PHP, though I suspect instantiating the objects is probably more costly here, if only by a little bit. That being said, if the cost is relatively low, it IS a bit easier to manage the objects, in my opinion. I'm only saying the following based on the title and your question, but: Bear in mind that classes provide the advantage of methods and access control, as well. So if you wanted to ensure that people weren't changing weights to negative numbers, you could make the weight field private and provide some accessor methods, like getWeight() and setWeight(). Inside setWeight(), you could do some value checking, like so: public function setWeight($weight) { if($weight >= 0) { $this->weight = $weight; } else { // Handle this scenario however you like } }
Classes vs 2D arrays Which is better to use in PHP, a 2D array or a class? I've included an example of what I mean by this. // Using a class class someClass { public $name; public $height; public $weight; function __construct($name, $height, $weight) { $this -> name = $name; $this -> height = $height; $this -> weight = $weight; } } $classArray[1] = new someClass('Bob', 10, 20); $classArray[2] = new someClass('Fred', 15, 10); $classArray[3] = new someClass('Ned', 25, 30); // Using a 2D array $normalArray[1]['name'] = 'Bob'; $normalArray[1]['height'] = 10; $normalArray[1]['weight'] = 20; $normalArray[2]['name'] = 'Fred'; $normalArray[2]['height'] = 15; $normalArray[2]['weight'] = 10; $normalArray[3]['name'] = 'Ned'; $normalArray[3]['height'] = 25; $normalArray[3]['weight'] = 30; Assuming that somebody doesn't come out and show that classes are too slow, it looks like class wins. I've not idea which answer I should accept to I've just upvoted all of them. And I have now written two near identical pages, one using the 2D array (written before this question was posted) and now one using a class and I must say that the class produces much nicer code. I have no idea how much overhead is going to be generated but I doubt it will rival the improvement to the code itself. Thank you for helping to make me a better programmer.
TITLE: Classes vs 2D arrays QUESTION: Which is better to use in PHP, a 2D array or a class? I've included an example of what I mean by this. // Using a class class someClass { public $name; public $height; public $weight; function __construct($name, $height, $weight) { $this -> name = $name; $this -> height = $height; $this -> weight = $weight; } } $classArray[1] = new someClass('Bob', 10, 20); $classArray[2] = new someClass('Fred', 15, 10); $classArray[3] = new someClass('Ned', 25, 30); // Using a 2D array $normalArray[1]['name'] = 'Bob'; $normalArray[1]['height'] = 10; $normalArray[1]['weight'] = 20; $normalArray[2]['name'] = 'Fred'; $normalArray[2]['height'] = 15; $normalArray[2]['weight'] = 10; $normalArray[3]['name'] = 'Ned'; $normalArray[3]['height'] = 25; $normalArray[3]['weight'] = 30; Assuming that somebody doesn't come out and show that classes are too slow, it looks like class wins. I've not idea which answer I should accept to I've just upvoted all of them. And I have now written two near identical pages, one using the 2D array (written before this question was posted) and now one using a class and I must say that the class produces much nicer code. I have no idea how much overhead is going to be generated but I doubt it will rival the improvement to the code itself. Thank you for helping to make me a better programmer. ANSWER: The "class" that you've constructed above is what most people would use a struct for in other languages. I'm not sure what the performance implications are in PHP, though I suspect instantiating the objects is probably more costly here, if only by a little bit. That being said, if the cost is relatively low, it IS a bit easier to manage the objects, in my opinion. I'm only saying the following based on the title and your question, but: Bear in mind that classes provide the advantage of methods and access control, as well. So if you wanted to ensure that people weren't changing weights to negative numbers, you could make the weight field private and provide some accessor methods, like getWeight() and setWeight(). Inside setWeight(), you could do some value checking, like so: public function setWeight($weight) { if($weight >= 0) { $this->weight = $weight; } else { // Handle this scenario however you like } }
[ "php", "arrays", "class" ]
6
9
1,887
9
0
2008-08-23T10:41:36.340000
2008-08-23T10:52:51.727000
24,179
36,398
How does Hive compare to HBase?
I'm interested in finding out how the recently-released Hive compares to HBase in terms of performance. The SQL-like interface used by Hive is very much preferable to the HBase API we have implemented.
It's hard to find much about Hive, but I found this snippet on the Hive site that leans heavily in favor of HBase (bold added): Hive is based on Hadoop which is a batch processing system. Accordingly, this system does not and cannot promise low latencies on queries. The paradigm here is strictly of submitting jobs and being notified when the jobs are completed as opposed to real time queries. As a result it should not be compared with systems like Oracle where analysis is done on a significantly smaller amount of data but the analysis proceeds much more iteratively with the response times between iterations being less than a few minutes. For Hive queries response times for even the smallest jobs can be of the order of 5-10 minutes and for larger jobs this may even run into hours. Since HBase and HyperTable are all about performance (being modeled on Google's BigTable), they sound like they would certainly be much faster than Hive, at the cost of functionality and a higher learning curve (e.g., they don't have joins or the SQL-like syntax).
How does Hive compare to HBase? I'm interested in finding out how the recently-released Hive compares to HBase in terms of performance. The SQL-like interface used by Hive is very much preferable to the HBase API we have implemented.
TITLE: How does Hive compare to HBase? QUESTION: I'm interested in finding out how the recently-released Hive compares to HBase in terms of performance. The SQL-like interface used by Hive is very much preferable to the HBase API we have implemented. ANSWER: It's hard to find much about Hive, but I found this snippet on the Hive site that leans heavily in favor of HBase (bold added): Hive is based on Hadoop which is a batch processing system. Accordingly, this system does not and cannot promise low latencies on queries. The paradigm here is strictly of submitting jobs and being notified when the jobs are completed as opposed to real time queries. As a result it should not be compared with systems like Oracle where analysis is done on a significantly smaller amount of data but the analysis proceeds much more iteratively with the response times between iterations being less than a few minutes. For Hive queries response times for even the smallest jobs can be of the order of 5-10 minutes and for larger jobs this may even run into hours. Since HBase and HyperTable are all about performance (being modeled on Google's BigTable), they sound like they would certainly be much faster than Hive, at the cost of functionality and a higher learning curve (e.g., they don't have joins or the SQL-like syntax).
[ "hadoop", "hbase", "hive" ]
57
51
44,500
7
0
2008-08-23T12:22:04.993000
2008-08-30T22:16:14.213000
24,193
24,248
Python code generator for Visual Studio?
I had an idea, if I add a python.py file to my C# project, and tag the file with a custom generator that would execute the python file, and treat the output as the result of the code generation, ie. put it into a C# file, that would allow me to do quite a lot of code generation as part of the build process. Does anyone know if such a custom generator for Visual Studio 2008 exists?
OK, I see. Well, as far as I know there isn't any code generator for Python. There is a good introduction on how to roll your own here. Actually, that's quite an under-used part of the environment, I suppose it's so because it needs you to use the IDE to compile the project, as it'd seem only the IDE knows about these "generators", but MSBuild ignores them.
Python code generator for Visual Studio? I had an idea, if I add a python.py file to my C# project, and tag the file with a custom generator that would execute the python file, and treat the output as the result of the code generation, ie. put it into a C# file, that would allow me to do quite a lot of code generation as part of the build process. Does anyone know if such a custom generator for Visual Studio 2008 exists?
TITLE: Python code generator for Visual Studio? QUESTION: I had an idea, if I add a python.py file to my C# project, and tag the file with a custom generator that would execute the python file, and treat the output as the result of the code generation, ie. put it into a C# file, that would allow me to do quite a lot of code generation as part of the build process. Does anyone know if such a custom generator for Visual Studio 2008 exists? ANSWER: OK, I see. Well, as far as I know there isn't any code generator for Python. There is a good introduction on how to roll your own here. Actually, that's quite an under-used part of the environment, I suppose it's so because it needs you to use the IDE to compile the project, as it'd seem only the IDE knows about these "generators", but MSBuild ignores them.
[ "python", "visual-studio-2008", "code-generation" ]
5
2
2,055
5
0
2008-08-23T12:41:43.433000
2008-08-23T14:07:27.080000
24,196
24,223
Simple Frameworks for Displaying Bitmaps and Handling Button Presses
We have a set of applications that basically display a bunch of bitmaps and text, then allow user to press "buttons" (certain bitmaps) that cause actions to occur. We currently have these implemented using DirectX and a bunch of code to place the bitmaps and handle the button-presses. But we'd like to have the following features: portable to Linux some sort of "editor" that would allow us to lay out screens without hard-coding locations of elements in code animation we need to be able to overlay video not resource intensive (these terminals don't have a lot of memory or CPU) we're currently using C++, so management would prefer that, but other languages would be considered We'd prefer a free, open-source solution, but would be willing to buy something if it is not too expensive. (We have a couple dozen developers, and tens of thousands of terminals deployed.) We don't like the common GUI toolkits or widgets. We want something that has more of the look of a game than of a dialog box. Any suggestions for off-the-shelf stuff we could use?
Maybe the way to go is something like Clutter or Allegro. If you check in this article at ArsTechnica what they are using Clutter for, you might get an idea how to use it. I don't know for sure if it works on Windows, but I'm pretty sure it does, considering it only depends on libraries that are supported under Windows.
Simple Frameworks for Displaying Bitmaps and Handling Button Presses We have a set of applications that basically display a bunch of bitmaps and text, then allow user to press "buttons" (certain bitmaps) that cause actions to occur. We currently have these implemented using DirectX and a bunch of code to place the bitmaps and handle the button-presses. But we'd like to have the following features: portable to Linux some sort of "editor" that would allow us to lay out screens without hard-coding locations of elements in code animation we need to be able to overlay video not resource intensive (these terminals don't have a lot of memory or CPU) we're currently using C++, so management would prefer that, but other languages would be considered We'd prefer a free, open-source solution, but would be willing to buy something if it is not too expensive. (We have a couple dozen developers, and tens of thousands of terminals deployed.) We don't like the common GUI toolkits or widgets. We want something that has more of the look of a game than of a dialog box. Any suggestions for off-the-shelf stuff we could use?
TITLE: Simple Frameworks for Displaying Bitmaps and Handling Button Presses QUESTION: We have a set of applications that basically display a bunch of bitmaps and text, then allow user to press "buttons" (certain bitmaps) that cause actions to occur. We currently have these implemented using DirectX and a bunch of code to place the bitmaps and handle the button-presses. But we'd like to have the following features: portable to Linux some sort of "editor" that would allow us to lay out screens without hard-coding locations of elements in code animation we need to be able to overlay video not resource intensive (these terminals don't have a lot of memory or CPU) we're currently using C++, so management would prefer that, but other languages would be considered We'd prefer a free, open-source solution, but would be willing to buy something if it is not too expensive. (We have a couple dozen developers, and tens of thousands of terminals deployed.) We don't like the common GUI toolkits or widgets. We want something that has more of the look of a game than of a dialog box. Any suggestions for off-the-shelf stuff we could use? ANSWER: Maybe the way to go is something like Clutter or Allegro. If you check in this article at ArsTechnica what they are using Clutter for, you might get an idea how to use it. I don't know for sure if it works on Windows, but I'm pretty sure it does, considering it only depends on libraries that are supported under Windows.
[ "c++", "user-interface", "graphics", "bitmap" ]
0
1
378
3
0
2008-08-23T12:47:55.587000
2008-08-23T13:24:48.540000
24,207
71,401
“rusage” statistics
I'm trying to use “rusage” statistics in my program to get data similar to that of the time tool. However, I'm pretty sure that I'm doing something wrong. The values seem about right but can be a bit weird at times. I didn't find good resources online. Does somebody know how to do it better? Sorry for the long code. class StopWatch { public: void start() { getrusage(RUSAGE_SELF, &m_begin); gettimeofday(&m_tmbegin, 0); } void stop() { getrusage(RUSAGE_SELF, &m_end); gettimeofday(&m_tmend, 0); timeval_sub(m_end.ru_utime, m_begin.ru_utime, m_diff.ru_utime); timeval_sub(m_end.ru_stime, m_begin.ru_stime, m_diff.ru_stime); timeval_sub(m_tmend, m_tmbegin, m_tmdiff); } void printf(std::ostream& out) const { using namespace std; timeval const& utime = m_diff.ru_utime; timeval const& stime = m_diff.ru_stime; format_time(out, utime); out << "u "; format_time(out, stime); out << "s "; format_time(out, m_tmdiff); } private: rusage m_begin; rusage m_end; rusage m_diff; timeval m_tmbegin; timeval m_tmend; timeval m_tmdiff; static void timeval_add(timeval const& a, timeval const& b, timeval& ret) { ret.tv_usec = a.tv_usec + b.tv_usec; ret.tv_sec = a.tv_sec + b.tv_sec; if (ret.tv_usec > 999999) { ret.tv_usec -= 1000000; ++ret.tv_sec; } } static void timeval_sub(timeval const& a, timeval const& b, timeval& ret) { ret.tv_usec = a.tv_usec - b.tv_usec; ret.tv_sec = a.tv_sec - b.tv_sec; if (a.tv_usec < b.tv_usec) { ret.tv_usec += 1000000; --ret.tv_sec; } } static void format_time(std::ostream& out, timeval const& tv) { using namespace std; long usec = tv.tv_usec; while (usec >= 1000) usec /= 10; out << tv.tv_sec << '.' << setw(3) << setfill('0') << usec; } }; // class StopWatch
What is the purpose of: while (usec >= 1000) usec /= 10; I gather that you want the most significant three digits of the usec; in that case, the most straightforward way I can think of is to divide usec by 1000, and be done with that. Test cases: 999999 ⇒ 999 99999 ⇒ 999 (should be 099) 9999 ⇒ 999 (should be 009) 999 ⇒ 999 (should be 000)
“rusage” statistics I'm trying to use “rusage” statistics in my program to get data similar to that of the time tool. However, I'm pretty sure that I'm doing something wrong. The values seem about right but can be a bit weird at times. I didn't find good resources online. Does somebody know how to do it better? Sorry for the long code. class StopWatch { public: void start() { getrusage(RUSAGE_SELF, &m_begin); gettimeofday(&m_tmbegin, 0); } void stop() { getrusage(RUSAGE_SELF, &m_end); gettimeofday(&m_tmend, 0); timeval_sub(m_end.ru_utime, m_begin.ru_utime, m_diff.ru_utime); timeval_sub(m_end.ru_stime, m_begin.ru_stime, m_diff.ru_stime); timeval_sub(m_tmend, m_tmbegin, m_tmdiff); } void printf(std::ostream& out) const { using namespace std; timeval const& utime = m_diff.ru_utime; timeval const& stime = m_diff.ru_stime; format_time(out, utime); out << "u "; format_time(out, stime); out << "s "; format_time(out, m_tmdiff); } private: rusage m_begin; rusage m_end; rusage m_diff; timeval m_tmbegin; timeval m_tmend; timeval m_tmdiff; static void timeval_add(timeval const& a, timeval const& b, timeval& ret) { ret.tv_usec = a.tv_usec + b.tv_usec; ret.tv_sec = a.tv_sec + b.tv_sec; if (ret.tv_usec > 999999) { ret.tv_usec -= 1000000; ++ret.tv_sec; } } static void timeval_sub(timeval const& a, timeval const& b, timeval& ret) { ret.tv_usec = a.tv_usec - b.tv_usec; ret.tv_sec = a.tv_sec - b.tv_sec; if (a.tv_usec < b.tv_usec) { ret.tv_usec += 1000000; --ret.tv_sec; } } static void format_time(std::ostream& out, timeval const& tv) { using namespace std; long usec = tv.tv_usec; while (usec >= 1000) usec /= 10; out << tv.tv_sec << '.' << setw(3) << setfill('0') << usec; } }; // class StopWatch
TITLE: “rusage” statistics QUESTION: I'm trying to use “rusage” statistics in my program to get data similar to that of the time tool. However, I'm pretty sure that I'm doing something wrong. The values seem about right but can be a bit weird at times. I didn't find good resources online. Does somebody know how to do it better? Sorry for the long code. class StopWatch { public: void start() { getrusage(RUSAGE_SELF, &m_begin); gettimeofday(&m_tmbegin, 0); } void stop() { getrusage(RUSAGE_SELF, &m_end); gettimeofday(&m_tmend, 0); timeval_sub(m_end.ru_utime, m_begin.ru_utime, m_diff.ru_utime); timeval_sub(m_end.ru_stime, m_begin.ru_stime, m_diff.ru_stime); timeval_sub(m_tmend, m_tmbegin, m_tmdiff); } void printf(std::ostream& out) const { using namespace std; timeval const& utime = m_diff.ru_utime; timeval const& stime = m_diff.ru_stime; format_time(out, utime); out << "u "; format_time(out, stime); out << "s "; format_time(out, m_tmdiff); } private: rusage m_begin; rusage m_end; rusage m_diff; timeval m_tmbegin; timeval m_tmend; timeval m_tmdiff; static void timeval_add(timeval const& a, timeval const& b, timeval& ret) { ret.tv_usec = a.tv_usec + b.tv_usec; ret.tv_sec = a.tv_sec + b.tv_sec; if (ret.tv_usec > 999999) { ret.tv_usec -= 1000000; ++ret.tv_sec; } } static void timeval_sub(timeval const& a, timeval const& b, timeval& ret) { ret.tv_usec = a.tv_usec - b.tv_usec; ret.tv_sec = a.tv_sec - b.tv_sec; if (a.tv_usec < b.tv_usec) { ret.tv_usec += 1000000; --ret.tv_sec; } } static void format_time(std::ostream& out, timeval const& tv) { using namespace std; long usec = tv.tv_usec; while (usec >= 1000) usec /= 10; out << tv.tv_sec << '.' << setw(3) << setfill('0') << usec; } }; // class StopWatch ANSWER: What is the purpose of: while (usec >= 1000) usec /= 10; I gather that you want the most significant three digits of the usec; in that case, the most straightforward way I can think of is to divide usec by 1000, and be done with that. Test cases: 999999 ⇒ 999 99999 ⇒ 999 (should be 099) 9999 ⇒ 999 (should be 009) 999 ⇒ 999 (should be 000)
[ "c++", "unix", "time", "profiling" ]
1
3
2,846
2
0
2008-08-23T12:57:16.483000
2008-09-16T11:32:17.767000
24,212
30,029
Use QItemDelegate to show image thumbnails
What's the best way to use QT4's QItemDelegate to show thumbnails for images in a view? Specifically, how do you stop the item delegate from blocking when generating pixmaps from very large image files (> 500MB)? Can anyone link to some example code that achieves this? Then again, perhaps this isn't the place to look for Qt-specific code.
You're doing it wrong if you are generating pixmaps inside any of the delegate methods (paint, draw...). Try to generate the thumbnails only once (on worker thread or maybe not even at runtime, if possible) and have the delegate just display them for the appropriate role. If you do it at runtime display a default picture until you have the thumbnail generated (like web browsers do with pictures that are not yet downloaded).
Use QItemDelegate to show image thumbnails What's the best way to use QT4's QItemDelegate to show thumbnails for images in a view? Specifically, how do you stop the item delegate from blocking when generating pixmaps from very large image files (> 500MB)? Can anyone link to some example code that achieves this? Then again, perhaps this isn't the place to look for Qt-specific code.
TITLE: Use QItemDelegate to show image thumbnails QUESTION: What's the best way to use QT4's QItemDelegate to show thumbnails for images in a view? Specifically, how do you stop the item delegate from blocking when generating pixmaps from very large image files (> 500MB)? Can anyone link to some example code that achieves this? Then again, perhaps this isn't the place to look for Qt-specific code. ANSWER: You're doing it wrong if you are generating pixmaps inside any of the delegate methods (paint, draw...). Try to generate the thumbnails only once (on worker thread or maybe not even at runtime, if possible) and have the delegate just display them for the appropriate role. If you do it at runtime display a default picture until you have the thumbnail generated (like web browsers do with pictures that are not yet downloaded).
[ "c++", "qt", "image", "thumbnails", "qitemdelegate" ]
3
4
2,136
1
0
2008-08-23T13:07:19.517000
2008-08-27T13:06:36.647000
24,221
24,231
Java Annotations
What is the purpose of annotations in Java? I have this fuzzy idea of them as somewhere in between a comment and actual code. Do they affect the program at run time? What are their typical usages? Are they unique to Java? Is there a C++ equivalent?
Annotations are primarily used by code that is inspecting other code. They are often used for modifying (i.e. decorating or wrapping) existing classes at run-time to change their behavior. Frameworks such as JUnit and Hibernate use annotations to minimize the amount of code you need to write yourself to use the frameworks. Oracle has a good explanation of the concept and its meaning in Java on their site.
Java Annotations What is the purpose of annotations in Java? I have this fuzzy idea of them as somewhere in between a comment and actual code. Do they affect the program at run time? What are their typical usages? Are they unique to Java? Is there a C++ equivalent?
TITLE: Java Annotations QUESTION: What is the purpose of annotations in Java? I have this fuzzy idea of them as somewhere in between a comment and actual code. Do they affect the program at run time? What are their typical usages? Are they unique to Java? Is there a C++ equivalent? ANSWER: Annotations are primarily used by code that is inspecting other code. They are often used for modifying (i.e. decorating or wrapping) existing classes at run-time to change their behavior. Frameworks such as JUnit and Hibernate use annotations to minimize the amount of code you need to write yourself to use the frameworks. Oracle has a good explanation of the concept and its meaning in Java on their site.
[ "java", "annotations", "glossary" ]
122
88
36,437
9
0
2008-08-23T13:23:14.957000
2008-08-23T13:38:25.760000
24,241
24,254
Code Injection With C#
Can you use windows hooks or other methods to do code injection with c#? I've seen lots of things about code injection but all of them are done in C/C++. I don't know either of those languages and have a really hard time translating. Does anyone have any ideas on how to do this?
Kevin, it is possible. You can create library with window hook proc using managed C++. All you need to do is to inject this hook into some application using standard WinAPI (SetWindowsHookEx etc.). Inside this hook you can call System::AppDomain::CurrentDomain->Load method to load your assembly into target application's AppDomain. Then you can call methods defined in your assembly using reflection. For example, Snoop uses this method.
Code Injection With C# Can you use windows hooks or other methods to do code injection with c#? I've seen lots of things about code injection but all of them are done in C/C++. I don't know either of those languages and have a really hard time translating. Does anyone have any ideas on how to do this?
TITLE: Code Injection With C# QUESTION: Can you use windows hooks or other methods to do code injection with c#? I've seen lots of things about code injection but all of them are done in C/C++. I don't know either of those languages and have a really hard time translating. Does anyone have any ideas on how to do this? ANSWER: Kevin, it is possible. You can create library with window hook proc using managed C++. All you need to do is to inject this hook into some application using standard WinAPI (SetWindowsHookEx etc.). Inside this hook you can call System::AppDomain::CurrentDomain->Load method to load your assembly into target application's AppDomain. Then you can call methods defined in your assembly using reflection. For example, Snoop uses this method.
[ "c#", "code-injection" ]
13
6
43,468
4
0
2008-08-23T13:57:06.263000
2008-08-23T14:23:52.330000
24,243
24,244
Select existing data from database to create test data
I have a SqlServer database that I've manually filled with some test data. Now I'd like to extract this test data as insert statements and check it in to source control. The idea is that other team members should be able to create the same database, run the created insert scripts and have the same data to test and develop on. Is there a good tool out there to do this? I'm not looking for a tool to generate data as discussed here.
EMS DB Extract for SQL Server ( http://www.sqlmanager.net/en/products/mssql/extract ) seems to do what you want, and it seems to be free. Hope this helps, Robin
Select existing data from database to create test data I have a SqlServer database that I've manually filled with some test data. Now I'd like to extract this test data as insert statements and check it in to source control. The idea is that other team members should be able to create the same database, run the created insert scripts and have the same data to test and develop on. Is there a good tool out there to do this? I'm not looking for a tool to generate data as discussed here.
TITLE: Select existing data from database to create test data QUESTION: I have a SqlServer database that I've manually filled with some test data. Now I'd like to extract this test data as insert statements and check it in to source control. The idea is that other team members should be able to create the same database, run the created insert scripts and have the same data to test and develop on. Is there a good tool out there to do this? I'm not looking for a tool to generate data as discussed here. ANSWER: EMS DB Extract for SQL Server ( http://www.sqlmanager.net/en/products/mssql/extract ) seems to do what you want, and it seems to be free. Hope this helps, Robin
[ "sql-server", "database" ]
3
1
892
4
0
2008-08-23T14:01:32.413000
2008-08-23T14:04:05.917000
24,262
24,274
About File permissions in C#
While creating a file synchronization program in C# I tried to make a method copy in LocalFileItem class that uses System.IO.File.Copy(destination.Path, Path, true) method where Path is a string. After executing this code with destination. Path = "C:\\Test2" and this.Path = "C:\\Test\\F1.txt" I get an exception saying that I do not have the required file permissions to do this operation on C:\Test, but C:\Test is owned by myself (the current user). Does anybody knows what is going on, or how to get around this? Here is the original code complete. using System; using System.Collections.Generic; using System.Text; using System.IO; namespace Diones.Util.IO { /// /// An object representation of a file or directory. /// public abstract class FileItem: IComparable { protected String path; public String Path { set { this.path = value; } get { return this.path; } } protected bool isDirectory; public bool IsDirectory { set { this.isDirectory = value; } get { return this.isDirectory; } } /// /// Delete this fileItem. /// public abstract void delete(); /// /// Delete this directory and all of its elements. /// protected abstract void deleteRecursive(); /// /// Copy this fileItem to the destination directory. /// public abstract void copy(FileItem fileD); /// /// Copy this directory and all of its elements /// to the destination directory. /// protected abstract void copyRecursive(FileItem fileD); /// /// Creates a FileItem from a string path. /// /// public FileItem(String path) { Path = path; if (path.EndsWith("\\") || path.EndsWith("/")) IsDirectory = true; else IsDirectory = false; } /// /// Creates a FileItem from a FileSource directory. /// /// public FileItem(FileSource directory) { Path = directory.Path; } public override String ToString() { return Path; } public abstract int CompareTo(object b); } /// /// A file or directory on the hard disk /// public class LocalFileItem: FileItem { public override void delete() { if (!IsDirectory) File.Delete(this.Path); else deleteRecursive(); } protected override void deleteRecursive() { Directory.Delete(Path, true); } public override void copy(FileItem destination) { if (!IsDirectory) File.Copy(destination.Path, Path, true); else copyRecursive(destination); } protected override void copyRecursive(FileItem destination) { Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory( Path, destination.Path, true); } /// /// Create's a LocalFileItem from a string path /// /// public LocalFileItem(String path): base(path) { } /// /// Creates a LocalFileItem from a FileSource path /// /// public LocalFileItem(FileSource path): base(path) { } public override int CompareTo(object obj) { if (obj is FileItem) { FileItem fi = (FileItem)obj; if (File.GetCreationTime(this.Path).CompareTo (File.GetCreationTime(fi.Path)) > 0) return 1; else if (File.GetCreationTime(this.Path).CompareTo (File.GetCreationTime(fi.Path)) < 0) return -1; else { if (File.GetLastWriteTime(this.Path).CompareTo (File.GetLastWriteTime(fi.Path)) < 0) return -1; else if (File.GetLastWriteTime(this.Path).CompareTo (File.GetLastWriteTime(fi.Path)) > 0) return 1; else return 0; } } else throw new ArgumentException("obj isn't a FileItem"); } } }
It seems you have misplaced the parameters in File.Copy(), it should be File.Copy(string source, string destination). Also is "C:\Test2" a directory? You can't copy file to a directory. Use something like that instead: File.Copy( sourceFile, Path.Combine(destinationDir,Path.GetFileName(sourceFile)) );
About File permissions in C# While creating a file synchronization program in C# I tried to make a method copy in LocalFileItem class that uses System.IO.File.Copy(destination.Path, Path, true) method where Path is a string. After executing this code with destination. Path = "C:\\Test2" and this.Path = "C:\\Test\\F1.txt" I get an exception saying that I do not have the required file permissions to do this operation on C:\Test, but C:\Test is owned by myself (the current user). Does anybody knows what is going on, or how to get around this? Here is the original code complete. using System; using System.Collections.Generic; using System.Text; using System.IO; namespace Diones.Util.IO { /// /// An object representation of a file or directory. /// public abstract class FileItem: IComparable { protected String path; public String Path { set { this.path = value; } get { return this.path; } } protected bool isDirectory; public bool IsDirectory { set { this.isDirectory = value; } get { return this.isDirectory; } } /// /// Delete this fileItem. /// public abstract void delete(); /// /// Delete this directory and all of its elements. /// protected abstract void deleteRecursive(); /// /// Copy this fileItem to the destination directory. /// public abstract void copy(FileItem fileD); /// /// Copy this directory and all of its elements /// to the destination directory. /// protected abstract void copyRecursive(FileItem fileD); /// /// Creates a FileItem from a string path. /// /// public FileItem(String path) { Path = path; if (path.EndsWith("\\") || path.EndsWith("/")) IsDirectory = true; else IsDirectory = false; } /// /// Creates a FileItem from a FileSource directory. /// /// public FileItem(FileSource directory) { Path = directory.Path; } public override String ToString() { return Path; } public abstract int CompareTo(object b); } /// /// A file or directory on the hard disk /// public class LocalFileItem: FileItem { public override void delete() { if (!IsDirectory) File.Delete(this.Path); else deleteRecursive(); } protected override void deleteRecursive() { Directory.Delete(Path, true); } public override void copy(FileItem destination) { if (!IsDirectory) File.Copy(destination.Path, Path, true); else copyRecursive(destination); } protected override void copyRecursive(FileItem destination) { Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory( Path, destination.Path, true); } /// /// Create's a LocalFileItem from a string path /// /// public LocalFileItem(String path): base(path) { } /// /// Creates a LocalFileItem from a FileSource path /// /// public LocalFileItem(FileSource path): base(path) { } public override int CompareTo(object obj) { if (obj is FileItem) { FileItem fi = (FileItem)obj; if (File.GetCreationTime(this.Path).CompareTo (File.GetCreationTime(fi.Path)) > 0) return 1; else if (File.GetCreationTime(this.Path).CompareTo (File.GetCreationTime(fi.Path)) < 0) return -1; else { if (File.GetLastWriteTime(this.Path).CompareTo (File.GetLastWriteTime(fi.Path)) < 0) return -1; else if (File.GetLastWriteTime(this.Path).CompareTo (File.GetLastWriteTime(fi.Path)) > 0) return 1; else return 0; } } else throw new ArgumentException("obj isn't a FileItem"); } } }
TITLE: About File permissions in C# QUESTION: While creating a file synchronization program in C# I tried to make a method copy in LocalFileItem class that uses System.IO.File.Copy(destination.Path, Path, true) method where Path is a string. After executing this code with destination. Path = "C:\\Test2" and this.Path = "C:\\Test\\F1.txt" I get an exception saying that I do not have the required file permissions to do this operation on C:\Test, but C:\Test is owned by myself (the current user). Does anybody knows what is going on, or how to get around this? Here is the original code complete. using System; using System.Collections.Generic; using System.Text; using System.IO; namespace Diones.Util.IO { /// /// An object representation of a file or directory. /// public abstract class FileItem: IComparable { protected String path; public String Path { set { this.path = value; } get { return this.path; } } protected bool isDirectory; public bool IsDirectory { set { this.isDirectory = value; } get { return this.isDirectory; } } /// /// Delete this fileItem. /// public abstract void delete(); /// /// Delete this directory and all of its elements. /// protected abstract void deleteRecursive(); /// /// Copy this fileItem to the destination directory. /// public abstract void copy(FileItem fileD); /// /// Copy this directory and all of its elements /// to the destination directory. /// protected abstract void copyRecursive(FileItem fileD); /// /// Creates a FileItem from a string path. /// /// public FileItem(String path) { Path = path; if (path.EndsWith("\\") || path.EndsWith("/")) IsDirectory = true; else IsDirectory = false; } /// /// Creates a FileItem from a FileSource directory. /// /// public FileItem(FileSource directory) { Path = directory.Path; } public override String ToString() { return Path; } public abstract int CompareTo(object b); } /// /// A file or directory on the hard disk /// public class LocalFileItem: FileItem { public override void delete() { if (!IsDirectory) File.Delete(this.Path); else deleteRecursive(); } protected override void deleteRecursive() { Directory.Delete(Path, true); } public override void copy(FileItem destination) { if (!IsDirectory) File.Copy(destination.Path, Path, true); else copyRecursive(destination); } protected override void copyRecursive(FileItem destination) { Microsoft.VisualBasic.FileIO.FileSystem.CopyDirectory( Path, destination.Path, true); } /// /// Create's a LocalFileItem from a string path /// /// public LocalFileItem(String path): base(path) { } /// /// Creates a LocalFileItem from a FileSource path /// /// public LocalFileItem(FileSource path): base(path) { } public override int CompareTo(object obj) { if (obj is FileItem) { FileItem fi = (FileItem)obj; if (File.GetCreationTime(this.Path).CompareTo (File.GetCreationTime(fi.Path)) > 0) return 1; else if (File.GetCreationTime(this.Path).CompareTo (File.GetCreationTime(fi.Path)) < 0) return -1; else { if (File.GetLastWriteTime(this.Path).CompareTo (File.GetLastWriteTime(fi.Path)) < 0) return -1; else if (File.GetLastWriteTime(this.Path).CompareTo (File.GetLastWriteTime(fi.Path)) > 0) return 1; else return 0; } } else throw new ArgumentException("obj isn't a FileItem"); } } } ANSWER: It seems you have misplaced the parameters in File.Copy(), it should be File.Copy(string source, string destination). Also is "C:\Test2" a directory? You can't copy file to a directory. Use something like that instead: File.Copy( sourceFile, Path.Combine(destinationDir,Path.GetFileName(sourceFile)) );
[ "c#", "file", "copy" ]
7
4
4,539
3
0
2008-08-23T14:31:21.780000
2008-08-23T14:47:54.207000
24,270
25,061
What's the point of OOP?
As far as I can tell, in spite of the countless millions or billions spent on OOP education, languages, and tools, OOP has not improved developer productivity or software reliability, nor has it reduced development costs. Few people use OOP in any rigorous sense (few people adhere to or understand principles such as LSP); there seems to be little uniformity or consistency to the approaches that people take to modelling problem domains. All too often, the class is used simply for its syntactic sugar; it puts the functions for a record type into their own little namespace. I've written a large amount of code for a wide variety of applications. Although there have been places where true substitutable subtyping played a valuable role in the application, these have been pretty exceptional. In general, though much lip service is given to talk of "re-use" the reality is that unless a piece of code does exactly what you want it to do, there's very little cost-effective "re-use". It's extremely hard to design classes to be extensible in the right way, and so the cost of extension is normally so great that "re-use" simply isn't worthwhile. In many regards, this doesn't surprise me. The real world isn't "OO", and the idea implicit in OO--that we can model things with some class taxonomy--seems to me very fundamentally flawed (I can sit on a table, a tree stump, a car bonnet, someone's lap--but not one of those is-a chair). Even if we move to more abstract domains, OO modelling is often difficult, counterintuitive, and ultimately unhelpful (consider the classic examples of circles/ellipses or squares/rectangles). So what am I missing here? Where's the value of OOP, and why has all the time and money failed to make software any better?
There's no empirical evidence that suggests that object orientation is a more natural way for people to think about the world. There's some work in the field of psychology of programming that shows that OO is not somehow more fitting than other approaches. Object-oriented representations do not appear to be universally more usable or less usable. It is not enough to simply adopt OO methods and require developers to use such methods, because that might have a negative impact on developer productivity, as well as the quality of systems developed. Which is from "On the Usability of OO Representations" from Communications of the ACM Oct. 2000. The articles mainly compares OO against theprocess-oriented approach. There's lots of study of how people who work with the OO method "think" (Int. J. of Human-Computer Studies 2001, issue 54, or Human-Computer Interaction 1995, vol. 10 has a whole theme on OO studies), and from what I read, there's nothing to indicate some kind of naturalness to the OO approach that makes it better suited than a more traditional procedural approach.
What's the point of OOP? As far as I can tell, in spite of the countless millions or billions spent on OOP education, languages, and tools, OOP has not improved developer productivity or software reliability, nor has it reduced development costs. Few people use OOP in any rigorous sense (few people adhere to or understand principles such as LSP); there seems to be little uniformity or consistency to the approaches that people take to modelling problem domains. All too often, the class is used simply for its syntactic sugar; it puts the functions for a record type into their own little namespace. I've written a large amount of code for a wide variety of applications. Although there have been places where true substitutable subtyping played a valuable role in the application, these have been pretty exceptional. In general, though much lip service is given to talk of "re-use" the reality is that unless a piece of code does exactly what you want it to do, there's very little cost-effective "re-use". It's extremely hard to design classes to be extensible in the right way, and so the cost of extension is normally so great that "re-use" simply isn't worthwhile. In many regards, this doesn't surprise me. The real world isn't "OO", and the idea implicit in OO--that we can model things with some class taxonomy--seems to me very fundamentally flawed (I can sit on a table, a tree stump, a car bonnet, someone's lap--but not one of those is-a chair). Even if we move to more abstract domains, OO modelling is often difficult, counterintuitive, and ultimately unhelpful (consider the classic examples of circles/ellipses or squares/rectangles). So what am I missing here? Where's the value of OOP, and why has all the time and money failed to make software any better?
TITLE: What's the point of OOP? QUESTION: As far as I can tell, in spite of the countless millions or billions spent on OOP education, languages, and tools, OOP has not improved developer productivity or software reliability, nor has it reduced development costs. Few people use OOP in any rigorous sense (few people adhere to or understand principles such as LSP); there seems to be little uniformity or consistency to the approaches that people take to modelling problem domains. All too often, the class is used simply for its syntactic sugar; it puts the functions for a record type into their own little namespace. I've written a large amount of code for a wide variety of applications. Although there have been places where true substitutable subtyping played a valuable role in the application, these have been pretty exceptional. In general, though much lip service is given to talk of "re-use" the reality is that unless a piece of code does exactly what you want it to do, there's very little cost-effective "re-use". It's extremely hard to design classes to be extensible in the right way, and so the cost of extension is normally so great that "re-use" simply isn't worthwhile. In many regards, this doesn't surprise me. The real world isn't "OO", and the idea implicit in OO--that we can model things with some class taxonomy--seems to me very fundamentally flawed (I can sit on a table, a tree stump, a car bonnet, someone's lap--but not one of those is-a chair). Even if we move to more abstract domains, OO modelling is often difficult, counterintuitive, and ultimately unhelpful (consider the classic examples of circles/ellipses or squares/rectangles). So what am I missing here? Where's the value of OOP, and why has all the time and money failed to make software any better? ANSWER: There's no empirical evidence that suggests that object orientation is a more natural way for people to think about the world. There's some work in the field of psychology of programming that shows that OO is not somehow more fitting than other approaches. Object-oriented representations do not appear to be universally more usable or less usable. It is not enough to simply adopt OO methods and require developers to use such methods, because that might have a negative impact on developer productivity, as well as the quality of systems developed. Which is from "On the Usability of OO Representations" from Communications of the ACM Oct. 2000. The articles mainly compares OO against theprocess-oriented approach. There's lots of study of how people who work with the OO method "think" (Int. J. of Human-Computer Studies 2001, issue 54, or Human-Computer Interaction 1995, vol. 10 has a whole theme on OO studies), and from what I read, there's nothing to indicate some kind of naturalness to the OO approach that makes it better suited than a more traditional procedural approach.
[ "language-agnostic", "oop" ]
126
24
31,089
45
0
2008-08-23T14:40:28.687000
2008-08-24T14:03:42.790000
24,279
24,294
Functional programming and non-functional programming
In my second year of University we were "taught" Haskell, I know almost nothing about it and even less about functional programming. What is functional programming, why and/xor where would I want to use it instead of non-functional programming and am I correct in thinking that C is a non-functional programming language?
One key feature in a functional language is the concept of first-class functions. The idea is that you can pass functions as parameters to other functions and return them as values. Functional programming involves writing code that does not change state. The primary reason for doing so is so that successive calls to a function will yield the same result. You can write functional code in any language that supports first-class functions, but there are some languages, like Haskell, which do not allow you to change state. In fact, you're not supposed to make any side effects (like printing out text) at all - which sounds like it could be completely useless. Haskell instead employs a different approach to IO: monads. These are objects that contain the desired IO operation to be executed by your interpreter's toplevel. At any other level they are simply objects in the system. What advantages does functional programming provide? Functional programming allows coding with fewer potentials for bugs because each component is completely isolated. Also, using recursion and first-class functions allows for simple proofs of correctness which typically mirror the structure of the code.
Functional programming and non-functional programming In my second year of University we were "taught" Haskell, I know almost nothing about it and even less about functional programming. What is functional programming, why and/xor where would I want to use it instead of non-functional programming and am I correct in thinking that C is a non-functional programming language?
TITLE: Functional programming and non-functional programming QUESTION: In my second year of University we were "taught" Haskell, I know almost nothing about it and even less about functional programming. What is functional programming, why and/xor where would I want to use it instead of non-functional programming and am I correct in thinking that C is a non-functional programming language? ANSWER: One key feature in a functional language is the concept of first-class functions. The idea is that you can pass functions as parameters to other functions and return them as values. Functional programming involves writing code that does not change state. The primary reason for doing so is so that successive calls to a function will yield the same result. You can write functional code in any language that supports first-class functions, but there are some languages, like Haskell, which do not allow you to change state. In fact, you're not supposed to make any side effects (like printing out text) at all - which sounds like it could be completely useless. Haskell instead employs a different approach to IO: monads. These are objects that contain the desired IO operation to be executed by your interpreter's toplevel. At any other level they are simply objects in the system. What advantages does functional programming provide? Functional programming allows coding with fewer potentials for bugs because each component is completely isolated. Also, using recursion and first-class functions allows for simple proofs of correctness which typically mirror the structure of the code.
[ "functional-programming", "paradigms", "glossary" ]
74
94
34,309
8
0
2008-08-23T14:58:11.623000
2008-08-23T15:19:17.390000
24,298
741,170
Best Solution For Authentication in Ruby on Rails
I'm looking for a pre-built solution I can use in my RoR application. I'm ideally looking for something similar to the ASP.NET Forms authentication that provides email validation, sign-up controls, and allows users to reset their passwords. Oh yeah, and easily allows me to pull the user that is currently logged into the application. I've started to look into the already written pieces, but I've found it to be really confusing. I've looked at LoginGenerator, RestfulAuthentication, SaltedLoginGenerator, but there doesn't seem to be one place that has great tutorials or provide a comparison of them. If there's a site I just haven't discovered yet, or if there is a de-facto standard that most people use, I'd appreciate the helping hand.
AuthLogic appears to be the new kid on the block and seems to be the next evolution of restful_authentication, easier to use, etc http://github.com/binarylogic/authlogic/tree/master Edit: now that Rails 3 is out, Devise seems to be the new, new kid on the block https://github.com/plataformatec/devise or I have been rolling my own authentication now with the has_secure_password built in to Rails http://railscasts.com/episodes/250-authentication-from-scratch-revised Side note: Ruby Toolbox is a great site for finding the current best solution in various categories (based on the number of GitHub watchers): http://ruby-toolbox.com/categories/rails_authentication.html
Best Solution For Authentication in Ruby on Rails I'm looking for a pre-built solution I can use in my RoR application. I'm ideally looking for something similar to the ASP.NET Forms authentication that provides email validation, sign-up controls, and allows users to reset their passwords. Oh yeah, and easily allows me to pull the user that is currently logged into the application. I've started to look into the already written pieces, but I've found it to be really confusing. I've looked at LoginGenerator, RestfulAuthentication, SaltedLoginGenerator, but there doesn't seem to be one place that has great tutorials or provide a comparison of them. If there's a site I just haven't discovered yet, or if there is a de-facto standard that most people use, I'd appreciate the helping hand.
TITLE: Best Solution For Authentication in Ruby on Rails QUESTION: I'm looking for a pre-built solution I can use in my RoR application. I'm ideally looking for something similar to the ASP.NET Forms authentication that provides email validation, sign-up controls, and allows users to reset their passwords. Oh yeah, and easily allows me to pull the user that is currently logged into the application. I've started to look into the already written pieces, but I've found it to be really confusing. I've looked at LoginGenerator, RestfulAuthentication, SaltedLoginGenerator, but there doesn't seem to be one place that has great tutorials or provide a comparison of them. If there's a site I just haven't discovered yet, or if there is a de-facto standard that most people use, I'd appreciate the helping hand. ANSWER: AuthLogic appears to be the new kid on the block and seems to be the next evolution of restful_authentication, easier to use, etc http://github.com/binarylogic/authlogic/tree/master Edit: now that Rails 3 is out, Devise seems to be the new, new kid on the block https://github.com/plataformatec/devise or I have been rolling my own authentication now with the has_secure_password built in to Rails http://railscasts.com/episodes/250-authentication-from-scratch-revised Side note: Ruby Toolbox is a great site for finding the current best solution in various categories (based on the number of GitHub watchers): http://ruby-toolbox.com/categories/rails_authentication.html
[ "ruby-on-rails", "ruby", "authentication" ]
84
84
56,537
12
0
2008-08-23T15:27:11.647000
2009-04-12T02:08:57.777000
24,310
844,821
Programming a simple IRC (Internet-Relay-Chat) Client
I started using IRC at a young age, and I have always been fascinated with it. As a language exercise, I was thinking about programming a simple IRC client in Ruby with Shoes as a graphical front-end. My question to you, kind-sirs, what do I need to become familiar with to start on this great adventure (besides shoes and Ruby of course)? I imagine there is some-sort of specification on IRC Protocol. Any pointers?
An earlier post mentioned RFC1459. While it is a very good introduction to IRC, it has actually been superseded by RFCs 2810-2813. Here is a more complete list of documentation you need to program anything IRC-related: RFC1459 (original RFC; superseded, but still useful) RFC2810 (IRC architecture) RFC2811 (IRC channel management) RFC2812 (IRC client protocol) RFC2813 (IRC server protocol) CTCP specification DCC specification Updated CTCP specification (not all clients support this) ISupport (response code 005) draft (almost all servers support this nowadays) Client capabilities (CAP command) draft (supported by some servers/clients) IRCv3 standards and proposals (the future features of IRC, some of which are already widely supported)
Programming a simple IRC (Internet-Relay-Chat) Client I started using IRC at a young age, and I have always been fascinated with it. As a language exercise, I was thinking about programming a simple IRC client in Ruby with Shoes as a graphical front-end. My question to you, kind-sirs, what do I need to become familiar with to start on this great adventure (besides shoes and Ruby of course)? I imagine there is some-sort of specification on IRC Protocol. Any pointers?
TITLE: Programming a simple IRC (Internet-Relay-Chat) Client QUESTION: I started using IRC at a young age, and I have always been fascinated with it. As a language exercise, I was thinking about programming a simple IRC client in Ruby with Shoes as a graphical front-end. My question to you, kind-sirs, what do I need to become familiar with to start on this great adventure (besides shoes and Ruby of course)? I imagine there is some-sort of specification on IRC Protocol. Any pointers? ANSWER: An earlier post mentioned RFC1459. While it is a very good introduction to IRC, it has actually been superseded by RFCs 2810-2813. Here is a more complete list of documentation you need to program anything IRC-related: RFC1459 (original RFC; superseded, but still useful) RFC2810 (IRC architecture) RFC2811 (IRC channel management) RFC2812 (IRC client protocol) RFC2813 (IRC server protocol) CTCP specification DCC specification Updated CTCP specification (not all clients support this) ISupport (response code 005) draft (almost all servers support this nowadays) Client capabilities (CAP command) draft (supported by some servers/clients) IRCv3 standards and proposals (the future features of IRC, some of which are already widely supported)
[ "ruby", "shoes", "irc" ]
11
31
13,187
5
0
2008-08-23T15:49:06.960000
2009-05-10T06:22:26.690000
24,408
24,841
Database query representation impersonating file on Windows share?
Is there any way to have something that looks just like a file on a Windows file share, but is really a resource served up over HTTP? For context, I'm working with an old app that can only deal with files on a Windows file share, I want to create a simple HTTP-based service to serve the content of the files dynamically to pick up real time changes to the underlying data on request.
WebDAV (basically) takes an existing directory, and shares it over HTTP - which sounds like the opposite of what you want. You need something that speaks SMB/CIFS on one end, and your own code on the other. The easiest way to do that is with a userspace file system. To that end, here's a couple of links: WinFUSE, which is kind of a barebones CIFS/SMB server that can host your own filesystem. I've done a couple of small samples with it - and the docs are terrible, but it more or less worked. Dokan, a userspace file driver with.NET bindings. I haven't used this one, but it looks promising. It has both.NET and Ruby bindings, so you should be able to get a POC up pretty quickly. Callback File System - yet another userspace file system. Again, I have no experience with this one. A Linux box with SAMBA and FUSE that shares the drive out to the Windows box.
Database query representation impersonating file on Windows share? Is there any way to have something that looks just like a file on a Windows file share, but is really a resource served up over HTTP? For context, I'm working with an old app that can only deal with files on a Windows file share, I want to create a simple HTTP-based service to serve the content of the files dynamically to pick up real time changes to the underlying data on request.
TITLE: Database query representation impersonating file on Windows share? QUESTION: Is there any way to have something that looks just like a file on a Windows file share, but is really a resource served up over HTTP? For context, I'm working with an old app that can only deal with files on a Windows file share, I want to create a simple HTTP-based service to serve the content of the files dynamically to pick up real time changes to the underlying data on request. ANSWER: WebDAV (basically) takes an existing directory, and shares it over HTTP - which sounds like the opposite of what you want. You need something that speaks SMB/CIFS on one end, and your own code on the other. The easiest way to do that is with a userspace file system. To that end, here's a couple of links: WinFUSE, which is kind of a barebones CIFS/SMB server that can host your own filesystem. I've done a couple of small samples with it - and the docs are terrible, but it more or less worked. Dokan, a userspace file driver with.NET bindings. I haven't used this one, but it looks promising. It has both.NET and Ruby bindings, so you should be able to get a POC up pretty quickly. Callback File System - yet another userspace file system. Again, I have no experience with this one. A Linux box with SAMBA and FUSE that shares the drive out to the Windows box.
[ "file", "http", "webdav" ]
3
2
350
3
0
2008-08-23T17:24:48.760000
2008-08-24T04:31:02.900000
24,414
25,826
Can I capture Windows Mobile PIE keyboard events?
Anyone know of a way to capture keyboard events (keyup / keydown) in Portable IE under Window mobile? I noticed that key events are not supported in JS, and would like to come up with a solution that works without any client side additions.
Without any client side additions? As per IEMobile Team Blog, the only way for that would be wait for the next release:(
Can I capture Windows Mobile PIE keyboard events? Anyone know of a way to capture keyboard events (keyup / keydown) in Portable IE under Window mobile? I noticed that key events are not supported in JS, and would like to come up with a solution that works without any client side additions.
TITLE: Can I capture Windows Mobile PIE keyboard events? QUESTION: Anyone know of a way to capture keyboard events (keyup / keydown) in Portable IE under Window mobile? I noticed that key events are not supported in JS, and would like to come up with a solution that works without any client side additions. ANSWER: Without any client side additions? As per IEMobile Team Blog, the only way for that would be wait for the next release:(
[ "internet-explorer", "windows-mobile", "key-events" ]
1
1
858
1
0
2008-08-23T17:30:23.020000
2008-08-25T09:46:43.663000
24,439
24,687
IE 7+ Favorites
Is it possible to develop a plug-in for Internet Explorer that can replace the existing favorites functionality?
Absolutely, however, it does depend somewhat on what you expect "replacing" to mean. You can develop an extension to provide a new set of menus or dropdown toolbar of some kind like the Google Bookmarks toolbar for example, or like the Delicious toolbar & sidebar. These IMO are much better designs for managing bookmarks than the built-in IE menu anyway. However, you could build a top level menu structure that worked the exact same way as the IE favorites menu if you wanted as well. There are many libraries out there that you could use to even handle the IE integration as well. I don't know what language you develop in, but some example libraries to make the IE addons a breeze are (for.NET, there are plenty others out there for other languages as well): http://www.add-in-express.com/programming-internet-explorer/ http://www.ssware.com/ezshell/ezshell.htm also some articles to create your own from scratch: http://www.codeproject.com/kb/applications/codeprojectsearchbar.aspx http://www.codeproject.com/KB/atl/rbdeskband.aspx That should get you going.
IE 7+ Favorites Is it possible to develop a plug-in for Internet Explorer that can replace the existing favorites functionality?
TITLE: IE 7+ Favorites QUESTION: Is it possible to develop a plug-in for Internet Explorer that can replace the existing favorites functionality? ANSWER: Absolutely, however, it does depend somewhat on what you expect "replacing" to mean. You can develop an extension to provide a new set of menus or dropdown toolbar of some kind like the Google Bookmarks toolbar for example, or like the Delicious toolbar & sidebar. These IMO are much better designs for managing bookmarks than the built-in IE menu anyway. However, you could build a top level menu structure that worked the exact same way as the IE favorites menu if you wanted as well. There are many libraries out there that you could use to even handle the IE integration as well. I don't know what language you develop in, but some example libraries to make the IE addons a breeze are (for.NET, there are plenty others out there for other languages as well): http://www.add-in-express.com/programming-internet-explorer/ http://www.ssware.com/ezshell/ezshell.htm also some articles to create your own from scratch: http://www.codeproject.com/kb/applications/codeprojectsearchbar.aspx http://www.codeproject.com/KB/atl/rbdeskband.aspx That should get you going.
[ "internet-explorer", "bookmarks", "favorites" ]
3
5
220
1
0
2008-08-23T17:54:12.260000
2008-08-23T22:59:47.003000
24,451
24,476
Are there any legitimate use-cases for "goto" in a language that supports loops and functions?
I've long been under the impression that goto should never be used if possible. However, while perusing libavcodec (which is written in C) the other day, I was surprised to notice multiple uses of it. Is it ever advantageous to use goto in a language that supports loops and functions? If so, why? Please provide a concrete example that clearly justifies the use of a goto.
There are a few reasons for using the "goto" statement that I'm aware of (some have spoken to this already): Cleanly exiting a function Often in a function, you may allocate resources and need to exit in multiple places. Programmers can simplify their code by putting the resource cleanup code at the end of the function, and all "exit points" of the function would goto the cleanup label. This way, you don't have to write cleanup code at every "exit point" of the function. Exiting nested loops If you're in a nested loop and need to break out of all loops, a goto can make this much cleaner and simpler than break statements and if-checks. Low-level performance improvements This is only valid in perf-critical code, but goto statements execute very quickly and can give you a boost when moving through a function. This is a double-edged sword, however, because a compiler typically cannot optimize code that contains gotos. Note that in all these examples, gotos are restricted to the scope of a single function.
Are there any legitimate use-cases for "goto" in a language that supports loops and functions? I've long been under the impression that goto should never be used if possible. However, while perusing libavcodec (which is written in C) the other day, I was surprised to notice multiple uses of it. Is it ever advantageous to use goto in a language that supports loops and functions? If so, why? Please provide a concrete example that clearly justifies the use of a goto.
TITLE: Are there any legitimate use-cases for "goto" in a language that supports loops and functions? QUESTION: I've long been under the impression that goto should never be used if possible. However, while perusing libavcodec (which is written in C) the other day, I was surprised to notice multiple uses of it. Is it ever advantageous to use goto in a language that supports loops and functions? If so, why? Please provide a concrete example that clearly justifies the use of a goto. ANSWER: There are a few reasons for using the "goto" statement that I'm aware of (some have spoken to this already): Cleanly exiting a function Often in a function, you may allocate resources and need to exit in multiple places. Programmers can simplify their code by putting the resource cleanup code at the end of the function, and all "exit points" of the function would goto the cleanup label. This way, you don't have to write cleanup code at every "exit point" of the function. Exiting nested loops If you're in a nested loop and need to break out of all loops, a goto can make this much cleaner and simpler than break statements and if-checks. Low-level performance improvements This is only valid in perf-critical code, but goto statements execute very quickly and can give you a boost when moving through a function. This is a double-edged sword, however, because a compiler typically cannot optimize code that contains gotos. Note that in all these examples, gotos are restricted to the scope of a single function.
[ "language-agnostic", "goto" ]
226
282
58,928
25
0
2008-08-23T18:18:04.933000
2008-08-23T18:42:33.003000
24,456
24,517
Embedding IPTC image data with PHP GD
I'm trying to embed a IPTC data onto a JPEG image using iptcembed() but am having a bit of trouble. I have verified it is in the end product: // Embed the IPTC data $content = iptcembed($data, $path); // Verify IPTC data is in the end image $iptc = iptcparse($content); var_dump($iptc); Which returns the tags entered. However when I save and reload the image the tags are non existant: // Save the edited image $im = imagecreatefromstring($content); imagejpeg($im, 'phplogo-edited.jpg'); imagedestroy($im); // Get data from the saved image $image = getimagesize('./phplogo-edited.jpg'); // If APP13/IPTC data exists output it if(isset($image['APP13'])) { $iptc = iptcparse($image['APP13']); print_r($iptc); } else { // Otherwise tell us what the image *does* contain // SO: This is what's happening print_r($image); } So why aren't the tags in the saved image? The PHP source is avaliable here, and the respective outputs are: Image output Data output
getimagesize has an optional second parameter Imageinfo which contains the info you need. From the manual: This optional parameter allows you to extract some extended information from the image file. Currently, this will return the different JPG APP markers as an associative array. Some programs use these APP markers to embed text information in images. A very common one is to embed » IPTC information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable. so you could use it like this: Hope this helps...
Embedding IPTC image data with PHP GD I'm trying to embed a IPTC data onto a JPEG image using iptcembed() but am having a bit of trouble. I have verified it is in the end product: // Embed the IPTC data $content = iptcembed($data, $path); // Verify IPTC data is in the end image $iptc = iptcparse($content); var_dump($iptc); Which returns the tags entered. However when I save and reload the image the tags are non existant: // Save the edited image $im = imagecreatefromstring($content); imagejpeg($im, 'phplogo-edited.jpg'); imagedestroy($im); // Get data from the saved image $image = getimagesize('./phplogo-edited.jpg'); // If APP13/IPTC data exists output it if(isset($image['APP13'])) { $iptc = iptcparse($image['APP13']); print_r($iptc); } else { // Otherwise tell us what the image *does* contain // SO: This is what's happening print_r($image); } So why aren't the tags in the saved image? The PHP source is avaliable here, and the respective outputs are: Image output Data output
TITLE: Embedding IPTC image data with PHP GD QUESTION: I'm trying to embed a IPTC data onto a JPEG image using iptcembed() but am having a bit of trouble. I have verified it is in the end product: // Embed the IPTC data $content = iptcembed($data, $path); // Verify IPTC data is in the end image $iptc = iptcparse($content); var_dump($iptc); Which returns the tags entered. However when I save and reload the image the tags are non existant: // Save the edited image $im = imagecreatefromstring($content); imagejpeg($im, 'phplogo-edited.jpg'); imagedestroy($im); // Get data from the saved image $image = getimagesize('./phplogo-edited.jpg'); // If APP13/IPTC data exists output it if(isset($image['APP13'])) { $iptc = iptcparse($image['APP13']); print_r($iptc); } else { // Otherwise tell us what the image *does* contain // SO: This is what's happening print_r($image); } So why aren't the tags in the saved image? The PHP source is avaliable here, and the respective outputs are: Image output Data output ANSWER: getimagesize has an optional second parameter Imageinfo which contains the info you need. From the manual: This optional parameter allows you to extract some extended information from the image file. Currently, this will return the different JPG APP markers as an associative array. Some programs use these APP markers to embed text information in images. A very common one is to embed » IPTC information in the APP13 marker. You can use the iptcparse() function to parse the binary APP13 marker into something readable. so you could use it like this: Hope this helps...
[ "php", "gd", "iptc" ]
2
3
3,086
1
0
2008-08-23T18:24:21.643000
2008-08-23T19:19:46.767000
24,467
26,282
(N)Hibernate Auto-Join
I'm developing a web- application using NHibernate. Can you tell me how to write a NHibernate Query for the following SQL query: SELECT v1.Id FROM VIEW v1 LEFT JOIN VIEW v2 ON v1.SourceView = v2.Id ORDER BY v1.Position It's basically a auto-join but I don't know how to write this in Nhibernate. Lets say the property names are the same as the table column names.
You could just perform the select on the original entity and make the association between the two objects "lazy = false". As long as the entities are mapped then both will be returned and you wont get a lazyloadingexception when trying to access the object. If you don't want to map "lazy=false" then you can also iterate through the results and perform some sort of operation (such as asking if it is null; if(v1.AssocatedObject == null){}) to ensure the data is loaded while the session is open. Update: I think there is actually a better one than that in, NHibernateUtil.Initialise() that can initialise a collection without having to wander through it.
(N)Hibernate Auto-Join I'm developing a web- application using NHibernate. Can you tell me how to write a NHibernate Query for the following SQL query: SELECT v1.Id FROM VIEW v1 LEFT JOIN VIEW v2 ON v1.SourceView = v2.Id ORDER BY v1.Position It's basically a auto-join but I don't know how to write this in Nhibernate. Lets say the property names are the same as the table column names.
TITLE: (N)Hibernate Auto-Join QUESTION: I'm developing a web- application using NHibernate. Can you tell me how to write a NHibernate Query for the following SQL query: SELECT v1.Id FROM VIEW v1 LEFT JOIN VIEW v2 ON v1.SourceView = v2.Id ORDER BY v1.Position It's basically a auto-join but I don't know how to write this in Nhibernate. Lets say the property names are the same as the table column names. ANSWER: You could just perform the select on the original entity and make the association between the two objects "lazy = false". As long as the entities are mapped then both will be returned and you wont get a lazyloadingexception when trying to access the object. If you don't want to map "lazy=false" then you can also iterate through the results and perform some sort of operation (such as asking if it is null; if(v1.AssocatedObject == null){}) to ensure the data is loaded while the session is open. Update: I think there is actually a better one than that in, NHibernateUtil.Initialise() that can initialise a collection without having to wander through it.
[ "sql", "nhibernate", "orm" ]
1
1
674
1
0
2008-08-23T18:31:02.187000
2008-08-25T15:45:33.647000
24,468
24,477
Running "partially trusted" .NET assemblies from a network share
When I try to run a.NET assembly ( boo.exe ) from a network share (mapped to a drive), it fails since it's only partially trusted: Unhandled Exception: System.Security.SecurityException: That assembly does not allow partially trusted callers. at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed) at BooCommandLine..ctor() at Program..ctor() at ProgramModule.Main(String[] argv) The action that failed was: LinkDemand The assembly or AppDomain that failed was: boo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=32c39770e9a21a67 The Zone of the assembly that failed was: Intranet The Url of the assembly that failed was: file:///H:/boo-svn/bin/boo.exe With instructions from a blog post, I added a policy to the.NET Configuration fully trusting all assemblies with file:///H:/* as their URL. I verified this by entering the URL file:///H:/boo-svn/bin/boo.exe into the Evaluate Assembly tool in the.NET Configuration and noting that boo.exe had the Unrestricted permission (which it didn't have before the policy). Even with the permission, boo.exe does not run. I still get the same error message. What can I do to debug this problem? Is there another way to run "partially trusted" assemblies from network shares without having to change something for every assembly I want to run?
With.NET 3.5 SP1,.NET assemblies running from UNC shares have full permissions. See Brad Abrams's Allow.exes to be run off a network shares for workaround and discussions, and finally the follow up.NET 3.5 SP1 allows managed code to be launched from a network share.
Running "partially trusted" .NET assemblies from a network share When I try to run a.NET assembly ( boo.exe ) from a network share (mapped to a drive), it fails since it's only partially trusted: Unhandled Exception: System.Security.SecurityException: That assembly does not allow partially trusted callers. at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed) at BooCommandLine..ctor() at Program..ctor() at ProgramModule.Main(String[] argv) The action that failed was: LinkDemand The assembly or AppDomain that failed was: boo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=32c39770e9a21a67 The Zone of the assembly that failed was: Intranet The Url of the assembly that failed was: file:///H:/boo-svn/bin/boo.exe With instructions from a blog post, I added a policy to the.NET Configuration fully trusting all assemblies with file:///H:/* as their URL. I verified this by entering the URL file:///H:/boo-svn/bin/boo.exe into the Evaluate Assembly tool in the.NET Configuration and noting that boo.exe had the Unrestricted permission (which it didn't have before the policy). Even with the permission, boo.exe does not run. I still get the same error message. What can I do to debug this problem? Is there another way to run "partially trusted" assemblies from network shares without having to change something for every assembly I want to run?
TITLE: Running "partially trusted" .NET assemblies from a network share QUESTION: When I try to run a.NET assembly ( boo.exe ) from a network share (mapped to a drive), it fails since it's only partially trusted: Unhandled Exception: System.Security.SecurityException: That assembly does not allow partially trusted callers. at System.Security.CodeAccessSecurityEngine.ThrowSecurityException(Assembly asm, PermissionSet granted, PermissionSet refused, RuntimeMethodHandle rmh, SecurityAction action, Object demand, IPermission permThatFailed) at BooCommandLine..ctor() at Program..ctor() at ProgramModule.Main(String[] argv) The action that failed was: LinkDemand The assembly or AppDomain that failed was: boo, Version=0.0.0.0, Culture=neutral, PublicKeyToken=32c39770e9a21a67 The Zone of the assembly that failed was: Intranet The Url of the assembly that failed was: file:///H:/boo-svn/bin/boo.exe With instructions from a blog post, I added a policy to the.NET Configuration fully trusting all assemblies with file:///H:/* as their URL. I verified this by entering the URL file:///H:/boo-svn/bin/boo.exe into the Evaluate Assembly tool in the.NET Configuration and noting that boo.exe had the Unrestricted permission (which it didn't have before the policy). Even with the permission, boo.exe does not run. I still get the same error message. What can I do to debug this problem? Is there another way to run "partially trusted" assemblies from network shares without having to change something for every assembly I want to run? ANSWER: With.NET 3.5 SP1,.NET assemblies running from UNC shares have full permissions. See Brad Abrams's Allow.exes to be run off a network shares for workaround and discussions, and finally the follow up.NET 3.5 SP1 allows managed code to be launched from a network share.
[ ".net", "security" ]
11
5
8,714
4
0
2008-08-23T18:33:55.287000
2008-08-23T18:42:49.883000