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
47,701
56,510
Is there a way to attach a debugger to a multi-threaded Python process?
I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all:)
Yeah, gdb is good for lower level debugging. You can change threads with the thread command. e.g (gdb) thr 2 [Switching to thread 2 (process 6159 thread 0x3f1b)] (gdb) backtrace.... You could also check out Python specific debuggers like Winpdb, or pydb. Both platform independent.
Is there a way to attach a debugger to a multi-threaded Python process? I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all:)
TITLE: Is there a way to attach a debugger to a multi-threaded Python process? QUESTION: I'm trying to debug a deadlock in a multi-threaded Python application after it has locked up. Is there a way to attach a debugger to inspect the state of the process? Edit: I'm attempting this on Linux, but it would be great if there were a cross-platform solution. It's Python after all:) ANSWER: Yeah, gdb is good for lower level debugging. You can change threads with the thread command. e.g (gdb) thr 2 [Switching to thread 2 (process 6159 thread 0x3f1b)] (gdb) backtrace.... You could also check out Python specific debuggers like Winpdb, or pydb. Both platform independent.
[ "python", "debugging" ]
36
12
41,992
10
0
2008-09-06T18:14:05.607000
2008-09-11T13:19:10.687000
47,703
47,705
Multiple threads and performance on a single CPU
Is here any performance benefit to using multiple threads on a computer with a single CPU that does not having hyperthreading?
In terms of speed of computation, No. In fact things will slow down due to the overhead of managing the threads. In terms of responsiveness, yes. You can for example have one thread wait on an IO operation and have another run a GUI at the same time.
Multiple threads and performance on a single CPU Is here any performance benefit to using multiple threads on a computer with a single CPU that does not having hyperthreading?
TITLE: Multiple threads and performance on a single CPU QUESTION: Is here any performance benefit to using multiple threads on a computer with a single CPU that does not having hyperthreading? ANSWER: In terms of speed of computation, No. In fact things will slow down due to the overhead of managing the threads. In terms of responsiveness, yes. You can for example have one thread wait on an IO operation and have another run a GUI at the same time.
[ "performance", "multithreading" ]
16
32
9,954
6
0
2008-09-06T18:21:09.507000
2008-09-06T18:24:06.300000
47,707
47,745
How to start coding the "Dining Philosophers" simulation?
I'm not a beginner at C# but I really need to increase my understanding, so I've picked a classic deadlock problem to code to help teach myself some of the more advanced concepts of C#. The Dining Philosophers Problem seems like a good one, but I need a little help to get started. I know I need to approach the "diners" as objects, but to simulate the random delays between eating, should I look to threading with each diner in a separate thread? Do I need some kind of "master" to monitor all the actions? Any general design concept advice is welcome, but I'd like to do the grunt programming as an exercise. Thanks!
I think the best approach to simulate it would be a Fork class with a method like use() that holds the fork ( bool available = false ) and a release() that releases it. A Philosopher class with getFork(Fork) and releaseFork(Fork) that operates the holding/releasing of the object Fork (seems to me a timer would be good in a method useFork() so you can really perceive the deadlock. And for Last a DinningTable (or any other name) class that creates instances, and do the log. If you plan to use threads, here is where you should implement a thread for each Philosopher concurring for the Fork. As a suggestion, you could implement a Plate Class, holding a quantity of spaghetti that the Philosopher.useFork() method lower during the time frame. This way you can see which Philosopher finishes first. I will let the implementations for you, of course, since your objective is to learn C#... in my experience, you better learn doing something concrete like these classes;) Besides, you can find lots of implementations on Google if you want to cheat... I invite you to share the code after it. It's a great Study Reference. Hope This helps you.
How to start coding the "Dining Philosophers" simulation? I'm not a beginner at C# but I really need to increase my understanding, so I've picked a classic deadlock problem to code to help teach myself some of the more advanced concepts of C#. The Dining Philosophers Problem seems like a good one, but I need a little help to get started. I know I need to approach the "diners" as objects, but to simulate the random delays between eating, should I look to threading with each diner in a separate thread? Do I need some kind of "master" to monitor all the actions? Any general design concept advice is welcome, but I'd like to do the grunt programming as an exercise. Thanks!
TITLE: How to start coding the "Dining Philosophers" simulation? QUESTION: I'm not a beginner at C# but I really need to increase my understanding, so I've picked a classic deadlock problem to code to help teach myself some of the more advanced concepts of C#. The Dining Philosophers Problem seems like a good one, but I need a little help to get started. I know I need to approach the "diners" as objects, but to simulate the random delays between eating, should I look to threading with each diner in a separate thread? Do I need some kind of "master" to monitor all the actions? Any general design concept advice is welcome, but I'd like to do the grunt programming as an exercise. Thanks! ANSWER: I think the best approach to simulate it would be a Fork class with a method like use() that holds the fork ( bool available = false ) and a release() that releases it. A Philosopher class with getFork(Fork) and releaseFork(Fork) that operates the holding/releasing of the object Fork (seems to me a timer would be good in a method useFork() so you can really perceive the deadlock. And for Last a DinningTable (or any other name) class that creates instances, and do the log. If you plan to use threads, here is where you should implement a thread for each Philosopher concurring for the Fork. As a suggestion, you could implement a Plate Class, holding a quantity of spaghetti that the Philosopher.useFork() method lower during the time frame. This way you can see which Philosopher finishes first. I will let the implementations for you, of course, since your objective is to learn C#... in my experience, you better learn doing something concrete like these classes;) Besides, you can find lots of implementations on Google if you want to cheat... I invite you to share the code after it. It's a great Study Reference. Hope This helps you.
[ "c#", "deadlock", "puzzle" ]
6
6
4,304
1
0
2008-09-06T18:26:18.433000
2008-09-06T19:09:56.613000
47,709
48,029
How does google make make those awesome PDF reports in Analytics and when you print a Google Doc etc?
When you print from Google Docs (using the "print" link, not File/Print) you end up printing a nicely formated PDF file instead of relying on the print engine of the browser. Same is true for some of the reports in Google Analytics... the printed reports as PDF's are beautiful. How do they do that? I can't imagine they use something like Adobe Acrobat to facilitate it but maybe they do. I've seen some expensive HTML to PDF converters online from time to time but have never tired it. Any thoughts?
If you are specifically looking at how Google does it. If you look at the PDF Properties page, they use Prince 6.0 (see princexml.com ) There are lots of other PDF generators out there. I've had great success with PDFlib for tricky jobs.
How does google make make those awesome PDF reports in Analytics and when you print a Google Doc etc? When you print from Google Docs (using the "print" link, not File/Print) you end up printing a nicely formated PDF file instead of relying on the print engine of the browser. Same is true for some of the reports in Google Analytics... the printed reports as PDF's are beautiful. How do they do that? I can't imagine they use something like Adobe Acrobat to facilitate it but maybe they do. I've seen some expensive HTML to PDF converters online from time to time but have never tired it. Any thoughts?
TITLE: How does google make make those awesome PDF reports in Analytics and when you print a Google Doc etc? QUESTION: When you print from Google Docs (using the "print" link, not File/Print) you end up printing a nicely formated PDF file instead of relying on the print engine of the browser. Same is true for some of the reports in Google Analytics... the printed reports as PDF's are beautiful. How do they do that? I can't imagine they use something like Adobe Acrobat to facilitate it but maybe they do. I've seen some expensive HTML to PDF converters online from time to time but have never tired it. Any thoughts? ANSWER: If you are specifically looking at how Google does it. If you look at the PDF Properties page, they use Prince 6.0 (see princexml.com ) There are lots of other PDF generators out there. I've had great success with PDFlib for tricky jobs.
[ "pdf", "google-analytics", "pdf-generation", "google-docs" ]
7
13
7,148
6
0
2008-09-06T18:28:22.920000
2008-09-07T01:53:02.977000
47,711
47,731
How do you determine how far to normalize a database?
When creating a database structure, what are good guidelines to follow or good ways to determine how far a database should be normalized? Should you create an un-normalized database and split it apart as the project progresses? Should you create it fully normalized and combine tables as needed for performance?
You want to start designing a normalized database up to 3rd normal form. As you develop the business logic layer you may decide you have to denormalize a bit but never, never go below the 3rd form. Always, keep 1st and 2nd form compliant. You want to denormalize for simplicity of code, not for performance. Use indexes and stored procedures for that:) The reason not "normalize as you go" is that you would have to modify the code you already have written most every time you modify the database design. There are a couple of good articles: http://www.agiledata.org/essays/dataNormalization.html
How do you determine how far to normalize a database? When creating a database structure, what are good guidelines to follow or good ways to determine how far a database should be normalized? Should you create an un-normalized database and split it apart as the project progresses? Should you create it fully normalized and combine tables as needed for performance?
TITLE: How do you determine how far to normalize a database? QUESTION: When creating a database structure, what are good guidelines to follow or good ways to determine how far a database should be normalized? Should you create an un-normalized database and split it apart as the project progresses? Should you create it fully normalized and combine tables as needed for performance? ANSWER: You want to start designing a normalized database up to 3rd normal form. As you develop the business logic layer you may decide you have to denormalize a bit but never, never go below the 3rd form. Always, keep 1st and 2nd form compliant. You want to denormalize for simplicity of code, not for performance. Use indexes and stored procedures for that:) The reason not "normalize as you go" is that you would have to modify the code you already have written most every time you modify the database design. There are a couple of good articles: http://www.agiledata.org/essays/dataNormalization.html
[ "database-design", "language-agnostic", "database-normalization" ]
20
20
8,926
13
0
2008-09-06T18:31:25.673000
2008-09-06T18:48:40.953000
47,749
47,781
Are mocks better than stubs?
A while ago I read the Mocks Aren't Stubs article by Martin Fowler and I must admit I'm a bit scared of external dependencies with regards to added complexity so I would like to ask: What is the best method to use when unit testing? Is it better to always use a mock framework to automatically mock the dependencies of the method being tested, or would you prefer to use simpler mechanisms like for instance test stubs?
As the mantra goes 'Go with the simplest thing that can possibly work.' If fake classes can get the job done, go with them. If you need an interface with multiple methods to be mocked, go with a mock framework. Avoid using mocks always because they make tests brittle. Your tests now have intricate knowledge of the methods called by the implementation, if the mocked interface or your implementation changes... your tests break. This is bad coz you'll spend additional time getting your tests to run instead of just getting your SUT to run. Tests should not be inappropriately intimate with the implementation. So use your best judgment.. I prefer mocks when it'll help save me writing-updating a fake class with n>>3 methods. Update Epilogue/Deliberation: (Thanks to Toran Billups for example of a mockist test. See below) Hi Doug, Well I think we've transcended into another holy war - Classic TDDers vs Mockist TDDers. I think I'm belong to the former. If I am on test#101 Test_ExportProductList and I find I need to add a new param to IProductService.GetProducts(). I do that get this test green. I use a refactoring tool to update all other references. Now I find all the mockist tests calling this member now blow up. Then I have to go back and update all these tests - a waste of time. Why did ShouldPopulateProductsListOnViewLoadWhenPostBackIsFalse fail? Was it because the code is broken? Rather the tests are broken. I favor the one test failure = 1 place to fix. Mocking freq goes against that. Would stubs be better? If it I had a fake_class.GetProducts().. sure One place to change instead of shotgun surgery over multiple Expect calls. In the end it's a matter of style.. if you had a common utility method MockHelper.SetupExpectForGetProducts() - that'd also suffice.. but you'll see that this is uncommon. If you place a white strip on the test name, the test is hard to read. Lot of plumbing code for the mock framework hides the actual test being performed. requires you to learn this particular flavor of a mocking framework
Are mocks better than stubs? A while ago I read the Mocks Aren't Stubs article by Martin Fowler and I must admit I'm a bit scared of external dependencies with regards to added complexity so I would like to ask: What is the best method to use when unit testing? Is it better to always use a mock framework to automatically mock the dependencies of the method being tested, or would you prefer to use simpler mechanisms like for instance test stubs?
TITLE: Are mocks better than stubs? QUESTION: A while ago I read the Mocks Aren't Stubs article by Martin Fowler and I must admit I'm a bit scared of external dependencies with regards to added complexity so I would like to ask: What is the best method to use when unit testing? Is it better to always use a mock framework to automatically mock the dependencies of the method being tested, or would you prefer to use simpler mechanisms like for instance test stubs? ANSWER: As the mantra goes 'Go with the simplest thing that can possibly work.' If fake classes can get the job done, go with them. If you need an interface with multiple methods to be mocked, go with a mock framework. Avoid using mocks always because they make tests brittle. Your tests now have intricate knowledge of the methods called by the implementation, if the mocked interface or your implementation changes... your tests break. This is bad coz you'll spend additional time getting your tests to run instead of just getting your SUT to run. Tests should not be inappropriately intimate with the implementation. So use your best judgment.. I prefer mocks when it'll help save me writing-updating a fake class with n>>3 methods. Update Epilogue/Deliberation: (Thanks to Toran Billups for example of a mockist test. See below) Hi Doug, Well I think we've transcended into another holy war - Classic TDDers vs Mockist TDDers. I think I'm belong to the former. If I am on test#101 Test_ExportProductList and I find I need to add a new param to IProductService.GetProducts(). I do that get this test green. I use a refactoring tool to update all other references. Now I find all the mockist tests calling this member now blow up. Then I have to go back and update all these tests - a waste of time. Why did ShouldPopulateProductsListOnViewLoadWhenPostBackIsFalse fail? Was it because the code is broken? Rather the tests are broken. I favor the one test failure = 1 place to fix. Mocking freq goes against that. Would stubs be better? If it I had a fake_class.GetProducts().. sure One place to change instead of shotgun surgery over multiple Expect calls. In the end it's a matter of style.. if you had a common utility method MockHelper.SetupExpectForGetProducts() - that'd also suffice.. but you'll see that this is uncommon. If you place a white strip on the test name, the test is hard to read. Lot of plumbing code for the mock framework hides the actual test being performed. requires you to learn this particular flavor of a mocking framework
[ "unit-testing", "mocking" ]
14
12
1,821
6
0
2008-09-06T19:13:08.413000
2008-09-06T20:00:23.650000
47,752
47,757
Remove duplicates from a List<T> in C#
Anyone have a quick method for de-duplicating a generic List in C#?
Perhaps you should consider using a HashSet. From the MSDN link: using System; using System.Collections.Generic; class Program { static void Main() { HashSet evenNumbers = new HashSet (); HashSet oddNumbers = new HashSet (); for (int i = 0; i < 5; i++) { // Populate numbers with just even numbers. evenNumbers.Add(i * 2); // Populate oddNumbers with just odd numbers. oddNumbers.Add((i * 2) + 1); } Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count); DisplaySet(evenNumbers); Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count); DisplaySet(oddNumbers); // Create a new HashSet populated with even numbers. HashSet numbers = new HashSet (evenNumbers); Console.WriteLine("numbers UnionWith oddNumbers..."); numbers.UnionWith(oddNumbers); Console.Write("numbers contains {0} elements: ", numbers.Count); DisplaySet(numbers); } private static void DisplaySet(HashSet set) { Console.Write("{"); foreach (int i in set) { Console.Write(" {0}", i); } Console.WriteLine(" }"); } } /* This example produces output similar to the following: * evenNumbers contains 5 elements: { 0 2 4 6 8 } * oddNumbers contains 5 elements: { 1 3 5 7 9 } * numbers UnionWith oddNumbers... * numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 } */
Remove duplicates from a List<T> in C# Anyone have a quick method for de-duplicating a generic List in C#?
TITLE: Remove duplicates from a List<T> in C# QUESTION: Anyone have a quick method for de-duplicating a generic List in C#? ANSWER: Perhaps you should consider using a HashSet. From the MSDN link: using System; using System.Collections.Generic; class Program { static void Main() { HashSet evenNumbers = new HashSet (); HashSet oddNumbers = new HashSet (); for (int i = 0; i < 5; i++) { // Populate numbers with just even numbers. evenNumbers.Add(i * 2); // Populate oddNumbers with just odd numbers. oddNumbers.Add((i * 2) + 1); } Console.Write("evenNumbers contains {0} elements: ", evenNumbers.Count); DisplaySet(evenNumbers); Console.Write("oddNumbers contains {0} elements: ", oddNumbers.Count); DisplaySet(oddNumbers); // Create a new HashSet populated with even numbers. HashSet numbers = new HashSet (evenNumbers); Console.WriteLine("numbers UnionWith oddNumbers..."); numbers.UnionWith(oddNumbers); Console.Write("numbers contains {0} elements: ", numbers.Count); DisplaySet(numbers); } private static void DisplaySet(HashSet set) { Console.Write("{"); foreach (int i in set) { Console.Write(" {0}", i); } Console.WriteLine(" }"); } } /* This example produces output similar to the following: * evenNumbers contains 5 elements: { 0 2 4 6 8 } * oddNumbers contains 5 elements: { 1 3 5 7 9 } * numbers UnionWith oddNumbers... * numbers contains 10 elements: { 0 2 4 6 8 1 3 5 7 9 } */
[ "c#", "list", "generics", "duplicates" ]
637
247
849,750
32
0
2008-09-06T19:15:27.690000
2008-09-06T19:21:55.070000
47,762
47,796
How-to: Ranking Search Results
I have a webapp development problem that I've developed one solution for, but am trying to find other ideas that might get around some performance issues I'm seeing. problem statement: a user enters several keywords/tokens the application searches for matches to the tokens need one result for each token ie, if an entry has 3 tokens, i need the entry id 3 times rank the results assign X points for token match sort the entry ids based on points if point values are the same, use date to sort results What I want to be able to do, but have not figured out, is to send 1 query that returns something akin to the results of an in(), but returns a duplicate entry id for each token matches for each entry id checked. Is there a better way to do this than what I'm doing, of using multiple, individual queries running one query per token? If so, what's the easiest way to implement those? edit I've already tokenized the entries, so, for example, "see spot run" has an entry id of 1, and three tokens, 'see', 'spot', 'run', and those are in a separate token table, with entry ids relevant to them so the table might look like this: 'see', 1 'spot', 1 'run', 1 'run', 2 'spot', 3
you could achive this in one query using 'UNION ALL' in MySQL. Just loop through the tokens in PHP creating a UNION ALL for each token: e.g if the tokens are 'x', 'y' and 'z' your query may look something like this SELECT * FROM `entries` WHERE token like "%x%" union all SELECT * FROM `entries` WHERE token like "%y%" union all SELECT * FROM `entries` WHERE token like "%z%" ORDER BY score ect... The order clause should operate on the entire result set as one, which is what you need. In terms of performance it won't be all that fast (I'm guessing), however with databases the main overhead in terms of speed is often sending the query to the database engine from PHP and receiving the results. With this technique this only happens once instead of once per token, so performance will increase, I just don't know if it'll be enough.
How-to: Ranking Search Results I have a webapp development problem that I've developed one solution for, but am trying to find other ideas that might get around some performance issues I'm seeing. problem statement: a user enters several keywords/tokens the application searches for matches to the tokens need one result for each token ie, if an entry has 3 tokens, i need the entry id 3 times rank the results assign X points for token match sort the entry ids based on points if point values are the same, use date to sort results What I want to be able to do, but have not figured out, is to send 1 query that returns something akin to the results of an in(), but returns a duplicate entry id for each token matches for each entry id checked. Is there a better way to do this than what I'm doing, of using multiple, individual queries running one query per token? If so, what's the easiest way to implement those? edit I've already tokenized the entries, so, for example, "see spot run" has an entry id of 1, and three tokens, 'see', 'spot', 'run', and those are in a separate token table, with entry ids relevant to them so the table might look like this: 'see', 1 'spot', 1 'run', 1 'run', 2 'spot', 3
TITLE: How-to: Ranking Search Results QUESTION: I have a webapp development problem that I've developed one solution for, but am trying to find other ideas that might get around some performance issues I'm seeing. problem statement: a user enters several keywords/tokens the application searches for matches to the tokens need one result for each token ie, if an entry has 3 tokens, i need the entry id 3 times rank the results assign X points for token match sort the entry ids based on points if point values are the same, use date to sort results What I want to be able to do, but have not figured out, is to send 1 query that returns something akin to the results of an in(), but returns a duplicate entry id for each token matches for each entry id checked. Is there a better way to do this than what I'm doing, of using multiple, individual queries running one query per token? If so, what's the easiest way to implement those? edit I've already tokenized the entries, so, for example, "see spot run" has an entry id of 1, and three tokens, 'see', 'spot', 'run', and those are in a separate token table, with entry ids relevant to them so the table might look like this: 'see', 1 'spot', 1 'run', 1 'run', 2 'spot', 3 ANSWER: you could achive this in one query using 'UNION ALL' in MySQL. Just loop through the tokens in PHP creating a UNION ALL for each token: e.g if the tokens are 'x', 'y' and 'z' your query may look something like this SELECT * FROM `entries` WHERE token like "%x%" union all SELECT * FROM `entries` WHERE token like "%y%" union all SELECT * FROM `entries` WHERE token like "%z%" ORDER BY score ect... The order clause should operate on the entire result set as one, which is what you need. In terms of performance it won't be all that fast (I'm guessing), however with databases the main overhead in terms of speed is often sending the query to the database engine from PHP and receiving the results. With this technique this only happens once instead of once per token, so performance will increase, I just don't know if it'll be enough.
[ "php", "mysql", "search" ]
10
6
4,598
4
0
2008-09-06T19:29:56.580000
2008-09-06T20:12:44.307000
47,786
47,811
Google App Engine: Is it possible to do a Gql LIKE query?
Simple one really. In SQL, if I want to search a text field for a couple of characters, I can do: SELECT blah FROM blah WHERE blah LIKE '%text%' The documentation for App Engine makes no mention of how to achieve this, but surely it's a common enough problem?
BigTable, which is the database back end for App Engine, will scale to millions of records. Due to this, App Engine will not allow you to do any query that will result in a table scan, as performance would be dreadful for a well populated table. In other words, every query must use an index. This is why you can only do =, > and < queries. (In fact you can also do!= but the API does this using a a combination of > and < queries.) This is also why the development environment monitors all the queries you do and automatically adds any missing indexes to your index.yaml file. There is no way to index for a LIKE query so it's simply not available. Have a watch of this Google IO session for a much better and more detailed explanation of this.
Google App Engine: Is it possible to do a Gql LIKE query? Simple one really. In SQL, if I want to search a text field for a couple of characters, I can do: SELECT blah FROM blah WHERE blah LIKE '%text%' The documentation for App Engine makes no mention of how to achieve this, but surely it's a common enough problem?
TITLE: Google App Engine: Is it possible to do a Gql LIKE query? QUESTION: Simple one really. In SQL, if I want to search a text field for a couple of characters, I can do: SELECT blah FROM blah WHERE blah LIKE '%text%' The documentation for App Engine makes no mention of how to achieve this, but surely it's a common enough problem? ANSWER: BigTable, which is the database back end for App Engine, will scale to millions of records. Due to this, App Engine will not allow you to do any query that will result in a table scan, as performance would be dreadful for a well populated table. In other words, every query must use an index. This is why you can only do =, > and < queries. (In fact you can also do!= but the API does this using a a combination of > and < queries.) This is also why the development environment monitors all the queries you do and automatically adds any missing indexes to your index.yaml file. There is no way to index for a LIKE query so it's simply not available. Have a watch of this Google IO session for a much better and more detailed explanation of this.
[ "google-app-engine", "google-cloud-datastore", "gql" ]
125
82
44,136
12
0
2008-09-06T20:05:24.420000
2008-09-06T20:29:30.197000
47,789
47,826
Generator expressions vs. list comprehensions
When should you use generator expressions and when should you use list comprehensions in Python? # Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)]
John's answer is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work: def gen(): return (something for something in get_some_stuff()) print gen()[:2] # generators don't support indexing or slicing print [5,6] + gen() # generators can't be added to lists Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension. Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code.
Generator expressions vs. list comprehensions When should you use generator expressions and when should you use list comprehensions in Python? # Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)]
TITLE: Generator expressions vs. list comprehensions QUESTION: When should you use generator expressions and when should you use list comprehensions in Python? # Generator expression (x*2 for x in range(256)) # List comprehension [x*2 for x in range(256)] ANSWER: John's answer is good (that list comprehensions are better when you want to iterate over something multiple times). However, it's also worth noting that you should use a list if you want to use any of the list methods. For example, the following code won't work: def gen(): return (something for something in get_some_stuff()) print gen()[:2] # generators don't support indexing or slicing print [5,6] + gen() # generators can't be added to lists Basically, use a generator expression if all you're doing is iterating once. If you want to store and use the generated results, then you're probably better off with a list comprehension. Since performance is the most common reason to choose one over the other, my advice is to not worry about it and just pick one; if you find that your program is running too slowly, then and only then should you go back and worry about tuning your code.
[ "python", "list-comprehension", "generator-expression" ]
528
358
209,375
13
0
2008-09-06T20:07:59
2008-09-06T20:54:08.063000
47,817
604,928
Most elegant way to force a TEXTAREA element to line-wrap, *regardless* of whitespace
Html Textarea elements only wrap when they reach a space or tab character. This is fine, until the user types a looooooooooooooooooooooong enough word. I'm looking for a way to strictly enforce line breaks (eg.: even if it results in "loooooooooooo \n ooooooooooong"). The best I've found is to add a zero-width unicode space after every letter, but this breaks copy and paste operations. Anyone know of a better way? Note: I'm referring to the "textarea" element here (i.e.: the one that behaves similarly to a text input) - not just a plain old block of text.
The CSS settings word-wrap:break-word and text-wrap:unrestricted appear to be CSS 3 features. Good luck finding a way to do this on current implementations.
Most elegant way to force a TEXTAREA element to line-wrap, *regardless* of whitespace Html Textarea elements only wrap when they reach a space or tab character. This is fine, until the user types a looooooooooooooooooooooong enough word. I'm looking for a way to strictly enforce line breaks (eg.: even if it results in "loooooooooooo \n ooooooooooong"). The best I've found is to add a zero-width unicode space after every letter, but this breaks copy and paste operations. Anyone know of a better way? Note: I'm referring to the "textarea" element here (i.e.: the one that behaves similarly to a text input) - not just a plain old block of text.
TITLE: Most elegant way to force a TEXTAREA element to line-wrap, *regardless* of whitespace QUESTION: Html Textarea elements only wrap when they reach a space or tab character. This is fine, until the user types a looooooooooooooooooooooong enough word. I'm looking for a way to strictly enforce line breaks (eg.: even if it results in "loooooooooooo \n ooooooooooong"). The best I've found is to add a zero-width unicode space after every letter, but this breaks copy and paste operations. Anyone know of a better way? Note: I'm referring to the "textarea" element here (i.e.: the one that behaves similarly to a text input) - not just a plain old block of text. ANSWER: The CSS settings word-wrap:break-word and text-wrap:unrestricted appear to be CSS 3 features. Good luck finding a way to do this on current implementations.
[ "javascript", "html", "css", "text" ]
25
18
55,077
7
0
2008-09-06T20:36:05.250000
2009-03-03T02:54:34.913000
47,824
47,829
How do you remove all the options of a select box and then add one option and select it with jQuery?
Using core jQuery, how do you remove all the options of a select box, then add one option and select it? My select box is the following. EDIT: The following code was helpful with chaining. However, (in Internet Explorer).val('whatever') did not select the option that was added. (I did use the same 'value' in both.append and.val.) $('#mySelect').find('option').remove().end().append(' text ').val('whatever'); EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons..focus() was closer, but the option did not appear selected like it does with.selected= "true". Nothing is wrong with my existing code - I am just trying to learn jQuery. var mySelect = document.getElementById('mySelect'); mySelect.options.length = 0; mySelect.options[0] = new Option ("Foo (only choice)", "Foo"); mySelect.options[0].selected="true"; EDIT: selected answer was close to what I needed. This worked for me: $('#mySelect').children().remove().end().append(' text '); But both answers led me to my final solution..
$('#mySelect').find('option').remove().end().append(' text ').val('whatever');
How do you remove all the options of a select box and then add one option and select it with jQuery? Using core jQuery, how do you remove all the options of a select box, then add one option and select it? My select box is the following. EDIT: The following code was helpful with chaining. However, (in Internet Explorer).val('whatever') did not select the option that was added. (I did use the same 'value' in both.append and.val.) $('#mySelect').find('option').remove().end().append(' text ').val('whatever'); EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons..focus() was closer, but the option did not appear selected like it does with.selected= "true". Nothing is wrong with my existing code - I am just trying to learn jQuery. var mySelect = document.getElementById('mySelect'); mySelect.options.length = 0; mySelect.options[0] = new Option ("Foo (only choice)", "Foo"); mySelect.options[0].selected="true"; EDIT: selected answer was close to what I needed. This worked for me: $('#mySelect').children().remove().end().append(' text '); But both answers led me to my final solution..
TITLE: How do you remove all the options of a select box and then add one option and select it with jQuery? QUESTION: Using core jQuery, how do you remove all the options of a select box, then add one option and select it? My select box is the following. EDIT: The following code was helpful with chaining. However, (in Internet Explorer).val('whatever') did not select the option that was added. (I did use the same 'value' in both.append and.val.) $('#mySelect').find('option').remove().end().append(' text ').val('whatever'); EDIT: Trying to get it to mimic this code, I use the following code whenever the page/form is reset. This select box is populated by a set of radio buttons..focus() was closer, but the option did not appear selected like it does with.selected= "true". Nothing is wrong with my existing code - I am just trying to learn jQuery. var mySelect = document.getElementById('mySelect'); mySelect.options.length = 0; mySelect.options[0] = new Option ("Foo (only choice)", "Foo"); mySelect.options[0].selected="true"; EDIT: selected answer was close to what I needed. This worked for me: $('#mySelect').children().remove().end().append(' text '); But both answers led me to my final solution.. ANSWER: $('#mySelect').find('option').remove().end().append(' text ').val('whatever');
[ "javascript", "jquery", "html-select", "dynamic-html" ]
1,231
1,863
1,391,256
28
0
2008-09-06T20:53:54.957000
2008-09-06T21:01:36.750000
47,833
47,841
In C#, what is the best way to test if a dataset is empty?
I know you can look at the row.count or tables.count, but are there other ways to tell if a dataset is empty?
I would suggest something like:- bool nonEmptyDataSet = dataSet!= null && (from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any(); Edits: I have significantly cleaned up the code after due consideration, I think this is much cleaner. Many thanks to Keith for the inspiration regarding the use of.Any(). In line with Keith's suggestion, here is an extension method version of this approach:- public static class ExtensionMethods { public static bool IsEmpty(this DataSet dataSet) { return dataSet == null ||!(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any(); } } Note, as Keith rightly corrected me on in the comments of his post, this method will work even when the data set is null.
In C#, what is the best way to test if a dataset is empty? I know you can look at the row.count or tables.count, but are there other ways to tell if a dataset is empty?
TITLE: In C#, what is the best way to test if a dataset is empty? QUESTION: I know you can look at the row.count or tables.count, but are there other ways to tell if a dataset is empty? ANSWER: I would suggest something like:- bool nonEmptyDataSet = dataSet!= null && (from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any(); Edits: I have significantly cleaned up the code after due consideration, I think this is much cleaner. Many thanks to Keith for the inspiration regarding the use of.Any(). In line with Keith's suggestion, here is an extension method version of this approach:- public static class ExtensionMethods { public static bool IsEmpty(this DataSet dataSet) { return dataSet == null ||!(from DataTable t in dataSet.Tables where t.Rows.Count > 0 select t).Any(); } } Note, as Keith rightly corrected me on in the comments of his post, this method will work even when the data set is null.
[ "c#", ".net" ]
7
17
11,557
6
0
2008-09-06T21:02:43.207000
2008-09-06T21:12:51.277000
47,837
47,844
Getting the base element from a jQuery object
I'm struggling to find the right terminology here, but if you have jQuery object... $('#MyObject')...is it possible to extract the base element? Meaning, the equivalent of this: document.getElementById('MyObject')
Yes, use.get(index). According to the documentation: The.get() method grants access to the DOM nodes underlying each jQuery object.
Getting the base element from a jQuery object I'm struggling to find the right terminology here, but if you have jQuery object... $('#MyObject')...is it possible to extract the base element? Meaning, the equivalent of this: document.getElementById('MyObject')
TITLE: Getting the base element from a jQuery object QUESTION: I'm struggling to find the right terminology here, but if you have jQuery object... $('#MyObject')...is it possible to extract the base element? Meaning, the equivalent of this: document.getElementById('MyObject') ANSWER: Yes, use.get(index). According to the documentation: The.get() method grants access to the DOM nodes underlying each jQuery object.
[ "jquery" ]
69
56
58,233
4
0
2008-09-06T21:10:33.453000
2008-09-06T21:15:25.857000
47,849
47,860
Refer to/select a drive based only on its label? (i.e., not the drive letter)
I'm trying to refer to a drive whose letter may change. I'd like to refer to it by its label (e.g., MyLabel (v:) within a Batch File. It can be referred to by V:\. I'd like to refer to it by MyLabel. (This was posted on Experts Echange for a month with no answer. Let's see how fast SO answers it )
This bat file will give you the drive letter from a drive label: Option Explicit Dim num, args, objWMIService, objItem, colItems set args = WScript.Arguments num = args.Count if num <> 1 then WScript.Echo "Usage: CScript DriveFromLabel.vbs " WScript.Quit 1 end if Set objWMIService = GetObject("winmgmts:\\.\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk") For Each objItem in colItems If strcomp(objItem.VolumeName, args.Item(0), 1) = 0 Then Wscript.Echo objItem.Name End If Next WScript.Quit 0 Run it as: cscript /nologo DriveFromLabel.vbs label
Refer to/select a drive based only on its label? (i.e., not the drive letter) I'm trying to refer to a drive whose letter may change. I'd like to refer to it by its label (e.g., MyLabel (v:) within a Batch File. It can be referred to by V:\. I'd like to refer to it by MyLabel. (This was posted on Experts Echange for a month with no answer. Let's see how fast SO answers it )
TITLE: Refer to/select a drive based only on its label? (i.e., not the drive letter) QUESTION: I'm trying to refer to a drive whose letter may change. I'd like to refer to it by its label (e.g., MyLabel (v:) within a Batch File. It can be referred to by V:\. I'd like to refer to it by MyLabel. (This was posted on Experts Echange for a month with no answer. Let's see how fast SO answers it ) ANSWER: This bat file will give you the drive letter from a drive label: Option Explicit Dim num, args, objWMIService, objItem, colItems set args = WScript.Arguments num = args.Count if num <> 1 then WScript.Echo "Usage: CScript DriveFromLabel.vbs " WScript.Quit 1 end if Set objWMIService = GetObject("winmgmts:\\.\root\cimv2") Set colItems = objWMIService.ExecQuery("Select * from Win32_LogicalDisk") For Each objItem in colItems If strcomp(objItem.VolumeName, args.Item(0), 1) = 0 Then Wscript.Echo objItem.Name End If Next WScript.Quit 0 Run it as: cscript /nologo DriveFromLabel.vbs label
[ "windows", "batch-file" ]
9
1
7,972
4
0
2008-09-06T21:21:10.820000
2008-09-06T21:49:03.423000
47,854
47,859
How do you create a virtual network interface on Windows?
On linux, it's possible to create a tun interface using a tun driver which provides a "network interface psuedo-device" that can be treated as a regular network interface. Is there a way to do this programmatically on windows? Is there a way to do this without writing my own driver?
You can do this on XP with the Microsoft Loopback Adapter which is a driver for a virtual network card. On newer Windows version: Installing the Microsoft Loopback Adapter in Windows 8 and Windows Server 2012
How do you create a virtual network interface on Windows? On linux, it's possible to create a tun interface using a tun driver which provides a "network interface psuedo-device" that can be treated as a regular network interface. Is there a way to do this programmatically on windows? Is there a way to do this without writing my own driver?
TITLE: How do you create a virtual network interface on Windows? QUESTION: On linux, it's possible to create a tun interface using a tun driver which provides a "network interface psuedo-device" that can be treated as a regular network interface. Is there a way to do this programmatically on windows? Is there a way to do this without writing my own driver? ANSWER: You can do this on XP with the Microsoft Loopback Adapter which is a driver for a virtual network card. On newer Windows version: Installing the Microsoft Loopback Adapter in Windows 8 and Windows Server 2012
[ "windows", "networking" ]
29
17
106,504
4
0
2008-09-06T21:26:15.567000
2008-09-06T21:45:23.087000
47,862
47,900
Upgrade database from SQL Server 2000 to 2005 -- and rebuild full-text indexes?
I'm loading a SQL Server 2000 database into my new SQL Server 2005 instance. As expected, the full-text catalogs don't come with it. How can I rebuild them? Right-clicking my full text catalogs and hitting " rebuild indexes " just hangs for hours and hours without doing anything, so it doesn't appear to be that simple...
Try it using SQL. CREATE FULLTEXT CATALOG ALTER FULLTEXT CATALOG Here's an example from Microsoft. --Change to accent insensitive USE AdventureWorks; GO ALTER FULLTEXT CATALOG ftCatalog REBUILD WITH ACCENT_SENSITIVITY=OFF; GO -- Check Accentsensitivity SELECT FULLTEXTCATALOGPROPERTY('ftCatalog', 'accentsensitivity'); GO --Returned 0, which means the catalog is not accent sensitive.
Upgrade database from SQL Server 2000 to 2005 -- and rebuild full-text indexes? I'm loading a SQL Server 2000 database into my new SQL Server 2005 instance. As expected, the full-text catalogs don't come with it. How can I rebuild them? Right-clicking my full text catalogs and hitting " rebuild indexes " just hangs for hours and hours without doing anything, so it doesn't appear to be that simple...
TITLE: Upgrade database from SQL Server 2000 to 2005 -- and rebuild full-text indexes? QUESTION: I'm loading a SQL Server 2000 database into my new SQL Server 2005 instance. As expected, the full-text catalogs don't come with it. How can I rebuild them? Right-clicking my full text catalogs and hitting " rebuild indexes " just hangs for hours and hours without doing anything, so it doesn't appear to be that simple... ANSWER: Try it using SQL. CREATE FULLTEXT CATALOG ALTER FULLTEXT CATALOG Here's an example from Microsoft. --Change to accent insensitive USE AdventureWorks; GO ALTER FULLTEXT CATALOG ftCatalog REBUILD WITH ACCENT_SENSITIVITY=OFF; GO -- Check Accentsensitivity SELECT FULLTEXTCATALOGPROPERTY('ftCatalog', 'accentsensitivity'); GO --Returned 0, which means the catalog is not accent sensitive.
[ "sql-server", "full-text-search", "recovery" ]
0
1
3,634
2
0
2008-09-06T21:51:52.837000
2008-09-06T22:41:21.753000
47,864
50,671
Handling HttpRequestValidationException gracefully and ASP.net AJAX compatible?
ValidateEvents is a great ASP.net function, but the Yellow Screen of Death is not so nice. I found a way how to handle the HttpRequestValidationException gracefully here, but that does not work with ASP.net AJAX properly. Basically, I got an UpdatePanel with a TextBox and a Button, and when the user types in HTML into the Textbox, a JavaScript Popup with a Error message saying not to modify the Response pops up. So I wonder what is the best way to handle HttpRequestValidationException gracefully? For "normal" requests I would like to just display an error message, but when it's an AJAX Request i'd like to throw the request away and return something to indicate an error, so that my frontend page can react on it?
Found it and blogged about it. Basically, the EndRequestHandler and the args.set_errorHandled are our friends here.
Handling HttpRequestValidationException gracefully and ASP.net AJAX compatible? ValidateEvents is a great ASP.net function, but the Yellow Screen of Death is not so nice. I found a way how to handle the HttpRequestValidationException gracefully here, but that does not work with ASP.net AJAX properly. Basically, I got an UpdatePanel with a TextBox and a Button, and when the user types in HTML into the Textbox, a JavaScript Popup with a Error message saying not to modify the Response pops up. So I wonder what is the best way to handle HttpRequestValidationException gracefully? For "normal" requests I would like to just display an error message, but when it's an AJAX Request i'd like to throw the request away and return something to indicate an error, so that my frontend page can react on it?
TITLE: Handling HttpRequestValidationException gracefully and ASP.net AJAX compatible? QUESTION: ValidateEvents is a great ASP.net function, but the Yellow Screen of Death is not so nice. I found a way how to handle the HttpRequestValidationException gracefully here, but that does not work with ASP.net AJAX properly. Basically, I got an UpdatePanel with a TextBox and a Button, and when the user types in HTML into the Textbox, a JavaScript Popup with a Error message saying not to modify the Response pops up. So I wonder what is the best way to handle HttpRequestValidationException gracefully? For "normal" requests I would like to just display an error message, but when it's an AJAX Request i'd like to throw the request away and return something to indicate an error, so that my frontend page can react on it? ANSWER: Found it and blogged about it. Basically, the EndRequestHandler and the args.set_errorHandled are our friends here.
[ "asp.net", "validation", "asp.net-ajax" ]
3
3
3,403
3
0
2008-09-06T21:54:07.637000
2008-09-08T20:59:39.797000
47,869
48,050
Programmatically determine how many comments a blog post has
What is the most efficient way to determine how many comments a particular blog post has? We want to store the data for a new web app. We have a list of permalink URl's as well as the RSS feeds.
If I understand correctly, you want a heuristic to estimate the number of comments in an HTML page which is known to be a blog post, yes? Very often, a specific blog will have some features which make it easy to work out. If you look at mine over at http://kstruct.com/ you'll see that all the pages with comments say 'X Responses', so if you were able to do some work on a per blog basis, it's probably not really difficult. If you needed something generic, I guess there are a few common features that comments have that you might be able to detect. For one, any links in them are quite likely to have rel="nofollow" attributes, so seeing that within a block might imply that it's a comment. The main interesting thing to look for would be changes in the structure of posts for m the same site. For example, there's also a very good chance that each comment will have its own anchor so people can link directly to it, so you could look at the differing numbers of tags in a given page on the same site to get an idea of the relative numbers of comments. As Michael Stum pointed out, if the pages have a Comment-RSS feed, your life is made a lot easier because you can get the comment data in a structured format. All in all, though, I think it's going to be quite a challenging problem to solve in general.
Programmatically determine how many comments a blog post has What is the most efficient way to determine how many comments a particular blog post has? We want to store the data for a new web app. We have a list of permalink URl's as well as the RSS feeds.
TITLE: Programmatically determine how many comments a blog post has QUESTION: What is the most efficient way to determine how many comments a particular blog post has? We want to store the data for a new web app. We have a list of permalink URl's as well as the RSS feeds. ANSWER: If I understand correctly, you want a heuristic to estimate the number of comments in an HTML page which is known to be a blog post, yes? Very often, a specific blog will have some features which make it easy to work out. If you look at mine over at http://kstruct.com/ you'll see that all the pages with comments say 'X Responses', so if you were able to do some work on a per blog basis, it's probably not really difficult. If you needed something generic, I guess there are a few common features that comments have that you might be able to detect. For one, any links in them are quite likely to have rel="nofollow" attributes, so seeing that within a block might imply that it's a comment. The main interesting thing to look for would be changes in the structure of posts for m the same site. For example, there's also a very good chance that each comment will have its own anchor so people can link directly to it, so you could look at the differing numbers of tags in a given page on the same site to get an idea of the relative numbers of comments. As Michael Stum pointed out, if the pages have a Comment-RSS feed, your life is made a lot easier because you can get the comment data in a structured format. All in all, though, I think it's going to be quite a challenging problem to solve in general.
[ "rss", "comments" ]
0
2
236
3
0
2008-09-06T22:00:41.677000
2008-09-07T02:27:36.717000
47,882
47,902
What are magic numbers and why do some consider them bad?
What is a magic number? Why do many programmers advise that they be avoided?
A magic number is a direct usage of a number in the code. For example, if you have (in Java): public class Foo { public void setPassword(String password) { // don't do this if (password.length() > 7) { throw new InvalidArgumentException("password"); } } } This should be refactored to: public class Foo { public static final int MAX_PASSWORD_SIZE = 7; public void setPassword(String password) { if (password.length() > MAX_PASSWORD_SIZE) { throw new InvalidArgumentException("password"); } } } It improves readability of the code and it's easier to maintain. Imagine the case where I set the size of the password field in the GUI. If I use a magic number, whenever the max size changes, I have to change in two code locations. If I forget one, this will lead to inconsistencies. The JDK is full of examples like in Integer, Character and Math classes. PS: Static analysis tools like FindBugs and PMD detects the use of magic numbers in your code and suggests the refactoring.
What are magic numbers and why do some consider them bad? What is a magic number? Why do many programmers advise that they be avoided?
TITLE: What are magic numbers and why do some consider them bad? QUESTION: What is a magic number? Why do many programmers advise that they be avoided? ANSWER: A magic number is a direct usage of a number in the code. For example, if you have (in Java): public class Foo { public void setPassword(String password) { // don't do this if (password.length() > 7) { throw new InvalidArgumentException("password"); } } } This should be refactored to: public class Foo { public static final int MAX_PASSWORD_SIZE = 7; public void setPassword(String password) { if (password.length() > MAX_PASSWORD_SIZE) { throw new InvalidArgumentException("password"); } } } It improves readability of the code and it's easier to maintain. Imagine the case where I set the size of the password field in the GUI. If I use a magic number, whenever the max size changes, I have to change in two code locations. If I forget one, this will lead to inconsistencies. The JDK is full of examples like in Integer, Character and Math classes. PS: Static analysis tools like FindBugs and PMD detects the use of magic numbers in your code and suggests the refactoring.
[ "language-agnostic", "terminology", "magic-numbers" ]
618
705
423,919
15
0
2008-09-06T22:24:24.757000
2008-09-06T22:46:17.840000
47,883
47,913
How Does gcc on Solaris Find Its Libraries?
I'm trying to install 'quadrupel', a library that relies on ffmpeg on Solaris x86. I managed to build ffmpeg and its libraries live in /opt/gnu/lib and the includes are in /opt/gnu/include but when I try to build quadrupel, it can't find the ffmpeg headers. What flags/configuration is required to include those two directories in the proper search paths for libraries and includes? I'm not much of a Makefile hacker.
You can override the path by setting the environmental variable LD_LIBRARY_PATH. However I would suggest changing the system paths as well so you don't have to change the library path for all users. This can be done using crel. crle -l -c /var/ld/ld.config -l /usr/lib:/usr/local/lib:/opt/gnu/lib For the includes just add -I/opt/gnu/include to your CFLAGS variable.
How Does gcc on Solaris Find Its Libraries? I'm trying to install 'quadrupel', a library that relies on ffmpeg on Solaris x86. I managed to build ffmpeg and its libraries live in /opt/gnu/lib and the includes are in /opt/gnu/include but when I try to build quadrupel, it can't find the ffmpeg headers. What flags/configuration is required to include those two directories in the proper search paths for libraries and includes? I'm not much of a Makefile hacker.
TITLE: How Does gcc on Solaris Find Its Libraries? QUESTION: I'm trying to install 'quadrupel', a library that relies on ffmpeg on Solaris x86. I managed to build ffmpeg and its libraries live in /opt/gnu/lib and the includes are in /opt/gnu/include but when I try to build quadrupel, it can't find the ffmpeg headers. What flags/configuration is required to include those two directories in the proper search paths for libraries and includes? I'm not much of a Makefile hacker. ANSWER: You can override the path by setting the environmental variable LD_LIBRARY_PATH. However I would suggest changing the system paths as well so you don't have to change the library path for all users. This can be done using crel. crle -l -c /var/ld/ld.config -l /usr/lib:/usr/local/lib:/opt/gnu/lib For the includes just add -I/opt/gnu/include to your CFLAGS variable.
[ "gcc", "makefile", "solaris", "ffmpeg" ]
0
1
2,904
2
0
2008-09-06T22:25:24.707000
2008-09-06T22:54:27.290000
47,886
47,998
SEO Superstitions: Are <script> tags really bad?
We have an SEO team at my office, and one of their dictums is that having lots of
It's been ages since I've played the reading google's tea leafs game, but there are a few reasons your SEO expert might be saying this Three or four years back there was a bit of conventional wisdom floating around that the search engine algorithms would give more weight to search terms that happened sooner in the page. If all other things were equal on Pages A and B, if Page A mentions widgets earlier in the HTML file than Page B, Page A "wins". It's not that Google's engineers and PhD employees couldn't skip over the blocks, it's that they found a valuable metric in their presence. Taking that into account, it's easy to see how unless something "needs" (see #2 below) to be in the head of a document, an SEO obsessed person would want it out. The SEO people who aren't offering a quick fix tend to be proponents of well-crafted, validating/conforming HTML/XHTML structure. Inline Javascript, particularly the kind web ignorant software engineers tend to favor makes these people (I'm one) seethe. The bias against script tags themselves could also stem from some of the work Yahoo and others have done in optimizing Ajax applications (don't make the browser parse Javascript until is has to). Not necessarily directly related to SEO, but a best practice a white hat SEO type will have picked up. It's also possible you're misunderstanding each other. Content that's generated by Javascript is considered controversial in the SEO world. It's not that Google can't "see" this content, it's that people are unsure how its presence will rank the page, as a lot of black hat SEO games revolve around hiding and showing content with Javascript. SEO is at best Kremlinology and at worse a field that the black hats won over a long time ago. My free unsolicited advice is to stay out of the SEO game, present your managers with estimates as so how long it will take to implement their SEO related changes, and leave it at that.
SEO Superstitions: Are <script> tags really bad? We have an SEO team at my office, and one of their dictums is that having lots of
TITLE: SEO Superstitions: Are <script> tags really bad? QUESTION: We have an SEO team at my office, and one of their dictums is that having lots of ANSWER: It's been ages since I've played the reading google's tea leafs game, but there are a few reasons your SEO expert might be saying this Three or four years back there was a bit of conventional wisdom floating around that the search engine algorithms would give more weight to search terms that happened sooner in the page. If all other things were equal on Pages A and B, if Page A mentions widgets earlier in the HTML file than Page B, Page A "wins". It's not that Google's engineers and PhD employees couldn't skip over the blocks, it's that they found a valuable metric in their presence. Taking that into account, it's easy to see how unless something "needs" (see #2 below) to be in the head of a document, an SEO obsessed person would want it out. The SEO people who aren't offering a quick fix tend to be proponents of well-crafted, validating/conforming HTML/XHTML structure. Inline Javascript, particularly the kind web ignorant software engineers tend to favor makes these people (I'm one) seethe. The bias against script tags themselves could also stem from some of the work Yahoo and others have done in optimizing Ajax applications (don't make the browser parse Javascript until is has to). Not necessarily directly related to SEO, but a best practice a white hat SEO type will have picked up. It's also possible you're misunderstanding each other. Content that's generated by Javascript is considered controversial in the SEO world. It's not that Google can't "see" this content, it's that people are unsure how its presence will rank the page, as a lot of black hat SEO games revolve around hiding and showing content with Javascript. SEO is at best Kremlinology and at worse a field that the black hats won over a long time ago. My free unsolicited advice is to stay out of the SEO game, present your managers with estimates as so how long it will take to implement their SEO related changes, and leave it at that.
[ "seo" ]
7
16
3,640
9
0
2008-09-06T22:28:13.203000
2008-09-07T01:04:11.753000
47,901
47,921
Can UDP data be delivered corrupted?
Is it possible for UDP data to come to you corrupted? I know it is possible for it to be lost.
UDP packets use a 16 bit checksum. It is not impossible for UDP packets to have corruption, but it's pretty unlikely. In any case it is not more susceptible to corruption than TCP.
Can UDP data be delivered corrupted? Is it possible for UDP data to come to you corrupted? I know it is possible for it to be lost.
TITLE: Can UDP data be delivered corrupted? QUESTION: Is it possible for UDP data to come to you corrupted? I know it is possible for it to be lost. ANSWER: UDP packets use a 16 bit checksum. It is not impossible for UDP packets to have corruption, but it's pretty unlikely. In any case it is not more susceptible to corruption than TCP.
[ "c++", "networking", "udp" ]
23
23
14,593
6
0
2008-09-06T22:45:32.257000
2008-09-06T22:58:46.703000
47,903
47,929
UDP vs TCP, how much faster is it?
For general protocol message exchange, which can tolerate some packet loss. How much more efficient is UDP over TCP?
UDP is faster than TCP, and the simple reason is because its non-existent acknowledge packet (ACK) that permits a continuous packet stream, instead of TCP that acknowledges a set of packets, calculated by using the TCP window size and round-trip time (RTT). For more information, I recommend the simple, but very comprehensible Skullbox explanation (TCP vs. UDP)
UDP vs TCP, how much faster is it? For general protocol message exchange, which can tolerate some packet loss. How much more efficient is UDP over TCP?
TITLE: UDP vs TCP, how much faster is it? QUESTION: For general protocol message exchange, which can tolerate some packet loss. How much more efficient is UDP over TCP? ANSWER: UDP is faster than TCP, and the simple reason is because its non-existent acknowledge packet (ACK) that permits a continuous packet stream, instead of TCP that acknowledges a set of packets, calculated by using the TCP window size and round-trip time (RTT). For more information, I recommend the simple, but very comprehensible Skullbox explanation (TCP vs. UDP)
[ "networking", "tcp", "udp" ]
225
95
275,748
14
0
2008-09-06T22:46:36.373000
2008-09-06T23:03:04.773000
47,919
47,948
Organization of C files
I'm used to doing all my coding in one C file. However, I'm working on a project large enough that it becomes impractical to do so. I've been #including them together but I've run into cases where I'm #including some files multiple times, etc. I've heard of.h files, but I'm not sure what their function is (or why having 2 files is better than 1). What strategies should I use for organizing my code? Is it possible to separate "public" functions from "private" ones for a particular file? This question precipitated my inquiry. The tea.h file makes no reference to the tea.c file. Does the compiler "know" that every.h file has a corresponding.c file?
You should regard.h files as interface files of your.c file. Every.c file represents a module with a certain amount of functionality. If functions in a.c file are used by other modules (i.e. other.c files) put the function prototype in the.h interface file. By including the interface file in your original modules.c file and every other.c file you need the function in, you make this function available to other modules. If you only need a function in a certain.c file (not in any other module), declare its scope static. This means it can only be called from within the c file it is defined in. Same goes for variables that are used across multiple modules. They should go in the header file and there they have to marked with the keyword 'extern'. Note: For functions the keyword 'extern' is optional. Functions are always considered 'extern'. The inclusion guards in header files help to not include the same header file multiple times. For example: Module1.c: #include "Module1.h" static void MyLocalFunction(void); static unsigned int MyLocalVariable; unsigned int MyExternVariable; void MyExternFunction(void) { MyLocalVariable = 1u; /* Do something */ MyLocalFunction(); } static void MyLocalFunction(void) { /* Do something */ MyExternVariable = 2u; } Module1.h: #ifndef __MODULE1.H #define __MODULE1.H extern unsigned int MyExternVariable; void MyExternFunction(void); #endif Module2.c #include "Module.1.h" static void MyLocalFunction(void); static void MyLocalFunction(void) { MyExternVariable = 1u; MyExternFunction(); }
Organization of C files I'm used to doing all my coding in one C file. However, I'm working on a project large enough that it becomes impractical to do so. I've been #including them together but I've run into cases where I'm #including some files multiple times, etc. I've heard of.h files, but I'm not sure what their function is (or why having 2 files is better than 1). What strategies should I use for organizing my code? Is it possible to separate "public" functions from "private" ones for a particular file? This question precipitated my inquiry. The tea.h file makes no reference to the tea.c file. Does the compiler "know" that every.h file has a corresponding.c file?
TITLE: Organization of C files QUESTION: I'm used to doing all my coding in one C file. However, I'm working on a project large enough that it becomes impractical to do so. I've been #including them together but I've run into cases where I'm #including some files multiple times, etc. I've heard of.h files, but I'm not sure what their function is (or why having 2 files is better than 1). What strategies should I use for organizing my code? Is it possible to separate "public" functions from "private" ones for a particular file? This question precipitated my inquiry. The tea.h file makes no reference to the tea.c file. Does the compiler "know" that every.h file has a corresponding.c file? ANSWER: You should regard.h files as interface files of your.c file. Every.c file represents a module with a certain amount of functionality. If functions in a.c file are used by other modules (i.e. other.c files) put the function prototype in the.h interface file. By including the interface file in your original modules.c file and every other.c file you need the function in, you make this function available to other modules. If you only need a function in a certain.c file (not in any other module), declare its scope static. This means it can only be called from within the c file it is defined in. Same goes for variables that are used across multiple modules. They should go in the header file and there they have to marked with the keyword 'extern'. Note: For functions the keyword 'extern' is optional. Functions are always considered 'extern'. The inclusion guards in header files help to not include the same header file multiple times. For example: Module1.c: #include "Module1.h" static void MyLocalFunction(void); static unsigned int MyLocalVariable; unsigned int MyExternVariable; void MyExternFunction(void) { MyLocalVariable = 1u; /* Do something */ MyLocalFunction(); } static void MyLocalFunction(void) { /* Do something */ MyExternVariable = 2u; } Module1.h: #ifndef __MODULE1.H #define __MODULE1.H extern unsigned int MyExternVariable; void MyExternFunction(void); #endif Module2.c #include "Module.1.h" static void MyLocalFunction(void); static void MyLocalFunction(void) { MyExternVariable = 1u; MyExternFunction(); }
[ "c", "header", "file-organization" ]
30
38
13,483
8
0
2008-09-06T22:58:35.080000
2008-09-06T23:29:14.977000
47,937
47,940
Combining and Caching multiple JavaScript files in ASP.net
Either I had a bad dream recently or I am just too stupid to google, but I remember that someone somewhere wrote that ASP.net has a Function which allows "merging" multiple JavaScript files automatically and only delivering one file to the client, thus reducing the number of HTTP Requests. Server Side, you still kept all the individual.js files, but the Runtime itself then creates one big JavaScript file which is then included in the script-tag instead and can be properly cached etc. In case that this function really exists and is not just a product of my imagination, can someone point me in the right direction please?
It's called Script Combining. There is a video example from asp.net explaining it here.
Combining and Caching multiple JavaScript files in ASP.net Either I had a bad dream recently or I am just too stupid to google, but I remember that someone somewhere wrote that ASP.net has a Function which allows "merging" multiple JavaScript files automatically and only delivering one file to the client, thus reducing the number of HTTP Requests. Server Side, you still kept all the individual.js files, but the Runtime itself then creates one big JavaScript file which is then included in the script-tag instead and can be properly cached etc. In case that this function really exists and is not just a product of my imagination, can someone point me in the right direction please?
TITLE: Combining and Caching multiple JavaScript files in ASP.net QUESTION: Either I had a bad dream recently or I am just too stupid to google, but I remember that someone somewhere wrote that ASP.net has a Function which allows "merging" multiple JavaScript files automatically and only delivering one file to the client, thus reducing the number of HTTP Requests. Server Side, you still kept all the individual.js files, but the Runtime itself then creates one big JavaScript file which is then included in the script-tag instead and can be properly cached etc. In case that this function really exists and is not just a product of my imagination, can someone point me in the right direction please? ANSWER: It's called Script Combining. There is a video example from asp.net explaining it here.
[ "asp.net", "javascript" ]
18
16
8,147
3
0
2008-09-06T23:10:54.333000
2008-09-06T23:14:09.443000
47,941
155,355
Invalid iPhone Application Binary
I'm trying to upload an application to the iPhone App Store, but I get this error message from iTunes Connect: The binary you uploaded was invalid. The signature was invalid, or it was not signed with an Apple submission certificate. Note: The details of original question have been removed, as this page has turned into a repository for all information about possible causes of that particular error message. For general information on submitting iPhone applications to the App Store, see Steps to upload an iPhone application to the AppStore.
It's been my experience that Xcode occasionally gets confused about which signing certificate to use. I got into the habit of quitting and restarting Xcode after any change to the code signing settings (and doing a clean build) to work around this problem.
Invalid iPhone Application Binary I'm trying to upload an application to the iPhone App Store, but I get this error message from iTunes Connect: The binary you uploaded was invalid. The signature was invalid, or it was not signed with an Apple submission certificate. Note: The details of original question have been removed, as this page has turned into a repository for all information about possible causes of that particular error message. For general information on submitting iPhone applications to the App Store, see Steps to upload an iPhone application to the AppStore.
TITLE: Invalid iPhone Application Binary QUESTION: I'm trying to upload an application to the iPhone App Store, but I get this error message from iTunes Connect: The binary you uploaded was invalid. The signature was invalid, or it was not signed with an Apple submission certificate. Note: The details of original question have been removed, as this page has turned into a repository for all information about possible causes of that particular error message. For general information on submitting iPhone applications to the App Store, see Steps to upload an iPhone application to the AppStore. ANSWER: It's been my experience that Xcode occasionally gets confused about which signing certificate to use. I got into the habit of quitting and restarting Xcode after any change to the code signing settings (and doing a clean build) to work around this problem.
[ "iphone", "ios", "app-store", "code-signing", "app-store-connect" ]
78
35
51,162
34
0
2008-09-06T23:18:22.007000
2008-09-30T22:20:05.153000
47,953
47,956
What are the advantages of packaging your python library/application as an .egg file?
I've read some about.egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer?
From the Python Enterprise Application Kit community: "Eggs are to Pythons as Jars are to Java..." Python eggs are a way of bundling additional information with a Python project, that allows the project's dependencies to be checked and satisfied at runtime, as well as allowing projects to provide plugins for other projects. There are several binary formats that embody eggs, but the most common is '.egg' zipfile format, because it's a convenient one for distributing projects. All of the formats support including package-specific data, project-wide metadata, C extensions, and Python code. The primary benefits of Python Eggs are: They enable tools like the "Easy Install" Python package manager.egg files are a "zero installation" format for a Python package; no build or install step is required, just put them on PYTHONPATH or sys.path and use them (may require the runtime installed if C extensions or data files are used) They can include package metadata, such as the other eggs they depend on They allow "namespace packages" (packages that just contain other packages) to be split into separate distributions (e.g. zope., twisted., peak.* packages can be distributed as separate eggs, unlike normal packages which must always be placed under the same parent directory. This allows what are now huge monolithic packages to be distributed as separate components.) They allow applications or libraries to specify the needed version of a library, so that you can e.g. require("Twisted-Internet>=2.0") before doing an import twisted.internet. They're a great format for distributing extensions or plugins to extensible applications and frameworks (such as Trac, which uses eggs for plugins as of 0.9b1), because the egg runtime provides simple APIs to locate eggs and find their advertised entry points (similar to Eclipse's "extension point" concept). There are also other benefits that may come from having a standardized format, similar to the benefits of Java's "jar" format. -Adam
What are the advantages of packaging your python library/application as an .egg file? I've read some about.egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer?
TITLE: What are the advantages of packaging your python library/application as an .egg file? QUESTION: I've read some about.egg files and I've noticed them in my lib directory but what are the advantages/disadvantages of using then as a developer? ANSWER: From the Python Enterprise Application Kit community: "Eggs are to Pythons as Jars are to Java..." Python eggs are a way of bundling additional information with a Python project, that allows the project's dependencies to be checked and satisfied at runtime, as well as allowing projects to provide plugins for other projects. There are several binary formats that embody eggs, but the most common is '.egg' zipfile format, because it's a convenient one for distributing projects. All of the formats support including package-specific data, project-wide metadata, C extensions, and Python code. The primary benefits of Python Eggs are: They enable tools like the "Easy Install" Python package manager.egg files are a "zero installation" format for a Python package; no build or install step is required, just put them on PYTHONPATH or sys.path and use them (may require the runtime installed if C extensions or data files are used) They can include package metadata, such as the other eggs they depend on They allow "namespace packages" (packages that just contain other packages) to be split into separate distributions (e.g. zope., twisted., peak.* packages can be distributed as separate eggs, unlike normal packages which must always be placed under the same parent directory. This allows what are now huge monolithic packages to be distributed as separate components.) They allow applications or libraries to specify the needed version of a library, so that you can e.g. require("Twisted-Internet>=2.0") before doing an import twisted.internet. They're a great format for distributing extensions or plugins to extensible applications and frameworks (such as Trac, which uses eggs for plugins as of 0.9b1), because the egg runtime provides simple APIs to locate eggs and find their advertised entry points (similar to Eclipse's "extension point" concept). There are also other benefits that may come from having a standardized format, similar to the benefits of Java's "jar" format. -Adam
[ "python", "zip", "packaging", "software-distribution", "egg" ]
28
32
11,098
6
0
2008-09-06T23:35:30.560000
2008-09-06T23:39:33.623000
47,960
1,079,575
What are the most useful (custom) code snippets for C#?
What are the best code snippets for C#? (using visual studio) VB has a lot that are pre-defined, but there are only a handful for C#. Do you have any really useful ones for C#? Anyone want to post a good custom one you created yourself? Anyone?... Bueller?
Microsoft have released a whole bunch of C# snippets that bring it up to parity with the ones for Visual Basic. You can download them here: http://msdn.microsoft.com/en-us/library/z41h7fat.aspx
What are the most useful (custom) code snippets for C#? What are the best code snippets for C#? (using visual studio) VB has a lot that are pre-defined, but there are only a handful for C#. Do you have any really useful ones for C#? Anyone want to post a good custom one you created yourself? Anyone?... Bueller?
TITLE: What are the most useful (custom) code snippets for C#? QUESTION: What are the best code snippets for C#? (using visual studio) VB has a lot that are pre-defined, but there are only a handful for C#. Do you have any really useful ones for C#? Anyone want to post a good custom one you created yourself? Anyone?... Bueller? ANSWER: Microsoft have released a whole bunch of C# snippets that bring it up to parity with the ones for Visual Basic. You can download them here: http://msdn.microsoft.com/en-us/library/z41h7fat.aspx
[ "c#", "visual-studio", "code-snippets" ]
8
3
11,338
8
0
2008-09-06T23:59:58.613000
2009-07-03T14:21:29.553000
47,972
275,998
What are some advantages of duck-typing vs. static typing?
I'm researching and experimenting more with Groovy and I'm trying to wrap my mind around the pros and cons of implementing things in Groovy that I can't/don't do in Java. Dynamic programming is still just a concept to me since I've been deeply steeped static and strongly typed languages. Groovy gives me the ability to duck-type, but I can't really see the value. How is duck-typing more productive than static typing? What kind of things can I do in my code practice to help me grasp the benefits of it? I ask this question with Groovy in mind but I understand it isn't necessarily a Groovy question so I welcome answers from every code camp.
Next, which is better: EMACS or vi? This is one of the running religious wars. Think of it this way: any program that is correct, will be correct if the language is statically typed. What static typing does is let the compiler have enough information to detect type mismatches at compile time instead of run time. This can be an annoyance if your doing incremental sorts of programming, although (I maintain) if you're thinking clearly about your program it doesn't much matter; on the other hand, if you're building a really big program, like an operating system or a telephone switch, with dozens or hundreds or thousands of people working on it, or with really high reliability requirements, then having he compiler be able to detect a large class of problems for you without needing a test case to exercise just the right code path. It's not as if dynamic typing is a new and different thing: C, for example, is effectively dynamically typed, since I can always cast a foo* to a bar*. It just means it's then my responsibility as a C programmer never to use code that is appropriate on a bar* when the address is really pointing to a foo*. But as a result of the issues with large programs, C grew tools like lint(1), strengthened its type system with typedef and eventually developed a strongly typed variant in C++. (And, of course, C++ in turn developed ways around the strong typing, with all the varieties of casts and generics/templates and with RTTI. One other thing, though --- don't confuse "agile programming" with "dynamic languages". Agile programming is about the way people work together in a project: can the project adapt to changing requirements to meet the customers' needs while maintaining a humane environment for the programmers? It can be done with dynamically typed languages, and often is, because they can be more productive (eg, Ruby, Smalltalk), but it can be done, has been done successfully, in C and even assembler. In fact, Rally Development even uses agile methods (SCRUM in particular) to do marketing and documentation.
What are some advantages of duck-typing vs. static typing? I'm researching and experimenting more with Groovy and I'm trying to wrap my mind around the pros and cons of implementing things in Groovy that I can't/don't do in Java. Dynamic programming is still just a concept to me since I've been deeply steeped static and strongly typed languages. Groovy gives me the ability to duck-type, but I can't really see the value. How is duck-typing more productive than static typing? What kind of things can I do in my code practice to help me grasp the benefits of it? I ask this question with Groovy in mind but I understand it isn't necessarily a Groovy question so I welcome answers from every code camp.
TITLE: What are some advantages of duck-typing vs. static typing? QUESTION: I'm researching and experimenting more with Groovy and I'm trying to wrap my mind around the pros and cons of implementing things in Groovy that I can't/don't do in Java. Dynamic programming is still just a concept to me since I've been deeply steeped static and strongly typed languages. Groovy gives me the ability to duck-type, but I can't really see the value. How is duck-typing more productive than static typing? What kind of things can I do in my code practice to help me grasp the benefits of it? I ask this question with Groovy in mind but I understand it isn't necessarily a Groovy question so I welcome answers from every code camp. ANSWER: Next, which is better: EMACS or vi? This is one of the running religious wars. Think of it this way: any program that is correct, will be correct if the language is statically typed. What static typing does is let the compiler have enough information to detect type mismatches at compile time instead of run time. This can be an annoyance if your doing incremental sorts of programming, although (I maintain) if you're thinking clearly about your program it doesn't much matter; on the other hand, if you're building a really big program, like an operating system or a telephone switch, with dozens or hundreds or thousands of people working on it, or with really high reliability requirements, then having he compiler be able to detect a large class of problems for you without needing a test case to exercise just the right code path. It's not as if dynamic typing is a new and different thing: C, for example, is effectively dynamically typed, since I can always cast a foo* to a bar*. It just means it's then my responsibility as a C programmer never to use code that is appropriate on a bar* when the address is really pointing to a foo*. But as a result of the issues with large programs, C grew tools like lint(1), strengthened its type system with typedef and eventually developed a strongly typed variant in C++. (And, of course, C++ in turn developed ways around the strong typing, with all the varieties of casts and generics/templates and with RTTI. One other thing, though --- don't confuse "agile programming" with "dynamic languages". Agile programming is about the way people work together in a project: can the project adapt to changing requirements to meet the customers' needs while maintaining a humane environment for the programmers? It can be done with dynamically typed languages, and often is, because they can be more productive (eg, Ruby, Smalltalk), but it can be done, has been done successfully, in C and even assembler. In fact, Rally Development even uses agile methods (SCRUM in particular) to do marketing and documentation.
[ "groovy", "duck-typing" ]
33
7
14,808
10
0
2008-09-07T00:28:08.063000
2008-11-09T15:12:25.043000
47,975
70,695
Is it possible to develop DirectX apps in Linux?
More out of interest than anything else, but can you compile a DirectX app under linux? Obviously there's no official SDK, but I was thinking it might be possible with wine. Presumably wine has an implementation of the DirectX interface in order to run games? Is it possible to link against that? (edit: This is called winelib) Failing that, maybe a mingw cross compiler with the app running under wine. Half answered my own question here, but wondered if anyone had heard of anything like this being done?
I've had some luck with this. I've managed to compile this simple Direct3D example. I used winelib for this (wine-dev package on Ubuntu). Thanks to alastair for pointing me to winelib. I modified the source slightly to convert the wchars to chars (1 on line 52, 2 on line 55, by removing the L before the string literals). There may be a way around this, but this got it up and running. I then compiled the source with the following: wineg++ -ld3d9 -ld3dx9 triangle.cpp This generates an a.out.exe.so binary, as well as an a.out script to run it under wine.
Is it possible to develop DirectX apps in Linux? More out of interest than anything else, but can you compile a DirectX app under linux? Obviously there's no official SDK, but I was thinking it might be possible with wine. Presumably wine has an implementation of the DirectX interface in order to run games? Is it possible to link against that? (edit: This is called winelib) Failing that, maybe a mingw cross compiler with the app running under wine. Half answered my own question here, but wondered if anyone had heard of anything like this being done?
TITLE: Is it possible to develop DirectX apps in Linux? QUESTION: More out of interest than anything else, but can you compile a DirectX app under linux? Obviously there's no official SDK, but I was thinking it might be possible with wine. Presumably wine has an implementation of the DirectX interface in order to run games? Is it possible to link against that? (edit: This is called winelib) Failing that, maybe a mingw cross compiler with the app running under wine. Half answered my own question here, but wondered if anyone had heard of anything like this being done? ANSWER: I've had some luck with this. I've managed to compile this simple Direct3D example. I used winelib for this (wine-dev package on Ubuntu). Thanks to alastair for pointing me to winelib. I modified the source slightly to convert the wchars to chars (1 on line 52, 2 on line 55, by removing the L before the string literals). There may be a way around this, but this got it up and running. I then compiled the source with the following: wineg++ -ld3d9 -ld3dx9 triangle.cpp This generates an a.out.exe.so binary, as well as an a.out script to run it under wine.
[ "c++", "linux", "directx", "mingw", "wine" ]
13
11
8,725
9
0
2008-09-07T00:30:48.667000
2008-09-16T09:24:47.260000
47,980
47,983
Deciphering C++ template error messages
I'm really beginning to understand what people mean when they say that C++'s error messages are pretty terrible in regards to templates. I've seen horrendously long errors for things as simple as a function not matching its prototype. Are there any tricks to deciphering these errors? EDIT: I'm using both gcc and MSVC. They both seem to be pretty terrible.
You can try the following tool to make things more sane: http://www.bdsoft.com/tools/stlfilt.html
Deciphering C++ template error messages I'm really beginning to understand what people mean when they say that C++'s error messages are pretty terrible in regards to templates. I've seen horrendously long errors for things as simple as a function not matching its prototype. Are there any tricks to deciphering these errors? EDIT: I'm using both gcc and MSVC. They both seem to be pretty terrible.
TITLE: Deciphering C++ template error messages QUESTION: I'm really beginning to understand what people mean when they say that C++'s error messages are pretty terrible in regards to templates. I've seen horrendously long errors for things as simple as a function not matching its prototype. Are there any tricks to deciphering these errors? EDIT: I'm using both gcc and MSVC. They both seem to be pretty terrible. ANSWER: You can try the following tool to make things more sane: http://www.bdsoft.com/tools/stlfilt.html
[ "c++", "templates", "compiler-errors" ]
32
17
11,351
6
0
2008-09-07T00:39:39.393000
2008-09-07T00:42:37.157000
47,981
47,990
How to set, clear, and toggle a single bit
How can I set, clear, and toggle a bit?
Setting a bit Use the bitwise OR operator ( | ) to set n th bit of number to 1. // Can be whatever unsigned integer type you want, but // it's important to use the same type everywhere to avoid // performance issues caused by mixing integer types. typedef unsigned long Uint; // In C++, this can be template. // In C11, you can make it generic with _Generic, or with macros prior to C11. inline Uint bit_set(Uint number, Uint n) { return number | ((Uint)1 << n); } Note that it's undefined behavior to shift by more than the width of a Uint. The same applies to all remaining examples. Clearing a bit Use the bitwise AND operator ( & ) to set the n th bit of number to 0. inline Uint bit_clear(Uint number, Uint n) { return number & ~((Uint)1 << n); } You must invert the bit string with the bitwise NOT operator ( ~ ), then AND it. Toggling a bit Use the bitwise XOR operator ( ^ ) to toggle the n th bit of number. inline Uint bit_toggle(Uint number, Uint n) { return number ^ ((Uint)1 << n); } Checking a bit You didn't ask for this, but I might as well add it. To check a bit, shift number n to the right, then bitwise AND it: // bool requires #include prior to C23 inline bool bit_check(Uint number, Uint n) { return (number >> n) & (Uint)1; } Changing the n th bit to x There are alternatives with worse codegen, but the best way is to clear the bit like in bit_clear, then set the bit to value, similar to bit_set. inline Uint bit_set_to(Uint number, Uint n, bool x) { return (number & ~((Uint)1 << n)) | ((Uint)x << n); } All solutions have been tested to provide optimal codegen with GCC and clang. See https://godbolt.org/z/Wfzh8xsjW.
How to set, clear, and toggle a single bit How can I set, clear, and toggle a bit?
TITLE: How to set, clear, and toggle a single bit QUESTION: How can I set, clear, and toggle a bit? ANSWER: Setting a bit Use the bitwise OR operator ( | ) to set n th bit of number to 1. // Can be whatever unsigned integer type you want, but // it's important to use the same type everywhere to avoid // performance issues caused by mixing integer types. typedef unsigned long Uint; // In C++, this can be template. // In C11, you can make it generic with _Generic, or with macros prior to C11. inline Uint bit_set(Uint number, Uint n) { return number | ((Uint)1 << n); } Note that it's undefined behavior to shift by more than the width of a Uint. The same applies to all remaining examples. Clearing a bit Use the bitwise AND operator ( & ) to set the n th bit of number to 0. inline Uint bit_clear(Uint number, Uint n) { return number & ~((Uint)1 << n); } You must invert the bit string with the bitwise NOT operator ( ~ ), then AND it. Toggling a bit Use the bitwise XOR operator ( ^ ) to toggle the n th bit of number. inline Uint bit_toggle(Uint number, Uint n) { return number ^ ((Uint)1 << n); } Checking a bit You didn't ask for this, but I might as well add it. To check a bit, shift number n to the right, then bitwise AND it: // bool requires #include prior to C23 inline bool bit_check(Uint number, Uint n) { return (number >> n) & (Uint)1; } Changing the n th bit to x There are alternatives with worse codegen, but the best way is to clear the bit like in bit_clear, then set the bit to value, similar to bit_set. inline Uint bit_set_to(Uint number, Uint n, bool x) { return (number & ~((Uint)1 << n)) | ((Uint)x << n); } All solutions have been tested to provide optimal codegen with GCC and clang. See https://godbolt.org/z/Wfzh8xsjW.
[ "c++", "c", "bit-manipulation", "bitwise-operators" ]
3,142
4,346
1,651,442
27
0
2008-09-07T00:42:17.500000
2008-09-07T00:50:45.403000
48,006
48,016
Is it worth investing time in learning to use Emacs?
Right up front: I do not want to start a religious war. I've used vi for as long as I can remember, and the few times I've tried to pick up Emacs I've been so lost that I've quickly given up. Lots of people find Emacs very powerful, however. Its programmability is somewhat legendary. I'm primarily doing Solaris+Java development, and I'd like to ask a simple question: will my productivity increase if I invest time in getting my head around Emacs? Is the functionality that it offers over Vim going to be paid back in productivity increases in a reasonable timeframe? Repeat: I don't want a "my editor is better than yours" answer. I just want a yes or no answer as to whether it's worth investing the time or not. Will my productivity really increase?
I prefer emacs to vi, but I'm comfortable in both. There are some things that you can do in emacs that make it more powerful than vi, but not all of them are even programming-related. (Can you send email or read news from within vi? No, but who cares?) If you're comfortable with lisp (I'm not), you might be able to write add-ons and modes and stuff to make your life easier, but that's just likely to be syntax colouring and brace matching and eye candy like that. I will stop rambling now. Will your productivity increase using emacs? No. Update: See my comment below. Since I posted this, I have come across ways that using emacs has made me more productive than using vi.
Is it worth investing time in learning to use Emacs? Right up front: I do not want to start a religious war. I've used vi for as long as I can remember, and the few times I've tried to pick up Emacs I've been so lost that I've quickly given up. Lots of people find Emacs very powerful, however. Its programmability is somewhat legendary. I'm primarily doing Solaris+Java development, and I'd like to ask a simple question: will my productivity increase if I invest time in getting my head around Emacs? Is the functionality that it offers over Vim going to be paid back in productivity increases in a reasonable timeframe? Repeat: I don't want a "my editor is better than yours" answer. I just want a yes or no answer as to whether it's worth investing the time or not. Will my productivity really increase?
TITLE: Is it worth investing time in learning to use Emacs? QUESTION: Right up front: I do not want to start a religious war. I've used vi for as long as I can remember, and the few times I've tried to pick up Emacs I've been so lost that I've quickly given up. Lots of people find Emacs very powerful, however. Its programmability is somewhat legendary. I'm primarily doing Solaris+Java development, and I'd like to ask a simple question: will my productivity increase if I invest time in getting my head around Emacs? Is the functionality that it offers over Vim going to be paid back in productivity increases in a reasonable timeframe? Repeat: I don't want a "my editor is better than yours" answer. I just want a yes or no answer as to whether it's worth investing the time or not. Will my productivity really increase? ANSWER: I prefer emacs to vi, but I'm comfortable in both. There are some things that you can do in emacs that make it more powerful than vi, but not all of them are even programming-related. (Can you send email or read news from within vi? No, but who cares?) If you're comfortable with lisp (I'm not), you might be able to write add-ons and modes and stuff to make your life easier, but that's just likely to be syntax colouring and brace matching and eye candy like that. I will stop rambling now. Will your productivity increase using emacs? No. Update: See my comment below. Since I posted this, I have come across ways that using emacs has made me more productive than using vi.
[ "vim", "emacs", "editor", "text-editor" ]
56
35
36,361
29
0
2008-09-07T01:22:09.040000
2008-09-07T01:39:54.957000
48,009
48,736
Implications of Instantiating Objects with Dynamic Variables in PHP
What are the performance, security, or "other" implications of using the following form to declare a new class instance in PHP This is a contrived example, but I've seen this form used in Factories (OOP) to avoid having a big if/switch statement. Problems that come immediately to mind are You lose the ability to pass arguments into a constructor (LIES. Thanks Jeremy) Smells like eval(), with all the security concerns it brings to the table (but not necessarily the performance concerns?) What other implications are there, or what search engine terms other than "Rank PHP Hackery" can someone use to research this?
One of the issues with the resolving at run time is that you make it really hard for the opcode caches (like APC). Still, for now, doing something like you describe in your question is a valid way if you need a certain amount of indirection when instanciating stuff. As long as you don't do something like $classname = 'SomeClassName'; for ($x = 0; $x < 100000; $x++){ $object = new $classname; } you are probably fine:-) (my point being: Dynamically looking up a class here and then doesn't hurt. If you do it often, it will). Also, be sure that $classname can never be set from the outside - you'd want to have some control over what exact class you will be instantiating.
Implications of Instantiating Objects with Dynamic Variables in PHP What are the performance, security, or "other" implications of using the following form to declare a new class instance in PHP This is a contrived example, but I've seen this form used in Factories (OOP) to avoid having a big if/switch statement. Problems that come immediately to mind are You lose the ability to pass arguments into a constructor (LIES. Thanks Jeremy) Smells like eval(), with all the security concerns it brings to the table (but not necessarily the performance concerns?) What other implications are there, or what search engine terms other than "Rank PHP Hackery" can someone use to research this?
TITLE: Implications of Instantiating Objects with Dynamic Variables in PHP QUESTION: What are the performance, security, or "other" implications of using the following form to declare a new class instance in PHP This is a contrived example, but I've seen this form used in Factories (OOP) to avoid having a big if/switch statement. Problems that come immediately to mind are You lose the ability to pass arguments into a constructor (LIES. Thanks Jeremy) Smells like eval(), with all the security concerns it brings to the table (but not necessarily the performance concerns?) What other implications are there, or what search engine terms other than "Rank PHP Hackery" can someone use to research this? ANSWER: One of the issues with the resolving at run time is that you make it really hard for the opcode caches (like APC). Still, for now, doing something like you describe in your question is a valid way if you need a certain amount of indirection when instanciating stuff. As long as you don't do something like $classname = 'SomeClassName'; for ($x = 0; $x < 100000; $x++){ $object = new $classname; } you are probably fine:-) (my point being: Dynamically looking up a class here and then doesn't hurt. If you do it often, it will). Also, be sure that $classname can never be set from the outside - you'd want to have some control over what exact class you will be instantiating.
[ "php", "performance", "oop" ]
12
8
6,220
10
0
2008-09-07T01:27:50.883000
2008-09-07T20:10:44.163000
48,012
52,881
How do the CakePHP and codeigniter frameworks compare to the ASP.NET MVC framework?
As a classic ASP developer about once a year since ASP.NET came out I decide I really gotta buckle down and learn this fancy new ASP.NET. A few days in and messing with code-behinds and webforms and all this other stuff. I decide the new fancy stuff is whack and go find something else to learn ( PHP and Ruby and Python were all fun to play with but I couldn't use it much with my existing ASP stuff ). Anyway, one project came up and I was able to use PHP and CakePHP and after getting my head around MVC I finally found something I liked and felt it was worth using over ASP ( PHP is cool too but it feels a lot like ASP so maybe that's why I like it so much ). But now with Jeff and the SO team raving about ASP.NET MVC, I think it's about time I start messing with ASP.NET again but I keep thinking that PHP is free and blah blah blah... is ASP.NET MVC that much better than PHP with tools like CakePHP? I know about compiled vs. not compiled and speed issues but most of that seems like a non-issue when you factor in all the caching and the fact that you can compile your PHP if you want.
For a classic ASP developer moving to ASP.NET MVC you are looking at learning a new language (C# or VB.NET), a new database layer (ADO.NET), and a new framework (ASP.NET MVC). That's a lot of new technologies to wrap your head around all at once. Also, I don't think it is so much that ASP.NET MVC is so much better than CakePHP (or Code Igniter, Ruby on Rails, etc.) The great thing about ASP.NET MVC (and other ASP.NET-based technologies such as MonoRail http://www.castleproject.org/monorail/index.html ) is that developers who are using ASP.NET now have the option of following the MVC pattern using tools and languages they are familiar with. That is an option that wasn't available before.
How do the CakePHP and codeigniter frameworks compare to the ASP.NET MVC framework? As a classic ASP developer about once a year since ASP.NET came out I decide I really gotta buckle down and learn this fancy new ASP.NET. A few days in and messing with code-behinds and webforms and all this other stuff. I decide the new fancy stuff is whack and go find something else to learn ( PHP and Ruby and Python were all fun to play with but I couldn't use it much with my existing ASP stuff ). Anyway, one project came up and I was able to use PHP and CakePHP and after getting my head around MVC I finally found something I liked and felt it was worth using over ASP ( PHP is cool too but it feels a lot like ASP so maybe that's why I like it so much ). But now with Jeff and the SO team raving about ASP.NET MVC, I think it's about time I start messing with ASP.NET again but I keep thinking that PHP is free and blah blah blah... is ASP.NET MVC that much better than PHP with tools like CakePHP? I know about compiled vs. not compiled and speed issues but most of that seems like a non-issue when you factor in all the caching and the fact that you can compile your PHP if you want.
TITLE: How do the CakePHP and codeigniter frameworks compare to the ASP.NET MVC framework? QUESTION: As a classic ASP developer about once a year since ASP.NET came out I decide I really gotta buckle down and learn this fancy new ASP.NET. A few days in and messing with code-behinds and webforms and all this other stuff. I decide the new fancy stuff is whack and go find something else to learn ( PHP and Ruby and Python were all fun to play with but I couldn't use it much with my existing ASP stuff ). Anyway, one project came up and I was able to use PHP and CakePHP and after getting my head around MVC I finally found something I liked and felt it was worth using over ASP ( PHP is cool too but it feels a lot like ASP so maybe that's why I like it so much ). But now with Jeff and the SO team raving about ASP.NET MVC, I think it's about time I start messing with ASP.NET again but I keep thinking that PHP is free and blah blah blah... is ASP.NET MVC that much better than PHP with tools like CakePHP? I know about compiled vs. not compiled and speed issues but most of that seems like a non-issue when you factor in all the caching and the fact that you can compile your PHP if you want. ANSWER: For a classic ASP developer moving to ASP.NET MVC you are looking at learning a new language (C# or VB.NET), a new database layer (ADO.NET), and a new framework (ASP.NET MVC). That's a lot of new technologies to wrap your head around all at once. Also, I don't think it is so much that ASP.NET MVC is so much better than CakePHP (or Code Igniter, Ruby on Rails, etc.) The great thing about ASP.NET MVC (and other ASP.NET-based technologies such as MonoRail http://www.castleproject.org/monorail/index.html ) is that developers who are using ASP.NET now have the option of following the MVC pattern using tools and languages they are familiar with. That is an option that wasn't available before.
[ "php", "asp.net-mvc", "cakephp", "asp-classic" ]
5
4
3,051
3
0
2008-09-07T01:34:43.800000
2008-09-09T20:54:04.793000
48,017
48,031
What is a jump table?
Can someone explain the mechanics of a jump table and why is would be needed in embedded systems?
A jump table can be either an array of pointers to functions or an array of machine code jump instructions. If you have a relatively static set of functions (such as system calls or virtual functions for a class) then you can create this table once and call the functions using a simple index into the array. This would mean retrieving the pointer and calling a function or jumping to the machine code depending on the type of table used. The benefits of doing this in embedded programming are: Indexes are more memory efficient than machine code or pointers, so there is a potential for memory savings in constrained environments. For any particular function the index will remain stable and changing the function merely requires swapping out the function pointer. If does cost you a tiny bit of performance for accessing the table, but this is no worse than any other virtual function call.
What is a jump table? Can someone explain the mechanics of a jump table and why is would be needed in embedded systems?
TITLE: What is a jump table? QUESTION: Can someone explain the mechanics of a jump table and why is would be needed in embedded systems? ANSWER: A jump table can be either an array of pointers to functions or an array of machine code jump instructions. If you have a relatively static set of functions (such as system calls or virtual functions for a class) then you can create this table once and call the functions using a simple index into the array. This would mean retrieving the pointer and calling a function or jumping to the machine code depending on the type of table used. The benefits of doing this in embedded programming are: Indexes are more memory efficient than machine code or pointers, so there is a potential for memory savings in constrained environments. For any particular function the index will remain stable and changing the function merely requires swapping out the function pointer. If does cost you a tiny bit of performance for accessing the table, but this is no worse than any other virtual function call.
[ "c++", "c", "memory", "embedded" ]
69
65
58,167
7
0
2008-09-07T01:40:27.843000
2008-09-07T01:54:54.547000
48,041
48,112
Hbase / Hadoop Query Help
I'm working on a project with a friend that will utilize Hbase to store it's data. Are there any good query examples? I seem to be writing a ton of Java code to iterate through lists of RowResult's when, in SQL land, I could write a simple query. Am I missing something? Or is Hbase missing something?
I think you, like many of us, are making the mistake of treating bigtable and HBase like just another RDBMS when it's actually a column-oriented storage model meant for efficiently storing and retrieving large sets of sparse data. This means storing, ideally, many-to-one relationships within a single row, for example. Your queries should return very few rows but contain (potentially) many datapoints. Perhaps if you told us more about what you were trying to store, we could help you design your schema to match the bigtable/HBase way of doing things. For a good rundown of what HBase does differently than a "traditional" RDBMS, check out this awesome article: Matching Impedance: When to use HBase by Bryan Duxbury.
Hbase / Hadoop Query Help I'm working on a project with a friend that will utilize Hbase to store it's data. Are there any good query examples? I seem to be writing a ton of Java code to iterate through lists of RowResult's when, in SQL land, I could write a simple query. Am I missing something? Or is Hbase missing something?
TITLE: Hbase / Hadoop Query Help QUESTION: I'm working on a project with a friend that will utilize Hbase to store it's data. Are there any good query examples? I seem to be writing a ton of Java code to iterate through lists of RowResult's when, in SQL land, I could write a simple query. Am I missing something? Or is Hbase missing something? ANSWER: I think you, like many of us, are making the mistake of treating bigtable and HBase like just another RDBMS when it's actually a column-oriented storage model meant for efficiently storing and retrieving large sets of sparse data. This means storing, ideally, many-to-one relationships within a single row, for example. Your queries should return very few rows but contain (potentially) many datapoints. Perhaps if you told us more about what you were trying to store, we could help you design your schema to match the bigtable/HBase way of doing things. For a good rundown of what HBase does differently than a "traditional" RDBMS, check out this awesome article: Matching Impedance: When to use HBase by Bryan Duxbury.
[ "hadoop", "hbase" ]
19
20
19,522
6
0
2008-09-07T02:14:07.543000
2008-09-07T03:42:38.080000
48,053
48,103
Is there any alternative to using % (modulus) in C/C++?
I read somewhere once that the modulus operator is inefficient on small embedded devices like 8 bit micro-controllers that do not have integer division instruction. Perhaps someone can confirm this but I thought the difference is 5-10 time slower than with an integer division operation. Is there another way to do this other than keeping a counter variable and manually overflowing to 0 at the mod point? const int FIZZ = 6; for(int x = 0; x < MAXCOUNT; x++) { if(!(x % FIZZ)) print("Fizz\n"); // slow on some systems } vs: The way I am currently doing it: const int FIZZ = 6; int fizzcount = 1; for(int x = 1; x < MAXCOUNT; x++) { if(fizzcount >= FIZZ) { print("Fizz\n"); fizzcount = 0; } }
Ah, the joys of bitwise arithmetic. A side effect of many division routines is the modulus - so in few cases should division actually be faster than modulus. I'm interested to see the source you got this information from. Processors with multipliers have interesting division routines using the multiplier, but you can get from division result to modulus with just another two steps (multiply and subtract) so it's still comparable. If the processor has a built in division routine you'll likely see it also provides the remainder. Still, there is a small branch of number theory devoted to Modular Arithmetic which requires study if you really want to understand how to optimize a modulus operation. Modular arithmatic, for instance, is very handy for generating magic squares. So, in that vein, here's a very low level look at the math of modulus for an example of x, which should show you how simple it can be compared to division: Maybe a better way to think about the problem is in terms of number bases and modulo arithmetic. For example, your goal is to compute DOW mod 7 where DOW is the 16-bit representation of the day of the week. You can write this as: DOW = DOW_HI*256 + DOW_LO DOW%7 = (DOW_HI*256 + DOW_LO) % 7 = ((DOW_HI*256)%7 + (DOW_LO % 7)) %7 = ((DOW_HI%7 * 256%7) + (DOW_LO%7)) %7 = ((DOW_HI%7 * 4) + (DOW_LO%7)) %7 Expressed in this manner, you can separately compute the modulo 7 result for the high and low bytes. Multiply the result for the high by 4 and add it to the low and then finally compute result modulo 7. Computing the mod 7 result of an 8-bit number can be performed in a similar fashion. You can write an 8-bit number in octal like so: X = a*64 + b*8 + c Where a, b, and c are 3-bit numbers. X%7 = ((a%7)*(64%7) + (b%7)*(8%7) + c%7) % 7 = (a%7 + b%7 + c%7) % 7 = (a + b + c) % 7 since 64%7 = 8%7 = 1 Of course, a, b, and c are c = X & 7 b = (X>>3) & 7 a = (X>>6) & 7 // (actually, a is only 2-bits). The largest possible value for a+b+c is 7+7+3 = 17. So, you'll need one more octal step. The complete (untested) C version could be written like: unsigned char Mod7Byte(unsigned char X) { X = (X&7) + ((X>>3)&7) + (X>>6); X = (X&7) + (X>>3); return X==7? 0: X; } I spent a few moments writing a PIC version. The actual implementation is slightly different than described above Mod7Byte: movwf temp1; andlw 7;W=c movwf temp2;temp2=c rlncf temp1,F; swapf temp1,W;W= a*8+b andlw 0x1F addwf temp2,W;W= a*8+b+c movwf temp2;temp2 is now a 6-bit number andlw 0x38;get the high 3 bits == a' xorwf temp2,F;temp2 now has the 3 low bits == b' rlncf WREG,F;shift the high bits right 4 swapf WREG,F; addwf temp2,W;W = a' + b'; at this point, W is between 0 and 10 addlw -7 bc Mod7Byte_L2 Mod7Byte_L1: addlw 7 Mod7Byte_L2: return Here's a liitle routine to test the algorithm clrf x clrf count TestLoop: movf x,W RCALL Mod7Byte cpfseq count bra fail incf count,W xorlw 7 skpz xorlw 7 movwf count incfsz x,F bra TestLoop passed: Finally, for the 16-bit result (which I have not tested), you could write: uint16 Mod7Word(uint16 X) { return Mod7Byte(Mod7Byte(X & 0xff) + Mod7Byte(X>>8)*4); } Scott
Is there any alternative to using % (modulus) in C/C++? I read somewhere once that the modulus operator is inefficient on small embedded devices like 8 bit micro-controllers that do not have integer division instruction. Perhaps someone can confirm this but I thought the difference is 5-10 time slower than with an integer division operation. Is there another way to do this other than keeping a counter variable and manually overflowing to 0 at the mod point? const int FIZZ = 6; for(int x = 0; x < MAXCOUNT; x++) { if(!(x % FIZZ)) print("Fizz\n"); // slow on some systems } vs: The way I am currently doing it: const int FIZZ = 6; int fizzcount = 1; for(int x = 1; x < MAXCOUNT; x++) { if(fizzcount >= FIZZ) { print("Fizz\n"); fizzcount = 0; } }
TITLE: Is there any alternative to using % (modulus) in C/C++? QUESTION: I read somewhere once that the modulus operator is inefficient on small embedded devices like 8 bit micro-controllers that do not have integer division instruction. Perhaps someone can confirm this but I thought the difference is 5-10 time slower than with an integer division operation. Is there another way to do this other than keeping a counter variable and manually overflowing to 0 at the mod point? const int FIZZ = 6; for(int x = 0; x < MAXCOUNT; x++) { if(!(x % FIZZ)) print("Fizz\n"); // slow on some systems } vs: The way I am currently doing it: const int FIZZ = 6; int fizzcount = 1; for(int x = 1; x < MAXCOUNT; x++) { if(fizzcount >= FIZZ) { print("Fizz\n"); fizzcount = 0; } } ANSWER: Ah, the joys of bitwise arithmetic. A side effect of many division routines is the modulus - so in few cases should division actually be faster than modulus. I'm interested to see the source you got this information from. Processors with multipliers have interesting division routines using the multiplier, but you can get from division result to modulus with just another two steps (multiply and subtract) so it's still comparable. If the processor has a built in division routine you'll likely see it also provides the remainder. Still, there is a small branch of number theory devoted to Modular Arithmetic which requires study if you really want to understand how to optimize a modulus operation. Modular arithmatic, for instance, is very handy for generating magic squares. So, in that vein, here's a very low level look at the math of modulus for an example of x, which should show you how simple it can be compared to division: Maybe a better way to think about the problem is in terms of number bases and modulo arithmetic. For example, your goal is to compute DOW mod 7 where DOW is the 16-bit representation of the day of the week. You can write this as: DOW = DOW_HI*256 + DOW_LO DOW%7 = (DOW_HI*256 + DOW_LO) % 7 = ((DOW_HI*256)%7 + (DOW_LO % 7)) %7 = ((DOW_HI%7 * 256%7) + (DOW_LO%7)) %7 = ((DOW_HI%7 * 4) + (DOW_LO%7)) %7 Expressed in this manner, you can separately compute the modulo 7 result for the high and low bytes. Multiply the result for the high by 4 and add it to the low and then finally compute result modulo 7. Computing the mod 7 result of an 8-bit number can be performed in a similar fashion. You can write an 8-bit number in octal like so: X = a*64 + b*8 + c Where a, b, and c are 3-bit numbers. X%7 = ((a%7)*(64%7) + (b%7)*(8%7) + c%7) % 7 = (a%7 + b%7 + c%7) % 7 = (a + b + c) % 7 since 64%7 = 8%7 = 1 Of course, a, b, and c are c = X & 7 b = (X>>3) & 7 a = (X>>6) & 7 // (actually, a is only 2-bits). The largest possible value for a+b+c is 7+7+3 = 17. So, you'll need one more octal step. The complete (untested) C version could be written like: unsigned char Mod7Byte(unsigned char X) { X = (X&7) + ((X>>3)&7) + (X>>6); X = (X&7) + (X>>3); return X==7? 0: X; } I spent a few moments writing a PIC version. The actual implementation is slightly different than described above Mod7Byte: movwf temp1; andlw 7;W=c movwf temp2;temp2=c rlncf temp1,F; swapf temp1,W;W= a*8+b andlw 0x1F addwf temp2,W;W= a*8+b+c movwf temp2;temp2 is now a 6-bit number andlw 0x38;get the high 3 bits == a' xorwf temp2,F;temp2 now has the 3 low bits == b' rlncf WREG,F;shift the high bits right 4 swapf WREG,F; addwf temp2,W;W = a' + b'; at this point, W is between 0 and 10 addlw -7 bc Mod7Byte_L2 Mod7Byte_L1: addlw 7 Mod7Byte_L2: return Here's a liitle routine to test the algorithm clrf x clrf count TestLoop: movf x,W RCALL Mod7Byte cpfseq count bra fail incf count,W xorlw 7 skpz xorlw 7 movwf count incfsz x,F bra TestLoop passed: Finally, for the 16-bit result (which I have not tested), you could write: uint16 Mod7Word(uint16 X) { return Mod7Byte(Mod7Byte(X & 0xff) + Mod7Byte(X>>8)*4); } Scott
[ "c++", "c", "modulo", "embedded" ]
34
48
60,761
13
0
2008-09-07T02:31:29.703000
2008-09-07T03:25:09.353000
48,083
48,227
Is there a .NET Control Similar to the Access 2007 Split Form?
Is there a.NET Control Similar to the Access 2007 Split Form? Or has anyone built such a control? I upgraded a small personal Name and Address DB to Access 2007 and noticed the Form had a property called “Default View” which can be set to “Split Form”. “Split Form” mode has a GridView and a Form together in one control. When a record is clicked in the GridView, it shows up in the form and it can be edited in either the GridView and/or the Form by setting some properties. Pretty slick.
Not that I know of, but pretty much all you need is: a split container a user control containing your actual form a grid view Now you just hook up the grid view's item selection events with a controller that loads data into the user control's child controls. From what I can tell, there Access Split Form doesn't do a lot more.
Is there a .NET Control Similar to the Access 2007 Split Form? Is there a.NET Control Similar to the Access 2007 Split Form? Or has anyone built such a control? I upgraded a small personal Name and Address DB to Access 2007 and noticed the Form had a property called “Default View” which can be set to “Split Form”. “Split Form” mode has a GridView and a Form together in one control. When a record is clicked in the GridView, it shows up in the form and it can be edited in either the GridView and/or the Form by setting some properties. Pretty slick.
TITLE: Is there a .NET Control Similar to the Access 2007 Split Form? QUESTION: Is there a.NET Control Similar to the Access 2007 Split Form? Or has anyone built such a control? I upgraded a small personal Name and Address DB to Access 2007 and noticed the Form had a property called “Default View” which can be set to “Split Form”. “Split Form” mode has a GridView and a Form together in one control. When a record is clicked in the GridView, it shows up in the form and it can be edited in either the GridView and/or the Form by setting some properties. Pretty slick. ANSWER: Not that I know of, but pretty much all you need is: a split container a user control containing your actual form a grid view Now you just hook up the grid view's item selection events with a controller that loads data into the user control's child controls. From what I can tell, there Access Split Form doesn't do a lot more.
[ ".net", "ms-access" ]
0
2
356
2
0
2008-09-07T03:07:42.003000
2008-09-07T07:50:56.393000
48,087
48,089
Select N random elements from a List<T> in C#
I need a quick algorithm to select 5 random elements from a generic list. For example, I'd like to get 5 random elements from a List.
Iterate through and for each element make the probability of selection = (number needed)/(number left) So if you had 40 items, the first would have a 5/40 chance of being selected. If it is, the next has a 4/39 chance, otherwise it has a 5/39 chance. By the time you get to the end you will have your 5 items, and often you'll have all of them before that. This technique is called selection sampling, a special case of Reservoir Sampling. It's similar in performance to shuffling the input, but of course allows the sample to be generated without modifying the original data.
Select N random elements from a List<T> in C# I need a quick algorithm to select 5 random elements from a generic list. For example, I'd like to get 5 random elements from a List.
TITLE: Select N random elements from a List<T> in C# QUESTION: I need a quick algorithm to select 5 random elements from a generic list. For example, I'd like to get 5 random elements from a List. ANSWER: Iterate through and for each element make the probability of selection = (number needed)/(number left) So if you had 40 items, the first would have a 5/40 chance of being selected. If it is, the next has a 4/39 chance, otherwise it has a 5/39 chance. By the time you get to the end you will have your 5 items, and often you'll have all of them before that. This technique is called selection sampling, a special case of Reservoir Sampling. It's similar in performance to shuffling the input, but of course allows the sample to be generated without modifying the original data.
[ "c#", "algorithm", "collections", "random", "element" ]
212
149
169,340
36
0
2008-09-07T03:12:28.120000
2008-09-07T03:16:16.507000
48,088
48,096
Returning from a finally block in Java
I was surprised recently to find that it's possible to have a return statement in a finally block in Java. It seems like lots of people think it's a bad thing to do as described in ' Don't return in a finally clause '. Scratching a little deeper, I also found ' Java's return doesn't always ' which shows some pretty horrible examples of other types of flow control in finally blocks. So, my question is, can anyone give me an example where a return statement (or other flow control) in a finally block produces better / more readable code?
The examples you provided are reason enough to not use flow-control from finally. Even if there's a contrived example where it's "better," consider the developer who has to maintain your code later and who might not be aware of the subtleties. That poor developer might even be you....
Returning from a finally block in Java I was surprised recently to find that it's possible to have a return statement in a finally block in Java. It seems like lots of people think it's a bad thing to do as described in ' Don't return in a finally clause '. Scratching a little deeper, I also found ' Java's return doesn't always ' which shows some pretty horrible examples of other types of flow control in finally blocks. So, my question is, can anyone give me an example where a return statement (or other flow control) in a finally block produces better / more readable code?
TITLE: Returning from a finally block in Java QUESTION: I was surprised recently to find that it's possible to have a return statement in a finally block in Java. It seems like lots of people think it's a bad thing to do as described in ' Don't return in a finally clause '. Scratching a little deeper, I also found ' Java's return doesn't always ' which shows some pretty horrible examples of other types of flow control in finally blocks. So, my question is, can anyone give me an example where a return statement (or other flow control) in a finally block produces better / more readable code? ANSWER: The examples you provided are reason enough to not use flow-control from finally. Even if there's a contrived example where it's "better," consider the developer who has to maintain your code later and who might not be aware of the subtleties. That poor developer might even be you....
[ "java", "exception", "return", "try-catch-finally" ]
189
95
69,749
6
0
2008-09-07T03:15:58.830000
2008-09-07T03:20:29.397000
48,094
48,102
C++ deleting a pointer to a pointer
So I have a pointer to an array of pointers. If I delete it like this: delete [] PointerToPointers; Will that delete all the pointed to pointers as well? If not, do I have to loop over all of the pointers and delete them as well, or is there an easier way to do it? My google-fu doesn't seem to give me any good answers to this question. (And yeah, I know I need to use a vector. This is one of those "catch up on C++" type assignments in school.)
Yes you have to loop over the pointers, deleting individually. Reason: What if other code had pointers to the objects in your array? The C++ compiler doesn't know if that's true or not, so you have to be explicit. For an "easier way," two suggestions: (1) Make a subroutine for this purpose so at least you won't have to write the code more than once. (2) Use the "smart pointer" design paradigm where you hold an array of objects with reference-counters, then the objects are deleted when the objects are no longer referenced by any code.
C++ deleting a pointer to a pointer So I have a pointer to an array of pointers. If I delete it like this: delete [] PointerToPointers; Will that delete all the pointed to pointers as well? If not, do I have to loop over all of the pointers and delete them as well, or is there an easier way to do it? My google-fu doesn't seem to give me any good answers to this question. (And yeah, I know I need to use a vector. This is one of those "catch up on C++" type assignments in school.)
TITLE: C++ deleting a pointer to a pointer QUESTION: So I have a pointer to an array of pointers. If I delete it like this: delete [] PointerToPointers; Will that delete all the pointed to pointers as well? If not, do I have to loop over all of the pointers and delete them as well, or is there an easier way to do it? My google-fu doesn't seem to give me any good answers to this question. (And yeah, I know I need to use a vector. This is one of those "catch up on C++" type assignments in school.) ANSWER: Yes you have to loop over the pointers, deleting individually. Reason: What if other code had pointers to the objects in your array? The C++ compiler doesn't know if that's true or not, so you have to be explicit. For an "easier way," two suggestions: (1) Make a subroutine for this purpose so at least you won't have to write the code more than once. (2) Use the "smart pointer" design paradigm where you hold an array of objects with reference-counters, then the objects are deleted when the objects are no longer referenced by any code.
[ "c++", "pointers" ]
21
30
32,800
7
0
2008-09-07T03:19:36.450000
2008-09-07T03:24:13.833000
48,115
88,316
DHCP overwrites Cisco VPN resolv.conf on Linux
I'm using an Ubuntu 8.04 (x86_64) machine to connect to my employer's Cisco VPN. (The client didn't compile out of the box, but I found patches to update the client to compile on kernels released in the last two years.) This all works great, until my DHCP client decides to renew its lease and updates /etc/resolv.conf, replacing the VPN-specific name servers with my general network servers. Is there a good way to prevent my DHCP client from updating /etc/resolv.conf while my VPN is active?
If you are using the Ubuntu default with NetworkManager, try removing the CiscoVPN client and use the NetworkManager vpnc plugin to connect to the Cisco VPN. This should avoid all problems, since NetworkManager then knows about your VPN connection.
DHCP overwrites Cisco VPN resolv.conf on Linux I'm using an Ubuntu 8.04 (x86_64) machine to connect to my employer's Cisco VPN. (The client didn't compile out of the box, but I found patches to update the client to compile on kernels released in the last two years.) This all works great, until my DHCP client decides to renew its lease and updates /etc/resolv.conf, replacing the VPN-specific name servers with my general network servers. Is there a good way to prevent my DHCP client from updating /etc/resolv.conf while my VPN is active?
TITLE: DHCP overwrites Cisco VPN resolv.conf on Linux QUESTION: I'm using an Ubuntu 8.04 (x86_64) machine to connect to my employer's Cisco VPN. (The client didn't compile out of the box, but I found patches to update the client to compile on kernels released in the last two years.) This all works great, until my DHCP client decides to renew its lease and updates /etc/resolv.conf, replacing the VPN-specific name servers with my general network servers. Is there a good way to prevent my DHCP client from updating /etc/resolv.conf while my VPN is active? ANSWER: If you are using the Ubuntu default with NetworkManager, try removing the CiscoVPN client and use the NetworkManager vpnc plugin to connect to the Cisco VPN. This should avoid all problems, since NetworkManager then knows about your VPN connection.
[ "linux", "vpn", "cisco" ]
4
2
6,729
7
0
2008-09-07T03:50:22.133000
2008-09-17T22:25:09.653000
48,123
48,734
Glade or no glade: What is the best way to use PyGtk?
I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade. The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade. I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem).
I would say that it depends: if you find that using Glade you can build the apps you want or need to make than that's absolutely fine. If however you actually want to learn how GTK works or you have some non-standard UI requirements you will have to dig into GTK internals (which are not that complicated). Personally I'm usually about 5 minutes into a rich client when I need some feature or customization that is simply impossible through a designer such as Glade or Stetic. Perhaps it's just me. Nevertheless it is still useful for me to bootstrap window design using a graphical tool. My recommendation: if making rich clients using GTK is going to be a significant part of your job/hobby then learn GTK as well since you will need to write that code someday. P.S. I personally find Stetic to be superior to Glade for design work, if a little bit more unstable.
Glade or no glade: What is the best way to use PyGtk? I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade. The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade. I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem).
TITLE: Glade or no glade: What is the best way to use PyGtk? QUESTION: I've been learning python for a while now with some success. I even managed to create one or two (simple) programs using PyGtk + Glade. The thing is: I am not sure if the best way to use GTK with python is by building the interfaces using Glade. I was wondering if the more experienced ones among us (remember, I'm just a beginner) could point out the benefits and caveats of using Glade as opposed to creating everything in the code itself (assuming that learning the correct gtk bindings wouldn't exactly be a problem). ANSWER: I would say that it depends: if you find that using Glade you can build the apps you want or need to make than that's absolutely fine. If however you actually want to learn how GTK works or you have some non-standard UI requirements you will have to dig into GTK internals (which are not that complicated). Personally I'm usually about 5 minutes into a rich client when I need some feature or customization that is simply impossible through a designer such as Glade or Stetic. Perhaps it's just me. Nevertheless it is still useful for me to bootstrap window design using a graphical tool. My recommendation: if making rich clients using GTK is going to be a significant part of your job/hobby then learn GTK as well since you will need to write that code someday. P.S. I personally find Stetic to be superior to Glade for design work, if a little bit more unstable.
[ "python", "gtk", "pygtk", "glade", "gtk2" ]
33
20
9,455
11
0
2008-09-07T04:00:41.437000
2008-09-07T20:09:47.990000
48,124
48,125
Generating (pseudo)random alpha-numeric strings
How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?
First make a string with all your possible characters: $characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; You could also use range() to do this more quickly. Then, in a loop, choose a random number and use it as the index to the $characters string to get a random character, and append it to your string: $string = ''; $max = strlen($characters) - 1; for ($i = 0; $i < $random_string_length; $i++) { $string.= $characters[mt_rand(0, $max)]; } $random_string_length is the length of the random string.
Generating (pseudo)random alpha-numeric strings How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP?
TITLE: Generating (pseudo)random alpha-numeric strings QUESTION: How can I generate a (pseudo)random alpha-numeric string, something like: 'd79jd8c' in PHP? ANSWER: First make a string with all your possible characters: $characters = 'abcdefghijklmnopqrstuvwxyz0123456789'; You could also use range() to do this more quickly. Then, in a loop, choose a random number and use it as the index to the $characters string to get a random character, and append it to your string: $string = ''; $max = strlen($characters) - 1; for ($i = 0; $i < $random_string_length; $i++) { $string.= $characters[mt_rand(0, $max)]; } $random_string_length is the length of the random string.
[ "php", "random" ]
87
166
105,435
18
0
2008-09-07T04:02:29.593000
2008-09-07T04:06:09.227000
48,126
48,161
PHP + MySql + Stored Procedures, how do I get access an "out" value?
Documentation is severely lacking on anything to do with stored procedures in mysql with PHP. I currently have a stored procedure that I call via PHP, how can I get the value of an out parameter?
it looks like it's answered in this post: http://forums.mysql.com/read.php?52,198596,198717#msg-198717 With mysqli PHP API: Assume sproc myproc( IN i int, OUT j int ): $mysqli = new mysqli( "HOST", "USR", "PWD", "DBNAME" ); $ivalue=1; $res = $mysqli->multi_query( "CALL myproc($ivalue,@x);SELECT @x" ); if( $res ) { $results = 0; do { if ($result = $mysqli->store_result()) { printf( " Result #%u: ", ++$results ); while( $row = $result->fetch_row() ) { foreach( $row as $cell ) echo $cell, " "; } $result->close(); if( $mysqli->more_results() ) echo " "; } } while( $mysqli->next_result() ); } $mysqli->close();
PHP + MySql + Stored Procedures, how do I get access an "out" value? Documentation is severely lacking on anything to do with stored procedures in mysql with PHP. I currently have a stored procedure that I call via PHP, how can I get the value of an out parameter?
TITLE: PHP + MySql + Stored Procedures, how do I get access an "out" value? QUESTION: Documentation is severely lacking on anything to do with stored procedures in mysql with PHP. I currently have a stored procedure that I call via PHP, how can I get the value of an out parameter? ANSWER: it looks like it's answered in this post: http://forums.mysql.com/read.php?52,198596,198717#msg-198717 With mysqli PHP API: Assume sproc myproc( IN i int, OUT j int ): $mysqli = new mysqli( "HOST", "USR", "PWD", "DBNAME" ); $ivalue=1; $res = $mysqli->multi_query( "CALL myproc($ivalue,@x);SELECT @x" ); if( $res ) { $results = 0; do { if ($result = $mysqli->store_result()) { printf( " Result #%u: ", ++$results ); while( $row = $result->fetch_row() ) { foreach( $row as $cell ) echo $cell, " "; } $result->close(); if( $mysqli->more_results() ) echo " "; } } while( $mysqli->next_result() ); } $mysqli->close();
[ "php", "mysql", "stored-procedures", "mysqli" ]
15
15
33,634
1
0
2008-09-07T04:06:34.137000
2008-09-07T04:58:27.197000
48,135
48,145
How can I allow incoming connections to a server inside of VirtualBox?
I have a NAT configured to run when loading up my favorite Linux distribution in VitualBox. This allows outgoing connections to work successfully. How do I allow incoming connections to this box, like, say, Web traffic? The IP address is 10.0.2.15. A ping request from my main box results in a Timeout.
VirtualBox (after version 1.3.8, anyway) will let you map incoming connections in the NAT configuration. There's an excellent tutorial on Aviran's Place that describes the steps to configure port mapping.
How can I allow incoming connections to a server inside of VirtualBox? I have a NAT configured to run when loading up my favorite Linux distribution in VitualBox. This allows outgoing connections to work successfully. How do I allow incoming connections to this box, like, say, Web traffic? The IP address is 10.0.2.15. A ping request from my main box results in a Timeout.
TITLE: How can I allow incoming connections to a server inside of VirtualBox? QUESTION: I have a NAT configured to run when loading up my favorite Linux distribution in VitualBox. This allows outgoing connections to work successfully. How do I allow incoming connections to this box, like, say, Web traffic? The IP address is 10.0.2.15. A ping request from my main box results in a Timeout. ANSWER: VirtualBox (after version 1.3.8, anyway) will let you map incoming connections in the NAT configuration. There's an excellent tutorial on Aviran's Place that describes the steps to configure port mapping.
[ "virtualbox" ]
4
5
5,040
1
0
2008-09-07T04:19:13.873000
2008-09-07T04:37:11.803000
48,144
48,153
What are advantages of bytecode over native code?
It seems like anything you can do with bytecode you can do just as easily and much faster in native code. In theory, you could even retain platform and language independence by distributing programs and libraries in bytecode then compiling to native code at installation, rather than JITing it. So in general, when would you want to execute bytecode instead of native?
Hank Shiffman from SGI said (a long time ago, but it's till true): There are three advantages of Java using byte code instead of going to the native code of the system: Portability: Each kind of computer has its unique instruction set. While some processors include the instructions for their predecessors, it's generally true that a program that runs on one kind of computer won't run on any other. Add in the services provided by the operating system, which each system describes in its own unique way, and you have a compatibility problem. In general, you can't write and compile a program for one kind of system and run it on any other without a lot of work. Java gets around this limitation by inserting its virtual machine between the application and the real environment (computer + operating system). If an application is compiled to Java byte code and that byte code is interpreted the same way in every environment then you can write a single program which will work on all the different platforms where Java is supported. (That's the theory, anyway. In practice there are always small incompatibilities lying in wait for the programmer.) Security: One of Java's virtues is its integration into the Web. Load a web page that uses Java into your browser and the Java code is automatically downloaded and executed. But what if the code destroys files, whether through malice or sloppiness on the programmer's part? Java prevents downloaded applets from doing anything destructive by disallowing potentially dangerous operations. Before it allows the code to run it examines it for attempts to bypass security. It verifies that data is used consistently: code that manipulates a data item as an integer at one stage and then tries to use it as a pointer later will be caught and prevented from executing. (The Java language doesn't allow pointer arithmetic, so you can't write Java code to do what we just described. However, there is nothing to prevent someone from writing destructive byte code themselves using a hexadecimal editor or even building a Java byte code assembler.) It generally isn't possible to analyze a program's machine code before execution and determine whether it does anything bad. Tricks like writing self-modifying code mean that the evil operations may not even exist until later. But Java byte code was designed for this kind of validation: it doesn't have the instructions a malicious programmer would use to hide their assault. Size: In the microprocessor world RISC is generally preferable over CISC. It's better to have a small instruction set and use many fast instructions to do a job than to have many complex operations implemented as single instructions. RISC designs require fewer gates on the chip to implement their instructions, allowing for more room for pipelines and other techniques to make each instruction faster. In an interpreter, however, none of this matters. If you want to implement a single instruction for the switch statement with a variable length depending on the number of case clauses, there's no reason not to do so. In fact, a complex instruction set is an advantage for a web-based language: it means that the same program will be smaller (fewer instructions of greater complexity), which means less time to transfer across our speed-limited network. So when considering byte code vs native, consider which trade-offs you want to make between portability, security, size, and execution speed. If speed is the only important factor, go native. If any of the others are more important, go with bytecode. I'll also add that maintaining a series of OS and architecture-targeted compilations of the same code base for every release can become very tedious. It's a huge win to use the same Java bytecode on multiple platforms and have it "just work."
What are advantages of bytecode over native code? It seems like anything you can do with bytecode you can do just as easily and much faster in native code. In theory, you could even retain platform and language independence by distributing programs and libraries in bytecode then compiling to native code at installation, rather than JITing it. So in general, when would you want to execute bytecode instead of native?
TITLE: What are advantages of bytecode over native code? QUESTION: It seems like anything you can do with bytecode you can do just as easily and much faster in native code. In theory, you could even retain platform and language independence by distributing programs and libraries in bytecode then compiling to native code at installation, rather than JITing it. So in general, when would you want to execute bytecode instead of native? ANSWER: Hank Shiffman from SGI said (a long time ago, but it's till true): There are three advantages of Java using byte code instead of going to the native code of the system: Portability: Each kind of computer has its unique instruction set. While some processors include the instructions for their predecessors, it's generally true that a program that runs on one kind of computer won't run on any other. Add in the services provided by the operating system, which each system describes in its own unique way, and you have a compatibility problem. In general, you can't write and compile a program for one kind of system and run it on any other without a lot of work. Java gets around this limitation by inserting its virtual machine between the application and the real environment (computer + operating system). If an application is compiled to Java byte code and that byte code is interpreted the same way in every environment then you can write a single program which will work on all the different platforms where Java is supported. (That's the theory, anyway. In practice there are always small incompatibilities lying in wait for the programmer.) Security: One of Java's virtues is its integration into the Web. Load a web page that uses Java into your browser and the Java code is automatically downloaded and executed. But what if the code destroys files, whether through malice or sloppiness on the programmer's part? Java prevents downloaded applets from doing anything destructive by disallowing potentially dangerous operations. Before it allows the code to run it examines it for attempts to bypass security. It verifies that data is used consistently: code that manipulates a data item as an integer at one stage and then tries to use it as a pointer later will be caught and prevented from executing. (The Java language doesn't allow pointer arithmetic, so you can't write Java code to do what we just described. However, there is nothing to prevent someone from writing destructive byte code themselves using a hexadecimal editor or even building a Java byte code assembler.) It generally isn't possible to analyze a program's machine code before execution and determine whether it does anything bad. Tricks like writing self-modifying code mean that the evil operations may not even exist until later. But Java byte code was designed for this kind of validation: it doesn't have the instructions a malicious programmer would use to hide their assault. Size: In the microprocessor world RISC is generally preferable over CISC. It's better to have a small instruction set and use many fast instructions to do a job than to have many complex operations implemented as single instructions. RISC designs require fewer gates on the chip to implement their instructions, allowing for more room for pipelines and other techniques to make each instruction faster. In an interpreter, however, none of this matters. If you want to implement a single instruction for the switch statement with a variable length depending on the number of case clauses, there's no reason not to do so. In fact, a complex instruction set is an advantage for a web-based language: it means that the same program will be smaller (fewer instructions of greater complexity), which means less time to transfer across our speed-limited network. So when considering byte code vs native, consider which trade-offs you want to make between portability, security, size, and execution speed. If speed is the only important factor, go native. If any of the others are more important, go with bytecode. I'll also add that maintaining a series of OS and architecture-targeted compilations of the same code base for every release can become very tedious. It's a huge win to use the same Java bytecode on multiple platforms and have it "just work."
[ "java", ".net", "bytecode" ]
41
33
33,069
8
0
2008-09-07T04:36:27.437000
2008-09-07T04:46:27.147000
48,148
48,171
Tool for analyzing .Net app memory dumps
Can somebody suggest a good free tool for analyzing.Net memory dumps other than Adplus/windbg/sos?
You can load sos and your memory dump into Visual Studio to at least insulate you from the 'interesting' ui that WinDbg presents.
Tool for analyzing .Net app memory dumps Can somebody suggest a good free tool for analyzing.Net memory dumps other than Adplus/windbg/sos?
TITLE: Tool for analyzing .Net app memory dumps QUESTION: Can somebody suggest a good free tool for analyzing.Net memory dumps other than Adplus/windbg/sos? ANSWER: You can load sos and your memory dump into Visual Studio to at least insulate you from the 'interesting' ui that WinDbg presents.
[ ".net", "memory-dump", "postmortem-debugging" ]
22
3
15,913
6
0
2008-09-07T04:39:17.350000
2008-09-07T05:16:58.883000
48,157
48,166
Configure static routes on Windows
There is a netsh and a route command on Windows. From their help text it looks like both can be used to configure static routes. When should you use one and not the other? Is IPv6 a distinguishing factor here?
route is a very old and basic tool for displaying and modifying the entries in the local IP routing table while netsh is the newer, more robust command-line scripting utility that allows you to, either locally or remotely, manipulate the network configuration. netsh has a zillion more features than route; it can even save your current settings as a script that another instance of netsh can parse. Check out Using netsh to see the giant feature set and compare it to how very basic and simple routes is.
Configure static routes on Windows There is a netsh and a route command on Windows. From their help text it looks like both can be used to configure static routes. When should you use one and not the other? Is IPv6 a distinguishing factor here?
TITLE: Configure static routes on Windows QUESTION: There is a netsh and a route command on Windows. From their help text it looks like both can be used to configure static routes. When should you use one and not the other? Is IPv6 a distinguishing factor here? ANSWER: route is a very old and basic tool for displaying and modifying the entries in the local IP routing table while netsh is the newer, more robust command-line scripting utility that allows you to, either locally or remotely, manipulate the network configuration. netsh has a zillion more features than route; it can even save your current settings as a script that another instance of netsh can parse. Check out Using netsh to see the giant feature set and compare it to how very basic and simple routes is.
[ "windows", "networking" ]
1
4
1,899
1
0
2008-09-07T04:53:39.563000
2008-09-07T05:04:05.763000
48,179
48,404
Video Thumbnails in Java
I want to generate a thumbnail preview of videos in Java. I'm mostly JMF and video manipulation alienated. Is there an easy way to do it? What about codecs? Will I have to deal with it? Any video type is suported? (including Quicktime)
There seems to be a few examples out there that are far better than what I was going to send you. See http://krishnabhargav.blogspot.com/2008/02/processing-videos-in-java.html. I'd agree with Stu, however. If you can find a way to get what you want using some command-line tools (and run them using Commons-Exec ), you might have a better overall solution than depending on what is essentially the Sanskrit of Java extensions.
Video Thumbnails in Java I want to generate a thumbnail preview of videos in Java. I'm mostly JMF and video manipulation alienated. Is there an easy way to do it? What about codecs? Will I have to deal with it? Any video type is suported? (including Quicktime)
TITLE: Video Thumbnails in Java QUESTION: I want to generate a thumbnail preview of videos in Java. I'm mostly JMF and video manipulation alienated. Is there an easy way to do it? What about codecs? Will I have to deal with it? Any video type is suported? (including Quicktime) ANSWER: There seems to be a few examples out there that are far better than what I was going to send you. See http://krishnabhargav.blogspot.com/2008/02/processing-videos-in-java.html. I'd agree with Stu, however. If you can find a way to get what you want using some command-line tools (and run them using Commons-Exec ), you might have a better overall solution than depending on what is essentially the Sanskrit of Java extensions.
[ "java", "video", "jmf" ]
15
7
30,342
5
0
2008-09-07T05:35:36.170000
2008-09-07T12:58:28.807000
48,198
48,199
How do I find out which process is listening on a TCP or UDP port on Windows?
How do I find out which process is listening on a TCP or UDP port on Windows?
PowerShell TCP Get-Process -Id (Get-NetTCPConnection -LocalPort YourPortNumberHere).OwningProcess UDP Get-Process -Id (Get-NetUDPEndpoint -LocalPort YourPortNumberHere).OwningProcess cmd netstat -a -b (Add -n to stop it trying to resolve hostnames, which will make it a lot faster.) Note Dane's recommendation for TCPView. It looks very useful! -a Displays all connections and listening ports. -b Displays the executable involved in creating each connection or listening port. In some cases well-known executables host multiple independent components, and in these cases the sequence of components involved in creating the connection or listening port is displayed. In this case the executable name is in [] at the bottom, on top is the component it called, and so forth until TCP/IP was reached. Note that this option can be time-consuming and will fail unless you have sufficient permissions. -n Displays addresses and port numbers in numerical form. -o Displays the owning process ID associated with each connection.
How do I find out which process is listening on a TCP or UDP port on Windows? How do I find out which process is listening on a TCP or UDP port on Windows?
TITLE: How do I find out which process is listening on a TCP or UDP port on Windows? QUESTION: How do I find out which process is listening on a TCP or UDP port on Windows? ANSWER: PowerShell TCP Get-Process -Id (Get-NetTCPConnection -LocalPort YourPortNumberHere).OwningProcess UDP Get-Process -Id (Get-NetUDPEndpoint -LocalPort YourPortNumberHere).OwningProcess cmd netstat -a -b (Add -n to stop it trying to resolve hostnames, which will make it a lot faster.) Note Dane's recommendation for TCPView. It looks very useful! -a Displays all connections and listening ports. -b Displays the executable involved in creating each connection or listening port. In some cases well-known executables host multiple independent components, and in these cases the sequence of components involved in creating the connection or listening port is displayed. In this case the executable name is in [] at the bottom, on top is the component it called, and so forth until TCP/IP was reached. Note that this option can be time-consuming and will fail unless you have sufficient permissions. -n Displays addresses and port numbers in numerical form. -o Displays the owning process ID associated with each connection.
[ "windows", "networking", "port" ]
3,298
3,761
5,422,595
34
0
2008-09-07T06:26:12.993000
2008-09-07T06:28:33.970000
48,203
48,217
Linux distros for Java Development
Simply, are there any Java Developer specific Linux distros?
A real Sun geek would chime in here about the virtues of using Solaris as a Java development platform, but I am much more ambivalent. Developing with Java is about the same on any linux distro; you are going to wind up having to install the JDK and tools of your choosing (Eclipse, Sun Studio, Tomcat, etc) so you may as well choose a distro on other criteria... perhaps how comfortable you are with it, how easy package management is, and if the look & feel suit your development habits are all big factors. So, to answer your question more directly, a Java developer would do well with any major linux distro that they are comfortable with using in general. If you want some Java goodness out of the box, Fedora 9 and Ubuntu 8.04 have OpenJDK (and NetBeans) according to a recent announcement.
Linux distros for Java Development Simply, are there any Java Developer specific Linux distros?
TITLE: Linux distros for Java Development QUESTION: Simply, are there any Java Developer specific Linux distros? ANSWER: A real Sun geek would chime in here about the virtues of using Solaris as a Java development platform, but I am much more ambivalent. Developing with Java is about the same on any linux distro; you are going to wind up having to install the JDK and tools of your choosing (Eclipse, Sun Studio, Tomcat, etc) so you may as well choose a distro on other criteria... perhaps how comfortable you are with it, how easy package management is, and if the look & feel suit your development habits are all big factors. So, to answer your question more directly, a Java developer would do well with any major linux distro that they are comfortable with using in general. If you want some Java goodness out of the box, Fedora 9 and Ubuntu 8.04 have OpenJDK (and NetBeans) according to a recent announcement.
[ "java", "linux", "distro" ]
19
32
45,002
18
0
2008-09-07T06:32:58.513000
2008-09-07T07:18:01.667000
48,215
48,302
jQuery & Objects, trying to make a lightweight widget
Trying to make a make generic select "control" that I can dynamically add elements to, but I am having trouble getting functions to work right. This is what I started with. $select = $(" "); $select.addOption = function(value,text){ $(this).append($(" ").val(value).text(text)); }; This worked fine alone but anytime $select is.clone(true) 'ed the addOption() function is lost. This is my object approach but still the function does not work. function $selectX() { return $(" "); } $selectX.prototype.addOption() = function(value,text){ $(this).append($(" ").val(value).text(text)); }; Hack solution is to add the function manually after creation: $nameSelect= new $selectX; $nameSelect.addOption = function(value,text){ $(this).append($(" ").val(value).text(text)); }; Am I barking up the wrong tree?
To add new method to jQuery You need to use jQuery.fn.methodName attribute, so in this case it will be: jQuery.fn.addOption = function (value, text) { jQuery(this).append(jQuery(' ').val(value).text(text)); }; But keep in mind that this addOption will be accessible from result of any $() call.
jQuery & Objects, trying to make a lightweight widget Trying to make a make generic select "control" that I can dynamically add elements to, but I am having trouble getting functions to work right. This is what I started with. $select = $(" "); $select.addOption = function(value,text){ $(this).append($(" ").val(value).text(text)); }; This worked fine alone but anytime $select is.clone(true) 'ed the addOption() function is lost. This is my object approach but still the function does not work. function $selectX() { return $(" "); } $selectX.prototype.addOption() = function(value,text){ $(this).append($(" ").val(value).text(text)); }; Hack solution is to add the function manually after creation: $nameSelect= new $selectX; $nameSelect.addOption = function(value,text){ $(this).append($(" ").val(value).text(text)); }; Am I barking up the wrong tree?
TITLE: jQuery & Objects, trying to make a lightweight widget QUESTION: Trying to make a make generic select "control" that I can dynamically add elements to, but I am having trouble getting functions to work right. This is what I started with. $select = $(" "); $select.addOption = function(value,text){ $(this).append($(" ").val(value).text(text)); }; This worked fine alone but anytime $select is.clone(true) 'ed the addOption() function is lost. This is my object approach but still the function does not work. function $selectX() { return $(" "); } $selectX.prototype.addOption() = function(value,text){ $(this).append($(" ").val(value).text(text)); }; Hack solution is to add the function manually after creation: $nameSelect= new $selectX; $nameSelect.addOption = function(value,text){ $(this).append($(" ").val(value).text(text)); }; Am I barking up the wrong tree? ANSWER: To add new method to jQuery You need to use jQuery.fn.methodName attribute, so in this case it will be: jQuery.fn.addOption = function (value, text) { jQuery(this).append(jQuery(' ').val(value).text(text)); }; But keep in mind that this addOption will be accessible from result of any $() call.
[ "javascript", "jquery" ]
8
7
417
1
0
2008-09-07T07:11:51.447000
2008-09-07T10:41:46.187000
48,224
48,234
How to use webclient in a secure site?
I need to automate a process involving a website that is using a login form. I need to capture some data in the pages following the login page. I know how to screen-scrape normal pages, but not those behind a secure site. Can this be done with the.NET WebClient class? How would I automatically login? How would I keep logged in for the other pages?
One way would be through automating a browser -- you mentioned WebClient, so I'm guessing you might be referring to WebClient in.NET. Two main points: There's nothing special about https related to WebClient - it just works Cookies are typically used to carry authentication -- you'll need to capture and replay them Here's the steps I'd follow: GET the login form, capture the the cookie in the response. Using Xpath and HtmlAgilityPack, find the "input type=hidden" field names and values. POST to login form's action with user name, password, and hidden field values in the request body. Include the cookie in the request headers. Again, capture the cookie in the response. GET the pages you want, again, with the cookie in the request headers. On step 2, I mention a somewhat complicated method for automating the login. Usually, you can post with username and password directly to the known login form action without getting the initial form or relaying the hidden fields. Some sites have form validation (different from field validation) on their forms which makes this method not work. HtmlAgilityPack is a.NET library that allows you to turn ill-formed html into an XmlDocument so you can XPath over it. Quite useful. Finally, you may run into a situation where the form relies on client script to alter the form values before submitting. You may need to simulate this behavior. Using a tool to view the http traffic for this type of work is extremely helpful - I recommend ieHttpHeaders, Fiddler, or FireBug (net tab).
How to use webclient in a secure site? I need to automate a process involving a website that is using a login form. I need to capture some data in the pages following the login page. I know how to screen-scrape normal pages, but not those behind a secure site. Can this be done with the.NET WebClient class? How would I automatically login? How would I keep logged in for the other pages?
TITLE: How to use webclient in a secure site? QUESTION: I need to automate a process involving a website that is using a login form. I need to capture some data in the pages following the login page. I know how to screen-scrape normal pages, but not those behind a secure site. Can this be done with the.NET WebClient class? How would I automatically login? How would I keep logged in for the other pages? ANSWER: One way would be through automating a browser -- you mentioned WebClient, so I'm guessing you might be referring to WebClient in.NET. Two main points: There's nothing special about https related to WebClient - it just works Cookies are typically used to carry authentication -- you'll need to capture and replay them Here's the steps I'd follow: GET the login form, capture the the cookie in the response. Using Xpath and HtmlAgilityPack, find the "input type=hidden" field names and values. POST to login form's action with user name, password, and hidden field values in the request body. Include the cookie in the request headers. Again, capture the cookie in the response. GET the pages you want, again, with the cookie in the request headers. On step 2, I mention a somewhat complicated method for automating the login. Usually, you can post with username and password directly to the known login form action without getting the initial form or relaying the hidden fields. Some sites have form validation (different from field validation) on their forms which makes this method not work. HtmlAgilityPack is a.NET library that allows you to turn ill-formed html into an XmlDocument so you can XPath over it. Quite useful. Finally, you may run into a situation where the form relies on client script to alter the form values before submitting. You may need to simulate this behavior. Using a tool to view the http traffic for this type of work is extremely helpful - I recommend ieHttpHeaders, Fiddler, or FireBug (net tab).
[ ".net", "screen-scraping" ]
7
9
3,663
4
0
2008-09-07T07:40:20.693000
2008-09-07T08:02:03.853000
48,235
692,397
How can I help port Google Chrome to Linux?
I really enjoy Chrome, and the sheer exercise of helping a port would boost my knowledge-base. Where do I start? What are the fundamental similarities and differences between the code which will operated under Windows and Linux? What skills and software do I need? Note: The official website is Visual Studio oriented! Netbeans or Eclipse are my only options. I will not pay Microsoft to help an Open Source project.
EDIT: (2/6/10) A Beta version of Chrome has been released for Linux. Although it is labeled beta, it works great on my Ubuntu box. You can download it from Google: http://www.google.com/chrome?platform=linux EDIT: (5/31/09) Since I answered this question, there have been more new developments in Chrome (actually "Chromium") for Linux: An alpha build has been released. This means it's not fully functional. If you use Ubuntu, you're in luck: add the following lines to your /etc/apt/sources.list deb http://ppa.launchpad.net/chromium-daily/ppa/ubuntu jaunty main deb-src http://ppa.launchpad.net/chromium-daily/ppa/ubuntu jaunty main Then, at the command line: aptitude update aptitude install chromium-browser Don't forget to s/jaunty/yourUbuntuVersion/ if necessary. Also, you can s/aptitude/apt-get/, if you insist. And.... Yes, it works. I'm typing this in my freshly installed Chromium browser right now! The build is hosted by launchpad, and gave me some security warnings upon install, which I promptly ignored. Here's the website: https://launchpad.net/~chromium-daily/+archive/ppa The original answer: Linux Build Instructions
How can I help port Google Chrome to Linux? I really enjoy Chrome, and the sheer exercise of helping a port would boost my knowledge-base. Where do I start? What are the fundamental similarities and differences between the code which will operated under Windows and Linux? What skills and software do I need? Note: The official website is Visual Studio oriented! Netbeans or Eclipse are my only options. I will not pay Microsoft to help an Open Source project.
TITLE: How can I help port Google Chrome to Linux? QUESTION: I really enjoy Chrome, and the sheer exercise of helping a port would boost my knowledge-base. Where do I start? What are the fundamental similarities and differences between the code which will operated under Windows and Linux? What skills and software do I need? Note: The official website is Visual Studio oriented! Netbeans or Eclipse are my only options. I will not pay Microsoft to help an Open Source project. ANSWER: EDIT: (2/6/10) A Beta version of Chrome has been released for Linux. Although it is labeled beta, it works great on my Ubuntu box. You can download it from Google: http://www.google.com/chrome?platform=linux EDIT: (5/31/09) Since I answered this question, there have been more new developments in Chrome (actually "Chromium") for Linux: An alpha build has been released. This means it's not fully functional. If you use Ubuntu, you're in luck: add the following lines to your /etc/apt/sources.list deb http://ppa.launchpad.net/chromium-daily/ppa/ubuntu jaunty main deb-src http://ppa.launchpad.net/chromium-daily/ppa/ubuntu jaunty main Then, at the command line: aptitude update aptitude install chromium-browser Don't forget to s/jaunty/yourUbuntuVersion/ if necessary. Also, you can s/aptitude/apt-get/, if you insist. And.... Yes, it works. I'm typing this in my freshly installed Chromium browser right now! The build is hosted by launchpad, and gave me some security warnings upon install, which I promptly ignored. Here's the website: https://launchpad.net/~chromium-daily/+archive/ppa The original answer: Linux Build Instructions
[ "linux", "google-chrome", "porting" ]
5
14
1,407
2
0
2008-09-07T08:03:45.050000
2009-03-28T07:41:51.487000
48,239
48,684
Getting the ID of the element that fired an event
Is there any way to get the ID of the element that fires an event? I'm thinking something like: $(document).ready(function() { $("a").click(function() { var test = caller.id; alert(test.val()); }); }); Except of course that the var test should contain the id "aaa", if the event is fired from the first form, and "bbb", if the event is fired from the second form.
In jQuery event.target always refers to the element that triggered the event, where event is the parameter passed to the function. http://api.jquery.com/category/events/event-object/ $(document).ready(function() { $("a").click(function(event) { alert(event.target.id); }); }); Note also that this will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as $(this), e.g.: $(document).ready(function() { $("a").click(function(event) { // this.append wouldn't work $(this).append(" Clicked"); }); });
Getting the ID of the element that fired an event Is there any way to get the ID of the element that fires an event? I'm thinking something like: $(document).ready(function() { $("a").click(function() { var test = caller.id; alert(test.val()); }); }); Except of course that the var test should contain the id "aaa", if the event is fired from the first form, and "bbb", if the event is fired from the second form.
TITLE: Getting the ID of the element that fired an event QUESTION: Is there any way to get the ID of the element that fires an event? I'm thinking something like: $(document).ready(function() { $("a").click(function() { var test = caller.id; alert(test.val()); }); }); Except of course that the var test should contain the id "aaa", if the event is fired from the first form, and "bbb", if the event is fired from the second form. ANSWER: In jQuery event.target always refers to the element that triggered the event, where event is the parameter passed to the function. http://api.jquery.com/category/events/event-object/ $(document).ready(function() { $("a").click(function(event) { alert(event.target.id); }); }); Note also that this will also work, but that it is not a jQuery object, so if you wish to use a jQuery function on it then you must refer to it as $(this), e.g.: $(document).ready(function() { $("a").click(function(event) { // this.append wouldn't work $(this).append(" Clicked"); }); });
[ "javascript", "jquery", "dom-events" ]
1,095
1,411
1,590,426
24
0
2008-09-07T08:09:38.610000
2008-09-07T19:02:37.010000
48,250
48,399
Free JSP plugin for eclipse?
I was looking out for a free plugin for developing/debugging JSP pages in eclipse. Any suggestions?
BEA seems to have a free one BEA JSP plugin - not used it, so not sure how good it is. Oracle now owns BEA, and they have this plugin which might do a similar job.
Free JSP plugin for eclipse? I was looking out for a free plugin for developing/debugging JSP pages in eclipse. Any suggestions?
TITLE: Free JSP plugin for eclipse? QUESTION: I was looking out for a free plugin for developing/debugging JSP pages in eclipse. Any suggestions? ANSWER: BEA seems to have a free one BEA JSP plugin - not used it, so not sure how good it is. Oracle now owns BEA, and they have this plugin which might do a similar job.
[ "eclipse", "jsp" ]
8
4
12,973
3
0
2008-09-07T08:23:51.430000
2008-09-07T12:54:52.557000
48,253
48,389
Compile a PHP script in Linux
I know PHP scripts don't actually compile until they are run. However, say I want to create a small simple program and compile it to a binary without requiring the PHP binary. How could I do this? I've seen a few IDE's out there that would do this, but either they are all for windows or the Linux versions don't actually build properly. What I would like is something like py2exe that does it in the script itself.
Check out phc: the PHP compiler If you just want to run it like a script, you may not need to compile it per se, but just run it via the command line. Read running PHP via the command line.
Compile a PHP script in Linux I know PHP scripts don't actually compile until they are run. However, say I want to create a small simple program and compile it to a binary without requiring the PHP binary. How could I do this? I've seen a few IDE's out there that would do this, but either they are all for windows or the Linux versions don't actually build properly. What I would like is something like py2exe that does it in the script itself.
TITLE: Compile a PHP script in Linux QUESTION: I know PHP scripts don't actually compile until they are run. However, say I want to create a small simple program and compile it to a binary without requiring the PHP binary. How could I do this? I've seen a few IDE's out there that would do this, but either they are all for windows or the Linux versions don't actually build properly. What I would like is something like py2exe that does it in the script itself. ANSWER: Check out phc: the PHP compiler If you just want to run it like a script, you may not need to compile it per se, but just run it via the command line. Read running PHP via the command line.
[ "php", "linux" ]
12
9
16,985
3
0
2008-09-07T08:32:11.690000
2008-09-07T12:39:17.680000
48,257
96,691
SharePoint Infrastructure Upgrade - whoops
I applied the MOSS infrastructure upgrade w/o applying the WSS one before it -- uh, help!
Quoting: Infrastructure Update for Microsoft Office Servers (KB951297) Other Relevant Updates It is strongly recommended that you install the Infrastructure Update for Windows SharePoint Services 3.0 (KB951695) before installing this update on any of the Office Servers listed in the system requirements section above. Therefore not applying first Infrastructure Update for WSS seem to be not recommended but not unsupported
SharePoint Infrastructure Upgrade - whoops I applied the MOSS infrastructure upgrade w/o applying the WSS one before it -- uh, help!
TITLE: SharePoint Infrastructure Upgrade - whoops QUESTION: I applied the MOSS infrastructure upgrade w/o applying the WSS one before it -- uh, help! ANSWER: Quoting: Infrastructure Update for Microsoft Office Servers (KB951297) Other Relevant Updates It is strongly recommended that you install the Infrastructure Update for Windows SharePoint Services 3.0 (KB951695) before installing this update on any of the Office Servers listed in the system requirements section above. Therefore not applying first Infrastructure Update for WSS seem to be not recommended but not unsupported
[ "sharepoint" ]
1
1
350
5
0
2008-09-07T08:36:14.647000
2008-09-18T20:39:28.170000
48,271
48,296
Setting DataGridView.DefaultCellStyle.NullValue to null at designtime raises error at adding rows runtime
In Visual Studio 2008 add a new DataGridView to a form Edit Columns Add a a new DataGridViewImageColumn Open the CellStyle Builder of this column (DefaultCellStyle property) Change the NullValue from System.Drawing.Bitmap to null Try to add a new Row to the DataGridView at runtime (dataGridView1.Rows.Add();) You get this error: System.FormatException: Formatted value of the cell has a wrong type. If you change back the NullValue to System.Drawing.Bitmap (as it was) you still get the same error at adding a row. If you set the NullValue at runtime instead of designtime you don't get anny error. (dataGridView1.Columns[0].DefaultCellStyle.NullValue = null;) Could you tell me why is that?
This may well be a bug in the designer; if you take a look around at the.designer.cs file (maybe doing a diff from before and after you set NullValue to null) you should be able to see the code it generates.
Setting DataGridView.DefaultCellStyle.NullValue to null at designtime raises error at adding rows runtime In Visual Studio 2008 add a new DataGridView to a form Edit Columns Add a a new DataGridViewImageColumn Open the CellStyle Builder of this column (DefaultCellStyle property) Change the NullValue from System.Drawing.Bitmap to null Try to add a new Row to the DataGridView at runtime (dataGridView1.Rows.Add();) You get this error: System.FormatException: Formatted value of the cell has a wrong type. If you change back the NullValue to System.Drawing.Bitmap (as it was) you still get the same error at adding a row. If you set the NullValue at runtime instead of designtime you don't get anny error. (dataGridView1.Columns[0].DefaultCellStyle.NullValue = null;) Could you tell me why is that?
TITLE: Setting DataGridView.DefaultCellStyle.NullValue to null at designtime raises error at adding rows runtime QUESTION: In Visual Studio 2008 add a new DataGridView to a form Edit Columns Add a a new DataGridViewImageColumn Open the CellStyle Builder of this column (DefaultCellStyle property) Change the NullValue from System.Drawing.Bitmap to null Try to add a new Row to the DataGridView at runtime (dataGridView1.Rows.Add();) You get this error: System.FormatException: Formatted value of the cell has a wrong type. If you change back the NullValue to System.Drawing.Bitmap (as it was) you still get the same error at adding a row. If you set the NullValue at runtime instead of designtime you don't get anny error. (dataGridView1.Columns[0].DefaultCellStyle.NullValue = null;) Could you tell me why is that? ANSWER: This may well be a bug in the designer; if you take a look around at the.designer.cs file (maybe doing a diff from before and after you set NullValue to null) you should be able to see the code it generates.
[ "c#", "datagridview", "null" ]
4
2
14,899
5
0
2008-09-07T09:28:23.023000
2008-09-07T10:29:34.983000
48,278
51,298
How to print css applied background images with WebBrowser control
I am using the webbrowser control in winforms and discovered now that background images which I apply with css are not included in the printouts. Is there a way to make the webbrowser print the background of the displayed document too? Edit: Since I wanted to do this programatically, I opted for this solution: using Microsoft.Win32;... RegistryKey regKey = Registry.CurrentUser.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Internet Explorer").OpenSubKey("Main"); //Get the current setting so that we can revert it after printjob var defaultValue = regKey.GetValue("Print_Background"); regKey.SetValue("Print_Background", "yes"); //Do the printing //Revert the registry key to the original value regKey.SetValue("Print_Background", defaultValue); Another way to handle this might be to just read the value, and notify the user to adjust this himself before printing. I have to agree that tweaking with the registry like this is not a good practice, so I am open for any suggestions. Thanks for all your feedback
If you're going to go and change an important system setting, make sure to first read the current setting and restore it when you are done. I consider this very bad practice in the first place, but if you must do it then be kind. Registry.LocalMachine Also, try changing LocalUser instead of LocalMachine - that way if your app crashes (and it will), then you'll only confounded the user, not everyone who uses the machine.
How to print css applied background images with WebBrowser control I am using the webbrowser control in winforms and discovered now that background images which I apply with css are not included in the printouts. Is there a way to make the webbrowser print the background of the displayed document too? Edit: Since I wanted to do this programatically, I opted for this solution: using Microsoft.Win32;... RegistryKey regKey = Registry.CurrentUser.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Internet Explorer").OpenSubKey("Main"); //Get the current setting so that we can revert it after printjob var defaultValue = regKey.GetValue("Print_Background"); regKey.SetValue("Print_Background", "yes"); //Do the printing //Revert the registry key to the original value regKey.SetValue("Print_Background", defaultValue); Another way to handle this might be to just read the value, and notify the user to adjust this himself before printing. I have to agree that tweaking with the registry like this is not a good practice, so I am open for any suggestions. Thanks for all your feedback
TITLE: How to print css applied background images with WebBrowser control QUESTION: I am using the webbrowser control in winforms and discovered now that background images which I apply with css are not included in the printouts. Is there a way to make the webbrowser print the background of the displayed document too? Edit: Since I wanted to do this programatically, I opted for this solution: using Microsoft.Win32;... RegistryKey regKey = Registry.CurrentUser.OpenSubKey("Software").OpenSubKey("Microsoft").OpenSubKey("Internet Explorer").OpenSubKey("Main"); //Get the current setting so that we can revert it after printjob var defaultValue = regKey.GetValue("Print_Background"); regKey.SetValue("Print_Background", "yes"); //Do the printing //Revert the registry key to the original value regKey.SetValue("Print_Background", defaultValue); Another way to handle this might be to just read the value, and notify the user to adjust this himself before printing. I have to agree that tweaking with the registry like this is not a good practice, so I am open for any suggestions. Thanks for all your feedback ANSWER: If you're going to go and change an important system setting, make sure to first read the current setting and restore it when you are done. I consider this very bad practice in the first place, but if you must do it then be kind. Registry.LocalMachine Also, try changing LocalUser instead of LocalMachine - that way if your app crashes (and it will), then you'll only confounded the user, not everyone who uses the machine.
[ "c#", ".net", "printing", "registry", "webbrowser-control" ]
4
1
4,818
5
0
2008-09-07T09:51:09.270000
2008-09-09T06:35:02.097000
48,288
48,318
Unexpected behaviour of Process.MainWindowHandle
I've been trying to understand Process.MainWindowHandle. According to MSDN; "The main window is the window that is created when the process is started. After initialization, other windows may be opened, including the Modal and TopLevel windows, but the first window associated with the process remains the main window." (Emphasis added) But while debugging I noticed that MainWindowHandle seemed to change value... which I wasn't expecting, especially after consulting the documentation above. To confirm the behaviour I created a standalone WinForms app with a timer to check the MainWindowHandle of the "DEVENV" (Visual Studio) process every 100ms. Here's the interesting part of this test app... IntPtr oldHWnd = IntPtr.Zero; void GetMainwindowHandle() { Process[] processes = Process.GetProcessesByName("DEVENV"); if (processes.Length!=1) return; IntPtr newHWnd = processes[0].MainWindowHandle; if (newHWnd!= oldHWnd) { oldHWnd = newHWnd; textBox1.AppendText(processes[0].MainWindowHandle.ToString("X")+"\r\n"); } } private void timer1Tick(object sender, EventArgs e) { GetMainwindowHandle(); } You can see the value of MainWindowHandle changing when you (for example) click on a drop-down menu inside VS. Perhaps I've misunderstood the documentation. Can anyone shed light?
@edg, I guess it's an error in MSDN. You can clearly see in Relfector, that "Main window" check in.NET looks like: private bool IsMainWindow(IntPtr handle) { return (!(NativeMethods.GetWindow(new HandleRef(this, handle), 4)!= IntPtr.Zero) && NativeMethods.IsWindowVisible(new HandleRef(this, handle))); } When.NET code enumerates windows, it's pretty obvious that first visible window (i.e. top level window) will match this criteria.
Unexpected behaviour of Process.MainWindowHandle I've been trying to understand Process.MainWindowHandle. According to MSDN; "The main window is the window that is created when the process is started. After initialization, other windows may be opened, including the Modal and TopLevel windows, but the first window associated with the process remains the main window." (Emphasis added) But while debugging I noticed that MainWindowHandle seemed to change value... which I wasn't expecting, especially after consulting the documentation above. To confirm the behaviour I created a standalone WinForms app with a timer to check the MainWindowHandle of the "DEVENV" (Visual Studio) process every 100ms. Here's the interesting part of this test app... IntPtr oldHWnd = IntPtr.Zero; void GetMainwindowHandle() { Process[] processes = Process.GetProcessesByName("DEVENV"); if (processes.Length!=1) return; IntPtr newHWnd = processes[0].MainWindowHandle; if (newHWnd!= oldHWnd) { oldHWnd = newHWnd; textBox1.AppendText(processes[0].MainWindowHandle.ToString("X")+"\r\n"); } } private void timer1Tick(object sender, EventArgs e) { GetMainwindowHandle(); } You can see the value of MainWindowHandle changing when you (for example) click on a drop-down menu inside VS. Perhaps I've misunderstood the documentation. Can anyone shed light?
TITLE: Unexpected behaviour of Process.MainWindowHandle QUESTION: I've been trying to understand Process.MainWindowHandle. According to MSDN; "The main window is the window that is created when the process is started. After initialization, other windows may be opened, including the Modal and TopLevel windows, but the first window associated with the process remains the main window." (Emphasis added) But while debugging I noticed that MainWindowHandle seemed to change value... which I wasn't expecting, especially after consulting the documentation above. To confirm the behaviour I created a standalone WinForms app with a timer to check the MainWindowHandle of the "DEVENV" (Visual Studio) process every 100ms. Here's the interesting part of this test app... IntPtr oldHWnd = IntPtr.Zero; void GetMainwindowHandle() { Process[] processes = Process.GetProcessesByName("DEVENV"); if (processes.Length!=1) return; IntPtr newHWnd = processes[0].MainWindowHandle; if (newHWnd!= oldHWnd) { oldHWnd = newHWnd; textBox1.AppendText(processes[0].MainWindowHandle.ToString("X")+"\r\n"); } } private void timer1Tick(object sender, EventArgs e) { GetMainwindowHandle(); } You can see the value of MainWindowHandle changing when you (for example) click on a drop-down menu inside VS. Perhaps I've misunderstood the documentation. Can anyone shed light? ANSWER: @edg, I guess it's an error in MSDN. You can clearly see in Relfector, that "Main window" check in.NET looks like: private bool IsMainWindow(IntPtr handle) { return (!(NativeMethods.GetWindow(new HandleRef(this, handle), 4)!= IntPtr.Zero) && NativeMethods.IsWindowVisible(new HandleRef(this, handle))); } When.NET code enumerates windows, it's pretty obvious that first visible window (i.e. top level window) will match this criteria.
[ "c#", ".net", "msdn" ]
10
11
5,263
2
0
2008-09-07T10:14:23.037000
2008-09-07T11:06:14.630000
48,293
48,332
Running a regular background event in Java web app
In podcast #15, Jeff mentioned he twittered about how to run a regular event in the background as if it was a normal function - unfortunately I can't seem to find that through twitter. Now I need to do a similar thing and are going to throw the question to the masses. My current plan is when the first user (probably me) enters the site it starts a background thread that waits until the alloted time (hourly on the hour) and then kicks off the event blocking the others (I am a Windows programmer by trade so I think in terms of events and WaitOnMultipleObjects) until it completes. How did Jeff do it in Asp.Net and is his method applicable to the Java web-app world?
I think developing a custom solution for running background tasks doesn't always worth, so I recommend to use the Quartz Scheduler in Java. In your situation (need to run background tasks in a web application) you could use the ServletContextListener included in the distribution to initialize the engine at the startup of your web container. After that you have a number of possibilities to start (trigger) your background tasks (jobs), e.g. you can use Calendars or cron-like expressions. In your situation most probably you should settle with SimpleTrigger that lets you run jobs in fixed, regular intervals. The jobs themselves can be described easily too in Quartz, however you haven't provided any details about what you need to run, so I can't provide a suggestion in that area.
Running a regular background event in Java web app In podcast #15, Jeff mentioned he twittered about how to run a regular event in the background as if it was a normal function - unfortunately I can't seem to find that through twitter. Now I need to do a similar thing and are going to throw the question to the masses. My current plan is when the first user (probably me) enters the site it starts a background thread that waits until the alloted time (hourly on the hour) and then kicks off the event blocking the others (I am a Windows programmer by trade so I think in terms of events and WaitOnMultipleObjects) until it completes. How did Jeff do it in Asp.Net and is his method applicable to the Java web-app world?
TITLE: Running a regular background event in Java web app QUESTION: In podcast #15, Jeff mentioned he twittered about how to run a regular event in the background as if it was a normal function - unfortunately I can't seem to find that through twitter. Now I need to do a similar thing and are going to throw the question to the masses. My current plan is when the first user (probably me) enters the site it starts a background thread that waits until the alloted time (hourly on the hour) and then kicks off the event blocking the others (I am a Windows programmer by trade so I think in terms of events and WaitOnMultipleObjects) until it completes. How did Jeff do it in Asp.Net and is his method applicable to the Java web-app world? ANSWER: I think developing a custom solution for running background tasks doesn't always worth, so I recommend to use the Quartz Scheduler in Java. In your situation (need to run background tasks in a web application) you could use the ServletContextListener included in the distribution to initialize the engine at the startup of your web container. After that you have a number of possibilities to start (trigger) your background tasks (jobs), e.g. you can use Calendars or cron-like expressions. In your situation most probably you should settle with SimpleTrigger that lets you run jobs in fixed, regular intervals. The jobs themselves can be described easily too in Quartz, however you haven't provided any details about what you need to run, so I can't provide a suggestion in that area.
[ "java", "events" ]
8
12
3,778
5
0
2008-09-07T10:25:25.960000
2008-09-07T11:25:27.407000
48,299
48,309
C++ UI resources
Now that I know C++ I want to get into desktop application that have a UI instead of Command Prompt stuff, where should I start?, and what are some good online resources?
wxWidgets is a cross platform GUI library for C++ (and other languages). The main site should have enough pointers to resources to get going. You might also want to check out this question/answer here on stack overflow if you are specifically thinking of Windows
C++ UI resources Now that I know C++ I want to get into desktop application that have a UI instead of Command Prompt stuff, where should I start?, and what are some good online resources?
TITLE: C++ UI resources QUESTION: Now that I know C++ I want to get into desktop application that have a UI instead of Command Prompt stuff, where should I start?, and what are some good online resources? ANSWER: wxWidgets is a cross platform GUI library for C++ (and other languages). The main site should have enough pointers to resources to get going. You might also want to check out this question/answer here on stack overflow if you are specifically thinking of Windows
[ "c++", "user-interface", "resources" ]
7
8
3,903
10
0
2008-09-07T10:36:30.800000
2008-09-07T10:55:28.210000
48,320
161,963
Best Ruby on Rails social networking framework
I'm planning on creating a social networking + MP3 lecture downloading / browsing / commenting / discovery website using Ruby on Rails. Partially for fun and also as a means to learn some Ruby on Rails. I'm looking for a social networking framework that I can use as a basis for my site. I don't want to re-invent the wheel. Searching the web I found three such frameworks. Which of these three would you recommend using and why? http://portal.insoshi.com/ http://www.communityengine.org/ http://lovdbyless.com/
It depends what your priorities are. If you really want to learn RoR, do it all from scratch. Seriously. Roll your own. It's the best way to learn, far better than hacking through someone else's code. If you do that, sometimes you'll be learning Rails, but sometimes you'll just be learning that specific social network framework. And you won't know which is which... The type of site you're suggesting sounds perfect for a Rails project. If you get stuck, then go browse the repositories of these frameworks. Who cares if you're reinventing the wheel? It's your site, your vision, your rules. If you just want a site up and running, then I would pick Insoshi or LovdbyLess simply because they're out of the box apps so you'll have to do less to do get running. I suggest trying to install them both, and introducing yourself in the Google Groups. That'll give you a good indication of wether you're going to get along.
Best Ruby on Rails social networking framework I'm planning on creating a social networking + MP3 lecture downloading / browsing / commenting / discovery website using Ruby on Rails. Partially for fun and also as a means to learn some Ruby on Rails. I'm looking for a social networking framework that I can use as a basis for my site. I don't want to re-invent the wheel. Searching the web I found three such frameworks. Which of these three would you recommend using and why? http://portal.insoshi.com/ http://www.communityengine.org/ http://lovdbyless.com/
TITLE: Best Ruby on Rails social networking framework QUESTION: I'm planning on creating a social networking + MP3 lecture downloading / browsing / commenting / discovery website using Ruby on Rails. Partially for fun and also as a means to learn some Ruby on Rails. I'm looking for a social networking framework that I can use as a basis for my site. I don't want to re-invent the wheel. Searching the web I found three such frameworks. Which of these three would you recommend using and why? http://portal.insoshi.com/ http://www.communityengine.org/ http://lovdbyless.com/ ANSWER: It depends what your priorities are. If you really want to learn RoR, do it all from scratch. Seriously. Roll your own. It's the best way to learn, far better than hacking through someone else's code. If you do that, sometimes you'll be learning Rails, but sometimes you'll just be learning that specific social network framework. And you won't know which is which... The type of site you're suggesting sounds perfect for a Rails project. If you get stuck, then go browse the repositories of these frameworks. Who cares if you're reinventing the wheel? It's your site, your vision, your rules. If you just want a site up and running, then I would pick Insoshi or LovdbyLess simply because they're out of the box apps so you'll have to do less to do get running. I suggest trying to install them both, and introducing yourself in the Google Groups. That'll give you a good indication of wether you're going to get along.
[ "ruby-on-rails", "ruby", "social-media" ]
27
34
38,522
9
0
2008-09-07T11:06:48.497000
2008-10-02T12:14:17.200000
48,322
48,922
Best practices for integrating third-party modules into your app
We have a few projects that involve building an application that is composed of maybe 50% custom functionality, but then pulls in, say, a wiki, a forum, and other components that are "wheels" that have already been invented that we do not wish to re-write from scratch. These third-party applications usually have their own databases, themes, and authentication systems. Getting things to work like a single-sign-on, or a common theme, or tagging/searching across entities in multiple sub-apps are pretty challenging problems, in my experience. What are some of the best practices for this kind of integration project? Our approach, so far, has been to try and pick your components carefully, choosing ones that have a clearly defined API, preferably via HTTP (like REST or SOAP), though that isn't always possible (we haven't found a decent forum that works that way). Are there suggestions folks can give to anyone trying to do this, as I suspect many of us are more and more frequently these days?
Make sure that the interface between your application and the third-party application or library is such that you can replace it easily with something else just in case. In some cases the third-party software may just be an implementation of an standard API (Java does this a lot with JDBC, JMS, JNDI,...). In other cases this means wrapping the third-party library in some API that you come up with. Of course there are times to throw that idea out the window and have things tightly integrated with the third-party software. Just be sure that you REALLY want to bind your application to that third-party. Once you go down this road it's REALLY hard to go back and change your mind.
Best practices for integrating third-party modules into your app We have a few projects that involve building an application that is composed of maybe 50% custom functionality, but then pulls in, say, a wiki, a forum, and other components that are "wheels" that have already been invented that we do not wish to re-write from scratch. These third-party applications usually have their own databases, themes, and authentication systems. Getting things to work like a single-sign-on, or a common theme, or tagging/searching across entities in multiple sub-apps are pretty challenging problems, in my experience. What are some of the best practices for this kind of integration project? Our approach, so far, has been to try and pick your components carefully, choosing ones that have a clearly defined API, preferably via HTTP (like REST or SOAP), though that isn't always possible (we haven't found a decent forum that works that way). Are there suggestions folks can give to anyone trying to do this, as I suspect many of us are more and more frequently these days?
TITLE: Best practices for integrating third-party modules into your app QUESTION: We have a few projects that involve building an application that is composed of maybe 50% custom functionality, but then pulls in, say, a wiki, a forum, and other components that are "wheels" that have already been invented that we do not wish to re-write from scratch. These third-party applications usually have their own databases, themes, and authentication systems. Getting things to work like a single-sign-on, or a common theme, or tagging/searching across entities in multiple sub-apps are pretty challenging problems, in my experience. What are some of the best practices for this kind of integration project? Our approach, so far, has been to try and pick your components carefully, choosing ones that have a clearly defined API, preferably via HTTP (like REST or SOAP), though that isn't always possible (we haven't found a decent forum that works that way). Are there suggestions folks can give to anyone trying to do this, as I suspect many of us are more and more frequently these days? ANSWER: Make sure that the interface between your application and the third-party application or library is such that you can replace it easily with something else just in case. In some cases the third-party software may just be an implementation of an standard API (Java does this a lot with JDBC, JMS, JNDI,...). In other cases this means wrapping the third-party library in some API that you come up with. Of course there are times to throw that idea out the window and have things tightly integrated with the third-party software. Just be sure that you REALLY want to bind your application to that third-party. Once you go down this road it's REALLY hard to go back and change your mind.
[ "architecture", "system-integration" ]
6
1
3,667
4
0
2008-09-07T11:07:44.390000
2008-09-08T00:17:22.713000
48,338
48,343
Am I allowed to run a javascript runtime (like v8) on the iPhone?
According to this discussion, the iphone agreement says that it doesn't allow "loading of plugins or running interpreted code that has been downloaded". Technically, I would like to download scripts from our server (embedded in a proprietary protocol). Does this mean I wouldn't be allowed to run a runtime like v8 in an iphone app? This is probably more of a legal question.
I think your interpretation is correct - You would not be allowed to download and execute JavaScript code in v8. If there were some way to run the code in an interpreter already on the iPhone (i.e. the javascript engine in MobileSafari) then that would be permitted I think.
Am I allowed to run a javascript runtime (like v8) on the iPhone? According to this discussion, the iphone agreement says that it doesn't allow "loading of plugins or running interpreted code that has been downloaded". Technically, I would like to download scripts from our server (embedded in a proprietary protocol). Does this mean I wouldn't be allowed to run a runtime like v8 in an iphone app? This is probably more of a legal question.
TITLE: Am I allowed to run a javascript runtime (like v8) on the iPhone? QUESTION: According to this discussion, the iphone agreement says that it doesn't allow "loading of plugins or running interpreted code that has been downloaded". Technically, I would like to download scripts from our server (embedded in a proprietary protocol). Does this mean I wouldn't be allowed to run a runtime like v8 in an iphone app? This is probably more of a legal question. ANSWER: I think your interpretation is correct - You would not be allowed to download and execute JavaScript code in v8. If there were some way to run the code in an interpreter already on the iPhone (i.e. the javascript engine in MobileSafari) then that would be permitted I think.
[ "javascript", "iphone", "c++" ]
7
4
1,850
4
0
2008-09-07T11:39:54.797000
2008-09-07T11:43:08.613000
48,356
48,383
Can't Re-bind a socket to an existing IP/Port Combination
Greetings, I'm trying to find a way to 'unbind' a socket from a particular IP/Port combination. My pseudocode looks like this: ClassA a = new ClassA(); //(class A instantiates socket and binds it to 127.0.0.1:4567) //do something //...much later, a has been garbage-collected away. ClassA aa = new ClassA(); //crash here. At this point,.Net informs me that I've already got a socket bound to 127.0.0.1:4567, which is technically true. But no matter what code I put in ClassA's destructor, or no matter what functions I call on the socket (I've tried.Close() and.Disconnect(true)), the socket remains proudly bound to 127.0.0.1:4567. What do I do to be able to 'un-bind' the socket? EDIT: I'm not relying solely on garbage collection (though I tried that approach as well). I tried calling a.Close() or a.Disconnect() and only then instantiating aa; this doesn't solve the problem. EDIT: I've also tried implementing IDisposable, but the code never got there without my calling the method (which was the equivalent of earlier attempts, as the method would simply try.Close and.Disconnect). Let me try calling.Dispose directly and get back to you. EDIT (lots of edits, apologies): Implementing IDisposable and calling a.Dispose() from where 'a' loses scope doesn't work - my Dispose implementation still has to call either.Close or.Disconnect(true) (or.Shutdown(Both)) but none of those unbind the socket. Any help would be appreciated!
(this is what finally got everything to work for me) Make sure EVERY socket that the socket in A connects to has socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress, true); set upon being initiated.
Can't Re-bind a socket to an existing IP/Port Combination Greetings, I'm trying to find a way to 'unbind' a socket from a particular IP/Port combination. My pseudocode looks like this: ClassA a = new ClassA(); //(class A instantiates socket and binds it to 127.0.0.1:4567) //do something //...much later, a has been garbage-collected away. ClassA aa = new ClassA(); //crash here. At this point,.Net informs me that I've already got a socket bound to 127.0.0.1:4567, which is technically true. But no matter what code I put in ClassA's destructor, or no matter what functions I call on the socket (I've tried.Close() and.Disconnect(true)), the socket remains proudly bound to 127.0.0.1:4567. What do I do to be able to 'un-bind' the socket? EDIT: I'm not relying solely on garbage collection (though I tried that approach as well). I tried calling a.Close() or a.Disconnect() and only then instantiating aa; this doesn't solve the problem. EDIT: I've also tried implementing IDisposable, but the code never got there without my calling the method (which was the equivalent of earlier attempts, as the method would simply try.Close and.Disconnect). Let me try calling.Dispose directly and get back to you. EDIT (lots of edits, apologies): Implementing IDisposable and calling a.Dispose() from where 'a' loses scope doesn't work - my Dispose implementation still has to call either.Close or.Disconnect(true) (or.Shutdown(Both)) but none of those unbind the socket. Any help would be appreciated!
TITLE: Can't Re-bind a socket to an existing IP/Port Combination QUESTION: Greetings, I'm trying to find a way to 'unbind' a socket from a particular IP/Port combination. My pseudocode looks like this: ClassA a = new ClassA(); //(class A instantiates socket and binds it to 127.0.0.1:4567) //do something //...much later, a has been garbage-collected away. ClassA aa = new ClassA(); //crash here. At this point,.Net informs me that I've already got a socket bound to 127.0.0.1:4567, which is technically true. But no matter what code I put in ClassA's destructor, or no matter what functions I call on the socket (I've tried.Close() and.Disconnect(true)), the socket remains proudly bound to 127.0.0.1:4567. What do I do to be able to 'un-bind' the socket? EDIT: I'm not relying solely on garbage collection (though I tried that approach as well). I tried calling a.Close() or a.Disconnect() and only then instantiating aa; this doesn't solve the problem. EDIT: I've also tried implementing IDisposable, but the code never got there without my calling the method (which was the equivalent of earlier attempts, as the method would simply try.Close and.Disconnect). Let me try calling.Dispose directly and get back to you. EDIT (lots of edits, apologies): Implementing IDisposable and calling a.Dispose() from where 'a' loses scope doesn't work - my Dispose implementation still has to call either.Close or.Disconnect(true) (or.Shutdown(Both)) but none of those unbind the socket. Any help would be appreciated! ANSWER: (this is what finally got everything to work for me) Make sure EVERY socket that the socket in A connects to has socket.SetSocketOption(SocketOptionLevel.Socket,SocketOptionName.ReuseAddress, true); set upon being initiated.
[ "c#", ".net", "networking", "sockets" ]
4
3
7,461
5
0
2008-09-07T11:56:49.657000
2008-09-07T12:34:48.550000
48,365
48,435
Is tagging organizationally superior to discrete subforums?
I am interested in choosing a good structure for an online message board-type application. I will use SO as an example, as I think it's an example that we are all familiar with, but my question is more general; it is about how to achieve the right balance between organization and flexibility in online message boards. The questions page is a load of random stuff. It moves quickly (some might say, too quickly) and contains a huge number of questions that I'm not interested in. The idea, I imagine, is that we can use tags to find questions that we're interested in. However, I'm not sure that this works: you can't use tags negatively. I'm not interested in PHP or perl or web development. I want to exclude such posts. But with the tags, I can't. Although discrete subforums are in a sense less flexible, as they generally force you to pick a category even if a question might fit into two (if SO had, say, areas for "Web Development", "Games development", "Computer Science", "Systems Programming", "Databases", etc. then sure, some people might want to post about developing of web-based games, for example) is it worth sacrificing some of that flexibility in order to make it easier to find the content that you are interested in, and hide the content that you are not interested in? Is there any way with a pure tagging system to achieve the greater ease of use that subforums provide?
The real problem with subforums comes when you guess wrong about which topics have enough interest to get their own subforums. While some topics end up with their own vibrant subcommunities others end up as empty ghettos, with little activity or feeling of community. Topics that might flourish as occasional subjects in a larger forum end up fragmented among many subforums, none of which has the critical mass of people necessary to have an active, vibrant community.
Is tagging organizationally superior to discrete subforums? I am interested in choosing a good structure for an online message board-type application. I will use SO as an example, as I think it's an example that we are all familiar with, but my question is more general; it is about how to achieve the right balance between organization and flexibility in online message boards. The questions page is a load of random stuff. It moves quickly (some might say, too quickly) and contains a huge number of questions that I'm not interested in. The idea, I imagine, is that we can use tags to find questions that we're interested in. However, I'm not sure that this works: you can't use tags negatively. I'm not interested in PHP or perl or web development. I want to exclude such posts. But with the tags, I can't. Although discrete subforums are in a sense less flexible, as they generally force you to pick a category even if a question might fit into two (if SO had, say, areas for "Web Development", "Games development", "Computer Science", "Systems Programming", "Databases", etc. then sure, some people might want to post about developing of web-based games, for example) is it worth sacrificing some of that flexibility in order to make it easier to find the content that you are interested in, and hide the content that you are not interested in? Is there any way with a pure tagging system to achieve the greater ease of use that subforums provide?
TITLE: Is tagging organizationally superior to discrete subforums? QUESTION: I am interested in choosing a good structure for an online message board-type application. I will use SO as an example, as I think it's an example that we are all familiar with, but my question is more general; it is about how to achieve the right balance between organization and flexibility in online message boards. The questions page is a load of random stuff. It moves quickly (some might say, too quickly) and contains a huge number of questions that I'm not interested in. The idea, I imagine, is that we can use tags to find questions that we're interested in. However, I'm not sure that this works: you can't use tags negatively. I'm not interested in PHP or perl or web development. I want to exclude such posts. But with the tags, I can't. Although discrete subforums are in a sense less flexible, as they generally force you to pick a category even if a question might fit into two (if SO had, say, areas for "Web Development", "Games development", "Computer Science", "Systems Programming", "Databases", etc. then sure, some people might want to post about developing of web-based games, for example) is it worth sacrificing some of that flexibility in order to make it easier to find the content that you are interested in, and hide the content that you are not interested in? Is there any way with a pure tagging system to achieve the greater ease of use that subforums provide? ANSWER: The real problem with subforums comes when you guess wrong about which topics have enough interest to get their own subforums. While some topics end up with their own vibrant subcommunities others end up as empty ghettos, with little activity or feeling of community. Topics that might flourish as occasional subjects in a larger forum end up fragmented among many subforums, none of which has the critical mass of people necessary to have an active, vibrant community.
[ "tags" ]
4
2
302
4
0
2008-09-07T12:04:24.350000
2008-09-07T13:36:44.813000
48,390
48,587
Eclipse spelling engine does not exist
I'm using Eclipse 3.4 (Ganymede) with CDT 5 on Windows. When the integrated spell checker doesn't know some word, it proposes (among others) the option to add the word to a user dictionary. If the user dictionary doesn't exist yet, the spell checker offers then to help configuring it and shows the "General/Editors/Text Editors/Spelling" preference pane. This preference pane however states that "The selected spelling engine does not exist", but has no control to add or install an engine. How can I put a spelling engine in existence? Update: What solved my problem was to install also the JDT. This solution was brought up on 2008-09-07 and was accepted, but is now missing.
Are you using the C/C++ Development Tools exclusively? The Spellcheck functionality is dependent upon the Java Development Tools being installed also. The spelling engine is scheduled to be pushed down from JDT to the Platform, so you can get rid of the Java related bloat soon enough.:)
Eclipse spelling engine does not exist I'm using Eclipse 3.4 (Ganymede) with CDT 5 on Windows. When the integrated spell checker doesn't know some word, it proposes (among others) the option to add the word to a user dictionary. If the user dictionary doesn't exist yet, the spell checker offers then to help configuring it and shows the "General/Editors/Text Editors/Spelling" preference pane. This preference pane however states that "The selected spelling engine does not exist", but has no control to add or install an engine. How can I put a spelling engine in existence? Update: What solved my problem was to install also the JDT. This solution was brought up on 2008-09-07 and was accepted, but is now missing.
TITLE: Eclipse spelling engine does not exist QUESTION: I'm using Eclipse 3.4 (Ganymede) with CDT 5 on Windows. When the integrated spell checker doesn't know some word, it proposes (among others) the option to add the word to a user dictionary. If the user dictionary doesn't exist yet, the spell checker offers then to help configuring it and shows the "General/Editors/Text Editors/Spelling" preference pane. This preference pane however states that "The selected spelling engine does not exist", but has no control to add or install an engine. How can I put a spelling engine in existence? Update: What solved my problem was to install also the JDT. This solution was brought up on 2008-09-07 and was accepted, but is now missing. ANSWER: Are you using the C/C++ Development Tools exclusively? The Spellcheck functionality is dependent upon the Java Development Tools being installed also. The spelling engine is scheduled to be pushed down from JDT to the Platform, so you can get rid of the Java related bloat soon enough.:)
[ "c++", "eclipse", "spell-checking", "eclipse-3.4", "eclipse-cdt" ]
4
1
5,283
3
0
2008-09-07T12:40:23.437000
2008-09-07T17:09:54.053000
48,397
48,400
.Net 3.5 silent installer?
Is there a redistributable.Net 3.5 installation package that is a silent installer? Or alternatively, is there a switch that can be passed to the main redistributable.Net 3.5 installer to make it silent?
dotnetfx35setup.exe /q /norestart see the.net deployment guide at: http://msdn.microsoft.com/en-us/library/cc160716.aspx
.Net 3.5 silent installer? Is there a redistributable.Net 3.5 installation package that is a silent installer? Or alternatively, is there a switch that can be passed to the main redistributable.Net 3.5 installer to make it silent?
TITLE: .Net 3.5 silent installer? QUESTION: Is there a redistributable.Net 3.5 installation package that is a silent installer? Or alternatively, is there a switch that can be passed to the main redistributable.Net 3.5 installer to make it silent? ANSWER: dotnetfx35setup.exe /q /norestart see the.net deployment guide at: http://msdn.microsoft.com/en-us/library/cc160716.aspx
[ ".net", ".net-3.5", "installation", "redistributable" ]
9
14
25,665
2
0
2008-09-07T12:52:12.610000
2008-09-07T12:55:46.830000
48,426
112,078
How could I graphically display the memory layout from a .map file?
My gcc build toolchain produces a.map file. How do I display the memory sections using memory map graphically?
Here's the beginnings of a script in Python. It loads the map file into a list of Sections and Symbols (first half). It then renders the map using HTML (or do whatever you want with the sections and symbols lists). You can control the script by modifying these lines: with open('t.map') as f: colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E'] total_height = 32.0 map2html.py from __future__ import with_statement import re class Section: def __init__(self, address, size, segment, section): self.address = address self.size = size self.segment = segment self.section = section def __str__(self): return self.section+"" class Symbol: def __init__(self, address, size, file, name): self.address = address self.size = size self.file = file self.name = name def __str__(self): return self.name #=============================== # Load the Sections and Symbols # sections = [] symbols = [] with open('t.map') as f: in_sections = True for line in f: m = re.search('^([0-9A-Fx]+)\s+([0-9A-Fx]+)\s+((\[[ 0-9]+\])|\w+)\s+(.*?)\s*$', line) if m: if in_sections: sections.append(Section(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5))) else: symbols.append(Symbol(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5))) else: if len(sections) > 0: in_sections = False #=============================== # Gererate the HTML File # colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E'] total_height = 32.0 segments = set() for s in sections: segments.add(s.segment) segment_colors = dict() i = 0 for s in segments: segment_colors[s] = colors[i % len(colors)] i += 1 total_size = 0 for s in symbols: total_size += s.size sections.sort(lambda a,b: a.address - b.address) symbols.sort(lambda a,b: a.address - b.address) def section_from_address(addr): for s in sections: if addr >= s.address and addr < (s.address + s.size): return s return None print " " print " " print " " print " " for sym in symbols: section = section_from_address(sym.address) height = (total_height/total_size) * sym.size font_size = 1.0 if height > 1.0 else height print " " % \ (segment_colors[section.segment], height, height, font_size) print " %s " % (sym.name, sym.name) print " " print " " print " " And here's a bad rendering of the HTML it outputs:
How could I graphically display the memory layout from a .map file? My gcc build toolchain produces a.map file. How do I display the memory sections using memory map graphically?
TITLE: How could I graphically display the memory layout from a .map file? QUESTION: My gcc build toolchain produces a.map file. How do I display the memory sections using memory map graphically? ANSWER: Here's the beginnings of a script in Python. It loads the map file into a list of Sections and Symbols (first half). It then renders the map using HTML (or do whatever you want with the sections and symbols lists). You can control the script by modifying these lines: with open('t.map') as f: colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E'] total_height = 32.0 map2html.py from __future__ import with_statement import re class Section: def __init__(self, address, size, segment, section): self.address = address self.size = size self.segment = segment self.section = section def __str__(self): return self.section+"" class Symbol: def __init__(self, address, size, file, name): self.address = address self.size = size self.file = file self.name = name def __str__(self): return self.name #=============================== # Load the Sections and Symbols # sections = [] symbols = [] with open('t.map') as f: in_sections = True for line in f: m = re.search('^([0-9A-Fx]+)\s+([0-9A-Fx]+)\s+((\[[ 0-9]+\])|\w+)\s+(.*?)\s*$', line) if m: if in_sections: sections.append(Section(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5))) else: symbols.append(Symbol(eval(m.group(1)), eval(m.group(2)), m.group(3), m.group(5))) else: if len(sections) > 0: in_sections = False #=============================== # Gererate the HTML File # colors = ['9C9F84', 'A97D5D', 'F7DCB4', '5C755E'] total_height = 32.0 segments = set() for s in sections: segments.add(s.segment) segment_colors = dict() i = 0 for s in segments: segment_colors[s] = colors[i % len(colors)] i += 1 total_size = 0 for s in symbols: total_size += s.size sections.sort(lambda a,b: a.address - b.address) symbols.sort(lambda a,b: a.address - b.address) def section_from_address(addr): for s in sections: if addr >= s.address and addr < (s.address + s.size): return s return None print " " print " " print " " print " " for sym in symbols: section = section_from_address(sym.address) height = (total_height/total_size) * sym.size font_size = 1.0 if height > 1.0 else height print " " % \ (segment_colors[section.segment], height, height, font_size) print " %s " % (sym.name, sym.name) print " " print " " print " " And here's a bad rendering of the HTML it outputs:
[ "c++", "c", "linker" ]
65
29
27,179
2
0
2008-09-07T13:26:57.503000
2008-09-21T20:45:17.683000
48,432
48,545
Pros & cons between LINQ and traditional collection based approaches
Being relatively new to the.net game, I was wondering, has anyone had any experience of the pros / cons between the use of LINQ and what could be considered more traditional methods working with lists / collections? For a specific example of a project I'm working on: a list of unique id / name pairs are being retrieved from a remote web-service. this list will change infrequently (once per day), will be read-only from the point of view of the application where it is being used will be stored at the application level for all requests to access Given those points, I plan to store the returned values at the application level in a singleton class. My initial approach was to iterate through the list returned from the remote service and store it in a NameValueCollection in a singleton class, with methods to retrieve from the collection based on an id: sugarsoap soapService = new sugarsoap(); branch_summary[] branchList = soapService.getBranches(); foreach (branch_summary aBranch in branchList) { branchNameList.Add(aBranch.id, aBranch.name); } The alternative using LINQ is to simply add a method that works on the list directly once it has been retrieved: public string branchName (string branchId) { //branchList populated in the constructor branch_summary bs = from b in branchList where b.id == branchId select b; return branch_summary.name; } Is either better than the other - is there a third way? I'm open to all answers, for both approaches and both in terms of solutions that offer elegance, and those which benefit performance.
i dont think the linq you wrote would compile, it'd have to be public string branchName (string branchId) { //branchList populated in the constructor branch_summary bs = (from b in branchList where b.id == branchId select b).FirstOrDefault(); return branch_summary == null? null: branch_summary.name; } note the.FirstsOrDefault() I'd rather use LINQ for the reason that it can be used in other places, for writing more complex filters on your data. I also think it's easier to read than NameValueCollection alternative. that's my $0.02
Pros & cons between LINQ and traditional collection based approaches Being relatively new to the.net game, I was wondering, has anyone had any experience of the pros / cons between the use of LINQ and what could be considered more traditional methods working with lists / collections? For a specific example of a project I'm working on: a list of unique id / name pairs are being retrieved from a remote web-service. this list will change infrequently (once per day), will be read-only from the point of view of the application where it is being used will be stored at the application level for all requests to access Given those points, I plan to store the returned values at the application level in a singleton class. My initial approach was to iterate through the list returned from the remote service and store it in a NameValueCollection in a singleton class, with methods to retrieve from the collection based on an id: sugarsoap soapService = new sugarsoap(); branch_summary[] branchList = soapService.getBranches(); foreach (branch_summary aBranch in branchList) { branchNameList.Add(aBranch.id, aBranch.name); } The alternative using LINQ is to simply add a method that works on the list directly once it has been retrieved: public string branchName (string branchId) { //branchList populated in the constructor branch_summary bs = from b in branchList where b.id == branchId select b; return branch_summary.name; } Is either better than the other - is there a third way? I'm open to all answers, for both approaches and both in terms of solutions that offer elegance, and those which benefit performance.
TITLE: Pros & cons between LINQ and traditional collection based approaches QUESTION: Being relatively new to the.net game, I was wondering, has anyone had any experience of the pros / cons between the use of LINQ and what could be considered more traditional methods working with lists / collections? For a specific example of a project I'm working on: a list of unique id / name pairs are being retrieved from a remote web-service. this list will change infrequently (once per day), will be read-only from the point of view of the application where it is being used will be stored at the application level for all requests to access Given those points, I plan to store the returned values at the application level in a singleton class. My initial approach was to iterate through the list returned from the remote service and store it in a NameValueCollection in a singleton class, with methods to retrieve from the collection based on an id: sugarsoap soapService = new sugarsoap(); branch_summary[] branchList = soapService.getBranches(); foreach (branch_summary aBranch in branchList) { branchNameList.Add(aBranch.id, aBranch.name); } The alternative using LINQ is to simply add a method that works on the list directly once it has been retrieved: public string branchName (string branchId) { //branchList populated in the constructor branch_summary bs = from b in branchList where b.id == branchId select b; return branch_summary.name; } Is either better than the other - is there a third way? I'm open to all answers, for both approaches and both in terms of solutions that offer elegance, and those which benefit performance. ANSWER: i dont think the linq you wrote would compile, it'd have to be public string branchName (string branchId) { //branchList populated in the constructor branch_summary bs = (from b in branchList where b.id == branchId select b).FirstOrDefault(); return branch_summary == null? null: branch_summary.name; } note the.FirstsOrDefault() I'd rather use LINQ for the reason that it can be used in other places, for writing more complex filters on your data. I also think it's easier to read than NameValueCollection alternative. that's my $0.02
[ "c#", ".net", "asp.net", "linq" ]
4
3
1,754
4
0
2008-09-07T13:33:25.227000
2008-09-07T16:07:10.333000
48,439
48,456
How Much Time Should be Allotted for Testing & Bug Fixing
Every time I have to estimate time for a project (or review someone else's estimate), time is allotted for testing/bug fixing that will be done between the alpha and production releases. I know very well that estimating so far into the future regarding a problem-set of unknown size is not a good recipe for a successful estimate. However for a variety of reasons, a defined number of hours invariably gets assigned at the outset to this segment of work. And the farther off this initial estimate is from the real, final value, the more grief those involved with the debugging will have to take later on when they go "over" the estimate. So my question is: what is the best strategy you have seen with regards to making estimates like this? A flat percentage of the overall dev estimate? Set number of hours (with the expectation that it will go up)? Something else? Something else to consider: how would you answer this differently if the client is responsible for testing (as opposed to internal QA) and you have to assign an amount of time for responding to the bugs that they may or may not find (so you need to figure out time estimates for bug fixing but not for testing)
It really depends on a lot of factors. To mention but a few: the development methodology you are using, the amount of testing resource you have, the number of developers available at this stage in the project (many project managers will move people onto something new at the end). As Rob Rolnick says 1:1 is a good rule of thumb- however in cases where a specification is bad the client may push for "bugs" which are actually badly specified features. I was recently involved in a project which used many releases but more time was spent on bug fixing than actual development due to the terrible specification. Ensure a good specification/design and your testing/bug fixing time will be reduced because it will be easier for testers to see what and how to test and any clients will have less lee-way to push for extra features.
How Much Time Should be Allotted for Testing & Bug Fixing Every time I have to estimate time for a project (or review someone else's estimate), time is allotted for testing/bug fixing that will be done between the alpha and production releases. I know very well that estimating so far into the future regarding a problem-set of unknown size is not a good recipe for a successful estimate. However for a variety of reasons, a defined number of hours invariably gets assigned at the outset to this segment of work. And the farther off this initial estimate is from the real, final value, the more grief those involved with the debugging will have to take later on when they go "over" the estimate. So my question is: what is the best strategy you have seen with regards to making estimates like this? A flat percentage of the overall dev estimate? Set number of hours (with the expectation that it will go up)? Something else? Something else to consider: how would you answer this differently if the client is responsible for testing (as opposed to internal QA) and you have to assign an amount of time for responding to the bugs that they may or may not find (so you need to figure out time estimates for bug fixing but not for testing)
TITLE: How Much Time Should be Allotted for Testing & Bug Fixing QUESTION: Every time I have to estimate time for a project (or review someone else's estimate), time is allotted for testing/bug fixing that will be done between the alpha and production releases. I know very well that estimating so far into the future regarding a problem-set of unknown size is not a good recipe for a successful estimate. However for a variety of reasons, a defined number of hours invariably gets assigned at the outset to this segment of work. And the farther off this initial estimate is from the real, final value, the more grief those involved with the debugging will have to take later on when they go "over" the estimate. So my question is: what is the best strategy you have seen with regards to making estimates like this? A flat percentage of the overall dev estimate? Set number of hours (with the expectation that it will go up)? Something else? Something else to consider: how would you answer this differently if the client is responsible for testing (as opposed to internal QA) and you have to assign an amount of time for responding to the bugs that they may or may not find (so you need to figure out time estimates for bug fixing but not for testing) ANSWER: It really depends on a lot of factors. To mention but a few: the development methodology you are using, the amount of testing resource you have, the number of developers available at this stage in the project (many project managers will move people onto something new at the end). As Rob Rolnick says 1:1 is a good rule of thumb- however in cases where a specification is bad the client may push for "bugs" which are actually badly specified features. I was recently involved in a project which used many releases but more time was spent on bug fixing than actual development due to the terrible specification. Ensure a good specification/design and your testing/bug fixing time will be reduced because it will be easier for testers to see what and how to test and any clients will have less lee-way to push for extra features.
[ "project-management", "estimation" ]
8
9
13,799
5
0
2008-09-07T13:42:08.670000
2008-09-07T14:05:45.757000
48,442
48,452
Rule of thumb for choosing an implementation of a Java Collection?
Anyone have a good rule of thumb for choosing between different implementations of Java Collection interfaces like List, Map, or Set? For example, generally why or in what cases would I prefer to use a Vector or an ArrayList, a Hashtable or a HashMap?
I've always made those decisions on a case by case basis, depending on the use case, such as: Do I need the ordering to remain? Will I have null key/values? Dups? Will it be accessed by multiple threads Do I need a key/value pair Will I need random access? And then I break out my handy 5th edition Java in a Nutshell and compare the ~20 or so options. It has nice little tables in Chapter five to help one figure out what is appropriate. Ok, maybe if I know off the cuff that a simple ArrayList or HashSet will do the trick I won't look it all up.;) but if there is anything remotely complex about my indended use, you bet I'm in the book. BTW, I though Vector is supposed to be 'old hat'--I've not used on in years.
Rule of thumb for choosing an implementation of a Java Collection? Anyone have a good rule of thumb for choosing between different implementations of Java Collection interfaces like List, Map, or Set? For example, generally why or in what cases would I prefer to use a Vector or an ArrayList, a Hashtable or a HashMap?
TITLE: Rule of thumb for choosing an implementation of a Java Collection? QUESTION: Anyone have a good rule of thumb for choosing between different implementations of Java Collection interfaces like List, Map, or Set? For example, generally why or in what cases would I prefer to use a Vector or an ArrayList, a Hashtable or a HashMap? ANSWER: I've always made those decisions on a case by case basis, depending on the use case, such as: Do I need the ordering to remain? Will I have null key/values? Dups? Will it be accessed by multiple threads Do I need a key/value pair Will I need random access? And then I break out my handy 5th edition Java in a Nutshell and compare the ~20 or so options. It has nice little tables in Chapter five to help one figure out what is appropriate. Ok, maybe if I know off the cuff that a simple ArrayList or HashSet will do the trick I won't look it all up.;) but if there is anything remotely complex about my indended use, you bet I'm in the book. BTW, I though Vector is supposed to be 'old hat'--I've not used on in years.
[ "java", "collections", "heuristics" ]
66
16
27,097
11
0
2008-09-07T13:46:15.413000
2008-09-07T14:03:48.913000
48,446
48,466
Scheduling Windows Mobile apps to run
How do you schedule a Windows Mobile application to periodically start up to perform some background processing. For example, assume I'm writing an email client and want to check for email every hour, regardless of whether my app is running at the time. The app is a native C/C++ app on Windows Mobile 5.0 or later.
the function you need is: CeRunAppAtTime( appname, time ) that isn't the exact signature, there is also CeRunAppAtEvent, they should both be in the MSDN docs (but linking is useless the way MSDN urls always change) The normal way to use these (and RunAppAtTime in the managed world via OpenNETCF.Win32.Notify ) is that for periodic execution, every time your app runs, it will rescedule itself for its next run-time. If your app is running, the new instance should bring up the already running process. If it isn't running, then it is just like starting up normally - from mmory it passes some argument to the process so it can tell it is being scheduled and not started some other way.
Scheduling Windows Mobile apps to run How do you schedule a Windows Mobile application to periodically start up to perform some background processing. For example, assume I'm writing an email client and want to check for email every hour, regardless of whether my app is running at the time. The app is a native C/C++ app on Windows Mobile 5.0 or later.
TITLE: Scheduling Windows Mobile apps to run QUESTION: How do you schedule a Windows Mobile application to periodically start up to perform some background processing. For example, assume I'm writing an email client and want to check for email every hour, regardless of whether my app is running at the time. The app is a native C/C++ app on Windows Mobile 5.0 or later. ANSWER: the function you need is: CeRunAppAtTime( appname, time ) that isn't the exact signature, there is also CeRunAppAtEvent, they should both be in the MSDN docs (but linking is useless the way MSDN urls always change) The normal way to use these (and RunAppAtTime in the managed world via OpenNETCF.Win32.Notify ) is that for periodic execution, every time your app runs, it will rescedule itself for its next run-time. If your app is running, the new instance should bring up the already running process. If it isn't running, then it is just like starting up normally - from mmory it passes some argument to the process so it can tell it is being scheduled and not started some other way.
[ "windows-mobile", "scheduled-tasks" ]
6
4
3,086
2
0
2008-09-07T13:53:10.827000
2008-09-07T14:23:52.767000
48,458
70,271
Project structure for Google App Engine
I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is BowlSK. However, as it has grown, and features have been added, it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project, and I didn't know anything about it until I started working. What I have: Main Level contains: all.py files (didn't know how to make packages work) all.html templates for main level pages Subdirectories: separate folders for css, images, js, etc. folders that hold.html templates for subdirecty-type urls Example: http://www.bowlsk.com/ maps to HomePage (default package), template at "index.html" http://www.bowlsk.com/games/view-series.html?series=7130 maps to ViewSeriesPage (again, default package), template at "games/view-series.html" It's nasty. How do I restructure? I had 2 ideas: Main Folder containing: appdef, indexes, main.py? Subfolder for code. Does this have to be my first package? Subfolder for templates. Folder heirarchy would match package heirarchy Individual subfolders for css, images, js, etc. Main Folder containing appdef, indexes, main.py? Subfolder for code + templates. This way I have the handler class right next to the template, because in this stage, I'm adding lots of features, so modifications to one mean modifications to the other. Again, do I have to have this folder name be the first package name for my classes? I'd like the folder to be "src", but I don't want my classes to be "src.WhateverPage" Is there a best practice? With Django 1.0 on the horizon, is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things, and seeing which seems better, but pyDev's refactoring support doesn't seem to handle package moves very well, so it will likely be a non-trivial task to get all of this working again.
First, I would suggest you have a look at " Rapid Development with Python, Django, and Google App Engine " GvR describes a general/standard project layout on page 10 of his slide presentation. Here I'll post a slightly modified version of the layout/structure from that page. I pretty much follow this pattern myself. You also mentioned you had trouble with packages. Just make sure each of your sub folders has an __init__.py file. It's ok if its empty. Boilerplate files These hardly vary between projects app.yaml: direct all non-static requests to main.py main.py: initialize app and send it all requests Project lay-out static/*: static files; served directly by App Engine myapp/*.py: app-specific python code views.py, models.py, tests.py, __init__.py, and more templates/*.html: templates (or myapp/templates/*.html) Here are some code examples that may help as well: main.py import wsgiref.handlers from google.appengine.ext import webapp from myapp.views import * application = webapp.WSGIApplication([ ('/', IndexHandler), ('/foo', FooHandler) ], debug=True) def main(): wsgiref.handlers.CGIHandler().run(application) myapp/views.py import os import datetime import logging import time from google.appengine.api import urlfetch from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from models import * class IndexHandler(webapp.RequestHandler): def get(self): date = "foo" # Do some processing template_values = {'data': data } path = os.path.join(os.path.dirname(__file__) + '/../templates/', 'main.html') self.response.out.write(template.render(path, template_values)) class FooHandler(webapp.RequestHandler): def get(self): #logging.debug("start of handler") myapp/models.py from google.appengine.ext import db class SampleModel(db.Model): I think this layout works great for new and relatively small to medium projects. For larger projects I would suggest breaking up the views and models to have their own sub-folders with something like: Project lay-out static/: static files; served directly by App Engine js/*.js images/*.gif|png|jpg css/*.css myapp/: app structure models/*.py views/*.py tests/*.py templates/*.html: templates
Project structure for Google App Engine I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is BowlSK. However, as it has grown, and features have been added, it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project, and I didn't know anything about it until I started working. What I have: Main Level contains: all.py files (didn't know how to make packages work) all.html templates for main level pages Subdirectories: separate folders for css, images, js, etc. folders that hold.html templates for subdirecty-type urls Example: http://www.bowlsk.com/ maps to HomePage (default package), template at "index.html" http://www.bowlsk.com/games/view-series.html?series=7130 maps to ViewSeriesPage (again, default package), template at "games/view-series.html" It's nasty. How do I restructure? I had 2 ideas: Main Folder containing: appdef, indexes, main.py? Subfolder for code. Does this have to be my first package? Subfolder for templates. Folder heirarchy would match package heirarchy Individual subfolders for css, images, js, etc. Main Folder containing appdef, indexes, main.py? Subfolder for code + templates. This way I have the handler class right next to the template, because in this stage, I'm adding lots of features, so modifications to one mean modifications to the other. Again, do I have to have this folder name be the first package name for my classes? I'd like the folder to be "src", but I don't want my classes to be "src.WhateverPage" Is there a best practice? With Django 1.0 on the horizon, is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things, and seeing which seems better, but pyDev's refactoring support doesn't seem to handle package moves very well, so it will likely be a non-trivial task to get all of this working again.
TITLE: Project structure for Google App Engine QUESTION: I started an application in Google App Engine right when it came out, to play with the technology and work on a pet project that I had been thinking about for a long time but never gotten around to starting. The result is BowlSK. However, as it has grown, and features have been added, it has gotten really difficult to keep things organized - mainly due to the fact that this is my first python project, and I didn't know anything about it until I started working. What I have: Main Level contains: all.py files (didn't know how to make packages work) all.html templates for main level pages Subdirectories: separate folders for css, images, js, etc. folders that hold.html templates for subdirecty-type urls Example: http://www.bowlsk.com/ maps to HomePage (default package), template at "index.html" http://www.bowlsk.com/games/view-series.html?series=7130 maps to ViewSeriesPage (again, default package), template at "games/view-series.html" It's nasty. How do I restructure? I had 2 ideas: Main Folder containing: appdef, indexes, main.py? Subfolder for code. Does this have to be my first package? Subfolder for templates. Folder heirarchy would match package heirarchy Individual subfolders for css, images, js, etc. Main Folder containing appdef, indexes, main.py? Subfolder for code + templates. This way I have the handler class right next to the template, because in this stage, I'm adding lots of features, so modifications to one mean modifications to the other. Again, do I have to have this folder name be the first package name for my classes? I'd like the folder to be "src", but I don't want my classes to be "src.WhateverPage" Is there a best practice? With Django 1.0 on the horizon, is there something I can do now to improve my ability to integrate with it when it becomes the official GAE templating engine? I would simply start trying these things, and seeing which seems better, but pyDev's refactoring support doesn't seem to handle package moves very well, so it will likely be a non-trivial task to get all of this working again. ANSWER: First, I would suggest you have a look at " Rapid Development with Python, Django, and Google App Engine " GvR describes a general/standard project layout on page 10 of his slide presentation. Here I'll post a slightly modified version of the layout/structure from that page. I pretty much follow this pattern myself. You also mentioned you had trouble with packages. Just make sure each of your sub folders has an __init__.py file. It's ok if its empty. Boilerplate files These hardly vary between projects app.yaml: direct all non-static requests to main.py main.py: initialize app and send it all requests Project lay-out static/*: static files; served directly by App Engine myapp/*.py: app-specific python code views.py, models.py, tests.py, __init__.py, and more templates/*.html: templates (or myapp/templates/*.html) Here are some code examples that may help as well: main.py import wsgiref.handlers from google.appengine.ext import webapp from myapp.views import * application = webapp.WSGIApplication([ ('/', IndexHandler), ('/foo', FooHandler) ], debug=True) def main(): wsgiref.handlers.CGIHandler().run(application) myapp/views.py import os import datetime import logging import time from google.appengine.api import urlfetch from google.appengine.ext.webapp import template from google.appengine.api import users from google.appengine.ext import webapp from models import * class IndexHandler(webapp.RequestHandler): def get(self): date = "foo" # Do some processing template_values = {'data': data } path = os.path.join(os.path.dirname(__file__) + '/../templates/', 'main.html') self.response.out.write(template.render(path, template_values)) class FooHandler(webapp.RequestHandler): def get(self): #logging.debug("start of handler") myapp/models.py from google.appengine.ext import db class SampleModel(db.Model): I think this layout works great for new and relatively small to medium projects. For larger projects I would suggest breaking up the views and models to have their own sub-folders with something like: Project lay-out static/: static files; served directly by App Engine js/*.js images/*.gif|png|jpg css/*.css myapp/: app structure models/*.py views/*.py tests/*.py templates/*.html: templates
[ "python", "google-app-engine" ]
119
104
28,381
6
0
2008-09-07T14:08:47.233000
2008-09-16T08:10:50.747000
48,470
296,494
How to disable Visual Studio macro "tip" balloon?
Whenever I use a macro in Visual Studio I get an annoying tip balloon in the system tray and an accompanying "pop" sound. It says: Visual Studio.NET macros To stop the macro from running, double-click the spinning cassette. Click here to not show this balloon again. I have trouble clicking the balloon because my macro runs so quickly. Is this controllable by some dialog box option? (I found someone else asking this question on some other site but it's not answered there. I give credit here because I've copied and pasted some pieces from there.)
This will disable the pop up: For Visual Studio 2008: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0 DWORD DontShowMacrosBalloon=6 For Visual Studio 2010 (the DWORD won't be there by default, use New | DWORD value to create it): HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0 DWORD DontShowMacrosBalloon=6 Delete the same key to re-enable it.
How to disable Visual Studio macro "tip" balloon? Whenever I use a macro in Visual Studio I get an annoying tip balloon in the system tray and an accompanying "pop" sound. It says: Visual Studio.NET macros To stop the macro from running, double-click the spinning cassette. Click here to not show this balloon again. I have trouble clicking the balloon because my macro runs so quickly. Is this controllable by some dialog box option? (I found someone else asking this question on some other site but it's not answered there. I give credit here because I've copied and pasted some pieces from there.)
TITLE: How to disable Visual Studio macro "tip" balloon? QUESTION: Whenever I use a macro in Visual Studio I get an annoying tip balloon in the system tray and an accompanying "pop" sound. It says: Visual Studio.NET macros To stop the macro from running, double-click the spinning cassette. Click here to not show this balloon again. I have trouble clicking the balloon because my macro runs so quickly. Is this controllable by some dialog box option? (I found someone else asking this question on some other site but it's not answered there. I give credit here because I've copied and pasted some pieces from there.) ANSWER: This will disable the pop up: For Visual Studio 2008: HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0 DWORD DontShowMacrosBalloon=6 For Visual Studio 2010 (the DWORD won't be there by default, use New | DWORD value to create it): HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\10.0 DWORD DontShowMacrosBalloon=6 Delete the same key to re-enable it.
[ "visual-studio", "macros", "tweak" ]
7
13
3,112
2
0
2008-09-07T14:29:07.997000
2008-11-17T18:58:43.860000
48,474
1,997,397
How do I position one image on top of another in HTML?
I'm a beginner at rails programming, attempting to show many images on a page. Some images are to lay on top of others. To make it simple, say I want a blue square, with a red square in the upper right corner of the blue square (but not tight in the corner). I am trying to avoid compositing (with ImageMagick and similar) due to performance issues. I just want to position overlapping images relative to one another. As a more difficult example, imagine an odometer placed inside a larger image. For six digits, I would need to composite a million different images, or do it all on the fly, where all that is needed is to place the six images on top of the other one.
Ok, after some time, here's what I landed on:.parent { position: relative; top: 0; left: 0; }.image1 { position: relative; top: 0; left: 0; border: 1px red solid; }.image2 { position: absolute; top: 30px; left: 30px; border: 1px green solid; } As the simplest solution. That is: Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.
How do I position one image on top of another in HTML? I'm a beginner at rails programming, attempting to show many images on a page. Some images are to lay on top of others. To make it simple, say I want a blue square, with a red square in the upper right corner of the blue square (but not tight in the corner). I am trying to avoid compositing (with ImageMagick and similar) due to performance issues. I just want to position overlapping images relative to one another. As a more difficult example, imagine an odometer placed inside a larger image. For six digits, I would need to composite a million different images, or do it all on the fly, where all that is needed is to place the six images on top of the other one.
TITLE: How do I position one image on top of another in HTML? QUESTION: I'm a beginner at rails programming, attempting to show many images on a page. Some images are to lay on top of others. To make it simple, say I want a blue square, with a red square in the upper right corner of the blue square (but not tight in the corner). I am trying to avoid compositing (with ImageMagick and similar) due to performance issues. I just want to position overlapping images relative to one another. As a more difficult example, imagine an odometer placed inside a larger image. For six digits, I would need to composite a million different images, or do it all on the fly, where all that is needed is to place the six images on top of the other one. ANSWER: Ok, after some time, here's what I landed on:.parent { position: relative; top: 0; left: 0; }.image1 { position: relative; top: 0; left: 0; border: 1px red solid; }.image2 { position: absolute; top: 30px; left: 30px; border: 1px green solid; } As the simplest solution. That is: Create a relative div that is placed in the flow of the page; place the base image first as relative so that the div knows how big it should be; place the overlays as absolutes relative to the upper left of the first image. The trick is to get the relatives and absolutes correct.
[ "html", "css", "optimization", "graphics" ]
324
543
1,094,097
13
0
2008-09-07T14:31:25.447000
2010-01-04T03:40:16.717000
48,475
48,652
Database Design for Tagging
How would you design a database to support the following tagging features: items can have a large number of tags searches for all items that are tagged with a given set of tags must be quick (the items must have ALL tags, so it's an AND-search, not an OR-search) creating/writing items may be slower to enable quick lookup/reading Ideally, the lookup of all items that are tagged with (at least) a set of n given tags should be done using a single SQL statement. Since the number of tags to search for as well as the number of tags on any item are unknown and may be high, using JOINs is impractical. Any ideas? Thanks for all the answers so far. If I'm not mistaken, however, the given answers show how to do an OR-search on tags. (Select all items that have one or more of n tags). I am looking for an efficient AND-search. (Select all items that have ALL n tags - and possibly more.)
About ANDing: It sounds like you are looking for the "relational division" operation. This article covers relational division in concise and yet comprehendible way. About performance: A bitmap-based approach intuitively sounds like it will suit the situation well. However, I'm not convinced it's a good idea to implement bitmap indexing "manually", like digiguru suggests: It sounds like a complicated situation whenever new tags are added(?) But some DBMSes (including Oracle) offer bitmap indexes which may somehow be of use, because a built-in indexing system does away with the potential complexity of index maintenance; additionally, a DBMS offering bitmap indexes should be able to consider them in a proper when when performing the query plan.
Database Design for Tagging How would you design a database to support the following tagging features: items can have a large number of tags searches for all items that are tagged with a given set of tags must be quick (the items must have ALL tags, so it's an AND-search, not an OR-search) creating/writing items may be slower to enable quick lookup/reading Ideally, the lookup of all items that are tagged with (at least) a set of n given tags should be done using a single SQL statement. Since the number of tags to search for as well as the number of tags on any item are unknown and may be high, using JOINs is impractical. Any ideas? Thanks for all the answers so far. If I'm not mistaken, however, the given answers show how to do an OR-search on tags. (Select all items that have one or more of n tags). I am looking for an efficient AND-search. (Select all items that have ALL n tags - and possibly more.)
TITLE: Database Design for Tagging QUESTION: How would you design a database to support the following tagging features: items can have a large number of tags searches for all items that are tagged with a given set of tags must be quick (the items must have ALL tags, so it's an AND-search, not an OR-search) creating/writing items may be slower to enable quick lookup/reading Ideally, the lookup of all items that are tagged with (at least) a set of n given tags should be done using a single SQL statement. Since the number of tags to search for as well as the number of tags on any item are unknown and may be high, using JOINs is impractical. Any ideas? Thanks for all the answers so far. If I'm not mistaken, however, the given answers show how to do an OR-search on tags. (Select all items that have one or more of n tags). I am looking for an efficient AND-search. (Select all items that have ALL n tags - and possibly more.) ANSWER: About ANDing: It sounds like you are looking for the "relational division" operation. This article covers relational division in concise and yet comprehendible way. About performance: A bitmap-based approach intuitively sounds like it will suit the situation well. However, I'm not convinced it's a good idea to implement bitmap indexing "manually", like digiguru suggests: It sounds like a complicated situation whenever new tags are added(?) But some DBMSes (including Oracle) offer bitmap indexes which may somehow be of use, because a built-in indexing system does away with the potential complexity of index maintenance; additionally, a DBMS offering bitmap indexes should be able to consider them in a proper when when performing the query plan.
[ "sql", "database-design", "tags", "tagging" ]
181
24
94,182
11
0
2008-09-07T14:31:31.547000
2008-09-07T18:22:46.497000
48,486
48,488
Choosing a desktop database
I'm looking for a desktop/embedded database. The two candidates I'm looking at are Microsoft SQL Server CE and Oracle Lite. If anyone's used both of these products, it'd be great if you could compare them. I haven't been able to find any comparisons online. The backend DB is Oracle10g. Update: Clarification, the business need is a client-server app with offline functionality (hence the need for a local data store on the client)
If the backend database is Oracle 10g it will probably be easier for you to use Oracle Lite - that way you don't have to use two completely different SQL dialects in the same project. BTW, In my product I use SQLite as the desktop database
Choosing a desktop database I'm looking for a desktop/embedded database. The two candidates I'm looking at are Microsoft SQL Server CE and Oracle Lite. If anyone's used both of these products, it'd be great if you could compare them. I haven't been able to find any comparisons online. The backend DB is Oracle10g. Update: Clarification, the business need is a client-server app with offline functionality (hence the need for a local data store on the client)
TITLE: Choosing a desktop database QUESTION: I'm looking for a desktop/embedded database. The two candidates I'm looking at are Microsoft SQL Server CE and Oracle Lite. If anyone's used both of these products, it'd be great if you could compare them. I haven't been able to find any comparisons online. The backend DB is Oracle10g. Update: Clarification, the business need is a client-server app with offline functionality (hence the need for a local data store on the client) ANSWER: If the backend database is Oracle 10g it will probably be easier for you to use Oracle Lite - that way you don't have to use two completely different SQL dialects in the same project. BTW, In my product I use SQLite as the desktop database
[ "database", "oracle", "sql-server-ce" ]
3
9
1,134
7
0
2008-09-07T14:45:38.860000
2008-09-07T14:50:55.667000
48,494
48,515
Firewall - Build or Buy
I have a Linux web server farm with about 5 web servers, web traffic is about 20Mbps. We currently have a Barracuda 340 Load Balancer (keep away from this device - piece of crap!) that is acting as a firewall. I want to put in a dedicated firewall and I'd like to know what peoples opinions are on building versus buying a dedicated firewall. Main requirements: Dynamically block rouge traffic Dynamically rate limit traffic Block all ports except 80, 443 Limit port 22 to a set of IPs High availability setup Also if we go for the build route, how do we know what level traffic the system can handle.
As they say - "there are more than one way to skin a cat": Build it yourself, running something like Linux or *BSD. The benefit of this, is that it makes it easy to do the dynamic part of your question, it's just a matter of a few well-placed shell/python/perl/whatever scripts. The drawback is that your ceiling traffic rate might not be what it would be on a purpose-built firewall device, although you should still be able to achieve data rates in the 300Mbit/sec range. (You start hitting PCI bus limitations at this point) This may be high enough to where it won't be a problem for you. Buy a dedicated "firewall device" - Possible drawbacks of doing this, is that doing the "dynamic" part of what you're trying to accomplish is somewhat more difficult - depending on the device, this could be easy (Net::Telnet/Net::SSH come to mind), or not. If you are worried about peak traffic rates, you'll have to carefully check the manufacturer's specifications - several of these devices are prone to the same traffic limitations as "regular" PC's, in that they still run into the PCI bus bandwidth issue, etc. At that point, you might as well roll your own. I guess you could read this more as a "pro's and con's" of doing either, if you want. FWIW, we run dual FreeBSD firewalls at my place of employment, and regularly push 40+Mbit/sec with no noticeable load/issues.
Firewall - Build or Buy I have a Linux web server farm with about 5 web servers, web traffic is about 20Mbps. We currently have a Barracuda 340 Load Balancer (keep away from this device - piece of crap!) that is acting as a firewall. I want to put in a dedicated firewall and I'd like to know what peoples opinions are on building versus buying a dedicated firewall. Main requirements: Dynamically block rouge traffic Dynamically rate limit traffic Block all ports except 80, 443 Limit port 22 to a set of IPs High availability setup Also if we go for the build route, how do we know what level traffic the system can handle.
TITLE: Firewall - Build or Buy QUESTION: I have a Linux web server farm with about 5 web servers, web traffic is about 20Mbps. We currently have a Barracuda 340 Load Balancer (keep away from this device - piece of crap!) that is acting as a firewall. I want to put in a dedicated firewall and I'd like to know what peoples opinions are on building versus buying a dedicated firewall. Main requirements: Dynamically block rouge traffic Dynamically rate limit traffic Block all ports except 80, 443 Limit port 22 to a set of IPs High availability setup Also if we go for the build route, how do we know what level traffic the system can handle. ANSWER: As they say - "there are more than one way to skin a cat": Build it yourself, running something like Linux or *BSD. The benefit of this, is that it makes it easy to do the dynamic part of your question, it's just a matter of a few well-placed shell/python/perl/whatever scripts. The drawback is that your ceiling traffic rate might not be what it would be on a purpose-built firewall device, although you should still be able to achieve data rates in the 300Mbit/sec range. (You start hitting PCI bus limitations at this point) This may be high enough to where it won't be a problem for you. Buy a dedicated "firewall device" - Possible drawbacks of doing this, is that doing the "dynamic" part of what you're trying to accomplish is somewhat more difficult - depending on the device, this could be easy (Net::Telnet/Net::SSH come to mind), or not. If you are worried about peak traffic rates, you'll have to carefully check the manufacturer's specifications - several of these devices are prone to the same traffic limitations as "regular" PC's, in that they still run into the PCI bus bandwidth issue, etc. At that point, you might as well roll your own. I guess you could read this more as a "pro's and con's" of doing either, if you want. FWIW, we run dual FreeBSD firewalls at my place of employment, and regularly push 40+Mbit/sec with no noticeable load/issues.
[ "firewall" ]
4
10
1,354
7
0
2008-09-07T14:58:17.393000
2008-09-07T15:14:55.577000
48,496
48,508
How to teach a crash course on C++?
In a few weeks, we'll be teaching a crash course on C++ for Java programmers straight out of college. They have little or no experience yet with C or C++. Previous editions of this course were just 1 or 2 half-day sessions and covered topics including: new language features, e.g. header vs. implementation pointers and references memory management operator overloading templates the standard libraries, e.g. the C library headers basic iostreams basic STL using libraries (headers, linking) they'll be using Linux, so Basic Linux console commands GCC and how to interpret its error messages Makefiles and Autotools basic debugger commands any topic they ask about During the course, each person individually writes, compiles, runs, and debugs simple programs using the newly introduced features. Is this the best way to learn? Which topics do you consider most crucial? Which topics should be added or removed? Which topics just can't be covered adequately in a short time?
I can only once again point to Stroustrup and preach: Don't teach the C subset! It's important, but not for beginners! C++ is complex enough as it is and the standard library classes, especially the STL, is much more important and (at least superficially) easier to understand than the C subset of C++. Same goes for pointers and heap memory allocation, incidentally. Of course they're important but only after having taught the STL containers. Another important concept that new students have to get their head around is the concept of different compilation units, the One Definition Rule (because if you don't know it you won't be able to decypher error messages) and headers. This is actually quite a barrier and one that has to be breached early on. Apart from the language features the most important thing to be taught is how to understand the C++ compiler and how to get help. Getting help (i.e. knowing how to search for the right information) in my experience is the single most important thing that has to be taught about C++. I've had quite good experiences with this order of teaching in the past. /EDIT: If you happen to know any German, take a look at http://madrat.net/coding/cpp/skript, part of a very short introduction used in one of my courses.
How to teach a crash course on C++? In a few weeks, we'll be teaching a crash course on C++ for Java programmers straight out of college. They have little or no experience yet with C or C++. Previous editions of this course were just 1 or 2 half-day sessions and covered topics including: new language features, e.g. header vs. implementation pointers and references memory management operator overloading templates the standard libraries, e.g. the C library headers basic iostreams basic STL using libraries (headers, linking) they'll be using Linux, so Basic Linux console commands GCC and how to interpret its error messages Makefiles and Autotools basic debugger commands any topic they ask about During the course, each person individually writes, compiles, runs, and debugs simple programs using the newly introduced features. Is this the best way to learn? Which topics do you consider most crucial? Which topics should be added or removed? Which topics just can't be covered adequately in a short time?
TITLE: How to teach a crash course on C++? QUESTION: In a few weeks, we'll be teaching a crash course on C++ for Java programmers straight out of college. They have little or no experience yet with C or C++. Previous editions of this course were just 1 or 2 half-day sessions and covered topics including: new language features, e.g. header vs. implementation pointers and references memory management operator overloading templates the standard libraries, e.g. the C library headers basic iostreams basic STL using libraries (headers, linking) they'll be using Linux, so Basic Linux console commands GCC and how to interpret its error messages Makefiles and Autotools basic debugger commands any topic they ask about During the course, each person individually writes, compiles, runs, and debugs simple programs using the newly introduced features. Is this the best way to learn? Which topics do you consider most crucial? Which topics should be added or removed? Which topics just can't be covered adequately in a short time? ANSWER: I can only once again point to Stroustrup and preach: Don't teach the C subset! It's important, but not for beginners! C++ is complex enough as it is and the standard library classes, especially the STL, is much more important and (at least superficially) easier to understand than the C subset of C++. Same goes for pointers and heap memory allocation, incidentally. Of course they're important but only after having taught the STL containers. Another important concept that new students have to get their head around is the concept of different compilation units, the One Definition Rule (because if you don't know it you won't be able to decypher error messages) and headers. This is actually quite a barrier and one that has to be breached early on. Apart from the language features the most important thing to be taught is how to understand the C++ compiler and how to get help. Getting help (i.e. knowing how to search for the right information) in my experience is the single most important thing that has to be taught about C++. I've had quite good experiences with this order of teaching in the past. /EDIT: If you happen to know any German, take a look at http://madrat.net/coding/cpp/skript, part of a very short introduction used in one of my courses.
[ "c++" ]
12
22
3,129
7
0
2008-09-07T15:02:08.180000
2008-09-07T15:11:38.627000
48,505
48,729
Citrix Server sort of app - on a Mac?
Does anyone know of a similar product to Citrix Server that'll run on the Mac OS? Essentially, I'm looking to allow multiple remote users to log in to the same OSX Server at the same time (with full visual desktop, not SSH).
Anyone have experience with Aqua Connect? Found them from Google, and they claim the next version works on RDP as well as VNC. Wondering if it's just a nice wrapper around the VNC capabilities @Soeren Kuklau pointed out. Thanks for the link to Vine Server, that's worth investigating.
Citrix Server sort of app - on a Mac? Does anyone know of a similar product to Citrix Server that'll run on the Mac OS? Essentially, I'm looking to allow multiple remote users to log in to the same OSX Server at the same time (with full visual desktop, not SSH).
TITLE: Citrix Server sort of app - on a Mac? QUESTION: Does anyone know of a similar product to Citrix Server that'll run on the Mac OS? Essentially, I'm looking to allow multiple remote users to log in to the same OSX Server at the same time (with full visual desktop, not SSH). ANSWER: Anyone have experience with Aqua Connect? Found them from Google, and they claim the next version works on RDP as well as VNC. Wondering if it's just a nice wrapper around the VNC capabilities @Soeren Kuklau pointed out. Thanks for the link to Vine Server, that's worth investigating.
[ "macos", "citrix" ]
3
1
2,409
5
0
2008-09-07T15:07:31.367000
2008-09-07T20:02:26.913000
48,521
48,522
How can you databind a single object in .NET?
I would like to use a component that exposes the datasource property, but instead of supplying the datasource with whole list of objects, I would like to use only simple object. Is there any way to do this? The mentioned component is DevExpress.XtraDataLayout.DataLayoutControl - this is fairly irrelevant to the question though.
Databinding expects an IEnumerable object, because it enumorates over it just like a foreach loop does. So to do this, just wrap your single object in an IEnumerable. Even this would work: DataBindObject.DataSource = new List ().Add(YourObjectInstance);
How can you databind a single object in .NET? I would like to use a component that exposes the datasource property, but instead of supplying the datasource with whole list of objects, I would like to use only simple object. Is there any way to do this? The mentioned component is DevExpress.XtraDataLayout.DataLayoutControl - this is fairly irrelevant to the question though.
TITLE: How can you databind a single object in .NET? QUESTION: I would like to use a component that exposes the datasource property, but instead of supplying the datasource with whole list of objects, I would like to use only simple object. Is there any way to do this? The mentioned component is DevExpress.XtraDataLayout.DataLayoutControl - this is fairly irrelevant to the question though. ANSWER: Databinding expects an IEnumerable object, because it enumorates over it just like a foreach loop does. So to do this, just wrap your single object in an IEnumerable. Even this would work: DataBindObject.DataSource = new List ().Add(YourObjectInstance);
[ ".net", "data-binding" ]
3
8
3,830
5
0
2008-09-07T15:18:43.477000
2008-09-07T15:19:44.707000
48,526
48,721
Call Visitors web stat program from PHP
I've been looking into different web statistics programs for my site, and one promising one is Visitors. Unfortunately, it's a C program and I don't know how to call it from the web server. I've tried using PHP's shell_exec, but my web host ( NFSN ) has PHP's safe mode on and it's giving me an error message. Is there a way to execute the program within safe mode? If not, can it work with CGI? If so, how? (I've never used CGI before)
I managed to solve this problem on my own. I put the following lines in a file named visitors.cgi: #!/bin/sh printf "Content-type: text/html\n\n" exec visitors -A /home/logs/access_log
Call Visitors web stat program from PHP I've been looking into different web statistics programs for my site, and one promising one is Visitors. Unfortunately, it's a C program and I don't know how to call it from the web server. I've tried using PHP's shell_exec, but my web host ( NFSN ) has PHP's safe mode on and it's giving me an error message. Is there a way to execute the program within safe mode? If not, can it work with CGI? If so, how? (I've never used CGI before)
TITLE: Call Visitors web stat program from PHP QUESTION: I've been looking into different web statistics programs for my site, and one promising one is Visitors. Unfortunately, it's a C program and I don't know how to call it from the web server. I've tried using PHP's shell_exec, but my web host ( NFSN ) has PHP's safe mode on and it's giving me an error message. Is there a way to execute the program within safe mode? If not, can it work with CGI? If so, how? (I've never used CGI before) ANSWER: I managed to solve this problem on my own. I put the following lines in a file named visitors.cgi: #!/bin/sh printf "Content-type: text/html\n\n" exec visitors -A /home/logs/access_log
[ "statistics", "cgi", "analytics", "visitors", "php-safe-mode" ]
0
0
307
5
0
2008-09-07T15:30:19.737000
2008-09-07T19:49:16.773000
48,550
48,553
How do I publish a Asp.NET web application using MSBuild?
I am trying to publish an Asp.net MVC web application locally using the NAnt and MSBuild. This is what I am using for my NAnt target; and all I get is this as a response; [msbuild] Skipping unpublishable project. Is it possible to publish web applications via the command line in this way?
The "Publish" target you are trying to invoke is for "OneClick" deployment, not for publishing a website... This is why you are getting the seemingly bizarre message. You would want to use the AspNetCompiler task, rather than the MSBuild task. See http://msdn2.microsoft.com/en-us/library/ms164291.aspx for more info on this task. Your "PublishDir" would correspond to the TargetPath property of the task. Source
How do I publish a Asp.NET web application using MSBuild? I am trying to publish an Asp.net MVC web application locally using the NAnt and MSBuild. This is what I am using for my NAnt target; and all I get is this as a response; [msbuild] Skipping unpublishable project. Is it possible to publish web applications via the command line in this way?
TITLE: How do I publish a Asp.NET web application using MSBuild? QUESTION: I am trying to publish an Asp.net MVC web application locally using the NAnt and MSBuild. This is what I am using for my NAnt target; and all I get is this as a response; [msbuild] Skipping unpublishable project. Is it possible to publish web applications via the command line in this way? ANSWER: The "Publish" target you are trying to invoke is for "OneClick" deployment, not for publishing a website... This is why you are getting the seemingly bizarre message. You would want to use the AspNetCompiler task, rather than the MSBuild task. See http://msdn2.microsoft.com/en-us/library/ms164291.aspx for more info on this task. Your "PublishDir" would correspond to the TargetPath property of the task. Source
[ "asp.net", ".net", "deployment", "msbuild" ]
19
21
25,233
2
0
2008-09-07T16:15:01.750000
2008-09-07T16:20:27.307000
48,562
50,507
How do I implement a pre-commit hook script in SVN that calls dos2unix to validate checked-in file
I was wondering if anyone here had some experience writing this type of script and if they could give me some pointers. I would like to modify this script to validate that the check-in file does not have a Carriage Return in the EOL formatting. The EOL format is CR LF in Windows and LF in Unix. When a User checks-in code with the Windows format. It does not compile in Unix anymore. I know this can be done on the client side but I need to have this validation done on the server side. To achieve this, I need to do the following: 1) Make sure the file I check is not a binary, I dont know how to do this with svnlook, should I check the mime:type of the file? The Red Book does not indicate this clearly or I must have not seen it. 2) I would like to run the dos2unix command to validate that the file has the correct EOL format. I would compare the output of the dos2unix command against the original file. If there is a diff between both, I give an error message to the client and cancel the check-in. I would like your comments/feedback on this approach.
I think you can avoid a commit hook script in this case by using the svn:eol-style property as described in the SVNBook: End-of-Line Character Sequences Subversion Properties This way SVN can worry about your line endings for you. Good luck!
How do I implement a pre-commit hook script in SVN that calls dos2unix to validate checked-in file I was wondering if anyone here had some experience writing this type of script and if they could give me some pointers. I would like to modify this script to validate that the check-in file does not have a Carriage Return in the EOL formatting. The EOL format is CR LF in Windows and LF in Unix. When a User checks-in code with the Windows format. It does not compile in Unix anymore. I know this can be done on the client side but I need to have this validation done on the server side. To achieve this, I need to do the following: 1) Make sure the file I check is not a binary, I dont know how to do this with svnlook, should I check the mime:type of the file? The Red Book does not indicate this clearly or I must have not seen it. 2) I would like to run the dos2unix command to validate that the file has the correct EOL format. I would compare the output of the dos2unix command against the original file. If there is a diff between both, I give an error message to the client and cancel the check-in. I would like your comments/feedback on this approach.
TITLE: How do I implement a pre-commit hook script in SVN that calls dos2unix to validate checked-in file QUESTION: I was wondering if anyone here had some experience writing this type of script and if they could give me some pointers. I would like to modify this script to validate that the check-in file does not have a Carriage Return in the EOL formatting. The EOL format is CR LF in Windows and LF in Unix. When a User checks-in code with the Windows format. It does not compile in Unix anymore. I know this can be done on the client side but I need to have this validation done on the server side. To achieve this, I need to do the following: 1) Make sure the file I check is not a binary, I dont know how to do this with svnlook, should I check the mime:type of the file? The Red Book does not indicate this clearly or I must have not seen it. 2) I would like to run the dos2unix command to validate that the file has the correct EOL format. I would compare the output of the dos2unix command against the original file. If there is a diff between both, I give an error message to the client and cancel the check-in. I would like your comments/feedback on this approach. ANSWER: I think you can avoid a commit hook script in this case by using the svn:eol-style property as described in the SVNBook: End-of-Line Character Sequences Subversion Properties This way SVN can worry about your line endings for you. Good luck!
[ "python", "svn", "dos2unix" ]
8
4
4,296
2
0
2008-09-07T16:32:55.653000
2008-09-08T19:45:24.840000
48,567
48,571
Change user for running windows forms program
I wrote a simple Windows Forms program in C#. I want to be able to input a windows user name and password and when I click a login button to run code run as the user I've entered as input.
You can use the WindowsIdentity.Impersonate method to achieve this. This method allows code to impersonate a different Windows user. Here is a link for more information on this method with a good sample: http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.impersonate.aspx Complete example: // This sample demonstrates the use of the WindowsIdentity class to impersonate a user. // IMPORTANT NOTES: // This sample can be run only on Windows XP. The default Windows 2000 security policy // prevents this sample from executing properly, and changing the policy to allow // proper execution presents a security risk. // This sample requests the user to enter a password on the console screen. // Because the console window does not support methods allowing the password to be masked, // it will be visible to anyone viewing the screen. // The sample is intended to be executed in a.NET Framework 1.1 environment. To execute // this code in a 1.0 environment you will need to use a duplicate token in the call to the // WindowsIdentity constructor. See KB article Q319615 for more information. using System; using System.Runtime.InteropServices; using System.Security.Principal; using System.Security.Permissions; using System.Windows.Forms; [assembly:SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode=true)] [assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")] public class ImpersonationDemo { [DllImport("advapi32.dll", SetLastError=true, CharSet = CharSet.Unicode)] public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("kernel32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)] private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource, int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr *Arguments); [DllImport("kernel32.dll", CharSet=CharSet.Auto)] public extern static bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); // Test harness. // If you incorporate this code into a DLL, be sure to demand FullTrust. [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public static void Main(string[] args) { IntPtr tokenHandle = new IntPtr(0); IntPtr dupeTokenHandle = new IntPtr(0); try { string userName, domainName; // Get the user token for the specified user, domain, and password using the // unmanaged LogonUser method. // The local machine name can be used for the domain name to impersonate a user on this machine. Console.Write("Enter the name of the domain on which to log on: "); domainName = Console.ReadLine(); Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName); userName = Console.ReadLine(); Console.Write("Enter the password for {0}: ", userName); const int LOGON32_PROVIDER_DEFAULT = 0; //This parameter causes LogonUser to create a primary token. const int LOGON32_LOGON_INTERACTIVE = 2; tokenHandle = IntPtr.Zero; // Call LogonUser to obtain a handle to an access token. bool returnValue = LogonUser(userName, domainName, Console.ReadLine(), LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle); Console.WriteLine("LogonUser called."); if (false == returnValue) { int ret = Marshal.GetLastWin32Error(); Console.WriteLine("LogonUser failed with error code: {0}", ret); throw new System.ComponentModel.Win32Exception(ret); } Console.WriteLine("Did LogonUser Succeed? " + (returnValue? "Yes": "No")); Console.WriteLine("Value of Windows NT token: " + tokenHandle); // Check the identity. Console.WriteLine("Before impersonation: " + WindowsIdentity.GetCurrent().Name); // Use the token handle returned by LogonUser. WindowsIdentity newId = new WindowsIdentity(tokenHandle); WindowsImpersonationContext impersonatedUser = newId.Impersonate(); // Check the identity. Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name); // Stop impersonating the user. impersonatedUser.Undo(); // Check the identity. Console.WriteLine("After Undo: " + WindowsIdentity.GetCurrent().Name); // Free the tokens. if (tokenHandle!= IntPtr.Zero) CloseHandle(tokenHandle); } catch(Exception ex) { Console.WriteLine("Exception occurred. " + ex.Message); } } }
Change user for running windows forms program I wrote a simple Windows Forms program in C#. I want to be able to input a windows user name and password and when I click a login button to run code run as the user I've entered as input.
TITLE: Change user for running windows forms program QUESTION: I wrote a simple Windows Forms program in C#. I want to be able to input a windows user name and password and when I click a login button to run code run as the user I've entered as input. ANSWER: You can use the WindowsIdentity.Impersonate method to achieve this. This method allows code to impersonate a different Windows user. Here is a link for more information on this method with a good sample: http://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity.impersonate.aspx Complete example: // This sample demonstrates the use of the WindowsIdentity class to impersonate a user. // IMPORTANT NOTES: // This sample can be run only on Windows XP. The default Windows 2000 security policy // prevents this sample from executing properly, and changing the policy to allow // proper execution presents a security risk. // This sample requests the user to enter a password on the console screen. // Because the console window does not support methods allowing the password to be masked, // it will be visible to anyone viewing the screen. // The sample is intended to be executed in a.NET Framework 1.1 environment. To execute // this code in a 1.0 environment you will need to use a duplicate token in the call to the // WindowsIdentity constructor. See KB article Q319615 for more information. using System; using System.Runtime.InteropServices; using System.Security.Principal; using System.Security.Permissions; using System.Windows.Forms; [assembly:SecurityPermissionAttribute(SecurityAction.RequestMinimum, UnmanagedCode=true)] [assembly:PermissionSetAttribute(SecurityAction.RequestMinimum, Name = "FullTrust")] public class ImpersonationDemo { [DllImport("advapi32.dll", SetLastError=true, CharSet = CharSet.Unicode)] public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken); [DllImport("kernel32.dll", CharSet=System.Runtime.InteropServices.CharSet.Auto)] private unsafe static extern int FormatMessage(int dwFlags, ref IntPtr lpSource, int dwMessageId, int dwLanguageId, ref String lpBuffer, int nSize, IntPtr *Arguments); [DllImport("kernel32.dll", CharSet=CharSet.Auto)] public extern static bool CloseHandle(IntPtr handle); [DllImport("advapi32.dll", CharSet=CharSet.Auto, SetLastError=true)] public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle); // Test harness. // If you incorporate this code into a DLL, be sure to demand FullTrust. [PermissionSetAttribute(SecurityAction.Demand, Name = "FullTrust")] public static void Main(string[] args) { IntPtr tokenHandle = new IntPtr(0); IntPtr dupeTokenHandle = new IntPtr(0); try { string userName, domainName; // Get the user token for the specified user, domain, and password using the // unmanaged LogonUser method. // The local machine name can be used for the domain name to impersonate a user on this machine. Console.Write("Enter the name of the domain on which to log on: "); domainName = Console.ReadLine(); Console.Write("Enter the login of a user on {0} that you wish to impersonate: ", domainName); userName = Console.ReadLine(); Console.Write("Enter the password for {0}: ", userName); const int LOGON32_PROVIDER_DEFAULT = 0; //This parameter causes LogonUser to create a primary token. const int LOGON32_LOGON_INTERACTIVE = 2; tokenHandle = IntPtr.Zero; // Call LogonUser to obtain a handle to an access token. bool returnValue = LogonUser(userName, domainName, Console.ReadLine(), LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT, ref tokenHandle); Console.WriteLine("LogonUser called."); if (false == returnValue) { int ret = Marshal.GetLastWin32Error(); Console.WriteLine("LogonUser failed with error code: {0}", ret); throw new System.ComponentModel.Win32Exception(ret); } Console.WriteLine("Did LogonUser Succeed? " + (returnValue? "Yes": "No")); Console.WriteLine("Value of Windows NT token: " + tokenHandle); // Check the identity. Console.WriteLine("Before impersonation: " + WindowsIdentity.GetCurrent().Name); // Use the token handle returned by LogonUser. WindowsIdentity newId = new WindowsIdentity(tokenHandle); WindowsImpersonationContext impersonatedUser = newId.Impersonate(); // Check the identity. Console.WriteLine("After impersonation: " + WindowsIdentity.GetCurrent().Name); // Stop impersonating the user. impersonatedUser.Undo(); // Check the identity. Console.WriteLine("After Undo: " + WindowsIdentity.GetCurrent().Name); // Free the tokens. if (tokenHandle!= IntPtr.Zero) CloseHandle(tokenHandle); } catch(Exception ex) { Console.WriteLine("Exception occurred. " + ex.Message); } } }
[ ".net", "windows", "winforms", "authentication" ]
3
4
7,117
2
0
2008-09-07T16:38:40.507000
2008-09-07T16:43:16.020000
48,570
48,591
Something like a callback delegate function in php
I would like to implement something similar to a c# delegate method in PHP. A quick word to explain what I'm trying to do overall: I am trying to implement some asynchronous functionality. Basically, some resource-intensive calls that get queued, cached and dispatched when the underlying system gets around to it. When the asynchronous call finally receives a response I would like a callback event to be raised. I am having some problems coming up with a mechanism to do callbacks in PHP. I have come up with a method that works for now but I am unhappy with it. Basically, it involves passing a reference to the object and the name of the method on it that will serve as the callback (taking the response as an argument) and then use eval to call the method when need be. This is sub-optimal for a variety of reasons, is there a better way of doing this that anyone knows of?
(Apart from the observer pattern) you can also use call_user_func() or call_user_func_array(). If you pass an array(obj, methodname) as first parameter it will invoked as $obj->methodname().
Something like a callback delegate function in php I would like to implement something similar to a c# delegate method in PHP. A quick word to explain what I'm trying to do overall: I am trying to implement some asynchronous functionality. Basically, some resource-intensive calls that get queued, cached and dispatched when the underlying system gets around to it. When the asynchronous call finally receives a response I would like a callback event to be raised. I am having some problems coming up with a mechanism to do callbacks in PHP. I have come up with a method that works for now but I am unhappy with it. Basically, it involves passing a reference to the object and the name of the method on it that will serve as the callback (taking the response as an argument) and then use eval to call the method when need be. This is sub-optimal for a variety of reasons, is there a better way of doing this that anyone knows of?
TITLE: Something like a callback delegate function in php QUESTION: I would like to implement something similar to a c# delegate method in PHP. A quick word to explain what I'm trying to do overall: I am trying to implement some asynchronous functionality. Basically, some resource-intensive calls that get queued, cached and dispatched when the underlying system gets around to it. When the asynchronous call finally receives a response I would like a callback event to be raised. I am having some problems coming up with a mechanism to do callbacks in PHP. I have come up with a method that works for now but I am unhappy with it. Basically, it involves passing a reference to the object and the name of the method on it that will serve as the callback (taking the response as an argument) and then use eval to call the method when need be. This is sub-optimal for a variety of reasons, is there a better way of doing this that anyone knows of? ANSWER: (Apart from the observer pattern) you can also use call_user_func() or call_user_func_array(). If you pass an array(obj, methodname) as first parameter it will invoked as $obj->methodname().
[ "php", "oop" ]
16
16
12,440
3
0
2008-09-07T16:42:07.707000
2008-09-07T17:14:11.903000
48,574
48,623
Troubleshooting a NullReference exception in a service
I have a windows service that runs various system monitoring operations. However, when running SNMP related checks, I always get a NullReference exception. The code runs fine when run through the user interface (under my username and password), but always errors running as the service. I've tried running the service as different user accounts (including mine), with no luck. I've tried replacing the SNMP monitoring code with calling the PowerShell cmdlet get-snmp (from the /n NetCmdlets ), but that yields the same error. The application I'm working with is PolyMon. Any ideas?
Some ways to debug: Is there any additional information in the Windows events log? I believe you should be able to listen to some kind of global-exception event like Application_Exception in windows services. I can't remember the exact name but you can atelast dump stack trace from there. You should be able to start debugging the project in service mode. Some code snippets/stack trace/information will definitely help.
Troubleshooting a NullReference exception in a service I have a windows service that runs various system monitoring operations. However, when running SNMP related checks, I always get a NullReference exception. The code runs fine when run through the user interface (under my username and password), but always errors running as the service. I've tried running the service as different user accounts (including mine), with no luck. I've tried replacing the SNMP monitoring code with calling the PowerShell cmdlet get-snmp (from the /n NetCmdlets ), but that yields the same error. The application I'm working with is PolyMon. Any ideas?
TITLE: Troubleshooting a NullReference exception in a service QUESTION: I have a windows service that runs various system monitoring operations. However, when running SNMP related checks, I always get a NullReference exception. The code runs fine when run through the user interface (under my username and password), but always errors running as the service. I've tried running the service as different user accounts (including mine), with no luck. I've tried replacing the SNMP monitoring code with calling the PowerShell cmdlet get-snmp (from the /n NetCmdlets ), but that yields the same error. The application I'm working with is PolyMon. Any ideas? ANSWER: Some ways to debug: Is there any additional information in the Windows events log? I believe you should be able to listen to some kind of global-exception event like Application_Exception in windows services. I can't remember the exact name but you can atelast dump stack trace from there. You should be able to start debugging the project in service mode. Some code snippets/stack trace/information will definitely help.
[ ".net", "exception", "powershell", "service" ]
1
2
366
4
0
2008-09-07T16:46:48.053000
2008-09-07T18:00:13.620000
48,605
48,611
Why do most system architects insist on first programming to an interface?
Almost every Java book I read talks about using the interface as a way to share state and behaviour between objects that when first "constructed" did not seem to share a relationship. However, whenever I see architects design an application, the first thing they do is start programming to an interface. How come? How do you know all the relationships between objects that will occur within that interface? If you already know those relationships, then why not just extend an abstract class?
Programming to an interface means respecting the "contract" created by using that interface. And so if your IPoweredByMotor interface has a start() method, future classes that implement the interface, be they MotorizedWheelChair, Automobile, or SmoothieMaker, in implementing the methods of that interface, add flexibility to your system, because one piece of code can start the motor of many different types of things, because all that one piece of code needs to know is that they respond to start(). It doesn't matter how they start, just that they must start.
Why do most system architects insist on first programming to an interface? Almost every Java book I read talks about using the interface as a way to share state and behaviour between objects that when first "constructed" did not seem to share a relationship. However, whenever I see architects design an application, the first thing they do is start programming to an interface. How come? How do you know all the relationships between objects that will occur within that interface? If you already know those relationships, then why not just extend an abstract class?
TITLE: Why do most system architects insist on first programming to an interface? QUESTION: Almost every Java book I read talks about using the interface as a way to share state and behaviour between objects that when first "constructed" did not seem to share a relationship. However, whenever I see architects design an application, the first thing they do is start programming to an interface. How come? How do you know all the relationships between objects that will occur within that interface? If you already know those relationships, then why not just extend an abstract class? ANSWER: Programming to an interface means respecting the "contract" created by using that interface. And so if your IPoweredByMotor interface has a start() method, future classes that implement the interface, be they MotorizedWheelChair, Automobile, or SmoothieMaker, in implementing the methods of that interface, add flexibility to your system, because one piece of code can start the motor of many different types of things, because all that one piece of code needs to know is that they respond to start(). It doesn't matter how they start, just that they must start.
[ "language-agnostic", "design-patterns", "interface" ]
27
30
2,936
16
0
2008-09-07T17:40:25.710000
2008-09-07T17:46:51.577000
48,616
1,315,742
How to access controls in listview's layouttemplate?
How do I set a property of a user control in ListView 's LayoutTemplate from the code-behind?... I want to do this: myControl.SomeProperty = somevalue; Please notice that my control is not in ItemTemplate, it is in LayoutTemplate, so it does not exist for all items, it exists only once. So I should be able to access it once, not for every data bound item.
To set a property of a control that is inside the LayoutTemplate, simply use the FindControl method on the ListView control. var control = (MyControl)myListView.FindControl("myControlId");
How to access controls in listview's layouttemplate? How do I set a property of a user control in ListView 's LayoutTemplate from the code-behind?... I want to do this: myControl.SomeProperty = somevalue; Please notice that my control is not in ItemTemplate, it is in LayoutTemplate, so it does not exist for all items, it exists only once. So I should be able to access it once, not for every data bound item.
TITLE: How to access controls in listview's layouttemplate? QUESTION: How do I set a property of a user control in ListView 's LayoutTemplate from the code-behind?... I want to do this: myControl.SomeProperty = somevalue; Please notice that my control is not in ItemTemplate, it is in LayoutTemplate, so it does not exist for all items, it exists only once. So I should be able to access it once, not for every data bound item. ANSWER: To set a property of a control that is inside the LayoutTemplate, simply use the FindControl method on the ListView control. var control = (MyControl)myListView.FindControl("myControlId");
[ "asp.net", "listview" ]
12
12
19,673
6
0
2008-09-07T17:54:48.797000
2009-08-22T10:53:40.647000
48,642
48,657
How do I specify "the word under the cursor" on VIM's commandline?
I want to write a command that specifies "the word under the cursor" in VIM. For instance, let's say I have the cursor on a word and I make it appear twice. For instance, if the word is "abc" and I want "abcabc" then I could type::s/\(abc\)/\1\1/ But then I'd like to be able to move the cursor to "def" and use the same command to change it to "defdef"::s/\(def\)/\1\1/ How can I write the command in the commandline so that it does this?:s/\(*whatever is under the commandline*\)/\1\1
is the word under the cursor (:help ). You can nmap a command to it, or this series of keystrokes for the lazy will work: b #go to beginning of current word yw #yank to register Then, when you are typing in your pattern you can hit 0 which will paste in your command the contents of the 0-th register. You can also make a command for this like::nmap w:s/\( =expand(" ") \)/ Which will map hitting '' and 'w' at the same time to replace your command line with:s/\( \)/
How do I specify "the word under the cursor" on VIM's commandline? I want to write a command that specifies "the word under the cursor" in VIM. For instance, let's say I have the cursor on a word and I make it appear twice. For instance, if the word is "abc" and I want "abcabc" then I could type::s/\(abc\)/\1\1/ But then I'd like to be able to move the cursor to "def" and use the same command to change it to "defdef"::s/\(def\)/\1\1/ How can I write the command in the commandline so that it does this?:s/\(*whatever is under the commandline*\)/\1\1
TITLE: How do I specify "the word under the cursor" on VIM's commandline? QUESTION: I want to write a command that specifies "the word under the cursor" in VIM. For instance, let's say I have the cursor on a word and I make it appear twice. For instance, if the word is "abc" and I want "abcabc" then I could type::s/\(abc\)/\1\1/ But then I'd like to be able to move the cursor to "def" and use the same command to change it to "defdef"::s/\(def\)/\1\1/ How can I write the command in the commandline so that it does this?:s/\(*whatever is under the commandline*\)/\1\1 ANSWER: is the word under the cursor (:help ). You can nmap a command to it, or this series of keystrokes for the lazy will work: b #go to beginning of current word yw #yank to register Then, when you are typing in your pattern you can hit 0 which will paste in your command the contents of the 0-th register. You can also make a command for this like::nmap w:s/\( =expand(" ") \)/ Which will map hitting '' and 'w' at the same time to replace your command line with:s/\( \)/
[ "vim", "command-line" ]
103
80
40,668
8
0
2008-09-07T18:17:14.170000
2008-09-07T18:24:56.447000
48,647
48,663
Does ScopeGuard use really lead to better code?
I came across this article written by Andrei Alexandrescu and Petru Marginean many years ago, which presents and discusses a utility class called ScopeGuard for writing exception-safe code. I'd like to know if coding with these objects truly leads to better code or if it obfuscates error handling, in that perhaps the guard's callback would be better presented in a catch block? Does anyone have any experience using these in actual production code?
It definitely improves your code. Your tentatively formulated claim, that it's obscure and that code would merit from a catch block is simply not true in C++ because RAII is an established idiom. Resource handling in C++ is done by resource acquisition and garbage collection is done by implicit destructor calls. On the other hand, explicit catch blocks would bloat the code and introduce subtle errors because the code flow gets much more complex and resource handling has to be done explicitly. RAII (including ScopeGuard s) isn't an obscure technique in C++ but firmly established best-practice.
Does ScopeGuard use really lead to better code? I came across this article written by Andrei Alexandrescu and Petru Marginean many years ago, which presents and discusses a utility class called ScopeGuard for writing exception-safe code. I'd like to know if coding with these objects truly leads to better code or if it obfuscates error handling, in that perhaps the guard's callback would be better presented in a catch block? Does anyone have any experience using these in actual production code?
TITLE: Does ScopeGuard use really lead to better code? QUESTION: I came across this article written by Andrei Alexandrescu and Petru Marginean many years ago, which presents and discusses a utility class called ScopeGuard for writing exception-safe code. I'd like to know if coding with these objects truly leads to better code or if it obfuscates error handling, in that perhaps the guard's callback would be better presented in a catch block? Does anyone have any experience using these in actual production code? ANSWER: It definitely improves your code. Your tentatively formulated claim, that it's obscure and that code would merit from a catch block is simply not true in C++ because RAII is an established idiom. Resource handling in C++ is done by resource acquisition and garbage collection is done by implicit destructor calls. On the other hand, explicit catch blocks would bloat the code and introduce subtle errors because the code flow gets much more complex and resource handling has to be done explicitly. RAII (including ScopeGuard s) isn't an obscure technique in C++ but firmly established best-practice.
[ "c++", "raii", "scopeguard" ]
33
63
12,877
8
0
2008-09-07T18:20:43.647000
2008-09-07T18:30:18.040000
48,659
48,678
How do you send and receive UDP packets in Java on a multihomed machine?
I have a machine with VmWare installed which added two extra network interfaces. The OS is Vista. I have two Java applications, one which broadcasts datagrams, and one which receives those datagrams. The problem I'm having is that unless I disable both VmWare network interfaces, the receiver can't receive the datagrams. What is the best way to make that work without disabling the interfaces?
Look at the alternate constructor for DatagramSocket: DatagramSocket(int port, InetAddress laddr) Creates a datagram socket, bound to the specified local address. I'm guessing you're only specifying the port.
How do you send and receive UDP packets in Java on a multihomed machine? I have a machine with VmWare installed which added two extra network interfaces. The OS is Vista. I have two Java applications, one which broadcasts datagrams, and one which receives those datagrams. The problem I'm having is that unless I disable both VmWare network interfaces, the receiver can't receive the datagrams. What is the best way to make that work without disabling the interfaces?
TITLE: How do you send and receive UDP packets in Java on a multihomed machine? QUESTION: I have a machine with VmWare installed which added two extra network interfaces. The OS is Vista. I have two Java applications, one which broadcasts datagrams, and one which receives those datagrams. The problem I'm having is that unless I disable both VmWare network interfaces, the receiver can't receive the datagrams. What is the best way to make that work without disabling the interfaces? ANSWER: Look at the alternate constructor for DatagramSocket: DatagramSocket(int port, InetAddress laddr) Creates a datagram socket, bound to the specified local address. I'm guessing you're only specifying the port.
[ "java", "sockets" ]
6
9
1,633
1
0
2008-09-07T18:27:59.823000
2008-09-07T18:55:52.130000
48,668
48,705
How should anonymous types be used in C#?
I've seen lots of descriptions how anonymous types work, but I'm not sure how they're really useful. What are some scenarios that anonymous types can be used to address in a well-designed program?
Anonymous types have nothing to do with the design of systems or even at the class level. They're a tool for developers to use when coding. I don't even treat anonymous types as types per-se. I use them mainly as method-level anonymous tuples. If I query the database and then manipulate the results, I would rather create an anonymous type and use that rather than declare a whole new type that will never be used or known outside of the scope of my method. For instance: var query = from item in database.Items //... select new { Id = item.Id, Name = item.Name }; return query.ToDictionary(item => item.Id, item => item.Name); Nobody cares about `a, the anonymous type. It's there so you don't have to declare another class.
How should anonymous types be used in C#? I've seen lots of descriptions how anonymous types work, but I'm not sure how they're really useful. What are some scenarios that anonymous types can be used to address in a well-designed program?
TITLE: How should anonymous types be used in C#? QUESTION: I've seen lots of descriptions how anonymous types work, but I'm not sure how they're really useful. What are some scenarios that anonymous types can be used to address in a well-designed program? ANSWER: Anonymous types have nothing to do with the design of systems or even at the class level. They're a tool for developers to use when coding. I don't even treat anonymous types as types per-se. I use them mainly as method-level anonymous tuples. If I query the database and then manipulate the results, I would rather create an anonymous type and use that rather than declare a whole new type that will never be used or known outside of the scope of my method. For instance: var query = from item in database.Items //... select new { Id = item.Id, Name = item.Name }; return query.ToDictionary(item => item.Id, item => item.Name); Nobody cares about `a, the anonymous type. It's there so you don't have to declare another class.
[ "c#", "anonymous-types" ]
21
23
6,068
7
0
2008-09-07T18:34:32.787000
2008-09-07T19:31:12.793000
48,679
48,689
Copy a file without using the windows file cache
Anybody know of a way to copy a file from path A to path B and suppressing the Windows file system cache? Typical use is copying a large file from a USB drive, or server to your local machine. Windows seems to swap everything out if the file is really big, e.g. 2GiB. Prefer example in C#, but I'm guessing this would be a Win32 call of some sort if possible.
Even more important, there are FILE_FLAG_WRITE_THROUGH and FILE_FLAG_NO_BUFFERING. MSDN has a nice article on them both: http://support.microsoft.com/kb/99794
Copy a file without using the windows file cache Anybody know of a way to copy a file from path A to path B and suppressing the Windows file system cache? Typical use is copying a large file from a USB drive, or server to your local machine. Windows seems to swap everything out if the file is really big, e.g. 2GiB. Prefer example in C#, but I'm guessing this would be a Win32 call of some sort if possible.
TITLE: Copy a file without using the windows file cache QUESTION: Anybody know of a way to copy a file from path A to path B and suppressing the Windows file system cache? Typical use is copying a large file from a USB drive, or server to your local machine. Windows seems to swap everything out if the file is really big, e.g. 2GiB. Prefer example in C#, but I'm guessing this would be a Win32 call of some sort if possible. ANSWER: Even more important, there are FILE_FLAG_WRITE_THROUGH and FILE_FLAG_NO_BUFFERING. MSDN has a nice article on them both: http://support.microsoft.com/kb/99794
[ "c#", "windows", "winapi", "filesystems", "file-copying" ]
6
5
11,928
6
0
2008-09-07T18:56:33.687000
2008-09-07T19:09:32.033000