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
4,752
97,256
MOSS SSP Issue - Failed database logons from deleted SSP
We've been having some issues with a SharePoint instance in a test environment. Thankfully this is not production;) The problems started when the disk with the SQL Server databases and search index ran out of space. Following this, the search service would not run and search settings in the SSP were not accessible. Reclaiming the disk space did not resolve the issue. So rather than restoring the VM, we decided to try to fix the issue. We created a new SSP and changed the association of all services to the new SSP. The old SSP and it's databases were then deleted. Search results for PDF files are no longer appearing, but the search works fine otherwise. MySites also works OK. Following the implementation of this change, these problems occur: 1) An audit failure message started appearing in the application event log, for 'DOMAIN\SPMOSSSvc' which is the MOSS farm account. Event Type: Failure Audit Event Source: MSSQLSERVER Event Category: (4) Event ID: 18456 Date: 8/5/2008 Time: 3:55:19 PM User: DOMAIN\SPMOSSSvc Computer: dastest01 Description: Login failed for user 'DOMAIN\SPMOSSSvc'. [CLIENT: ] 2) SQL Server profiler is showing queries from SharePoint that reference the old (deleted) SSP database. So... Where would these references to DOMAIN\SPMOSSSvc and the old SSP database exist? Is there a way to 'completely' remove the SSP from the server, and re-create? The option to delete was not available (greyed out) when a single SSP is in place.
As Daniel McPherson said, this is caused when SSPs are deleted but the associated job are not and attempt to communicate with the deleted database. If the SSP database has been deleted or a problem occurred when deleting an SSP, the job may not be deleted. When the job attempts to run, it will fail since the database no longer exists. Follow the steps Daniel mentioned: 1. Go to SQL Server Management Studio 2. Disable the job called SSPNAME_JobDeleteExpiredSessions, right click and choose Disable Job.
MOSS SSP Issue - Failed database logons from deleted SSP We've been having some issues with a SharePoint instance in a test environment. Thankfully this is not production;) The problems started when the disk with the SQL Server databases and search index ran out of space. Following this, the search service would not run and search settings in the SSP were not accessible. Reclaiming the disk space did not resolve the issue. So rather than restoring the VM, we decided to try to fix the issue. We created a new SSP and changed the association of all services to the new SSP. The old SSP and it's databases were then deleted. Search results for PDF files are no longer appearing, but the search works fine otherwise. MySites also works OK. Following the implementation of this change, these problems occur: 1) An audit failure message started appearing in the application event log, for 'DOMAIN\SPMOSSSvc' which is the MOSS farm account. Event Type: Failure Audit Event Source: MSSQLSERVER Event Category: (4) Event ID: 18456 Date: 8/5/2008 Time: 3:55:19 PM User: DOMAIN\SPMOSSSvc Computer: dastest01 Description: Login failed for user 'DOMAIN\SPMOSSSvc'. [CLIENT: ] 2) SQL Server profiler is showing queries from SharePoint that reference the old (deleted) SSP database. So... Where would these references to DOMAIN\SPMOSSSvc and the old SSP database exist? Is there a way to 'completely' remove the SSP from the server, and re-create? The option to delete was not available (greyed out) when a single SSP is in place.
TITLE: MOSS SSP Issue - Failed database logons from deleted SSP QUESTION: We've been having some issues with a SharePoint instance in a test environment. Thankfully this is not production;) The problems started when the disk with the SQL Server databases and search index ran out of space. Following this, the search service would not run and search settings in the SSP were not accessible. Reclaiming the disk space did not resolve the issue. So rather than restoring the VM, we decided to try to fix the issue. We created a new SSP and changed the association of all services to the new SSP. The old SSP and it's databases were then deleted. Search results for PDF files are no longer appearing, but the search works fine otherwise. MySites also works OK. Following the implementation of this change, these problems occur: 1) An audit failure message started appearing in the application event log, for 'DOMAIN\SPMOSSSvc' which is the MOSS farm account. Event Type: Failure Audit Event Source: MSSQLSERVER Event Category: (4) Event ID: 18456 Date: 8/5/2008 Time: 3:55:19 PM User: DOMAIN\SPMOSSSvc Computer: dastest01 Description: Login failed for user 'DOMAIN\SPMOSSSvc'. [CLIENT: ] 2) SQL Server profiler is showing queries from SharePoint that reference the old (deleted) SSP database. So... Where would these references to DOMAIN\SPMOSSSvc and the old SSP database exist? Is there a way to 'completely' remove the SSP from the server, and re-create? The option to delete was not available (greyed out) when a single SSP is in place. ANSWER: As Daniel McPherson said, this is caused when SSPs are deleted but the associated job are not and attempt to communicate with the deleted database. If the SSP database has been deleted or a problem occurred when deleting an SSP, the job may not be deleted. When the job attempts to run, it will fail since the database no longer exists. Follow the steps Daniel mentioned: 1. Go to SQL Server Management Studio 2. Disable the job called SSPNAME_JobDeleteExpiredSessions, right click and choose Disable Job.
[ "sql-server", "database", "sharepoint", "search", "ssp" ]
16
5
3,445
3
0
2008-08-07T14:21:10.087000
2008-09-18T21:37:19.153000
4,782
70,009
How much database performance overhead when using LINQ?
How much database performance overhead is involved with using C# and LINQ compared to custom optimized queries loaded with mostly low-level C, both with a SQL Server 2008 backend? I'm specifically thinking here of a case where you have a fairly data-intensive program and will be doing a data refresh or update at least once per screen and will have 50-100 simultaneous users.
In my experience the overhead is minimal, provided that the person writing the queries knows what he/she is doing, and take the usual precautions to ensure the generated queries are optimal, that the necessary indexes are in place etc etc. In other words, the database impact should be the same; there is a minimal but usually negligible overhead on the app side. That said... there is one exception to this; if a single query generates multiple aggregates the L2S provider translates it to a large query with one sub-query per aggregate. For a large table this can have a significant I/O impact as the db I/O cost for the query grows by magnitudes for each new aggregate in the query. The workaround for that is of course to move the aggregates to stored proc or view. Matt Warren has some sample code for an alternative query provider that translate that kind of queries in a more efficient way. Resources: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=334211 http://blogs.msdn.com/mattwar/archive/2008/07/08/linq-building-an-iqueryable-provider-part-x.aspx
How much database performance overhead when using LINQ? How much database performance overhead is involved with using C# and LINQ compared to custom optimized queries loaded with mostly low-level C, both with a SQL Server 2008 backend? I'm specifically thinking here of a case where you have a fairly data-intensive program and will be doing a data refresh or update at least once per screen and will have 50-100 simultaneous users.
TITLE: How much database performance overhead when using LINQ? QUESTION: How much database performance overhead is involved with using C# and LINQ compared to custom optimized queries loaded with mostly low-level C, both with a SQL Server 2008 backend? I'm specifically thinking here of a case where you have a fairly data-intensive program and will be doing a data refresh or update at least once per screen and will have 50-100 simultaneous users. ANSWER: In my experience the overhead is minimal, provided that the person writing the queries knows what he/she is doing, and take the usual precautions to ensure the generated queries are optimal, that the necessary indexes are in place etc etc. In other words, the database impact should be the same; there is a minimal but usually negligible overhead on the app side. That said... there is one exception to this; if a single query generates multiple aggregates the L2S provider translates it to a large query with one sub-query per aggregate. For a large table this can have a significant I/O impact as the db I/O cost for the query grows by magnitudes for each new aggregate in the query. The workaround for that is of course to move the aggregates to stored proc or view. Matt Warren has some sample code for an alternative query provider that translate that kind of queries in a more efficient way. Resources: https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=334211 http://blogs.msdn.com/mattwar/archive/2008/07/08/linq-building-an-iqueryable-provider-part-x.aspx
[ "sql-server", "linq", "performance", "linq-to-sql" ]
21
2
1,767
2
0
2008-08-07T14:38:59.723000
2008-09-16T07:14:18.153000
4,794
4,919
Flex / Air obfuscation
I've written (most of) an application in Flex and I am concerned with protecting the source code. I fired up a demo of Trillix swf decompiler and opened up the swf file that was installed to my Program Files directory. I saw that all of the actionscript packages I wrote were there. I'm not too concerned with the packages, even though there is a substantial amount of code, because it still seems pretty unusable without the mxml files. I think they are converted to actionscript, or atleast I hope. However, I would still like to explore obfuscation. Does anyone have any experience with Flash / Actionscript 3 / Flex obfuscators? Can you recommend a good product?
Here's what I would do. Compile your application to a SWF file. Then encrypt the SWF using AES. Make a "wrapper" application that loads the encrypted SWF into a ByteArray using URLLoader Use the as3crypto library to decrypt the swf at runtime. Once decrypted, use Loader.loadBytes to load the decrypted swf into the wrapper application. This will make it a lot harder to get your code. Not impossible, but harder. For AIR applications you could leave the SWF encrypted when delivering the application to the end-user. Then you could provide a registration key that contains the key used to decrypt the SWF. Also, here is a link to an AS3 obfuscator. I am not sure how well it works though. http://www.ambiera.com/irrfuscator/index.html
Flex / Air obfuscation I've written (most of) an application in Flex and I am concerned with protecting the source code. I fired up a demo of Trillix swf decompiler and opened up the swf file that was installed to my Program Files directory. I saw that all of the actionscript packages I wrote were there. I'm not too concerned with the packages, even though there is a substantial amount of code, because it still seems pretty unusable without the mxml files. I think they are converted to actionscript, or atleast I hope. However, I would still like to explore obfuscation. Does anyone have any experience with Flash / Actionscript 3 / Flex obfuscators? Can you recommend a good product?
TITLE: Flex / Air obfuscation QUESTION: I've written (most of) an application in Flex and I am concerned with protecting the source code. I fired up a demo of Trillix swf decompiler and opened up the swf file that was installed to my Program Files directory. I saw that all of the actionscript packages I wrote were there. I'm not too concerned with the packages, even though there is a substantial amount of code, because it still seems pretty unusable without the mxml files. I think they are converted to actionscript, or atleast I hope. However, I would still like to explore obfuscation. Does anyone have any experience with Flash / Actionscript 3 / Flex obfuscators? Can you recommend a good product? ANSWER: Here's what I would do. Compile your application to a SWF file. Then encrypt the SWF using AES. Make a "wrapper" application that loads the encrypted SWF into a ByteArray using URLLoader Use the as3crypto library to decrypt the swf at runtime. Once decrypted, use Loader.loadBytes to load the decrypted swf into the wrapper application. This will make it a lot harder to get your code. Not impossible, but harder. For AIR applications you could leave the SWF encrypted when delivering the application to the end-user. Then you could provide a registration key that contains the key used to decrypt the SWF. Also, here is a link to an AS3 obfuscator. I am not sure how well it works though. http://www.ambiera.com/irrfuscator/index.html
[ "apache-flex", "actionscript-3", "air", "obfuscation" ]
20
12
8,483
4
0
2008-08-07T14:41:42.883000
2008-08-07T16:28:34.337000
4,816
4,821
How do you resolve a domain name to an IP address with .NET/C#?
How do you resolve a domain name to an IP address with.NET/C#?
using System.Net; foreach (IPAddress address in Dns.GetHostAddresses("www.google.com")) { Console.WriteLine(address.ToString()); }
How do you resolve a domain name to an IP address with .NET/C#? How do you resolve a domain name to an IP address with.NET/C#?
TITLE: How do you resolve a domain name to an IP address with .NET/C#? QUESTION: How do you resolve a domain name to an IP address with.NET/C#? ANSWER: using System.Net; foreach (IPAddress address in Dns.GetHostAddresses("www.google.com")) { Console.WriteLine(address.ToString()); }
[ "c#", ".net", "dns", "reverse-dns" ]
30
20
6,512
2
0
2008-08-07T14:56:59.797000
2008-08-07T14:59:15.517000
4,824
4,838
String.indexOf function in C
Is there a C library function that will return the index of a character in a string? So far, all I've found are functions like strstr that will return the found char *, not it's location in the original string.
I think that size_t strcspn ( const char * str1, const char * str2 ); is what you want. Here is an example pulled from here: /* strcspn example */ #include #include int main () { char str[] = "fcba73"; char keys[] = "1234567890"; int i; i = strcspn (str,keys); printf ("The first number in str is at position %d.\n",i+1); return 0; }
String.indexOf function in C Is there a C library function that will return the index of a character in a string? So far, all I've found are functions like strstr that will return the found char *, not it's location in the original string.
TITLE: String.indexOf function in C QUESTION: Is there a C library function that will return the index of a character in a string? So far, all I've found are functions like strstr that will return the found char *, not it's location in the original string. ANSWER: I think that size_t strcspn ( const char * str1, const char * str2 ); is what you want. Here is an example pulled from here: /* strcspn example */ #include #include int main () { char str[] = "fcba73"; char keys[] = "1234567890"; int i; i = strcspn (str,keys); printf ("The first number in str is at position %d.\n",i+1); return 0; }
[ "c", "string" ]
47
16
107,506
7
0
2008-08-07T15:00:34.530000
2008-08-07T15:09:30.973000
4,839
4,877
How do I configure eclipse (zend studio 6) to hint and code complete several languages?
My dream IDE does full code hints, explains and completes PHP, Javascript, HTML and CSS. I know it exists! so far, Zend studio 6, under the Eclipse IDE does a great job at hinting PHP, some Javascript and HTML, any way I can expand this? edit: a bit more information: right now, using zend-6 under eclipse, i type in and I get a hint tooltip with all the available php functions that begin with "p" (phpinfo(), parse_ini_file(), parse_str(), etc...), each with its own explanation: phpinfo()->"outputs lots of PHP information", the same applies for regular HTML (no explanations however). However, I get nothing when I do:
I think the JavaScript and CSS need to be in separate files for this to work. Example of CSS autocomplete in Eclipse: Starting to type border Then setting thickness Then choosing the color Chose red, and it added the; for me Works pretty good IMHO.
How do I configure eclipse (zend studio 6) to hint and code complete several languages? My dream IDE does full code hints, explains and completes PHP, Javascript, HTML and CSS. I know it exists! so far, Zend studio 6, under the Eclipse IDE does a great job at hinting PHP, some Javascript and HTML, any way I can expand this? edit: a bit more information: right now, using zend-6 under eclipse, i type in and I get a hint tooltip with all the available php functions that begin with "p" (phpinfo(), parse_ini_file(), parse_str(), etc...), each with its own explanation: phpinfo()->"outputs lots of PHP information", the same applies for regular HTML (no explanations however). However, I get nothing when I do:
TITLE: How do I configure eclipse (zend studio 6) to hint and code complete several languages? QUESTION: My dream IDE does full code hints, explains and completes PHP, Javascript, HTML and CSS. I know it exists! so far, Zend studio 6, under the Eclipse IDE does a great job at hinting PHP, some Javascript and HTML, any way I can expand this? edit: a bit more information: right now, using zend-6 under eclipse, i type in and I get a hint tooltip with all the available php functions that begin with "p" (phpinfo(), parse_ini_file(), parse_str(), etc...), each with its own explanation: phpinfo()->"outputs lots of PHP information", the same applies for regular HTML (no explanations however). However, I get nothing when I do: ANSWER: I think the JavaScript and CSS need to be in separate files for this to work. Example of CSS autocomplete in Eclipse: Starting to type border Then setting thickness Then choosing the color Chose red, and it added the; for me Works pretty good IMHO.
[ "zend-studio", "code-completion" ]
8
2
3,529
2
0
2008-08-07T15:12:10.530000
2008-08-07T15:47:35.420000
4,850
5,026
C# and Arrow Keys
I am new to C# and am doing some work in an existing application. I have a DirectX viewport that has components in it that I want to be able to position using arrow keys. Currently I am overriding ProcessCmdKey and catching arrow input and send an OnKeyPress event. This works, but I want to be able to use modifiers( ALT + CTRL + SHIFT ). As soon as I am holding a modifier and press an arrow no events are triggered that I am listening to. Does anyone have any ideas or suggestions on where I should go with this?
Within your overridden ProcessCmdKey how are you determining which key has been pressed? The value of keyData (the second parameter) will change dependant on the key pressed and any modifier keys, so, for example, pressing the left arrow will return code 37, shift-left will return 65573, ctrl-left 131109 and alt-left 262181. You can extract the modifiers and the key pressed by ANDing with appropriate enum values: protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { bool shiftPressed = (keyData & Keys.Shift)!= 0; Keys unmodifiedKey = (keyData & Keys.KeyCode); // rest of code goes here }
C# and Arrow Keys I am new to C# and am doing some work in an existing application. I have a DirectX viewport that has components in it that I want to be able to position using arrow keys. Currently I am overriding ProcessCmdKey and catching arrow input and send an OnKeyPress event. This works, but I want to be able to use modifiers( ALT + CTRL + SHIFT ). As soon as I am holding a modifier and press an arrow no events are triggered that I am listening to. Does anyone have any ideas or suggestions on where I should go with this?
TITLE: C# and Arrow Keys QUESTION: I am new to C# and am doing some work in an existing application. I have a DirectX viewport that has components in it that I want to be able to position using arrow keys. Currently I am overriding ProcessCmdKey and catching arrow input and send an OnKeyPress event. This works, but I want to be able to use modifiers( ALT + CTRL + SHIFT ). As soon as I am holding a modifier and press an arrow no events are triggered that I am listening to. Does anyone have any ideas or suggestions on where I should go with this? ANSWER: Within your overridden ProcessCmdKey how are you determining which key has been pressed? The value of keyData (the second parameter) will change dependant on the key pressed and any modifier keys, so, for example, pressing the left arrow will return code 37, shift-left will return 65573, ctrl-left 131109 and alt-left 262181. You can extract the modifiers and the key pressed by ANDing with appropriate enum values: protected override bool ProcessCmdKey(ref Message msg, Keys keyData) { bool shiftPressed = (keyData & Keys.Shift)!= 0; Keys unmodifiedKey = (keyData & Keys.KeyCode); // rest of code goes here }
[ "c#", "user-interface", "directx" ]
26
13
9,629
2
0
2008-08-07T15:23:28.883000
2008-08-07T17:38:05.510000
4,860
17,014
Authoritative source on XML-sig
We have a question with regards to XML-sig and need detail about the optional elements as well as some of the canonicalization and transform stuff. We're writing a spec for a very small XML-syntax payload that will go into the metadata of media files and it needs to by cryptographically signed. Rather than re-invent the wheel, We thought we should use the XML-sig spec but I think most of it is overkill for what we need, and so we like to have more information/dialogue with people who know the details. Specifically, do we need to care about either transforms or canonicalization if the XML is very basic with no tabs for formatting and is specific to our needs?
If the option exists to not do an XML signature and instead just to treat the XML as a byte stream and to sign that, do it. It will be easier to implement, easier to understand, more stable (no canonicalization, transform, policy,...) and faster. If you absolutely must have XML DSIG (sadly, some of us must), it is certainly possible these days but there are many, many caveats. You need good library support, with Java this is out of the box in JDK 1.6, I am not familiar with other platforms. You must test interoperability with the receiving end of your signed XML, especially if they are potentially on a different platform. Be sure to read Why XML Security Is Broken, it basically covers all the ground regarding the horror that is XML Canonicalization and gives some pointers to some alternatives.
Authoritative source on XML-sig We have a question with regards to XML-sig and need detail about the optional elements as well as some of the canonicalization and transform stuff. We're writing a spec for a very small XML-syntax payload that will go into the metadata of media files and it needs to by cryptographically signed. Rather than re-invent the wheel, We thought we should use the XML-sig spec but I think most of it is overkill for what we need, and so we like to have more information/dialogue with people who know the details. Specifically, do we need to care about either transforms or canonicalization if the XML is very basic with no tabs for formatting and is specific to our needs?
TITLE: Authoritative source on XML-sig QUESTION: We have a question with regards to XML-sig and need detail about the optional elements as well as some of the canonicalization and transform stuff. We're writing a spec for a very small XML-syntax payload that will go into the metadata of media files and it needs to by cryptographically signed. Rather than re-invent the wheel, We thought we should use the XML-sig spec but I think most of it is overkill for what we need, and so we like to have more information/dialogue with people who know the details. Specifically, do we need to care about either transforms or canonicalization if the XML is very basic with no tabs for formatting and is specific to our needs? ANSWER: If the option exists to not do an XML signature and instead just to treat the XML as a byte stream and to sign that, do it. It will be easier to implement, easier to understand, more stable (no canonicalization, transform, policy,...) and faster. If you absolutely must have XML DSIG (sadly, some of us must), it is certainly possible these days but there are many, many caveats. You need good library support, with Java this is out of the box in JDK 1.6, I am not familiar with other platforms. You must test interoperability with the receiving end of your signed XML, especially if they are potentially on a different platform. Be sure to read Why XML Security Is Broken, it basically covers all the ground regarding the horror that is XML Canonicalization and gives some pointers to some alternatives.
[ "xml", "xml-signature" ]
12
0
577
3
0
2008-08-07T15:33:59.223000
2008-08-19T21:37:21.100000
4,884
13,918
How to keyboard down or up between dropdown "options"?
I have a custom built ajax [div] based dynamic dropdown. I have an [input] box which; onkeyup, runs an Ajax search which returns results in div s and are drawn back in using innerHTML. These div s all have highlights onmouseover so, a typical successful search yields the following structure (pardon the semi-code): [input] [div id=results] //this gets overwritten contantly by my AJAX function [div id=result1 onmouseover=highlight onclick=input.value=result1] [div id=result2 onmouseover=highlight onclick=input.value=result2] [div id=result2 onmouseover=highlight onclick=input.value=result2] [/div] It works. However, I'm missing the important functions behind regular HTML elements. I can't keyboard down or up between "options". I know javascript handles keyboard events but; I haven't been able to find a good guide. (Of course, the follow-up question will end up being: can I use to trigger that onclick event?)
What you need to do is attach event listeners to the div with id="results". You can do this by adding onkeyup, onkeydown, etc. attributes to the div when you create it or you can attach these using JavaScript. My recommendation would be that you use an AJAX library like YUI, jQuery, Prototype, etc. for two reasons: It sounds like you are trying to create an Auto Complete control which is something most AJAX libaries should provide. If you can use an existing component you'll save yourself a lot of time. Even if you don't want to use the control provided by a library, all libraries provide event libraries that help to hide the differences between the event APIs provided by different browsers. Forget addEvent, use Yahoo!’s Event Utility provides a good summary of what an event library should provide for you. I'm pretty sure that the event libraries provided by jQuery, Prototype, et. al. provide similar features. If that article goes over your head have a look at this documentation first and then re-read the original article (I found the article made much more sense after I'd used the event library). A couple of other things: Using JavaScript gives you much more control than writing onkeyup etc. attributes into your HTML. Unless you want to do something really simple I would use JavaScript. If you write your own code to handle keyboard events a good key code reference is really handy.
How to keyboard down or up between dropdown "options"? I have a custom built ajax [div] based dynamic dropdown. I have an [input] box which; onkeyup, runs an Ajax search which returns results in div s and are drawn back in using innerHTML. These div s all have highlights onmouseover so, a typical successful search yields the following structure (pardon the semi-code): [input] [div id=results] //this gets overwritten contantly by my AJAX function [div id=result1 onmouseover=highlight onclick=input.value=result1] [div id=result2 onmouseover=highlight onclick=input.value=result2] [div id=result2 onmouseover=highlight onclick=input.value=result2] [/div] It works. However, I'm missing the important functions behind regular HTML elements. I can't keyboard down or up between "options". I know javascript handles keyboard events but; I haven't been able to find a good guide. (Of course, the follow-up question will end up being: can I use to trigger that onclick event?)
TITLE: How to keyboard down or up between dropdown "options"? QUESTION: I have a custom built ajax [div] based dynamic dropdown. I have an [input] box which; onkeyup, runs an Ajax search which returns results in div s and are drawn back in using innerHTML. These div s all have highlights onmouseover so, a typical successful search yields the following structure (pardon the semi-code): [input] [div id=results] //this gets overwritten contantly by my AJAX function [div id=result1 onmouseover=highlight onclick=input.value=result1] [div id=result2 onmouseover=highlight onclick=input.value=result2] [div id=result2 onmouseover=highlight onclick=input.value=result2] [/div] It works. However, I'm missing the important functions behind regular HTML elements. I can't keyboard down or up between "options". I know javascript handles keyboard events but; I haven't been able to find a good guide. (Of course, the follow-up question will end up being: can I use to trigger that onclick event?) ANSWER: What you need to do is attach event listeners to the div with id="results". You can do this by adding onkeyup, onkeydown, etc. attributes to the div when you create it or you can attach these using JavaScript. My recommendation would be that you use an AJAX library like YUI, jQuery, Prototype, etc. for two reasons: It sounds like you are trying to create an Auto Complete control which is something most AJAX libaries should provide. If you can use an existing component you'll save yourself a lot of time. Even if you don't want to use the control provided by a library, all libraries provide event libraries that help to hide the differences between the event APIs provided by different browsers. Forget addEvent, use Yahoo!’s Event Utility provides a good summary of what an event library should provide for you. I'm pretty sure that the event libraries provided by jQuery, Prototype, et. al. provide similar features. If that article goes over your head have a look at this documentation first and then re-read the original article (I found the article made much more sense after I'd used the event library). A couple of other things: Using JavaScript gives you much more control than writing onkeyup etc. attributes into your HTML. Unless you want to do something really simple I would use JavaScript. If you write your own code to handle keyboard events a good key code reference is really handy.
[ "javascript", "events", "dom", "keyboard" ]
20
8
2,047
2
0
2008-08-07T15:58:10.313000
2008-08-17T20:48:41.760000
4,891
4,908
What point should someone decide to switch Database Systems
When developing whether its Web or Desktop at which point should a developer switch from SQLite, MySQL, MS SQL, etc
It depends on what you are doing. You might switch if: You need more scalability or better performance - say from SQLite to SQL Server or Oracle. You need access to more specific datatypes. You need to support a customer that only runs a particular database. You need better DBA tools. Your application is using a different platform where your database no longer runs, or it's libraries do not run. You have the ability/time/budget to actually make the change. Depending on the situation, the migration could be a bigger project than everything in the project up to that point. Migrations like these are great places to introduce inconsistencies, or to lose data, so a lot of care is required. There are many more reasons for switching and it all depends on your requirements and the attributes of the databases.
What point should someone decide to switch Database Systems When developing whether its Web or Desktop at which point should a developer switch from SQLite, MySQL, MS SQL, etc
TITLE: What point should someone decide to switch Database Systems QUESTION: When developing whether its Web or Desktop at which point should a developer switch from SQLite, MySQL, MS SQL, etc ANSWER: It depends on what you are doing. You might switch if: You need more scalability or better performance - say from SQLite to SQL Server or Oracle. You need access to more specific datatypes. You need to support a customer that only runs a particular database. You need better DBA tools. Your application is using a different platform where your database no longer runs, or it's libraries do not run. You have the ability/time/budget to actually make the change. Depending on the situation, the migration could be a bigger project than everything in the project up to that point. Migrations like these are great places to introduce inconsistencies, or to lose data, so a lot of care is required. There are many more reasons for switching and it all depends on your requirements and the attributes of the databases.
[ "sql", "database" ]
11
4
1,158
3
0
2008-08-07T16:06:33.947000
2008-08-07T16:19:10.753000
4,911
5,057
Should I use the username, or the user's ID to reference authenticated users in ASP.NET
So in my simple learning website, I use the built in ASP.NET authentication system. I am adding now a user table to save stuff like his zip, DOB etc. My question is: In the new table, should the key be the user name (the string) or the user ID which is that GUID looking number they use in the asp_ tables. If the best practice is to use that ugly guid, does anyone know how to get it? it seems to not be accessible as easily as the name ( System.Web.HttpContext.Current.User.Identity.Name ) If you suggest I use neither (not the guid nor the userName fields provided by ASP.NET authentication) then how do I do it with ASP.NET authentication? One option I like is to use the email address of the user as login, but how to I make ASP.NET authentication system use an email address instead of a user name? (or there is nothing to do there, it is just me deciding I "know" userName is actually an email address? Please note: I am not asking on how get a GUID in.NET, I am just referring to the userID column in the asp_ tables as guid. The user name is unique in ASP.NET authentication.
I would suggest using the username as the primary key in the table if the username is going to be unique, there are a few good reasons to do this: The primary key will be a clustered index and thus search for a users details via their username will be very quick. It will stop duplicate usernames from appearing You don't have to worry about using two different peices of information (username or guid) It will make writing code much easier because of not having to lookup two bits of information.
Should I use the username, or the user's ID to reference authenticated users in ASP.NET So in my simple learning website, I use the built in ASP.NET authentication system. I am adding now a user table to save stuff like his zip, DOB etc. My question is: In the new table, should the key be the user name (the string) or the user ID which is that GUID looking number they use in the asp_ tables. If the best practice is to use that ugly guid, does anyone know how to get it? it seems to not be accessible as easily as the name ( System.Web.HttpContext.Current.User.Identity.Name ) If you suggest I use neither (not the guid nor the userName fields provided by ASP.NET authentication) then how do I do it with ASP.NET authentication? One option I like is to use the email address of the user as login, but how to I make ASP.NET authentication system use an email address instead of a user name? (or there is nothing to do there, it is just me deciding I "know" userName is actually an email address? Please note: I am not asking on how get a GUID in.NET, I am just referring to the userID column in the asp_ tables as guid. The user name is unique in ASP.NET authentication.
TITLE: Should I use the username, or the user's ID to reference authenticated users in ASP.NET QUESTION: So in my simple learning website, I use the built in ASP.NET authentication system. I am adding now a user table to save stuff like his zip, DOB etc. My question is: In the new table, should the key be the user name (the string) or the user ID which is that GUID looking number they use in the asp_ tables. If the best practice is to use that ugly guid, does anyone know how to get it? it seems to not be accessible as easily as the name ( System.Web.HttpContext.Current.User.Identity.Name ) If you suggest I use neither (not the guid nor the userName fields provided by ASP.NET authentication) then how do I do it with ASP.NET authentication? One option I like is to use the email address of the user as login, but how to I make ASP.NET authentication system use an email address instead of a user name? (or there is nothing to do there, it is just me deciding I "know" userName is actually an email address? Please note: I am not asking on how get a GUID in.NET, I am just referring to the userID column in the asp_ tables as guid. The user name is unique in ASP.NET authentication. ANSWER: I would suggest using the username as the primary key in the table if the username is going to be unique, there are a few good reasons to do this: The primary key will be a clustered index and thus search for a users details via their username will be very quick. It will stop duplicate usernames from appearing You don't have to worry about using two different peices of information (username or guid) It will make writing code much easier because of not having to lookup two bits of information.
[ "asp.net", "authentication" ]
34
14
33,473
12
0
2008-08-07T16:19:40.487000
2008-08-07T17:56:36.657000
4,913
4,924
How to make a button appear as if it is pressed?
Using VS2008, C#,.Net 2 and Winforms how can I make a regular Button look "pressed"? Imagine this button is an on/off switch. ToolStripButton has the Checked property, but the regular Button does not.
One method you can used to obtain this option is by placing a "CheckBox" object and changing its "Appearance" from "Normal" to "Button" this will give you the same functionality that I believe you are looking for.
How to make a button appear as if it is pressed? Using VS2008, C#,.Net 2 and Winforms how can I make a regular Button look "pressed"? Imagine this button is an on/off switch. ToolStripButton has the Checked property, but the regular Button does not.
TITLE: How to make a button appear as if it is pressed? QUESTION: Using VS2008, C#,.Net 2 and Winforms how can I make a regular Button look "pressed"? Imagine this button is an on/off switch. ToolStripButton has the Checked property, but the regular Button does not. ANSWER: One method you can used to obtain this option is by placing a "CheckBox" object and changing its "Appearance" from "Normal" to "Button" this will give you the same functionality that I believe you are looking for.
[ "c#", ".net", "winforms", "user-interface", "button" ]
49
97
34,821
3
0
2008-08-07T16:21:59.280000
2008-08-07T16:30:46.953000
4,922
5,091
Is this really widening vs autoboxing?
I saw this in an answer to another question, in reference to shortcomings of the Java spec: There are more shortcomings and this is a subtle topic. Check this out: public class methodOverloading{ public static void hello(Integer x){ System.out.println("Integer"); } public static void hello(long x){ System.out.println("long"); } public static void main(String[] args){ int i = 5; hello(i); } } Here "long" would be printed (haven't checked it myself), because the compiler chooses widening over auto-boxing. Be careful when using auto-boxing or don't use it at all! Are we sure that this is actually an example of widening instead of autoboxing, or is it something else entirely? On my initial scanning, I would agree with the statement that the output would be "long" on the basis of i being declared as a primitive and not an object. However, if you changed hello(long x) to hello(Long x) the output would print "Integer" What's really going on here? I know nothing about the compilers/bytecode interpreters for java...
In the first case, you have a widening conversion happening. This can be see when runinng the "javap" utility program (included w/ the JDK), on the compiled class: public static void main(java.lang.String[]); Code: 0: iconst_ 5 1: istore_ 1 2: iload_ 1 3: i2l 4: invokestatic #6; //Method hello:(J)V 7: return } Clearly, you see the I2L, which is the mnemonic for the widening Integer-To-Long bytecode instruction. See reference here. And in the other case, replacing the "long x" with the object "Long x" signature, you'll have this code in the main method: public static void main(java.lang.String[]); Code: 0: iconst_ 5 1: istore_ 1 2: iload_ 1 3: invokestatic #6; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 6: invokestatic #7; //Method hello:(Ljava/lang/Integer;)V 9: return } So you see the compiler has created the instruction Integer.valueOf(int), to box the primitive inside the wrapper.
Is this really widening vs autoboxing? I saw this in an answer to another question, in reference to shortcomings of the Java spec: There are more shortcomings and this is a subtle topic. Check this out: public class methodOverloading{ public static void hello(Integer x){ System.out.println("Integer"); } public static void hello(long x){ System.out.println("long"); } public static void main(String[] args){ int i = 5; hello(i); } } Here "long" would be printed (haven't checked it myself), because the compiler chooses widening over auto-boxing. Be careful when using auto-boxing or don't use it at all! Are we sure that this is actually an example of widening instead of autoboxing, or is it something else entirely? On my initial scanning, I would agree with the statement that the output would be "long" on the basis of i being declared as a primitive and not an object. However, if you changed hello(long x) to hello(Long x) the output would print "Integer" What's really going on here? I know nothing about the compilers/bytecode interpreters for java...
TITLE: Is this really widening vs autoboxing? QUESTION: I saw this in an answer to another question, in reference to shortcomings of the Java spec: There are more shortcomings and this is a subtle topic. Check this out: public class methodOverloading{ public static void hello(Integer x){ System.out.println("Integer"); } public static void hello(long x){ System.out.println("long"); } public static void main(String[] args){ int i = 5; hello(i); } } Here "long" would be printed (haven't checked it myself), because the compiler chooses widening over auto-boxing. Be careful when using auto-boxing or don't use it at all! Are we sure that this is actually an example of widening instead of autoboxing, or is it something else entirely? On my initial scanning, I would agree with the statement that the output would be "long" on the basis of i being declared as a primitive and not an object. However, if you changed hello(long x) to hello(Long x) the output would print "Integer" What's really going on here? I know nothing about the compilers/bytecode interpreters for java... ANSWER: In the first case, you have a widening conversion happening. This can be see when runinng the "javap" utility program (included w/ the JDK), on the compiled class: public static void main(java.lang.String[]); Code: 0: iconst_ 5 1: istore_ 1 2: iload_ 1 3: i2l 4: invokestatic #6; //Method hello:(J)V 7: return } Clearly, you see the I2L, which is the mnemonic for the widening Integer-To-Long bytecode instruction. See reference here. And in the other case, replacing the "long x" with the object "Long x" signature, you'll have this code in the main method: public static void main(java.lang.String[]); Code: 0: iconst_ 5 1: istore_ 1 2: iload_ 1 3: invokestatic #6; //Method java/lang/Integer.valueOf:(I)Ljava/lang/Integer; 6: invokestatic #7; //Method hello:(Ljava/lang/Integer;)V 9: return } So you see the compiler has created the instruction Integer.valueOf(int), to box the primitive inside the wrapper.
[ "java", "primitive", "autoboxing" ]
31
16
4,609
3
0
2008-08-07T16:30:32.180000
2008-08-07T18:18:34.897000
4,923
5,156
Wrapping lists into columns
I'm using ColdFusion to populate a template that includes HTML unordered lists ( s). Most of these aren't that long, but a few have ridiculously long lengths and could really stand to be in 2-3 columns. Is there an HTML, ColdFusion or perhaps JavaScript (I'm accepting jQuery solutions) way to do this easily? It's not worth some over-complicated heavyweight solution to save some scrolling.
So I dug up this article from A List Apart CSS Swag: Multi-Column Lists. I ended up using the first solution, it's not the best but the others require either using complex HTML that can't be generated dynamically, or creating a lot of custom classes, which could be done but would require loads of in-line styling and possibly a huge page. Other solutions are still welcome though.
Wrapping lists into columns I'm using ColdFusion to populate a template that includes HTML unordered lists ( s). Most of these aren't that long, but a few have ridiculously long lengths and could really stand to be in 2-3 columns. Is there an HTML, ColdFusion or perhaps JavaScript (I'm accepting jQuery solutions) way to do this easily? It's not worth some over-complicated heavyweight solution to save some scrolling.
TITLE: Wrapping lists into columns QUESTION: I'm using ColdFusion to populate a template that includes HTML unordered lists ( s). Most of these aren't that long, but a few have ridiculously long lengths and could really stand to be in 2-3 columns. Is there an HTML, ColdFusion or perhaps JavaScript (I'm accepting jQuery solutions) way to do this easily? It's not worth some over-complicated heavyweight solution to save some scrolling. ANSWER: So I dug up this article from A List Apart CSS Swag: Multi-Column Lists. I ended up using the first solution, it's not the best but the others require either using complex HTML that can't be generated dynamically, or creating a lot of custom classes, which could be done but would require loads of in-line styling and possibly a huge page. Other solutions are still welcome though.
[ "javascript", "jquery", "html", "css", "cfml" ]
68
30
24,498
13
0
2008-08-07T16:30:45.613000
2008-08-07T18:59:58.167000
4,939
5,098
LINQ to SQL strings to enums
LINQ to SQL allows table mappings to automatically convert back and forth to Enums by specifying the type for the column - this works for strings or integers. Is there a way to make the conversion case insensitive or add a custom mapping class or extenstion method into the mix so that I can specify what the string should look like in more detail. Reasons for doing so might be in order to supply a nicer naming convention inside some new funky C# code in a system where the data schema is already set (and is being relied upon by some legacy apps) so the actual text in the database can't be changed.
You can always add a partial class with the same name as your LinqToSql class, and then define your own parameters and functions. These will then be accessible as object parameters and methods for this object, the same way as the auto-generated LinqToSql methods are accessible. Example: You have a LinqToSql class named Car which maps to the Car table in the DB. You can then add a file to App_Code with the following code in it: public partial class Car { // Add properties and methods to extend the functionality of Car } I am not sure if this totally meets your requirement of changing the way that Enums are mapped into a column. However, you could add a parameter where the get/set properties will work to map the enums that you need while keeping things case-insensitive.
LINQ to SQL strings to enums LINQ to SQL allows table mappings to automatically convert back and forth to Enums by specifying the type for the column - this works for strings or integers. Is there a way to make the conversion case insensitive or add a custom mapping class or extenstion method into the mix so that I can specify what the string should look like in more detail. Reasons for doing so might be in order to supply a nicer naming convention inside some new funky C# code in a system where the data schema is already set (and is being relied upon by some legacy apps) so the actual text in the database can't be changed.
TITLE: LINQ to SQL strings to enums QUESTION: LINQ to SQL allows table mappings to automatically convert back and forth to Enums by specifying the type for the column - this works for strings or integers. Is there a way to make the conversion case insensitive or add a custom mapping class or extenstion method into the mix so that I can specify what the string should look like in more detail. Reasons for doing so might be in order to supply a nicer naming convention inside some new funky C# code in a system where the data schema is already set (and is being relied upon by some legacy apps) so the actual text in the database can't be changed. ANSWER: You can always add a partial class with the same name as your LinqToSql class, and then define your own parameters and functions. These will then be accessible as object parameters and methods for this object, the same way as the auto-generated LinqToSql methods are accessible. Example: You have a LinqToSql class named Car which maps to the Car table in the DB. You can then add a file to App_Code with the following code in it: public partial class Car { // Add properties and methods to extend the functionality of Car } I am not sure if this totally meets your requirement of changing the way that Enums are mapped into a column. However, you could add a parameter where the get/set properties will work to map the enums that you need while keeping things case-insensitive.
[ "linq-to-sql" ]
18
3
2,592
1
0
2008-08-07T16:38:51.820000
2008-08-07T18:23:10.923000
4,942
4,978
How to sell Python to a client/boss/person
When asked to create system XYZ and you ask to do it in Python over PHP or Ruby, what are the main features you can mention when they require you to explain it?
This is one of those cases that really boil down to personal preference or situational details. If you're more comfortable and experienced with Python, then say so. Are they asking you to justify it because they're more comfortable with one of the other environments? After you're done, will the system be passed off to someone else for long-term maintenance? If they ask you to use a technology or language that you're not as familiar with, then make sure they know up-front that it's going to take you longer.
How to sell Python to a client/boss/person When asked to create system XYZ and you ask to do it in Python over PHP or Ruby, what are the main features you can mention when they require you to explain it?
TITLE: How to sell Python to a client/boss/person QUESTION: When asked to create system XYZ and you ask to do it in Python over PHP or Ruby, what are the main features you can mention when they require you to explain it? ANSWER: This is one of those cases that really boil down to personal preference or situational details. If you're more comfortable and experienced with Python, then say so. Are they asking you to justify it because they're more comfortable with one of the other environments? After you're done, will the system be passed off to someone else for long-term maintenance? If they ask you to use a technology or language that you're not as familiar with, then make sure they know up-front that it's going to take you longer.
[ "php", "python", "ruby-on-rails", "ruby" ]
14
13
1,477
8
0
2008-08-07T16:43:21.937000
2008-08-07T17:04:25.810000
4,949
4,965
Version control PHP Web Project
We have a PHP project that we would like to version control. Right now there are three of us working on a development version of the project which resides in an external folder to which all of our Eclipse IDEs are linked, and thus no version control. What is the right way and the best way to version control this? We have an SVN set up, but we just need to find a good way to check in and out that allows us to test on the development server. Any ideas?
We were in a similar situation, and here's what we ended up doing: Set up two branches -- the release and development branch. For the development branch, include a post-commit hook that deploys the repository to the dev server, so you can test. Once you're ready, you merge your changes into the release branch. I'd also suggest putting in a post-commit hook for deployment there. You can also set up individual development servers for each of the team members, on their workstations. I find that it speeds things up a bit, although you do have some more setup time. We had to use a single development server, because we were using a proprietary CMS and ran into licensing issues. So our post-commit hook was a simple FTP bot.
Version control PHP Web Project We have a PHP project that we would like to version control. Right now there are three of us working on a development version of the project which resides in an external folder to which all of our Eclipse IDEs are linked, and thus no version control. What is the right way and the best way to version control this? We have an SVN set up, but we just need to find a good way to check in and out that allows us to test on the development server. Any ideas?
TITLE: Version control PHP Web Project QUESTION: We have a PHP project that we would like to version control. Right now there are three of us working on a development version of the project which resides in an external folder to which all of our Eclipse IDEs are linked, and thus no version control. What is the right way and the best way to version control this? We have an SVN set up, but we just need to find a good way to check in and out that allows us to test on the development server. Any ideas? ANSWER: We were in a similar situation, and here's what we ended up doing: Set up two branches -- the release and development branch. For the development branch, include a post-commit hook that deploys the repository to the dev server, so you can test. Once you're ready, you merge your changes into the release branch. I'd also suggest putting in a post-commit hook for deployment there. You can also set up individual development servers for each of the team members, on their workstations. I find that it speeds things up a bit, although you do have some more setup time. We had to use a single development server, because we were using a proprietary CMS and ran into licensing issues. So our post-commit hook was a simple FTP bot.
[ "php", "svn", "version-control", "cvs" ]
36
27
8,653
8
0
2008-08-07T16:46:32.507000
2008-08-07T16:56:03.330000
4,954
4,972
What are good regular expressions?
I have worked for 5 years mainly in java desktop applications accessing Oracle databases and I have never used regular expressions. Now I enter Stack Overflow and I see a lot of questions about them; I feel like I missed something. For what do you use regular expressions? P.S. sorry for my bad english
Consider an example in Ruby: puts "Matched!" unless /\d{3}-\d{4}/.match("555-1234").nil? puts "Didn't match!" if /\d{3}-\d{4}/.match("Not phone number").nil? The "/\d{3}-\d{4}/" is the regular expression, and as you can see it is a VERY concise way of finding a match in a string. Furthermore, using groups you can extract information, as such: match = /([^@]*)@(.*)/.match("myaddress@domain.com") name = match[1] domain = match[2] Here, the parenthesis in the regular expression mark a capturing group, so you can see exactly WHAT the data is that you matched, so you can do further processing. This is just the tip of the iceberg... there are many many different things you can do in a regular expression that makes processing text REALLY easy.
What are good regular expressions? I have worked for 5 years mainly in java desktop applications accessing Oracle databases and I have never used regular expressions. Now I enter Stack Overflow and I see a lot of questions about them; I feel like I missed something. For what do you use regular expressions? P.S. sorry for my bad english
TITLE: What are good regular expressions? QUESTION: I have worked for 5 years mainly in java desktop applications accessing Oracle databases and I have never used regular expressions. Now I enter Stack Overflow and I see a lot of questions about them; I feel like I missed something. For what do you use regular expressions? P.S. sorry for my bad english ANSWER: Consider an example in Ruby: puts "Matched!" unless /\d{3}-\d{4}/.match("555-1234").nil? puts "Didn't match!" if /\d{3}-\d{4}/.match("Not phone number").nil? The "/\d{3}-\d{4}/" is the regular expression, and as you can see it is a VERY concise way of finding a match in a string. Furthermore, using groups you can extract information, as such: match = /([^@]*)@(.*)/.match("myaddress@domain.com") name = match[1] domain = match[2] Here, the parenthesis in the regular expression mark a capturing group, so you can see exactly WHAT the data is that you matched, so you can do further processing. This is just the tip of the iceberg... there are many many different things you can do in a regular expression that makes processing text REALLY easy.
[ "regex" ]
11
7
3,337
9
0
2008-08-07T16:48:42.270000
2008-08-07T17:02:10.353000
4,973
5,103
Setting a div's height in HTML with CSS
I am trying to lay out a table-like page with two columns. I want the rightmost column to dock to the right of the page, and this column should have a distinct background color. The content in the right side is almost always going to be smaller than that on the left. I would like the div on the right to always be tall enough to reach the separator for the row below it. How can I make my background color fill that space?.rightfloat { color: red; background-color: #BBBBBB; float: right; width: 200px; }.left { font-size: 20pt; }.separator { clear: both; width: 100%; border-top: 1px solid black; } Some really short content. Some really really really really really really really really really really big content Some more short content. Some really really really really really really really really really really big content Edit: I agree that this example is very table-like and an actual table would be a fine choice. But my "real" page will eventually be less table-like, and I'd just like to first master this task! Also, for some reason, when I create/edit my posts in IE7, the code shows up correctly in the preview view, but when I actually post the message, the formatting gets removed. Editing my post in Firefox 2 seems to have worked, FWIW. Another edit: Yeah, I unaccepted GateKiller's answer. It does indeed work nicely on my simple page, but not in my actual heavier page. I'll investigate some of the links y'all have pointed me to.
Ahem... The short answer to your question is that you must set the height of 100% to the body and html tag, then set the height to 100% on each div element you want to make 100% the height of the page. Actually, 100% height will not work in most design situations - this may be short but it is not a good answer. Google "any column longest" layouts. The best way is to put the left and right cols inside a wrapper div, float the left and right cols and then float the wrapper - this makes it stretch to the height of the inner containers - then set background image on the outer wrapper. But watch for any horizontal margins on the floated elements in case you get the IE "double margin float bug".
Setting a div's height in HTML with CSS I am trying to lay out a table-like page with two columns. I want the rightmost column to dock to the right of the page, and this column should have a distinct background color. The content in the right side is almost always going to be smaller than that on the left. I would like the div on the right to always be tall enough to reach the separator for the row below it. How can I make my background color fill that space?.rightfloat { color: red; background-color: #BBBBBB; float: right; width: 200px; }.left { font-size: 20pt; }.separator { clear: both; width: 100%; border-top: 1px solid black; } Some really short content. Some really really really really really really really really really really big content Some more short content. Some really really really really really really really really really really big content Edit: I agree that this example is very table-like and an actual table would be a fine choice. But my "real" page will eventually be less table-like, and I'd just like to first master this task! Also, for some reason, when I create/edit my posts in IE7, the code shows up correctly in the preview view, but when I actually post the message, the formatting gets removed. Editing my post in Firefox 2 seems to have worked, FWIW. Another edit: Yeah, I unaccepted GateKiller's answer. It does indeed work nicely on my simple page, but not in my actual heavier page. I'll investigate some of the links y'all have pointed me to.
TITLE: Setting a div's height in HTML with CSS QUESTION: I am trying to lay out a table-like page with two columns. I want the rightmost column to dock to the right of the page, and this column should have a distinct background color. The content in the right side is almost always going to be smaller than that on the left. I would like the div on the right to always be tall enough to reach the separator for the row below it. How can I make my background color fill that space?.rightfloat { color: red; background-color: #BBBBBB; float: right; width: 200px; }.left { font-size: 20pt; }.separator { clear: both; width: 100%; border-top: 1px solid black; } Some really short content. Some really really really really really really really really really really big content Some more short content. Some really really really really really really really really really really big content Edit: I agree that this example is very table-like and an actual table would be a fine choice. But my "real" page will eventually be less table-like, and I'd just like to first master this task! Also, for some reason, when I create/edit my posts in IE7, the code shows up correctly in the preview view, but when I actually post the message, the formatting gets removed. Editing my post in Firefox 2 seems to have worked, FWIW. Another edit: Yeah, I unaccepted GateKiller's answer. It does indeed work nicely on my simple page, but not in my actual heavier page. I'll investigate some of the links y'all have pointed me to. ANSWER: Ahem... The short answer to your question is that you must set the height of 100% to the body and html tag, then set the height to 100% on each div element you want to make 100% the height of the page. Actually, 100% height will not work in most design situations - this may be short but it is not a good answer. Google "any column longest" layouts. The best way is to put the left and right cols inside a wrapper div, float the left and right cols and then float the wrapper - this makes it stretch to the height of the inner containers - then set background image on the outer wrapper. But watch for any horizontal margins on the floated elements in case you get the IE "double margin float bug".
[ "html", "css" ]
40
22
180,205
14
0
2008-08-07T17:02:23.413000
2008-08-07T18:24:16.803000
5,017
5,266
Open local file with AIR / Flex
I have written an AIR Application that downloads videos and documents from a server. The videos play inside of the application, but I would like the user to be able to open the documents in their native applications. I am looking for a way to prompt the user to Open / Save As on a local file stored in the Application Storage Directory. I have tried using the FileReference + URLRequest classes but this throws an exception that it needs a remote url. My last resort is just copying the file to their desktop: \
Only way I could figure out how to do it without just moving the file and telling the user was to pass it off to the browser. navigateToURL(new URLRequest(File.applicationStorageDirectory.nativePath + "/courses/" + fileName));
Open local file with AIR / Flex I have written an AIR Application that downloads videos and documents from a server. The videos play inside of the application, but I would like the user to be able to open the documents in their native applications. I am looking for a way to prompt the user to Open / Save As on a local file stored in the Application Storage Directory. I have tried using the FileReference + URLRequest classes but this throws an exception that it needs a remote url. My last resort is just copying the file to their desktop: \
TITLE: Open local file with AIR / Flex QUESTION: I have written an AIR Application that downloads videos and documents from a server. The videos play inside of the application, but I would like the user to be able to open the documents in their native applications. I am looking for a way to prompt the user to Open / Save As on a local file stored in the Application Storage Directory. I have tried using the FileReference + URLRequest classes but this throws an exception that it needs a remote url. My last resort is just copying the file to their desktop: \ ANSWER: Only way I could figure out how to do it without just moving the file and telling the user was to pass it off to the browser. navigateToURL(new URLRequest(File.applicationStorageDirectory.nativePath + "/courses/" + fileName));
[ "apache-flex", "actionscript-3", "air" ]
12
3
19,663
5
0
2008-08-07T17:31:12.167000
2008-08-07T20:25:47.293000
5,024
5,041
Is The Perl Journal available online?
Does anyone know where online copies of the old The Perl Journal articles can be found? I know they are now owned by Dr. Dobb's, just the main page for it says they are part of whatever section the subject matter is relevant too, rather than being indexed together. That said, I have never been able to find any of them online on that site. I know Mark Jason Dominus has a few of his articles on his site, any one know of any other good places? Or even what search terms to use at Dr. Dobb's?
Volumes 1-5 (1996 -> 2000) can be found at http://www.foo.be/docs/tpj/ Hmm, looks like that was the entire run? I though it was longer than that for some reason.
Is The Perl Journal available online? Does anyone know where online copies of the old The Perl Journal articles can be found? I know they are now owned by Dr. Dobb's, just the main page for it says they are part of whatever section the subject matter is relevant too, rather than being indexed together. That said, I have never been able to find any of them online on that site. I know Mark Jason Dominus has a few of his articles on his site, any one know of any other good places? Or even what search terms to use at Dr. Dobb's?
TITLE: Is The Perl Journal available online? QUESTION: Does anyone know where online copies of the old The Perl Journal articles can be found? I know they are now owned by Dr. Dobb's, just the main page for it says they are part of whatever section the subject matter is relevant too, rather than being indexed together. That said, I have never been able to find any of them online on that site. I know Mark Jason Dominus has a few of his articles on his site, any one know of any other good places? Or even what search terms to use at Dr. Dobb's? ANSWER: Volumes 1-5 (1996 -> 2000) can be found at http://www.foo.be/docs/tpj/ Hmm, looks like that was the entire run? I though it was longer than that for some reason.
[ "perl" ]
23
17
6,660
3
0
2008-08-07T17:34:27.857000
2008-08-07T17:52:19.177000
5,025
5,031
Locking a SQL Server Database with PHP
I'm wanting extra security for a particular point in my web app. So I want to lock the database (SQL Server 2005). Any suggestions or is this even necessary with SQL Server? Edit on question: The query is failing silently with no errors messages logged, and does not occur inside of a transaction. Final Solution: I never was able to solve the problem, however what I wound up doing was switching to MySQL and using a transactional level query here. This was not the main or even a primary reason to switch. I had been having problems with SQL Server and it allowed me to have our CMS and various other tools all running on the same database. Previous we had a SQL Server and a MySQL database running to run our site. The port was a bit on the time consuming however in the long run I feel it will work much better for the site and the business.
I suppose you have three options. Set user permissions so that user x can only read from the database. Set the database into single user mode so only one connection can access it sp_dboption 'myDataBaseName', single, true Set the database to readonly sp_dboption 'myDataBaseName', read only, true
Locking a SQL Server Database with PHP I'm wanting extra security for a particular point in my web app. So I want to lock the database (SQL Server 2005). Any suggestions or is this even necessary with SQL Server? Edit on question: The query is failing silently with no errors messages logged, and does not occur inside of a transaction. Final Solution: I never was able to solve the problem, however what I wound up doing was switching to MySQL and using a transactional level query here. This was not the main or even a primary reason to switch. I had been having problems with SQL Server and it allowed me to have our CMS and various other tools all running on the same database. Previous we had a SQL Server and a MySQL database running to run our site. The port was a bit on the time consuming however in the long run I feel it will work much better for the site and the business.
TITLE: Locking a SQL Server Database with PHP QUESTION: I'm wanting extra security for a particular point in my web app. So I want to lock the database (SQL Server 2005). Any suggestions or is this even necessary with SQL Server? Edit on question: The query is failing silently with no errors messages logged, and does not occur inside of a transaction. Final Solution: I never was able to solve the problem, however what I wound up doing was switching to MySQL and using a transactional level query here. This was not the main or even a primary reason to switch. I had been having problems with SQL Server and it allowed me to have our CMS and various other tools all running on the same database. Previous we had a SQL Server and a MySQL database running to run our site. The port was a bit on the time consuming however in the long run I feel it will work much better for the site and the business. ANSWER: I suppose you have three options. Set user permissions so that user x can only read from the database. Set the database into single user mode so only one connection can access it sp_dboption 'myDataBaseName', single, true Set the database to readonly sp_dboption 'myDataBaseName', read only, true
[ "php", "sql-server", "database", "sql-server-2005" ]
16
7
1,247
2
0
2008-08-07T17:36:23.873000
2008-08-07T17:43:01.787000
5,027
5,029
Reduce ASP.NET menu control size (without 3rd party libraries)
I have a fairly simple ASP.NET 2.0 menu control using a sitemap file and security trimmings. There are only 21 menu options, but the results HTML of the menu is a whopping 14k. The site is hosted on our company's intranet and must be serverd to people worldwide on limited bandwidth, so I'd like to reduce the size of the menus. What is the best way to do this? Does anybody have a good reference? I have the following constraints: The solution must not reference any 3rd part DLL files (getting approval would be a nightmare) Has to work with IE 6 CSS and JavaScript are fine, as long as they work with IE 6.
Take a look at: http://www.asp.net/CSSAdapters/Menu.aspx The default Menu control is rendering far too much HTML.
Reduce ASP.NET menu control size (without 3rd party libraries) I have a fairly simple ASP.NET 2.0 menu control using a sitemap file and security trimmings. There are only 21 menu options, but the results HTML of the menu is a whopping 14k. The site is hosted on our company's intranet and must be serverd to people worldwide on limited bandwidth, so I'd like to reduce the size of the menus. What is the best way to do this? Does anybody have a good reference? I have the following constraints: The solution must not reference any 3rd part DLL files (getting approval would be a nightmare) Has to work with IE 6 CSS and JavaScript are fine, as long as they work with IE 6.
TITLE: Reduce ASP.NET menu control size (without 3rd party libraries) QUESTION: I have a fairly simple ASP.NET 2.0 menu control using a sitemap file and security trimmings. There are only 21 menu options, but the results HTML of the menu is a whopping 14k. The site is hosted on our company's intranet and must be serverd to people worldwide on limited bandwidth, so I'd like to reduce the size of the menus. What is the best way to do this? Does anybody have a good reference? I have the following constraints: The solution must not reference any 3rd part DLL files (getting approval would be a nightmare) Has to work with IE 6 CSS and JavaScript are fine, as long as they work with IE 6. ANSWER: Take a look at: http://www.asp.net/CSSAdapters/Menu.aspx The default Menu control is rendering far too much HTML.
[ "asp.net", "size", "menu" ]
10
3
1,764
2
0
2008-08-07T17:38:09.143000
2008-08-07T17:42:00.150000
5,071
5,262
How to add CVS directories recursively
I've played with CVS a little bit and am not the most familiar with all of its capabilities, but a huge annoyance for me is trying to add new directories that contain more directories in them. Running " cvs add " only adds the contents of the current directory, and using " cvs import " didn't look like the right thing either since it's still all code I'm producing (this howto claimed import is for 3rd party sources ) Do you guys know any way to recursively add everything in a given directory to the current CVS project (or if SVN or git makes this notably easier)?
Ah, spaces. This will work with spaces: find. -type f -print0| xargs -0 cvs add
How to add CVS directories recursively I've played with CVS a little bit and am not the most familiar with all of its capabilities, but a huge annoyance for me is trying to add new directories that contain more directories in them. Running " cvs add " only adds the contents of the current directory, and using " cvs import " didn't look like the right thing either since it's still all code I'm producing (this howto claimed import is for 3rd party sources ) Do you guys know any way to recursively add everything in a given directory to the current CVS project (or if SVN or git makes this notably easier)?
TITLE: How to add CVS directories recursively QUESTION: I've played with CVS a little bit and am not the most familiar with all of its capabilities, but a huge annoyance for me is trying to add new directories that contain more directories in them. Running " cvs add " only adds the contents of the current directory, and using " cvs import " didn't look like the right thing either since it's still all code I'm producing (this howto claimed import is for 3rd party sources ) Do you guys know any way to recursively add everything in a given directory to the current CVS project (or if SVN or git makes this notably easier)? ANSWER: Ah, spaces. This will work with spaces: find. -type f -print0| xargs -0 cvs add
[ "cvs" ]
40
11
71,701
14
0
2008-08-07T18:05:28.183000
2008-08-07T20:22:32.807000
5,075
5,079
Bigger than a char but smaller than a blob
Char's are great because they are fixed size and thus make for a faster table. They are however limited to 255 characters. I want to hold 500 characters but a blob is variable length and that's not what I want. Is there some way to have a fixed length field of 500 characters in MySQL or am I going to have to use 2 char fields?
I would suggest using a varchar(500). Even though varchar isn't a fixed length, the database should reserve the correct amount of space. You shouldn't notice any performance difference using varchar(500) over 2xchar(255). You're also probably going to cause extra overhead by joining two char fields together.
Bigger than a char but smaller than a blob Char's are great because they are fixed size and thus make for a faster table. They are however limited to 255 characters. I want to hold 500 characters but a blob is variable length and that's not what I want. Is there some way to have a fixed length field of 500 characters in MySQL or am I going to have to use 2 char fields?
TITLE: Bigger than a char but smaller than a blob QUESTION: Char's are great because they are fixed size and thus make for a faster table. They are however limited to 255 characters. I want to hold 500 characters but a blob is variable length and that's not what I want. Is there some way to have a fixed length field of 500 characters in MySQL or am I going to have to use 2 char fields? ANSWER: I would suggest using a varchar(500). Even though varchar isn't a fixed length, the database should reserve the correct amount of space. You shouldn't notice any performance difference using varchar(500) over 2xchar(255). You're also probably going to cause extra overhead by joining two char fields together.
[ "mysql", "database" ]
6
7
729
3
0
2008-08-07T18:07:48.460000
2008-08-07T18:12:03.350000
5,078
5,108
Securing a linux webserver for public access
I'd like to set up a cheap Linux box as a web server to host a variety of web technologies (PHP & Java EE come to mind, but I'd like to experiment with Ruby or Python in the future as well). I'm fairly versed in setting up Tomcat to run on Linux for serving up Java EE applications, but I'd like to be able to open this server up, even just so I can create some tools I can use while I am working in the office. All the experience I've had with configuring Java EE sites has all been for intranet applications where we were told not to focus on securing the pages for external users. What is your advice on setting up a personal Linux web server in a secure enough way to open it up for external traffic?
This article has some of the best ways to lock things down: http://www.petefreitag.com/item/505.cfm Some highlights: Make sure no one can browse the directories Make sure only root has write privileges to everything, and only root has read privileges to certain config files Run mod_security The article also takes some pointers from this book: Apache Securiy (O'Reilly Press) As far as distros, I've run Debain and Ubuntu, but it just depends on how much you want to do. I ran Debian with no X and just ssh'd into it whenever i needed anything. That is a simple way to keep overhead down. Or Ubuntu has some nice GUI things that make it easy to control Apache/MySQL/PHP.
Securing a linux webserver for public access I'd like to set up a cheap Linux box as a web server to host a variety of web technologies (PHP & Java EE come to mind, but I'd like to experiment with Ruby or Python in the future as well). I'm fairly versed in setting up Tomcat to run on Linux for serving up Java EE applications, but I'd like to be able to open this server up, even just so I can create some tools I can use while I am working in the office. All the experience I've had with configuring Java EE sites has all been for intranet applications where we were told not to focus on securing the pages for external users. What is your advice on setting up a personal Linux web server in a secure enough way to open it up for external traffic?
TITLE: Securing a linux webserver for public access QUESTION: I'd like to set up a cheap Linux box as a web server to host a variety of web technologies (PHP & Java EE come to mind, but I'd like to experiment with Ruby or Python in the future as well). I'm fairly versed in setting up Tomcat to run on Linux for serving up Java EE applications, but I'd like to be able to open this server up, even just so I can create some tools I can use while I am working in the office. All the experience I've had with configuring Java EE sites has all been for intranet applications where we were told not to focus on securing the pages for external users. What is your advice on setting up a personal Linux web server in a secure enough way to open it up for external traffic? ANSWER: This article has some of the best ways to lock things down: http://www.petefreitag.com/item/505.cfm Some highlights: Make sure no one can browse the directories Make sure only root has write privileges to everything, and only root has read privileges to certain config files Run mod_security The article also takes some pointers from this book: Apache Securiy (O'Reilly Press) As far as distros, I've run Debain and Ubuntu, but it just depends on how much you want to do. I ran Debian with no X and just ssh'd into it whenever i needed anything. That is a simple way to keep overhead down. Or Ubuntu has some nice GUI things that make it easy to control Apache/MySQL/PHP.
[ "linux", "security", "webserver" ]
21
5
4,133
12
0
2008-08-07T18:10:17.033000
2008-08-07T18:26:07.207000
5,084
5,089
Upload form does not work in Firefox 3 with Mac OS X?
Today, I ran into this weird problem with a user using Mac OS X. This user always had a failed upload. The form uses a regular "input type=file". The user could upload using any browser except Firefox 3 on his Mac. Only this particular user was seeing this error. Obviously, the problem is only with this one particular user.
User corrected this weird problem by recreating their FireFox profile. How to manage FireFox profiles I imagine a re-install of FireFox would have corrected the problem as well.
Upload form does not work in Firefox 3 with Mac OS X? Today, I ran into this weird problem with a user using Mac OS X. This user always had a failed upload. The form uses a regular "input type=file". The user could upload using any browser except Firefox 3 on his Mac. Only this particular user was seeing this error. Obviously, the problem is only with this one particular user.
TITLE: Upload form does not work in Firefox 3 with Mac OS X? QUESTION: Today, I ran into this weird problem with a user using Mac OS X. This user always had a failed upload. The form uses a regular "input type=file". The user could upload using any browser except Firefox 3 on his Mac. Only this particular user was seeing this error. Obviously, the problem is only with this one particular user. ANSWER: User corrected this weird problem by recreating their FireFox profile. How to manage FireFox profiles I imagine a re-install of FireFox would have corrected the problem as well.
[ "macos", "firefox", "upload" ]
5
2
1,389
2
0
2008-08-07T18:16:00.033000
2008-08-07T18:17:56.833000
5,087
1,158,483
Learning Ruby on Rails any good for Grails?
My company is in the process of starting down the Grails path. The reason for that is that the current developers are heavy on Java but felt the need for a MVC-style language for some future web development projects. Personally, I'm coming from the design/usability world, but as I take more "front-end" responsibilities I'm starting to feel the need for learning a language more intensively so I can code some logic but especially the front-end code for my UIs and stuff. I've been trying to get into Python/Django personally, but just never invested too much time on it. Now that my company is "jumping" into Grails I bought the " Agile Web Development with Rails (3rd Ed - Beta) " and I'm starting to get into RoR. I'd still like to learn Python in the future or on the side, but my biggest question is: Should I be learning RoR, and have a more versatile language in my "portfolio", knowing that my RoR knowledge will be useful for my Grails needs as well?? -OR- Should I just skip RoR and focus on learning Grails that I'll be needing for work soon, and work on learning RoR/Django (Ruby/Python) later? Basically the question revolves around the usefulness of Grails in a non-corporate setting and the similarities between Rails and Grails. (and this, while trying to avoid the centennial discussion of Python vs Ruby (on Rails):))
Mmh, I don't know how to say this. Some people might bash me over this. Language (Groovy and Ruby) As a language I reckon Ruby is more funky compared to Groovy. Groovy only exists to ease Java programmer as you don't need to learn too much new syntax. But overall I reckon is not as funky as Ruby. Groovy wouldn't be the JVM language that is worth to learn based on attender's vote in this year's JavaOne but instead Scala is the one to go. Besides that, the original creator of Groovy himself does not have faith in the language he created himself in the first place. Community and Job openings As for the community, Grails community is not as big as Rails, though since the acquirement by Spring more and more people are using it in serious application. Rails has more job openings in the market compared to Grails (that is if you want to invest in looking a new job). The framework (Grails and Rails) But, as a framework, if you really care about maintainability and need access to Java framework and legacy Java system, Grails is the way to go as it provides cleaner access to Java. Grails itself is built upon several popular Java framework (Spring & Hibernate). Rails itself IMHO is funky like Ruby itself, but it's funkyness costs you maintainability. Matz himself prefers Merb over Rails 2 because Rails create a DSL on top of Ruby which is really against the Ruby philosophy. And I reckon because Rails itself is opiniated, which in turn if you don't have the same opinion as the creator, it might not fit your needs. Conclusion So in your case, learn Grails as that is the company's consensus (you need to respect the consensus) and if you still want to secure your job. But, invest some time learning Rails and Ruby too if you want to open a chance getting a new job in the future.
Learning Ruby on Rails any good for Grails? My company is in the process of starting down the Grails path. The reason for that is that the current developers are heavy on Java but felt the need for a MVC-style language for some future web development projects. Personally, I'm coming from the design/usability world, but as I take more "front-end" responsibilities I'm starting to feel the need for learning a language more intensively so I can code some logic but especially the front-end code for my UIs and stuff. I've been trying to get into Python/Django personally, but just never invested too much time on it. Now that my company is "jumping" into Grails I bought the " Agile Web Development with Rails (3rd Ed - Beta) " and I'm starting to get into RoR. I'd still like to learn Python in the future or on the side, but my biggest question is: Should I be learning RoR, and have a more versatile language in my "portfolio", knowing that my RoR knowledge will be useful for my Grails needs as well?? -OR- Should I just skip RoR and focus on learning Grails that I'll be needing for work soon, and work on learning RoR/Django (Ruby/Python) later? Basically the question revolves around the usefulness of Grails in a non-corporate setting and the similarities between Rails and Grails. (and this, while trying to avoid the centennial discussion of Python vs Ruby (on Rails):))
TITLE: Learning Ruby on Rails any good for Grails? QUESTION: My company is in the process of starting down the Grails path. The reason for that is that the current developers are heavy on Java but felt the need for a MVC-style language for some future web development projects. Personally, I'm coming from the design/usability world, but as I take more "front-end" responsibilities I'm starting to feel the need for learning a language more intensively so I can code some logic but especially the front-end code for my UIs and stuff. I've been trying to get into Python/Django personally, but just never invested too much time on it. Now that my company is "jumping" into Grails I bought the " Agile Web Development with Rails (3rd Ed - Beta) " and I'm starting to get into RoR. I'd still like to learn Python in the future or on the side, but my biggest question is: Should I be learning RoR, and have a more versatile language in my "portfolio", knowing that my RoR knowledge will be useful for my Grails needs as well?? -OR- Should I just skip RoR and focus on learning Grails that I'll be needing for work soon, and work on learning RoR/Django (Ruby/Python) later? Basically the question revolves around the usefulness of Grails in a non-corporate setting and the similarities between Rails and Grails. (and this, while trying to avoid the centennial discussion of Python vs Ruby (on Rails):)) ANSWER: Mmh, I don't know how to say this. Some people might bash me over this. Language (Groovy and Ruby) As a language I reckon Ruby is more funky compared to Groovy. Groovy only exists to ease Java programmer as you don't need to learn too much new syntax. But overall I reckon is not as funky as Ruby. Groovy wouldn't be the JVM language that is worth to learn based on attender's vote in this year's JavaOne but instead Scala is the one to go. Besides that, the original creator of Groovy himself does not have faith in the language he created himself in the first place. Community and Job openings As for the community, Grails community is not as big as Rails, though since the acquirement by Spring more and more people are using it in serious application. Rails has more job openings in the market compared to Grails (that is if you want to invest in looking a new job). The framework (Grails and Rails) But, as a framework, if you really care about maintainability and need access to Java framework and legacy Java system, Grails is the way to go as it provides cleaner access to Java. Grails itself is built upon several popular Java framework (Spring & Hibernate). Rails itself IMHO is funky like Ruby itself, but it's funkyness costs you maintainability. Matz himself prefers Merb over Rails 2 because Rails create a DSL on top of Ruby which is really against the Ruby philosophy. And I reckon because Rails itself is opiniated, which in turn if you don't have the same opinion as the creator, it might not fit your needs. Conclusion So in your case, learn Grails as that is the company's consensus (you need to respect the consensus) and if you still want to secure your job. But, invest some time learning Rails and Ruby too if you want to open a chance getting a new job in the future.
[ "ruby-on-rails", "ruby", "grails", "groovy" ]
21
16
9,205
15
0
2008-08-07T18:17:22.323000
2009-07-21T10:52:45.673000
5,118
5,160
How to set up a CSS switcher
I'm working on a website that will switch to a new style on a set date. The site's built-in semantic HTML and CSS, so the change should just require a CSS reference change. I'm working with a designer who will need to be able to see how it's looking, as well as a client who will need to be able to review content updates in the current look as well as design progress on the new look. I'm planning to use a magic querystring value and/or a javascript link in the footer which writes out a cookie to select the new CSS page. We're working in ASP.NET 3.5. Any recommendations? I should mention that we're using IE Conditional Comments for IE8, 7, and 6 support. I may create a function that does a replacement:
In Asp.net 3.5, you should be able to set up the Link tag in the header as a server tag. Then in the codebehind you can set the href property for the link element, based on a cookie value, querystring, date, etc. In your aspx file: And in the Code behind: protected void Page_Load(object sender, EventArgs e) { string stylesheetAddress = // logic to determine stylesheet linkStyles.Href = stylesheetAddress; }
How to set up a CSS switcher I'm working on a website that will switch to a new style on a set date. The site's built-in semantic HTML and CSS, so the change should just require a CSS reference change. I'm working with a designer who will need to be able to see how it's looking, as well as a client who will need to be able to review content updates in the current look as well as design progress on the new look. I'm planning to use a magic querystring value and/or a javascript link in the footer which writes out a cookie to select the new CSS page. We're working in ASP.NET 3.5. Any recommendations? I should mention that we're using IE Conditional Comments for IE8, 7, and 6 support. I may create a function that does a replacement:
TITLE: How to set up a CSS switcher QUESTION: I'm working on a website that will switch to a new style on a set date. The site's built-in semantic HTML and CSS, so the change should just require a CSS reference change. I'm working with a designer who will need to be able to see how it's looking, as well as a client who will need to be able to review content updates in the current look as well as design progress on the new look. I'm planning to use a magic querystring value and/or a javascript link in the footer which writes out a cookie to select the new CSS page. We're working in ASP.NET 3.5. Any recommendations? I should mention that we're using IE Conditional Comments for IE8, 7, and 6 support. I may create a function that does a replacement: ANSWER: In Asp.net 3.5, you should be able to set up the Link tag in the header as a server tag. Then in the codebehind you can set the href property for the link element, based on a cookie value, querystring, date, etc. In your aspx file: And in the Code behind: protected void Page_Load(object sender, EventArgs e) { string stylesheetAddress = // logic to determine stylesheet linkStyles.Href = stylesheetAddress; }
[ "javascript", "html", "asp.net", "css" ]
37
22
3,916
4
0
2008-08-07T18:31:22.780000
2008-08-07T19:00:58.757000
5,134
1,198,468
Best strategy to write hooks for subversion in Windows
What is the best approach to write hooks for Subversion in Windows? As far as I know, only executable files can be used. So what is the best choice? Plain batch files (very limited but perhaps OK for very simple solutions) Dedicated compiled executable applications (sledgehammer to crack a nutshell?) Some other hybrid choice (like a batch file running a Powershell script)
I’ve just spent several days procrastinating about exactly this question. There are third party products available and plenty of PERL and Python scripts but I wanted something simple and a language I was familiar with so ended up just writing hooks in a C# console app. It’s very straight forward: public void Main(string[] args) { string repositories = args[0]; string transaction = args[1]; var processStartInfo = new ProcessStartInfo { FileName = "svnlook.exe", UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, Arguments = String.Format("log -t \"{0}\" \"{1}\"", transaction, repositories) }; var p = Process.Start(processStartInfo); var s = p.StandardOutput.ReadToEnd(); p.WaitForExit(); if (s == string.Empty) { Console.Error.WriteLine("Message must be provided"); Environment.Exit(1); } Environment.Exit(0); } You can then invoke this on pre commit by adding a pre-commit.cmd file to the hooks folder of the repo with the following line: [path]\PreCommit.exe %1 %2 You may consider this overkill but ultimately it’s only a few minutes of coding. What’s more, you get the advantage of the.NET language suite which IMHO is far preferable to the alternatives. I’ll expand my hooks out significantly and write appropriate tests against them as well – bit hard to do this with a DOS batch file! BTW, the code has been adapted from this post.
Best strategy to write hooks for subversion in Windows What is the best approach to write hooks for Subversion in Windows? As far as I know, only executable files can be used. So what is the best choice? Plain batch files (very limited but perhaps OK for very simple solutions) Dedicated compiled executable applications (sledgehammer to crack a nutshell?) Some other hybrid choice (like a batch file running a Powershell script)
TITLE: Best strategy to write hooks for subversion in Windows QUESTION: What is the best approach to write hooks for Subversion in Windows? As far as I know, only executable files can be used. So what is the best choice? Plain batch files (very limited but perhaps OK for very simple solutions) Dedicated compiled executable applications (sledgehammer to crack a nutshell?) Some other hybrid choice (like a batch file running a Powershell script) ANSWER: I’ve just spent several days procrastinating about exactly this question. There are third party products available and plenty of PERL and Python scripts but I wanted something simple and a language I was familiar with so ended up just writing hooks in a C# console app. It’s very straight forward: public void Main(string[] args) { string repositories = args[0]; string transaction = args[1]; var processStartInfo = new ProcessStartInfo { FileName = "svnlook.exe", UseShellExecute = false, CreateNoWindow = true, RedirectStandardOutput = true, RedirectStandardError = true, Arguments = String.Format("log -t \"{0}\" \"{1}\"", transaction, repositories) }; var p = Process.Start(processStartInfo); var s = p.StandardOutput.ReadToEnd(); p.WaitForExit(); if (s == string.Empty) { Console.Error.WriteLine("Message must be provided"); Environment.Exit(1); } Environment.Exit(0); } You can then invoke this on pre commit by adding a pre-commit.cmd file to the hooks folder of the repo with the following line: [path]\PreCommit.exe %1 %2 You may consider this overkill but ultimately it’s only a few minutes of coding. What’s more, you get the advantage of the.NET language suite which IMHO is far preferable to the alternatives. I’ll expand my hooks out significantly and write appropriate tests against them as well – bit hard to do this with a DOS batch file! BTW, the code has been adapted from this post.
[ "svn", "hook", "svn-hooks" ]
20
7
6,407
6
0
2008-08-07T18:47:50.580000
2009-07-29T07:03:06.380000
5,136
5,302
Creating a shared library in MATLAB
A researcher has created a small simulation in MATLAB and we want to make it accessible to others. My plan is to take the simulation, clean up a few things and turn it into a set of functions. Then I plan to compile it into a C library and use SWIG to create a Python wrapper. At that point, I should be able to call the simulation from a small Django application. At least I hope so. Do I have the right plan? Are there are any serious pitfalls that I'm not aware of at the moment?
I remember that I was able to wrap a MATLAB simulation into a DLL file and then call it from a Delphi application. It worked really well.
Creating a shared library in MATLAB A researcher has created a small simulation in MATLAB and we want to make it accessible to others. My plan is to take the simulation, clean up a few things and turn it into a set of functions. Then I plan to compile it into a C library and use SWIG to create a Python wrapper. At that point, I should be able to call the simulation from a small Django application. At least I hope so. Do I have the right plan? Are there are any serious pitfalls that I'm not aware of at the moment?
TITLE: Creating a shared library in MATLAB QUESTION: A researcher has created a small simulation in MATLAB and we want to make it accessible to others. My plan is to take the simulation, clean up a few things and turn it into a set of functions. Then I plan to compile it into a C library and use SWIG to create a Python wrapper. At that point, I should be able to call the simulation from a small Django application. At least I hope so. Do I have the right plan? Are there are any serious pitfalls that I'm not aware of at the moment? ANSWER: I remember that I was able to wrap a MATLAB simulation into a DLL file and then call it from a Delphi application. It worked really well.
[ "python", "c", "matlab" ]
15
4
2,470
4
0
2008-08-07T18:47:58.487000
2008-08-07T20:57:20.303000
5,170
5,270
SQL Server Management Studio alternatives to browse/edit tables and run queries
I was wondering if there are any alternatives to Microsoft's SQL Server Management Studio? Not there's anything wrong with SSMS, but sometimes it just seem too big an application where all I want todo is browse/edit tables and run queries.
I've started using LinqPad. In addition to being more lightweight than SSMS, you can also practice writing LINQ queries- way more fun than boring old TSQL!
SQL Server Management Studio alternatives to browse/edit tables and run queries I was wondering if there are any alternatives to Microsoft's SQL Server Management Studio? Not there's anything wrong with SSMS, but sometimes it just seem too big an application where all I want todo is browse/edit tables and run queries.
TITLE: SQL Server Management Studio alternatives to browse/edit tables and run queries QUESTION: I was wondering if there are any alternatives to Microsoft's SQL Server Management Studio? Not there's anything wrong with SSMS, but sometimes it just seem too big an application where all I want todo is browse/edit tables and run queries. ANSWER: I've started using LinqPad. In addition to being more lightweight than SSMS, you can also practice writing LINQ queries- way more fun than boring old TSQL!
[ "sql-server" ]
132
52
112,888
12
0
2008-08-07T19:06:03.600000
2008-08-07T20:31:12.413000
5,179
5,219
How Do I Post and then redirect to an external URL from ASP.Net?
ASP.NET server-side controls postback to their own page. This makes cases where you want to redirect a user to an external page, but need to post to that page for some reason (for authentication, for instance) a pain. An HttpWebRequest works great if you don't want to redirect, and JavaScript is fine in some cases, but can get tricky if you really do need the server-side code to get the data together for the post. So how do you both post to an external URL and redirect the user to the result from your ASP.NET codebehind code?
Here's how I solved this problem today. I started from this article on C# Corner, but found the example - while technically sound - a little incomplete. Everything he said was right, but I needed to hit a few external sites to piece this together to work exactly as I wanted. It didn't help that the user was not technically submitting a form at all; they were clicking a link to go to our support center, but to log them in an http post had to be made to the support center's site. This solution involves using HttpContext.Current.Response.Write() to write the data for the form, then using a bit of Javascript on the method to submit the form to the proper URL. When the user clicks on the Support Center link, the following method is called to write the response and redirect the user: public static void PassthroughAuthentication() { System.Web.HttpContext.Current.Response.Write(" "); System.Web.HttpContext.Current.Response.Write(" "); System.Web.HttpContext.Current.Response.Write(string.Format(" ", "Username")); System.Web.HttpContext.Current.Response.Write(" "); System.Web.HttpContext.Current.Response.Write(" "); } The key to this method is in that onload bit of Javascript, which, when the body of the page loads, submits the form and then redirects the user back to my own Home page. The reason for that bit of hoodoo is that I'm launching the external site in a new window, but don't want the user to resubmit the hidden form if they refresh the page. Plus that hidden form pushed the page down a few pixels which got on my nerves. I'd be very interested in any cleaner ideas anyone has on this one. Eric Sipple
How Do I Post and then redirect to an external URL from ASP.Net? ASP.NET server-side controls postback to their own page. This makes cases where you want to redirect a user to an external page, but need to post to that page for some reason (for authentication, for instance) a pain. An HttpWebRequest works great if you don't want to redirect, and JavaScript is fine in some cases, but can get tricky if you really do need the server-side code to get the data together for the post. So how do you both post to an external URL and redirect the user to the result from your ASP.NET codebehind code?
TITLE: How Do I Post and then redirect to an external URL from ASP.Net? QUESTION: ASP.NET server-side controls postback to their own page. This makes cases where you want to redirect a user to an external page, but need to post to that page for some reason (for authentication, for instance) a pain. An HttpWebRequest works great if you don't want to redirect, and JavaScript is fine in some cases, but can get tricky if you really do need the server-side code to get the data together for the post. So how do you both post to an external URL and redirect the user to the result from your ASP.NET codebehind code? ANSWER: Here's how I solved this problem today. I started from this article on C# Corner, but found the example - while technically sound - a little incomplete. Everything he said was right, but I needed to hit a few external sites to piece this together to work exactly as I wanted. It didn't help that the user was not technically submitting a form at all; they were clicking a link to go to our support center, but to log them in an http post had to be made to the support center's site. This solution involves using HttpContext.Current.Response.Write() to write the data for the form, then using a bit of Javascript on the method to submit the form to the proper URL. When the user clicks on the Support Center link, the following method is called to write the response and redirect the user: public static void PassthroughAuthentication() { System.Web.HttpContext.Current.Response.Write(" "); System.Web.HttpContext.Current.Response.Write(" "); System.Web.HttpContext.Current.Response.Write(string.Format(" ", "Username")); System.Web.HttpContext.Current.Response.Write(" "); System.Web.HttpContext.Current.Response.Write(" "); } The key to this method is in that onload bit of Javascript, which, when the body of the page loads, submits the form and then redirects the user back to my own Home page. The reason for that bit of hoodoo is that I'm launching the external site in a new window, but don't want the user to resubmit the hidden form if they refresh the page. Plus that hidden form pushed the page down a few pixels which got on my nerves. I'd be very interested in any cleaner ideas anyone has on this one. Eric Sipple
[ "javascript", "c#", "asp.net", "forms", "postback" ]
38
15
22,053
6
0
2008-08-07T19:13:04.583000
2008-08-07T19:36:56.580000
5,188
5,192
How do you pull the URL for an ASP.NET web reference from a configuration file in Visual Studio 2008?
I have a web reference for our report server embedded in our application. The server that the reports live on could change though, and I'd like to be able to change it "on the fly" if necessary. I know I've done this before, but can't seem to remember how. Thanks for your help. I've manually driven around this for the time being. It's not a big deal to set the URL in the code, but I'd like to figure out what the "proper" way of doing this in VS 2008 is. Could anyone provide any further insights? Thanks! In VS2008 when I change the URL Behavior property to Dynamic I get the following code auto-generated in the Reference class. Can I override this setting (MySettings) in the web.config? I guess I don't know how the settings stuff works. Public Sub New() MyBase.New Me.Url = Global.My.MySettings.Default.Namespace_Reference_ServiceName If (Me.IsLocalFileSystemWebService(Me.Url) = true) Then Me.UseDefaultCredentials = true Me.useDefaultCredentialsSetExplicitly = false Else Me.useDefaultCredentialsSetExplicitly = true End If End Sub EDIT So this stuff has changed a bit since VS03 (which was probably the last VS version I used to do this). According to: http://msdn.microsoft.com/en-us/library/a65txexh.aspx it looks like I have a settings object on which I can set the property programatically, but that I would need to provide the logic to retrieve that URL from the web.config. Is this the new standard way of doing this in VS2008, or am I missing something? EDIT #2 Anyone have any ideas here? I drove around it in my application and just put the URL in my web.config myself and read it out. But I'm not happy with that because it still feels like I'm missing something.
In the properties window change the "behavior" to Dynamic. See: http://www.codeproject.com/KB/XML/wsdldynamicurl.aspx
How do you pull the URL for an ASP.NET web reference from a configuration file in Visual Studio 2008? I have a web reference for our report server embedded in our application. The server that the reports live on could change though, and I'd like to be able to change it "on the fly" if necessary. I know I've done this before, but can't seem to remember how. Thanks for your help. I've manually driven around this for the time being. It's not a big deal to set the URL in the code, but I'd like to figure out what the "proper" way of doing this in VS 2008 is. Could anyone provide any further insights? Thanks! In VS2008 when I change the URL Behavior property to Dynamic I get the following code auto-generated in the Reference class. Can I override this setting (MySettings) in the web.config? I guess I don't know how the settings stuff works. Public Sub New() MyBase.New Me.Url = Global.My.MySettings.Default.Namespace_Reference_ServiceName If (Me.IsLocalFileSystemWebService(Me.Url) = true) Then Me.UseDefaultCredentials = true Me.useDefaultCredentialsSetExplicitly = false Else Me.useDefaultCredentialsSetExplicitly = true End If End Sub EDIT So this stuff has changed a bit since VS03 (which was probably the last VS version I used to do this). According to: http://msdn.microsoft.com/en-us/library/a65txexh.aspx it looks like I have a settings object on which I can set the property programatically, but that I would need to provide the logic to retrieve that URL from the web.config. Is this the new standard way of doing this in VS2008, or am I missing something? EDIT #2 Anyone have any ideas here? I drove around it in my application and just put the URL in my web.config myself and read it out. But I'm not happy with that because it still feels like I'm missing something.
TITLE: How do you pull the URL for an ASP.NET web reference from a configuration file in Visual Studio 2008? QUESTION: I have a web reference for our report server embedded in our application. The server that the reports live on could change though, and I'd like to be able to change it "on the fly" if necessary. I know I've done this before, but can't seem to remember how. Thanks for your help. I've manually driven around this for the time being. It's not a big deal to set the URL in the code, but I'd like to figure out what the "proper" way of doing this in VS 2008 is. Could anyone provide any further insights? Thanks! In VS2008 when I change the URL Behavior property to Dynamic I get the following code auto-generated in the Reference class. Can I override this setting (MySettings) in the web.config? I guess I don't know how the settings stuff works. Public Sub New() MyBase.New Me.Url = Global.My.MySettings.Default.Namespace_Reference_ServiceName If (Me.IsLocalFileSystemWebService(Me.Url) = true) Then Me.UseDefaultCredentials = true Me.useDefaultCredentialsSetExplicitly = false Else Me.useDefaultCredentialsSetExplicitly = true End If End Sub EDIT So this stuff has changed a bit since VS03 (which was probably the last VS version I used to do this). According to: http://msdn.microsoft.com/en-us/library/a65txexh.aspx it looks like I have a settings object on which I can set the property programatically, but that I would need to provide the logic to retrieve that URL from the web.config. Is this the new standard way of doing this in VS2008, or am I missing something? EDIT #2 Anyone have any ideas here? I drove around it in my application and just put the URL in my web.config myself and read it out. But I'm not happy with that because it still feels like I'm missing something. ANSWER: In the properties window change the "behavior" to Dynamic. See: http://www.codeproject.com/KB/XML/wsdldynamicurl.aspx
[ "asmx" ]
8
3
2,965
2
0
2008-08-07T19:20:27.097000
2008-08-07T19:22:25.983000
5,194
5,199
When to use an extension method with lambda over LINQtoObjects to filter a collection?
I am prototyping some C# 3 collection filters and came across this. I have a collection of products: public class MyProduct { public string Name { get; set; } public Double Price { get; set; } public string Description { get; set; } } var MyProducts = new List { new MyProduct { Name = "Surfboard", Price = 144.99, Description = "Most important thing you will ever own." }, new MyProduct { Name = "Leash", Price = 29.28, Description = "Keep important things close to you." }, new MyProduct { Name = "Sun Screen", Price = 15.88, Description = "1000 SPF! Who Could ask for more?" } }; Now if I use LINQ to filter it works as expected: var d = (from mp in MyProducts where mp.Price < 50d select mp); And if I use the Where extension method combined with a Lambda the filter works as well: var f = MyProducts.Where(mp => mp.Price < 50d).ToList(); Question: What is the difference, and why use one over the other?
LINQ turns into method calls like the code you have. In other words, there should be no difference. However, in your two pieces of code you are not calling.ToList in the first, so the first piece of code will produce an enumerable data source, but if you call.ToList on it, the two should be the same.
When to use an extension method with lambda over LINQtoObjects to filter a collection? I am prototyping some C# 3 collection filters and came across this. I have a collection of products: public class MyProduct { public string Name { get; set; } public Double Price { get; set; } public string Description { get; set; } } var MyProducts = new List { new MyProduct { Name = "Surfboard", Price = 144.99, Description = "Most important thing you will ever own." }, new MyProduct { Name = "Leash", Price = 29.28, Description = "Keep important things close to you." }, new MyProduct { Name = "Sun Screen", Price = 15.88, Description = "1000 SPF! Who Could ask for more?" } }; Now if I use LINQ to filter it works as expected: var d = (from mp in MyProducts where mp.Price < 50d select mp); And if I use the Where extension method combined with a Lambda the filter works as well: var f = MyProducts.Where(mp => mp.Price < 50d).ToList(); Question: What is the difference, and why use one over the other?
TITLE: When to use an extension method with lambda over LINQtoObjects to filter a collection? QUESTION: I am prototyping some C# 3 collection filters and came across this. I have a collection of products: public class MyProduct { public string Name { get; set; } public Double Price { get; set; } public string Description { get; set; } } var MyProducts = new List { new MyProduct { Name = "Surfboard", Price = 144.99, Description = "Most important thing you will ever own." }, new MyProduct { Name = "Leash", Price = 29.28, Description = "Keep important things close to you." }, new MyProduct { Name = "Sun Screen", Price = 15.88, Description = "1000 SPF! Who Could ask for more?" } }; Now if I use LINQ to filter it works as expected: var d = (from mp in MyProducts where mp.Price < 50d select mp); And if I use the Where extension method combined with a Lambda the filter works as well: var f = MyProducts.Where(mp => mp.Price < 50d).ToList(); Question: What is the difference, and why use one over the other? ANSWER: LINQ turns into method calls like the code you have. In other words, there should be no difference. However, in your two pieces of code you are not calling.ToList in the first, so the first piece of code will produce an enumerable data source, but if you call.ToList on it, the two should be the same.
[ "c#", "linq", ".net-3.5", "lambda" ]
16
6
3,956
4
0
2008-08-07T19:23:13.127000
2008-08-07T19:25:49.487000
5,222
5,224
Accessing post variables using Java Servlets
What is the Java equivalent of PHP's $_POST? After searching the web for an hour, I'm still nowhere closer.
Your HttpServletRequest object has a getParameter(String paramName) method that can be used to get parameter values. http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String)
Accessing post variables using Java Servlets What is the Java equivalent of PHP's $_POST? After searching the web for an hour, I'm still nowhere closer.
TITLE: Accessing post variables using Java Servlets QUESTION: What is the Java equivalent of PHP's $_POST? After searching the web for an hour, I'm still nowhere closer. ANSWER: Your HttpServletRequest object has a getParameter(String paramName) method that can be used to get parameter values. http://java.sun.com/javaee/5/docs/api/javax/servlet/ServletRequest.html#getParameter(java.lang.String)
[ "java", "http", "servlets" ]
66
54
145,898
5
0
2008-08-07T19:39:31.240000
2008-08-07T19:43:36.113000
5,223
6,700
Length of a JavaScript object
I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object? const myObject = new Object(); myObject["firstname"] = "Gareth"; myObject["lastname"] = "Simpson"; myObject["age"] = 21;
Updated answer Here's an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, you can use Object.keys() so the above code just becomes: var size = Object.keys(myObj).length; This doesn't have to modify any existing prototype since Object.keys() is now built-in. Edit: Objects can have symbolic properties that can not be returned via Object.key method. So the answer would be incomplete without mentioning them. Symbol type was added to the language to create unique identifiers for object properties. The main benefit of the Symbol type is the prevention of overwrites. Object.keys or Object.getOwnPropertyNames does not work for symbolic properties. To return them you need to use Object.getOwnPropertySymbols. var person = { [Symbol('name')]: 'John Doe', [Symbol('age')]: 33, "occupation": "Programmer" }; const propOwn = Object.getOwnPropertyNames(person); console.log(propOwn.length); // 1 let propSymb = Object.getOwnPropertySymbols(person); console.log(propSymb.length); // 2 Older answer The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be: Object.size = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; // Get the size of an object const myObj = {} var size = Object.size(myObj); There's a sort of convention in JavaScript that you don't add things to Object.prototype, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.
Length of a JavaScript object I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object? const myObject = new Object(); myObject["firstname"] = "Gareth"; myObject["lastname"] = "Simpson"; myObject["age"] = 21;
TITLE: Length of a JavaScript object QUESTION: I have a JavaScript object. Is there a built-in or accepted best practice way to get the length of this object? const myObject = new Object(); myObject["firstname"] = "Gareth"; myObject["lastname"] = "Simpson"; myObject["age"] = 21; ANSWER: Updated answer Here's an update as of 2016 and widespread deployment of ES5 and beyond. For IE9+ and all other modern ES5+ capable browsers, you can use Object.keys() so the above code just becomes: var size = Object.keys(myObj).length; This doesn't have to modify any existing prototype since Object.keys() is now built-in. Edit: Objects can have symbolic properties that can not be returned via Object.key method. So the answer would be incomplete without mentioning them. Symbol type was added to the language to create unique identifiers for object properties. The main benefit of the Symbol type is the prevention of overwrites. Object.keys or Object.getOwnPropertyNames does not work for symbolic properties. To return them you need to use Object.getOwnPropertySymbols. var person = { [Symbol('name')]: 'John Doe', [Symbol('age')]: 33, "occupation": "Programmer" }; const propOwn = Object.getOwnPropertyNames(person); console.log(propOwn.length); // 1 let propSymb = Object.getOwnPropertySymbols(person); console.log(propSymb.length); // 2 Older answer The most robust answer (i.e. that captures the intent of what you're trying to do while causing the fewest bugs) would be: Object.size = function(obj) { var size = 0, key; for (key in obj) { if (obj.hasOwnProperty(key)) size++; } return size; }; // Get the size of an object const myObj = {} var size = Object.size(myObj); There's a sort of convention in JavaScript that you don't add things to Object.prototype, because it can break enumerations in various libraries. Adding methods to Object is usually safe, though.
[ "javascript", "object", "javascript-objects" ]
3,026
3,391
2,940,325
44
0
2008-08-07T19:42:21.060000
2008-08-09T08:31:04.577000
5,226
5,293
HTML Comments Markup
I am currently in the process of creating my own blog and I have got to marking up the comments, but what is the best way to mark it up? The information I need to present is: Persons Name Gravatar Icon Comment Date The Comment PS: I'm only interested in semantic HTML markup.
I think that your version with the cite, blockquote, etc. would definitely work, but if semantics is your main concern then I personally wouldn't use cite and blockquote as they have specific things that they are supposed to represent. The blockquote tag is meant to represent a quotation taken from another source and the cite tag is meant to represent a source of information (like a magazine, newspaper, etc.). I think an argument can certainly made that you can use semantic HTML with class names, provided they are meaningful. This article on Plain Old Semantic HTML makes a reference to using class names - http://www.fooclass.com/plain_old_semantic_html
HTML Comments Markup I am currently in the process of creating my own blog and I have got to marking up the comments, but what is the best way to mark it up? The information I need to present is: Persons Name Gravatar Icon Comment Date The Comment PS: I'm only interested in semantic HTML markup.
TITLE: HTML Comments Markup QUESTION: I am currently in the process of creating my own blog and I have got to marking up the comments, but what is the best way to mark it up? The information I need to present is: Persons Name Gravatar Icon Comment Date The Comment PS: I'm only interested in semantic HTML markup. ANSWER: I think that your version with the cite, blockquote, etc. would definitely work, but if semantics is your main concern then I personally wouldn't use cite and blockquote as they have specific things that they are supposed to represent. The blockquote tag is meant to represent a quotation taken from another source and the cite tag is meant to represent a source of information (like a magazine, newspaper, etc.). I think an argument can certainly made that you can use semantic HTML with class names, provided they are meaningful. This article on Plain Old Semantic HTML makes a reference to using class names - http://www.fooclass.com/plain_old_semantic_html
[ "html", "semantic-markup" ]
16
6
2,470
5
0
2008-08-07T19:46:47.417000
2008-08-07T20:46:19.840000
5,242
5,246
User Interfaces - Colors and Layout
Although I'm specifically interested in web application information, I would also be somewhat curious about desktop application development as well. This question is driven by my work on my personal website as well as my job, where I have developed a few features, but left it to others to integrate into the look and feel of the site. Are there any guides or rules of thumb for things like color schemes, layouts, formatting, etc? I want to ensure readability and clarity for visitors, but not be bland and dull at the same time. As for my knowledge in this area - If you hand me a picture, I have enough knowledge to reproduce it on the screen, but if you ask me to design a new interface or redesign an existing one, I wouldn't know where to begin.
Usually, each operating System has user Interface Guidelines. For Windows, have a look here. (Edit: The links in that post are broken. But a Search for " User Interface Guidelines " on MSDN has articles about everything) Apple has it's own as well. Also, you may want to keep accessibility in mind.
User Interfaces - Colors and Layout Although I'm specifically interested in web application information, I would also be somewhat curious about desktop application development as well. This question is driven by my work on my personal website as well as my job, where I have developed a few features, but left it to others to integrate into the look and feel of the site. Are there any guides or rules of thumb for things like color schemes, layouts, formatting, etc? I want to ensure readability and clarity for visitors, but not be bland and dull at the same time. As for my knowledge in this area - If you hand me a picture, I have enough knowledge to reproduce it on the screen, but if you ask me to design a new interface or redesign an existing one, I wouldn't know where to begin.
TITLE: User Interfaces - Colors and Layout QUESTION: Although I'm specifically interested in web application information, I would also be somewhat curious about desktop application development as well. This question is driven by my work on my personal website as well as my job, where I have developed a few features, but left it to others to integrate into the look and feel of the site. Are there any guides or rules of thumb for things like color schemes, layouts, formatting, etc? I want to ensure readability and clarity for visitors, but not be bland and dull at the same time. As for my knowledge in this area - If you hand me a picture, I have enough knowledge to reproduce it on the screen, but if you ask me to design a new interface or redesign an existing one, I wouldn't know where to begin. ANSWER: Usually, each operating System has user Interface Guidelines. For Windows, have a look here. (Edit: The links in that post are broken. But a Search for " User Interface Guidelines " on MSDN has articles about everything) Apple has it's own as well. Also, you may want to keep accessibility in mind.
[ "user-interface", "usability" ]
10
5
1,413
8
0
2008-08-07T20:01:13.520000
2008-08-07T20:04:55.197000
5,263
24,472
How do you persist a tree structure to a database table with auto incrementing IDs using an ADO.NET DataSet and a DataAdapter
I have a self-referential Role table that represents a tree structure ID [INT] AUTO INCREMENT Name [VARCHAR] ParentID [INT] I am using an ADO.NET DataTable and DataAdapter to load and save values to this table. This works if I only create children of existing rows. If I make a child row, then make a child of that child, then Update, the temporary ID value generated by the DataTable is going into the ParentID column. I have the following data relation set: dataset.Relations.Add(New DataRelation("RoleToRole",RoleTable.Columns("ID"), RoleTable.Columns("ParentID"))) And when I make new child rows in the DataTable I call the SetParentRow method newRow.SetParentRow(parentRow) Is there something special I have to do to get the ID generation to propagate recursively when I call Update on the DataAdapter?
I don't know ADO.net in particular, but most ORMs won't automatically insert the ID of a new record in a relationship. You'll have to resort to the 2-step process: build and save parent build and save child with relationship to parent The reason that this is difficult for ORMs is because you might have circular dependencies, and it wouldn't know which object it needed to create an ID for first. Some ORMs are smart enough to figure out those relationships where there are no such circular dependencies, but most aren't.
How do you persist a tree structure to a database table with auto incrementing IDs using an ADO.NET DataSet and a DataAdapter I have a self-referential Role table that represents a tree structure ID [INT] AUTO INCREMENT Name [VARCHAR] ParentID [INT] I am using an ADO.NET DataTable and DataAdapter to load and save values to this table. This works if I only create children of existing rows. If I make a child row, then make a child of that child, then Update, the temporary ID value generated by the DataTable is going into the ParentID column. I have the following data relation set: dataset.Relations.Add(New DataRelation("RoleToRole",RoleTable.Columns("ID"), RoleTable.Columns("ParentID"))) And when I make new child rows in the DataTable I call the SetParentRow method newRow.SetParentRow(parentRow) Is there something special I have to do to get the ID generation to propagate recursively when I call Update on the DataAdapter?
TITLE: How do you persist a tree structure to a database table with auto incrementing IDs using an ADO.NET DataSet and a DataAdapter QUESTION: I have a self-referential Role table that represents a tree structure ID [INT] AUTO INCREMENT Name [VARCHAR] ParentID [INT] I am using an ADO.NET DataTable and DataAdapter to load and save values to this table. This works if I only create children of existing rows. If I make a child row, then make a child of that child, then Update, the temporary ID value generated by the DataTable is going into the ParentID column. I have the following data relation set: dataset.Relations.Add(New DataRelation("RoleToRole",RoleTable.Columns("ID"), RoleTable.Columns("ParentID"))) And when I make new child rows in the DataTable I call the SetParentRow method newRow.SetParentRow(parentRow) Is there something special I have to do to get the ID generation to propagate recursively when I call Update on the DataAdapter? ANSWER: I don't know ADO.net in particular, but most ORMs won't automatically insert the ID of a new record in a relationship. You'll have to resort to the 2-step process: build and save parent build and save child with relationship to parent The reason that this is difficult for ORMs is because you might have circular dependencies, and it wouldn't know which object it needed to create an ID for first. Some ORMs are smart enough to figure out those relationships where there are no such circular dependencies, but most aren't.
[ ".net", "database", "ado.net" ]
8
2
1,572
3
0
2008-08-07T20:23:51.057000
2008-08-23T18:37:59.287000
5,264
5,273
How can I dynamically center an image in a MS Reporting Services report?
Out of the box, in MS Reporting Services, the image element does not allow for the centering of the image itself, when the dimensions are unknown at design time. In other words, the image (if smaller than the dimensions allotted on the design surface) will be anchored to the top left corner, not in the center. My report will know the URL of the image at runtime, and I need to be able to center this image if it is smaller than the dimensions specified in my designer.
Here is how I was able to accomplish this. With help from Chris Hays Size the image to be as big as you would want it on the report, change "Sizing" property to "Clip". Dynamically set the image's left padding using an expression: =CStr(Round((4.625-System.Drawing.Image.FromStream(System.Net.WebRequest.Create(Parameters!LogoURL.Value).GetResponse().GetResponseStream()).Width/96)/2,2)) & "in" Dynamically set the image's top padding using an expression: =CStr(Round((1.125-System.Drawing.Image.FromStream(System.Net.WebRequest.Create(Parameters!LogoURL.Value).GetResponse().GetResponseStream()).Height/96)/2,2)) & "in" The first modification made to Chris's code was to swap out the dimensions of my image element on the report (my image was 4.625x1.125 - see numbers above). I also chose to get the stream from a URL instead of the database. I used WebRequest.Create.GetResponse. GetResponseStream do to so. So far so good - I Hope that helps!
How can I dynamically center an image in a MS Reporting Services report? Out of the box, in MS Reporting Services, the image element does not allow for the centering of the image itself, when the dimensions are unknown at design time. In other words, the image (if smaller than the dimensions allotted on the design surface) will be anchored to the top left corner, not in the center. My report will know the URL of the image at runtime, and I need to be able to center this image if it is smaller than the dimensions specified in my designer.
TITLE: How can I dynamically center an image in a MS Reporting Services report? QUESTION: Out of the box, in MS Reporting Services, the image element does not allow for the centering of the image itself, when the dimensions are unknown at design time. In other words, the image (if smaller than the dimensions allotted on the design surface) will be anchored to the top left corner, not in the center. My report will know the URL of the image at runtime, and I need to be able to center this image if it is smaller than the dimensions specified in my designer. ANSWER: Here is how I was able to accomplish this. With help from Chris Hays Size the image to be as big as you would want it on the report, change "Sizing" property to "Clip". Dynamically set the image's left padding using an expression: =CStr(Round((4.625-System.Drawing.Image.FromStream(System.Net.WebRequest.Create(Parameters!LogoURL.Value).GetResponse().GetResponseStream()).Width/96)/2,2)) & "in" Dynamically set the image's top padding using an expression: =CStr(Round((1.125-System.Drawing.Image.FromStream(System.Net.WebRequest.Create(Parameters!LogoURL.Value).GetResponse().GetResponseStream()).Height/96)/2,2)) & "in" The first modification made to Chris's code was to swap out the dimensions of my image element on the report (my image was 4.625x1.125 - see numbers above). I also chose to get the stream from a URL instead of the database. I used WebRequest.Create.GetResponse. GetResponseStream do to so. So far so good - I Hope that helps!
[ "reporting-services" ]
17
8
12,417
1
0
2008-08-07T20:24:34.003000
2008-08-07T20:31:41.010000
5,269
5,276
C# logic order and compiler behavior
In C#, (and feel free to answer for other languages), what order does the runtime evaluate a logic statement? Example: DataTable myDt = new DataTable(); if (myDt!= null && myDt.Rows.Count > 0) { //do some stuff with myDt } Which statement does the runtime evaluate first - myDt!= null or: myDt.Rows.Count > 0? Is there a time when the compiler would ever evaluate the statement backwards? Perhaps when an "OR" operator is involved? & is known as a logical bitwise operator and will always evaluate all the sub-expressions What is a good example of when to use the bitwise operator instead of the "short-circuited boolean"?
C#: Left to right, and processing stops if a non-match (evaluates to false) is found.
C# logic order and compiler behavior In C#, (and feel free to answer for other languages), what order does the runtime evaluate a logic statement? Example: DataTable myDt = new DataTable(); if (myDt!= null && myDt.Rows.Count > 0) { //do some stuff with myDt } Which statement does the runtime evaluate first - myDt!= null or: myDt.Rows.Count > 0? Is there a time when the compiler would ever evaluate the statement backwards? Perhaps when an "OR" operator is involved? & is known as a logical bitwise operator and will always evaluate all the sub-expressions What is a good example of when to use the bitwise operator instead of the "short-circuited boolean"?
TITLE: C# logic order and compiler behavior QUESTION: In C#, (and feel free to answer for other languages), what order does the runtime evaluate a logic statement? Example: DataTable myDt = new DataTable(); if (myDt!= null && myDt.Rows.Count > 0) { //do some stuff with myDt } Which statement does the runtime evaluate first - myDt!= null or: myDt.Rows.Count > 0? Is there a time when the compiler would ever evaluate the statement backwards? Perhaps when an "OR" operator is involved? & is known as a logical bitwise operator and will always evaluate all the sub-expressions What is a good example of when to use the bitwise operator instead of the "short-circuited boolean"? ANSWER: C#: Left to right, and processing stops if a non-match (evaluates to false) is found.
[ "c#", "language-agnostic", "compiler-construction", "logic" ]
18
16
4,081
18
0
2008-08-07T20:30:00.683000
2008-08-07T20:33:22.847000
5,307
5,317
Print a Winform/visual element
All the articles I've found via google are either obsolete or contradict one another. What's the easiest way to print a form or, say, a richtextbox in c#? I think it's using the PrintDiaglog class by setting the Document, but how does this get converted?
At least in VS 2008, its very easy. It took me about a couple of minutes to code the answer after reading your question. Here's where I borrowed it from: http://msdn.microsoft.com/en-us/library/6he9hz8c.aspx I tested this, and it works.
Print a Winform/visual element All the articles I've found via google are either obsolete or contradict one another. What's the easiest way to print a form or, say, a richtextbox in c#? I think it's using the PrintDiaglog class by setting the Document, but how does this get converted?
TITLE: Print a Winform/visual element QUESTION: All the articles I've found via google are either obsolete or contradict one another. What's the easiest way to print a form or, say, a richtextbox in c#? I think it's using the PrintDiaglog class by setting the Document, but how does this get converted? ANSWER: At least in VS 2008, its very easy. It took me about a couple of minutes to code the answer after reading your question. Here's where I borrowed it from: http://msdn.microsoft.com/en-us/library/6he9hz8c.aspx I tested this, and it works.
[ "c#", "winforms" ]
12
6
1,722
2
0
2008-08-07T20:58:14.060000
2008-08-07T21:09:17.423000
5,328
5,351
Why can't I use a try block around my super() call?
So, in Java, the first line of your constructor HAS to be a call to super... be it implicitly calling super(), or explicitly calling another constructor. What I want to know is, why can't I put a try block around that? My specific case is that I have a mock class for a test. There is no default constructor, but I want one to make the tests simpler to read. I also want to wrap the exceptions thrown from the constructor into a RuntimeException. So, what I want to do is effectively this: public class MyClassMock extends MyClass { public MyClassMock() { try { super(0); } catch (Exception e) { throw new RuntimeException(e); } } // Mocked methods } But Java complains that super isn't the first statement. My workaround: public class MyClassMock extends MyClass { public static MyClassMock construct() { try { return new MyClassMock(); } catch (Exception e) { throw new RuntimeException(e); } } public MyClassMock() throws Exception { super(0); } // Mocked methods } Is this the best workaround? Why doesn't Java let me do the former? My best guess as to the "why" is that Java doesn't want to let me have a constructed object in a potentially inconsistent state... however, in doing a mock, I don't care about that. It seems I should be able to do the above... or at least I know that the above is safe for my case... or seems as though it should be anyways. I am overriding any methods I use from the tested class, so there is no risk that I am using uninitialized variables.
Unfortunately, compilers can't work on theoretical principles, and even though you may know that it is safe in your case, if they allowed it, it would have to be safe for all cases. In other words, the compiler isn't stopping just you, it's stopping everyone, including all those that don't know that it is unsafe and needs special handling. There are probably other reasons for this as well, as all languages usually have ways to do unsafe things if one knows how to deal with them. In C#.NET there are similar provisions, and the only way to declare a constructor that calls a base constructor is this: public ClassName(...): base(...) in doing so, the base constructor will be called before the body of the constructor, and you cannot change this order.
Why can't I use a try block around my super() call? So, in Java, the first line of your constructor HAS to be a call to super... be it implicitly calling super(), or explicitly calling another constructor. What I want to know is, why can't I put a try block around that? My specific case is that I have a mock class for a test. There is no default constructor, but I want one to make the tests simpler to read. I also want to wrap the exceptions thrown from the constructor into a RuntimeException. So, what I want to do is effectively this: public class MyClassMock extends MyClass { public MyClassMock() { try { super(0); } catch (Exception e) { throw new RuntimeException(e); } } // Mocked methods } But Java complains that super isn't the first statement. My workaround: public class MyClassMock extends MyClass { public static MyClassMock construct() { try { return new MyClassMock(); } catch (Exception e) { throw new RuntimeException(e); } } public MyClassMock() throws Exception { super(0); } // Mocked methods } Is this the best workaround? Why doesn't Java let me do the former? My best guess as to the "why" is that Java doesn't want to let me have a constructed object in a potentially inconsistent state... however, in doing a mock, I don't care about that. It seems I should be able to do the above... or at least I know that the above is safe for my case... or seems as though it should be anyways. I am overriding any methods I use from the tested class, so there is no risk that I am using uninitialized variables.
TITLE: Why can't I use a try block around my super() call? QUESTION: So, in Java, the first line of your constructor HAS to be a call to super... be it implicitly calling super(), or explicitly calling another constructor. What I want to know is, why can't I put a try block around that? My specific case is that I have a mock class for a test. There is no default constructor, but I want one to make the tests simpler to read. I also want to wrap the exceptions thrown from the constructor into a RuntimeException. So, what I want to do is effectively this: public class MyClassMock extends MyClass { public MyClassMock() { try { super(0); } catch (Exception e) { throw new RuntimeException(e); } } // Mocked methods } But Java complains that super isn't the first statement. My workaround: public class MyClassMock extends MyClass { public static MyClassMock construct() { try { return new MyClassMock(); } catch (Exception e) { throw new RuntimeException(e); } } public MyClassMock() throws Exception { super(0); } // Mocked methods } Is this the best workaround? Why doesn't Java let me do the former? My best guess as to the "why" is that Java doesn't want to let me have a constructed object in a potentially inconsistent state... however, in doing a mock, I don't care about that. It seems I should be able to do the above... or at least I know that the above is safe for my case... or seems as though it should be anyways. I am overriding any methods I use from the tested class, so there is no risk that I am using uninitialized variables. ANSWER: Unfortunately, compilers can't work on theoretical principles, and even though you may know that it is safe in your case, if they allowed it, it would have to be safe for all cases. In other words, the compiler isn't stopping just you, it's stopping everyone, including all those that don't know that it is unsafe and needs special handling. There are probably other reasons for this as well, as all languages usually have ways to do unsafe things if one knows how to deal with them. In C#.NET there are similar provisions, and the only way to declare a constructor that calls a base constructor is this: public ClassName(...): base(...) in doing so, the base constructor will be called before the body of the constructor, and you cannot change this order.
[ "java", "exception", "mocking", "try-catch" ]
47
18
12,206
7
0
2008-08-07T21:17:56.813000
2008-08-07T21:32:34.367000
5,329
5,403
What is the difference between a bug and a change request in MSF for CMMI?
I'm currently evaluating the MSF for CMMI process template under TFS for use on my development team, and I'm having trouble understanding the need for separate bug and change request work item types. I understand that it is beneficial to be able to differentiate between bugs (errors) and change requests (changing requirements) when generating reports. In our current system, however, we only have a single type of change request and just use a field to indicate whether it is a bug, requirement change, etc (this field can be used to build report queries). What are the benefits of having a separate workflow for bugs? I'm also confused by the fact that developers can submit work against a bug or a change request, I thought the intended workflow was for bugs to generate change requests which are what the developer references when making changes.
@Luke I don't disagree with you, but this difference is typically the explanation given for why there is two different processes available for handling the two types of issues. I'd say that if the color of the home page was originally designed to be red, and for some reason it is blue, that's easily a quick fix and doesn't need to involve many people or man-hours to do the change. Just check out the file, change the color, check it back in and update the bug. However, if the color of the home page was designed to be red, and is red, but someone thinks it needs to be blue, that is, to me anyway, a different type of change. For instance, have someone thought about the impact this might have on other parts of the page, like images and logos overlaying the blue background? Could there be borders of things that looks bad? Link underlining is blue, will that show up? As an example, I am red/green color blind, changing the color of something is, for me, not something I take lightly. There are enough webpages on the web that gives me problems. Just to make a point that even the most trivial change can be nontrivial if you consider everything. The actual end implementation change is probably much of the same, but to me a change request is a different beast, precisely because it needs to be thought about more to make sure it will work as expected. A bug, however, is that someone said this is how we're going to do it and then someone did it differently. A change request is more like but we need to consider this other thing as well... hmm.... There are exceptions of course, but let me take your examples apart. If the server was designed to handle more than 300,000,000,000 pageviews, then yes, it is a bug that it doesn't. But designing a server to handle that many pageviews is more than just saying our server should handle 300,000,000,000 pageviews, it should contain a very detailed specification for how it can do that, right down to processing time guarantees and disk access average times. If the code is then implemented exactly as designed, and unable to perform as expected, then the question becomes: did we design it incorrectly or did we implement it incorrectly?. I agree that in this case, wether it is to be considered a design flaw or a implementation flaw depends on the actual reason for why it fails to live up to expectations. For instance, if someone assumed disks were 100x times as fast as they actually are, and this is deemed to be the reason for why the server fails to perform as expected, I'd say this is a design bug, and someone needs to redesign. If the original requirement of that many pageviews is still to be held, a major redesign with more in-memory data and similar might have to be undertaken. However, if someone has just failed to take into account how raid disks operate and how to correctly benefit from striped media, that's a bug and might not need that big of a change to fix. Again, there will of course be exceptions. In any case, the original difference I stated is the one I have found to be true in most cases.
What is the difference between a bug and a change request in MSF for CMMI? I'm currently evaluating the MSF for CMMI process template under TFS for use on my development team, and I'm having trouble understanding the need for separate bug and change request work item types. I understand that it is beneficial to be able to differentiate between bugs (errors) and change requests (changing requirements) when generating reports. In our current system, however, we only have a single type of change request and just use a field to indicate whether it is a bug, requirement change, etc (this field can be used to build report queries). What are the benefits of having a separate workflow for bugs? I'm also confused by the fact that developers can submit work against a bug or a change request, I thought the intended workflow was for bugs to generate change requests which are what the developer references when making changes.
TITLE: What is the difference between a bug and a change request in MSF for CMMI? QUESTION: I'm currently evaluating the MSF for CMMI process template under TFS for use on my development team, and I'm having trouble understanding the need for separate bug and change request work item types. I understand that it is beneficial to be able to differentiate between bugs (errors) and change requests (changing requirements) when generating reports. In our current system, however, we only have a single type of change request and just use a field to indicate whether it is a bug, requirement change, etc (this field can be used to build report queries). What are the benefits of having a separate workflow for bugs? I'm also confused by the fact that developers can submit work against a bug or a change request, I thought the intended workflow was for bugs to generate change requests which are what the developer references when making changes. ANSWER: @Luke I don't disagree with you, but this difference is typically the explanation given for why there is two different processes available for handling the two types of issues. I'd say that if the color of the home page was originally designed to be red, and for some reason it is blue, that's easily a quick fix and doesn't need to involve many people or man-hours to do the change. Just check out the file, change the color, check it back in and update the bug. However, if the color of the home page was designed to be red, and is red, but someone thinks it needs to be blue, that is, to me anyway, a different type of change. For instance, have someone thought about the impact this might have on other parts of the page, like images and logos overlaying the blue background? Could there be borders of things that looks bad? Link underlining is blue, will that show up? As an example, I am red/green color blind, changing the color of something is, for me, not something I take lightly. There are enough webpages on the web that gives me problems. Just to make a point that even the most trivial change can be nontrivial if you consider everything. The actual end implementation change is probably much of the same, but to me a change request is a different beast, precisely because it needs to be thought about more to make sure it will work as expected. A bug, however, is that someone said this is how we're going to do it and then someone did it differently. A change request is more like but we need to consider this other thing as well... hmm.... There are exceptions of course, but let me take your examples apart. If the server was designed to handle more than 300,000,000,000 pageviews, then yes, it is a bug that it doesn't. But designing a server to handle that many pageviews is more than just saying our server should handle 300,000,000,000 pageviews, it should contain a very detailed specification for how it can do that, right down to processing time guarantees and disk access average times. If the code is then implemented exactly as designed, and unable to perform as expected, then the question becomes: did we design it incorrectly or did we implement it incorrectly?. I agree that in this case, wether it is to be considered a design flaw or a implementation flaw depends on the actual reason for why it fails to live up to expectations. For instance, if someone assumed disks were 100x times as fast as they actually are, and this is deemed to be the reason for why the server fails to perform as expected, I'd say this is a design bug, and someone needs to redesign. If the original requirement of that many pageviews is still to be held, a major redesign with more in-memory data and similar might have to be undertaken. However, if someone has just failed to take into account how raid disks operate and how to correctly benefit from striped media, that's a bug and might not need that big of a change to fix. Again, there will of course be exceptions. In any case, the original difference I stated is the one I have found to be true in most cases.
[ "tfs", "workflow", "lifecycle", "cmmi", "ms-solution-framework" ]
11
13
17,807
6
0
2008-08-07T21:17:58.170000
2008-08-07T22:17:29.877000
5,349
6,192
Memcached chunk limit
Why is there a hardcoded chunk limit (.5 meg after compression) in memcached? Has anyone recompiled theirs to up it? I know I should not be sending big chunks like that around, but these extra heavy chunks happen for me from time to time and wreak havoc.
This question used to be in the official FAQ What are some limits in memcached I might hit? (Wayback Machine) To quote: The simple limits you will probably see with memcache are the key and item size limits. Keys are restricted to 250 characters. Stored data cannot exceed 1 megabyte in size, since that is the largest typical slab size." The FAQ has now been revised and there are now two separate questions covering this: What is the maxiumum key length? (250 bytes) The maximum size of a key is 250 characters. Note this value will be less if you are using client "prefixes" or similar features, since the prefix is tacked onto the front of the original key. Shorter keys are generally better since they save memory and use less bandwidth. Why are items limited to 1 megabyte in size? Ahh, this is a popular question! Short answer: Because of how the memory allocator's algorithm works. Long answer: Memcached's memory storage engine (which will be pluggable/adjusted in the future...), uses a slabs approach to memory management. Memory is broken up into slabs chunks of varying sizes, starting at a minimum number and ascending by a factorial up to the largest possible value. Say the minimum value is 400 bytes, and the maximum value is 1 megabyte, and the factorial is 1.20: slab 1 - 400 bytes slab 2 - 480 bytes slab 3 - 576 bytes... etc. The larger the slab, the more of a gap there is between it and the previous slab. So the larger the maximum value the less efficient the memory storage is. Memcached also has to pre-allocate some memory for every slab that exists, so setting a smaller factorial with a larger max value will require even more overhead. There're other reason why you wouldn't want to do that... If we're talking about a web page and you're attempting to store/load values that large, you're probably doing something wrong. At that size it'll take a noticeable amount of time to load and unpack the data structure into memory, and your site will likely not perform very well. If you really do want to store items larger than 1MB, you can recompile memcached with an edited slabs.c:POWER_BLOCK value, or use the inefficient malloc/free backend. Other suggestions include a database, MogileFS, etc.
Memcached chunk limit Why is there a hardcoded chunk limit (.5 meg after compression) in memcached? Has anyone recompiled theirs to up it? I know I should not be sending big chunks like that around, but these extra heavy chunks happen for me from time to time and wreak havoc.
TITLE: Memcached chunk limit QUESTION: Why is there a hardcoded chunk limit (.5 meg after compression) in memcached? Has anyone recompiled theirs to up it? I know I should not be sending big chunks like that around, but these extra heavy chunks happen for me from time to time and wreak havoc. ANSWER: This question used to be in the official FAQ What are some limits in memcached I might hit? (Wayback Machine) To quote: The simple limits you will probably see with memcache are the key and item size limits. Keys are restricted to 250 characters. Stored data cannot exceed 1 megabyte in size, since that is the largest typical slab size." The FAQ has now been revised and there are now two separate questions covering this: What is the maxiumum key length? (250 bytes) The maximum size of a key is 250 characters. Note this value will be less if you are using client "prefixes" or similar features, since the prefix is tacked onto the front of the original key. Shorter keys are generally better since they save memory and use less bandwidth. Why are items limited to 1 megabyte in size? Ahh, this is a popular question! Short answer: Because of how the memory allocator's algorithm works. Long answer: Memcached's memory storage engine (which will be pluggable/adjusted in the future...), uses a slabs approach to memory management. Memory is broken up into slabs chunks of varying sizes, starting at a minimum number and ascending by a factorial up to the largest possible value. Say the minimum value is 400 bytes, and the maximum value is 1 megabyte, and the factorial is 1.20: slab 1 - 400 bytes slab 2 - 480 bytes slab 3 - 576 bytes... etc. The larger the slab, the more of a gap there is between it and the previous slab. So the larger the maximum value the less efficient the memory storage is. Memcached also has to pre-allocate some memory for every slab that exists, so setting a smaller factorial with a larger max value will require even more overhead. There're other reason why you wouldn't want to do that... If we're talking about a web page and you're attempting to store/load values that large, you're probably doing something wrong. At that size it'll take a noticeable amount of time to load and unpack the data structure into memory, and your site will likely not perform very well. If you really do want to store items larger than 1MB, you can recompile memcached with an edited slabs.c:POWER_BLOCK value, or use the inefficient malloc/free backend. Other suggestions include a database, MogileFS, etc.
[ "membership" ]
8
4
3,019
1
0
2008-08-07T21:31:59.187000
2008-08-08T17:37:02.743000
5,374
5,469
How do you use a variable in xsl when trying to select a node?
I would have thought this would be an easy one to Google, but I've been unsuccessful. I want to assign a variable the value out of an attribute (easy so far) then use that variable to select another node based on the value of that attribute. Example:
Ok, I finally figured it out. Silly problem really, I simply needed to leave out the quotes and the braces. One of those times when I thought that I'd already tried that.:D Oh, and I mistyped @myId in the first example, the code was actually $myId.
How do you use a variable in xsl when trying to select a node? I would have thought this would be an easy one to Google, but I've been unsuccessful. I want to assign a variable the value out of an attribute (easy so far) then use that variable to select another node based on the value of that attribute. Example:
TITLE: How do you use a variable in xsl when trying to select a node? QUESTION: I would have thought this would be an easy one to Google, but I've been unsuccessful. I want to assign a variable the value out of an attribute (easy so far) then use that variable to select another node based on the value of that attribute. Example: ANSWER: Ok, I finally figured it out. Silly problem really, I simply needed to leave out the quotes and the braces. One of those times when I thought that I'd already tried that.:D Oh, and I mistyped @myId in the first example, the code was actually $myId.
[ "xslt" ]
16
17
20,204
2
0
2008-08-07T21:53:58.440000
2008-08-07T23:16:07.947000
5,396
5,481
SQL Server 2008 FileStream on a Web Server
I've been developing a site using ASP.NET MVC, and have decided to use the new SQL Server 2008 FILESTREAM facility to store files 'within' the database rather than as separate entities. While initially working within VS2008 (using a trusted connection to the database), everything was fine and dandy. Issues arose, however, when I shifted the site to IIS7 and changed over to SQL authentication on the database. It seems that streaming a FILESTREAM doesn't work with SQL authentication, only with Windows authentication. Given this, what is the best practice to follow? Is there a way to force this sort of thing to work under SQL authentication? Should I add NETWORK SERVICE as a database user and then use Trusted authentication? Should I create another user, and run both the IIS site and the database connection under this? Any other suggestions?
Take a look at this article. I don't know a whole lot about FileStreaming and security, but there are a couple of interesting options in the FileStreaming setup such as allowing remote connections and allow remote clients to access FileStreaming
SQL Server 2008 FileStream on a Web Server I've been developing a site using ASP.NET MVC, and have decided to use the new SQL Server 2008 FILESTREAM facility to store files 'within' the database rather than as separate entities. While initially working within VS2008 (using a trusted connection to the database), everything was fine and dandy. Issues arose, however, when I shifted the site to IIS7 and changed over to SQL authentication on the database. It seems that streaming a FILESTREAM doesn't work with SQL authentication, only with Windows authentication. Given this, what is the best practice to follow? Is there a way to force this sort of thing to work under SQL authentication? Should I add NETWORK SERVICE as a database user and then use Trusted authentication? Should I create another user, and run both the IIS site and the database connection under this? Any other suggestions?
TITLE: SQL Server 2008 FileStream on a Web Server QUESTION: I've been developing a site using ASP.NET MVC, and have decided to use the new SQL Server 2008 FILESTREAM facility to store files 'within' the database rather than as separate entities. While initially working within VS2008 (using a trusted connection to the database), everything was fine and dandy. Issues arose, however, when I shifted the site to IIS7 and changed over to SQL authentication on the database. It seems that streaming a FILESTREAM doesn't work with SQL authentication, only with Windows authentication. Given this, what is the best practice to follow? Is there a way to force this sort of thing to work under SQL authentication? Should I add NETWORK SERVICE as a database user and then use Trusted authentication? Should I create another user, and run both the IIS site and the database connection under this? Any other suggestions? ANSWER: Take a look at this article. I don't know a whole lot about FileStreaming and security, but there are a couple of interesting options in the FileStreaming setup such as allowing remote connections and allow remote clients to access FileStreaming
[ "sql-server", "sql-server-2008", "iis" ]
8
2
1,422
1
0
2008-08-07T22:10:05.663000
2008-08-07T23:36:46.673000
5,415
73,281
Convert Bytes to Floating Point Numbers?
I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?
>>> import struct >>> struct.pack('f', 3.141592654) b'\xdb\x0fI@' >>> struct.unpack('f', b'\xdb\x0fI@') (3.1415927410125732,) >>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0) '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'
Convert Bytes to Floating Point Numbers? I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number?
TITLE: Convert Bytes to Floating Point Numbers? QUESTION: I have a binary file that I have to parse and I'm using Python. Is there a way to take 4 bytes and convert it to a single precision floating point number? ANSWER: >>> import struct >>> struct.pack('f', 3.141592654) b'\xdb\x0fI@' >>> struct.unpack('f', b'\xdb\x0fI@') (3.1415927410125732,) >>> struct.pack('4f', 1.0, 2.0, 3.0, 4.0) '\x00\x00\x80?\x00\x00\x00@\x00\x00@@\x00\x00\x80@'
[ "python", "floating-point" ]
97
130
160,210
4
0
2008-08-07T22:24:27.740000
2008-09-16T14:59:37.253000
5,419
5,430
Python, Unicode, and the Windows console
When I try to print a string in a Windows console, sometimes I get an error that says UnicodeEncodeError: 'charmap' codec can't encode character..... I assume this is because the Windows console cannot handle all Unicode characters. How can I work around this? For example, how can I make the program display a replacement character (such as? ) instead of failing?
Note: This answer is sort of outdated (from 2008). Please use the solution below with care!! Here is a page that details the problem and a solution (search the page for the text Wrapping sys.stdout into an instance ): PrintFails - Python Wiki Here's a code excerpt from that page: $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' UTF-8 2 Б Б $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' | cat None 2 Б Б There's some more information on that page, well worth a read.
Python, Unicode, and the Windows console When I try to print a string in a Windows console, sometimes I get an error that says UnicodeEncodeError: 'charmap' codec can't encode character..... I assume this is because the Windows console cannot handle all Unicode characters. How can I work around this? For example, how can I make the program display a replacement character (such as? ) instead of failing?
TITLE: Python, Unicode, and the Windows console QUESTION: When I try to print a string in a Windows console, sometimes I get an error that says UnicodeEncodeError: 'charmap' codec can't encode character..... I assume this is because the Windows console cannot handle all Unicode characters. How can I work around this? For example, how can I make the program display a replacement character (such as? ) instead of failing? ANSWER: Note: This answer is sort of outdated (from 2008). Please use the solution below with care!! Here is a page that details the problem and a solution (search the page for the text Wrapping sys.stdout into an instance ): PrintFails - Python Wiki Here's a code excerpt from that page: $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' UTF-8 2 Б Б $ python -c 'import sys, codecs, locale; print sys.stdout.encoding; \ sys.stdout = codecs.getwriter(locale.getpreferredencoding())(sys.stdout); \ line = u"\u0411\n"; print type(line), len(line); \ sys.stdout.write(line); print line' | cat None 2 Б Б There's some more information on that page, well worth a read.
[ "python", "unicode" ]
177
38
135,664
15
0
2008-08-07T22:26:58.063000
2008-08-07T22:32:23.510000
5,425
5,441
HTML comments break down
I have a page that is generated which inserts an HTML comment near the top of the page. Inside the comment is a *nix-style command. This comment breaks the page completely. What is wrong with the comment to cause this to happen, and why is this the case?
Comments in the XML Spec from the w3.org: For compatibility, the string "--" (double-hyphen) MUST NOT occur within comments.
HTML comments break down I have a page that is generated which inserts an HTML comment near the top of the page. Inside the comment is a *nix-style command. This comment breaks the page completely. What is wrong with the comment to cause this to happen, and why is this the case?
TITLE: HTML comments break down QUESTION: I have a page that is generated which inserts an HTML comment near the top of the page. Inside the comment is a *nix-style command. This comment breaks the page completely. What is wrong with the comment to cause this to happen, and why is this the case? ANSWER: Comments in the XML Spec from the w3.org: For compatibility, the string "--" (double-hyphen) MUST NOT occur within comments.
[ "html", "xml", "comments", "sgml" ]
24
27
1,093
3
0
2008-08-07T22:30:25.357000
2008-08-07T22:39:12.983000
5,428
5,439
Do people use the Hungarian Naming Conventions in the real world?
Is it worth learning the convention or is it a bane to readability and maintainability?
Considering that most people that use Hungarian Notation is following the misunderstood version of it, I'd say it's pretty pointless. If you want to use the original definition of it, it might make more sense, but other than that it is mostly syntactic sugar. If you read the Wikipedia article on the subject, you'll find two conflicting notations, Systems Hungarian Notation and Apps Hungarian Notation. The original, good, definition is the Apps Hungarian Notation, but most people use the Systems Hungarian Notation. As an example of the two, consider prefixing variables with l for length, a for area and v for volume. With such notation, the following expression makes sense: int vBox = aBottom * lVerticalSide; but this doesn't: int aBottom = lSide1; If you're mixing the prefixes, they're to be considered part of the equation, and volume = area * length is fine for a box, but copying a length value into an area variable should raise some red flags. Unfortunately, the other notation is less useful, where people prefix the variable names with the type of the value, like this: int iLength; int iVolume; int iArea; some people use n for number, or i for integer, f for float, s for string etc. The original prefix was meant to be used to spot problems in equations, but has somehow devolved into making the code slightly easier to read since you don't have to go look for the variable declaration. With todays smart editors where you can simply hover over any variable to find the full type, and not just an abbreviation for it, this type of hungarian notation has lost a lot of its meaning. But, you should make up your own mind. All I can say is that I don't use either. Edit Just to add a short notice, while I don't use Hungarian Notation, I do use a prefix, and it's the underscore. I prefix all private fields of classes with a _ and otherwise spell their names as I would a property, titlecase with the first letter uppercase.
Do people use the Hungarian Naming Conventions in the real world? Is it worth learning the convention or is it a bane to readability and maintainability?
TITLE: Do people use the Hungarian Naming Conventions in the real world? QUESTION: Is it worth learning the convention or is it a bane to readability and maintainability? ANSWER: Considering that most people that use Hungarian Notation is following the misunderstood version of it, I'd say it's pretty pointless. If you want to use the original definition of it, it might make more sense, but other than that it is mostly syntactic sugar. If you read the Wikipedia article on the subject, you'll find two conflicting notations, Systems Hungarian Notation and Apps Hungarian Notation. The original, good, definition is the Apps Hungarian Notation, but most people use the Systems Hungarian Notation. As an example of the two, consider prefixing variables with l for length, a for area and v for volume. With such notation, the following expression makes sense: int vBox = aBottom * lVerticalSide; but this doesn't: int aBottom = lSide1; If you're mixing the prefixes, they're to be considered part of the equation, and volume = area * length is fine for a box, but copying a length value into an area variable should raise some red flags. Unfortunately, the other notation is less useful, where people prefix the variable names with the type of the value, like this: int iLength; int iVolume; int iArea; some people use n for number, or i for integer, f for float, s for string etc. The original prefix was meant to be used to spot problems in equations, but has somehow devolved into making the code slightly easier to read since you don't have to go look for the variable declaration. With todays smart editors where you can simply hover over any variable to find the full type, and not just an abbreviation for it, this type of hungarian notation has lost a lot of its meaning. But, you should make up your own mind. All I can say is that I don't use either. Edit Just to add a short notice, while I don't use Hungarian Notation, I do use a prefix, and it's the underscore. I prefix all private fields of classes with a _ and otherwise spell their names as I would a property, titlecase with the first letter uppercase.
[ "conventions", "hungarian-notation", "self-documenting-code" ]
34
59
12,784
20
0
2008-08-07T22:31:13.653000
2008-08-07T22:39:00.533000
5,459
19,601
Accessing a CONST attribute of series of Classes
This is how I wanted to do it which would work in PHP 5.3.0+ But I'm restricted to using PHP 5.2.6. Can anyone think of a simple way to simulate this behavior without instantiating the class?
You can accomplish this without using eval in pre-5.3 code. Just use the constant function:
Accessing a CONST attribute of series of Classes This is how I wanted to do it which would work in PHP 5.3.0+ But I'm restricted to using PHP 5.2.6. Can anyone think of a simple way to simulate this behavior without instantiating the class?
TITLE: Accessing a CONST attribute of series of Classes QUESTION: This is how I wanted to do it which would work in PHP 5.3.0+ But I'm restricted to using PHP 5.2.6. Can anyone think of a simple way to simulate this behavior without instantiating the class? ANSWER: You can accomplish this without using eval in pre-5.3 code. Just use the constant function:
[ "php", "oop" ]
11
10
792
2
0
2008-08-07T22:58:42.617000
2008-08-21T10:48:23.407000
5,460
5,462
Telligent's Community Server
The company I work for is wanting to add blog functionality to our website and they were looking to spend an awful amount of money to have some crap being built on top of a CMS they purchased (sitecore). I pointed them to Telligent's Community Server and we had a sales like meeting today to get the Marketing folks on board. My question is if anyone has had issues working with Community Server, skinning it and extending it? I wanted to explain a bit why I am thinking Community Server, the company is wanting multiple blogs with multiple authors. I want to be out of the admin part of this as much as possible and didn't think there were too many engines that having multiple blogs didn't mean db work. I also like the other functionality that Community Server provides and think the company will find it useful, particularly the media section as right now we have some really shotty way of dealing with whitepapers and stuff. edit: We are actually using the Sitecore blog module for a single blog on our intranet (which is actually what the CMS is serving). Some reasoning for why I don't like it for our public site are they are on different servers, it doesn't support multiple authors, there is no built in syndication, it is a little flimsy feeling to me from looking at the source and I personally think the other features of Community Server make its price tag worth it. another edit: Need to stick to.net software that run on sql server in my company's case, but I don't mind seeing recommendations for others. ExpressionEngine looks promising, will try it out on my personal box.
I've done quite a few projects using Community Server. If you're okay with the out-of-the-box functionality, or you don't mind sticking to the version you start with, I think you'll be very happy. The times I've run into headaches using CS is when the client wants functionality CS does not provide, but also insists on keeping the ability to upgrade to the latest version whenever Telligent releases an update. You can mostly support that by making all of your changes either in a separate project or by only modifying aspx/ascx files (no codebehinds). Some kind of merge is going to be required though no matter how well you plan it out.
Telligent's Community Server The company I work for is wanting to add blog functionality to our website and they were looking to spend an awful amount of money to have some crap being built on top of a CMS they purchased (sitecore). I pointed them to Telligent's Community Server and we had a sales like meeting today to get the Marketing folks on board. My question is if anyone has had issues working with Community Server, skinning it and extending it? I wanted to explain a bit why I am thinking Community Server, the company is wanting multiple blogs with multiple authors. I want to be out of the admin part of this as much as possible and didn't think there were too many engines that having multiple blogs didn't mean db work. I also like the other functionality that Community Server provides and think the company will find it useful, particularly the media section as right now we have some really shotty way of dealing with whitepapers and stuff. edit: We are actually using the Sitecore blog module for a single blog on our intranet (which is actually what the CMS is serving). Some reasoning for why I don't like it for our public site are they are on different servers, it doesn't support multiple authors, there is no built in syndication, it is a little flimsy feeling to me from looking at the source and I personally think the other features of Community Server make its price tag worth it. another edit: Need to stick to.net software that run on sql server in my company's case, but I don't mind seeing recommendations for others. ExpressionEngine looks promising, will try it out on my personal box.
TITLE: Telligent's Community Server QUESTION: The company I work for is wanting to add blog functionality to our website and they were looking to spend an awful amount of money to have some crap being built on top of a CMS they purchased (sitecore). I pointed them to Telligent's Community Server and we had a sales like meeting today to get the Marketing folks on board. My question is if anyone has had issues working with Community Server, skinning it and extending it? I wanted to explain a bit why I am thinking Community Server, the company is wanting multiple blogs with multiple authors. I want to be out of the admin part of this as much as possible and didn't think there were too many engines that having multiple blogs didn't mean db work. I also like the other functionality that Community Server provides and think the company will find it useful, particularly the media section as right now we have some really shotty way of dealing with whitepapers and stuff. edit: We are actually using the Sitecore blog module for a single blog on our intranet (which is actually what the CMS is serving). Some reasoning for why I don't like it for our public site are they are on different servers, it doesn't support multiple authors, there is no built in syndication, it is a little flimsy feeling to me from looking at the source and I personally think the other features of Community Server make its price tag worth it. another edit: Need to stick to.net software that run on sql server in my company's case, but I don't mind seeing recommendations for others. ExpressionEngine looks promising, will try it out on my personal box. ANSWER: I've done quite a few projects using Community Server. If you're okay with the out-of-the-box functionality, or you don't mind sticking to the version you start with, I think you'll be very happy. The times I've run into headaches using CS is when the client wants functionality CS does not provide, but also insists on keeping the ability to upgrade to the latest version whenever Telligent releases an update. You can mostly support that by making all of your changes either in a separate project or by only modifying aspx/ascx files (no codebehinds). Some kind of merge is going to be required though no matter how well you plan it out.
[ "community-server" ]
5
9
2,909
8
0
2008-08-07T23:00:30.053000
2008-08-07T23:08:54.110000
5,473
21,778
How can I undo git reset --hard HEAD~1?
Is it possible to undo the changes caused by the following command? If so, how? git reset --hard HEAD~1
Pat Notz is correct. You can get the commit back so long as it's been within a few days. git only garbage collects after about a month or so unless you explicitly tell it to remove newer blobs. $ git init Initialized empty Git repository in.git/ $ echo "testing reset" > file1 $ git add file1 $ git commit -m 'added file1' Created initial commit 1a75c1d: added file1 1 files changed, 1 insertions(+), 0 deletions(-) create mode 100644 file1 $ echo "added new file" > file2 $ git add file2 $ git commit -m 'added file2' Created commit f6e5064: added file2 1 files changed, 1 insertions(+), 0 deletions(-) create mode 100644 file2 $ git reset --hard HEAD^ HEAD is now at 1a75c1d... added file1 $ cat file2 cat: file2: No such file or directory $ git reflog 1a75c1d... HEAD@{0}: reset --hard HEAD^: updating HEAD f6e5064... HEAD@{1}: commit: added file2 $ git reset --hard f6e5064 HEAD is now at f6e5064... added file2 $ cat file2 added new file You can see in the example that the file2 was removed as a result of the hard reset, but was put back in place when I reset via the reflog.
How can I undo git reset --hard HEAD~1? Is it possible to undo the changes caused by the following command? If so, how? git reset --hard HEAD~1
TITLE: How can I undo git reset --hard HEAD~1? QUESTION: Is it possible to undo the changes caused by the following command? If so, how? git reset --hard HEAD~1 ANSWER: Pat Notz is correct. You can get the commit back so long as it's been within a few days. git only garbage collects after about a month or so unless you explicitly tell it to remove newer blobs. $ git init Initialized empty Git repository in.git/ $ echo "testing reset" > file1 $ git add file1 $ git commit -m 'added file1' Created initial commit 1a75c1d: added file1 1 files changed, 1 insertions(+), 0 deletions(-) create mode 100644 file1 $ echo "added new file" > file2 $ git add file2 $ git commit -m 'added file2' Created commit f6e5064: added file2 1 files changed, 1 insertions(+), 0 deletions(-) create mode 100644 file2 $ git reset --hard HEAD^ HEAD is now at 1a75c1d... added file1 $ cat file2 cat: file2: No such file or directory $ git reflog 1a75c1d... HEAD@{0}: reset --hard HEAD^: updating HEAD f6e5064... HEAD@{1}: commit: added file2 $ git reset --hard f6e5064 HEAD is now at f6e5064... added file2 $ cat file2 added new file You can see in the example that the file2 was removed as a result of the hard reset, but was put back in place when I reset via the reflog.
[ "git", "version-control", "git-reset" ]
1,637
2,420
856,927
20
0
2008-08-07T23:22:51.273000
2008-08-22T04:36:02.187000
5,482
5,500
How to specify javascript to run when ModalPopupExtender is shown
The ASP.NET AJAX ModalPopupExtender has OnCancelScript and OnOkScript properties, but it doesn't seem to have an OnShowScript property. I'd like to specify a javascript function to run each time the popup is shown. In past situations, I set the TargetControlID to a dummy control and provide my own control that first does some JS code and then uses the JS methods to show the popup. But in this case, I am showing the popup from both client and server side code. Anyone know of a way to do this? BTW, I needed this because I have a textbox in the modal that I want to make a TinyMCE editor. But the TinyMCE init script doesn't work on invisible textboxes, so I had to find a way to run it at the time the modal was shown
hmmm... I'm pretty sure that there's a shown event for the MPE... this is off the top of my head, but I think you can add an event handler to the shown event on page_load function pageLoad() { var popup = $find('ModalPopupClientID'); popup.add_shown(SetFocus); } function SetFocus() { $get('TriggerClientId').focus(); } i'm not sure tho if this will help you with calling it from the server side tho
How to specify javascript to run when ModalPopupExtender is shown The ASP.NET AJAX ModalPopupExtender has OnCancelScript and OnOkScript properties, but it doesn't seem to have an OnShowScript property. I'd like to specify a javascript function to run each time the popup is shown. In past situations, I set the TargetControlID to a dummy control and provide my own control that first does some JS code and then uses the JS methods to show the popup. But in this case, I am showing the popup from both client and server side code. Anyone know of a way to do this? BTW, I needed this because I have a textbox in the modal that I want to make a TinyMCE editor. But the TinyMCE init script doesn't work on invisible textboxes, so I had to find a way to run it at the time the modal was shown
TITLE: How to specify javascript to run when ModalPopupExtender is shown QUESTION: The ASP.NET AJAX ModalPopupExtender has OnCancelScript and OnOkScript properties, but it doesn't seem to have an OnShowScript property. I'd like to specify a javascript function to run each time the popup is shown. In past situations, I set the TargetControlID to a dummy control and provide my own control that first does some JS code and then uses the JS methods to show the popup. But in this case, I am showing the popup from both client and server side code. Anyone know of a way to do this? BTW, I needed this because I have a textbox in the modal that I want to make a TinyMCE editor. But the TinyMCE init script doesn't work on invisible textboxes, so I had to find a way to run it at the time the modal was shown ANSWER: hmmm... I'm pretty sure that there's a shown event for the MPE... this is off the top of my head, but I think you can add an event handler to the shown event on page_load function pageLoad() { var popup = $find('ModalPopupClientID'); popup.add_shown(SetFocus); } function SetFocus() { $get('TriggerClientId').focus(); } i'm not sure tho if this will help you with calling it from the server side tho
[ "asp.net", "javascript", "asp.net-ajax" ]
39
30
31,759
8
0
2008-08-07T23:37:30.807000
2008-08-08T00:03:41.067000
5,494
12,519
Alternative Hostname for an IIS web site for internal access only
I'm using IIS in Windows 2003 Server for a SharePoint intranet. External incoming requests will be using the host header portal.mycompany.com and be forced to use SSL. I was wondering if there's a way to set up an alternate host header such as http://internalportal/ which only accepts requests from the internal network, but doesn't force the users to use SSL. Any recommendations for how to set this up?
Daniel, keep in mind that just because something is possbile in IIS, and via any number of off box solutions (like hardware load balancers and SSL) doesn't mean that it is supported by SharePoint, or that it is implemented in the same way. You can do what you are asking for, however you should do it via SharePoint Central Administration, and "Create or Extend a Web Application" and then "Extend and Existing Application". In this way you can create a new web site (in IIS) for accessing your existing SharePoint Web Application, one that can be accessed via a different hostheader, port, using SSL, Authentication mechanism, etc. As a general rule, if you can do something in IIS AND in SharePoint, you should do it only in SharePoint.
Alternative Hostname for an IIS web site for internal access only I'm using IIS in Windows 2003 Server for a SharePoint intranet. External incoming requests will be using the host header portal.mycompany.com and be forced to use SSL. I was wondering if there's a way to set up an alternate host header such as http://internalportal/ which only accepts requests from the internal network, but doesn't force the users to use SSL. Any recommendations for how to set this up?
TITLE: Alternative Hostname for an IIS web site for internal access only QUESTION: I'm using IIS in Windows 2003 Server for a SharePoint intranet. External incoming requests will be using the host header portal.mycompany.com and be forced to use SSL. I was wondering if there's a way to set up an alternate host header such as http://internalportal/ which only accepts requests from the internal network, but doesn't force the users to use SSL. Any recommendations for how to set this up? ANSWER: Daniel, keep in mind that just because something is possbile in IIS, and via any number of off box solutions (like hardware load balancers and SSL) doesn't mean that it is supported by SharePoint, or that it is implemented in the same way. You can do what you are asking for, however you should do it via SharePoint Central Administration, and "Create or Extend a Web Application" and then "Extend and Existing Application". In this way you can create a new web site (in IIS) for accessing your existing SharePoint Web Application, one that can be accessed via a different hostheader, port, using SSL, Authentication mechanism, etc. As a general rule, if you can do something in IIS AND in SharePoint, you should do it only in SharePoint.
[ "sharepoint", "iis", "moss", "wss" ]
3
3
6,303
3
0
2008-08-07T23:53:55.717000
2008-08-15T17:34:38.593000
5,507
5,524
Does it still make sense to learn low level WinAPI programming?
Does it make sense, having all of the C#-managed-bliss, to go back to Petzold's Programming Windows and try to produce code w/ pure WinAPI? What can be learn from it? Isn't it just too outdated to be useful?
This question is bordering on religious:) But I'll give my thoughts anyway. I do see value in learing the Win32 API. Most, if not all, GUI libraries (managed or unmanaged) result in calls to the Win32 API. Even the most thorough libraries don't cover 100% of the API, and hence there are always gaps which need to be plugged by direct API calls or P/invoking. Some of the names of the wrappers around the API calls have similar names to the underlying API calls, but those names aren't exactly self-documenting. So understanding the underlying API, and the terminology used therein, will aid in understanding the wrapper APIs and what they actually do. Plus, if you understand the nature of the underlying APIs that are used by frameworks, then you will make better choices with regards to which library functionality you should use in a given scenario. Cheers!
Does it still make sense to learn low level WinAPI programming? Does it make sense, having all of the C#-managed-bliss, to go back to Petzold's Programming Windows and try to produce code w/ pure WinAPI? What can be learn from it? Isn't it just too outdated to be useful?
TITLE: Does it still make sense to learn low level WinAPI programming? QUESTION: Does it make sense, having all of the C#-managed-bliss, to go back to Petzold's Programming Windows and try to produce code w/ pure WinAPI? What can be learn from it? Isn't it just too outdated to be useful? ANSWER: This question is bordering on religious:) But I'll give my thoughts anyway. I do see value in learing the Win32 API. Most, if not all, GUI libraries (managed or unmanaged) result in calls to the Win32 API. Even the most thorough libraries don't cover 100% of the API, and hence there are always gaps which need to be plugged by direct API calls or P/invoking. Some of the names of the wrappers around the API calls have similar names to the underlying API calls, but those names aren't exactly self-documenting. So understanding the underlying API, and the terminology used therein, will aid in understanding the wrapper APIs and what they actually do. Plus, if you understand the nature of the underlying APIs that are used by frameworks, then you will make better choices with regards to which library functionality you should use in a given scenario. Cheers!
[ "windows", "winapi" ]
55
66
12,771
22
0
2008-08-08T00:29:13.963000
2008-08-08T01:00:49.203000
5,509
81,892
Rational Purify failing to jump to memory leaks
So my company uses a delightfully buggy program called Rational Purify (as a plugin to Microsoft Visual Developer Studio) to manage memory leaks. The program is deigned to let you click on a memory leak after you have encountered it, and then jump to the line that the leak occurs on. Unfortunately Purify is malfunctioning and Purify will not jump to the place that the leak occurred it only mentions the class and method that the leak occurs in. Unfortunately, sometimes this is about as useful as hiring a guide to help you hunt bears and having him point to the forest and tell you there are bears there. Does anyone with Purify experience have any idea how I might fix this problem or have a good manual to look though?
Generally you have two options, one exclude modules DLL's from instrumentation in Purify, it helps some times. Second is get BoundsChecker, this does compile time instrumentation much slower but the level of detail is an order of magnitude better. We generally use Purify on check-in, sanity checking, and BoundsChecker when we know a bug/crash exists. BoundsChecker has some nice features like only instrument files A.cpp & B.cpp, excluding all the rest. Be aware neither of these two applications function on 64 bit operating systems, and BoundsChecker will not install on 64 bit OS. Most frustrating if you make the switch to native 64 bit development with 32 bit back port!
Rational Purify failing to jump to memory leaks So my company uses a delightfully buggy program called Rational Purify (as a plugin to Microsoft Visual Developer Studio) to manage memory leaks. The program is deigned to let you click on a memory leak after you have encountered it, and then jump to the line that the leak occurs on. Unfortunately Purify is malfunctioning and Purify will not jump to the place that the leak occurred it only mentions the class and method that the leak occurs in. Unfortunately, sometimes this is about as useful as hiring a guide to help you hunt bears and having him point to the forest and tell you there are bears there. Does anyone with Purify experience have any idea how I might fix this problem or have a good manual to look though?
TITLE: Rational Purify failing to jump to memory leaks QUESTION: So my company uses a delightfully buggy program called Rational Purify (as a plugin to Microsoft Visual Developer Studio) to manage memory leaks. The program is deigned to let you click on a memory leak after you have encountered it, and then jump to the line that the leak occurs on. Unfortunately Purify is malfunctioning and Purify will not jump to the place that the leak occurred it only mentions the class and method that the leak occurs in. Unfortunately, sometimes this is about as useful as hiring a guide to help you hunt bears and having him point to the forest and tell you there are bears there. Does anyone with Purify experience have any idea how I might fix this problem or have a good manual to look though? ANSWER: Generally you have two options, one exclude modules DLL's from instrumentation in Purify, it helps some times. Second is get BoundsChecker, this does compile time instrumentation much slower but the level of detail is an order of magnitude better. We generally use Purify on check-in, sanity checking, and BoundsChecker when we know a bug/crash exists. BoundsChecker has some nice features like only instrument files A.cpp & B.cpp, excluding all the rest. Be aware neither of these two applications function on 64 bit operating systems, and BoundsChecker will not install on 64 bit OS. Most frustrating if you make the switch to native 64 bit development with 32 bit back port!
[ "memory-leaks", "purify" ]
0
3
2,082
5
0
2008-08-08T00:31:19.823000
2008-09-17T10:39:03.347000
5,511
7,794
Numeric Data Entry in WPF
How are you handling the entry of numeric values in WPF applications? Without a NumericUpDown control, I've been using a TextBox and handling its PreviewKeyDown event with the code below, but it's pretty ugly. Has anyone found a more graceful way to get numeric data from the user without relying on a third-party control? private void NumericEditPreviewKeyDown(object sender, KeyEventArgs e) { bool isNumPadNumeric = (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal; bool isNumeric = (e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod; if ((isNumeric || isNumPadNumeric) && Keyboard.Modifiers!= ModifierKeys.None) { e.Handled = true; return; } bool isControl = ((Keyboard.Modifiers!= ModifierKeys.None && Keyboard.Modifiers!= ModifierKeys.Shift) || e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Insert || e.Key == Key.Down || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Tab || e.Key == Key.PageDown || e.Key == Key.PageUp || e.Key == Key.Enter || e.Key == Key.Return || e.Key == Key.Escape || e.Key == Key.Home || e.Key == Key.End); e.Handled =!isControl &&!isNumeric &&!isNumPadNumeric; }
How about: protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e) { e.Handled =!AreAllValidNumericChars(e.Text); base.OnPreviewTextInput(e); } private bool AreAllValidNumericChars(string str) { foreach(char c in str) { if(!Char.IsNumber(c)) return false; } return true; }
Numeric Data Entry in WPF How are you handling the entry of numeric values in WPF applications? Without a NumericUpDown control, I've been using a TextBox and handling its PreviewKeyDown event with the code below, but it's pretty ugly. Has anyone found a more graceful way to get numeric data from the user without relying on a third-party control? private void NumericEditPreviewKeyDown(object sender, KeyEventArgs e) { bool isNumPadNumeric = (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal; bool isNumeric = (e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod; if ((isNumeric || isNumPadNumeric) && Keyboard.Modifiers!= ModifierKeys.None) { e.Handled = true; return; } bool isControl = ((Keyboard.Modifiers!= ModifierKeys.None && Keyboard.Modifiers!= ModifierKeys.Shift) || e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Insert || e.Key == Key.Down || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Tab || e.Key == Key.PageDown || e.Key == Key.PageUp || e.Key == Key.Enter || e.Key == Key.Return || e.Key == Key.Escape || e.Key == Key.Home || e.Key == Key.End); e.Handled =!isControl &&!isNumeric &&!isNumPadNumeric; }
TITLE: Numeric Data Entry in WPF QUESTION: How are you handling the entry of numeric values in WPF applications? Without a NumericUpDown control, I've been using a TextBox and handling its PreviewKeyDown event with the code below, but it's pretty ugly. Has anyone found a more graceful way to get numeric data from the user without relying on a third-party control? private void NumericEditPreviewKeyDown(object sender, KeyEventArgs e) { bool isNumPadNumeric = (e.Key >= Key.NumPad0 && e.Key <= Key.NumPad9) || e.Key == Key.Decimal; bool isNumeric = (e.Key >= Key.D0 && e.Key <= Key.D9) || e.Key == Key.OemPeriod; if ((isNumeric || isNumPadNumeric) && Keyboard.Modifiers!= ModifierKeys.None) { e.Handled = true; return; } bool isControl = ((Keyboard.Modifiers!= ModifierKeys.None && Keyboard.Modifiers!= ModifierKeys.Shift) || e.Key == Key.Back || e.Key == Key.Delete || e.Key == Key.Insert || e.Key == Key.Down || e.Key == Key.Left || e.Key == Key.Right || e.Key == Key.Up || e.Key == Key.Tab || e.Key == Key.PageDown || e.Key == Key.PageUp || e.Key == Key.Enter || e.Key == Key.Return || e.Key == Key.Escape || e.Key == Key.Home || e.Key == Key.End); e.Handled =!isControl &&!isNumeric &&!isNumPadNumeric; } ANSWER: How about: protected override void OnPreviewTextInput(System.Windows.Input.TextCompositionEventArgs e) { e.Handled =!AreAllValidNumericChars(e.Text); base.OnPreviewTextInput(e); } private bool AreAllValidNumericChars(string str) { foreach(char c in str) { if(!Char.IsNumber(c)) return false; } return true; }
[ "c#", "wpf" ]
66
57
61,585
17
0
2008-08-08T00:37:55.020000
2008-08-11T13:47:12.253000
5,527
5,532
Is there a real benefit of using J#?
I just saw a comment of suggesting J#, and it made me wonder... is there a real, beneficial use of J# over Java? So, my feeling is that the only reason you would even consider using J# is that management has decreed that the company should jump on the Java bandwagon... and the.NET bandwagon. If you use J#, you are effectively losing the biggest benefit of picking Java... rich cross platform support. Sure there is Mono, but it's not as richly supported or as full featured right? I remember hearing Forms are not fully (perhaps at all) supported. I'm not trying to bash.NET here, I'm just saying, if you are going to go the Microsoft route, why not just use C#? If you are going to go the Java route, why would J# enter the picture? I'm hoping to find some real world cases here, so please especially respond if you've ACTUALLY used J# in a REAL project, and why.
J# is no longer included in VS2008. Unless you already have J# code, you should probably stay away. From j# product page: Since customers have told us that the existing J# feature set largely meets their needs and usage of J# is declining, Microsoft is retiring the Visual J# product and Java Language Conversion Assistant tool to better allocate resources for other customer requirements. The J# language and JLCA tool will not be available in future versions of Visual Studio. To preserve existing customer investments in J#, Microsoft will continue to support the J# and JLCA technology that shipped with Visual Studio 2005 through to 2015 as per our product life-cycle strategy. For more information, see Expanded Microsoft Support Lifecycle Policy for Business & Development Products.
Is there a real benefit of using J#? I just saw a comment of suggesting J#, and it made me wonder... is there a real, beneficial use of J# over Java? So, my feeling is that the only reason you would even consider using J# is that management has decreed that the company should jump on the Java bandwagon... and the.NET bandwagon. If you use J#, you are effectively losing the biggest benefit of picking Java... rich cross platform support. Sure there is Mono, but it's not as richly supported or as full featured right? I remember hearing Forms are not fully (perhaps at all) supported. I'm not trying to bash.NET here, I'm just saying, if you are going to go the Microsoft route, why not just use C#? If you are going to go the Java route, why would J# enter the picture? I'm hoping to find some real world cases here, so please especially respond if you've ACTUALLY used J# in a REAL project, and why.
TITLE: Is there a real benefit of using J#? QUESTION: I just saw a comment of suggesting J#, and it made me wonder... is there a real, beneficial use of J# over Java? So, my feeling is that the only reason you would even consider using J# is that management has decreed that the company should jump on the Java bandwagon... and the.NET bandwagon. If you use J#, you are effectively losing the biggest benefit of picking Java... rich cross platform support. Sure there is Mono, but it's not as richly supported or as full featured right? I remember hearing Forms are not fully (perhaps at all) supported. I'm not trying to bash.NET here, I'm just saying, if you are going to go the Microsoft route, why not just use C#? If you are going to go the Java route, why would J# enter the picture? I'm hoping to find some real world cases here, so please especially respond if you've ACTUALLY used J# in a REAL project, and why. ANSWER: J# is no longer included in VS2008. Unless you already have J# code, you should probably stay away. From j# product page: Since customers have told us that the existing J# feature set largely meets their needs and usage of J# is declining, Microsoft is retiring the Visual J# product and Java Language Conversion Assistant tool to better allocate resources for other customer requirements. The J# language and JLCA tool will not be available in future versions of Visual Studio. To preserve existing customer investments in J#, Microsoft will continue to support the J# and JLCA technology that shipped with Visual Studio 2005 through to 2015 as per our product life-cycle strategy. For more information, see Expanded Microsoft Support Lifecycle Policy for Business & Development Products.
[ "java", "j#" ]
26
22
4,299
8
0
2008-08-08T01:04:02.300000
2008-08-08T01:11:58.680000
5,544
14,474
In ASP.NET MVC I encounter an incorrect type error when rendering a user control with the correct typed object
I encounter an error of the form: "The model item passed into the dictionary is of type FooViewData but this dictionary requires a model item of type bar" even though I am passing in an object of the correct type (bar) for the typed user control.
What @MattMitchell said is probably the reason you're seeing this error. If you want to know why; it is because when you pass null as the controlData parameter when using RenderUserControl(), the framework will try to pass the view data from the current view context onto the user control instead (see UserControlExtensions.DoRendering method in System.Web.Mvc).
In ASP.NET MVC I encounter an incorrect type error when rendering a user control with the correct typed object I encounter an error of the form: "The model item passed into the dictionary is of type FooViewData but this dictionary requires a model item of type bar" even though I am passing in an object of the correct type (bar) for the typed user control.
TITLE: In ASP.NET MVC I encounter an incorrect type error when rendering a user control with the correct typed object QUESTION: I encounter an error of the form: "The model item passed into the dictionary is of type FooViewData but this dictionary requires a model item of type bar" even though I am passing in an object of the correct type (bar) for the typed user control. ANSWER: What @MattMitchell said is probably the reason you're seeing this error. If you want to know why; it is because when you pass null as the controlData parameter when using RenderUserControl(), the framework will try to pass the view data from the current view context onto the user control instead (see UserControlExtensions.DoRendering method in System.Web.Mvc).
[ "asp.net-mvc" ]
4
4
464
2
0
2008-08-08T01:31:21.963000
2008-08-18T11:31:39.730000
5,598
6,100
Document or RPC based web services
My gut feel is that document based web services are preferred in practice - is this other peoples experience? Are they easier to support? (I noted that SharePoint uses Any for the "document type" in its WSDL interface, I guess that makes it Document based). Also - are people offering both WSDL and Rest type services now for the same functionality? WSDL is popular for code generation, but for front ends like PHP and Rails they seem to prefer rest.
Document versus RPC is only a question if you are using SOAP Web Services which require a service description ( WSDL ). RESTful web services do not not use WSDL because the service can't be described by it, and the feeling is that REST is simpler and easier to understand. Some people have proposed WADL as a way to describe REST services. Languages like Python, Ruby and PHP make it easier to work with REST. the WSDL is used to generate C# code (a web service proxy) that can be easily called from a static language. This happens when you add a Service Reference or Web Reference in Visual Studio. Whether you provide SOAP or REST services depends on your user population. Whether the services are to be used over the internet or just inside your organization affects your choice. SOAP may have some features (WS-* standards) that work well for B2B or internal use, but suck for an internet service. Document/literal versus RPC for SOAP services are described on this IBM DevelopWorks article. Document/literal is generally considered the best to use in terms of interoperability (Java to.NET etc). As to whether it is easier to support, that depends on your circumstances. My personal view is that people tend to make this stuff more complicated than it needs to be, and REST's simpler approach is superior.
Document or RPC based web services My gut feel is that document based web services are preferred in practice - is this other peoples experience? Are they easier to support? (I noted that SharePoint uses Any for the "document type" in its WSDL interface, I guess that makes it Document based). Also - are people offering both WSDL and Rest type services now for the same functionality? WSDL is popular for code generation, but for front ends like PHP and Rails they seem to prefer rest.
TITLE: Document or RPC based web services QUESTION: My gut feel is that document based web services are preferred in practice - is this other peoples experience? Are they easier to support? (I noted that SharePoint uses Any for the "document type" in its WSDL interface, I guess that makes it Document based). Also - are people offering both WSDL and Rest type services now for the same functionality? WSDL is popular for code generation, but for front ends like PHP and Rails they seem to prefer rest. ANSWER: Document versus RPC is only a question if you are using SOAP Web Services which require a service description ( WSDL ). RESTful web services do not not use WSDL because the service can't be described by it, and the feeling is that REST is simpler and easier to understand. Some people have proposed WADL as a way to describe REST services. Languages like Python, Ruby and PHP make it easier to work with REST. the WSDL is used to generate C# code (a web service proxy) that can be easily called from a static language. This happens when you add a Service Reference or Web Reference in Visual Studio. Whether you provide SOAP or REST services depends on your user population. Whether the services are to be used over the internet or just inside your organization affects your choice. SOAP may have some features (WS-* standards) that work well for B2B or internal use, but suck for an internet service. Document/literal versus RPC for SOAP services are described on this IBM DevelopWorks article. Document/literal is generally considered the best to use in terms of interoperability (Java to.NET etc). As to whether it is easier to support, that depends on your circumstances. My personal view is that people tend to make this stuff more complicated than it needs to be, and REST's simpler approach is superior.
[ "web-services", "rest", "wsdl" ]
19
30
9,287
3
0
2008-08-08T02:42:48.887000
2008-08-08T15:55:58.517000
5,600
5,607
Tables with no Primary Key
I have several tables whose only unique data is a uniqueidentifier (a Guid) column. Because guids are non-sequential (and they're client-side generated so I can't use newsequentialid()), I have made a non-primary, non-clustered index on this ID field rather than giving the tables a clustered primary key. I'm wondering what the performance implications are for this approach. I've seen some people suggest that tables should have an auto-incrementing ("identity") int as a clustered primary key even if it doesn't have any meaning, as it means that the database engine itself can use that value to quickly look up a row instead of having to use a bookmark. My database is merge-replicated across a bunch of servers, so I've shied away from identity int columns as they're a bit hairy to get right in replication. What are your thoughts? Should tables have primary keys? Or is it ok to not have any clustered indexes if there are no sensible columns to index that way?
When dealing with indexes, you have to determine what your table is going to be used for. If you are primarily inserting 1000 rows a second and not doing any querying, then a clustered index is a hit to performance. If you are doing 1000 queries a second, then not having an index will lead to very bad performance. The best thing to do when trying to tune queries/indexes is to use the Query Plan Analyzer and SQL Profiler in SQL Server. This will show you where you are running into costly table scans or other performance blockers. As for the GUID vs ID argument, you can find people online that swear by both. I have always been taught to use GUIDs unless I have a really good reason not to. Jeff has a good post that talks about the reasons for using GUIDs: https://blog.codinghorror.com/primary-keys-ids-versus-guids/. As with most anything development related, if you are looking to improve performance there is not one, single right answer. It really depends on what you are trying to accomplish and how you are implementing the solution. The only true answer is to test, test, and test again against performance metrics to ensure that you are meeting your goals. [Edit] @Matt, after doing some more research on the GUID/ID debate I came across this post. Like I mentioned before, there is not a true right or wrong answer. It depends on your specific implementation needs. But these are some pretty valid reasons to use GUIDs as the primary key: For example, there is an issue known as a "hotspot", where certain pages of data in a table are under relatively high currency contention. Basically, what happens is most of the traffic on a table (and hence page-level locks) occurs on a small area of the table, towards the end. New records will always go to this hotspot, because IDENTITY is a sequential number generator. These inserts are troublesome because they require Exlusive page lock on the page they are added to (the hotspot). This effectively serializes all inserts to a table thanks to the page locking mechanism. NewID() on the other hand does not suffer from hotspots. Values generated using the NewID() function are only sequential for short bursts of inserts (where the function is being called very quickly, such as during a multi-row insert), which causes the inserted rows to spread randomly throughout the table's data pages instead of all at the end - thus eliminating a hotspot from inserts. Also, because the inserts are randomly distributed, the chance of page splits is greatly reduced. While a page split here and there isnt too bad, the effects do add up quickly. With IDENTITY, page Fill Factor is pretty useless as a tuning mechanism and might as well be set to 100% - rows will never be inserted in any page but the last one. With NewID(), you can actually make use of Fill Factor as a performance-enabling tool. You can set Fill Factor to a level that approximates estimated volume growth between index rebuilds, and then schedule the rebuilds during off-peak hours using dbcc reindex. This effectively delays the performance hits of page splits until off-peak times. If you even think you might need to enable replication for the table in question - then you might as well make the PK a uniqueidentifier and flag the guid field as ROWGUIDCOL. Replication will require a uniquely valued guid field with this attribute, and it will add one if none exists. If a suitable field exists, then it will just use the one thats there. Yet another huge benefit for using GUIDs for PKs is the fact that the value is indeed guaranteed unique - not just among all values generated by this server, but all values generated by all computers - whether it be your db server, web server, app server, or client machine. Pretty much every modern language has the capability of generating a valid guid now - in.NET you can use System.Guid.NewGuid. This is VERY handy when dealing with cached master-detail datasets in particular. You dont have to employ crazy temporary keying schemes just to relate your records together before they are committed. You just fetch a perfectly valid new Guid from the operating system for each new record's permanent key value at the time the record is created. http://forums.asp.net/t/264350.aspx
Tables with no Primary Key I have several tables whose only unique data is a uniqueidentifier (a Guid) column. Because guids are non-sequential (and they're client-side generated so I can't use newsequentialid()), I have made a non-primary, non-clustered index on this ID field rather than giving the tables a clustered primary key. I'm wondering what the performance implications are for this approach. I've seen some people suggest that tables should have an auto-incrementing ("identity") int as a clustered primary key even if it doesn't have any meaning, as it means that the database engine itself can use that value to quickly look up a row instead of having to use a bookmark. My database is merge-replicated across a bunch of servers, so I've shied away from identity int columns as they're a bit hairy to get right in replication. What are your thoughts? Should tables have primary keys? Or is it ok to not have any clustered indexes if there are no sensible columns to index that way?
TITLE: Tables with no Primary Key QUESTION: I have several tables whose only unique data is a uniqueidentifier (a Guid) column. Because guids are non-sequential (and they're client-side generated so I can't use newsequentialid()), I have made a non-primary, non-clustered index on this ID field rather than giving the tables a clustered primary key. I'm wondering what the performance implications are for this approach. I've seen some people suggest that tables should have an auto-incrementing ("identity") int as a clustered primary key even if it doesn't have any meaning, as it means that the database engine itself can use that value to quickly look up a row instead of having to use a bookmark. My database is merge-replicated across a bunch of servers, so I've shied away from identity int columns as they're a bit hairy to get right in replication. What are your thoughts? Should tables have primary keys? Or is it ok to not have any clustered indexes if there are no sensible columns to index that way? ANSWER: When dealing with indexes, you have to determine what your table is going to be used for. If you are primarily inserting 1000 rows a second and not doing any querying, then a clustered index is a hit to performance. If you are doing 1000 queries a second, then not having an index will lead to very bad performance. The best thing to do when trying to tune queries/indexes is to use the Query Plan Analyzer and SQL Profiler in SQL Server. This will show you where you are running into costly table scans or other performance blockers. As for the GUID vs ID argument, you can find people online that swear by both. I have always been taught to use GUIDs unless I have a really good reason not to. Jeff has a good post that talks about the reasons for using GUIDs: https://blog.codinghorror.com/primary-keys-ids-versus-guids/. As with most anything development related, if you are looking to improve performance there is not one, single right answer. It really depends on what you are trying to accomplish and how you are implementing the solution. The only true answer is to test, test, and test again against performance metrics to ensure that you are meeting your goals. [Edit] @Matt, after doing some more research on the GUID/ID debate I came across this post. Like I mentioned before, there is not a true right or wrong answer. It depends on your specific implementation needs. But these are some pretty valid reasons to use GUIDs as the primary key: For example, there is an issue known as a "hotspot", where certain pages of data in a table are under relatively high currency contention. Basically, what happens is most of the traffic on a table (and hence page-level locks) occurs on a small area of the table, towards the end. New records will always go to this hotspot, because IDENTITY is a sequential number generator. These inserts are troublesome because they require Exlusive page lock on the page they are added to (the hotspot). This effectively serializes all inserts to a table thanks to the page locking mechanism. NewID() on the other hand does not suffer from hotspots. Values generated using the NewID() function are only sequential for short bursts of inserts (where the function is being called very quickly, such as during a multi-row insert), which causes the inserted rows to spread randomly throughout the table's data pages instead of all at the end - thus eliminating a hotspot from inserts. Also, because the inserts are randomly distributed, the chance of page splits is greatly reduced. While a page split here and there isnt too bad, the effects do add up quickly. With IDENTITY, page Fill Factor is pretty useless as a tuning mechanism and might as well be set to 100% - rows will never be inserted in any page but the last one. With NewID(), you can actually make use of Fill Factor as a performance-enabling tool. You can set Fill Factor to a level that approximates estimated volume growth between index rebuilds, and then schedule the rebuilds during off-peak hours using dbcc reindex. This effectively delays the performance hits of page splits until off-peak times. If you even think you might need to enable replication for the table in question - then you might as well make the PK a uniqueidentifier and flag the guid field as ROWGUIDCOL. Replication will require a uniquely valued guid field with this attribute, and it will add one if none exists. If a suitable field exists, then it will just use the one thats there. Yet another huge benefit for using GUIDs for PKs is the fact that the value is indeed guaranteed unique - not just among all values generated by this server, but all values generated by all computers - whether it be your db server, web server, app server, or client machine. Pretty much every modern language has the capability of generating a valid guid now - in.NET you can use System.Guid.NewGuid. This is VERY handy when dealing with cached master-detail datasets in particular. You dont have to employ crazy temporary keying schemes just to relate your records together before they are committed. You just fetch a perfectly valid new Guid from the operating system for each new record's permanent key value at the time the record is created. http://forums.asp.net/t/264350.aspx
[ "sql-server", "indexing" ]
42
34
38,173
7
0
2008-08-08T02:47:15.620000
2008-08-08T03:04:29.047000
5,611
5,820
Better Random Generating PHP
I know that just using rand() is predictable, if you know what you're doing, and have access to the server. I have a project that is highly dependent upon choosing a random number that is as unpredictable as possible. So I'm looking for suggestions, either other built-in functions or user functions, that can generate a better random number. I used this to do a little test: $i = 0; while($i < 10000){ $rand = rand(0, 100); if(!isset($array[$rand])){ $array[$rand] = 1; } else { $array[$rand]++; } sort($array); $i++; } I found the results to be evenly distributed, and there is an odd pattern to the number of times each number is generated.
Adding, multiplying, or truncating a poor random source will give you a poor random result. See Introduction to Randomness and Random Numbers for an explanation. You're right about PHP rand() function. See the second figure on Statistical Analysis for a striking illustration. (The first figure is striking, but it's been drawn by Scott Adams, not plotted with rand()). One solution is to use a true random generator such as random.org. Another, if you're on Linux/BSD/etc. is to use /dev/random. If the randomness is mission critical, you will have to use a hardware random generator.
Better Random Generating PHP I know that just using rand() is predictable, if you know what you're doing, and have access to the server. I have a project that is highly dependent upon choosing a random number that is as unpredictable as possible. So I'm looking for suggestions, either other built-in functions or user functions, that can generate a better random number. I used this to do a little test: $i = 0; while($i < 10000){ $rand = rand(0, 100); if(!isset($array[$rand])){ $array[$rand] = 1; } else { $array[$rand]++; } sort($array); $i++; } I found the results to be evenly distributed, and there is an odd pattern to the number of times each number is generated.
TITLE: Better Random Generating PHP QUESTION: I know that just using rand() is predictable, if you know what you're doing, and have access to the server. I have a project that is highly dependent upon choosing a random number that is as unpredictable as possible. So I'm looking for suggestions, either other built-in functions or user functions, that can generate a better random number. I used this to do a little test: $i = 0; while($i < 10000){ $rand = rand(0, 100); if(!isset($array[$rand])){ $array[$rand] = 1; } else { $array[$rand]++; } sort($array); $i++; } I found the results to be evenly distributed, and there is an odd pattern to the number of times each number is generated. ANSWER: Adding, multiplying, or truncating a poor random source will give you a poor random result. See Introduction to Randomness and Random Numbers for an explanation. You're right about PHP rand() function. See the second figure on Statistical Analysis for a striking illustration. (The first figure is striking, but it's been drawn by Scott Adams, not plotted with rand()). One solution is to use a true random generator such as random.org. Another, if you're on Linux/BSD/etc. is to use /dev/random. If the randomness is mission critical, you will have to use a hardware random generator.
[ "php", "security", "random" ]
22
22
8,416
6
0
2008-08-08T03:18:56.397000
2008-08-08T11:48:42.400000
5,619
5,626
Debugging: IE6 + SSL + AJAX + post form = 404 error
The Setting: The program in question tries to post form data via an AJAX call to a target procedure contained in the same package as the caller. This is done for a site that uses a secure connection (HTTPS). The technology used here is PLSQL and the DOJO JavaScript library. The development tool is basically a text editor. Code Snippet: > function testPost() { >> dojo.xhrPost( { url: ''dr_tm_w_0120.test_post'', form: ''orgForm'', load: testPostXHRCallback, error: testPostXHRError }); } > function testPostXHRCallback(data,ioArgs) { >> alert(''post callback''); try{ dojo.byId("messageDiv").innerHTML = data; } catch(ex){ if(ex.name == "TypeError") { alert("A type error occurred."); } } return data; } > function testPostXHRError(data, ioArgs) { >> alert(data); alert(''Error when retrieving data from the server!''); return data; } The Problem: When using IE6 (which the entire user-base uses), the response sent back from the server is a 404 error. Observations: The program works fine in Firefox. The calling procedure cannot target any procedures within the same package. The calling procedure can target outside sites (both http, https). The other AJAX calls in the package that are not posts of form data work fine. I've searched the internets and consulted with senior-skilled team members and haven't discovered anything that satisfactorily addresses the issue. *Tried Q&A over at Dojo support forums. The Questions: What troubleshooting techniques do you recommend? What troubleshooting tools do you recommend for HTTPS analyzing? Any hypotheses on what the issue might be? Any ideas for workarounds that aren't total (bad) hacks? Ed. The Solution lomaxx, thx for the fiddler tip. you have no idea how awesome it was to get that and use it as a debugging tool. after starting it up this is what i found and how i fixed it (at least in the short term): > ef Fri, 8 Aug 2008 14:01:26 GMT dr_tm_w_0120.test_post: SIGNATURE (parameter names) MISMATCH VARIABLES IN FORM NOT IN PROCEDURE: SO1_DISPLAYED_,PO1_DISPLAYED_,RWA2_DISPLAYED_,DD1_DISPLAYED_ NON-DEFAULT VARIABLES IN PROCEDURE NOT IN FORM: 0 After seeing that message from the server, I kicked around Fiddler a bit more to see what else I could learn from it. Found that there's a WebForms tab that shows the values in the web form. Wouldn't you know it, the " xxx_DISPLAYED_ " fields above were in it. I don't really understand yet why these fields exist, because I didn't create them explicitly in the web PLSQL code. But I do understand now that the target procedure has to include them as parameters to work correctly. Again, this is only in the case of IE6 for me, as Firefox worked fine. Well, that the short term answer and hack to fix it. Hopefully, a little more work in this area will lead to a better understanding of the fundamentals going on here.
First port of call would be to fire up Fiddler and analyze the data going to and from the browser. Take a look at the headers, the url actually being called and the params (if any) being passed to the AJAX method and see if it all looks good before getting to the server. If that all looks ok, is there any way you can verify it's actually hitting the server via logging, or tracing in the AJAX method? ed: another thing I would try is rig up a test page to call the AJAX method on the server using a non-ajax based call and analyze the traffic in fiddler and compare the two.
Debugging: IE6 + SSL + AJAX + post form = 404 error The Setting: The program in question tries to post form data via an AJAX call to a target procedure contained in the same package as the caller. This is done for a site that uses a secure connection (HTTPS). The technology used here is PLSQL and the DOJO JavaScript library. The development tool is basically a text editor. Code Snippet: > function testPost() { >> dojo.xhrPost( { url: ''dr_tm_w_0120.test_post'', form: ''orgForm'', load: testPostXHRCallback, error: testPostXHRError }); } > function testPostXHRCallback(data,ioArgs) { >> alert(''post callback''); try{ dojo.byId("messageDiv").innerHTML = data; } catch(ex){ if(ex.name == "TypeError") { alert("A type error occurred."); } } return data; } > function testPostXHRError(data, ioArgs) { >> alert(data); alert(''Error when retrieving data from the server!''); return data; } The Problem: When using IE6 (which the entire user-base uses), the response sent back from the server is a 404 error. Observations: The program works fine in Firefox. The calling procedure cannot target any procedures within the same package. The calling procedure can target outside sites (both http, https). The other AJAX calls in the package that are not posts of form data work fine. I've searched the internets and consulted with senior-skilled team members and haven't discovered anything that satisfactorily addresses the issue. *Tried Q&A over at Dojo support forums. The Questions: What troubleshooting techniques do you recommend? What troubleshooting tools do you recommend for HTTPS analyzing? Any hypotheses on what the issue might be? Any ideas for workarounds that aren't total (bad) hacks? Ed. The Solution lomaxx, thx for the fiddler tip. you have no idea how awesome it was to get that and use it as a debugging tool. after starting it up this is what i found and how i fixed it (at least in the short term): > ef Fri, 8 Aug 2008 14:01:26 GMT dr_tm_w_0120.test_post: SIGNATURE (parameter names) MISMATCH VARIABLES IN FORM NOT IN PROCEDURE: SO1_DISPLAYED_,PO1_DISPLAYED_,RWA2_DISPLAYED_,DD1_DISPLAYED_ NON-DEFAULT VARIABLES IN PROCEDURE NOT IN FORM: 0 After seeing that message from the server, I kicked around Fiddler a bit more to see what else I could learn from it. Found that there's a WebForms tab that shows the values in the web form. Wouldn't you know it, the " xxx_DISPLAYED_ " fields above were in it. I don't really understand yet why these fields exist, because I didn't create them explicitly in the web PLSQL code. But I do understand now that the target procedure has to include them as parameters to work correctly. Again, this is only in the case of IE6 for me, as Firefox worked fine. Well, that the short term answer and hack to fix it. Hopefully, a little more work in this area will lead to a better understanding of the fundamentals going on here.
TITLE: Debugging: IE6 + SSL + AJAX + post form = 404 error QUESTION: The Setting: The program in question tries to post form data via an AJAX call to a target procedure contained in the same package as the caller. This is done for a site that uses a secure connection (HTTPS). The technology used here is PLSQL and the DOJO JavaScript library. The development tool is basically a text editor. Code Snippet: > function testPost() { >> dojo.xhrPost( { url: ''dr_tm_w_0120.test_post'', form: ''orgForm'', load: testPostXHRCallback, error: testPostXHRError }); } > function testPostXHRCallback(data,ioArgs) { >> alert(''post callback''); try{ dojo.byId("messageDiv").innerHTML = data; } catch(ex){ if(ex.name == "TypeError") { alert("A type error occurred."); } } return data; } > function testPostXHRError(data, ioArgs) { >> alert(data); alert(''Error when retrieving data from the server!''); return data; } The Problem: When using IE6 (which the entire user-base uses), the response sent back from the server is a 404 error. Observations: The program works fine in Firefox. The calling procedure cannot target any procedures within the same package. The calling procedure can target outside sites (both http, https). The other AJAX calls in the package that are not posts of form data work fine. I've searched the internets and consulted with senior-skilled team members and haven't discovered anything that satisfactorily addresses the issue. *Tried Q&A over at Dojo support forums. The Questions: What troubleshooting techniques do you recommend? What troubleshooting tools do you recommend for HTTPS analyzing? Any hypotheses on what the issue might be? Any ideas for workarounds that aren't total (bad) hacks? Ed. The Solution lomaxx, thx for the fiddler tip. you have no idea how awesome it was to get that and use it as a debugging tool. after starting it up this is what i found and how i fixed it (at least in the short term): > ef Fri, 8 Aug 2008 14:01:26 GMT dr_tm_w_0120.test_post: SIGNATURE (parameter names) MISMATCH VARIABLES IN FORM NOT IN PROCEDURE: SO1_DISPLAYED_,PO1_DISPLAYED_,RWA2_DISPLAYED_,DD1_DISPLAYED_ NON-DEFAULT VARIABLES IN PROCEDURE NOT IN FORM: 0 After seeing that message from the server, I kicked around Fiddler a bit more to see what else I could learn from it. Found that there's a WebForms tab that shows the values in the web form. Wouldn't you know it, the " xxx_DISPLAYED_ " fields above were in it. I don't really understand yet why these fields exist, because I didn't create them explicitly in the web PLSQL code. But I do understand now that the target procedure has to include them as parameters to work correctly. Again, this is only in the case of IE6 for me, as Firefox worked fine. Well, that the short term answer and hack to fix it. Hopefully, a little more work in this area will lead to a better understanding of the fundamentals going on here. ANSWER: First port of call would be to fire up Fiddler and analyze the data going to and from the browser. Take a look at the headers, the url actually being called and the params (if any) being passed to the AJAX method and see if it all looks good before getting to the server. If that all looks ok, is there any way you can verify it's actually hitting the server via logging, or tracing in the AJAX method? ed: another thing I would try is rig up a test page to call the AJAX method on the server using a non-ajax based call and analyze the traffic in fiddler and compare the two.
[ "ajax", "debugging", "internet-explorer", "ssl", "internet-explorer-6" ]
6
4
3,695
1
0
2008-08-08T03:38:57.747000
2008-08-08T03:47:22.703000
5,628
30,573
Is there a way to include a fragment identifier when using Asp.Net MVC ActionLink, RedirectToAction, etc.?
I want some links to include a fragment identifier. Like some of the URLs on this site: Debugging: IE6 + SSL + AJAX + post form = 404 error #5626 Is there a way to do this with any of the built-in methods in MVC? Or would I have to roll my own HTML helpers?
We're looking at including support for this in our next release.
Is there a way to include a fragment identifier when using Asp.Net MVC ActionLink, RedirectToAction, etc.? I want some links to include a fragment identifier. Like some of the URLs on this site: Debugging: IE6 + SSL + AJAX + post form = 404 error #5626 Is there a way to do this with any of the built-in methods in MVC? Or would I have to roll my own HTML helpers?
TITLE: Is there a way to include a fragment identifier when using Asp.Net MVC ActionLink, RedirectToAction, etc.? QUESTION: I want some links to include a fragment identifier. Like some of the URLs on this site: Debugging: IE6 + SSL + AJAX + post form = 404 error #5626 Is there a way to do this with any of the built-in methods in MVC? Or would I have to roll my own HTML helpers? ANSWER: We're looking at including support for this in our next release.
[ "asp.net-mvc" ]
22
6
4,975
7
0
2008-08-08T03:54:08.090000
2008-08-27T16:18:45.187000
5,629
14,192
Any reason not to start using the HTML 5 doctype?
It is supposed to be backwards compatible with HTML4 and XHTML. John Resig posted about some of the benefits. As long as we don't use any of the new and not supported yet features, would there be any downside to start building sites with this doctype?
Well consider this: When serving as text/html, all you need a doctype for is to trigger standards mode. Beyond that, the doctype does nothing as far as browsers are concerned. When serving as text/html, whether you use XHTML markup or HTML markup, it's treated by browsers as HTML. So, really it comes down to using the shortest doctype that triggers standards mode ( ) and using HTML markup that produces the correct result in browsers. The rest is about conforming, validation and markup prerference. With that said, using now and trying to make your markup conform to HTML5 is not a bad idea as long as you stick to stable features that work in browsers now. You wouldn't use anything in HTML4 or XHTML 1.x that doesn't work in browsers, would you? In other words, you use with HTML4-like markup while honoring things that have been clarified in HTML5. HTML5 is about browser compatibility after all. The downside to using HTML5 now is that the spec can change quite often. This makes it important for you to keep up with the spec as it actively changes. Also http://validator.nu/ might not always be up-to-date, but http://validator.w3.org/ isn't always up-to-date either, so don't let that stop you. Of course, if you want to use XHTML 1.0 markup and conform to XHTML 1.0, then you shouldn't use. Personally, I always use for HTML.
Any reason not to start using the HTML 5 doctype? It is supposed to be backwards compatible with HTML4 and XHTML. John Resig posted about some of the benefits. As long as we don't use any of the new and not supported yet features, would there be any downside to start building sites with this doctype?
TITLE: Any reason not to start using the HTML 5 doctype? QUESTION: It is supposed to be backwards compatible with HTML4 and XHTML. John Resig posted about some of the benefits. As long as we don't use any of the new and not supported yet features, would there be any downside to start building sites with this doctype? ANSWER: Well consider this: When serving as text/html, all you need a doctype for is to trigger standards mode. Beyond that, the doctype does nothing as far as browsers are concerned. When serving as text/html, whether you use XHTML markup or HTML markup, it's treated by browsers as HTML. So, really it comes down to using the shortest doctype that triggers standards mode ( ) and using HTML markup that produces the correct result in browsers. The rest is about conforming, validation and markup prerference. With that said, using now and trying to make your markup conform to HTML5 is not a bad idea as long as you stick to stable features that work in browsers now. You wouldn't use anything in HTML4 or XHTML 1.x that doesn't work in browsers, would you? In other words, you use with HTML4-like markup while honoring things that have been clarified in HTML5. HTML5 is about browser compatibility after all. The downside to using HTML5 now is that the spec can change quite often. This makes it important for you to keep up with the spec as it actively changes. Also http://validator.nu/ might not always be up-to-date, but http://validator.w3.org/ isn't always up-to-date either, so don't let that stop you. Of course, if you want to use XHTML 1.0 markup and conform to XHTML 1.0, then you shouldn't use. Personally, I always use for HTML.
[ "html", "doctype" ]
132
143
72,132
10
0
2008-08-08T04:03:10.583000
2008-08-18T04:42:59.413000
5,649
5,756
x86 Assembly on a Mac
Does anyone know of any good tools (I'm looking for IDEs) to write assembly on the Mac. Xcode is a little cumbersome to me. Also, on the Intel Macs, can I use generic x86 asm? Or is there a modified instruction set? Any information about post Intel. Also: I know that on windows, asm can run in an emulated environment created by the OS to let the code think it's running on its own dedicated machine. Does OS X provide the same thing?
After installing any version of Xcode targeting Intel-based Macs, you should be able to write assembly code. Xcode is a suite of tools, only one of which is the IDE, so you don't have to use it if you don't want to. (That said, if there are specific things you find clunky, please file a bug at Apple's bug reporter - every bug goes to engineering.) Furthermore, installing Xcode will install both the Netwide Assembler (NASM) and the GNU Assembler (GAS); that will let you use whatever assembly syntax you're most comfortable with. You'll also want to take a look at the Compiler & Debugging Guides, because those document the calling conventions used for the various architectures that Mac OS X runs on, as well as how the binary format and the loader work. The IA-32 (x86-32) calling conventions in particular may be slightly different from what you're used to. Another thing to keep in mind is that the system call interface on Mac OS X is different from what you might be used to on DOS/Windows, Linux, or the other BSD flavors. System calls aren't considered a stable API on Mac OS X; instead, you always go through libSystem. That will ensure you're writing code that's portable from one release of the OS to the next. Finally, keep in mind that Mac OS X runs across a pretty wide array of hardware - everything from the 32-bit Core Single through the high-end quad-core Xeon. By coding in assembly you might not be optimizing as much as you think; what's optimal on one machine may be pessimal on another. Apple regularly measures its compilers and tunes their output with the "-Os" optimization flag to be decent across its line, and there are extensive vector/matrix-processing libraries that you can use to get high performance with hand-tuned CPU-specific implementations. Going to assembly for fun is great. Going to assembly for speed is not for the faint of heart these days.
x86 Assembly on a Mac Does anyone know of any good tools (I'm looking for IDEs) to write assembly on the Mac. Xcode is a little cumbersome to me. Also, on the Intel Macs, can I use generic x86 asm? Or is there a modified instruction set? Any information about post Intel. Also: I know that on windows, asm can run in an emulated environment created by the OS to let the code think it's running on its own dedicated machine. Does OS X provide the same thing?
TITLE: x86 Assembly on a Mac QUESTION: Does anyone know of any good tools (I'm looking for IDEs) to write assembly on the Mac. Xcode is a little cumbersome to me. Also, on the Intel Macs, can I use generic x86 asm? Or is there a modified instruction set? Any information about post Intel. Also: I know that on windows, asm can run in an emulated environment created by the OS to let the code think it's running on its own dedicated machine. Does OS X provide the same thing? ANSWER: After installing any version of Xcode targeting Intel-based Macs, you should be able to write assembly code. Xcode is a suite of tools, only one of which is the IDE, so you don't have to use it if you don't want to. (That said, if there are specific things you find clunky, please file a bug at Apple's bug reporter - every bug goes to engineering.) Furthermore, installing Xcode will install both the Netwide Assembler (NASM) and the GNU Assembler (GAS); that will let you use whatever assembly syntax you're most comfortable with. You'll also want to take a look at the Compiler & Debugging Guides, because those document the calling conventions used for the various architectures that Mac OS X runs on, as well as how the binary format and the loader work. The IA-32 (x86-32) calling conventions in particular may be slightly different from what you're used to. Another thing to keep in mind is that the system call interface on Mac OS X is different from what you might be used to on DOS/Windows, Linux, or the other BSD flavors. System calls aren't considered a stable API on Mac OS X; instead, you always go through libSystem. That will ensure you're writing code that's portable from one release of the OS to the next. Finally, keep in mind that Mac OS X runs across a pretty wide array of hardware - everything from the 32-bit Core Single through the high-end quad-core Xeon. By coding in assembly you might not be optimizing as much as you think; what's optimal on one machine may be pessimal on another. Apple regularly measures its compilers and tunes their output with the "-Os" optimization flag to be decent across its line, and there are extensive vector/matrix-processing libraries that you can use to get high performance with hand-tuned CPU-specific implementations. Going to assembly for fun is great. Going to assembly for speed is not for the faint of heart these days.
[ "xcode", "macos", "x86", "assembly" ]
71
86
125,783
7
0
2008-08-08T04:25:11.630000
2008-08-08T07:07:10.540000
5,667
80,353
Sleep from within an Informix SPL procedure
What's the best way to do the semantic equivalent of the traditional sleep() system call from within an Informix SPL routine? In other words, simply "pause" for N seconds (or milliseconds or whatever, but seconds are fine). I'm looking for a solution that does not involve linking some new (perhaps written by me) C code or other library into the Informix server. This has to be something I can do purely from SPL. A solution for IDS 10 or 11 would be fine. @RET - The "obvious" answer wasn't obvious to me! I didn't know about the SYSTEM command. Thank you! (And yes, I'm the guy you think I am.) Yes, it's for debugging purposes only. Unfortunately, CURRENT within an SPL will always return the same value, set at the entry to the call: "any call to CURRENT from inside the SPL function that an EXECUTE FUNCTION (or EXECUTE PROCEDURE) statement invokes returns the value of the system clock when the SPL function starts." — IBM Informix Guide to SQL Wrapping CURRENT in its own subroutine does not help. You do get a different answer on the first call to your wrapper (provided you're using YEAR TO FRACTION(5) or some other type with high enough resolution to show the the difference) but then you get that same value back on every single subsequent call, which ensures that any sort of loop will never terminate.
There must be some good reason you're not wanting the obvious answer: SYSTEM "sleep 5". If all you're wanting is for the SPL to pause while you check various values etc, here are a couple of thoughts (all of which are utter hacks, of course): Make the TRACE FILE a named pipe (assuming Unix back-end), so it blocks until you choose to read from it, or Create another table that your SPL polls for a particular entry from a WHILE loop, and insert said row from elsewhere (horribly inefficient) Make SET LOCK MODE your friend: execute "SET LOCK MODE TO WAIT n" and deliberately requery a table you're already holding a cursor open on. You'll need to wrap this in an EXCEPTION handler, of course. Hope that is some help (and if you're the same JS of Ars and Rose::DB fame, it's the least I could do;-)
Sleep from within an Informix SPL procedure What's the best way to do the semantic equivalent of the traditional sleep() system call from within an Informix SPL routine? In other words, simply "pause" for N seconds (or milliseconds or whatever, but seconds are fine). I'm looking for a solution that does not involve linking some new (perhaps written by me) C code or other library into the Informix server. This has to be something I can do purely from SPL. A solution for IDS 10 or 11 would be fine. @RET - The "obvious" answer wasn't obvious to me! I didn't know about the SYSTEM command. Thank you! (And yes, I'm the guy you think I am.) Yes, it's for debugging purposes only. Unfortunately, CURRENT within an SPL will always return the same value, set at the entry to the call: "any call to CURRENT from inside the SPL function that an EXECUTE FUNCTION (or EXECUTE PROCEDURE) statement invokes returns the value of the system clock when the SPL function starts." — IBM Informix Guide to SQL Wrapping CURRENT in its own subroutine does not help. You do get a different answer on the first call to your wrapper (provided you're using YEAR TO FRACTION(5) or some other type with high enough resolution to show the the difference) but then you get that same value back on every single subsequent call, which ensures that any sort of loop will never terminate.
TITLE: Sleep from within an Informix SPL procedure QUESTION: What's the best way to do the semantic equivalent of the traditional sleep() system call from within an Informix SPL routine? In other words, simply "pause" for N seconds (or milliseconds or whatever, but seconds are fine). I'm looking for a solution that does not involve linking some new (perhaps written by me) C code or other library into the Informix server. This has to be something I can do purely from SPL. A solution for IDS 10 or 11 would be fine. @RET - The "obvious" answer wasn't obvious to me! I didn't know about the SYSTEM command. Thank you! (And yes, I'm the guy you think I am.) Yes, it's for debugging purposes only. Unfortunately, CURRENT within an SPL will always return the same value, set at the entry to the call: "any call to CURRENT from inside the SPL function that an EXECUTE FUNCTION (or EXECUTE PROCEDURE) statement invokes returns the value of the system clock when the SPL function starts." — IBM Informix Guide to SQL Wrapping CURRENT in its own subroutine does not help. You do get a different answer on the first call to your wrapper (provided you're using YEAR TO FRACTION(5) or some other type with high enough resolution to show the the difference) but then you get that same value back on every single subsequent call, which ensures that any sort of loop will never terminate. ANSWER: There must be some good reason you're not wanting the obvious answer: SYSTEM "sleep 5". If all you're wanting is for the SPL to pause while you check various values etc, here are a couple of thoughts (all of which are utter hacks, of course): Make the TRACE FILE a named pipe (assuming Unix back-end), so it blocks until you choose to read from it, or Create another table that your SPL polls for a particular entry from a WHILE loop, and insert said row from elsewhere (horribly inefficient) Make SET LOCK MODE your friend: execute "SET LOCK MODE TO WAIT n" and deliberately requery a table you're already holding a cursor open on. You'll need to wrap this in an EXCEPTION handler, of course. Hope that is some help (and if you're the same JS of Ars and Rose::DB fame, it's the least I could do;-)
[ "informix", "spl" ]
4
2
5,318
4
0
2008-08-08T04:36:30.593000
2008-09-17T05:45:52.350000
5,682
5,693
Is it just me, or are characters being rendered incorrectly more lately?
I'm not sure if it's my system, although I haven't done anything unusual with it, but I've started noticing incorrectly rendered characters popping up in web pages, text-files, like this: http://www.kbssource.com/strange-characters.gif I have a hunch it's a related to the fairly recent trend to use unicode for everything, which is a good thing I think, combined with fonts that don't support all possible characters. So, does anyone know what's causing these blips (am I right?), and how do I stop this showing up in my own content?
It appears that for this particular author, the text was edited in some editor that assumed it wasn't UTF8, and then re-wrote it out in UTF8. I'm basing this off the fact that if I tell my browser to interpret the page as different common encodings, none make it display correctly. This tells me that some conversion was done at some point improperly. The only problem with UTF8 is that there isn't a standardized way to recognize that a file is UTF8, and until all editors are standardizing on UTF8, there will still be conversion errors. For other unicode variants, a Byte Order Mark (BOM) is fairly standard to help identify a file, but BOMs in UTF8 files are pretty rare. To keep it from showing up in your content, make sure you're always using unicode-aware editors, and make sure that you always open your files with the proper encodings. It's a pain, unfortunately, and errors will occasionally crop up. The key is just catching them early so that you can undo it or make a few edits.
Is it just me, or are characters being rendered incorrectly more lately? I'm not sure if it's my system, although I haven't done anything unusual with it, but I've started noticing incorrectly rendered characters popping up in web pages, text-files, like this: http://www.kbssource.com/strange-characters.gif I have a hunch it's a related to the fairly recent trend to use unicode for everything, which is a good thing I think, combined with fonts that don't support all possible characters. So, does anyone know what's causing these blips (am I right?), and how do I stop this showing up in my own content?
TITLE: Is it just me, or are characters being rendered incorrectly more lately? QUESTION: I'm not sure if it's my system, although I haven't done anything unusual with it, but I've started noticing incorrectly rendered characters popping up in web pages, text-files, like this: http://www.kbssource.com/strange-characters.gif I have a hunch it's a related to the fairly recent trend to use unicode for everything, which is a good thing I think, combined with fonts that don't support all possible characters. So, does anyone know what's causing these blips (am I right?), and how do I stop this showing up in my own content? ANSWER: It appears that for this particular author, the text was edited in some editor that assumed it wasn't UTF8, and then re-wrote it out in UTF8. I'm basing this off the fact that if I tell my browser to interpret the page as different common encodings, none make it display correctly. This tells me that some conversion was done at some point improperly. The only problem with UTF8 is that there isn't a standardized way to recognize that a file is UTF8, and until all editors are standardizing on UTF8, there will still be conversion errors. For other unicode variants, a Byte Order Mark (BOM) is fairly standard to help identify a file, but BOMs in UTF8 files are pretty rare. To keep it from showing up in your content, make sure you're always using unicode-aware editors, and make sure that you always open your files with the proper encodings. It's a pain, unfortunately, and errors will occasionally crop up. The key is just catching them early so that you can undo it or make a few edits.
[ "unicode", "utf-8", "fonts" ]
2
2
699
3
0
2008-08-08T04:51:27.973000
2008-08-08T05:08:02.807000
5,690
5,699
MVC Preview 4 - No route in the route table matches the supplied values
I have a route that I am calling through a RedirectToRoute like this: return this.RedirectToRoute("Super-SuperRoute", new { year = selectedYear }); I have also tried: return this.RedirectToRoute("Super-SuperRoute", new { controller = "Super", action = "SuperRoute", id = "RouteTopic", year = selectedYear }); The route in the global.asax is like this: routes.MapRoute( "Super-SuperRoute", // Route name "Super.mvc/SuperRoute/{year}", // URL with parameters new { controller = "Super", action = "SuperRoute", id = "RouteTopic" } // Parameter defaults ); So why do I get the error: "No route in the route table matches the supplied values."? I saw that the type of selectedYear was var. When I tried to convert to int with int.Parse I realised that selectedYear was actually null, which would explain the problems. I guess next time I'll pay more attention to the values of the variables at a breakpoint:)
What type is selectedYear? A DateTime? If so then you might need to convert to a string.
MVC Preview 4 - No route in the route table matches the supplied values I have a route that I am calling through a RedirectToRoute like this: return this.RedirectToRoute("Super-SuperRoute", new { year = selectedYear }); I have also tried: return this.RedirectToRoute("Super-SuperRoute", new { controller = "Super", action = "SuperRoute", id = "RouteTopic", year = selectedYear }); The route in the global.asax is like this: routes.MapRoute( "Super-SuperRoute", // Route name "Super.mvc/SuperRoute/{year}", // URL with parameters new { controller = "Super", action = "SuperRoute", id = "RouteTopic" } // Parameter defaults ); So why do I get the error: "No route in the route table matches the supplied values."? I saw that the type of selectedYear was var. When I tried to convert to int with int.Parse I realised that selectedYear was actually null, which would explain the problems. I guess next time I'll pay more attention to the values of the variables at a breakpoint:)
TITLE: MVC Preview 4 - No route in the route table matches the supplied values QUESTION: I have a route that I am calling through a RedirectToRoute like this: return this.RedirectToRoute("Super-SuperRoute", new { year = selectedYear }); I have also tried: return this.RedirectToRoute("Super-SuperRoute", new { controller = "Super", action = "SuperRoute", id = "RouteTopic", year = selectedYear }); The route in the global.asax is like this: routes.MapRoute( "Super-SuperRoute", // Route name "Super.mvc/SuperRoute/{year}", // URL with parameters new { controller = "Super", action = "SuperRoute", id = "RouteTopic" } // Parameter defaults ); So why do I get the error: "No route in the route table matches the supplied values."? I saw that the type of selectedYear was var. When I tried to convert to int with int.Parse I realised that selectedYear was actually null, which would explain the problems. I guess next time I'll pay more attention to the values of the variables at a breakpoint:) ANSWER: What type is selectedYear? A DateTime? If so then you might need to convert to a string.
[ "asp.net-mvc", "asp.net-mvc-routing" ]
4
5
3,280
1
0
2008-08-08T05:03:42.783000
2008-08-08T05:21:07.477000
5,694
5,695
The imported project "C:\Microsoft.CSharp.targets" was not found
I got this error today when trying to open a Visual Studio 2008 project in Visual Studio 2005: The imported project "C:\Microsoft.CSharp.targets" was not found.
Open your csproj file in notepad (or notepad++) Find the line: and change it to
The imported project "C:\Microsoft.CSharp.targets" was not found I got this error today when trying to open a Visual Studio 2008 project in Visual Studio 2005: The imported project "C:\Microsoft.CSharp.targets" was not found.
TITLE: The imported project "C:\Microsoft.CSharp.targets" was not found QUESTION: I got this error today when trying to open a Visual Studio 2008 project in Visual Studio 2005: The imported project "C:\Microsoft.CSharp.targets" was not found. ANSWER: Open your csproj file in notepad (or notepad++) Find the line: and change it to
[ "c#", "visual-studio" ]
142
117
187,980
20
0
2008-08-08T05:08:45.020000
2008-08-08T05:10:20.760000
5,706
5,709
When do Request.Params and Request.Form differ?
I recently encountered a problem where a value was null if accessed with Request.Form but fine if retrieved with Request.Params. What are the differences between these methods that could cause this?
Request.Form only includes variables posted through a form, while Request.Params includes both posted form variables and get variables specified as URL parameters.
When do Request.Params and Request.Form differ? I recently encountered a problem where a value was null if accessed with Request.Form but fine if retrieved with Request.Params. What are the differences between these methods that could cause this?
TITLE: When do Request.Params and Request.Form differ? QUESTION: I recently encountered a problem where a value was null if accessed with Request.Form but fine if retrieved with Request.Params. What are the differences between these methods that could cause this? ANSWER: Request.Form only includes variables posted through a form, while Request.Params includes both posted form variables and get variables specified as URL parameters.
[ "c#", "asp.net", "request" ]
36
32
29,058
3
0
2008-08-08T05:40:49.713000
2008-08-08T05:51:54.420000
5,724
5,823
Better windows command line shells
Is there a better windows command line shell other than cmd which has better copy paste between Windows' windows and console windows?
Take Command does support Copy/Cut/Paste from the keyboard and the mouse. It's pretty handy if you do a lot of work from a command prompt. It also supports: Command and folder history, with popup windows to select prior commands or folders. Screen scroll back buffer Enhanced batch commands Built in FTP/HTTP file access A toolbar with programmable buttons Note: It's a paid tool, with price of $99.95.
Better windows command line shells Is there a better windows command line shell other than cmd which has better copy paste between Windows' windows and console windows?
TITLE: Better windows command line shells QUESTION: Is there a better windows command line shell other than cmd which has better copy paste between Windows' windows and console windows? ANSWER: Take Command does support Copy/Cut/Paste from the keyboard and the mouse. It's pretty handy if you do a lot of work from a command prompt. It also supports: Command and folder history, with popup windows to select prior commands or folders. Screen scroll back buffer Enhanced batch commands Built in FTP/HTTP file access A toolbar with programmable buttons Note: It's a paid tool, with price of $99.95.
[ "windows", "shell", "cmd" ]
66
11
47,687
14
0
2008-08-08T06:15:11.033000
2008-08-08T11:59:40.503000
5,727
5,754
What are the barriers to understanding pointers and what can be done to overcome them?
Why are pointers such a leading factor of confusion for many new, and even old, college-level students in C or C++? Are there any tools or thought processes that helped you understand how pointers work at the variable, function, and beyond level? What are some good practice things that can be done to bring somebody to the level of, "Ah-hah, I got it," without getting them bogged down in the overall concept? Basically, drill-like scenarios.
Pointers is a concept that for many can be confusing at first, in particular when it comes to copying pointer values around and still referencing the same memory block. I've found that the best analogy is to consider the pointer as a piece of paper with a house address on it, and the memory block it references as the actual house. All sorts of operations can thus be easily explained. I've added some Delphi code down below, and some comments where appropriate. I chose Delphi since my other main programming language, C#, does not exhibit things like memory leaks in the same way. If you only wish to learn the high-level concept of pointers, then you should ignore the parts labelled "Memory layout" in the explanation below. They are intended to give examples of what memory could look like after operations, but they are more low-level in nature. However, in order to accurately explain how buffer overruns really work, it was important that I added these diagrams. Disclaimer: For all intents and purposes, this explanation and the example memory layouts are vastly simplified. There's more overhead and a lot more details you would need to know if you need to deal with memory on a low-level basis. However, for the intents of explaining memory and pointers, it is accurate enough. Let's assume the THouse class used below looks like this: type THouse = class private FName: array[0..9] of Char; public constructor Create(name: PChar); end; When you initialize the house object, the name given to the constructor is copied into the private field FName. There is a reason it is defined as a fixed-size array. In memory, there will be some overhead associated with the house allocation, I'll illustrate this below like this: ---[ttttNNNNNNNNNN]--- ^ ^ | | | +- the FName array | +- overhead The "tttt" area is overhead, there will typically be more of this for various types of runtimes and languages, like 8 or 12 bytes. It is imperative that whatever values are stored in this area never gets changed by anything other than the memory allocator or the core system routines, or you risk crashing the program. Allocate memory Get an entrepreneur to build your house, and give you the address to the house. In contrast to the real world, memory allocation cannot be told where to allocate, but will find a suitable spot with enough room, and report back the address to the allocated memory. In other words, the entrepreneur will choose the spot. THouse.Create('My house'); Memory layout: ---[ttttNNNNNNNNNN]--- 1234My house Keep a variable with the address Write the address to your new house down on a piece of paper. This paper will serve as your reference to your house. Without this piece of paper, you're lost, and cannot find the house, unless you're already in it. var h: THouse; begin h:= THouse.Create('My house');... Memory layout: h v ---[ttttNNNNNNNNNN]--- 1234My house Copy pointer value Just write the address on a new piece of paper. You now have two pieces of paper that will get you to the same house, not two separate houses. Any attempts to follow the address from one paper and rearrange the furniture at that house will make it seem that the other house has been modified in the same manner, unless you can explicitly detect that it's actually just one house. Note This is usually the concept that I have the most problem explaining to people, two pointers does not mean two objects or memory blocks. var h1, h2: THouse; begin h1:= THouse.Create('My house'); h2:= h1; // copies the address, not the house... h1 v ---[ttttNNNNNNNNNN]--- 1234My house ^ h2 Freeing the memory Demolish the house. You can then later on reuse the paper for a new address if you so wish, or clear it to forget the address to the house that no longer exists. var h: THouse; begin h:= THouse.Create('My house');... h.Free; h:= nil; Here I first construct the house, and get hold of its address. Then I do something to the house (use it, the... code, left as an exercise for the reader), and then I free it. Lastly I clear the address from my variable. Memory layout: h <--+ v +- before free ---[ttttNNNNNNNNNN]--- | 1234My house <--+ h (now points nowhere) <--+ +- after free ---------------------- | (note, memory might still xx34My house <--+ contain some data) Dangling pointers You tell your entrepreneur to destroy the house, but you forget to erase the address from your piece of paper. When later on you look at the piece of paper, you've forgotten that the house is no longer there, and goes to visit it, with failed results (see also the part about an invalid reference below). var h: THouse; begin h:= THouse.Create('My house');... h.Free;... // forgot to clear h here h.OpenFrontDoor; // will most likely fail Using h after the call to.Free might work, but that is just pure luck. Most likely it will fail, at a customers place, in the middle of a critical operation. h <--+ v +- before free ---[ttttNNNNNNNNNN]--- | 1234My house <--+ h <--+ v +- after free ---------------------- | xx34My house <--+ As you can see, h still points to the remnants of the data in memory, but since it might not be complete, using it as before might fail. Memory leak You lose the piece of paper and cannot find the house. The house is still standing somewhere though, and when you later on want to construct a new house, you cannot reuse that spot. var h: THouse; begin h:= THouse.Create('My house'); h:= THouse.Create('My house'); // uh-oh, what happened to our first house?... h.Free; h:= nil; Here we overwrote the contents of the h variable with the address of a new house, but the old one is still standing... somewhere. After this code, there is no way to reach that house, and it will be left standing. In other words, the allocated memory will stay allocated until the application closes, at which point the operating system will tear it down. Memory layout after first allocation: h v ---[ttttNNNNNNNNNN]--- 1234My house Memory layout after second allocation: h v ---[ttttNNNNNNNNNN]---[ttttNNNNNNNNNN] 1234My house 5678My house A more common way to get this method is just to forget to free something, instead of overwriting it as above. In Delphi terms, this will occur with the following method: procedure OpenTheFrontDoorOfANewHouse; var h: THouse; begin h:= THouse.Create('My house'); h.OpenFrontDoor; // uh-oh, no.Free here, where does the address go? end; After this method has executed, there's no place in our variables that the address to the house exists, but the house is still out there. Memory layout: h <--+ v +- before losing pointer ---[ttttNNNNNNNNNN]--- | 1234My house <--+ h (now points nowhere) <--+ +- after losing pointer ---[ttttNNNNNNNNNN]--- | 1234My house <--+ As you can see, the old data is left intact in memory, and will not be reused by the memory allocator. The allocator keeps track of which areas of memory has been used, and will not reuse them unless you free it. Freeing the memory but keeping a (now invalid) reference Demolish the house, erase one of the pieces of paper but you also have another piece of paper with the old address on it, when you go to the address, you won't find a house, but you might find something that resembles the ruins of one. Perhaps you will even find a house, but it is not the house you were originally given the address to, and thus any attempts to use it as though it belongs to you might fail horribly. Sometimes you might even find that a neighbouring address has a rather big house set up on it that occupies three address (Main Street 1-3), and your address goes to the middle of the house. Any attempts to treat that part of the large 3-address house as a single small house might also fail horribly. var h1, h2: THouse; begin h1:= THouse.Create('My house'); h2:= h1; // copies the address, not the house... h1.Free; h1:= nil; h2.OpenFrontDoor; // uh-oh, what happened to our house? Here the house was torn down, through the reference in h1, and while h1 was cleared as well, h2 still has the old, out-of-date, address. Access to the house that is no longer standing might or might not work. This is a variation of the dangling pointer above. See its memory layout. Buffer overrun You move more stuff into the house than you can possibly fit, spilling into the neighbours house or yard. When the owner of that neighbouring house later on comes home, he'll find all sorts of things he'll consider his own. This is the reason I chose a fixed-size array. To set the stage, assume that the second house we allocate will, for some reason, be placed before the first one in memory. In other words, the second house will have a lower address than the first one. Also, they're allocated right next to each other. Thus, this code: var h1, h2: THouse; begin h1:= THouse.Create('My house'); h2:= THouse.Create('My other house somewhere'); ^-----------------------^ longer than 10 characters 0123456789 <-- 10 characters Memory layout after first allocation: h1 v -----------------------[ttttNNNNNNNNNN] 5678My house Memory layout after second allocation: h2 h1 v v ---[ttttNNNNNNNNNN]----[ttttNNNNNNNNNN] 1234My other house somewhereouse ^---+--^ | +- overwritten The part that will most often cause crash is when you overwrite important parts of the data you stored that really should not be randomly changed. For instance it might not be a problem that parts of the name of the h1-house was changed, in terms of crashing the program, but overwriting the overhead of the object will most likely crash when you try to use the broken object, as will overwriting links that is stored to other objects in the object. Linked lists When you follow an address on a piece of paper, you get to a house, and at that house there is another piece of paper with a new address on it, for the next house in the chain, and so on. var h1, h2: THouse; begin h1:= THouse.Create('Home'); h2:= THouse.Create('Cabin'); h1.NextHouse:= h2; Here we create a link from our home house to our cabin. We can follow the chain until a house has no NextHouse reference, which means it's the last one. To visit all our houses, we could use the following code: var h1, h2: THouse; h: THouse; begin h1:= THouse.Create('Home'); h2:= THouse.Create('Cabin'); h1.NextHouse:= h2;... h:= h1; while h <> nil do begin h.LockAllDoors; h.CloseAllWindows; h:= h.NextHouse; end; Memory layout (added NextHouse as a link in the object, noted with the four LLLL's in the below diagram): h1 h2 v v ---[ttttNNNNNNNNNNLLLL]----[ttttNNNNNNNNNNLLLL] 1234Home + 5678Cabin + | ^ | +--------+ * (no link) In basic terms, what is a memory address? A memory address is in basic terms just a number. If you think of memory as a big array of bytes, the very first byte has the address 0, the next one the address 1 and so on upwards. This is simplified, but good enough. So this memory layout: h1 h2 v v ---[ttttNNNNNNNNNN]---[ttttNNNNNNNNNN] 1234My house 5678My house Might have these two address (the leftmost - is address 0): h1 = 4 h2 = 23 Which means that our linked list above might actuall look like this: h1 (=4) h2 (=28) v v ---[ttttNNNNNNNNNNLLLL]----[ttttNNNNNNNNNNLLLL] 1234Home 0028 5678Cabin 0000 | ^ | +--------+ * (no link) It is typical to store an address that "points nowhere" as a zero-address. In basic terms, what is a pointer? A pointer is just a variable holding a memory address. You can typically ask the programming language to give you its number, but most programming languages and runtimes tries to hide the fact that there is a number beneath, just because the number itself does not really hold any meaning to you. It is best to think of a pointer as a black box, ie. you don't really know or care about how it is actually implemented, just as long as it works.
What are the barriers to understanding pointers and what can be done to overcome them? Why are pointers such a leading factor of confusion for many new, and even old, college-level students in C or C++? Are there any tools or thought processes that helped you understand how pointers work at the variable, function, and beyond level? What are some good practice things that can be done to bring somebody to the level of, "Ah-hah, I got it," without getting them bogged down in the overall concept? Basically, drill-like scenarios.
TITLE: What are the barriers to understanding pointers and what can be done to overcome them? QUESTION: Why are pointers such a leading factor of confusion for many new, and even old, college-level students in C or C++? Are there any tools or thought processes that helped you understand how pointers work at the variable, function, and beyond level? What are some good practice things that can be done to bring somebody to the level of, "Ah-hah, I got it," without getting them bogged down in the overall concept? Basically, drill-like scenarios. ANSWER: Pointers is a concept that for many can be confusing at first, in particular when it comes to copying pointer values around and still referencing the same memory block. I've found that the best analogy is to consider the pointer as a piece of paper with a house address on it, and the memory block it references as the actual house. All sorts of operations can thus be easily explained. I've added some Delphi code down below, and some comments where appropriate. I chose Delphi since my other main programming language, C#, does not exhibit things like memory leaks in the same way. If you only wish to learn the high-level concept of pointers, then you should ignore the parts labelled "Memory layout" in the explanation below. They are intended to give examples of what memory could look like after operations, but they are more low-level in nature. However, in order to accurately explain how buffer overruns really work, it was important that I added these diagrams. Disclaimer: For all intents and purposes, this explanation and the example memory layouts are vastly simplified. There's more overhead and a lot more details you would need to know if you need to deal with memory on a low-level basis. However, for the intents of explaining memory and pointers, it is accurate enough. Let's assume the THouse class used below looks like this: type THouse = class private FName: array[0..9] of Char; public constructor Create(name: PChar); end; When you initialize the house object, the name given to the constructor is copied into the private field FName. There is a reason it is defined as a fixed-size array. In memory, there will be some overhead associated with the house allocation, I'll illustrate this below like this: ---[ttttNNNNNNNNNN]--- ^ ^ | | | +- the FName array | +- overhead The "tttt" area is overhead, there will typically be more of this for various types of runtimes and languages, like 8 or 12 bytes. It is imperative that whatever values are stored in this area never gets changed by anything other than the memory allocator or the core system routines, or you risk crashing the program. Allocate memory Get an entrepreneur to build your house, and give you the address to the house. In contrast to the real world, memory allocation cannot be told where to allocate, but will find a suitable spot with enough room, and report back the address to the allocated memory. In other words, the entrepreneur will choose the spot. THouse.Create('My house'); Memory layout: ---[ttttNNNNNNNNNN]--- 1234My house Keep a variable with the address Write the address to your new house down on a piece of paper. This paper will serve as your reference to your house. Without this piece of paper, you're lost, and cannot find the house, unless you're already in it. var h: THouse; begin h:= THouse.Create('My house');... Memory layout: h v ---[ttttNNNNNNNNNN]--- 1234My house Copy pointer value Just write the address on a new piece of paper. You now have two pieces of paper that will get you to the same house, not two separate houses. Any attempts to follow the address from one paper and rearrange the furniture at that house will make it seem that the other house has been modified in the same manner, unless you can explicitly detect that it's actually just one house. Note This is usually the concept that I have the most problem explaining to people, two pointers does not mean two objects or memory blocks. var h1, h2: THouse; begin h1:= THouse.Create('My house'); h2:= h1; // copies the address, not the house... h1 v ---[ttttNNNNNNNNNN]--- 1234My house ^ h2 Freeing the memory Demolish the house. You can then later on reuse the paper for a new address if you so wish, or clear it to forget the address to the house that no longer exists. var h: THouse; begin h:= THouse.Create('My house');... h.Free; h:= nil; Here I first construct the house, and get hold of its address. Then I do something to the house (use it, the... code, left as an exercise for the reader), and then I free it. Lastly I clear the address from my variable. Memory layout: h <--+ v +- before free ---[ttttNNNNNNNNNN]--- | 1234My house <--+ h (now points nowhere) <--+ +- after free ---------------------- | (note, memory might still xx34My house <--+ contain some data) Dangling pointers You tell your entrepreneur to destroy the house, but you forget to erase the address from your piece of paper. When later on you look at the piece of paper, you've forgotten that the house is no longer there, and goes to visit it, with failed results (see also the part about an invalid reference below). var h: THouse; begin h:= THouse.Create('My house');... h.Free;... // forgot to clear h here h.OpenFrontDoor; // will most likely fail Using h after the call to.Free might work, but that is just pure luck. Most likely it will fail, at a customers place, in the middle of a critical operation. h <--+ v +- before free ---[ttttNNNNNNNNNN]--- | 1234My house <--+ h <--+ v +- after free ---------------------- | xx34My house <--+ As you can see, h still points to the remnants of the data in memory, but since it might not be complete, using it as before might fail. Memory leak You lose the piece of paper and cannot find the house. The house is still standing somewhere though, and when you later on want to construct a new house, you cannot reuse that spot. var h: THouse; begin h:= THouse.Create('My house'); h:= THouse.Create('My house'); // uh-oh, what happened to our first house?... h.Free; h:= nil; Here we overwrote the contents of the h variable with the address of a new house, but the old one is still standing... somewhere. After this code, there is no way to reach that house, and it will be left standing. In other words, the allocated memory will stay allocated until the application closes, at which point the operating system will tear it down. Memory layout after first allocation: h v ---[ttttNNNNNNNNNN]--- 1234My house Memory layout after second allocation: h v ---[ttttNNNNNNNNNN]---[ttttNNNNNNNNNN] 1234My house 5678My house A more common way to get this method is just to forget to free something, instead of overwriting it as above. In Delphi terms, this will occur with the following method: procedure OpenTheFrontDoorOfANewHouse; var h: THouse; begin h:= THouse.Create('My house'); h.OpenFrontDoor; // uh-oh, no.Free here, where does the address go? end; After this method has executed, there's no place in our variables that the address to the house exists, but the house is still out there. Memory layout: h <--+ v +- before losing pointer ---[ttttNNNNNNNNNN]--- | 1234My house <--+ h (now points nowhere) <--+ +- after losing pointer ---[ttttNNNNNNNNNN]--- | 1234My house <--+ As you can see, the old data is left intact in memory, and will not be reused by the memory allocator. The allocator keeps track of which areas of memory has been used, and will not reuse them unless you free it. Freeing the memory but keeping a (now invalid) reference Demolish the house, erase one of the pieces of paper but you also have another piece of paper with the old address on it, when you go to the address, you won't find a house, but you might find something that resembles the ruins of one. Perhaps you will even find a house, but it is not the house you were originally given the address to, and thus any attempts to use it as though it belongs to you might fail horribly. Sometimes you might even find that a neighbouring address has a rather big house set up on it that occupies three address (Main Street 1-3), and your address goes to the middle of the house. Any attempts to treat that part of the large 3-address house as a single small house might also fail horribly. var h1, h2: THouse; begin h1:= THouse.Create('My house'); h2:= h1; // copies the address, not the house... h1.Free; h1:= nil; h2.OpenFrontDoor; // uh-oh, what happened to our house? Here the house was torn down, through the reference in h1, and while h1 was cleared as well, h2 still has the old, out-of-date, address. Access to the house that is no longer standing might or might not work. This is a variation of the dangling pointer above. See its memory layout. Buffer overrun You move more stuff into the house than you can possibly fit, spilling into the neighbours house or yard. When the owner of that neighbouring house later on comes home, he'll find all sorts of things he'll consider his own. This is the reason I chose a fixed-size array. To set the stage, assume that the second house we allocate will, for some reason, be placed before the first one in memory. In other words, the second house will have a lower address than the first one. Also, they're allocated right next to each other. Thus, this code: var h1, h2: THouse; begin h1:= THouse.Create('My house'); h2:= THouse.Create('My other house somewhere'); ^-----------------------^ longer than 10 characters 0123456789 <-- 10 characters Memory layout after first allocation: h1 v -----------------------[ttttNNNNNNNNNN] 5678My house Memory layout after second allocation: h2 h1 v v ---[ttttNNNNNNNNNN]----[ttttNNNNNNNNNN] 1234My other house somewhereouse ^---+--^ | +- overwritten The part that will most often cause crash is when you overwrite important parts of the data you stored that really should not be randomly changed. For instance it might not be a problem that parts of the name of the h1-house was changed, in terms of crashing the program, but overwriting the overhead of the object will most likely crash when you try to use the broken object, as will overwriting links that is stored to other objects in the object. Linked lists When you follow an address on a piece of paper, you get to a house, and at that house there is another piece of paper with a new address on it, for the next house in the chain, and so on. var h1, h2: THouse; begin h1:= THouse.Create('Home'); h2:= THouse.Create('Cabin'); h1.NextHouse:= h2; Here we create a link from our home house to our cabin. We can follow the chain until a house has no NextHouse reference, which means it's the last one. To visit all our houses, we could use the following code: var h1, h2: THouse; h: THouse; begin h1:= THouse.Create('Home'); h2:= THouse.Create('Cabin'); h1.NextHouse:= h2;... h:= h1; while h <> nil do begin h.LockAllDoors; h.CloseAllWindows; h:= h.NextHouse; end; Memory layout (added NextHouse as a link in the object, noted with the four LLLL's in the below diagram): h1 h2 v v ---[ttttNNNNNNNNNNLLLL]----[ttttNNNNNNNNNNLLLL] 1234Home + 5678Cabin + | ^ | +--------+ * (no link) In basic terms, what is a memory address? A memory address is in basic terms just a number. If you think of memory as a big array of bytes, the very first byte has the address 0, the next one the address 1 and so on upwards. This is simplified, but good enough. So this memory layout: h1 h2 v v ---[ttttNNNNNNNNNN]---[ttttNNNNNNNNNN] 1234My house 5678My house Might have these two address (the leftmost - is address 0): h1 = 4 h2 = 23 Which means that our linked list above might actuall look like this: h1 (=4) h2 (=28) v v ---[ttttNNNNNNNNNNLLLL]----[ttttNNNNNNNNNNLLLL] 1234Home 0028 5678Cabin 0000 | ^ | +--------+ * (no link) It is typical to store an address that "points nowhere" as a zero-address. In basic terms, what is a pointer? A pointer is just a variable holding a memory address. You can typically ask the programming language to give you its number, but most programming languages and runtimes tries to hide the fact that there is a number beneath, just because the number itself does not really hold any meaning to you. It is best to think of a pointer as a black box, ie. you don't really know or care about how it is actually implemented, just as long as it works.
[ "c++", "c", "pointers" ]
470
757
91,470
28
0
2008-08-08T06:17:51.543000
2008-08-08T06:58:48.700000
5,743
5,771
What is a good plotting library for .Net?
I'm writing some data acquisition software and need a gui plotting library that is fast enough to do realtime updated graphs. I've been using Nplot which is pretty good for a free library, but I'm wondering if there are any better libraries (preferably free or cheap).
There's a good post about this here and here. I have also used NPlot in our last project since it's easier to use.
What is a good plotting library for .Net? I'm writing some data acquisition software and need a gui plotting library that is fast enough to do realtime updated graphs. I've been using Nplot which is pretty good for a free library, but I'm wondering if there are any better libraries (preferably free or cheap).
TITLE: What is a good plotting library for .Net? QUESTION: I'm writing some data acquisition software and need a gui plotting library that is fast enough to do realtime updated graphs. I've been using Nplot which is pretty good for a free library, but I'm wondering if there are any better libraries (preferably free or cheap). ANSWER: There's a good post about this here and here. I have also used NPlot in our last project since it's easier to use.
[ ".net", "windows", "graphing" ]
19
4
4,393
7
0
2008-08-08T06:40:46.553000
2008-08-08T07:49:30.297000
5,759
5,761
Equivalent VB keyword for 'break'
I just moved over to the Visual Basic team here at work. What is the equivalent keyword to break in Visual Basic, that is, to exit a loop early but not the method?
In both Visual Basic 6.0 and VB.NET you would use: Exit For to break from For loop Wend to break from While loop Exit Do to break from Do loop depending on the loop type. See Exit Statements for more details.
Equivalent VB keyword for 'break' I just moved over to the Visual Basic team here at work. What is the equivalent keyword to break in Visual Basic, that is, to exit a loop early but not the method?
TITLE: Equivalent VB keyword for 'break' QUESTION: I just moved over to the Visual Basic team here at work. What is the equivalent keyword to break in Visual Basic, that is, to exit a loop early but not the method? ANSWER: In both Visual Basic 6.0 and VB.NET you would use: Exit For to break from For loop Wend to break from While loop Exit Do to break from Do loop depending on the loop type. See Exit Statements for more details.
[ "vb.net", "loops", "vb6", "exit" ]
113
199
145,095
3
0
2008-08-08T07:11:40.560000
2008-08-08T07:13:56.237000
5,787
5,788
Tab Escape Character?
I'm just in the process of parsing some text and can't remember what the escape character is for a tab in C#?
Easy one! "\t" Edit: In fact, here's something official: Escape Sequences
Tab Escape Character? I'm just in the process of parsing some text and can't remember what the escape character is for a tab in C#?
TITLE: Tab Escape Character? QUESTION: I'm just in the process of parsing some text and can't remember what the escape character is for a tab in C#? ANSWER: Easy one! "\t" Edit: In fact, here's something official: Escape Sequences
[ "c#" ]
74
117
114,994
2
0
2008-08-08T09:28:41.423000
2008-08-08T09:30:40.860000
5,791
5,837
IsNothing versus Is Nothing
Does anyone here use VB.NET and have a strong preference for or against using IsNothing as opposed to Is Nothing (for example, If IsNothing(anObject) or If anObject Is Nothing... )? If so, why? EDIT: If you think they're both equally acceptable, do you think it's best to pick one and stick with it, or is it OK to mix them?
If you take a look at the MSIL as it's being executed you'll see that it doesn't compile down to the exact same code. When you use IsNothing() it actually makes a call to that method as opposed to just evaluating the expression. The reason I would tend to lean towards using "Is Nothing" is when I'm negating it becomes "IsNot Nothing' rather than "Not IsNothing(object)" which I personally feel looks more readable.
IsNothing versus Is Nothing Does anyone here use VB.NET and have a strong preference for or against using IsNothing as opposed to Is Nothing (for example, If IsNothing(anObject) or If anObject Is Nothing... )? If so, why? EDIT: If you think they're both equally acceptable, do you think it's best to pick one and stick with it, or is it OK to mix them?
TITLE: IsNothing versus Is Nothing QUESTION: Does anyone here use VB.NET and have a strong preference for or against using IsNothing as opposed to Is Nothing (for example, If IsNothing(anObject) or If anObject Is Nothing... )? If so, why? EDIT: If you think they're both equally acceptable, do you think it's best to pick one and stick with it, or is it OK to mix them? ANSWER: If you take a look at the MSIL as it's being executed you'll see that it doesn't compile down to the exact same code. When you use IsNothing() it actually makes a call to that method as opposed to just evaluating the expression. The reason I would tend to lean towards using "Is Nothing" is when I'm negating it becomes "IsNot Nothing' rather than "Not IsNothing(object)" which I personally feel looks more readable.
[ "vb.net" ]
137
128
213,285
8
0
2008-08-08T09:45:29.067000
2008-08-08T12:28:37.483000
5,802
5,812
Inheritance in database?
Is there any way to use inheritance in database (Specifically in SQL Server 2005)? Suppose I have few field like CreatedOn, CreatedBy which I want to add on all of my entities. I looking for an alternative way instead of adding these fields to every table.
There is no such thing as inheritance between tables in SQL Server 2005, and as noted by the others, you can get as far as getting help adding the necessary columns to the tables when you create them, but it won't be inheritance as you know it. Think of it more like a template for your source code files. As GateKiller mentions, you can create a table containing the shared data and reference it with a foreign key, but you'll either have to have audit hooks, triggers, or do the update manually. Bottom line: Manual work.
Inheritance in database? Is there any way to use inheritance in database (Specifically in SQL Server 2005)? Suppose I have few field like CreatedOn, CreatedBy which I want to add on all of my entities. I looking for an alternative way instead of adding these fields to every table.
TITLE: Inheritance in database? QUESTION: Is there any way to use inheritance in database (Specifically in SQL Server 2005)? Suppose I have few field like CreatedOn, CreatedBy which I want to add on all of my entities. I looking for an alternative way instead of adding these fields to every table. ANSWER: There is no such thing as inheritance between tables in SQL Server 2005, and as noted by the others, you can get as far as getting help adding the necessary columns to the tables when you create them, but it won't be inheritance as you know it. Think of it more like a template for your source code files. As GateKiller mentions, you can create a table containing the shared data and reference it with a foreign key, but you'll either have to have audit hooks, triggers, or do the update manually. Bottom line: Manual work.
[ "sql", "database", "inheritance", "sql-server-2005" ]
9
3
4,984
9
0
2008-08-08T10:41:00.950000
2008-08-08T11:08:22.923000
5,821
5,822
SQL Server Escape an Underscore
How do I escape the underscore character? I am writing something like the following where clause and want to be able to find actual entries with _d at the end. Where Username Like '%_d'
T-SQL Reference for LIKE: You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets. The following table shows several examples of using the LIKE keyword and the [ ] wildcard characters. For your case:... LIKE '%[_]d'
SQL Server Escape an Underscore How do I escape the underscore character? I am writing something like the following where clause and want to be able to find actual entries with _d at the end. Where Username Like '%_d'
TITLE: SQL Server Escape an Underscore QUESTION: How do I escape the underscore character? I am writing something like the following where clause and want to be able to find actual entries with _d at the end. Where Username Like '%_d' ANSWER: T-SQL Reference for LIKE: You can use the wildcard pattern matching characters as literal characters. To use a wildcard character as a literal character, enclose the wildcard character in brackets. The following table shows several examples of using the LIKE keyword and the [ ] wildcard characters. For your case:... LIKE '%[_]d'
[ "sql-server" ]
467
724
281,438
8
0
2008-08-08T11:56:36.207000
2008-08-08T11:59:36.340000
5,831
5,878
Binary patch-generation in C#
Does anyone have, or know of, a binary patch generation algorithm implementation in C#? Basically, compare two files (designated old and new ), and produce a patch file that can be used to upgrade the old file to have the same contents as the new file. The implementation would have to be relatively fast, and work with huge files. It should exhibit O(n) or O(logn) runtimes. My own algorithms tend to either be lousy (fast but produce huge patches) or slow (produce small patches but have O(n^2) runtime). Any advice, or pointers for implementation would be nice. Specifically, the implementation will be used to keep servers in sync for various large datafiles that we have one master server for. When the master server datafiles change, we need to update several off-site servers as well. The most naive algorithm I have made, which only works for files that can be kept in memory, is as follows: Grab the first four bytes from the old file, call this the key Add those bytes to a dictionary, where key -> position, where position is the position where I grabbed those 4 bytes, 0 to begin with Skip the first of these four bytes, grab another 4 (3 overlap, 1 one), and add to the dictionary the same way Repeat steps 1-3 for all 4-byte blocks in the old file From the start of the new file, grab 4 bytes, and attempt to look it up in the dictionary If found, find the longest match if there are several, by comparing bytes from the two files Encode a reference to that location in the old file, and skip the matched block in the new file If not found, encode 1 byte from the new file, and skip it Repeat steps 5-8 for the rest of the new file This is somewhat like compression, without windowing, so it will use a lot of memory. It is, however, fairly fast, and produces quite small patches, as long as I try to make the codes output minimal. A more memory-efficient algorithm uses windowing, but produces much bigger patch files. There are more nuances to the above algorithm that I skipped in this post, but I can post more details if necessary. I do, however, feel that I need a different algorithm altogether, so improving on the above algorithm is probably not going to get me far enough. Edit #1: Here is a more detailed description of the above algorithm. First, combine the two files, so that you have one big file. Remember the cut-point between the two files. Secondly, do that grab 4 bytes and add their position to the dictionary step for everything in the whole file. Thirdly, from where the new file starts, do the loop with attempting to locate an existing combination of 4 bytes, and find the longest match. Make sure we only consider positions from the old file, or from earlier in the new file than we're currently at. This ensures that we can reuse material in both the old and the new file during patch application. Edit #2: Source code to the above algorithm You might get a warning about the certificate having some problems. I don't know how to resolve that so for the time being just accept the certificate. The source uses lots of other types from the rest of my library so that file isn't all it takes, but that's the algorithm implementation. @lomaxx, I have tried to find a good documentation for the algorithm used in subversion, called xdelta, but unless you already know how the algorithm works, the documents I've found fail to tell me what I need to know. Or perhaps I'm just dense...:) I took a quick peek on the algorithm from that site you gave, and it is unfortunately not usable. A comment from the binary diff file says: Finding an optimal set of differences requires quadratic time relative to the input size, so it becomes unusable very quickly. My needs aren't optimal though, so I'm looking for a more practical solution. Thanks for the answer though, added a bookmark to his utilities if I ever need them. Edit #1: Note, I will look at his code to see if I can find some ideas, and I'll also send him an email later with questions, but I've read that book he references and though the solution is good for finding optimal solutions, it is impractical in use due to the time requirements. Edit #2: I'll definitely hunt down the python xdelta implementation.
Sorry I couldn't be more help. I would definately keep looking at xdelta because I have used it a number of times to produce quality diffs on 600MB+ ISO files we have generated for distributing our products and it performs very well.
Binary patch-generation in C# Does anyone have, or know of, a binary patch generation algorithm implementation in C#? Basically, compare two files (designated old and new ), and produce a patch file that can be used to upgrade the old file to have the same contents as the new file. The implementation would have to be relatively fast, and work with huge files. It should exhibit O(n) or O(logn) runtimes. My own algorithms tend to either be lousy (fast but produce huge patches) or slow (produce small patches but have O(n^2) runtime). Any advice, or pointers for implementation would be nice. Specifically, the implementation will be used to keep servers in sync for various large datafiles that we have one master server for. When the master server datafiles change, we need to update several off-site servers as well. The most naive algorithm I have made, which only works for files that can be kept in memory, is as follows: Grab the first four bytes from the old file, call this the key Add those bytes to a dictionary, where key -> position, where position is the position where I grabbed those 4 bytes, 0 to begin with Skip the first of these four bytes, grab another 4 (3 overlap, 1 one), and add to the dictionary the same way Repeat steps 1-3 for all 4-byte blocks in the old file From the start of the new file, grab 4 bytes, and attempt to look it up in the dictionary If found, find the longest match if there are several, by comparing bytes from the two files Encode a reference to that location in the old file, and skip the matched block in the new file If not found, encode 1 byte from the new file, and skip it Repeat steps 5-8 for the rest of the new file This is somewhat like compression, without windowing, so it will use a lot of memory. It is, however, fairly fast, and produces quite small patches, as long as I try to make the codes output minimal. A more memory-efficient algorithm uses windowing, but produces much bigger patch files. There are more nuances to the above algorithm that I skipped in this post, but I can post more details if necessary. I do, however, feel that I need a different algorithm altogether, so improving on the above algorithm is probably not going to get me far enough. Edit #1: Here is a more detailed description of the above algorithm. First, combine the two files, so that you have one big file. Remember the cut-point between the two files. Secondly, do that grab 4 bytes and add their position to the dictionary step for everything in the whole file. Thirdly, from where the new file starts, do the loop with attempting to locate an existing combination of 4 bytes, and find the longest match. Make sure we only consider positions from the old file, or from earlier in the new file than we're currently at. This ensures that we can reuse material in both the old and the new file during patch application. Edit #2: Source code to the above algorithm You might get a warning about the certificate having some problems. I don't know how to resolve that so for the time being just accept the certificate. The source uses lots of other types from the rest of my library so that file isn't all it takes, but that's the algorithm implementation. @lomaxx, I have tried to find a good documentation for the algorithm used in subversion, called xdelta, but unless you already know how the algorithm works, the documents I've found fail to tell me what I need to know. Or perhaps I'm just dense...:) I took a quick peek on the algorithm from that site you gave, and it is unfortunately not usable. A comment from the binary diff file says: Finding an optimal set of differences requires quadratic time relative to the input size, so it becomes unusable very quickly. My needs aren't optimal though, so I'm looking for a more practical solution. Thanks for the answer though, added a bookmark to his utilities if I ever need them. Edit #1: Note, I will look at his code to see if I can find some ideas, and I'll also send him an email later with questions, but I've read that book he references and though the solution is good for finding optimal solutions, it is impractical in use due to the time requirements. Edit #2: I'll definitely hunt down the python xdelta implementation.
TITLE: Binary patch-generation in C# QUESTION: Does anyone have, or know of, a binary patch generation algorithm implementation in C#? Basically, compare two files (designated old and new ), and produce a patch file that can be used to upgrade the old file to have the same contents as the new file. The implementation would have to be relatively fast, and work with huge files. It should exhibit O(n) or O(logn) runtimes. My own algorithms tend to either be lousy (fast but produce huge patches) or slow (produce small patches but have O(n^2) runtime). Any advice, or pointers for implementation would be nice. Specifically, the implementation will be used to keep servers in sync for various large datafiles that we have one master server for. When the master server datafiles change, we need to update several off-site servers as well. The most naive algorithm I have made, which only works for files that can be kept in memory, is as follows: Grab the first four bytes from the old file, call this the key Add those bytes to a dictionary, where key -> position, where position is the position where I grabbed those 4 bytes, 0 to begin with Skip the first of these four bytes, grab another 4 (3 overlap, 1 one), and add to the dictionary the same way Repeat steps 1-3 for all 4-byte blocks in the old file From the start of the new file, grab 4 bytes, and attempt to look it up in the dictionary If found, find the longest match if there are several, by comparing bytes from the two files Encode a reference to that location in the old file, and skip the matched block in the new file If not found, encode 1 byte from the new file, and skip it Repeat steps 5-8 for the rest of the new file This is somewhat like compression, without windowing, so it will use a lot of memory. It is, however, fairly fast, and produces quite small patches, as long as I try to make the codes output minimal. A more memory-efficient algorithm uses windowing, but produces much bigger patch files. There are more nuances to the above algorithm that I skipped in this post, but I can post more details if necessary. I do, however, feel that I need a different algorithm altogether, so improving on the above algorithm is probably not going to get me far enough. Edit #1: Here is a more detailed description of the above algorithm. First, combine the two files, so that you have one big file. Remember the cut-point between the two files. Secondly, do that grab 4 bytes and add their position to the dictionary step for everything in the whole file. Thirdly, from where the new file starts, do the loop with attempting to locate an existing combination of 4 bytes, and find the longest match. Make sure we only consider positions from the old file, or from earlier in the new file than we're currently at. This ensures that we can reuse material in both the old and the new file during patch application. Edit #2: Source code to the above algorithm You might get a warning about the certificate having some problems. I don't know how to resolve that so for the time being just accept the certificate. The source uses lots of other types from the rest of my library so that file isn't all it takes, but that's the algorithm implementation. @lomaxx, I have tried to find a good documentation for the algorithm used in subversion, called xdelta, but unless you already know how the algorithm works, the documents I've found fail to tell me what I need to know. Or perhaps I'm just dense...:) I took a quick peek on the algorithm from that site you gave, and it is unfortunately not usable. A comment from the binary diff file says: Finding an optimal set of differences requires quadratic time relative to the input size, so it becomes unusable very quickly. My needs aren't optimal though, so I'm looking for a more practical solution. Thanks for the answer though, added a bookmark to his utilities if I ever need them. Edit #1: Note, I will look at his code to see if I can find some ideas, and I'll also send him an email later with questions, but I've read that book he references and though the solution is good for finding optimal solutions, it is impractical in use due to the time requirements. Edit #2: I'll definitely hunt down the python xdelta implementation. ANSWER: Sorry I couldn't be more help. I would definately keep looking at xdelta because I have used it a number of times to produce quality diffs on 600MB+ ISO files we have generated for distributing our products and it performs very well.
[ "c#", "file", "patch" ]
20
5
11,717
6
0
2008-08-08T12:22:07.713000
2008-08-08T13:03:06.197000
5,842
9,200
Issues using MS Access as a front-end to a MySQL database back-end?
Two users wanted to share the same database, originally written in MS Access, without conflicting with one another over a single MDB file. I moved the tables from a simple MS Access database to MySQL using its Migration Toolkit (which works well, by the way) and set up Access to link to those tables via ODBC. So far, I've run into the following: You can't insert/update/delete rows in a table without a primary key (no surprise there). AutoNumber fields in MS Access must be the primary key or they'll just end up as integer columns in MySQL (natch, why wouldn't it be the PK?) The tables were migrated to MySQL's InnoDB table type, but the Access relationships didn't become MySQL foreign key constraints. Once the database is in use, can I expect any other issues? Particularly when both users are working in the same table?
I had an application that worked likewise: an MS Access frontend to a MySQL backend. It was such a huge pain that I ended up writing a Win32 frontend instead. From the top of my head, I encountered the following problems: Development of the ODBC link seems to have ceased long ago. There are various different versions floating around --- very confusing. The ODBC link doesn't support Unicode/UTF8, and I remember there were other issues with it as well (though some could be overcome by careful configuration). You probably want to manually tweak your db schema to make it compatible with MS Access. I see you already found out about the needed surrogate keys (i.e., int primary keys):-) You should keep in mind that you may need to use pass-through queries to do more sophisticated SQL manipulations of the MySQL database. Be careful with using lots of VBA, as that tends to corrupt your frontend file. Regularly compressing the database (using main menu, Tools | Database utilities | Compress and restore, or something like that --- I'm using the Dutch version) and making lots of backups is necessary. Access tends to cause lots of network traffic. Like, really huge lots. I haven't been able to find a solution for that. Using a network monitor is recommended if you want to keep an eye on that! Access insists on storing booleans as 0/-1. IMHO, 0/+1 makes more sense, and I believe it is the default way of doing things in MySQL as well. Not a huge problem, but if your checkboxes don't work, you should definitely check this. One possible alternative would be to put the backend (with the data) on a shared drive. I remember this is well-documented, also in the help. You may want to have a look at some general advice on splitting into a frontend and a backend and code that automatically reconnects to the backend on startup; I can also send you some more sample code, or post it here. Otherwise, you might also want to consider MS SQL. I don't have experience with that, but I presume it works together with MS Access much more nicely!
Issues using MS Access as a front-end to a MySQL database back-end? Two users wanted to share the same database, originally written in MS Access, without conflicting with one another over a single MDB file. I moved the tables from a simple MS Access database to MySQL using its Migration Toolkit (which works well, by the way) and set up Access to link to those tables via ODBC. So far, I've run into the following: You can't insert/update/delete rows in a table without a primary key (no surprise there). AutoNumber fields in MS Access must be the primary key or they'll just end up as integer columns in MySQL (natch, why wouldn't it be the PK?) The tables were migrated to MySQL's InnoDB table type, but the Access relationships didn't become MySQL foreign key constraints. Once the database is in use, can I expect any other issues? Particularly when both users are working in the same table?
TITLE: Issues using MS Access as a front-end to a MySQL database back-end? QUESTION: Two users wanted to share the same database, originally written in MS Access, without conflicting with one another over a single MDB file. I moved the tables from a simple MS Access database to MySQL using its Migration Toolkit (which works well, by the way) and set up Access to link to those tables via ODBC. So far, I've run into the following: You can't insert/update/delete rows in a table without a primary key (no surprise there). AutoNumber fields in MS Access must be the primary key or they'll just end up as integer columns in MySQL (natch, why wouldn't it be the PK?) The tables were migrated to MySQL's InnoDB table type, but the Access relationships didn't become MySQL foreign key constraints. Once the database is in use, can I expect any other issues? Particularly when both users are working in the same table? ANSWER: I had an application that worked likewise: an MS Access frontend to a MySQL backend. It was such a huge pain that I ended up writing a Win32 frontend instead. From the top of my head, I encountered the following problems: Development of the ODBC link seems to have ceased long ago. There are various different versions floating around --- very confusing. The ODBC link doesn't support Unicode/UTF8, and I remember there were other issues with it as well (though some could be overcome by careful configuration). You probably want to manually tweak your db schema to make it compatible with MS Access. I see you already found out about the needed surrogate keys (i.e., int primary keys):-) You should keep in mind that you may need to use pass-through queries to do more sophisticated SQL manipulations of the MySQL database. Be careful with using lots of VBA, as that tends to corrupt your frontend file. Regularly compressing the database (using main menu, Tools | Database utilities | Compress and restore, or something like that --- I'm using the Dutch version) and making lots of backups is necessary. Access tends to cause lots of network traffic. Like, really huge lots. I haven't been able to find a solution for that. Using a network monitor is recommended if you want to keep an eye on that! Access insists on storing booleans as 0/-1. IMHO, 0/+1 makes more sense, and I believe it is the default way of doing things in MySQL as well. Not a huge problem, but if your checkboxes don't work, you should definitely check this. One possible alternative would be to put the backend (with the data) on a shared drive. I remember this is well-documented, also in the help. You may want to have a look at some general advice on splitting into a frontend and a backend and code that automatically reconnects to the backend on startup; I can also send you some more sample code, or post it here. Otherwise, you might also want to consider MS SQL. I don't have experience with that, but I presume it works together with MS Access much more nicely!
[ "mysql", "database", "ms-access" ]
14
15
32,411
7
0
2008-08-08T12:30:48.633000
2008-08-12T20:02:41.557000
5,846
5,848
Add 1 to a field
How do I turn the following 2 queries into 1 query $sql = "SELECT level FROM skills WHERE id = $id LIMIT 1;"; $result = $db->sql_query($sql); $level = (int) $db->sql_fetchfield('level'); $db->sql_freeresult($result); ++$level; $sql = "UPDATE skills SET level = $level WHERE id = $id;"; $result = $db->sql_query($sql); $db->sql_freeresult($result); I'm using it in a phpBB mod but the gist is that I grab the level, add one to it then update, it seems that it'd be much easier and faster if I could do it as one query. Edit: $id has already been forced to be an integer, thus no escaping is needed this time.
I get downmodded for this? $sql = "UPDATE skills SET level = level+1 WHERE id = $id"; $result = $db->sql_query($sql); $db->sql_freeresult($result); In Teifion's specific case, the phpBB DDL lists that particular field as NOT NULL, so there's no danger of incrementing NULL. In the general case, you should not use NULL to represent zero. Incrementing NULL should give an answer of NULL. If you're the kind of misguided developer who thinks NULL=0, step away from keyboard and find another pastime, you're just making life hard for the rest of us. Of course, this is the computer industry and who are we to say you're wrong? If you're not wrong, use $sql = "UPDATE skills SET level = COALESCE(level,0)+1 WHERE id = $id";...but let's face it: you're wrong. If everyone starts at level 0, then your DDL should include level INT DEFAULT '0' NOT NULL in case the programmers forget to set it when they create a record. If not everyone starts on level 0, then skip the DEFAULT and force the programmer to supply a value on creation. If some people are beyond levels, for whom having a level is a meaningless thing, then adding one to their level equally has no meaning. In that case, drop the NOT NULL from the DDL.
Add 1 to a field How do I turn the following 2 queries into 1 query $sql = "SELECT level FROM skills WHERE id = $id LIMIT 1;"; $result = $db->sql_query($sql); $level = (int) $db->sql_fetchfield('level'); $db->sql_freeresult($result); ++$level; $sql = "UPDATE skills SET level = $level WHERE id = $id;"; $result = $db->sql_query($sql); $db->sql_freeresult($result); I'm using it in a phpBB mod but the gist is that I grab the level, add one to it then update, it seems that it'd be much easier and faster if I could do it as one query. Edit: $id has already been forced to be an integer, thus no escaping is needed this time.
TITLE: Add 1 to a field QUESTION: How do I turn the following 2 queries into 1 query $sql = "SELECT level FROM skills WHERE id = $id LIMIT 1;"; $result = $db->sql_query($sql); $level = (int) $db->sql_fetchfield('level'); $db->sql_freeresult($result); ++$level; $sql = "UPDATE skills SET level = $level WHERE id = $id;"; $result = $db->sql_query($sql); $db->sql_freeresult($result); I'm using it in a phpBB mod but the gist is that I grab the level, add one to it then update, it seems that it'd be much easier and faster if I could do it as one query. Edit: $id has already been forced to be an integer, thus no escaping is needed this time. ANSWER: I get downmodded for this? $sql = "UPDATE skills SET level = level+1 WHERE id = $id"; $result = $db->sql_query($sql); $db->sql_freeresult($result); In Teifion's specific case, the phpBB DDL lists that particular field as NOT NULL, so there's no danger of incrementing NULL. In the general case, you should not use NULL to represent zero. Incrementing NULL should give an answer of NULL. If you're the kind of misguided developer who thinks NULL=0, step away from keyboard and find another pastime, you're just making life hard for the rest of us. Of course, this is the computer industry and who are we to say you're wrong? If you're not wrong, use $sql = "UPDATE skills SET level = COALESCE(level,0)+1 WHERE id = $id";...but let's face it: you're wrong. If everyone starts at level 0, then your DDL should include level INT DEFAULT '0' NOT NULL in case the programmers forget to set it when they create a record. If not everyone starts on level 0, then skip the DEFAULT and force the programmer to supply a value on creation. If some people are beyond levels, for whom having a level is a meaningless thing, then adding one to their level equally has no meaning. In that case, drop the NOT NULL from the DDL.
[ "php", "mysql" ]
24
31
23,151
7
0
2008-08-08T12:34:20.887000
2008-08-08T12:35:53.007000
5,855
6,687
Automate builds for Java RCP for deployment with JNLP
I've found many sources that talk about the automated Eclipse PDE process. I feel these sources don't do a good job explaining what's going on. I can create the deployable package, in a semi-manual process via the Feature Export. The automated process requires knowledge of how the org.eclipse.pde.build scripts work. I have gotten a build created, but not for JNLP. Questions: Has anyone ever deployed RCP through JNLP? Were you able to automate the builds?
I haven't done this before, but I found this site on the web giving an explanation.
Automate builds for Java RCP for deployment with JNLP I've found many sources that talk about the automated Eclipse PDE process. I feel these sources don't do a good job explaining what's going on. I can create the deployable package, in a semi-manual process via the Feature Export. The automated process requires knowledge of how the org.eclipse.pde.build scripts work. I have gotten a build created, but not for JNLP. Questions: Has anyone ever deployed RCP through JNLP? Were you able to automate the builds?
TITLE: Automate builds for Java RCP for deployment with JNLP QUESTION: I've found many sources that talk about the automated Eclipse PDE process. I feel these sources don't do a good job explaining what's going on. I can create the deployable package, in a semi-manual process via the Feature Export. The automated process requires knowledge of how the org.eclipse.pde.build scripts work. I have gotten a build created, but not for JNLP. Questions: Has anyone ever deployed RCP through JNLP? Were you able to automate the builds? ANSWER: I haven't done this before, but I found this site on the web giving an explanation.
[ "java", "build-automation", "rcp", "jnlp" ]
9
5
1,148
1
0
2008-08-08T12:40:02.793000
2008-08-09T07:50:31.647000
5,857
5,860
mailto link for large bodies
I have a page upon which a user can choose up to many different paragraphs. When the link is clicked (or button), an email will open up and put all those paragraphs into the body of the email, address it, and fill in the subject. However, the text can be too long for a mailto link. Any way around this? We were thinking about having an SP from the SQL Server do it but the user needs a nice way of 'seeing' the email before they blast 50 executive level employees with items that shouldn't be sent...and of course there's the whole thing about doing IT for IT rather than doing software programming. 80( When you build stuff for IT, it doesn't (some say shouldn't) have to be pretty just functional. In other words, this isn't the dogfood we wake it's just the dog food we have to eat. We started talking about it and decided that the 'mail form' would give us exactly what we are looking for. A very different look to let the user know that the gun is loaded and aimed. The ability to change/add text to the email. Send a copy to themselves or not. Can be coded quickly.
By putting the data into a form, I was able to make the body around 1800 characters long before the form stopped working. The code looked like this: Edit: The best way to send emails from a web application is of course to do just that, send it directly from the web application, instead of relying on the users mailprogram. As you've discovered, the protocol for sending information to that program is limited, but with a server-based solution you would of course not have those limitations.
mailto link for large bodies I have a page upon which a user can choose up to many different paragraphs. When the link is clicked (or button), an email will open up and put all those paragraphs into the body of the email, address it, and fill in the subject. However, the text can be too long for a mailto link. Any way around this? We were thinking about having an SP from the SQL Server do it but the user needs a nice way of 'seeing' the email before they blast 50 executive level employees with items that shouldn't be sent...and of course there's the whole thing about doing IT for IT rather than doing software programming. 80( When you build stuff for IT, it doesn't (some say shouldn't) have to be pretty just functional. In other words, this isn't the dogfood we wake it's just the dog food we have to eat. We started talking about it and decided that the 'mail form' would give us exactly what we are looking for. A very different look to let the user know that the gun is loaded and aimed. The ability to change/add text to the email. Send a copy to themselves or not. Can be coded quickly.
TITLE: mailto link for large bodies QUESTION: I have a page upon which a user can choose up to many different paragraphs. When the link is clicked (or button), an email will open up and put all those paragraphs into the body of the email, address it, and fill in the subject. However, the text can be too long for a mailto link. Any way around this? We were thinking about having an SP from the SQL Server do it but the user needs a nice way of 'seeing' the email before they blast 50 executive level employees with items that shouldn't be sent...and of course there's the whole thing about doing IT for IT rather than doing software programming. 80( When you build stuff for IT, it doesn't (some say shouldn't) have to be pretty just functional. In other words, this isn't the dogfood we wake it's just the dog food we have to eat. We started talking about it and decided that the 'mail form' would give us exactly what we are looking for. A very different look to let the user know that the gun is loaded and aimed. The ability to change/add text to the email. Send a copy to themselves or not. Can be coded quickly. ANSWER: By putting the data into a form, I was able to make the body around 1800 characters long before the form stopped working. The code looked like this: Edit: The best way to send emails from a web application is of course to do just that, send it directly from the web application, instead of relying on the users mailprogram. As you've discovered, the protocol for sending information to that program is limited, but with a server-based solution you would of course not have those limitations.
[ "mailto" ]
13
15
12,574
2
0
2008-08-08T12:40:48.627000
2008-08-08T12:47:13.653000
5,863
15,966
WCF Service - Backward compatibility issue
I'm just getting into creating some WCF services, but I have a requirement to make them backward compatible for legacy (.NET 1.1 and 2.0) client applications. I've managed to get the services to run correctly for 3.0 and greater clients, but when I publish the services using a basicHttpBinding endpoint (which I believe is required for the compatibility I need), the service refactors my method signatures. e.g. public bool MethodToReturnTrue(string seedValue); appears to the client apps as public void MethodToReturnTrue(string seedValue, out bool result, out bool MethodToReturnTrueResultSpecified); I've tried every configuration parameter I can think of in the app.config for my self-hosting console app, but I can't seem to make this function as expected. I suppose this might lead to the fact that my expectations are flawed, but I'd be surprised that a WCF service is incapable of handling a bool return type to a down-level client. My current app.config looks like this. Can anyone advise, please?
OK, we needed to resolve this issue in the short term, and so we came up with the idea of a "interop", or compatibility layer. Baiscally, all we did was added a traditional ASMX web service to the project, and called the WCF service from that using native WCF calls. We were then able to return the appropriate types back to the client applications without a significant amount of re-factoring work. I know it was a hacky solution, but it was the best option we had with such a large legacy code-base. And the added bonus is that it actually works surprisingly well.:)
WCF Service - Backward compatibility issue I'm just getting into creating some WCF services, but I have a requirement to make them backward compatible for legacy (.NET 1.1 and 2.0) client applications. I've managed to get the services to run correctly for 3.0 and greater clients, but when I publish the services using a basicHttpBinding endpoint (which I believe is required for the compatibility I need), the service refactors my method signatures. e.g. public bool MethodToReturnTrue(string seedValue); appears to the client apps as public void MethodToReturnTrue(string seedValue, out bool result, out bool MethodToReturnTrueResultSpecified); I've tried every configuration parameter I can think of in the app.config for my self-hosting console app, but I can't seem to make this function as expected. I suppose this might lead to the fact that my expectations are flawed, but I'd be surprised that a WCF service is incapable of handling a bool return type to a down-level client. My current app.config looks like this. Can anyone advise, please?
TITLE: WCF Service - Backward compatibility issue QUESTION: I'm just getting into creating some WCF services, but I have a requirement to make them backward compatible for legacy (.NET 1.1 and 2.0) client applications. I've managed to get the services to run correctly for 3.0 and greater clients, but when I publish the services using a basicHttpBinding endpoint (which I believe is required for the compatibility I need), the service refactors my method signatures. e.g. public bool MethodToReturnTrue(string seedValue); appears to the client apps as public void MethodToReturnTrue(string seedValue, out bool result, out bool MethodToReturnTrueResultSpecified); I've tried every configuration parameter I can think of in the app.config for my self-hosting console app, but I can't seem to make this function as expected. I suppose this might lead to the fact that my expectations are flawed, but I'd be surprised that a WCF service is incapable of handling a bool return type to a down-level client. My current app.config looks like this. Can anyone advise, please? ANSWER: OK, we needed to resolve this issue in the short term, and so we came up with the idea of a "interop", or compatibility layer. Baiscally, all we did was added a traditional ASMX web service to the project, and called the WCF service from that using native WCF calls. We were then able to return the appropriate types back to the client applications without a significant amount of re-factoring work. I know it was a hacky solution, but it was the best option we had with such a large legacy code-base. And the added bonus is that it actually works surprisingly well.:)
[ "c#", ".net", "wcf", "web-services", "backwards-compatibility" ]
10
3
2,822
3
0
2008-08-08T12:48:25.197000
2008-08-19T10:45:19.497000
5,872
5,887
Making a production build of a PHP project with Subversion
If you are working in PHP (or I guess any programming language) and using subversion as your source control, is there a way to take your project (for example): C:\Projects\test\.svn C:\Projects\test\docs\ C:\Projects\test\faq.php C:\Projects\test\guestbook.php C:\Projects\test\index.php C:\Projects\test\test.php and build/copy/whatever it so it weeds out certain files and becomes: C:\Projects\test\faq.php C:\Projects\test\guestbook.php C:\Projects\test\index.php automatically? I'm getting tired of making a branch, and then going through the branch and deleting all of the ".svn" folders, the docs directory, and my prototyping files. I know I could probably use a.bat file to only copy the specific files I want, but I was hoping there was some way with subversion to sort of pseudo ignore a file, to where it will still version it, but where you could make a snapshot of the project that ignores the files you told it to pseudo ignore. I know I read online somewhere about some functionality that at least lets you copy without the.svn folders, but I can't find it now.
If you use TortoiseSVN, you can use the export feature to automatically strip out all of the.svn files. I think other svn things have the same feature. Right click the root project folder, then select TortoiseSVN > Export, and tell it where you want the.svn free directory.
Making a production build of a PHP project with Subversion If you are working in PHP (or I guess any programming language) and using subversion as your source control, is there a way to take your project (for example): C:\Projects\test\.svn C:\Projects\test\docs\ C:\Projects\test\faq.php C:\Projects\test\guestbook.php C:\Projects\test\index.php C:\Projects\test\test.php and build/copy/whatever it so it weeds out certain files and becomes: C:\Projects\test\faq.php C:\Projects\test\guestbook.php C:\Projects\test\index.php automatically? I'm getting tired of making a branch, and then going through the branch and deleting all of the ".svn" folders, the docs directory, and my prototyping files. I know I could probably use a.bat file to only copy the specific files I want, but I was hoping there was some way with subversion to sort of pseudo ignore a file, to where it will still version it, but where you could make a snapshot of the project that ignores the files you told it to pseudo ignore. I know I read online somewhere about some functionality that at least lets you copy without the.svn folders, but I can't find it now.
TITLE: Making a production build of a PHP project with Subversion QUESTION: If you are working in PHP (or I guess any programming language) and using subversion as your source control, is there a way to take your project (for example): C:\Projects\test\.svn C:\Projects\test\docs\ C:\Projects\test\faq.php C:\Projects\test\guestbook.php C:\Projects\test\index.php C:\Projects\test\test.php and build/copy/whatever it so it weeds out certain files and becomes: C:\Projects\test\faq.php C:\Projects\test\guestbook.php C:\Projects\test\index.php automatically? I'm getting tired of making a branch, and then going through the branch and deleting all of the ".svn" folders, the docs directory, and my prototyping files. I know I could probably use a.bat file to only copy the specific files I want, but I was hoping there was some way with subversion to sort of pseudo ignore a file, to where it will still version it, but where you could make a snapshot of the project that ignores the files you told it to pseudo ignore. I know I read online somewhere about some functionality that at least lets you copy without the.svn folders, but I can't find it now. ANSWER: If you use TortoiseSVN, you can use the export feature to automatically strip out all of the.svn files. I think other svn things have the same feature. Right click the root project folder, then select TortoiseSVN > Export, and tell it where you want the.svn free directory.
[ "php", "svn", "scripting", "tortoisesvn", "build-process" ]
6
6
2,313
3
0
2008-08-08T12:57:55.880000
2008-08-08T13:10:13.250000
5,880
5,885
Are there any negative reasons to use an N-Tier solution?
I'm pretty new to my company (2 weeks) and we're starting a new platform for our system using.NET 3.5 Team Foundation from DotNetNuke. Our "architect" is suggesting we use one class project. Of course, I chime back with a "3-tier" architecture (Business, Data, Web class projects). Is there any disadvantages to using this architecture? Pro's would be separation of code from data, keeping class objects away from your code, etc.
I guess a fairly big downside is that the extra volume of code that you have to write, manage and maintain for a small project may just be overkill. It's all down to what's appropriate for the size of the project, the expected life of the final project and the budget! Sometimes, whilst doing things 'properly' is appealing, doing something a little more 'lightweight' can be the right commercial decision!
Are there any negative reasons to use an N-Tier solution? I'm pretty new to my company (2 weeks) and we're starting a new platform for our system using.NET 3.5 Team Foundation from DotNetNuke. Our "architect" is suggesting we use one class project. Of course, I chime back with a "3-tier" architecture (Business, Data, Web class projects). Is there any disadvantages to using this architecture? Pro's would be separation of code from data, keeping class objects away from your code, etc.
TITLE: Are there any negative reasons to use an N-Tier solution? QUESTION: I'm pretty new to my company (2 weeks) and we're starting a new platform for our system using.NET 3.5 Team Foundation from DotNetNuke. Our "architect" is suggesting we use one class project. Of course, I chime back with a "3-tier" architecture (Business, Data, Web class projects). Is there any disadvantages to using this architecture? Pro's would be separation of code from data, keeping class objects away from your code, etc. ANSWER: I guess a fairly big downside is that the extra volume of code that you have to write, manage and maintain for a small project may just be overkill. It's all down to what's appropriate for the size of the project, the expected life of the final project and the budget! Sometimes, whilst doing things 'properly' is appealing, doing something a little more 'lightweight' can be the right commercial decision!
[ "architecture", "n-tier-architecture" ]
10
9
2,201
6
0
2008-08-08T13:04:02.980000
2008-08-08T13:08:40.927000
5,892
5,903
Link issues (VC6)
I've opened an old workspace that is a library and its test harness. It used to work fine but now doesn't and older versions of the code don't work either with the same errors. I've tried recreating the project and that causes the same errors too. Nothing seems out of order in project settings and the code generated works in the main app. I've stripped out most of the files and got it down to the bare minimum to generate the error. Unfortunately, I can't post the project as this is used in production code. The LNK2001 linker error I get usually means I've left off a library or forgot to implement a virtual function. However, this is part of the standard template library - and is a header at that. The code that is listed as having the problem in IOCompletionPort.obj doesn't actually use std::string directly, but does call a class that does: Comms::Exception accepts a std::string and the value of GetLastError or WSAGetLastError. The function mentioned in the error ( GetMessage ) is implemented but is a virtual function so other classes can override it if need be. However it appears that the compiler has made it as an ANSI version, but I can't find any options in the settings that would control that. I suspect that might be the problem but since there's very little in the way of options for the library I have no way of knowing for sure. However, both projects specify _MBCS in the compiler options. --------------------Configuration: TestComms - Win32 Debug-------------------- Linking... Comms.lib(IOCompletionPort.obj): error LNK2001: unresolved external symbol "public: virtual class std::basic_string __thiscall Comms::Exception::GetMessageA(void)const " (?GetMessageA@ Exception@Comms@@UBE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) Debug/TestComms.exe: fatal error LNK1120: 1 unresolved externals Error executing link.exe. TestComms.exe - 2 error(s), 0 warning(s) Any suggestions? I've lost most of the morning to this and don't want to lose most of the afternoon too.
One possibility lies with Win32 ANSI/Unicode "name-mangling", which turns the symbol GetMessage into either GetMessageA or GetMessageW. There are three possibilities: Windows.h hasn't been loaded, so GetMessage stays GetMessage Windows.h was loaded with symbols set for ANSI, so GetMessage becomes GetMessageA Windows.h was loaded with symbols set for Unicode, so GetMessage becomes GetMessageW If you've compiled two different files in ways that trigger two different scenarios, you'll get a linker error. The error message indicates that the Comms::Exception class was an instance of #2, above -- perhaps it's used somewhere that windows.h hasn't been loaded? Other things I'd do in your place, just as a matter of routine: 1) Ensure that my include and library paths don't contain anything that I'm not expecting. 2) Do a "build clean" and then manually verify it, deleting any extra object files if necessary. 3) Make sure there aren't any hardcoded paths in include statements that don't mean what they meant when the project was originally rebuilt. EDIT: Fighting with the formatting:(
Link issues (VC6) I've opened an old workspace that is a library and its test harness. It used to work fine but now doesn't and older versions of the code don't work either with the same errors. I've tried recreating the project and that causes the same errors too. Nothing seems out of order in project settings and the code generated works in the main app. I've stripped out most of the files and got it down to the bare minimum to generate the error. Unfortunately, I can't post the project as this is used in production code. The LNK2001 linker error I get usually means I've left off a library or forgot to implement a virtual function. However, this is part of the standard template library - and is a header at that. The code that is listed as having the problem in IOCompletionPort.obj doesn't actually use std::string directly, but does call a class that does: Comms::Exception accepts a std::string and the value of GetLastError or WSAGetLastError. The function mentioned in the error ( GetMessage ) is implemented but is a virtual function so other classes can override it if need be. However it appears that the compiler has made it as an ANSI version, but I can't find any options in the settings that would control that. I suspect that might be the problem but since there's very little in the way of options for the library I have no way of knowing for sure. However, both projects specify _MBCS in the compiler options. --------------------Configuration: TestComms - Win32 Debug-------------------- Linking... Comms.lib(IOCompletionPort.obj): error LNK2001: unresolved external symbol "public: virtual class std::basic_string __thiscall Comms::Exception::GetMessageA(void)const " (?GetMessageA@ Exception@Comms@@UBE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) Debug/TestComms.exe: fatal error LNK1120: 1 unresolved externals Error executing link.exe. TestComms.exe - 2 error(s), 0 warning(s) Any suggestions? I've lost most of the morning to this and don't want to lose most of the afternoon too.
TITLE: Link issues (VC6) QUESTION: I've opened an old workspace that is a library and its test harness. It used to work fine but now doesn't and older versions of the code don't work either with the same errors. I've tried recreating the project and that causes the same errors too. Nothing seems out of order in project settings and the code generated works in the main app. I've stripped out most of the files and got it down to the bare minimum to generate the error. Unfortunately, I can't post the project as this is used in production code. The LNK2001 linker error I get usually means I've left off a library or forgot to implement a virtual function. However, this is part of the standard template library - and is a header at that. The code that is listed as having the problem in IOCompletionPort.obj doesn't actually use std::string directly, but does call a class that does: Comms::Exception accepts a std::string and the value of GetLastError or WSAGetLastError. The function mentioned in the error ( GetMessage ) is implemented but is a virtual function so other classes can override it if need be. However it appears that the compiler has made it as an ANSI version, but I can't find any options in the settings that would control that. I suspect that might be the problem but since there's very little in the way of options for the library I have no way of knowing for sure. However, both projects specify _MBCS in the compiler options. --------------------Configuration: TestComms - Win32 Debug-------------------- Linking... Comms.lib(IOCompletionPort.obj): error LNK2001: unresolved external symbol "public: virtual class std::basic_string __thiscall Comms::Exception::GetMessageA(void)const " (?GetMessageA@ Exception@Comms@@UBE?AV?$basic_string@DU?$char_traits@D@std@@V?$allocator@D@2@@std@@XZ) Debug/TestComms.exe: fatal error LNK1120: 1 unresolved externals Error executing link.exe. TestComms.exe - 2 error(s), 0 warning(s) Any suggestions? I've lost most of the morning to this and don't want to lose most of the afternoon too. ANSWER: One possibility lies with Win32 ANSI/Unicode "name-mangling", which turns the symbol GetMessage into either GetMessageA or GetMessageW. There are three possibilities: Windows.h hasn't been loaded, so GetMessage stays GetMessage Windows.h was loaded with symbols set for ANSI, so GetMessage becomes GetMessageA Windows.h was loaded with symbols set for Unicode, so GetMessage becomes GetMessageW If you've compiled two different files in ways that trigger two different scenarios, you'll get a linker error. The error message indicates that the Comms::Exception class was an instance of #2, above -- perhaps it's used somewhere that windows.h hasn't been loaded? Other things I'd do in your place, just as a matter of routine: 1) Ensure that my include and library paths don't contain anything that I'm not expecting. 2) Do a "build clean" and then manually verify it, deleting any extra object files if necessary. 3) Make sure there aren't any hardcoded paths in include statements that don't mean what they meant when the project was originally rebuilt. EDIT: Fighting with the formatting:(
[ "c++", "visual-c++", "linker", "visual-c++-6" ]
11
6
1,355
5
0
2008-08-08T13:13:08.920000
2008-08-08T13:30:03.507000
5,908
5,914
User access log to SQL Server
I need to get a log of user access to our SQL Server so I can track average and peak concurrency usage. Is there a hidden table or something I'm missing that has this information for me? To my knowledge the application I'm looking at does not track this at the application level. I'm currently working on SQL Server 2000, but will moving to SQL Server 2005 shortly, so solutions for both are greatly appreciated.
In SQL Server 2005, go to tree view on the left and select Server (name of the actual server) > Management > Activity Monitor. Hope this helps.
User access log to SQL Server I need to get a log of user access to our SQL Server so I can track average and peak concurrency usage. Is there a hidden table or something I'm missing that has this information for me? To my knowledge the application I'm looking at does not track this at the application level. I'm currently working on SQL Server 2000, but will moving to SQL Server 2005 shortly, so solutions for both are greatly appreciated.
TITLE: User access log to SQL Server QUESTION: I need to get a log of user access to our SQL Server so I can track average and peak concurrency usage. Is there a hidden table or something I'm missing that has this information for me? To my knowledge the application I'm looking at does not track this at the application level. I'm currently working on SQL Server 2000, but will moving to SQL Server 2005 shortly, so solutions for both are greatly appreciated. ANSWER: In SQL Server 2005, go to tree view on the left and select Server (name of the actual server) > Management > Activity Monitor. Hope this helps.
[ "sql-server", "logging", "statistics" ]
7
7
20,952
2
0
2008-08-08T13:34:38.770000
2008-08-08T13:36:47.923000
5,909
5,985
Get size of a file before downloading in Python
I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server? import urllib import re url = "http://www.someurl.com" # Download the page locally f = urllib.urlopen(url) html = f.read() f.close() f = open ("temp.htm", "w") f.write (html) f.close() # List only the.TXT /.ZIP files fnames = re.findall('^.* @Jon: thank for your quick answer. It works, but the filesize on the web server is slightly less than the filesize of the downloaded file. Examples: Local Size Server Size 2.223.533 2.115.516 664.603 662.121 It has anything to do with the CR/LF conversion?
I have reproduced what you are seeing: import urllib, os link = "http://python.org" print "opening url:", link site = urllib.urlopen(link) meta = site.info() print "Content-Length:", meta.getheaders("Content-Length")[0] f = open("out.txt", "r") print "File on disk:",len(f.read()) f.close() f = open("out.txt", "w") f.write(site.read()) site.close() f.close() f = open("out.txt", "r") print "File on disk after download:",len(f.read()) f.close() print "os.stat().st_size returns:", os.stat("out.txt").st_size Outputs this: opening url: http://python.org Content-Length: 16535 File on disk: 16535 File on disk after download: 16535 os.stat().st_size returns: 16861 What am I doing wrong here? Is os.stat().st_size not returning the correct size? Edit: OK, I figured out what the problem was: import urllib, os link = "http://python.org" print "opening url:", link site = urllib.urlopen(link) meta = site.info() print "Content-Length:", meta.getheaders("Content-Length")[0] f = open("out.txt", "rb") print "File on disk:",len(f.read()) f.close() f = open("out.txt", "wb") f.write(site.read()) site.close() f.close() f = open("out.txt", "rb") print "File on disk after download:",len(f.read()) f.close() print "os.stat().st_size returns:", os.stat("out.txt").st_size this outputs: $ python test.py opening url: http://python.org Content-Length: 16535 File on disk: 16535 File on disk after download: 16535 os.stat().st_size returns: 16535 Make sure you are opening both files for binary read/write. // open for binary write open(filename, "wb") // open for binary read open(filename, "rb")
Get size of a file before downloading in Python I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server? import urllib import re url = "http://www.someurl.com" # Download the page locally f = urllib.urlopen(url) html = f.read() f.close() f = open ("temp.htm", "w") f.write (html) f.close() # List only the.TXT /.ZIP files fnames = re.findall('^.* @Jon: thank for your quick answer. It works, but the filesize on the web server is slightly less than the filesize of the downloaded file. Examples: Local Size Server Size 2.223.533 2.115.516 664.603 662.121 It has anything to do with the CR/LF conversion?
TITLE: Get size of a file before downloading in Python QUESTION: I'm downloading an entire directory from a web server. It works OK, but I can't figure how to get the file size before download to compare if it was updated on the server or not. Can this be done as if I was downloading the file from a FTP server? import urllib import re url = "http://www.someurl.com" # Download the page locally f = urllib.urlopen(url) html = f.read() f.close() f = open ("temp.htm", "w") f.write (html) f.close() # List only the.TXT /.ZIP files fnames = re.findall('^.* @Jon: thank for your quick answer. It works, but the filesize on the web server is slightly less than the filesize of the downloaded file. Examples: Local Size Server Size 2.223.533 2.115.516 664.603 662.121 It has anything to do with the CR/LF conversion? ANSWER: I have reproduced what you are seeing: import urllib, os link = "http://python.org" print "opening url:", link site = urllib.urlopen(link) meta = site.info() print "Content-Length:", meta.getheaders("Content-Length")[0] f = open("out.txt", "r") print "File on disk:",len(f.read()) f.close() f = open("out.txt", "w") f.write(site.read()) site.close() f.close() f = open("out.txt", "r") print "File on disk after download:",len(f.read()) f.close() print "os.stat().st_size returns:", os.stat("out.txt").st_size Outputs this: opening url: http://python.org Content-Length: 16535 File on disk: 16535 File on disk after download: 16535 os.stat().st_size returns: 16861 What am I doing wrong here? Is os.stat().st_size not returning the correct size? Edit: OK, I figured out what the problem was: import urllib, os link = "http://python.org" print "opening url:", link site = urllib.urlopen(link) meta = site.info() print "Content-Length:", meta.getheaders("Content-Length")[0] f = open("out.txt", "rb") print "File on disk:",len(f.read()) f.close() f = open("out.txt", "wb") f.write(site.read()) site.close() f.close() f = open("out.txt", "rb") print "File on disk after download:",len(f.read()) f.close() print "os.stat().st_size returns:", os.stat("out.txt").st_size this outputs: $ python test.py opening url: http://python.org Content-Length: 16535 File on disk: 16535 File on disk after download: 16535 os.stat().st_size returns: 16535 Make sure you are opening both files for binary read/write. // open for binary write open(filename, "wb") // open for binary read open(filename, "rb")
[ "python", "urllib" ]
57
40
58,368
12
0
2008-08-08T13:35:19.970000
2008-08-08T14:21:51.107000
5,913
5,947
Getting the text from a drop-down box
This gets the value of whatever is selected in my dropdown menu. document.getElementById('newSkill').value I cannot however find out what property to go after for the text that's currently displayed by the drop down menu. I tried "text" then looked at W3Schools but that didn't have the answer, does anybody here know? For those not sure, here's the HTML for a drop down box. A skill Another skill Yet another skill
Based on your example HTML code, here's one way to get the displayed text of the currently selected option: var skillsSelect = document.getElementById("newSkill"); var selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;
Getting the text from a drop-down box This gets the value of whatever is selected in my dropdown menu. document.getElementById('newSkill').value I cannot however find out what property to go after for the text that's currently displayed by the drop down menu. I tried "text" then looked at W3Schools but that didn't have the answer, does anybody here know? For those not sure, here's the HTML for a drop down box. A skill Another skill Yet another skill
TITLE: Getting the text from a drop-down box QUESTION: This gets the value of whatever is selected in my dropdown menu. document.getElementById('newSkill').value I cannot however find out what property to go after for the text that's currently displayed by the drop down menu. I tried "text" then looked at W3Schools but that didn't have the answer, does anybody here know? For those not sure, here's the HTML for a drop down box. A skill Another skill Yet another skill ANSWER: Based on your example HTML code, here's one way to get the displayed text of the currently selected option: var skillsSelect = document.getElementById("newSkill"); var selectedText = skillsSelect.options[skillsSelect.selectedIndex].text;
[ "javascript", "dom", "browser", "client-side" ]
89
154
263,322
14
0
2008-08-08T13:36:16.877000
2008-08-08T13:54:55.983000
5,916
7,767
How do you feel about code folding?
For those of you in the Visual Studio environment, how do you feel about wrapping any of your code in #regions? (or if any other IDE has something similar...)
9 out of 10 times, code folding means that you have failed to use the SoC principle for what its worth. I more or less feel the same thing about partial classes. If you have a piece of code you think is too big you need to chop it up in manageable (and reusable) parts, not hide or split it up. It will bite you the next time someone needs to change it, and cannot see the logic hidden in a 250 line monster of a method. Whenever you can, pull some code out of the main class, and into a helper or factory class. foreach (var item in Items) { //.. 100 lines of validation and data logic.. } is not as readable as foreach (var item in Items) { if (ValidatorClass.Validate(item)) RepositoryClass.Update(item); } My $0.02 anyways.
How do you feel about code folding? For those of you in the Visual Studio environment, how do you feel about wrapping any of your code in #regions? (or if any other IDE has something similar...)
TITLE: How do you feel about code folding? QUESTION: For those of you in the Visual Studio environment, how do you feel about wrapping any of your code in #regions? (or if any other IDE has something similar...) ANSWER: 9 out of 10 times, code folding means that you have failed to use the SoC principle for what its worth. I more or less feel the same thing about partial classes. If you have a piece of code you think is too big you need to chop it up in manageable (and reusable) parts, not hide or split it up. It will bite you the next time someone needs to change it, and cannot see the logic hidden in a 250 line monster of a method. Whenever you can, pull some code out of the main class, and into a helper or factory class. foreach (var item in Items) { //.. 100 lines of validation and data logic.. } is not as readable as foreach (var item in Items) { if (ValidatorClass.Validate(item)) RepositoryClass.Update(item); } My $0.02 anyways.
[ "visual-studio", "folding" ]
26
37
7,321
24
0
2008-08-08T13:38:30.260000
2008-08-11T13:17:40.453000
5,918
5,984
API Yahoo India Maps
Yahoo has separate map for India ( which has more details than the regular maps.yahoo.com) at http://in.maps.yahoo.com/. But when I use the API it goes to default map. How do I get API access to YMaps India?
I don't know about yahoo, but there is another mapping website that provides an API for India. http://biz.mapmyindia.com/APIs.html
API Yahoo India Maps Yahoo has separate map for India ( which has more details than the regular maps.yahoo.com) at http://in.maps.yahoo.com/. But when I use the API it goes to default map. How do I get API access to YMaps India?
TITLE: API Yahoo India Maps QUESTION: Yahoo has separate map for India ( which has more details than the regular maps.yahoo.com) at http://in.maps.yahoo.com/. But when I use the API it goes to default map. How do I get API access to YMaps India? ANSWER: I don't know about yahoo, but there is another mapping website that provides an API for India. http://biz.mapmyindia.com/APIs.html
[ "yahoo-api", "yahoo-maps" ]
5
1
1,302
1
0
2008-08-08T13:39:03.487000
2008-08-08T14:21:09.830000
5,948
587,244
Always Commit the same file with SVN
In my web application I have a file which hold the current revision number via $Rev$. This work fine except, if I don't make any changes to that file, it doesn't get committed. Is there anyway I can force a single file to always get committed to the SVN server? I'm using TortoiseSVN for Windows so any code or step-by-step instructions would be helpful.
If you have TortoiseSVN installed, you also have the SubWCRev tool available. Use that tool to get the revision instead of misusing the $REV$ keyword. create a template file which contains your defines, maybe something like const long WC_REV = $WCREV$; in a file named version.h.tmpl on every build, call SubWCRev to create the 'real' file you can use in your application: SubWCRev path\to\workingcopy path\to\version.h.tmpl path\to\version.h This will create the file version.h from version.h.tmpl, with the text $WCREV$ replaced with the revision your working copy is currently at. The docs for SubWCRev might help too.
Always Commit the same file with SVN In my web application I have a file which hold the current revision number via $Rev$. This work fine except, if I don't make any changes to that file, it doesn't get committed. Is there anyway I can force a single file to always get committed to the SVN server? I'm using TortoiseSVN for Windows so any code or step-by-step instructions would be helpful.
TITLE: Always Commit the same file with SVN QUESTION: In my web application I have a file which hold the current revision number via $Rev$. This work fine except, if I don't make any changes to that file, it doesn't get committed. Is there anyway I can force a single file to always get committed to the SVN server? I'm using TortoiseSVN for Windows so any code or step-by-step instructions would be helpful. ANSWER: If you have TortoiseSVN installed, you also have the SubWCRev tool available. Use that tool to get the revision instead of misusing the $REV$ keyword. create a template file which contains your defines, maybe something like const long WC_REV = $WCREV$; in a file named version.h.tmpl on every build, call SubWCRev to create the 'real' file you can use in your application: SubWCRev path\to\workingcopy path\to\version.h.tmpl path\to\version.h This will create the file version.h from version.h.tmpl, with the text $WCREV$ replaced with the revision your working copy is currently at. The docs for SubWCRev might help too.
[ "svn" ]
10
9
4,411
13
0
2008-08-08T13:55:04.453000
2009-02-25T18:32:54.177000
5,949
5,963
What's your opinion on using UUIDs as database row identifiers, particularly in web apps?
I've always preferred to use long integers as primary keys in databases, for simplicity and (assumed) speed. But when using a REST or Rails-like URL scheme for object instances, I'd then end up with URLs like this: http://example.com/user/783 And then the assumption is that there are also users with IDs of 782, 781,..., 2, and 1. Assuming that the web app in question is secure enough to prevent people entering other numbers to view other users without authorization, a simple sequentially-assigned surrogate key also "leaks" the total number of instances (older than this one), in this case users, which might be privileged information. (For instance, I am user #726 in stackoverflow.) Would a UUID /GUID be a better solution? Then I could set up URLs like this: http://example.com/user/035a46e0-6550-11dd-ad8b-0800200c9a66 Not exactly succinct, but there's less implied information about users on display. Sure, it smacks of "security through obscurity" which is no substitute for proper security, but it seems at least a little more secure. Is that benefit worth the cost and complexity of implementing UUIDs for web-addressable object instances? I think that I'd still want to use integer columns as database PKs just to speed up joins. There's also the question of in-database representation of UUIDs. I know MySQL stores them as 36-character strings. Postgres seems to have a more efficient internal representation (128 bits?) but I haven't tried it myself. Anyone have any experience with this? Update: for those who asked about just using the user name in the URL (e.g., http://example.com/user/yukondude ), that works fine for object instances with names that are unique, but what about the zillions of web app objects that can really only be identified by number? Orders, transactions, invoices, duplicate image names, stackoverflow questions,...
I can't say about the web side of your question. But uuids are great for n-tier applications. PK generation can be decentralized: each client generates it's own pk without risk of collision. And the speed difference is generally small. Make sure your database supports an efficient storage datatype (16 bytes, 128 bits). At the very least you can encode the uuid string in base64 and use char(22). I've used them extensively with Firebird and do recommend.
What's your opinion on using UUIDs as database row identifiers, particularly in web apps? I've always preferred to use long integers as primary keys in databases, for simplicity and (assumed) speed. But when using a REST or Rails-like URL scheme for object instances, I'd then end up with URLs like this: http://example.com/user/783 And then the assumption is that there are also users with IDs of 782, 781,..., 2, and 1. Assuming that the web app in question is secure enough to prevent people entering other numbers to view other users without authorization, a simple sequentially-assigned surrogate key also "leaks" the total number of instances (older than this one), in this case users, which might be privileged information. (For instance, I am user #726 in stackoverflow.) Would a UUID /GUID be a better solution? Then I could set up URLs like this: http://example.com/user/035a46e0-6550-11dd-ad8b-0800200c9a66 Not exactly succinct, but there's less implied information about users on display. Sure, it smacks of "security through obscurity" which is no substitute for proper security, but it seems at least a little more secure. Is that benefit worth the cost and complexity of implementing UUIDs for web-addressable object instances? I think that I'd still want to use integer columns as database PKs just to speed up joins. There's also the question of in-database representation of UUIDs. I know MySQL stores them as 36-character strings. Postgres seems to have a more efficient internal representation (128 bits?) but I haven't tried it myself. Anyone have any experience with this? Update: for those who asked about just using the user name in the URL (e.g., http://example.com/user/yukondude ), that works fine for object instances with names that are unique, but what about the zillions of web app objects that can really only be identified by number? Orders, transactions, invoices, duplicate image names, stackoverflow questions,...
TITLE: What's your opinion on using UUIDs as database row identifiers, particularly in web apps? QUESTION: I've always preferred to use long integers as primary keys in databases, for simplicity and (assumed) speed. But when using a REST or Rails-like URL scheme for object instances, I'd then end up with URLs like this: http://example.com/user/783 And then the assumption is that there are also users with IDs of 782, 781,..., 2, and 1. Assuming that the web app in question is secure enough to prevent people entering other numbers to view other users without authorization, a simple sequentially-assigned surrogate key also "leaks" the total number of instances (older than this one), in this case users, which might be privileged information. (For instance, I am user #726 in stackoverflow.) Would a UUID /GUID be a better solution? Then I could set up URLs like this: http://example.com/user/035a46e0-6550-11dd-ad8b-0800200c9a66 Not exactly succinct, but there's less implied information about users on display. Sure, it smacks of "security through obscurity" which is no substitute for proper security, but it seems at least a little more secure. Is that benefit worth the cost and complexity of implementing UUIDs for web-addressable object instances? I think that I'd still want to use integer columns as database PKs just to speed up joins. There's also the question of in-database representation of UUIDs. I know MySQL stores them as 36-character strings. Postgres seems to have a more efficient internal representation (128 bits?) but I haven't tried it myself. Anyone have any experience with this? Update: for those who asked about just using the user name in the URL (e.g., http://example.com/user/yukondude ), that works fine for object instances with names that are unique, but what about the zillions of web app objects that can really only be identified by number? Orders, transactions, invoices, duplicate image names, stackoverflow questions,... ANSWER: I can't say about the web side of your question. But uuids are great for n-tier applications. PK generation can be decentralized: each client generates it's own pk without risk of collision. And the speed difference is generally small. Make sure your database supports an efficient storage datatype (16 bytes, 128 bits). At the very least you can encode the uuid string in base64 and use char(22). I've used them extensively with Firebird and do recommend.
[ "database", "web-applications", "uuid" ]
83
34
28,087
16
0
2008-08-08T13:55:48.773000
2008-08-08T14:03:00.833000
5,966
10,778
Best way to abstract season/show/episode data
Basically, I've written an API to www.thetvdb.com in Python. The current code can be found here. It grabs data from the API as requested, and has to store the data somehow, and make it available by doing: print tvdbinstance[1][23]['episodename'] # get the name of episode 23 of season 1 What is the "best" way to abstract this data within the Tvdb() class? I originally used a extended Dict() that automatically created sub-dicts (so you could do x[1][2][3][4] = "something" without having to do if x[1].has_key(2): x[1][2] = [] and so on) Then I just stored the data by doing self.data[show_id][season_number][episode_number][attribute_name] = "something" This worked okay, but there was no easy way of checking if x[3][24] was supposed to exist or not (so I couldn't raise the season_not_found exception). Currently it's using four classes: ShowContainer, Show, Season and Episode. Each one is a very basic dict, which I can easily add extra functionality in (the search() function on Show() for example). Each has a __setitem__, __getitem_ and has_key. This works mostly fine, I can check in Shows if it has that season in it's self.data dict, if not, raise season_not_found. I can also check in Season() if it has that episode and so on. The problem now is it's presenting itself as a dict, but doesn't have all the functionality, and because I'm overriding the __getitem__ and __setitem__ functions, it's easy to accidentally recursively call __getitem__ (so I'm not sure if extending the Dict class will cause problems). The other slight problem is adding data into the dict is a lot more work than the old Dict method (which was self.data[seas_no][ep_no]['attribute'] = 'something' ). See _setItem and _setData. It's not too bad, since it's currently only a read-only API interface (so the users of the API should only ever retrieve data, not add more), but it's hardly... Elegant. I think the series-of-classes system is probably the best way, but does anyone have a better idea for storing the data? And would extending the ShowContainer /etc classes with Dict cause problems?
OK, what you need is classobj from new module. That would allow you to construct exception classes dynamically ( classobj takes a string as an argument for the class name). import new myexc=new.classobj("ExcName",(Exception,),{}) i=myexc("This is the exc msg!") raise i this gives you: Traceback (most recent call last): File " ", line 1, in __main__.ExcName: This is the exc msg! remember that you can always get the class name through: self.__class__.__name__ So, after some string mangling and concatenation, you should be able to obtain appropriate exception class name and construct a class object using that name and then raise that exception. P.S. - you can also raise strings, but this is deprecated. raise(self.__class__.__name__+"Exception")
Best way to abstract season/show/episode data Basically, I've written an API to www.thetvdb.com in Python. The current code can be found here. It grabs data from the API as requested, and has to store the data somehow, and make it available by doing: print tvdbinstance[1][23]['episodename'] # get the name of episode 23 of season 1 What is the "best" way to abstract this data within the Tvdb() class? I originally used a extended Dict() that automatically created sub-dicts (so you could do x[1][2][3][4] = "something" without having to do if x[1].has_key(2): x[1][2] = [] and so on) Then I just stored the data by doing self.data[show_id][season_number][episode_number][attribute_name] = "something" This worked okay, but there was no easy way of checking if x[3][24] was supposed to exist or not (so I couldn't raise the season_not_found exception). Currently it's using four classes: ShowContainer, Show, Season and Episode. Each one is a very basic dict, which I can easily add extra functionality in (the search() function on Show() for example). Each has a __setitem__, __getitem_ and has_key. This works mostly fine, I can check in Shows if it has that season in it's self.data dict, if not, raise season_not_found. I can also check in Season() if it has that episode and so on. The problem now is it's presenting itself as a dict, but doesn't have all the functionality, and because I'm overriding the __getitem__ and __setitem__ functions, it's easy to accidentally recursively call __getitem__ (so I'm not sure if extending the Dict class will cause problems). The other slight problem is adding data into the dict is a lot more work than the old Dict method (which was self.data[seas_no][ep_no]['attribute'] = 'something' ). See _setItem and _setData. It's not too bad, since it's currently only a read-only API interface (so the users of the API should only ever retrieve data, not add more), but it's hardly... Elegant. I think the series-of-classes system is probably the best way, but does anyone have a better idea for storing the data? And would extending the ShowContainer /etc classes with Dict cause problems?
TITLE: Best way to abstract season/show/episode data QUESTION: Basically, I've written an API to www.thetvdb.com in Python. The current code can be found here. It grabs data from the API as requested, and has to store the data somehow, and make it available by doing: print tvdbinstance[1][23]['episodename'] # get the name of episode 23 of season 1 What is the "best" way to abstract this data within the Tvdb() class? I originally used a extended Dict() that automatically created sub-dicts (so you could do x[1][2][3][4] = "something" without having to do if x[1].has_key(2): x[1][2] = [] and so on) Then I just stored the data by doing self.data[show_id][season_number][episode_number][attribute_name] = "something" This worked okay, but there was no easy way of checking if x[3][24] was supposed to exist or not (so I couldn't raise the season_not_found exception). Currently it's using four classes: ShowContainer, Show, Season and Episode. Each one is a very basic dict, which I can easily add extra functionality in (the search() function on Show() for example). Each has a __setitem__, __getitem_ and has_key. This works mostly fine, I can check in Shows if it has that season in it's self.data dict, if not, raise season_not_found. I can also check in Season() if it has that episode and so on. The problem now is it's presenting itself as a dict, but doesn't have all the functionality, and because I'm overriding the __getitem__ and __setitem__ functions, it's easy to accidentally recursively call __getitem__ (so I'm not sure if extending the Dict class will cause problems). The other slight problem is adding data into the dict is a lot more work than the old Dict method (which was self.data[seas_no][ep_no]['attribute'] = 'something' ). See _setItem and _setData. It's not too bad, since it's currently only a read-only API interface (so the users of the API should only ever retrieve data, not add more), but it's hardly... Elegant. I think the series-of-classes system is probably the best way, but does anyone have a better idea for storing the data? And would extending the ShowContainer /etc classes with Dict cause problems? ANSWER: OK, what you need is classobj from new module. That would allow you to construct exception classes dynamically ( classobj takes a string as an argument for the class name). import new myexc=new.classobj("ExcName",(Exception,),{}) i=myexc("This is the exc msg!") raise i this gives you: Traceback (most recent call last): File " ", line 1, in __main__.ExcName: This is the exc msg! remember that you can always get the class name through: self.__class__.__name__ So, after some string mangling and concatenation, you should be able to obtain appropriate exception class name and construct a class object using that name and then raise that exception. P.S. - you can also raise strings, but this is deprecated. raise(self.__class__.__name__+"Exception")
[ "python", "data-structures" ]
17
7
1,806
5
0
2008-08-08T14:05:45.290000
2008-08-14T07:08:19.280000
5,997
6,018
Should I provide accessor methods / Getter Setters for public/protected components on a form?
If I have.Net Form with a component/object such as a textbox that I need to access from a parent or other form I obviously need to "upgrade" the modifier to this component to an Internal or Public level variable. Now, if I were providing a public variable of an int or string type etc. in my form class I wouldn't think twice about using Getters and (maybe) Setters around this, even if they didn't do anything other than provide direct access to the variable. However, the VS designer doesn't seem to implement such Getters/Setters for those public objects that are components on a form (and therefore does not comply with good programming practice). So, the question is; In order to do the "right thing" should I wrap such VS designer components or objects in a Getter and/or Setter?
" However, the VS designer doesn't seem to implement such Getters/Setters for those public objects that are components on a form (and therefore does not comply with good programming practice). " If you mean the controls you're dragging and dropping onto the form, these are marked as private instance members and are added to the form's Controls collection. Why would they be otherwise? A form could have forty or fifty controls, it'd be somewhat unnecessary and unwieldy to provide a getter/setter for every control on the form. The designer leaves it up to you to provide delegated access to specific controls via public getter/setters. The designer does the right thing here.
Should I provide accessor methods / Getter Setters for public/protected components on a form? If I have.Net Form with a component/object such as a textbox that I need to access from a parent or other form I obviously need to "upgrade" the modifier to this component to an Internal or Public level variable. Now, if I were providing a public variable of an int or string type etc. in my form class I wouldn't think twice about using Getters and (maybe) Setters around this, even if they didn't do anything other than provide direct access to the variable. However, the VS designer doesn't seem to implement such Getters/Setters for those public objects that are components on a form (and therefore does not comply with good programming practice). So, the question is; In order to do the "right thing" should I wrap such VS designer components or objects in a Getter and/or Setter?
TITLE: Should I provide accessor methods / Getter Setters for public/protected components on a form? QUESTION: If I have.Net Form with a component/object such as a textbox that I need to access from a parent or other form I obviously need to "upgrade" the modifier to this component to an Internal or Public level variable. Now, if I were providing a public variable of an int or string type etc. in my form class I wouldn't think twice about using Getters and (maybe) Setters around this, even if they didn't do anything other than provide direct access to the variable. However, the VS designer doesn't seem to implement such Getters/Setters for those public objects that are components on a form (and therefore does not comply with good programming practice). So, the question is; In order to do the "right thing" should I wrap such VS designer components or objects in a Getter and/or Setter? ANSWER: " However, the VS designer doesn't seem to implement such Getters/Setters for those public objects that are components on a form (and therefore does not comply with good programming practice). " If you mean the controls you're dragging and dropping onto the form, these are marked as private instance members and are added to the form's Controls collection. Why would they be otherwise? A form could have forty or fifty controls, it'd be somewhat unnecessary and unwieldy to provide a getter/setter for every control on the form. The designer leaves it up to you to provide delegated access to specific controls via public getter/setters. The designer does the right thing here.
[ ".net", "winforms" ]
6
5
1,492
4
0
2008-08-08T14:35:25.353000
2008-08-08T14:50:30.130000