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 | 7 | How to convert Decimal to Double in C#? | I want to assign the decimal variable "trans" to the double variable "this.Opacity". decimal trans = trackBar1.Value / 5000; this.Opacity = trans; When I build the app it gives the following error: Cannot implicitly convert type decimal to double | An explicit cast to double like this isn't necessary: double trans = (double) trackBar1.Value / 5000.0; Identifying the constant as 5000.0 (or as 5000d ) is sufficient: double trans = trackBar1.Value / 5000.0; double trans = trackBar1.Value / 5000d; | How to convert Decimal to Double in C#? I want to assign the decimal variable "trans" to the double variable "this.Opacity". decimal trans = trackBar1.Value / 5000; this.Opacity = trans; When I build the app it gives the following error: Cannot implicitly convert type decimal to double | TITLE:
How to convert Decimal to Double in C#?
QUESTION:
I want to assign the decimal variable "trans" to the double variable "this.Opacity". decimal trans = trackBar1.Value / 5000; this.Opacity = trans; When I build the app it gives the following error: Cannot implicitly convert type decimal to double
ANSWER:
An explicit cast to double like this isn't necessary: double trans = (double) trackBar1.Value / 5000.0; Identifying the constant as 5000.0 (or as 5000d ) is sufficient: double trans = trackBar1.Value / 5000.0; double trans = trackBar1.Value / 5000d; | [
"c#",
"floating-point",
"type-conversion",
"double",
"decimal"
] | 806 | 529 | 76,733 | 13 | 0 | 2008-07-31T21:42:52.667000 | 2008-07-31T22:17:57.883000 |
6 | 31 | Why did the width collapse in the percentage width child element in an absolutely positioned parent on Internet Explorer 7? | I have an absolutely positioned div containing several children, one of which is a relatively positioned div. When I use a percentage-based width on the child div, it collapses to 0 width on IE7, but not on Firefox or Safari. If I use pixel width, it works. If the parent is relatively positioned, the percentage width on the child works. Is there something I'm missing here? Is there an easy fix for this besides the pixel-based width on the child? Is there an area of the CSS specification that covers this? | The parent div needs to have a defined width, either in pixels or as a percentage. In Internet Explorer 7, the parent div needs a defined width for child percentage div s to work correctly. | Why did the width collapse in the percentage width child element in an absolutely positioned parent on Internet Explorer 7? I have an absolutely positioned div containing several children, one of which is a relatively positioned div. When I use a percentage-based width on the child div, it collapses to 0 width on IE7, but not on Firefox or Safari. If I use pixel width, it works. If the parent is relatively positioned, the percentage width on the child works. Is there something I'm missing here? Is there an easy fix for this besides the pixel-based width on the child? Is there an area of the CSS specification that covers this? | TITLE:
Why did the width collapse in the percentage width child element in an absolutely positioned parent on Internet Explorer 7?
QUESTION:
I have an absolutely positioned div containing several children, one of which is a relatively positioned div. When I use a percentage-based width on the child div, it collapses to 0 width on IE7, but not on Firefox or Safari. If I use pixel width, it works. If the parent is relatively positioned, the percentage width on the child works. Is there something I'm missing here? Is there an easy fix for this besides the pixel-based width on the child? Is there an area of the CSS specification that covers this?
ANSWER:
The parent div needs to have a defined width, either in pixels or as a percentage. In Internet Explorer 7, the parent div needs a defined width for child percentage div s to work correctly. | [
"html",
"css",
"internet-explorer-7"
] | 320 | 160 | 24,503 | 7 | 0 | 2008-07-31T22:08:08.620000 | 2008-08-01T12:22:51.593000 |
9 | 1,404 | How do I calculate someone's age based on a DateTime type birthday? | Given a DateTime representing a person's birthday, how do I calculate their age in years? | An easy to understand and simple solution. // Save today's date. var today = DateTime.Today;
// Calculate the age. var age = today.Year - birthdate.Year;
// Go back to the year in which the person was born in case of a leap year if (birthdate.Date > today.AddYears(-age)) age--; However, this assumes you are looking for the western idea of the age and not using East Asian reckoning. | How do I calculate someone's age based on a DateTime type birthday? Given a DateTime representing a person's birthday, how do I calculate their age in years? | TITLE:
How do I calculate someone's age based on a DateTime type birthday?
QUESTION:
Given a DateTime representing a person's birthday, how do I calculate their age in years?
ANSWER:
An easy to understand and simple solution. // Save today's date. var today = DateTime.Today;
// Calculate the age. var age = today.Year - birthdate.Year;
// Go back to the year in which the person was born in case of a leap year if (birthdate.Date > today.AddYears(-age)) age--; However, this assumes you are looking for the western idea of the age and not using East Asian reckoning. | [
"c#",
".net",
"datetime"
] | 2,248 | 2,417 | 827,598 | 75 | 0 | 2008-07-31T23:40:59.743000 | 2008-08-04T16:50:06.170000 |
11 | 1,248 | Calculate relative time in C# | Given a specific DateTime value, how do I display relative time, like: 2 hours ago 3 days ago a month ago | Jeff, your code is nice but could be clearer with constants (as suggested in Code Complete). const int SECOND = 1; const int MINUTE = 60 * SECOND; const int HOUR = 60 * MINUTE; const int DAY = 24 * HOUR; const int MONTH = 30 * DAY;
var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks); double delta = Math.Abs(ts.TotalSeconds);
if (delta < 1 * MINUTE) return ts.Seconds == 1? "one second ago": ts.Seconds + " seconds ago";
if (delta < 2 * MINUTE) return "a minute ago";
if (delta < 45 * MINUTE) return ts.Minutes + " minutes ago";
if (delta < 90 * MINUTE) return "an hour ago";
if (delta < 24 * HOUR) return ts.Hours + " hours ago";
if (delta < 48 * HOUR) return "yesterday";
if (delta < 30 * DAY) return ts.Days + " days ago";
if (delta < 12 * MONTH) { int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30)); return months <= 1? "one month ago": months + " months ago"; } else { int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365)); return years <= 1? "one year ago": years + " years ago"; } | Calculate relative time in C# Given a specific DateTime value, how do I display relative time, like: 2 hours ago 3 days ago a month ago | TITLE:
Calculate relative time in C#
QUESTION:
Given a specific DateTime value, how do I display relative time, like: 2 hours ago 3 days ago a month ago
ANSWER:
Jeff, your code is nice but could be clearer with constants (as suggested in Code Complete). const int SECOND = 1; const int MINUTE = 60 * SECOND; const int HOUR = 60 * MINUTE; const int DAY = 24 * HOUR; const int MONTH = 30 * DAY;
var ts = new TimeSpan(DateTime.UtcNow.Ticks - yourDate.Ticks); double delta = Math.Abs(ts.TotalSeconds);
if (delta < 1 * MINUTE) return ts.Seconds == 1? "one second ago": ts.Seconds + " seconds ago";
if (delta < 2 * MINUTE) return "a minute ago";
if (delta < 45 * MINUTE) return ts.Minutes + " minutes ago";
if (delta < 90 * MINUTE) return "an hour ago";
if (delta < 24 * HOUR) return ts.Hours + " hours ago";
if (delta < 48 * HOUR) return "yesterday";
if (delta < 30 * DAY) return ts.Days + " days ago";
if (delta < 12 * MONTH) { int months = Convert.ToInt32(Math.Floor((double)ts.Days / 30)); return months <= 1? "one month ago": months + " months ago"; } else { int years = Convert.ToInt32(Math.Floor((double)ts.Days / 365)); return years <= 1? "one year ago": years + " years ago"; } | [
"c#",
"datetime",
"time",
"datediff",
"relative-time-span"
] | 1,653 | 1,070 | 202,800 | 42 | 0 | 2008-07-31T23:55:37.967000 | 2008-08-04T13:57:26.097000 |
16 | 12,446 | Filling a DataSet or a DataTable from a LINQ query result set | How do you expose a LINQ query as an ASMX web service? Usually, from the business tier, I can return a typed DataSet or a DataTable which can be serialized for transport over ASMX. How can I do the same for a LINQ query? Is there a way to populate a typed DataSet or a DataTable via a LINQ query? public static MyDataTable CallMySproc() { string conn = "...";
MyDatabaseDataContext db = new MyDatabaseDataContext(conn); MyDataTable dt = new MyDataTable();
// execute a sproc via LINQ var query = from dr in db.MySproc().AsEnumerable select dr;
// copy LINQ query resultset into a DataTable -this does not work! dt = query.CopyToDataTable();
return dt; } How could I put the result set of a LINQ query into a DataSet or a DataTable? Alternatively, can the LINQ query be serializable so that I can expose it as an ASMX web service? | As mentioned in the question, IEnumerable has a CopyToDataTable method: IEnumerable query = from order in orders.AsEnumerable() where order.Field ("OrderDate") > new DateTime(2001, 8, 1) select order;
// Create a table from the query. DataTable boundTable = query.CopyToDataTable (); Why won't that work for you? | Filling a DataSet or a DataTable from a LINQ query result set How do you expose a LINQ query as an ASMX web service? Usually, from the business tier, I can return a typed DataSet or a DataTable which can be serialized for transport over ASMX. How can I do the same for a LINQ query? Is there a way to populate a typed DataSet or a DataTable via a LINQ query? public static MyDataTable CallMySproc() { string conn = "...";
MyDatabaseDataContext db = new MyDatabaseDataContext(conn); MyDataTable dt = new MyDataTable();
// execute a sproc via LINQ var query = from dr in db.MySproc().AsEnumerable select dr;
// copy LINQ query resultset into a DataTable -this does not work! dt = query.CopyToDataTable();
return dt; } How could I put the result set of a LINQ query into a DataSet or a DataTable? Alternatively, can the LINQ query be serializable so that I can expose it as an ASMX web service? | TITLE:
Filling a DataSet or a DataTable from a LINQ query result set
QUESTION:
How do you expose a LINQ query as an ASMX web service? Usually, from the business tier, I can return a typed DataSet or a DataTable which can be serialized for transport over ASMX. How can I do the same for a LINQ query? Is there a way to populate a typed DataSet or a DataTable via a LINQ query? public static MyDataTable CallMySproc() { string conn = "...";
MyDatabaseDataContext db = new MyDatabaseDataContext(conn); MyDataTable dt = new MyDataTable();
// execute a sproc via LINQ var query = from dr in db.MySproc().AsEnumerable select dr;
// copy LINQ query resultset into a DataTable -this does not work! dt = query.CopyToDataTable();
return dt; } How could I put the result set of a LINQ query into a DataSet or a DataTable? Alternatively, can the LINQ query be serializable so that I can expose it as an ASMX web service?
ANSWER:
As mentioned in the question, IEnumerable has a CopyToDataTable method: IEnumerable query = from order in orders.AsEnumerable() where order.Field ("OrderDate") > new DateTime(2001, 8, 1) select order;
// Create a table from the query. DataTable boundTable = query.CopyToDataTable (); Why won't that work for you? | [
"c#",
"linq",
"web-services",
".net-3.5"
] | 159 | 99 | 88,393 | 7 | 0 | 2008-08-01T04:59:33.643000 | 2008-08-15T16:27:31.600000 |
17 | 26 | Binary Data in MySQL | How do I store binary data in MySQL? | The answer by phpguy is correct but I think there is a lot of confusion in the additional details there. The basic answer is in a BLOB data type / attribute domain. BLOB is short for Binary Large Object and that column data type is specific for handling binary data. See the relevant manual page for MySQL. | Binary Data in MySQL How do I store binary data in MySQL? | TITLE:
Binary Data in MySQL
QUESTION:
How do I store binary data in MySQL?
ANSWER:
The answer by phpguy is correct but I think there is a lot of confusion in the additional details there. The basic answer is in a BLOB data type / attribute domain. BLOB is short for Binary Large Object and that column data type is specific for handling binary data. See the relevant manual page for MySQL. | [
"mysql",
"database",
"binary-data",
"data-storage"
] | 199 | 143 | 87,599 | 9 | 0 | 2008-08-01T05:09:55.993000 | 2008-08-01T12:16:22.167000 |
19 | 531 | What is the fastest way to get the value of π? | I'm looking for the fastest way to obtain the value of π, as a personal challenge. More specifically, I'm using ways that don't involve using #define constants like M_PI, or hard-coding the number in. The program below tests the various ways I know of. The inline assembly version is, in theory, the fastest option, though clearly not portable. I've included it as a baseline to compare against the other versions. In my tests, with built-ins, the 4 * atan(1) version is fastest on GCC 4.2, because it auto-folds the atan(1) into a constant. With -fno-builtin specified, the atan2(0, -1) version is fastest. Here's the main testing program ( pitimes.c ): #include #include #include #define ITERS 10000000 #define TESTWITH(x) { \ diff = 0.0; \ time1 = clock(); \ for (i = 0; i < ITERS; ++i) \ diff += (x) - M_PI; \ time2 = clock(); \ printf("%s\t=> %e, time => %f\n", #x, diff, diffclock(time2, time1)); \ }
static inline double diffclock(clock_t time1, clock_t time0) { return (double) (time1 - time0) / CLOCKS_PER_SEC; }
int main() { int i; clock_t time1, time2; double diff;
/* Warmup. The atan2 case catches GCC's atan folding (which would * optimise the ``4 * atan(1) - M_PI'' to a no-op), if -fno-builtin * is not used. */ TESTWITH(4 * atan(1)) TESTWITH(4 * atan2(1, 1))
#if defined(__GNUC__) && (defined(__i386__) || defined(__amd64__)) extern double fldpi(); TESTWITH(fldpi()) #endif
/* Actual tests start here. */ TESTWITH(atan2(0, -1)) TESTWITH(acos(-1)) TESTWITH(2 * asin(1)) TESTWITH(4 * atan2(1, 1)) TESTWITH(4 * atan(1))
return 0; } And the inline assembly stuff ( fldpi.c ) that will only work for x86 and x64 systems: double fldpi() { double pi; asm("fldpi": "=t" (pi)); return pi; } And a build script that builds all the configurations I'm testing ( build.sh ): #!/bin/sh gcc -O3 -Wall -c -m32 -o fldpi-32.o fldpi.c gcc -O3 -Wall -c -m64 -o fldpi-64.o fldpi.c
gcc -O3 -Wall -ffast-math -m32 -o pitimes1-32 pitimes.c fldpi-32.o gcc -O3 -Wall -m32 -o pitimes2-32 pitimes.c fldpi-32.o -lm gcc -O3 -Wall -fno-builtin -m32 -o pitimes3-32 pitimes.c fldpi-32.o -lm gcc -O3 -Wall -ffast-math -m64 -o pitimes1-64 pitimes.c fldpi-64.o -lm gcc -O3 -Wall -m64 -o pitimes2-64 pitimes.c fldpi-64.o -lm gcc -O3 -Wall -fno-builtin -m64 -o pitimes3-64 pitimes.c fldpi-64.o -lm Apart from testing between various compiler flags (I've compared 32-bit against 64-bit too because the optimizations are different), I've also tried switching the order of the tests around. But still, the atan2(0, -1) version still comes out on top every time. | The Monte Carlo method, as mentioned, applies some great concepts but it is, clearly, not the fastest, not by a long shot, not by any reasonable measure. Also, it all depends on what kind of accuracy you are looking for. The fastest π I know of is the one with the digits hard coded. Looking at Pi and Pi[PDF], there are a lot of formulae. Here is a method that converges quickly — about 14 digits per iteration. PiFast, the current fastest application, uses this formula with the FFT. I'll just write the formula, since the code is straightforward. This formula was almost found by Ramanujan and discovered by Chudnovsky. It is actually how he calculated several billion digits of the number — so it isn't a method to disregard. The formula will overflow quickly and, since we are dividing factorials, it would be advantageous then to delay such calculations to remove terms. where, Below is the Brent–Salamin algorithm. Wikipedia mentions that when a and b are "close enough" then (a + b)² / 4t will be an approximation of π. I'm not sure what "close enough" means, but from my tests, one iteration got 2 digits, two got 7, and three had 15, of course this is with doubles, so it might have an error based on its representation and the true calculation could be more accurate. let pi_2 iters = let rec loop_ a b t p i = if i = 0 then a,b,t,p else let a_n = (a +. b) /. 2.0 and b_n = sqrt (a*.b) and p_n = 2.0 *. p in let t_n = t -. (p *. (a -. a_n) *. (a -. a_n)) in loop_ a_n b_n t_n p_n (i - 1) in let a,b,t,p = loop_ (1.0) (1.0 /. (sqrt 2.0)) (1.0/.4.0) (1.0) iters in (a +. b) *. (a +. b) /. (4.0 *. t) Lastly, how about some pi golf (800 digits)? 160 characters! int a=10000,b,c=2800,d,e,f[2801],g;main(){for(;b-c;)f[b++]=a/5;for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);} | What is the fastest way to get the value of π? I'm looking for the fastest way to obtain the value of π, as a personal challenge. More specifically, I'm using ways that don't involve using #define constants like M_PI, or hard-coding the number in. The program below tests the various ways I know of. The inline assembly version is, in theory, the fastest option, though clearly not portable. I've included it as a baseline to compare against the other versions. In my tests, with built-ins, the 4 * atan(1) version is fastest on GCC 4.2, because it auto-folds the atan(1) into a constant. With -fno-builtin specified, the atan2(0, -1) version is fastest. Here's the main testing program ( pitimes.c ): #include #include #include #define ITERS 10000000 #define TESTWITH(x) { \ diff = 0.0; \ time1 = clock(); \ for (i = 0; i < ITERS; ++i) \ diff += (x) - M_PI; \ time2 = clock(); \ printf("%s\t=> %e, time => %f\n", #x, diff, diffclock(time2, time1)); \ }
static inline double diffclock(clock_t time1, clock_t time0) { return (double) (time1 - time0) / CLOCKS_PER_SEC; }
int main() { int i; clock_t time1, time2; double diff;
/* Warmup. The atan2 case catches GCC's atan folding (which would * optimise the ``4 * atan(1) - M_PI'' to a no-op), if -fno-builtin * is not used. */ TESTWITH(4 * atan(1)) TESTWITH(4 * atan2(1, 1))
#if defined(__GNUC__) && (defined(__i386__) || defined(__amd64__)) extern double fldpi(); TESTWITH(fldpi()) #endif
/* Actual tests start here. */ TESTWITH(atan2(0, -1)) TESTWITH(acos(-1)) TESTWITH(2 * asin(1)) TESTWITH(4 * atan2(1, 1)) TESTWITH(4 * atan(1))
return 0; } And the inline assembly stuff ( fldpi.c ) that will only work for x86 and x64 systems: double fldpi() { double pi; asm("fldpi": "=t" (pi)); return pi; } And a build script that builds all the configurations I'm testing ( build.sh ): #!/bin/sh gcc -O3 -Wall -c -m32 -o fldpi-32.o fldpi.c gcc -O3 -Wall -c -m64 -o fldpi-64.o fldpi.c
gcc -O3 -Wall -ffast-math -m32 -o pitimes1-32 pitimes.c fldpi-32.o gcc -O3 -Wall -m32 -o pitimes2-32 pitimes.c fldpi-32.o -lm gcc -O3 -Wall -fno-builtin -m32 -o pitimes3-32 pitimes.c fldpi-32.o -lm gcc -O3 -Wall -ffast-math -m64 -o pitimes1-64 pitimes.c fldpi-64.o -lm gcc -O3 -Wall -m64 -o pitimes2-64 pitimes.c fldpi-64.o -lm gcc -O3 -Wall -fno-builtin -m64 -o pitimes3-64 pitimes.c fldpi-64.o -lm Apart from testing between various compiler flags (I've compared 32-bit against 64-bit too because the optimizations are different), I've also tried switching the order of the tests around. But still, the atan2(0, -1) version still comes out on top every time. | TITLE:
What is the fastest way to get the value of π?
QUESTION:
I'm looking for the fastest way to obtain the value of π, as a personal challenge. More specifically, I'm using ways that don't involve using #define constants like M_PI, or hard-coding the number in. The program below tests the various ways I know of. The inline assembly version is, in theory, the fastest option, though clearly not portable. I've included it as a baseline to compare against the other versions. In my tests, with built-ins, the 4 * atan(1) version is fastest on GCC 4.2, because it auto-folds the atan(1) into a constant. With -fno-builtin specified, the atan2(0, -1) version is fastest. Here's the main testing program ( pitimes.c ): #include #include #include #define ITERS 10000000 #define TESTWITH(x) { \ diff = 0.0; \ time1 = clock(); \ for (i = 0; i < ITERS; ++i) \ diff += (x) - M_PI; \ time2 = clock(); \ printf("%s\t=> %e, time => %f\n", #x, diff, diffclock(time2, time1)); \ }
static inline double diffclock(clock_t time1, clock_t time0) { return (double) (time1 - time0) / CLOCKS_PER_SEC; }
int main() { int i; clock_t time1, time2; double diff;
/* Warmup. The atan2 case catches GCC's atan folding (which would * optimise the ``4 * atan(1) - M_PI'' to a no-op), if -fno-builtin * is not used. */ TESTWITH(4 * atan(1)) TESTWITH(4 * atan2(1, 1))
#if defined(__GNUC__) && (defined(__i386__) || defined(__amd64__)) extern double fldpi(); TESTWITH(fldpi()) #endif
/* Actual tests start here. */ TESTWITH(atan2(0, -1)) TESTWITH(acos(-1)) TESTWITH(2 * asin(1)) TESTWITH(4 * atan2(1, 1)) TESTWITH(4 * atan(1))
return 0; } And the inline assembly stuff ( fldpi.c ) that will only work for x86 and x64 systems: double fldpi() { double pi; asm("fldpi": "=t" (pi)); return pi; } And a build script that builds all the configurations I'm testing ( build.sh ): #!/bin/sh gcc -O3 -Wall -c -m32 -o fldpi-32.o fldpi.c gcc -O3 -Wall -c -m64 -o fldpi-64.o fldpi.c
gcc -O3 -Wall -ffast-math -m32 -o pitimes1-32 pitimes.c fldpi-32.o gcc -O3 -Wall -m32 -o pitimes2-32 pitimes.c fldpi-32.o -lm gcc -O3 -Wall -fno-builtin -m32 -o pitimes3-32 pitimes.c fldpi-32.o -lm gcc -O3 -Wall -ffast-math -m64 -o pitimes1-64 pitimes.c fldpi-64.o -lm gcc -O3 -Wall -m64 -o pitimes2-64 pitimes.c fldpi-64.o -lm gcc -O3 -Wall -fno-builtin -m64 -o pitimes3-64 pitimes.c fldpi-64.o -lm Apart from testing between various compiler flags (I've compared 32-bit against 64-bit too because the optimizations are different), I've also tried switching the order of the tests around. But still, the atan2(0, -1) version still comes out on top every time.
ANSWER:
The Monte Carlo method, as mentioned, applies some great concepts but it is, clearly, not the fastest, not by a long shot, not by any reasonable measure. Also, it all depends on what kind of accuracy you are looking for. The fastest π I know of is the one with the digits hard coded. Looking at Pi and Pi[PDF], there are a lot of formulae. Here is a method that converges quickly — about 14 digits per iteration. PiFast, the current fastest application, uses this formula with the FFT. I'll just write the formula, since the code is straightforward. This formula was almost found by Ramanujan and discovered by Chudnovsky. It is actually how he calculated several billion digits of the number — so it isn't a method to disregard. The formula will overflow quickly and, since we are dividing factorials, it would be advantageous then to delay such calculations to remove terms. where, Below is the Brent–Salamin algorithm. Wikipedia mentions that when a and b are "close enough" then (a + b)² / 4t will be an approximation of π. I'm not sure what "close enough" means, but from my tests, one iteration got 2 digits, two got 7, and three had 15, of course this is with doubles, so it might have an error based on its representation and the true calculation could be more accurate. let pi_2 iters = let rec loop_ a b t p i = if i = 0 then a,b,t,p else let a_n = (a +. b) /. 2.0 and b_n = sqrt (a*.b) and p_n = 2.0 *. p in let t_n = t -. (p *. (a -. a_n) *. (a -. a_n)) in loop_ a_n b_n t_n p_n (i - 1) in let a,b,t,p = loop_ (1.0) (1.0 /. (sqrt 2.0)) (1.0/.4.0) (1.0) iters in (a +. b) *. (a +. b) /. (4.0 *. t) Lastly, how about some pi golf (800 digits)? 160 characters! int a=10000,b,c=2800,d,e,f[2801],g;main(){for(;b-c;)f[b++]=a/5;for(;d=0,g=c*2;c-=14,printf("%.4d",e+d/a),e=d%a)for(b=c;d+=f[b]*a,f[b]=d%--g,d/=g--,--b;d*=b);} | [
"performance",
"algorithm",
"language-agnostic",
"unix",
"pi"
] | 352 | 223 | 70,352 | 23 | 0 | 2008-08-01T05:21:22.257000 | 2008-08-02T18:22:52.690000 |
24 | 49 | Throw an error preventing a table update in a MySQL trigger | If I have a trigger before the update on a table, how can I throw an error that prevents the update on that table? | Here is one hack that may work. It isn't clean, but it looks like it might work: Essentially, you just try to update a column that doesn't exist. | Throw an error preventing a table update in a MySQL trigger If I have a trigger before the update on a table, how can I throw an error that prevents the update on that table? | TITLE:
Throw an error preventing a table update in a MySQL trigger
QUESTION:
If I have a trigger before the update on a table, how can I throw an error that prevents the update on that table?
ANSWER:
Here is one hack that may work. It isn't clean, but it looks like it might work: Essentially, you just try to update a column that doesn't exist. | [
"mysql",
"database",
"triggers"
] | 195 | 67 | 105,586 | 7 | 0 | 2008-08-01T12:12:19.350000 | 2008-08-01T13:02:51.900000 |
25 | 1,443,907 | How to use the C socket API in C++ on z/OS | I'm having issues getting the C sockets API to work properly in C++ on z/OS. Although I am including sys/socket.h, I still get compile time errors telling me that AF_INET is not defined. Am I missing something obvious, or is this related to the fact that being on z/OS makes my problems much more complicated? I discovered that there is a #ifdef that I'm hitting. Apparently, z/OS isn't happy unless I define which "type" of sockets I'm using with: #define _OE_SOCKETS Now, I personally have no idea what this _OE_SOCKETS is actually for, so if any z/OS sockets programmers are out there (all 3 of you), perhaps you could give me a rundown of how this all works? Test App: #include int main() { return AF_INET; } Compile/Link Output: cxx -Wc,xplink -Wl,xplink -o inet_test inet.C
"./inet.C", line 5.16: CCN5274 (S) The name lookup for "AF_INET" did not find a declaration. CCN0797(I) Compilation failed for file./inet.C. Object file not created. A check of sys/sockets.h does include the definition I need, and as far as I can tell, it is not being blocked by any #ifdef statements. I have however noticed it contains the following: #ifdef __cplusplus extern "C" { #endif which encapsulates basically the whole file? Not sure if it matters. | Keep a copy of the IBM manuals handy: z/OS V1R11.0 XL C/C++ Programming Guide z/OS V1R11.0 XL C/C++ Run-Time Library Reference The IBM publications are generally very good, but you need to get used to their format, as well as knowing where to look for an answer. You'll find quite often that a feature that you want to use is guarded by a "feature test macro" You should ask your friendly system programmer to install the XL C/C++ Run-Time Library Reference: Man Pages on your system. Then you can do things like "man connect" to pull up the man page for the socket connect() API. When I do that, this is what I see: FORMAT X/Open #define _XOPEN_SOURCE_EXTENDED 1 #include int connect(int socket, const struct sockaddr *address, socklen_t address_len); Berkeley Sockets #define _OE_SOCKETS #include #include int connect(int socket, struct sockaddr *address, int address_len); | How to use the C socket API in C++ on z/OS I'm having issues getting the C sockets API to work properly in C++ on z/OS. Although I am including sys/socket.h, I still get compile time errors telling me that AF_INET is not defined. Am I missing something obvious, or is this related to the fact that being on z/OS makes my problems much more complicated? I discovered that there is a #ifdef that I'm hitting. Apparently, z/OS isn't happy unless I define which "type" of sockets I'm using with: #define _OE_SOCKETS Now, I personally have no idea what this _OE_SOCKETS is actually for, so if any z/OS sockets programmers are out there (all 3 of you), perhaps you could give me a rundown of how this all works? Test App: #include int main() { return AF_INET; } Compile/Link Output: cxx -Wc,xplink -Wl,xplink -o inet_test inet.C
"./inet.C", line 5.16: CCN5274 (S) The name lookup for "AF_INET" did not find a declaration. CCN0797(I) Compilation failed for file./inet.C. Object file not created. A check of sys/sockets.h does include the definition I need, and as far as I can tell, it is not being blocked by any #ifdef statements. I have however noticed it contains the following: #ifdef __cplusplus extern "C" { #endif which encapsulates basically the whole file? Not sure if it matters. | TITLE:
How to use the C socket API in C++ on z/OS
QUESTION:
I'm having issues getting the C sockets API to work properly in C++ on z/OS. Although I am including sys/socket.h, I still get compile time errors telling me that AF_INET is not defined. Am I missing something obvious, or is this related to the fact that being on z/OS makes my problems much more complicated? I discovered that there is a #ifdef that I'm hitting. Apparently, z/OS isn't happy unless I define which "type" of sockets I'm using with: #define _OE_SOCKETS Now, I personally have no idea what this _OE_SOCKETS is actually for, so if any z/OS sockets programmers are out there (all 3 of you), perhaps you could give me a rundown of how this all works? Test App: #include int main() { return AF_INET; } Compile/Link Output: cxx -Wc,xplink -Wl,xplink -o inet_test inet.C
"./inet.C", line 5.16: CCN5274 (S) The name lookup for "AF_INET" did not find a declaration. CCN0797(I) Compilation failed for file./inet.C. Object file not created. A check of sys/sockets.h does include the definition I need, and as far as I can tell, it is not being blocked by any #ifdef statements. I have however noticed it contains the following: #ifdef __cplusplus extern "C" { #endif which encapsulates basically the whole file? Not sure if it matters.
ANSWER:
Keep a copy of the IBM manuals handy: z/OS V1R11.0 XL C/C++ Programming Guide z/OS V1R11.0 XL C/C++ Run-Time Library Reference The IBM publications are generally very good, but you need to get used to their format, as well as knowing where to look for an answer. You'll find quite often that a feature that you want to use is guarded by a "feature test macro" You should ask your friendly system programmer to install the XL C/C++ Run-Time Library Reference: Man Pages on your system. Then you can do things like "man connect" to pull up the man page for the socket connect() API. When I do that, this is what I see: FORMAT X/Open #define _XOPEN_SOURCE_EXTENDED 1 #include int connect(int socket, const struct sockaddr *address, socklen_t address_len); Berkeley Sockets #define _OE_SOCKETS #include #include int connect(int socket, struct sockaddr *address, int address_len); | [
"c++",
"c",
"sockets",
"mainframe",
"zos"
] | 176 | 97 | 16,412 | 9 | 0 | 2008-08-01T12:13:50.207000 | 2009-09-18T11:17:01.933000 |
36 | 352 | Check for changes to an SQL Server table? | How can I monitor an SQL Server database for changes to a table without using triggers or modifying the structure of the database in any way? My preferred programming environment is.NET and C#. I'd like to be able to support any SQL Server 2000 SP4 or newer. My application is a bolt-on data visualization for another company's product. Our customer base is in the thousands, so I don't want to have to put in requirements that we modify the third-party vendor's table at every installation. By "changes to a table" I mean changes to table data, not changes to table structure. Ultimately, I would like the change to trigger an event in my application, instead of having to check for changes at an interval. The best course of action given my requirements (no triggers or schema modification, SQL Server 2000 and 2005) seems to be to use the BINARY_CHECKSUM function in T-SQL. The way I plan to implement is this: Every X seconds run the following query: SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM sample_table WITH (NOLOCK); And compare that against the stored value. If the value has changed, go through the table row by row using the query: SELECT row_id, BINARY_CHECKSUM(*) FROM sample_table WITH (NOLOCK); And compare the returned checksums against stored values. | Take a look at the CHECKSUM command: SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM sample_table WITH (NOLOCK); That will return the same number each time it's run as long as the table contents haven't changed. See my post on this for more information: CHECKSUM Here's how I used it to rebuild cache dependencies when tables changed: ASP.NET 1.1 database cache dependency (without triggers) | Check for changes to an SQL Server table? How can I monitor an SQL Server database for changes to a table without using triggers or modifying the structure of the database in any way? My preferred programming environment is.NET and C#. I'd like to be able to support any SQL Server 2000 SP4 or newer. My application is a bolt-on data visualization for another company's product. Our customer base is in the thousands, so I don't want to have to put in requirements that we modify the third-party vendor's table at every installation. By "changes to a table" I mean changes to table data, not changes to table structure. Ultimately, I would like the change to trigger an event in my application, instead of having to check for changes at an interval. The best course of action given my requirements (no triggers or schema modification, SQL Server 2000 and 2005) seems to be to use the BINARY_CHECKSUM function in T-SQL. The way I plan to implement is this: Every X seconds run the following query: SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM sample_table WITH (NOLOCK); And compare that against the stored value. If the value has changed, go through the table row by row using the query: SELECT row_id, BINARY_CHECKSUM(*) FROM sample_table WITH (NOLOCK); And compare the returned checksums against stored values. | TITLE:
Check for changes to an SQL Server table?
QUESTION:
How can I monitor an SQL Server database for changes to a table without using triggers or modifying the structure of the database in any way? My preferred programming environment is.NET and C#. I'd like to be able to support any SQL Server 2000 SP4 or newer. My application is a bolt-on data visualization for another company's product. Our customer base is in the thousands, so I don't want to have to put in requirements that we modify the third-party vendor's table at every installation. By "changes to a table" I mean changes to table data, not changes to table structure. Ultimately, I would like the change to trigger an event in my application, instead of having to check for changes at an interval. The best course of action given my requirements (no triggers or schema modification, SQL Server 2000 and 2005) seems to be to use the BINARY_CHECKSUM function in T-SQL. The way I plan to implement is this: Every X seconds run the following query: SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM sample_table WITH (NOLOCK); And compare that against the stored value. If the value has changed, go through the table row by row using the query: SELECT row_id, BINARY_CHECKSUM(*) FROM sample_table WITH (NOLOCK); And compare the returned checksums against stored values.
ANSWER:
Take a look at the CHECKSUM command: SELECT CHECKSUM_AGG(BINARY_CHECKSUM(*)) FROM sample_table WITH (NOLOCK); That will return the same number each time it's run as long as the table contents haven't changed. See my post on this for more information: CHECKSUM Here's how I used it to rebuild cache dependencies when tables changed: ASP.NET 1.1 database cache dependency (without triggers) | [
"sql",
"sql-server",
"datatable",
"rdbms"
] | 153 | 101 | 78,517 | 9 | 0 | 2008-08-01T12:35:56.917000 | 2008-08-02T05:20:22.397000 |
39 | 45 | Reliable timer in a console application | I am aware that in.NET there are three timer types (see Comparing the Timer Classes in the.NET Framework Class Library ). I have chosen a threaded timer as the other types can drift if the main thread is busy, and I need this to be reliable. The way this timer works in the control of the timer is put on another thread so it can always tick along with the work begin completed on the parent thread when it is not busy. The issue with this timer in a console application is that while the timer is ticking along on another thread the main thread is not doing anything to the application closes. I tried adding a while true loop, but then the main thread is too busy when the timer does go off. | You can use something like Console.ReadLine() to block the main thread, so other background threads (like timer threads) will still work. You may also use an AutoResetEvent to block the execution, then (when you need to) you can call Set() method on that AutoResetEvent object to release the main thread. Also ensure that your reference to Timer object doesn't go out of scope and garbage collected. | Reliable timer in a console application I am aware that in.NET there are three timer types (see Comparing the Timer Classes in the.NET Framework Class Library ). I have chosen a threaded timer as the other types can drift if the main thread is busy, and I need this to be reliable. The way this timer works in the control of the timer is put on another thread so it can always tick along with the work begin completed on the parent thread when it is not busy. The issue with this timer in a console application is that while the timer is ticking along on another thread the main thread is not doing anything to the application closes. I tried adding a while true loop, but then the main thread is too busy when the timer does go off. | TITLE:
Reliable timer in a console application
QUESTION:
I am aware that in.NET there are three timer types (see Comparing the Timer Classes in the.NET Framework Class Library ). I have chosen a threaded timer as the other types can drift if the main thread is busy, and I need this to be reliable. The way this timer works in the control of the timer is put on another thread so it can always tick along with the work begin completed on the parent thread when it is not busy. The issue with this timer in a console application is that while the timer is ticking along on another thread the main thread is not doing anything to the application closes. I tried adding a while true loop, but then the main thread is too busy when the timer does go off.
ANSWER:
You can use something like Console.ReadLine() to block the main thread, so other background threads (like timer threads) will still work. You may also use an AutoResetEvent to block the execution, then (when you need to) you can call Set() method on that AutoResetEvent object to release the main thread. Also ensure that your reference to Timer object doesn't go out of scope and garbage collected. | [
"c#",
".net",
"vb.net",
"timer"
] | 114 | 63 | 8,237 | 3 | 0 | 2008-08-01T12:43:11.503000 | 2008-08-01T12:56:37.920000 |
42 | 77 | Best way to allow plugins for a PHP application | I am starting a new web application in PHP and this time around I want to create something that people can extend by using a plugin interface. How does one go about writing 'hooks' into their code so that plugins can attach to specific events? | You could use an Observer pattern. A simple functional way to accomplish this: Output: This is my CRAZY application 4 + 5 = 9 4 * 5 = 20 Notes: For this example source code, you must declare all your plugins before the actual source code that you want to be extendable. I've included an example of how to handle single or multiple values being passed to the plugin. The hardest part of this is writing the actual documentation which lists what arguments get passed to each hook. This is just one method of accomplishing a plugin system in PHP. There are better alternatives, I suggest you check out the WordPress Documentation for more information. | Best way to allow plugins for a PHP application I am starting a new web application in PHP and this time around I want to create something that people can extend by using a plugin interface. How does one go about writing 'hooks' into their code so that plugins can attach to specific events? | TITLE:
Best way to allow plugins for a PHP application
QUESTION:
I am starting a new web application in PHP and this time around I want to create something that people can extend by using a plugin interface. How does one go about writing 'hooks' into their code so that plugins can attach to specific events?
ANSWER:
You could use an Observer pattern. A simple functional way to accomplish this: Output: This is my CRAZY application 4 + 5 = 9 4 * 5 = 20 Notes: For this example source code, you must declare all your plugins before the actual source code that you want to be extendable. I've included an example of how to handle single or multiple values being passed to the plugin. The hardest part of this is writing the actual documentation which lists what arguments get passed to each hook. This is just one method of accomplishing a plugin system in PHP. There are better alternatives, I suggest you check out the WordPress Documentation for more information. | [
"php",
"plugins",
"architecture",
"hook"
] | 293 | 168 | 40,824 | 8 | 0 | 2008-08-01T12:50:18.587000 | 2008-08-01T13:46:00.097000 |
48 | 31,910 | Multiple submit buttons in an HTML form | Let's say you create a wizard in an HTML form. One button goes back, and one goes forward. Since the back button appears first in the markup when you press Enter, it will use that button to submit the form. Example: I would like to get to decide which button is used to submit the form when a user presses Enter. That way, when you press Enter the wizard will move to the next page, not the previous. Do you have to use tabindex to do this? | I'm just doing the trick of float ing the buttons to the right. This way the Prev button is left of the Next button, but the Next comes first in the HTML structure:.f { float: right; }.clr { clear: both; } Benefits over other suggestions: no JavaScript code, accessible, and both buttons remain type="submit". | Multiple submit buttons in an HTML form Let's say you create a wizard in an HTML form. One button goes back, and one goes forward. Since the back button appears first in the markup when you press Enter, it will use that button to submit the form. Example: I would like to get to decide which button is used to submit the form when a user presses Enter. That way, when you press Enter the wizard will move to the next page, not the previous. Do you have to use tabindex to do this? | TITLE:
Multiple submit buttons in an HTML form
QUESTION:
Let's say you create a wizard in an HTML form. One button goes back, and one goes forward. Since the back button appears first in the markup when you press Enter, it will use that button to submit the form. Example: I would like to get to decide which button is used to submit the form when a user presses Enter. That way, when you press Enter the wizard will move to the next page, not the previous. Do you have to use tabindex to do this?
ANSWER:
I'm just doing the trick of float ing the buttons to the right. This way the Prev button is left of the Next button, but the Next comes first in the HTML structure:.f { float: right; }.clr { clear: both; } Benefits over other suggestions: no JavaScript code, accessible, and both buttons remain type="submit". | [
"html",
"forms",
"form-submit",
"submit-button"
] | 291 | 152 | 257,419 | 28 | 0 | 2008-08-01T13:01:17.303000 | 2008-08-28T09:34:40.143000 |
59 | 43,110 | How do I get a distinct, ordered list of names from a DataTable using LINQ? | I have a DataTable with a Name column. I want to generate a collection of the unique names ordered alphabetically. The following query ignores the order by clause. var names = (from DataRow dr in dataTable.Rows orderby (string)dr["Name"] select (string)dr["Name"]).Distinct(); Why does the orderby not get enforced? | To make it more readable and maintainable, you can also split it up into multiple LINQ statements. First, select your data into a new list, let's call it x1, do a projection if desired Next, create a distinct list, from x1 into x2, using whatever distinction you require Finally, create an ordered list, from x2 into x3, sorting by whatever you desire | How do I get a distinct, ordered list of names from a DataTable using LINQ? I have a DataTable with a Name column. I want to generate a collection of the unique names ordered alphabetically. The following query ignores the order by clause. var names = (from DataRow dr in dataTable.Rows orderby (string)dr["Name"] select (string)dr["Name"]).Distinct(); Why does the orderby not get enforced? | TITLE:
How do I get a distinct, ordered list of names from a DataTable using LINQ?
QUESTION:
I have a DataTable with a Name column. I want to generate a collection of the unique names ordered alphabetically. The following query ignores the order by clause. var names = (from DataRow dr in dataTable.Rows orderby (string)dr["Name"] select (string)dr["Name"]).Distinct(); Why does the orderby not get enforced?
ANSWER:
To make it more readable and maintainable, you can also split it up into multiple LINQ statements. First, select your data into a new list, let's call it x1, do a projection if desired Next, create a distinct list, from x1 into x2, using whatever distinction you require Finally, create an ordered list, from x2 into x3, sorting by whatever you desire | [
"c#",
"linq",
".net-3.5"
] | 117 | 40 | 27,375 | 7 | 0 | 2008-08-01T13:14:33.797000 | 2008-09-04T02:57:27.263000 |
66 | 4,521 | Paging a collection with LINQ | How do you page through a collection in LINQ given that you have a startIndex and a count? | A few months back I wrote a blog post about Fluent Interfaces and LINQ which used an Extension Method on IQueryable and another class to provide the following natural way of paginating a LINQ collection. var query = from i in ideas select i; var pagedCollection = query.InPagesOf(10); var pageOfIdeas = pagedCollection.Page(2); You can get the code from the MSDN Code Gallery Page: Pipelines, Filters, Fluent API and LINQ to SQL. | Paging a collection with LINQ How do you page through a collection in LINQ given that you have a startIndex and a count? | TITLE:
Paging a collection with LINQ
QUESTION:
How do you page through a collection in LINQ given that you have a startIndex and a count?
ANSWER:
A few months back I wrote a blog post about Fluent Interfaces and LINQ which used an Extension Method on IQueryable and another class to provide the following natural way of paginating a LINQ collection. var query = from i in ideas select i; var pagedCollection = query.InPagesOf(10); var pageOfIdeas = pagedCollection.Page(2); You can get the code from the MSDN Code Gallery Page: Pipelines, Filters, Fluent API and LINQ to SQL. | [
"linq",
".net-3.5"
] | 89 | 45 | 6,204 | 4 | 0 | 2008-08-01T13:20:46.890000 | 2008-08-07T08:22:27.440000 |
79 | 62,853 | Getting Subclipse in Aptana to work with the newest release of Subversion | The version of Subclipse (1.2.4) currently available through Aptana's automatic Plugins Manager does not work with the newest version of Subversion. I see on the Subclipse website however that they have 1.4.2 out for Eclipse. So I added a new remote update site to my Update manager. When I tried to install it, it told me I needed Mylyn 3.0.0. So after much searching I found Mylyn 3.0.0 and added another new remote update site to my update manager. Then when I tried to install that, it told me I needed org.eclipse.ui 3.3.0 or equivalent. Looking at the configuration details for Aptana, it looks like it is built against eclipse 3.2.2. Does anyone know if there is a way to upgrade the version of Eclipse Aptana that is built against to 3.3.0? Or if there is some other way to get Subclipse to work with the very newest version of Subversion? I know this isn't necessarily a "programming" question, but I hope it's ok since it's highly relevant to the programming experience. | Subclipse does not require Mylyn, but the update site includes a plugin that integrates Mylyn and Subclipse. This is intended for people that use Mylyn. In your case, you would want to just de-select Mylyn in the update dialog. Subclipse also requires Subversion 1.5 and the corresponding version of the JavaHL native libraries. I have written the start of an FAQ to help people understand JavaHL and how to get it. See: http://desktop-eclipse.open.collab.net/wiki/JavaHL | Getting Subclipse in Aptana to work with the newest release of Subversion The version of Subclipse (1.2.4) currently available through Aptana's automatic Plugins Manager does not work with the newest version of Subversion. I see on the Subclipse website however that they have 1.4.2 out for Eclipse. So I added a new remote update site to my Update manager. When I tried to install it, it told me I needed Mylyn 3.0.0. So after much searching I found Mylyn 3.0.0 and added another new remote update site to my update manager. Then when I tried to install that, it told me I needed org.eclipse.ui 3.3.0 or equivalent. Looking at the configuration details for Aptana, it looks like it is built against eclipse 3.2.2. Does anyone know if there is a way to upgrade the version of Eclipse Aptana that is built against to 3.3.0? Or if there is some other way to get Subclipse to work with the very newest version of Subversion? I know this isn't necessarily a "programming" question, but I hope it's ok since it's highly relevant to the programming experience. | TITLE:
Getting Subclipse in Aptana to work with the newest release of Subversion
QUESTION:
The version of Subclipse (1.2.4) currently available through Aptana's automatic Plugins Manager does not work with the newest version of Subversion. I see on the Subclipse website however that they have 1.4.2 out for Eclipse. So I added a new remote update site to my Update manager. When I tried to install it, it told me I needed Mylyn 3.0.0. So after much searching I found Mylyn 3.0.0 and added another new remote update site to my update manager. Then when I tried to install that, it told me I needed org.eclipse.ui 3.3.0 or equivalent. Looking at the configuration details for Aptana, it looks like it is built against eclipse 3.2.2. Does anyone know if there is a way to upgrade the version of Eclipse Aptana that is built against to 3.3.0? Or if there is some other way to get Subclipse to work with the very newest version of Subversion? I know this isn't necessarily a "programming" question, but I hope it's ok since it's highly relevant to the programming experience.
ANSWER:
Subclipse does not require Mylyn, but the update site includes a plugin that integrates Mylyn and Subclipse. This is intended for people that use Mylyn. In your case, you would want to just de-select Mylyn in the update dialog. Subclipse also requires Subversion 1.5 and the corresponding version of the JavaHL native libraries. I have written the start of an FAQ to help people understand JavaHL and how to get it. See: http://desktop-eclipse.open.collab.net/wiki/JavaHL | [
"eclipse",
"svn",
"aptana",
"subclipse"
] | 50 | 18 | 11,457 | 4 | 0 | 2008-08-01T13:56:33.837000 | 2008-09-15T13:26:34.350000 |
80 | 124 | SQLStatement.execute() - multiple queries in one statement | I've written a database generation script in SQL and want to execute it in my Adobe AIR application: Create Table tRole ( roleID integer Primary Key,roleName varchar(40) ); Create Table tFile ( fileID integer Primary Key,fileName varchar(50),fileDescription varchar(500),thumbnailID integer,fileFormatID integer,categoryID integer,isFavorite boolean,dateAdded date,globalAccessCount integer,lastAccessTime date,downloadComplete boolean,isNew boolean,isSpotlight boolean,duration varchar(30) ); Create Table tCategory ( categoryID integer Primary Key,categoryName varchar(50),parent_categoryID integer );... I execute this in Adobe AIR using the following methods: public static function RunSqlFromFile(fileName:String):void { var file:File = File.applicationDirectory.resolvePath(fileName); var stream:FileStream = new FileStream(); stream.open(file, FileMode.READ) var strSql:String = stream.readUTFBytes(stream.bytesAvailable); NonQuery(strSql); }
public static function NonQuery(strSQL:String):void { var sqlConnection:SQLConnection = new SQLConnection(); sqlConnection.open(File.applicationStorageDirectory.resolvePath(DBPATH)); var sqlStatement:SQLStatement = new SQLStatement(); sqlStatement.text = strSQL; sqlStatement.sqlConnection = sqlConnection; try { sqlStatement.execute(); } catch (error:SQLError) { Alert.show(error.toString()); } } No errors are generated, however only tRole exists. It seems that it only looks at the first query (up to the semicolon- if I remove it, the query fails). Is there a way to call multiple queries in one statement? | I wound up using this. It is a kind of a hack, but it actually works pretty well. The only thing is you have to be very careful with your semicolons.: D var strSql:String = stream.readUTFBytes(stream.bytesAvailable); var i:Number = 0; var strSqlSplit:Array = strSql.split(";"); for (i = 0; i < strSqlSplit.length; i++){ NonQuery(strSqlSplit[i].toString()); } | SQLStatement.execute() - multiple queries in one statement I've written a database generation script in SQL and want to execute it in my Adobe AIR application: Create Table tRole ( roleID integer Primary Key,roleName varchar(40) ); Create Table tFile ( fileID integer Primary Key,fileName varchar(50),fileDescription varchar(500),thumbnailID integer,fileFormatID integer,categoryID integer,isFavorite boolean,dateAdded date,globalAccessCount integer,lastAccessTime date,downloadComplete boolean,isNew boolean,isSpotlight boolean,duration varchar(30) ); Create Table tCategory ( categoryID integer Primary Key,categoryName varchar(50),parent_categoryID integer );... I execute this in Adobe AIR using the following methods: public static function RunSqlFromFile(fileName:String):void { var file:File = File.applicationDirectory.resolvePath(fileName); var stream:FileStream = new FileStream(); stream.open(file, FileMode.READ) var strSql:String = stream.readUTFBytes(stream.bytesAvailable); NonQuery(strSql); }
public static function NonQuery(strSQL:String):void { var sqlConnection:SQLConnection = new SQLConnection(); sqlConnection.open(File.applicationStorageDirectory.resolvePath(DBPATH)); var sqlStatement:SQLStatement = new SQLStatement(); sqlStatement.text = strSQL; sqlStatement.sqlConnection = sqlConnection; try { sqlStatement.execute(); } catch (error:SQLError) { Alert.show(error.toString()); } } No errors are generated, however only tRole exists. It seems that it only looks at the first query (up to the semicolon- if I remove it, the query fails). Is there a way to call multiple queries in one statement? | TITLE:
SQLStatement.execute() - multiple queries in one statement
QUESTION:
I've written a database generation script in SQL and want to execute it in my Adobe AIR application: Create Table tRole ( roleID integer Primary Key,roleName varchar(40) ); Create Table tFile ( fileID integer Primary Key,fileName varchar(50),fileDescription varchar(500),thumbnailID integer,fileFormatID integer,categoryID integer,isFavorite boolean,dateAdded date,globalAccessCount integer,lastAccessTime date,downloadComplete boolean,isNew boolean,isSpotlight boolean,duration varchar(30) ); Create Table tCategory ( categoryID integer Primary Key,categoryName varchar(50),parent_categoryID integer );... I execute this in Adobe AIR using the following methods: public static function RunSqlFromFile(fileName:String):void { var file:File = File.applicationDirectory.resolvePath(fileName); var stream:FileStream = new FileStream(); stream.open(file, FileMode.READ) var strSql:String = stream.readUTFBytes(stream.bytesAvailable); NonQuery(strSql); }
public static function NonQuery(strSQL:String):void { var sqlConnection:SQLConnection = new SQLConnection(); sqlConnection.open(File.applicationStorageDirectory.resolvePath(DBPATH)); var sqlStatement:SQLStatement = new SQLStatement(); sqlStatement.text = strSQL; sqlStatement.sqlConnection = sqlConnection; try { sqlStatement.execute(); } catch (error:SQLError) { Alert.show(error.toString()); } } No errors are generated, however only tRole exists. It seems that it only looks at the first query (up to the semicolon- if I remove it, the query fails). Is there a way to call multiple queries in one statement?
ANSWER:
I wound up using this. It is a kind of a hack, but it actually works pretty well. The only thing is you have to be very careful with your semicolons.: D var strSql:String = stream.readUTFBytes(stream.bytesAvailable); var i:Number = 0; var strSqlSplit:Array = strSql.split(";"); for (i = 0; i < strSqlSplit.length; i++){ NonQuery(strSqlSplit[i].toString()); } | [
"apache-flex",
"actionscript-3",
"air"
] | 54 | 20 | 6,683 | 3 | 0 | 2008-08-01T13:57:07.033000 | 2008-08-01T16:09:47.687000 |
85 | 154 | Flat file databases | What are the best practices around creating flat file database structures in PHP? A lot of more matured PHP flat file frameworks out there which I attempt to implement SQL-like query syntax which is over the top for my purposes in most cases. (I would just use a database at that point). Are there any elegant tricks out there to get good performance and features with a small code overhead? | Well, what is the nature of the flat databases. Are they large or small. Is it simple arrays with arrays in them? if its something simple say userprofiles built as such: $user = array("name" => "bob", "age" => 20, "websites" => array("example.com","bob.example.com","bob2.example.com"), "and_one" => "more"); and to save or update the db record for that user. $dir = "../userdata/"; //make sure to put it bellow what the server can reach. file_put_contents($dir.$user['name'],serialize($user)); and to load the record for the user function &get_user($name){ return unserialize(file_get_contents("../userdata/".$name)); } but again this implementation will vary on the application and nature of the database you need. | Flat file databases What are the best practices around creating flat file database structures in PHP? A lot of more matured PHP flat file frameworks out there which I attempt to implement SQL-like query syntax which is over the top for my purposes in most cases. (I would just use a database at that point). Are there any elegant tricks out there to get good performance and features with a small code overhead? | TITLE:
Flat file databases
QUESTION:
What are the best practices around creating flat file database structures in PHP? A lot of more matured PHP flat file frameworks out there which I attempt to implement SQL-like query syntax which is over the top for my purposes in most cases. (I would just use a database at that point). Are there any elegant tricks out there to get good performance and features with a small code overhead?
ANSWER:
Well, what is the nature of the flat databases. Are they large or small. Is it simple arrays with arrays in them? if its something simple say userprofiles built as such: $user = array("name" => "bob", "age" => 20, "websites" => array("example.com","bob.example.com","bob2.example.com"), "and_one" => "more"); and to save or update the db record for that user. $dir = "../userdata/"; //make sure to put it bellow what the server can reach. file_put_contents($dir.$user['name'],serialize($user)); and to load the record for the user function &get_user($name){ return unserialize(file_get_contents("../userdata/".$name)); } but again this implementation will vary on the application and nature of the database you need. | [
"php",
"sql",
"database",
"flat-file"
] | 132 | 81 | 69,859 | 11 | 0 | 2008-08-01T14:19:52.510000 | 2008-08-01T17:45:06.513000 |
88 | 98 | Is gettimeofday() guaranteed to be of microsecond resolution? | I am porting a game, that was originally written for the Win32 API, to Linux (well, porting the OS X port of the Win32 port to Linux). I have implemented QueryPerformanceCounter by giving the uSeconds since the process start up: BOOL QueryPerformanceCounter(LARGE_INTEGER* performanceCount) { gettimeofday(¤tTimeVal, NULL); performanceCount->QuadPart = (currentTimeVal.tv_sec - startTimeVal.tv_sec); performanceCount->QuadPart *= (1000 * 1000); performanceCount->QuadPart += (currentTimeVal.tv_usec - startTimeVal.tv_usec);
return true; } This, coupled with QueryPerformanceFrequency() giving a constant 1000000 as the frequency, works well on my machine, and gives me a 64-bit variable that contains uSeconds since the program's start-up. So is this portable? I don't want to discover it works differently if the kernel was compiled in a certain way or anything like that. I am fine with it being non-portable to something other than Linux, however. | Maybe. But you have bigger problems. gettimeofday() can result in incorrect timings if there are processes on your system that change the timer (ie, ntpd). On a "normal" Linux, though, I believe the resolution of gettimeofday() is 10us. It can jump forward and backward and time, consequently, based on the processes running on your system. This effectively makes the answer to your question no. You should look into clock_gettime(CLOCK_MONOTONIC) for timing intervals. It suffers from several fewer issues due to things like multi-core systems and external clock settings. Also, look into the clock_getres() function. | Is gettimeofday() guaranteed to be of microsecond resolution? I am porting a game, that was originally written for the Win32 API, to Linux (well, porting the OS X port of the Win32 port to Linux). I have implemented QueryPerformanceCounter by giving the uSeconds since the process start up: BOOL QueryPerformanceCounter(LARGE_INTEGER* performanceCount) { gettimeofday(¤tTimeVal, NULL); performanceCount->QuadPart = (currentTimeVal.tv_sec - startTimeVal.tv_sec); performanceCount->QuadPart *= (1000 * 1000); performanceCount->QuadPart += (currentTimeVal.tv_usec - startTimeVal.tv_usec);
return true; } This, coupled with QueryPerformanceFrequency() giving a constant 1000000 as the frequency, works well on my machine, and gives me a 64-bit variable that contains uSeconds since the program's start-up. So is this portable? I don't want to discover it works differently if the kernel was compiled in a certain way or anything like that. I am fine with it being non-portable to something other than Linux, however. | TITLE:
Is gettimeofday() guaranteed to be of microsecond resolution?
QUESTION:
I am porting a game, that was originally written for the Win32 API, to Linux (well, porting the OS X port of the Win32 port to Linux). I have implemented QueryPerformanceCounter by giving the uSeconds since the process start up: BOOL QueryPerformanceCounter(LARGE_INTEGER* performanceCount) { gettimeofday(¤tTimeVal, NULL); performanceCount->QuadPart = (currentTimeVal.tv_sec - startTimeVal.tv_sec); performanceCount->QuadPart *= (1000 * 1000); performanceCount->QuadPart += (currentTimeVal.tv_usec - startTimeVal.tv_usec);
return true; } This, coupled with QueryPerformanceFrequency() giving a constant 1000000 as the frequency, works well on my machine, and gives me a 64-bit variable that contains uSeconds since the program's start-up. So is this portable? I don't want to discover it works differently if the kernel was compiled in a certain way or anything like that. I am fine with it being non-portable to something other than Linux, however.
ANSWER:
Maybe. But you have bigger problems. gettimeofday() can result in incorrect timings if there are processes on your system that change the timer (ie, ntpd). On a "normal" Linux, though, I believe the resolution of gettimeofday() is 10us. It can jump forward and backward and time, consequently, based on the processes running on your system. This effectively makes the answer to your question no. You should look into clock_gettime(CLOCK_MONOTONIC) for timing intervals. It suffers from several fewer issues due to things like multi-core systems and external clock settings. Also, look into the clock_getres() function. | [
"linux",
"winapi",
"visual-c++",
"unix",
"timer"
] | 106 | 63 | 45,129 | 10 | 0 | 2008-08-01T14:36:18.640000 | 2008-08-01T14:53:47.497000 |
90 | 1,466,832 | How do you branch and merge with TortoiseSVN? | How do you branch and merge with Apache Subversion using the TortoiseSVN client? | My easy click-by-click instructions ( specific to TortoiseSVN ) are in Stack Overflow question What is the simplest way to do branching and merging using TortoiseSVN?. | How do you branch and merge with TortoiseSVN? How do you branch and merge with Apache Subversion using the TortoiseSVN client? | TITLE:
How do you branch and merge with TortoiseSVN?
QUESTION:
How do you branch and merge with Apache Subversion using the TortoiseSVN client?
ANSWER:
My easy click-by-click instructions ( specific to TortoiseSVN ) are in Stack Overflow question What is the simplest way to do branching and merging using TortoiseSVN?. | [
"svn",
"tortoisesvn",
"branch",
"branching-and-merging"
] | 163 | 23 | 56,424 | 3 | 0 | 2008-08-01T14:41:24.277000 | 2009-09-23T15:40:46.943000 |
104 | 112 | Anatomy of a "Memory Leak" | In.NET perspective: What is a memory leak? How can you determine whether your application leaks? What are the effects? How can you prevent a memory leak? If your application has memory leak, does it go away when the process exits or is killed? Or do memory leaks in your application affect other processes on the system even after process completion? And what about unmanaged code accessed via COM Interop and/or P/Invoke? | The best explanation I've seen is in Chapter 7 of the free Foundations of Programming e-book. Basically, in.NET a memory leak occurs when referenced objects are rooted and thus cannot be garbage collected. This occurs accidentally when you hold on to references beyond the intended scope. You'll know that you have leaks when you start getting OutOfMemoryExceptions or your memory usage goes up beyond what you'd expect ( PerfMon has nice memory counters). Understanding.NET 's memory model is your best way of avoiding it. Specifically, understanding how the garbage collector works and how references work — again, I refer you to chapter 7 of the e-book. Also, be mindful of common pitfalls, probably the most common being events. If object A is registered to an event on object B, then object A will stick around until object B disappears because B holds a reference to A. The solution is to unregister your events when you're done. Of course, a good memory profile will let you see your object graphs and explore the nesting/referencing of your objects to see where references are coming from and what root object is responsible ( red-gate ants profile, JetBrains dotMemory, memprofiler are really good choices, or you can use the text-only WinDbg and SOS, but I'd strongly recommend a commercial/visual product unless you're a real guru). I believe unmanaged code is subject to its typical memory leaks, except that shared references are managed by the garbage collector. I could be wrong about this last point. | Anatomy of a "Memory Leak" In.NET perspective: What is a memory leak? How can you determine whether your application leaks? What are the effects? How can you prevent a memory leak? If your application has memory leak, does it go away when the process exits or is killed? Or do memory leaks in your application affect other processes on the system even after process completion? And what about unmanaged code accessed via COM Interop and/or P/Invoke? | TITLE:
Anatomy of a "Memory Leak"
QUESTION:
In.NET perspective: What is a memory leak? How can you determine whether your application leaks? What are the effects? How can you prevent a memory leak? If your application has memory leak, does it go away when the process exits or is killed? Or do memory leaks in your application affect other processes on the system even after process completion? And what about unmanaged code accessed via COM Interop and/or P/Invoke?
ANSWER:
The best explanation I've seen is in Chapter 7 of the free Foundations of Programming e-book. Basically, in.NET a memory leak occurs when referenced objects are rooted and thus cannot be garbage collected. This occurs accidentally when you hold on to references beyond the intended scope. You'll know that you have leaks when you start getting OutOfMemoryExceptions or your memory usage goes up beyond what you'd expect ( PerfMon has nice memory counters). Understanding.NET 's memory model is your best way of avoiding it. Specifically, understanding how the garbage collector works and how references work — again, I refer you to chapter 7 of the e-book. Also, be mindful of common pitfalls, probably the most common being events. If object A is registered to an event on object B, then object A will stick around until object B disappears because B holds a reference to A. The solution is to unregister your events when you're done. Of course, a good memory profile will let you see your object graphs and explore the nesting/referencing of your objects to see where references are coming from and what root object is responsible ( red-gate ants profile, JetBrains dotMemory, memprofiler are really good choices, or you can use the text-only WinDbg and SOS, but I'd strongly recommend a commercial/visual product unless you're a real guru). I believe unmanaged code is subject to its typical memory leaks, except that shared references are managed by the garbage collector. I could be wrong about this last point. | [
".net",
"performance",
"memory-leaks",
"com-interop"
] | 181 | 112 | 15,291 | 15 | 0 | 2008-08-01T15:12:34.837000 | 2008-08-01T15:28:12.543000 |
108 | 111 | Best Subversion clients for Windows Vista (64bit) | I've been using TortoiseSVN in a Windows environment for quite some time. It seems very feature-complete and nicely integrated into the Windows shell, and more importantly, it's fairly painless to teach to colleagues with little or no experience with source control. However, since we have moved to Windows Vista 64bit, Tortoise has been very buggy and has seemed to cause lots of explorer.exe abnormalities and crashes. This has happened both with older versions of the software and the latest version (1.5.1 build 13563). I was curious if anyone has suggestions for other Subversion clients that will run on Windows (specifically Vista 64bit). Developers here use a variety of text editors so using Visual Studio or Dreamweaver for SVN is not ideal. I have heard great things about Cornerstone, and would love something similar for Windows if it exists. I'm correlating the Vista/explorer problems with Tortoise because they normally occur when I'm using the functionality in Tortoise. Sometimes bringing up the "merge" screen will cause the GUI to start acting very strange and eventually hang or crash. I did not see 1.5.2 -- I'm installing now, maybe that will fix some of my issues. | I have been using the 64Bit version of TortoiseSVN for ages and I have never had issues with it on Windows 64Bit or Vista 64Bit. I am currently not aware of any other similiar SVN clients that do work on Vista. Is it possible the problem could lie within the configuration of TortoiseSVN or even the installation of Vista? Is the problem occurring on Vista native or SP 1? | Best Subversion clients for Windows Vista (64bit) I've been using TortoiseSVN in a Windows environment for quite some time. It seems very feature-complete and nicely integrated into the Windows shell, and more importantly, it's fairly painless to teach to colleagues with little or no experience with source control. However, since we have moved to Windows Vista 64bit, Tortoise has been very buggy and has seemed to cause lots of explorer.exe abnormalities and crashes. This has happened both with older versions of the software and the latest version (1.5.1 build 13563). I was curious if anyone has suggestions for other Subversion clients that will run on Windows (specifically Vista 64bit). Developers here use a variety of text editors so using Visual Studio or Dreamweaver for SVN is not ideal. I have heard great things about Cornerstone, and would love something similar for Windows if it exists. I'm correlating the Vista/explorer problems with Tortoise because they normally occur when I'm using the functionality in Tortoise. Sometimes bringing up the "merge" screen will cause the GUI to start acting very strange and eventually hang or crash. I did not see 1.5.2 -- I'm installing now, maybe that will fix some of my issues. | TITLE:
Best Subversion clients for Windows Vista (64bit)
QUESTION:
I've been using TortoiseSVN in a Windows environment for quite some time. It seems very feature-complete and nicely integrated into the Windows shell, and more importantly, it's fairly painless to teach to colleagues with little or no experience with source control. However, since we have moved to Windows Vista 64bit, Tortoise has been very buggy and has seemed to cause lots of explorer.exe abnormalities and crashes. This has happened both with older versions of the software and the latest version (1.5.1 build 13563). I was curious if anyone has suggestions for other Subversion clients that will run on Windows (specifically Vista 64bit). Developers here use a variety of text editors so using Visual Studio or Dreamweaver for SVN is not ideal. I have heard great things about Cornerstone, and would love something similar for Windows if it exists. I'm correlating the Vista/explorer problems with Tortoise because they normally occur when I'm using the functionality in Tortoise. Sometimes bringing up the "merge" screen will cause the GUI to start acting very strange and eventually hang or crash. I did not see 1.5.2 -- I'm installing now, maybe that will fix some of my issues.
ANSWER:
I have been using the 64Bit version of TortoiseSVN for ages and I have never had issues with it on Windows 64Bit or Vista 64Bit. I am currently not aware of any other similiar SVN clients that do work on Vista. Is it possible the problem could lie within the configuration of TortoiseSVN or even the installation of Vista? Is the problem occurring on Vista native or SP 1? | [
"windows",
"svn",
"64-bit"
] | 52 | 39 | 16,513 | 8 | 0 | 2008-08-01T15:22:29.467000 | 2008-08-01T15:27:23.093000 |
109 | 2,585 | Decoding T-SQL CAST in C#/VB.NET | Recently our site has been deluged with the resurgence of the Asprox botnet SQL injection attack. Without going into details, the attack attempts to execute SQL code by encoding the T-SQL commands in an ASCII encoded BINARY string. It looks something like this: DECLARE%20@S%20NVARCHAR(4000);SET%20@S=CAST(0x44004500...06F007200%20AS%20NVARCHAR(4000));EXEC(@S);-- I was able to decode this in SQL, but I was a little wary of doing this since I didn't know exactly what was happening at the time. I tried to write a simple decode tool, so I could decode this type of text without even touching SQL Server. The main part I need to be decoded is: CAST(0x44004500...06F007200 AS NVARCHAR(4000)) I've tried all of the following commands with no luck: txtDecodedText.Text = System.Web.HttpUtility.UrlDecode(txtURLText.Text); txtDecodedText.Text = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(txtURLText.Text)); txtDecodedText.Text = Encoding.Unicode.GetString(Encoding.Unicode.GetBytes(txtURLText.Text)); txtDecodedText.Text = Encoding.ASCII.GetString(Encoding.Unicode.GetBytes(txtURLText.Text)); txtDecodedText.Text = Encoding.Unicode.GetString(Convert.FromBase64String(txtURLText.Text)); What is the proper way to translate this encoding without using SQL Server? Is it possible? I'll take VB.NET code since I'm familiar with that too. Okay, I'm sure I'm missing something here, so here's where I'm at. Since my input is a basic string, I started with just a snippet of the encoded portion - 4445434C41 (which translates to DECLA) - and the first attempt was to do this... txtDecodedText.Text = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(txtURL.Text));...and all it did was return the exact same thing that I put in since it converted each character into is a byte. I realized that I need to parse every two characters into a byte manually since I don't know of any methods yet that will do that, so now my little decoder looks something like this: while (!boolIsDone) { bytURLChar = byte.Parse(txtURLText.Text.Substring(intParseIndex, 2)); bytURL[intURLIndex] = bytURLChar; intParseIndex += 2; intURLIndex++;
if (txtURLText.Text.Length - intParseIndex < 2) { boolIsDone = true; } }
txtDecodedText.Text = Encoding.UTF8.GetString(bytURL); Things look good for the first couple of pairs, but then the loop balks when it gets to the "4C" pair and says that the string is in the incorrect format. Interestingly enough, when I step through the debugger and to the GetString method on the byte array that I was able to parse up to that point, I get ",-+" as the result. How do I figure out what I'm missing - do I need to do a "direct cast" for each byte instead of attempting to parse it? | I went back to Michael's post, did some more poking and realized that I did need to do a double conversion, and eventually worked out this little nugget: Convert.ToString(Convert.ToChar(Int32.Parse(EncodedString.Substring(intParseIndex, 2), System.Globalization.NumberStyles.HexNumber))); From there I simply made a loop to go through all the characters 2 by 2 and get them "hexified" and then translated to a string. To Nick, and anybody else interested, I went ahead and posted my little application over in CodePlex. Feel free to use/modify as you need. | Decoding T-SQL CAST in C#/VB.NET Recently our site has been deluged with the resurgence of the Asprox botnet SQL injection attack. Without going into details, the attack attempts to execute SQL code by encoding the T-SQL commands in an ASCII encoded BINARY string. It looks something like this: DECLARE%20@S%20NVARCHAR(4000);SET%20@S=CAST(0x44004500...06F007200%20AS%20NVARCHAR(4000));EXEC(@S);-- I was able to decode this in SQL, but I was a little wary of doing this since I didn't know exactly what was happening at the time. I tried to write a simple decode tool, so I could decode this type of text without even touching SQL Server. The main part I need to be decoded is: CAST(0x44004500...06F007200 AS NVARCHAR(4000)) I've tried all of the following commands with no luck: txtDecodedText.Text = System.Web.HttpUtility.UrlDecode(txtURLText.Text); txtDecodedText.Text = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(txtURLText.Text)); txtDecodedText.Text = Encoding.Unicode.GetString(Encoding.Unicode.GetBytes(txtURLText.Text)); txtDecodedText.Text = Encoding.ASCII.GetString(Encoding.Unicode.GetBytes(txtURLText.Text)); txtDecodedText.Text = Encoding.Unicode.GetString(Convert.FromBase64String(txtURLText.Text)); What is the proper way to translate this encoding without using SQL Server? Is it possible? I'll take VB.NET code since I'm familiar with that too. Okay, I'm sure I'm missing something here, so here's where I'm at. Since my input is a basic string, I started with just a snippet of the encoded portion - 4445434C41 (which translates to DECLA) - and the first attempt was to do this... txtDecodedText.Text = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(txtURL.Text));...and all it did was return the exact same thing that I put in since it converted each character into is a byte. I realized that I need to parse every two characters into a byte manually since I don't know of any methods yet that will do that, so now my little decoder looks something like this: while (!boolIsDone) { bytURLChar = byte.Parse(txtURLText.Text.Substring(intParseIndex, 2)); bytURL[intURLIndex] = bytURLChar; intParseIndex += 2; intURLIndex++;
if (txtURLText.Text.Length - intParseIndex < 2) { boolIsDone = true; } }
txtDecodedText.Text = Encoding.UTF8.GetString(bytURL); Things look good for the first couple of pairs, but then the loop balks when it gets to the "4C" pair and says that the string is in the incorrect format. Interestingly enough, when I step through the debugger and to the GetString method on the byte array that I was able to parse up to that point, I get ",-+" as the result. How do I figure out what I'm missing - do I need to do a "direct cast" for each byte instead of attempting to parse it? | TITLE:
Decoding T-SQL CAST in C#/VB.NET
QUESTION:
Recently our site has been deluged with the resurgence of the Asprox botnet SQL injection attack. Without going into details, the attack attempts to execute SQL code by encoding the T-SQL commands in an ASCII encoded BINARY string. It looks something like this: DECLARE%20@S%20NVARCHAR(4000);SET%20@S=CAST(0x44004500...06F007200%20AS%20NVARCHAR(4000));EXEC(@S);-- I was able to decode this in SQL, but I was a little wary of doing this since I didn't know exactly what was happening at the time. I tried to write a simple decode tool, so I could decode this type of text without even touching SQL Server. The main part I need to be decoded is: CAST(0x44004500...06F007200 AS NVARCHAR(4000)) I've tried all of the following commands with no luck: txtDecodedText.Text = System.Web.HttpUtility.UrlDecode(txtURLText.Text); txtDecodedText.Text = Encoding.ASCII.GetString(Encoding.ASCII.GetBytes(txtURLText.Text)); txtDecodedText.Text = Encoding.Unicode.GetString(Encoding.Unicode.GetBytes(txtURLText.Text)); txtDecodedText.Text = Encoding.ASCII.GetString(Encoding.Unicode.GetBytes(txtURLText.Text)); txtDecodedText.Text = Encoding.Unicode.GetString(Convert.FromBase64String(txtURLText.Text)); What is the proper way to translate this encoding without using SQL Server? Is it possible? I'll take VB.NET code since I'm familiar with that too. Okay, I'm sure I'm missing something here, so here's where I'm at. Since my input is a basic string, I started with just a snippet of the encoded portion - 4445434C41 (which translates to DECLA) - and the first attempt was to do this... txtDecodedText.Text = Encoding.UTF8.GetString(Encoding.UTF8.GetBytes(txtURL.Text));...and all it did was return the exact same thing that I put in since it converted each character into is a byte. I realized that I need to parse every two characters into a byte manually since I don't know of any methods yet that will do that, so now my little decoder looks something like this: while (!boolIsDone) { bytURLChar = byte.Parse(txtURLText.Text.Substring(intParseIndex, 2)); bytURL[intURLIndex] = bytURLChar; intParseIndex += 2; intURLIndex++;
if (txtURLText.Text.Length - intParseIndex < 2) { boolIsDone = true; } }
txtDecodedText.Text = Encoding.UTF8.GetString(bytURL); Things look good for the first couple of pairs, but then the loop balks when it gets to the "4C" pair and says that the string is in the incorrect format. Interestingly enough, when I step through the debugger and to the GetString method on the byte array that I was able to parse up to that point, I get ",-+" as the result. How do I figure out what I'm missing - do I need to do a "direct cast" for each byte instead of attempting to parse it?
ANSWER:
I went back to Michael's post, did some more poking and realized that I did need to do a double conversion, and eventually worked out this little nugget: Convert.ToString(Convert.ToChar(Int32.Parse(EncodedString.Substring(intParseIndex, 2), System.Globalization.NumberStyles.HexNumber))); From there I simply made a loop to go through all the characters 2 by 2 and get them "hexified" and then translated to a string. To Nick, and anybody else interested, I went ahead and posted my little application over in CodePlex. Feel free to use/modify as you need. | [
"c#",
"sql",
"vb.net",
"ascii",
"hex"
] | 68 | 24 | 6,199 | 2 | 0 | 2008-08-01T15:23:05.190000 | 2008-08-05T17:02:30.870000 |
123 | 183 | Java lib or app to convert CSV to XML file? | Is there an existing application or library in Java which will allow me to convert a CSV data file to XML file? The XML tags would be provided through possibly the first row containing column headings. | Maybe this might help: JSefa You can read CSV file with this tool and serialize it to XML. | Java lib or app to convert CSV to XML file? Is there an existing application or library in Java which will allow me to convert a CSV data file to XML file? The XML tags would be provided through possibly the first row containing column headings. | TITLE:
Java lib or app to convert CSV to XML file?
QUESTION:
Is there an existing application or library in Java which will allow me to convert a CSV data file to XML file? The XML tags would be provided through possibly the first row containing column headings.
ANSWER:
Maybe this might help: JSefa You can read CSV file with this tool and serialize it to XML. | [
"java",
"xml",
"csv",
"data-conversion"
] | 121 | 70 | 81,172 | 16 | 0 | 2008-08-01T16:08:52.353000 | 2008-08-01T18:51:12.090000 |
126 | 127 | How would you access Object properties from within an object method? | What is the "purist" or "correct" way to access an object's properties from within an object method that is not a getter/setter method? I know that from outside of the object you should use a getter/setter, but from within would you just do: Java: String property = this.property; PHP: $property = $this->property; or would you do: Java: String property = this.getProperty(); PHP: $property = $this->getProperty(); Forgive me if my Java is a little off, it's been a year since I programmed in Java... EDIT: It seems people are assuming I am talking about private or protected variables/properties only. When I learned OO I was taught to use getters/setters for every single property even if it was public (and actually I was told never to make any variable/property public). So, I may be starting off from a false assumption from the get go. It appears that people answering this question are maybe saying that you should have public properties and that those don't need getters and setters, which goes against what I was taught, and what I was talking about, although maybe that needs to be discussed as well. That's probably a good topic for a different question though... | This has religious war potential, but it seems to me that if you're using a getter/setter, you should use it internally as well - using both will lead to maintenance problems down the road (e.g. somebody adds code to a setter that needs to run every time that property is set, and the property is being set internally w/o that setter being called). | How would you access Object properties from within an object method? What is the "purist" or "correct" way to access an object's properties from within an object method that is not a getter/setter method? I know that from outside of the object you should use a getter/setter, but from within would you just do: Java: String property = this.property; PHP: $property = $this->property; or would you do: Java: String property = this.getProperty(); PHP: $property = $this->getProperty(); Forgive me if my Java is a little off, it's been a year since I programmed in Java... EDIT: It seems people are assuming I am talking about private or protected variables/properties only. When I learned OO I was taught to use getters/setters for every single property even if it was public (and actually I was told never to make any variable/property public). So, I may be starting off from a false assumption from the get go. It appears that people answering this question are maybe saying that you should have public properties and that those don't need getters and setters, which goes against what I was taught, and what I was talking about, although maybe that needs to be discussed as well. That's probably a good topic for a different question though... | TITLE:
How would you access Object properties from within an object method?
QUESTION:
What is the "purist" or "correct" way to access an object's properties from within an object method that is not a getter/setter method? I know that from outside of the object you should use a getter/setter, but from within would you just do: Java: String property = this.property; PHP: $property = $this->property; or would you do: Java: String property = this.getProperty(); PHP: $property = $this->getProperty(); Forgive me if my Java is a little off, it's been a year since I programmed in Java... EDIT: It seems people are assuming I am talking about private or protected variables/properties only. When I learned OO I was taught to use getters/setters for every single property even if it was public (and actually I was told never to make any variable/property public). So, I may be starting off from a false assumption from the get go. It appears that people answering this question are maybe saying that you should have public properties and that those don't need getters and setters, which goes against what I was taught, and what I was talking about, although maybe that needs to be discussed as well. That's probably a good topic for a different question though...
ANSWER:
This has religious war potential, but it seems to me that if you're using a getter/setter, you should use it internally as well - using both will lead to maintenance problems down the road (e.g. somebody adds code to a setter that needs to run every time that property is set, and the property is being set internally w/o that setter being called). | [
"java",
"php",
"oop",
"theory"
] | 106 | 66 | 26,730 | 18 | 0 | 2008-08-01T16:10:30.337000 | 2008-08-01T16:13:47.600000 |
134 | 206 | XSD DataSets and ignoring foreign keys | I have a pretty standard table set-up in a current application using the.NET XSD DataSet and TableAdapter features. My contracts table consists of some standard contract information, with a column for the primary department. This column is a foreign key to my Departments table, where I store the basic department name, id, notes. This is all setup and functioning in my SQL Server. When I use the XSD tool, I can drag both tables in at once and it auto detects/creates the foreign key I have between these two tables. This works great when I'm on my main page and am viewing contract data. However, when I go to my administrative page to modify the department data, I typically do something like this: Dim dtDepartment As New DepartmentDataTable() Dim taDepartment As New DepartmentTableAdapter()
taDepartment.Fill(dtDepartment) However, at this point an exception is thrown saying to the effect that there is a foreign key reference broken here, I'm guessing since I don't have the Contract DataTable filled. How can I fix this problem? I know I can simply remove the foreign key from the XSD to make things work fine, but having the additional integrity check there and having the XSD schema match the SQL schema in the database is nice. | You can try turning Check-constraints off on the DataSet (it's in its properties), or altering the properties of that relationship, and change the key to a simple reference - up to you. | XSD DataSets and ignoring foreign keys I have a pretty standard table set-up in a current application using the.NET XSD DataSet and TableAdapter features. My contracts table consists of some standard contract information, with a column for the primary department. This column is a foreign key to my Departments table, where I store the basic department name, id, notes. This is all setup and functioning in my SQL Server. When I use the XSD tool, I can drag both tables in at once and it auto detects/creates the foreign key I have between these two tables. This works great when I'm on my main page and am viewing contract data. However, when I go to my administrative page to modify the department data, I typically do something like this: Dim dtDepartment As New DepartmentDataTable() Dim taDepartment As New DepartmentTableAdapter()
taDepartment.Fill(dtDepartment) However, at this point an exception is thrown saying to the effect that there is a foreign key reference broken here, I'm guessing since I don't have the Contract DataTable filled. How can I fix this problem? I know I can simply remove the foreign key from the XSD to make things work fine, but having the additional integrity check there and having the XSD schema match the SQL schema in the database is nice. | TITLE:
XSD DataSets and ignoring foreign keys
QUESTION:
I have a pretty standard table set-up in a current application using the.NET XSD DataSet and TableAdapter features. My contracts table consists of some standard contract information, with a column for the primary department. This column is a foreign key to my Departments table, where I store the basic department name, id, notes. This is all setup and functioning in my SQL Server. When I use the XSD tool, I can drag both tables in at once and it auto detects/creates the foreign key I have between these two tables. This works great when I'm on my main page and am viewing contract data. However, when I go to my administrative page to modify the department data, I typically do something like this: Dim dtDepartment As New DepartmentDataTable() Dim taDepartment As New DepartmentTableAdapter()
taDepartment.Fill(dtDepartment) However, at this point an exception is thrown saying to the effect that there is a foreign key reference broken here, I'm guessing since I don't have the Contract DataTable filled. How can I fix this problem? I know I can simply remove the foreign key from the XSD to make things work fine, but having the additional integrity check there and having the XSD schema match the SQL schema in the database is nice.
ANSWER:
You can try turning Check-constraints off on the DataSet (it's in its properties), or altering the properties of that relationship, and change the key to a simple reference - up to you. | [
".net",
"database",
"xsd"
] | 39 | 13 | 1,519 | 1 | 0 | 2008-08-01T16:33:38.183000 | 2008-08-01T19:52:14.227000 |
146 | 152 | How do I track file downloads | I have a website that plays mp3s in a flash player. If a user clicks 'play' the flash player automatically downloads an mp3 and starts playing it. Is there an easy way to track how many times a particular song clip (or any binary file) has been downloaded? Is the play link a link to the actual mp3 file or to some javascript code that pops up a player? If the latter, you can easily add your own logging code in there to track the number of hits to it. If the former, you'll need something that can track the web server log itself and make that distinction. My hosting plan comes with Webalizer, which does this nicely. It's a javascript code so that answers that. However, it would be nice to know how to track downloads using the other method (without switching hosts). | The funny thing is I wrote a php media gallery for all my musics 2 days ago. I had a similar problem. I'm using http://musicplayer.sourceforge.net/ for the player. And the playlist is built via php. All music requests go to a script called xfer.php?file=WHATEVER $filename = base64_url_decode($_REQUEST['file']); header("Cache-Control: public"); header('Content-disposition: attachment; filename='.basename($filename)); header("Content-Transfer-Encoding: binary"); header('Content-Length: '. filesize($filename));
// Put either file counting code here, either a db or static files // readfile($filename); //and spit the user the file
function base64_url_decode($input) { return base64_decode(strtr($input, '-_,', '+/=')); } And when you call files use something like: function base64_url_encode($input) { return strtr(base64_encode($input), '+/=', '-_,'); } http://us.php.net/manual/en/function.base64-encode.php If you are using some JavaScript or a flash player (JW player for example) that requires the actual link of an mp3 file or whatever, you can append the text "&type=.mp3" so the final link becomes something like: "www.example.com/xfer.php?file=34842ffjfjxfh&type=.mp3". That way it looks like it ends with an mp3 extension without affecting the file link. | How do I track file downloads I have a website that plays mp3s in a flash player. If a user clicks 'play' the flash player automatically downloads an mp3 and starts playing it. Is there an easy way to track how many times a particular song clip (or any binary file) has been downloaded? Is the play link a link to the actual mp3 file or to some javascript code that pops up a player? If the latter, you can easily add your own logging code in there to track the number of hits to it. If the former, you'll need something that can track the web server log itself and make that distinction. My hosting plan comes with Webalizer, which does this nicely. It's a javascript code so that answers that. However, it would be nice to know how to track downloads using the other method (without switching hosts). | TITLE:
How do I track file downloads
QUESTION:
I have a website that plays mp3s in a flash player. If a user clicks 'play' the flash player automatically downloads an mp3 and starts playing it. Is there an easy way to track how many times a particular song clip (or any binary file) has been downloaded? Is the play link a link to the actual mp3 file or to some javascript code that pops up a player? If the latter, you can easily add your own logging code in there to track the number of hits to it. If the former, you'll need something that can track the web server log itself and make that distinction. My hosting plan comes with Webalizer, which does this nicely. It's a javascript code so that answers that. However, it would be nice to know how to track downloads using the other method (without switching hosts).
ANSWER:
The funny thing is I wrote a php media gallery for all my musics 2 days ago. I had a similar problem. I'm using http://musicplayer.sourceforge.net/ for the player. And the playlist is built via php. All music requests go to a script called xfer.php?file=WHATEVER $filename = base64_url_decode($_REQUEST['file']); header("Cache-Control: public"); header('Content-disposition: attachment; filename='.basename($filename)); header("Content-Transfer-Encoding: binary"); header('Content-Length: '. filesize($filename));
// Put either file counting code here, either a db or static files // readfile($filename); //and spit the user the file
function base64_url_decode($input) { return base64_decode(strtr($input, '-_,', '+/=')); } And when you call files use something like: function base64_url_encode($input) { return strtr(base64_encode($input), '+/=', '-_,'); } http://us.php.net/manual/en/function.base64-encode.php If you are using some JavaScript or a flash player (JW player for example) that requires the actual link of an mp3 file or whatever, you can append the text "&type=.mp3" so the final link becomes something like: "www.example.com/xfer.php?file=34842ffjfjxfh&type=.mp3". That way it looks like it ends with an mp3 extension without affecting the file link. | [
"php",
"apache",
"logging",
"download",
"analytics"
] | 90 | 42 | 21,872 | 8 | 0 | 2008-08-01T17:14:58.337000 | 2008-08-01T17:33:58.750000 |
163 | 170 | How do I sync the SVN revision number with my ASP.NET web site? | Stack Overflow has a subversion version number at the bottom: svn revision: 679 I want to use such automatic versioning with my.NET Web Site/Application, Windows Forms, WPD projects/solutions. How do I implement this? | Looks like Jeff is using CruiseControl.NET based on some leafing through the podcast transcripts. This seems to have automated deployment capabilities from source control to production. Might this be where the insertion is happening? | How do I sync the SVN revision number with my ASP.NET web site? Stack Overflow has a subversion version number at the bottom: svn revision: 679 I want to use such automatic versioning with my.NET Web Site/Application, Windows Forms, WPD projects/solutions. How do I implement this? | TITLE:
How do I sync the SVN revision number with my ASP.NET web site?
QUESTION:
Stack Overflow has a subversion version number at the bottom: svn revision: 679 I want to use such automatic versioning with my.NET Web Site/Application, Windows Forms, WPD projects/solutions. How do I implement this?
ANSWER:
Looks like Jeff is using CruiseControl.NET based on some leafing through the podcast transcripts. This seems to have automated deployment capabilities from source control to production. Might this be where the insertion is happening? | [
".net",
"asp.net",
"svn",
"versioning"
] | 101 | 32 | 9,524 | 7 | 0 | 2008-08-01T18:00:13.830000 | 2008-08-01T18:24:30.550000 |
164 | 699 | Embedding Windows Media Player for all browsers | Edit: This question was written in 2008, which was like 3 internet ages ago. If this question is still relevant to your environment, please accept my condolences. Everyone else should convert into a format supported by your browsers (That would be H.264 if Internet Explorer is needed, and probably AV1, VP8/VP9 if not) and use the element. We are using WMV videos on an internal site, and we are embedding them into web sites. This works quite well on Internet Explorer, but not on Firefox. I've found ways to make it work in Firefox, but then it stops working in Internet Explorer. We do not want to use Silverlight just yet, especially since we cannot be sure that all clients will be running Windows XP with Windows Media Player installed. Is there some sort of Universal Code that embeds WMP into both Internet Explorer and Firefox, or do we need to implement some user-agent-detection and deliver different HTML for different browsers? | The following works for me in Firefox and Internet Explorer: | Embedding Windows Media Player for all browsers Edit: This question was written in 2008, which was like 3 internet ages ago. If this question is still relevant to your environment, please accept my condolences. Everyone else should convert into a format supported by your browsers (That would be H.264 if Internet Explorer is needed, and probably AV1, VP8/VP9 if not) and use the element. We are using WMV videos on an internal site, and we are embedding them into web sites. This works quite well on Internet Explorer, but not on Firefox. I've found ways to make it work in Firefox, but then it stops working in Internet Explorer. We do not want to use Silverlight just yet, especially since we cannot be sure that all clients will be running Windows XP with Windows Media Player installed. Is there some sort of Universal Code that embeds WMP into both Internet Explorer and Firefox, or do we need to implement some user-agent-detection and deliver different HTML for different browsers? | TITLE:
Embedding Windows Media Player for all browsers
QUESTION:
Edit: This question was written in 2008, which was like 3 internet ages ago. If this question is still relevant to your environment, please accept my condolences. Everyone else should convert into a format supported by your browsers (That would be H.264 if Internet Explorer is needed, and probably AV1, VP8/VP9 if not) and use the element. We are using WMV videos on an internal site, and we are embedding them into web sites. This works quite well on Internet Explorer, but not on Firefox. I've found ways to make it work in Firefox, but then it stops working in Internet Explorer. We do not want to use Silverlight just yet, especially since we cannot be sure that all clients will be running Windows XP with Windows Media Player installed. Is there some sort of Universal Code that embeds WMP into both Internet Explorer and Firefox, or do we need to implement some user-agent-detection and deliver different HTML for different browsers?
ANSWER:
The following works for me in Firefox and Internet Explorer: | [
"windows",
"embed",
"media"
] | 64 | 47 | 177,305 | 10 | 0 | 2008-08-01T18:02:22.797000 | 2008-08-03T14:27:20.967000 |
173 | 516 | How to do version control for SQL Server database? | I want to get my databases under version control. I'll always want to have at least some data in there (as alumb mentions: user types and administrators). I'll also often want a large collection of generated test data for performance measurements. How would I apply version control to my database? | Martin Fowler wrote my favorite article on the subject, http://martinfowler.com/articles/evodb.html. I choose not to put schema dumps in under version control as alumb and others suggest because I want an easy way to upgrade my production database. For a web application where I'll have a single production database instance, I use two techniques: Database Upgrade Scripts A sequence database upgrade scripts that contain the DDL necessary to move the schema from version N to N+1. (These go in your version control system.) A _version_history_ table, something like create table VersionHistory ( Version int primary key, UpgradeStart datetime not null, UpgradeEnd datetime ); gets a new entry every time an upgrade script runs which corresponds to the new version. This ensures that it's easy to see what version of the database schema exists and that database upgrade scripts are run only once. Again, these are not database dumps. Rather, each script represents the changes necessary to move from one version to the next. They're the script that you apply to your production database to "upgrade" it. Developer Sandbox Synchronization A script to backup, sanitize, and shrink a production database. Run this after each upgrade to the production DB. A script to restore (and tweak, if necessary) the backup on a developer's workstation. Each developer runs this script after each upgrade to the production DB. A caveat: My automated tests run against a schema-correct but empty database, so this advice will not perfectly suit your needs. | How to do version control for SQL Server database? I want to get my databases under version control. I'll always want to have at least some data in there (as alumb mentions: user types and administrators). I'll also often want a large collection of generated test data for performance measurements. How would I apply version control to my database? | TITLE:
How to do version control for SQL Server database?
QUESTION:
I want to get my databases under version control. I'll always want to have at least some data in there (as alumb mentions: user types and administrators). I'll also often want a large collection of generated test data for performance measurements. How would I apply version control to my database?
ANSWER:
Martin Fowler wrote my favorite article on the subject, http://martinfowler.com/articles/evodb.html. I choose not to put schema dumps in under version control as alumb and others suggest because I want an easy way to upgrade my production database. For a web application where I'll have a single production database instance, I use two techniques: Database Upgrade Scripts A sequence database upgrade scripts that contain the DDL necessary to move the schema from version N to N+1. (These go in your version control system.) A _version_history_ table, something like create table VersionHistory ( Version int primary key, UpgradeStart datetime not null, UpgradeEnd datetime ); gets a new entry every time an upgrade script runs which corresponds to the new version. This ensures that it's easy to see what version of the database schema exists and that database upgrade scripts are run only once. Again, these are not database dumps. Rather, each script represents the changes necessary to move from one version to the next. They're the script that you apply to your production database to "upgrade" it. Developer Sandbox Synchronization A script to backup, sanitize, and shrink a production database. Run this after each upgrade to the production DB. A script to restore (and tweak, if necessary) the backup on a developer's workstation. Each developer runs this script after each upgrade to the production DB. A caveat: My automated tests run against a schema-correct but empty database, so this advice will not perfectly suit your needs. | [
"sql-server",
"database",
"svn",
"version-control"
] | 341 | 191 | 124,650 | 21 | 0 | 2008-08-01T18:33:08.333000 | 2008-08-02T17:33:54.927000 |
176 | 207 | error_log per Virtual Host? | On one Linux Server running Apache and PHP 5, we have multiple Virtual Hosts with separate log files. We cannot seem to separate the php error_log between virtual hosts. Overriding this setting in the of the httpd.conf does not seem to do anything. Is there a way to have separate php error_logs for each Virtual Host? | To set the Apache ( not the PHP ) log, the easiest way to do this would be to do: # Stuff, # More Stuff, ErrorLog /path/where/you/want/the/error.log If there is no leading "/" it is assumed to be relative. Apache Error Log Page | error_log per Virtual Host? On one Linux Server running Apache and PHP 5, we have multiple Virtual Hosts with separate log files. We cannot seem to separate the php error_log between virtual hosts. Overriding this setting in the of the httpd.conf does not seem to do anything. Is there a way to have separate php error_logs for each Virtual Host? | TITLE:
error_log per Virtual Host?
QUESTION:
On one Linux Server running Apache and PHP 5, we have multiple Virtual Hosts with separate log files. We cannot seem to separate the php error_log between virtual hosts. Overriding this setting in the of the httpd.conf does not seem to do anything. Is there a way to have separate php error_logs for each Virtual Host?
ANSWER:
To set the Apache ( not the PHP ) log, the easiest way to do this would be to do: # Stuff, # More Stuff, ErrorLog /path/where/you/want/the/error.log If there is no leading "/" it is assumed to be relative. Apache Error Log Page | [
"linux",
"apache",
"virtualhost"
] | 124 | 89 | 120,269 | 11 | 0 | 2008-08-01T18:37:40.150000 | 2008-08-01T19:58:45.837000 |
180 | 539 | Function for creating color wheels | This is something I've pseudo-solved many times and have never quite found a solution for. The problem is to come up with a way to generate N colors, that are as distinguishable as possible where N is a parameter. | My first thought on this is "how to generate N vectors in a space that maximize distance from each other." You can see that the RGB (or any other scale you use that forms a basis in color space) are just vectors. Take a look at Random Point Picking. Once you have a set of vectors that are maximized apart, you can save them in a hash table or something for later, and just perform random rotations on them to get all the colors you desire that are maximally apart from each other! Thinking about this problem more, it would be better to map the colors in a linear manner, possibly (0,0,0) → (255,255,255) lexicographically, and then distribute them evenly. I really don't know how well this will work, but it should since, let us say: n = 10 we know we have 16777216 colors (256^3). We can use Buckles Algorithm 515 to find the lexicographically indexed color.. You'll probably have to edit the algorithm to avoid overflow and probably add some minor speed improvements. | Function for creating color wheels This is something I've pseudo-solved many times and have never quite found a solution for. The problem is to come up with a way to generate N colors, that are as distinguishable as possible where N is a parameter. | TITLE:
Function for creating color wheels
QUESTION:
This is something I've pseudo-solved many times and have never quite found a solution for. The problem is to come up with a way to generate N colors, that are as distinguishable as possible where N is a parameter.
ANSWER:
My first thought on this is "how to generate N vectors in a space that maximize distance from each other." You can see that the RGB (or any other scale you use that forms a basis in color space) are just vectors. Take a look at Random Point Picking. Once you have a set of vectors that are maximized apart, you can save them in a hash table or something for later, and just perform random rotations on them to get all the colors you desire that are maximally apart from each other! Thinking about this problem more, it would be better to map the colors in a linear manner, possibly (0,0,0) → (255,255,255) lexicographically, and then distribute them evenly. I really don't know how well this will work, but it should since, let us say: n = 10 we know we have 16777216 colors (256^3). We can use Buckles Algorithm 515 to find the lexicographically indexed color.. You'll probably have to edit the algorithm to avoid overflow and probably add some minor speed improvements. | [
"algorithm",
"language-agnostic",
"colors",
"color-space"
] | 71 | 28 | 19,598 | 8 | 0 | 2008-08-01T18:42:19.343000 | 2008-08-02T19:03:52.170000 |
192 | 258 | Floating Point Number parsing: Is there a Catch All algorithm? | One of the fun parts of multi-cultural programming is number formats. Americans use 10,000.50 Germans use 10.000,50 French use 10 000,50 My first approach would be to take the string, parse it backwards until I encounter a separator and use this as my decimal separator. There is an obvious flaw with that: 10.000 would be interpreted as 10. Another approach: if the string contains 2 different non-numeric characters, use the last one as the decimal separator and discard the others. If I only have one, check if it occurs more than once and discards it if it does. If it only appears once, check if it has 3 digits after it. If yes, discard it, otherwise, use it as decimal separator. The obvious "best solution" would be to detect the User's culture or Browser, but that does not work if you have a Frenchman using an en-US Windows/Browser. Does the.net Framework contain some mythical black magic floating point parser that is better than Double.(Try)Parse() in trying to auto-detect the number format? | I think the best you can do in this case is to take their input and then show them what you think they meant. If they disagree, show them the format you're expecting and get them to enter it again. | Floating Point Number parsing: Is there a Catch All algorithm? One of the fun parts of multi-cultural programming is number formats. Americans use 10,000.50 Germans use 10.000,50 French use 10 000,50 My first approach would be to take the string, parse it backwards until I encounter a separator and use this as my decimal separator. There is an obvious flaw with that: 10.000 would be interpreted as 10. Another approach: if the string contains 2 different non-numeric characters, use the last one as the decimal separator and discard the others. If I only have one, check if it occurs more than once and discards it if it does. If it only appears once, check if it has 3 digits after it. If yes, discard it, otherwise, use it as decimal separator. The obvious "best solution" would be to detect the User's culture or Browser, but that does not work if you have a Frenchman using an en-US Windows/Browser. Does the.net Framework contain some mythical black magic floating point parser that is better than Double.(Try)Parse() in trying to auto-detect the number format? | TITLE:
Floating Point Number parsing: Is there a Catch All algorithm?
QUESTION:
One of the fun parts of multi-cultural programming is number formats. Americans use 10,000.50 Germans use 10.000,50 French use 10 000,50 My first approach would be to take the string, parse it backwards until I encounter a separator and use this as my decimal separator. There is an obvious flaw with that: 10.000 would be interpreted as 10. Another approach: if the string contains 2 different non-numeric characters, use the last one as the decimal separator and discard the others. If I only have one, check if it occurs more than once and discards it if it does. If it only appears once, check if it has 3 digits after it. If yes, discard it, otherwise, use it as decimal separator. The obvious "best solution" would be to detect the User's culture or Browser, but that does not work if you have a Frenchman using an en-US Windows/Browser. Does the.net Framework contain some mythical black magic floating point parser that is better than Double.(Try)Parse() in trying to auto-detect the number format?
ANSWER:
I think the best you can do in this case is to take their input and then show them what you think they meant. If they disagree, show them the format you're expecting and get them to enter it again. | [
"c#",
".net",
"asp.net",
"internationalization",
"globalization"
] | 72 | 32 | 3,583 | 4 | 0 | 2008-08-01T19:23:13.117000 | 2008-08-01T23:17:53.657000 |
194 | 197 | Upgrading SQL Server 6.5 | Yes, I know. The existence of a running copy of SQL Server 6.5 in 2008 is absurd. That stipulated, what is the best way to migrate from 6.5 to 2005? Is there any direct path? Most of the documentation I've found deals with upgrading 6.5 to 7. Should I forget about the native SQL Server upgrade utilities, script out all of the objects and data, and try to recreate from scratch? I was going to attempt the upgrade this weekend, but server issues pushed it back till next. So, any ideas would be welcomed during the course of the week. Update. This is how I ended up doing it: Back up the database in question and Master on 6.5. Execute SQL Server 2000 's instcat.sql against 6.5 's Master. This allows SQL Server 2000 's OLEDB provider to connect to 6.5. Use SQL Server 2000 's standalone "Import and Export Data" to create a DTS package, using OLEDB to connect to 6.5. This successfully copied all 6.5 's tables to a new 2005 database (also using OLEDB ). Use 6.5 's Enterprise Manager to script out all of the database's indexes and triggers to a.sql file. Execute that.sql file against the new copy of the database, in 2005's Management Studio. Use 6.5's Enterprise Manager to script out all of the stored procedures. Execute that.sql file against the 2005 database. Several dozen sprocs had issues making them incompatible with 2005. Mainly non-ANSI joins and quoted identifier issues. Corrected all of those issues and re-executed the.sql file. Recreated the 6.5 's logins in 2005 and gave them appropriate permissions. There was a bit of rinse/repeat when correcting the stored procedures (there were hundreds of them to correct), but the upgrade went great otherwise. Being able to use Management Studio instead of Query Analyzer and Enterprise Manager 6.5 is such an amazing difference. A few report queries that took 20-30 seconds on the 6.5 database are now running in 1-2 seconds, without any modification, new indexes, or anything. I didn't expect that kind of immediate improvement. | Hey, I'm still stuck in that camp too. The third party application we have to support is FINALLY going to 2K5, so we're almost out of the wood. But I feel your pain 8^D That said, from everything I heard from our DBA, the key is to convert the database to 8.0 format first, and then go to 2005. I believe they used the built in migration/upgrade tools for this. There are some big steps between 6.5 and 8.0 that are better solved there than going from 6.5 to 2005 directly. Your BIGGEST pain, if you didn't know already, is that DTS is gone in favor of SSIS. There is a shell type module that will run your existing DTS packages, but you're going to want to manually recreate them all in SSIS. Ease of this will depend on the complexity of the packages themselves, but I've done a few at work so far and they've been pretty smooth. | Upgrading SQL Server 6.5 Yes, I know. The existence of a running copy of SQL Server 6.5 in 2008 is absurd. That stipulated, what is the best way to migrate from 6.5 to 2005? Is there any direct path? Most of the documentation I've found deals with upgrading 6.5 to 7. Should I forget about the native SQL Server upgrade utilities, script out all of the objects and data, and try to recreate from scratch? I was going to attempt the upgrade this weekend, but server issues pushed it back till next. So, any ideas would be welcomed during the course of the week. Update. This is how I ended up doing it: Back up the database in question and Master on 6.5. Execute SQL Server 2000 's instcat.sql against 6.5 's Master. This allows SQL Server 2000 's OLEDB provider to connect to 6.5. Use SQL Server 2000 's standalone "Import and Export Data" to create a DTS package, using OLEDB to connect to 6.5. This successfully copied all 6.5 's tables to a new 2005 database (also using OLEDB ). Use 6.5 's Enterprise Manager to script out all of the database's indexes and triggers to a.sql file. Execute that.sql file against the new copy of the database, in 2005's Management Studio. Use 6.5's Enterprise Manager to script out all of the stored procedures. Execute that.sql file against the 2005 database. Several dozen sprocs had issues making them incompatible with 2005. Mainly non-ANSI joins and quoted identifier issues. Corrected all of those issues and re-executed the.sql file. Recreated the 6.5 's logins in 2005 and gave them appropriate permissions. There was a bit of rinse/repeat when correcting the stored procedures (there were hundreds of them to correct), but the upgrade went great otherwise. Being able to use Management Studio instead of Query Analyzer and Enterprise Manager 6.5 is such an amazing difference. A few report queries that took 20-30 seconds on the 6.5 database are now running in 1-2 seconds, without any modification, new indexes, or anything. I didn't expect that kind of immediate improvement. | TITLE:
Upgrading SQL Server 6.5
QUESTION:
Yes, I know. The existence of a running copy of SQL Server 6.5 in 2008 is absurd. That stipulated, what is the best way to migrate from 6.5 to 2005? Is there any direct path? Most of the documentation I've found deals with upgrading 6.5 to 7. Should I forget about the native SQL Server upgrade utilities, script out all of the objects and data, and try to recreate from scratch? I was going to attempt the upgrade this weekend, but server issues pushed it back till next. So, any ideas would be welcomed during the course of the week. Update. This is how I ended up doing it: Back up the database in question and Master on 6.5. Execute SQL Server 2000 's instcat.sql against 6.5 's Master. This allows SQL Server 2000 's OLEDB provider to connect to 6.5. Use SQL Server 2000 's standalone "Import and Export Data" to create a DTS package, using OLEDB to connect to 6.5. This successfully copied all 6.5 's tables to a new 2005 database (also using OLEDB ). Use 6.5 's Enterprise Manager to script out all of the database's indexes and triggers to a.sql file. Execute that.sql file against the new copy of the database, in 2005's Management Studio. Use 6.5's Enterprise Manager to script out all of the stored procedures. Execute that.sql file against the 2005 database. Several dozen sprocs had issues making them incompatible with 2005. Mainly non-ANSI joins and quoted identifier issues. Corrected all of those issues and re-executed the.sql file. Recreated the 6.5 's logins in 2005 and gave them appropriate permissions. There was a bit of rinse/repeat when correcting the stored procedures (there were hundreds of them to correct), but the upgrade went great otherwise. Being able to use Management Studio instead of Query Analyzer and Enterprise Manager 6.5 is such an amazing difference. A few report queries that took 20-30 seconds on the 6.5 database are now running in 1-2 seconds, without any modification, new indexes, or anything. I didn't expect that kind of immediate improvement.
ANSWER:
Hey, I'm still stuck in that camp too. The third party application we have to support is FINALLY going to 2K5, so we're almost out of the wood. But I feel your pain 8^D That said, from everything I heard from our DBA, the key is to convert the database to 8.0 format first, and then go to 2005. I believe they used the built in migration/upgrade tools for this. There are some big steps between 6.5 and 8.0 that are better solved there than going from 6.5 to 2005 directly. Your BIGGEST pain, if you didn't know already, is that DTS is gone in favor of SSIS. There is a shell type module that will run your existing DTS packages, but you're going to want to manually recreate them all in SSIS. Ease of this will depend on the complexity of the packages themselves, but I've done a few at work so far and they've been pretty smooth. | [
"sql-server",
"migration"
] | 40 | 11 | 4,760 | 4 | 0 | 2008-08-01T19:26:37.883000 | 2008-08-01T19:34:49.067000 |
227 | 2,943,318 | Create a tag cloud by wrapping array values in h1 through h6 tags based on a mapping array of weights | I have the following arrays: $artist = ["the roots", "michael jackson", "billy idol", "more", "and more", "and_YET_MORE"]; $count = [5, 3, 9, 1, 1, 3]; I want to generate a tag cloud that will have artists with a higher number in $count enclosed in h6 tags and the lowest enclosed h1 tags. | You will want to add a logarithmic function to it too. (taken from tagadelic, my Drupal module to create tag clouds http://drupal.org/project/tagadelic ): db_query('SELECT COUNT(*) AS count, id, name FROM... ORDER BY count DESC');
$steps = 6; $tags = array(); $min = 1e9; $max = -1e9;
while ($tag = db_fetch_object($result)) { $tag->number_of_posts = $tag->count; #sets the amount of items a certain tag has attached to it $tag->count = log($tag->count); $min = min($min, $tag->count); $max = max($max, $tag->count); $tags[$tag->tid] = $tag; } // Note: we need to ensure the range is slightly too large to make sure even // the largest element is rounded down. $range = max(.01, $max - $min) * 1.0001;
foreach ($tags as $key => $value) { $tags[$key]->weight = 1 + floor($steps * ($value->count - $min) / $range); } Then in your view or template: foreach ($tags as $tag) { $output.= " weight>$tag->name weight>" } | Create a tag cloud by wrapping array values in h1 through h6 tags based on a mapping array of weights I have the following arrays: $artist = ["the roots", "michael jackson", "billy idol", "more", "and more", "and_YET_MORE"]; $count = [5, 3, 9, 1, 1, 3]; I want to generate a tag cloud that will have artists with a higher number in $count enclosed in h6 tags and the lowest enclosed h1 tags. | TITLE:
Create a tag cloud by wrapping array values in h1 through h6 tags based on a mapping array of weights
QUESTION:
I have the following arrays: $artist = ["the roots", "michael jackson", "billy idol", "more", "and more", "and_YET_MORE"]; $count = [5, 3, 9, 1, 1, 3]; I want to generate a tag cloud that will have artists with a higher number in $count enclosed in h6 tags and the lowest enclosed h1 tags.
ANSWER:
You will want to add a logarithmic function to it too. (taken from tagadelic, my Drupal module to create tag clouds http://drupal.org/project/tagadelic ): db_query('SELECT COUNT(*) AS count, id, name FROM... ORDER BY count DESC');
$steps = 6; $tags = array(); $min = 1e9; $max = -1e9;
while ($tag = db_fetch_object($result)) { $tag->number_of_posts = $tag->count; #sets the amount of items a certain tag has attached to it $tag->count = log($tag->count); $min = min($min, $tag->count); $max = max($max, $tag->count); $tags[$tag->tid] = $tag; } // Note: we need to ensure the range is slightly too large to make sure even // the largest element is rounded down. $range = max(.01, $max - $min) * 1.0001;
foreach ($tags as $key => $value) { $tags[$key]->weight = 1 + floor($steps * ($value->count - $min) / $range); } Then in your view or template: foreach ($tags as $tag) { $output.= " weight>$tag->name weight>" } | [
"php",
"arrays",
"mapping",
"tag-cloud"
] | 79 | 43 | 9,776 | 9 | 0 | 2008-08-01T21:40:55.833000 | 2010-05-31T11:53:57.940000 |
231 | 1,812 | Register Windows program with the mailto protocol programmatically | How do I make it so mailto: links will be registered with my program? How would I then handle that event in my program? Most of the solutions I found from a quick Google search are how to do this manually, but I need to do this automatically for users of my program if they click a button, such as "set as default email client". #Edit: Removed reference to the Delphi Programming Language, because the answer is independent of your language. | @Dillie-O: Your answer put me in the right direction (I should have expected it to just be a registry change) and I got this working. But I'm going to mark this as the answer because I'm going to put some additional information that I found while working on this. The solution to this question really doesn't depend on what programming language you're using, as long as there's some way to modify Windows registry settings. Finally, here's the answer: To associate a program with the mailto protocol for all users on a computer, change the HKEY_CLASSES_ROOT\mailto\shell\open\command Default value to: " Your program's executable " "%1" To associate a program with the mailto protocol for the current user, change the HKEY_CURRENT_USER\Software\Classes\mailto\shell\open\command Default value to: " Your program's executable " "%1" The %1 will be replaced with the entire mailto URL. For example, given the link: Email me The following will be executed: " Your program's executable " "mailto:user@example.com" Update (via comment by shellscape): As of Windows 8, this method no longer works as expected. Win8 enforces the following key: HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\URLAssociations\MAILTO\UserChoice for which the ProgID of the selected app is hashed and can't be forged. It's a royal PITA. | Register Windows program with the mailto protocol programmatically How do I make it so mailto: links will be registered with my program? How would I then handle that event in my program? Most of the solutions I found from a quick Google search are how to do this manually, but I need to do this automatically for users of my program if they click a button, such as "set as default email client". #Edit: Removed reference to the Delphi Programming Language, because the answer is independent of your language. | TITLE:
Register Windows program with the mailto protocol programmatically
QUESTION:
How do I make it so mailto: links will be registered with my program? How would I then handle that event in my program? Most of the solutions I found from a quick Google search are how to do this manually, but I need to do this automatically for users of my program if they click a button, such as "set as default email client". #Edit: Removed reference to the Delphi Programming Language, because the answer is independent of your language.
ANSWER:
@Dillie-O: Your answer put me in the right direction (I should have expected it to just be a registry change) and I got this working. But I'm going to mark this as the answer because I'm going to put some additional information that I found while working on this. The solution to this question really doesn't depend on what programming language you're using, as long as there's some way to modify Windows registry settings. Finally, here's the answer: To associate a program with the mailto protocol for all users on a computer, change the HKEY_CLASSES_ROOT\mailto\shell\open\command Default value to: " Your program's executable " "%1" To associate a program with the mailto protocol for the current user, change the HKEY_CURRENT_USER\Software\Classes\mailto\shell\open\command Default value to: " Your program's executable " "%1" The %1 will be replaced with the entire mailto URL. For example, given the link: Email me The following will be executed: " Your program's executable " "mailto:user@example.com" Update (via comment by shellscape): As of Windows 8, this method no longer works as expected. Win8 enforces the following key: HKEY_CURRENT_USER\Software\Microsoft\Windows\Shell\Associations\URLAssociations\MAILTO\UserChoice for which the ProgID of the selected app is hashed and can't be forged. It's a royal PITA. | [
"windows",
"mailto"
] | 43 | 19 | 31,416 | 2 | 0 | 2008-08-01T22:08:14.453000 | 2008-08-05T01:49:25.940000 |
234 | 12,202 | SQL Server 2005 implementation of MySQL REPLACE INTO? | MySQL has this incredibly useful yet proprietary REPLACE INTO SQL Command. Can this easily be emulated in SQL Server 2005? Starting a new Transaction, doing a Select() and then either UPDATE or INSERT and COMMIT is always a little bit of a pain, especially when doing it in the application and therefore always keeping 2 versions of the statement. I wonder if there is an easy and universal way to implement such a function into SQL Server 2005? | This is something that annoys me about MSSQL ( rant on my blog ). I wish MSSQL supported upsert. @Dillie-O's code is a good way in older SQL versions (+1 vote), but it still is basically two IO operations (the exists and then the update or insert ) There's a slightly better way on this post, basically: --try an update update tablename set field1 = 'new value', field2 = 'different value',... where idfield = 7
--insert if failed if @@rowcount = 0 and @@error = 0 insert into tablename ( idfield, field1, field2,... ) values ( 7, 'value one', 'another value',... ) This reduces it to one IO operations if it's an update, or two if an insert. MS Sql2008 introduces merge from the SQL:2003 standard: merge tablename as target using (values ('new value', 'different value')) as source (field1, field2) on target.idfield = 7 when matched then update set field1 = source.field1, field2 = source.field2,... when not matched then insert ( idfield, field1, field2,... ) values ( 7, source.field1, source.field2,... ) Now it's really just one IO operation, but awful code:-( | SQL Server 2005 implementation of MySQL REPLACE INTO? MySQL has this incredibly useful yet proprietary REPLACE INTO SQL Command. Can this easily be emulated in SQL Server 2005? Starting a new Transaction, doing a Select() and then either UPDATE or INSERT and COMMIT is always a little bit of a pain, especially when doing it in the application and therefore always keeping 2 versions of the statement. I wonder if there is an easy and universal way to implement such a function into SQL Server 2005? | TITLE:
SQL Server 2005 implementation of MySQL REPLACE INTO?
QUESTION:
MySQL has this incredibly useful yet proprietary REPLACE INTO SQL Command. Can this easily be emulated in SQL Server 2005? Starting a new Transaction, doing a Select() and then either UPDATE or INSERT and COMMIT is always a little bit of a pain, especially when doing it in the application and therefore always keeping 2 versions of the statement. I wonder if there is an easy and universal way to implement such a function into SQL Server 2005?
ANSWER:
This is something that annoys me about MSSQL ( rant on my blog ). I wish MSSQL supported upsert. @Dillie-O's code is a good way in older SQL versions (+1 vote), but it still is basically two IO operations (the exists and then the update or insert ) There's a slightly better way on this post, basically: --try an update update tablename set field1 = 'new value', field2 = 'different value',... where idfield = 7
--insert if failed if @@rowcount = 0 and @@error = 0 insert into tablename ( idfield, field1, field2,... ) values ( 7, 'value one', 'another value',... ) This reduces it to one IO operations if it's an update, or two if an insert. MS Sql2008 introduces merge from the SQL:2003 standard: merge tablename as target using (values ('new value', 'different value')) as source (field1, field2) on target.idfield = 7 when matched then update set field1 = source.field1, field2 = source.field2,... when not matched then insert ( idfield, field1, field2,... ) values ( 7, source.field1, source.field2,... ) Now it's really just one IO operation, but awful code:-( | [
"mysql",
"sql-server",
"sql-server-2005"
] | 89 | 63 | 51,546 | 4 | 0 | 2008-08-01T22:13:34.100000 | 2008-08-15T12:50:22.350000 |
246 | 176,741 | Create a SQLite database based on an XSD Data Set | Does anybody know if there is a way to create an SQLite database based on an XSD DataSet? In the past, I've just used a basic SQLite manager, but I want to fuse things a bit more with my.NET development if possible. | I suspect in the general case this is hard; XML Schema allows for some quite bizarre type constructions. I'm not sure how you would do substitution groups, or extensions to restrictions of types for example. However it should be possible to knock something together quite quickly (especially mapping from the classes in System.Xml.Schema) that works for 90% of schemas (i.e. sequence and choice elements with a few simple data types). | Create a SQLite database based on an XSD Data Set Does anybody know if there is a way to create an SQLite database based on an XSD DataSet? In the past, I've just used a basic SQLite manager, but I want to fuse things a bit more with my.NET development if possible. | TITLE:
Create a SQLite database based on an XSD Data Set
QUESTION:
Does anybody know if there is a way to create an SQLite database based on an XSD DataSet? In the past, I've just used a basic SQLite manager, but I want to fuse things a bit more with my.NET development if possible.
ANSWER:
I suspect in the general case this is hard; XML Schema allows for some quite bizarre type constructions. I'm not sure how you would do substitution groups, or extensions to restrictions of types for example. However it should be possible to knock something together quite quickly (especially mapping from the classes in System.Xml.Schema) that works for 90% of schemas (i.e. sequence and choice elements with a few simple data types). | [
".net",
"database",
"sqlite"
] | 45 | 19 | 3,283 | 3 | 0 | 2008-08-01T22:34:42.853000 | 2008-10-06T23:58:50.823000 |
260 | 307 | Adding scripting functionality to .NET applications | I have a little game written in C#. It uses a database as back-end. It's a trading card game, and I wanted to implement the function of the cards as a script. What I mean is that I essentially have an interface, ICard, which a card class implements ( public class Card056: ICard ) and which contains a function that is called by the game. Now, to make the thing maintainable/moddable, I would like to have the class for each card as source code in the database and essentially compile it on first use. So when I have to add/change a card, I'll just add it to the database and tell my application to refresh, without needing any assembly deployment (especially since we would be talking about 1 assembly per card which means hundreds of assemblies). Is that possible? Register a class from a source file and then instantiate it, etc. ICard Cards[current] = new MyGame.CardLibrary.Card056(); Cards[current].OnEnterPlay(ref currentGameState); The language is C# but extra bonus if it's possible to write the script in any.NET language. | Oleg Shilo's C# Script solution (at The Code Project ) really is a great introduction to providing script abilities in your application. A different approach would be to consider a language that is specifically built for scripting, such as IronRuby, IronPython, or Lua. IronPython and IronRuby are both available today. For a guide to embedding IronPython read How to embed IronPython script support in your existing app in 10 easy steps. Lua is a scripting language commonly used in games. There is a Lua compiler for.NET, available from CodePlex -- http://www.codeplex.com/Nua That codebase is a great read if you want to learn about building a compiler in.NET. A different angle altogether is to try PowerShell. There are numerous examples of embedding PowerShell into an application -- here's a thorough project on the topic: Powershell Tunnel | Adding scripting functionality to .NET applications I have a little game written in C#. It uses a database as back-end. It's a trading card game, and I wanted to implement the function of the cards as a script. What I mean is that I essentially have an interface, ICard, which a card class implements ( public class Card056: ICard ) and which contains a function that is called by the game. Now, to make the thing maintainable/moddable, I would like to have the class for each card as source code in the database and essentially compile it on first use. So when I have to add/change a card, I'll just add it to the database and tell my application to refresh, without needing any assembly deployment (especially since we would be talking about 1 assembly per card which means hundreds of assemblies). Is that possible? Register a class from a source file and then instantiate it, etc. ICard Cards[current] = new MyGame.CardLibrary.Card056(); Cards[current].OnEnterPlay(ref currentGameState); The language is C# but extra bonus if it's possible to write the script in any.NET language. | TITLE:
Adding scripting functionality to .NET applications
QUESTION:
I have a little game written in C#. It uses a database as back-end. It's a trading card game, and I wanted to implement the function of the cards as a script. What I mean is that I essentially have an interface, ICard, which a card class implements ( public class Card056: ICard ) and which contains a function that is called by the game. Now, to make the thing maintainable/moddable, I would like to have the class for each card as source code in the database and essentially compile it on first use. So when I have to add/change a card, I'll just add it to the database and tell my application to refresh, without needing any assembly deployment (especially since we would be talking about 1 assembly per card which means hundreds of assemblies). Is that possible? Register a class from a source file and then instantiate it, etc. ICard Cards[current] = new MyGame.CardLibrary.Card056(); Cards[current].OnEnterPlay(ref currentGameState); The language is C# but extra bonus if it's possible to write the script in any.NET language.
ANSWER:
Oleg Shilo's C# Script solution (at The Code Project ) really is a great introduction to providing script abilities in your application. A different approach would be to consider a language that is specifically built for scripting, such as IronRuby, IronPython, or Lua. IronPython and IronRuby are both available today. For a guide to embedding IronPython read How to embed IronPython script support in your existing app in 10 easy steps. Lua is a scripting language commonly used in games. There is a Lua compiler for.NET, available from CodePlex -- http://www.codeplex.com/Nua That codebase is a great read if you want to learn about building a compiler in.NET. A different angle altogether is to try PowerShell. There are numerous examples of embedding PowerShell into an application -- here's a thorough project on the topic: Powershell Tunnel | [
"c#",
".net",
"scripting",
"compiler-construction"
] | 83 | 44 | 22,879 | 9 | 0 | 2008-08-01T23:22:08.983000 | 2008-08-02T01:49:46.220000 |
263 | 607 | GTK implementation of MessageBox | I have been trying to implement Win32's MessageBox using GTK. The app uses SDL/OpenGL, so this isn't a GTK app. I handle the initialization ( gtk_init ) sort of stuff inside the MessageBox function as follows: int MessageBox(HWND hwnd, const char* text, const char* caption, UINT type) { GtkWidget *window = NULL; GtkWidget *dialog = NULL;
gtk_init(>kArgc, >kArgv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(delete_event), NULL); g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(destroy), NULL); // gcallback calls gtk_main_quit() gtk_init_add((GtkFunction)gcallback, NULL);
if (type & MB_YESNO) { dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, text); } else { dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, text); }
gtk_window_set_title(GTK_WINDOW(dialog), caption); gint result = gtk_dialog_run(GTK_DIALOG(dialog));
gtk_main();
gtk_widget_destroy(dialog);
if (type & MB_YESNO) { switch (result) { default: case GTK_RESPONSE_DELETE_EVENT: case GTK_RESPONSE_NO: return IDNO; break; case GTK_RESPONSE_YES: return IDYES; break; } }
return IDOK; } Now, I am by no means an experienced GTK programmer, and I realize that I'm probably doing something horribly wrong. However, my problem is that the last dialog popped up with this function staying around until the process exits. Any ideas? | Hmm, ok. I'd suggest code like this, then: typedef struct { int type; int result; } DialogData;
static gboolean display_dialog(gpointer user_data) { DialogData *dialog_data = user_data; GtkWidget *dialog;
if (dialog_data->type & MB_YESNO) dialog = gtk_message_dialog_new(...); else dialog = gtk_message_dialog_new(...);
// Set title, etc.
dialog_data->result = gtk_dialog_run(...);
gtk_main_quit(); // Quits the main loop run in MessageBox()
return FALSE; }
int MessageBox(...) { DialogData dialog_data;
dialog_data.type = type;
gtk_idle_add(display_dialog, &dialog_data);
gtk_main();
// Do stuff based on dialog_data.result } The struct is required because you need to pass around a couple pieces of data. The gtk_idle_add() call adds a method to be run when the main loop is running and idle, and the FALSE return value from the display_dialog() call means that it's only run once. After we get the result from the dialog, we quit the main loop. That'll cause the gtk_main() in your main MessageBox() method to return, and you'll be able to access the result from there. | GTK implementation of MessageBox I have been trying to implement Win32's MessageBox using GTK. The app uses SDL/OpenGL, so this isn't a GTK app. I handle the initialization ( gtk_init ) sort of stuff inside the MessageBox function as follows: int MessageBox(HWND hwnd, const char* text, const char* caption, UINT type) { GtkWidget *window = NULL; GtkWidget *dialog = NULL;
gtk_init(>kArgc, >kArgv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(delete_event), NULL); g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(destroy), NULL); // gcallback calls gtk_main_quit() gtk_init_add((GtkFunction)gcallback, NULL);
if (type & MB_YESNO) { dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, text); } else { dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, text); }
gtk_window_set_title(GTK_WINDOW(dialog), caption); gint result = gtk_dialog_run(GTK_DIALOG(dialog));
gtk_main();
gtk_widget_destroy(dialog);
if (type & MB_YESNO) { switch (result) { default: case GTK_RESPONSE_DELETE_EVENT: case GTK_RESPONSE_NO: return IDNO; break; case GTK_RESPONSE_YES: return IDYES; break; } }
return IDOK; } Now, I am by no means an experienced GTK programmer, and I realize that I'm probably doing something horribly wrong. However, my problem is that the last dialog popped up with this function staying around until the process exits. Any ideas? | TITLE:
GTK implementation of MessageBox
QUESTION:
I have been trying to implement Win32's MessageBox using GTK. The app uses SDL/OpenGL, so this isn't a GTK app. I handle the initialization ( gtk_init ) sort of stuff inside the MessageBox function as follows: int MessageBox(HWND hwnd, const char* text, const char* caption, UINT type) { GtkWidget *window = NULL; GtkWidget *dialog = NULL;
gtk_init(>kArgc, >kArgv); window = gtk_window_new(GTK_WINDOW_TOPLEVEL); g_signal_connect(G_OBJECT(window), "delete_event", G_CALLBACK(delete_event), NULL); g_signal_connect(G_OBJECT(window), "destroy", G_CALLBACK(destroy), NULL); // gcallback calls gtk_main_quit() gtk_init_add((GtkFunction)gcallback, NULL);
if (type & MB_YESNO) { dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_QUESTION, GTK_BUTTONS_YES_NO, text); } else { dialog = gtk_message_dialog_new(GTK_WINDOW(window), GTK_DIALOG_DESTROY_WITH_PARENT, GTK_MESSAGE_INFO, GTK_BUTTONS_OK, text); }
gtk_window_set_title(GTK_WINDOW(dialog), caption); gint result = gtk_dialog_run(GTK_DIALOG(dialog));
gtk_main();
gtk_widget_destroy(dialog);
if (type & MB_YESNO) { switch (result) { default: case GTK_RESPONSE_DELETE_EVENT: case GTK_RESPONSE_NO: return IDNO; break; case GTK_RESPONSE_YES: return IDYES; break; } }
return IDOK; } Now, I am by no means an experienced GTK programmer, and I realize that I'm probably doing something horribly wrong. However, my problem is that the last dialog popped up with this function staying around until the process exits. Any ideas?
ANSWER:
Hmm, ok. I'd suggest code like this, then: typedef struct { int type; int result; } DialogData;
static gboolean display_dialog(gpointer user_data) { DialogData *dialog_data = user_data; GtkWidget *dialog;
if (dialog_data->type & MB_YESNO) dialog = gtk_message_dialog_new(...); else dialog = gtk_message_dialog_new(...);
// Set title, etc.
dialog_data->result = gtk_dialog_run(...);
gtk_main_quit(); // Quits the main loop run in MessageBox()
return FALSE; }
int MessageBox(...) { DialogData dialog_data;
dialog_data.type = type;
gtk_idle_add(display_dialog, &dialog_data);
gtk_main();
// Do stuff based on dialog_data.result } The struct is required because you need to pass around a couple pieces of data. The gtk_idle_add() call adds a method to be run when the main loop is running and idle, and the FALSE return value from the display_dialog() call means that it's only run once. After we get the result from the dialog, we quit the main loop. That'll cause the gtk_main() in your main MessageBox() method to return, and you'll be able to access the result from there. | [
"c",
"linux",
"gtk",
"x11"
] | 42 | 18 | 11,832 | 3 | 0 | 2008-08-01T23:27:24.993000 | 2008-08-03T02:30:05.907000 |
265 | 266 | Best Practice: Collaborative Environment, Bin Directory, SVN | What are the best practices for checking in BIN directories in a collaborative development environment using SVN? Should project level references be excluded from checkin? Is it easier to just add all bin directories? I develop a lot of DotNetNuke sites and it seems that in a multi-developer environment, it's always a huge task to get the environment setup correctly. The ultimate goal (of course) is to have a new developer checkout the trunk from SVN, restore the DNN database and have it all just 'work'... | Any assemblies that are expected to be in the GAC should stay in the GAC. This includes System.web.dll or any other 3rd party dll that you'll deploy to the GAC in production. This means a new developer would have to install these assemblies. All other 3rd party assemblies should be references through a relative path. My typical structure is: -Project --Project.sln --References ---StructureMap.dll ---NUnit.dll ---System.Web.Mvc.dll --Project.Web ---Project.Web.Proj ---Project.Web.Proj files --Project ---Project.Proj ---Project.Proj files Project.Web and Project reference the assemblies in the root/References folder relatively. These.dlls are checked into subversion. Aside from that, */bin */bin/* obj should be in your global ignore path. With this setup, all references to assemblies are either through the GAC (so should work across all computers), or relative to each project within your solution. | Best Practice: Collaborative Environment, Bin Directory, SVN What are the best practices for checking in BIN directories in a collaborative development environment using SVN? Should project level references be excluded from checkin? Is it easier to just add all bin directories? I develop a lot of DotNetNuke sites and it seems that in a multi-developer environment, it's always a huge task to get the environment setup correctly. The ultimate goal (of course) is to have a new developer checkout the trunk from SVN, restore the DNN database and have it all just 'work'... | TITLE:
Best Practice: Collaborative Environment, Bin Directory, SVN
QUESTION:
What are the best practices for checking in BIN directories in a collaborative development environment using SVN? Should project level references be excluded from checkin? Is it easier to just add all bin directories? I develop a lot of DotNetNuke sites and it seems that in a multi-developer environment, it's always a huge task to get the environment setup correctly. The ultimate goal (of course) is to have a new developer checkout the trunk from SVN, restore the DNN database and have it all just 'work'...
ANSWER:
Any assemblies that are expected to be in the GAC should stay in the GAC. This includes System.web.dll or any other 3rd party dll that you'll deploy to the GAC in production. This means a new developer would have to install these assemblies. All other 3rd party assemblies should be references through a relative path. My typical structure is: -Project --Project.sln --References ---StructureMap.dll ---NUnit.dll ---System.Web.Mvc.dll --Project.Web ---Project.Web.Proj ---Project.Web.Proj files --Project ---Project.Proj ---Project.Proj files Project.Web and Project reference the assemblies in the root/References folder relatively. These.dlls are checked into subversion. Aside from that, */bin */bin/* obj should be in your global ignore path. With this setup, all references to assemblies are either through the GAC (so should work across all computers), or relative to each project within your solution. | [
"svn",
"collaboration"
] | 38 | 19 | 3,296 | 5 | 0 | 2008-08-01T23:29:32.853000 | 2008-08-01T23:40:28.463000 |
289 | 298 | How do you sort a dictionary by value? | I often have to sort a dictionary (consisting of keys & values) by value. For example, I have a hash of words and respective frequencies that I want to order by frequency. There is a SortedList which is good for a single value (say frequency), that I want to map back to the word. SortedDictionary orders by key, not value. Some resort to a custom class, but is there a cleaner way? | Use: using System.Linq.Enumerable;... List > myList = aDictionary.ToList();
myList.Sort( delegate(KeyValuePair pair1, KeyValuePair pair2) { return pair1.Value.CompareTo(pair2.Value); } ); Since you're targeting.NET 2.0 or above, you can simplify this into lambda syntax -- it's equivalent, but shorter. If you're targeting.NET 2.0 you can only use this syntax if you're using the compiler from Visual Studio 2008 (or above). var myList = aDictionary.ToList();
myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value)); | How do you sort a dictionary by value? I often have to sort a dictionary (consisting of keys & values) by value. For example, I have a hash of words and respective frequencies that I want to order by frequency. There is a SortedList which is good for a single value (say frequency), that I want to map back to the word. SortedDictionary orders by key, not value. Some resort to a custom class, but is there a cleaner way? | TITLE:
How do you sort a dictionary by value?
QUESTION:
I often have to sort a dictionary (consisting of keys & values) by value. For example, I have a hash of words and respective frequencies that I want to order by frequency. There is a SortedList which is good for a single value (say frequency), that I want to map back to the word. SortedDictionary orders by key, not value. Some resort to a custom class, but is there a cleaner way?
ANSWER:
Use: using System.Linq.Enumerable;... List > myList = aDictionary.ToList();
myList.Sort( delegate(KeyValuePair pair1, KeyValuePair pair2) { return pair1.Value.CompareTo(pair2.Value); } ); Since you're targeting.NET 2.0 or above, you can simplify this into lambda syntax -- it's equivalent, but shorter. If you're targeting.NET 2.0 you can only use this syntax if you're using the compiler from Visual Studio 2008 (or above). var myList = aDictionary.ToList();
myList.Sort((pair1,pair2) => pair1.Value.CompareTo(pair2.Value)); | [
"c#",
".net",
"sorting",
"dictionary"
] | 955 | 572 | 825,359 | 21 | 0 | 2008-08-02T00:40:58.200000 | 2008-08-02T01:15:42.123000 |
308 | 360 | Is there a version control system for database structure changes? | I often run into the following problem. I work on some changes to a project that require new tables or columns in the database. I make the database modifications and continue my work. Usually, I remember to write down the changes so that they can be replicated on the live system. However, I don't always remember what I've changed and I don't always remember to write it down. So, I make a push to the live system and get a big, obvious error that there is no NewColumnX, ugh. Regardless of the fact that this may not be the best practice for this situation, is there a version control system for databases? I don't care about the specific database technology. I just want to know if one exists. If it happens to work with MS SQL Server, then great. | In Ruby on Rails, there's a concept of a migration -- a quick script to change the database. You generate a migration file, which has rules to increase the db version (such as adding a column) and rules to downgrade the version (such as removing a column). Each migration is numbered, and a table keeps track of your current db version. To migrate up, you run a command called "db:migrate" which looks at your version and applies the needed scripts. You can migrate down in a similar way. The migration scripts themselves are kept in a version control system -- whenever you change the database you check in a new script, and any developer can apply it to bring their local db to the latest version. | Is there a version control system for database structure changes? I often run into the following problem. I work on some changes to a project that require new tables or columns in the database. I make the database modifications and continue my work. Usually, I remember to write down the changes so that they can be replicated on the live system. However, I don't always remember what I've changed and I don't always remember to write it down. So, I make a push to the live system and get a big, obvious error that there is no NewColumnX, ugh. Regardless of the fact that this may not be the best practice for this situation, is there a version control system for databases? I don't care about the specific database technology. I just want to know if one exists. If it happens to work with MS SQL Server, then great. | TITLE:
Is there a version control system for database structure changes?
QUESTION:
I often run into the following problem. I work on some changes to a project that require new tables or columns in the database. I make the database modifications and continue my work. Usually, I remember to write down the changes so that they can be replicated on the live system. However, I don't always remember what I've changed and I don't always remember to write it down. So, I make a push to the live system and get a big, obvious error that there is no NewColumnX, ugh. Regardless of the fact that this may not be the best practice for this situation, is there a version control system for databases? I don't care about the specific database technology. I just want to know if one exists. If it happens to work with MS SQL Server, then great.
ANSWER:
In Ruby on Rails, there's a concept of a migration -- a quick script to change the database. You generate a migration file, which has rules to increase the db version (such as adding a column) and rules to downgrade the version (such as removing a column). Each migration is numbered, and a table keeps track of your current db version. To migrate up, you run a command called "db:migrate" which looks at your version and applies the needed scripts. You can migrate down in a similar way. The migration scripts themselves are kept in a version control system -- whenever you change the database you check in a new script, and any developer can apply it to bring their local db to the latest version. | [
"sql",
"database",
"oracle",
"version-control"
] | 133 | 66 | 38,383 | 22 | 0 | 2008-08-02T01:52:54.653000 | 2008-08-02T06:23:33.737000 |
328 | 7,488 | PHP Session Security | What are some guidelines for maintaining responsible session security with PHP? There's information all over the web and it's about time it all landed in one place! | There are a couple of things to do in order to keep your session secure: Use SSL when authenticating users or performing sensitive operations. Regenerate the session id whenever the security level changes (such as logging in). You can even regenerate the session id every request if you wish. Have sessions time out Don't use register globals Store authentication details on the server. That is, don't send details such as username in the cookie. Check the $_SERVER['HTTP_USER_AGENT']. This adds a small barrier to session hijacking. You can also check the IP address. But this causes problems for users that have changing IP address due to load balancing on multiple internet connections etc (which is the case in our environment here). Lock down access to the sessions on the file system or use custom session handling For sensitive operations consider requiring logged in users to provide their authenication details again | PHP Session Security What are some guidelines for maintaining responsible session security with PHP? There's information all over the web and it's about time it all landed in one place! | TITLE:
PHP Session Security
QUESTION:
What are some guidelines for maintaining responsible session security with PHP? There's information all over the web and it's about time it all landed in one place!
ANSWER:
There are a couple of things to do in order to keep your session secure: Use SSL when authenticating users or performing sensitive operations. Regenerate the session id whenever the security level changes (such as logging in). You can even regenerate the session id every request if you wish. Have sessions time out Don't use register globals Store authentication details on the server. That is, don't send details such as username in the cookie. Check the $_SERVER['HTTP_USER_AGENT']. This adds a small barrier to session hijacking. You can also check the IP address. But this causes problems for users that have changing IP address due to load balancing on multiple internet connections etc (which is the case in our environment here). Lock down access to the sessions on the file system or use custom session handling For sensitive operations consider requiring logged in users to provide their authenication details again | [
"security",
"php"
] | 125 | 88 | 85,917 | 13 | 0 | 2008-08-02T02:41:34.493000 | 2008-08-11T02:38:06.737000 |
330 | 332 | Should I use nested classes in this case? | I am working on a collection of classes used for video playback and recording. I have one main class which acts like the public interface, with methods like play(), stop(), pause(), record() etc... Then I have workhorse classes that do the video decoding and video encoding. I just learned about the existence of nested classes in C++, and I'm curious to know what programmers think about using them. I am a little wary and not really sure what the benefits/drawbacks are, but they seem (according to the book I'm reading) to be used in cases such as mine. The book suggests that in a scenario like mine, a good solution would be to nest the workhorse classes inside the interface class, so there are no separate files for classes the client is not meant to use and to avoid any possible naming conflicts. I don't know about these justifications. Nested classes are a new concept to me. Just want to see what programmers think about the issue. | I would be a bit reluctant to use nested classes here. What if you created an abstract base class for a "multimedia driver" to handle the back-end stuff (workhorse), and a separate class for the front-end work? The front-end class could take a pointer/reference to an implemented driver class (for the appropriate media type and situation) and perform the abstract operations on the workhorse structure. My philosophy would be to go ahead and make both structures accessible to the client in a polished way, just under the assumption they would be used in tandem. I would reference something like a QTextDocument in Qt. You provide a direct interface to the bare metal data handling, but pass the authority along to an object like a QTextEdit to do the manipulation. | Should I use nested classes in this case? I am working on a collection of classes used for video playback and recording. I have one main class which acts like the public interface, with methods like play(), stop(), pause(), record() etc... Then I have workhorse classes that do the video decoding and video encoding. I just learned about the existence of nested classes in C++, and I'm curious to know what programmers think about using them. I am a little wary and not really sure what the benefits/drawbacks are, but they seem (according to the book I'm reading) to be used in cases such as mine. The book suggests that in a scenario like mine, a good solution would be to nest the workhorse classes inside the interface class, so there are no separate files for classes the client is not meant to use and to avoid any possible naming conflicts. I don't know about these justifications. Nested classes are a new concept to me. Just want to see what programmers think about the issue. | TITLE:
Should I use nested classes in this case?
QUESTION:
I am working on a collection of classes used for video playback and recording. I have one main class which acts like the public interface, with methods like play(), stop(), pause(), record() etc... Then I have workhorse classes that do the video decoding and video encoding. I just learned about the existence of nested classes in C++, and I'm curious to know what programmers think about using them. I am a little wary and not really sure what the benefits/drawbacks are, but they seem (according to the book I'm reading) to be used in cases such as mine. The book suggests that in a scenario like mine, a good solution would be to nest the workhorse classes inside the interface class, so there are no separate files for classes the client is not meant to use and to avoid any possible naming conflicts. I don't know about these justifications. Nested classes are a new concept to me. Just want to see what programmers think about the issue.
ANSWER:
I would be a bit reluctant to use nested classes here. What if you created an abstract base class for a "multimedia driver" to handle the back-end stuff (workhorse), and a separate class for the front-end work? The front-end class could take a pointer/reference to an implemented driver class (for the appropriate media type and situation) and perform the abstract operations on the workhorse structure. My philosophy would be to go ahead and make both structures accessible to the client in a polished way, just under the assumption they would be used in tandem. I would reference something like a QTextDocument in Qt. You provide a direct interface to the bare metal data handling, but pass the authority along to an object like a QTextEdit to do the manipulation. | [
"c++",
"class",
"oop",
"inner-classes"
] | 58 | 30 | 5,019 | 10 | 0 | 2008-08-02T02:51:36.470000 | 2008-08-02T03:00:24.613000 |
336 | 339 | When to use unsigned values over signed ones? | When is it appropriate to use an unsigned variable over a signed one? What about in a for loop? I hear a lot of opinions about this and I wanted to see if there was anything resembling a consensus. for (unsigned int i = 0; i < someThing.length(); i++) { SomeThing var = someThing.at(i); // You get the idea. } I know Java doesn't have unsigned values, and that must have been a concious decision on Sun Microsystems ' part. | I was glad to find a good conversation on this subject, as I hadn't really given it much thought before. In summary, signed is a good general choice - even when you're dead sure all the numbers are positive - if you're going to do arithmetic on the variable (like in a typical for loop case). unsigned starts to make more sense when: You're going to do bitwise things like masks, or You're desperate to to take advantage of the sign bit for that extra positive range. Personally, I like signed because I don't trust myself to stay consistent and avoid mixing the two types (like the article warns against). | When to use unsigned values over signed ones? When is it appropriate to use an unsigned variable over a signed one? What about in a for loop? I hear a lot of opinions about this and I wanted to see if there was anything resembling a consensus. for (unsigned int i = 0; i < someThing.length(); i++) { SomeThing var = someThing.at(i); // You get the idea. } I know Java doesn't have unsigned values, and that must have been a concious decision on Sun Microsystems ' part. | TITLE:
When to use unsigned values over signed ones?
QUESTION:
When is it appropriate to use an unsigned variable over a signed one? What about in a for loop? I hear a lot of opinions about this and I wanted to see if there was anything resembling a consensus. for (unsigned int i = 0; i < someThing.length(); i++) { SomeThing var = someThing.at(i); // You get the idea. } I know Java doesn't have unsigned values, and that must have been a concious decision on Sun Microsystems ' part.
ANSWER:
I was glad to find a good conversation on this subject, as I hadn't really given it much thought before. In summary, signed is a good general choice - even when you're dead sure all the numbers are positive - if you're going to do arithmetic on the variable (like in a typical for loop case). unsigned starts to make more sense when: You're going to do bitwise things like masks, or You're desperate to to take advantage of the sign bit for that extra positive range. Personally, I like signed because I don't trust myself to stay consistent and avoid mixing the two types (like the article warns against). | [
"language-agnostic",
"types"
] | 93 | 82 | 29,448 | 5 | 0 | 2008-08-02T03:34:44.763000 | 2008-08-02T03:49:21.987000 |
337 | 342 | XML Processing in Python | I am about to build a piece of a project that will need to construct and post an XML document to a web service and I'd like to do it in Python, as a means to expand my skills in it. Unfortunately, whilst I know the XML model fairly well in.NET, I'm uncertain what the pros and cons are of the XML models in Python. Anyone have experience doing XML processing in Python? Where would you suggest I start? The XML files I'll be building will be fairly simple. | Personally, I've played with several of the built-in options on an XML-heavy project and have settled on pulldom as the best choice for less complex documents. Especially for small simple stuff, I like the event-driven theory of parsing rather than setting up a whole slew of callbacks for a relatively simple structure. Here is a good quick discussion of how to use the API. What I like: you can handle the parsing in a for loop rather than using callbacks. You also delay full parsing (the "pull" part) and only get additional detail when you call expandNode(). This satisfies my general requirement for "responsible" efficiency without sacrificing ease of use and simplicity. | XML Processing in Python I am about to build a piece of a project that will need to construct and post an XML document to a web service and I'd like to do it in Python, as a means to expand my skills in it. Unfortunately, whilst I know the XML model fairly well in.NET, I'm uncertain what the pros and cons are of the XML models in Python. Anyone have experience doing XML processing in Python? Where would you suggest I start? The XML files I'll be building will be fairly simple. | TITLE:
XML Processing in Python
QUESTION:
I am about to build a piece of a project that will need to construct and post an XML document to a web service and I'd like to do it in Python, as a means to expand my skills in it. Unfortunately, whilst I know the XML model fairly well in.NET, I'm uncertain what the pros and cons are of the XML models in Python. Anyone have experience doing XML processing in Python? Where would you suggest I start? The XML files I'll be building will be fairly simple.
ANSWER:
Personally, I've played with several of the built-in options on an XML-heavy project and have settled on pulldom as the best choice for less complex documents. Especially for small simple stuff, I like the event-driven theory of parsing rather than setting up a whole slew of callbacks for a relatively simple structure. Here is a good quick discussion of how to use the API. What I like: you can handle the parsing in a for loop rather than using callbacks. You also delay full parsing (the "pull" part) and only get additional detail when you call expandNode(). This satisfies my general requirement for "responsible" efficiency without sacrificing ease of use and simplicity. | [
"python",
"xml"
] | 82 | 36 | 10,595 | 12 | 0 | 2008-08-02T03:35:55.697000 | 2008-08-02T04:01:34.600000 |
361 | 362 | Generate list of all possible permutations of a string | How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters. Any language would work, but it should be portable. | There are several ways to do this. Common methods use recursion, memoization, or dynamic programming. The basic idea is that you produce a list of all strings of length 1, then in each iteration, for all strings produced in the last iteration, add that string concatenated with each character in the string individually. (the variable index in the code below keeps track of the start of the last and the next iteration) Some pseudocode: list = originalString.split('') index = (0,0) list = [""] for iteration n in 1 to y: index = (index[1], len(list)) for string s in list.subset(index[0] to end): for character c in originalString: list.add(s + c) you'd then need to remove all strings less than x in length, they'll be the first (x-1) * len(originalString) entries in the list. | Generate list of all possible permutations of a string How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters. Any language would work, but it should be portable. | TITLE:
Generate list of all possible permutations of a string
QUESTION:
How would I go about generating a list of all possible permutations of a string between x and y characters in length, containing a variable list of characters. Any language would work, but it should be portable.
ANSWER:
There are several ways to do this. Common methods use recursion, memoization, or dynamic programming. The basic idea is that you produce a list of all strings of length 1, then in each iteration, for all strings produced in the last iteration, add that string concatenated with each character in the string individually. (the variable index in the code below keeps track of the start of the last and the next iteration) Some pseudocode: list = originalString.split('') index = (0,0) list = [""] for iteration n in 1 to y: index = (index[1], len(list)) for string s in list.subset(index[0] to end): for character c in originalString: list.add(s + c) you'd then need to remove all strings less than x in length, they'll be the first (x-1) * len(originalString) entries in the list. | [
"string",
"language-agnostic",
"cross-platform",
"permutation",
"combinatorics"
] | 166 | 69 | 214,067 | 36 | 0 | 2008-08-02T06:57:57.957000 | 2008-08-02T07:48:07.607000 |
371 | 396 | How do you make sure email you send programmatically is not automatically marked as spam? | This is a tricky one and I've always relied on techniques, such as permission-based emails (i.e. only sending to people you have permission to send to) and not using blatantly spamish terminology. Of late, some of the emails I send out programmatically have started being shuffled into people's spam folder automatically and I'm wondering what I can do about it. This is despite the fact that these particular emails are not ones that humans would mark as spam, specifically, they are emails that contain license keys that people have paid good money for, so I don't think they're going to consider them spam I figure this is a big topic in which I am essentially an ignorant simpleton. | Use email authentication methods, such as SPF, and DKIM to prove that your emails and your domain name belong together, and to prevent spoofing of your domain name. The SPF website includes a wizard to generate the DNS information for your site. Check your reverse DNS to make sure the IP address of your mail server points to the domain name that you use for sending mail. Make sure that the IP-address that you're using is not on a blacklist Make sure that the reply-to address is a valid, existing address. Use the full, real name of the addressee in the To field, not just the email-address (e.g. "John Smith" ). Monitor your abuse accounts, such as abuse@yourdomain.example and postmaster@yourdomain.example. That means - make sure that these accounts exist, read what's sent to them, and act on complaints. Finally, make it really easy to unsubscribe. Otherwise, your users will unsubscribe by pressing the spam button, and that will affect your reputation. That said, getting Hotmail to accept your emails remains a black art. | How do you make sure email you send programmatically is not automatically marked as spam? This is a tricky one and I've always relied on techniques, such as permission-based emails (i.e. only sending to people you have permission to send to) and not using blatantly spamish terminology. Of late, some of the emails I send out programmatically have started being shuffled into people's spam folder automatically and I'm wondering what I can do about it. This is despite the fact that these particular emails are not ones that humans would mark as spam, specifically, they are emails that contain license keys that people have paid good money for, so I don't think they're going to consider them spam I figure this is a big topic in which I am essentially an ignorant simpleton. | TITLE:
How do you make sure email you send programmatically is not automatically marked as spam?
QUESTION:
This is a tricky one and I've always relied on techniques, such as permission-based emails (i.e. only sending to people you have permission to send to) and not using blatantly spamish terminology. Of late, some of the emails I send out programmatically have started being shuffled into people's spam folder automatically and I'm wondering what I can do about it. This is despite the fact that these particular emails are not ones that humans would mark as spam, specifically, they are emails that contain license keys that people have paid good money for, so I don't think they're going to consider them spam I figure this is a big topic in which I am essentially an ignorant simpleton.
ANSWER:
Use email authentication methods, such as SPF, and DKIM to prove that your emails and your domain name belong together, and to prevent spoofing of your domain name. The SPF website includes a wizard to generate the DNS information for your site. Check your reverse DNS to make sure the IP address of your mail server points to the domain name that you use for sending mail. Make sure that the IP-address that you're using is not on a blacklist Make sure that the reply-to address is a valid, existing address. Use the full, real name of the addressee in the To field, not just the email-address (e.g. "John Smith" ). Monitor your abuse accounts, such as abuse@yourdomain.example and postmaster@yourdomain.example. That means - make sure that these accounts exist, read what's sent to them, and act on complaints. Finally, make it really easy to unsubscribe. Otherwise, your users will unsubscribe by pressing the spam button, and that will affect your reputation. That said, getting Hotmail to accept your emails remains a black art. | [
"email",
"email-spam"
] | 464 | 354 | 119,005 | 24 | 0 | 2008-08-02T08:19:18.260000 | 2008-08-02T10:21:54.300000 |
382 | 384 | What is the meaning of the type safety warning in certain Java generics casts? | What is the meaning of the Java warning? Type safety: The cast from Object to List is actually checking against the erased type List I get this warning when I try to cast an Object to a type with generic information, such as in the following code: Object object = getMyList(); List list = (List ) object; | This warning is there because Java is not actually storing type information at run-time in an object that uses generics. Thus, if object is actually a List, there will be no ClassCastException at run-time except until an item is accessed from the list that doesn't match the generic type defined in the variable. This can cause further complications if items are added to the list, with this incorrect generic type information. Any code still holding a reference to the list but with the correct generic type information will now have an inconsistent list. To remove the warning, try: List list = (List ) object; However, note that you will not be able to use certain methods such as add because the compiler doesn't know if you are trying to add an object of incorrect type. The above will work in a lot of situations, but if you have to use add, or some similarly restricted method, you will just have to suffer the yellow underline in Eclipse (or a SuppressWarning annotation). | What is the meaning of the type safety warning in certain Java generics casts? What is the meaning of the Java warning? Type safety: The cast from Object to List is actually checking against the erased type List I get this warning when I try to cast an Object to a type with generic information, such as in the following code: Object object = getMyList(); List list = (List ) object; | TITLE:
What is the meaning of the type safety warning in certain Java generics casts?
QUESTION:
What is the meaning of the Java warning? Type safety: The cast from Object to List is actually checking against the erased type List I get this warning when I try to cast an Object to a type with generic information, such as in the following code: Object object = getMyList(); List list = (List ) object;
ANSWER:
This warning is there because Java is not actually storing type information at run-time in an object that uses generics. Thus, if object is actually a List, there will be no ClassCastException at run-time except until an item is accessed from the list that doesn't match the generic type defined in the variable. This can cause further complications if items are added to the list, with this incorrect generic type information. Any code still holding a reference to the list but with the correct generic type information will now have an inconsistent list. To remove the warning, try: List list = (List ) object; However, note that you will not be able to use certain methods such as add because the compiler doesn't know if you are trying to add an object of incorrect type. The above will work in a lot of situations, but if you have to use add, or some similarly restricted method, you will just have to suffer the yellow underline in Eclipse (or a SuppressWarning annotation). | [
"java",
"generics",
"warnings",
"casting",
"type-safety"
] | 81 | 53 | 10,291 | 1 | 0 | 2008-08-02T08:58:27.540000 | 2008-08-02T08:58:48.430000 |
End of preview. Expand in Data Studio
StackOverflow QA Dataset for RAG
Description
This dataset contains question–answer pairs extracted from the public StackOverflow data dump.
Each example consists of a question with its accepted answer, along with metadata such as tags, scores, and engagement statistics. The dataset is designed for retrieval-augmented generation (RAG), semantic search, and information retrieval tasks.
Dataset Structure
Each row is a JSON object with the following fields:
question_id— unique ID of the questionanswer_id— unique ID of the accepted answertitle— question titlequestion_body— cleaned text of the questionanswer_body— cleaned text of the accepted answerquestion_text— title + question bodycombined_text— title + question + answer (used for retrieval)tags— list of StackOverflow tagsquestion_score— score of the questionanswer_score— score of the answerview_count— number of viewsanswer_count— number of answersfavorite_count— number of favoritesquestion_creation_date— timestampanswer_creation_date— timestamp
- Downloads last month
- -