qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
12,611
<p>I have to create something similiar to Google Calendar, so I created an events table that contains all the events for a user.</p> <p>The hard part is handling re-occurring events, the row in the events table has an event_type field that tells you what kind of event it is, since an event can be for a single date only, OR a re-occuring event every x days.</p> <p><strong>The main design challenge is handling re-occurring events.</strong></p> <p>When a user views the calendar, using the month's view, how can I display all the events for the given month? The query is going to be tricky, so I thought it would be easier to create another table and create a row for each and every event, including the re-occuring events.</p> <p>What do you guys think?</p>
[ { "answer_id": 12993, "author": "eplawless", "author_id": 1370, "author_profile": "https://Stackoverflow.com/users/1370", "pm_score": 2, "selected": false, "text": "SELECT * FROM events WHERE id = 3 OR parentid = 3\n SELECT * FROM events WHERE startdate >= '2008-08-01' AND enddate <= '2008-08-31'\n" }, { "answer_id": 23653, "author": "Matt S.", "author_id": 1458, "author_profile": "https://Stackoverflow.com/users/1458", "pm_score": 3, "selected": false, "text": "(:month + (:year * 12)) - (MONTH(occursOn) + (YEAR(occursOn) * 12))\n MOD(:month + (:year * 12)) - (MONTH(occursOn) + (YEAR(occursOn) * 12), repeatIncrement) = 0\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12611", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
12,613
<p>I've been using Emacs's sql interactive mode to talk to the MySQL db server and gotten to enjoy it. A developer has set up another db on a new non-default port number but I don't know how to access it using sql-mysql.</p> <p>How do I specify a port number when I'm trying to connect to a database?</p> <p>It would be even better if Emacs can prompt me for a port number and just use the default if I don't specify. Any chances of that?</p>
[ { "answer_id": 12628, "author": "Marcel Levy", "author_id": 676, "author_profile": "https://Stackoverflow.com/users/676", "pm_score": 3, "selected": false, "text": "(setq sql-mysql-options (list \"-P <port number>\"))\n" }, { "answer_id": 12658, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 3, "selected": false, "text": "M-x customize-group\nSQL\n Mysql Options:\n (custom-set-variables\n '(sql-mysql-options (quote (\"-P ???\"))))\n" }, { "answer_id": 12538719, "author": "Cristian", "author_id": 680, "author_profile": "https://Stackoverflow.com/users/680", "pm_score": 5, "selected": true, "text": "(setq sql-mysql-login-params (append sql-mysql-login-params '(port)))\n sql-port (setq sql-port 3306) ;; default MySQL port\n sql-*-login-params sql-port" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/680/" ]
12,633
<p>I'm trying to parse an INI file using C++. Any tips on what is the best way to achieve this? Should I use the Windows API tools for INI file processing (with which I am totally unfamiliar), an open-source solution or attempt to parse it manually?</p>
[ { "answer_id": 1964505, "author": "Mike", "author_id": 124476, "author_profile": "https://Stackoverflow.com/users/124476", "pm_score": 3, "selected": false, "text": "#include \"SimpleIni\\SimpleIni.h\" \nCSimpleIniA ini;\nini.SetUnicode();\nini.LoadFile(FileName);\nconst char * pVal = ini.GetValue(section, entry, DefaultStr);\n" }, { "answer_id": 4343216, "author": "Dat Chu", "author_id": 82159, "author_profile": "https://Stackoverflow.com/users/82159", "pm_score": 4, "selected": false, "text": "QSettings my_settings(\"filename.ini\", QSettings::IniFormat);\n my_settings.value(\"GroupName/ValueName\", <<DEFAULT_VAL>>).toInt()\n" }, { "answer_id": 18209017, "author": "nimcap", "author_id": 87987, "author_profile": "https://Stackoverflow.com/users/87987", "pm_score": 3, "selected": false, "text": "#include \"INIReader.h\" \n\nINIReader reader(\"test.ini\");\n\nstd::cout << \"version=\"\n << reader.GetInteger(\"protocol\", \"version\", -1) << \", name=\"\n << reader.Get(\"user\", \"name\", \"UNKNOWN\") << \", active=\"\n << reader.GetBoolean(\"user\", \"active\", true) << \"\\n\";\n" }, { "answer_id": 48179083, "author": "12oclocker", "author_id": 8936790, "author_profile": "https://Stackoverflow.com/users/8936790", "pm_score": 2, "selected": false, "text": "// -----note: no escape is nessesary for inner quotes or ticks-----\n// -----------------------------example----------------------------\n// [Entry2]\n// Alignment = 1\n// LightLvl=128\n// Library = 5555\n// StrValA = Inner \"quoted\" or 'quoted' strings are ok to use\n// StrValB = \"This a \"quoted\" or 'quoted' String Value\"\n// StrValC = 'This a \"tick\" or 'tick' String Value'\n// StrValD = \"Missing quote at end will still work\n// StrValE = This is another \"quote\" example\n// StrValF = \" Spaces inside the quote are preserved \"\n// StrValG = This works too and spaces are trimmed away\n// StrValH =\n// ----------------------------------------------------------------\n//12oClocker super lean and mean INI file parser (with section support)\n//set section to 0 to disable section support\n//returns TRUE if we were able to extract a string into ret value\n//NextSection is a char* pointer, will be set to zero if no next section is found\n//will be set to pointer of next section if it was found.\n//use it like this... char* NextSection = 0; GrabIniValue(X,X,X,X,X,&NextSection);\n//buf is data to parse, ret is the user supplied return buffer\nBOOL GrabIniValue(char* buf, const char* section, const char* valname, char* ret, int retbuflen, char** NextSection)\n{\n if(!buf){*ret=0; return FALSE;}\n\n char* s = buf; //search starts at \"s\" pointer\n char* e = 0; //end of section pointer\n\n //find section\n if(section)\n {\n int L = strlen(section);\n SearchAgain1:\n s = strstr(s,section); if(!s){*ret=0; return FALSE;} //find section\n if(s > buf && (*(s-1))!='\\n'){s+=L; goto SearchAgain1;} //section must be at begining of a line!\n s+=L; //found section, skip past section name\n while(*s!='\\n'){s++;} s++; //spin until next line, s is now begining of section data\n e = strstr(s,\"\\n[\"); //find begining of next section or end of file\n if(e){*e=0;} //if we found begining of next section, null the \\n so we don't search past section\n if(NextSection) //user passed in a NextSection pointer\n { if(e){*NextSection=(e+1);}else{*NextSection=0;} } //set pointer to next section\n }\n\n //restore char at end of section, ret=empty_string, return FALSE\n #define RESTORE_E if(e){*e='\\n';}\n #define SAFE_RETURN RESTORE_E; (*ret)=0; return FALSE\n\n //find valname\n int L = strlen(valname);\n SearchAgain2:\n s = strstr(s,valname); if(!s){SAFE_RETURN;} //find valname\n if(s > buf && (*(s-1))!='\\n'){s+=L; goto SearchAgain2;} //valname must be at begining of a line!\n s+=L; //found valname match, skip past it\n while(*s==' ' || *s == '\\t'){s++;} //skip spaces and tabs\n if(!(*s)){SAFE_RETURN;} //if NULL encounted do safe return\n if(*s != '='){goto SearchAgain2;} //no equal sign found after valname, search again\n s++; //skip past the equal sign\n while(*s==' ' || *s=='\\t'){s++;} //skip spaces and tabs\n while(*s=='\\\"' || *s=='\\''){s++;} //skip past quotes and ticks\n if(!(*s)){SAFE_RETURN;} //if NULL encounted do safe return\n char* E = s; //s is now the begining of the valname data\n while(*E!='\\r' && *E!='\\n' && *E!=0){E++;} E--; //find end of line or end of string, then backup 1 char\n while(E > s && (*E==' ' || *E=='\\t')){E--;} //move backwards past spaces and tabs\n while(E > s && (*E=='\\\"' || *E=='\\'')){E--;} //move backwards past quotes and ticks\n L = E-s+1; //length of string to extract NOT including NULL\n if(L<1 || L+1 > retbuflen){SAFE_RETURN;} //empty string or buffer size too small\n strncpy(ret,s,L); //copy the string\n ret[L]=0; //null last char on return buffer\n RESTORE_E;\n return TRUE;\n\n #undef RESTORE_E\n #undef SAFE_RETURN\n}\n char sFileData[] = \"[MySection]\\r\\n\"\n\"MyValue1 = 123\\r\\n\"\n\"MyValue2 = 456\\r\\n\"\n\"MyValue3 = 789\\r\\n\"\n\"\\r\\n\"\n\"[MySection]\\r\\n\"\n\"MyValue1 = Hello1\\r\\n\"\n\"MyValue2 = Hello2\\r\\n\"\n\"MyValue3 = Hello3\\r\\n\"\n\"\\r\\n\";\nchar str[256];\nchar* sSec = sFileData;\nchar secName[] = \"[MySection]\"; //we support sections with same name\nwhile(sSec)//while we have a valid sNextSec\n{\n //print values of the sections\n char* next=0;//in case we dont have any sucessful grabs\n if(GrabIniValue(sSec,secName,\"MyValue1\",str,sizeof(str),&next)) { printf(\"MyValue1 = [%s]\\n\",str); }\n if(GrabIniValue(sSec,secName,\"MyValue2\",str,sizeof(str),0)) { printf(\"MyValue2 = [%s]\\n\",str); }\n if(GrabIniValue(sSec,secName,\"MyValue3\",str,sizeof(str),0)) { printf(\"MyValue3 = [%s]\\n\",str); }\n printf(\"\\n\");\n sSec = next; //parse next section, next will be null if no more sections to parse\n}\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1467/" ]
12,638
<p>So basically I'm building an app for my company and it NEEDS to be built using MS Access and it needs to be built on SQL Server.</p> <p>I've drawn up most of the plans but am having a hard time figuring out a way to handle the auditing system.</p> <p>Since it is being used internally only and you won't even be able to touch the db from outside the building we are not using a login system as the program will only be used once a user has already logged in to our internal network via Active Directory. Knowing this, we're using <a href="https://stackoverflow.com/questions/9052/is-there-a-way-for-ms-access-to-grab-the-current-active-directory-user">a system to detect automatically the name of the Active Directory user</a> and with their permissions in one of the DB tables, deciding what they can or cannot do.</p> <p>So the actual audit table will have 3 columns (this design may change but for this question it doesn't matter); who (Active Directory User), when (time of addition/deletion/edit), what (what was changed)</p> <p>My question is how should I be handling this. Ideally I know I should be using a trigger so that it is impossible for the database to be updated without an audit being logged, however I don't know how I could grab the Active Directory User that way. An alternate would be to code it directly into the Access source so that whenever something changes I run an INSERT statement. Obviously that is flawed because if something happens to Access or the database is touched by something else then it will not log the audit.</p> <p>Any advice, examples or articles that may help me would be greatly appreciated!</p>
[ { "answer_id": 12650, "author": "Jay Mooney", "author_id": 733, "author_profile": "https://Stackoverflow.com/users/733", "pm_score": 2, "selected": false, "text": "\nselect user_name(),suser_sname()\n" }, { "answer_id": 12653, "author": "SQLMenace", "author_id": 740, "author_profile": "https://Stackoverflow.com/users/740", "pm_score": 0, "selected": false, "text": "select user name(),suser sname()\n" }, { "answer_id": 12724, "author": "Andrew G. Johnson", "author_id": 428190, "author_profile": "https://Stackoverflow.com/users/428190", "pm_score": 1, "selected": false, "text": "CREATE TRIGGER testtrigger1\nON testdatatable\nAFTER update\nAS \nBEGIN\n INSERT INTO testtable (datecol,usercol1,usercol2) VALUES (getdate(),user_name(),suser_sname());\nEND\nGO\n" }, { "answer_id": 67920, "author": "Mark Plumpton", "author_id": 10422, "author_profile": "https://Stackoverflow.com/users/10422", "pm_score": 1, "selected": false, "text": "CREATE FUNCTION dbo.UserName() RETURNS varchar(50)\nAS\n BEGIN\n RETURN (SELECT nt_username FROM master.dbo.sysprocesses WHERE spid = @@SPID)\n END\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12638", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428190/" ]
12,642
<p>I am trying to upload a file or stream of data to our web server and I cant find a decent way of doing this. I have tried both <code>WebClient</code> and <code>WebRequest</code> both have their problems. </p> <p><strong>WebClient</strong><br> Nice and easy but you do not get any notification that the asynchronous upload has completed, and the <code>UploadProgressChanged</code> event doesnt get called back with anything useful. The alternative is to convert your binary data to a string and use <code>UploadStringASync</code> because then at least you get a <code>UploadStringCompleted</code>, problem is you need a lot of ram for big files as its encoding all the data and uploading it in one go.</p> <p><strong>HttpWebRequest</strong><br> Bit more complicated but still does what is needed, problem I am getting is that even though it is called on a background thread (supposedly), it still seems to be blocking my UI and the whole browser until the upload has completed which doesnt seem quite right.</p> <p>Normal .net does have some appropriate <code>WebClient</code> methods for <a href="http://msdn.microsoft.com/en-us/library/system.net.webclient.onuploaddatacompleted.aspx" rel="nofollow noreferrer">OnUploadDataCompleted</a> and progress but these arent available in Silverlight .net ... big omission I think!</p> <p>Does anyone have any solutions, I need to upload multiple binary files preferrably with a progress but I need to perform some actions when the files have completed their upload.</p> <p>Look forward to some help with this.</p>
[ { "answer_id": 12691, "author": "Brian Leahy", "author_id": 580, "author_profile": "https://Stackoverflow.com/users/580", "pm_score": 2, "selected": true, "text": " public void DoIt(){\nthis.IsUploading = True; \n\n WebRequest postRequest = WebRequest.Create(new Uri(ServiceURL));\n\n postRequest.BeginGetRequestStream(new AsyncCallback(RequestOpened), postRequest);\n }\n\nprivate void RequestOpened(IAsyncResult result){\n WebRequest req = result.AsyncState as WebRequest;\n req.BeginGetResponse(new AsyncCallback(GetResponse), req);\n }\n\n private void GetResponse(IAsyncResult result)\n {\n WebRequest req = result.AsyncState as WebRequest;\n string serverresult = string.Empty;\n WebResponse postResponse = req.EndGetResponse(result);\n\n StreamReader responseReader = new StreamReader(postResponse.GetResponseStream());\n\nthis.IsUploading= False;\n}\n\n private Bool_IsUploading;\n public Bool IsUploading\n {\n get { return _IsUploading; }\n private set\n {\n\n _IsUploading = value;\n\n OnPropertyChanged(\"IsUploading\");\n }\n }\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1478/" ]
12,647
<p>Is there a simple way in Perl that will allow me to determine if a given variable is numeric? Something along the lines of:</p> <pre><code>if (is_number($x)) { ... } </code></pre> <p>would be ideal. A technique that won't throw warnings when the <code>-w</code> switch is being used is certainly preferred.</p>
[ { "answer_id": 12654, "author": "farmerchris", "author_id": 1317, "author_profile": "https://Stackoverflow.com/users/1317", "pm_score": 2, "selected": false, "text": "sub isnumber \n{\n shift =~ /^-?\\d+\\.?\\d*$/;\n}\n" }, { "answer_id": 12667, "author": "andrewrk", "author_id": 432, "author_profile": "https://Stackoverflow.com/users/432", "pm_score": 4, "selected": false, "text": "sub is_integer {\n defined $_[0] && $_[0] =~ /^[+-]?\\d+$/;\n}\n\nsub is_float {\n defined $_[0] && $_[0] =~ /^[+-]?\\d+(\\.\\d+)?$/;\n}\n" }, { "answer_id": 12736, "author": "Jon Ericson", "author_id": 1438, "author_profile": "https://Stackoverflow.com/users/1438", "pm_score": 2, "selected": false, "text": "sub is_number{\n my $n = shift;\n my $ret = 1;\n $SIG{\"__WARN__\"} = sub {$ret = 0};\n eval { my $x = $n + 1 };\n return $ret\n}\n {\n no warnings \"numeric\"; # Ignore \"isn't numeric\" warning\n ... # Use a variable that might not be numeric\n}\n" }, { "answer_id": 12742, "author": "naumcho", "author_id": 779, "author_profile": "https://Stackoverflow.com/users/779", "pm_score": 5, "selected": false, "text": "use Regexp::Common;\nif ($var =~ /$RE{num}{real}/) { print q{a number}; }\n" }, { "answer_id": 28589, "author": "nohat", "author_id": 3101, "author_profile": "https://Stackoverflow.com/users/3101", "pm_score": 8, "selected": true, "text": "Scalar::Util::looks_like_number() #!/usr/bin/perl\n\nuse warnings;\nuse strict;\n\nuse Scalar::Util qw(looks_like_number);\n\nmy @exprs = qw(1 5.25 0.001 1.3e8 foo bar 1dd inf infinity);\n\nforeach my $expr (@exprs) {\n print \"$expr is\", looks_like_number($expr) ? '' : ' not', \" a number\\n\";\n}\n 1 is a number\n5.25 is a number\n0.001 is a number\n1.3e8 is a number\nfoo is not a number\nbar is not a number\n1dd is not a number\ninf is a number\ninfinity is a number\n looks_like_number" }, { "answer_id": 3806159, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 5, "selected": false, "text": "$x = \"123\"; 0+$x $x if ( length( do { no warnings \"numeric\"; $x & \"\" } ) ) {\n print \"$x is numeric\\n\";\n}\n & &. if ( length( do { no if $] >= 5.022, \"feature\", \"bitwise\"; no warnings \"numeric\"; $x & \"\" } ) ) {\n print \"$x is numeric\\n\";\n}\n use 5.028;" }, { "answer_id": 4412308, "author": "fringd", "author_id": 284511, "author_profile": "https://Stackoverflow.com/users/284511", "pm_score": 2, "selected": false, "text": "use Try::Tiny;\n\nsub is_numeric {\n my ($x) = @_;\n my $numeric = 1;\n try {\n use warnings FATAL => qw/numeric/;\n 0 + $x;\n }\n catch {\n $numeric = 0;\n };\n return $numeric;\n}\n" }, { "answer_id": 12937508, "author": "Peter Vanroose", "author_id": 1753621, "author_profile": "https://Stackoverflow.com/users/1753621", "pm_score": 3, "selected": false, "text": "$x if ($x eq $x+0) { .... }\n $x $x" }, { "answer_id": 16861447, "author": "CDC", "author_id": 2441129, "author_profile": "https://Stackoverflow.com/users/2441129", "pm_score": 1, "selected": false, "text": "If (($x !~ /\\D/) && ($x ne \"\")) { ... }\n" }, { "answer_id": 32889849, "author": "Swadhikar", "author_id": 5397845, "author_profile": "https://Stackoverflow.com/users/5397845", "pm_score": 1, "selected": false, "text": "if ( $value + 0 eq $value) {\n # A number\n push @args, $value;\n} else {\n # A string\n push @args, \"'$value'\";\n}\n" }, { "answer_id": 34547363, "author": "zagrimsan", "author_id": 2745865, "author_profile": "https://Stackoverflow.com/users/2745865", "pm_score": 0, "selected": false, "text": "-w no warnings do { \n no warnings \"numeric\";\n if ($x + 0 ne $x) { return \"not numeric\"; } else { return \"numeric\"; }\n}\n" }, { "answer_id": 72480461, "author": "Kevin", "author_id": 824897, "author_profile": "https://Stackoverflow.com/users/824897", "pm_score": 0, "selected": false, "text": "/^0$|^[+-]?[1-9][0-9]*$|^[+-]?[1-9][0-9]*(\\.[0-9]+)?([eE]-?[1-9][0-9]*)?$|^[+-]?[0-9]?\\.[0-9]+$|^[+-]?[1-9][0-9]*\\.[0-9]+$/\n ^0$ ^[+-]?[1-9][0-9]*$ ^[+-]?[1-9][0-9]*(\\.[0-9]+)?([eE]-?[1-9][0-9]*)?$ [1-9][0-9]* [0-9] ^[+-]?[0-9]?\\.[0-9]+$ ^[+-]?[1-9][0-9]*\\.[0-9]+$ sub is_number {\n my $testVal = shift;\n return $testVal =~ /^0$|^[+-]?[1-9][0-9]*$|^[+-]?[1-9][0-9]*(\\.[0-9]+)?([eE]-?[1-9][0-9]*)?$|^[+-]?[0-9]?\\.[0-9]+$|^[+-]?[1-9][0-9]*\\.[0-9]+$/;\n}\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/872/" ]
12,656
<p>In a project that I'm about to wrap up, I've written and implemented an object-relational mapping solution for PHP. Before the doubters and dreamers cry out "how on earth?", relax -- I haven't found a way to make late static binding work -- I'm just working around it in the best way that I possibly can.</p> <p>Anyway, I'm not currently using prepared statements for querying, because I couldn't come up with a way to pass a variable number of arguments to the <code>bind_params()</code> or <code>bind_result()</code> methods. </p> <p>Why do I need to support a variable number of arguments, you ask? Because the superclass of my models (think of my solution as a hacked-up PHP ActiveRecord wannabe) is where the querying is defined, and so the find() method, for example, doesn't know how many parameters it would need to bind.</p> <p>Now, I've already thought of building an argument list and passing a string to eval(), but I don't like that solution very much -- I'd rather just implement my own security checks and pass on statements.</p> <p>Does anyone have any suggestions (or success stories) about how to get this done? If you can help me solve this first problem, perhaps we can tackle binding the result set (something I suspect will be more difficult, or at least more resource-intensive if it involves an initial query to determine table structure).</p>
[ { "answer_id": 13092, "author": "John Downey", "author_id": 200, "author_profile": "https://Stackoverflow.com/users/200", "pm_score": 5, "selected": true, "text": "call_user_func_array call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);\n" }, { "answer_id": 80352, "author": "Steven Oxley", "author_id": 3831, "author_profile": "https://Stackoverflow.com/users/3831", "pm_score": 0, "selected": false, "text": "call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);\n $stmt bindparams call_user_func_array(array($stmt, 'bindparams'), $array_of_params);\n" }, { "answer_id": 2575732, "author": "jsleuth", "author_id": 275700, "author_profile": "https://Stackoverflow.com/users/275700", "pm_score": 0, "selected": false, "text": "call_user_func_array(array(&$stmt, 'bindparams'), $array_of_params);\n $sitesql = '';\n$array_of_params = array();\nforeach($_POST['multiselect'] as $value){\n if($sitesql!=''){\n $sitesql .= \"OR siteID=? \";\n $array_of_params[0] .= 'i';\n $array_of_params[] = $value;\n }else{\n $sitesql = \" siteID=? \";\n $array_of_params[0] .= 'i';\n $array_of_params[] = $value;\n }\n}\n\n$stmt = $linki->prepare(\"SELECT IFNULL(SUM(hours),0) FROM table WHERE \".$sitesql.\" AND week!='0000-00-00'\");\ncall_user_func_array(array(&$stmt, 'bind_param'), $array_of_params);\n$stmt->execute();\n" }, { "answer_id": 7240875, "author": "zhikharev", "author_id": 919105, "author_profile": "https://Stackoverflow.com/users/919105", "pm_score": 1, "selected": false, "text": "$array_of_params[0] = &$param_string; //link to variable that stores types\n $param_string .= \"i\";\n$user_id_var = $_GET['user_id'];//\n$array_of_params[] = &$user_id_var; //link to variable that stores value\n $bind_names[] = implode($types); //putting types of parameters in a string\nfor ($i = 0; $i < count($params); $i++)\n{\n $bind_name = 'bind'.$i; //generate a name for variable bind1, bind2, bind3...\n $$bind_name = $params[$i]; //create a variable with this name and put value in it\n $bind_names[] = & $$bind_name; //put a link to this variable in array\n}\n call_user_func_array( array ($stmt, 'bind_param'), $bind_names); \n" }, { "answer_id": 58364199, "author": "mickmackusa", "author_id": 2943403, "author_profile": "https://Stackoverflow.com/users/2943403", "pm_score": 2, "selected": false, "text": "... $values $stmt->bind_param(str_repeat('s', count($values)), ...$values);\n bind_param() array_unshift($values, str_repeat('s', count($values)));\n$stmt->bind_param(...$values);\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12656", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1344/" ]
12,661
<p>What's the most efficient way to resize large images in PHP?</p> <p>I'm currently using the <a href="http://en.wikipedia.org/wiki/GD_Graphics_Library" rel="noreferrer">GD</a> function imagecopyresampled to take high resolution images, and cleanly resize them down to a size for web viewing (roughly 700 pixels wide by 700 pixels tall).</p> <p>This works great on small (under 2 MB) photos and the entire resize operation takes less than a second on the server. However, the site will eventually service photographers who may be uploading images up to 10 MB in size (or images up to 5000x4000 pixels in size).</p> <p>Doing this kind of resize operation with large images tends to increase the memory usage by a very large margin (larger images can spike the memory usage for the script past 80 MB). Is there any way to make this resize operation more efficient? Should I be using an alternate image library such as <a href="http://en.wikipedia.org/wiki/ImageMagick" rel="noreferrer">ImageMagick</a>?</p> <p>Right now, the resize code looks something like this</p> <pre><code>function makeThumbnail($sourcefile, $endfile, $thumbwidth, $thumbheight, $quality) { // Takes the sourcefile (path/to/image.jpg) and makes a thumbnail from it // and places it at endfile (path/to/thumb.jpg). // Load image and get image size. $img = imagecreatefromjpeg($sourcefile); $width = imagesx( $img ); $height = imagesy( $img ); if ($width &gt; $height) { $newwidth = $thumbwidth; $divisor = $width / $thumbwidth; $newheight = floor( $height / $divisor); } else { $newheight = $thumbheight; $divisor = $height / $thumbheight; $newwidth = floor( $width / $divisor ); } // Create a new temporary image. $tmpimg = imagecreatetruecolor( $newwidth, $newheight ); // Copy and resize old image into new image. imagecopyresampled( $tmpimg, $img, 0, 0, 0, 0, $newwidth, $newheight, $width, $height ); // Save thumbnail into a file. imagejpeg( $tmpimg, $endfile, $quality); // release the memory imagedestroy($tmpimg); imagedestroy($img); </code></pre>
[ { "answer_id": 12805, "author": "Kevin", "author_id": 40, "author_profile": "https://Stackoverflow.com/users/40", "pm_score": 5, "selected": false, "text": "<?\nfunction fastimagecopyresampled (&$dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h, $quality = 3) {\n // Plug-and-Play fastimagecopyresampled function replaces much slower imagecopyresampled.\n // Just include this function and change all \"imagecopyresampled\" references to \"fastimagecopyresampled\".\n // Typically from 30 to 60 times faster when reducing high resolution images down to thumbnail size using the default quality setting.\n // Author: Tim Eckel - Date: 09/07/07 - Version: 1.1 - Project: FreeRingers.net - Freely distributable - These comments must remain.\n //\n // Optional \"quality\" parameter (defaults is 3). Fractional values are allowed, for example 1.5. Must be greater than zero.\n // Between 0 and 1 = Fast, but mosaic results, closer to 0 increases the mosaic effect.\n // 1 = Up to 350 times faster. Poor results, looks very similar to imagecopyresized.\n // 2 = Up to 95 times faster. Images appear a little sharp, some prefer this over a quality of 3.\n // 3 = Up to 60 times faster. Will give high quality smooth results very close to imagecopyresampled, just faster.\n // 4 = Up to 25 times faster. Almost identical to imagecopyresampled for most images.\n // 5 = No speedup. Just uses imagecopyresampled, no advantage over imagecopyresampled.\n\n if (empty($src_image) || empty($dst_image) || $quality <= 0) { return false; }\n if ($quality < 5 && (($dst_w * $quality) < $src_w || ($dst_h * $quality) < $src_h)) {\n $temp = imagecreatetruecolor ($dst_w * $quality + 1, $dst_h * $quality + 1);\n imagecopyresized ($temp, $src_image, 0, 0, $src_x, $src_y, $dst_w * $quality + 1, $dst_h * $quality + 1, $src_w, $src_h);\n imagecopyresampled ($dst_image, $temp, $dst_x, $dst_y, 0, 0, $dst_w, $dst_h, $dst_w * $quality, $dst_h * $quality);\n imagedestroy ($temp);\n } else imagecopyresampled ($dst_image, $src_image, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h);\n return true;\n}\n?>\n" }, { "answer_id": 4613341, "author": "Steve-o", "author_id": 175849, "author_profile": "https://Stackoverflow.com/users/175849", "pm_score": 3, "selected": false, "text": "$im = new Imagick();\ntry {\n $im->pingImage($file_name);\n} catch (ImagickException $e) {\n throw new Exception(_('Invalid or corrupted image file, please try uploading another image.'));\n}\n\n$width = $im->getImageWidth();\n$height = $im->getImageHeight();\nif ($width > $config['width_threshold'] || $height > $config['height_threshold'])\n{\n try {\n/* send thumbnail parameters to Imagick so that libjpeg can resize images\n * as they are loaded instead of consuming additional resources to pass back\n * to PHP.\n */\n $fitbyWidth = ($config['width_threshold'] / $width) > ($config['height_threshold'] / $height);\n $aspectRatio = $height / $width;\n if ($fitbyWidth) {\n $im->setSize($config['width_threshold'], abs($width * $aspectRatio));\n } else {\n $im->setSize(abs($height / $aspectRatio), $config['height_threshold']);\n }\n $im->readImage($file_name);\n\n/* Imagick::thumbnailImage(fit = true) has a bug that it does fit both dimensions\n */\n// $im->thumbnailImage($config['width_threshold'], $config['height_threshold'], true);\n\n// workaround:\n if ($fitbyWidth) {\n $im->thumbnailImage($config['width_threshold'], 0, false);\n } else {\n $im->thumbnailImage(0, $config['height_threshold'], false);\n }\n\n $im->setImageFileName($thumbnail_name);\n $im->writeImage();\n }\n catch (ImagickException $e)\n {\n header('HTTP/1.1 500 Internal Server Error');\n throw new Exception(_('An error occured reszing the image.'));\n }\n}\n\n/* cleanup Imagick\n */\n$im->destroy();\n" }, { "answer_id": 8321603, "author": "Alasdair", "author_id": 1018582, "author_profile": "https://Stackoverflow.com/users/1018582", "pm_score": 2, "selected": false, "text": "exec" }, { "answer_id": 19675318, "author": "Eathen Nutt", "author_id": 1970939, "author_profile": "https://Stackoverflow.com/users/1970939", "pm_score": 3, "selected": false, "text": "$_FILES['image']['tmp_name'] function getContentsFromImage($image) {\n if (@is_file($image) == true) {\n return file_get_contents($image);\n } else {\n throw new \\Exception('Invalid image');\n }\n }\n $contents = getContentsFromImage($_FILES['image']['tmp_name']);\n $_FILES[\"image\"][\"type\"] $_FILES[\"image\"][\"type\"] $_FILES[\"image\"][\"type\"] function getFormatFromContents($contents) {\n $finfo = new \\finfo();\n $mimetype = $finfo->buffer($contents, FILEINFO_MIME_TYPE);\n switch ($mimetype) {\n case 'image/jpeg':\n return 'jpeg';\n break;\n case 'image/png':\n return 'png';\n break;\n case 'image/gif':\n return 'gif';\n break;\n default:\n throw new \\Exception('Unknown or unsupported image format');\n }\n }\n $format = getFormatFromContents($contents);\n function getGDResourceFromContents($contents) {\n $resource = @imagecreatefromstring($contents);\n if ($resource == false) {\n throw new \\Exception('Cannot process image');\n }\n return $resource;\n }\n $resource = getGDResourceFromContents($contents);\n $width = imagesx($resource);\n $height = imagesy($resource);\n $contents, $format, $resource, $width, $height\n OK, lets move on\n imagecopyresampled() function getResizeArgs($width, $height, $newwidth, $newheight, $option) {\n if ($option === 'stretch') {\n if ($width === $newwidth && $height === $newheight) {\n return false;\n }\n $dst_w = $newwidth;\n $dst_h = $newheight;\n $src_w = $width;\n $src_h = $height;\n $src_x = 0;\n $src_y = 0;\n } else if ($option === 'shrink') {\n if ($width <= $newwidth && $height <= $newheight) {\n return false;\n } else if ($width / $height >= $newwidth / $newheight) {\n $dst_w = $newwidth;\n $dst_h = (int) round(($newwidth * $height) / $width);\n } else {\n $dst_w = (int) round(($newheight * $width) / $height);\n $dst_h = $newheight;\n }\n $src_x = 0;\n $src_y = 0;\n $src_w = $width;\n $src_h = $height;\n } else if ($option === 'fill') {\n if ($width === $newwidth && $height === $newheight) {\n return false;\n }\n if ($width / $height >= $newwidth / $newheight) {\n $src_w = (int) round(($newwidth * $height) / $newheight);\n $src_h = $height;\n $src_x = (int) round(($width - $src_w) / 2);\n $src_y = 0;\n } else {\n $src_w = $width;\n $src_h = (int) round(($width * $newheight) / $newwidth);\n $src_x = 0;\n $src_y = (int) round(($height - $src_h) / 2);\n }\n $dst_w = $newwidth;\n $dst_h = $newheight;\n }\n if ($src_w < 1 || $src_h < 1) {\n throw new \\Exception('Image width or height is too small');\n }\n return array(\n 'dst_x' => 0,\n 'dst_y' => 0,\n 'src_x' => $src_x,\n 'src_y' => $src_y,\n 'dst_w' => $dst_w,\n 'dst_h' => $dst_h,\n 'src_w' => $src_w,\n 'src_h' => $src_h\n );\n }\n $args = getResizeArgs($width, $height, 150, 170, 'fill');\n $args $width $height $format function runResize($width, $height, $format, $resource, $args) {\n if ($args === false) {\n return; //if $args equal to false, this means no resize occurs;\n }\n $newimage = imagecreatetruecolor($args['dst_w'], $args['dst_h']);\n if ($format === 'png') {\n imagealphablending($newimage, false);\n imagesavealpha($newimage, true);\n $transparentindex = imagecolorallocatealpha($newimage, 255, 255, 255, 127);\n imagefill($newimage, 0, 0, $transparentindex);\n } else if ($format === 'gif') {\n $transparentindex = imagecolorallocatealpha($newimage, 255, 255, 255, 127);\n imagefill($newimage, 0, 0, $transparentindex);\n imagecolortransparent($newimage, $transparentindex);\n }\n imagecopyresampled($newimage, $resource, $args['dst_x'], $args['dst_y'], $args['src_x'], $args['src_y'], $args['dst_w'], $args['dst_h'], $args['src_w'], $args['src_h']);\n imagedestroy($resource);\n return $newimage;\n }\n $newresource = runResize($width, $height, $format, $resource, $args);\n function getContentsFromGDResource($resource, $format) {\n ob_start();\n switch ($format) {\n case 'gif':\n imagegif($resource);\n break;\n case 'jpeg':\n imagejpeg($resource, NULL, 100);\n break;\n case 'png':\n imagepng($resource, NULL, 9);\n }\n $contents = ob_get_contents();\n ob_end_clean();\n return $contents;\n }\n $newcontents = getContentsFromGDResource($newresource, $format);\n function getExtensionFromFormat($format) {\n switch ($format) {\n case 'gif':\n return 'gif';\n break;\n case 'jpeg':\n return 'jpg';\n break;\n case 'png':\n return 'png';\n }\n }\n $extension = getExtensionFromFormat($format);\n $user_name = 'mike';\n$filename = $user_name . '.' . $extension;\nfile_put_contents($filename, $newcontents);\n imagedestroy($newresource);\n public function __destruct() {\n @imagedestroy($this->resource);\n }\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1477/" ]
12,671
<p>I'm fairly new to ASP.NET and trying to learn how things are done. I come from a C# background so the code-behind portion is easy, but thinking like a web developer is unfamiliar.</p> <p>I have an aspx page that contains a grid of checkboxes. I have a button that is coded via a Button_Click event to collect a list of which rows are checked and create a session variable out of that list. The same button is referenced (via TargetControlID) by my ascx page's ModalPopupExtender which controls the panel on the ascx page.</p> <p>When the button is clicked, the modal popup opens but the Button_Click event is never fired, so the modal doesn't get its session data.</p> <p>Since the two pages are separate, I can't call the ModalPopupExtender from the aspx.cs code, I can't reach the list of checkboxes from the ascx.cs code, and I don't see a way to populate my session variable and then programmatically activate some other hidden button or control which will then open my modal popup.</p> <p>Any thoughts?</p>
[ { "answer_id": 14735, "author": "Erick B", "author_id": 1373, "author_profile": "https://Stackoverflow.com/users/1373", "pm_score": 1, "selected": false, "text": "<uc1:ChildPage ID=\"MyModalPage\" runat=\"server\" />\n AjaxControlToolkit.ModalPopupExtender mpe = \n (AjaxControlToolkit.ModalPopupExtender) \n MyModalPage.FindControl(\"modalPopup\");\nmpe.Show();\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12671", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1373/" ]
12,702
<p>I have a WCF service from which I want to return a DataTable. I know that this is often a highly-debated topic, as far as whether or not returning DataTables is a good practice. Let's put that aside for a moment.</p> <p>When I create a DataTable from scratch, as below, there are no problems whatsoever. The table is created, populated, and returned to the client, and all is well:</p> <pre><code>[DataContract] public DataTable GetTbl() { DataTable tbl = new DataTable("testTbl"); for(int i=0;i&lt;100;i++) { tbl.Columns.Add(i); tbl.Rows.Add(new string[]{"testValue"}); } return tbl; } </code></pre> <p>However, as soon as I go out and hit the database to create the table, as below, I get a CommunicationException "The underlying connection was closed: The connection was closed unexpectedly."</p> <pre><code>[DataContract] public DataTable GetTbl() { DataTable tbl = new DataTable("testTbl"); //Populate table with SQL query return tbl; } </code></pre> <p>The table is being populated correctly on the server side. It is significantly smaller than the test table that I looped through and returned, and the query is small and fast - there is no issue here with timeouts or large data transfer. The same exact functions and DataContracts/ServiceContracts/BehaviorContracts are being used.</p> <p>Why would the way that the table is being populated have any bearing on the table returning successfully?</p>
[ { "answer_id": 12712, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "[ServiceContract]\npublic interface ITableProvider\n{\n [OperationContract]\n DataTable GetTbl();\n}\n\n\n[OperationBehavior]\npublic DataTable GetTbl(){\n DataTable tbl = new DataTable(\"testTbl\");\n //Populate table with SQL query\n\n return tbl;\n}\n web.config app.config" }, { "answer_id": 24492, "author": "Chris Gillum", "author_id": 2069, "author_profile": "https://Stackoverflow.com/users/2069", "pm_score": 4, "selected": false, "text": " <system.diagnostics>\n <sources>\n <source name=\"System.ServiceModel\" \n switchValue=\"Information\" \n propagateActivity=\"true\">\n <listeners>\n <add name=\"ServiceModelTraceListener\" \n type=\"System.Diagnostics.XmlWriterTraceListener, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" \n initializeData=\"wcf-traces.svclog\"/>\n </listeners>\n </source>\n </sources>\n </system.diagnostics>\n" }, { "answer_id": 42332, "author": "goric", "author_id": 940, "author_profile": "https://Stackoverflow.com/users/940", "pm_score": 7, "selected": true, "text": "return new DataTable();\n return new DataTable(\"someName\");\n TableName var table = new DataTable();\ntable.TableName = \"someName\";\n" }, { "answer_id": 4499790, "author": "aditya pathak", "author_id": 549975, "author_profile": "https://Stackoverflow.com/users/549975", "pm_score": 3, "selected": false, "text": "table.tablename" }, { "answer_id": 7872975, "author": "Jani5e", "author_id": 1008160, "author_profile": "https://Stackoverflow.com/users/1008160", "pm_score": 3, "selected": false, "text": "DataTable result = new DataTable(\"result\");\n\n//linq to populate the table\n\nDataset ds = new DataSet();\nds.Tables.Add(result);\nreturn ds.Tables[0];\n" }, { "answer_id": 40925254, "author": "Mukesh Methaniya", "author_id": 1410033, "author_profile": "https://Stackoverflow.com/users/1410033", "pm_score": 1, "selected": false, "text": "datatable MyTable=new DataTable(\"tableName\");\n system.data datatable [DataMember]\npublic DataTable MyTable{ get; set; }\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/940/" ]
12,706
<p>I'm coming from a Rails background and doing some work on a ASP.NET project (not ASP MVC). Newbie question: what's the easiest way to make a custom editor for a table of records?</p> <p>For example: I have a bunch of data rows and want to change the "category" field on each -- maybe a dropdown, maybe a link, maybe the user types it in.</p> <p>In Rails, I'd iterate over the rows to build a table, and would have a form for each row. The form would have an input box or dropdown, and submit the data to a controller like "/item/edit/15?category=foo" where 15 was the itemID and the new category was "foo".</p> <p>I'm new to the ASP.NET model and am not sure of the "right" way to do this -- just the simplest way to get back the new data &amp; save it off. Would I make a custom control and append it to each row? Any help appreciated.</p>
[ { "answer_id": 12873, "author": "Kalid", "author_id": 109, "author_profile": "https://Stackoverflow.com/users/109", "pm_score": 0, "selected": false, "text": "<asp:DataGrid ID=\"GridView1\" runat=\"server\" AutoGenerateColumns=\"False\">\n <Columns>\n <asp:BoundColumn DataField=\"RuleID\" Visible=\"False\" HeaderText=\"RuleID\"></asp:BoundColumn>\n <asp:TemplateColumn HeaderText=\"Category\">\n <ItemTemplate>\n <!-- in case we want to display an image -->\n <asp:Literal ID=\"litImage\" runat=\"server\">\n </asp:Literal>\n <asp:DropDownList ID=\"categoryListDropdown\" runat=\"server\"></asp:DropDownList>\n </ItemTemplate>\n </asp:TemplateColumn>\n\n </Columns>\n</asp:DataGrid>\n foreach (DataGridItem item in this.GridView1.Items)\n{\n DropDownList categoryListDropdown = ((DropDownList)item.FindControl(\"categoryListDropdown\"));\n categoryListDropdown.Items.AddRange(listItems.ToArray());\n}\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12706", "https://Stackoverflow.com", "https://Stackoverflow.com/users/109/" ]
12,716
<p>In C++ program, I am trying to #import TLB of .NET out-of-proc server.</p> <p>I get errors like:</p> <blockquote> <p>z:\server.tlh(111) : error C2146: syntax error : missing ';' before identifier 'GetType'</p> <p>z:\server.tlh(111) : error C2501: '_TypePtr' : missing storage-class or type specifiers</p> <p>z:\server.tli(74) : error C2143: syntax error : missing ';' before 'tag::id'</p> <p>z:\server.tli(74) : error C2433: '_TypePtr' : 'inline' not permitted on data declarations</p> <p>z:\server.tli(74) : error C2501: '_TypePtr' : missing storage-class or type specifiers</p> <p>z:\server.tli(74) : fatal error C1004: unexpected end of file found</p> </blockquote> <p>The TLH looks like:</p> <pre><code>_bstr_t GetToString(); VARIANT_BOOL Equals (const _variant_t &amp; obj); long GetHashCode(); _TypePtr GetType(); long Open(); </code></pre> <p>I am not really interested in the having the base object .NET object methods like GetType(), Equals(), etc. But GetType() seems to be causing problems.</p> <p>Some google research indicates I could <code>#import mscorlib.tlb</code> (or put it in path), but I can't get that to compile either.</p> <p>Any tips?</p>
[ { "answer_id": 12751, "author": "jm.", "author_id": 814, "author_profile": "https://Stackoverflow.com/users/814", "pm_score": 2, "selected": true, "text": "#import \"server.tlb\" no_namespace named_guids\n" }, { "answer_id": 758927, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "TLB #import \"C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\mscorlib.tlb\"\n stdafx.h #import \"your_own.tlb\"\n _Type _ObjRef" }, { "answer_id": 2071836, "author": "OndrejP_SK", "author_id": 251550, "author_profile": "https://Stackoverflow.com/users/251550", "pm_score": 1, "selected": false, "text": "[ClassInterface(ClassInterfaceType.None)]\n" }, { "answer_id": 2731679, "author": "ggo", "author_id": 328135, "author_profile": "https://Stackoverflow.com/users/328135", "pm_score": 2, "selected": false, "text": "#import \"C:\\WINDOWS\\Microsoft.NET\\Framework\\v2.0.50727\\mscorlib.tlb\"\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814/" ]
12,794
<p>I'm trying to use <code>jQuery</code> to format code blocks, specifically to add a <code>&lt;pre&gt;</code> tag inside the <code>&lt;code&gt;</code> tag:</p> <pre><code>$(document).ready(function() { $("code").wrapInner("&lt;pre&gt;&lt;/pre&gt;"); }); </code></pre> <p>Firefox applies the formatting correctly, but IE puts the entire code block on one line. If I add an alert </p> <pre><code>alert($("code").html()); </code></pre> <p>I see that IE has inserted some additional text into the pre tag:</p> <pre><code>&lt;PRE jQuery1218834632572="null"&gt; </code></pre> <p>If I reload the page, the number following jQuery changes.</p> <p>If I use <code>wrap()</code> instead of <code>wrapInner()</code>, to wrap the <code>&lt;pre&gt;</code> outside the <code>&lt;code&gt;</code> tag, both IE and Firefox handle it correctly. But shouldn't <code>&lt;pre&gt;</code> work <em>inside</em> <code>&lt;code&gt;</code> as well?</p> <p>I'd prefer to use <code>wrapInner()</code> because I can then add a CSS class to the <code>&lt;pre&gt;</code> tag to handle all formatting, but if I use <code>wrap()</code>, I have to put page formatting CSS in the <code>&lt;pre&gt;</code> tag and text/font formatting in the <code>&lt;code&gt;</code> tag, or Firefox and IE both choke. Not a huge deal, but I'd like to keep it as simple as possible.</p> <p>Has anyone else encountered this? Am I missing something?</p>
[ { "answer_id": 12804, "author": "Pat", "author_id": 238, "author_profile": "https://Stackoverflow.com/users/238", "pm_score": 1, "selected": false, "text": "$(\"code\").wrapInner(document.createElement(\"pre\"));\n" }, { "answer_id": 12983, "author": "markpasc", "author_id": 1472, "author_profile": "https://Stackoverflow.com/users/1472", "pm_score": 5, "selected": true, "text": "pre code code pre code pre code pre white-space: pre" }, { "answer_id": 7108933, "author": "Harry B", "author_id": 897266, "author_profile": "https://Stackoverflow.com/users/897266", "pm_score": 1, "selected": false, "text": "$('code').each(function(i,e)\n{\n var self = $(e);\n self.html('<pre>' + self.html() + '</pre>');\n});\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12794", "https://Stackoverflow.com", "https://Stackoverflow.com/users/311/" ]
12,836
<p>We have our own ORM we use here, and provide strongly typed wrappers for all of our db tables. We also allow weakly typed ad-hoc SQL to be executed, but these queries still go through the same class for getting values out of a data reader.</p> <p>In tweaking that class to work with Oracle, we've come across an interesting question. Is it better to use DBNull.Value, or null? Are there any benefits to using DBNull.Value? It seems more "correct" to use null, since we've separated ourselves from the DB world, but there are implications (you can't just blindly <code>ToString()</code> when a value is null for example) so its definitely something we need to make a conscious decision about.</p>
[ { "answer_id": 12854, "author": "John Smithers", "author_id": 1069, "author_profile": "https://Stackoverflow.com/users/1069", "pm_score": 1, "selected": false, "text": "DBNull" }, { "answer_id": 12935, "author": "Dan Herbert", "author_id": 392, "author_profile": "https://Stackoverflow.com/users/392", "pm_score": 5, "selected": true, "text": "DBNull" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/489/" ]
12,843
<p>I have two separate mercurial repositories. At this point it makes sense that they "become one" because I want to work on the two projects simultaneously.</p> <p>I'd really like the two projects to each be a subdirectory in the new repository.</p> <ol> <li>How do I merge the two projects?</li> <li>Is this a good idea, or should I keep them separate?</li> </ol> <p>It seems I ought to be able to push from one repository to the other... Maybe this is really straight forward?</p>
[ { "answer_id": 18175, "author": "nlucaroni", "author_id": 157, "author_profile": "https://Stackoverflow.com/users/157", "pm_score": 2, "selected": false, "text": "transplant hg transplant -s REPOSITORY lower_rev:high_rev\n" }, { "answer_id": 20591, "author": "jm.", "author_id": 814, "author_profile": "https://Stackoverflow.com/users/814", "pm_score": 7, "selected": true, "text": "hg clone first_repository hg pull -f other_repository -f" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12843", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814/" ]
12,855
<p>I have a query where I am searching against a string:</p> <pre><code>SELECT county FROM city WHERE UPPER(name) = 'SAN FRANCISCO'; </code></pre> <p>Now, this works fine, but it doesn't scale well, and I need to optimize it. I have <a href="http://www.ibm.com/developerworks/db2/library/techarticle/0203adamache/0203adamache.html" rel="nofollow noreferrer">found an option</a> along the lines of creating a generated view, or something like that, but I was hoping for a simpler solution using an index.</p> <p>We are using DB2, and I really want to use an <a href="http://ibmsystemsmag.blogs.com/db2utor/2007/11/db2-9-index-wit.html" rel="nofollow noreferrer">expression in an index</a>, but this option seems to only be available on z/OS, however we are running Linux. I tried the expression index anyways:</p> <pre><code>CREATE INDEX city_upper_name_idx ON city UPPER(name) ALLOW REVERSE SCANS; </code></pre> <p>But of course, it chokes on the UPPER(name).</p> <p>Is there another way I can create an index or something similar in this manner such that I don't have to restructure my existing queries to use a new generated view, or alter my existing columns, or any other such intrusive change?</p> <p>EDIT: I'm open to hearing solutions for other databases... it might carry over to DB2...</p>
[ { "answer_id": 12886, "author": "nsanders", "author_id": 1244, "author_profile": "https://Stackoverflow.com/users/1244", "pm_score": 3, "selected": false, "text": "hash = [compute hash key for 'SAN FRANCISCO']\n\nSELECT county \nFROM city \nWHERE cityHash = hash \n AND UPPER(name) = 'SAN FRANCISCO' ;\n" }, { "answer_id": 12962, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 1, "selected": false, "text": " create index emp_upper_idx on emp(upper(ename)); \n" }, { "answer_id": 13108, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 1, "selected": false, "text": "CREATE INDEX mytable_lower_col1_idx ON mytable (lower(col1));\n" }, { "answer_id": 16544, "author": "Kevin Crumley", "author_id": 1818, "author_profile": "https://Stackoverflow.com/users/1818", "pm_score": 2, "selected": false, "text": "ALTER TABLE city ALTER COLUMN name nvarchar(200) \n COLLATE SQL_Latin1_General_CP1_CI_AS\n" }, { "answer_id": 419382, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "CREATE TABLE tbl (\n lname VARCHAR(20),\n fname VARCHAR(20),\n ulname VARCHAR(20) GENERATED ALWAYS AS UPPER(lname)\n);\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/122/" ]
12,865
<p>Got a bluescreen in windows while cloning a mercurial repository.</p> <p>After reboot, I now get this message for almost all hg commands:</p> <pre> c:\src\>hg commit waiting for lock on repository c:\src\McVrsServer held by '\x00\x00\x00\x00\x00\ x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' interrupted! </pre> <p>Google is no help.</p> <p>Any tips?</p>
[ { "answer_id": 12879, "author": "jm.", "author_id": 814, "author_profile": "https://Stackoverflow.com/users/814", "pm_score": 10, "selected": true, "text": ".hg/wlock .hg/store/lock .hg/store/lock" }, { "answer_id": 2960524, "author": "Tiago Matos", "author_id": 356772, "author_profile": "https://Stackoverflow.com/users/356772", "pm_score": 8, "selected": false, "text": "waiting for lock on working directory .hg/wlock" }, { "answer_id": 16423091, "author": "Ian Kemp", "author_id": 70345, "author_profile": "https://Stackoverflow.com/users/70345", "pm_score": 4, "selected": false, "text": ".hg/store/lock .hg/store/phaseroots hg debuglock .hg/store/lock" }, { "answer_id": 25089553, "author": "Krazy Glew", "author_id": 1051115, "author_profile": "https://Stackoverflow.com/users/1051115", "pm_score": 3, "selected": false, "text": "A/.hg --symlinked-to--> B/.hg\n" }, { "answer_id": 41527661, "author": "Thomas Sharpless", "author_id": 1789624, "author_profile": "https://Stackoverflow.com/users/1789624", "pm_score": 6, "selected": false, "text": "% hg debuglocks\nlock: user None, process 7168, host HPv32 (114213199s)\nwlock: free\n[command returned code 1 Sat Jan 07 18:00:18 2017]\n% hg debuglocks --force-lock\n[command completed successfully Sat Jan 07 18:03:15 2017]\ncmdserver: Process crashed\nPaniniDev% hg debuglocks\n% hg debuglocks\nlock: free\nwlock: free\n[command completed successfully Sat Jan 07 18:03:30 2017]\n" }, { "answer_id": 51491278, "author": "user10125940", "author_id": 10125940, "author_profile": "https://Stackoverflow.com/users/10125940", "pm_score": 3, "selected": false, "text": "waiting for lock on working directory of <MyProject> held by '...'\n hg debuglock lock: free\nwlock: (66722s)\n hg debuglocks -W\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/814/" ]
12,870
<p>This is a nasty one for me... I'm a PHP guy working in Java on a JSP project. I know how to do what I'm attempting through too much code and a complete lack of finesse. </p> <p>I'd prefer to do it right. Here is the situation:</p> <p>I'm writing a small display to show customers what days they can water their lawns based on their watering group (ABCDE) and what time of year it is. Our seasons look like this: Summer (5-1 to 8-31) Spring (3-1 to 4-30) Fall (9-1 to 10-31) Winter (11-1 to 2-28) </p> <p>An example might be:</p> <p>If I'm in group A, here would be my allowed times: Winter: Mondays only Spring: Tues, Thurs, Sat Summer: Any Day Fall: Tues, Thurs, Sat</p> <p>If I was writing this in PHP I would use arrays like this:</p> <pre><code>//M=Monday,t=Tuesday,T=Thursday.... etc $schedule["A"]["Winter"]='M'; $schedule["A"]["Spring"]='tTS'; $schedule["A"]["Summer"]='Any'; $schedule["A"]["Fall"]='tTS'; $schedule["B"]["Winter"]='t'; </code></pre> <p>I COULD make the days arrays (array("Tuesday","Thursday","Saturday")) etc, but it is not necessary for what I'm really trying to accomplish.</p> <p>I will also need to setup arrays to determine what season I'm in:</p> <pre><code>$seasons["Summer"]["start"]=0501; $seasons["Summer"]["end"]=0801; </code></pre> <p>Can anyone suggest a really cool way to do this? I will have today's date and the group letter. I will need to get out of my function a day (M) or a series of days (tTS), (Any).</p>
[ { "answer_id": 12878, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 5, "selected": true, "text": "Hashtable<String, Hashtable<String, String>> schedule\n = new Hashtable<String, Hashtable<String, String>>();\nschedule.put(\"A\", new Hashtable<String, String>());\nschedule.put(\"B\", new Hashtable<String, String>());\nschedule.put(\"C\", new Hashtable<String, String>());\nschedule.put(\"D\", new Hashtable<String, String>());\nschedule.put(\"E\", new Hashtable<String, String>());\n\nschedule.get(\"A\").put(\"Winter\", \"M\");\nschedule.get(\"A\").put(\"Spring\", \"tTS\");\n// Etc...\n" }, { "answer_id": 12885, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 0, "selected": false, "text": "Hashtable<String, String> schedule = new Hashtable<String, String>();\nschedule.put(\"A-Winter\", \"M\");\nschedule.put(\"A-Spring\", \"tTS\");\n String val = schedule.get(group + \"-\" + season);\n String whenCanIWater(String group, Date date) { /* ugliness here */ }\n" }, { "answer_id": 12899, "author": "Wing", "author_id": 958, "author_profile": "https://Stackoverflow.com/users/958", "pm_score": 2, "selected": false, "text": "int A = 0;\nint B = 1;\nint C = 2;\nint D = 3;\n\nint Spring = 0; \nint Summer = 1;\nint Winter = 2; \nint Fall = 3;\n...\n schedule[A][Winter]=\"M\";\nschedule[A][Spring]=\"tTS\";\nschedule[A][Summer]=\"Any\";\nschedule[A][Fall]=\"tTS\";\nschedule[B][Winter]=\"t\";\n enum groups\n{\n A = 0,\n B = 1,\n C = 2,\n D = 3\n}\n\nenum seasons\n{\n Spring = 0,\n Summer = 1,\n Fall = 2,\n Winter = 3\n}\n...\nschedule[groups.A][seasons.Winter]=\"M\";\nschedule[groups.A][seasons.Spring]=\"tTS\";\nschedule[groups.A][seasons.Summer]=\"Any\";\nschedule[groups.A][seasons.Fall]=\"tTS\";\nschedule[groups.B][seasons.Winter]=\"t\";\n" }, { "answer_id": 12918, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 3, "selected": false, "text": "interface Season\n{\n public string getDays();\n}\n\ninterface User\n{\n public Season getWinter();\n public Season getSpring();\n public Season getSummer();\n public Season getFall();\n}\n\ninterface UserMap\n{\n public User getUser(string name);\n}\n" }, { "answer_id": 12923, "author": "Ian Good", "author_id": 1195, "author_profile": "https://Stackoverflow.com/users/1195", "pm_score": 3, "selected": false, "text": "class Schedule\n{\n private String group;\n private String season;\n private String rundays;\n public Schedule() { this.group = null; this.season = null; this.rundays= null; }\n public void setGroup(String g) { this.group = g; }\n public String getGroup() { return this.group; }\n ...\n}\n\npublic ArrayList<Schedule> schedules = new ArrayList<Schedule>();\nSchedule s = new Schedule();\ns.setGroup(...);\n...\nschedules.add(s);\n...\n" }, { "answer_id": 12932, "author": "Tim Frey", "author_id": 1471, "author_profile": "https://Stackoverflow.com/users/1471", "pm_score": 1, "selected": false, "text": "public String lookupDays(String group, String date);\n public class WaterScheduler\n{\n private static final Map<String, String> GROUP2SEASON = new HashMap<String, String>();\n static\n {\n addEntry(\"A\", \"Summer\", \"M\");\n addEntry(\"A\", \"Spring\", \"tTS\");\n addEntry(\"B\", \"Summer\", \"T\");\n }\n\n private static void addEntry(String group, String season, String value)\n {\n GROUP2SEASON.put(group + \".\" + season, value);\n }\n\n}\n" }, { "answer_id": 12941, "author": "Derek Park", "author_id": 872, "author_profile": "https://Stackoverflow.com/users/872", "pm_score": 2, "selected": false, "text": "Group Group" }, { "answer_id": 12992, "author": "bpapa", "author_id": 543, "author_profile": "https://Stackoverflow.com/users/543", "pm_score": 1, "selected": false, "text": "public Map<String,List<String>> getGroupToScheduledDaysMap() {\n // instantiate a date or whatever to decide what Map to return\n}\n <c:forEach var=\"day\" items=\"${scheduler.groupToScheduledDaysMap[\"A\"]}\">\n ${day}\n</c:forEach>\n" }, { "answer_id": 13037, "author": "Akira", "author_id": 795, "author_profile": "https://Stackoverflow.com/users/795", "pm_score": 2, "selected": false, "text": "A = new Group();\nA.getSeason(Seasons.WINTER).addDay(Days.MONDAY);\nA.getSeason(Seasons.SPRING).addDay(Days.TUESDAY).addDay(Days.THURSDAY);\nA.getSeason(Seasons.SPRING).addDays(Days.MONDAY, Days.TUESDAY, ...);\n\nschedule = new Schedule();\nschedule.addWateringGroup( A );\n" }, { "answer_id": 13099, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 2, "selected": false, "text": "import java.util.Date;\nimport java.util.Map;\nimport java.util.Set;\n\npublic class Group {\n\n private String groupName;\n\n private Map<Season, Set<Day>> schedule;\n\n public String getGroupName() {\n return groupName;\n }\n\n public void setGroupName(String groupName) {\n this.groupName = groupName;\n }\n\n public Map<Season, Set<Day>> getSchedule() {\n return schedule;\n }\n\n public void setSchedule(Map<Season, Set<Day>> schedule) {\n this.schedule = schedule;\n }\n\n public String getScheduleFor(Date date) {\n Season now = Season.getSeason(date);\n Set<Day> days = schedule.get(now);\n return Day.getDaysForDisplay(days);\n }\n\n}\n" }, { "answer_id": 48512739, "author": "Basil Bourque", "author_id": 642706, "author_profile": "https://Stackoverflow.com/users/642706", "pm_score": 0, "selected": false, "text": "Schedule.daysForGroupOnDate( \n Group.D , \n LocalDate.now()\n) \n Set DayOfWeek DayOfWeek.TUESDAY DayOfWeek.THURSDAY Month DayOfWeek EnumSet EnumMap Set Map Season Season List Month List.of package com.basilbourque.watering;\n\nimport java.time.LocalDate;\nimport java.time.Month;\nimport java.util.EnumSet;\nimport java.util.List;\nimport java.util.Set;\n\npublic enum Season\n{\n SPRING( List.of( Month.MARCH , Month.APRIL ) ),\n SUMMER( List.of( Month.MAY , Month.JUNE, Month.JULY , Month.AUGUST ) ),\n FALL( List.of( Month.SEPTEMBER , Month.OCTOBER ) ),\n WINTER( List.of( Month.NOVEMBER , Month.DECEMBER , Month.JANUARY , Month.FEBRUARY ) );\n\n private List< Month > months;\n\n // Constructor\n Season ( List < Month > monthsArg )\n {\n this.months = monthsArg;\n }\n\n public List < Month > getMonths ( )\n {\n return this.months;\n }\n\n // For any given month, determine the season.\n static public Season ofLocalMonth ( Month monthArg )\n {\n Season s = null;\n for ( Season season : EnumSet.allOf( Season.class ) )\n {\n if ( season.getMonths().contains( monthArg ) )\n {\n s = season;\n break; // Bail out of this FOR loop.\n }\n }\n return s;\n }\n\n // For any given date, determine the season.\n static public Season ofLocalDate ( LocalDate localDateArg )\n {\n Month month = localDateArg.getMonth();\n Season s = Season.ofLocalMonth( month );\n return s;\n }\n\n // Run `main` for demo/testing.\n public static void main ( String[] args )\n {\n // Dump all these enum objects to console.\n for ( Season season : EnumSet.allOf( Season.class ) )\n {\n System.out.println( \"Season: \" + season.toString() + \" = \" + season.getMonths() );\n }\n }\n}\n Group Group Map Season Set DayOfWeek Group.A Season.SPRING DayOfWeek.TUESDAY DayOfWeek.THURSDAY package com.basilbourque.watering;\n\nimport java.time.DayOfWeek;\nimport java.util.EnumMap;\nimport java.util.EnumSet;\nimport java.util.Map;\nimport java.util.Set;\n\npublic enum Group\n{\n A(\n Map.of(\n Season.SPRING , EnumSet.of( DayOfWeek.TUESDAY , DayOfWeek.THURSDAY ) ,\n Season.SUMMER , EnumSet.allOf( DayOfWeek.class ) ,\n Season.FALL , EnumSet.of( DayOfWeek.TUESDAY , DayOfWeek.THURSDAY ) ,\n Season.WINTER , EnumSet.of( DayOfWeek.TUESDAY )\n )\n ),\n B(\n Map.of(\n Season.SPRING , EnumSet.of( DayOfWeek.FRIDAY ) ,\n Season.SUMMER , EnumSet.allOf( DayOfWeek.class ) ,\n Season.FALL , EnumSet.of( DayOfWeek.TUESDAY , DayOfWeek.FRIDAY ) ,\n Season.WINTER , EnumSet.of( DayOfWeek.FRIDAY )\n )\n ),\n C(\n Map.of(\n Season.SPRING , EnumSet.of( DayOfWeek.MONDAY ) ,\n Season.SUMMER , EnumSet.allOf( DayOfWeek.class ) ,\n Season.FALL , EnumSet.of( DayOfWeek.MONDAY , DayOfWeek.TUESDAY ) ,\n Season.WINTER , EnumSet.of( DayOfWeek.MONDAY )\n )\n ),\n D(\n Map.of(\n Season.SPRING , EnumSet.of( DayOfWeek.WEDNESDAY , DayOfWeek.FRIDAY ) ,\n Season.SUMMER , EnumSet.allOf( DayOfWeek.class ) ,\n Season.FALL , EnumSet.of( DayOfWeek.FRIDAY ) ,\n Season.WINTER , EnumSet.of( DayOfWeek.WEDNESDAY )\n )\n ),\n E(\n Map.of(\n Season.SPRING , EnumSet.of( DayOfWeek.TUESDAY ) ,\n Season.SUMMER , EnumSet.allOf( DayOfWeek.class ) ,\n Season.FALL , EnumSet.of( DayOfWeek.TUESDAY , DayOfWeek.WEDNESDAY ) ,\n Season.WINTER , EnumSet.of( DayOfWeek.WEDNESDAY )\n )\n );\n\n private Map < Season, Set < DayOfWeek > > map;\n\n // Constructor\n Group ( Map < Season, Set < DayOfWeek > > mapArg )\n {\n this.map = mapArg;\n }\n\n // Getter\n private Map < Season, Set < DayOfWeek > > getMapOfSeasonToDaysOfWeek() {\n return this.map ;\n }\n\n // Retrieve the DayOfWeek set for this particular Group.\n public Set<DayOfWeek> daysForSeason (Season season ) {\n Set<DayOfWeek> days = this.map.get( season ) ; // Retrieve the value (set of days) for this key (a season) for this particular grouping of lawns/yards.\n return days;\n }\n\n\n\n // Run `main` for demo/testing.\n public static void main ( String[] args )\n {\n // Dump all these enum objects to console.\n for ( Group group : EnumSet.allOf( Group.class ) )\n {\n System.out.println( \"Group: \" + group.toString() + \" = \" + group.getMapOfSeasonToDaysOfWeek() );\n }\n }\n\n}\n Schedule Schedule Season main package com.basilbourque.watering;\n\nimport java.time.DayOfWeek;\nimport java.time.LocalDate;\nimport java.time.ZoneId;\nimport java.time.format.DateTimeFormatter;\nimport java.time.temporal.ChronoField;\nimport java.time.temporal.IsoFields;\nimport java.util.EnumSet;\nimport java.util.Set;\n\npublic class Schedule\n{\n static private DateTimeFormatter isoWeekFormatter = DateTimeFormatter.ofPattern( \"uuuu-'W'ww\" ) ;\n\n static public Set < DayOfWeek > daysForGroupOnDate ( Group group , LocalDate localDate )\n {\n Season season = Season.ofLocalDate( localDate );\n Set < DayOfWeek > days = group.daysForSeason( season );\n return days;\n }\n\n // Run `main` for demo/testing.\n public static void main ( String[] args )\n {\n Season.main( null );\n Group.main( null );\n // Dump all these enum objects to console.\n for ( Group group : EnumSet.allOf( Group.class ) )\n {\n LocalDate localDate = LocalDate.now( ZoneId.of( \"Africa/Tunis\" ) );\n Set < DayOfWeek > days = Schedule.daysForGroupOnDate( group , localDate );\n String week = localDate.format( Schedule.isoWeekFormatter ) ; // Standard ISO 8601 week, where week number one has the first Thursday of the calendar year, and week starts on Monday, so year is either 52 or 53 weeks long.\n String message = \"Group \" + group + \" – Watering days on \" + localDate + \" week # \" + week + \" is: \" + days;\n System.out.println( message );\n }\n }\n}\n Schedule.main YearWeek LocalDate LocalDate continent/region America/Montreal Africa/Casablanca Pacific/Auckland EST IST ZoneId z = ZoneId.of( \"America/Montreal\" ) ; \nLocalDate today = LocalDate.now( z ) ;\n ZoneId z = ZoneId.systemDefault() ; // Get JVM’s current default time zone.\n LocalDate ld = LocalDate.of( 1986 , 2 , 23 ) ; // Years use sane direct numbering (1986 means year 1986). Months use sane numbering, 1-12 for January-December.\n Month Month LocalDate ld = LocalDate.of( 1986 , Month.FEBRUARY , 23 ) ;\n List.of Map.of Map EnumMap Map.of Set.of EnumMap EnumSet Sets.immutableEnumSet( … ) Maps.immutableEnumMap( … ) EnumSet EnumMap get put Season Group Season package com.basilbourque.watering;\n\nimport java.time.LocalDate;\nimport java.time.Month;\nimport java.util.EnumSet;\nimport java.util.List;\n\npublic enum Season\n{\n SPRING( List.of( Month.MARCH , Month.APRIL ) ), // `List.of` provides literals-style syntax, and returns an immutable `List`. New in Java 9.\n SUMMER( List.of( Month.MAY , Month.JUNE, Month.JULY , Month.AUGUST ) ),\n FALL( List.of( Month.SEPTEMBER , Month.OCTOBER ) ),\n WINTER( List.of( Month.NOVEMBER , Month.DECEMBER , Month.JANUARY , Month.FEBRUARY ) );\n\n private List< Month > months;\n\n // Constructor\n Season ( List < Month > monthsArg )\n {\n this.months = monthsArg;\n }\n\n public List < Month > getMonths ( )\n {\n return this.months;\n }\n\n // For any given month, determine the season.\n static public Season ofLocalMonth ( Month monthArg )\n {\n Season s = null;\n for ( Season season : EnumSet.allOf( Season.class ) )\n {\n if ( season.getMonths().contains( monthArg ) )\n {\n s = season;\n break; // Bail out of this FOR loop.\n }\n }\n return s;\n }\n\n // For any given date, determine the season.\n static public Season ofLocalDate ( LocalDate localDateArg )\n {\n Month month = localDateArg.getMonth();\n Season s = Season.ofLocalMonth( month );\n return s;\n }\n\n // Run `main` for demo/testing.\n public static void main ( String[] args )\n {\n // Dump all these enum objects to console.\n for ( Season season : EnumSet.allOf( Season.class ) )\n {\n System.out.println( \"Season: \" + season.toString() + \" = \" + season.getMonths() );\n }\n }\n}\n Group package com.basilbourque.watering;\n\nimport com.google.common.collect.Maps;\nimport com.google.common.collect.Sets;\n\nimport java.time.DayOfWeek;\nimport java.util.EnumSet;\nimport java.util.Map;\nimport java.util.Set;\n\npublic enum Group\n{\n A(\n Maps.immutableEnumMap(\n Map.of( // `Map.of` provides literals-style syntax, and returns an immutable `Map`. New in Java 9.\n Season.SPRING , Sets.immutableEnumSet( DayOfWeek.TUESDAY , DayOfWeek.THURSDAY ) ,\n Season.SUMMER , Sets.immutableEnumSet( EnumSet.allOf( DayOfWeek.class ) ) ,\n Season.FALL , Sets.immutableEnumSet( DayOfWeek.TUESDAY , DayOfWeek.THURSDAY ) ,\n Season.WINTER , Sets.immutableEnumSet( DayOfWeek.TUESDAY )\n )\n )\n ),\n\n B(\n Maps.immutableEnumMap(\n Map.of(\n Season.SPRING , Sets.immutableEnumSet( DayOfWeek.FRIDAY ) ,\n Season.SUMMER , Sets.immutableEnumSet( EnumSet.allOf( DayOfWeek.class ) ) ,\n Season.FALL , Sets.immutableEnumSet( DayOfWeek.TUESDAY , DayOfWeek.FRIDAY ) ,\n Season.WINTER , Sets.immutableEnumSet( DayOfWeek.FRIDAY )\n )\n )\n ),\n\n C(\n Maps.immutableEnumMap(\n Map.of(\n Season.SPRING , Sets.immutableEnumSet( DayOfWeek.MONDAY ) ,\n Season.SUMMER , Sets.immutableEnumSet( EnumSet.allOf( DayOfWeek.class ) ) ,\n Season.FALL , Sets.immutableEnumSet( DayOfWeek.MONDAY , DayOfWeek.TUESDAY ) ,\n Season.WINTER , Sets.immutableEnumSet( DayOfWeek.MONDAY )\n )\n )\n ),\n\n D(\n Maps.immutableEnumMap(\n Map.of(\n Season.SPRING , Sets.immutableEnumSet( DayOfWeek.WEDNESDAY , DayOfWeek.FRIDAY ) ,\n Season.SUMMER , Sets.immutableEnumSet( EnumSet.allOf( DayOfWeek.class ) ) ,\n Season.FALL , Sets.immutableEnumSet( DayOfWeek.FRIDAY ) ,\n Season.WINTER , Sets.immutableEnumSet( DayOfWeek.WEDNESDAY )\n )\n )\n ),\n\n E(\n Maps.immutableEnumMap(\n Map.of(\n Season.SPRING , Sets.immutableEnumSet( DayOfWeek.TUESDAY ) ,\n Season.SUMMER , Sets.immutableEnumSet( EnumSet.allOf( DayOfWeek.class ) ) ,\n Season.FALL , Sets.immutableEnumSet( EnumSet.of( DayOfWeek.TUESDAY , DayOfWeek.WEDNESDAY ) ) ,\n Season.WINTER , Sets.immutableEnumSet( DayOfWeek.WEDNESDAY )\n )\n )\n );\n\n private Map < Season, Set < DayOfWeek > > map;\n\n // Constructor\n Group ( Map < Season, Set < DayOfWeek > > mapArg )\n {\n this.map = mapArg;\n }\n\n // Getter\n private Map < Season, Set < DayOfWeek > > getMapOfSeasonToDaysOfWeek ( )\n {\n return this.map;\n }\n\n // Retrieve the DayOfWeek set for this particular Group.\n public Set < DayOfWeek > daysForSeason ( Season season )\n {\n Set < DayOfWeek > days = this.map.get( season ); // Retrieve the value (set of days) for this key (a season) for this particular grouping of lawns/yards.\n return days;\n }\n\n // Run `main` for demo/testing.\n public static void main ( String[] args )\n {\n // Dump all these enum objects to console.\n for ( Group group : EnumSet.allOf( Group.class ) )\n {\n System.out.println( \"Group: \" + group.toString() + \" = \" + group.getMapOfSeasonToDaysOfWeek() );\n }\n }\n\n}\n java.util.Date Calendar SimpleDateFormat Interval YearWeek YearQuarter" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/172/" ]
12,890
<p>I have a large database of normalized order data that is becoming very slow to query for reporting. Many of the queries that I use in reports join five or six tables and are having to examine tens or hundreds of thousands of lines.</p> <p>There are lots of queries and most have been optimized as much as possible to reduce server load and increase speed. I think it's time to start keeping a copy of the data in a denormalized format.</p> <p>Any ideas on an approach? Should I start with a couple of my worst queries and go from there?</p>
[ { "answer_id": 12950, "author": "Eric Z Beard", "author_id": 1219, "author_profile": "https://Stackoverflow.com/users/1219", "pm_score": 5, "selected": true, "text": "select a.name, b.address from tbla a \njoin tblb b on b.fk_a_id = a.id where a.id=1\n create table tbl_ab (a_id, a_name, b_address); \n-- (types elided)\n insert tbl_ab select a.id, a.name, b.address from tbla a\njoin tblb b on b.fk_a_id = a.id \n-- no where clause because you want everything\n select a_name as name, b_address as address \nfrom tbl_ab where a_id = 1;\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1430/" ]
12,896
<p>I'm looking for good/working/simple to use PHP code for parsing raw email into parts.</p> <p>I've written a couple of brute force solutions, but every time, one small change/header/space/something comes along and my whole parser fails and the project falls apart.</p> <p>And before I get pointed at PEAR/PECL, I need actual code. My host has some screwy config or something, I can never seem to get the .so's to build right. If I do get the .so made, some difference in path/environment/php.ini doesn't always make it available (apache vs cron vs CLI).</p> <p>Oh, and one last thing, I'm parsing the raw email text, NOT POP3, and NOT IMAP. It's being piped into the PHP script via a .qmail email redirect.</p> <p>I'm not expecting SOF to write it for me, I'm looking for some tips/starting points on doing it &quot;right&quot;. This is one of those &quot;wheel&quot; problems that I know has already been solved.</p>
[ { "answer_id": 12965, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 6, "selected": true, "text": "HEADERS\\n\n\\n\nBODY\n HSTRING:HTEXT\n HEADER: HEADER TEXT\nHEADER: MORE HEADER TEXT\n INCLUDING A LINE CONTINUATION\nHEADER: LAST HEADER\n\nTHIS IS ANY\nARBITRARY DATA\n(FOR THE MOST PART)\n" }, { "answer_id": 5954640, "author": "Carter Cole", "author_id": 180434, "author_profile": "https://Stackoverflow.com/users/180434", "pm_score": 3, "selected": false, "text": "#!/usr/bin/php -q\n<?php\n// Config\n$dbuser = 'emlusr';\n$dbpass = 'pass';\n$dbname = 'email';\n$dbhost = 'localhost';\n$notify= '[email protected]'; // an email address required in case of errors\nfunction mailRead($iKlimit = \"\") \n { \n // Purpose: \n // Reads piped mail from STDIN \n // \n // Arguements: \n // $iKlimit (integer, optional): specifies after how many kilobytes reading of mail should stop \n // Defaults to 1024k if no value is specified \n // A value of -1 will cause reading to continue until the entire message has been read \n // \n // Return value: \n // A string containing the entire email, headers, body and all. \n\n // Variable perparation \n // Set default limit of 1024k if no limit has been specified \n if ($iKlimit == \"\") { \n $iKlimit = 1024; \n } \n\n // Error strings \n $sErrorSTDINFail = \"Error - failed to read mail from STDIN!\"; \n\n // Attempt to connect to STDIN \n $fp = fopen(\"php://stdin\", \"r\"); \n\n // Failed to connect to STDIN? (shouldn't really happen) \n if (!$fp) { \n echo $sErrorSTDINFail; \n exit(); \n } \n\n // Create empty string for storing message \n $sEmail = \"\"; \n\n // Read message up until limit (if any) \n if ($iKlimit == -1) { \n while (!feof($fp)) { \n $sEmail .= fread($fp, 1024); \n } \n } else { \n while (!feof($fp) && $i_limit < $iKlimit) { \n $sEmail .= fread($fp, 1024); \n $i_limit++; \n } \n } \n\n // Close connection to STDIN \n fclose($fp); \n\n // Return message \n return $sEmail; \n } \n$email = mailRead();\n\n// handle email\n$lines = explode(\"\\n\", $email);\n\n// empty vars\n$from = \"\";\n$subject = \"\";\n$headers = \"\";\n$message = \"\";\n$splittingheaders = true;\nfor ($i=0; $i < count($lines); $i++) {\n if ($splittingheaders) {\n // this is a header\n $headers .= $lines[$i].\"\\n\";\n\n // look out for special headers\n if (preg_match(\"/^Subject: (.*)/\", $lines[$i], $matches)) {\n $subject = $matches[1];\n }\n if (preg_match(\"/^From: (.*)/\", $lines[$i], $matches)) {\n $from = $matches[1];\n }\n if (preg_match(\"/^To: (.*)/\", $lines[$i], $matches)) {\n $to = $matches[1];\n }\n } else {\n // not a header, but message\n $message .= $lines[$i].\"\\n\";\n }\n\n if (trim($lines[$i])==\"\") {\n // empty line, header section has ended\n $splittingheaders = false;\n }\n}\n\nif ($conn = @mysql_connect($dbhost,$dbuser,$dbpass)) {\n if(!@mysql_select_db($dbname,$conn))\n mail($email,'Email Logger Error',\"There was an error selecting the email logger database.\\n\\n\".mysql_error());\n $from = mysql_real_escape_string($from);\n $to = mysql_real_escape_string($to);\n $subject = mysql_real_escape_string($subject);\n $headers = mysql_real_escape_string($headers);\n $message = mysql_real_escape_string($message);\n $email = mysql_real_escape_string($email);\n $result = @mysql_query(\"INSERT INTO email_log (`to`,`from`,`subject`,`headers`,`message`,`source`) VALUES('$to','$from','$subject','$headers','$message','$email')\");\n if (mysql_affected_rows() == 0)\n mail($notify,'Email Logger Error',\"There was an error inserting into the email logger database.\\n\\n\".mysql_error());\n} else {\n mail($notify,'Email Logger Error',\"There was an error connecting the email logger database.\\n\\n\".mysql_error());\n}\n?>\n" }, { "answer_id": 31186504, "author": "Yaroslav", "author_id": 3238670, "author_profile": "https://Stackoverflow.com/users/3238670", "pm_score": 2, "selected": false, "text": "array(\n 'received' => '28 Apr 2010 22:00:38 -0400',\n 'headers' => array(\n 'received' => array(\n 0 => '(qmail 25838 invoked from network); 28 Apr 2010 22:00:38 -0400',\n 1 => 'from example.com (HELO ?192.168.10.2?) (example) by example.com with (DHE-RSA-AES256-SHA encrypted) SMTP; 28 Apr 2010 22:00:38 -0400'\n ),\n 'message-id' => '<[email protected]>',\n 'date' => 'Wed, 28 Apr 2010 21:59:49 -0400',\n 'from' => array(\n 'personal' => 'Will Bond',\n 'mailbox' => 'tests',\n 'host' => 'flourishlib.com'\n ),\n 'user-agent' => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.9) Gecko/20100317 Thunderbird/3.0.4',\n 'mime-version' => '1.0',\n 'to' => array(\n 0 => array(\n 'mailbox' => 'tests',\n 'host' => 'flourishlib.com'\n )\n ),\n 'subject' => 'This message is encrypted'\n ),\n 'text' => 'This message is encrypted',\n 'decrypted' => TRUE,\n 'uid' => 15\n);\n" }, { "answer_id": 40764732, "author": "TomaszKane", "author_id": 1829368, "author_profile": "https://Stackoverflow.com/users/1829368", "pm_score": 2, "selected": false, "text": "<?php\necho $message->getHeaderValue('from'); // [email protected]\necho $message\n ->getHeader('from')\n ->getPersonName(); // Person Name\necho $message->getHeaderValue('subject'); // The email's subject\n\necho $message->getTextContent(); // or getHtmlContent\n" }, { "answer_id": 47110625, "author": "Kazik", "author_id": 8885286, "author_profile": "https://Stackoverflow.com/users/8885286", "pm_score": 0, "selected": false, "text": "$str = file_get_contents('mime-mixed-related-alternative.eml');\n\n// MimeParser\n$m = new PhpMimeParser($str);\n\n// Emails\nprint_r($m->mTo);\nprint_r($m->mFrom);\n\n// Message\necho $m->mSubject;\necho $m->mHtml;\necho $m->mText;\n\n// Attachments and inline images\nprint_r($m->mFiles);\nprint_r($m->mInlineList);\n" }, { "answer_id": 67923886, "author": "Adam Winter", "author_id": 10664600, "author_profile": "https://Stackoverflow.com/users/10664600", "pm_score": 0, "selected": false, "text": "FROM php:7.4-apache\nWORKDIR /var/www/html\nEXPOSE 80\nWORKDIR /var/www\nRUN chown -R www-data html\nRUN docker-php-ext-install mysqli\nRUN pear install --alldeps mail\nRUN pear install Mail_mimeDecode\n <?php\n\nrequire_once \"/usr/local/lib/php/Mail.php\";\nrequire_once \"/usr/local/lib/php/Mail/mimeDecode.php\";\n\n$mailfiles = ['/var/www/mail/mailFile1','/var/www/mail/mailFile2'];\n\nforeach($mailfiles as $filename){\n $theFile = fopen($filename, \"r\") or die(\"Unable to open file!\");\n $rawEmail = fread($theFile, filesize($filename));\n fclose($theFile);\n\n $args = [];\n $args['include_bodies'] = true;\n $args['decode_bodies'] = FALSE;\n $args['decode_headers'] = FALSE;\n $objMail = new Mail_mimeDecode($rawEmail);\n $return = $objMail->decode($args);\n\n if (PEAR::isError($return)) {\n echo(\"<p>\" . $return->getMessage() . \"</p>\");\n var_dump($return);\n } else {\n //echo(\"No error in PEAR::isError(return)\");\n }\n\n if($return->body){\n $decoded = base64_decode($return->body, true);\n var_dump($decoded);\n }//end if(body)\n\n}//end foreach(mailfiles as file)\n\n\n?>\n" } ]
2008/08/15
[ "https://Stackoverflow.com/questions/12896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/314/" ]
12,905
<p>I'm experimenting with creating an add-in for Infopath 2007. The documentation is very skimpy. What I'm trying to determine is what kind of actions an add-in can take while designing a form. Most of the discussion and samples are for when the user is filling out the form. Can I, for example, add a new field to the form in the designer? Add a new item to the schema? Move a form field on the design surface? It doesn't appear so, but I can't find anything definitive.</p>
[ { "answer_id": 12965, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 6, "selected": true, "text": "HEADERS\\n\n\\n\nBODY\n HSTRING:HTEXT\n HEADER: HEADER TEXT\nHEADER: MORE HEADER TEXT\n INCLUDING A LINE CONTINUATION\nHEADER: LAST HEADER\n\nTHIS IS ANY\nARBITRARY DATA\n(FOR THE MOST PART)\n" }, { "answer_id": 5954640, "author": "Carter Cole", "author_id": 180434, "author_profile": "https://Stackoverflow.com/users/180434", "pm_score": 3, "selected": false, "text": "#!/usr/bin/php -q\n<?php\n// Config\n$dbuser = 'emlusr';\n$dbpass = 'pass';\n$dbname = 'email';\n$dbhost = 'localhost';\n$notify= '[email protected]'; // an email address required in case of errors\nfunction mailRead($iKlimit = \"\") \n { \n // Purpose: \n // Reads piped mail from STDIN \n // \n // Arguements: \n // $iKlimit (integer, optional): specifies after how many kilobytes reading of mail should stop \n // Defaults to 1024k if no value is specified \n // A value of -1 will cause reading to continue until the entire message has been read \n // \n // Return value: \n // A string containing the entire email, headers, body and all. \n\n // Variable perparation \n // Set default limit of 1024k if no limit has been specified \n if ($iKlimit == \"\") { \n $iKlimit = 1024; \n } \n\n // Error strings \n $sErrorSTDINFail = \"Error - failed to read mail from STDIN!\"; \n\n // Attempt to connect to STDIN \n $fp = fopen(\"php://stdin\", \"r\"); \n\n // Failed to connect to STDIN? (shouldn't really happen) \n if (!$fp) { \n echo $sErrorSTDINFail; \n exit(); \n } \n\n // Create empty string for storing message \n $sEmail = \"\"; \n\n // Read message up until limit (if any) \n if ($iKlimit == -1) { \n while (!feof($fp)) { \n $sEmail .= fread($fp, 1024); \n } \n } else { \n while (!feof($fp) && $i_limit < $iKlimit) { \n $sEmail .= fread($fp, 1024); \n $i_limit++; \n } \n } \n\n // Close connection to STDIN \n fclose($fp); \n\n // Return message \n return $sEmail; \n } \n$email = mailRead();\n\n// handle email\n$lines = explode(\"\\n\", $email);\n\n// empty vars\n$from = \"\";\n$subject = \"\";\n$headers = \"\";\n$message = \"\";\n$splittingheaders = true;\nfor ($i=0; $i < count($lines); $i++) {\n if ($splittingheaders) {\n // this is a header\n $headers .= $lines[$i].\"\\n\";\n\n // look out for special headers\n if (preg_match(\"/^Subject: (.*)/\", $lines[$i], $matches)) {\n $subject = $matches[1];\n }\n if (preg_match(\"/^From: (.*)/\", $lines[$i], $matches)) {\n $from = $matches[1];\n }\n if (preg_match(\"/^To: (.*)/\", $lines[$i], $matches)) {\n $to = $matches[1];\n }\n } else {\n // not a header, but message\n $message .= $lines[$i].\"\\n\";\n }\n\n if (trim($lines[$i])==\"\") {\n // empty line, header section has ended\n $splittingheaders = false;\n }\n}\n\nif ($conn = @mysql_connect($dbhost,$dbuser,$dbpass)) {\n if(!@mysql_select_db($dbname,$conn))\n mail($email,'Email Logger Error',\"There was an error selecting the email logger database.\\n\\n\".mysql_error());\n $from = mysql_real_escape_string($from);\n $to = mysql_real_escape_string($to);\n $subject = mysql_real_escape_string($subject);\n $headers = mysql_real_escape_string($headers);\n $message = mysql_real_escape_string($message);\n $email = mysql_real_escape_string($email);\n $result = @mysql_query(\"INSERT INTO email_log (`to`,`from`,`subject`,`headers`,`message`,`source`) VALUES('$to','$from','$subject','$headers','$message','$email')\");\n if (mysql_affected_rows() == 0)\n mail($notify,'Email Logger Error',\"There was an error inserting into the email logger database.\\n\\n\".mysql_error());\n} else {\n mail($notify,'Email Logger Error',\"There was an error connecting the email logger database.\\n\\n\".mysql_error());\n}\n?>\n" }, { "answer_id": 31186504, "author": "Yaroslav", "author_id": 3238670, "author_profile": "https://Stackoverflow.com/users/3238670", "pm_score": 2, "selected": false, "text": "array(\n 'received' => '28 Apr 2010 22:00:38 -0400',\n 'headers' => array(\n 'received' => array(\n 0 => '(qmail 25838 invoked from network); 28 Apr 2010 22:00:38 -0400',\n 1 => 'from example.com (HELO ?192.168.10.2?) (example) by example.com with (DHE-RSA-AES256-SHA encrypted) SMTP; 28 Apr 2010 22:00:38 -0400'\n ),\n 'message-id' => '<[email protected]>',\n 'date' => 'Wed, 28 Apr 2010 21:59:49 -0400',\n 'from' => array(\n 'personal' => 'Will Bond',\n 'mailbox' => 'tests',\n 'host' => 'flourishlib.com'\n ),\n 'user-agent' => 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.9) Gecko/20100317 Thunderbird/3.0.4',\n 'mime-version' => '1.0',\n 'to' => array(\n 0 => array(\n 'mailbox' => 'tests',\n 'host' => 'flourishlib.com'\n )\n ),\n 'subject' => 'This message is encrypted'\n ),\n 'text' => 'This message is encrypted',\n 'decrypted' => TRUE,\n 'uid' => 15\n);\n" }, { "answer_id": 40764732, "author": "TomaszKane", "author_id": 1829368, "author_profile": "https://Stackoverflow.com/users/1829368", "pm_score": 2, "selected": false, "text": "<?php\necho $message->getHeaderValue('from'); // [email protected]\necho $message\n ->getHeader('from')\n ->getPersonName(); // Person Name\necho $message->getHeaderValue('subject'); // The email's subject\n\necho $message->getTextContent(); // or getHtmlContent\n" }, { "answer_id": 47110625, "author": "Kazik", "author_id": 8885286, "author_profile": "https://Stackoverflow.com/users/8885286", "pm_score": 0, "selected": false, "text": "$str = file_get_contents('mime-mixed-related-alternative.eml');\n\n// MimeParser\n$m = new PhpMimeParser($str);\n\n// Emails\nprint_r($m->mTo);\nprint_r($m->mFrom);\n\n// Message\necho $m->mSubject;\necho $m->mHtml;\necho $m->mText;\n\n// Attachments and inline images\nprint_r($m->mFiles);\nprint_r($m->mInlineList);\n" }, { "answer_id": 67923886, "author": "Adam Winter", "author_id": 10664600, "author_profile": "https://Stackoverflow.com/users/10664600", "pm_score": 0, "selected": false, "text": "FROM php:7.4-apache\nWORKDIR /var/www/html\nEXPOSE 80\nWORKDIR /var/www\nRUN chown -R www-data html\nRUN docker-php-ext-install mysqli\nRUN pear install --alldeps mail\nRUN pear install Mail_mimeDecode\n <?php\n\nrequire_once \"/usr/local/lib/php/Mail.php\";\nrequire_once \"/usr/local/lib/php/Mail/mimeDecode.php\";\n\n$mailfiles = ['/var/www/mail/mailFile1','/var/www/mail/mailFile2'];\n\nforeach($mailfiles as $filename){\n $theFile = fopen($filename, \"r\") or die(\"Unable to open file!\");\n $rawEmail = fread($theFile, filesize($filename));\n fclose($theFile);\n\n $args = [];\n $args['include_bodies'] = true;\n $args['decode_bodies'] = FALSE;\n $args['decode_headers'] = FALSE;\n $objMail = new Mail_mimeDecode($rawEmail);\n $return = $objMail->decode($args);\n\n if (PEAR::isError($return)) {\n echo(\"<p>\" . $return->getMessage() . \"</p>\");\n var_dump($return);\n } else {\n //echo(\"No error in PEAR::isError(return)\");\n }\n\n if($return->body){\n $decoded = base64_decode($return->body, true);\n var_dump($decoded);\n }//end if(body)\n\n}//end foreach(mailfiles as file)\n\n\n?>\n" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/12905", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9/" ]
12,906
<p>I need to know how much space occupies all the databases inside an SQL Server 2000. I did some research but could not found any script to help me out.</p>
[ { "answer_id": 12915, "author": "Jon Galloway", "author_id": 5, "author_profile": "https://Stackoverflow.com/users/5", "pm_score": 4, "selected": true, "text": "USE master;\nGO\n\nIF OBJECT_ID('dbo.sp_SDS', 'P') IS NOT NULL\n DROP PROCEDURE dbo.sp_SDS;\nGO\n\nCREATE PROCEDURE dbo.sp_SDS \n @TargetDatabase sysname = NULL, -- NULL: all dbs\n @Level varchar(10) = 'Database', -- or \"File\"\n @UpdateUsage bit = 0, -- default no update\n @Unit char(2) = 'MB' -- Megabytes, Kilobytes or Gigabytes\nAS\n\n/**************************************************************************************************\n**\n** author: Richard Ding\n** date: 4/8/2008\n** usage: list db size AND path w/o SUMmary\n** test code: sp_SDS -- default behavior\n** sp_SDS 'maAster'\n** sp_SDS NULL, NULL, 0\n** sp_SDS NULL, 'file', 1, 'GB'\n** sp_SDS 'Test_snapshot', 'Database', 1\n** sp_SDS 'Test', 'File', 0, 'kb'\n** sp_SDS 'pfaids', 'Database', 0, 'gb'\n** sp_SDS 'tempdb', NULL, 1, 'kb'\n** \n**************************************************************************************************/\n\nSET NOCOUNT ON;\n\nIF @TargetDatabase IS NOT NULL AND DB_ID(@TargetDatabase) IS NULL\n BEGIN\n RAISERROR(15010, -1, -1, @TargetDatabase);\n RETURN (-1)\n END\n\nIF OBJECT_ID('tempdb.dbo.##Tbl_CombinedInfo', 'U') IS NOT NULL\n DROP TABLE dbo.##Tbl_CombinedInfo;\n\nIF OBJECT_ID('tempdb.dbo.##Tbl_DbFileStats', 'U') IS NOT NULL\n DROP TABLE dbo.##Tbl_DbFileStats;\n\nIF OBJECT_ID('tempdb.dbo.##Tbl_ValidDbs', 'U') IS NOT NULL\n DROP TABLE dbo.##Tbl_ValidDbs;\n\nIF OBJECT_ID('tempdb.dbo.##Tbl_Logs', 'U') IS NOT NULL\n DROP TABLE dbo.##Tbl_Logs;\n\nCREATE TABLE dbo.##Tbl_CombinedInfo (\n DatabaseName sysname NULL, \n [type] VARCHAR(10) NULL, \n LogicalName sysname NULL,\n T dec(10, 2) NULL,\n U dec(10, 2) NULL,\n [U(%)] dec(5, 2) NULL,\n F dec(10, 2) NULL,\n [F(%)] dec(5, 2) NULL,\n PhysicalName sysname NULL );\n\nCREATE TABLE dbo.##Tbl_DbFileStats (\n Id int identity, \n DatabaseName sysname NULL, \n FileId int NULL, \n FileGroup int NULL, \n TotalExtents bigint NULL, \n UsedExtents bigint NULL, \n Name sysname NULL, \n FileName varchar(255) NULL );\n\nCREATE TABLE dbo.##Tbl_ValidDbs (\n Id int identity, \n Dbname sysname NULL );\n\nCREATE TABLE dbo.##Tbl_Logs (\n DatabaseName sysname NULL, \n LogSize dec (10, 2) NULL, \n LogSpaceUsedPercent dec (5, 2) NULL,\n Status int NULL );\n\nDECLARE @Ver varchar(10), \n @DatabaseName sysname, \n @Ident_last int, \n @String varchar(2000),\n @BaseString varchar(2000);\n\nSELECT @DatabaseName = '', \n @Ident_last = 0, \n @String = '', \n @Ver = CASE WHEN @@VERSION LIKE '%9.0%' THEN 'SQL 2005' \n WHEN @@VERSION LIKE '%8.0%' THEN 'SQL 2000' \n WHEN @@VERSION LIKE '%10.0%' THEN 'SQL 2008' \n END;\n\nSELECT @BaseString = \n' SELECT DB_NAME(), ' + \nCASE WHEN @Ver = 'SQL 2000' THEN 'CASE WHEN status & 0x40 = 0x40 THEN ''Log'' ELSE ''Data'' END' \n ELSE ' CASE type WHEN 0 THEN ''Data'' WHEN 1 THEN ''Log'' WHEN 4 THEN ''Full-text'' ELSE ''reserved'' END' END + \n', name, ' + \nCASE WHEN @Ver = 'SQL 2000' THEN 'filename' ELSE 'physical_name' END + \n', size*8.0/1024.0 FROM ' + \nCASE WHEN @Ver = 'SQL 2000' THEN 'sysfiles' ELSE 'sys.database_files' END + \n' WHERE '\n+ CASE WHEN @Ver = 'SQL 2000' THEN ' HAS_DBACCESS(DB_NAME()) = 1' ELSE 'state_desc = ''ONLINE''' END + '';\n\nSELECT @String = 'INSERT INTO dbo.##Tbl_ValidDbs SELECT name FROM ' + \n CASE WHEN @Ver = 'SQL 2000' THEN 'master.dbo.sysdatabases' \n WHEN @Ver IN ('SQL 2005', 'SQL 2008') THEN 'master.sys.databases' \n END + ' WHERE HAS_DBACCESS(name) = 1 ORDER BY name ASC';\nEXEC (@String);\n\nINSERT INTO dbo.##Tbl_Logs EXEC ('DBCC SQLPERF (LOGSPACE) WITH NO_INFOMSGS');\n\n-- For data part\nIF @TargetDatabase IS NOT NULL\n BEGIN\n SELECT @DatabaseName = @TargetDatabase;\n IF @UpdateUsage <> 0 AND DATABASEPROPERTYEX (@DatabaseName,'Status') = 'ONLINE' \n AND DATABASEPROPERTYEX (@DatabaseName, 'Updateability') <> 'READ_ONLY'\n BEGIN\n SELECT @String = 'USE [' + @DatabaseName + '] DBCC UPDATEUSAGE (0)';\n PRINT '*** ' + @String + ' *** ';\n EXEC (@String);\n PRINT '';\n END\n\n SELECT @String = 'INSERT INTO dbo.##Tbl_CombinedInfo (DatabaseName, type, LogicalName, PhysicalName, T) ' + @BaseString; \n\n INSERT INTO dbo.##Tbl_DbFileStats (FileId, FileGroup, TotalExtents, UsedExtents, Name, FileName)\n EXEC ('USE [' + @DatabaseName + '] DBCC SHOWFILESTATS WITH NO_INFOMSGS');\n EXEC ('USE [' + @DatabaseName + '] ' + @String);\n\n UPDATE dbo.##Tbl_DbFileStats SET DatabaseName = @DatabaseName; \n END\nELSE\n BEGIN\n WHILE 1 = 1\n BEGIN\n SELECT TOP 1 @DatabaseName = Dbname FROM dbo.##Tbl_ValidDbs WHERE Dbname > @DatabaseName ORDER BY Dbname ASC;\n IF @@ROWCOUNT = 0\n BREAK;\n IF @UpdateUsage <> 0 AND DATABASEPROPERTYEX (@DatabaseName, 'Status') = 'ONLINE' \n AND DATABASEPROPERTYEX (@DatabaseName, 'Updateability') <> 'READ_ONLY'\n BEGIN\n SELECT @String = 'DBCC UPDATEUSAGE (''' + @DatabaseName + ''') ';\n PRINT '*** ' + @String + '*** ';\n EXEC (@String);\n PRINT '';\n END\n\n SELECT @Ident_last = ISNULL(MAX(Id), 0) FROM dbo.##Tbl_DbFileStats;\n\n SELECT @String = 'INSERT INTO dbo.##Tbl_CombinedInfo (DatabaseName, type, LogicalName, PhysicalName, T) ' + @BaseString; \n\n EXEC ('USE [' + @DatabaseName + '] ' + @String);\n\n INSERT INTO dbo.##Tbl_DbFileStats (FileId, FileGroup, TotalExtents, UsedExtents, Name, FileName)\n EXEC ('USE [' + @DatabaseName + '] DBCC SHOWFILESTATS WITH NO_INFOMSGS');\n\n UPDATE dbo.##Tbl_DbFileStats SET DatabaseName = @DatabaseName WHERE Id BETWEEN @Ident_last + 1 AND @@IDENTITY;\n END\n END\n\n-- set used size for data files, do not change total obtained from sys.database_files as it has for log files\nUPDATE dbo.##Tbl_CombinedInfo \nSET U = s.UsedExtents*8*8/1024.0 \nFROM dbo.##Tbl_CombinedInfo t JOIN dbo.##Tbl_DbFileStats s \nON t.LogicalName = s.Name AND s.DatabaseName = t.DatabaseName;\n\n-- set used size and % values for log files:\nUPDATE dbo.##Tbl_CombinedInfo \nSET [U(%)] = LogSpaceUsedPercent, \nU = T * LogSpaceUsedPercent/100.0\nFROM dbo.##Tbl_CombinedInfo t JOIN dbo.##Tbl_Logs l \nON l.DatabaseName = t.DatabaseName \nWHERE t.type = 'Log';\n\nUPDATE dbo.##Tbl_CombinedInfo SET F = T - U, [U(%)] = U*100.0/T;\n\nUPDATE dbo.##Tbl_CombinedInfo SET [F(%)] = F*100.0/T;\n\nIF UPPER(ISNULL(@Level, 'DATABASE')) = 'FILE'\n BEGIN\n IF @Unit = 'KB'\n UPDATE dbo.##Tbl_CombinedInfo\n SET T = T * 1024, U = U * 1024, F = F * 1024;\n\n IF @Unit = 'GB'\n UPDATE dbo.##Tbl_CombinedInfo\n SET T = T / 1024, U = U / 1024, F = F / 1024;\n\n SELECT DatabaseName AS 'Database',\n type AS 'Type',\n LogicalName,\n T AS 'Total',\n U AS 'Used',\n [U(%)] AS 'Used (%)',\n F AS 'Free',\n [F(%)] AS 'Free (%)',\n PhysicalName\n FROM dbo.##Tbl_CombinedInfo \n WHERE DatabaseName LIKE ISNULL(@TargetDatabase, '%') \n ORDER BY DatabaseName ASC, type ASC;\n\n SELECT CASE WHEN @Unit = 'GB' THEN 'GB' WHEN @Unit = 'KB' THEN 'KB' ELSE 'MB' END AS 'SUM',\n SUM (T) AS 'TOTAL', SUM (U) AS 'USED', SUM (F) AS 'FREE' FROM dbo.##Tbl_CombinedInfo;\n END\n\nIF UPPER(ISNULL(@Level, 'DATABASE')) = 'DATABASE'\n BEGIN\n DECLARE @Tbl_Final TABLE (\n DatabaseName sysname NULL,\n TOTAL dec (10, 2),\n [=] char(1),\n used dec (10, 2),\n [used (%)] dec (5, 2),\n [+] char(1),\n free dec (10, 2),\n [free (%)] dec (5, 2),\n [==] char(2),\n Data dec (10, 2),\n Data_Used dec (10, 2),\n [Data_Used (%)] dec (5, 2),\n Data_Free dec (10, 2),\n [Data_Free (%)] dec (5, 2),\n [++] char(2),\n Log dec (10, 2),\n Log_Used dec (10, 2),\n [Log_Used (%)] dec (5, 2),\n Log_Free dec (10, 2),\n [Log_Free (%)] dec (5, 2) );\n\n INSERT INTO @Tbl_Final\n SELECT x.DatabaseName, \n x.Data + y.Log AS 'TOTAL', \n '=' AS '=', \n x.Data_Used + y.Log_Used AS 'U',\n (x.Data_Used + y.Log_Used)*100.0 / (x.Data + y.Log) AS 'U(%)',\n '+' AS '+',\n x.Data_Free + y.Log_Free AS 'F',\n (x.Data_Free + y.Log_Free)*100.0 / (x.Data + y.Log) AS 'F(%)',\n '==' AS '==',\n x.Data, \n x.Data_Used, \n x.Data_Used*100/x.Data AS 'D_U(%)',\n x.Data_Free, \n x.Data_Free*100/x.Data AS 'D_F(%)',\n '++' AS '++', \n y.Log, \n y.Log_Used, \n y.Log_Used*100/y.Log AS 'L_U(%)',\n y.Log_Free, \n y.Log_Free*100/y.Log AS 'L_F(%)'\n FROM \n ( SELECT d.DatabaseName, \n SUM(d.T) AS 'Data', \n SUM(d.U) AS 'Data_Used', \n SUM(d.F) AS 'Data_Free' \n FROM dbo.##Tbl_CombinedInfo d WHERE d.type = 'Data' GROUP BY d.DatabaseName ) AS x\n JOIN \n ( SELECT l.DatabaseName, \n SUM(l.T) AS 'Log', \n SUM(l.U) AS 'Log_Used', \n SUM(l.F) AS 'Log_Free' \n FROM dbo.##Tbl_CombinedInfo l WHERE l.type = 'Log' GROUP BY l.DatabaseName ) AS y\n ON x.DatabaseName = y.DatabaseName;\n\n IF @Unit = 'KB'\n UPDATE @Tbl_Final SET TOTAL = TOTAL * 1024,\n used = used * 1024,\n free = free * 1024,\n Data = Data * 1024,\n Data_Used = Data_Used * 1024,\n Data_Free = Data_Free * 1024,\n Log = Log * 1024,\n Log_Used = Log_Used * 1024,\n Log_Free = Log_Free * 1024;\n\n IF @Unit = 'GB'\n UPDATE @Tbl_Final SET TOTAL = TOTAL / 1024,\n used = used / 1024,\n free = free / 1024,\n Data = Data / 1024,\n Data_Used = Data_Used / 1024,\n Data_Free = Data_Free / 1024,\n Log = Log / 1024,\n Log_Used = Log_Used / 1024,\n Log_Free = Log_Free / 1024;\n\n DECLARE @GrantTotal dec(11, 2);\n SELECT @GrantTotal = SUM(TOTAL) FROM @Tbl_Final;\n\n SELECT \n CONVERT(dec(10, 2), TOTAL*100.0/@GrantTotal) AS 'WEIGHT (%)', \n DatabaseName AS 'DATABASE',\n CONVERT(VARCHAR(12), used) + ' (' + CONVERT(VARCHAR(12), [used (%)]) + ' %)' AS 'USED (%)',\n [+],\n CONVERT(VARCHAR(12), free) + ' (' + CONVERT(VARCHAR(12), [free (%)]) + ' %)' AS 'FREE (%)',\n [=],\n TOTAL, \n [=],\n CONVERT(VARCHAR(12), Data) + ' (' + CONVERT(VARCHAR(12), Data_Used) + ', ' + \n CONVERT(VARCHAR(12), [Data_Used (%)]) + '%)' AS 'DATA (used, %)',\n [+],\n CONVERT(VARCHAR(12), Log) + ' (' + CONVERT(VARCHAR(12), Log_Used) + ', ' + \n CONVERT(VARCHAR(12), [Log_Used (%)]) + '%)' AS 'LOG (used, %)'\n FROM @Tbl_Final \n WHERE DatabaseName LIKE ISNULL(@TargetDatabase, '%')\n ORDER BY DatabaseName ASC;\n\n IF @TargetDatabase IS NULL\n SELECT CASE WHEN @Unit = 'GB' THEN 'GB' WHEN @Unit = 'KB' THEN 'KB' ELSE 'MB' END AS 'SUM', \n SUM (used) AS 'USED', \n SUM (free) AS 'FREE', \n SUM (TOTAL) AS 'TOTAL', \n SUM (Data) AS 'DATA', \n SUM (Log) AS 'LOG' \n FROM @Tbl_Final;\n END\n\nRETURN (0)\n\nGO\n" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/12906", "https://Stackoverflow.com", "https://Stackoverflow.com/users/296/" ]
12,927
<p>I am calling a vendor's Java API, and on some servers it appears that the JVM goes into a low priority polling loop after logging into the API (CPU at 100% usage). The same app on other servers does not exhibit this behavior. This happens on WebSphere and Tomcat. The environment is tricky to set up so it is difficult to try to do something like profiling within Eclipse.</p> <p>Is there a way to profile (or some other method of inspecting) an existing Java app running in Tomcat to find out what methods are being executed while it's in this spinwait kind of state? The app is only executing one method when it gets in this state (vendor's method). Vendor can't replicate the behavior (of course).</p> <hr> <p>Update: </p> <p>Using JConsole I was able to determine who was running and what they were doing. It took me a few hours to then figure out why it was doing it. The problem ended up being that the vendor's API jar that was being used did not match exactly to the the database configuration that it was using. It was defaulting to having tracing and performance monitoring enabled on the servers that had the slight mis-match in configuration. I used a different jar and all is well.</p> <p>So thanks, Joshua, for your answer. JConsole was extremely easy to setup and use to monitor an existing application. </p> <p>@Cringe - I did some experimenting with some of the options you suggested. I had some problems with getting JProfiler set up, it looks good (but pricey). Going forward I went ahead and added the Eclipse Profiler plugin and I'll be looking over the different open source profilers to compare functionality.</p>
[ { "answer_id": 24082, "author": "Marcel", "author_id": 2554, "author_profile": "https://Stackoverflow.com/users/2554", "pm_score": 2, "selected": false, "text": "kill -3 <process id>" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/12927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/791/" ]
12,936
<p>Does anybody have experience working with PHP accelerators such as <a href="http://turck-mmcache.sourceforge.net/" rel="noreferrer">MMCache</a> or <a href="http://www.zend.com/en/" rel="noreferrer">Zend Accelerator</a>? I'd like to know if using either of these makes PHP comparable to <em>faster</em> web-technologies. Also, are there trade offs for using these?</p>
[ { "answer_id": 31990, "author": "John Douthat", "author_id": 2774, "author_profile": "https://Stackoverflow.com/users/2774", "pm_score": 1, "selected": false, "text": "yum install php-devel httpd-devel php-pear\npecl install apc \necho \"extension=apc.so\" > /etc/php.d/apc.ini\n# if you're using SELinux:\nchcon \"system_u:object_r:textrel_shlib_t\" /usr/lib/php/modules/apc.so\n/etc/init.d/httpd restart\n" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/12936", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40/" ]
12,982
<p>It's 2008, and I'm still torn on this one. So I'm developing a web method that needs a complex type passed into it and returned from it. The two options I'm toying with are:</p> <ol> <li><p>Pass and return <em>actual</em> business objects with both data and behavior. When wsdl.exe is run, it will automatically create proxy classes that contain just the data portion, and these will be automatically converted to and from my real business objects on the server side. On the client side, they will only get to use the dumb proxy type, and they will have to map them into some real business objects as they see fit. A big drawback here is that if I "own" both the server and client side, and I want to use the same set of real business objects, I can run into certain headaches with name conflicts, etc. (Since the real objects and the proxies are named the same.)</p></li> <li><p>Forget trying to pass "real" business objects. Instead, just create simple DataTransfer objects which I will map back and forth to my real business objects manually. They still get copied to new proxy objects by wsdl.exe anyway, but at least I'm not tricking myself into thinking that web services can natively handle objects with business logic in them.</p></li> </ol> <p>By the way - Does anyone know how to tell wsdl.exe to <em>not</em> make a copy of the object? Shouldn't we be able to just tell it, "Hey, use this existing type right over here. Don't copy it!"</p> <p>Anyway, I've kinda settled on #2 for now, but I'm curious what you all think. I have a feeling there are <em>way</em> better ways to do this in general, and I may not even be totally accurate on all my points, so please let me know what your experiences have been.</p> <p><strong>Update</strong>: I just found out that VS 2008 has an option to reuse existing types when adding a "Service Reference", rather than creating brand new identical type in the proxy file. Sweet.</p>
[ { "answer_id": 12990, "author": "Darren Kopp", "author_id": 77, "author_profile": "https://Stackoverflow.com/users/77", "pm_score": 2, "selected": false, "text": "public class TransferObject\n{\n public string Type { get; set; }\n public byte[] Data { get; set; }\n}\n public static class CompressedSerializer\n{\n /// <summary>\n /// Decompresses the specified compressed data.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"compressedData\">The compressed data.</param>\n /// <returns></returns>\n public static T Decompress<T>(byte[] compressedData) where T : class\n {\n T result = null;\n using (MemoryStream memory = new MemoryStream())\n {\n memory.Write(compressedData, 0, compressedData.Length);\n memory.Position = 0L;\n\n using (GZipStream zip= new GZipStream(memory, CompressionMode.Decompress, true))\n {\n zip.Flush();\n var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();\n result = formatter.Deserialize(zip) as T;\n }\n }\n\n return result;\n }\n\n /// <summary>\n /// Compresses the specified data.\n /// </summary>\n /// <typeparam name=\"T\"></typeparam>\n /// <param name=\"data\">The data.</param>\n /// <returns></returns>\n public static byte[] Compress<T>(T data)\n {\n byte[] result = null;\n using (MemoryStream memory = new MemoryStream())\n {\n using (GZipStream zip= new GZipStream(memory, CompressionMode.Compress, true))\n {\n var formatter = new System.Runtime.Serialization.Formatters.Binary.BinaryFormatter();\n formatter.Serialize(zip, data);\n }\n\n result = memory.ToArray();\n }\n\n return result;\n }\n}\n [WebMethod]\npublic void ReceiveData(TransferObject data)\n{\n Type originType = Type.GetType(data.Type);\n object item = CompressedSerializer.Decompress<object>(data.Data);\n}\n" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/12982", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1436/" ]
13,000
<p>I want to define something like this in <em>php</em>:</p> <pre><code>$EL = "\n&lt;br /&gt;\n"; </code></pre> <p>and then use that variable as an "endline" marker all over my site, like this:</p> <pre><code>echo "Blah blah blah{$EL}"; </code></pre> <p>How do I define $EL once (in only 1 file), include it on every page on my site, and <em>not</em> have to reference it using the (strangely backwards) <code>global $EL;</code> statement in every page function?</p>
[ { "answer_id": 13003, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 4, "selected": true, "text": " include 'header.php';\n" }, { "answer_id": 13008, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": -1, "selected": false, "text": "<?php\n$EL = \"\\n<br />\\n\";\n?>\n require 'config.php'\n" }, { "answer_id": 13075, "author": "UnkwnTech", "author_id": 115, "author_profile": "https://Stackoverflow.com/users/115", "pm_score": 0, "selected": false, "text": "function myFunc()\n {\nrequire 'config.php';\n//Variables from config are available now.\n }\n" }, { "answer_id": 13094, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 1, "selected": false, "text": "MyClass::MY_CONST\n <br /> echo \"Blah Blah Blah\\n<br />\\n\";\n <?php\nif($condition) {\n?>\n<p>Blah blah blah\n<br />\n</p>\n<?php\n}\n?>\n" }, { "answer_id": 53094, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 0, "selected": false, "text": "<?php\n\nclass SITE {\n public static $el;\n}\n\nSITE::$el = \"\\n<br />\\n\";\n\nfunction Test() {\n echo SITE::$el;\n}\n\nTest();\n\n?>\n <br />" }, { "answer_id": 4432971, "author": "dbwebtek", "author_id": 538362, "author_profile": "https://Stackoverflow.com/users/538362", "pm_score": 2, "selected": false, "text": "\ndefine ('el','\\n\\<\\br/>\\n');\n" }, { "answer_id": 59923336, "author": "Progrock", "author_id": 3392762, "author_profile": "https://Stackoverflow.com/users/3392762", "pm_score": 0, "selected": false, "text": "<?php\ndefine('FOO', 'badger');\n echo 'this is my '. FOO;\n" }, { "answer_id": 63679111, "author": "Ezekiel Arin", "author_id": 14135718, "author_profile": "https://Stackoverflow.com/users/14135718", "pm_score": 0, "selected": false, "text": "Include 'functions.php';\nrequire('functions');\n" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/13000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/103/" ]
13,021
<p>I've frequently encountered sites that put all of their JavaScript inside a <code>namespace</code> structure along the lines of:</p> <pre><code>namespaces = { com : { example: { example.com's data} } </code></pre> <p>However, setting this up safely with respect to other namespaced frameworks seems to require a relatively hefty amount of code (defined as > 2 lines). I was wondering whether anyone knows of a concise way to do this? Furthermore, whether there's a relatively standard/consistent way to structure it? For example, is the <code>com</code> namespace directly attached to the global object, or is it attached through a namespace object?</p> <p>[Edit: whoops, obviously <code>{com = { ... } }</code> wouldn't accomplish anything close to what I intended, thanks to Shog9 for pointing that out.] </p>
[ { "answer_id": 13193, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 5, "selected": true, "text": "var namespaces = { com: { example: { /* example.com's data */ } } }\n namespaces com example var com_example_data = { /* example.com's data */ };\n com_example = com_example || {};\ncom_example.flags = com_example.flags || { active: false, restricted: true};\n\ncom_example.ops = com_example.ops || (function()\n {\n var launchCodes = \"38925491753824\"; // hidden / private\n return {\n activate: function() { /* ... */ },\n destroyTheWorld: function() { /* ... */ }\n };\n })();\n" }, { "answer_id": 13583, "author": "Polsonby", "author_id": 137, "author_profile": "https://Stackoverflow.com/users/137", "pm_score": 3, "selected": false, "text": "var FP = {};\nFP.module = {};\nFP.module.property = 'foo';\n" }, { "answer_id": 14085, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "var namespaces$com$example = \"data\"; \n" }, { "answer_id": 14748, "author": "Ricky", "author_id": 653, "author_profile": "https://Stackoverflow.com/users/653", "pm_score": 3, "selected": false, "text": "if(!window.NameSpace) {\n NameSpace = {};\n}\n var NameSpace = window.NameSpace || {};\n" }, { "answer_id": 1015213, "author": "dfa", "author_id": 89266, "author_profile": "https://Stackoverflow.com/users/89266", "pm_score": 1, "selected": false, "text": "(function() {\n var a = 'Invisible outside of anonymous function';\n function invisibleOutside() {\n }\n\n function visibleOutside() {\n }\n window.visibleOutside = visibleOutside;\n\n var html = '--INSIDE Anonymous--';\n html += '<br/> typeof invisibleOutside: ' + typeof invisibleOutside;\n html += '<br/> typeof visibleOutside: ' + typeof visibleOutside;\n contentDiv.innerHTML = html + '<br/><br/>';\n})();\n\nvar html = '--OUTSIDE Anonymous--';\nhtml += '<br/> typeof invisibleOutside: ' + typeof invisibleOutside;\nhtml += '<br/> typeof visibleOutside: ' + typeof visibleOutside;\ncontentDiv.innerHTML += html + '<br/>';​\n" }, { "answer_id": 9847719, "author": "Paul Sweatte", "author_id": 1113772, "author_profile": "https://Stackoverflow.com/users/1113772", "pm_score": 0, "selected": false, "text": "this var foo = { bar: function(){return this.name; }, name: \"rodimus\" }\nvar baz = { bar: function(){return this.name; }, name: \"optimus\" }\n\nconsole.log(foo.bar());\nconsole.log(baz.bar()); name var foo = { bar: function rodimus(){return this; } }\nvar baz = { bar: function optimus(){return this; } }\n\nconsole.log(foo.bar.name);\nconsole.log(baz.bar.name); this var foo = { bar: function rodimus(){return rodimus; } }\nvar baz = { bar: function optimus(){return optimus; } }\n\nconsole.log(foo.bar.name);\nconsole.log(baz.bar.name); RegExp Object hasOwnProperty var foo = RegExp(/bar/);\n \n/* Add property */\nfoo.name = \"alpha\";\n\ndocument.body.innerHTML = String(\"<pre>\" + [\"name\", \"value\", \"namespace\"] + \"</pre>\").replace(/,/g, \"&#09;\");\n\n/* Check type */\nif (foo.hasOwnProperty(\"name\")) \n {\n document.body.innerHTML += String(\"<pre>\" + [\"foo\", String(foo.exec(foo)), foo.name] + \"</pre>\").replace(/,/g, \"&#09;\");\n }\n\n/* Fallback to atomic value */\nelse \n {\n foo = \"baz\";\n }\n\nvar counter = Object(1);\n\n/* Add property */\ncounter.name = \"beta\";\n\nif (counter.hasOwnProperty(\"name\")) \n {\n document.body.innerHTML += String(\"<pre>\" + [\"counter\", Number(counter), counter.name] + \"</pre>\").replace(/,/g, \"&#09;\");\n } \nelse \n {\n /* Fallback to atomic value */\n counter = 0;\n } toString" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/13021", "https://Stackoverflow.com", "https://Stackoverflow.com/users/784/" ]
13,049
<p>What's the difference between struct and class in .NET?</p>
[ { "answer_id": 13053, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 6, "selected": false, "text": "struct MyStruct \n{\n string MyProperty { get; set; }\n}\n\nvoid ChangeMyStruct(MyStruct input) \n{ \n input.MyProperty = \"new value\";\n}\n\n...\n\n// Create value type\nMyStruct testStruct = new MyStruct { MyProperty = \"initial value\" }; \n\nChangeMyStruct(testStruct);\n\n// Value of testStruct.MyProperty is still \"initial value\"\n// - the method changed a new copy of the structure.\n class MyClass \n{\n string MyProperty { get; set; }\n}\n\nvoid ChangeMyClass(MyClass input) \n{ \n input.MyProperty = \"new value\";\n}\n\n...\n\n// Create reference type\nMyClass testClass = new MyClass { MyProperty = \"initial value\" };\n\nChangeMyClass(testClass);\n\n// Value of testClass.MyProperty is now \"new value\" \n// - the method changed the instance passed.\n" }, { "answer_id": 13132, "author": "denis phillips", "author_id": 748, "author_profile": "https://Stackoverflow.com/users/748", "pm_score": 2, "selected": false, "text": "int? value = null;\nvalue = 1;\n" }, { "answer_id": 6812085, "author": "Zain Ali", "author_id": 538789, "author_profile": "https://Stackoverflow.com/users/538789", "pm_score": 3, "selected": false, "text": "class DefaultConstructor\n{\n static void Eg()\n {\n Direct yes = new Direct(); // Always compiles OK\n InDirect maybe = new InDirect(); // Compiles if constructor exists and is accessible\n //...\n }\n}\n class NonInstantiable\n{\n private NonInstantiable() // OK\n {\n }\n}\n\nstruct Direct\n{\n private Direct() // Compile-time error\n {\n }\n}\n struct Direct\n{\n ~Direct() {} // Compile-time error\n}\nclass InDirect\n{\n ~InDirect() {} // Compiles OK\n}\n\nAnd the CIL for ~Indirect() looks like this:\n\n.method family hidebysig virtual instance void\n Finalize() cil managed\n{\n // ...\n} // end of method Indirect::Finalize\n" }, { "answer_id": 23930370, "author": "Arijit Mukherjee", "author_id": 3336204, "author_profile": "https://Stackoverflow.com/users/3336204", "pm_score": 2, "selected": false, "text": " static void Main(string[] args)\n {\n //Struct\n myStruct objStruct = new myStruct();\n objStruct.x = 10;\n Console.WriteLine(\"Initial value of Struct Object is: \" + objStruct.x);\n Console.WriteLine();\n methodStruct(objStruct);\n Console.WriteLine();\n Console.WriteLine(\"After Method call value of Struct Object is: \" + objStruct.x);\n Console.WriteLine();\n\n //Class\n myClass objClass = new myClass(10);\n Console.WriteLine(\"Initial value of Class Object is: \" + objClass.x);\n Console.WriteLine();\n methodClass(objClass);\n Console.WriteLine();\n Console.WriteLine(\"After Method call value of Class Object is: \" + objClass.x);\n Console.Read();\n }\n static void methodStruct(myStruct newStruct)\n {\n newStruct.x = 20;\n Console.WriteLine(\"Inside Struct Method\");\n Console.WriteLine(\"Inside Method value of Struct Object is: \" + newStruct.x);\n }\n static void methodClass(myClass newClass)\n {\n newClass.x = 20;\n Console.WriteLine(\"Inside Class Method\");\n Console.WriteLine(\"Inside Method value of Class Object is: \" + newClass.x);\n }\n public struct myStruct\n {\n public int x;\n public myStruct(int xCons)\n {\n this.x = xCons;\n }\n }\n public class myClass\n {\n public int x;\n public myClass(int xCons)\n {\n this.x = xCons;\n }\n }\n" }, { "answer_id": 32204716, "author": "Will Calderwood", "author_id": 654070, "author_profile": "https://Stackoverflow.com/users/654070", "pm_score": 4, "selected": false, "text": "[struct][struct][struct][struct][struct][struct][struct][struct] [pointer][pointer][pointer][pointer][pointer][pointer][pointer][pointer] private struct PerformanceStruct\n {\n public int i1;\n public int i2;\n }\n\n private class PerformanceClass\n {\n public int i1;\n public int i2;\n }\n\n private static void DoTest()\n {\n var structArray = new PerformanceStruct[100000000];\n var classArray = new PerformanceClass[structArray.Length];\n\n for (var i = 0; i < structArray.Length; i++)\n {\n structArray[i] = new PerformanceStruct();\n classArray[i] = new PerformanceClass();\n }\n\n long total = 0;\n var sw = new Stopwatch();\n sw.Start();\n for (var loops = 0; loops < 100; loops++)\n for (var i = 0; i < structArray.Length; i++)\n {\n total += structArray[i].i1 + structArray[i].i2;\n }\n\n sw.Stop();\n Console.WriteLine($\"Struct Time: {sw.ElapsedMilliseconds}\");\n sw = new Stopwatch();\n sw.Start();\n for (var loops = 0; loops < 100; loops++)\n for (var i = 0; i < classArray.Length; i++)\n {\n total += classArray[i].i1 + classArray[i].i2;\n }\n\n Console.WriteLine($\"Class Time: {sw.ElapsedMilliseconds}\");\n }\n" }, { "answer_id": 45462416, "author": "Ning", "author_id": 8360058, "author_profile": "https://Stackoverflow.com/users/8360058", "pm_score": 3, "selected": false, "text": "Equals class A{\n public int a, b;\n}\nstruct B{\n public int a, b;\n}\n static void Main{\n A c1 = new A(), c2 = new A();\n c1.a = c1.b = c2.a = c2.b = 1;\n B s1 = new B(), s2 = new B();\n s1.a = s1.b = s2.a = s2.b = 1;\n}\n s1.Equals(s2) // true\ns1.Equals(c1) // false\nc1.Equals(c2) // false\nc1 == c2 // false\n" }, { "answer_id": 47864451, "author": "Roman Pokrovskij", "author_id": 506147, "author_profile": "https://Stackoverflow.com/users/506147", "pm_score": 2, "selected": false, "text": "BenchmarkDotNet=v0.10.10, OS=Windows 10 Redstone 2 [1703, Creators Update] (10.0.15063.726)\nProcessor=Intel Core i5-2500K CPU 3.30GHz (Sandy Bridge), ProcessorCount=4\nFrequency=3233540 Hz, Resolution=309.2586 ns, Timer=TSC\n.NET Core SDK=2.0.3\n [Host] : .NET Core 2.0.3 (Framework 4.6.25815.02), 64bit RyuJIT\n Clr : .NET Framework 4.7 (CLR 4.0.30319.42000), 64bit RyuJIT-v4.7.2115.0\n Core : .NET Core 2.0.3 (Framework 4.6.25815.02), 64bit RyuJIT\n\n\n Method | Job | Runtime | Mean | Error | StdDev | Min | Max | Median | Rank | Gen 0 | Allocated |\n------------------ |----- |-------- |---------:|----------:|----------:|---------:|---------:|---------:|-----:|-------:|----------:|\n TestStructReturn | Clr | Clr | 17.57 ns | 0.1960 ns | 0.1834 ns | 17.25 ns | 17.89 ns | 17.55 ns | 4 | 0.0127 | 40 B |\n TestClassReturn | Clr | Clr | 21.93 ns | 0.4554 ns | 0.5244 ns | 21.17 ns | 23.26 ns | 21.86 ns | 5 | 0.0229 | 72 B |\n TestStructReturn8 | Clr | Clr | 38.99 ns | 0.8302 ns | 1.4097 ns | 37.36 ns | 42.35 ns | 38.50 ns | 8 | 0.0127 | 40 B |\n TestClassReturn8 | Clr | Clr | 23.69 ns | 0.5373 ns | 0.6987 ns | 22.70 ns | 25.24 ns | 23.37 ns | 6 | 0.0305 | 96 B |\n TestStructReturn | Core | Core | 12.28 ns | 0.1882 ns | 0.1760 ns | 11.92 ns | 12.57 ns | 12.30 ns | 1 | 0.0127 | 40 B |\n TestClassReturn | Core | Core | 15.33 ns | 0.4343 ns | 0.4063 ns | 14.83 ns | 16.44 ns | 15.31 ns | 2 | 0.0229 | 72 B |\n TestStructReturn8 | Core | Core | 34.11 ns | 0.7089 ns | 1.4954 ns | 31.52 ns | 36.81 ns | 34.03 ns | 7 | 0.0127 | 40 B |\n TestClassReturn8 | Core | Core | 17.04 ns | 0.2299 ns | 0.2150 ns | 16.68 ns | 17.41 ns | 16.98 ns | 3 | 0.0305 | 96 B |\n using System;\nusing System.Text;\nusing System.Collections.Generic;\nusing BenchmarkDotNet.Attributes;\nusing BenchmarkDotNet.Attributes.Columns;\nusing BenchmarkDotNet.Attributes.Exporters;\nusing BenchmarkDotNet.Attributes.Jobs;\nusing DashboardCode.Routines.Json;\n\nnamespace Benchmark\n{\n //[Config(typeof(MyManualConfig))]\n [RankColumn, MinColumn, MaxColumn, StdDevColumn, MedianColumn]\n [ClrJob, CoreJob]\n [HtmlExporter, MarkdownExporter]\n [MemoryDiagnoser]\n public class BenchmarkStructOrClass\n {\n static TestStruct testStruct = new TestStruct();\n static TestClass testClass = new TestClass();\n static TestStruct8 testStruct8 = new TestStruct8();\n static TestClass8 testClass8 = new TestClass8();\n [Benchmark]\n public void TestStructReturn()\n {\n testStruct.TestMethod();\n }\n\n [Benchmark]\n public void TestClassReturn()\n {\n testClass.TestMethod();\n }\n\n\n [Benchmark]\n public void TestStructReturn8()\n {\n testStruct8.TestMethod();\n }\n\n [Benchmark]\n public void TestClassReturn8()\n {\n testClass8.TestMethod();\n }\n\n public class TestStruct\n {\n public int Number = 5;\n public struct StructType<T>\n {\n public T Instance;\n public List<string> List;\n }\n\n public int TestMethod()\n {\n var s = Method1(1);\n return s.Instance;\n }\n\n private StructType<int> Method1(int i)\n {\n return Method2(++i);\n }\n\n private StructType<int> Method2(int i)\n {\n return Method3(++i);\n }\n\n private StructType<int> Method3(int i)\n {\n return Method4(++i);\n }\n\n private StructType<int> Method4(int i)\n {\n var x = new StructType<int>();\n x.List = new List<string>();\n x.Instance = ++i;\n return x;\n }\n }\n\n public class TestClass\n {\n public int Number = 5;\n public class ClassType<T>\n {\n public T Instance;\n public List<string> List;\n }\n\n public int TestMethod()\n {\n var s = Method1(1);\n return s.Instance;\n }\n\n private ClassType<int> Method1(int i)\n {\n return Method2(++i);\n }\n\n private ClassType<int> Method2(int i)\n {\n return Method3(++i);\n }\n\n private ClassType<int> Method3(int i)\n {\n return Method4(++i);\n }\n\n private ClassType<int> Method4(int i)\n {\n var x = new ClassType<int>();\n x.List = new List<string>();\n x.Instance = ++i;\n return x;\n }\n }\n\n public class TestStruct8\n {\n public int Number = 5;\n public struct StructType<T>\n {\n public T Instance1;\n public T Instance2;\n public T Instance3;\n public T Instance4;\n public T Instance5;\n public T Instance6;\n public T Instance7;\n public List<string> List;\n }\n\n public int TestMethod()\n {\n var s = Method1(1);\n return s.Instance1;\n }\n\n private StructType<int> Method1(int i)\n {\n return Method2(++i);\n }\n\n private StructType<int> Method2(int i)\n {\n return Method3(++i);\n }\n\n private StructType<int> Method3(int i)\n {\n return Method4(++i);\n }\n\n private StructType<int> Method4(int i)\n {\n var x = new StructType<int>();\n x.List = new List<string>();\n x.Instance1 = ++i;\n return x;\n }\n }\n\n public class TestClass8\n {\n public int Number = 5;\n public class ClassType<T>\n {\n public T Instance1;\n public T Instance2;\n public T Instance3;\n public T Instance4;\n public T Instance5;\n public T Instance6;\n public T Instance7;\n public List<string> List;\n }\n\n public int TestMethod()\n {\n var s = Method1(1);\n return s.Instance1;\n }\n\n private ClassType<int> Method1(int i)\n {\n return Method2(++i);\n }\n\n private ClassType<int> Method2(int i)\n {\n return Method3(++i);\n }\n\n private ClassType<int> Method3(int i)\n {\n return Method4(++i);\n }\n\n private ClassType<int> Method4(int i)\n {\n var x = new ClassType<int>();\n x.List = new List<string>();\n x.Instance1 = ++i;\n return x;\n }\n }\n }\n}\n" }, { "answer_id": 51536921, "author": "Avestura", "author_id": 7825034, "author_profile": "https://Stackoverflow.com/users/7825034", "pm_score": 5, "selected": false, "text": "sealed Sealed abstract AbstractClass public private internal public protected internal protected internal private protected null" }, { "answer_id": 62454991, "author": "Arsen Khachaturyan", "author_id": 806202, "author_profile": "https://Stackoverflow.com/users/806202", "pm_score": 5, "selected": false, "text": "+--------------------------------------------------+------+----------------------------------------------+\n| Struct | | Class |\n+--------------------------------------------------+------+----------------------------------------------+\n| - 1 per Thread. | | - 1 per application. |\n| | | |\n| - Holds value types. | | - Holds reference types. |\n| | | |\n| - Types in the stack are positioned | | - No type ordering (data is fragmented). |\n| using the LIFO principle. | | |\n| | | |\n| - Can't have a default constructor and/or | | - Can have a default constructor |\n| finalizer(destructor). | | and/or finalizer. |\n| | | |\n| - Can be created with or without a new operator. | | - Can be created only with a new operator. |\n| | | |\n| - Can't derive from the class or struct | VS | - Can have only one base class and/or |\n| but can derive from the multiple interfaces. | | derive from multiple interfaces. |\n| | | |\n| - The data members can't be protected. | | - Data members can be protected. |\n| | | |\n| - Function members can't be | | - Function members can be |\n| virtual or abstract. | | virtual or abstract. |\n| | | |\n| - Can't have a null value. | | - Can have a null value. |\n| | | |\n| - During an assignment, the contents are | | - Assignment is happening |\n| copied from one variable to another. | | by reference. |\n+--------------------------------------------------+------+----------------------------------------------+\n" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/13049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
13,055
<p>I'm looking for a clear, concise and accurate answer. </p> <p>Ideally as the actual answer, although links to good explanations welcome.</p>
[ { "answer_id": 13056, "author": "Justin Standard", "author_id": 92, "author_profile": "https://Stackoverflow.com/users/92", "pm_score": 6, "selected": false, "text": "int Integer Collection Collection Collection int Integer" }, { "answer_id": 13057, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 5, "selected": false, "text": "object object List<int> notBoxed = new List<int> { 1, 2, 3 };\nint i = notBoxed[1]; // this is the actual value\n\nList<object> boxed = new List<object> { 1, 2, 3 };\nint j = (int) boxed[1]; // this is an object that can be 'unboxed' to an int\n object int int object int structs classes structs classes int a = 7;\nint b = 7;\n\nif(a == b) // Evaluates to true, because a and b have the same value\n\nobject c = (object) 7;\nobject d = (object) 7;\n\nif(c == d) // Evaluates to false, because c and d are different instances\n if(c.Equals(d)) // Evaluates to true because it calls the underlying int's equals\n\nif(((int) c) == ((int) d)) // Evaluates to true once the values are cast\n" }, { "answer_id": 13059, "author": "Christian Hagelid", "author_id": 202, "author_profile": "https://Stackoverflow.com/users/202", "pm_score": 7, "selected": false, "text": "int x = 9; \nobject o = x; // boxing the int\n // unboxing o\nobject o = 9; \nint x = (int)o; \n" }, { "answer_id": 13073, "author": "Jonathan Webb", "author_id": 1518, "author_profile": "https://Stackoverflow.com/users/1518", "pm_score": 2, "selected": false, "text": "List<T>\nDictionary<TKey, UValue>\nSortedDictionary<TKey, UValue>\nStack<T>\nQueue<T>\nLinkedList<T>\n" }, { "answer_id": 101638, "author": "PEELY", "author_id": 17641, "author_profile": "https://Stackoverflow.com/users/17641", "pm_score": -1, "selected": false, "text": "public class TestAutoboxNPE\n{\n public static void main(String[] args)\n {\n Integer i = null;\n\n // .. do some other stuff and forget to initialise i\n\n i = addOne(i); // Whoa! NPE!\n }\n\n public static int addOne(int i)\n {\n return i + 1;\n }\n}\n" }, { "answer_id": 21588698, "author": "vani", "author_id": 2900075, "author_profile": "https://Stackoverflow.com/users/2900075", "pm_score": 2, "selected": false, "text": "Boxing Unboxing EX: int i = 123;\n object o = i;// Boxing\n int j = (int)o;// UnBoxing\n int char structures enumerations Classes interfaces arrays strings objects" }, { "answer_id": 37943012, "author": "Sanjay Kumar", "author_id": 6493838, "author_profile": "https://Stackoverflow.com/users/6493838", "pm_score": 1, "selected": false, "text": "Int int int Int Int int int i=123;\nobject o=(object)i; //Boxing\n\no=123;\ni=(int)o; //Unboxing.\n" }, { "answer_id": 69991369, "author": "FrankHB", "author_id": 2307646, "author_profile": "https://Stackoverflow.com/users/2307646", "pm_score": 2, "selected": false, "text": "std::basic_string double double double PyObject*" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/13055", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
13,060
<p>I'm looking for a clear, concise and accurate answer. </p> <p>Ideally as the actual answer, although links to good explanations welcome.</p> <p>This also applies to VB.Net, but the keywords are different - <code>ByRef</code> and <code>ByVal</code>.</p>
[ { "answer_id": 13061, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 2, "selected": false, "text": "out int result; //not initialised\n\nif( int.TryParse( \"123\", out result ) )\n //result is now 123\nelse\n //if TryParse failed result has still be \n // initialised to its default value (0)\n ref void ChangeMyClass1( MyClass input ) {\n input.MyProperty = \"changed by 1\";\n input = null;\n //can't see input anymore ... \n // I've only nulled my local scope's reference\n}\n\nvoid ChangeMyClass2( ref MyClass input ) {\n input.MyProperty = \"changed by 2\";\n input = null;\n //the passed reference is now null too.\n}\n\nMyClass tester = new MyClass { MyProperty = \"initial value\" };\n\nChangeMyClass1( tester );\n// now tester.MyProperty is \"changed by 1\"\n\nChangeMyClass2( ref tester );\n// now tester is null\n" }, { "answer_id": 13100, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 6, "selected": true, "text": "void Test1(string param)\n{\n param = \"new value\";\n}\n\nstring s1 = \"initial value\";\nTest1(s1);\n// s1 == \"initial value\"\n out ref out ref out ref ref out ref out void Test2(ref string param)\n{\n param = \"new value\";\n}\n\nvoid Test3(out string param)\n{\n // Use of param here will not compile\n param = \"another value\";\n}\n\nstring s2 = \"initial value\";\nstring s3;\nTest2(ref s2);\n// s2 == \"new value\"\n// Test2(ref s3); // Passing ref s3 will not compile\nTest3(out s2);\n// s2 == \"another value\"\nTest3(out s3);\n// s3 == \"another value\"\n out ref out ref ByRef" }, { "answer_id": 13105, "author": "denis phillips", "author_id": 748, "author_profile": "https://Stackoverflow.com/users/748", "pm_score": 3, "selected": false, "text": "void foo(int value) {}\n\n// Only one of the following would be allowed\n\n// valid to overload with ref\nvoid foo(ref int value) {}\n\n// OR with out\nvoid foo(out int value) {}\n" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/13060", "https://Stackoverflow.com", "https://Stackoverflow.com/users/905/" ]
13,109
<p>In php, I often need to map a variable using an array ... but I can not seem to be able to do this in a one liner. c.f. example:</p> <pre><code>// the following results in an error: echo array('a','b','c')[$key]; // this works, using an unnecessary variable: $variable = array('a','b','c'); echo $variable[$key]; </code></pre> <p>This is a minor problem, but it keeps bugging every once in a while ... I don't like the fact, that I use a variable for nothing ;)</p>
[ { "answer_id": 13113, "author": "onnodb", "author_id": 1037, "author_profile": "https://Stackoverflow.com/users/1037", "pm_score": 5, "selected": true, "text": "$variable = array('a','b','c');\necho $variable[$key];\nunset($variable);\n function indexonce(&$ar, $index) {\n return $ar[$index];\n}\n $something = indexonce(array('a', 'b', 'c'), 2);\n" }, { "answer_id": 31942, "author": "John Douthat", "author_id": 2774, "author_profile": "https://Stackoverflow.com/users/2774", "pm_score": 5, "selected": false, "text": "$x = array(1,2,3);\nprint ($x)[1]; //illegal, on a parenthetical expression, not a variable exp.\n\nfunction ret($foo) { return $foo; }\necho ret($x)[1]; // illegal, on a call expression, not a variable exp.\n" }, { "answer_id": 1270349, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "$variable = array('a','b','c');\n$variable = $variable[$key];\n" }, { "answer_id": 2912626, "author": "John Smith", "author_id": 350866, "author_profile": "https://Stackoverflow.com/users/350866", "pm_score": 1, "selected": false, "text": "$myvar = array_shift(array_splice(myfunc(),2));\n" }, { "answer_id": 5040293, "author": "tjma2001", "author_id": 622961, "author_profile": "https://Stackoverflow.com/users/622961", "pm_score": 2, "selected": false, "text": "function doSomething()\n{\n return $somearray;\n}\n\necho doSomething()->get(1)->getOtherPropertyIfThisIsAnObject();\n" }, { "answer_id": 8613413, "author": "Uneebe", "author_id": 283534, "author_profile": "https://Stackoverflow.com/users/283534", "pm_score": 3, "selected": false, "text": "Array\n(\n [School] => Array\n (\n [parent_id] => 9ce8e78a-f4cc-ff64-8de0-4d9c1819a56a\n )\n)\n array_pop( array_pop( the_function_which_returned_the_above_array() ) )\n" }, { "answer_id": 35601314, "author": "Dan Jay", "author_id": 2035600, "author_profile": "https://Stackoverflow.com/users/2035600", "pm_score": 0, "selected": false, "text": " array_pop ( array_filter( array_returning_func(), function($key){ return $key==\"array_index_you_want\"? TRUE:FALSE; },ARRAY_FILTER_USE_KEY ) );\n" }, { "answer_id": 51780191, "author": "Elementary", "author_id": 10127060, "author_profile": "https://Stackoverflow.com/users/10127060", "pm_score": 0, "selected": false, "text": "echo $var=($var=array(0,1,2,3))?$var[3]:false;\n unset" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/13109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1532/" ]
13,128
<p>I'm tired of adding ten link libraries into my project, or requiring eight of them to use my own. I'd like to take existing libraries like libpng.a, libz.a, libjpeg.a, and combine them into one single .a library. Is that possible? How about combining .lib libraries?</p>
[ { "answer_id": 13206, "author": "Judge Maygarden", "author_id": 1491, "author_profile": "https://Stackoverflow.com/users/1491", "pm_score": 5, "selected": false, "text": "ar x <library name>\n ar cs <new library name> <list each extracted object file>\n" }, { "answer_id": 22041, "author": "Greg Whitfield", "author_id": 2102, "author_profile": "https://Stackoverflow.com/users/2102", "pm_score": 0, "selected": false, "text": "---------------------\n| End-user EXE file |\n---------------------\n |\n | makes calls to\n |\n v\n --------------------\n | Your static lib.a |\n --------------------\n | makes calls to and links\n v\n ------------------------------------ .....\n | | |\n ------------- -------- ----------\n | libjpeg.a | |libz.a| |libpng.a|\n ------------- -------- ----------\n" }, { "answer_id": 27676078, "author": "Star Brilliant", "author_id": 2557927, "author_profile": "https://Stackoverflow.com/users/2557927", "pm_score": 3, "selected": false, "text": "ar -M <<EOM\n CREATE libab.a\n ADDLIB liba.a\n ADDLIB libb.a\n SAVE\n END\nEOM\nranlib libab.a\n liba.a libb.a ar crsT libab.a liba.a libb.a\n lib.exe /OUT:libab.lib liba.lib libb.lib\n" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/13128", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1536/" ]
13,170
<p>From time to time I get a System.Threading.ThreadStateException when attempting to restart a thread. The code in question is as follows:</p> <pre><code>// Make sure the thread is done stopping while (this.mThread.ThreadState == ThreadState.Running) { Thread.Sleep(0); } // Respawn a thread if the current one is stopped or doesn't exist if (this.mThread == null || this.mThread.ThreadState == ThreadState.Stopped) { this.mThread = new Thread(new ParameterizedThreadStart(Monitor)); } // Start the thread if (check) { this.mThread.Start(60000); } else { this.mThread.Start(0); } </code></pre> <p>So two questions - is this the correct way of doing things, and it is, is there a way to prevent the error from occurring?</p>
[ { "answer_id": 13207, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 1, "selected": false, "text": "if (this.mThread == null || this.mThread.ThreadState != ThreadState.Suspended)" }, { "answer_id": 13214, "author": "John Richardson", "author_id": 887, "author_profile": "https://Stackoverflow.com/users/887", "pm_score": 3, "selected": false, "text": "if((mThread.ThreadState & ThreadState.Running) != 0)\n mThread.Join();\nmThread = new Thread(new ParameterizedThreadStart(Monitor));\nif(check)\n mThread.Start(60000);\nelse\n mThread.Start(0);\n" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/13170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1185/" ]
13,204
<p>I have a cron job on an Ubuntu Hardy VPS that only half works and I can't work out why. The job is a Ruby script that uses mysqldump to back up a MySQL database used by a Rails application, which is then gzipped and uploaded to a remote server using SFTP.</p> <p>The gzip file is created and copied successfully but it's always zero bytes. Yet if I run the cron command directly from the command line it works perfectly.</p> <p>This is the cron job:</p> <pre><code>PATH=/usr/bin 10 3 * * * ruby /home/deploy/bin/datadump.rb </code></pre> <p>This is datadump.rb:</p> <pre><code>#!/usr/bin/ruby require 'yaml' require 'logger' require 'rubygems' require 'net/ssh' require 'net/sftp' APP = '/home/deploy/apps/myapp/current' LOGFILE = '/home/deploy/log/data.log' TIMESTAMP = '%Y%m%d-%H%M' TABLES = 'table1 table2' log = Logger.new(LOGFILE, 5, 10 * 1024) dump = "myapp-#{Time.now.strftime(TIMESTAMP)}.sql.gz" ftpconfig = YAML::load(open('/home/deploy/apps/myapp/shared/config/sftp.yml')) config = YAML::load(open(APP + '/config/database.yml'))['production'] cmd = "mysqldump -u #{config['username']} -p#{config['password']} -h #{config['host']} --add-drop-table --add-locks --extended-insert --lock-tables #{config['database']} #{TABLES} | gzip -cf9 &gt; #{dump}" log.info 'Getting ready to create a backup' `#{cmd}` # Strongspace log.info 'Backup created, starting the transfer to Strongspace' Net::SSH.start(ftpconfig['strongspace']['host'], ftpconfig['strongspace']['username'], ftpconfig['strongspace']['password']) do |ssh| ssh.sftp.connect do |sftp| sftp.open_handle("#{ftpconfig['strongspace']['dir']}/#{dump}", 'w') do |handle| sftp.write(handle, open("#{dump}").read) end end end log.info 'Finished transferring backup to Strongspace' log.info 'Removing local file' cmd = "rm -f #{dump}" log.debug "Executing: #{cmd}" `#{cmd}` log.info 'Local file removed' </code></pre> <p>I've checked and double-checked all the paths and they're correct. Both <strong>sftp.yml</strong> (SFTP credentials) and <strong>database.yml</strong> (MySQL credentials) are owned by the executing user (deploy) with read-only permissions for that user (chmod 400). I'm using the 1.1.x versions of net-ssh and net-sftp. I know they're not the latest, but they're what I'm familiar with at the moment.</p> <p>What could be causing the cron job to fail?</p>
[ { "answer_id": 13232, "author": "T Percival", "author_id": 954, "author_profile": "https://Stackoverflow.com/users/954", "pm_score": 2, "selected": false, "text": "PATH /bin /bin/rm /etc/crontab PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin\n" }, { "answer_id": 214503, "author": "tardate", "author_id": 6329, "author_profile": "https://Stackoverflow.com/users/6329", "pm_score": 3, "selected": false, "text": "source /etc/profile\n" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/13204", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1450/" ]
13,213
<p>I see often (rewritten) URLs without ID in it, like on some wordpress installations. What is the best way of achieve this?</p> <p>Example: site.com/product/some-product-name/</p> <p>Maybe to keep an array of page names and IDs in cache, to avoid DB query on every page request? How to avoid conflicts, and what are other issues on using urls without IDs?</p>
[ { "answer_id": 89901, "author": "Devin Reams", "author_id": 16248, "author_profile": "https://Stackoverflow.com/users/16248", "pm_score": 1, "selected": false, "text": "RewriteRule ^([0-9]{4})/([0-9]{1,2})/([0-9]{1,2})/?$ /index.php?year=$1&monthnum=$2&day=$3 [QSA,L]\n /2008/01/01/ /index.php?year=2008&monthnum=01&day=01 product-name" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/13213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1407/" ]
13,224
<p>I've included a mobile web form in my asp.net project, I thought that it could/should be seen just for my mobile users but I realize that it can also be seen from any browser, I don't see problem there cause I could diff the access using HttpBrowserCapabilities.IsMobileDevice=true and transferring to the appropiate aspx page, but it results that when I access to the web form from my mobile device it is identified as IsMobileDevice = false and sends me to another page.</p> <p>How could it be possible that?</p> <p>The mobile device runs Pocket PC 2003.</p>
[ { "answer_id": 14182, "author": "Pat Hermens", "author_id": 1677, "author_profile": "https://Stackoverflow.com/users/1677", "pm_score": 2, "selected": false, "text": "HttpContext.Current.Request.Headers(\"User-Agent\") HttpCapabilitiesBase.IsMobileDevice HttpContext.Current.Request.Browser.IsMobileDevice" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/13224", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1130097/" ]
13,225
<p>I've recently inherited a internationalized and text-heavy Struts 1.1 web application. Many of the JSP files look like:</p> <pre class="lang-jsp prettyprint-override"><code>&lt;p&gt; &lt;bean:message key="alert" /&gt; &lt;/p&gt; </code></pre> <p>and the properties files look like:</p> <pre><code>messages.properties alert=Please update your &lt;a href="/address.do"&gt;address&lt;/a&gt; and &lt;a href="/contact.do"&gt;contact information&lt;/a&gt;. </code></pre> <p>with the appropriate translations in N other languages (messages_fr.properties, etc).</p> <p>Problems:</p> <ol> <li><em><strong>DRY violation</strong></em> - I have N references to my Struts action URLs instead of 1, which makes refactoring action URLs error-prone.</li> <li><em><strong>Mixed concerns</strong></em> - My application's markup is now in more than just my JSP files, making it difficult for a web specialist to tweak the markup (using CSS, etc).</li> <li><em><strong>Post-translation markup</strong></em> - Anytime I receive newly-translated text, I must decide what to surround with the <code>&lt;a&gt;...&lt;/a&gt;</code> markup. Easy for English but less so for unfamiliar languages.</li> </ol> <p>I've considered adding placeholders in the messages file, like:</p> <pre><code>alert=Please update your {0} and {1}. </code></pre> <p>but then the words "address" and "contact information" would somehow need to be localized, wrapped with markup, and passed to my message tag - and I can't see an easy way to do it.</p> <p>What can I do to improve this?</p>
[ { "answer_id": 13239, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 0, "selected": false, "text": "#\nalert=Please update your {0}address{1} and {2}contact information{3}.\n" }, { "answer_id": 13359, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 0, "selected": false, "text": "<fmt:bundle basename=\"messages\">\n <fmt:message key=\"alert\">\n <fmt:param value='<a href=\"/\">' />\n <fmt:param value=\"</a>\" />\n <fmt:param value='<a href=\"/\">' />\n <fmt:param value=\"</a>\" />\n </fmt:message>\n</fmt:bundle>\n <a>...</a> {0} <a href=\"/address.do\">Please update your address.</a>\n<a href=\"/contact.do\">Please update your contact information.</a>\n" }, { "answer_id": 13381, "author": "McDowell", "author_id": 304, "author_profile": "https://Stackoverflow.com/users/304", "pm_score": 3, "selected": true, "text": "<p>Please update your address and contact information.\n<br />\n<a href=\"/address.do\">update address</a>\n<br />\n<a href=\"/contact.do\">update contact information</a></p>\n" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/13225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1557/" ]
13,343
<p>I've been thinking about software estimation lately, and I have a bunch of questions around time spent coding. I'm curious to hear from people who have had at least a couple years of experience developing software.</p> <p>When you have to estimate the amount of time you'll spend working on something, how many hours of the day do you spend coding? What occupies the other non-coding hours?</p> <p>Do you find you spend more or less hours than your teammates coding? Do you feel like you're getting more or less work done than they are?</p> <p>What are your work conditions like? Private office, shared office, team room? Coding alone or as a pair? How has your working condition changed the amount of time you spend coding each day? If you can work from home, does that help or hurt your productivity?</p> <p>What development methodology do you use? Waterfall? Agile? Has changing from one methodology to another had an impact on your coding hours per day?</p> <p>Most importantly: Are you happy with your productivity? If not, what single change would you make that would have the most impact on it?</p>
[ { "answer_id": 9800326, "author": "Coral Doe", "author_id": 1252063, "author_profile": "https://Stackoverflow.com/users/1252063", "pm_score": 1, "selected": false, "text": "formality" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/13343", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1554/" ]
13,345
<p>I've always wanted a way to make a socket connection to a server and allow the server to manipulate the page DOM. For example, this could be used in a stock quotes page, so the server can push new quotes as they become available. </p> <p>I know this is a classic limitation (feature?) of HTTP's request/response protocol, but I think this could be implemented as a Firefox plugin (cross-browser compatibility is not important for my application). Java/Flash solutions are not acceptable, because (as far as i know) they live in a box and can't interact with the DOM. </p> <p>Can anyone confirm whether this is within the ability of a Firefox plugin? Has someone already created this or something similar? </p>
[ { "answer_id": 12466445, "author": "Beachhouse", "author_id": 783004, "author_profile": "https://Stackoverflow.com/users/783004", "pm_score": 1, "selected": false, "text": "socket_send(\"This was sent via the socket\\n\\n\"); on_socket_get(message){ more_code(message); }" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/13345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
13,362
<p>I've got a div that uses overflow:auto to keep the contents inside the div as it is resized and dragged around the page. I'm using some ajax to retrieve lines of text from the server, then append them to the end of the div, so the content is growing downwards. Every time this happens, I'd like to use JS to scroll the div to the bottom so the most recently added content is visible, similar to the way a chat room or command line console would work.</p> <p>So far I've been using this snippet to do it (I'm also using jQuery, hence the $() function):</p> <pre><code>$("#thediv").scrollTop = $("#thediv").scrollHeight; </code></pre> <p>However it's been giving me inconsistent results. Sometimes it works, sometimes not, and it completely ceases to work if the user ever resizes the div or moves the scroll bar manually.</p> <p>The target browser is Firefox 3, and it's being deployed in a controlled environment so it doesn't need to work in IE at all.</p> <p>Any ideas guys? This one's got me stumped. Thanks!</p>
[ { "answer_id": 13365, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 7, "selected": true, "text": "scrollHeight scrollTop $(\"#thediv\").each( function() \n{\n // certain browsers have a bug such that scrollHeight is too small\n // when content does not fill the client area of the element\n var scrollHeight = Math.max(this.scrollHeight, this.clientHeight);\n this.scrollTop = scrollHeight - this.clientHeight;\n});\n clientHeight" }, { "answer_id": 14494, "author": "Vincent Robert", "author_id": 268, "author_profile": "https://Stackoverflow.com/users/268", "pm_score": 3, "selected": false, "text": "var div = $(\"#thediv\")[0];\n\n// certain browsers have a bug such that scrollHeight is too small\n// when content does not fill the client area of the element\nvar scrollHeight = Math.max(div.scrollHeight, div.clientHeight);\ndiv.scrollTop = scrollHeight - div.clientHeight;\n" }, { "answer_id": 741982, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 5, "selected": false, "text": "scrollIntoView" }, { "answer_id": 7605343, "author": "peterbrown", "author_id": 972295, "author_profile": "https://Stackoverflow.com/users/972295", "pm_score": 3, "selected": false, "text": "$(\"#thediv\").scrollTop($(\"#thediv\")[0].scrollHeight);\n" }, { "answer_id": 19598983, "author": "ObjectiveTC", "author_id": 802196, "author_profile": "https://Stackoverflow.com/users/802196", "pm_score": -1, "selected": false, "text": "<div id=\"div-wrapper\">\n <div class=\"left-div\"></div>\n <div id=\"div-content\" class=\"middle-div\">\n Some short/sweet content that will be elongated by Jquery.\n </div>\n <div class=\"right-div\"></div>\n</div>\n <script>\n$(\"#div-content\").text(\"a very long string of text that will overflow beyond the width/height of the div-content\");\n//now I need to resize the div...\nvar contentHeight = $('#div-content').prop('scrollHeight')\n$(\"#div-wrapper\").height(contentHeight);\n</script>\n" }, { "answer_id": 55489459, "author": "daniels", "author_id": 2270233, "author_profile": "https://Stackoverflow.com/users/2270233", "pm_score": 1, "selected": false, "text": "scrollHeight const theDiv = document.querySelector('#thediv');\ntheDiv.scrollTop = Math.pow(10, 10);\n Math.pow(10, 10) Infintiy Number.MAX_VALUE 0" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/13362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1384/" ]
13,396
<p>I love list comprehensions in Python, because they concisely represent a transformation of a list.</p> <p>However, in other languages, I frequently find myself writing something along the lines of:</p> <pre><code>foreach (int x in intArray) if (x &gt; 3) //generic condition on x x++ //do other processing </code></pre> <p>This example is in C#, where I'm under the impression LINQ can help with this, but is there some common programming construct which can replace this slightly less-than-elegant solution? Perhaps a data structure I'm not considering?</p>
[ { "answer_id": 13403, "author": "James A. Rosen", "author_id": 1190, "author_profile": "https://Stackoverflow.com/users/1190", "pm_score": 0, "selected": false, "text": "intArray.select { |x| x > 3 }.each do |x|\n # do other processing\nend\n intArray.select { |x| x > 3 }.each { |x| something_that_uses x }\n intArray.select { |x| x > 3 }.map { |x| do_something_to x }\n" }, { "answer_id": 13405, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 1, "selected": false, "text": "map(lambda x: foo(x + 1) filter(lambda x: x > 3, intArray))\n [f(x + 1) for x in intArray if x > 3]\n" }, { "answer_id": 13406, "author": "Lars Mæhlum", "author_id": 960, "author_profile": "https://Stackoverflow.com/users/960", "pm_score": 2, "selected": false, "text": "intArray.Where(i => i > 3).ConvertAll();\nDoStuff(intArray.Where(i => i 3));\n" }, { "answer_id": 13435, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 4, "selected": true, "text": "foreach for for(int i = 0; i < intArray.Length; ++i)\n{\n if(intArray[i] > 3) ++intArray[i];\n}\n var newArray1 = from i in intArray select ((i > 3) ? (i + 1) : (i));\nvar newArray2 = intArray.Select(i => (i > 3) ? (i + 1) : (i));\n where var intArray = new int[] { 10, 1, 20, 2 };\nvar newArray = from i in intArray where i > 3 select i + 1;\n// newArray == { 11, 21 }\n ForEach foreach foreach intArray.ForEach(i => DoSomething(i));\n" }, { "answer_id": 6477444, "author": "sam", "author_id": 778942, "author_profile": "https://Stackoverflow.com/users/778942", "pm_score": 0, "selected": false, "text": "map(lambda x: test(x + 1) filter(lambda x: x > 3, arr))\n" } ]
2008/08/16
[ "https://Stackoverflow.com/questions/13396", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1266/" ]
13,434
<p>How can I get programmatic access to the call stack?</p>
[ { "answer_id": 13439, "author": "James Avery", "author_id": 537, "author_profile": "https://Stackoverflow.com/users/537", "pm_score": 3, "selected": false, "text": "StackTrace StrackFrame System.Diagnostics" }, { "answer_id": 13621, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 0, "selected": false, "text": "StackTrace StackFrame" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13434", "https://Stackoverflow.com", "https://Stackoverflow.com/users/100/" ]
13,454
<p>I wrote a piece of code to convert PHP's striplashes into valid Python [backslash] escapes:</p> <pre><code>cleaned = stringwithslashes cleaned = cleaned.replace('\\n', '\n') cleaned = cleaned.replace('\\r', '\n') cleaned = cleaned.replace('\\', '') </code></pre> <p>How can I condense it? </p>
[ { "answer_id": 13456, "author": "Brad Wilson", "author_id": 1554, "author_profile": "https://Stackoverflow.com/users/1554", "pm_score": 0, "selected": false, "text": "cleaned = stringwithslashes.replace(\"\\\\n\",\"\\n\").replace(\"\\\\r\",\"\\n\").replace(\"\\\\\",\"\")\n" }, { "answer_id": 13579, "author": "eplawless", "author_id": 1370, "author_profile": "https://Stackoverflow.com/users/1370", "pm_score": -1, "selected": false, "text": "p = re.compile( '\\\\(\\\\\\S)')\np.sub('\\1',escapedstring)\n >>> escapedstring\n'This is a \\\\n\\\\n\\\\n test'\n>>> p = re.compile( r'\\\\(\\S)' )\n>>> p.sub(r\"\\1\",escapedstring)\n'This is a nnn test'\n>>> p.sub(r\"\\\\1\",escapedstring)\n'This is a \\\\1\\\\1\\\\1 test'\n>>> p.sub(r\"\\\\\\1\",escapedstring)\n'This is a \\\\n\\\\n\\\\n test'\n>>> p.sub(r\"\\(\\1)\",escapedstring)\n'This is a \\\\(n)\\\\(n)\\\\(n) test'\n" }, { "answer_id": 13598, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 4, "selected": false, "text": "cleaned = stringwithslashes.decode('string_escape')\n" }, { "answer_id": 13608, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 2, "selected": false, "text": "import re\ndef stripslashes(s):\n r = re.sub(r\"\\\\(n|r)\", \"\\n\", s)\n r = re.sub(r\"\\\\\", \"\", r)\n return r\ncleaned = stripslashes(stringwithslashes)\n" }, { "answer_id": 21862975, "author": "Jorgesys", "author_id": 250260, "author_profile": "https://Stackoverflow.com/users/250260", "pm_score": 1, "selected": false, "text": "decode('string_escape') cleaned = stringwithslashes.decode('string_escape')\n cleaned = stringwithslashes.replace(\"\\\\\",\"\").replace(\"\\\\n\",\"\\n\").replace(\"\\\\r\",\"\\n\")\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
13,470
<p>I was reading <a href="https://stackoverflow.com/questions/6173/regular-expression-for-parsing-links-from-a-webpage">this question</a> about how to parse URLs out of web pages and had a question about the <a href="https://stackoverflow.com/questions/6173/regular-expression-for-parsing-links-from-a-webpage#6183">accepted answer</a> which offered this solution:</p> <pre class="lang-none prettyprint-override"><code>((mailto\:|(news|(ht|f)tp(s?))\://){1}\S+) </code></pre> <p>The solution was offered by <a href="https://stackoverflow.com/users/350/csmba">csmba</a> and he credited it to <a href="http://regexlib.com/Search.aspx?k=URL" rel="nofollow noreferrer">regexlib.com</a>. Whew. Credits done.</p> <p>I think this is a fairly naive regular expression but it's a fine starting point for building something better. But, my question is this:</p> <p>What is the point of <code>{1}</code>? It means "exactly one of the previous grouping", right? Isn't that the default behavior of a grouping in a regular expression? Would the expression be changed in any way if the <code>{1}</code> were removed?</p> <p>If I saw this from a coworker I would point out his or her error but as I write this the response is rated at a 6 and the expression on regexlib.com is rated a 4 of 5. So maybe I'm missing something?</p>
[ { "answer_id": 13483, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 2, "selected": false, "text": "tibook 0 /home/jj33/swap > cat text\nText this is http://example.com text this is\nText this is http://http://example.com text this is\ntibook 0 /home/jj33/swap > cat p\n#!/usr/bin/perl\n\nmy $re1 = '((mailto\\:|(news|(ht|f)tp(s?))\\://){1}\\S+)';\nmy $re2 = '((mailto\\:|(news|(ht|f)tp(s?))\\://)\\S+)';\n\nwhile (<>) {\n print \"Evaluating: $_\";\n print \"re1 saw \\$1 = $1\\n\" if (/$re1/);\n print \"re2 saw \\$1 = $1\\n\" if (/$re2/);\n}\ntibook 0 /home/jj33/swap > cat text | perl p\nEvaluating: Text this is http://example.com text this is\nre1 saw $1 = http://example.com\nre2 saw $1 = http://example.com\nEvaluating: Text this is http://http://example.com text this is\nre1 saw $1 = http://http://example.com\nre2 saw $1 = http://http://example.com\ntibook 0 /home/jj33/swap >\n" }, { "answer_id": 13484, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 2, "selected": true, "text": "http://http://example.org http://example.org http://http://example.org" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/430/" ]
13,473
<p>I would like to sort an array in ascending order using <code>C/C++</code>. The outcome is an array containing element indexes. Each index is corespondent to the element location in the sorted array.</p> <p><strong>Example</strong></p> <pre><code>Input: 1, 3, 4, 9, 6 Output: 1, 2, 3, 5, 4 </code></pre> <p><strong>Edit:</strong> I am using shell sort procedure. The duplicate value indexes are arbitrarily chosen based on which duplicate values are first in the original array.</p> <h3>Update:</h3> <p>Despite my best efforts, I haven't been able to implement a sorting algorithm for an array of pointers. The current example won't compile.</p> <p>Could someone please tell me what's wrong?</p> <p>I'd very much appreciate some help!</p> <pre><code>void SortArray(int ** pArray, int ArrayLength) { int i, j, flag = 1; // set flag to 1 to begin initial pass int * temp; // holding variable orig with no * for (i = 1; (i &lt;= ArrayLength) &amp;&amp; flag; i++) { flag = 0; for (j = 0; j &lt; (ArrayLength - 1); j++) { if (*pArray[j + 1] &gt; *pArray[j]) // ascending order simply changes to &lt; { &amp;temp = &amp;pArray[j]; // swap elements &amp;pArray[j] = &amp;pArray[j + 1]; //the problem lies somewhere in here &amp;pArray[j + 1] = &amp;temp; flag = 1; // indicates that a swap occurred. } } } }; </code></pre>
[ { "answer_id": 13477, "author": "Patrick", "author_id": 429, "author_profile": "https://Stackoverflow.com/users/429", "pm_score": 0, "selected": false, "text": "newArray = sorted(oldArray)\nblankArray = [0] * len(oldArray)\nfor i in xrange(len(newArray)):\n dex = oldArray.index(newArray[i])\n blankArray[dex] = i\n" }, { "answer_id": 13481, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 4, "selected": true, "text": "SortIntPointers int int* intArray; // set somewhere else\nint arrayLen; // set somewhere else \n\nint** pintArray = new int*[arrayLen];\nfor(int i = 0; i < arrayLen; ++i)\n{\n pintArray[i] = &intArray[i];\n}\n\n// This function sorts the pointers according to the values they\n// point to. In effect, it sorts intArray without losing the positional\n// information.\nSortIntPointers(pintArray, arrayLen);\n\n// Dereference the pointers and assign their sorted position.\nfor(int i = 0; i < arrayLen; ++i)\n{\n *pintArray[i] = i;\n}\n" }, { "answer_id": 13482, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 2, "selected": false, "text": "function bubbleRank(A){\n var B = new Array();\n for(var i=0; i<A.length; i++){\n B[i] = i;\n }\n do{\n swapped = false;\n for(var i=0; i<A.length; i++){\n if(A[B[i]] > A[B[i+1]]){\n var temp = B[i];\n B[i] = B[i+1];\n B[i+1] = temp;\n swapped = true;\n }\n }\n }while(swapped);\n return B;\n}\n" }, { "answer_id": 119587, "author": "Maciej Hehl", "author_id": 19939, "author_profile": "https://Stackoverflow.com/users/19939", "pm_score": 2, "selected": false, "text": "#include <iostream>\n#include <algorithm>\n\nstruct mycomparison\n{\n bool operator() (int* lhs, int* rhs) {return (*lhs) < (*rhs);}\n};\n\nint main(int argc, char* argv[])\n{\n int myarray[] = {1, 3, 6, 2, 4, 9, 5, 12, 10};\n const size_t size = sizeof(myarray) / sizeof(myarray[0]);\n int *arrayofpointers[size];\n for(int i = 0; i < size; ++i)\n {\n arrayofpointers[i] = myarray + i;\n }\n std::sort(arrayofpointers, arrayofpointers + size, mycomparison());\n for(int i = 0; i < size; ++i)\n {\n *arrayofpointers[i] = i + 1;\n }\n for(int i = 0; i < size; ++i)\n {\n std::cout << myarray[i] << \" \";\n }\n std::cout << std::endl;\n return 0;\n}\n" }, { "answer_id": 122083, "author": "oz10", "author_id": 14069, "author_profile": "https://Stackoverflow.com/users/14069", "pm_score": 0, "selected": false, "text": " std::vector<int> intVector;\n std::vector<int> rank;\n\n // set up values according to your example...\n intVector.push_back( 1 );\n intVector.push_back( 3 );\n intVector.push_back( 4 );\n intVector.push_back( 9 );\n intVector.push_back( 6 );\n\n\n for( int i = 0; i < intVector.size(); ++i )\n {\n rank.push_back( i );\n }\n\n using namespace boost::lambda;\n std::sort( \n rank.begin(), rank.end(),\n var( intVector )[ _1 ] < var( intVector )[ _2 ] \n );\n\n //... and because you wanted to replace the values of the original with \n // their rank\n intVector = rank;\n" }, { "answer_id": 33194962, "author": "aravinth", "author_id": 3553385, "author_profile": "https://Stackoverflow.com/users/3553385", "pm_score": 1, "selected": false, "text": "int arr[n];\nint rank[n];\n for(int i=0;i<n;i++)\n for(int j=0;j<n;j++)\n if(arr[i]>arr[j])\n rank[i]++;\n" }, { "answer_id": 44255995, "author": "Phillip Kigenyi", "author_id": 4991437, "author_profile": "https://Stackoverflow.com/users/4991437", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n\nvoid swap(int *xp, int *yp) {\n int temp = *xp;\n *xp = *yp;\n *yp = temp;\n}\n\n// A function to implement bubble sort\nvoid bubbleSort(int arr[], int n) {\n int i, j;\n for (i = 0; i < n - 1; i++)\n\n // Last i elements are already in place\n for (j = 0; j < n - i - 1; j++)\n if (arr[j] > arr[j + 1])\n swap(&arr[j], &arr[j + 1]);\n}\n\n/* Function to print an array */\nvoid printArray(int arr[], int size) {\n for (int i = 0; i < size; i++)\n printf(\"%d \", arr[i]);\n printf(\"\\n\");\n}\n\nint main() {\n int arr[] = {64, 34, 25, 12, 22, 11, 98};\n int arr_original[] = {64, 34, 25, 12, 22, 11, 98};\n int rank[7];\n\n int n = sizeof(arr) / sizeof(arr[0]);\n bubbleSort(arr, n);\n\n printf(\"Sorted array: \\n\");\n printArray(arr, n);\n\n //PLACE RANK\n //look for location of number in original array\n //place the location in rank array\n int counter = 1;\n for (int k = 0; k < n; k++){\n for (int i = 0; i < n; i++){\n printf(\"Checking..%d\\n\", i);\n if (arr_original[i] == arr[k]){\n rank[i] = counter;\n counter++;\n printf(\"Found..%d\\n\", i);\n }\n }\n }\n\n printf(\"Original array: \\n\");\n printArray(arr_original, n);\n\n printf(\"Rank array: \\n\");\n printArray(rank, n);\n return 0;\n}\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13473", "https://Stackoverflow.com", "https://Stackoverflow.com/users/522/" ]
13,537
<p>I've heard of the idea of bootstrapping a language, that is, writing a compiler/interpreter for the language in itself. I was wondering how this could be accomplished and looked around a bit, and saw someone say that it could only be done by either</p> <ul> <li>writing an initial compiler in a different language.</li> <li>hand-coding an initial compiler in Assembly, which seems like a special case of the first</li> </ul> <p>To me, neither of these seem to actually be <em>bootstrapping</em> a language in the sense that they both require outside support. Is there a way to actually write a compiler in its own language?</p>
[ { "answer_id": 29983650, "author": "Basile Starynkevitch", "author_id": 841108, "author_profile": "https://Stackoverflow.com/users/841108", "pm_score": 1, "selected": false, "text": "*/*.{ml,mli} boot/ocamlc *.ml[i] boot/ocamlc wget *.melt melt/generated/*.cc [A-Z]*.c dx.h _[0-9]*" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1266/" ]
13,540
<p>I've written a stored proc that will do an update if a record exists, otherwise it will do an insert. It looks something like this:</p> <pre><code>update myTable set Col1=@col1, Col2=@col2 where ID=@ID if @@rowcount = 0 insert into myTable (Col1, Col2) values (@col1, @col2) </code></pre> <p>My logic behind writing it in this way is that the update will perform an implicit select using the where clause and if that returns 0 then the insert will take place.</p> <p>The alternative to doing it this way would be to do a select and then based on the number of rows returned either do an update or insert. This I considered inefficient because if you are to do an update it will cause 2 selects (the first explicit select call and the second implicit in the where of the update). If the proc were to do an insert then there'd be no difference in efficiency.</p> <p>Is my logic sound here? Is this how you would combine an insert and update into a stored proc?</p>
[ { "answer_id": 25318, "author": "Dima Malenko", "author_id": 2586, "author_profile": "https://Stackoverflow.com/users/2586", "pm_score": 3, "selected": false, "text": "BEGIN TRANSACTION Upsert\nupdate myTable set Col1=@col1, Col2=@col2 where ID=@ID\nif @@rowcount = 0\ninsert into myTable (Col1, Col2) values (@col1, @col2)\nCOMMIT TRANSACTION Upsert\n" }, { "answer_id": 80790, "author": "Tomas Tintera", "author_id": 15136, "author_profile": "https://Stackoverflow.com/users/15136", "pm_score": 3, "selected": false, "text": "SET transaction isolation level SERIALIZABLE\nBEGIN TRANSACTION Upsert\nUPDATE myTable set Col1=@col1, Col2=@col2 where ID=@ID\nif @@rowcount = 0\n begin\n INSERT into myTable (ID, Col1, Col2) values (@ID @col1, @col2)\n end\nCOMMIT TRANSACTION Upsert\n" }, { "answer_id": 193876, "author": "Sam Saffron", "author_id": 17174, "author_profile": "https://Stackoverflow.com/users/17174", "pm_score": 6, "selected": false, "text": "begin tran\n update t with (serializable)\n set hitCount = hitCount + 1\n where pk = @id\n if @@rowcount = 0\n begin\n insert t (pk, hitCount)\n values (@id,1)\n end\ncommit tran\n" }, { "answer_id": 10399131, "author": "thughes78013", "author_id": 1367900, "author_profile": "https://Stackoverflow.com/users/1367900", "pm_score": 2, "selected": false, "text": "SET TRANSACTION ISOLATION LEVEL SERIALIZABLE \n\nBEGIN TRANSACTION UPSERT \n\nUPDATE MYTABLE \nSET COL1 = @col1, \n COL2 = @col2 \nWHERE ID = @ID \n\nIF @@rowcount = 0 \n BEGIN \n INSERT INTO MYTABLE \n (ID, \n COL1, \n COL2) \n VALUES (@ID, \n @col1, \n @col2) \n END \n\nIF @@Error > 0 \n BEGIN \n INSERT INTO MYERRORTABLE \n (ID, \n COL1, \n COL2) \n VALUES (@ID, \n @col1, \n @col2) \n END \n\nCOMMIT TRANSACTION UPSERT \n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13540", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
13,569
<p>In our place we're split between using mysqli and PDO for stuff like prepared statements and transaction support. Some projects use one, some the other. There is little realistic likelihood of us ever moving to another RDBMS.</p> <p>I prefer PDO for the single reason that it allows named parameters for prepared statements, and as far as I am aware mysqli does not.</p> <p>Are there any other pros and cons to choosing one over the other as a standard as we consolidate our projects to use just one approach?</p>
[ { "answer_id": 49787, "author": "Brian Warshaw", "author_id": 1344, "author_profile": "https://Stackoverflow.com/users/1344", "pm_score": 5, "selected": false, "text": "call_user_func_array()" }, { "answer_id": 127319, "author": "Unlabeled Meat", "author_id": 20291, "author_profile": "https://Stackoverflow.com/users/20291", "pm_score": 2, "selected": false, "text": "$pdo->fetchObject('MyClass') fetch_object() stdClass" }, { "answer_id": 368758, "author": "Tom", "author_id": 26155, "author_profile": "https://Stackoverflow.com/users/26155", "pm_score": 4, "selected": false, "text": "PDOStatement unset()" }, { "answer_id": 368990, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 8, "selected": false, "text": "class Student {\n\n public $id;\n public $first_name;\n public $last_name\n\n public function getFullName() {\n return $this->first_name.' '.$this->last_name\n }\n}\n\ntry \n{\n $dbh = new PDO(\"mysql:host=$hostname;dbname=school\", $username, $password)\n\n $stmt = $dbh->query(\"SELECT * FROM students\");\n\n /* MAGIC HAPPENS HERE */\n\n $stmt->setFetchMode(PDO::FETCH_INTO, new Student);\n\n\n foreach($stmt as $student)\n {\n echo $student->getFullName().'<br />';\n } \n\n $dbh = null;\n}\ncatch(PDOException $e)\n{\n echo $e->getMessage();\n}\n" }, { "answer_id": 3937381, "author": "Dobb", "author_id": 476285, "author_profile": "https://Stackoverflow.com/users/476285", "pm_score": 2, "selected": false, "text": "SELECT NULL\" -> PGO() SHOW TABLE STATUS\" -> mysqli() SELECT * FROM users\" -> mysqli()" }, { "answer_id": 6825215, "author": "Alix Axel", "author_id": 89771, "author_profile": "https://Stackoverflow.com/users/89771", "pm_score": 3, "selected": false, "text": "PDO::quote() mysqli::real_escape_string()" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13569", "https://Stackoverflow.com", "https://Stackoverflow.com/users/137/" ]
13,578
<p>The need arose, in our product, to determine how long the current user has been logged on to Windows (specifically, Vista). It seems there is no straight forward API function for this and I couldn't find anything relevant with WMI (although I'm no expert with WMI, so I might have missed something).</p> <p>Any ideas?</p>
[ { "answer_id": 13600, "author": "Nickolay", "author_id": 1026, "author_profile": "https://Stackoverflow.com/users/1026", "pm_score": 3, "selected": true, "text": "strComputer = \".\"\nSet objWMIService = GetObject(\"winmgmts:\" _\n & \"{impersonationLevel=impersonate}!\\\\\" _\n & strComputer & \"\\root\\cimv2\")\nSet sessions = objWMIService.ExecQuery _\n (\"select * from Win32_Session\")\n\nFor Each objSession in sessions\n Wscript.Echo objSession.StartTime\nNext\n" }, { "answer_id": 543364, "author": "Matt Hanson", "author_id": 5473, "author_profile": "https://Stackoverflow.com/users/5473", "pm_score": 0, "selected": false, "text": "Set logins = objWMIService.ExecQuery _\n (\"select * from Win32_NetworkLoginProfile\")\nFor Each objSession in logins\n Wscript.Echo objSession.LastLogon\nNext\n" }, { "answer_id": 43794118, "author": "Gnat", "author_id": 478380, "author_profile": "https://Stackoverflow.com/users/478380", "pm_score": 2, "selected": false, "text": "Get-WmiObject win32_networkloginprofile | ? {$_.lastlogon -ne $null} | % {[PSCustomObject]@{User=$_.caption; LastLogon=[Management.ManagementDateTimeConverter]::ToDateTime($_.lastlogon)}}\n NT AUTHORITY\\SYSTEM" }, { "answer_id": 64367682, "author": "mhmd", "author_id": 12484958, "author_profile": "https://Stackoverflow.com/users/12484958", "pm_score": 2, "selected": false, "text": "C:\\> query user\nUSERNAME SESSIONNAME ID STATE IDLE TIME LOGON TIME\njohn rdp-tcp#56 9 Active . 5/3/2020 10:19 AM\nmax rdp-tcp#5 30 Active 5+23:42 9/4/2020 7:31 PM\nyee 35 Disc 6:41 10/14/2020 6:37 PM\nmohammd rdp-tcp#3 37 Active . 10/15/2020 7:51 AM\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13578", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1596/" ]
13,599
<p>Does anyone know how to transform a enum value to a human readable value?</p> <p>For example:</p> <blockquote> <p>ThisIsValueA should be "This is Value A".</p> </blockquote>
[ { "answer_id": 13611, "author": "Adam Haile", "author_id": 194, "author_profile": "https://Stackoverflow.com/users/194", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Reflection;\nnamespace FunWithEnum\n{\n enum Coolness : byte\n {\n [Description(\"Not so cool\")]\n NotSoCool = 5,\n Cool, // since description same as ToString no attr are used\n [Description(\"Very cool\")]\n VeryCool = NotSoCool + 7,\n [Description(\"Super cool\")]\n SuperCool\n }\n class Description : Attribute\n {\n public string Text;\n public Description(string text)\n {\n Text = text;\n }\n }\n class Program\n {\n static string GetDescription(Enum en)\n {\n Type type = en.GetType();\n MemberInfo[] memInfo = type.GetMember(en.ToString());\n if (memInfo != null && memInfo.Length > 0)\n {\n object[] attrs = memInfo[0].GetCustomAttributes(typeof(Description), false);\n if (attrs != null && attrs.Length > 0)\n return ((Description)attrs[0]).Text;\n }\n return en.ToString();\n }\n static void Main(string[] args)\n {\n Coolness coolType1 = Coolness.Cool;\n Coolness coolType2 = Coolness.NotSoCool;\n Console.WriteLine(GetDescription(coolType1));\n Console.WriteLine(GetDescription(coolType2));\n }\n }\n}\n" }, { "answer_id": 13613, "author": "Leon Bambrick", "author_id": 49, "author_profile": "https://Stackoverflow.com/users/49", "pm_score": 5, "selected": true, "text": " /// <summary>\n /// Add spaces to separate the capitalized words in the string, \n /// i.e. insert a space before each uppercase letter that is \n /// either preceded by a lowercase letter or followed by a \n /// lowercase letter (but not for the first char in string). \n /// This keeps groups of uppercase letters - e.g. acronyms - together.\n /// </summary>\n /// <param name=\"pascalCaseString\">A string in PascalCase</param>\n /// <returns></returns>\n public static string Wordify(string pascalCaseString)\n { \n Regex r = new Regex(\"(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])\");\n return r.Replace(pascalCaseString, \" ${x}\");\n }\n Console.WriteLine(Wordify(ThisIsValueA.ToString()));\n \"This Is Value A\".\n" }, { "answer_id": 13697, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 4, "selected": false, "text": "public static string Wordify(this Enum input)\n{ \n Regex r = new Regex(\"(?<=[a-z])(?<x>[A-Z])|(?<=.)(?<x>[A-Z])(?=[a-z])\");\n return r.Replace( input.ToString() , \" ${x}\");\n}\n\n//then your calling syntax is down to:\nMyEnum.ThisIsA.Wordify();\n" }, { "answer_id": 52067663, "author": "Matt Williams", "author_id": 3905343, "author_profile": "https://Stackoverflow.com/users/3905343", "pm_score": 0, "selected": false, "text": "Description public enum Coolness\n{\n NotSoCool,\n Cool,\n VeryCool,\n SuperCool\n}\n\npublic static class CoolnessExtensions\n{\n public static string ToString(this Coolness coolness)\n {\n switch (coolness)\n {\n case Coolness.NotSoCool:\n return \"Not so cool\";\n case Coolness.Cool:\n return \"Cool\";\n case Coolness.VeryCool:\n return \"Very cool\";\n case Coolness.SuperCool:\n return Properties.Settings.Default[\"SuperCoolDescription\"].ToString();\n default:\n throw new ArgumentException(\"Unknown amount of coolness\", nameof(coolness));\n }\n }\n}\n VeryCool" }, { "answer_id": 68849180, "author": "osynavets", "author_id": 9547346, "author_profile": "https://Stackoverflow.com/users/9547346", "pm_score": 0, "selected": false, "text": "Enum.GetName(typeof(EnumFoo), EnumFoo.BarValue)\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13599", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1154/" ]
13,615
<p>I need to validate an integer to know if is a valid enum value.</p> <p>What is the best way to do this in C#?</p>
[ { "answer_id": 13635, "author": "Jon Limjap", "author_id": 372, "author_profile": "https://Stackoverflow.com/users/372", "pm_score": 3, "selected": false, "text": "Enum.IsDefined" }, { "answer_id": 13651, "author": "Mike Polen", "author_id": 212, "author_profile": "https://Stackoverflow.com/users/212", "pm_score": 0, "selected": false, "text": "(ENUMTYPE)Enum.ToObject(typeof(ENUMTYPE), INT)\n" }, { "answer_id": 4807469, "author": "Vman", "author_id": 299529, "author_profile": "https://Stackoverflow.com/users/299529", "pm_score": 8, "selected": true, "text": "IsDefined public static bool TryParseEnum<TEnum>(this int enumValue, out TEnum retVal)\n{\n retVal = default(TEnum);\n bool success = Enum.IsDefined(typeof(TEnum), enumValue);\n if (success)\n {\n retVal = (TEnum)Enum.ToObject(typeof(TEnum), enumValue);\n }\n return success;\n}\n" }, { "answer_id": 15752719, "author": "deegee", "author_id": 1655625, "author_profile": "https://Stackoverflow.com/users/1655625", "pm_score": 5, "selected": false, "text": "public const MyEnum MYENUM_MINIMUM = MyEnum.One;\npublic const MyEnum MYENUM_MAXIMUM = MyEnum.Four;\n\npublic enum MyEnum\n{\n One,\n Two,\n Three,\n Four\n};\n\npublic static MyEnum Validate(MyEnum value)\n{\n if (value < MYENUM_MINIMUM) { return MYENUM_MINIMUM; }\n if (value > MYENUM_MAXIMUM) { return MYENUM_MAXIMUM; }\n return value;\n}\n public static T Clamp<T>(T value)\n{\n int minimum = Enum.GetValues(typeof(T)).GetLowerBound(0);\n int maximum = Enum.GetValues(typeof(T)).GetUpperBound(0);\n\n if (Convert.ToInt32(value) < minimum) { return (T)Enum.ToObject(typeof(T), minimum); }\n if (Convert.ToInt32(value) > maximum) { return (T)Enum.ToObject(typeof(T), maximum); }\n return value;\n}\n public static T ValidateItem<T>(T eEnumItem)\n{\n if (Enum.IsDefined(typeof(T), eEnumItem) == true)\n return eEnumItem;\n else\n return default(T);\n}\n public static Enum Clamp(this Enum value, Enum minimum, Enum maximum)\n{\n if (Convert.ToInt32(value) < Convert.ToInt32(minimum)) { return minimum; }\n if (Convert.ToInt32(value) > Convert.ToInt32(maximum)) { return maximum; }\n return value;\n}\n public static MyEnum Clamp(MyEnum value)\n{\n if (value < MYENUM_MINIMUM) { return MYENUM_MINIMUM; }\n if (value > MYENUM_MAXIMUM) { return MYENUM_MAXIMUM; }\n return value;\n}\n" }, { "answer_id": 19036239, "author": "Schultz9999", "author_id": 494343, "author_profile": "https://Stackoverflow.com/users/494343", "pm_score": 1, "selected": false, "text": "Flags public static TEnum ParseEnum<TEnum>(string valueString, string parameterName = null)\n{\n var parsed = (TEnum)Enum.Parse(typeof(TEnum), valueString, true);\n decimal d;\n if (!decimal.TryParse(parsed.ToString(), out d))\n {\n return parsed;\n }\n\n if (!string.IsNullOrEmpty(parameterName))\n {\n throw new ArgumentException(string.Format(\"Bad parameter value. Name: {0}, value: {1}\", parameterName, valueString), parameterName);\n }\n else\n {\n throw new ArgumentException(\"Bad value. Value: \" + valueString);\n }\n}\n" }, { "answer_id": 21990178, "author": "Vman", "author_id": 299529, "author_profile": "https://Stackoverflow.com/users/299529", "pm_score": 3, "selected": false, "text": "public abstract class EnumValidator<TEnum> where TEnum : struct, IConvertible\n{\n protected static bool IsContiguous\n {\n get\n {\n int[] enumVals = Enum.GetValues(typeof(TEnum)).Cast<int>().ToArray();\n\n int lowest = enumVals.OrderBy(i => i).First();\n int highest = enumVals.OrderByDescending(i => i).First();\n\n return !Enumerable.Range(lowest, highest).Except(enumVals).Any();\n }\n }\n\n public static EnumValidator<TEnum> Create()\n {\n if (!typeof(TEnum).IsEnum)\n {\n throw new ArgumentException(\"Please use an enum!\");\n }\n\n return IsContiguous ? (EnumValidator<TEnum>)new ContiguousEnumValidator<TEnum>() : new JumbledEnumValidator<TEnum>();\n }\n\n public abstract bool IsValid(int value);\n}\n\npublic class JumbledEnumValidator<TEnum> : EnumValidator<TEnum> where TEnum : struct, IConvertible\n{\n private readonly int[] _values;\n\n public JumbledEnumValidator()\n {\n _values = Enum.GetValues(typeof (TEnum)).Cast<int>().ToArray();\n }\n\n public override bool IsValid(int value)\n {\n return _values.Contains(value);\n }\n}\n\npublic class ContiguousEnumValidator<TEnum> : EnumValidator<TEnum> where TEnum : struct, IConvertible\n{\n private readonly int _highest;\n private readonly int _lowest;\n\n public ContiguousEnumValidator()\n {\n List<int> enumVals = Enum.GetValues(typeof (TEnum)).Cast<int>().ToList();\n\n _lowest = enumVals.OrderBy(i => i).First();\n _highest = enumVals.OrderByDescending(i => i).First();\n }\n\n public override bool IsValid(int value)\n {\n return value >= _lowest && value <= _highest;\n }\n}\n //Pre import-loop\nEnumValidator< MyEnum > enumValidator = EnumValidator< MyEnum >.Create();\nwhile(import) //Tight RT loop.\n{\n bool isValid = enumValidator.IsValid(theValue);\n}\n" }, { "answer_id": 27305198, "author": "Doug S", "author_id": 1145177, "author_profile": "https://Stackoverflow.com/users/1145177", "pm_score": 4, "selected": false, "text": "Enum.IsDefined HashSet Contains int userInput = 4;\n// below, Enum.GetValues converts enum to array. We then convert the array to hashset.\nHashSet<int> validVals = new HashSet<int>((int[])Enum.GetValues(typeof(MyEnum)));\n// the following could be in a loop, or do multiple comparisons, etc.\nif (validVals.Contains(userInput))\n{\n // is valid\n}\n" }, { "answer_id": 38331283, "author": "Juan Carlos Velez", "author_id": 391895, "author_profile": "https://Stackoverflow.com/users/391895", "pm_score": 0, "selected": false, "text": "int value = 99;//Your int value\nif (Enum.IsDefined(typeof(your_enum_type), value))\n{\n //Todo when value is valid\n}else{\n //Todo when value is not valid\n}\n" }, { "answer_id": 55028274, "author": "Timo", "author_id": 543814, "author_profile": "https://Stackoverflow.com/users/543814", "pm_score": 4, "selected": false, "text": "Enum.IsDefined<TEnum>(TEnum value) HashSet<T> public static class EnumHelpers\n{\n /// <summary>\n /// Returns whether the given enum value is a defined value for its type.\n /// Throws if the type parameter is not an enum type.\n /// </summary>\n public static bool IsDefined<T>(T enumValue)\n {\n if (typeof(T).BaseType != typeof(System.Enum)) throw new ArgumentException($\"{nameof(T)} must be an enum type.\");\n\n return EnumValueCache<T>.DefinedValues.Contains(enumValue);\n }\n\n /// <summary>\n /// Statically caches each defined value for each enum type for which this class is accessed.\n /// Uses the fact that static things exist separately for each distinct type parameter.\n /// </summary>\n internal static class EnumValueCache<T>\n {\n public static HashSet<T> DefinedValues { get; }\n\n static EnumValueCache()\n {\n if (typeof(T).BaseType != typeof(System.Enum)) throw new Exception($\"{nameof(T)} must be an enum type.\");\n\n DefinedValues = new HashSet<T>((T[])System.Enum.GetValues(typeof(T)));\n }\n }\n}\n" }, { "answer_id": 56796430, "author": "Matt Jenkins", "author_id": 251200, "author_profile": "https://Stackoverflow.com/users/251200", "pm_score": 2, "selected": false, "text": "public static class EnumExtensions\n{\n /// <summary>Whether the given value is defined on its enum type.</summary>\n public static bool IsDefined<T>(this T enumValue) where T : Enum\n {\n return EnumValueCache<T>.DefinedValues.Contains(enumValue);\n }\n \n private static class EnumValueCache<T> where T : Enum\n {\n public static readonly HashSet<T> DefinedValues = new HashSet<T>((T[])Enum.GetValues(typeof(T)));\n }\n}\n if (myEnumValue.IsDefined()) { ... }\n public static class EnumExtensions\n{\n /// <summary>Whether the given value is defined on its enum type.</summary>\n public static bool IsDefined<T>(this T enumValue) where T : struct, Enum\n {\n return EnumValueCache<T>.DefinedValues.Contains(enumValue);\n }\n\n private static class EnumValueCache<T> where T : struct, Enum\n {\n public static readonly HashSet<T> DefinedValues = new(Enum.GetValues<T>());\n }\n}\n" }, { "answer_id": 59470338, "author": "Cemal", "author_id": 12493422, "author_profile": "https://Stackoverflow.com/users/12493422", "pm_score": 1, "selected": false, "text": "public class EnumValidator<TEnum> : AbstractValidator<TEnum> where TEnum : struct, IConvertible, IComparable, IFormattable\n{\n public EnumValidator(string message)\n {\n RuleFor(a => a).Must(a => typeof(TEnum).IsEnum).IsInEnum().WithMessage(message);\n }\n\n}\n public class Customer \n{\n public string Name { get; set; }\n public Address address{ get; set; }\n public AddressType type {get; set;}\n}\npublic class Address \n{\n public string Line1 { get; set; }\n public string Line2 { get; set; }\n public string Town { get; set; }\n public string County { get; set; }\n public string Postcode { get; set; }\n public enum AddressType\n{\n HOME,\n WORK\n}\n public class CustomerValidator : AbstractValidator<Customer>\n{\n public CustomerValidator()\n {\n RuleFor(x => x.type).SetValidator(new EnumValidator<AddressType>(\"errormessage\");\n }\n}\n" }, { "answer_id": 71877470, "author": "Christopher Eberle", "author_id": 15324778, "author_profile": "https://Stackoverflow.com/users/15324778", "pm_score": 1, "selected": false, "text": "//System.Diagnostics - Stopwatch\n//System - ConsoleColor\n//System.Linq - Enumerable\nStopwatch myTimer = Stopwatch.StartNew();\nint myCyclesMin = 0;\nint myCyclesCount = 10000000;\nlong myExt_IsDefinedTicks;\nlong myEnum_IsDefinedTicks;\nforeach (int lCycles in Enumerable.Range(myCyclesMin, myCyclesMax))\n{\n Console.WriteLine(string.Format(\"Cycles: {0}\", lCycles));\n\n myTimer.Restart();\n foreach (int _ in Enumerable.Range(0, lCycles)) { ConsoleColor.Green.IsDefined(); }\n myExt_IsDefinedTicks = myTimer.ElapsedTicks;\n\n myTimer.Restart();\n foreach (int _ in Enumerable.Range(0, lCycles)) { Enum.IsDefined(typeof(ConsoleColor), ConsoleColor.Green); }\n myEnum_IsDefinedTicks = myTimer.E\n\n Console.WriteLine(string.Format(\"object.IsDefined() Extension Elapsed: {0}\", myExt_IsDefinedTicks.ToString()));\n Console.WriteLine(string.Format(\"Enum.IsDefined(Type, object): {0}\", myEnum_IsDefinedTicks.ToString()));\n if (myExt_IsDefinedTicks == myEnum_IsDefinedTicks) { Console.WriteLine(\"Same\"); }\n else if (myExt_IsDefinedTicks < myEnum_IsDefinedTicks) { Console.WriteLine(\"Extension\"); }\n else if (myExt_IsDefinedTicks > myEnum_IsDefinedTicks) { Console.WriteLine(\"Enum\"); }\n}\n Cycles: 0\nobject.IsDefined() Extension Elapsed: 399\nEnum.IsDefined(Type, object): 31\nEnum\nCycles: 1\nobject.IsDefined() Extension Elapsed: 213654\nEnum.IsDefined(Type, object): 1077\nEnum\nCycles: 2\nobject.IsDefined() Extension Elapsed: 108\nEnum.IsDefined(Type, object): 112\nExtension\nCycles: 3\nobject.IsDefined() Extension Elapsed: 9\nEnum.IsDefined(Type, object): 30\nExtension\nCycles: 4\nobject.IsDefined() Extension Elapsed: 9\nEnum.IsDefined(Type, object): 35\nExtension\n Enum.IsDefined(typeof(T), object) Enum.IsDefined(typeof(T), object) lCycles = 50000 Enum.IsDefined(typeof(T), object) object.IsDefined() object.IsDefined() Enum.IsDefined(typeof(T), object) Enum.IsDefined(typeof(T), object) Enum.IsDefined(typeof(T), object) Enum.IsDefined(typeof(T), object) //System.Collections.Specialized - HybridDictionary\nprivate static class EnumHybridDictionaryValueCache<T> where T : Enum\n {\n static T[] enumValues = (T[])Enum.GetValues(typeof(T));\n\n static HybridDictionary PopulateDefinedValues()\n {\n HybridDictionary myDictionary = new HybridDictionary(enumValues.Length);\n foreach (T lEnumValue in enumValues)\n {\n //Has to be unique, values are actually based on the int value. Enums with multiple aliases for one value will fail without checking.\n //Check implicitly by using assignment.\n myDictionary[lEnumValue] = lEnumValue;\n }\n return myDictionary;\n }\n\n public static readonly HybridDictionary DefinedValues = PopulateDefinedValues();\n }\n\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13615", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1154/" ]
13,620
<p>(assume php5) consider</p> <pre><code>&lt;?php $foo = 'some words'; //case 1 print "these are $foo"; //case 2 print "these are {$foo}"; //case 3 print 'these are ' . $foo; ?&gt; </code></pre> <p>Is there much of a difference between 1 and 2?</p> <p>If not, what about between 1/2 and 3?</p>
[ { "answer_id": 13665, "author": "Adam Wright", "author_id": 1200, "author_profile": "https://Stackoverflow.com/users/1200", "pm_score": 7, "selected": true, "text": "function timeFunc($function, $runs)\n{\n $times = array();\n\n for ($i = 0; $i < $runs; $i++)\n {\n $time = microtime();\n call_user_func($function);\n $times[$i] = microtime() - $time;\n }\n\n return array_sum($times) / $runs;\n}\n\nfunction Method1()\n{ \n $foo = 'some words';\n for ($i = 0; $i < 10000; $i++)\n $t = \"these are $foo\";\n}\n\nfunction Method2()\n{\n $foo = 'some words';\n for ($i = 0; $i < 10000; $i++)\n $t = \"these are {$foo}\";\n}\n\nfunction Method3()\n {\n $foo = 'some words';\n for ($i = 0; $i < 10000; $i++)\n $t = \"these are \" . $foo;\n}\n\nprint timeFunc('Method1', 10) . \"\\n\";\nprint timeFunc('Method2', 10) . \"\\n\";\nprint timeFunc('Method3', 10) . \"\\n\";\n function Method4()\n {\n $foo = 'some words';\n for ($i = 0; $i < 10000; $i++)\n $t = 'these are ' . $foo;\n}\n\nprint timeFunc('Method4', 10) . \"\\n\";\n\nResults were:\n\n0.0014739\n0.0015574\n0.0011955\n0.001169\n" }, { "answer_id": 13680, "author": "Pierre Spring", "author_id": 1532, "author_profile": "https://Stackoverflow.com/users/1532", "pm_score": 4, "selected": false, "text": "\"these are \" . $foo\n 'these are ' . $foo;\n" }, { "answer_id": 482204, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 7, "selected": false, "text": "Single quotes: 0.061846971511841 seconds\nDouble quotes: 0.061599016189575 seconds\n" }, { "answer_id": 482318, "author": "kimsk", "author_id": 58905, "author_profile": "https://Stackoverflow.com/users/58905", "pm_score": 1, "selected": false, "text": "'parse me '.$i.' times'\n \"parse me $i times\"\n" }, { "answer_id": 1435564, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "$a = 'parse' . $this; \n $a = \"parse $this\";\n" }, { "answer_id": 12856650, "author": "Rob Forrest", "author_id": 236755, "author_profile": "https://Stackoverflow.com/users/236755", "pm_score": 2, "selected": false, "text": "$foo = \"hello {$bar}\";\n $foo = \"hello $bar\";\n $foo = 'hello' . $bar; \n" }, { "answer_id": 43625364, "author": "ywarnier", "author_id": 6499848, "author_profile": "https://Stackoverflow.com/users/6499848", "pm_score": 0, "selected": false, "text": "function timeFunc($function, $runs)\n{\n $times = array();\n\n for ($i = 0; $i < $runs; $i++)\n {\n $time = microtime();\n call_user_func($function);\n @$times[$i] = microtime() - $time;\n }\n\n return array_sum($times) / $runs;\n}\n\nfunction Method1()\n{ \n $foo = 'some words';\n $bar = 'other words';\n $bas = 3;\n for ($i = 0; $i < 10000; $i++)\n $t = \"these are $foo, $bar and $bas\";\n}\n\nfunction Method2()\n{\n $foo = 'some words';\n $bar = 'other words';\n $bas = 3;\n for ($i = 0; $i < 10000; $i++)\n $t = \"these are {$foo}, {$bar} and {$bas}\";\n}\n\nfunction Method3()\n{\n $foo = 'some words';\n $bar = 'other words';\n $bas = 3;\n for ($i = 0; $i < 10000; $i++)\n $t = \"these are \" . $foo . \", \" . $bar . \" and \" .$bas;\n}\n\nprint timeFunc('Method1', 10) . \"\\n\";\nprint timeFunc('Method2', 10) . \"\\n\";\nprint timeFunc('Method3', 10) . \"\\n\";\n 0.0016254\n0.0015719\n0.0019806\n 0.0016495\n0.0015608\n0.0022755\n" }, { "answer_id": 62986215, "author": "Stackoverflow", "author_id": 7180968, "author_profile": "https://Stackoverflow.com/users/7180968", "pm_score": 0, "selected": false, "text": "function Method6(){\n $k1 = 'AAA';\n for($i = 0; $i < 10000; $i ++)$t = <<<'EOF'\nK1= \nEOF\n.$k1.\n<<<'EOF'\nK2=\nEOF\n.$k1;\n }\n function Method5(){\n $k1 = 'AAA';\n for($i = 0; $i < 10000; $i ++)$t = <<<EOF\nK1= $k1\nEOF\n.<<<EOF\nK2=$k1 \nEOF;\n }\n function timeFunc($function)" }, { "answer_id": 68206483, "author": "Rinshan Kolayil", "author_id": 11543253, "author_profile": "https://Stackoverflow.com/users/11543253", "pm_score": 0, "selected": false, "text": "<?php\n$start_time = microtime(true);\n$result = \"\";\nfor ($i = 0; $i < 700000; $i++) {\n $result .= \"THE STRING APPENDED IS \" . $i;\n // AND $result .= 'THE STRING APPENDED IS ' . $i;\n // AND $result .= \"THE STRING APPENDED IS $i\";\n}\necho $result;\n$end_time = microtime(true);\necho \"<br><br>\";\necho ($end_time - $start_time) . \" Seconds\";\n 1. \"THE STRING APPENDED IS \" . $i = 0.16744208335876\n 2. 'THE STRING APPENDED IS ' . $i = 0.16724419593811\n 3. \"THE STRING APPENDED IS $i\" = 0.16815495491028\n 1. \"THE STRING APPENDED IS \" . $i = 0.27664494514465\n 2. 'THE STRING APPENDED IS ' . $i = 0.27818703651428\n 3. \"THE STRING APPENDED IS $i\" = 0.28839707374573\n" }, { "answer_id": 68391660, "author": "Meloman", "author_id": 2282880, "author_profile": "https://Stackoverflow.com/users/2282880", "pm_score": 0, "selected": false, "text": "$array['key'] $array[\"key\"] $var = \"some text\"; $var = 'some text'; function getArrDblQuote() { \n $start1 = microtime(true);\n $array1 = array(\"key\" => \"value\");\n for ($i = 0; $i < 10000000; $i++)\n $t1 = $array1[\"key\"];\n echo microtime(true) - $start1;\n}\nfunction getArrSplQuote() {\n $start2 = microtime(true);\n $array2 = array('key' => 'value');\n for ($j = 0; $j < 10000000; $j++)\n $t2 = $array2['key'];\n echo microtime(true) - $start2;\n}\n\nfunction setArrDblQuote() { \n $start3 = microtime(true);\n for ($k = 0; $k < 10000000; $k++)\n $array3 = array(\"key\" => \"value\");\n echo microtime(true) - $start3;\n}\nfunction setArrSplQuote() {\n $start4 = microtime(true);\n for ($l = 0; $l < 10000000; $l++)\n $array4 = array('key' => 'value');\n echo microtime(true) - $start4;\n}\n\nfunction setStrDblQuote() { \n $start5 = microtime(true);\n for ($m = 0; $m < 10000000; $m++)\n $var1 = \"value\";\n echo microtime(true) - $start5;\n}\nfunction setStrSplQuote() {\n $start6 = microtime(true);\n for ($n = 0; $n < 10000000; $n++)\n $var2 = 'value';\n echo microtime(true) - $start6;\n}\n\nprint getArrDblQuote() . \"\\n<br>\";\nprint getArrSplQuote() . \"\\n<br>\";\nprint setArrDblQuote() . \"\\n<br>\";\nprint setArrSplQuote() . \"\\n<br>\";\nprint setStrDblQuote() . \"\\n<br>\";\nprint setStrSplQuote() . \"\\n<br>\";\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13620", "https://Stackoverflow.com", "https://Stackoverflow.com/users/314/" ]
13,678
<p>I am part of a high school robotics team, and there is some debate about which language to use to program our robot. We are choosing between C (or maybe C++) and LabVIEW. There are pros for each language.</p> <p>C(++):</p> <ul> <li>Widely used</li> <li>Good preparation for the future (most programming positions require text-based programmers.)</li> <li>We can expand upon our C codebase from last year</li> <li>Allows us to better understand what our robot is doing.</li> </ul> <p>LabVIEW</p> <ul> <li>Easier to visualize program flow (blocks and wires, instead of lines of code)</li> <li>Easier to teach (Supposedly...)</li> <li>"The future of programming is graphical." (Think so?)</li> <li>Closer to the Robolab background that some new members may have.</li> <li>Don't need to intimately know what's going on. Simply tell the module to find the red ball, don't need to know how.</li> </ul> <p>This is a very difficult decision for us, and we've been debating for a while. Based on those pros for each language, and on the experience you've got, <strong>what do you think the better option is?</strong> Keep in mind that we aren't necessarily going for pure efficiency. We also hope to prepare our programmers for a future in programming.</p> <p>Also:</p> <ul> <li><strong>Do you think that graphical languages such as LabVEIW are the future of programming?</strong></li> <li><strong>Is a graphical language easier to learn than a textual language?</strong> I think that they should be about equally challenging to learn.</li> <li>Seeing as we are partailly rooted in helping people learn, <strong>how much should we rely on prewritten modules, and how much should we try to write on our own?</strong> ("Good programmers write good code, great programmers copy great code." But isn't it worth being a good programmer, first?)</li> </ul> <p>Thanks for the advice!</p> <hr> <p>Edit: I'd like to emphasize this question more: The team captain thinks that LabVIEW is better for its ease of learning and teaching. <strong>Is that true?</strong> I think that C could be taught just as easily, and beginner-level tasks would still be around with C. I'd really like to hear your opinions. <strong>Is there any reason that typing while{} should be any more difficult than creating a "while box?"</strong> <strong>Isn't it just as intuitive that program flows line by line, only modified by ifs and loops, as it is intuitive that the program flows through the wire, only modified by ifs and loops!?</strong></p> <p>Thanks again!</p> <hr> <p>Edit: I just realized that this falls under the topic of "language debate." I hope it's okay, because it's about what's best for a specific branch of programming, with certain goals. If it's not... I'm sorry...</p>
[ { "answer_id": 13746, "author": "Brendan", "author_id": 199, "author_profile": "https://Stackoverflow.com/users/199", "pm_score": 6, "selected": true, "text": "y = x*x + x + 1 while, for, if" }, { "answer_id": 352310, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 1, "selected": false, "text": "INCREASEJITTER oval(100, 200, 10, 10)" }, { "answer_id": 1324004, "author": "Stephen Friederichs", "author_id": 39492, "author_profile": "https://Stackoverflow.com/users/39492", "pm_score": 0, "selected": false, "text": "z=x+y x+=y" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ]
13,698
<p>I've seen it mentioned in many blogs around the net, but I believe it shoud be discussed here. What can we do when we have an MVC framework (I am interested in ZEND) in PHP but our host does not provide mod_rewrite? Are there any "short-cuts"? Can we transfer control in any way (so that a mapping may occur between pages)? Any ideas? Thank you :-)</p>
[ { "answer_id": 13777, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 3, "selected": true, "text": "mod_rewrite" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13698", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1622/" ]
13,725
<p><code>NSInteger</code>/<code>NSUInteger</code> are Cocoa-defined replacements for the regular built-in types.</p> <p>Is there any benefit to using the NS* types over the built-ins? Which do you prefer and why? Are <code>NSInteger</code> and <code>int</code> the same width on 32-bit / 64-bit platforms?</p>
[ { "answer_id": 13730, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 4, "selected": false, "text": "#if __LP64__ || NS_BUILD_32_LIKE_64\ntypedef long NSInteger;\ntypedef unsigned long NSUInteger;\n#else\ntypedef int NSInteger;\ntypedef unsigned int NSUInteger;\n#endif\n" }, { "answer_id": 199472, "author": "mmalc", "author_id": 23233, "author_profile": "https://Stackoverflow.com/users/23233", "pm_score": 5, "selected": false, "text": "NSInteger malloc malloc NSInteger NSInteger sint_32" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13725", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1043/" ]
13,751
<p>How can I permanently enable line numbers in IntelliJ IDEA?</p>
[ { "answer_id": 27353549, "author": "MaxM", "author_id": 1518458, "author_profile": "https://Stackoverflow.com/users/1518458", "pm_score": 3, "selected": false, "text": "Editor -> General -> Appearance" }, { "answer_id": 34649002, "author": "mpontillo", "author_id": 77939, "author_profile": "https://Stackoverflow.com/users/77939", "pm_score": 4, "selected": false, "text": "Show Line Numbers :set nu\n" }, { "answer_id": 37281299, "author": "A0__oN", "author_id": 5065092, "author_profile": "https://Stackoverflow.com/users/5065092", "pm_score": 3, "selected": false, "text": "IntelliJ IDEA 2016.1.2" }, { "answer_id": 61404545, "author": "bhordupur", "author_id": 5174618, "author_profile": "https://Stackoverflow.com/users/5174618", "pm_score": 3, "selected": false, "text": "Editor Show line numbers" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13751", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
13,753
<p>I'm missing something here:</p> <pre><code>$objSearcher = New-Object System.DirectoryServices.DirectorySearcher $objSearcher.SearchRoot = New-Object System.DirectoryServices.DirectoryEntry $objSearcher.Filter = ("(objectclass=computer)") $computers = $objSearcher.findall() </code></pre> <p>So the question is why do the two following outputs differ?</p> <pre><code>$computers | %{ "Server name in quotes $_.properties.name" "Server name not in quotes " + $_.properties.name } PS&gt; $computers[0] | %{"$_.properties.name"; $_.properties.name} System.DirectoryServices.SearchResult.properties.name GORILLA </code></pre>
[ { "answer_id": 13878, "author": "slipsec", "author_id": 1635, "author_profile": "https://Stackoverflow.com/users/1635", "pm_score": 0, "selected": false, "text": "PS C:\\> $computers[0] | %{ \"$_.properties.name\"; \"$($_.properties.name)\" }\nSystem.DirectoryServices.SearchResult.properties.name\nGORILLA\n $computers[0] | %{ $_.properties.name[0]}\n" }, { "answer_id": 13972, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 2, "selected": true, "text": "\"Server name in quotes $($_.properties.name)\" \n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1635/" ]
13,763
<p>Is there a function like <code>document.getElementById("FirstDiv").clear()</code>?</p>
[ { "answer_id": 13769, "author": "eplawless", "author_id": 1370, "author_profile": "https://Stackoverflow.com/users/1370", "pm_score": 6, "selected": false, "text": "var mydiv = document.getElementById('FirstDiv');\nwhile(mydiv.firstChild) {\n mydiv.removeChild(mydiv.firstChild);\n}\n" }, { "answer_id": 14782, "author": "Jason Bunting", "author_id": 1790, "author_profile": "https://Stackoverflow.com/users/1790", "pm_score": 8, "selected": true, "text": "myChildNode.parentNode.removeChild(myChildNode);\n function removeElement(node) {\n node.parentNode.removeChild(node);\n}\n" }, { "answer_id": 3388480, "author": "Chris Jacob", "author_id": 114140, "author_profile": "https://Stackoverflow.com/users/114140", "pm_score": 2, "selected": false, "text": "<select id=\"foo\">\n <option value=\"1\">1</option>\n <option value=\"2\">2</option>\n <option value=\"3\">3</option>\n</select>\n // remove child \"option\" element with a \"value\" attribute equal to \"2\"\n$(\"#foo > option[value='2']\").remove();\n\n// remove all child \"option\" elements\n$(\"#foo > option\").remove();\n" }, { "answer_id": 7750327, "author": "eagle", "author_id": 961780, "author_profile": "https://Stackoverflow.com/users/961780", "pm_score": 2, "selected": false, "text": "//for Internet Explorer\ndocument.getElementById(\"FirstDiv\").removeNode(true);\n\n//for other browsers\nvar fDiv = document.getElementById(\"FirstDiv\");\nfDiv.removeChild(fDiv.childNodes[0]); //first check on which node your required node exists, if it is on [0] use this, otherwise use where it exists.\n" }, { "answer_id": 40543830, "author": "Gibolt", "author_id": 974045, "author_profile": "https://Stackoverflow.com/users/974045", "pm_score": 4, "selected": false, "text": "child.remove() document.getElementById(\"FirstDiv\").remove()\n" }, { "answer_id": 44698638, "author": "Vivek Tiwari", "author_id": 7921020, "author_profile": "https://Stackoverflow.com/users/7921020", "pm_score": 1, "selected": false, "text": " var p=document.getElementById('childId').parentNode;\n var c=document.getElementById('childId');\n p.removeChild(c);\n alert('Deleted');\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13763", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
13,786
<p>Are we supposed to find workarounds in our web applications so that they will work in every situation? Is it time to do away with IE6 programming?</p>
[ { "answer_id": 2863045, "author": "alemani", "author_id": 291181, "author_profile": "https://Stackoverflow.com/users/291181", "pm_score": 1, "selected": false, "text": "http://browsershots.org/\n http://www.cmsmatrix.org/\n http://www.w3schools.com/\n http://meyerweb.com/eric/thoughts/2007/05/01/reset-reloaded/\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13786", "https://Stackoverflow.com", "https://Stackoverflow.com/users/184/" ]
13,791
<p>I am trying to implement string unescaping with Python regex and backreferences, and it doesn't seem to want to work very well. I'm sure it's something I'm doing wrong but I can't figure out what...</p> <pre><code>&gt;&gt;&gt; import re &gt;&gt;&gt; mystring = r"This is \n a test \r" &gt;&gt;&gt; p = re.compile( "\\\\(\\S)" ) &gt;&gt;&gt; p.sub( "\\1", mystring ) 'This is n a test r' &gt;&gt;&gt; p.sub( "\\\\\\1", mystring ) 'This is \\n a test \\r' &gt;&gt;&gt; p.sub( "\\\\1", mystring ) 'This is \\1 a test \\1' </code></pre> <p>I'd like to replace \\[char] with \[char], but backreferences in Python don't appear to follow the same rules they do in every other implementation I've ever used. Could someone shed some light?</p>
[ { "answer_id": 13844, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 2, "selected": false, "text": "\"\\\\n\" == r\"\\n\"\n\n>>> import re\n>>> mystring = r\"This is \\\\n a test \\\\r\"\n>>> p = re.compile( r\"[\\\\][\\\\](.)\" )\n>>> print p.sub( r\"\\\\\\1\", mystring )\nThis is \\n a test \\r\n>>>\n >>> d = {'n':'\\n', 'r':'\\r', 'f':'\\f'}\n>>> p = re.compile(r\"[\\\\]([nrfv])\")\n>>> print p.sub(lambda mo: d[mo.group(1)], mystring)\nThis is \\\n a test \\\n>>>\n" }, { "answer_id": 13869, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "'This is \\\\n a test \\\\r'\n This is \\n a test \\r\n >>> mystring = r\"This is \\n a test \\r\"\n>>> mystring\n'This is \\\\n a test \\\\r'\n>>> print mystring\nThis is \\n a test \\r\n" }, { "answer_id": 13882, "author": "eplawless", "author_id": 1370, "author_profile": "https://Stackoverflow.com/users/1370", "pm_score": 1, "selected": false, "text": ">>> mystring = r\"This is \\n ridiculous\"\n>>> print mystring\nThis is \\n ridiculous\n>>> p = re.compile( r\"\\\\(\\S)\" )\n>>> print p.sub( 'bloody', mystring )\nThis is bloody ridiculous\n>>> print p.sub( r'\\1', mystring )\nThis is n ridiculous\n>>> print p.sub( r'\\\\1', mystring )\nThis is \\1 ridiculous\n>>> print p.sub( r'\\\\\\1', mystring )\nThis is \\n ridiculous\n This is \nridiculous\n" }, { "answer_id": 13943, "author": "markpasc", "author_id": 1472, "author_profile": "https://Stackoverflow.com/users/1472", "pm_score": 4, "selected": true, "text": "string-escape >>> mystring = r\"This is \\n a test \\r\"\n>>> mystring.decode('string-escape')\n'This is \\n a test \\r'\n>>> print mystring.decode('string-escape')\nThis is \n a test \n>>> \n" }, { "answer_id": 13958, "author": "eplawless", "author_id": 1370, "author_profile": "https://Stackoverflow.com/users/1370", "pm_score": 0, "selected": false, "text": "preg_replace_callback() preg_replace() string.decode('string-escape')" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13791", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1370/" ]
13,832
<p>I have taken over the development of a web application that is targeted at the .net 1.0 framework and is written in C# and Visual Basic. </p> <p>I decided that the first thing we need to do is refine the build process, I wrote build files for the C# projects, but am having tons of problems creating a build file for Visual Basic. </p> <p>Admittedly, I do not personally know VB, but it seems like I have to hardcode all the imports and references in my build file to get anything to work...certainly not the best way to be doing things...</p> <p>For any example: if I do not include the namespace System in the build file I will get several errors of common Unkown Types e.g: Guid</p> <p>does NAnt typically require this for VB code or is does the VB code need a possible NAnt-freindly refactoring?</p> <p>Does anybody have VB NAnt tips?</p>
[ { "answer_id": 32391, "author": "RobertTheGrey", "author_id": 1107, "author_profile": "https://Stackoverflow.com/users/1107", "pm_score": 1, "selected": false, "text": "<target name=\"WinBuild\">\n <exec program=\"msbuild.exe\"\n basedir=\"${DotNetPath}\"\n workingdir=\"${SolutionPath}\"\n commandline=\"MySolution.sln \n /nologo /verbosity:normal /noconsolelogger \n /p:Configuration=Debug /target:Rebuild\" />\n</target>\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13832", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
13,851
<p>I am having trouble with IE7. I have a header, which is an IMG. Under it I have a div that represents a menu, they have to be attached to each other without space in between. Both are 1000px width. In Opera and FireFox the header and the menu are neatly attached to each other. However, in IE7, there is a small space between the menu DIV and the IMG. I have tried explicitly defining padding and margin on the IMG, however it does not work. I have had this problem before, so it seems to be a IE7 quirk.</p> <p>My HTML Code:</p> <p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false"> <div class="snippet-code"> <pre class="snippet-code-html lang-html prettyprint-override"><code>&lt;div id="middle"&gt; &lt;img id="ctl00_headerHolder_headerImage" src="pictures/headers/header_home.jpg" style="border-width:0px;" /&gt; &lt;div id="ctl00_menuPanel" class="menu"&gt; &lt;a id="ctl00_home" href="Default.aspx" style="color:#FFCC33;"&gt;Home&lt;/a&gt; | &lt;a id="ctl00_leden" href="Leden.aspx"&gt;Leden&lt;/a&gt; | &lt;a id="ctl00_agenda" href="Agenda.aspx"&gt;Agenda&lt;/a&gt; | &lt;a id="ctl00_fotos" href="Fotos.aspx"&gt;Foto's&lt;/a&gt; | &lt;a id="ctl00_geschiedenis" href="Geschiedenis.aspx"&gt;Geschiedenis&lt;/a&gt; | &lt;a id="ctl00_gastenboek" href="Gastenboek.aspx"&gt;Gastenboek&lt;/a&gt; &lt;/div&gt; &lt;/div&gt;</code></pre> </div> </div> </p>
[ { "answer_id": 13855, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "img {\npadding: 0px;\nmargin: 0px;\ndisplay: block;\n}\n" }, { "answer_id": 14183, "author": "Akira", "author_id": 795, "author_profile": "https://Stackoverflow.com/users/795", "pm_score": 0, "selected": false, "text": "#middle { font-size: 0; line-height: 0; }\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
13,857
<p>I've been reading a lot about closures and I think I understand them, but without clouding the picture for myself and others, I am hoping someone can explain closures as succinctly and clearly as possible. I'm looking for a simple explanation that might help me understand where and why I would want to use them.</p>
[ { "answer_id": 13875, "author": "Anders Eurenius", "author_id": 1421, "author_profile": "https://Stackoverflow.com/users/1421", "pm_score": 6, "selected": false, "text": ">>> def makeConstantAdder(x):\n... constant = x\n... def adder(y):\n... return y + constant\n... return adder\n... \n>>> f = makeConstantAdder(12)\n>>> f(3)\n15\n>>> g = makeConstantAdder(4)\n>>> g(3)\n7\n" }, { "answer_id": 13902, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "x = 0\n\ndef f():\n def g(): \n return x * 2\n return g\n\n\nclosure = f()\nprint(closure()) # 0\nx = 2\nprint(closure()) # 4\n" }, { "answer_id": 24061, "author": "Jegschemesch", "author_id": 1586, "author_profile": "https://Stackoverflow.com/users/1586", "pm_score": 4, "selected": false, "text": "def foo():\n x = 3\n def bar():\n print x\n x = 5\n return bar\n\nbar = foo()\nbar() # print 5\n def foo():\n x = 3\n def bar():\n print x\n def ack():\n nonlocal x\n x = 7\n x = 5\n return (bar, ack)\n\nbar, ack = foo()\nack() # modify x of the call to foo\nbar() # print 7\n" }, { "answer_id": 141426, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 8, "selected": true, "text": "def make_counter():\n i = 0\n def counter(): # counter() is a closure\n nonlocal i\n i += 1\n return i\n return counter\n\nc1 = make_counter()\nc2 = make_counter()\n\nprint (c1(), c1(), c2(), c2())\n# -> 1 2 1 2\n" }, { "answer_id": 18918261, "author": "Ricardo Avila", "author_id": 2799405, "author_profile": "https://Stackoverflow.com/users/2799405", "pm_score": 0, "selected": false, "text": "def makefunction (x)\n def multiply (a,b)\n puts a*b\n end\n return lambda {|n| multiply(n,x)} # => returning a closure\nend\n\nfunc = makefunction(2) # => we capture the closure\nfunc.call(6) # => Result equal \"12\" \n" }, { "answer_id": 24816814, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 2, "selected": false, "text": "__closure__ def enclosure(foo):\n def closure(bar):\n print(foo, bar)\n return closure\n\nclosure_instance = enclosure('foo')\n closure_instance bar 'foo' bar cell_contents __closure__ >>> closure_instance.__closure__[0].cell_contents\n'foo'\n 'foo' >>> closure_instance('bar')\nfoo bar\n>>> closure_instance('baz')\nfoo baz\n>>> closure_instance('quux')\nfoo quux\n >>> closure_instance.__closure__ = None\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\nTypeError: readonly attribute\n functools.partial >>> from __future__ import print_function # use this if you're in Python 2.\n>>> partial_function = functools.partial(print, 'foo')\n>>> partial_function('bar')\nfoo bar\n>>> partial_function('baz')\nfoo baz\n>>> partial_function('quux')\nfoo quux\n" }, { "answer_id": 32726068, "author": "thiagoh", "author_id": 889213, "author_profile": "https://Stackoverflow.com/users/889213", "pm_score": 1, "selected": false, "text": "def closure(x):\n def counter():\n nonlocal x\n x += 1\n return x\n return counter;\n\ncounter1 = closure(100);\ncounter2 = closure(200);\n\nprint(\"i from closure 1 \" + str(counter1()))\nprint(\"i from closure 1 \" + str(counter1()))\nprint(\"i from closure 2 \" + str(counter2()))\nprint(\"i from closure 1 \" + str(counter1()))\nprint(\"i from closure 1 \" + str(counter1()))\nprint(\"i from closure 1 \" + str(counter1()))\nprint(\"i from closure 2 \" + str(counter2()))\n\n# result\n\ni from closure 1 101\ni from closure 1 102\ni from closure 2 201\ni from closure 1 103\ni from closure 1 104\ni from closure 1 105\ni from closure 2 202\n" }, { "answer_id": 47981346, "author": "Dinesh Sonachalam", "author_id": 5674391, "author_profile": "https://Stackoverflow.com/users/5674391", "pm_score": 3, "selected": false, "text": "# A Closure is a function object that remembers values in enclosing scopes even if they are not present in memory.\n\n# Defining a closure\n\n# This is an outer function.\ndef outer_function(message):\n # This is an inner nested function.\n def inner_function():\n print(message)\n return inner_function\n\n# Now lets call the outer function and return value bound to name 'temp'\ntemp = outer_function(\"Hello\")\n# On calling temp, 'message' will be still be remembered although we had finished executing outer_function()\ntemp()\n# Technique by which some data('message') that remembers values in enclosing scopes \n# even if they are not present in memory is called closures\n\n# Output: Hello\n # Example 2\ndef make_multiplier_of(n): # Outer function\n def multiplier(x): # Inner nested function\n return x * n\n return multiplier\n# Multiplier of 3\ntimes3 = make_multiplier_of(3)\n# Multiplier of 5\ntimes5 = make_multiplier_of(5)\nprint(times5(3)) # 15\nprint(times3(2)) # 6\n" }, { "answer_id": 49885629, "author": "Nitish Chauhan", "author_id": 4708210, "author_profile": "https://Stackoverflow.com/users/4708210", "pm_score": 1, "selected": false, "text": "class Test():\n def decorator(func):\n def wrapper(*args):\n b = args[1] + 5\n return func(b)\n return wrapper\n\n@decorator\ndef foo(val):\n print val + 2\n\nobj = Test()\nobj.foo(5)\n" }, { "answer_id": 50302797, "author": "Eunjung Lee", "author_id": 9779393, "author_profile": "https://Stackoverflow.com/users/9779393", "pm_score": 1, "selected": false, "text": "def maker(a, b, n):\n margin_top = 2\n padding = 4\n def message(msg):\n print('\\n’ * margin_top, a * n, \n ' ‘ * padding, msg, ' ‘ * padding, b * n)\n return message\n\nf = maker('*', '#', 5)\ng = maker('', '♥’, 3)\n…\nf('hello')\ng(‘good bye!')\n ***** hello #####\n\n good bye! ♥♥♥\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13857", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1649/" ]
13,863
<p>I have been trying to find an easy way to parse a search query and convert it to an SQL query for my DB. </p> <p>I have found two solutions:</p> <ol> <li><em><a href="https://lucene.apache.org/" rel="nofollow noreferrer">Lucene</a></em>: Powerful Java-based search engine, contains a query parser but it isn't very configurable and I could find a way to easily hack/adapt it to create SQL queries.</li> <li><em><a href="http://www.antlr.org/" rel="nofollow noreferrer">ANTLR</a></em>: A veteran text lexer-parser. Used for building anything from compilers to sky scrapers. ANTLR is highly configurable but everyone touching the code from now on will have to learn a new language...</li> </ol> <p>Any other ideas?</p>
[ { "answer_id": 154639, "author": "Mr. Shiny and New 安宇", "author_id": 7867, "author_profile": "https://Stackoverflow.com/users/7867", "pm_score": 1, "selected": false, "text": "new AndExp(new FieldContainsExp(\"NAME\", \"Harry\"), new FieldContainsExp(\"NAME\", \"Potter\")\n new AndExp(new FieldContainsExp(\"PUBLISHER\", \"Nature\"), FieldGreaterThan(\"PAGES\", 100))\n FieldContainsExp.toSQL(StringBuffer sql, Collection<Object> args) {\n sql.append(fieldName);\n sql.append(\" like \");\n sql.append(\"'%?%'\");\n args.add(value);\n}\n\nAndExp.toSQL(StringBuffer sql, Collection<Object> args) {\n exp1.toSQL(sql, args);\n sql.append(\" AND \");\n exp2.toSQL(sql, args);\n}\n" }, { "answer_id": 19051117, "author": "user2815040", "author_id": 2815040, "author_profile": "https://Stackoverflow.com/users/2815040", "pm_score": -1, "selected": false, "text": "int checkWord(String searchWord)\n{\n for(int i = 0; i < array.length; i++)\n {\n if(searchWord.equals(array[i]))\n return i;\n }\n return 0;\n\n}\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1651/" ]
13,927
<p>When I've registered an object <strong>foo</strong> to receive KVO notifications from another object <strong>bar</strong> (using addObserver:...), if I then deallocate <strong>foo</strong> do I need to send a <code>removeObserver:forKeyPath:</code> message to <strong>bar</strong> in -dealloc?</p>
[ { "answer_id": 14054, "author": "Chris Hanson", "author_id": 714, "author_profile": "https://Stackoverflow.com/users/714", "pm_score": 6, "selected": true, "text": "-removeObserver:forKeyPath: -[NSObject dealloc] -dealloc -retain -autorelease -finalize -dealloc -removeObserver:forKeyPath: -finalize -dealloc -finalize -invalidate" }, { "answer_id": 65336, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "-invalidate dealloc finalize." } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
13,938
<p><img src="https://i.stack.imgur.com/DibJS.jpg" alt="Visual Studio folder structure"></p> <p>I need some advice as to how I easily can separate test runs for unit tests and integration test in Visual Studio. Often, or always, I structure the solution as presented in the above picture: separate projects for unit tests and integration tests. The unit tests is run very frequently while the integration tests naturally is run when the context is correctly aligned.</p> <p>My goal is to somehow be able configure which tests (or test folders) to run when I use a keyboard shortcut. The tests should preferably be run by a graphical test runner (ReSharpers). So for example</p> <ul> <li>Alt+1 runs the tests in project BLL.Test, </li> <li>Alt+2 runs the tests in project DAL.Tests, </li> <li>Alt+3 runs them both (i.e. all the tests in the [Tests] folder, and</li> <li>Alt+4 runs the tests in folder [Tests.Integration].</li> </ul> <p>TestDriven.net have an option of running just the test in the selected folder or project by right-clicking it and select Run Test(s). Being able to do this, but via a keyboard command and with a graphical test runner would be awesome.</p> <p><img src="https://i.stack.imgur.com/NYnmJ.jpg" alt="TestDriven.net test run output"></p> <p>Currently I use VS2008, ReSharper 4 and nUnit. But advice for a setup in the general is of course also appreciated.</p>
[ { "answer_id": 13969, "author": "andynil", "author_id": 446, "author_profile": "https://Stackoverflow.com/users/446", "pm_score": 3, "selected": true, "text": "Sub TemporaryMacro()\n DTE.Windows.Item(Constants.vsWindowKindSolutionExplorer).Activate\n DTE.ActiveWindow.Object.GetItem(\"TestUnitTest\\Tests\").Select(vsUISelectionType.vsUISelectionTypeSelect)\n DTE.ExecuteCommand(\"ReSharper.UnitTest_ContextRun\")\nEnd Sub\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13938", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446/" ]
13,941
<p>I'd like to have a python program alert me when it has completed its task by making a beep noise. Currently, I use <code>import os</code> and then use a command line speech program to say &quot;Process complete&quot;. I much rather it be a simple &quot;bell.&quot;</p> <p>I know that there's a function that can be used in <em>Cocoa</em> apps, <code>NSBeep</code>, but I don't think that has much anything to do with this.</p> <p>I've also tried</p> <pre class="lang-py prettyprint-override"><code>print(\a) </code></pre> <p>but that didn't work.</p> <p>I'm using a Mac, if you couldn't tell by my <em>Cocoa</em> comment, so that may help.</p>
[ { "answer_id": 13949, "author": "gbc", "author_id": 1667, "author_profile": "https://Stackoverflow.com/users/1667", "pm_score": 7, "selected": true, "text": "import sys\nsys.stdout.write('\\a')\nsys.stdout.flush()\n print('\\a')\n" }, { "answer_id": 13959, "author": "markpasc", "author_id": 1472, "author_profile": "https://Stackoverflow.com/users/1472", "pm_score": 3, "selected": false, "text": "print('\\a') Carbon.Snd >>> import Carbon.Snd\n>>> Carbon.Snd.SysBeep(1)\n>>> \n help(Carbon.Snd)" }, { "answer_id": 34482, "author": "Barry Wark", "author_id": 2140, "author_profile": "https://Stackoverflow.com/users/2140", "pm_score": 4, "selected": false, "text": "from AppKit import NSBeep\nNSBeep()\n" }, { "answer_id": 6110229, "author": "Abhranil Das", "author_id": 711017, "author_profile": "https://Stackoverflow.com/users/711017", "pm_score": 3, "selected": false, "text": "$ sudo apt-get install python-pygame\n from pygame import mixer\nmixer.init() #you must initialize the mixer\nalert=mixer.Sound('bell.wav')\nalert.play()\n" }, { "answer_id": 46743047, "author": "Martin Müller", "author_id": 6488645, "author_profile": "https://Stackoverflow.com/users/6488645", "pm_score": 2, "selected": false, "text": "NSBeep() NSSound() from AppKit import NSSound\n#prepare sound:\nsound = NSSound.alloc()\nsound.initWithContentsOfFile_byReference_('/System/Library/Sounds/Ping.aiff', True)\n#rewind and play whenever you need it:\nsound.stop() #rewind\nsound.play()\n locate /System/Library/Sounds/*.aiff NSBeep() '/System/Library/Sounds/Funk.aiff'" }, { "answer_id": 71458296, "author": "chrischma", "author_id": 14157064, "author_profile": "https://Stackoverflow.com/users/14157064", "pm_score": 0, "selected": false, "text": "pip3 install mac_alerts\n from mac_alerts import alerts\nalerts.play_error() # plays an error sound\n" }, { "answer_id": 72691776, "author": "jitheshKuyyalil", "author_id": 9472425, "author_profile": "https://Stackoverflow.com/users/9472425", "pm_score": 0, "selected": false, "text": "pip3 install playsound\n from playsound import playsound\nplaysound('beep.wav')\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13941", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1615/" ]
13,963
<p>I want to parse a config file sorta thing, like so:</p> <pre><code>[KEY:Value] [SUBKEY:SubValue] </code></pre> <p>Now I started with a <code>StreamReader</code>, converting lines into character arrays, when I figured there's gotta be a better way. So I ask you, humble reader, to help me.</p> <p>One restriction is that it has to work in a Linux/Mono environment (1.2.6 to be exact). I don't have the latest 2.0 release (of Mono), so try to restrict language features to C# 2.0 or C# 1.0.</p>
[ { "answer_id": 13975, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "public string check()\n {\n ArrayList tags = getTags();\n\n\n int stackSize = tags.Count;\n\n Stack stack = new Stack(stackSize);\n\n foreach (string tag in tags)\n {\n if (!tag.Contains('/'))\n {\n stack.push(tag);\n }\n else\n {\n if (!stack.isEmpty())\n {\n string startTag = stack.pop();\n startTag = startTag.Substring(1, startTag.Length - 1);\n string endTag = tag.Substring(2, tag.Length - 2);\n if (!startTag.Equals(endTag))\n {\n return \"Fout: geen matchende eindtag\";\n }\n }\n else\n {\n return \"Fout: geen matchende openeningstag\";\n }\n }\n }\n\n if (!stack.isEmpty())\n {\n return \"Fout: geen matchende eindtag\";\n } \n return \"Xml is valid\";\n }\n" }, { "answer_id": 13983, "author": "eplawless", "author_id": 1370, "author_profile": "https://Stackoverflow.com/users/1370", "pm_score": 2, "selected": false, "text": "@\"(?&ltlevel>\\s) | \" +\n@\"(?&ltterm>[^:\\s]) | \" +\n@\"(?&ltseparator>:)\"\n abc ace" }, { "answer_id": 13990, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 5, "selected": true, "text": "customer:\n name: Orion\n age: 26\n addresses:\n - type: Work\n number: 12\n street: Bob Street\n - type: Home\n number: 15\n street: Secret Road\n" }, { "answer_id": 14274, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": -1, "selected": false, "text": "\\[KEY:(.*)\\] \n\\[SUBKEY:(.*)\\]\n" }, { "answer_id": 14292, "author": "ICR", "author_id": 214, "author_profile": "https://Stackoverflow.com/users/214", "pm_score": 0, "selected": false, "text": "private static Node ParseNode(TextReader reader)\n{\n Node node = new Node();\n int indentation = ParseWhitespace(reader);\n Expect(reader, '[');\n node.Key = ParseTerminatedString(reader, ':');\n node.Value = ParseTerminatedString(reader, ']');\n}\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/61/" ]
13,981
<p>I understand that the <code>Ruby 1.8 AST</code> is traversed at runtime using a big switch statement, and many things like calling a method in a class or parent module involve the interpreter looking up and down the tree as it goes. Is there a straightforward way of accessing this <code>AST</code> in a <code>Ruby C</code> extension? Does it involve the Ruby extension API, or necessitate hacking the internal data structures directly?</p>
[ { "answer_id": 14498, "author": "maetl", "author_id": 14446, "author_profile": "https://Stackoverflow.com/users/14446", "pm_score": 0, "selected": false, "text": "ParseTree" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/13981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14446/" ]
14,008
<p>I've been looking for some good genetic programming examples for C#. Anyone knows of good online/book resources? Wonder if there is a C# library out there for Evolutionary/Genetic programming?</p>
[ { "answer_id": 24674105, "author": "giacomelli", "author_id": 956886, "author_profile": "https://Stackoverflow.com/users/956886", "pm_score": 2, "selected": false, "text": "var selection = new EliteSelection();\nvar crossover = new OrderedCrossover();\nvar mutation = new ReverseSequenceMutation();\nvar fitness = new YourFitnessFunction();\nvar chromosome = new YourChromosome();\nvar population = new Population (50, 70, chromosome);\n\nvar ga = new GeneticAlgorithm(population, fitness, selection, crossover, mutation);\n\nga.Start();\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/14008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/877/" ]
14,029
<p>I have a ListView control, and I'm trying to figure out the easiest/best way to disallow changing the selected row(s), without <em>hiding</em> the selected row(s).</p> <p>I know there's a <code>HideSelection</code> property, but that only works when the <code>ListView</code> is still enabled (but not focused). I need the selection to be viewable even when the ListView is disabled.</p> <p>How can I implement this?</p>
[ { "answer_id": 1090706, "author": "Mugunth", "author_id": 90165, "author_profile": "https://Stackoverflow.com/users/90165", "pm_score": 0, "selected": false, "text": " private void listViewABC_SelectedIndexChanged(object sender, EventArgs e)\n {\n listViewABC.SelectedItems.Clear();\n }\n" } ]
2008/08/17
[ "https://Stackoverflow.com/questions/14029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/369/" ]
14,031
<p>In the past I've never been a fan of using triggers on database tables. To me they always represented some "magic" that was going to happen on the database side, far far away from the control of my application code. I also wanted to limit the amount of work the DB had to do, as it's generally a shared resource and I always assumed triggers could get to be expensive in high load scenarios.</p> <p>That said, I have found a couple of instances where triggers have made sense to use (at least in my opinion they made sense). Recently though, I found myself in a situation where I sometimes might need to "bypass" the trigger. I felt really guilty about having to look for ways to do this, and I still think that a better database design would alleviate the need for this bypassing. Unfortunately this DB is used by mulitple applications, some of which are maintained by a very uncooperative development team who would scream about schema changes, so I was stuck.</p> <p>What's the general consesus out there about triggers? Love em? Hate em? Think they serve a purpose in some scenarios? Do think that having a need to bypass a trigger means that you're "doing it wrong"?</p>
[ { "answer_id": 15093, "author": "jinsungy", "author_id": 1316, "author_profile": "https://Stackoverflow.com/users/1316", "pm_score": 0, "selected": false, "text": "UPDATE tblUsers\nSET Age = 11\nWHERE State = 'NY'\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14031", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1680/" ]
14,061
<p>I've created an "attached behaviour" in my WPF application which lets me handle the Enter keypress and move to the next control. I call it EnterKeyTraversal.IsEnabled, and you can see the code on my blog <a href="http://www.madprops.org/blog/enter-to-tab-as-an-attached-property/" rel="noreferrer">here</a>.</p> <p>My main concern now is that I may have a memory leak, since I'm handling the PreviewKeyDown event on UIElements and never explicitly "unhook" the event.</p> <p>What's the best approach to prevent this leak (if indeed there is one)? Should I keep a list of the elements I'm managing, and unhook the PreviewKeyDown event in the Application.Exit event? Has anyone had success with attached behaviours in their own WPF applications and come up with an elegant memory-management solution?</p>
[ { "answer_id": 6169737, "author": "John Fenton", "author_id": 613519, "author_profile": "https://Stackoverflow.com/users/613519", "pm_score": 3, "selected": false, "text": "ue.PreviewKeyDown += ue_PreviewKeyDown;\n ue_PreviewKeyDown ue.PreviewKeyDown ue_PreviewKeyDown STATIC GCed ue GCed" }, { "answer_id": 28239309, "author": "Daniel Bişar", "author_id": 613320, "author_profile": "https://Stackoverflow.com/users/613320", "pm_score": 2, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n var a = new A();\n var b = new B();\n\n a.Clicked += b.HandleClicked;\n //a.Clicked += B.StaticHandleClicked;\n //A.StaticClicked += b.HandleClicked;\n\n var weakA = new WeakReference(a);\n var weakB = new WeakReference(b);\n\n a = null;\n //b = null;\n\n GC.Collect();\n GC.WaitForPendingFinalizers();\n GC.Collect();\n\n Console.WriteLine(\"a is alive: \" + weakA.IsAlive);\n Console.WriteLine(\"b is alive: \" + weakB.IsAlive);\n Console.ReadKey();\n }\n\n\n}\n\nclass A\n{\n public event EventHandler Clicked;\n public static event EventHandler StaticClicked;\n}\n\nclass B\n{\n public void HandleClicked(object sender, EventArgs e)\n {\n }\n\n public static void StaticHandleClicked(object sender, EventArgs e)\n {\n }\n}\n a.Clicked += b.HandleClicked;\n a.Clicked += B.StaticHandleClicked;\n A.StaticClicked += b.HandleClicked;\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14061", "https://Stackoverflow.com", "https://Stackoverflow.com/users/615/" ]
14,118
<p>I'm writing my first Perl app -- an AOL Instant Messenger bot that talks to an Arduino microcontroller, which in turn controls a servo that will push the power button on our sysadmin's server, which freezes randomly every 28 hours or so. </p> <p>I've gotten all the hard stuff done, I'm just trying to add one last bit of code to break the main loop and log out of AIM when the user types 'quit'.</p> <p>The problem is, if I try to read from STDIN in the main program loop, it blocks the process until input is entered, essentially rendering the bot inactive. I've tried testing for EOF before reading, but no dice... EOF just always returns false.</p> <p>Here's below is some sample code I'm working with:</p> <pre><code>while(1) { $oscar-&gt;do_one_loop(); # Poll to see if any arduino data is coming in over serial port my $char = $port-&gt;lookfor(); # If we get data from arduino, then print it if ($char) { print "" . $char ; } # reading STDIN blocks until input is received... AAARG! my $a = &lt;STDIN&gt;; print $a; if($a eq "exit" || $a eq "quit" || $a eq 'c' || $a eq 'q') {last;} } print "Signing off... "; $oscar-&gt;signoff(); print "Done\n"; print "Closing serial port... "; $port-&gt;close() || warn "close failed"; print "Done\n"; </code></pre>
[ { "answer_id": 14124, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 5, "selected": true, "text": "select() select() IO::Select #!/usr/bin/perl\n\nuse IO::Select;\n\n$s = IO::Select->new();\n$s->add(\\*STDIN);\n\nwhile (++$i) {\n print \"Hiya $i!\\n\";\n sleep(5);\n if ($s->can_read(.5)) {\n chomp($foo = <STDIN>);\n print \"Got '$foo' from STDIN\\n\";\n }\n}\n" }, { "answer_id": 54816600, "author": "Gus Schlachter", "author_id": 3935928, "author_profile": "https://Stackoverflow.com/users/3935928", "pm_score": 2, "selected": false, "text": "<STDIN> #!/usr/bin/perl\nuse IO::Select;\n$s = IO::Select->new(\\*STDIN);\n\nwhile (++$i) {\n if ($s->can_read(2)) {\n last unless defined($foo=get_unbuf_line());\n print \"Got '$foo'\\n\";\n }\n}\n\nsub get_unbuf_line {\n my $line=\"\";\n while (sysread(STDIN, my $nextbyte, 1)) {\n return $line if $nextbyte eq \"\\n\";\n $line .= $nextbyte;\n }\n return(undef);\n}\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14118", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
14,138
<p>I installed the wxWidgets source code, compiled it and am linking the libraries thus obtained with my application code. Now I need to use OpenGL in my wxWidgets application. How do I enable this?</p>
[ { "answer_id": 35975, "author": "Jason Weathered", "author_id": 3736, "author_profile": "https://Stackoverflow.com/users/3736", "pm_score": 2, "selected": false, "text": "configure --with-opengl" }, { "answer_id": 72787, "author": "Baxissimo", "author_id": 9631, "author_profile": "https://Stackoverflow.com/users/9631", "pm_score": 4, "selected": true, "text": "#define wxUSE_GLCANVAS ./configure ./configure --with-opengl" }, { "answer_id": 24235871, "author": "demented hedgehog", "author_id": 871196, "author_profile": "https://Stackoverflow.com/users/871196", "pm_score": 1, "selected": false, "text": "./configure --with-opengl > configure.log\n make\nsudo make install \n sudo apt-get install mesa-common-dev\nsudo apt-get install freeglut3-dev\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
14,165
<p>I'm seeing strange errors when my C++ code has min() or max() calls. I'm using Visual C++ compilers.</p>
[ { "answer_id": 14169, "author": "Ashwin Nanjappa", "author_id": 1630, "author_profile": "https://Stackoverflow.com/users/1630", "pm_score": 5, "selected": true, "text": "#define NOMINMAX\n#include <windows.h>\n" }, { "answer_id": 14177, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 0, "selected": false, "text": "std::min() std::max()" }, { "answer_id": 1793313, "author": "dhorn", "author_id": 148632, "author_profile": "https://Stackoverflow.com/users/148632", "pm_score": -1, "selected": false, "text": "#define min(a,b) ((a) < (b) ? (a) : (b))\n#define max(a,b) ((a) >= (b) ? (a) : (b))\n" }, { "answer_id": 4783177, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 2, "selected": false, "text": "int i = std::min<int>(3,5);\n min() min ( <" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14165", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
14,209
<p><code>System.Data.SqlClient.SqlException: Failed to generate a user instance of SQL Server due to a failure in starting the process for the user instance. The connection will be closed.</code></p> <p>Anybody ever get this error and/or have any idea on it's cause and/or solution?</p> <p><a href="http://forums.microsoft.com/MSDN/ShowPost.aspx?PostID=125227&amp;SiteID=1" rel="nofollow noreferrer">This link may have relevant information.</a></p> <p><strong>Update</strong></p> <p>The connection string is <code>=.\SQLEXPRESS;AttachDbFilename=C:\temp\HelloWorldTest.mdf;Integrated Security=True</code></p> <p>The suggested <code>User Instance=false</code> worked.</p>
[ { "answer_id": 1086442, "author": "Roboblob", "author_id": 125718, "author_profile": "https://Stackoverflow.com/users/125718", "pm_score": 4, "selected": false, "text": "exec sp_configure 'user instances enabled', 1.\nGO\nReconfigure\n C:\\Documents and Settings\\{YOUR_USERNAME}\\Local Settings\\Application Data\\Microsoft\\Microsoft SQL Server Data\\{SQL_INSTANCE_NAME} {YOUR_USERNAME} {SQL_INSTANCE_NAME}" }, { "answer_id": 33201997, "author": "mukhtar ghaleb", "author_id": 5042080, "author_profile": "https://Stackoverflow.com/users/5042080", "pm_score": 0, "selected": false, "text": "C:\\Users\\Arabic\\{YOUR_USERNAME}\\Local\\Microsoft\\Microsoft SQL Server Data" }, { "answer_id": 68836220, "author": "user8128167", "author_id": 351154, "author_profile": "https://Stackoverflow.com/users/351154", "pm_score": 0, "selected": false, "text": "AttachDBFilename web.config connectionString=\"data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\\aspnetdb.mdf\"\n connectionString=\"data source=.\\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|\\aspnetdb.mdf;User Instance=true\"\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1659/" ]
14,247
<p>I've only done a bit of Flex development thus far, but I've preferred the approach of creating controls programmatically over mxml files, because (and <em>please</em>, correct me if I'm wrong!) I've gathered that you can't have it both ways -- that is to say, have the class functionality in a separate ActionScript class file but have the contained elements declared in mxml.</p> <p>There doesn't seem to be much of a difference productivity-wise, but doing data binding programmatically seems somewhat less than trivial. I took a look at how the mxml compiler transforms the data binding expressions. The result is a bunch of generated callbacks and a lot more lines than in the mxml representation. So here's the question: <strong>is there a way to do data binding programmatically that doesn't involve a world of hurt?</strong></p>
[ { "answer_id": 14261, "author": "Theo", "author_id": 1109, "author_profile": "https://Stackoverflow.com/users/1109", "pm_score": 6, "selected": true, "text": "BindingUtils bindSetter bindProperty invalidateProperties ChangeWatcher BindingUtils.bindSetter(nameChanged, selectedEmployee, \"name\");\n nameChanged name selectedEmployee nameChanged name private function nameChanged( newName : String ) : void \n selectedEmployee ChangeWatcher BindingUtils.bindSetter unwatch currentEmployee public function set currentEmployee( employee : Employee ) : void {\n if ( _currentEmployee != employee ) {\n if ( _currentEmployee != null ) {\n currentEmployeeNameCW.unwatch();\n }\n\n _currentEmployee = employee;\n\n if ( _currentEmployee != null ) {\n currentEmployeeNameCW = BindingUtils.bindSetter(currentEmployeeNameChanged, _currentEmployee, \"name\");\n }\n }\n}\n currentEmployee currentEmployeeNameCW.unwatch() null name ChangeWatcher currentEmployee creationComplete BindingUtils.bindSetter(currentEmployeeNameChanged, this, [\"currentEmployee\", \"name\"]);\n currentEmployee this name currentEmployeeNameChanged ChangeWatcher this currentEmployee" }, { "answer_id": 36010, "author": "Nick Higgs", "author_id": 3187, "author_profile": "https://Stackoverflow.com/users/3187", "pm_score": 2, "selected": false, "text": "package CustomComponents\n{\n import mx.containers.*;\n import mx.controls.*;\n import flash.events.Event;\n\n public class MyCanvasCode extends Canvas\n {\n public var myLabel : Label;\n\n protected function onInitialize(event : Event):void\n {\n MyLabel.text = \"Lorem ipsum dolor sit amet, consectetuer adipiscing elit.\";\n }\n }\n}\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<MyCanvasCode xmlns=\"CustomComponents.*\" \n xmlns:mx=\"http://www.adobe.com/2006/mxml\"\n initialize=\"onInitialize(event)\">\n <mx:Label id=\"myLabel\"/> \n</MyCanvasCode>\n" }, { "answer_id": 5521481, "author": "qualidafial", "author_id": 13253, "author_profile": "https://Stackoverflow.com/users/13253", "pm_score": 3, "selected": false, "text": "Bind.fromProperty(person, \"firstName\")\n .toProperty(firstNameInput, \"text\");\n Bind.twoWay(\n Bind.fromProperty(person, \"firstName\"),\n Bind.fromProperty(firstNameInput, \"text\"));\n Bind.twoWay(\n Bind.fromProperty(person, \"age\")\n .convert(valueToString()),\n Bind.fromProperty(ageInput, \"text\")\n .validate(isNumeric()) // (Hamcrest-as3 matcher)\n .convert(toNumber()));\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/266/" ]
14,264
<p>What are the basic steps to compile an OpenGL application using <em>GLUT (OpenGL Utility Toolkit)</em> under Visual C++ Express Edition?</p>
[ { "answer_id": 112729, "author": "Baxissimo", "author_id": 9631, "author_profile": "https://Stackoverflow.com/users/9631", "pm_score": 3, "selected": false, "text": "exit() exit() glut.h stdlib.h #define GLUT_DISABLE_ATEXIT_HACK #include <gl/glut.h> glut.h #ifdef blocks --- c:\\naterobbins\\glut.h 2000-12-13 00:22:52.000000000 +0900\n+++ c:\\updated\\glut.h 2006-05-23 11:06:10.000000000 +0900\n@@ -143,7 +143,12 @@\n\n #if defined(_WIN32)\n # ifndef GLUT_BUILDING_LIB\n-extern _CRTIMP void __cdecl exit(int);\n+/* extern _CRTIMP void __cdecl exit(int); /* Changed for .NET */\n+# if _MSC_VER >= 1200\n+extern _CRTIMP __declspec(noreturn) void __cdecl exit(int);\n+# else\n+extern _CRTIMP void __cdecl exit(int);\n+# endif\n # endif\n #else\n /* non-Win32 case. */\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14264", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
14,278
<p>I'd like to provide some way of creating dynamically loadable plugins in my software. Typical way to do this is using the <a href="http://msdn.microsoft.com/en-us/library/ms684175(VS.85).aspx" rel="noreferrer">LoadLibrary</a> WinAPI function to load a dll and calling <a href="http://msdn.microsoft.com/en-us/library/ms683212(VS.85).aspx" rel="noreferrer">GetProcAddress</a> to get an pointer to a function inside that dll.</p> <p>My question is how do I dynamically load a plugin in C#/.Net application?</p>
[ { "answer_id": 14282, "author": "Zooba", "author_id": 891, "author_profile": "https://Stackoverflow.com/users/891", "pm_score": 5, "selected": true, "text": "Base using System.IO;\nusing System.Reflection;\n\nList<Base> objects = new List<Base>();\nDirectoryInfo dir = new DirectoryInfo(Application.StartupPath);\n\nforeach (FileInfo file in dir.GetFiles(\"*.dll\"))\n{\n Assembly assembly = Assembly.LoadFrom(file.FullName);\n foreach (Type type in assembly.GetTypes())\n {\n if (type.IsSubclassOf(typeof(Base)) && type.IsAbstract == false)\n {\n Base b = type.InvokeMember(null,\n BindingFlags.CreateInstance,\n null, null, null) as Base;\n objects.Add(b);\n }\n }\n}\n" }, { "answer_id": 14286, "author": "Biri", "author_id": 968, "author_profile": "https://Stackoverflow.com/users/968", "pm_score": 2, "selected": false, "text": "[DllImport(\"kernel32.dll\")]\n\ninternal static extern IntPtr LoadLibrary(String dllname);\n\n[DllImport(\"kernel32.dll\")]\n\ninternal static extern IntPtr GetProcAddress(IntPtr hModule, String procname);\n" }, { "answer_id": 14312, "author": "Patrik Svensson", "author_id": 936, "author_profile": "https://Stackoverflow.com/users/936", "pm_score": 3, "selected": false, "text": "AppDomain domain = AppDomain.CreateDomain(\"tempDomain\");\n AssemblyName assemblyName = AssemblyName.GetAssemblyName(assemblyPath);\nAssembly assembly = domain.Load(assemblyName);\n AppDomain.Unload(domain);\n" }, { "answer_id": 14185590, "author": "cdiggins", "author_id": 184528, "author_profile": "https://Stackoverflow.com/users/184528", "pm_score": 3, "selected": false, "text": "AppDomain var domain = AppDomain.CreateDomain(\"NewDomainName\");\nvar pathToDll = @\"C:\\myDll.dll\"; \nvar t = typeof(TypeIWantToLoad);\nvar runnable = domain.CreateInstanceFromAndUnwrap(pathToDll, t.FullName) \n as IRunnable;\nif (runnable == null) throw new Exception(\"broke\");\nrunnable.Run();\n AppDomain System.AddIn" }, { "answer_id": 59571238, "author": "LeonardoX", "author_id": 1683040, "author_profile": "https://Stackoverflow.com/users/1683040", "pm_score": 0, "selected": false, "text": "public interface IYourInterface\n{\n Task YourMethod();\n}\n public class YourClass: IYourInterface\n{\n async Task IYourInterface.YourMethod()\n {\n //.....\n }\n}\n using System;\nusing System.Collections;\nusing System.Collections.Generic;\nusing System.Linq.Expressions;\nusing System.Reflection;\nusing System.Linq;\n\npublic abstract class ReflectionTool<TSource> where TSource : class\n{\n public static TSource LoadInstanceFromLibrary(string libraryPath)\n {\n TSource pluginclass = null;\n if (!System.IO.File.Exists(libraryPath))\n throw new Exception($\"Library '{libraryPath}' not found\");\n else\n {\n Assembly.LoadFrom(libraryPath);\n\n var fileName = System.IO.Path.GetFileName(libraryPath).Replace(\".dll\", \"\");\n var assembly = AppDomain.CurrentDomain.GetAssemblies().FirstOrDefault(c => c.FullName.StartsWith(fileName));\n var type = assembly.GetTypes().FirstOrDefault(c => c.GetInterface(typeof(TSource).FullName) != null);\n\n try\n {\n pluginclass = Activator.CreateInstance(type) as TSource;\n }\n catch (Exception ex)\n {\n LogError(\"\", ex);\n throw;\n }\n }\n\n return pluginclass;\n }\n}\n IYourInterface instance = ReflectionTool<IYourInterface>.LoadInstanceFromLibrary(\"c:\\pathToYourLibrary.dll\");\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1534/" ]
14,281
<p>I have over a million text files compressed into 40 zip files. I also have a list of about 500 model names of phones. I want to find out the number of times a particular model was mentioned in the text files. </p> <p>Is there any python module which can do a regex match on the files without unzipping it. Is there a simple way to solve this problem without unzipping?</p>
[ { "answer_id": 14320, "author": "Mark Harrison", "author_id": 116, "author_profile": "https://Stackoverflow.com/users/116", "pm_score": 4, "selected": true, "text": "#!/usr/bin/python\n\nimport zipfile\nf = zipfile.ZipFile('myfile.zip')\n\nfor subfile in f.namelist():\n print subfile\n data = f.read(subfile)\n for line in data.split('\\n'):\n print line\n" }, { "answer_id": 41822, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 0, "selected": false, "text": "zipfile" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14281", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
14,287
<p>In my C/C++ program, I'm using <a href="http://opencvlibrary.sourceforge.net/" rel="noreferrer">OpenCV</a> to capture images from my webcam. The camera (<a href="http://en.wikipedia.org/wiki/Quickcam" rel="noreferrer">Logitech QuickCam IM</a>) can capture at resolutions <strong>320x240</strong>, <strong>640x480</strong> and <strong>1280x960</strong>. But, for some strange reason, OpenCV gives me images of resolution <strong>320x240</strong> only. Calls to change the resolution using <strong>cvSetCaptureProperty()</strong> with other resolution values just don't work. How do I capture images with the other resolutions possible with my webcam?</p>
[ { "answer_id": 14290, "author": "Ashwin Nanjappa", "author_id": 1630, "author_profile": "https://Stackoverflow.com/users/1630", "pm_score": 5, "selected": true, "text": "#define CV_CAP_PROP_DIALOG_DISPLAY 8\n#define CV_CAP_PROP_DIALOG_FORMAT 9\n#define CV_CAP_PROP_DIALOG_SOURCE 10\n#define CV_CAP_PROP_DIALOG_COMPRESSION 11\n#define CV_CAP_PROP_FRAME_WIDTH_HEIGHT 12\n static int icvSetPropertyCAM_VFW( CvCaptureCAM_VFW* capture, int property_id, double value )\n{\n int result = -1;\n CAPSTATUS capstat;\n CAPTUREPARMS capparam;\n BITMAPINFO btmp;\n\n switch( property_id )\n {\n case CV_CAP_PROP_DIALOG_DISPLAY:\n result = capDlgVideoDisplay(capture->capWnd);\n //SendMessage(capture->capWnd,WM_CAP_DLG_VIDEODISPLAY,0,0);\n break;\n\n case CV_CAP_PROP_DIALOG_FORMAT:\n result = capDlgVideoFormat(capture->capWnd);\n //SendMessage(capture->capWnd,WM_CAP_DLG_VIDEOFORMAT,0,0);\n break;\n\n case CV_CAP_PROP_DIALOG_SOURCE:\n result = capDlgVideoSource(capture->capWnd);\n //SendMessage(capture->capWnd,WM_CAP_DLG_VIDEOSOURCE,0,0);\n break;\n\n case CV_CAP_PROP_DIALOG_COMPRESSION:\n result = capDlgVideoCompression(capture->capWnd);\n break;\n\n case CV_CAP_PROP_FRAME_WIDTH_HEIGHT:\n capGetVideoFormat(capture->capWnd, &btmp, sizeof(BITMAPINFO));\n btmp.bmiHeader.biWidth = floor(value/1000);\n btmp.bmiHeader.biHeight = value-floor(value/1000)*1000;\n btmp.bmiHeader.biSizeImage = btmp.bmiHeader.biHeight *\n btmp.bmiHeader.biWidth * btmp.bmiHeader.biPlanes *\n btmp.bmiHeader.biBitCount / 8;\n capSetVideoFormat(capture->capWnd, &btmp, sizeof(BITMAPINFO));\n break;\n\n default:\n break;\n }\n\n return result;\n}\n static CvCaptureVTable captureCAM_VFW_vtable =\n{\n6,\n(CvCaptureCloseFunc)icvCloseCAM_VFW,\n(CvCaptureGrabFrameFunc)icvGrabFrameCAM_VFW,\n(CvCaptureRetrieveFrameFunc)icvRetrieveFrameCAM_VFW,\n(CvCaptureGetPropertyFunc)icvGetPropertyCAM_VFW,\n(CvCaptureSetPropertyFunc)icvSetPropertyCAM_VFW, // was NULL\n(CvCaptureGetDescriptionFunc)0\n};\n" }, { "answer_id": 713742, "author": "Grifo", "author_id": 86629, "author_profile": "https://Stackoverflow.com/users/86629", "pm_score": 5, "selected": false, "text": "capture = cvCreateCameraCapture(cameraIndex);\n\ncvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, 640 );\n\ncvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, 480 );\n\n\nvideoFrame = cvQueryFrame(capture);\n" }, { "answer_id": 3076521, "author": "mg72", "author_id": 371133, "author_profile": "https://Stackoverflow.com/users/371133", "pm_score": -1, "selected": false, "text": "cvQueryFrame(capture);\n\ncvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, any_supported_size );\n\ncvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, any_supported_size);\n\ncvQueryFrame(capture);\n" }, { "answer_id": 3867859, "author": "fantom1210", "author_id": 467332, "author_profile": "https://Stackoverflow.com/users/467332", "pm_score": -1, "selected": false, "text": "capture = cvCreateCameraCapture(-1);\n//set resolution\ncvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, frameWidth);\ncvSetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, frameHeight);\n" }, { "answer_id": 12253652, "author": "Forrest Erickson", "author_id": 1644581, "author_profile": "https://Stackoverflow.com/users/1644581", "pm_score": 3, "selected": false, "text": "#Camera_Get_Set.py\n#By Forrest L. Erickson of VRX Company Inc. 8-31-12.\n#Opens the camera and reads and reports the settings.\n#Then tries to set for higher resolution.\n#Workes with Logitech C525 for resolutions 960 by 720 and 1600 by 896\n\n\nimport cv2.cv as cv\nimport numpy\n\nCV_CAP_PROP_POS_MSEC = 0\nCV_CAP_PROP_POS_FRAMES = 1\nCV_CAP_PROP_POS_AVI_RATIO = 2\nCV_CAP_PROP_FRAME_WIDTH = 3\nCV_CAP_PROP_FRAME_HEIGHT = 4\nCV_CAP_PROP_FPS = 5\nCV_CAP_PROP_POS_FOURCC = 6\nCV_CAP_PROP_POS_FRAME_COUNT = 7\nCV_CAP_PROP_BRIGHTNESS = 8\nCV_CAP_PROP_CONTRAST = 9\nCV_CAP_PROP_SATURATION = 10\nCV_CAP_PROP_HUE = 11\n\nCV_CAPTURE_PROPERTIES = tuple({\nCV_CAP_PROP_POS_MSEC,\nCV_CAP_PROP_POS_FRAMES,\nCV_CAP_PROP_POS_AVI_RATIO,\nCV_CAP_PROP_FRAME_WIDTH,\nCV_CAP_PROP_FRAME_HEIGHT,\nCV_CAP_PROP_FPS,\nCV_CAP_PROP_POS_FOURCC,\nCV_CAP_PROP_POS_FRAME_COUNT,\nCV_CAP_PROP_BRIGHTNESS,\nCV_CAP_PROP_CONTRAST,\nCV_CAP_PROP_SATURATION,\nCV_CAP_PROP_HUE})\n\nCV_CAPTURE_PROPERTIES_NAMES = [\n\"CV_CAP_PROP_POS_MSEC\",\n\"CV_CAP_PROP_POS_FRAMES\",\n\"CV_CAP_PROP_POS_AVI_RATIO\",\n\"CV_CAP_PROP_FRAME_WIDTH\",\n\"CV_CAP_PROP_FRAME_HEIGHT\",\n\"CV_CAP_PROP_FPS\",\n\"CV_CAP_PROP_POS_FOURCC\",\n\"CV_CAP_PROP_POS_FRAME_COUNT\",\n\"CV_CAP_PROP_BRIGHTNESS\",\n\"CV_CAP_PROP_CONTRAST\",\n\"CV_CAP_PROP_SATURATION\",\n\"CV_CAP_PROP_HUE\"]\n\n\ncapture = cv.CaptureFromCAM(0)\n\nprint (\"\\nCamera properties before query of frame.\")\nfor i in range(len(CV_CAPTURE_PROPERTIES_NAMES)):\n# camera_valeus =[CV_CAPTURE_PROPERTIES_NAMES, foo]\n foo = cv.GetCaptureProperty(capture, CV_CAPTURE_PROPERTIES[i])\n camera_values =[CV_CAPTURE_PROPERTIES_NAMES[i], foo]\n# print str(camera_values)\n print str(CV_CAPTURE_PROPERTIES_NAMES[i]) + \": \" + str(foo)\n\n\nprint (\"\\nOpen a window for display of image\")\ncv.NamedWindow(\"Camera\", 1)\nwhile True:\n img = cv.QueryFrame(capture)\n cv.ShowImage(\"Camera\", img)\n if cv.WaitKey(10) == 27:\n break\ncv.DestroyWindow(\"Camera\")\n\n\n#cv.SetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 1024)\n#cv.SetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 768)\ncv.SetCaptureProperty(capture, CV_CAP_PROP_FRAME_WIDTH, 1600)\ncv.SetCaptureProperty(capture, CV_CAP_PROP_FRAME_HEIGHT, 896)\n\n\nprint (\"\\nCamera properties after query and display of frame.\")\nfor i in range(len(CV_CAPTURE_PROPERTIES_NAMES)):\n# camera_valeus =[CV_CAPTURE_PROPERTIES_NAMES, foo]\n foo = cv.GetCaptureProperty(capture, CV_CAPTURE_PROPERTIES[i])\n camera_values =[CV_CAPTURE_PROPERTIES_NAMES[i], foo]\n# print str(camera_values)\n print str(CV_CAPTURE_PROPERTIES_NAMES[i]) + \": \" + str(foo)\n\n\nprint (\"/nOpen a window for display of image\")\ncv.NamedWindow(\"Camera\", 1)\nwhile True:\n img = cv.QueryFrame(capture)\n cv.ShowImage(\"Camera\", img)\n if cv.WaitKey(10) == 27:\n break\ncv.DestroyWindow(\"Camera\")\n" }, { "answer_id": 19108254, "author": "user2833455", "author_id": 2833455, "author_profile": "https://Stackoverflow.com/users/2833455", "pm_score": 0, "selected": false, "text": "cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_WIDTH, ... \n cvSetCaptureProperty( capture, CV_CAP_PROP_FRAME_HEIGHT, ...\n *#define DEFAULT_V4L_WIDTH 1280 // Originally 640* \n\n*#define DEFAULT_V4L_HEIGHT 720 // Originally 480*\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14287", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
14,300
<p>For example; with the old command prompt it would be:</p> <pre><code>cmd.exe /k mybatchfile.bat </code></pre>
[ { "answer_id": 14313, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 6, "selected": true, "text": "powershell -?\n" }, { "answer_id": 5346936, "author": "john", "author_id": 665321, "author_profile": "https://Stackoverflow.com/users/665321", "pm_score": -1, "selected": false, "text": "$CreateDate = (Get-Date -format 'yyyy-MM-dd hh-mm-ss')\n\n$RemoteServerName =\"server name\"\n$process = [WMICLASS]\"\\\\$RemoteServerName\\ROOT\\CIMV2:win32_process\" \n$result = $process.Create(\"C:\\path to a script\\test.bat\") \n$result | out-file -file \"C:\\some path \\Log-$CreatedDate.txt\"\n" }, { "answer_id": 20060082, "author": "deadlydog", "author_id": 602585, "author_profile": "https://Stackoverflow.com/users/602585", "pm_score": 4, "selected": false, "text": "PowerShell -NoExit -File \"C:\\SomeFolder\\SomePowerShellScript.ps1\"\n\nPowerShell -NoExit -Command \"Write-Host 'This window will stay open.'\"\n PowerShell -NoExit \"& 'C:\\SomeFolder\\SomePowerShellScript.ps1'; Write-Host 'This window will stay open.'\"\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14300", "https://Stackoverflow.com", "https://Stackoverflow.com/users/887/" ]
14,308
<p>I'm currently working at a small web development company, we mostly do campaign sites and other promotional stuff. For our first year we've been using a "server" for sharing project files, a plain windows machine with a network share. But this isn't exactly future proof. </p> <p>SVN is great for code (it's what we use now), but I want to have the comfort of versioning (or atleast some form of syncing) for all or most of our files. </p> <p><em>What I essentially want is something that does what subversion does for code, but for our documents/psd/pdf files.</em> </p> <p>I realize subversion handles binary files too, but I feel it might be a bit overkill for our purposes. It doesn't necessarily need all the bells and whistles of a full version control system, but something that that removes the need for incremental naming (Notes_1.23.doc) and lessens the chance of overwriting something by mistake. </p> <p>It also needs to be multiplatform, handle large files (100 mb+) and be usable by somewhat non technical people. </p>
[ { "answer_id": 14429, "author": "dbr", "author_id": 745, "author_profile": "https://Stackoverflow.com/users/745", "pm_score": 1, "selected": false, "text": "vcs checkout blah -r 234" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14308", "https://Stackoverflow.com", "https://Stackoverflow.com/users/914/" ]
14,330
<p>How do I convert the RGB values of a pixel to a single monochrome value?</p>
[ { "answer_id": 14331, "author": "Ashwin Nanjappa", "author_id": 1630, "author_profile": "https://Stackoverflow.com/users/1630", "pm_score": 6, "selected": true, "text": "mono = (0.2125 * color.r) + (0.7154 * color.g) + (0.0721 * color.b);\n" }, { "answer_id": 14339, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "(0.299 * color.R + 0.587 * color.G + 0.114 * color.B); (0.3* color.R + 0.59 * color.G + 0.11 * color.B);" }, { "answer_id": 69980882, "author": "Myndex", "author_id": 10315269, "author_profile": "https://Stackoverflow.com/users/10315269", "pm_score": 1, "selected": false, "text": "// Andy's Easy Greyscale in one line.\n// Send it sR sG sB channels as 8 bit ints, and\n// it returns three channels sRgrey sGgrey sBgrey\n// as 8 bit ints that display glorious grey.\n\n\n sRgrey = sGgrey = sBgrey = Math.min(Math.pow((Math.pow(sR/255.0,2.2)*0.2126+Math.pow(sG/255.0,2.2)*0.7152+Math.pow(sB/255.0,2.2)*0.0722),0.454545)*255),255);\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14330", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
14,344
<p>Is it possible to compile and run OpenGL programs from under Cygwin? If yes, how?</p>
[ { "answer_id": 68074857, "author": "Adriana", "author_id": 6908795, "author_profile": "https://Stackoverflow.com/users/6908795", "pm_score": 1, "selected": false, "text": "C:\\Program Files(x86)\\Microsoft Visual Studio\\2019\\Community\\SDK\\ScopeCPPSDK\\vc15\\lib\\SDK\\lib\\opengl32.lib\n C:\\Windows\\SysWOW64\\opengl32.dll\n opengl32.lib Properties -> Configuration Properties -> Linker -> Input -> Additional Dependencies /lib/w32api/libopengl32.a\n C:\\Windows\\SysWOW64\\opengl32.dll\n http://glew.sourceforge.net/ C:\\OpenGL\\glew-2.1.0 #include GL/glew.h C:\\OpenGL\\glew-2.1.0\\include\n C:\\OpenGL\\glew-2.1.0\\lib\\Release\\x64\\glew32.lib\n C:\\OpenGL\\glew-2.1.0\\bin\\Release\\x64\\glew32.dll\n INCS LIBS LDLIBS Makefile /cygdrive/c/OpenGL/glew-2.1.0/include\n /cygdrive/c/OpenGL/glew-2.1.0/lib/Release/x64\n /cygdrive/c/OpenGL/glew-2.1.0/bin/Release/x64\n INCS LIBS LDLIBS Makefile https://www.glfw.org/download C:\\OpenGL\\glfw-3.3.4.bin.WIN64 #include GLFW/glfw3.h C:\\OpenGL\\glfw-3.3.4.bin.WIN64\\include\\GLFW\\*.h\nC:\\OpenGL\\glfw-3.3.4.bin.WIN64\\lib-mingw-w64\\*.a\nC:\\OpenGL\\glfw-3.3.4.bin.WIN64\\lib-mingw-w64\\*.dll\n include /usr/x86_64-w64-mingw32/include/GLFW/*.h\n /usr/x86_64-w64-mingw32/lib/*.a\n /usr/x86_64-w64-mingw32/bin/*.dll\n .bash_profile Makefile CC=/usr/bin/x86_64-w64-mingw32-c++.exe\nOPTS=-std=c++11\nDEBUG=-g\nCFLAGS=-Wall -c ${DEBUG}\n\nINCS= -I.\\\n -I/cygdrive/c/OpenGL/glew-2.1.0/include\\\n -I/cygdrive/c/cygwin64/usr/x86_64-w64-mingw32\n\nLIBS= -L/usr/lib\\\n -L/cygdrive/c/OpenGL/glew-2.1.0/lib/Release/x64\\\n -L/cygdrive/c/cygwin64/usr/x86_64-w64-mingw32/lib\n\nLDLIBS= -L/bin\\\n -L/cygdrive/c/OpenGL/glew-2.1.0/bin/Release/x64\\\n -L/cygdrive/c/cygwin64/usr/x86_64-w64-mingw32\\bin\n\nProgram.o: Program.cpp\n ${CC} ${OPTS} ${INCS} -c $<\n\nProgram: Program.o\n ${CC} ${OPTS} ${LIBS} ${LDLIBS} Program.o -lopengl32 -lglew32 -lglew32.dll -lglfw3 -lgdi32 -luser32 -o Program\n Program.exe $ make Program\n$ ./Program.exe\n *.exe Project/Debug Project/Release #include <GL/glew.h>\n#include <GLFW/glfw3.h>\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14344", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
14,350
<p>I have a Flex swf hosted at <a href="http://www.a.com/a.swf" rel="nofollow noreferrer">http://www.a.com/a.swf</a>. I have a flash code on another doamin that tries loading the SWF:</p> <pre><code>_loader = new Loader(); var req:URLRequest = new URLRequest("http://services.nuconomy.com/n.swf"); _loader.contentLoaderInfo.addEventListener(Event.COMPLETE,onLoaderFinish); _loader.load(req); </code></pre> <p>On the onLoaderFinish event I try to load classes from the remote SWF and create them:</p> <pre><code>_loader.contentLoaderInfo.applicationDomain.getDefinition("someClassName") as Class </code></pre> <p>When this code runs I get the following exception</p> <pre><code>SecurityError: Error #2119: Security sandbox violation: caller http://localhost.service:1234/flashTest/Main.swf cannot access LoaderInfo.applicationDomain owned by http://www.b.com/b.swf. at flash.display::LoaderInfo/get applicationDomain() at NuconomyLoader/onLoaderFinish() </code></pre> <p>Is there any way to get this code working?</p>
[ { "answer_id": 14409, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\"?>\n<!-- http://www.foo.com/crossdomain.xml -->\n<cross-domain-policy>\n <allow-access-from domain=\"www.friendOfFoo.com\" />\n <allow-access-from domain=\"*.foo.com\" />\n <allow-access-from domain=\"105.216.0.40\" />\n</cross-domain-policy>\n var loaderContext:LoaderContext = new LoaderContext();\nloaderContext.checkPolicyFile = true;\n\nvar loader:Loader = new Loader();\nloader.contentLoaderInfo.addEventListener( Event.COMPLETE, onComplete );\nloader.load( new URLRequest( \"http://my.domain.com/image.png\" ), loaderContext );\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1228206/" ]
14,359
<p>What recommendations can you give for a system which must do the following:</p> <p>Load Plugins (and eventually execute them) but have 2 methods of loading these plugins:</p> <ul> <li>Load only authorized plugins (developed by the owner of the software) </li> <li>Load all plugins</li> </ul> <p>And we need to be reasonably secure that the authorized plugins are the real deal (unmodified). However all plugins must be in seperate assemblies. I've been looking at using strong named assemblies for the plugins, with the public key stored in the loader application, but to me this seems too easy to modify the public key within the loader application (if the user was so inclined) regardless of any obfuscation of the loader application. Any more secure ideas?</p>
[ { "answer_id": 14409, "author": "grapefrukt", "author_id": 914, "author_profile": "https://Stackoverflow.com/users/914", "pm_score": 2, "selected": false, "text": "<?xml version=\"1.0\"?>\n<!-- http://www.foo.com/crossdomain.xml -->\n<cross-domain-policy>\n <allow-access-from domain=\"www.friendOfFoo.com\" />\n <allow-access-from domain=\"*.foo.com\" />\n <allow-access-from domain=\"105.216.0.40\" />\n</cross-domain-policy>\n var loaderContext:LoaderContext = new LoaderContext();\nloaderContext.checkPolicyFile = true;\n\nvar loader:Loader = new Loader();\nloader.contentLoaderInfo.addEventListener( Event.COMPLETE, onComplete );\nloader.load( new URLRequest( \"http://my.domain.com/image.png\" ), loaderContext );\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14359", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1111/" ]
14,373
<p>I am converting from existing CVS repository to SVN repository. CVS repository has few brances and I'd like to rename branches while converting.</p> <p>Wanted conversion is like this:</p> <pre><code>CVS branch SVN branch HEAD -&gt; branches/branchX branchA -&gt; trunk branchB -&gt; branches/branchB branchC -&gt; branches/branchC </code></pre> <p>That is, CVS HEAD becomes a normal branch and CVS branchA becomes SVN trunk.</p> <p>Both CVS and SVN repositories will be on same linux machine.</p> <p>How could this be done? </p> <p>Also conversion where CVS branchA becomes SVN trunk and all other CVS branches are ignored might be enough.</p>
[ { "answer_id": 211627, "author": "mhagger", "author_id": 24478, "author_profile": "https://Stackoverflow.com/users/24478", "pm_score": 1, "selected": false, "text": "--symbol-hints=symbol-hints.txt SymbolHintsFileRule('symbol-hints.txt') symbol-hints.txt . .trunk. trunk branches/branchX .\n. branchX branch trunk .\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1431/" ]
14,375
<p>I'm using repository pattern with LINQ, have IRepository.DeleteOnSubmit(T Entity). It works fine, but when my entity class has interface, like this: </p> <pre><code>public interface IEntity { int ID {get;set;} } public partial class MyEntity: IEntity { public int ID { get { return this.IDfield; } set { this.IDfield=value; } } } </code></pre> <p>and then trying to delete some entity like this: </p> <pre><code>IEntity ie=repository.GetByID(1); repoitory.DeleteOnSubmit(ie); </code></pre> <p>throws<br> The member 'IEntity.ID' has no supported translation to SQL. </p> <p>fetching data from DB works, but delete and insert doesn't. How to use interface against DataContext?</p> <hr> <p>Here it is:<br> Exception message: The member 'MMRI.DAL.ITag.idContent' has no supported translation to SQL. </p> <p>Code: </p> <pre><code>var d = repContent.GetAll().Where(x =&gt; x.idContent.Equals(idContent)); foreach (var tagConnect in d) &lt;- error line { repContet.DeleteOnSubmit(tagConnect); </code></pre> <p>(it gets all tags from DB, and deletes them)</p> <p>And stack trace: </p> <pre><code>[NotSupportedException: The member 'MMRI.DAL.ITag.idContent' has no supported translation to SQL.] System.Data.Linq.SqlClient.Visitor.VisitMember(SqlMember m) +621763 System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +541 System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression exp) +8 System.Data.Linq.SqlClient.SqlVisitor.VisitBinaryOperator(SqlBinary bo) +18 System.Data.Linq.SqlClient.Visitor.VisitBinaryOperator(SqlBinary bo) +18 System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +196 System.Data.Linq.SqlClient.SqlVisitor.VisitExpression(SqlExpression exp) +8 System.Data.Linq.SqlClient.SqlVisitor.VisitSelectCore(SqlSelect select) +46 System.Data.Linq.SqlClient.Visitor.VisitSelect(SqlSelect select) +20 System.Data.Linq.SqlClient.SqlVisitor.Visit(SqlNode node) +1024 System.Data.Linq.SqlClient.SqlProvider.BuildQuery( ... </code></pre> <p>When I try do decorate partial class:</p> <pre><code>[Column(Storage = "_idEvent", DbType = "Int NOT NULL", IsPrimaryKey = true)] public int idContent { get { return this.idEvent; } set { this.idEvent=value; } } </code></pre> <p>it throws error "Invalid column name 'idContent'."</p>
[ { "answer_id": 14381, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 0, "selected": false, "text": "using System.Data.Linq.Mapping;\n\npublic partial class MyEntity: IEntity \n { [Column(Storage=\"IDfield\", DbType=\"int not null\", IsPrimaryKey=true)]\n public int ID \n { \n get { return this.IDfield; } \n set { this.IDfield=value; } \n } \n }\n" }, { "answer_id": 2069586, "author": "Frank Tzanabetis", "author_id": 251210, "author_profile": "https://Stackoverflow.com/users/251210", "pm_score": 2, "selected": false, "text": "public partial class MyEntity: IEntity \n { [Column(Name = \"IDfield\", Storage = \"_IDfield\", IsDbGenerated = true)]\n public int ID \n { \n get { return this.IDfield; } \n set { this.IDfield=value; } \n } \n }\n" }, { "answer_id": 2070758, "author": "jeroenh", "author_id": 20047, "author_profile": "https://Stackoverflow.com/users/20047", "pm_score": 0, "selected": false, "text": "public partial class MyEntity: IEntity \n{ \n}\n" }, { "answer_id": 27485863, "author": "jahu", "author_id": 2123652, "author_profile": "https://Stackoverflow.com/users/2123652", "pm_score": 3, "selected": false, "text": "== i.ID.Equals(someId) == IQueryable IEnumerable IQueryable IEnumerable IQueryable IEnumerable IQueryable IEnumerable == IQueryable" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14375", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1407/" ]
14,378
<p>I want to use the mouse scrollwheel in my OpenGL GLUT program to zoom in and out of a scene? How do I do that?</p>
[ { "answer_id": 14379, "author": "Ashwin Nanjappa", "author_id": 1630, "author_profile": "https://Stackoverflow.com/users/1630", "pm_score": 6, "selected": true, "text": "void mouseWheel(int, int, int, int);\n glutMouseWheelFunc(mouseWheel);\n void mouseWheel(int button, int dir, int x, int y)\n{\n if (dir > 0)\n {\n // Zoom in\n }\n else\n {\n // Zoom out\n }\n\n return;\n}\n" }, { "answer_id": 7885789, "author": "BentFX", "author_id": 710913, "author_profile": "https://Stackoverflow.com/users/710913", "pm_score": 5, "selected": false, "text": "#include <GL/glut.h>\n\n<snip...>\n\nvoid mouse(int button, int state, int x, int y)\n{\n // Wheel reports as button 3(scroll up) and button 4(scroll down)\n if ((button == 3) || (button == 4)) // It's a wheel event\n {\n // Each wheel event reports like a button click, GLUT_DOWN then GLUT_UP\n if (state == GLUT_UP) return; // Disregard redundant GLUT_UP events\n printf(\"Scroll %s At %d %d\\n\", (button == 3) ? \"Up\" : \"Down\", x, y);\n }else{ // normal button event\n printf(\"Button %s At %d %d\\n\", (state == GLUT_DOWN) ? \"Down\" : \"Up\", x, y);\n }\n}\n\n<snip...>\n\nglutMouseFunc(mouse);\n" }, { "answer_id": 53304965, "author": "StackAttack", "author_id": 4513646, "author_profile": "https://Stackoverflow.com/users/4513646", "pm_score": 2, "selected": false, "text": "glutMouseFunc(mouseClick);\n void mouseClick(int btn, int state, int x, int y) {\n if (state == GLUT_DOWN) {\n switch(btn) {\n case GLUT_LEFT_BUTTON:\n std::cout << \"left click at: (\" << x << \", \" << y << \")\\n\";\n break;\n case GLUT_RIGHT_BUTTON:\n std::cout << \"right click at: (\" << x << \", \" << y << \")\\n\";\n break;\n case GLUT_MIDDLE_BUTTON:\n std::cout << \"middle click at: (\" << x << \", \" << y << \")\\n\";\n break;\n case 3: //mouse wheel scrolls\n std::cout << \"mouse wheel scroll up\\n\";\n break;\n case 4:\n std::cout << \"mouse wheel scroll down\\n\";\n break;\n default:\n break;\n }\n }\n glutPostRedisplay();\n}\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14378", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
14,386
<p>With the <em>Visual Studio 2005 C++ compiler</em>, I get the following warning when my code uses the <code>fopen()</code> and such calls:</p> <pre class="lang-none prettyprint-override"><code>1&gt;foo.cpp(5) : warning C4996: 'fopen' was declared deprecated 1&gt; c:\program files\microsoft visual studio 8\vc\include\stdio.h(234) : see declaration of 'fopen' 1&gt; Message: 'This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_DEPRECATE. See online help for details.' </code></pre> <p>How do I prevent this?</p>
[ { "answer_id": 14387, "author": "Ashwin Nanjappa", "author_id": 1630, "author_profile": "https://Stackoverflow.com/users/1630", "pm_score": 8, "selected": true, "text": "#define _CRT_SECURE_NO_DEPRECATE\n#include <stdio.h>\n" }, { "answer_id": 14506, "author": "John Sibly", "author_id": 1078, "author_profile": "https://Stackoverflow.com/users/1078", "pm_score": 5, "selected": false, "text": "#pragma warning (disable : 4996)\n" }, { "answer_id": 8069439, "author": "Denys Yurchenko", "author_id": 1038233, "author_profile": "https://Stackoverflow.com/users/1038233", "pm_score": 3, "selected": false, "text": "#ifdef _WIN32\n#define _CRT_SECURE_NO_DEPRECATE\n#endif\n" }, { "answer_id": 27709586, "author": "Karthik_elan", "author_id": 3220295, "author_profile": "https://Stackoverflow.com/users/3220295", "pm_score": 0, "selected": false, "text": "#include <opencv\\cv.h>\n error C4996: 'fopen': This function or variable may be unsafe. Consider using fopen_s instead. To disable deprecation, use _CRT_SECURE_NO_WARNINGS. See online help for details. c:\\program files (x86)\\opencv\\build\\include\\opencv2\\flann\\logger.h \n" }, { "answer_id": 28692707, "author": "JTIM", "author_id": 2076775, "author_profile": "https://Stackoverflow.com/users/2076775", "pm_score": 1, "selected": false, "text": "#if defined(_MSC_VER) || defined(WIN32) || defined(_WIN32) || defined(__WIN32__) \\\n || defined(WIN64) || defined(_WIN64) || defined(__WIN64__) \n\n errno_t err = fopen_s(&stream,name, \"w\");\n\n#endif\n\n#if defined(unix) || defined(__unix) || defined(__unix__) \\\n || defined(linux) || defined(__linux) || defined(__linux__) \\\n || defined(sun) || defined(__sun) \\\n || defined(BSD) || defined(__OpenBSD__) || defined(__NetBSD__) \\\n || defined(__FreeBSD__) || defined __DragonFly__ \\\n || defined(sgi) || defined(__sgi) \\\n || defined(__MACOSX__) || defined(__APPLE__) \\\n || defined(__CYGWIN__) \n\n stream = fopen(name, \"w\");\n\n#endif\n" }, { "answer_id": 35191511, "author": "riderBill", "author_id": 4079867, "author_profile": "https://Stackoverflow.com/users/4079867", "pm_score": 1, "selected": false, "text": "#pragma once\n#if !defined(FCN_S_MACROS_H)\n #define FCN_S_MACROS_H\n\n #include <cstdio>\n #include <string> // Need this for _stricmp\n using namespace std;\n\n // _MSC_VER = 1400 is MSVC 2005. _MSC_VER = 1600 (MSVC 2010) was the current\n // value when I wrote (some of) these macros.\n\n #if (defined(_MSC_VER) && (_MSC_VER >= 1400) )\n\n inline extern\n FILE* fcnSMacro_fopen_s(char *fname, char *mode)\n { FILE *fptr;\n fopen_s(&fptr, fname, mode);\n return fptr;\n }\n #define fopen(fname, mode) fcnSMacro_fopen_s((fname), (mode))\n\n #else\n #define fopen_s(fp, fmt, mode) *(fp)=fopen( (fmt), (mode))\n\n #endif //_MSC_VER\n\n#endif // FCN_S_MACROS_H\n" }, { "answer_id": 42908405, "author": "Marcelo Coronel", "author_id": 7642855, "author_profile": "https://Stackoverflow.com/users/7642855", "pm_score": 1, "selected": false, "text": "#define _CRT_SECURE_NO_WARNINGS\n" }, { "answer_id": 45114212, "author": "Bryant", "author_id": 7666772, "author_profile": "https://Stackoverflow.com/users/7666772", "pm_score": 3, "selected": false, "text": "Preprocessor Definitions _CRT_SECURE_NO_WARNINGS" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14386", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
14,389
<p>I have a script that parses the filenames of TV episodes (show.name.s01e02.avi for example), grabs the episode name (from the www.thetvdb.com API) and automatically renames them into something nicer (Show Name - [01x02].avi)</p> <p>The script works fine, that is until you try and use it on files that have Unicode show-names (something I never really thought about, since all the files I have are English, so mostly pretty-much all fall within <code>[a-zA-Z0-9'\-]</code>)</p> <p>How can I allow the regular expressions to match accented characters and the likes? Currently the regex's config section looks like..</p> <pre><code>config['valid_filename_chars'] = """0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!@£$%^&amp;*()_+=-[]{}"'.,&lt;&gt;`~? """ config['valid_filename_chars_regex'] = re.escape(config['valid_filename_chars']) config['name_parse'] = [ # foo_[s01]_[e01] re.compile('''^([%s]+?)[ \._\-]\[[Ss]([0-9]+?)\]_\[[Ee]([0-9]+?)\]?[^\\/]*$'''% (config['valid_filename_chars_regex'])), # foo.1x09* re.compile('''^([%s]+?)[ \._\-]\[?([0-9]+)x([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])), # foo.s01.e01, foo.s01_e01 re.compile('''^([%s]+?)[ \._\-][Ss]([0-9]+)[\.\- ]?[Ee]([0-9]+)[^\\/]*$''' % (config['valid_filename_chars_regex'])), # foo.103* re.compile('''^([%s]+)[ \._\-]([0-9]{1})([0-9]{2})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])), # foo.0103* re.compile('''^([%s]+)[ \._\-]([0-9]{2})([0-9]{2,3})[\._ -][^\\/]*$''' % (config['valid_filename_chars_regex'])), ] </code></pre>
[ { "answer_id": 14391, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": true, "text": "[\\u0000-\\uFFFF] re.UNICODE UNICODE \\w [0-9_]" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14389", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
14,395
<p>For my own project at home, I'm using the rather excellent managed subversion hosting from <a href="http://cvsdude.com/" rel="nofollow noreferrer">CVSDude</a>. As it's only me working on the code right now, I'm not using CruiseControl.net, however I expect this will change in the next couple of months and will want a full build process to kick off upon check-in.</p> <p>Has anyone managed to get CruiseControl.net working with CVSDude? My collegue Mike has this <a href="http://mikehadlow.blogspot.com/2008/01/more-on-source-repository-hosting-what.html" rel="nofollow noreferrer">blog post</a> where someone from CVSDude said: </p> <blockquote> <p>"Your can use our post-commit call back facility to call a URL on your server, which passes variables relating to the last checkin (variables detailed in our specification). Your CGI script will these variables and perform whatever tasks are required i.e. updating Cruise Control, etc."</p> </blockquote> <p>Sounds lovely. But has anyone <em>actually done it</em> with cruisecontrol?</p>
[ { "answer_id": 14391, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": true, "text": "[\\u0000-\\uFFFF] re.UNICODE UNICODE \\w [0-9_]" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1122/" ]
14,397
<p>Currently we have a project with a standard subversion repository layout of:</p> <p>./trunk<br> ./branches<br> ./tags</p> <p>However, as we're moving down the road of OSGi and a modular project, we've ended up with:</p> <p>./trunk/bundle/main<br> ./trunk/bundle/modulea<br> ./trunk/bundle/moduleb ./tags/bundle/main-1.0.0<br> ./tags/bundle/main-1.0.1<br> ./tags/bundle/modulea-1.0.0</p> <p>The 'build' is still quite monolithic in that it builds all modules in sequence, though I'm starting to wonder if we should refactor the build/repository to something more like:</p> <p>./bundle/main/trunk<br> ./bundle/main/tags/main-1.0.0<br> ./bundle/main/tags/main-1.0.1<br> ./bundle/modulea/trunk<br> ./bundle/modulea/tags/modulea-1.0.0 </p> <p>In this pattern I would imagine each module building itself, and storing its binary in a repository (maven, ivy, or another path of the subversion repository itself).</p> <p>Are there guidelines or 'best-practices' over project layouts once one goes modular?</p>
[ { "answer_id": 14441, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 4, "selected": true, "text": "/bundle/<project>/(trunk|tags|branches)" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14397", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1720/" ]
14,402
<p>In my simple OpenGL program I get the following error about exit redefinition:</p> <pre><code>1&gt;c:\program files\microsoft visual studio 8\vc\include\stdlib.h(406) : error C2381: 'exit' : redefinition; __declspec(noreturn) differs 1&gt; c:\program files\microsoft visual studio 8\vc\platformsdk\include\gl\glut.h(146) : see declaration of 'exit' </code></pre> <p>I'm using Nate Robins' <a href="http://www.xmission.com/~nate/glut.html" rel="noreferrer">GLUT for Win32</a> and get this error with Visual Studio 2005 or Visual C++ 2005 (Express Edition). What is the cause of this error and how do I fix it?</p>
[ { "answer_id": 14403, "author": "Ashwin Nanjappa", "author_id": 1630, "author_profile": "https://Stackoverflow.com/users/1630", "pm_score": 7, "selected": true, "text": "#include <stdlib.h>\n#include <GL/glut.h>\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14402", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
14,413
<p>I want to use the functions exposed under the OpenGL extensions. I'm on Windows, how do I do this?</p>
[ { "answer_id": 14414, "author": "Ashwin Nanjappa", "author_id": 1630, "author_profile": "https://Stackoverflow.com/users/1630", "pm_score": 5, "selected": true, "text": "glGenFramebuffersEXT()\nglBindFramebufferEXT()\nglFramebufferTexture2DEXT()\nglCheckFramebufferStatusEXT()\nglDeleteFramebuffersEXT()\n #include <glext.h> typedef void (APIENTRYP PFNGLGENFRAMEBUFFERSEXTPROC) (GLsizei n, GLuint *framebuffers); for GLAPI void APIENTRY glGenFramebuffersEXT (GLsizei, GLuint *);\n PFNGLGENFRAMEBUFFERSEXTPROC glGenFramebuffersEXT;\nPFNGLBINDFRAMEBUFFEREXTPROC glBindFramebufferEXT;\nPFNGLFRAMEBUFFERTEXTURE2DEXTPROC glFramebufferTexture2DEXT;\nPFNGLCHECKFRAMEBUFFERSTATUSEXTPROC glCheckFramebufferStatusEXT;\nPFNGLDELETEFRAMEBUFFERSEXTPROC glDeleteFramebuffersEXT;\n glGenFramebuffersEXT = (PFNGLGENFRAMEBUFFERSEXTPROC) wglGetProcAddress(\"glGenFramebuffersEXT\");\nglBindFramebufferEXT = (PFNGLBINDFRAMEBUFFEREXTPROC) wglGetProcAddress(\"glBindFramebufferEXT\");\nglFramebufferTexture2DEXT = (PFNGLFRAMEBUFFERTEXTURE2DEXTPROC) wglGetProcAddress(\"glFramebufferTexture2DEXT\");\nglCheckFramebufferStatusEXT = (PFNGLCHECKFRAMEBUFFERSTATUSEXTPROC) wglGetProcAddress(\"glCheckFramebufferStatusEXT\");\nglDeleteFramebuffersEXT = (PFNGLDELETEFRAMEBUFFERSEXTPROC) wglGetProcAddress(\"glDeleteFramebuffersEXT\");\n if (NULL == glGenFramebuffersEXT || NULL == glBindFramebufferEXT || NULL == glFramebufferTexture2DEXT\n || NULL == glCheckFramebufferStatusEXT || NULL == glDeleteFramebuffersEXT)\n{\n // Extension functions not loaded!\n exit(1);\n}\n glGenFramebuffersEXT(1, &fbo);\nglBindFramebufferEXT(GL_FRAMEBUFFER_EXT, fbo);\nglFramebufferTexture2DEXT(GL_FRAMEBUFFER_EXT, GL_COLOR_ATTACHMENT0_EXT, GL_TEXTURE_2D, colorTex[0], 0);\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14413", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1630/" ]
14,422
<p>For example, <a href="http://developer.apple.com/cocoa/pyobjc.html" rel="nofollow noreferrer">http://developer.apple.com/cocoa/pyobjc.html</a> is still for OS X 10.4 Tiger, not 10.5 Leopard.. And that's the official Apple documentation for it..</p> <p>The official PyObjC page is equally bad, <a href="http://pyobjc.sourceforge.net/" rel="nofollow noreferrer">http://pyobjc.sourceforge.net/</a></p> <p>It's so bad it's baffling.. I'm considering learning Ruby primarily because the RubyCocoa stuff is so much better documented, and there's lots of decent tutorials (<a href="http://www.rubycocoa.com/" rel="nofollow noreferrer">http://www.rubycocoa.com/</a> for example), and because of the Shoes GUI toolkit..</p> <p>Even <a href="http://66.163.168.225/babelfish/translate_url_content?lp=ja_en&amp;url=http%3A%2F%2Fblog.monospace.jp%2F2007%2F11%2F05%2Fxcode3_cocoa_python%2F&amp;fr=avbbf-us&amp;.intl=us" rel="nofollow noreferrer">this badly-auto-translated Japanese tutorial</a> is more useful than the rest of the documentation I could find..</p> <p>All I want to do is create fairly simple Python applications with Cocoa GUI's..<br> Can anyone shed light on the horrible documentation, or point me at some tutorials that don't just give you huge blocks of code and assume you know what <code>NSThread.detachNewThreadSelector_toTarget_withObject_("queryController", self, None)</code> does..?</p>
[ { "answer_id": 14479, "author": "Sören Kuklau", "author_id": 1600, "author_profile": "https://Stackoverflow.com/users/1600", "pm_score": 3, "selected": false, "text": "NSThread.detachNewThreadSelector_toTarget_withObject_(\"queryController\", self, None)\n NSThread + detachNewThreadSelector:toTarget:withObject:" }, { "answer_id": 121316, "author": "Christopher Ashworth", "author_id": 20021, "author_profile": "https://Stackoverflow.com/users/20021", "pm_score": 3, "selected": false, "text": "NSThread.detachNewThreadSelector_toTarget_withObject_(\"queryController\", self, None) \n [NSThread detachNewThreadSelector:@selector(queryController:) toTarget:self withObject:nil];\n" }, { "answer_id": 396823, "author": "Dan", "author_id": 49663, "author_profile": "https://Stackoverflow.com/users/49663", "pm_score": 3, "selected": false, "text": "@PyObjcTools.AppHelper.endSheetMethod\ndef alertEnded_code_context_(self, alert, choice, context):\n pass\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14422", "https://Stackoverflow.com", "https://Stackoverflow.com/users/745/" ]
14,451
<p>What is the best way to make a delphi application (delphi 2007 for win32 here) go completely full screen, removing the application border and covering windows task bar ?</p> <p>I am looking for something similar to what IE does when you hit F11.</p> <p>I wish this to be a run time option for the user not a design time decision by my good self.</p> <p>As Mentioned in the accepted answer </p> <pre><code>BorderStyle := bsNone; </code></pre> <p>was part of the way to do it. Strangely I kept getting a <code>E2010 Incompatible types: 'TFormBorderStyle' and 'TBackGroundSymbol'</code> error when using that line (another type had <code>bsNone</code> defined).</p> <p>To overcome this I had to use : </p> <pre><code>BorderStyle := Forms.bsNone; </code></pre>
[ { "answer_id": 14458, "author": "JosephStyons", "author_id": 672, "author_profile": "https://Stackoverflow.com/users/672", "pm_score": 2, "selected": false, "text": "procedure TForm1.FormCreate(Sender: TObject) ;\nbegin\n //maximize the window\n WindowState := wsMaximized;\n //hide the title bar\n SetWindowLong(Handle,GWL_STYLE,GetWindowLong(Handle,GWL_STYLE) and not WS_CAPTION);\n ClientHeight := Height;\nend;\n unit Unit1;\n\ninterface\n\nuses\n Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,\n Dialogs, StdCtrls;\n\ntype\n TForm1 = class(TForm)\n btnGoFullScreen: TButton;\n btnNotFullScreen: TButton;\n btnShowTitleBar: TButton;\n btnHideTitleBar: TButton;\n btnQuit: TButton;\n procedure btnGoFullScreenClick(Sender: TObject);\n procedure btnShowTitleBarClick(Sender: TObject);\n procedure btnHideTitleBarClick(Sender: TObject);\n procedure btnNotFullScreenClick(Sender: TObject);\n procedure btnQuitClick(Sender: TObject);\n private\n SavedLeft : integer;\n SavedTop : integer;\n SavedWidth : integer;\n SavedHeight : integer;\n SavedWindowState : TWindowState;\n procedure FullScreen;\n procedure NotFullScreen;\n procedure SavePosition;\n procedure HideTitleBar;\n procedure ShowTitleBar;\n procedure RestorePosition;\n procedure MaximizeWindow;\n public\n { Public declarations }\n end;\n\nvar\n Form1: TForm1;\n\nimplementation\n\n{$R *.dfm}\n\nprocedure TForm1.btnQuitClick(Sender: TObject);\nbegin\n Application.Terminate;\nend;\n\nprocedure TForm1.btnGoFullScreenClick(Sender: TObject);\nbegin\n FullScreen;\nend;\n\nprocedure TForm1.btnNotFullScreenClick(Sender: TObject);\nbegin\n NotFullScreen;\nend;\n\nprocedure TForm1.btnShowTitleBarClick(Sender: TObject);\nbegin\n ShowTitleBar;\nend;\n\nprocedure TForm1.btnHideTitleBarClick(Sender: TObject);\nbegin\n HideTitleBar;\nend;\n\nprocedure TForm1.FullScreen;\nbegin\n SavePosition;\n HideTitleBar;\n MaximizeWindow;\nend;\n\nprocedure TForm1.HideTitleBar;\nbegin\n SetWindowLong(Handle,GWL_STYLE,GetWindowLong(Handle,GWL_STYLE) and not WS_CAPTION);\n ClientHeight := Height;\nend;\n\nprocedure TForm1.MaximizeWindow;\nbegin\n WindowState := wsMaximized;\nend;\n\nprocedure TForm1.NotFullScreen;\nbegin\n RestorePosition;\n ShowTitleBar;\nend;\n\nprocedure TForm1.RestorePosition;\nbegin\n //this proc uses what we saved in \"SavePosition\"\n WindowState := SavedWindowState;\n Top := SavedTop;\n Left := SavedLeft;\n Width := SavedWidth;\n Height := SavedHeight;\nend;\n\nprocedure TForm1.SavePosition;\nbegin\n SavedLeft := Left;\n SavedHeight := Height;\n SavedTop := Top;\n SavedWidth := Width;\n SavedWindowState := WindowState;\nend;\n\nprocedure TForm1.ShowTitleBar;\nbegin\n SetWindowLong(Handle,gwl_Style,GetWindowLong(Handle,gwl_Style) or ws_Caption or ws_border);\n Height := Height + GetSystemMetrics(SM_CYCAPTION);\n Refresh;\nend;\n\nend.\n" }, { "answer_id": 14472, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 6, "selected": true, "text": "procedure TForm52.Button1Click(Sender: TObject);\nbegin\n BorderStyle := bsNone;\n WindowState := wsMaximized;\nend;\n" }, { "answer_id": 14480, "author": "onnodb", "author_id": 1037, "author_profile": "https://Stackoverflow.com/users/1037", "pm_score": 3, "selected": false, "text": "procedure TSomeForm.FormShow(Sender: TObject) ;\nvar\n r : TRect;\nbegin\n Borderstyle := bsNone;\n SystemParametersInfo\n (SPI_GETWORKAREA, 0, @r,0) ;\n SetBounds\n (r.Left, r.Top, r.Right-r.Left, r.Bottom-r.Top) ;\nend;\n FormStyle := fsStayOnTop;\nBorderStyle := bsNone;\nLeft := 0;\nTop := 0;\nWidth := Screen.Width;\nHeight := Screen.Height;\n private // in form declaration\n Procedure WMGetMinMaxInfo(Var msg: TWMGetMinMaxInfo);\n message WM_GETMINMAXINFO;\n\nProcedure TForm1.WMGetMinMaxInfo(Var msg: TWMGetMinMaxInfo);\n Begin\n inherited;\n With msg.MinMaxInfo^.ptMaxTrackSize Do Begin\n X := GetDeviceCaps( Canvas.handle, HORZRES ) + (Width - ClientWidth);\n Y := GetDeviceCaps( Canvas.handle, VERTRES ) + (Height - ClientHeight\n);\n End;\n End;\n\nprocedure TForm1.Button2Click(Sender: TObject);\nConst\n Rect: TRect = (Left:0; Top:0; Right:0; Bottom:0);\n FullScreen: Boolean = False;\nbegin\n FullScreen := not FullScreen; \n If FullScreen Then Begin\n Rect := BoundsRect;\n SetBounds(\n Left - ClientOrigin.X,\n Top - ClientOrigin.Y,\n GetDeviceCaps( Canvas.handle, HORZRES ) + (Width - ClientWidth),\n GetDeviceCaps( Canvas.handle, VERTRES ) + (Height - ClientHeight ));\n // Label2.caption := IntToStr(GetDeviceCaps( Canvas.handle, VERTRES ));\n End\n Else\n BoundsRect := Rect;\nend; \n" }, { "answer_id": 3157913, "author": "Freddie Bell", "author_id": 381084, "author_profile": "https://Stackoverflow.com/users/381084", "pm_score": 1, "selected": false, "text": "private\n{ Private declarations }\n StickyAt: Word;\n procedure WMWINDOWPOSCHANGING(Var Msg: TWMWINDOWPOSCHANGING); Message M_WINDOWPOSCHANGING;\n Procedure WMGetMinMaxInfo(Var msg: TWMGetMinMaxInfo); message WM_GETMINMAXINFO;\n procedure TForm2.WMWINDOWPOSCHANGING(var Msg: TWMWINDOWPOSCHANGING);\n var\n A, B: Integer;\n iFrameSize: Integer;\n iCaptionHeight: Integer;\n iMenuHeight: Integer;\n begin\n\n iFrameSize := GetSystemMetrics(SM_CYFIXEDFRAME);\n iCaptionHeight := GetSystemMetrics(SM_CYCAPTION);\n iMenuHeight := GetSystemMetrics(SM_CYMENU);\n\n // inside the Mainform client area\n A := Application.MainForm.Left + iFrameSize;\n B := Application.MainForm.Top + iFrameSize + iCaptionHeight + iMenuHeight;\n\n with Msg.WindowPos^ do\n begin\n\n if x <= A + StickyAt then\n x := A;\n\n if x + cx >= A + Application.MainForm.ClientWidth - StickyAt then\n x := (A + Application.MainForm.ClientWidth) - cx + 1;\n\n if y <= B + StickyAt then\n y := B;\n\n if y + cy >= B + Application.MainForm.ClientHeight - StickyAt then\n y := (B + Application.MainForm.ClientHeight) - cy + 1;\n\n end;\nend;\n Procedure TForm2.WMGetMinMaxInfo(Var msg: TWMGetMinMaxInfo);\nvar\n iFrameSize: Integer;\n iCaptionHeight: Integer;\n iMenuHeight: Integer;\nBegin\n inherited;\n iFrameSize := GetSystemMetrics(SM_CYFIXEDFRAME);\n iCaptionHeight := GetSystemMetrics(SM_CYCAPTION);\n iMenuHeight := GetSystemMetrics(SM_CYMENU);\n With msg.MinMaxInfo^.ptMaxPosition Do\n begin\n // position of top when maximised\n X := Application.MainForm.Left + iFrameSize + 1;\n Y := Application.MainForm.Top + iFrameSize + iCaptionHeight + iMenuHeight + 1;\n end;\n With msg.MinMaxInfo^.ptMaxSize Do\n Begin\n // width and height when maximized\n X := Application.MainForm.ClientWidth;\n Y := Application.MainForm.ClientHeight;\n End;\n With msg.MinMaxInfo^.ptMaxTrackSize Do\n Begin\n // maximum size when maximised\n X := Application.MainForm.ClientWidth;\n Y := Application.MainForm.ClientHeight;\n End;\n // to do: minimum size (maybe)\nEnd;\n" }, { "answer_id": 11867212, "author": "Taras", "author_id": 889787, "author_profile": "https://Stackoverflow.com/users/889787", "pm_score": 2, "selected": false, "text": " WindowState:=wsMaximized;\n if (newwidth<width) and (newheight<height) then\n Resize:=false;\n" }, { "answer_id": 17927052, "author": "Edijs Kolesnikovičs", "author_id": 2578854, "author_profile": "https://Stackoverflow.com/users/2578854", "pm_score": 0, "selected": false, "text": "Form1.Position := poDefaultPosOnly;\nForm1.FormStyle := fsStayOnTop;\nForm1.BorderStyle := bsNone;\nForm1.Left := 0;\nForm1.Top := 0;\nForm1.Width := Screen.Width;\nForm1.Height := Screen.Height;\n" }, { "answer_id": 23679070, "author": "Noener", "author_id": 3218191, "author_profile": "https://Stackoverflow.com/users/3218191", "pm_score": 0, "selected": false, "text": "Align = alClient \nFormStyle = fsStayOnTop\n" }, { "answer_id": 53226931, "author": "Jacek Krawczyk", "author_id": 1960514, "author_profile": "https://Stackoverflow.com/users/1960514", "pm_score": 1, "selected": false, "text": "procedure TFormHelper.FullScreenMode;\nbegin\n BorderStyle := bsNone;\n ShowWindowAsync(Handle, SW_MAXIMIZE);\nend;\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14451", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1724/" ]
14,453
<p>I'm needing to access Excel workbooks from .Net. I know all about the different ways of doing it (I've written them up in a <a href="http://blog.functionalfun.net/2008/06/reading-and-writing-excel-files-with.html" rel="noreferrer" title="Reading and Writing Excel files in .Net">blog post</a>), and I know that using a native .Net component is going to be the fastest. But the question is, which of the components wins? Has anybody benchmarked them? I've been using Syncfusion XlsIO, but that's very slow for some key operations (like deleting rows in a workbook containing thousands of Named ranges).</p>
[ { "answer_id": 47135283, "author": "CAD bloke", "author_id": 492, "author_profile": "https://Stackoverflow.com/users/492", "pm_score": 0, "selected": false, "text": "headerStyle.BeginUpdate();\nworkbook.SetPaletteColor(8, System.Drawing.Color.FromArgb(255, 174, 33));\nheaderStyle.Color = System.Drawing.Color.FromArgb(255, 174, 33);\nheaderStyle.Font.Bold = true;\nheaderStyle.Borders[ExcelBordersIndex.EdgeLeft] .LineStyle = ExcelLineStyle.Thin;\nheaderStyle.Borders[ExcelBordersIndex.EdgeRight] .LineStyle = ExcelLineStyle.Thin;\nheaderStyle.Borders[ExcelBordersIndex.EdgeTop] .LineStyle = ExcelLineStyle.Thin;\nheaderStyle.Borders[ExcelBordersIndex.EdgeBottom].LineStyle = ExcelLineStyle.Thin;\nheaderStyle.EndUpdate();\n ExcelNamedStyleXml headerStyle = xlPackage.Workbook.Styles.CreateNamedStyle(\"HeaderStyle\");\nheaderStyle.Style.Fill.PatternType = ExcelFillStyle.Solid; // <== needed or BackgroundColor throws an exception\nheaderStyle.Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.FromArgb(255, 174, 33));\nheaderStyle.Style.Font.Bold = true;\nheaderStyle.Style.Border.Left.Style = ExcelBorderStyle.Thin;\nheaderStyle.Style.Border.Right.Style = ExcelBorderStyle.Thin;\nheaderStyle.Style.Border.Top.Style = ExcelBorderStyle.Thin;\nheaderStyle.Style.Border.Bottom.Style = ExcelBorderStyle.Thin;\n" } ]
2008/08/18
[ "https://Stackoverflow.com/questions/14453", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1727/" ]