qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
207,959
<p>I'm converting some Windows batch files to Unix scripts using sh. I have problems because some behavior is dependent on the %~dp0 macro available in batch files.</p> <p>Is there any sh equivalent to this? Any way to obtain the directory where the executing script lives?</p>
[ { "answer_id": 207961, "author": "Sarien", "author_id": 1994377, "author_profile": "https://Stackoverflow.com/users/1994377", "pm_score": 3, "selected": false, "text": "${0}\n {$var%Pattern}\nRemove from $var the shortest part of $Pattern that matches the back end of $var.\n ${0%/*}\n #!/bin/bash\ncalled_path=${0%/*}\nstripped=${called_path#[^/]*}\nreal_path=`pwd`$stripped\necho \"called path: $called_path\"\necho \"stripped: $stripped\"\necho \"pwd: `pwd`\"\necho \"real path: $real_path\n" }, { "answer_id": 207966, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "${0%/*}\n" }, { "answer_id": 208023, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 4, "selected": false, "text": "$0 %~dp0 dollar.sh #!/bin/bash\necho $0\n # ./dollar.sh\n./dollar.sh\n# /tmp/dollar.sh\n/tmp/dollar.sh\n cd `dirname $0`\nSCRIPTDIR=`pwd`\ncd -\n cd SCRIPTDIR cd -" }, { "answer_id": 212419, "author": "Steve Baker", "author_id": 13566, "author_profile": "https://Stackoverflow.com/users/13566", "pm_score": 2, "selected": false, "text": "readlink /proc/$$/fd/255\n dir=$(dirname $(readlink /proc/$$/fd/255))\n" }, { "answer_id": 24299484, "author": "Joel.L", "author_id": 3755059, "author_profile": "https://Stackoverflow.com/users/3755059", "pm_score": 1, "selected": false, "text": "dir=$(dirname $(readlink -m $BASH_SOURCE))\n #!/bin/bash\necho $(dirname $(readlink -m $BASH_SOURCE))\n $ ./somedir/test.sh \n/tmp/somedir\n$ source ./somedir/test.sh \n/tmp/somedir\n$ bash ./somedir/test.sh \n/tmp/somedir\n$ . ./somedir/test.sh \n/tmp/somedir\n" }, { "answer_id": 70477052, "author": "Don Johnny", "author_id": 9467336, "author_profile": "https://Stackoverflow.com/users/9467336", "pm_score": 1, "selected": false, "text": "#!/usr/bin/env bash\n\necho \"---------------- GET SELF PATH ----------------\"\necho \"NOW \\$(pwd) >>> $(pwd)\"\nORIGINAL_PWD_GETSELFPATHVAR=$(pwd)\n\necho \"NOW \\$0 >>> $0\"\necho \"NOW \\$_ >>> $_\"\necho \"NOW \\${0##*/} >>> ${0##*/}\"\n\nif test -n \"$BASH\"; then\n echo \"RUNNING IN BASH...\"\n SH_FILE_RUN_PATH_GETSELFPATHVAR=${BASH_SOURCE[0]}\nelif test -n \"$ZSH_NAME\"; then\n echo \"RUNNING IN ZSH...\"\n SH_FILE_RUN_PATH_GETSELFPATHVAR=${(%):-%x}\nelif test -n \"$KSH_VERSION\"; then\n echo \"RUNNING IN KSH...\"\n SH_FILE_RUN_PATH_GETSELFPATHVAR=${.sh.file}\nelse\n echo \"RUNNING IN DASH OR OTHERS ELSE...\"\n SH_FILE_RUN_PATH_GETSELFPATHVAR=$(lsof -p $$ -Fn0 | tr -d '\\0' | grep \"${0##*/}\" | tail -1 | sed 's/^[^\\/]*//g')\nfi\n\necho \"EXECUTING FILE PATH: $SH_FILE_RUN_PATH_GETSELFPATHVAR\"\n\ncd \"$(dirname \"$SH_FILE_RUN_PATH_GETSELFPATHVAR\")\" || return 1\n\nSH_FILE_RUN_BASENAME_GETSELFPATHVAR=$(basename \"$SH_FILE_RUN_PATH_GETSELFPATHVAR\")\n\n# Iterate down a (possible) chain of symlinks as lsof of macOS doesn't have -f option.\nwhile [ -L \"$SH_FILE_RUN_BASENAME_GETSELFPATHVAR\" ]; do\n SH_FILE_REAL_PATH_GETSELFPATHVAR=$(readlink \"$SH_FILE_RUN_BASENAME_GETSELFPATHVAR\")\n cd \"$(dirname \"$SH_FILE_REAL_PATH_GETSELFPATHVAR\")\" || return 1\n SH_FILE_RUN_BASENAME_GETSELFPATHVAR=$(basename \"$SH_FILE_REAL_PATH_GETSELFPATHVAR\")\ndone\n\n# Compute the canonicalized name by finding the physical path\n# for the directory we're in and appending the target file.\nSH_SELF_PATH_DIR_RESULT=$(pwd -P)\nSH_FILE_REAL_PATH_GETSELFPATHVAR=$SH_SELF_PATH_DIR_RESULT/$SH_FILE_RUN_BASENAME_GETSELFPATHVAR\necho \"EXECUTING REAL PATH: $SH_FILE_REAL_PATH_GETSELFPATHVAR\"\necho \"EXECUTING FILE DIR: $SH_SELF_PATH_DIR_RESULT\"\n\ncd \"$ORIGINAL_PWD_GETSELFPATHVAR\" || return 1\nunset ORIGINAL_PWD_GETSELFPATHVAR\nunset SH_FILE_RUN_PATH_GETSELFPATHVAR\nunset SH_FILE_RUN_BASENAME_GETSELFPATHVAR\nunset SH_FILE_REAL_PATH_GETSELFPATHVAR\necho \"---------------- GET SELF PATH ----------------\"\n# USE $SH_SELF_PATH_DIR_RESULT BEBLOW\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11628/" ]
207,964
<p>I have a large query in a PostgreSQL database. The Query is something like this:</p> <pre><code>SELECT * FROM table1, table2, ... WHERE table1.id = table2.id... </code></pre> <p>When I run this query as a sql query, the it returns the wanted row.</p> <p>But when I tries to use the same query to create a view, it returns an error:</p> <p>"error: column "id" specified more than once."</p> <p>(I use pgAdminIII when executing the queries.)</p> <p>I'll guess this happens because the resultset will have more than one column named "id". Is there someway to solve this, without writing all the column names in the query?</p>
[ { "answer_id": 208004, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 6, "selected": true, "text": "SELECT table1.id, column2, column3, ... FROM table1, table2 \nWHERE table1.id = table2.id\n postgres=# select 1 as a, 2 as a;\n a | a\n---+---\n 1 | 2\n(1 row)\n\npostgres=# create view foobar as select 1 as a, 2 as a;\nERROR: column \"a\" duplicated\npostgres=# create view foobar as select 1 as a, 2 as b;\nCREATE VIEW\n" }, { "answer_id": 208685, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": -1, "selected": false, "text": "DECLARE @sql AS varchar\n\nSELECT @sql = COALESCE(@sql + ', ', '') \n + '[' + TABLE_NAME + '].[' + COLUMN_NAME + ']'\n + CHAR(13) + CHAR(10)\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE TABLE_NAME IN ('table1', 'table2')\nORDER BY TABLE_NAME, ORDINAL_POSITION\n\nPRINT @sql\n SELECT @sql = COALESCE(@sql + ', ', '') \n + '[' + TABLE_NAME + '].[' + COLUMN_NAME + '] '\n + 'AS [' + TABLE_NAME + '_' + COLUMN_NAME + ']'\n + CHAR(13) + CHAR(10)\nFROM INFORMATION_SCHEMA.COLUMNS\nWHERE TABLE_NAME IN ('table1', 'table2')\nORDER BY TABLE_NAME, ORDINAL_POSITION\n" }, { "answer_id": 1493920, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "select *\nfrom a, b\nwhere a.id = b.id\n select *\nfrom a join b using (id)\n" }, { "answer_id": 45685957, "author": "Ben Wilson", "author_id": 908121, "author_profile": "https://Stackoverflow.com/users/908121", "pm_score": 0, "selected": false, "text": "to_date to_date(o.publication_date, 'DD/MM/YYYY') AS publication_date\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207964", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26567/" ]
207,965
<p>I came across a class instance function that needed to temporarily change a class instance variable, and then restore it when the function completed. The function had return statements all over the place, and before each return there was a restoring statement. That seemed messy to me, not to mention scary when a exception is thrown.</p> <p>As an improvement I came up with this generalization using a inner class definition. Here is a sample driver program (class restorer).</p> <pre><code>class Unwind { private: bool b_active_; ///&lt; the thing I want to be restored template&lt;typename T&gt; class restorer { T* ref_; T save_; public: restorer(T* perm) : ref_(perm), save_(*ref_) {}; ~restorer() { *ref_ = save_; } }; public: Unwind() : b_active_(false) {}; void a() { out("a in"); b(); out("a end"); } void b() { out("b in"); { restorer&lt;bool&gt; trust_in_the_stack(&amp;b_active_); // "restorer" created on the stack b_active_ = true; // change b_active_ only while "within" b() c(); out("b inner end"); } out("b end"); } void c() { out("c in"); d(); out("c end"); } void d() { out("d in"); cout &lt;&lt; "deepest" &lt;&lt; endl; out("d end"); } void out(const std::string&amp; msg) { std::cout &lt;&lt; msg &lt;&lt; ": " &lt;&lt; b_active_ &lt;&lt; std::endl; } }; int main() { Unwind u; u.a(); return 0; } </code></pre> <p>The output using g++ 4.2.3 (-Wall) was:</p> <pre> a in: 0 b in: 0 c in: 1 d in: 1 deepest d end: 1 c end: 1 b inner end: 1 b end: 0 a end: 0 </pre> <p>Which is what I expect at "b end".</p> <p>I felt that defining the class restorer inside the class Unwind helps to discourage misuse.</p> <p>My question is, is there a general and safer way to do this? I am worried about lifetime issues.</p> <p>Edit: Please assume that there are no threads, but "downstream" methods on the stack that change behavior based on this b_active_ flag.</p>
[ { "answer_id": 208108, "author": "dalle", "author_id": 19100, "author_profile": "https://Stackoverflow.com/users/19100", "pm_score": 3, "selected": false, "text": "template<typename T>\nclass restorer {\n T& ref_;\n T save_;\npublic:\n restorer(T& perm) : ref_(perm), save_(ref_) {};\n ~restorer() { ref_ = save_; }\n};\n" }, { "answer_id": 255524, "author": "piyo", "author_id": 28524, "author_profile": "https://Stackoverflow.com/users/28524", "pm_score": 1, "selected": true, "text": "/// c++ code sample\n#ifndef UTIL_RESTORER_HPP\n#define UTIL_RESTORER_HPP\n\nnamespace Utility {\n\n/// A Restorer instance (\"inst\") uses the stack to restore a saved\n/// value to the named variable when the instance \"inst\" goes out of\n/// scope.\n/// \n/// Restorer is designed to be an auto variable, not allocated on any\n/// other memory resource like a heap or in-place.\ntemplate<typename T>\nclass restorer {\n T& ref_;\n T save_;\npublic:\n restorer(T& perm) : ref_(perm), save_(perm) {}\n ~restorer() { ref_ = save_; }\n};\n\n}//NAMESPACE\n#endif//UTIL_RESTORER_HPP\n" }, { "answer_id": 63563179, "author": "J Howe", "author_id": 3756613, "author_profile": "https://Stackoverflow.com/users/3756613", "pm_score": 0, "selected": false, "text": " restorer<bool> trust_in_the_stack(&b_active_);\n #define restorer_macro(var) restorer<decltype(var)> restorer_##named{var};\n restorer_macro(b_active_);\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207965", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28524/" ]
207,976
<p>I have a bunch of enum types in some library header files that I'm using, and I want to have a way of converting enum values to user strings - and vice-versa. </p> <p>RTTI won't do it for me, because the 'user strings' need to be a bit more readable than the enumerations.</p> <p>A brute force solution would be a bunch of functions like this, but I feel that's a bit too C-like.</p> <pre><code>enum MyEnum {VAL1, VAL2,VAL3}; String getStringFromEnum(MyEnum e) { switch e { case VAL1: return "Value 1"; case VAL2: return "Value 2"; case VAL1: return "Value 3"; default: throw Exception("Bad MyEnum"); } } </code></pre> <p>I have a gut feeling that there's an elegant solution using templates, but I can't quite get my head round it yet.</p> <p><strong>UPDATE:</strong> Thanks for suggestions - I should have made clear that the enums are defined in a third-party library header, so I don't want to have to change the definition of them.</p> <p>My gut feeling now is to avoid templates and do something like this:</p> <pre><code>char * MyGetValue(int v, char *tmp); // implementation is trivial #define ENUM_MAP(type, strings) char * getStringValue(const type &amp;T) \ { \ return MyGetValue((int)T, strings); \ } ; enum eee {AA,BB,CC}; - exists in library header file ; enum fff {DD,GG,HH}; ENUM_MAP(eee,"AA|BB|CC") ENUM_MAP(fff,"DD|GG|HH") // To use... eee e; fff f; std::cout&lt;&lt; getStringValue(e); std::cout&lt;&lt; getStringValue(f); </code></pre>
[ { "answer_id": 207985, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 4, "selected": false, "text": "enum {\n VALUE1, /* value 1 */\n VALUE2, /* value 2 */\n};\n const char* enum2str[] = {\n \"value 1\", /* VALUE1 */\n \"value 2\", /* VALUE2 */\n};\n enum State{\n state0 = 0, /* state 0 */\n state1 = 1, /* state 1 */\n state2 = 2, /* state 2 */\n state3 = 4, /* state 3 */\n\n state16 = 0x10000, /* state 16 */\n};\n template <State n> struct enum2str { static const char * const value; };\ntemplate <State n> const char * const enum2str<n>::value = \"error\";\n\ntemplate <> struct enum2str<state0> { static const char * const value; };\nconst char * const enum2str<state0>::value = \"state 0\";\n #include <iostream>\n\nint main()\n{\n std::cout << enum2str<state16>::value << std::endl;\n return 0;\n}\n" }, { "answer_id": 207993, "author": "moogs", "author_id": 26374, "author_profile": "https://Stackoverflow.com/users/26374", "pm_score": 1, "selected": false, "text": "enum EFooOptions\n {\nFooOptionsA = 0, EFooOptionsMin = 0,\nFooOptionsB,\nFooOptionsC,\nFooOptionsD \nEFooOptionsMax\n};\nextern const wchar* FOO_OPTIONS[EFooOptionsMax];\n const wchar* FOO_OPTIONS[] = {\n L\"One\",\n L\"Two\",\n L\"Three\",\n L\"Four\"\n};\n" }, { "answer_id": 207995, "author": "Constantin", "author_id": 20310, "author_profile": "https://Stackoverflow.com/users/20310", "pm_score": 2, "selected": false, "text": "MyEnum #include <iostream>\n\nenum MyEnum { VAL1, VAL2 };\n\ntemplate<MyEnum n> struct StrMyEnum {\n static char const* name() { return \"Unknown\"; }\n};\n\n#define STRENUM(val, str) \\\n template<> struct StrMyEnum<val> { \\\n static char const* name() { return str; }};\n\nSTRENUM(VAL1, \"Value 1\");\nSTRENUM(VAL2, \"Value 2\");\n\nint main() {\n std::cout << StrMyEnum<VAL2>::name();\n}\n case VAL1" }, { "answer_id": 208003, "author": "MSalters", "author_id": 15416, "author_profile": "https://Stackoverflow.com/users/15416", "pm_score": 6, "selected": false, "text": "std::map<MyEnum, char const*> std::map<MyEnum, const char*> MyMap;\nmap_init(MyMap)\n (eValue1, \"A\")\n (eValue2, \"B\")\n (eValue3, \"C\")\n;\n template <typename T> map_init(T&) map_init_helper<T> map_init_helper<T> map_init_helper& operator()(typename T::key_type const&, typename T::value_type const&) *this operator() operator() operator<< std::ostream template<typename T> struct map_init_helper\n{\n T& data;\n map_init_helper(T& d) : data(d) {}\n map_init_helper& operator() (typename T::key_type const& key, typename T::mapped_type const& value)\n {\n data[key] = value;\n return *this;\n }\n};\n\ntemplate<typename T> map_init_helper<T> map_init(T& item)\n{\n return map_init_helper<T>(item);\n}\n std::unordered_map" }, { "answer_id": 320727, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "std::map<std::string, switches::FCSW2::type> init_FCSW2_map() {\n std::map<std::string, switches::FCSW2::type> ans;\n ans[\"Act365Fixed\"] = FCSW2::Act365Fixed;\n ans[\"actual/365 (fixed)\"] = FCSW2::Act365Fixed;\n ans[\"Act360\"] = FCSW2::Act360;\n ans[\"actual/360\"] = FCSW2::Act360;\n ans[\"Act365Act\"] = FCSW2::Act365Act;\n ans[\"actual/365 (actual)\"] = FCSW2::Act365Act;\n ans[\"ISDA30360\"] = FCSW2::ISDA30360;\n ans[\"30/360 (ISDA)\"] = FCSW2::ISDA30360;\n ans[\"ISMA30E360\"] = FCSW2::ISMA30E360;\n ans[\"30E/360 (30/360 ISMA)\"] = FCSW2::ISMA30E360;\n return ans;\n}\nswitches::FCSW2::type FCSW2_lookup(const char* fincad_switch) {\n static std::map<std::string, switches::FCSW2::type> switch_map = init_FCSW2_map();\n std::map<std::string, switches::FCSW2::type>::iterator it = switch_map.find(fincad_switch);\n if(it != switch_map.end()) {\n return it->second;\n } else {\n throw FCSwitchLookupError(\"Bad Match: FCSW2\");\n }\n}\n" }, { "answer_id": 320888, "author": "David Allan Finch", "author_id": 27417, "author_profile": "https://Stackoverflow.com/users/27417", "pm_score": 4, "selected": false, "text": "enum Colours {\n# define X(a) a,\n# include \"colours.def\"\n# undef X\n ColoursCount\n};\n\nchar const* const colours_str[] = {\n# define X(a) #a,\n# include \"colours.def\"\n# undef X\n 0\n};\n\ntemplate <class T> T str2enum( const char* );\ntemplate <class T> const char* enum2str( T );\n\n#define STR2ENUM(TYPE,ARRAY) \\\ntemplate <> \\\nTYPE str2enum<TYPE>( const char* str ) \\\n { \\\n for( int i = 0; i < (sizeof(ARRAY)/sizeof(ARRAY[0])); i++ ) \\\n if( !strcmp( ARRAY[i], str ) ) \\\n return TYPE(i); \\\n return TYPE(0); \\\n }\n\n#define ENUM2STR(TYPE,ARRAY) \\\ntemplate <> \\\nconst char* enum2str<TYPE>( TYPE v ) \\\n { \\\n return ARRAY[v]; \\\n }\n\n#define ENUMANDSTR(TYPE,ARRAY)\\\n STR2ENUM(TYPE,ARRAY) \\\n ENUM2STR(TYPE,ARRAY)\n\nENUMANDSTR(Colours,colours_str)\n X(Red)\nX(Green)\nX(Blue)\nX(Cyan)\nX(Yellow)\nX(Magenta)\n" }, { "answer_id": 340233, "author": "Alastair", "author_id": 31038, "author_profile": "https://Stackoverflow.com/users/31038", "pm_score": 5, "selected": false, "text": "boost::assign::map_list_of #include <boost/assign/list_of.hpp>\n#include <boost/unordered_map.hpp>\n#include <iostream>\n\nusing boost::assign::map_list_of;\n\nenum eee { AA,BB,CC };\n\nconst boost::unordered_map<eee,const char*> eeeToString = map_list_of\n (AA, \"AA\")\n (BB, \"BB\")\n (CC, \"CC\");\n\nint main()\n{\n std::cout << \" enum AA = \" << eeeToString.at(AA) << std::endl;\n return 0;\n}\n" }, { "answer_id": 966567, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "// WeekEnd enumeration\nenum WeekEnd\n{\n Sunday = 1,\n Saturday = 7\n};\n\n// String support for WeekEnd\nBegin_Enum_String( WeekEnd )\n{\n Enum_String( Sunday );\n Enum_String( Saturday );\n}\nEnd_Enum_String;\n\n// Convert from WeekEnd to string\nconst std::string &str = EnumString<WeekEnd>::From( Saturday );\n// str should now be \"Saturday\"\n\n// Convert from string to WeekEnd\nWeekEnd w;\nEnumString<WeekEnd>::To( w, \"Sunday\" );\n// w should now be Sunday\n" }, { "answer_id": 2485213, "author": "Valentin H", "author_id": 298206, "author_profile": "https://Stackoverflow.com/users/298206", "pm_score": 2, "selected": false, "text": "toString toString Enum const char*" }, { "answer_id": 12422133, "author": "jamk", "author_id": 1359083, "author_profile": "https://Stackoverflow.com/users/1359083", "pm_score": 1, "selected": false, "text": "#define MY_LIST(X) X(value1), X(value2), X(value3)\n\nenum eMyEnum\n {\n MY_LIST(PLAIN)\n };\n\nconst char *szMyEnum[] =\n {\n MY_LIST(STRINGY)\n };\n\n\nint main(int argc, char *argv[])\n{\n\nstd::cout << szMyEnum[value1] << value1 <<\" \" << szMyEnum[value2] << value2 << std::endl;\n\nreturn 0;\n}\n //this is the enum definition\n#define COLOR_LIST(X) \\\n X( RED ,=21) \\\n X( GREEN ) \\\n X( BLUE ) \\\n X( PURPLE , =242) \\\n X( ORANGE ) \\\n X( YELLOW )\n\n//these are the macros\n#define enumfunc(enums,value) enums,\n#define enumfunc2(enums,value) enums value,\n#define ENUM2SWITCHCASE(enums) case(enums): return #enums;\n\n#define AUTOENUM(enumname,listname) enum enumname{listname(enumfunc2)};\n#define ENUM2STRTABLE(funname,listname) char* funname(int val) {switch(val) {listname(ENUM2SWITCHCASE) default: return \"undef\";}}\n#define ENUM2STRUCTINFO(spacename,listname) namespace spacename { int values[] = {listname(enumfunc)};int N = sizeof(values)/sizeof(int);ENUM2STRTABLE(enum2str,listname)};\n\n//here the enum and the string enum map table are generated\nAUTOENUM(testenum,COLOR_LIST)\nENUM2STRTABLE(testfunenum,COLOR_LIST)\nENUM2STRUCTINFO(colorinfo,COLOR_LIST)//colorinfo structur {int values[]; int N; char * enum2str(int);}\n\n//debug macros\n#define str(a) #a\n#define xstr(a) str(a)\n\n\nint main( int argc, char** argv )\n{\ntestenum x = YELLOW;\nstd::cout << testfunenum(GREEN) << \" \" << testfunenum(PURPLE) << PURPLE << \" \" << testfunenum(x);\n\nfor (int i=0;i< colorinfo::N;i++)\nstd::cout << std::endl << colorinfo::values[i] << \" \"<< colorinfo::enum2str(colorinfo::values[i]);\n\n return EXIT_SUCCESS;\n}\n #define ENUM2STRUCTINFO(spacename,listname) namespace spacename { int spacename##_##values[] = {listname(enumfunc)};int spacename##_##N = sizeof(spacename##_##values)/sizeof(int);ENUM2STRTABLE(spacename##_##enum2str,listname)};\n" }, { "answer_id": 20134475, "author": "muqker", "author_id": 1812866, "author_profile": "https://Stackoverflow.com/users/1812866", "pm_score": 2, "selected": false, "text": "map<int, string> & operator , (map<int, string> & dest, \n const pair<int, string> & keyValue) {\n dest[keyValue.first] = keyValue.second; \n return dest;\n}\n\n#define ADD_TO_MAP(name, value) pair<int, string>(name, #name)\n #include \"EnumUtilsImpl.h\"\n#define ADD_TO_ENUM(name, value) \\\n name value\n\n#define MAKE_ENUM_MAP_GLOBAL(values, mapName) \\\n int __makeMap##mapName() {mapName, values(ADD_TO_MAP); return 0;} \\\n int __makeMapTmp##mapName = __makeMap##mapName();\n\n#define MAKE_ENUM_MAP(values, mapName) \\\n mapName, values(ADD_TO_MAP);\n #include \"EnumUtils.h*\n\n#define MyEnumValues(ADD) \\\n ADD(val1, ), \\\n ADD(val2, ), \\\n ADD(val3, = 100), \\\n ADD(val4, )\n\nenum MyEnum {\n MyEnumValues(ADD_TO_ENUM)\n};\n\nmap<int, string> MyEnumStrings;\n// this is how you initialize it outside any function\nMAKE_ENUM_MAP_GLOBAL(MyEnumValues, MyEnumStrings); \n\nvoid MyInitializationMethod()\n{ \n // or you can initialize it inside one of your functions/methods\n MAKE_ENUM_MAP(MyEnumValues, MyEnumStrings); \n}\n" }, { "answer_id": 22255352, "author": "OlivierB", "author_id": 586277, "author_profile": "https://Stackoverflow.com/users/586277", "pm_score": 2, "selected": false, "text": "#include <string>\n#include <iostream>\n#include <stdexcept>\n#include <algorithm>\n#include <iterator>\n#include <sstream>\n#include <vector>\n\n#define MAKE_STRING(str, ...) #str, MAKE_STRING1_(__VA_ARGS__)\n#define MAKE_STRING1_(str, ...) #str, MAKE_STRING2_(__VA_ARGS__)\n#define MAKE_STRING2_(str, ...) #str, MAKE_STRING3_(__VA_ARGS__)\n#define MAKE_STRING3_(str, ...) #str, MAKE_STRING4_(__VA_ARGS__)\n#define MAKE_STRING4_(str, ...) #str, MAKE_STRING5_(__VA_ARGS__)\n#define MAKE_STRING5_(str, ...) #str, MAKE_STRING6_(__VA_ARGS__)\n#define MAKE_STRING6_(str, ...) #str, MAKE_STRING7_(__VA_ARGS__)\n#define MAKE_STRING7_(str, ...) #str, MAKE_STRING8_(__VA_ARGS__)\n#define MAKE_STRING8_(str, ...) #str, MAKE_STRING9_(__VA_ARGS__)\n#define MAKE_STRING9_(str, ...) #str, MAKE_STRING10_(__VA_ARGS__)\n#define MAKE_STRING10_(str) #str\n\n#define MAKE_ENUM(name, ...) MAKE_ENUM_(, name, __VA_ARGS__)\n#define MAKE_CLASS_ENUM(name, ...) MAKE_ENUM_(friend, name, __VA_ARGS__)\n\n#define MAKE_ENUM_(attribute, name, ...) name { __VA_ARGS__ }; \\\n attribute std::istream& operator>>(std::istream& is, name& e) { \\\n const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \\\n std::string str; \\\n std::istream& r = is >> str; \\\n const size_t len = sizeof(name##Str)/sizeof(name##Str[0]); \\\n const std::vector<std::string> enumStr(name##Str, name##Str + len); \\\n const std::vector<std::string>::const_iterator it = std::find(enumStr.begin(), enumStr.end(), str); \\\n if (it != enumStr.end())\\\n e = name(it - enumStr.begin()); \\\n else \\\n throw std::runtime_error(\"Value \\\"\" + str + \"\\\" is not part of enum \"#name); \\\n return r; \\\n }; \\\n attribute std::ostream& operator<<(std::ostream& os, const name& e) { \\\n const char* name##Str[] = { MAKE_STRING(__VA_ARGS__) }; \\\n return (os << name##Str[e]); \\\n }\n // Declare global enum\nenum MAKE_ENUM(Test3, Item13, Item23, Item33, Itdsdgem43);\n\nclass Essai {\npublic:\n // Declare enum inside class\n enum MAKE_CLASS_ENUM(Test, Item1, Item2, Item3, Itdsdgem4);\n\n};\n\nint main() {\n std::cout << Essai::Item1 << std::endl;\n\n Essai::Test ddd = Essai::Item1;\n std::cout << ddd << std::endl;\n\n std::istringstream strm(\"Item2\");\n strm >> ddd;\n\n std::cout << (int) ddd << std::endl;\n std::cout << ddd << std::endl;\n}\n" }, { "answer_id": 23404302, "author": "Debdatta Basu", "author_id": 1078703, "author_profile": "https://Stackoverflow.com/users/1078703", "pm_score": 4, "selected": false, "text": "#define AWESOME_MAKE_ENUM(name, ...) enum class name { __VA_ARGS__, __COUNT}; \\\ninline std::ostream& operator<<(std::ostream& os, name value) { \\\nstd::string enumName = #name; \\\nstd::string str = #__VA_ARGS__; \\\nint len = str.length(); \\\nstd::vector<std::string> strings; \\\nstd::ostringstream temp; \\\nfor(int i = 0; i < len; i ++) { \\\nif(isspace(str[i])) continue; \\\n else if(str[i] == ',') { \\\n strings.push_back(temp.str()); \\\n temp.str(std::string());\\\n } \\\n else temp<< str[i]; \\\n} \\\nstrings.push_back(temp.str()); \\\nos << enumName << \"::\" << strings[static_cast<int>(value)]; \\\nreturn os;} \n AWESOME_MAKE_ENUM(Animal,\n DOG,\n CAT,\n HORSE\n);\nauto dog = Animal::DOG;\nstd::cout<<dog;\n" }, { "answer_id": 26014689, "author": "Madwyn", "author_id": 1726669, "author_profile": "https://Stackoverflow.com/users/1726669", "pm_score": 1, "selected": false, "text": "typedef enum {\n ERR_CODE_OK = 0,\n ERR_CODE_SNAP,\n\n ERR_CODE_NUM\n} ERR_CODE;\n\nconst char* g_err_msg[ERR_CODE_NUM] = {\n /* ERR_CODE_OK */ \"OK\",\n /* ERR_CODE_SNAP */ \"Oh, snap!\",\n};\n const char* get_err_msg(ERR_CODE code) {\n return g_err_msg[code];\n}\n" }, { "answer_id": 29561635, "author": "Juan Gonzalez Burgos", "author_id": 4622991, "author_profile": "https://Stackoverflow.com/users/4622991", "pm_score": 3, "selected": false, "text": "#define MACROSTR(k) #k\n\n#define X_NUMBERS \\\n X(kZero ) \\\n X(kOne ) \\\n X(kTwo ) \\\n X(kThree ) \\\n X(kFour ) \\\n X(kMax )\n\nenum {\n#define X(Enum) Enum,\n X_NUMBERS\n#undef X\n} kConst;\n\nstatic char *kConstStr[] = {\n#define X(String) MACROSTR(String),\n X_NUMBERS\n#undef X\n};\n\nint main(void)\n{\n int k;\n printf(\"Hello World!\\n\\n\");\n\n for (k = 0; k < kMax; k++)\n {\n printf(\"%s\\n\", kConstStr[k]);\n }\n\n return 0;\n}\n" }, { "answer_id": 57618885, "author": "rmawatson", "author_id": 6661174, "author_profile": "https://Stackoverflow.com/users/6661174", "pm_score": 0, "selected": false, "text": "#define _enum_expand(arg) arg\n#define _enum_select_for_each(_,_0, _1, _2,_3,_4, _5, _6,_7,_8,_9,_10,_11,_12,_13,_14,_15,_16,_17,_18,_19,N, ...) N\n#define _enum_for_each_0(_call, arg0,arg1,...)\n#define _enum_for_each_1(_call, arg0,arg1) _call(arg0,arg1)\n#define _enum_for_each_2(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_1(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_3(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_2(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_4(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_3(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_5(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_4(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_6(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_5(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_7(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_6(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_8(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_7(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_9(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_8(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_10(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_9(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_11(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_10(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_12(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_11(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_13(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_12(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_14(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_13(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_15(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_14(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_16(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_15(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_17(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_16(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_18(_call, arg0,arg1, ...) _call(arg0,arg1) _enum_expand(_enum_for_each_17(_call,arg0, __VA_ARGS__))\n#define _enum_for_each_19(_call, arg0,arg1, ...) _call(arg) _enum_expand(_enum_for_each_18(_call,arg0, __VA_ARGS__))\n#define _enum_for_each(arg, ...) \\\n _enum_expand(_enum_select_for_each(_, ##__VA_ARGS__, \\\n _enum_for_each_19, _enum_for_each_18, _enum_for_each_17, _enum_for_each_16, _enum_for_each_15, \\\n _enum_for_each_14, _enum_for_each_13, _enum_for_each_12, _enum_for_each_11, _enum_for_each_10, \\\n _enum_for_each_9, _enum_for_each_8, _enum_for_each_7, _enum_for_each_6, _enum_for_each_5, \\\n _enum_for_each_4, _enum_for_each_3, _enum_for_each_2, _enum_for_each_1, _enum_for_each_0)(arg, ##__VA_ARGS__))\n\n#define _enum_strip_args_1(arg0) arg0\n#define _enum_strip_args_2(arg0, arg1) arg0, arg1\n#define _enum_make_args(...) (__VA_ARGS__)\n\n#define _enum_elem_arity1_1(arg) arg,\n#define _enum_elem_arity1( ...) _enum_expand(_enum_elem_arity1_1 __VA_ARGS__)\n#define _enum_elem_arity2_1(arg0,arg1) arg0 = arg1,\n#define _enum_elem_arity2( ...) _enum_expand(_enum_elem_arity2_1 __VA_ARGS__)\n\n#define _enum_elem_select_arity_2(_0, _1, NAME,...) NAME\n#define _enum_elem_select_arity_1(...) _enum_expand(_enum_elem_select_arity_2(__VA_ARGS__, _enum_elem_arity2,_enum_elem_arity1,_))\n#define _enum_elem_select_arity(enum_type,...) _enum_expand(_enum_elem_select_arity_1 __VA_ARGS__)(__VA_ARGS__)\n\n#define _enum_str_arity1_1(enum_type,arg) { enum_type::arg,#arg },\n#define _enum_str_arity1(enum_type,...) _enum_expand(_enum_str_arity1_1 _enum_make_args( enum_type, _enum_expand(_enum_strip_args_1 __VA_ARGS__)))\n#define _enum_str_arity2_1(enum_type,arg,value) { enum_type::arg,#arg },\n#define _enum_str_arity2(enum_type, ...) _enum_expand(_enum_str_arity2_1 _enum_make_args( enum_type, _enum_expand(_enum_strip_args_2 __VA_ARGS__)))\n#define _enum_str_select_arity_2(_0, _1, NAME,...) NAME\n#define _enum_str_select_arity_1(...) _enum_expand(_enum_str_select_arity_2(__VA_ARGS__, _enum_str_arity2,_enum_str_arity1,_))\n#define _enum_str_select_arity(enum_type,...) _enum_expand(_enum_str_select_arity_1 __VA_ARGS__)(enum_type,__VA_ARGS__)\n\n#define error_code_enum(enum_type,...) enum class enum_type { \\\n _enum_expand(_enum_for_each(_enum_elem_select_arity,enum_type, ##__VA_ARGS__))}; \\\n namespace _ ## enum_type ## _detail { \\\n template <typename> struct _ ## enum_type ## _error_code{ \\\n static const std::map<enum_type, const char*> enum_type ## _map; \\\n }; \\\n template <typename T> \\\n const std::map<enum_type, const char*> _ ## enum_type ## _error_code<T>::enum_type ## _map = { \\\n _enum_expand(_enum_for_each(_enum_str_select_arity,enum_type, ##__VA_ARGS__)) \\\n }; \\\n } \\\n inline const char* get_error_code_name(const enum_type& value) { \\\n return _ ## enum_type ## _detail::_ ## enum_type ## _error_code<enum_type>::enum_type ## _map.find(value)->second; \\\n } \n\nerror_code_enum(myenum,\n (one, 1),\n (two)\n);\n enum class myenum { \n one = 1,\n two,\n};\nnamespace _myenum_detail {\n template <typename>\n struct _myenum_error_code {\n static const std::map<myenum, const char*> myenum_map;\n };\n template <typename T>\n const std::map<myenum, const char*> _myenum_error_code<T>::myenum_map = {\n { myenum::one, \"one\" }, \n { myenum::two, \"two\" },\n };\n}\ninline const char* get_error_code_name(const myenum& value) { \n return _myenum_detail::_myenum_error_code<myenum>::myenum_map.find(value)->second; \n}\n" }, { "answer_id": 60169407, "author": "uIM7AI9S", "author_id": 11587896, "author_profile": "https://Stackoverflow.com/users/11587896", "pm_score": 3, "selected": false, "text": "namespace texs {\n typedef std::string Type;\n Type apple = \"apple\";\n Type wood = \"wood\";\n}\n" }, { "answer_id": 63265237, "author": "Daniel", "author_id": 2435924, "author_profile": "https://Stackoverflow.com/users/2435924", "pm_score": 2, "selected": false, "text": "enum Values {\n Val1,\n Val2\n};\n\nconstexpr string_view v_name[] = {\n [Val1] = \"Value 1\",\n [Val2] = \"Value 2\"\n}\n" }, { "answer_id": 67811462, "author": "Jerzy Jamroz", "author_id": 13100162, "author_profile": "https://Stackoverflow.com/users/13100162", "pm_score": 1, "selected": false, "text": "#include <vector>\n#include <string>\n\n//Split one comma-separated value string to vector\nstd::vector<std::string> split(std::string csv, char separator){/*trivial*/}\n\n//Initializer\n#define ENUMIFY(name, ...) \\\n struct name \\\n { \\\n enum Enum \\\n { \\\n __VA_ARGS__ \\\n }; \\\n static const std::vector<std::string>& Names() \\\n { \\\n const static std::vector<std::string> _{split(#__VA_ARGS__, ',')}; \\\n return _; \\\n }; \\\n };\n ENUMIFY(States, INIT, ON, OFF, RUNNING)\n std::string enum_str = States::Names()[States::ON];\n" }, { "answer_id": 69505404, "author": "Tom", "author_id": 5480147, "author_profile": "https://Stackoverflow.com/users/5480147", "pm_score": 1, "selected": false, "text": "#ifndef ENUM_ITEMS\n...\nenum myEnum\n{\n#ifndef ENUM_ITEM\n#define ENUM_ITEM(i) i\n#endif // !ENUM_ITEM\n#endif // !ENUM_ITEMS trick: ENUM_ITEM(i) = ENUM_ITEMS ? #i : i\n ENUM_ITEM(DEFINITION),\n ...\n ENUM_ITEM(DEFINITION_N)\n#ifndef ENUM_ITEMS\n};\n...\n#endif // !ENUM_ITEMS\n #define ENUM_ITEMS\n#define ENUM_ITEM(i) i\nenum myEnum\n{\n#include \"myCpp.cpp\"\n};\n#undef ENUM_ITEM\n static const char* myEnum[] =\n {\n#define ENUM_ITEM(i) #i\n#include \"myCpp.cpp\"\n// Include full file with defined ENUM_ITEMS => get enum items without code around\n };\n int max = sizeof(myEnum) / sizeof(char*);\n #define FOREACH_FRUIT(item) \\\n item(apple) \\\n item(orange) \\\n item(grape, 5) \\\n item(banana) \\\n class EnumClass\n{\n#define GENERATE_ENUM(ENUM, ...) ENUM,\n#define GENERATE_STRINGS(STRING, ...) { #STRING, ##__VA_ARGS__ },\n#define GENERATE_SIZE(...) + 1\npublic:\n enum Enum {\n FOREACH_FRUIT(GENERATE_ENUM) // apple, orange, grape, banana,\n } _;\n EnumClass(Enum init)\n {\n _ = init; // grape(2)\n _EnumItem build[itemsNo] = { FOREACH_FRUIT(GENERATE_STRINGS) }; // _EnumItem build[itemsNo] = { { \"apple\" }, { \"orange\" }, { \"grape\",5 }, { \"banana\" }, };\n int pos = 0;\n for (int i = 0; i < itemsNo; i++)\n {\n items[i].Name = build[i].Name;\n if (0 == build[i].No) {\n items[i].No = pos;\n for (int j = i; j--;)\n {\n if (items[j].No == pos)\n throw \"Existing item # !\";\n }\n pos++;\n }\n else {\n int destPos = build[i].No;\n if (destPos < pos) {\n for (int j = 0; j < i; j++)\n {\n if (items[j].No == destPos)\n throw \"Existing item # !\";\n }\n }\n items[i].No = destPos;\n pos = destPos + 1;\n }\n }\n }\n operator int()\n {\n return items[_].No;\n }\n operator char*()\n {\n return items[_].Name;\n }\n EnumClass& operator ++(int)\n {\n if (_ == itemsNo - 1) {\n throw \"Out of Enum options !\";\n }\n _ = static_cast<EnumClass::Enum>(_ + 1);\n return *this;\n }\n EnumClass& operator --(int)\n {\n if (0 == _) {\n throw \"Out of Enum options !\";\n }\n _ = static_cast<EnumClass::Enum>(_ - 1);\n return *this;\n }\n EnumClass operator =(int right)\n {\n for (int i = 0; i < itemsNo; i++)\n {\n if (items[i].No == right)\n {\n _ = static_cast<EnumClass::Enum>(i);\n return *this;\n }\n }\n throw \"Enum option does not exist !\";\n }\n EnumClass operator =(char *right)\n {\n for (int i = 0; i < itemsNo; i++)\n {\n if (!strcmp(items[i].Name, right))\n {\n _ = static_cast<EnumClass::Enum>(i);\n return *this;\n }\n }\n throw \"Enum option does not exist !\";\n }\nprotected:\n static const int itemsNo = FOREACH_FRUIT(GENERATE_SIZE); // + 1 + 1 + 1 + 1; \n struct _EnumItem {\n char *Name;\n int No;\n } items[itemsNo]; // { Name = \"apple\" No = 0 }, { Name = \"orange\" No = 1 } ,{ Name = \"grape\" No = 5 } ,{ Name = \"banana\" No = 6 }\n\n#undef GENERATE_ENUM\n#undef GENERATE_STRINGS\n#undef GENERATE_SIZE\n};\n int main()\n{\n EnumClass ec(EnumClass::grape);\n ec = \"banana\"; // ec {_=banana (3)...}\n ec--; // ec {_=grape (2)...}\n char *name = ec;\n int val = ec; // 5\n printf(\"%s(%i)\", name, val); // grape(5)\n return 0;\n}\n" }, { "answer_id": 69897469, "author": "shawn", "author_id": 8539544, "author_profile": "https://Stackoverflow.com/users/8539544", "pm_score": 1, "selected": false, "text": "// file: enum_with_string.h\n#pragma once\n\n#include <map>\n#include <string>\n#include <vector>\n\nnamespace EnumString {\n\ntemplate <typename T>\nstatic inline void split_string_for_each(const std::string &str,\n const std::string &delimiter,\n const T &foreach_function,\n ssize_t max_number = -1) {\n ssize_t num = 0;\n std::string::size_type start;\n std::string::size_type end = -1;\n while (true) {\n start = str.find_first_not_of(delimiter, end + 1);\n if (start == std::string::npos) break; // over\n\n end = str.find_first_of(delimiter, start + 1);\n\n if (end == std::string::npos) {\n foreach_function(num, str.substr(start));\n break;\n }\n foreach_function(num, str.substr(start, end - start));\n ++num;\n\n if (max_number > 0 && num == max_number) break;\n }\n}\n\n/**\n * Strip function, delete the specified characters on both sides of the string.\n */\ninline std::string &strip(std::string &s,\n const std::string &characters = \" \\t\\r\\n\") {\n s.erase(0, s.find_first_not_of(characters));\n return s.erase(s.find_last_not_of(characters) + 1);\n}\n\nstatic inline std::map<int, std::string> ParserEnumDefine(\n const std::string &define_str) {\n int cur_num = 0;\n std::string cur_item_str;\n std::map<int, std::string> result_map;\n split_string_for_each(define_str, \",\", [&](int num, const std::string &str) {\n split_string_for_each(\n str, \"=\",\n [&](int num, const std::string &str) {\n if (num == 0) cur_item_str = str;\n if (num == 1) cur_num = std::stoi(str);\n },\n 2);\n result_map.emplace(cur_num, strip(cur_item_str));\n cur_num++;\n });\n return result_map;\n}\n\n} // namespace EnumString\n\n/**\n * Example:\n * @code\n * @endcode\n */\n#define ENUM_WITH_STRING(Name, ...) \\\n enum class Name { __VA_ARGS__, __COUNT }; \\\n static inline const std::string &to_string(Name value) { \\\n static const auto map = EnumString::ParserEnumDefine(#__VA_ARGS__); \\\n static const std::string cannot_converted = \\\n \"Cannot be converted to string\"; \\\n int int_value = (int)value; \\\n if (map.count(int_value)) \\\n return map.at(int_value); \\\n else \\\n return cannot_converted; \\\n }\n #include <iostream>\n#include \"enum_with_string.h\"\nENUM_WITH_STRING(Animal, dog, cat, monkey = 50, fish, human = 100, duck)\nint main() {\n std::cout << to_string(Animal::dog) << std::endl;\n std::cout << to_string(Animal::cat) << std::endl;\n std::cout << to_string(Animal::monkey) << std::endl;\n std::cout << to_string(Animal::fish) << std::endl;\n std::cout << to_string(Animal::human) << std::endl;\n std::cout << to_string(Animal::duck) << std::endl;\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207976", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1737/" ]
207,981
<p>I came across PHP way of doing the trick:</p> <pre><code>my_bool reconnect = 1; mysql_options(&amp;mysql, MYSQL_OPT_RECONNECT, &amp;reconnect); </code></pre> <p>but no luck with MySQLdb (python-mysql).</p> <p>Can anybody please give a clue? Thanks.</p>
[ { "answer_id": 210096, "author": "Paul D. Eden", "author_id": 3045, "author_profile": "https://Stackoverflow.com/users/3045", "pm_score": 4, "selected": false, "text": " # Here is another sad story about bad transactional behavior. MySQL\n # offers a feature to automatically reconnect dropped connections.\n # What sounds like a dream, is actually a nightmare for anyone who\n # is dealing with transactions. When a reconnection happens, the\n # currently running transaction is transparently rolled back, and\n # everything that was being done is lost, without notice. Not only\n # that, but the connection may be put back in AUTOCOMMIT mode, even\n # when that's not the default MySQLdb behavior. The MySQL developers\n # quickly understood that this is a terrible idea, and removed the\n # behavior in MySQL 5.0.3. Unfortunately, Debian and Ubuntu still\n # have a patch right now which *reenables* that behavior by default\n # even past version 5.0.3.\n" }, { "answer_id": 210112, "author": "Paul D. Eden", "author_id": 3045, "author_profile": "https://Stackoverflow.com/users/3045", "pm_score": -1, "selected": false, "text": "import MySQLdb\n\nclass DB:\n conn = None\n\n def connect(self):\n self.conn = MySQLdb.connect()\n\n def cursor(self):\n try:\n return self.conn.cursor()\n except (AttributeError, MySQLdb.OperationalError):\n self.connect()\n return self.conn.cursor()\n\ndb = DB()\ncur = db.cursor()\n# wait a long time for the Mysql connection to timeout\ncur = db.cursor()\n# still works\n" }, { "answer_id": 982873, "author": "Garret Heaton", "author_id": 121515, "author_profile": "https://Stackoverflow.com/users/121515", "pm_score": 6, "selected": false, "text": "cursor.execute() MySQLdb.OperationalError conn.cursor() import MySQLdb\n\nclass DB:\n conn = None\n\n def connect(self):\n self.conn = MySQLdb.connect()\n\n def query(self, sql):\n try:\n cursor = self.conn.cursor()\n cursor.execute(sql)\n except (AttributeError, MySQLdb.OperationalError):\n self.connect()\n cursor = self.conn.cursor()\n cursor.execute(sql)\n return cursor\n\ndb = DB()\nsql = \"SELECT * FROM foo\"\ncur = db.query(sql)\n# wait a long time for the Mysql connection to timeout\ncur = db.query(sql)\n# still works\n" }, { "answer_id": 4101812, "author": "Pierre-Luc Bedard", "author_id": 497777, "author_profile": "https://Stackoverflow.com/users/497777", "pm_score": 2, "selected": false, "text": "class SqlManager(object):\n \"\"\"\n Class that handle the database operation\n \"\"\"\n def __init__(self,server, database, username, pswd):\n\n self.server = server\n self.dataBase = database\n self.userID = username\n self.password = pswd\n\ndef Close_Transation(self):\n \"\"\"\n Commit the SQL Query\n \"\"\"\n try:\n self.conn.commit()\n except Sql.Error, e:\n print \"-- reading SQL Error %d: %s\" % (e.args[0], e.args[1])\n\n def Close_db(self):\n try:\n self.conn.close()\n except Sql.Error, e:\n print \"-- reading SQL Error %d: %s\" % (e.args[0], e.args[1])\n\n def __del__(self):\n print \"close connection with database..\"\n self.conn.close() \n" }, { "answer_id": 29331237, "author": "joaquintopiso", "author_id": 4419857, "author_profile": "https://Stackoverflow.com/users/4419857", "pm_score": 5, "selected": false, "text": "ping(True) import MySQLdb\ncon=MySQLdb.Connect()\ncon.ping(True)\ncur=con.cursor()\n" }, { "answer_id": 51207712, "author": "Liviu Chircu", "author_id": 2054305, "author_profile": "https://Stackoverflow.com/users/2054305", "pm_score": 3, "selected": false, "text": "cursor.execute() MySQLdb #!/usr/bin/env python\n\nimport MySQLdb\n\nclass DisconnectSafeCursor(object):\n db = None\n cursor = None\n\n def __init__(self, db, cursor):\n self.db = db\n self.cursor = cursor\n\n def close(self):\n self.cursor.close()\n\n def execute(self, *args, **kwargs):\n try:\n return self.cursor.execute(*args, **kwargs)\n except MySQLdb.OperationalError:\n self.db.reconnect()\n self.cursor = self.db.cursor()\n return self.cursor.execute(*args, **kwargs)\n\n def fetchone(self):\n return self.cursor.fetchone()\n\n def fetchall(self):\n return self.cursor.fetchall()\n\nclass DisconnectSafeConnection(object):\n connect_args = None\n connect_kwargs = None\n conn = None\n\n def __init__(self, *args, **kwargs):\n self.connect_args = args\n self.connect_kwargs = kwargs\n self.reconnect()\n\n def reconnect(self):\n self.conn = MySQLdb.connect(*self.connect_args, **self.connect_kwargs)\n\n def cursor(self, *args, **kwargs):\n cur = self.conn.cursor(*args, **kwargs)\n return DisconnectSafeCursor(self, cur)\n\n def commit(self):\n self.conn.commit()\n\n def rollback(self):\n self.conn.rollback()\n\ndisconnectSafeConnect = DisconnectSafeConnection\n import mydb\n\ndb = mydb.disconnectSafeConnect()\n# ... use as a regular MySQLdb.connections.Connection object\n\ncursor = db.cursor()\n\n# no more \"2006: MySQL server has gone away\" exceptions now\ncursor.execute(\"SELECT * FROM foo WHERE bar=%s\", (\"baz\",))\n" }, { "answer_id": 62594893, "author": "Roose", "author_id": 13819043, "author_profile": "https://Stackoverflow.com/users/13819043", "pm_score": 0, "selected": false, "text": "def __getattr__(self, name):\n return getattr(self.cursor, name)\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/207981", "https://Stackoverflow.com", "https://Stackoverflow.com/users/140995/" ]
208,007
<p>In our administration team everyone has root passwords for all client servers. But what should we do if one of the team members is not longer working with us? He still has our passwords and we have to change them all, every time someone leave us. </p> <p>Now we are using ssh keys instead of passwords, but this is not helpful if we have to use something other than ssh.</p>
[ { "answer_id": 208011, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 5, "selected": false, "text": "* sudoers" }, { "answer_id": 208040, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 0, "selected": false, "text": "root passwd sudo passwd" }, { "answer_id": 31954977, "author": "sjas", "author_id": 805284, "author_profile": "https://Stackoverflow.com/users/805284", "pm_score": 0, "selected": false, "text": "authorized_keys bash clush" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28528/" ]
208,016
<p>Say I create an object thus:</p> <pre><code>var myObject = {"ircEvent": "PRIVMSG", "method": "newURI", "regex": "^http://.*"}; </code></pre> <p>What is the best way to retrieve a list of the property names? i.e. I would like to end up with some variable 'keys' such that:</p> <pre><code>keys == ["ircEvent", "method", "regex"] </code></pre>
[ { "answer_id": 208020, "author": "slashnick", "author_id": 21030, "author_profile": "https://Stackoverflow.com/users/21030", "pm_score": 11, "selected": true, "text": "var keys = Object.keys(myObject);\n var getKeys = function(obj){\n var keys = [];\n for(var key in obj){\n keys.push(key);\n }\n return keys;\n}\n var getKeys Object.prototype.keys .keys()" }, { "answer_id": 208439, "author": "Pablo Cabrera", "author_id": 12540, "author_profile": "https://Stackoverflow.com/users/12540", "pm_score": 8, "selected": false, "text": "for (var key in obj) {\n if (obj.hasOwnProperty(key)) {\n /* useful code here */\n }\n}\n" }, { "answer_id": 3821585, "author": "Sam Dutton", "author_id": 51593, "author_profile": "https://Stackoverflow.com/users/51593", "pm_score": 5, "selected": false, "text": "var o = {\"foo\": 1, \"bar\": 2}; \nalert(Object.keys(o));\n" }, { "answer_id": 3937321, "author": "Andy E", "author_id": 94197, "author_profile": "https://Stackoverflow.com/users/94197", "pm_score": 7, "selected": false, "text": "Object.keys() Object.keys = Object.keys || (function () {\n var hasOwnProperty = Object.prototype.hasOwnProperty,\n hasDontEnumBug = !{toString:null}.propertyIsEnumerable(\"toString\"),\n DontEnums = [ \n 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty',\n 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'\n ],\n DontEnumsLength = DontEnums.length;\n \n return function (o) {\n if (typeof o != \"object\" && typeof o != \"function\" || o === null)\n throw new TypeError(\"Object.keys called on a non-object\");\n \n var result = [];\n for (var name in o) {\n if (hasOwnProperty.call(o, name))\n result.push(name);\n }\n \n if (hasDontEnumBug) {\n for (var i = 0; i < DontEnumsLength; i++) {\n if (hasOwnProperty.call(o, DontEnums[i]))\n result.push(DontEnums[i]);\n } \n }\n \n return result;\n };\n})();\n Object.forIn()" }, { "answer_id": 9513536, "author": "zeacuss", "author_id": 312329, "author_profile": "https://Stackoverflow.com/users/312329", "pm_score": 3, "selected": false, "text": "this.getKeys = function() {\n\n var keys = new Array();\n for(var key in this) {\n\n if( typeof this[key] !== 'function') {\n\n keys.push(key);\n }\n }\n return keys;\n}\n" }, { "answer_id": 11472787, "author": "qwerty_jones", "author_id": 1523875, "author_profile": "https://Stackoverflow.com/users/1523875", "pm_score": 3, "selected": false, "text": "var myJSONObject = {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"}; \nvar keys=[];\nfor (var i in myJSONObject ) { keys.push(i); }\nalert(keys);\n" }, { "answer_id": 13580645, "author": "Rix Beck", "author_id": 1855940, "author_profile": "https://Stackoverflow.com/users/1855940", "pm_score": 3, "selected": false, "text": "[i for(i in obj)]\n" }, { "answer_id": 13870355, "author": "sbonami", "author_id": 1106878, "author_profile": "https://Stackoverflow.com/users/1106878", "pm_score": 4, "selected": false, "text": "var objectKeys = $.map(object, function(value, key) {\n return key;\n});\n" }, { "answer_id": 17198247, "author": "Kristofer Sommestad", "author_id": 572693, "author_profile": "https://Stackoverflow.com/users/572693", "pm_score": 3, "selected": false, "text": "if (!Object.keys) {\n Object.keys = (function () {\n var hasOwnProperty = Object.prototype.hasOwnProperty,\n hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),\n dontEnums = [\n 'toString',\n 'toLocaleString',\n 'valueOf',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'constructor'\n ],\n dontEnumsLength = dontEnums.length;\n\n return function (obj) {\n if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');\n\n var result = [];\n\n for (var prop in obj) {\n if (hasOwnProperty.call(obj, prop)) result.push(prop);\n }\n\n if (hasDontEnumBug) {\n for (var i=0; i < dontEnumsLength; i++) {\n if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);\n }\n }\n return result;\n };\n })();\n}\n extensions.js" }, { "answer_id": 29926934, "author": "Sydwell", "author_id": 344050, "author_profile": "https://Stackoverflow.com/users/344050", "pm_score": 3, "selected": false, "text": "var keys = Object.keys(myJSONObject);\n\nfor (var j=0; j < keys.length; j++) {\n Object[keys[j]].properties();\n}\n" }, { "answer_id": 31992102, "author": "schmijos", "author_id": 430418, "author_profile": "https://Stackoverflow.com/users/430418", "pm_score": 3, "selected": false, "text": "keys var obj = {name: 'gach', hello: 'world'};\nconsole.log(_.keys(obj));\n ['name', 'hello']\n" }, { "answer_id": 32413145, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 5, "selected": false, "text": "Object.getOwnPropertyNames(obj) Object.keys(obj) enumerable var o = Object.create({base:0})\nObject.defineProperty(o, 'yes', {enumerable: true})\nObject.defineProperty(o, 'not', {enumerable: false})\n\nconsole.log(Object.getOwnPropertyNames(o))\n// [ 'yes', 'not' ]\n\nconsole.log(Object.keys(o))\n// [ 'yes' ]\n\nfor (var x in o)\n console.log(x)\n// yes, base Object.getOwnPropertyNames Object.keys base for in" }, { "answer_id": 38816555, "author": "christian Nguyen", "author_id": 4225143, "author_profile": "https://Stackoverflow.com/users/4225143", "pm_score": 1, "selected": false, "text": "var getKeys = function(obj) {\n var type = typeof obj;\n var isObjectType = type === 'function' || type === 'object' || !!obj;\n\n // 1\n if(isObjectType) {\n return Object.keys(obj);\n }\n\n // 2\n var keys = [];\n for(var i in obj) {\n if(obj.hasOwnProperty(i)) {\n keys.push(i)\n }\n }\n if(keys.length) {\n return keys;\n }\n\n // 3 - bug for ie9 <\n var hasEnumbug = !{toString: null}.propertyIsEnumerable('toString');\n if(hasEnumbug) {\n var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',\n 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];\n\n var nonEnumIdx = nonEnumerableProps.length;\n\n while (nonEnumIdx--) {\n var prop = nonEnumerableProps[nonEnumIdx];\n if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n keys.push(prop);\n }\n }\n\n }\n\n return keys;\n};\n" }, { "answer_id": 52245137, "author": "sametcodes", "author_id": 8574166, "author_profile": "https://Stackoverflow.com/users/8574166", "pm_score": 3, "selected": false, "text": "Reflect.ownKeys() var obj = {a: 1, b: 2, c: 3};\nReflect.ownKeys(obj) // [\"a\", \"b\", \"c\"]\n var obj = {a: 1, b: 2, c: 3};\nobj[Symbol()] = 4;\nReflect.ownKeys(obj) // [\"a\", \"b\", \"c\", Symbol()]\n" }, { "answer_id": 64477537, "author": "Anh Hoang", "author_id": 2181111, "author_profile": "https://Stackoverflow.com/users/2181111", "pm_score": 3, "selected": false, "text": "let keys = Object.keys(myObject);\n let values = Object.keys(myObject).map(key => myObject[key]);\n" }, { "answer_id": 69744194, "author": "febaisi", "author_id": 1261206, "author_profile": "https://Stackoverflow.com/users/1261206", "pm_score": 2, "selected": false, "text": "mylittleJson = {\n \"one\": \"blah\",\n \"two\": {\n \"twoone\": \"\",\n \"twotwo\": \"\",\n \"twothree\": ['blah', 'blah']\n },\n \"three\": \"\"\n}\n .one\n.two.twoone\n.two.twotwo\n.two.twothree\n.three\n function listatts(parent, currentJson){\n var attList = []\n if (typeof currentJson !== 'object' || currentJson == undefined || currentJson.length > 0) {\n return\n }\n for(var attributename in currentJson){\n if (Object.prototype.hasOwnProperty.call(currentJson, attributename)) {\n childAtts = listatts(parent + \".\" + attributename, currentJson[attributename])\n if (childAtts != undefined && childAtts.length > 0)\n attList = [...attList, ...childAtts]\n else \n attList.push(parent + \".\" + attributename)\n }\n }\n return attList\n}\n\nmylittleJson = {\n \"one\": \"blah\",\n \"two\": {\n \"twoone\": \"\",\n \"twotwo\": \"\",\n \"twothree\": ['blah', 'blah']\n },\n \"three\": \"\"\n}\n\nconsole.log(listatts(\"\", mylittleJson));" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208016", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27929/" ]
208,017
<p>I've got simple java-based ppt->swf sub-project that basically works. The open source software out there, <a href="http://www.openoffice.org/" rel="nofollow noreferrer">OpenOffice.org</a> and <a href="http://www.artofsolving.com/opensource/jodconverter" rel="nofollow noreferrer">JODConverter</a> do the job great.</p> <p>The thing is, to do this I need to install OO.o and run it in server mode. And to do that I have to install OO.o, which is <em>allot</em> of software (~160MB) just to convert the source PPT files to an intermediate format. Also, the public OO.o distributions are platform specific and I'd really like a single, cross platform set of files. And, I'd like to not interfer with a system's current settings, like file extension associations. </p> <p>As things are now, my project is not particularly 'software distribution friendly'. </p> <p>So, the questions are:</p> <ul> <li>Is it possible to create a custom distribution of OpenOffice? How would one about this? </li> <li>How lightweight and unobtrusive can I make the installation?</li> <li>Would it be possible to have a truly cross platform distribution since there would be no OO.o UI? </li> <li>Are there any licensing issues I need to be aware of? (On my list of things to check out, but if you them already then TIA!) </li> </ul>
[ { "answer_id": 208020, "author": "slashnick", "author_id": 21030, "author_profile": "https://Stackoverflow.com/users/21030", "pm_score": 11, "selected": true, "text": "var keys = Object.keys(myObject);\n var getKeys = function(obj){\n var keys = [];\n for(var key in obj){\n keys.push(key);\n }\n return keys;\n}\n var getKeys Object.prototype.keys .keys()" }, { "answer_id": 208439, "author": "Pablo Cabrera", "author_id": 12540, "author_profile": "https://Stackoverflow.com/users/12540", "pm_score": 8, "selected": false, "text": "for (var key in obj) {\n if (obj.hasOwnProperty(key)) {\n /* useful code here */\n }\n}\n" }, { "answer_id": 3821585, "author": "Sam Dutton", "author_id": 51593, "author_profile": "https://Stackoverflow.com/users/51593", "pm_score": 5, "selected": false, "text": "var o = {\"foo\": 1, \"bar\": 2}; \nalert(Object.keys(o));\n" }, { "answer_id": 3937321, "author": "Andy E", "author_id": 94197, "author_profile": "https://Stackoverflow.com/users/94197", "pm_score": 7, "selected": false, "text": "Object.keys() Object.keys = Object.keys || (function () {\n var hasOwnProperty = Object.prototype.hasOwnProperty,\n hasDontEnumBug = !{toString:null}.propertyIsEnumerable(\"toString\"),\n DontEnums = [ \n 'toString', 'toLocaleString', 'valueOf', 'hasOwnProperty',\n 'isPrototypeOf', 'propertyIsEnumerable', 'constructor'\n ],\n DontEnumsLength = DontEnums.length;\n \n return function (o) {\n if (typeof o != \"object\" && typeof o != \"function\" || o === null)\n throw new TypeError(\"Object.keys called on a non-object\");\n \n var result = [];\n for (var name in o) {\n if (hasOwnProperty.call(o, name))\n result.push(name);\n }\n \n if (hasDontEnumBug) {\n for (var i = 0; i < DontEnumsLength; i++) {\n if (hasOwnProperty.call(o, DontEnums[i]))\n result.push(DontEnums[i]);\n } \n }\n \n return result;\n };\n})();\n Object.forIn()" }, { "answer_id": 9513536, "author": "zeacuss", "author_id": 312329, "author_profile": "https://Stackoverflow.com/users/312329", "pm_score": 3, "selected": false, "text": "this.getKeys = function() {\n\n var keys = new Array();\n for(var key in this) {\n\n if( typeof this[key] !== 'function') {\n\n keys.push(key);\n }\n }\n return keys;\n}\n" }, { "answer_id": 11472787, "author": "qwerty_jones", "author_id": 1523875, "author_profile": "https://Stackoverflow.com/users/1523875", "pm_score": 3, "selected": false, "text": "var myJSONObject = {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"}; \nvar keys=[];\nfor (var i in myJSONObject ) { keys.push(i); }\nalert(keys);\n" }, { "answer_id": 13580645, "author": "Rix Beck", "author_id": 1855940, "author_profile": "https://Stackoverflow.com/users/1855940", "pm_score": 3, "selected": false, "text": "[i for(i in obj)]\n" }, { "answer_id": 13870355, "author": "sbonami", "author_id": 1106878, "author_profile": "https://Stackoverflow.com/users/1106878", "pm_score": 4, "selected": false, "text": "var objectKeys = $.map(object, function(value, key) {\n return key;\n});\n" }, { "answer_id": 17198247, "author": "Kristofer Sommestad", "author_id": 572693, "author_profile": "https://Stackoverflow.com/users/572693", "pm_score": 3, "selected": false, "text": "if (!Object.keys) {\n Object.keys = (function () {\n var hasOwnProperty = Object.prototype.hasOwnProperty,\n hasDontEnumBug = !({toString: null}).propertyIsEnumerable('toString'),\n dontEnums = [\n 'toString',\n 'toLocaleString',\n 'valueOf',\n 'hasOwnProperty',\n 'isPrototypeOf',\n 'propertyIsEnumerable',\n 'constructor'\n ],\n dontEnumsLength = dontEnums.length;\n\n return function (obj) {\n if (typeof obj !== 'object' && typeof obj !== 'function' || obj === null) throw new TypeError('Object.keys called on non-object');\n\n var result = [];\n\n for (var prop in obj) {\n if (hasOwnProperty.call(obj, prop)) result.push(prop);\n }\n\n if (hasDontEnumBug) {\n for (var i=0; i < dontEnumsLength; i++) {\n if (hasOwnProperty.call(obj, dontEnums[i])) result.push(dontEnums[i]);\n }\n }\n return result;\n };\n })();\n}\n extensions.js" }, { "answer_id": 29926934, "author": "Sydwell", "author_id": 344050, "author_profile": "https://Stackoverflow.com/users/344050", "pm_score": 3, "selected": false, "text": "var keys = Object.keys(myJSONObject);\n\nfor (var j=0; j < keys.length; j++) {\n Object[keys[j]].properties();\n}\n" }, { "answer_id": 31992102, "author": "schmijos", "author_id": 430418, "author_profile": "https://Stackoverflow.com/users/430418", "pm_score": 3, "selected": false, "text": "keys var obj = {name: 'gach', hello: 'world'};\nconsole.log(_.keys(obj));\n ['name', 'hello']\n" }, { "answer_id": 32413145, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 5, "selected": false, "text": "Object.getOwnPropertyNames(obj) Object.keys(obj) enumerable var o = Object.create({base:0})\nObject.defineProperty(o, 'yes', {enumerable: true})\nObject.defineProperty(o, 'not', {enumerable: false})\n\nconsole.log(Object.getOwnPropertyNames(o))\n// [ 'yes', 'not' ]\n\nconsole.log(Object.keys(o))\n// [ 'yes' ]\n\nfor (var x in o)\n console.log(x)\n// yes, base Object.getOwnPropertyNames Object.keys base for in" }, { "answer_id": 38816555, "author": "christian Nguyen", "author_id": 4225143, "author_profile": "https://Stackoverflow.com/users/4225143", "pm_score": 1, "selected": false, "text": "var getKeys = function(obj) {\n var type = typeof obj;\n var isObjectType = type === 'function' || type === 'object' || !!obj;\n\n // 1\n if(isObjectType) {\n return Object.keys(obj);\n }\n\n // 2\n var keys = [];\n for(var i in obj) {\n if(obj.hasOwnProperty(i)) {\n keys.push(i)\n }\n }\n if(keys.length) {\n return keys;\n }\n\n // 3 - bug for ie9 <\n var hasEnumbug = !{toString: null}.propertyIsEnumerable('toString');\n if(hasEnumbug) {\n var nonEnumerableProps = ['valueOf', 'isPrototypeOf', 'toString',\n 'propertyIsEnumerable', 'hasOwnProperty', 'toLocaleString'];\n\n var nonEnumIdx = nonEnumerableProps.length;\n\n while (nonEnumIdx--) {\n var prop = nonEnumerableProps[nonEnumIdx];\n if (Object.prototype.hasOwnProperty.call(obj, prop)) {\n keys.push(prop);\n }\n }\n\n }\n\n return keys;\n};\n" }, { "answer_id": 52245137, "author": "sametcodes", "author_id": 8574166, "author_profile": "https://Stackoverflow.com/users/8574166", "pm_score": 3, "selected": false, "text": "Reflect.ownKeys() var obj = {a: 1, b: 2, c: 3};\nReflect.ownKeys(obj) // [\"a\", \"b\", \"c\"]\n var obj = {a: 1, b: 2, c: 3};\nobj[Symbol()] = 4;\nReflect.ownKeys(obj) // [\"a\", \"b\", \"c\", Symbol()]\n" }, { "answer_id": 64477537, "author": "Anh Hoang", "author_id": 2181111, "author_profile": "https://Stackoverflow.com/users/2181111", "pm_score": 3, "selected": false, "text": "let keys = Object.keys(myObject);\n let values = Object.keys(myObject).map(key => myObject[key]);\n" }, { "answer_id": 69744194, "author": "febaisi", "author_id": 1261206, "author_profile": "https://Stackoverflow.com/users/1261206", "pm_score": 2, "selected": false, "text": "mylittleJson = {\n \"one\": \"blah\",\n \"two\": {\n \"twoone\": \"\",\n \"twotwo\": \"\",\n \"twothree\": ['blah', 'blah']\n },\n \"three\": \"\"\n}\n .one\n.two.twoone\n.two.twotwo\n.two.twothree\n.three\n function listatts(parent, currentJson){\n var attList = []\n if (typeof currentJson !== 'object' || currentJson == undefined || currentJson.length > 0) {\n return\n }\n for(var attributename in currentJson){\n if (Object.prototype.hasOwnProperty.call(currentJson, attributename)) {\n childAtts = listatts(parent + \".\" + attributename, currentJson[attributename])\n if (childAtts != undefined && childAtts.length > 0)\n attList = [...attList, ...childAtts]\n else \n attList.push(parent + \".\" + attributename)\n }\n }\n return attList\n}\n\nmylittleJson = {\n \"one\": \"blah\",\n \"two\": {\n \"twoone\": \"\",\n \"twotwo\": \"\",\n \"twothree\": ['blah', 'blah']\n },\n \"three\": \"\"\n}\n\nconsole.log(listatts(\"\", mylittleJson));" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208017", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2961/" ]
208,018
<p>I need to export multiple data tables to Excel on the clients machine, each to their own sheet. If it was just one sheet, I'd use the Excel/csv content type, but I've heard something about an XML format that can represent an entire workbook. I don't want to go down the Packaging and .xlsx route, so I need standard .xls.</p> <p>Our bug tracker, Gemini, used to have an export function that produced an XML file that Excel automatically opened as a multi-sheet workbook, but I can't find it. Is there still such a mechanism, and where can I find that schema?</p>
[ { "answer_id": 665594, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": " private static string getWorkbookTemplate()\n {\n var sb = new StringBuilder(818);\n sb.AppendFormat(@\"<?xml version=\"\"1.0\"\"?>{0}\", Environment.NewLine);\n sb.AppendFormat(@\"<?mso-application progid=\"\"Excel.Sheet\"\"?>{0}\", Environment.NewLine);\n sb.AppendFormat(@\"<Workbook xmlns=\"\"urn:schemas-microsoft-com:office:spreadsheet\"\"{0}\", Environment.NewLine);\n sb.AppendFormat(@\" xmlns:o=\"\"urn:schemas-microsoft-com:office:office\"\"{0}\", Environment.NewLine);\n sb.AppendFormat(@\" xmlns:x=\"\"urn:schemas-microsoft-com:office:excel\"\"{0}\", Environment.NewLine);\n sb.AppendFormat(@\" xmlns:ss=\"\"urn:schemas-microsoft-com:office:spreadsheet\"\"{0}\", Environment.NewLine);\n sb.AppendFormat(@\" xmlns:html=\"\"http://www.w3.org/TR/REC-html40\"\">{0}\", Environment.NewLine);\n sb.AppendFormat(@\" <Styles>{0}\", Environment.NewLine);\n sb.AppendFormat(@\" <Style ss:ID=\"\"Default\"\" ss:Name=\"\"Normal\"\">{0}\", Environment.NewLine);\n sb.AppendFormat(@\" <Alignment ss:Vertical=\"\"Bottom\"\"/>{0}\", Environment.NewLine);\n sb.AppendFormat(@\" <Borders/>{0}\", Environment.NewLine);\n sb.AppendFormat(@\" <Font ss:FontName=\"\"Calibri\"\" x:Family=\"\"Swiss\"\" ss:Size=\"\"11\"\" ss:Color=\"\"#000000\"\"/>{0}\", Environment.NewLine);\n sb.AppendFormat(@\" <Interior/>{0}\", Environment.NewLine);\n sb.AppendFormat(@\" <NumberFormat/>{0}\", Environment.NewLine);\n sb.AppendFormat(@\" <Protection/>{0}\", Environment.NewLine);\n sb.AppendFormat(@\" </Style>{0}\", Environment.NewLine);\n sb.AppendFormat(@\" <Style ss:ID=\"\"s62\"\">{0}\", Environment.NewLine);\n sb.AppendFormat(@\" <Font ss:FontName=\"\"Calibri\"\" x:Family=\"\"Swiss\"\" ss:Size=\"\"11\"\" ss:Color=\"\"#000000\"\"{0}\", Environment.NewLine);\n sb.AppendFormat(@\" ss:Bold=\"\"1\"\"/>{0}\", Environment.NewLine);\n sb.AppendFormat(@\" </Style>{0}\", Environment.NewLine);\n sb.AppendFormat(@\" <Style ss:ID=\"\"s63\"\">{0}\", Environment.NewLine);\n sb.AppendFormat(@\" <NumberFormat ss:Format=\"\"Short Date\"\"/>{0}\", Environment.NewLine);\n sb.AppendFormat(@\" </Style>{0}\", Environment.NewLine);\n sb.AppendFormat(@\" </Styles>{0}\", Environment.NewLine);\n sb.Append(@\"{0}\\r\\n</Workbook>\");\n return sb.ToString();\n }\n\n private static string replaceXmlChar(string input)\n {\n input = input.Replace(\"&\", \"&amp\");\n input = input.Replace(\"<\", \"&lt;\");\n input = input.Replace(\">\", \"&gt;\");\n input = input.Replace(\"\\\"\", \"&quot;\");\n input = input.Replace(\"'\", \"&apos;\");\n return input;\n }\n\n private static string getCell(Type type, object cellData)\n {\n var data = (cellData is DBNull) ? \"\" : cellData;\n if (type.Name.Contains(\"Int\") || type.Name.Contains(\"Double\") || type.Name.Contains(\"Decimal\")) return string.Format(\"<Cell><Data ss:Type=\\\"Number\\\">{0}</Data></Cell>\", data);\n if (type.Name.Contains(\"Date\") && data.ToString() != string.Empty)\n {\n return string.Format(\"<Cell ss:StyleID=\\\"s63\\\"><Data ss:Type=\\\"DateTime\\\">{0}</Data></Cell>\", Convert.ToDateTime(data).ToString(\"yyyy-MM-dd\"));\n }\n return string.Format(\"<Cell><Data ss:Type=\\\"String\\\">{0}</Data></Cell>\", replaceXmlChar(data.ToString()));\n }\n private static string getWorksheets(DataSet source)\n {\n var sw = new StringWriter();\n if (source == null || source.Tables.Count == 0)\n {\n sw.Write(\"<Worksheet ss:Name=\\\"Sheet1\\\">\\r\\n<Table>\\r\\n<Row><Cell><Data ss:Type=\\\"String\\\"></Data></Cell></Row>\\r\\n</Table>\\r\\n</Worksheet>\");\n return sw.ToString();\n }\n foreach (DataTable dt in source.Tables)\n {\n if (dt.Rows.Count == 0)\n sw.Write(\"<Worksheet ss:Name=\\\"\" + replaceXmlChar(dt.TableName) + \"\\\">\\r\\n<Table>\\r\\n<Row><Cell ss:StyleID=\\\"s62\\\"><Data ss:Type=\\\"String\\\"></Data></Cell></Row>\\r\\n</Table>\\r\\n</Worksheet>\");\n else\n {\n //write each row data \n var sheetCount = 0;\n for (int i = 0; i < dt.Rows.Count; i++)\n {\n if ((i % rowLimit) == 0)\n {\n //add close tags for previous sheet of the same data table\n if ((i / rowLimit) > sheetCount)\n {\n sw.Write(\"\\r\\n</Table>\\r\\n</Worksheet>\");\n sheetCount = (i / rowLimit);\n }\n sw.Write(\"\\r\\n<Worksheet ss:Name=\\\"\" + replaceXmlChar(dt.TableName) +\n (((i / rowLimit) == 0) ? \"\" : Convert.ToString(i / rowLimit)) + \"\\\">\\r\\n<Table>\");\n //write column name row\n sw.Write(\"\\r\\n<Row>\");\n foreach (DataColumn dc in dt.Columns)\n sw.Write(string.Format(\"<Cell ss:StyleID=\\\"s62\\\"><Data ss:Type=\\\"String\\\">{0}</Data></Cell>\", replaceXmlChar(dc.ColumnName)));\n sw.Write(\"</Row>\");\n }\n sw.Write(\"\\r\\n<Row>\");\n foreach (DataColumn dc in dt.Columns)\n sw.Write(getCell(dc.DataType, dt.Rows[i][dc.ColumnName]));\n sw.Write(\"</Row>\");\n }\n sw.Write(\"\\r\\n</Table>\\r\\n</Worksheet>\");\n }\n }\n\n return sw.ToString();\n }\n public static string GetExcelXml(DataTable dtInput, string filename)\n {\n var excelTemplate = getWorkbookTemplate();\n var ds = new DataSet();\n ds.Tables.Add(dtInput.Copy());\n var worksheets = getWorksheets(ds);\n var excelXml = string.Format(excelTemplate, worksheets);\n return excelXml;\n }\n\n public static string GetExcelXml(DataSet dsInput, string filename)\n {\n var excelTemplate = getWorkbookTemplate();\n var worksheets = getWorksheets(dsInput);\n var excelXml = string.Format(excelTemplate, worksheets);\n return excelXml;\n }\n\n public static void ToExcel(DataSet dsInput, string filename, HttpResponse response)\n {\n var excelXml = GetExcelXml(dsInput, filename);\n response.Clear();\n response.AppendHeader(\"Content-Type\", \"application/vnd.ms-excel\");\n response.AppendHeader(\"Content-disposition\", \"attachment; filename=\" + filename);\n response.Write(excelXml);\n response.Flush();\n response.End();\n }\n\n public static void ToExcel(DataTable dtInput, string filename, HttpResponse response)\n {\n var ds = new DataSet();\n ds.Tables.Add(dtInput.Copy());\n ToExcel(ds, filename, response);\n }\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208018", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
208,027
<p>and can it be configured not to happen?</p> <p>I'm usually finding myself saving a result of a query as a .csv and processing it later on my Unix machine. The characters being null separated makes me have to filter those chars and is a bit of a pain.</p> <p>So, these are the questions:</p> <ul> <li>Why is this so?</li> </ul> <p>EDIT:</p> <p>Because it outputs in UTF-16 by default. Easiest conversion would then be: </p> <pre><code>iconv -f utf-16 -t utf-8 origFile.csv &gt; newFile.csv </code></pre> <ul> <li>Can it be disabled somehow? How?</li> </ul> <p>Here's a piece of a hexdump of a file thus generated. Each char is followed by a null char (00):</p> <pre><code>00000cf0 36 00 36 00 32 00 0d 00 0a 00 36 00 38 00 34 00 |6.6.2.....6.8.4.| 00000d00 30 00 36 00 32 00 31 00 36 00 0d 00 0a 00 36 00 |0.6.2.1.6.....6.| 00000d10 38 00 34 00 30 00 36 00 33 00 36 00 34 00 0d 00 |8.4.0.6.3.6.4...| 00000d20 0a 00 36 00 38 00 34 00 30 00 36 00 38 00 34 00 |..6.8.4.0.6.8.4.| 00000d30 32 00 0d 00 0a 00 36 00 38 00 34 00 30 00 37 00 |2.....6.8.4.0.7.| 00000d40 30 00 32 00 31 00 0d 00 0a 00 36 00 38 00 34 00 |0.2.1.....6.8.4.| 00000d50 30 00 37 00 37 00 39 00 37 00 0d 00 0a 00 36 00 |0.7.7.9.7.....6.| 00000d60 38 00 34 00 30 00 37 00 39 00 32 00 31 00 0d 00 |8.4.0.7.9.2.1...| 00000d70 0a 00 36 00 38 00 34 00 30 00 38 00 32 00 34 00 |..6.8.4.0.8.2.4.| 00000d80 31 00 0d 00 0a 00 36 00 38 00 34 00 30 00 38 00 |1.....6.8.4.0.8.| 00000d90 36 00 36 00 31 00 0d 00 0a 00 36 00 38 00 34 00 |6.6.1.....6.8.4.| 00000da0 30 00 38 00 37 00 35 00 31 00 0d 00 0a 00 36 00 |0.8.7.5.1.....6.| 00000db0 38 00 34 00 31 00 30 00 32 00 35 00 34 00 0d 00 |8.4.1.0.2.5.4...| 00000dc0 0a 00 36 00 38 00 34 00 31 00 30 00 34 00 34 00 |..6.8.4.1.0.4.4.| </code></pre>
[ { "answer_id": 208037, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "iconv -futf-16le -tutf-8" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208027", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5190/" ]
208,038
<p>I'm looking for a way to selectively apply a CSS class to individual rows in a <code>GridView</code> based upon a property of the data bound item.</p> <p>e.g.:</p> <p>GridView's data source is a generic list of <code>SummaryItems</code> and <code>SummaryItem</code> has a property <code>ShouldHighlight</code>. When <code>ShouldHighlight == true</code> the CSS for the associated row should be set to <code>highlighted</code></p> <p>any ideas?</p>
[ { "answer_id": 208067, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 6, "selected": true, "text": "protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n if (e.Row.RowType == DataControlRowType.DataRow)\n {\n DataRowView drv = e.Row.DataItem as DataRowView;\n if (drv[\"ShouldHighlight\"].ToString().ToLower() == \"true\")\n e.Row.CssClass = \"highlighted\";\n }\n}\n protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n{\n if (e.Row.RowType == DataControlRowType.DataRow)\n {\n myClass drv = (myClass)e.Row.DataItem;\n if (drv.ShouldHighlight)\n e.Row.CssClass = \"highlighted\";\n }\n}\n public class myClass\n{ \n public Boolean ShouldHighlight\n { get; set; }\n}\n e.Row.dataItem\n" }, { "answer_id": 315284, "author": "TheZenker", "author_id": 10552, "author_profile": "https://Stackoverflow.com/users/10552", "pm_score": 3, "selected": false, "text": "gvGrid.AlternatingRowStyle.CssClass = ALTROW_CSSCLASS\ngvGrid.RowStyle.CssClass = ROW_CSSCLASS\n If(item.ShouldHighlight)\n {\n If(e.Row.RowState == DataControlRowState.Alternate)\n {\n e.Row.CssClass = String.Format(\"{0} {1}\", \"highlight\", ALTROW_CSSCLASS)\n }\n else\n {\n e.Row.CssClass = String.Format(\"{0} {1}\", \"highlight\", ROW_CSSCLASS)\n }\n\n\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3599/" ]
208,046
<p>I'm pretty new to regular expressions. I have a requirement to replace spaces in a piece of multi-line text. The replacement rules are these:</p> <ul> <li>Replace all spaces at start-of-line with a non-breaking space (<code>&amp;nbsp;</code>).</li> <li>Replace any instance of repeated spaces (more than one space together) with the same number of non-breaking-spaces.</li> <li>Single spaces which are not at start-of-line remain untouched.</li> </ul> <p>I used the <a href="http://www.weitz.de/regex-coach/" rel="nofollow noreferrer">Regex Coach</a> to build the matching pattern:</p> <pre><code>/( ){2,}|^( )/ </code></pre> <p>Let's assume I have this input text:</p> <pre><code>asdasd asdasd asdas1 asda234 4545 54 34545 345 34534 34 345 </code></pre> <p>Using a PHP regular expression replace function (like <a href="http://ch.php.net/manual/en/function.preg-replace.php" rel="nofollow noreferrer"><code>preg_replace()</code></a>), I want to get this output:</p> <pre><code>asdasd asdasd&amp;amp;nbsp;&amp;amp;nbsp;asdas1 &amp;amp;nbsp;asda234 4545&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;&amp;amp;nbsp;54 &amp;amp;nbsp;&amp;amp;nbsp;34545 345&amp;amp;nbsp;&amp;amp;nbsp;34534 34 345 </code></pre> <p>I'm happy doing simple text substitutions using regular expressions, but I'm having trouble working out how to replace multiple-times inside the match in order to get the output I desire.</p>
[ { "answer_id": 208076, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 4, "selected": true, "text": "\\x20 \\s $str = \"asdasd asdasd asdas1\\n asda234 4545 54\\n 34545 345 34534\\n34 345\\n\";\n\nprint preg_replace(\"/(?<=\\s)\\x20|\\x20(?=\\s)/\", \"&#160;\", $str);\n asdasd asdasd&#160;&#160;asdas1\n&#160;asda234 4545&#160;&#160;&#160;&#160;54\n&#160;&#160;34545 345&#160;&#160;34534\n34 345\n \"\\n \" => \"\\n&nbsp;\"" }, { "answer_id": 208079, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "/e $str = preg_replace('/( {2,}|^ )/em', 'str_repeat(\"&nbsp;\", strlen(\"\\1\"))', $str);\n /m ^" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208046", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17981/" ]
208,051
<p>Is there a way to consume a web service using JavaScript? I'm Looking for a built-in way to do it, using a JavaScript framework is not an option. </p>
[ { "answer_id": 208182, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 0, "selected": false, "text": "// javascript global variables\nvar soapHeader = '<?xml version=\\\"1.0\\\"?>'\n + '<SOAP-ENV:Envelope xmlns:SOAP-ENV=\\\"http://schemas.xmlsoap.org/soap/envelope/\\\"'\n + ' SOAP-ENV:encodingStyle=\\\"http://schemas.xmlsoap.org/soap/encoding/\\\"'\n + ' xmlns:xsi=\\\"http://www.w3.org/1999/XMLSchema-instance\\\"'\n + ' xmlns:xsd=\\\"http://www.w3.org/1999/XMLSchema\\\"'\n + '>'\n + '<SOAP-ENV:Header/>'\n + '<SOAP-ENV:Body>';\n\nvar soapFooter = '</SOAP-ENV:Body>'\n + '</SOAP-ENV:Envelope>';\n\nvar destinationURI = '/webservices/websalm';\n\nvar actionURI = '';\n\nfunction callWebService(nsCallback,ieCallback,parms) {\n try\n {\n // Create XmlHttpRequest obj for current browser = Netscape or IE\n if (navigator.userAgent.indexOf('Netscape') != -1)\n {\n SOAPObject = new XMLHttpRequest();\n SOAPObject.onload = nsCallback;\n } else { //IE\n SOAPObject = new ActiveXObject('Microsoft.XMLHTTP');\n SOAPObject.onreadystatechange = ieCallback;\n }\n\n SOAPObject.open('POST', destinationURI, true);\n\n // Set 2 Request headers, based on browser\n if (actionURI == '') {\n SOAPObject.setRequestHeader('SOAPAction', '\\\"\\\"');\n } else { SOAPObject.setRequestHeader('SOAPAction', actionURI);\n }\n\n SOAPObject.setRequestHeader('Content-Type', 'text/xml');\n\n // Compose the Request body from input parameter + global variables\n var requestBody = soapHeader + parms + soapFooter\n\n // Send, based on browser\n if (navigator.userAgent.indexOf('Netscape') != -1)\n {\n SOAPObject.send(new DOMParser().parseFromString(requestBody,'text/xml'));\n } else {\n SOAPObject.send(requestBody);\n }\n } catch (E)\n {\n alert('callWebService exception: ' + E);\n }\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208051", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15152/" ]
208,063
<p>I want to develop a website in ASP classic that uses HTTP Authentication against a database or password list that is under the control of the script. Ideally, the solution should involve no components or IIS settings as the script should be runnable in a hosted environment.</p> <p>Any clues/code deeply appreciated.</p>
[ { "answer_id": 208195, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Dim DatabaseObject1\nSet DatabaseObject1 = Server.CreateObject(\"ADODB.Connection\")\nDatabaseObject1.Open(\"DSN=DSNname;\")\n" }, { "answer_id": 208223, "author": "brianb", "author_id": 27892, "author_profile": "https://Stackoverflow.com/users/27892", "pm_score": 2, "selected": false, "text": " WWW-Authenticate: Basic realm=\"SomethingGoesHere\"\n Authorization: Basic YnJpYW5iOmJvYmJ5Ym95\n brianb:bobbyboy\n" }, { "answer_id": 1726629, "author": "lambacck", "author_id": 108518, "author_profile": "https://Stackoverflow.com/users/108518", "pm_score": 5, "selected": true, "text": "<%@LANGUAGE=\"VBSCRIPT\"%>\n\n<!--#include file=\"decbase64.asp\" -->\n\n<%\nSub Unauth()\n Call Response.AddHeader(\"WWW-Authenticate\", \"Basic realm=\"\"SomethingGoesHere\"\"\")\n Response.Status = \"401 Unauthorized\"\n Call Response.End()\nEnd Sub\n\nDim strAuth\nstrAuth = Request.ServerVariables(\"HTTP_AUTHORIZATION\")\n\nIf IsNull(strAuth) Or IsEmpty(strAuth) Or strAuth = \"\" Then\n Call Unauth\nElse \n %>\n <html>\n <body>\n <% \n Dim aParts, aCredentials, strType, strBase64, strPlain, strUser, strPassword\n aParts = Split(strAuth, \" \")\n If aParts(0) <> \"Basic\" Then\n Call Unauth\n End If\n strPlain = Base64Decode(aParts(1))\n aCredentials = Split(strPlain, \":\")\n %>\n <%= Server.HTMLEncode(aCredentials(0) & \" - \" & aCredentials(1)) %>\n </body>\n </html>\n <%\nEnd If\n%>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24461/" ]
208,074
<p>I need to search all cpp/h files in svn working copy for "foo", excluding svn's special folders completely. What is the <strong>exact</strong> command for GNU grep?</p>
[ { "answer_id": 208135, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "svn ls -R | xargs -d '\\n' grep <string-to-search-for>\n" }, { "answer_id": 1369762, "author": "Ether", "author_id": 40468, "author_profile": "https://Stackoverflow.com/users/40468", "pm_score": 1, "selected": false, "text": "vim s () {\n local PATTERN=$1\n local COLOR=$2\n shift; shift;\n local MOREFLAGS=$*\n\n if ! test -n \"$COLOR\" ; then\n # is stdout connected to terminal?\n if test -t 1; then\n COLOR=always\n else\n COLOR=none\n fi\n fi\n\n find -L . \\\n -not \\( -name .svn -a -prune \\) \\\n -not \\( -name templates_c -a -prune \\) \\\n -not \\( -name log -a -prune \\) \\\n -not \\( -name logs -a -prune \\) \\\n -type f \\\n -not -name \\*.swp \\\n -not -name \\*.swo \\\n -not -name \\*.obj \\\n -not -name \\*.map \\\n -not -name access.log \\\n -not -name \\*.gif \\\n -not -name \\*.jpg \\\n -not -name \\*.png \\\n -not -name \\*.sql \\\n -not -name \\*.js \\\n -exec grep -iIHn -E --color=${COLOR} ${MOREFLAGS} -e \"${PATTERN}\" \\{\\} \\;\n}\n\n# s foo | less\nsl () {\n local PATTERN=$*\n s \"$PATTERN\" always | less\n}\n\n# like s but only lists the files that match\nsmatch () {\n local PATTERN=$1\n s $PATTERN always -l\n}\n\n# recursive search (filenames) - find file\nf () {\n find -L . -not \\( -name .svn -a -prune \\) \\( -type f -or -type d \\) -name \"$1\"\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20310/" ]
208,077
<p>If i can use</p> <pre><code>&lt;td&gt;&lt;textarea&gt;&lt;bean:write name="smlMoverDetailForm" property="empFDJoiningDate"/&gt; &lt;/textarea&gt;&lt;/td&gt; </code></pre> <p>to displace a value how can i use the struts tags to save a vaiable to the sesssion </p> <p>in sudo code</p> <pre><code>session.setAttribute("test" , "&lt;bean:write name="smlMoverDetailForm" property="empFDJoiningDate"/&gt;"); </code></pre> <p>is this possible?</p>
[ { "answer_id": 271570, "author": "Fred", "author_id": 33630, "author_profile": "https://Stackoverflow.com/users/33630", "pm_score": 1, "selected": false, "text": "session.setAttribute(\"test\",((THECLASSOFTHEBEAN)request.getAttribute(\"smlMoverDetailForm\")).getEmpFDJoiningDate());\n session.setAttribute(\"test\",((THECLASSOFTHEBEAN)request.getSession().getAttribute(\"smlMoverDetailForm\")).getEmpFDJoiningDate());\n" }, { "answer_id": 12176297, "author": "Sal", "author_id": 818060, "author_profile": "https://Stackoverflow.com/users/818060", "pm_score": 0, "selected": false, "text": "struts-config.xml" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208077", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
208,084
<p>In Visual Studio 2008 (and others) when creating a .NET or silverlight application if you look at your project properties, it seems like you can only have one assembly name - across all configurations. I would like to compile my application as:</p> <p>MyAppDebug - in debug mode and just MyApp - in release mode</p> <p>Does anyone know if this is possible?</p> <p><strong>Edit:</strong></p> <p>It seems some people are questioning the reasoning behind the question, so I'll explain a little further:</p> <p>I'm working on a Silverlight application which gets automatically uploaded to our test site when I to a "build solution". The trouble is, the test team are now testing the online version, whilst I work on a new one. So, I want to have a url like .\MyApp.html for the regular version that the QA team will test and then .\MyApp.html?version=debug for the current version that I'm working on.</p>
[ { "answer_id": 208158, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 2, "selected": false, "text": "#if DEBUG\n[assembly: AssemblyTitle(\"MyAssemblyDebug\")]\n#else\n[assembly: AssemblyTitle(\"MyAssembly\")]\n#endif\n" }, { "answer_id": 208354, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 2, "selected": true, "text": "if \"$(ConfigurationName)\"==\"Debug\" goto debug\n\"$(SolutionDir)ftp.bat\" \"$(TargetDir)$(TargetName).xap\"\n:debug\n\"$(SolutionDir)ftp.bat\" \"$(TargetDir)$(TargetName).xap\" \"$(TargetDir)$(TargetName)Debug.xap\"\n" }, { "answer_id": 2576142, "author": "Roman Starkov", "author_id": 33080, "author_profile": "https://Stackoverflow.com/users/33080", "pm_score": 4, "selected": false, "text": "<AssemblyName>MyApp</AssemblyName>\n<AssemblyName Condition=\" '$(Configuration)' == 'Debug' \">MyAppDebug</AssemblyName>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208084", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
208,085
<pre><code>Apache/2.2.6 (Unix) DAV/2 mod_python/3.2.8 Python/2.4.4 configured ... </code></pre> <p>One of apache processes spawns some long-running python script asynchronously, and apparently doesn't seem to collect its child process table entry. After that long-run-in-subprocess python script finishes - defunct python process has been left.</p> <pre><code># ps -ef | grep httpd root 23911 1 0 Oct15 ? 00:00:01 /usr/sbin/httpd ... qa 23920 23911 0 Oct15 ? 00:00:00 /usr/sbin/httpd # ps -ef | grep python ... qa 28449 23920 0 12:38 ? 00:00:00 [python] &lt;defunct&gt; </code></pre> <p>What is the way to make the Apache process to collect its children? Is it possible to do the job via a mod_python request handler ( like PythonCleanupHandler for example)?</p> <p>Thanks.</p>
[ { "answer_id": 208158, "author": "Josh", "author_id": 11702, "author_profile": "https://Stackoverflow.com/users/11702", "pm_score": 2, "selected": false, "text": "#if DEBUG\n[assembly: AssemblyTitle(\"MyAssemblyDebug\")]\n#else\n[assembly: AssemblyTitle(\"MyAssembly\")]\n#endif\n" }, { "answer_id": 208354, "author": "Mark Ingram", "author_id": 986, "author_profile": "https://Stackoverflow.com/users/986", "pm_score": 2, "selected": true, "text": "if \"$(ConfigurationName)\"==\"Debug\" goto debug\n\"$(SolutionDir)ftp.bat\" \"$(TargetDir)$(TargetName).xap\"\n:debug\n\"$(SolutionDir)ftp.bat\" \"$(TargetDir)$(TargetName).xap\" \"$(TargetDir)$(TargetName)Debug.xap\"\n" }, { "answer_id": 2576142, "author": "Roman Starkov", "author_id": 33080, "author_profile": "https://Stackoverflow.com/users/33080", "pm_score": 4, "selected": false, "text": "<AssemblyName>MyApp</AssemblyName>\n<AssemblyName Condition=\" '$(Configuration)' == 'Debug' \">MyAppDebug</AssemblyName>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/140995/" ]
208,089
<p>I am using Spring Forms for my web application. For nested properties, the form tag generates the input elements having id / name in form of .</p> <p>For example, Person is the command class and Address is contained into its address field then the city element would be,</p> <pre><code>&lt;input type="text" id="address**.**city" name="address**.**city" /&gt; </code></pre> <p>now, the problem is whenever I try to get its value using jQuery,</p> <pre><code>$("#address.city").val(); </code></pre> <p>jQuery fails to select any appropriate element !</p> <p>Please let me know any solution.</p> <p>Thanks in advance.</p>
[ { "answer_id": 208116, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 5, "selected": true, "text": "$(\"#address\\\\.city\").val();\n \\ #foo\\\\:bar\n#foo\\\\[bar\\\\]\n#foo\\\\.bar\n" }, { "answer_id": 389599, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 3, "selected": false, "text": "$('[id=\"address.city\"]') \n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208089", "https://Stackoverflow.com", "https://Stackoverflow.com/users/959/" ]
208,098
<p>We have an application on Linux that used the <a href="http://linux.die.net/man/3/syslog" rel="noreferrer">syslog</a> mechanism. After a week spent trying to figure out why this application was running slower than expected, we discovered that if we eliminated syslog, and just wrote directly to a log file, performance improved dramatically.</p> <p>I understand why syslog is slower than direct file writes. But I was wondering: Are there ways to configure syslog to optimize its performance?</p>
[ { "answer_id": 208109, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 1, "selected": false, "text": "LD_PRELOAD stderr /dev/log syslogd" }, { "answer_id": 208276, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 2, "selected": false, "text": "use Sys::Syslog;\n# Start system logging\n# setlogmask controls what levels we're going to let get through. If we mask\n# them off here, then the syslog daemon doesn't need to be concerned by them\n# 1 = emerg\n# 2 = alert\n# 4 = crit\n# 8 = err\n# 16 = warning\n# 32 = notice\n# 64 = info\n# 128 = debug\nSys::Syslog::setlogsock('unix');\nopenlog($myname,'pid,cons,nowait','mail');\nsetlogmask(127); # allow everything but debug\n#setlogmask(255); # everything\nsyslog('debug',\"syslog opened\");\n" }, { "answer_id": 299720, "author": "Phillip Whelan", "author_id": 25305, "author_profile": "https://Stackoverflow.com/users/25305", "pm_score": 3, "selected": false, "text": " int LogMask = LOG_UPTO(LOG_WARNING);\n #define syslog(a, ...) if ((a) & LogMask ) syslog((a), __VA_ARGS__)\n\n int main(int argc, char **argv)\n {\n LogMask = setlogmask(LOG_UPTO(LOG_WARNING));\n ...\n }\n setlogmask(LOG_UPTO(LOG_LEVEL))\n *.err /var/log/messages\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208098", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1175/" ]
208,105
<p>Given an object:</p> <pre><code>let myObject = { &quot;ircEvent&quot;: &quot;PRIVMSG&quot;, &quot;method&quot;: &quot;newURI&quot;, &quot;regex&quot;: &quot;^http://.*&quot; }; </code></pre> <p>How do I remove the property <code>regex</code> to end up with the following <code>myObject</code>?</p> <pre><code>let myObject = { &quot;ircEvent&quot;: &quot;PRIVMSG&quot;, &quot;method&quot;: &quot;newURI&quot; }; </code></pre>
[ { "answer_id": 208106, "author": "nickf", "author_id": 9021, "author_profile": "https://Stackoverflow.com/users/9021", "pm_score": 14, "selected": true, "text": "delete myObject.regex;\n// or,\ndelete myObject['regex'];\n// or,\nvar prop = \"regex\";\ndelete myObject[prop];\n var myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};\ndelete myObject.regex;\n\nconsole.log(myObject); delete let myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};\n\n// assign the key regex to the variable _ indicating it will be unused\nconst {regex: _, ...newObj} = myObject;\n\nconsole.log(newObj); // has no 'regex' key\nconsole.log(myObject); // remains unchanged" }, { "answer_id": 208117, "author": "redsquare", "author_id": 6440, "author_profile": "https://Stackoverflow.com/users/6440", "pm_score": 8, "selected": false, "text": "var myObject = {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"};\n \ndelete myObject.regex;\n\nconsole.log ( myObject.regex); // logs: undefined" }, { "answer_id": 12469043, "author": "Braden Best", "author_id": 1175714, "author_profile": "https://Stackoverflow.com/users/1175714", "pm_score": 8, "selected": false, "text": "delete const obj = { foo: \"bar\" };\n\ndelete obj.foo;\nobj.hasOwnProperty(\"foo\"); // false\n Array#splice Array#pop arr; // [0, 1, 2, 3, 4]\narr.splice(3,1); // 3\narr; // [0, 1, 2, 4]\n delete undefined let parent = {\n member: { str: \"Hello\" }\n};\nlet secondref = parent.member;\n\ndelete parent.member;\nparent.member; // undefined\nsecondref; // { str: \"Hello\" }\n delete let array = [0, 1, 2, 3]; // [0, 1, 2, 3]\ndelete array[2]; // [0, 1, empty, 3]\n let fauxarray = {0: 1, 1: 2, length: 2};\nfauxarray.__proto__ = [].__proto__;\nfauxarray.push(3);\nfauxarray; // [1, 2, 3]\nArray.isArray(fauxarray); // false\nArray.isArray([1, 2, 3]); // true\n for..in for undefined Symbol.iterator undefined forEach map reduce let array = [1, 2, 3]; // [1,2,3]\ndelete array[1]; // [1, empty, 3]\narray.map(x => 0); // [0, empty, 0]\n delete Array#splice() Array#pop Array#splice deleteCount start item1, item2... itemN start deleteCount let a = [0,1,2,3,4]\na.splice(2,2) // returns the removed elements [2,3]\n// ...and `a` is now [0,1,4]\n Array.prototype Array#slice Array#slice start end end end end end <= start let a = [0,1,2,3,4]\nlet slices = [\n a.slice(0,2),\n a.slice(2,2),\n a.slice(2,3),\n a.slice(2,5) ]\n\n// a [0,1,2,3,4]\n// slices[0] [0 1]- - - \n// slices[1] - - - - -\n// slices[2] - -[3]- -\n// slices[3] - -[2 4 5]\n Array#pop push Array#shift pop unshift" }, { "answer_id": 21720354, "author": "Mehran Hatami", "author_id": 2877719, "author_profile": "https://Stackoverflow.com/users/2877719", "pm_score": 6, "selected": false, "text": "delete myJSONObject = {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"};\n console.log(Object.keys(myJSONObject));\n [\"ircEvent\", \"method\", \"regex\"]\n delete myJSONObject[\"regex\"];\n Object.keys(myJSONObject) [\"ircEvent\", \"method\"]\n myJSONObject[\"regex\"] = null;\ndelete myJSONObject[\"regex\"];\n var regex = myJSONObject[\"regex\"];\n var myOtherObject = {};\nmyOtherObject[\"regex\"] = myJSONObject[\"regex\"];\n myJSONObject regex myOtherObject[\"regex\"] var var var regex var delete regex; //False\n false myOtherObject[\"regex\"] myOtherObject[\"regex\"] = null;\ndelete myOtherObject[\"regex\"];\n Object.seal" }, { "answer_id": 21735614, "author": "Dan", "author_id": 139361, "author_profile": "https://Stackoverflow.com/users/139361", "pm_score": 10, "selected": false, "text": "delete var obj = {\n myProperty: 1 \n}\nconsole.log(obj.hasOwnProperty('myProperty')) // true\ndelete obj.myProperty\nconsole.log(obj.hasOwnProperty('myProperty')) // false delete null undefined delete" }, { "answer_id": 23848569, "author": "Thaddeus Albers", "author_id": 1684480, "author_profile": "https://Stackoverflow.com/users/1684480", "pm_score": 7, "selected": false, "text": "_.pick() _.omit() var myJSONObject = \n{\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"};\n\n_.pick(myJSONObject, \"ircEvent\", \"method\");\n=> {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\"};\n var myJSONObject = \n{\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"};\n\n_.omit(myJSONObject, \"regex\");\n=> {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\"};\n _.filter() _.reject()" }, { "answer_id": 25839420, "author": "Willem", "author_id": 1811818, "author_profile": "https://Stackoverflow.com/users/1811818", "pm_score": 5, "selected": false, "text": "var obj = {\"property\":\"value\", \"property2\":\"value\"};\n\nif (obj && obj.hasOwnProperty(\"property2\")) {\n delete obj.property2;\n} else {\n //error handling\n}\n" }, { "answer_id": 27223633, "author": "talsibony", "author_id": 1220652, "author_profile": "https://Stackoverflow.com/users/1220652", "pm_score": 5, "selected": false, "text": "unset function unset(unsetKey, unsetArr, resort) {\n var tempArr = unsetArr;\n var unsetArr = {};\n delete tempArr[unsetKey];\n if (resort) {\n j = -1;\n }\n for (i in tempArr) {\n if (typeof(tempArr[i]) !== 'undefined') {\n if (resort) {\n j++;\n } else {\n j = i;\n }\n unsetArr[j] = tempArr[i];\n }\n }\n return unsetArr;\n}\n\nvar unsetArr = ['test', 'deletedString', 'test2'];\n\nconsole.log(unset('1', unsetArr, true)); // output Object {0: \"test\", 1: \"test2\"}\nconsole.log(unset('1', unsetArr, false)); // output Object {0: \"test\", 2: \"test2\"}" }, { "answer_id": 34707963, "author": "madox2", "author_id": 741871, "author_profile": "https://Stackoverflow.com/users/741871", "pm_score": 6, "selected": false, "text": "Reflect.deleteProperty(myJSONObject, 'regex');\n delete myJSONObject['regex'];\n let obj = Object.freeze({ prop: \"value\" });\nlet success = Reflect.deleteProperty(obj, \"prop\");\nconsole.log(success); // false\nconsole.log(obj.prop); // value\n deleteProperty false true delete deleteProperty \"use strict\";\n\nlet obj = Object.freeze({ prop: \"value\" });\nReflect.deleteProperty(obj, \"prop\"); // false\ndelete obj[\"prop\"];\n// TypeError: property \"prop\" is non-configurable and can't be deleted\n" }, { "answer_id": 34937997, "author": "emil", "author_id": 3773265, "author_profile": "https://Stackoverflow.com/users/3773265", "pm_score": 5, "selected": false, "text": "myObject = _.omit(myObject, 'regex');\n" }, { "answer_id": 35539892, "author": "John Slegers", "author_id": 1946501, "author_profile": "https://Stackoverflow.com/users/1946501", "pm_score": 6, "selected": false, "text": "var Hogwarts = {\n staff : [\n 'Argus Filch',\n 'Filius Flitwick',\n 'Gilderoy Lockhart',\n 'Minerva McGonagall',\n 'Poppy Pomfrey',\n ...\n ],\n students : [\n 'Hannah Abbott',\n 'Katie Bell',\n 'Susan Bones',\n 'Terry Boot',\n 'Lavender Brown',\n ...\n ]\n};\n staff delete Hogwarts.staff;\n delete Hogwarts['staff'];\n delete Hogwarts.students; delete Hogwarts['students']; Hogwarts.staff.splice(3, 1);\n Hogwarts.staff.splice(Hogwarts.staff.indexOf('Minerva McGonnagall') - 1, 1);\n delete Hogwarts.staff.length delete length delete" }, { "answer_id": 37987813, "author": "ayushgp", "author_id": 3719089, "author_profile": "https://Stackoverflow.com/users/3719089", "pm_score": 4, "selected": false, "text": "var deepObjectRemove = function(obj, path_to_key){\n if(path_to_key.length === 1){\n delete obj[path_to_key[0]];\n return true;\n }else{\n if(obj[path_to_key[0]])\n return deepObjectRemove(obj[path_to_key[0]], path_to_key.slice(1));\n else\n return false;\n }\n};\n var a = {\n level1:{\n level2:{\n level3: {\n level4: \"yolo\"\n }\n }\n }\n};\n\ndeepObjectRemove(a, [\"level1\", \"level2\", \"level3\"]);\nconsole.log(a);\n\n//Prints {level1: {level2: {}}}\n" }, { "answer_id": 38227080, "author": "Mohammed Safeer", "author_id": 2293686, "author_profile": "https://Stackoverflow.com/users/2293686", "pm_score": 4, "selected": false, "text": "Object undefined stringify parse var myObject = {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"};\n\nmyObject.regex = undefined;\nmyObject = JSON.parse(JSON.stringify(myObject));\n\nconsole.log(myObject);" }, { "answer_id": 40493600, "author": "Koen.", "author_id": 189431, "author_profile": "https://Stackoverflow.com/users/189431", "pm_score": 8, "selected": false, "text": "const { a, ...rest } = { a: 1, b: 2, c: 3 };\n const myObject = {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"};\nconst { regex, ...newObject } = myObject;\nconsole.log(newObject);\n let let myObject = {\"ircEvent\": \"PRIVMSG\", \"method\": \"newURI\", \"regex\": \"^http://.*\"};\n({ regex, ...myObject } = myObject);\nconsole.log(myObject);\n" }, { "answer_id": 40847647, "author": "Amio.io", "author_id": 1075289, "author_profile": "https://Stackoverflow.com/users/1075289", "pm_score": 4, "selected": false, "text": "regex const newObject = R.dissoc('regex', myObject);\n// newObject !== myObject\n" }, { "answer_id": 43030580, "author": "kind user", "author_id": 6695924, "author_profile": "https://Stackoverflow.com/users/6695924", "pm_score": 5, "selected": false, "text": "Array#reduce var myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};\n\nmyObject = Object.keys(myObject).reduce(function(obj, key) {\n if (key != \"regex\") { //key you want to remove\n obj[key] = myObject[key];\n }\n return obj;\n}, {});\n\nconsole.log(myObject); const myObject = {\n ircEvent: 'PRIVMSG',\n method: 'newURI',\n regex: '^http://.*',\n};\n\nconst myNewObject = Object.keys(myObject).reduce((obj, key) => {\n key !== 'regex' ? obj[key] = myObject[key] : null;\n return obj;\n}, {});\n\nconsole.log(myNewObject);" }, { "answer_id": 43282814, "author": "Alireza", "author_id": 5423108, "author_profile": "https://Stackoverflow.com/users/5423108", "pm_score": 5, "selected": false, "text": "delete myObject.regex;\n// OR\ndelete myObject['regex'];\n var Employee = {\n age: 28,\n name: 'Alireza',\n designation: 'developer'\n}\n\nconsole.log(delete Employee.name); // returns true\nconsole.log(delete Employee.age); // returns true\n\n// When trying to delete a property that does \n// not exist, true is returned \nconsole.log(delete Employee.salary); // returns true" }, { "answer_id": 45320042, "author": "Chong Lip Phang", "author_id": 2435020, "author_profile": "https://Stackoverflow.com/users/2435020", "pm_score": 4, "selected": false, "text": "var iterationsTotal = 10000000; // 10 million\nvar o;\nvar t1 = Date.now(),t2;\nfor (let i=0; i<iterationsTotal; i++) {\n o = {a:1,b:2,c:3,d:4,e:5};\n delete o.a; delete o.b; delete o.c; delete o.d; delete o.e;\n}\nconsole.log ((t2=Date.now())-t1); // 6135\nfor (let i=0; i<iterationsTotal; i++) {\n o = {a:1,b:2,c:3,d:4,e:5};\n o.a = o.b = o.c = o.d = o.e = undefined;\n}\nconsole.log (Date.now()-t2); // 205\n" }, { "answer_id": 46221459, "author": "johndavedecano", "author_id": 790403, "author_profile": "https://Stackoverflow.com/users/790403", "pm_score": 4, "selected": false, "text": "import omit from 'lodash/omit';\n\nconst prevObject = {test: false, test2: true};\n// Removes test2 key from previous object\nconst nextObject = omit(prevObject, 'test2');\n R.omit(['a', 'd'], {a: 1, b: 2, c: 3, d: 4}); //=> {b: 2, c: 3}\n" }, { "answer_id": 46295693, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "const obj = {\n \"Filters\":[\n {\n \"FilterType\":\"between\",\n \"Field\":\"BasicInformationRow.A0\",\n \"MaxValue\":\"2017-10-01\",\n \"MinValue\":\"2017-09-01\",\n \"Value\":\"Filters value\"\n }\n ]\n};\n\nlet new_obj1 = Object.assign({}, obj.Filters[0]);\nlet new_obj2 = Object.assign({}, obj.Filters[0]);\n\n/*\n\n// old version\n\nlet shaped_obj1 = Object.keys(new_obj1).map(\n (key, index) => {\n switch (key) {\n case \"MaxValue\":\n delete new_obj1[\"MaxValue\"];\n break;\n case \"MinValue\":\n delete new_obj1[\"MinValue\"];\n break;\n }\n return new_obj1;\n }\n)[0];\n\n\nlet shaped_obj2 = Object.keys(new_obj2).map(\n (key, index) => {\n if(key === \"Value\"){\n delete new_obj2[\"Value\"];\n }\n return new_obj2;\n }\n)[0];\n\n\n*/\n\n\n// new version!\n\nlet shaped_obj1 = Object.keys(new_obj1).forEach(\n (key, index) => {\n switch (key) {\n case \"MaxValue\":\n delete new_obj1[\"MaxValue\"];\n break;\n case \"MinValue\":\n delete new_obj1[\"MinValue\"];\n break;\n default:\n break;\n }\n }\n);\n\nlet shaped_obj2 = Object.keys(new_obj2).forEach(\n (key, index) => {\n if(key === \"Value\"){\n delete new_obj2[\"Value\"];\n }\n }\n);" }, { "answer_id": 46484377, "author": "BEJGAM SHIVA PRASAD", "author_id": 5293976, "author_profile": "https://Stackoverflow.com/users/5293976", "pm_score": 3, "selected": false, "text": "var a = {\"bool\":{\"must\":[{\"range\":{\"price_index.final_price\":{\"gt\":\"450\", \"lt\":\"500\"}}}, {\"bool\":{\"should\":[{\"term\":{\"color_value.keyword\":\"Black\"}}]}}]}};\n\nfunction getPathOfKey(object,key,currentPath, t){\n var currentPath = currentPath || [];\n\n for(var i in object){\n if(i == key){\n t = currentPath;\n }\n else if(typeof object[i] == \"object\"){\n currentPath.push(i)\n return getPathOfKey(object[i], key,currentPath)\n }\n }\n t.push(key);\n return t;\n}\ndocument.getElementById(\"output\").innerHTML =JSON.stringify(getPathOfKey(a,\"price_index.final_price\")) <div id=\"output\">\n\n</div> var unset = require('lodash.unset');\nunset(a, getPathOfKey(a, \"price_index.final_price\"));" }, { "answer_id": 47805034, "author": "james_womack", "author_id": 230571, "author_profile": "https://Stackoverflow.com/users/230571", "pm_score": 4, "selected": false, "text": "'use strict'\nconst iLikeMutatingStuffDontI = { myNameIs: 'KIDDDDD!', [Symbol.for('amICool')]: true }\ndelete iLikeMutatingStuffDontI[Symbol.for('amICool')] // true\nObject.defineProperty({ myNameIs: 'KIDDDDD!', 'amICool', { value: true, configurable: false })\ndelete iLikeMutatingStuffDontI['amICool'] // throws\n Symbol const foo = { name: 'KIDDDDD!', [Symbol.for('isCool')]: true }\nconst { name, ...coolio } = foo // coolio doesn't have \"name\"\nconst { isCool, ...coolio2 } = foo // coolio2 has everything from `foo` because `isCool` doesn't account for Symbols :(\n 'use strict'\nconst iLikeMutatingStuffDontI = { myNameIs: 'KIDDDDD!', [Symbol.for('amICool')]: true }\nReflect.deleteProperty(iLikeMutatingStuffDontI, Symbol.for('amICool')) // true\nObject.defineProperty({ myNameIs: 'KIDDDDD!', 'amICool', { value: true, configurable: false })\nReflect.deleteProperty(iLikeMutatingStuffDontI, 'amICool') // false\n Reflect.deleteProperty delete const foo = { name: 'KIDDDDD!', [Symbol.for('isCool')]: true }\nconst { name, ...coolio } = foo // coolio doesn't have \"name\"\nconst { isCool, ...coolio2 } = foo // coolio2 has everything from `foo` because `isCool` doesn't account for Symbols :(\n const o = require(\"lodash.omit\")\nconst foo = { [Symbol.for('a')]: 'abc', b: 'b', c: 'c' }\nconst bar = o(foo, 'a') // \"'a' undefined\"\nconst baz = o(foo, [ Symbol.for('a'), 'b' ]) // Symbol supported, more than one prop at a time, \"Symbol.for('a') undefined\"\n" }, { "answer_id": 50516140, "author": "hygull", "author_id": 6615163, "author_profile": "https://Stackoverflow.com/users/6615163", "pm_score": 3, "selected": false, "text": "var myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};\n\n// 1st and direct way \ndelete myObject.regex; // delete myObject[\"regex\"]\nconsole.log(myObject); // { ircEvent: 'PRIVMSG', method: 'newURI' }\n\n// 2 way - by using the concept of JavaScript's prototyping concept\nObject.prototype.removeFromObjectByKey = function(key) {\n // If key exists, remove it and return true\n if (this[key] !== undefined) {\n delete this[key]\n return true;\n }\n // Else return false\n return false;\n}\n\nvar isRemoved = myObject.removeFromObjectByKey('method')\nconsole.log(myObject) // { ircEvent: 'PRIVMSG' }\n\n// More examples\nvar obj = {\n a: 45,\n b: 56,\n c: 67\n}\nconsole.log(obj) // { a: 45, b: 56, c: 67 }\n\n// Remove key 'a' from obj\nisRemoved = obj.removeFromObjectByKey('a')\nconsole.log(isRemoved); //true\nconsole.log(obj); // { b: 56, c: 67 }\n\n// Remove key 'd' from obj which doesn't exist\nvar isRemoved = obj.removeFromObjectByKey('d')\nconsole.log(isRemoved); // false\nconsole.log(obj); // { b: 56, c: 67 }" }, { "answer_id": 52301527, "author": "Lior Elrom", "author_id": 1843451, "author_profile": "https://Stackoverflow.com/users/1843451", "pm_score": 8, "selected": false, "text": "const key = 'a';\n\nconst { [key]: foo, ...rest } = { a: 1, b: 2, c: 3 };\n\nconsole.log(foo); // 1\nconsole.log(rest); // { b: 2, c: 3 } foo a delete obj[key];\n delete obj[key] = null;\nobj[key] = false;\nobj[key] = undefined;\n ES6 { [key]: val, ...rest } = obj;\n" }, { "answer_id": 56030135, "author": "YairTawil", "author_id": 4309299, "author_profile": "https://Stackoverflow.com/users/4309299", "pm_score": 7, "selected": false, "text": "let object = { a: 1, b: 2, c: 3 };\n a const { a, ...rest } = object;\nobject = rest;\n const propKey = 'a';\nconst { [propKey]: propValue, ...rest } = object;\nobject = rest;\n const removeProperty = (propKey, { [propKey]: propValue, ...rest }) => rest;\n\nobject = removeProperty('a', object);\n const removeProperties = (object, ...keys) => (keys.length ? removeProperties(removeProperty(keys.pop(), object), ...keys) : object);\n object = removeProperties(object, 'a', 'b') // result => { c: 3 }\n const propsToRemove = ['a', 'b']\nobject = removeProperties(object, ...propsToRemove) // result => { c: 3 }\n" }, { "answer_id": 57991193, "author": "ANIK ISLAM SHOJIB", "author_id": 4235636, "author_profile": "https://Stackoverflow.com/users/4235636", "pm_score": 4, "selected": false, "text": "var myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};\n\n// Way 1\n\nlet filter1 = {}\n Object.keys({...myObject}).filter(d => {\n if(d !== 'regex'){\n filter1[d] = myObject[d];\n }\n})\n\nconsole.log(filter1)\n\n// Way 2\n\nlet filter2 = Object.fromEntries(Object.entries({...myObject}).filter(d =>\nd[0] !== 'regex'\n))\n\nconsole.log(filter2)" }, { "answer_id": 63913960, "author": "B''H Bi'ezras -- Boruch Hashem", "author_id": 2016831, "author_profile": "https://Stackoverflow.com/users/2016831", "pm_score": 3, "selected": false, "text": "let myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};\n\n\nobj = Object.fromEntries(\n Object.entries(myObject).filter(function (m){\n return m[0] != \"regex\"/*or whatever key to delete*/\n }\n))\n\nconsole.log(obj) a2d Object.entries" }, { "answer_id": 64869433, "author": "akhtarvahid", "author_id": 6544460, "author_profile": "https://Stackoverflow.com/users/6544460", "pm_score": 3, "selected": false, "text": "let myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};\n\nlet prop = 'regex';\nconst updatedObject = Object.keys(myObject).reduce((object, key) => {\n if (key !== prop) {\n object[key] = myObject[key]\n }\n return object\n}, {})\n\nconsole.log(updatedObject);" }, { "answer_id": 65777869, "author": "John Doe", "author_id": 7461599, "author_profile": "https://Stackoverflow.com/users/7461599", "pm_score": 4, "selected": false, "text": "let myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\"\n};\n\nconst removeItem = 'regex';\n\nconst { [removeItem]: remove, ...rest } = myObject;\n\nconsole.log(remove); // \"^http://.*\"\nconsole.log(rest); // Object { ircEvent: \"PRIVMSG\", method: \"newURI\" }" }, { "answer_id": 66318382, "author": "Rashid Iqbal", "author_id": 11216947, "author_profile": "https://Stackoverflow.com/users/11216947", "pm_score": 2, "selected": false, "text": " function deleteUser(key) {\n\n const newUsers = {};\n for (const uid in users) {\n if (uid !== key) {\n newUsers[uid] = users[uid];\n }\n\n return newUsers\n }\n delete users[key]\n" }, { "answer_id": 70405397, "author": "Ran Turner", "author_id": 7494218, "author_profile": "https://Stackoverflow.com/users/7494218", "pm_score": 4, "selected": false, "text": "const myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\",\n};\n\ndelete myObject.regex;\nconsole.log(myObject); const myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\",\n };\n\ndelete myObject['regex'];\nconsole.log(myObject);\n// or\nconst name = 'ircEvent';\ndelete myObject[name];\nconsole.log(myObject); const myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\",\n };\n\nconst { regex, ...myObjectRest} = myObject;\nconsole.log(myObjectRest); " }, { "answer_id": 71333136, "author": "Sahil Thummar", "author_id": 14229690, "author_profile": "https://Stackoverflow.com/users/14229690", "pm_score": 1, "selected": false, "text": "let myObject = {\n \"ircEvent\": \"PRIVMSG\",\n \"method\": \"newURI\",\n \"regex\": \"^http://.*\",\n \"regex1\": \"^http://.*\",\n \"regex2\": \"^http://.*\",\n \"regex3\": \"^http://.*\",\n \"regex4\": \"^http://.*\"\n};\n\ndelete myObject.regex; // using delete object.property\n\n// Or \n\ndelete myObject['regex1']; // using delete object['property']\n\nconst { regex2, regex3, regex4, ...newMyObject } = myObject;\n\nconsole.log(newMyObject);" }, { "answer_id": 72751498, "author": "rohithpoya", "author_id": 18436980, "author_profile": "https://Stackoverflow.com/users/18436980", "pm_score": 1, "selected": false, "text": "delete object.property const {property, ...rest} = object" }, { "answer_id": 73562633, "author": "Yusuf Ganiyu", "author_id": 6070546, "author_profile": "https://Stackoverflow.com/users/6070546", "pm_score": 1, "selected": false, "text": "var obj = {\n data: 1,\n anotherData: 'sample' \n}\ndelete obj.data //this removes data from the obj\n var obj = {\n anotherData: 'sample' \n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208105", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27929/" ]
208,119
<p>How can I launch an event that has accessors like this :</p> <pre><code>public event EventHandler CanExecuteChanged { add { CommandManager.RequerySuggested += value; } remove { CommandManager.RequerySuggested -= value; } } </code></pre> <p>If it were a normal event I would launch it by: </p> <pre><code>CanExecuteChanged(sender, EventArgs..). </code></pre> <p>But here it doesn't work - I can only do </p> <pre><code>CanExecuteChanged +=.. </code></pre> <p>to attach a method do the event - but I can't Launch it. </p> <p>Also some documentation on the subject would be appreciated. Thanks.</p> <p><strong>EDIT</strong> The event is from class implementing ICommand in WPF. there's nothing more to show :). And no - the CommandManager.RequerySuggested(this, EventArgs.Empty); doesn't work.</p> <p><strong>EDIT2</strong> Not sure what to say - Jon's example should have worked yet even if the add method is called correctly - when I try to call the event - it's null :|. I probably will drop events with accessors.</p>
[ { "answer_id": 208127, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "<blockquote>CommandManager.RequerySuggested(sender, EventArgs.…)</blockquote>\n CommandManager canExecuteChanged(sender, EventArgs.Empty);\n" }, { "answer_id": 208131, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 2, "selected": false, "text": "public class Hash1 \n {\n\n private EventHandler myHomeMadeDelegate;\n public event EventHandler FancyEvent\n {\n add\n {\n //myDelegate += value;\n myHomeMadeDelegate = (EventHandler)Delegate.Combine(myHomeMadeDelegate, value);\n }\n remove\n {\n //myDelegate -= value;\n myHomeMadeDelegate = (EventHandler)Delegate.Remove(myHomeMadeDelegate, value);\n }\n }\n public event EventHandler PlainEvent;\n\n\n public Hash1()\n {\n FancyEvent += new EventHandler(On_Hash1_FancyEvent);\n PlainEvent += new EventHandler(On_Hash1_PlainEvent);\n\n // FancyEvent(this, EventArgs.Empty); //won't work:What is the backing delegate called? I don't know\n myHomeMadeDelegate(this, EventArgs.Empty); // Aha!\n PlainEvent(this, EventArgs.Empty);\n }\n\n void On_Hash1_PlainEvent(object sender, EventArgs e)\n {\n Console.WriteLine(\"Bang Bang!\");\n }\n\n void On_Hash1_FancyEvent(object sender, EventArgs e)\n {\n Console.WriteLine(\"Bang!\");\n }\n}\n" }, { "answer_id": 208150, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "private EventHandler canExecuteChanged;\n\npublic event EventHandler CanExecuteChanged\n{\n add\n {\n CommandManager.RequerySuggested += value;\n canExecuteChanged += value;\n }\n remove\n {\n CommandManager.RequerySuggested -= value;\n canExecuteChanged -= value;\n }\n}\n" }, { "answer_id": 208197, "author": "sirrocco", "author_id": 5246, "author_profile": "https://Stackoverflow.com/users/5246", "pm_score": 1, "selected": false, "text": "CommandManager.InvalidateRequerySuggested();.\n" }, { "answer_id": 13617868, "author": "sss", "author_id": 796912, "author_profile": "https://Stackoverflow.com/users/796912", "pm_score": 0, "selected": false, "text": "class X\n{\n public event D Ev;\n}\n class X\n{\n private D __Ev; // field to hold the delegate\n\n public event D Ev {\n add {\n lock(this) { __Ev = __Ev + value; }\n }\n\n remove {\n lock(this) { __Ev = __Ev - value; }\n }\n }\n}\n namespace ConsoleApplication1\n{ \n class Program \n {\n public event EventHandler ss;\n\n Program()\n {\n if (null != ss)\n {\n ss(this, EventArgs.Empty) ;\n\n }\n }\n\n static void Main(string[] args)\n {\n new Program();\n }\n }\n}\n namespace ConsoleApplication1\n{ \n class Program \n {\n public event EventHandler ss\n {\n add { }\n remove { }\n }\n\n Program()\n {\n if (null != ss)\n {\n ss(this, EventArgs.Empty) ;\n\n }\n }\n\n static void Main(string[] args)\n {\n new Program();\n }\n }\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5246/" ]
208,120
<p>I want to write a program for this: In a folder I have <em>n</em> number of files; first read one file and perform some operation then store result in a separate file. Then read 2nd file, perform operation again and save result in new 2nd file. Do the same procedure for <em>n</em> number of files. The program reads all files one by one and stores results of each file separately. Please give examples how I can do it.</p>
[ { "answer_id": 208156, "author": "Matthew Scharley", "author_id": 15537, "author_profile": "https://Stackoverflow.com/users/15537", "pm_score": 4, "selected": false, "text": "import sys\n\n# argv is your commandline arguments, argv[0] is your program name, so skip it\nfor n in sys.argv[1:]:\n print(n) #print out the filename we are currently processing\n input = open(n, \"r\")\n output = open(n + \".out\", \"w\")\n # do some processing\n input.close()\n output.close()\n" }, { "answer_id": 208227, "author": "Alex Coventry", "author_id": 1941213, "author_profile": "https://Stackoverflow.com/users/1941213", "pm_score": 3, "selected": false, "text": "fileinput" }, { "answer_id": 208342, "author": "Mapad", "author_id": 28165, "author_profile": "https://Stackoverflow.com/users/28165", "pm_score": 4, "selected": false, "text": "import glob\n\nlist_of_files = glob.glob('./*.txt') # create the list of file\nfor file_name in list_of_files:\n FI = open(file_name, 'r')\n FO = open(file_name.replace('txt', 'out'), 'w') \n for line in FI:\n FO.write(line)\n\n FI.close()\n FO.close()\n" }, { "answer_id": 208731, "author": "michaeljoseph", "author_id": 5549, "author_profile": "https://Stackoverflow.com/users/5549", "pm_score": 1, "selected": false, "text": "import sys\nimport os.path\nimport glob\n\ndef processFile(filename):\n fileHandle = open(filename, \"r\")\n for line in fileHandle:\n # do some processing\n pass\n fileHandle.close()\n\ndef outputResults(filename):\n output_filemask = \"out\"\n fileHandle = open(\"%s.%s\" % (filename, output_filemask), \"w\")\n # do some processing\n fileHandle.write('processed\\n')\n fileHandle.close()\n\ndef processFiles(args):\n input_filemask = \"log\"\n directory = args[1]\n if os.path.isdir(directory):\n print \"processing a directory\"\n list_of_files = glob.glob('%s/*.%s' % (directory, input_filemask))\n else:\n print \"processing a list of files\"\n list_of_files = sys.argv[1:]\n\n for file_name in list_of_files:\n print file_name\n processFile(file_name)\n outputResults(file_name)\n\nif __name__ == '__main__':\n if (len(sys.argv) > 1):\n processFiles(sys.argv)\n else:\n print 'usage message'\n" }, { "answer_id": 211188, "author": "monkut", "author_id": 24718, "author_profile": "https://Stackoverflow.com/users/24718", "pm_score": 2, "selected": false, "text": "import os\nOUTPUT_DIR = 'C:\\\\RESULTS'\nfor path, dirs, files in os.walk('.'):\n for file in files:\n read_f = open(os.join(path,file),'r')\n write_f = open(os.path.join(OUTPUT_DIR,file))\n\n # Do stuff\n" }, { "answer_id": 11945810, "author": "pramod", "author_id": 1597032, "author_profile": "https://Stackoverflow.com/users/1597032", "pm_score": 0, "selected": false, "text": "from pylab import * \nimport csv \nimport os \nimport glob \nimport re \nx=[] \ny=[]\n\nf=open(\"one.txt\",'w')\n\nfor infile in glob.glob(('*.csv')):\n # print \"\" +infile\n csv23=csv2rec(\"\"+infile,'rb',delimiter=',')\n for line in csv23: \n x.append(line[1])\n # print len(x)\n for i in range(3000,8000):\n y.append(x[i])\n print \"\"+infile,\"\\t\",mean(y)\n print >>f,\"\"+infile,\"\\t\\t\",mean(y)\n del y[:len(y)]\n del x[:len(x)]\n" }, { "answer_id": 62671116, "author": "codearena", "author_id": 13845372, "author_profile": "https://Stackoverflow.com/users/13845372", "pm_score": -1, "selected": false, "text": "fedaralist_1.txt federalist_2.txt fedaralist_84.txt for file in filename:\n with open(f'federalist_{file}.txt','r') as f:\n f.read()\n" }, { "answer_id": 66648439, "author": "tldr", "author_id": 7803343, "author_profile": "https://Stackoverflow.com/users/7803343", "pm_score": 0, "selected": false, "text": "with open() \"\"\" A module to clean code(js, py, json or whatever) files saved as .txt files to \nbe used in HTML code blocks. \"\"\"\nfrom os import listdir\nfrom os.path import abspath, dirname, splitext\nfrom re import sub, MULTILINE\n\ndef cleanForHTML():\n \"\"\" This function will search a directory text files to be edited. \"\"\"\n\n ## define some regex for our search and replace. We are looking for <, > and &\n ## To replaced with &ls;, &gt; and &amp;. We might want to replace proper whitespace\n ## chars to as well? (r'\\t', ' ') and (f'\\n', '<br>')\n search_ = ((r'(<)', '&lt;'), (r'(>)', '&gt;'), (r'(&)', '&amp;'))\n\n ## Read and loop our file location. Our location is the same one that our python file is in.\n for loc in listdir(abspath(dirname(__file__))):\n\n ## Here we split our filename into it's parts ('fileName', '.txt')\n name = splitext(loc)\n\n if name[1] == '.txt':\n ## we found our .txt file so we can start file operations.\n with open(loc, 'r') as file_1, open(f'{name[0]}(fixed){name[1]}', 'w') as file_2:\n\n ## read our first file\n retFile = file_1.read()\n\n ## find and replace some text.\n for find_ in search_:\n retFile = sub(find_[0], find_[1], retFile, 0, MULTILINE)\n\n ## finally we can write to our newly created text file.\n file_2.write(retFile)\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208120", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17451/" ]
208,123
<p>I've just completed a Silverlight project and it's time to have a little clean up. I'd like to take my core files and put them into a separate project which I will reference from my main Silverlight app. Some of these classes are compatible with WPF and I would quite like to be able to have Silverlight / WPF code all in one project. My ideal solution would be a single project that allows multiple configurations. So,</p> <p>Configuration: Silverlight would generate: Company.Controls.Silverlight.dll</p> <p>Configuration: WPF would generate: Company.Controls.Wpf.dll</p> <p>Is it possible to have the same source in the same file just seperated via defines?</p> <p>Has anyone done this before?</p> <p><strong>Edit:</strong> I've created a solution per project, like MyCompany.Windows.Controls, which then contains 2 projects, MyCompany.Windows.Controls &amp; MyCompany.Windows.Controls.Silverlight. Alongside those 2 folders I have a "Shared" folder, which contains files used by both projects. It works well so far :)</p>
[ { "answer_id": 210364, "author": "Christopher Bennage", "author_id": 6855, "author_profile": "https://Stackoverflow.com/users/6855", "pm_score": 3, "selected": false, "text": " public static T GetResource<T>(this FrameworkElement element, object key)\n {\n DependencyObject currentElement = element;\n\n while (currentElement != null)\n {\n var frameworkElement = currentElement as FrameworkElement;\n\n if (frameworkElement != null && frameworkElement.Resources.Contains(key))\n return (T)frameworkElement.Resources[key];\n\n#if !SILVERLIGHT\n currentElement = (LogicalTreeHelper.GetParent(currentElement) ??\n VisualTreeHelper.GetParent(currentElement));\n#else\n currentElement = VisualTreeHelper.GetParent(currentElement);\n#endif\n }\n\n if (Application.Current.Resources.Contains(key))\n return (T)Application.Current.Resources[key];\n\n return default(T);\n }\n <target name=\"config-platform-silverlight20\">\n <property name=\"nant.settings.currentframework\" value=\"silverlight-2.0\"/>\n <property name=\"build.platform\" value=\"silverlight-2.0\"/>\n <property name=\"build.defines\" value=\"${global.build.defines},SILVERLIGHT,SILVERLIGHT_20,NO_WEB,NO_REMOTING,NO_CONVERT,NO_PARTIAL_TRUST,NO_EXCEPTION_SERIALIZATION,NO_SKIP_VISIBILITY,NO_DEBUG_SYMBOLS\"/>\n <property name=\"current.path.bin\" value=\"${path.bin}/silverlight-2.0/${build.config}\"/>\n <property name=\"current.path.test\" value=\"${path.bin}/silverlight-2.0/tests\" />\n <property name=\"current.path.lib\" value=\"${path.lib}/Silverlight\" />\n</target>\n <target name=\"platform-silverlight20\" depends=\"config\">\n <if test=\"${framework::exists('silverlight-2.0')}\">\n <echo message=\"Building Caliburn ${build.version} for Silverlight v2.0.\"/>\n <call target=\"config-platform-silverlight20\"/>\n <copy todir=\"${current.path.bin}\">\n <fileset basedir=\"${current.path.lib}\">\n <include name=\"*.dll\"/>\n <include name=\"*.xml\"/>\n </fileset>\n </copy>\n <call target=\"core\"/>\n <call target=\"messaging\"/>\n <call target=\"actions\"/>\n <call target=\"commands\"/>\n <call target=\"package-platform\"/>\n </if>\n <if test=\"${not(framework::exists('silverlight-2.0'))}\">\n <echo message=\"Silverlight v2.0 is not available. Skipping platform.\"/>\n </if>\n</target>\n <target name=\"core\" depends=\"config, ensure-platform-selected\">\n <mkdir dir=\"${current.path.bin}\"/>\n <csc keyfile=\"${path.src}/Caliburn.snk\" noconfig=\"true\" warnaserror=\"false\" target=\"library\" debug=\"${build.debug}\" optimize=\"${build.optimize}\" define=\"${build.defines}\"\n output=\"${current.path.bin}/Caliburn.Core.dll\"\n doc=\"${current.path.bin}/Caliburn.Core.xml\">\n <sources basedir=\"${path.src}\">\n <include name=\"${build.asminfo}\"/>\n <include name=\"Caliburn.Core/**/*.cs\"/>\n </sources>\n <references basedir=\"${current.path.bin}\">\n <include name=\"mscorlib.dll\"/>\n <include name=\"System.dll\"/>\n <include name=\"System.Core.dll\"/>\n <!--WPF-->\n <include name=\"PresentationCore.dll\"/>\n <include name=\"PresentationFramework.dll\"/>\n <include name=\"WindowsBase.dll\"/>\n <!--Silverlight-->\n <include name=\"System.Windows.dll\" />\n </references>\n <nowarn>\n <warning number=\"1584\"/>\n </nowarn>\n </csc>\n</target>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/986/" ]
208,133
<p>By default the SQL Server comes with the Langauge set to "English (United States)", setting the date format to mm/dd/yy instead of the date format I want it in, which is Australian and has a date format such as dd/mm/yy.</p> <p>Is there an option in the Server Management Studio / Configuration tools where I can set the locale of the SQL Server, which will prevent the DateTime fields from being formatted in US date format?</p> <p>If not, how can I convert it when I am using a SQL query such as (forgive me if there is incorrect syntax, I made it up on the spot):</p> <pre><code>Dim dc As New SqlCommand("INSERT INTO hello VALUES (@Date)", cn) dc.Parameters.Add(New SqlParameter("Date", System.DateTime.Now)) </code></pre> <p>Many thanks in advance. :)</p>
[ { "answer_id": 208168, "author": "balexandre", "author_id": 28004, "author_profile": "https://Stackoverflow.com/users/28004", "pm_score": 0, "selected": false, "text": "INSERT INTO hello VALUES convert(datetime, @Date + ' 00:00:00', 103)\n INSERT INTO hello VALUES convert(datetime, @Date, 103)\n SELECT myColumn FROM myTable WHERE myDateField >= convert(datetime, @Date + '00:00:00', 103)\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208133", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20900/" ]
208,151
<p>I have a checkbox list control on my asp.net web form that I am dynamically populating from an arraylist. In javascript I want to be able to iterate through the values in the list and if a particular value has been selected to display other controls on the page. </p> <p>My issue is that all the values in the checkbox list are showing up as 'on' instead of the actual value set. How do I get the actual values for each checkbox?</p> <p>Thanks.</p> <p>Javascript:</p> <pre><code>checkBoxs=document.getElementById(CheckboxList); var options=checkBoxs.getElementsByTagName('input'); for(var i=0;i&lt;options.length;i++) { if(options[i].value=="Other") { if(options[i].checked) { var otherPub=document.getElementById('&lt;%=alsOtherPublicity.ClientID%&gt;'); otherPub.style.display='block'; } } } </code></pre> <p><strong>Edit:</strong> The line that I'm having problems with is if(options[i].value=="Other") as the values showing up in firebug are given as 'on' rather than the values that I set.</p> <p><strong>Edit 2:</strong> The html that is produces looks like:</p> <pre><code>&lt;span id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity" class="ucFieldCBL" onChange="alValidate();" onClick="alPublicity('ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity');"&gt; &lt;input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_0" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$0"/&gt; &lt;label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_0"&gt;Text1&lt;/label&gt; &lt;input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_1" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$1"/&gt; &lt;label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_1"&gt;Text2&lt;/label&gt; &lt;input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_2" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$2"/&gt; &lt;label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_2"&gt;Text3&lt;/label&gt; &lt;input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_3" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$3"/&gt; &lt;label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_3"&gt;Text4&lt;/label&gt; &lt;input id="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_4" type="checkbox" name="ctl00$ContentPlaceHolderMetadata$Allocation1$alfPublicity$4"/&gt; &lt;label for="ctl00_ContentPlaceHolderMetadata_Allocation1_alfPublicity_4"&gt;Text5&lt;/label&gt; &lt;/span&gt; </code></pre> <p>It looks as if the issue stems from the lack of a value attribute available on the asp.net checkbox control as described by <a href="http://www.daveparslow.com/2007/08/assigning-value-to-aspnet-checkbox.html" rel="nofollow noreferrer" title="Dave Parslow">Dave Parslow</a>. I'm currently trying a workaround by calling a function server side to return the text of the checkbox and using that instead. </p>
[ { "answer_id": 208167, "author": "Dylan Beattie", "author_id": 5017, "author_profile": "https://Stackoverflow.com/users/5017", "pm_score": 2, "selected": false, "text": "options[i].checked options[i].value" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208151", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1076/" ]
208,181
<p>How do I do <code>mv original.filename new.original.filename</code> without retyping the original filename?</p> <p>I would imagine being able to do something like <code>mv -p=new. original.filename</code> or perhaps <code>mv original.filename new.~</code> or whatever - but I can't see anything like this after looking at <code>man mv</code> / <code>info mv</code> pages.</p> <p>Of course, I could write a shell script to do this, but isn't there an existing command/flag for it?</p>
[ { "answer_id": 208220, "author": "Simon Lehmann", "author_id": 27011, "author_profile": "https://Stackoverflow.com/users/27011", "pm_score": 8, "selected": false, "text": "rename(1) rename 's/(.*)$/new.$1/' original.filename\n rename *.jpg prefix_*.jpg for filename in *.jpg; do mv \"$filename\" \"prefix_${filename}\"; done;\n for filename in *.jpg; do mv {,prefix_}\"$filename\"; done;\n" }, { "answer_id": 208260, "author": "David Webb", "author_id": 3171, "author_profile": "https://Stackoverflow.com/users/3171", "pm_score": 8, "selected": true, "text": "# echo {vanilla,chocolate,strawberry}-ice-cream\nvanilla-ice-cream chocolate-ice-cream strawberry-ice-cream\n mv {,new.}original.filename\n mv original.filename new.original.filename\n" }, { "answer_id": 208389, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "rename rename rename from to file ...\n rename foo foo0 foo? foo??\n rename #!/bin/perl -w\n#\n# @(#)$Id: rename.pl,v 1.7 2008/02/16 07:53:08 jleffler Exp $\n#\n# Rename files using a Perl substitute or transliterate command\n\nuse strict;\nuse Getopt::Std;\n\nmy(%opts);\nmy($usage) = \"Usage: $0 [-fnxV] perlexpr [filenames]\\n\";\nmy($force) = 0;\nmy($noexc) = 0;\nmy($trace) = 0;\n\ndie $usage unless getopts('fnxV', \\%opts);\n\nif ($opts{V})\n{\n printf \"%s\\n\", q'RENAME Version $Revision: 1.7 $ ($Date: 2008/02/16 07:53:08 $)';\n exit 0;\n}\n$force = 1 if ($opts{f});\n$noexc = 1 if ($opts{n});\n$trace = 1 if ($opts{x});\n\nmy($op) = shift;\ndie $usage unless defined $op;\n\nif (!@ARGV) {\n @ARGV = <STDIN>;\n chop(@ARGV);\n}\n\nfor (@ARGV)\n{\n if (-e $_ || -l $_)\n {\n my($was) = $_;\n eval $op;\n die $@ if $@;\n next if ($was eq $_);\n if ($force == 0 && -f $_)\n {\n print STDERR \"rename failed: $was - $_ exists\\n\";\n }\n else\n {\n print \"+ $was --> $_\\n\" if $trace;\n print STDERR \"rename failed: $was - $!\\n\"\n unless ($noexc || rename($was, $_));\n }\n }\n else\n {\n print STDERR \"$_ - $!\\n\";\n }\n}\n rename 's/^/new./' original.filename\n" }, { "answer_id": 13439876, "author": "A Muguro", "author_id": 1833424, "author_profile": "https://Stackoverflow.com/users/1833424", "pm_score": 5, "selected": false, "text": "for file in *; do\n mv $file new.${file%%}\ndone\n" }, { "answer_id": 35025855, "author": "aprodan", "author_id": 2468335, "author_profile": "https://Stackoverflow.com/users/2468335", "pm_score": 1, "selected": false, "text": "f=`ls *canctn[0-9]*` ; mv $f CNLC.$f\nf=`ls *acustb[0-9]*` ; mv $f CATB.$f\nf=`ls *accusgtb[0-9]*` ; mv $f CATB.$f\nf=`ls *acus[0-9]*` ; mv $f CAUS.$f\n f=MyFileName; mv $f {pref1,pref2}$f{suf1,suf2}\n pref1.MyFileName.suf1\n...\npref2.MyFileName.suf2\n #!/bin/bash\nunset masks\ntypeset -A masks\nmasks[ip[0-9]]=ip\nmasks[iaf_usg[0-9]]=ip_usg\nmasks[ipusg[0-9]]=ip_usg\n...\nfor fileMask in ${!masks[*]}; \ndo \nregistryEntry=\"${masks[$fileMask]}\";\nfileName=*${fileMask}*\n[ -e ${fileName} ] && mv ${fileName} ${registryEntry}.${fileName} \ndone\n" }, { "answer_id": 35820900, "author": "Harkály Gergő", "author_id": 4519702, "author_profile": "https://Stackoverflow.com/users/4519702", "pm_score": 1, "selected": false, "text": "#!/bin/bash\n# USAGE: cd FILESDIRECTORY; RENAMERFILEPATH/MultipleFileRenamer.sh FILENAMEPREFIX INITNUMBER\n# USAGE EXAMPLE: cd PHOTOS; /home/Desktop/MultipleFileRenamer.sh 2016_\n# VERSION: 2016.03.05.\n# COPYRIGHT: Harkály Gergő | mangoRDI (https://wwww.mangordi.com/) \n\n# check isset INITNUMBER argument, if not, set 1 | INITNUMBER is the first number after renaming\nif [ -z \"$2\" ]\n then i=1;\nelse\n i=$2;\nfi\n\n# counts the files to set leading zeros before number | max 1000 files\ncount=$(ls -l * | wc -l)\nif [ $count -lt 10 ]\n then zeros=1;\nelse\n if [ $count -lt 100 ]\n then zeros=2;\n else\n zeros=3\n fi\nfi\n\n# rename script\nfor file in *\ndo\n mv $file $1_$(printf %0\"$zeros\"d.%s ${i%.*} ${file##*.})\n let i=\"$i+1\"\ndone\n" }, { "answer_id": 53449302, "author": "Brajan Elektro", "author_id": 10696255, "author_profile": "https://Stackoverflow.com/users/10696255", "pm_score": 3, "selected": false, "text": "ls | xargs -I fileName mv fileName fileName.suffix\n" }, { "answer_id": 62514228, "author": "yeya", "author_id": 3107689, "author_profile": "https://Stackoverflow.com/users/3107689", "pm_score": 3, "selected": false, "text": "wav %.* for filename in *.wav; do mv $filename ${filename%.*}_en.wav; done;" }, { "answer_id": 66929918, "author": "botenvouwer", "author_id": 1714329, "author_profile": "https://Stackoverflow.com/users/1714329", "pm_score": 1, "selected": false, "text": "find . -type f -exec bash -c 'echo prefix_${0#./}' {} \\; prefix_ new. find . -type f -exec bash -c 'echo mv $0 new.${0#./}' {} \\; find . -type f -exec bash -c 'echo ${0%.*}_suffix.${0##*.}' {} \\; mv $0 find . -type f -exec bash -c 'mv $0 1.${0#./}' {} \\;" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208181", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9360/" ]
208,184
<p>I'm writing an app in C# (.net 3.5) and I have a question about class design: </p> <p>I'd like to create a class which accesses a file (read, write) and provides its content to the users (instanciators) of the class. The most common operation on an instance will be to retrieve a certain value from the file. The actual read and write (io) operations are faily expensive so I'd like to keep the file data in memory and let all instances access this data. The class is located in an assembly that is used from various applications simultaniously, so I guess I should be worrying about thread safety.</p> <p>How do I design this with respect to thread-safety and unit-testability (for unit-tests, different inputfiles must be used than in operational code)? Any help is greatly appreciated.</p>
[ { "answer_id": 208881, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 1, "selected": false, "text": "public class MyFooBarClass\n{\n private static ReaderWriterLock readerWriterLock = new ReaderWriterLock();\n private static MemoryStream fileMemoryStream;\n\n // other instance members here\n\n public void MyFooBarClass()\n {\n if(fileMemoryStream != null)\n {\n // probably expensive file read here\n }\n\n // initialize instance members here\n }\n\n public byte[] ReadBytes()\n {\n try\n {\n try\n {\n readerWriterLock.AcquireReaderLock(1000);\n //... read bytes here\n return bytesRead;\n }\n finally\n {\n readerWriterLock.ReleaseReaderLock();\n }\n }\n catch(System.ApplicationException ex)\n {\n System.Diagnostics.Debug.WriteLine(ex.Message);\n }\n }\n\n public void WriteBytes(bytes[] bytesToWrite)\n {\n try\n {\n try\n {\n readerWriterLock.AcquireWriterLock(1000);\n //... write bytes here\n }\n finally\n {\n readerWriterLock.ReleaseWriterLock();\n }\n }\n catch(System.ApplicationException ex)\n {\n System.Diagnostics.Debug.WriteLine(ex.Message);\n }\n }\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208184", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16440/" ]
208,186
<p>I'm using a web service that returns a dataset. in this dataset there are 5 table, let's say table A, B, C, D, E. I use table A.</p> <p>So </p> <pre><code>DataTable dt = new DataTable() dt = dataset.Table["A"] </code></pre> <p>Now in this datatable there are columns a1,a2,a3,a4,a5,a6,a7.</p> <p>Let's say I only want to get columns a3 and a4 then bind it to my datagrid.</p> <p>How do I do this?</p>
[ { "answer_id": 208201, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 5, "selected": true, "text": "AutoGenerateColumns false BoundColumns a3 a4" }, { "answer_id": 208205, "author": "Ilya Komakhin", "author_id": 21603, "author_profile": "https://Stackoverflow.com/users/21603", "pm_score": 1, "selected": false, "text": "dgvMain.Columns[ColumnA3_Name].Visible = true;\ndgvMain.Columns[ColumnA1_Name].Visible = false;\n" }, { "answer_id": 208285, "author": "Vivek", "author_id": 7418, "author_profile": "https://Stackoverflow.com/users/7418", "pm_score": 3, "selected": false, "text": "DataGrid DataSet ds;\n\n//Get Data\nusing (SqlConnection connection = new SqlConnection(connectionString))\n {\n // Create the command and set its properties.\n SqlCommand command = new SqlCommand();\n command.Connection = connection;\n command.CommandText = \"GetMyData\";\n command.CommandType = CommandType.StoredProcedure;\n\n ds = connection.ExecuteDataSet();\n }\nif(ds !=null && ds.Tables.Count > 0)\n{\n dg.DataSource = ds.Tables[0];\n // disable autogeneration of columns\n dg.AutoGenerateColumns = false;\n //Hide unecessary columns\n dg.Columns[\"a3\"].Visible = false;\n dg.Columns[\"a4\"].Visible = false;\n}\n" }, { "answer_id": 11022372, "author": "Dominik Ras", "author_id": 311410, "author_profile": "https://Stackoverflow.com/users/311410", "pm_score": 0, "selected": false, "text": "ALTER PROCEDURE ps_Clients_Get\nAS\nBEGIN\n SELECT \n convert(varchar(2000), path) as [Client Folder], \n c.description as [Client Name],\n c.* \n FROM Client c\nEND \nGO\n using (DataTable dt = new DataTable())\n{\n using (OdbcConnection cnDsn = new OdbcConnection(cmLocalTrackingDBDSNAME))\n {\n cnDsn.Open();\n using (OdbcCommand cmdDSN = new OdbcCommand())\n {\n var _with1 = cmdDSN;\n _with1.Connection = cnDsn;\n _with1.CommandType = System.Data.CommandType.StoredProcedure;\n _with1.CommandText = \"{ CALL ps_Clients_Get }\";\n using (OdbcDataAdapter adapter = new OdbcDataAdapter())\n {\n dt.Locale = System.Globalization.CultureInfo.InvariantCulture;\n adapter.SelectCommand = cmdDSN;\n adapter.Fill(dt);\n bindingSourceDataLocation.DataSource = dt;\n dataGridViewDataLocation.AutoGenerateColumns = false;\n\n dataGridViewDataLocation.DataSource = bindingSourceDataLocation;\n }\n }\n cnDsn.Close();\n }\n}\n" }, { "answer_id": 19114890, "author": "lokendra jayaswal", "author_id": 553088, "author_profile": "https://Stackoverflow.com/users/553088", "pm_score": 1, "selected": false, "text": "//It represent name of column for which you want to select records\nstring[] selectedColumns = new[] { \"a3\", \"a4\" }; \n\nDataTable tableWithSelectedColumns = new DataView(dataset.Table[\"A\"]).ToTable(false, selectedColumns);\n" }, { "answer_id": 39923055, "author": "Chris978", "author_id": 6938566, "author_profile": "https://Stackoverflow.com/users/6938566", "pm_score": 0, "selected": false, "text": " Dim DT As DataTable = YourDT\n\n DGV.DataSource = dt\n DGV.AutoGenerateColumns = False\n\n Dim cc = DGV.ColumnCount\n\n For i = 0 To cc - 1\n DGV.Columns(i).Visible = False\n Next\n\n DGV.Columns(\"ColumnToShow\").Visible = True\n DGV.Columns(\"ColumnToShow\").Visible = True\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208186", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23491/" ]
208,231
<p>I want to use the java.util.Preferences API but I don't want my program to attempt to read or write to the Windows registry. How would I go about this?</p>
[ { "answer_id": 208289, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 5, "selected": true, "text": "java.util.Preferences Preference Preferences java.util.prefs.AbstractPreferences de.unika.ipd.grgen.util.MyPreferences import java.util.HashMap;\nimport java.util.Iterator;\nimport java.util.Map;\nimport java.util.prefs.AbstractPreferences;\nimport java.util.prefs.BackingStoreException;\n\n/**\n * Own implementation of the Java preferences API, that does not use\n * a \"OS backing store\" but relies on importing and exporting the\n * preferences via xml files.\n * Also, If a preference is got, but was not in the tree, it is entered.\n */\npublic class MyPreferences extends AbstractPreferences {\n\n private Map<String, String> prefs = new HashMap<String, String>();\n private Map<String, AbstractPreferences> children = new HashMap<String, AbstractPreferences>();\n\n public MyPreferences(MyPreferences parent, String name) {\n super(parent, name);\n }\n\n /**\n * @see java.util.prefs.AbstractPreferences#putSpi(java.lang.String, java.lang.String)\n */\n protected void putSpi(String key, String value) {\n prefs.put(key, value);\n }\n de.tarent.ldap.prefs.LDAPSystemPreferences import java.util.prefs.AbstractPreferences;\nimport java.util.prefs.BackingStoreException;\n\nimport javax.naming.NamingException;\nimport javax.naming.directory.Attributes;\n\nimport de.tarent.ldap.LDAPException;\nimport de.tarent.ldap.LDAPManager;\n\n/**\n * @author kirchner\n * \n * Preferences im LDAP\n */\npublic class LDAPSystemPreferences extends AbstractPreferences {\n LDAPManager ldm = null;\n Properties properties = new Properties();\n //Map für key/value der Preferences\n Map cache = new HashMap();\n //Map für timestamp der Preferences\n Map timestamp = new HashMap();\n private Boolean deleted = Boolean.FALSE;\n com.adito.boot.PropertyPreferences import java.util.prefs.AbstractPreferences;\nimport java.util.prefs.BackingStoreException;\nimport java.util.prefs.Preferences;\n\nimport org.apache.commons.logging.Log;\nimport org.apache.commons.logging.LogFactory;\n\n\n/**\n * A simple implementation for the preferences API. That stores preferences\n * in propery files. We do not have to worry about sharing the preferencese \n * with other JVM instance so there is no need for any kind of synchronising\n * or locking.\n */\npublic class PropertyPreferences extends AbstractPreferences {\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208231", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6583/" ]
208,234
<p>I have a form that kicks off a Response.Redirect to download a file once complete. I also want to hide the form and show a 'thank you' panel before the redirect takes place, however it seems the asp.net engine just does the redirect without doing the 2 tasks before in the following code:</p> <pre><code>if (success) { lblSuccessMessage.Text = _successMessage; showMessage(true); } else { lblSuccessMessage.Text = _failureMessage; showMessage(false); } if(success) Response.Redirect(_downloadURL); </code></pre> <p>Any idea how i can force the page to update before the Redirect kicks in??</p> <p>Thanks heaps Greg</p>
[ { "answer_id": 208247, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 1, "selected": false, "text": "Response.AddHeader(\"Redirect\", \"3; URL=\" + _downloadURL\")\n Response.Redirect() Response.AddHeader()" }, { "answer_id": 208252, "author": "StingyJack", "author_id": 16391, "author_profile": "https://Stackoverflow.com/users/16391", "pm_score": 1, "selected": false, "text": "Response.AddHeader(\"Content-disposition\", \"attachment; filename=\" & myUserFriendlyFileName)\nResponse.ContentType = \"application/octet-stream\"\nResponse.OutputStream.Write(buffer, 0, buffer.Length)\n" }, { "answer_id": 208369, "author": "Robin Bennett", "author_id": 27794, "author_profile": "https://Stackoverflow.com/users/27794", "pm_score": 2, "selected": false, "text": "<script>\n location.href = \"http://otherServerName/fileToDownload\";\n</script>\n <body onload='location.href=\"http://otherServerName/fileToDownload\";'>\n" }, { "answer_id": 209498, "author": "Andy Brudtkuhl", "author_id": 12442, "author_profile": "https://Stackoverflow.com/users/12442", "pm_score": -1, "selected": true, "text": "if (success)\n {\n lblSuccessMessage.Text = _successMessage;\n showMessage(true); \n }\n else\n {\n lblSuccessMessage.Text = _failureMessage;\n showMessage(false);\n }\n\n if(success) {\n Threading.Thread.Sleep(200)\n Response.Redirect(_downloadURL);\n }\n if (success)\n {\n lblSuccessMessage.Text = _successMessage + \"<br /><INPUT TYPE='button' VALUE='Continue...' onClick='parent.location='\" + _downloadURL + \"'/>\";\n showMessage(true); \n }\n else\n {\n lblSuccessMessage.Text = _failureMessage;\n showMessage(false);\n }\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208234", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21969/" ]
208,254
<p>I've just started with opengl but I ran into some strange behaviour.</p> <p>Below I posted code that runs well in xp but on vista it renders just black screen.</p> <p>Sorry for posting unusally (as for this board) long code.</p> <p>Is there something very specific to open gl in vista? Thanks.</p> <pre><code>#include&lt;windows.h&gt; #include&lt;gl\gl.h&gt; #include&lt;gl\glu.h&gt; #pragma comment(lib, "opengl32.lib") #pragma comment(lib, "glu32.lib") void InitGL(void) { glClearColor(1,0.3f,0.3f,0.3f); } void DrawGLScene(void) { /* code removed */ } HGLRC hRC = NULL; HDC hDC = NULL; HWND hWnd = NULL; HINSTANCE hInstance = NULL; LRESULT CALLBACK WndProc(HWND, UINT, WPARAM, LPARAM); bool CreateGLWindow(char* title, int width, int height) { GLuint PixelFormat; WNDCLASS wc; RECT WindowRect; WindowRect.left = (long)0; WindowRect.right = (long)width; WindowRect.top = (long)0; WindowRect.bottom = (long)height; LPCSTR nazwa = TEXT("Start"); hInstance = GetModuleHandle(NULL); wc.style = CS_HREDRAW | CS_VREDRAW | CS_OWNDC; wc.lpfnWndProc = (WNDPROC)WndProc; wc.cbClsExtra = 0; wc.cbWndExtra = 0; wc.hInstance = hInstance; wc.hIcon = LoadIcon(NULL, IDI_WINLOGO); wc.hCursor = LoadCursor(NULL, IDC_ARROW); wc.hbrBackground = NULL; wc.lpszMenuName = NULL; wc.lpszClassName = nazwa; RegisterClass(&amp;wc); hWnd = CreateWindowEx(WS_EX_APPWINDOW | WS_EX_WINDOWEDGE, nazwa, nazwa, WS_SYSMENU | WS_CLIPSIBLINGS | WS_CLIPCHILDREN, 0,0, width, height, NULL, NULL, hInstance, NULL); static PIXELFORMATDESCRIPTOR pfd = { sizeof(PIXELFORMATDESCRIPTOR), 1, PFD_DRAW_TO_WINDOW | PFD_SUPPORT_OPENGL | PFD_DOUBLEBUFFER, PFD_TYPE_RGBA, 32, 0,0,0,0,0,0, 0, 0, 0, 0,0,0,0, 16, 0, 0, PFD_MAIN_PLANE, 0, 0,0,0 }; hDC = GetDC(hWnd); PixelFormat = ChoosePixelFormat(hDC, &amp;pfd); HRESULT rez = SetPixelFormat(hDC, PixelFormat, &amp;pfd); hRC = wglCreateContext(hDC); wglMakeCurrent(hDC, hRC); ShowWindow(hWnd, SW_SHOW); InitGL(); return true; } LRESULT CALLBACK WndProc(HWND hWnd, UINT uMsg, WPARAM wParam, LPARAM lParam) { switch(uMsg) { case WM_ACTIVATE: { return 0; } case WM_CLOSE: { PostQuitMessage(0); return 0; } } return DefWindowProc(hWnd, uMsg, wParam, lParam); } int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) { MSG msg; bool done = false; if (!CreateGLWindow(NULL, 800,600)) { return 0; } while(!done) { if (PeekMessage(&amp;msg, NULL, 0, 0, PM_NOREMOVE)) { if (!GetMessage(&amp;msg, 0, 0, 0)) done = true; else { TranslateMessage(&amp;msg); DispatchMessage(&amp;msg); } } else { DrawGLScene(); SwapBuffers(hDC); } } return (msg.wParam); } </code></pre>
[ { "answer_id": 208318, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "PFD_SUPPORT_COMPOSITION DescribePixelFormat glGetString(GL_RENDERER);" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208254", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25587/" ]
208,261
<p>Ok, so I want to get a webapp running in tomcat (5.5) to run behind apache 2 (2.2.3 to be precise) serving from the root of the site (i.e. without the context), with static content being served via apache.</p> <p>So if the app is running under "<code>/myapp</code>" on tomcat I want to use apache (plus <code>mod_rewrite</code>) to make it behave as if it's running under "<code>/</code>" instead.</p> <p><code>Mod_jk</code> is setup and working ok. I can access the app from "<code>/myapp</code>", but I can't quite get the last bit working. Below is the config I've got for <code>mod_rewrite</code> to try and get this working. It correctly gets rewrites <code>/static/</code> urls to get apache to serve them from the unpacked webapp and if I enable the rewrite log I see that it does attempt to pass through all other requests to <code>/myapp</code> via <code>mod_jk</code>. However it seems that mod_jk is not processing the request afterwards.</p> <pre> <code> JkMount /myapp/* worker1 RewriteEngine On # ensure static stuff gets served by apache RewriteRule ^/static/(.*)$ /var/lib/tomcat5.5/webapps/myapp/static/$1 [L] # everything else should go through tomcat RewriteRule ^/(.*)$ /myapp/$1 [L,PT] </code> </pre> <p>When I've done this with apache 1 in the past I've had to make sure <code>mod_jk</code> get's loaded before <code>mod_rewrite</code>, but I can't seem to achieve this under apache 2. Any thoughts? How do other people usually do this?</p>
[ { "answer_id": 208407, "author": "Leonel Martins", "author_id": 26673, "author_profile": "https://Stackoverflow.com/users/26673", "pm_score": -1, "selected": false, "text": "RewriteRule ^/(.*)$ /myapp/$1 [L,R]\n JkMount /* worker1\nJkUnmount /static/* worker1\n mod_jk mod_rewrite +ForwardURICompatUnparsed" }, { "answer_id": 208549, "author": "John Montgomery", "author_id": 5868, "author_profile": "https://Stackoverflow.com/users/5868", "pm_score": 2, "selected": true, "text": "\nJkOptions +ForwardURICompat\n mod_jk" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208261", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5868/" ]
208,262
<p>I've created a jQuery wee plugin for myself which takes care of showing, hiding and submitting a form to give in-place editing. Currently I have several of these on a page which function independently and I am happy. However, I'm thinking that an 'Edit All' might be useful. I'd therefore want to be able to access all instances of the plugin within the page and access their show/hide/validate/submit functions in unison. Is there a way to do this?</p>
[ { "answer_id": 208284, "author": "jammus", "author_id": 984, "author_profile": "https://Stackoverflow.com/users/984", "pm_score": 0, "selected": false, "text": "var plugins = new Array();\n\nplugins.push($('first_editable_section').pluginThing());\nplugins.push($('second_editable_section').pluginThing());\n" }, { "answer_id": 213931, "author": "Josh Bush", "author_id": 1672, "author_profile": "https://Stackoverflow.com/users/1672", "pm_score": 4, "selected": true, "text": "(function($) { \n $.fn.myPlugin = function() { \n return this.each(function(){ \n\n //Plugin Code Goes Here\n\n $(this).bind(\"pluginEdit\",function(){\n internalEditFunction();\n }); \n });\n };\n})(jQuery);\n $(selector).trigger(\"pluginEdit\");\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/984/" ]
208,263
<p>I have a dev and a UAT environments. Dev is in our place, UAT is in client's place.</p> <p>Our DEV machine is a XEON 4 core @2,33GHz, 4Go RAM with Windows server 2003 The UAT physical machine is quite the same but a virtual machine is used (under VMWare). I don't know the exact parameters used for this VM.</p> <p>The problem is that the SQL Server on the dev machine runs very well and the one on the UAT is very very slow.</p> <p>Opening SQL Server Management Studio takes 2 minutes on the UAT machine. Runing even a simple select request is also very slow. The database is quite small (6 GB). Opening any other application on that server works well.</p> <p>So we think there is a problem with the sql server instance and I must investigate to find the reason.</p> <p>Here is what I checked :</p> <ul> <li>server configuration is similar to the one we have on DEV.</li> <li>there is enough space on disk</li> <li>processors are not overloaded (10% used is the max reached)</li> <li>memory seems also to be OK.</li> <li>data and log files are set to grow automatically</li> <li>SQL Server Recovery model : FULL</li> </ul> <p>It seems in the database log that this error occured at least once (I only have access to a small part) :</p> <blockquote> <p>2008-10-14 19:16:54.84 spid55<br> Autogrow of file 'xxxxx_log' in database 'xxxxxx' was cancelled by user or timed out after 6766 milliseconds. Use ALTER DATABASE to set a smaller FILEGROWTH value for this file or to explicitly set a new file size.</p> </blockquote> <p>As there is enough space on the hard drive, what could be the cause ? Could it be related to my perfs problem ? What should I check to find the cause of the problem ?</p> <p>I'm not a SqlServer expert so if someone has any suggestion, I'd love to hear it. Thanks !</p> <hr> <p><strong>Update 1 :</strong><br> SQL Server Recovery model : FULL<br> The database is new so so far we didn't performed any backup.<br> I don't know the log file size, I'll check that. </p> <p><strong>Update 2 :</strong><br> The Management Studio problem is solved.</p> <p>It's caused by the fact that there is not Internet access on the server and that Management Studio seems to try to connect when starting : <a href="http://weblogs.sqlteam.com/tarad/archive/2006/10/05/13676.aspx" rel="nofollow noreferrer">http://weblogs.sqlteam.com/tarad/archive/2006/10/05/13676.aspx</a></p> <p>But it seems that the perf problem is not linked to that problem. Still searching.</p>
[ { "answer_id": 208284, "author": "jammus", "author_id": 984, "author_profile": "https://Stackoverflow.com/users/984", "pm_score": 0, "selected": false, "text": "var plugins = new Array();\n\nplugins.push($('first_editable_section').pluginThing());\nplugins.push($('second_editable_section').pluginThing());\n" }, { "answer_id": 213931, "author": "Josh Bush", "author_id": 1672, "author_profile": "https://Stackoverflow.com/users/1672", "pm_score": 4, "selected": true, "text": "(function($) { \n $.fn.myPlugin = function() { \n return this.each(function(){ \n\n //Plugin Code Goes Here\n\n $(this).bind(\"pluginEdit\",function(){\n internalEditFunction();\n }); \n });\n };\n})(jQuery);\n $(selector).trigger(\"pluginEdit\");\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208263", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28544/" ]
208,272
<p>I have seen this macro defined before but never really knew its purpose. Can anyone shed light on this?</p>
[ { "answer_id": 208511, "author": "JayG", "author_id": 5823, "author_profile": "https://Stackoverflow.com/users/5823", "pm_score": 4, "selected": true, "text": " /* Get DTMF index */\n switch(dtmf)\n {\n case '0':\n case '1':\n case '2':\n case '3':\n case '4':\n case '5':\n case '6':\n case '7':\n case '8':\n case '9':\n /* Handle numeric DTMF */\n index = dtmf - '0';\n break;\n case 'A':\n case 'B':\n case 'C':\n case 'D':\n index = dtmf - 'A' + 10;\n break:\n default:\n _never_executed();\n break;\n }\n" }, { "answer_id": 209273, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "__assume() int main(int p)\n{\n switch(p){\n case 1:\n func1(1);\n break;\n case 2:\n func1(-1);\n break;\n default:\n __assume(0);\n // This tells the optimizer that the default\n // cannot be reached. As so, it does not have to generate\n // the extra code to check that 'p' has a value \n // not represented by a case arm. This makes the switch \n // run faster.\n }\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208272", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ]
208,306
<p>i know that i can get stacktrace by using Thread.getAllStackTraces()(it returns Map, but clear does not work). When I run recursion method i can get exception because of stacktrace being too big, is there any way to clear it?</p>
[ { "answer_id": 208655, "author": "Pierre", "author_id": 24449, "author_profile": "https://Stackoverflow.com/users/24449", "pm_score": -1, "selected": false, "text": "ulimit ulimit -s 8000\n ulimit -s unlimited\n struct ClearStack {} ;\n\nvoid myLongComputationWhichCausesStackOverflow() {\n // do something\n if (needsToClearTheStack)\n throw ClearStack() ;\n // do something else\n}\n\nint main(int ac, char *av[]) {\n try {\n mylongcomputation() ;\n // continuation of program\n // no stack clearing occurred\n }\n catch(const ClearStack & cs) {\n // the stack was cleared and do something appropriately\n }\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
208,316
<p>How can I tell if an App is ASP.NET 2.0 or ASP.NET 1.1. This is in C#</p> <p>I don't have the source code and I don't have access to IIS Manager. But I can ftp and check the ASPX files. Any Ideas?</p>
[ { "answer_id": 208319, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 4, "selected": true, "text": "<%@ Page Language=\"C#\" EnableSessionState=\"False\" EnableViewState=\"False\" Trace=\"False\" Debug=\"False\" %>\n\n<script language=\"C#\" runat=\"server\">\n\nprotected void Page_Load(object s, EventArgs e)\n{\n Response.Write(System.Environment.Version);\n}\n</script>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208316", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3208/" ]
208,333
<p>I took a wsp file, and did my <strong>stsadm -o addsolution</strong> like usual. Then I went into <em>central administration->solution management</em> and it showed up just fine. Then I deployed the web part, no problems so far.</p> <p>The problem is when I go to add it to the webpart gallery (<em>Web Part Gallery: New Web Parts</em>) usually the web part is in the list, I check the box next to it and click <strong>populate gallery</strong> but it is not showing up in the list? Could I be missing something in my manifest.xml to cause this? I just wrote and deployed another web part this <em>exact</em> same way and it went fine. Also, I wrote a dummy webpart that does nothing but print "working" and tried it with that getting the same results. </p> <p>Any ideas?</p>
[ { "answer_id": 208499, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 1, "selected": false, "text": "string cmd_StsAdm = @\"C:\\Program files\\Common files\\Microsoft Shared\\web server extensions\\12\\BIN\\stsadm.exe\";\nstring url_Site = \"http://localhost\";\nstring url_Web = \"http://localhost\";\nif ( string.IsNullOrEmpty( url_Web ) ) { url_Web = url_Web; }\n\nConsole.WriteLine( \"Deleting sharepoint solution\" );\nstring args_DeleteSolution = string.Format( \"-o deletesolution -name \\\"{0}\\\" -override\", startInfo.fileNameWsp );\nShellWait( cmd_StsAdm, args_DeleteSolution );\n\nstring filePathWsp = \"**** path to wsp file ****\";\nConsole.WriteLine( \"Adding sharepoint solution\" );\nstring args_AddSolution = string.Format( \"-o addsolution -filename \\\"{0}\\\"\", filePathWsp );\nShellWait( cmd_StsAdm, args_AddSolution );\n\nConsole.WriteLine( \"Deploy sharepoint solution\" );\nstring args_DeploySolution = \"-o deploysolution -name \\\"{0}\\\" -local -allowGacDeployment -url \\\"{1}\\\" -force\";\nargs_DeploySolution = string.Format( args_DeploySolution, startInfo.fileNameWsp, url_Web );\nShellWait( cmd_StsAdm, args_DeploySolution );\n\nint counter = 0;\nforeach ( CWebPartVytvoreniInfo wpRslt in solutionInfo.WebParts ) {\n counter++;\n string msg = string.Format( \"Aktivace web part {0} - {1} z {2}\", wpRslt.Info.Nazev, counter, solutionInfo.WebParts.Count );\n Console.WriteLine( msg );\n string args_ActivateFeature = \"-o activatefeature -id {0} -url {1}\";\n args_ActivateFeature = string.Format( args_ActivateFeature, wpRslt.Info.ID, url_Site );\n ShellWait( cmd_StsAdm, args_ActivateFeature );\n}\n\nConsole.WriteLine( \"Connecting to sharepoint site\" );\nusing ( Microsoft.SharePoint.SPSite site = new Microsoft.SharePoint.SPSite( url_Site ) ) {\n Microsoft.SharePoint.SPList ctg_WebParts = site.GetCatalog( Microsoft.SharePoint.SPListTemplateType.WebPartCatalog );\n\n counter = 0;\n foreach ( WebPartInfo wpInfo in solutionInfo.WebParts ) {\n counter++;\n string dirPath = System.IO.Path.Combine( wpInfo.DirectoryPath );\n string fileName = wpRslt.Info.Nazev + \".webpart\";\n string filePath = System.IO.Path.Combine( dirPath, fileName );\n\n string msg = string.Format( \"Uploading file '{0}' - {1} z {2}\", fileName, counter, solutionInfo.WebParts.Count );\n Console.WriteLine( msg );\n using ( System.IO.FileStream fstrm = OtevritSoubor( filePath ) ) {\n ctg_WebParts.RootFolder.Files.Add( fileName, fstrm, true );\n }\n }\n}\n" }, { "answer_id": 14378240, "author": "Mariusz Ignatowicz", "author_id": 1813219, "author_profile": "https://Stackoverflow.com/users/1813219", "pm_score": 2, "selected": false, "text": ".feature > Manifest" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14777/" ]
208,355
<p>This is a follow up from this <a href="https://stackoverflow.com/questions/198087/how-do-i-list-installed-msi-from-the-command-line">question</a>.</p> <p>I'm using this slightly modified script to enumerate all installed MSI packages:</p> <pre><code>strComputer = "." Set objWMIService = GetObject("winmgmts:" &amp; _ "{impersonationLevel=impersonate}!\\" &amp; _ strComputer &amp; _ "\root\cimv2") Set colSoftware = objWMIService.ExecQuery _ ("SELECT * FROM Win32_Product") If colSoftware.Count &gt; 0 Then For Each objSoftware in colSoftware WScript.Echo objSoftware.Caption &amp; vbtab &amp; _ objSoftware.Version Next Else WScript.Echo "Cannot retrieve software from this computer." End If </code></pre> <p>What is surprising however, is its abysmal performance. Enumerating the 34 installed MSI packages on my XP box takes between 3 and 5 minutes !</p> <p>By comparison, the Linux box that sits besides is taking 7s to enumerate 1400+ RPMs... <em>sigh</em></p> <p>Any clues on this ?</p>
[ { "answer_id": 15538973, "author": "Stephen Quan", "author_id": 881441, "author_profile": "https://Stackoverflow.com/users/881441", "pm_score": 1, "selected": false, "text": "Dim installer\nSet installer = CreateObject(\"WindowsInstaller.Installer\")\nDim productCode, productName\nFor Each productCode In installer.Products\n productName = installer.ProductInfo(productCode, \"ProductName\")\n WScript.Echo productCode & \" , \" & productName\nNext\n Installer" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208355", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11892/" ]
208,367
<p>I'm trying to create a custom JSP tag that would take an array object and display the elements of the tag in an HTML table. Does anyone have suggestions on how to do this?</p>
[ { "answer_id": 15538973, "author": "Stephen Quan", "author_id": 881441, "author_profile": "https://Stackoverflow.com/users/881441", "pm_score": 1, "selected": false, "text": "Dim installer\nSet installer = CreateObject(\"WindowsInstaller.Installer\")\nDim productCode, productName\nFor Each productCode In installer.Products\n productName = installer.ProductInfo(productCode, \"ProductName\")\n WScript.Echo productCode & \" , \" & productName\nNext\n Installer" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208367", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28557/" ]
208,368
<p>How can I set the font used by the FLVPlaybackCaptioning component for subtitles? Using the style property of the textarea does nothing, and using a TextFormat makes the text go blank, even though the font had been embedded.</p>
[ { "answer_id": 208585, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 3, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n <tt xml:lang=\"en\" xmlns=\"http://www.w3.org/2006/04/ttaf1\" xmlns:tts=\"http://www.w3.org/2006/04/ttaf1#styling\">\n <head>\n <styling>\n <style id=\"1\" tts:textAlign=\"right\"/>\n <style id=\"2\" tts:color=\"transparent\"/>\n <style id=\"3\" style=\"2\" tts:backgroundColor=\"white\"/>\n <style id=\"4\" style=\"2 3\" tts:fontSize=\"20\"/>\n </styling>\n </head>\n <body>\n <div xml:lang=\"en\">\n <p begin=\"00:00:00.50\" dur=\"500ms\">Four score and twenty years ago</p>\n <p begin=\"00:00:02.50\"><span tts:fontFamily=\"monospaceSansSerif,proportionalSerif,TheOther\"tts:fontSize=\"+2\">our forefathers</span> brought forth<br /> on this continent</p>\n <p begin=\"00:00:04.40\" dur=\"10s\" style=\"1\">a <span tts:fontSize=\"12 px\">new</span> <span tts:fontSize=\"300%\">nation</span></p>\n <p begin=\"00:00:06.50\" dur=\"3\">conceived in <span tts:fontWeight=\"bold\" tts:color=\"#ccc333\">liberty</span> <span tts:color=\"#ccc333\">and dedicated to</span> the proposition</p>\n <p begin=\"00:00:11.50\" tts:textAlign=\"right\">that <span tts:fontStyle=\"italic\">all</span> men are created equal.</p>\n <p begin=\"15s\" style=\"4\">The end.</p>\n </div> \n </body>\n </tt>\n" }, { "answer_id": 2858582, "author": "Trevor Boyle", "author_id": 344169, "author_profile": "https://Stackoverflow.com/users/344169", "pm_score": 1, "selected": false, "text": "myFLVPlybkcap.addEventListener(CaptionTargetEvent.CAPTION_TARGET_CREATED, captionTargetCreatedHandler);\n private function captionTargetCreatedHandler(e:CaptionTargetEvent):void{\n var myTextFormat:TextFormat = new TextFormat();\n myTextFormat.font = \"Arial\";\n myTextFormat.color = 0x00FF00;\n myTextFormat.size = 18;\n (e.captionTarget as TextField).defaultTextFormat = myTextFormat; \n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208368", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15371/" ]
208,373
<p>We need to write unit tests for a <em>wxWidgets</em> application using <em>Google Test Framework</em>. The problem is that <em>wxWidgets</em> uses the macro <strong>IMPLEMENT_APP(MyApp)</strong> to initialize and enter the application main loop. This macro creates several functions including <strong>int main()</strong>. The google test framework also uses macro definitions for each test. </p> <p>One of the problems is that it is not possible to call the wxWidgets macro from within the test macro, because the first one creates functions.. So, we found that we could replace the macro with the following code:</p> <pre><code>wxApp* pApp = new MyApp(); wxApp::SetInstance(pApp); wxEntry(argc, argv); </code></pre> <p>That's a good replacement, but wxEntry() call enters the original application loop. If we don't call wxEntry() there are still some parts of the application not initialized.</p> <p>The question is how to initialize everything required for a wxApp to run, without actually running it, so we are able to unit test portions of it?</p>
[ { "answer_id": 210742, "author": "antik", "author_id": 1625, "author_profile": "https://Stackoverflow.com/users/1625", "pm_score": -1, "selected": false, "text": "IMPLEMENT_APP_NO_MAIN // Use this macro if you want to define your own main() or WinMain() function\n// and call wxEntry() from there.\n#define IMPLEMENT_APP_NO_MAIN(appname) \\\n wxAppConsole *wxCreateApp() \\\n { \\\n wxAppConsole::CheckBuildOptions(WX_BUILD_OPTIONS_SIGNATURE, \\\n \"your program\"); \\\n return new appname; \\\n } \\\n wxAppInitializer \\\n wxTheAppInitializer((wxAppInitializerFunction) wxCreateApp); \\\n DECLARE_APP(appname) \\\n appname& wxGetApp() { return *wx_static_cast(appname*, wxApp::GetInstance()); }\n" }, { "answer_id": 212953, "author": "kbluck", "author_id": 13402, "author_profile": "https://Stackoverflow.com/users/13402", "pm_score": 4, "selected": true, "text": "bool wxEntryStart(int& argc, wxChar **argv)\n wxTheApp->CallOnInit() void wxEntryCleanup()\n" }, { "answer_id": 920518, "author": "Daniel Paull", "author_id": 43066, "author_profile": "https://Stackoverflow.com/users/43066", "pm_score": 4, "selected": false, "text": "// MyWxApp derives from wxApp\nwxApp::SetInstance( new MyWxApp() );\nwxEntryStart( argc, argv );\nwxTheApp->CallOnInit();\n\n// you can create top level-windows here or in OnInit()\n...\n// do your testing here\n\nwxTheApp->OnRun();\nwxTheApp->OnExit();\nwxEntryCleanup();\n" }, { "answer_id": 19295901, "author": "Byllgrim", "author_id": 2867010, "author_profile": "https://Stackoverflow.com/users/2867010", "pm_score": 3, "selected": false, "text": "IMPLEMENT_APP_NO_MAIN(MyApp);\nIMPLEMENT_WX_THEME_SUPPORT;\n\nint main(int argc, char *argv[])\n{\n wxEntryStart( argc, argv );\n wxTheApp->CallOnInit();\n wxTheApp->OnRun();\n\n return 0;\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208373", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446104/" ]
208,381
<p>What is the difference between <strong><em>anonymous methods</em></strong> of C# 2.0 and <strong><em>lambda expressions</em></strong> of C# 3.0.?</p>
[ { "answer_id": 208410, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": false, "text": "Expression<T> Func<int,bool> Func<int,bool> isEven = i => i % 2 == 0;\nExpression<Func<int,bool>> isEven = i => i % 2 == 0;\n Expression Action a = () => { Console.WriteLine(obj.ToString()); };\n" }, { "answer_id": 208782, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": false, "text": "public event EventHandler Click = delegate{};\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208381", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4021/" ]
208,404
<p>Are C# enums typesafe?</p> <p>If not what are the implications? </p>
[ { "answer_id": 208523, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "enum Foo { A = 1, B = 2, C = 3 } \nstatic void Main()\n{\n Foo foo = (Foo)500; // works fine\n Console.WriteLine(foo); // also fine - shows 500\n}\n default switch [Flags] bool isValid = Enum.IsDefined(typeof(Foo), foo);\n" }, { "answer_id": 208997, "author": "John Rudy", "author_id": 14048, "author_profile": "https://Stackoverflow.com/users/14048", "pm_score": 0, "selected": false, "text": "Flags" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208404", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24773/" ]
208,411
<p>I am adding a context menu using <code>QAction</code> for a widget. Now, there is some white space beside the text of the action. I assume this is the space where the <code>QIcon</code> association with the <code>QAction</code> should have been there. Now how do I hide this space. I tried doing:</p> <pre><code>action-&gt;setIcon(QIcon()); </code></pre> <p>but still does not seem to work.</p> <p>Kindly let me know if you have the way to remove that space before the text.</p>
[ { "answer_id": 210756, "author": "Chris Roland", "author_id": 27975, "author_profile": "https://Stackoverflow.com/users/27975", "pm_score": -1, "selected": false, "text": "QAction::QAction ( const QString & text, QObject * parent )" }, { "answer_id": 220213, "author": "Andy Brice", "author_id": 455552, "author_profile": "https://Stackoverflow.com/users/455552", "pm_score": 1, "selected": false, "text": "qt_mac_set_menubar_icons( false );\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11212/" ]
208,421
<p>How can I have a view render a partial (user control) from a different folder? With preview 3 I used to call RenderUserControl with the complete path, but whith upgrading to preview 5 this is not possible anymore. Instead we got the RenderPartial method, but it's not offering me the functionality I'm looking for.</p>
[ { "answer_id": 208448, "author": "Elijah Manor", "author_id": 4481, "author_profile": "https://Stackoverflow.com/users/4481", "pm_score": 10, "selected": true, "text": "@Html.Partial(\"~/Views/AnotherFolder/Messages.cshtml\", ViewData.Model.Successes)\n <% Html.RenderPartial(\"~/Views/AnotherFolder/Messages.ascx\", ViewData.Model.Successes); %>\n" }, { "answer_id": 220350, "author": "Andrew Stanton-Nurse", "author_id": 29813, "author_profile": "https://Stackoverflow.com/users/29813", "pm_score": 2, "selected": false, "text": "<%Html.RenderPartial(\"~/Views/Account/myPartial.ascx\");%>" }, { "answer_id": 3126876, "author": "Rahatur", "author_id": 218408, "author_profile": "https://Stackoverflow.com/users/218408", "pm_score": 3, "selected": false, "text": "<%Html.RenderPartial(\"~/Views/Account/myPartial.ascx\");%>\n" }, { "answer_id": 4639143, "author": "mounir", "author_id": 568761, "author_profile": "https://Stackoverflow.com/users/568761", "pm_score": 0, "selected": false, "text": "~/Views/Shared/parts/UMFview.ascx\n ~/Views/" }, { "answer_id": 6181762, "author": "Siva Kandaraj", "author_id": 716368, "author_profile": "https://Stackoverflow.com/users/716368", "pm_score": -1, "selected": false, "text": "RenderAction(\"myPartial\",\"Account\");" }, { "answer_id": 12398005, "author": "Jacob", "author_id": 119549, "author_profile": "https://Stackoverflow.com/users/119549", "pm_score": 3, "selected": false, "text": "HtmlHelper public static IDisposable ControllerContextRegion(\n this HtmlHelper html, \n string controllerName)\n{\n return new ControllerContextRegion(html.ViewContext.RouteData, controllerName);\n}\n ControllerContextRegion internal class ControllerContextRegion : IDisposable\n{\n private readonly RouteData routeData;\n private readonly string previousControllerName;\n\n public ControllerContextRegion(RouteData routeData, string controllerName)\n {\n this.routeData = routeData;\n this.previousControllerName = routeData.GetRequiredString(\"controller\");\n this.SetControllerName(controllerName);\n }\n\n public void Dispose()\n {\n this.SetControllerName(this.previousControllerName);\n }\n\n private void SetControllerName(string controllerName)\n {\n this.routeData.Values[\"controller\"] = controllerName;\n }\n}\n @using (Html.ControllerContextRegion(\"Foo\")) {\n // Html.Action, Html.Partial, etc. now looks things up as though\n // FooController was our controller.\n}\n controller" }, { "answer_id": 14125317, "author": "Aaron Sherman", "author_id": 1560273, "author_profile": "https://Stackoverflow.com/users/1560273", "pm_score": 5, "selected": false, "text": "@Html.Partial(\"../MyViewFolder/Partials/_PartialView\", Model.MyObject)\n" }, { "answer_id": 28991614, "author": "Paul", "author_id": 630407, "author_profile": "https://Stackoverflow.com/users/630407", "pm_score": 5, "selected": false, "text": "public class NewViewEngine : RazorViewEngine {\n\n private static readonly string[] NEW_PARTIAL_VIEW_FORMATS = new[] {\n \"~/Views/Foo/{0}.cshtml\",\n \"~/Views/Shared/Bar/{0}.cshtml\"\n };\n\n public NewViewEngine() {\n // Keep existing locations in sync\n base.PartialViewLocationFormats = base.PartialViewLocationFormats.Union(NEW_PARTIAL_VIEW_FORMATS).ToArray();\n }\n}\n ViewEngines.Engines.Add(new NewViewEngine());\n" }, { "answer_id": 56444287, "author": "Demian Berisford-Maynard", "author_id": 6193118, "author_profile": "https://Stackoverflow.com/users/6193118", "pm_score": 0, "selected": false, "text": "_options.ViewLocationFormats public ViewEngineResult FindView(ActionContext context, string viewName, bool isMainPage)\n {\n var controllerName = context.GetNormalizedRouteValue(CONTROLLER_KEY);\n var areaName = context.GetNormalizedRouteValue(AREA_KEY);\n\n var checkedLocations = new List<string>();\n foreach (var location in _options.ViewLocationFormats)\n {\n var view = string.Format(location, viewName, controllerName);\n if (File.Exists(view))\n {\n return ViewEngineResult.Found(\"Default\", new View(view, _ViewRendering));\n }\n checkedLocations.Add(view);\n }\n\n return ViewEngineResult.NotFound(viewName, checkedLocations);\n }\n" }, { "answer_id": 61232216, "author": "Theophilus", "author_id": 2615878, "author_profile": "https://Stackoverflow.com/users/2615878", "pm_score": 3, "selected": false, "text": "<partial name=\"~/Views/Folder/_PartialName.cshtml\" />\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208421", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11333/" ]
208,433
<p>Very basic question: how do I write a <code>short</code> literal in C++?</p> <p>I know the following:</p> <ul> <li><code>2</code> is an <code>int</code></li> <li><code>2U</code> is an <code>unsigned int</code></li> <li><code>2L</code> is a <code>long</code></li> <li><code>2LL</code> is a <code>long long</code></li> <li><code>2.0f</code> is a <code>float</code></li> <li><code>2.0</code> is a <code>double</code></li> <li><code>'\2'</code> is a <code>char</code>.</li> </ul> <p>But how would I write a <code>short</code> literal? I tried <code>2S</code> but that gives a compiler warning.</p>
[ { "answer_id": 208446, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 8, "selected": true, "text": "((short)2)\n a = 2L;\nb = 2.0;\nc = (short)2;\nd = '\\2';\n movl $2, _a\nmovl $2, _b\nmovl $2, _c\nmovl $2, _d\n" }, { "answer_id": 209313, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": false, "text": "stdint.h /* 7.18.4.1 Macros for minimum-width integer constants\n\n Accoding to Douglas Gwyn <gwyn@arl.mil>:\n \"This spec was changed in ISO/IEC 9899:1999 TC1; in ISO/IEC\n 9899:1999 as initially published, the expansion was required\n to be an integer constant of precisely matching type, which\n is impossible to accomplish for the shorter types on most\n platforms, because C99 provides no standard way to designate\n an integer constant with width less than that of type int.\n TC1 changed this to require just an integer constant\n *expression* with *promoted* type.\"\n*/\n" }, { "answer_id": 12152296, "author": "Ken Smith", "author_id": 385892, "author_profile": "https://Stackoverflow.com/users/385892", "pm_score": 6, "selected": false, "text": "#include <cstdint>\n\ninline std::uint16_t operator \"\" _u(unsigned long long value)\n{\n return static_cast<std::uint16_t>(value);\n}\n\nvoid func(std::uint32_t value); // 1\nvoid func(std::uint16_t value); // 2\n\nfunc(0x1234U); // calls 1\nfunc(0x1234_u); // calls 2\n\n// also\ninline std::int16_t operator \"\" _s(unsigned long long value)\n{\n return static_cast<std::int16_t>(value);\n}\n" }, { "answer_id": 29735864, "author": "jimvonmoon", "author_id": 1578824, "author_profile": "https://Stackoverflow.com/users/1578824", "pm_score": 4, "selected": false, "text": "short(2)\n" }, { "answer_id": 30627005, "author": "Alexander Revo", "author_id": 3811791, "author_profile": "https://Stackoverflow.com/users/3811791", "pm_score": 5, "selected": false, "text": "auto var1 = 10i8; // char\nauto var2 = 10ui8; // unsigned char\n\nauto var3 = 10i16; // short\nauto var4 = 10ui16; // unsigned short\n\nauto var5 = 10i32; // int\nauto var6 = 10ui32; // unsigned int\n\nauto var7 = 10i64; // long long\nauto var8 = 10ui64; // unsigned long long\n" }, { "answer_id": 65004693, "author": "P. Saladin", "author_id": 8510645, "author_profile": "https://Stackoverflow.com/users/8510645", "pm_score": 3, "selected": false, "text": "short{42};\n auto number1 = short(100000); // Oops: Stores -31072, you may get a warning\nauto number2 = short{100000}; // Compiler error. Value too large for type short\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208433", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
208,436
<p>When I plug my HP Laserjet 3015, Windows detects the correct model and then tries to install the appropriate drivers.</p> <p>How can I detect the model of connected printer(s)? I don't want to use the list of installed printers because a Zebra printer can be installed with a Generic/Text only driver.</p> <p>I'm a Delphi and C# programmer, so any tips in any language will be appreciated.</p>
[ { "answer_id": 208503, "author": "Roman Ganz", "author_id": 17981, "author_profile": "https://Stackoverflow.com/users/17981", "pm_score": 2, "selected": false, "text": "TComboBox TMemo unit Unit1;\n\ninterface\n\nuses\n Windows, StdCtrls, Classes, Controls, Forms;\n\ntype\n TForm1 = class(TForm)\n ComboBox1: TComboBox;\n Memo1: TMemo;\n procedure ComboBox1Change(Sender: TObject);\n procedure FormCreate(Sender: TObject);\n private\n { Private declarations }\n public\n { Public declarations }\n end;\n\nvar\n Form1: TForm1;\n\nimplementation\n\n{$R *.dfm}\n\nuses\n Printers, WinSpool, SysUtils;\n\ntype\n _DRIVER_INFO_6A = record\n cVersion: DWORD;\n pName: PAnsiChar; \n pEnvironment: PAnsiChar; \n pDriverPath: PAnsiChar; \n pDataFile: PAnsiChar; \n pConfigFile: PAnsiChar; \n pHelpFile: PAnsiChar; \n pDependentFiles: PAnsiChar; \n pMonitorName: PAnsiChar; \n pDefaultDataType: PAnsiChar; \n pszzPreviousNames: PAnsiChar;\n ftDriverDate: TFileTime;\n dwlDriverVersion: Int64;\n pszMfgName: PAnsiChar;\n pszOEMUrl: PAnsiChar;\n pszHardwareID: PAnsiChar;\n pszProvider: PAnsiChar;\n end;\n TDriverInfo6A = _DRIVER_INFO_6A;\n PDriverInfo6A = ^TDriverInfo6A;\n PDriverInfo6 = PDriverInfo6A;\n\nprocedure TForm1.FormCreate(Sender: TObject);\nbegin\n ComboBox1.Items.Assign(Printer.Printers);\n ComboBox1.ItemIndex := 0;\n ComboBox1Change(nil);\nend;\n\nfunction FileTimeToDateTime(ft: TFileTime): TDateTime;\nvar\n st: TSystemTime;\n lt: TFileTime;\nbegin\n FillChar(st, SizeOf(st), 0);\n FillChar(lt, SizeOf(lt), 0);\n FileTimeToLocalFileTime(ft, lt);\n FileTimeToSystemTime(lt, st);\n result := SystemTimeToDateTime(st);\nend;\n\nprocedure TForm1.ComboBox1Change(Sender: TObject);\nvar\n hPrinter: THandle;\n PrtName: String;\n DriverInfo: PDriverInfo6;\n dwNeeded: DWORD;\nbegin\n Memo1.Clear;\n PrtName := Combobox1.Text;\n OpenPrinter(PChar(PrtName), hPrinter, nil);\n DriverInfo := nil;\n try\n GetPrinterDriver(hPrinter, nil, 6, DriverInfo, 0, dwNeeded);\n GetMem(DriverInfo, dwNeeded);\n try\n if GetPrinterDriver(hPrinter, nil, 6, DriverInfo, dwNeeded, dwNeeded) then begin\n Memo1.Lines.Add('cVersion: ' + IntToStr(DriverInfo.cVersion));\n Memo1.Lines.Add('pName: '+StrPas(DriverInfo.pName));\n Memo1.Lines.Add('pEnvironment: '+StrPas(DriverInfo.pEnvironment));\n Memo1.Lines.Add('pDriverPath: '+StrPas(DriverInfo.pDriverPath));\n Memo1.Lines.Add('pDataFile: '+StrPas(DriverInfo.pDataFile));\n Memo1.Lines.Add('pConfigFile: '+StrPas(DriverInfo.pConfigFile));\n Memo1.Lines.Add('pHelpFile: '+StrPas(DriverInfo.pHelpFile));\n Memo1.Lines.Add('pDependentFiles: '+StrPas(DriverInfo.pDependentFiles));\n Memo1.Lines.Add('pMonitorName: '+StrPas(DriverInfo.pMonitorName));\n Memo1.Lines.Add('pDefaultDataType: '+StrPas(DriverInfo.pDefaultDataType));\n Memo1.Lines.Add('pszzPreviousNames: '+StrPas(DriverInfo.pszzPreviousNames));\n Memo1.Lines.Add('ftDriverDate: '+DateTimeToStr(FileTimeToDateTime(DriverInfo.ftDriverDate)));\n Memo1.Lines.Add('dwlDriverVersion: '+IntToStr(DriverInfo.dwlDriverVersion));\n Memo1.Lines.Add('pszMfgName: '+StrPas(DriverInfo.pszMfgName));\n Memo1.Lines.Add('pszOEMUrl: '+StrPas(DriverInfo.pszOEMUrl));\n Memo1.Lines.Add('pszHardwareID: '+StrPas(DriverInfo.pszHardwareID));\n Memo1.Lines.Add('pszProvider: '+StrPas(DriverInfo.pszProvider));\n end else\n Memo1.Lines.Add('No Info needed = ' + IntToStr(dwNeeded));\n finally\n FreeMem(DriverInfo);\n end;\n finally\n ClosePrinter(hPrinter);\n end;\nend;\n\nend.\n GetDriverNameByOSPrinterName pName" }, { "answer_id": 558133, "author": "Ovi Tisler", "author_id": 64238, "author_profile": "https://Stackoverflow.com/users/64238", "pm_score": 3, "selected": false, "text": "~HI\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17766/" ]
208,468
<p>What issues or refactoring did you have to do when you upgraded from ASP.NET MVC Preview 5 to the newly released <a href="http://www.microsoft.com/downloads/details.aspx?familyid=a24d1e00-cd35-4f66-baa0-2362bdde0766&amp;displaylang=en&amp;tm" rel="nofollow noreferrer">Beta</a> version?</p>
[ { "answer_id": 208883, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": true, "text": "<add namespace=\"System.Web.Mvc.Html\"/> [AcceptVerbs(HttpVerbs.Post | HttpVerbs.Put)] \npublic ActionResult Update() {...\n}\n public ActionResult Edit() { \n //... \n} \n\n[AcceptVerbs(HttpVerbs.Post)] \npublic ActionResult Edit(FormCollection form) { \n //...\n}\n" }, { "answer_id": 209347, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "CS0234: The type or namespace name 'Mvc' does not exist in the namespace 'System.Web' (are you missing an assembly reference?)" }, { "answer_id": 210439, "author": "JarrettV", "author_id": 16340, "author_profile": "https://Stackoverflow.com/users/16340", "pm_score": 3, "selected": false, "text": "<add assembly=\"System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/>\n" }, { "answer_id": 216597, "author": "Søren Pedersen", "author_id": 379419, "author_profile": "https://Stackoverflow.com/users/379419", "pm_score": 2, "selected": false, "text": "public class GuestbookEntryBinder : IModelBinder\n {\n #region IModelBinder Members\n\n public object GetValue(ControllerContext controllerContext, string modelName, Type modelType, ModelStateDictionary modelState)\n {\n if (modelType == typeof(GuestbookEntry))\n {\n return new GuestbookEntry\n {\n Name = controllerContext.HttpContext.Request.Form[\"name\"] ?? \"\",\n Website = controllerContext.HttpContext.Request.Form[\"website\"] ?? \"\",\n Message = controllerContext.HttpContext.Request.Form[\"message\"] ?? \"\",\n };\n }\n return null;\n }\n #endregion\n }\n #region IModelBinder Members\n\npublic ModelBinderResult BindModel(ModelBindingContext bindingContext)\n{\n throw new NotImplementedException();\n}\n\n#endregion\n" }, { "answer_id": 218985, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 0, "selected": false, "text": "Html.Form<FooController>(c => c.Bar(), FormMethod.Post, new Hash(@class => \"foobar\"))\n <%@ Import Namespace=\"FormMethod=Microsoft.Web.Mvc.FormMethod\"%>\n" }, { "answer_id": 219014, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 0, "selected": false, "text": "Method not found: 'Void System.Web.Mvc.UrlHelper..ctor(System.Web.Mvc.ViewContext)'\n <%=Html.Image(\"~/Content/Images/logo.jpg\") %>\n <img src=\"<%=Html.ResolveUrl(\"~/Content/Images/logo_350.jpg\")%>\" />\n" }, { "answer_id": 219181, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 1, "selected": false, "text": "<%=Html.TextBox(\"Name\", new Hash(@class => \"required\"))%>\n <%=Html.TextBox(\"Name\")%>\n <%=Html.TextBox(\"Name\", ViewData.Model.Name, new Hash(@class => \"required\"))%>\n <%=Html.TextBox(\"Name\", ViewData.Model == null ? null : ViewData.Model.Name, new Hash(@class => \"required\"))%>\n" }, { "answer_id": 225236, "author": "CraftyFella", "author_id": 30317, "author_profile": "https://Stackoverflow.com/users/30317", "pm_score": 2, "selected": false, "text": "<assemblies> <add assembly=\"System.Web.Mvc, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35\"/> \n <namespaces> <add namespace=\"System.Web.Mvc.Html\"/>\n <%using (Html.Form()) <%using (Html.BeginForm()) System.Web.Mvc.Html;" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4481/" ]
208,469
<p>I have multiple RequireFieldValidators on my aspx page.</p> <p>On the backend (C#) I want to be able to tell which control specifically wasn't valid so I can apply a style to that control. I use the Page.IsValid method to see if the overall page passed validation but I need to know specifically which one control failed. </p>
[ { "answer_id": 208541, "author": "Nikki9696", "author_id": 456669, "author_profile": "https://Stackoverflow.com/users/456669", "pm_score": 3, "selected": true, "text": "If (Me.IsPostBack) Then\nMe.Validate()\nIf (Not Me.IsValid) Then\n Dim msg As String\n ' Loop through all validation controls to see which \n ' generated the error(s).\n Dim oValidator As IValidator\n For Each oValidator In Validators\n If oValidator.IsValid = False Then\n msg = msg & \"<br />\" & oValidator.ErrorMessage\n End If\n Next\n Label1.Text = msg\nEnd If\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208469", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4144/" ]
208,471
<p>I'm using jQuery to hide and show elements when a radio button group is altered/clicked. It works fine in browsers like Firefox, but in IE 6 and 7, the action only occurs when the user then clicks somewhere else on the page.</p> <p>To elaborate, when you load the page, everything looks fine. In Firefox, if you click a radio button, one table row is hidden and the other one is shown immediately. However, in IE 6 and 7, you click the radio button and nothing will happen until you click somewhere on the page. Only then does IE redraw the page, hiding and showing the relevant elements.</p> <p>Here's the jQuery I'm using:</p> <pre><code>$(document).ready(function () { $(".hiddenOnLoad").hide(); $("#viewByOrg").change(function () { $(".visibleOnLoad").show(); $(".hiddenOnLoad").hide(); }); $("#viewByProduct").change(function () { $(".visibleOnLoad").hide(); $(".hiddenOnLoad").show(); }); }); </code></pre> <p>Here's the part of the XHTML that it affects. The whole page validates as XHTML 1.0 Strict.</p> <pre><code>&lt;tr&gt; &lt;td&gt;View by:&lt;/td&gt; &lt;td&gt; &lt;p&gt; &lt;input type="radio" name="viewBy" id="viewByOrg" value="organisation" checked="checked" /&gt;Organisation&lt;/p&gt; &lt;p&gt; &lt;input type="radio" name="viewBy" id="viewByProduct" value="product" /&gt;Product&lt;/p&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr class="visibleOnLoad"&gt; &lt;td&gt;Organisation:&lt;/td&gt; &lt;td&gt; &lt;select name="organisation" id="organisation" multiple="multiple" size="10"&gt; &lt;option value="1"&gt;Option 1&lt;/option&gt; &lt;option value="2"&gt;Option 2&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; &lt;tr class="hiddenOnLoad"&gt; &lt;td&gt;Product:&lt;/td&gt; &lt;td&gt; &lt;select name="product" id="product" multiple="multiple" size="10"&gt; &lt;option value="1"&gt;Option 1&lt;/option&gt; &lt;option value="2"&gt;Option 2&lt;/option&gt; &lt;/select&gt; &lt;/td&gt; &lt;/tr&gt; </code></pre> <p>If anyone has any ideas why this is happening and how to fix it, they would be very much appreciated!</p>
[ { "answer_id": 208488, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 8, "selected": true, "text": ".click .change" }, { "answer_id": 208491, "author": "Chris Zwiryk", "author_id": 734, "author_profile": "https://Stackoverflow.com/users/734", "pm_score": 1, "selected": false, "text": "onclick $(document).ready(function(){\n\n $(\".hiddenOnLoad\").hide();\n\n $(\"#viewByOrg\").change(function () {\n $(\".visibleOnLoad\").show();\n $(\".hiddenOnLoad\").hide();\n });\n\n $(\"#viewByOrg\").click(function () {\n $(\".visibleOnLoad\").show();\n $(\".hiddenOnLoad\").hide();\n });\n\n $(\"#viewByProduct\").change(function () {\n $(\".visibleOnLoad\").hide();\n $(\".hiddenOnLoad\").show();\n }); \n\n $(\"#viewByProduct\").click(function () {\n $(\".visibleOnLoad\").hide();\n $(\".hiddenOnLoad\").show();\n }); \n});\n" }, { "answer_id": 208515, "author": "Pier Luigi", "author_id": 27789, "author_profile": "https://Stackoverflow.com/users/27789", "pm_score": 3, "selected": false, "text": "$(document).ready(function(){\n $(\".hiddenOnLoad\").hide();\n var evt = $.browser.msie ? \"click\" : \"change\";\n $(\"#viewByOrg\").bind(evt, function () {\n $(\".visibleOnLoad\").show();\n $(\".hiddenOnLoad\").hide();\n });\n\n $(\"#viewByProduct\").bind(evt, function () {\n $(\".visibleOnLoad\").hide();\n $(\".hiddenOnLoad\").show();\n }); \n});\n" }, { "answer_id": 231342, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "$(document).ready(function(){\n $(\".hiddenOnLoad\").hide();\n $(\"#viewByOrg, #viewByProduct\").bind(($.browser.msie ? \"click\" : \"change\"), function () {\n $(\".visibleOnLoad\").show();\n $(\".hiddenOnLoad\").hide();\n });\n});\n" }, { "answer_id": 1080243, "author": "Mark A. Nicolosi", "author_id": 1103052, "author_profile": "https://Stackoverflow.com/users/1103052", "pm_score": 6, "selected": false, "text": "click change change blur() click change // This is the hack for IE\nif ($.browser.msie) {\n $(\"#viewByOrg\").click(function() {\n this.blur();\n this.focus();\n });\n}\n\n$(\"#viewByOrg\").change(function() {\n // Do stuff here\n});\n" }, { "answer_id": 1256261, "author": "Ken Egozi", "author_id": 123921, "author_profile": "https://Stackoverflow.com/users/123921", "pm_score": 0, "selected": false, "text": "if ($.browser.msie) {\n var interval = 50;\n var changeHack = 'change-hac';\n var select = $(\"#viewByOrg\");\n select.data(changeHack) = select.val();\n var checkVal=function() {\n var oldVal = select.data(changeHack);\n var newVal = select.val();\n if (oldVal !== newVal) {\n select.data(changeHack, newVal);\n select.trigger('change')\n }\n setTimeout(changeHack, interval);\n }\n setTimeout(changeHack, interval);\n}\n\n$(\"#viewByOrg\").change(function() {\n // Do stuff here\n});\n" }, { "answer_id": 1639696, "author": "Kevin", "author_id": 198406, "author_profile": "https://Stackoverflow.com/users/198406", "pm_score": 5, "selected": false, "text": "$(\"#viewByOrg\").bind($.browser.msie? 'propertychange': 'change', function(e) {\n e.preventDefault(); // Your code here \n}); \n" }, { "answer_id": 2355282, "author": "fabrice", "author_id": 216828, "author_profile": "https://Stackoverflow.com/users/216828", "pm_score": 2, "selected": false, "text": "$(\"#myinput\").change(function() { \"alert('I changed')\" });\n $(\"#myinput\").attr(\"onChange\", \"alert('I changed')\");\n" }, { "answer_id": 2713812, "author": "paul", "author_id": 155753, "author_profile": "https://Stackoverflow.com/users/155753", "pm_score": 2, "selected": false, "text": "if($.browser.msie) {\n $(\"#viewByOrg\").click(function() {\n $(this).change();\n });\n}\n if($.browser.msie) {\n $(\"input, select\").click(function() {\n $(this).change();\n });\n $(\"input, textarea\").keyup(function() {\n $(this).change();\n });\n}\n" }, { "answer_id": 3177218, "author": "RainChen", "author_id": 130353, "author_profile": "https://Stackoverflow.com/users/130353", "pm_score": 0, "selected": false, "text": "$(\"#viewByOrg\")\n .attr('onChange', $.browser.msie ? \"$(this).data('onChange').apply(this)\" : \"\")\n .change( function(){if(!$.browser.msie)$(this).data('onChange').apply(this)} )\n .data('onChange',function(){alert('put your codes here')});\n" }, { "answer_id": 3471668, "author": "dovidweisz", "author_id": 280595, "author_profile": "https://Stackoverflow.com/users/280595", "pm_score": 3, "selected": false, "text": "jQuery.fn.radioChange = function(newFn){\n this.bind(jQuery.browser.msie? \"click\" : \"change\", newFn);\n}\n $(function(){\n $(\"radioBtnSelector\").radioChange(function(){\n //do stuff\n });\n});\n" }, { "answer_id": 3483685, "author": "Jeoff Wilks", "author_id": 255794, "author_profile": "https://Stackoverflow.com/users/255794", "pm_score": 1, "selected": false, "text": "if($.browser.msie && $.browser.version < 8)\n $('input[type=radio],[type=checkbox]').live('click', function(){\n $(this).trigger('change');\n });\n" }, { "answer_id": 4923595, "author": "Jongosi", "author_id": 606747, "author_profile": "https://Stackoverflow.com/users/606747", "pm_score": 0, "selected": false, "text": "<form id='filterIt' action='' method='post'>\n <select id='val' name='val'>\n <option value='1'>One</option>\n <option value='2'>Two</option>\n <option value='6'>Six</option>\n </select>\n <input type=\"submit\" value=\"go\" />\n</form>\n $('#val').change(function(){\n $('#filterIt').submit();\n});\n" }, { "answer_id": 6298463, "author": "kiev", "author_id": 59508, "author_profile": "https://Stackoverflow.com/users/59508", "pm_score": 0, "selected": false, "text": "//global\nvar prev_value = \"\"; \n\n$(document).ready(function () {\n\n if (jQuery.browser.msie && $.browser.version < 8)\n $('input:not(:submit):not(:button):not(:hidden), select, textarea').bind(\"focus\", function () { \n prev_value = $(this).val();\n\n }).bind(\"blur\", function () { \n if($(this).val() != prev_value)\n has_changes = true;\n });\n}\n" }, { "answer_id": 7889288, "author": "Bas Matthee", "author_id": 808445, "author_profile": "https://Stackoverflow.com/users/808445", "pm_score": 1, "selected": false, "text": "$(SELECTOR).change(function() {\n // Shizzle\n});\n" }, { "answer_id": 11292093, "author": "nostop", "author_id": 1495818, "author_profile": "https://Stackoverflow.com/users/1495818", "pm_score": 1, "selected": false, "text": "(function($) {\n $('input[type=checkbox], input[type=radio]').live('click', function() {\n var $this = $(this);\n setTimeout(function() {\n $this.trigger('changeIE'); \n }, 10) \n });\n})(jQuery);\n\n$(selector).bind($.browser.msie && $.browser.version <= 8 ? 'changeIE' : 'change', function() {\n // do whatever you want\n})\n" }, { "answer_id": 14248785, "author": "Bilal Jalil", "author_id": 1370811, "author_profile": "https://Stackoverflow.com/users/1370811", "pm_score": 0, "selected": false, "text": ".bind($.browser.msie ? 'click' : 'change', function(event) {\n" }, { "answer_id": 37541986, "author": "Dayanand Rupanavar", "author_id": 6403896, "author_profile": "https://Stackoverflow.com/users/6403896", "pm_score": 0, "selected": false, "text": "$(\"#checkboxid\").**change**(function () {\n\n});\n $(\"#checkboxid\").**each**(function () {\n\n});\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208471", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21709/" ]
208,484
<p>I have a PHP website backed by a MySQL database and a small team of programmers submitting code to subversion. Typically we write code, test it locally, commit to subversion and then copy changed files to a hidden area for online testing.</p> <p>However mistakes can be made. Occasionally I want to refresh the site so that I know, without a doubt, that the site code and database really represents what's in subversion. I'd like to get as close to a one click solution as possible so that it's foolproof.</p> <p>What's the best way to do that?</p> <p>BTW, if it matters, we develop on windows machines.</p>
[ { "answer_id": 208572, "author": "Lucas Oman", "author_id": 6726, "author_profile": "https://Stackoverflow.com/users/6726", "pm_score": 0, "selected": false, "text": "svn export svn checkout" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28565/" ]
208,490
<p>I came across the function <a href="http://msdn.microsoft.com/en-us/library/ms683590(VS.85).aspx" rel="noreferrer" title="MSDN Link">InterlockedExchange</a> and was wondering when I should use this function. In my opinion, setting a 32 Bit value on an x86 processor should always be atomic? <br/> In the case where I want to use the function, the new value does not depend on the old value (it is not an increment operation). Could you provide an example where this method is mandatory (I'm not looking for InterlockedCompareExchange)</p>
[ { "answer_id": 208535, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 4, "selected": false, "text": "InterlockedExchange InterlockedExchange InterlockedExchange" }, { "answer_id": 208543, "author": "moonshadow", "author_id": 11834, "author_profile": "https://Stackoverflow.com/users/11834", "pm_score": 4, "selected": false, "text": "InterlockedExchange" }, { "answer_id": 208547, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 2, "selected": false, "text": "mov eax,dword ptr [a] \nmov dword ptr [b],eax \n" }, { "answer_id": 5985234, "author": "helmk", "author_id": 751479, "author_profile": "https://Stackoverflow.com/users/751479", "pm_score": 2, "selected": false, "text": "a = i;\ni = 9;\ni = a;\ni = a + 9;\na = i + 9;\nif(0 == i)\n a = i++; //a = InterlockedExchange(&i, i + 1);\n if(0 == i++) //if(0 == InterlockedExchange(&i, i + 1))\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208490", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28572/" ]
208,493
<p>Is it possible to search every field of every table for a particular value in Oracle?</p> <p>There are hundreds of tables with thousands of rows in some tables so I know this could take a very long time to query. But the only thing I know is that a value for the field I would like to query against is <code>1/22/2008P09RR8</code>. &lt;</p> <p>I've tried using this statement below to find an appropriate column based on what I think it should be named but it returned no results.</p> <pre><code>SELECT * from dba_objects WHERE object_name like '%DTN%' </code></pre> <p>There is absolutely no documentation on this database and I have no idea where this field is being pulled from.</p> <p>Any thoughts?</p>
[ { "answer_id": 208548, "author": "jim", "author_id": 27628, "author_profile": "https://Stackoverflow.com/users/27628", "pm_score": 3, "selected": false, "text": "select column_name from all_tab_columns c, user_all_tables u where c.table_name = u.table_name;\n v$session v$sqlarea" }, { "answer_id": 208637, "author": "diciu", "author_id": 2811, "author_profile": "https://Stackoverflow.com/users/2811", "pm_score": 3, "selected": false, "text": "echo \"select table_name from user_tables;\" | sqlplus -S user/pwd | grep -v \"^--\" | grep -v \"TABLE_NAME\" | grep \"^[A-Z]\" | while read sw;\ndo echo \"desc $sw\" | sqlplus -S user/pwd | grep -v \"\\-\\-\\-\\-\\-\\-\" | awk -F' ' '{print $1}' | while read nw;\ndo echo \"select * from $sw where $nw='val'\";\ndone;\ndone;\n select * from TBL1 where DESCRIPTION='val'\nselect * from TBL1 where ='val'\nselect * from TBL2 where Name='val'\nselect * from TBL2 where LNG_ID='val'\n table_name user_tables" }, { "answer_id": 208892, "author": "Dave Costa", "author_id": 6568, "author_profile": "https://Stackoverflow.com/users/6568", "pm_score": 8, "selected": true, "text": "SELECT * from dba_objects WHERE\nobject_name like '%DTN%'\n SELECT owner, table_name, column_name FROM all_tab_columns WHERE column_name LIKE '%DTN%';\n SET SERVEROUTPUT ON SIZE 100000\n\n DECLARE\n match_count INTEGER;\n BEGIN\n FOR t IN (SELECT owner, table_name, column_name\n FROM all_tab_columns\n WHERE owner <> 'SYS' and data_type LIKE '%CHAR%') LOOP\n\n EXECUTE IMMEDIATE\n 'SELECT COUNT(*) FROM ' || t.owner || '.' || t.table_name ||\n ' WHERE '||t.column_name||' = :1'\n INTO match_count\n USING '1/22/2008P09RR8';\n\n IF match_count > 0 THEN\n dbms_output.put_line( t.table_name ||' '||t.column_name||' '||match_count );\n END IF;\n\n END LOOP;\n\n END;\n /\n SELECT * FROM table1\n WHERE column1 = 'value'\n OR column2 = 'value'\n OR column3 = 'value'\n ...\n ;\n" }, { "answer_id": 5114486, "author": "Flood", "author_id": 633692, "author_profile": "https://Stackoverflow.com/users/633692", "pm_score": 5, "selected": false, "text": "SET SERVEROUTPUT ON SIZE 100000\n\nDECLARE\n match_count INTEGER;\n-- Type the owner of the tables you are looking at\n v_owner VARCHAR2(255) :='ENTER_USERNAME_HERE';\n\n-- Type the data type you are look at (in CAPITAL)\n-- VARCHAR2, NUMBER, etc.\n v_data_type VARCHAR2(255) :='VARCHAR2';\n\n-- Type the string you are looking at\n v_search_string VARCHAR2(4000) :='string to search here...';\n\nBEGIN\n FOR t IN (SELECT table_name, column_name FROM all_tab_cols where owner=v_owner and data_type = v_data_type) LOOP\n\n EXECUTE IMMEDIATE \n 'SELECT COUNT(*) FROM '||t.table_name||' WHERE '||t.column_name||' = :1'\n INTO match_count\n USING v_search_string;\n\n IF match_count > 0 THEN\n dbms_output.put_line( t.table_name ||' '||t.column_name||' '||match_count );\n END IF;\n\n END LOOP;\nEND;\n/\n" }, { "answer_id": 7516413, "author": "xojins", "author_id": 664493, "author_profile": "https://Stackoverflow.com/users/664493", "pm_score": 3, "selected": false, "text": "DECLARE\n match_count INTEGER;\n-- Type the owner of the tables you are looking at\n v_owner VARCHAR2(255) :='OWNER_NAME';\n\n-- Type the data type you are look at (in CAPITAL)\n-- VARCHAR2, NUMBER, etc.\n v_data_type VARCHAR2(255) :='VARCHAR2';\n\n-- Type the string you are looking at\n v_search_string VARCHAR2(4000) :='%lower-search-sub-string%';\n\nBEGIN\n FOR t IN (SELECT table_name, column_name FROM all_tab_cols where owner=v_owner and data_type = v_data_type) LOOP\n\n EXECUTE IMMEDIATE \n 'SELECT COUNT(*) FROM '||t.table_name||' WHERE lower('||t.column_name||') like :1'\n INTO match_count\n USING v_search_string;\n\n IF match_count > 0 THEN\n dbms_output.put_line( t.table_name ||' '||t.column_name||' '||match_count );\n END IF;\n\n END LOOP;\nEND;\n/\n" }, { "answer_id": 8091300, "author": "Hemanth", "author_id": 1024038, "author_profile": "https://Stackoverflow.com/users/1024038", "pm_score": 2, "selected": false, "text": " CREATE or REPLACE PROCEDURE SEARCH_DB(SEARCH_STR IN VARCHAR2, TAB_COL_RECS OUT VARCHAR2) IS\n match_count integer;\n qry_str varchar2(1000);\n CURSOR TAB_COL_CURSOR IS \n SELECT TABLE_NAME,COLUMN_NAME,OWNER,DATA_TYPE FROM ALL_TAB_COLUMNS WHERE DATA_TYPE in ('NUMBER','VARCHAR2') AND OWNER='SCOTT';\n BEGIN \n FOR TAB_COL_REC IN TAB_COL_CURSOR\n LOOP\n qry_str := 'SELECT COUNT(*) FROM '||TAB_COL_REC.OWNER||'.'||TAB_COL_REC.TABLE_NAME|| \n ' WHERE '||TAB_COL_REC.COLUMN_NAME;\n IF TAB_COL_REC.DATA_TYPE = 'NUMBER' THEN\n qry_str := qry_str||'='||SEARCH_STR; \n ELSE\n qry_str := qry_str||' like '||SEARCH_STR; \n END IF;\n --dbms_output.put_line( qry_str );\n EXECUTE IMMEDIATE qry_str INTO match_count;\n IF match_count > 0 THEN \n dbms_output.put_line( qry_str );\n --dbms_output.put_line( TAB_COL_REC.TABLE_NAME ||' '||TAB_COL_REC.COLUMN_NAME ||' '||match_count); \n TAB_COL_RECS := TAB_COL_RECS||'@@'||TAB_COL_REC.TABLE_NAME||'##'||TAB_COL_REC.COLUMN_NAME;\n END IF; \n END LOOP;\n END SEARCH_DB; \n DECLARE\n SEARCH_STR VARCHAR2(200);\n TAB_COL_RECS VARCHAR2(200);\n BEGIN\n SEARCH_STR := 10;\n SEARCH_DB(\n SEARCH_STR => SEARCH_STR,\n TAB_COL_RECS => TAB_COL_RECS\n );\n DBMS_OUTPUT.PUT_LINE('TAB_COL_RECS = ' || TAB_COL_RECS);\n END;\n Connecting to the database test.\nSELECT COUNT(*) FROM SCOTT.EMP WHERE DEPTNO=10\nSELECT COUNT(*) FROM SCOTT.DEPT WHERE DEPTNO=10\nTAB_COL_RECS = @@EMP##DEPTNO@@DEPT##DEPTNO\nProcess exited.\nDisconnecting from the database test.\n" }, { "answer_id": 9614022, "author": "Mike Rodey", "author_id": 27284, "author_profile": "https://Stackoverflow.com/users/27284", "pm_score": 3, "selected": false, "text": " set serveroutput on size 100000\n\ndeclare\n v_match_count integer;\n v_counter integer;\n\n -- The owner of the tables to search through (case-sensitive)\n v_owner varchar2(255) := 'OWNER_NAME';\n -- A string that is part of the data type(s) of the columns to search through (case-insensitive)\n v_data_type varchar2(255) := 'CHAR';\n -- The string to be searched for (case-insensitive)\n v_search_string varchar2(4000) := 'FIND_ME';\n\n -- Store the SQL to execute for each table in a CLOB to get around the 32767 byte max size for a VARCHAR2 in PL/SQL\n v_sql clob := '';\nbegin\n for cur_tables in (select owner, table_name from all_tables where owner = v_owner and table_name in \n (select table_name from all_tab_columns where owner = all_tables.owner and data_type like '%' || upper(v_data_type) || '%')\n order by table_name) loop\n v_counter := 0;\n v_sql := '';\n\n for cur_columns in (select column_name from all_tab_columns where \n owner = v_owner and table_name = cur_tables.table_name and data_type like '%' || upper(v_data_type) || '%') loop\n if v_counter > 0 then\n v_sql := v_sql || ' or ';\n end if;\n v_sql := v_sql || 'upper(' || cur_columns.column_name || ') like ''%' || upper(v_search_string) || '%''';\n v_counter := v_counter + 1;\n end loop;\n\n v_sql := 'select count(*) from ' || cur_tables.table_name || ' where ' || v_sql;\n\n execute immediate v_sql\n into v_match_count;\n\n if v_match_count > 0 then\n dbms_output.put_line('Match in ' || cur_tables.owner || ': ' || cur_tables.table_name || ' - ' || v_match_count || ' records');\n end if;\n end loop;\n\n exception\n when others then\n dbms_output.put_line('Error when executing the following: ' || dbms_lob.substr(v_sql, 32600));\nend;\n/\n" }, { "answer_id": 13192755, "author": "umesh", "author_id": 1793822, "author_profile": "https://Stackoverflow.com/users/1793822", "pm_score": 2, "selected": false, "text": "Declare\n\nowner VARCHAR2(1000);\ntbl VARCHAR2(1000);\ncnt number;\nct number;\nstr_sql varchar2(1000);\nreason varchar2(1000);\nx varchar2(1000):='%string_to_be_searched%';\n\ncursor csr is select owner,table_name \nfrom all_tables where table_name ='table_name';\n\ntype rec1 is record (\nct VARCHAR2(1000));\n\ntype rec is record (\nowner VARCHAR2(1000):='',\ntable_name VARCHAR2(1000):='');\n\nrec2 rec;\nrec3 rec1;\nbegin\n\nfor rec2 in csr loop\n\n--str_sql:= 'select count(*) from '||rec.owner||'.'||rec.table_name||' where CTV_REMARKS like '||chr(39)||x||chr(39);\n--dbms_output.put_line(str_sql);\n--execute immediate str_sql\n\nexecute immediate 'select count(*) from '||rec2.owner||'.'||rec2.table_name||' where column_name like '||chr(39)||x||chr(39)\ninto rec3;\nif rec3.ct <> 0 then\ndbms_output.put_line(rec2.owner||','||rec3.ct);\nelse null;\nend if;\nend loop;\nend;\n" }, { "answer_id": 27794127, "author": "Lalit Kumar B", "author_id": 3989608, "author_profile": "https://Stackoverflow.com/users/3989608", "pm_score": 3, "selected": false, "text": "SQL PL/SQL KING SCOTT SQL> variable val varchar2(10)\nSQL> exec :val := 'KING'\n\nPL/SQL procedure successfully completed.\n\nSQL> SELECT DISTINCT SUBSTR (:val, 1, 11) \"Searchword\",\n 2 SUBSTR (table_name, 1, 14) \"Table\",\n 3 SUBSTR (column_name, 1, 14) \"Column\"\n 4 FROM cols,\n 5 TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select '\n 6 || column_name\n 7 || ' from '\n 8 || table_name\n 9 || ' where upper('\n 10 || column_name\n 11 || ') like upper(''%'\n 12 || :val\n 13 || '%'')' ).extract ('ROWSET/ROW/*') ) ) t\n 14 ORDER BY \"Table\"\n 15 /\n\nSearchword Table Column\n----------- -------------- --------------\nKING EMP ENAME\n\nSQL>\n 20 SCOTT SQL> variable val NUMBER\nSQL> exec :val := 20\n\nPL/SQL procedure successfully completed.\n\nSQL> SELECT DISTINCT SUBSTR (:val, 1, 11) \"Searchword\",\n 2 SUBSTR (table_name, 1, 14) \"Table\",\n 3 SUBSTR (column_name, 1, 14) \"Column\"\n 4 FROM cols,\n 5 TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select '\n 6 || column_name\n 7 || ' from '\n 8 || table_name\n 9 || ' where upper('\n 10 || column_name\n 11 || ') like upper(''%'\n 12 || :val\n 13 || '%'')' ).extract ('ROWSET/ROW/*') ) ) t\n 14 ORDER BY \"Table\"\n 15 /\n\nSearchword Table Column\n----------- -------------- --------------\n20 DEPT DEPTNO\n20 EMP DEPTNO\n20 EMP HIREDATE\n20 SALGRADE HISAL\n20 SALGRADE LOSAL\n\nSQL>\n" }, { "answer_id": 29597017, "author": "iCrazybest", "author_id": 1465252, "author_profile": "https://Stackoverflow.com/users/1465252", "pm_score": 0, "selected": false, "text": " SET SERVEROUTPUT ON SIZE 100000\n\nDECLARE\n v_match_count INTEGER;\n v_counter INTEGER;\n\n\n\n\nv_owner VARCHAR2 (255) := 'VASOA';\nv_search_string VARCHAR2 (4000) := '99999';\nv_data_type VARCHAR2 (255) := 'CHAR';\nv_sql CLOB := '';\n\nBEGIN\n FOR cur_tables\n IN ( SELECT owner, table_name\n FROM all_tables\n WHERE owner = v_owner\n AND table_name IN (SELECT table_name\n FROM all_tab_columns\n WHERE owner = all_tables.owner\n AND data_type LIKE\n '%'\n || UPPER (v_data_type)\n || '%')\n ORDER BY table_name)\n LOOP\n v_counter := 0;\n v_sql := '';\n\n FOR cur_columns\n IN (SELECT column_name, table_name\n FROM all_tab_columns\n WHERE owner = v_owner\n AND table_name = cur_tables.table_name\n AND data_type LIKE '%' || UPPER (v_data_type) || '%')\n LOOP\n IF v_counter > 0\n THEN\n v_sql := v_sql || ' or ';\n END IF;\n\n IF cur_columns.column_name is not null\n THEN\n v_sql :=\n v_sql\n || 'upper('\n || cur_columns.column_name\n || ') ='''\n || UPPER (v_search_string)||'''';\n\n v_counter := v_counter + 1;\n END IF;\n\n END LOOP;\n\n IF v_sql is null\n THEN\n v_sql :=\n 'select count(*) from '\n || v_owner\n || '.'\n || cur_tables.table_name;\n\n END IF;\n\n IF v_sql is not null\n THEN\n v_sql :=\n 'select count(*) from '\n || v_owner\n || '.'\n || cur_tables.table_name\n || ' where '\n || v_sql;\n END IF;\n\n --v_sql := 'select count(*) from ' ||v_owner||'.'|| cur_tables.table_name ||' where '|| v_sql;\n\n\n --dbms_output.put_line(v_sql);\n --DBMS_OUTPUT.put_line (v_sql);\n\n EXECUTE IMMEDIATE v_sql INTO v_match_count;\n\n IF v_match_count > 0\n THEN\n DBMS_OUTPUT.put_line (v_sql);\n dbms_output.put_line('Match in ' || cur_tables.owner || ': ' || cur_tables.table_name || ' - ' || v_match_count || ' records');\n END IF;\n\n END LOOP;\nEXCEPTION\n WHEN OTHERS\n THEN\n DBMS_OUTPUT.put_line (\n 'Error when executing the following: '\n || DBMS_LOB.SUBSTR (v_sql, 32600));\nEND;\n/\n" }, { "answer_id": 44634994, "author": "Alexandru", "author_id": 982639, "author_profile": "https://Stackoverflow.com/users/982639", "pm_score": 1, "selected": false, "text": "DECLARE\n match_count INTEGER;\n -- Type the owner of the tables you want to search.\n v_owner VARCHAR2(255) :='USER';\n -- Type the data type you're looking for (in CAPS). Examples include: VARCHAR2, NUMBER, etc.\n v_data_type VARCHAR2(255) :='VARCHAR2';\n -- Type the string you are looking for.\n v_search_string VARCHAR2(4000) :='Test';\nBEGIN\n dbms_output.put_line( 'Starting the search...' );\n FOR t IN (SELECT table_name, column_name FROM all_tab_cols where owner=v_owner and data_type = v_data_type) LOOP\n EXECUTE IMMEDIATE \n 'SELECT COUNT(*) FROM '||t.table_name||' WHERE LOWER('||t.column_name||') LIKE :1'\n INTO match_count\n USING LOWER('%'||v_search_string||'%');\n IF match_count > 0 THEN\n dbms_output.put_line( t.table_name ||' '||t.column_name||' '||match_count );\n END IF;\n END LOOP;\nEND;\n" }, { "answer_id": 46302478, "author": "Steve Chambers", "author_id": 1063716, "author_profile": "https://Stackoverflow.com/users/1063716", "pm_score": 0, "selected": false, "text": "SELECT DISTINCT (:val) \"Search Value\", TABLE_NAME \"Table\", COLUMN_NAME \"Column\"\nFROM cols,\n TABLE (XMLSEQUENCE (DBMS_XMLGEN.GETXMLTYPE(\n 'SELECT \"' || COLUMN_NAME || '\" FROM \"' || TABLE_NAME || '\" WHERE UPPER(\"'\n || COLUMN_NAME || '\") LIKE UPPER(''%' || :val || '%'')' ).EXTRACT ('ROWSET/ROW/*')))\nORDER BY \"Table\";\n" }, { "answer_id": 47518893, "author": "AKB", "author_id": 706295, "author_profile": "https://Stackoverflow.com/users/706295", "pm_score": 3, "selected": false, "text": "ORA-19202: Error occurred in XML processing\nORA-00904: \"SUCCESS\": invalid identifier\nORA-06512: at \"SYS.DBMS_XMLGEN\", line 288\nORA-06512: at line 1\n19202. 00000 - \"Error occurred in XML processing%s\"\n*Cause: An error occurred when processing the XML function\n*Action: Check the given error message and fix the appropriate problem\n WITH char_cols AS\n (SELECT /*+materialize */ table_name, column_name\n FROM cols\n WHERE data_type IN ('CHAR', 'VARCHAR2'))\nSELECT DISTINCT SUBSTR (:val, 1, 11) \"Searchword\",\n SUBSTR (table_name, 1, 14) \"Table\",\n SUBSTR (column_name, 1, 14) \"Column\"\nFROM char_cols,\n TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select \"'\n || column_name\n || '\" from \"'\n || table_name\n || '\" where upper(\"'\n || column_name\n || '\") like upper(''%'\n || :val\n || '%'')' ).extract ('ROWSET/ROW/*') ) ) t\nORDER BY \"Table\"\n/ \n" }, { "answer_id": 67442934, "author": "Necip Sunmaz", "author_id": 6670104, "author_profile": "https://Stackoverflow.com/users/6670104", "pm_score": 1, "selected": false, "text": "SELECT DISTINCT table_name, column_name, data_type\n FROM user_tab_cols,\n TABLE (xmlsequence (dbms_xmlgen.getxmltype ('select '\n || column_name\n || ' from '\n || table_name\n || ' where lower('\n || column_name\n || ') like lower(''%'\n || 'your_text_here'\n || '%'')' ).extract ('ROWSET/ROW/*') ) ) a\n where table_name not in (\n select distinct table_name\n from user_tab_cols where data_type like 'SDO%'\n or data_type like '%LOB') AND DATA_TYPE = 'VARCHAR2'\n order by table_name, column_name;\n" }, { "answer_id": 68095798, "author": "Senthuja", "author_id": 9585103, "author_profile": "https://Stackoverflow.com/users/9585103", "pm_score": -1, "selected": false, "text": "SELECT last_name\n FROM customer_tab\n WHERE last_name LIKE '%A%';\n SELECT last_name\n FROM customer_tab\n WHERE last_name LIKE 'A_t';\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208493", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2849/" ]
208,518
<p>Does anyone know how I can retrieve the previous JSP URL that a page has come from within a JSP?</p> <p>Can I retrieve this from the session/ request/ response object?</p> <p>Hope this makes sense, Thank you </p>
[ { "answer_id": 208559, "author": "Julien Grenier", "author_id": 23051, "author_profile": "https://Stackoverflow.com/users/23051", "pm_score": 0, "selected": false, "text": "\n public ActionForward action(ActionMapping mapping, ActionForm form,\n HttpServletRequest request, HttpServletResponse response) {\n //do some stuff\n return mapping.getInputForward(); //return to the caller\n }\n" }, { "answer_id": 208588, "author": "Vincent Ramdhanie", "author_id": 27439, "author_profile": "https://Stackoverflow.com/users/27439", "pm_score": 0, "selected": false, "text": "<action name=\"myaction\" class=\"com.me.MyActionClass\">\n <result name=\"success\">${next}</result>\n</action>\n" }, { "answer_id": 218000, "author": "Steve McLeod", "author_id": 2959, "author_profile": "https://Stackoverflow.com/users/2959", "pm_score": 2, "selected": false, "text": "<%= request.getHeader(\"Referer\") %> \n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21004/" ]
208,530
<p>As most of you probably noticed, when uninstalling an MSI package Windows will ask for the original <code>.msi</code> file. Why is that?</p> <p>I can only see disadvantages to that:</p> <ul> <li>not resilient to network changes.</li> <li>not resilient to local disk changes.</li> <li>unexpected by users.</li> <li>typically requires users to leave their desk and start a crusade to get the correct CD.</li> <li>kind of proves installations are not self-contained.</li> <li>promotes the use of unsafe tools such as msizap.</li> <li>which in turn promotes the "next time I'll just use a zip file" mentality.</li> </ul> <p>Could someone shed some light on this?</p>
[ { "answer_id": 208558, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "%WINDIR%\\Installer\\" }, { "answer_id": 1189524, "author": "Stein Åsmul", "author_id": 129130, "author_profile": "https://Stackoverflow.com/users/129130", "pm_score": 6, "selected": true, "text": "MSI design errors anti-virus quarantining system restore tinkering developer system in erroneous state from development work etc..." } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208530", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11892/" ]
208,532
<p>Currently, I'm using:</p> <pre><code>DataTable dt = CreateDataTableInSomeWay(); List&lt;DataRow&gt; list = new List&lt;DataRow&gt;(); foreach (DataRow dr in dt.Rows) { list.Add(dr); } </code></pre> <p>Is there a better/magic way?</p>
[ { "answer_id": 208544, "author": "Kibbee", "author_id": 1862, "author_profile": "https://Stackoverflow.com/users/1862", "pm_score": 5, "selected": false, "text": "List<DataRow> list = new List<DataRow>(dt.Select());\n dt.Select() List" }, { "answer_id": 208550, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": false, "text": "List<DataRow> rows = table.Rows.Cast<DataRow>().ToList();\n" }, { "answer_id": 208683, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 9, "selected": true, "text": "DataTableExtensions.AsEnumerable List<DataRow> IEnumerable<DataRow> Enumerable.ToList IEnumerable<DataRow> sequence = dt.AsEnumerable();\n using System.Linq;\n...\nList<DataRow> list = dt.AsEnumerable().ToList();\n" }, { "answer_id": 697812, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "DBDatatable Dim gList As New List(Of Guid)\ngList.AddRange(DirectCast(DBDataTable.Select(), IEnumerable(Of Guid)))\n" }, { "answer_id": 1102901, "author": "user_v", "author_id": 129206, "author_profile": "https://Stackoverflow.com/users/129206", "pm_score": 2, "selected": false, "text": "DataTable.Select() DataTable.Select(string filterexpression, string sort)" }, { "answer_id": 2447326, "author": "Guilherme Duarte", "author_id": 209880, "author_profile": "https://Stackoverflow.com/users/209880", "pm_score": 3, "selected": false, "text": "dt.Select().ToList()\n" }, { "answer_id": 8525024, "author": "darshan pandya", "author_id": 1100553, "author_profile": "https://Stackoverflow.com/users/1100553", "pm_score": 6, "selected": false, "text": "List<Employee> emp = new List<Employee>();\n\n//Maintaining DataTable on ViewState\n//For Demo only\n\nDataTable dt = ViewState[\"CurrentEmp\"] as DataTable;\n\n//read data from DataTable \n//using lamdaexpression\n\n\nemp = (from DataRow row in dt.Rows\n\n select new Employee\n {\n _FirstName = row[\"FirstName\"].ToString(),\n _LastName = row[\"Last_Name\"].ToString()\n\n }).ToList();\n" }, { "answer_id": 11734042, "author": "Morteza", "author_id": 1863179, "author_profile": "https://Stackoverflow.com/users/1863179", "pm_score": 4, "selected": false, "text": "using System.Data;\n\n\nvar myEnumerable = myDataTable.AsEnumerable();\n\nList<MyClass> myClassList =\n (from item in myEnumerable\n select new MyClass{\n MyClassProperty1 = item.Field<string>(\"DataTableColumnName1\"),\n MyClassProperty2 = item.Field<string>(\"DataTableColumnName2\")\n }).ToList();\n" }, { "answer_id": 12822367, "author": "Stuart", "author_id": 253131, "author_profile": "https://Stackoverflow.com/users/253131", "pm_score": 4, "selected": false, "text": "List<int> ids = (from row in dt.AsEnumerable() select Convert.ToInt32(row[\"ID\"])).ToList();\n" }, { "answer_id": 13737679, "author": "syed ali abbas", "author_id": 1881332, "author_profile": "https://Stackoverflow.com/users/1881332", "pm_score": 2, "selected": false, "text": "DataTable dt; // datatable should contains datacolumns with Id,Name\n\nList<Employee> employeeList=new List<Employee>(); // Employee should contain EmployeeId, EmployeeName as properties\n\nforeach (DataRow dr in dt.Rows)\n{\n employeeList.Add(new Employee{EmployeeId=dr.Id,EmplooyeeName=dr.Name});\n}\n" }, { "answer_id": 17819916, "author": "Nathan", "author_id": 1860737, "author_profile": "https://Stackoverflow.com/users/1860737", "pm_score": 3, "selected": false, "text": "// this is better suited for expensive object creation/initialization\nIEnumerable<Employee> ParseEmployeeTable(DataTable dtEmployees)\n{\n var employees = new ConcurrentBag<Employee>();\n\n Parallel.ForEach(dtEmployees.AsEnumerable(), (dr) =>\n {\n employees.Add(new Employee() \n {\n _FirstName = dr[\"FirstName\"].ToString(),\n _LastName = dr[\"Last_Name\"].ToString()\n });\n });\n\n return employees;\n}\n" }, { "answer_id": 25624546, "author": "Levi", "author_id": 3576274, "author_profile": "https://Stackoverflow.com/users/3576274", "pm_score": 0, "selected": false, "text": "using System.Linq;\n\nDataTable dt = new DataTable(); \ndt = myClass.myMethod(); \nList<object> list = (from row in dt.AsEnumerable() select (row[\"name\"])).ToList();\ncomboBox1.DataSource = list;\n" }, { "answer_id": 29625894, "author": "Bondaryuk Vladimir", "author_id": 4489664, "author_profile": "https://Stackoverflow.com/users/4489664", "pm_score": 4, "selected": false, "text": "public static List<T> DataTableToList<T>(this DataTable table) where T: new()\n{\n List<T> list = new List<T>();\n var typeProperties = typeof(T).GetProperties().Select(propertyInfo => new\n {\n PropertyInfo = propertyInfo,\n Type = Nullable.GetUnderlyingType(propertyInfo.PropertyType) ?? propertyInfo.PropertyType\n }).ToList();\n\n foreach (var row in table.Rows.Cast<DataRow>())\n {\n T obj = new T();\n foreach (var typeProperty in typeProperties)\n {\n object value = row[typeProperty.PropertyInfo.Name];\n object safeValue = value == null || DBNull.Value.Equals(value)\n ? null\n : Convert.ChangeType(value, typeProperty.Type);\n\n typeProperty.PropertyInfo.SetValue(obj, safeValue, null);\n }\n list.Add(obj);\n }\n return list;\n}\n" }, { "answer_id": 29740741, "author": "rajashekar", "author_id": 4809112, "author_profile": "https://Stackoverflow.com/users/4809112", "pm_score": 1, "selected": false, "text": "System.Data .AsEnumerable()" }, { "answer_id": 29877551, "author": "Rahul Garg", "author_id": 3368262, "author_profile": "https://Stackoverflow.com/users/3368262", "pm_score": 4, "selected": false, "text": "public static List<T> ToListof<T>(this DataTable dt)\n{\n const BindingFlags flags = BindingFlags.Public | BindingFlags.Instance;\n var columnNames = dt.Columns.Cast<DataColumn>()\n .Select(c => c.ColumnName)\n .ToList();\n var objectProperties = typeof(T).GetProperties(flags);\n var targetList = dt.AsEnumerable().Select(dataRow =>\n {\n var instanceOfT = Activator.CreateInstance<T>();\n\n foreach (var properties in objectProperties.Where(properties => columnNames.Contains(properties.Name) && dataRow[properties.Name] != DBNull.Value))\n {\n properties.SetValue(instanceOfT, dataRow[properties.Name], null);\n }\n return instanceOfT;\n }).ToList();\n\n return targetList;\n}\n\n\nvar output = yourDataInstance.ToListof<targetModelType>();\n" }, { "answer_id": 35251566, "author": "mrtwin", "author_id": 4976237, "author_profile": "https://Stackoverflow.com/users/4976237", "pm_score": 0, "selected": false, "text": "public class ModelUser\n{\n #region Model\n\n private string _username;\n private string _userpassword;\n private string _useremail;\n private int _userid;\n\n /// <summary>\n /// \n /// </summary>\n public int userid\n {\n set { _userid = value; }\n get { return _userid; }\n }\n\n\n /// <summary>\n /// \n /// </summary>\n\n public string username\n {\n set { _username = value; }\n get { return _username; }\n }\n\n /// <summary>\n /// \n /// </summary>\n public string useremail\n {\n set { _useremail = value; }\n get { return _useremail; }\n }\n\n /// <summary>\n /// \n /// </summary>\n public string userpassword\n {\n set { _userpassword = value; }\n get { return _userpassword; }\n }\n #endregion Model\n}\n\npublic List<ModelUser> DataTableToList(DataTable dt)\n{\n List<ModelUser> modelList = new List<ModelUser>();\n int rowsCount = dt.Rows.Count;\n if (rowsCount > 0)\n {\n ModelUser model;\n for (int n = 0; n < rowsCount; n++)\n {\n model = new ModelUser();\n\n model.userid = (int)dt.Rows[n][\"userid\"];\n model.username = dt.Rows[n][\"username\"].ToString();\n model.useremail = dt.Rows[n][\"useremail\"].ToString();\n model.userpassword = dt.Rows[n][\"userpassword\"].ToString();\n\n modelList.Add(model);\n }\n }\n return modelList;\n}\n\nstatic DataTable GetTable()\n{\n // Here we create a DataTable with four columns.\n DataTable table = new DataTable();\n table.Columns.Add(\"userid\", typeof(int));\n table.Columns.Add(\"username\", typeof(string));\n table.Columns.Add(\"useremail\", typeof(string));\n table.Columns.Add(\"userpassword\", typeof(string));\n\n // Here we add five DataRows.\n table.Rows.Add(25, \"Jame\", \"Jame@hotmail.com\", DateTime.Now.ToString());\n table.Rows.Add(50, \"luci\", \"luci@hotmail.com\", DateTime.Now.ToString());\n table.Rows.Add(10, \"Andrey\", \"Andrey@hotmail.com\", DateTime.Now.ToString());\n table.Rows.Add(21, \"Michael\", \"Michael@hotmail.com\", DateTime.Now.ToString());\n table.Rows.Add(100, \"Steven\", \"Steven@hotmail.com\", DateTime.Now.ToString());\n return table;\n}\n\nprotected void Page_Load(object sender, EventArgs e)\n{\n List<ModelUser> userList = new List<ModelUser>();\n\n DataTable dt = GetTable();\n\n userList = DataTableToList(dt);\n\n gv.DataSource = userList;\n gv.DataBind();\n}[enter image description here][1]\n </asp:GridView>\n</div>\n" }, { "answer_id": 35915879, "author": "Jayaprakash", "author_id": 6038187, "author_profile": "https://Stackoverflow.com/users/6038187", "pm_score": 0, "selected": false, "text": "DataTable List DataTable List DataTable ColumnName Type PropertyName long result = Utilities.ConvertTo<Student>(dt ,out listStudent);\n\n// Generic Method\npublic class Utilities\n{\n public static long ConvertTo<T>(DataTable table, out List<T> entity)\n {\n long returnCode = -1;\n entity = null;\n\n if (table == null)\n {\n return -1;\n }\n\n try\n {\n entity = ConvertTo<T>(table.Rows);\n returnCode = 0;\n }\n\n catch (Exception ex)\n {\n returnCode = 1000;\n }\n\n return returnCode;\n }\n\n static List<T> ConvertTo<T>(DataRowCollection rows)\n {\n List<T> list = null;\n if (rows != null)\n {\n list = new List<T>();\n\n foreach (DataRow row in rows)\n {\n T item = CreateItem<T>(row);\n list.Add(item);\n }\n }\n\n return list;\n }\n\n static T CreateItem<T>(DataRow row)\n {\n string str = string.Empty;\n string strObj = string.Empty;\n\n T obj = default(T);\n\n if (row != null)\n {\n obj = Activator.CreateInstance<T>();\n strObj = obj.ToString();\n NameValueCollection objDictionary = new NameValueCollection();\n\n foreach (DataColumn column in row.Table.Columns)\n {\n PropertyInfo prop = obj.GetType().GetProperty(column.ColumnName);\n\n if (prop != null)\n {\n str = column.ColumnName;\n\n try\n {\n objDictionary.Add(str, row[str].ToString());\n object value = row[column.ColumnName];\n Type vType = obj.GetType();\n\n if (value == DBNull.Value)\n {\n if (vType == typeof(int) || vType == typeof(Int16)\n || vType == typeof(Int32)\n || vType == typeof(Int64)\n || vType == typeof(decimal)\n || vType == typeof(float)\n || vType == typeof(double))\n {\n value = 0;\n }\n\n else if (vType == typeof(bool))\n {\n value = false;\n }\n\n else if (vType == typeof(DateTime))\n {\n value = DateTime.MaxValue;\n }\n\n else\n {\n value = null;\n }\n\n prop.SetValue(obj, value, null);\n }\n\n else\n {\n prop.SetValue(obj, value, null);\n }\n }\n\n catch(Exception ex)\n {\n\n }\n }\n }\n\n PropertyInfo ActionProp = obj.GetType().GetProperty(\"ActionTemplateValue\");\n\n if (ActionProp != null)\n {\n object ActionValue = objDictionary;\n ActionProp.SetValue(obj, ActionValue, null);\n }\n }\n\n return obj;\n }\n}\n" }, { "answer_id": 48518142, "author": "Saurin", "author_id": 8493056, "author_profile": "https://Stackoverflow.com/users/8493056", "pm_score": 2, "selected": false, "text": " /* This is a generic method that will convert any type of DataTable to a List \n * \n * \n * Example : List< Student > studentDetails = new List< Student >(); \n * studentDetails = ConvertDataTable< Student >(dt); \n *\n * Warning : In this case the DataTable column's name and class property name\n * should be the same otherwise this function will not work properly\n */\n public static List<T> ConvertDataTable<T>(DataTable dt)\n {\n List<T> data = new List<T>();\n foreach (DataRow row in dt.Rows)\n {\n T item = GetItem<T>(row);\n data.Add(item);\n }\n return data;\n }\n\n\n private static T GetItem<T>(DataRow dr)\n {\n Type temp = typeof(T);\n T obj = Activator.CreateInstance<T>();\n\n foreach (DataColumn column in dr.Table.Columns)\n {\n foreach (PropertyInfo pro in temp.GetProperties())\n {\n //in case you have a enum/GUID datatype in your model\n //We will check field's dataType, and convert the value in it.\n if (pro.Name == column.ColumnName){ \n try\n {\n var convertedValue = GetValueByDataType(pro.PropertyType, dr[column.ColumnName]);\n pro.SetValue(obj, convertedValue, null);\n }\n catch (Exception e)\n { \n //ex handle code \n throw;\n }\n //pro.SetValue(obj, dr[column.ColumnName], null);\n }\n else\n continue;\n }\n }\n return obj;\n }\n private static object GetValueByDataType(Type propertyType, object o)\n {\n if (o.ToString() == \"null\")\n {\n return null;\n }\n if (propertyType == (typeof(Guid)) || propertyType == typeof(Guid?))\n {\n return Guid.Parse(o.ToString());\n }\n else if (propertyType == typeof(int) || propertyType.IsEnum) \n {\n return Convert.ToInt32(o);\n }\n else if (propertyType == typeof(decimal) )\n {\n return Convert.ToDecimal(o);\n }\n else if (propertyType == typeof(long))\n {\n return Convert.ToInt64(o);\n }\n else if (propertyType == typeof(bool) || propertyType == typeof(bool?))\n {\n return Convert.ToBoolean(o);\n }\n else if (propertyType == typeof(DateTime) || propertyType == typeof(DateTime?))\n {\n return Convert.ToDateTime(o);\n }\n return o.ToString();\n }\n List< Student > studentDetails = new List< Student >(); \nstudentDetails = ConvertDataTable< Student >(dt); \n" }, { "answer_id": 52390575, "author": "Ömer Ceylan", "author_id": 9215988, "author_profile": "https://Stackoverflow.com/users/9215988", "pm_score": 0, "selected": false, "text": "public static List<T> DataTableToList<T>(this DataTable table) where T : class, new()\n{\n try\n {\n List<T> list = new List<T>();\n\n foreach (var row in table.AsEnumerable())\n {\n T obj = new T();\n\n foreach (var prop in obj.GetType().GetProperties())\n {\n try\n {\n PropertyInfo propertyInfo = obj.GetType().GetProperty(prop.Name);\n if (propertyInfo.PropertyType.IsEnum)\n {\n propertyInfo.SetValue(obj, Enum.Parse(propertyInfo.PropertyType, row[prop.Name].ToString()));\n }\n else\n {\n propertyInfo.SetValue(obj, Convert.ChangeType(row[prop.Name], propertyInfo.PropertyType), null);\n } \n }\n catch\n {\n continue;\n }\n }\n\n list.Add(obj);\n }\n\n return list;\n }\n catch\n {\n return null;\n }\n}\n" }, { "answer_id": 56472159, "author": "Anil", "author_id": 6603475, "author_profile": "https://Stackoverflow.com/users/6603475", "pm_score": 0, "selected": false, "text": "DataTable Dictionary public static Dictionary<object,IList<dynamic>> DataTable2Dictionary(DataTable dt)\n{\n Dictionary<object, IList<dynamic>> dict = new Dictionary<dynamic, IList<dynamic>>();\n\n foreach(DataColumn column in dt.Columns)\n {\n IList<dynamic> ts = dt.AsEnumerable()\n .Select(r => r.Field<dynamic>(column.ToString()))\n .ToList();\n dict.Add(column, ts);\n }\n return dict;\n}\n" }, { "answer_id": 58899557, "author": "mohamed mostafa", "author_id": 11079832, "author_profile": "https://Stackoverflow.com/users/11079832", "pm_score": 0, "selected": false, "text": "public static class Extensions\n{\n #region Convert Datatable To List\n public static IList<T> ToList<T>(this DataTable table) where T : new()\n {\n IList<PropertyInfo> properties = typeof(T).GetProperties().ToList();\n IList<T> result = new List<T>();\n\n foreach (var row in table.Rows)\n {\n var item = CreateItemFromRow<T>((DataRow)row, properties);\n result.Add(item);\n }\n return result;\n }\n private static T CreateItemFromRow<T>(DataRow row, IList<PropertyInfo> properties) where T : new()\n {\n T item = new T();\n foreach (var property in properties)\n {\n property.SetValue(item, row[property.Name], null);\n }\n return item;\n }\n #endregion\n}\n" }, { "answer_id": 59407777, "author": "Maghalakshmi Saravana", "author_id": 12562878, "author_profile": "https://Stackoverflow.com/users/12562878", "pm_score": 0, "selected": false, "text": " List<Candidate> temp = new List<Candidate>();//List that holds the Candidate Class,\n //Note:The Candidate class contains RollNo,Name and Department\n //tb is DataTable\n temp = (from DataRow dr in tb.Rows\n select new Candidate()\n {\n RollNO = Convert.ToInt32(dr[\"RollNO\"]),\n Name = dr[\"Name\"].ToString(),\n Department = dr[\"Department\"].ToString(),\n\n }).ToList();\n" }, { "answer_id": 59878996, "author": "Maghalakshmi Saravana", "author_id": 12562878, "author_profile": "https://Stackoverflow.com/users/12562878", "pm_score": 2, "selected": false, "text": "var json = JsonConvert.SerializeObject(dataTable);\nvar model = JsonConvert.DeserializeObject<List<ClassName>>(json);\n" }, { "answer_id": 59966814, "author": "hosam hemaily", "author_id": 8607709, "author_profile": "https://Stackoverflow.com/users/8607709", "pm_score": 0, "selected": false, "text": "private static List<T> ConvertDataTable<T>(DataTable dt)\n {\n List<T> data = new List<T>();\n foreach (DataRow row in dt.Rows)\n {\n T item = GetItem<T>(row);\n data.Add(item);\n }\n return data;\n }\n private static T GetItem<T>(DataRow dr)\n {\n\n Type temp = typeof(T);\n T obj = Activator.CreateInstance<T>();\n\n foreach (DataColumn column in dr.Table.Columns)\n {\n foreach (PropertyInfo pro in temp.GetProperties())\n {\n if (pro.Name == column.ColumnName)\n pro.SetValue(obj, dr[column.ColumnName].ToString(), null);\n else\n continue;\n }\n }\n return obj;\n }\n List<StudentScanExamsDTO> studentDetails = ConvertDataTable<StudentScanExamsDTO>(dt);\n" }, { "answer_id": 61636125, "author": "mr R", "author_id": 1831734, "author_profile": "https://Stackoverflow.com/users/1831734", "pm_score": 2, "selected": false, "text": "lPerson = dt.AsEnumerable().Select(s => new Person()\n {\n Name = s.Field<string>(\"Name\"),\n SurName = s.Field<string>(\"SurName\"),\n Age = s.Field<int>(\"Age\"),\n InsertDate = s.Field<DateTime>(\"InsertDate\")\n }).ToList();\n using System;\n using System.Collections.Generic; \n using System.Data;\n using System.Linq;\n using System.Data.DataSetExtensions;\n\n public static void Main()\n {\n DataTable dt = new DataTable();\n dt.Columns.Add(\"Name\", typeof(string));\n dt.Columns.Add(\"SurName\", typeof(string));\n dt.Columns.Add(\"Age\", typeof(int));\n dt.Columns.Add(\"InsertDate\", typeof(DateTime));\n\n var row1= dt.NewRow();\n row1[\"Name\"] = \"Adam\";\n row1[\"SurName\"] = \"Adam\";\n row1[\"Age\"] = 20;\n row1[\"InsertDate\"] = new DateTime(2020, 1, 1);\n dt.Rows.Add(row1);\n\n var row2 = dt.NewRow();\n row2[\"Name\"] = \"John\";\n row2[\"SurName\"] = \"Smith\";\n row2[\"Age\"] = 25;\n row2[\"InsertDate\"] = new DateTime(2020, 3, 12);\n dt.Rows.Add(row2);\n\n var row3 = dt.NewRow();\n row3[\"Name\"] = \"Jack\";\n row3[\"SurName\"] = \"Strong\";\n row3[\"Age\"] = 32;\n row3[\"InsertDate\"] = new DateTime(2020, 5, 20);\n dt.Rows.Add(row3);\n\n List<Person> lPerson = new List<Person>();\n lPerson = dt.AsEnumerable().Select(s => new Person()\n {\n Name = s.Field<string>(\"Name\"),\n SurName = s.Field<string>(\"SurName\"),\n Age = s.Field<int>(\"Age\"),\n InsertDate = s.Field<DateTime>(\"InsertDate\")\n }).ToList();\n \n foreach(Person pers in lPerson)\n {\n Console.WriteLine(\"{0} {1} {2} {3}\", pers.Name, pers.SurName, pers.Age, pers.InsertDate);\n }\n } \n \n public class Person\n {\n public string Name { get; set; }\n public string SurName { get; set; }\n public int Age { get; set; }\n public DateTime InsertDate { get; set; }\n }\n}\n" }, { "answer_id": 64503270, "author": "Vikas Lalwani", "author_id": 3559462, "author_profile": "https://Stackoverflow.com/users/3559462", "pm_score": 0, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n DataTable table = GetDataTable();\n var sw = new Stopwatch();\n\n sw.Start();\n LinqMethod(table);\n sw.Stop();\n Console.WriteLine(\"Elapsed time for Linq Method={0}\", sw.ElapsedMilliseconds);\n\n sw.Reset();\n\n sw.Start();\n ForEachMethod(table);\n sw.Stop();\n Console.WriteLine(\"Elapsed time for Foreach method={0}\", sw.ElapsedMilliseconds);\n\n Console.ReadKey();\n }\n\n private static DataTable GetDataTable()\n {\n var table = new DataTable();\n table.Columns.Add(\"ID\", typeof(double));\n table.Columns.Add(\"CategoryName\", typeof(string));\n table.Columns.Add(\"Active\", typeof(double));\n\n var rand = new Random();\n\n for (int i = 0; i < 100000; i++)\n {\n table.Rows.Add(i, \"name\" + i, rand.Next(0, 2));\n }\n return table;\n }\n\n private static void LinqMethod(DataTable table)\n {\n var list = table.AsEnumerable()\n .Skip(1)\n .Select(dr =>\n new Category\n {\n Id = Convert.ToInt32(dr.Field<double>(\"ID\")),\n CategoryName = dr.Field<string>(\"CategoryName\"), \n IsActive =\n dr.Field<double>(\"Active\") == 1 ? true : false\n }).ToList();\n }\n private static void ForEachMethod(DataTable table)\n {\n var categoryList = new List<Category>(table.Rows.Count);\n foreach (DataRow row in table.Rows)\n {\n var values = row.ItemArray;\n var category = new Category()\n {\n Id = Convert.ToInt32(values[0]),\n CategoryName = Convert.ToString(values[1]), \n IsActive = (double)values[2] == 1 ? true : false\n };\n categoryList.Add(category);\n }\n }\n\n private class Category\n {\n public int Id { get; set; }\n public string CategoryName { get; set; }\n public bool IsActive { get; set; }\n }\n}\n" }, { "answer_id": 69779114, "author": "Ali Amini", "author_id": 9185347, "author_profile": "https://Stackoverflow.com/users/9185347", "pm_score": 0, "selected": false, "text": "var json = JsonConvert.SerializeObject(dataTable);\nvar YourConvertedDataType = JsonConvert.DeserializeObject<YourDataType>(json);\n" }, { "answer_id": 71446491, "author": "bobt", "author_id": 18443704, "author_profile": "https://Stackoverflow.com/users/18443704", "pm_score": 0, "selected": false, "text": "List ItemArray List<string> s = dt.AsEnumerable().Select(x => x[0].ToString()).ToList();\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208532", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1122/" ]
208,557
<p>The back button just causes my page to refresh. Is there a way around this without disabling the cache?</p>
[ { "answer_id": 208598, "author": "Kon", "author_id": 22303, "author_profile": "https://Stackoverflow.com/users/22303", "pm_score": 2, "selected": true, "text": "<META HTTP-EQUIV=\"CACHE-CONTROL\" CONTENT=\"NO-CACHE\">\n<META HTTP-EQUIV=\"PRAGMA\" CONTENT=\"NO-CACHE\">\n" }, { "answer_id": 16318187, "author": "vijay", "author_id": 2339123, "author_profile": "https://Stackoverflow.com/users/2339123", "pm_score": 0, "selected": false, "text": "function getHashOnBack(valueget) \n{\n location.hash = \"#backTo=\" + $(window).scrollTop();$(document).height();\n}\n $(document).ready(function () \n{\n var ab = window.location.hash.substring(1).split(\"=\");\n if (ab[0] == \"backTo\") \n {\n // this would be called automatically when back putton pressed and hav #back=1234 etc. // value in url\n\n $(window).scrollTop(parseInt(ab[1]));\n}\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208557", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24481/" ]
208,562
<p>Is there a way to create register a handler that will be called exactly at the time when the last reference to a certain object is released?</p> <p>An example would be an object that is backed by a physical data file and once the object become unreferenced, the file should be closed and than renamed. It would be nice if this was possible without having to explicitly call a "close" method on that object.</p> <p>All the notification mechanisms I am aware of from the Weak/Phantom reference area only state that notification will occur at some point in time but there is no gurantee as to when this will happen...</p>
[ { "answer_id": 208803, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": -1, "selected": false, "text": "finalize() File.deleteOnExit()" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208562", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23424/" ]
208,570
<p>I have a class which is marked with a custom attribute, like this:</p> <pre><code>public class OrderLine : Entity { ... [Parent] public Order Order { get; set; } public Address ShippingAddress{ get; set; } ... } </code></pre> <p>I want to write a generic method, where I need to get the Property on a Entity which is marked with the Parent attribute.</p> <p>Here is my Attribute:</p> <pre><code>[AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = false)] public class ParentAttribute : Attribute { } </code></pre> <p>How do I write this?</p>
[ { "answer_id": 208595, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "public static object GetParentValue<T>(T obj) {\n Type t = obj.GetType();\n foreach (var prop in t.GetProperties()) {\n var attrs = prop.GetCustomAttributes(typeof(ParentAttribute), false);\n if (attrs.Length != 0)\n return prop.GetValue(obj, null);\n }\n\n return null;\n}\n" }, { "answer_id": 208602, "author": "Jon B", "author_id": 27414, "author_profile": "https://Stackoverflow.com/users/27414", "pm_score": 3, "selected": true, "text": " T GetPropertyValue<T>(object o)\n {\n T value = default(T);\n\n foreach (System.Reflection.PropertyInfo prop in o.GetType().GetProperties())\n {\n object[] attrs = prop.GetCustomAttributes(typeof(ParentAttribute), false);\n if (attrs.Length > 0)\n {\n value = (T)prop.GetValue(o, null);\n break;\n }\n }\n\n return value;\n }\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208570", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8547/" ]
208,580
<p>I was wondering peoples opinions on the naming of ID columns in database tables.</p> <p>If I have a table called Invoices with a primary key of an identity column I would call that column InvoiceID so that I would not conflict with other tables and it's obvious what it is.</p> <p>Where I am workind current they have called all ID columns ID.</p> <p>So they would do the following:</p> <pre><code>Select i.ID , il.ID From Invoices i Left Join InvoiceLines il on i.ID = il.InvoiceID </code></pre> <p>Now, I see a few problems here:<br> 1. You would need to alias the columns on the select<br> 2. ID = InvoiceID does not fit in my brain<br> 3. If you did not alias the tables and referred to InvoiceID is it obvious what table it is on?</p> <p>What are other peoples thoughts on the topic?</p>
[ { "answer_id": 208591, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 5, "selected": false, "text": "InvoiceID ID ID i" }, { "answer_id": 208600, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "SELECT * from Invoice inv, InvoiceLine inv_l where \ninv_l.InvoiceID = inv.ID \nSELECT * from Invoice inv, InvoiceLine inv_l where \ninv_l.ID = inv.InvoiceLineID \nSELECT * from Invoice inv, InvoiceLine inv_l where \ninv_l.ID = inv.InvoiceID \nSELECT * from Invoice inv, InvoiceLine inv_l where \ninv_l.InvoiceLineID = inv.ID \n" }, { "answer_id": 208607, "author": "Ilya Kochetov", "author_id": 15329, "author_profile": "https://Stackoverflow.com/users/15329", "pm_score": -1, "selected": false, "text": "inv invl inv_id invl_id invl_inv_id SELECT * FROM Invoice LEFT JOIN InvoiceLines ON inv_id = invl_inv_id\n" }, { "answer_id": 208800, "author": "Steven Huwig", "author_id": 28604, "author_profile": "https://Stackoverflow.com/users/28604", "pm_score": 1, "selected": false, "text": "SELECT * FROM invoices NATURAL JOIN invoice_lines\nSELECT * FROM invoices JOIN invoice_lines USING (invoice_id)\n SELECT * from invoices JOIN invoice_lines\n ON invoices.id = invoice_lines.invoice_id\n" }, { "answer_id": 209055, "author": "Rob Allen", "author_id": 149, "author_profile": "https://Stackoverflow.com/users/149", "pm_score": 2, "selected": false, "text": " Select Invoice.InvoiceID, Lines.InvoiceLine, Customer.OrgName\n From Invoices Invoice\n Join InvoiceLines Lines on Lines.InvoiceID = Invoice.InvoiceID\n Join Customers Customer on Customer.CustomerID = Invoice.CustomerID\n" }, { "answer_id": 209942, "author": "onedaywhen", "author_id": 15354, "author_profile": "https://Stackoverflow.com/users/15354", "pm_score": 2, "selected": false, "text": "invoice_ID employee_ID supervisor_employee_ID subordinate_employee_ID employee_ID Personnel TableNameID TableName.ID=PK TableNameID=FK IDENTITY employee_last_name last_name Personnel UNION last_name" }, { "answer_id": 212414, "author": "flamingLogos", "author_id": 8161, "author_profile": "https://Stackoverflow.com/users/8161", "pm_score": 0, "selected": false, "text": "_prd _ctg id_prd idctg_prd _prd" }, { "answer_id": 213382, "author": "Ian Andrews", "author_id": 2382102, "author_profile": "https://Stackoverflow.com/users/2382102", "pm_score": 1, "selected": false, "text": "Table_pk PrimaryKeyTable_fk Customer_pk Customer_fk SELECT * \nFROM Customer AS c\n INNER JOIN Order AS c ON c.Customer_pk = o.Customer_fk\n" }, { "answer_id": 213496, "author": "CMPalmer", "author_id": 14894, "author_profile": "https://Stackoverflow.com/users/14894", "pm_score": 2, "selected": false, "text": "pk_ _id fk_ _VW is_ pk_name_id, first_name, last_name, is_alive, fk_company LIVING_CUSTOMERS_VW" }, { "answer_id": 7502536, "author": "bjdodo", "author_id": 803277, "author_profile": "https://Stackoverflow.com/users/803277", "pm_score": 4, "selected": false, "text": "Select \n Invoices.ID \n, InvoiceLines.ID \nFrom\n Invoices\n Left Join InvoiceLines\n on Invoices.ID = InvoiceLines.InvoiceID\n" }, { "answer_id": 7504177, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 6, "selected": true, "text": "select t1.field1, t2.field2, t3.field3\nfrom table1 t1 \njoin table2 t2 on t1.id = t2.table1id\njoin table3 t3 on t1.id = t3.table2id\n select t1.field1, t2.field2, t3.field3 \nfrom table1 t1 \njoin table2 t2 on t1.id = t2.table1id\njoin table3 t3 on t2.id = t3.table2id\n" }, { "answer_id": 18242860, "author": "percebus", "author_id": 1361858, "author_profile": "https://Stackoverflow.com/users/1361858", "pm_score": 3, "selected": false, "text": "SELECT Employee.*, eMail.Address\nFROM Employees AS Employee LEFT JOIN eMails as eMail on Employee.eMailID = eMail.eMailID -- I would sure like it to just have the eMail.ID here.... but oh well\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208580", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26792/" ]
208,604
<p>I have successfully been able to rename a table and drop all constraints on that table with foreign key relationships and build they all back up. However, now I am at a point where the PK_tblFoo exists in more than one place (when I transfer the table to another DB). Renaming the table does not rename the primary key.</p> <p>How would I cascade rename the primary key? I have renamed the table, I just need to get this portion figured out.</p>
[ { "answer_id": 208686, "author": "RyanKeeter", "author_id": 7952, "author_profile": "https://Stackoverflow.com/users/7952", "pm_score": 1, "selected": false, "text": "IF EXISTS ( SELECT *\n FROM sys.indexes\n WHERE object_id = OBJECT_ID(N'[dbo].[tblFoo]')\n AND name = N'PK_tblBusinessListings' ) \nALTER TABLE [dbo].[tblFoo] DROP CONSTRAINT [PK_tblBusinessListings]\nGO\nALTER TABLE [dbo].[tblFoo]\nADD CONSTRAINT [PK_tblFoo_1] PRIMARY KEY CLUSTERED ( [ListingID] ASC )\n WITH ( PAD_INDEX = OFF, SORT_IN_TEMPDB = OFF, IGNORE_DUP_KEY = OFF,\n ONLINE = OFF ) ON [PRIMARY]\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208604", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7952/" ]
208,612
<p>I am kinda repeating this question bit the 1st time it was asked incorrectly.</p> <p>I have this:</p> <pre><code>&lt;xsd:complexType name="A"&gt; &lt;xsd:sequence&gt; &lt;xsd:element name="options" type="options"/&gt; &lt;/xsd:sequence&gt; &lt;/xsd:complexType&gt; &lt;xsd:complexType name="B"&gt; &lt;xsd:complexContent&gt; &lt;xsd:element name="options" type="ex_options"/&gt; &lt;/xsd:complexContent&gt; &lt;/xsd:complexType&gt; &lt;xsd:complexType name="options"&gt; &lt;xsd:sequence&gt; ...some options &lt;/xsd:sequence&gt; &lt;/xsd:element&gt; &lt;xsd:complexType name="ex_options"&gt; &lt;xsd:complexContent&gt; &lt;xsd:extension base="options"&gt; &lt;xsd:sequence&gt; ...some more options &lt;/xsd:sequence&gt; &lt;/xsd:extension&gt; &lt;/xsd:complexContent&gt; &lt;/xsd:element&gt; </code></pre> <p>So basically I have class A with an inner class of options Class B inherits from class A and I want B.options to inherit from A.options so that when we do webservices we only need to pass a and when we call getOptions it will return the right object B.options. Currently with the way the xsd stands I get an error saying multiple elements with name options with different types appear in the model group. The errors is in the B type.</p>
[ { "answer_id": 208858, "author": "Jeff Yates", "author_id": 23234, "author_profile": "https://Stackoverflow.com/users/23234", "pm_score": 0, "selected": false, "text": "options options type A B <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<xs:schema targetNamespace=\"http://tempuri.org/XMLSchema.xs\"\n elementFormDefault=\"qualified\"\n xmlns=\"http://tempuri.org/XMLSchema.xs\"\n xmlns:mstns=\"http://tempuri.org/XMLSchema.xs\"\n xmlns:xs=\"http://www.w3.org/2001/XMLSchema\">\n\n <!-- Elements for document structure. -->\n <!-- This section is just for validating my example file to -->\n <!-- demonstrate the schema. -->\n <xs:element name=\"root\">\n <xs:complexType>\n <xs:sequence>\n <xs:element name=\"elementA\" type=\"A\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n <xs:element name=\"elementB\" type=\"A\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n </xs:sequence>\n </xs:complexType>\n </xs:element>\n\n\n\n <!-- The important part of the schema. -->\n <!-- Types -->\n <!-- A has options of type options. -->\n <xs:complexType name=\"A\">\n <xs:sequence>\n <xs:element name=\"options\" type=\"options\"/>\n </xs:sequence>\n </xs:complexType>\n\n <!-- Options specifies a options with a type attribute specifying which options will be available. -->\n <xs:complexType name=\"options\">\n <xs:sequence>\n <xs:element name=\"option\" minOccurs=\"0\" maxOccurs=\"unbounded\"/>\n </xs:sequence>\n <xs:attribute name=\"type\" use=\"optional\" default=\"A\">\n <xs:simpleType>\n <xs:restriction base=\"xs:string\">\n <xs:enumeration value=\"A\"/>\n <xs:enumeration value=\"B\"/>\n </xs:restriction>\n </xs:simpleType>\n </xs:attribute>\n </xs:complexType>\n\n</xs:schema>\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<root xmlns=\"http://tempuri.org/XMLSchema.xs\">\n <elementA>\n <options type=\"A\">\n <option>Test-A</option>\n <option>Test2-A</option>\n </options>\n </elementA>\n <elementB>\n <options type=\"B\">\n <option>Test-B</option>\n <option>Test2-B</option>\n <option>Test3-B</option>\n <option>Test4-B</option>\n </options>\n </elementB>\n</root>\n" }, { "answer_id": 274369, "author": "6eorge Jetson", "author_id": 23422, "author_profile": "https://Stackoverflow.com/users/23422", "pm_score": 2, "selected": false, "text": "xsi:type <xsd:complexType name=\"B\"> \n  <xsd:complexContent>\n    <xsd:element name=\"options\" type=\"ex_options\"/>\n  </xsd:complexContent>\n</xsd:complexType>\n\n<xsd:complexType name=\"options\">\n  <xsd:sequence>\n      ...some options\n  </xsd:sequence>\n</xsd:element>\n\n<xsd:complexType name=\"ex_options\">\n  <xsd:complexContent>\n    <xsd:extension base=\"options\">\n      <xsd:sequence>\n          ...some more options\n      </xsd:sequence>\n    </xsd:extension>\n  </xsd:complexContent>\n</xsd:element>\n <options xsi:type=\"ex_options\"> ...     (this will work)\n <options xsi:type=\"options\"> ...     (I think you can do this as long as the base xsi:type is not abstract)\n xsi:type" }, { "answer_id": 3346638, "author": "rodnower", "author_id": 297977, "author_profile": "https://Stackoverflow.com/users/297977", "pm_score": 0, "selected": false, "text": "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsd:schema xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <!-- Root element -->\n <xsd:element name=\"root\" type=\"B\"/>\n\n <!-- Base abstract type -->\n <xsd:complexType name=\"A\" abstract=\"true\">\n <xsd:sequence>\n <!-- Option that we will override -->\n <xsd:element name=\"options\" type=\"options\"/>\n </xsd:sequence>\n </xsd:complexType>\n\n <!-- Derived type -->\n <xsd:complexType name=\"B\">\n <xsd:complexContent>\n <!--Overriding -->\n <xsd:restriction base=\"A\">\n <xsd:sequence>\n <xsd:element name=\"options\" type=\"ex_options\"/>\n </xsd:sequence>\n </xsd:restriction>\n </xsd:complexContent>\n </xsd:complexType>\n\n <!-- Base included class -->\n <xsd:complexType name=\"options\">\n <xsd:sequence>\n <xsd:element name=\"baseOption\"/>\n </xsd:sequence>\n </xsd:complexType>\n\n <!-- Overriding of included class -->\n <xsd:complexType name=\"ex_options\">\n <xsd:complexContent>\n <xsd:restriction base=\"options\">\n <xsd:sequence>\n <xsd:element name=\"overridedOption\"/>\n </xsd:sequence>\n </xsd:restriction>\n </xsd:complexContent>\n </xsd:complexType>\n</xsd:schema>\n {\n B root;\n\n abstract class A\n {\n options options;\n }\n\n class B override A\n {\n ex_options options;\n }\n\n class options\n {\n empty baseOption;\n }\n\n class ex_option override options\n {\n empty overridedOption\n }\n}\n <?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<root xsi:noNamespaceSchemaLocation=\"polymorphism.xsd\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n <options>\n <overridedOption/>\n </options>\n</root>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22763/" ]
208,647
<p>I have a <a href="https://jqueryui.com/draggable/" rel="nofollow noreferrer"><code>draggable</code></a> with a custom <a href="http://api.jqueryui.com/draggable/#option-helper" rel="nofollow noreferrer"><code>helper</code></a>. Sometimes the helper is a clone and sometimes it is the original element. </p> <p>The problem is that when the helper is the original element and is <strong>not</strong> dropped on a valid droppable it gets removed. My solution looks like this so far:</p> <p>in my <code>on_dropped</code> callback I set <code>ui.helper.dropped_on_droppable</code> to <code>true</code>;</p> <p>In the <code>stop</code> callback of the draggable, I check for that variable and then ... what do I do? </p> <pre><code>$('.my_draggable').draggable({ stop : function(e, ui) { if (!ui.helper.dropped_on_droppable) { /* what do I do here? */ } }, </code></pre> <p>Is this even the right approach?</p>
[ { "answer_id": 212623, "author": "Adam Hepton", "author_id": 2268, "author_profile": "https://Stackoverflow.com/users/2268", "pm_score": 0, "selected": false, "text": "revert: \"invalid\"\n" }, { "answer_id": 217894, "author": "MDCore", "author_id": 1896, "author_profile": "https://Stackoverflow.com/users/1896", "pm_score": 3, "selected": true, "text": "element.draggable({\n stop : function(e, ui) {\n /* \"dropped_on_droppable\" is custom and set in my custom drop method\n \".moved_draggable\" is custom and set in my custom drag method, \n to differentiate between the two types of draggables\n */ \n if (!ui.helper.dropped_on_droppable & ui.helper.hasClass('moved_draggable')) {\n /* this is the big hack that breaks encapsulation */\n $.ui.ddmanager.current.cancelHelperRemoval = true;\n }\n },\n" }, { "answer_id": 936342, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": ".draggable({\n helper: function() {\n var div = $(document.createElement('div'))\n .data('lastParent', $(this).parent());\n return div;\n },\n start: function() {\n //... add multiple selection items to the helper.. \n },\n stop: function(event,ui) {\n $( $(ui.helper).data('lastParent') ).append( $(ui.helper).children() );\n }\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208647", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1896/" ]
208,659
<p>Does anyone know of a good .NET library rules library (ideally open-source)? I need something that can do nested logic expressions, e.g., (A AND B) AND (B OR C OR D). I need to do comparisons of object properties, e.g., A.P1 AND B.P1. (Ideally, I could compare any property -- A.P1 AND B.P2). </p> <p>It should store the rules in a database (I've got a lot of simple configurable logic). And it should have a rule creation/management API. The management tool would have to inspect the instances to determine which properties are available and which constraints exist. </p> <p>Thanks!</p> <hr> <p>Oh, one more thing. As a rules-engine, I need to include the concept of Actions (Commands). These are what execute when the expression returns:</p> <pre><code>If (expression.Evaluation) { actions.Execute(); } </code></pre> <p>So I see a rule as something like:</p> <pre><code>class Rule { Expression Exp; Actions[] Actions; Run() { if(Exp.Evaluate()) { foreach(action in Actions) { action.Execute(); } } } } </code></pre>
[ { "answer_id": 208769, "author": "Shaun Bowe", "author_id": 1514, "author_profile": "https://Stackoverflow.com/users/1514", "pm_score": 4, "selected": false, "text": "String result = ExpressionEvaluator.EvaluateToString(\"(2+5) < 8\");\n using System;\nusing System.CodeDom.Compiler;\nusing System.Globalization;\nusing System.Reflection;\nusing Microsoft.JScript;\n\nnamespace Common.Rule\n{\n internal static class ExpressionEvaluator\n {\n #region static members\n private static object _evaluator = GetEvaluator();\n private static Type _evaluatorType;\n private const string _evaluatorSourceCode =\n @\"package Evaluator\n {\n class Evaluator\n {\n public function Eval(expr : String) : String \n { \n return eval(expr); \n }\n }\n }\";\n\n #endregion\n\n #region static methods\n private static object GetEvaluator()\n {\n CompilerParameters parameters;\n parameters = new CompilerParameters();\n parameters.GenerateInMemory = true;\n\n JScriptCodeProvider jp = new JScriptCodeProvider();\n CompilerResults results = jp.CompileAssemblyFromSource(parameters, _evaluatorSourceCode);\n\n Assembly assembly = results.CompiledAssembly;\n _evaluatorType = assembly.GetType(\"Evaluator.Evaluator\");\n\n return Activator.CreateInstance(_evaluatorType);\n }\n\n /// <summary>\n /// Executes the passed JScript Statement and returns the string representation of the result\n /// </summary>\n /// <param name=\"statement\">A JScript statement to execute</param>\n /// <returns>The string representation of the result of evaluating the passed statement</returns>\n public static string EvaluateToString(string statement)\n {\n object o = EvaluateToObject(statement);\n return o.ToString();\n }\n\n /// <summary>\n /// Executes the passed JScript Statement and returns the result\n /// </summary>\n /// <param name=\"statement\">A JScript statement to execute</param>\n /// <returns>The result of evaluating the passed statement</returns>\n public static object EvaluateToObject(string statement)\n {\n lock (_evaluator)\n {\n return _evaluatorType.InvokeMember(\n \"Eval\",\n BindingFlags.InvokeMethod,\n null,\n _evaluator,\n new object[] { statement },\n CultureInfo.CurrentCulture\n );\n }\n }\n #endregion\n } \n}\n" }, { "answer_id": 933297, "author": "Brendan Kowitz", "author_id": 25767, "author_profile": "https://Stackoverflow.com/users/25767", "pm_score": 1, "selected": false, "text": "BUSINESS RULES IN NATURAL LANGUAGE \n\nBefore\nIf (Customer.Age > 50 && Customer.Status == Status.Active) {\npolicy.SetDiscount(true, 10%);\n}\n\nAfter (with Smart Rules)\nIf Customer is older than 50 and\nthe Customer Status is Active Then\nApply 10 % of Discount\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28588/" ]
208,666
<p>I was wondering, is there any possibility to create a table without a primary key, but with two foreign keys, where the foreign keys pairs are always different? For example, a <code>STOCK</code> table with <code>item_id</code> and <code>warehouse_id</code> as foreign keys from <code>ITEMS</code> and <code>WAREHOUSES</code> tables. So same item can be in different warehouses. The view of the table:</p> <pre><code>item_id warehouse_id quantity 10 200 1000 10 201 3000 10 202 10000 11 200 7000 11 202 2000 12 203 5000 </code></pre> <p>Or do i have to create unused primary key field with auto increment or something? The database is oracle.</p> <p>Thanks!</p>
[ { "answer_id": 208688, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 2, "selected": false, "text": "ALTER TABLE [dbo].[RepresentativeData] \nadd CONSTRAINT [UK_Representative_repRecID_AppID] unique (repRecID,AppId)\ngo\n" }, { "answer_id": 208720, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 3, "selected": false, "text": "create table stock\n( item_id references items(item_id)\n, warehouse_id references warehouses(warehouse_id)\n, quantity number(12,2) not null\n, constraint stock_pk primary key (item_id, warehouse_id)\n);\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208666", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
208,668
<p>I had an odd problem today when I was trying to serialize an object. The object was generated via "Add service reference" from a web service (svcutil.exe). </p> <p>The problem was that the below property (agencyId) was not being serialized with the rest of the object. Out of desperation I commented the property below it because it had the "XMLIgnoreAttribute" assigned... after I commented the ignored property, the agencyId field serialized as expected. </p> <p>Can someone please explain to me why this behavior occurred? Thanks!!</p> <pre><code> /// &lt;remarks/&gt; [System.Xml.Serialization.XmlElementAttribute(Form=System.Xml.Schema.XmlSchemaForm.Unqualified, Order=1)] public string agencyId { get { return this.agencyIdField; } set { this.agencyIdField = value; this.RaisePropertyChanged("agencyId"); } } /// &lt;remarks/&gt; [System.Xml.Serialization.XmlIgnoreAttribute()] public bool agencyIdSpecified { get { return this.agencyIdFieldSpecified; } set { this.agencyIdFieldSpecified = value; this.RaisePropertyChanged("agencyIdSpecified"); } } </code></pre>
[ { "answer_id": 208687, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "[DefaultValue] [XmlIgnore]" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208668", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10589/" ]
208,682
<p>So - I have a checkbox</p> <pre><code>&lt;asp:CheckBox ID="chkOrder" runat="server" Visible='&lt;%#IsCheckBoxVisible() %&gt;' Checked="false" OnCheckedChanged="chkOrder_CheckedChanged" AutoPostBack="true" EnableViewState="false"&gt;&lt;/asp:CheckBox&gt; </code></pre> <p>the one above. Now, the checkbox is in a gridview and on databound - for all the rows in the gridview the checkbox is set to false. The problem is that the first checkbox is still true checked. </p> <p>In IE the problem doesn't exist, same for Chrome. I'm running out of options. Also if i use </p> <pre><code>$("checkboxName").attr("checked"); // verified on jquery ready function. </code></pre> <p>In FF it is true; IE false; Chrome false. </p> <p>Any tips?</p> <p><strong>EDIT</strong></p> <p>Now get ready for this : in the generated html - there is NO checked attribute. The diff between FF and IE is <strong>exactly the same</strong>.</p> <p>Another thing - the grid that contains the checkboxes has an ajax panel on it and when I page the grid, try to go to page 2 - the checkedChanged in codebehind is triggered.</p>
[ { "answer_id": 208730, "author": "Jonny Buchanan", "author_id": 6760, "author_profile": "https://Stackoverflow.com/users/6760", "pm_score": 3, "selected": false, "text": "checked <input type=\"checkbox\" checked=\"false\">\n" }, { "answer_id": 209155, "author": "Karl", "author_id": 2932, "author_profile": "https://Stackoverflow.com/users/2932", "pm_score": 4, "selected": false, "text": "Ctrl+F5 <form autocomplete=\"off\"> \n\n<input ... autocomplete=\"off\" /> \n" }, { "answer_id": 2686913, "author": "antipattern", "author_id": 322739, "author_profile": "https://Stackoverflow.com/users/322739", "pm_score": 0, "selected": false, "text": "$(\"input[id$=chkOrder]\").click(function() { \n if (!$(this).attr(\"checked\")) { $(this).removeAttr(\"checked\"); }\n else { $(this).attr(\"checked\", \"checked\"); }\n})\n" }, { "answer_id": 5393527, "author": "checktarded", "author_id": 671474, "author_profile": "https://Stackoverflow.com/users/671474", "pm_score": 1, "selected": false, "text": "<html>\n<body>\n\n<input type=\"checkbox\" checked=\"false\" id=\"cb\" />\n\n<script language=\"javascript\">\nif (cb.checked == true)\n document.write('this is retarded');\n</script>\n\n</body>\n</html>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208682", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5246/" ]
208,691
<p>I am using a DBGrid component in Delphi. I wonder how I can set the format of a column. I have real values that I want to be displayed as currency in the grid. </p> <p>Someone knows how?</p>
[ { "answer_id": 208833, "author": "Germán Estévez -Neftalí-", "author_id": 17487, "author_profile": "https://Stackoverflow.com/users/17487", "pm_score": 4, "selected": true, "text": "DisplayFormat Field OnGetText" }, { "answer_id": 210404, "author": "Mohammed Nasman", "author_id": 24462, "author_profile": "https://Stackoverflow.com/users/24462", "pm_score": 3, "selected": false, "text": "TFloatField(MyQuery.fieldByName('MyField').DisplayFormat := '0.00';\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208691", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6636/" ]
208,703
<p>I have seen the following code:</p> <pre><code>[DefaultValue(100)] [Description("Some descriptive field here")] public int MyProperty{...} </code></pre> <p>The functionality from the above snippit seems clear enough, I have no idea as to how I can use it to do useful things. Im not even sure as to what name to give it!</p> <p>Does anyone know where I can find more information/a tutorial on these property attributes? I would be also interested in any novel / useful tasks this feature can do.</p>
[ { "answer_id": 208708, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 3, "selected": false, "text": "DefaultValue" }, { "answer_id": 208740, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "[PrincipalPermission(...)] INotifyPropertyChanged" }, { "answer_id": 208948, "author": "TimothyP", "author_id": 28149, "author_profile": "https://Stackoverflow.com/users/28149", "pm_score": 2, "selected": false, "text": "[CompositeMetaData(\"Delay\",\"Sets the delay between commands\",1)]\n[CompositeDesigner(typeof(DelayCompositeDesigner))]\npublic class DelayComposite : CompositeBase \n{\n // code here\n}\n foreach (Type t in assembly.GetExportedTypes()) \n{\n Console.WriteLine(t.Name);\n\n if (t.Name.EndsWith(\"Composite\"))\n {\n var attributes = t.GetCustomAttributes(false);\n ToolboxListItem item = new ToolboxListItem();\n\n CompositeMetaDataAttribute meta = (CompositeMetaDataAttribute)attributes\n .Where(a => a.GetType() == typeof(Vialis.LightLink.Attributes.CompositeMetaDataAttribute)).First();\n item.Name = meta.DisplayName;\n item.Description = meta.Description;\n item.Length = meta.Length;\n item.CompositType = t;\n\n this.lstCommands.Items.Add(item);\n } \n}\n var designerAttribute = (CompositeDesignerAttribute)item.CompositType.GetCustomAttributes(false)\n .Where(a => a.GetType() == typeof(CompositeDesignerAttribute)).FirstOrDefault();\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
208,721
<p>Is it true that a WCF either runs as a console application that you have to manually start OR under a more traditional IIS application (like a website or webservice)</p>
[ { "answer_id": 208863, "author": "jezell", "author_id": 27453, "author_profile": "https://Stackoverflow.com/users/27453", "pm_score": 1, "selected": false, "text": "using (ServiceHost host = new ServiceHost(typeof(MyService))\n{\n host.Open();\n\n WaitForClose();\n\n host.Close();\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
208,735
<p>I've begun to the the built-in TraceSource and TraceListener classes and I would like to modify the output format of the events independently of the TraceSources and TraceListeners. It seems that the TraceListeners apply their own formatting. Is it possible to completely change the formatting without creating a new class for each and every TraceListener I use?</p>
[ { "answer_id": 806528, "author": "Greg D", "author_id": 6932, "author_profile": "https://Stackoverflow.com/users/6932", "pm_score": 0, "selected": false, "text": "Write() WriteLine() Trace" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208735", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2033241/" ]
208,736
<p>How can I strip out extra whitespace from jsp pages' output? Is there a switch I can flip on my web.xml? Is there a Tomcat specific setting?</p>
[ { "answer_id": 208752, "author": "Rontologist", "author_id": 13925, "author_profile": "https://Stackoverflow.com/users/13925", "pm_score": 9, "selected": true, "text": "<%@ page trimDirectiveWhitespaces=\"true\" %>\n <jsp-config>\n <jsp-property-group>\n <url-pattern>*.jsp</url-pattern>\n <trim-directive-whitespaces>true</trim-directive-whitespaces>\n </jsp-property-group>\n</jsp-config>\n" }, { "answer_id": 2614812, "author": "BalusC", "author_id": 157882, "author_profile": "https://Stackoverflow.com/users/157882", "pm_score": 5, "selected": false, "text": "trimDirectiveWhitespaces JspServlet trimSpaces true JspServlet /conf/web.xml <init-param>\n <param-name>trimSpaces</param-name>\n <param-value>true</param-value>\n</init-param>\n" }, { "answer_id": 7623458, "author": "redolent", "author_id": 970175, "author_profile": "https://Stackoverflow.com/users/970175", "pm_score": 2, "selected": false, "text": "${\"<!--\"}\n<c:if test=\"${first}\">\n <c:set var=\"extraClass\" value=\"${extraClass} firstRadio\"/>\n</c:if>\n<c:set var=\"first\" value=\"${false}\"/>\n${\"-->\"}<%\n\n%><input type=\"radio\" id=\"input1\" name=\"dayChooser\" value=\"Tuesday\"/><%\n%><label for=\"input1\" class=\"${extraClass}\">Tuesday</label>\n" }, { "answer_id": 14074542, "author": "Rajkumar Rajadurai", "author_id": 1935237, "author_profile": "https://Stackoverflow.com/users/1935237", "pm_score": 0, "selected": false, "text": "catalina.properties org.apache.jasper.compiler.Parser.STRICT_QUOTE_ESCAPING=false\n" }, { "answer_id": 41463687, "author": "yglodt", "author_id": 272180, "author_profile": "https://Stackoverflow.com/users/272180", "pm_score": 1, "selected": false, "text": "<p>Hello</p>\n<p>How are you?</p>\n <p>Hello</p><p>How are you?</p>\n maven-replacer-plugin pom.xml <plugin>\n <groupId>com.google.code.maven-replacer-plugin</groupId>\n <artifactId>replacer</artifactId>\n <version>1.5.3</version>\n <executions>\n <execution>\n <id>stripNewlines</id>\n <phase>prepare-package</phase>\n <goals>\n <goal>replace</goal>\n </goals>\n <configuration>\n <basedir>${project.build.directory}</basedir>\n <filesToInclude>projectname/WEB-INF/jsp/**/*.jsp</filesToInclude>\n <token>&gt;\\s*&lt;</token>\n <value>&gt;&lt;</value>\n <regexFlags>\n <regexFlag>MULTILINE</regexFlag>\n </regexFlags>\n </configuration>\n </execution>\n </executions>\n</plugin>\n <filesToInclude>" }, { "answer_id": 42395535, "author": "Andres", "author_id": 2079513, "author_profile": "https://Stackoverflow.com/users/2079513", "pm_score": 2, "selected": false, "text": "<%@ tag description=\"My Tag\" trimDirectiveWhitespaces=\"true\" %>\n <%@ page trimDirectiveWhitespaces=\"true\" %>\n" }, { "answer_id": 56814739, "author": "Jorge Santos Neill", "author_id": 7994269, "author_profile": "https://Stackoverflow.com/users/7994269", "pm_score": 1, "selected": false, "text": "fn:trim(string1)\n" }, { "answer_id": 60548563, "author": "Ghostff", "author_id": 4036303, "author_profile": "https://Stackoverflow.com/users/4036303", "pm_score": 0, "selected": false, "text": "out.clearBuffer();\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208736", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5586/" ]
208,739
<p>Eric Meyer's advice to keep individual rules alphabetized in a CSS style definition makes sense - there's no &quot;natural&quot; way to order rules, and this makes it easy in a complex definition to make sure you don't define the same thing twice.</p> <pre><code>div.Foo { background:Green; border:1px solid Khaki; display:none; left:225px; max-height:300px; overflow-x:hidden; overflow-y:auto; position:absolute; top:0; width:230px; z-index:99; } </code></pre> <p>So my question: Is there a plugin or some other easy way to select a list of rules in Visual Studio and alphabetize them? (Better yet, to apply this throughout a stylesheet in one fell swoop.)</p> <h3>Update</h3> <p>@Geoff suggests CleanCSS, which is very cool and will do the above-requested alphabetization all at once, in addition to a lot of other nice clean-up (e.g. merging definitions with the same selector). Unfortunately it collapses multiple selectors in a definition into a single line. For example</p> <pre><code>div.Foo, div.Foo p, div.Foo li { color:Green; } </code></pre> <p>becomes</p> <pre><code>div.Foo,div.Foo p,div.Foo li { color:Green; } </code></pre> <p>which is much harder to read and kind of a deal-breaker. This is with the lowest compression setting, and I don't see a way to override it.</p>
[ { "answer_id": 59001982, "author": "Joel Stransky", "author_id": 1538634, "author_profile": "https://Stackoverflow.com/users/1538634", "pm_score": 4, "selected": false, "text": "settings.json \"postcssSorting.config\": {\n \"properties-order\": \"alphabetical\"\n}\n PostCSS Sorting: Run" }, { "answer_id": 70409665, "author": "migli", "author_id": 3691488, "author_profile": "https://Stackoverflow.com/users/3691488", "pm_score": 0, "selected": false, "text": "// Don't do this\n.rule1,\n.rule2 {\n color: red;\n}\n\n// Do that\n.rule1, .rule2 {\n color: red;\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
208,767
<p>What is the return value of the <code>WaitForObject()</code> function?</p> <p>I do not mean the type of return value (int).</p> <p>What does it return if the event is signalled and what does it return if the event is not signalled?</p>
[ { "answer_id": 208776, "author": "Roger Lipscombe", "author_id": 8446, "author_profile": "https://Stackoverflow.com/users/8446", "pm_score": 3, "selected": true, "text": "WaitForObject WaitForSingleObject WaitForMultipleObjects WaitForSingleObject WAIT_TIMEOUT WAIT_OBJECT_0 WAIT_ERROR WaitForMultipleObjects WAIT_TIMEOUT WAIT_OBJECT_0 + n WAIT_ERROR" }, { "answer_id": 208810, "author": "Chris Becke", "author_id": 27491, "author_profile": "https://Stackoverflow.com/users/27491", "pm_score": 0, "selected": false, "text": "WaitForObject WaitForSingleObject WaitForMultipleObjects" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27213/" ]
208,772
<p>The situation is as follows:</p> <p>A series of remote workstations collect field data and ftp the collected field data to a server through ftp. The data is sent as a CSV file which is stored in a unique directory for each workstation in the FTP server.</p> <p>Each workstation sends a new update every 10 minutes, causing the previous data to be overwritten. We would like to somehow concatenate or store this data automatically. The workstation's processing is limited and cannot be extended as it's an embedded system. </p> <p>One suggestion offered was to run a cronjob in the FTP server, however there is a Terms of service restriction to only allow cronjobs in 30 minute intervals as it's shared-hosting. Given the number of workstations uploading and the 10 minute interval between uploads it looks like the cronjob's 30 minute limit between calls might be a problem.</p> <p>Is there any other approach that might be suggested? The available server-side scripting languages are perl, php and python.</p> <p>Upgrading to a dedicated server might be necessary, but I'd still like to get input on how to solve this problem in the most elegant manner.</p>
[ { "answer_id": 208789, "author": "bmdhacks", "author_id": 14032, "author_profile": "https://Stackoverflow.com/users/14032", "pm_score": 2, "selected": false, "text": "grab_lockfile() or exit();\nwhile (1) {\n if (new_files()) {\n process_new_files();\n }\n sleep(60);\n}\n" }, { "answer_id": 712207, "author": "Jay", "author_id": 20840, "author_profile": "https://Stackoverflow.com/users/20840", "pm_score": 1, "selected": false, "text": "on_file_received()" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14177/" ]
208,777
<p>I have a class which has the following constructor</p> <pre><code>public DelayCompositeDesigner(DelayComposite CompositeObject) { InitializeComponent(); compositeObject = CompositeObject; } </code></pre> <p>along with a default constructor with no parameters.</p> <p>Next I'm trying to create an instance, but it only works without parameters:</p> <pre><code>var designer = Activator.CreateInstance(designerAttribute.Designer); </code></pre> <p>This works just fine, but if I want to pass parameters it does not:</p> <pre><code>var designer = Activator.CreateInstance(designerAttribute.Designer, new DelayComposite(4)); </code></pre> <p>This results in an <code>MissingMethodException</code>:</p> <blockquote> <p>Constructor voor type Vialis.LightLink.Controller.Scenarios.Composites.DelayCompositeDesigner was not found</p> </blockquote> <p>Any ideas here?</p> <hr> <p>The problem is I really need to pass an object during construction.</p> <p>You see I have a designer which loads all the types that inherit from the <code>CompositeBase</code>. These are then added to a list from which the users can drag them to a designer. Upon doing so an instance of the dragged is added to the designer. Each of these classes have custom properties defined on them:</p> <pre><code>[CompositeMetaData("Delay","Sets the delay between commands",1)] [CompositeDesigner(typeof(DelayCompositeDesigner))] public class DelayComposite : CompositeBase { } </code></pre> <p>When the user selects an item in the designer, it looks at these attributes in order to load up a designer for that type. For example, in the case of the <code>DelayComposite</code> it would load up a user control which has a label and a slider which allow the user to set the "Delay" property of the <code>DelayComposite</code> instance.</p> <p>So far this works fine if I don't pass any parameters to the constructor. The designer creates an instance of the <code>DelayCompositeDesigner</code> and assigns it to the content property of a WPF <code>ContentPresenter</code>.</p> <p>But since that designer needs to modify the properties of the selected <code>DelayComposite</code> in the designer, I have to pass this instance to it. That is why the constructor looks lie this:</p> <pre><code>public DelayCompositeDesigner(DelayComposite CompositeObject) { InitializeComponent(); compositeObject = CompositeObject; } </code></pre> <p>Suggestions are welcome</p> <hr> <p>@VolkerK</p> <p>The result of your code is this:</p> <blockquote> <p>&lt;---- foo Vialis.LightLink.Controller.Scenarios.Composites.DelayCompositeDesignerVoid .ctor() Vialis.LightLink.Controller.Scenarios.Composites.DelayCompositeDesignerVoid .ctor(Vialis.LightLink.Controller.Scenarios.Composites.DelayComposite) param:Vialis.LightLink.Controller.Scenarios.Composites.DelayComposite foo ----></p> </blockquote> <hr> <p>Leppie, you were correct, I had for some reason referenced the Composites assembly in my UI application... which is not something I should have done as I was loading it at runtime. The following code works:</p> <pre><code>object composite = Activator.CreateInstance(item.CompositType,(byte)205); var designer = Activator.CreateInstance(designerAttribute.Designer, composite); </code></pre> <p>As you can see the code does not have knowledge of the <code>DelayComposite</code> type.</p> <p>This solves the current problem, but introduces many new ones for what I want to achieve, either way thank you and thank you to everyone who has replied here.</p> <hr> <p>As for the following code, suggested by multiple people:</p> <pre><code>var designer = Activator.CreateInstance( designerAttribute.Designer, new object[] { new DelayComposite(4) } ); </code></pre> <p>The <code>Activator.CreateInstance</code> has a signature that looks like this:</p> <pre><code>Activator.CreateInstance(Type type, params object[] obj) </code></pre> <p>So it should accept my code, but I will try the suggested code</p> <p><strong>UPDATE:</strong></p> <p>I've tried this as suggested:</p> <pre><code>var designer = Activator.CreateInstance(designerAttribute.Designer, new object[] { new DelayComposite(4)}); </code></pre> <p>The result is the same.</p>
[ { "answer_id": 208812, "author": "DocMax", "author_id": 6234, "author_profile": "https://Stackoverflow.com/users/6234", "pm_score": 4, "selected": false, "text": "var designer = Activator.CreateInstance(designerAttribute.Designer, new object[] { new DelayComposite(4) });\n" }, { "answer_id": 208825, "author": "Kev", "author_id": 419, "author_profile": "https://Stackoverflow.com/users/419", "pm_score": 0, "selected": false, "text": "public static Object CreateInstance(\n Type type,\n Object[] args\n)\n var designer = Activator.CreateInstance(\n typeof(DelayCompositeDesigner), \n new object[] { new DelayComposite(4) } \n);\n" }, { "answer_id": 208934, "author": "Ishmaeel", "author_id": 227, "author_profile": "https://Stackoverflow.com/users/227", "pm_score": 2, "selected": false, "text": "public DelayCompositeDesigner(DelayComposite CompositeObject)\n var designer = Activator.CreateInstance(typeof(DelayCompositeDesigner), new DelayComposite(4));\n var designer = Activator.CreateInstance<DelayCompositeDesigner>(new DelayComposite(4));\n" }, { "answer_id": 208988, "author": "VolkerK", "author_id": 4833, "author_profile": "https://Stackoverflow.com/users/4833", "pm_score": 3, "selected": false, "text": "public static void foo(Type t, params object[] p)\n{\n System.Diagnostics.Debug.WriteLine(\"<---- foo\");\n foreach(System.Reflection.ConstructorInfo ci in t.GetConstructors())\n {\n System.Diagnostics.Debug.WriteLine(t.FullName + ci.ToString());\n }\n foreach (object o in p)\n {\n System.Diagnostics.Debug.WriteLine(\"param:\" + o.GetType().FullName);\n }\n System.Diagnostics.Debug.WriteLine(\"foo ---->\");\n}\n// ...\nfoo(designerAttribute.Designer, new DelayComposite(4));\nvar designer = Activator.CreateInstance(designerAttribute.Designer, new DelayComposite(4));\n" }, { "answer_id": 209182, "author": "leppie", "author_id": 15541, "author_profile": "https://Stackoverflow.com/users/15541", "pm_score": 5, "selected": true, "text": "paramtype == typeof(DelayComposite)" }, { "answer_id": 41137106, "author": "Louis Marais", "author_id": 7295182, "author_profile": "https://Stackoverflow.com/users/7295182", "pm_score": 0, "selected": false, "text": "private void LoadTask(FileInfo dll)\n {\n Assembly assembly = Assembly.LoadFrom(dll.FullName);\n\n foreach (Type type in assembly.GetTypes())\n {\n var hasInterface = type.GetInterface(\"ITask\") != null;\n\n if (type.IsClass && hasInterface)\n {\n var instance = Activator.CreateInstance(type, _proxy, _context);\n _tasks.Add(type.Name, (ITask)instance);\n }\n }\n }\n public class CalculateDowntimeTask : Task<CalculateDowntimeTask>\n{\n public CalculateDowntimeTask(object proxy, object context) : \n base((TaskServiceClient)proxy, (TaskDataDataContext)context) { }\n\n public override void Execute()\n {\n LogMessage(new TaskMessage() { Message = \"Testing\" });\n BroadcastMessage(new TaskMessage() { Message = \"Testing\" });\n }\n}\n" }, { "answer_id": 68482229, "author": "Viettel Solutions", "author_id": 7740166, "author_profile": "https://Stackoverflow.com/users/7740166", "pm_score": 1, "selected": false, "text": "ExecutionEngineException Type type = assembly.GetType(dllName + \".dll\");\nActivator.CreateInstance(type ), new Stream[] { stream };\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28149/" ]
208,784
<p>Suppose A.css styles B.html. What tools/techniques are there to programmatically reduce the size of A.css while holding its styling effects on B.html constant? Here are some techniques I would imagine such a tool using:</p> <ol> <li><p><strong>Remove redundancies in A.css.</strong> For example, if the same class is defined twice you can remove the second definition without affecting semantics. This seems pretty easy.</p></li> <li><p><strong>Remove style definitions that aren't used</strong>. Does A.css style any elements that don't appear in B.html? If so, remove them.</p></li> <li><p><strong>Combine styles where appropriate</strong>. If A.css defines styles for div.x and div.y and every div that happens to have class x also has class y, one could combine the class definitions in A.css.</p></li> </ol> <p>A different strategy would be to have a tool that examines the computed styles of each element in a piece of styled HTML and spits out the minimal style sheet that would preserve the computed styles. Does something like <em>this</em> exist?</p> <h2>UPDATE</h2> <p>Let me explain how I got in this situation. The CSS file in question is for an <strong>email</strong>, and it was created by basically copying a similar CSS file that we used in an associated web page. Because the HTML in the email is a proper subset of the HTML in the web page from which the CSS came, some of the CSS in the email is superfluous.</p>
[ { "answer_id": 208841, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 0, "selected": false, "text": "mod_gzip mod_deflate" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208784", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25068/" ]
208,828
<p>A colleague and I are discussing best practices regarding ordering method parameters. The goal is to establish a standard in our organization to improve readability and productivity by giving our methods common signatures. We are merely establishing guidelines for the recent grads we are hiring. </p> <p><strong>Example (userId is always passed in to audit the calls):</strong></p> <p>GetOrders(string userId, int customerId); GetOrders(string userId, int[] orderIds); GetCustomer(string userId, int customerId);</p> <p>My argument is the following:</p> <ol> <li>common arguments are left most.</li> <li>remaining arguments are based on importance</li> <li>optional (nullable) arguments last.</li> </ol> <p>His argument is essentially the opposite.</p> <p>I'm not asking for a right or wrong answer here, nor a discussion. I just want to see what standards exist already.</p> <p>Thanks!</p>
[ { "answer_id": 208866, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 2, "selected": false, "text": "public method foo (string name)\npublic method foo (string name, string city)\npublic method foo (string name, string city, string state)\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208828", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6617/" ]
208,835
<p>I am just now learning about function pointers and, as I was reading the K&amp;R chapter on the subject, the first thing that hit me was, &quot;Hey, this is kinda like a closure.&quot; I knew this assumption is fundamentally wrong somehow and after a search online I didn't find really any analysis of this comparison.</p> <p>So why are C-style function pointers fundamentally different from closures or lambdas? As far as I can tell it has to do with the fact that the function pointer still points to a defined (named) function as opposed to the practice of anonymously defining the function.</p> <p>Why is passing a function to a function seen as more powerful in the second case, where it is unnamed, than the first where it is just a normal, everyday function that is being passed?</p> <p>Please tell me how and why I am wrong to compare the two so closely.</p>
[ { "answer_id": 208851, "author": "Herms", "author_id": 1409, "author_profile": "https://Stackoverflow.com/users/1409", "pm_score": 3, "selected": false, "text": "function runLater(f:Function):Void {\n sleep(100);\n f();\n}\n function objectProcessor(o:Object):Void {\n /* Do something cool with the object! */\n}\n\nfunction process(o:Object):Void {\n runLater(function() { objectProcessor(o); });\n}\n" }, { "answer_id": 208864, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "public Person FindPerson(IEnumerable<Person> people, string name)\n{\n return people.Where(person => person.Name == name);\n}\n" }, { "answer_id": 208916, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 2, "selected": false, "text": "(defun get-counter (n-start +-number)\n \"Returns a function that returns a number incremented\n by +-number every time it is called\"\n (lambda () (setf n-start (+ +-number n-start))))\n get-counter [1]> (defun get-counter (n-start +-number)\n \"Returns a function that returns a number incremented\n by +-number every time it is called\"\n (lambda () (setf n-start (+ +-number n-start))))\nGET-COUNTER\n[2]> (defvar x (get-counter 2 3))\nX\n[3]> (funcall x)\n5\n[4]> (funcall x)\n8\n[5]> (funcall x)\n11\n[6]> (funcall x)\n14\n[7]> (funcall x)\n17\n[8]> (funcall x)\n20\n[9]> \n" }, { "answer_id": 208940, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 8, "selected": true, "text": "int lessThan = 100;\nFunc<int, bool> lessThanTest = delegate(int i) {\n return i < lessThan;\n};\n int lessThan = 100;\nFunc<int, bool> lessThanTest = delegate(int i) {\n return i < lessThan;\n};\n\nlessThanTest(99); // returns true\nlessThan = 10;\nlessThanTest(99); // returns false\n BOOL (*lessThanTest)(int);\nint lessThan = 100;\n\nlessThanTest = &LessThan;\n\nBOOL LessThan(int i) {\n return i < lessThan; // compile error - lessThan is not in scope\n}\n int lessThan = 100;\nBOOL (*lessThanTest)(int, int);\n\nlessThanTest = &LessThan;\nlessThanTest(99, lessThan); // returns true\nlessThan = 10;\nlessThanTest(100, lessThan); // returns false\n\nBOOL LessThan(int i, int lessThan) {\n return i < lessThan;\n}\n" }, { "answer_id": 212382, "author": "Michael Carman", "author_id": 8233, "author_profile": "https://Stackoverflow.com/users/8233", "pm_score": 1, "selected": false, "text": "{\n my $count;\n sub increment { return $count++ }\n}\n $count increment" }, { "answer_id": 33886856, "author": "secretformula", "author_id": 897794, "author_profile": "https://Stackoverflow.com/users/897794", "pm_score": 2, "selected": false, "text": "#define lambda(l_ret_type, l_arguments, l_body) \\\n({ \\\n l_ret_type l_anonymous_functions_name l_arguments \\\n l_body \\\n &l_anonymous_functions_name; \\\n})\n qsort (array, sizeof (array) / sizeof (array[0]), sizeof (array[0]),\n lambda (int, (const void *a, const void *b),\n {\n dump ();\n printf (\"Comparison %d: %d and %d\\n\",\n ++ comparison, *(const int *) a, *(const int *) b);\n return *(const int *) a - *(const int *) b;\n }));\n" }, { "answer_id": 33945544, "author": "Rainer Joswig", "author_id": 69545, "author_profile": "https://Stackoverflow.com/users/69545", "pm_score": 2, "selected": false, "text": "MAKE-ADDER CL-USER 53 > (defun make-adder (start delta) (lambda () (incf start delta)))\nMAKE-ADDER\n\nCL-USER 54 > (compile *)\nMAKE-ADDER\nNIL\nNIL\n CL-USER 55 > (let ((adder1 (make-adder 0 10))\n (adder2 (make-adder 17 20)))\n (print (funcall adder1))\n (print (funcall adder1))\n (print (funcall adder1))\n (print (funcall adder1))\n (print (funcall adder2))\n (print (funcall adder2))\n (print (funcall adder2))\n (print (funcall adder1))\n (print (funcall adder1))\n (describe adder1)\n (describe adder2)\n (values))\n\n10 \n20 \n30 \n40 \n37 \n57 \n77 \n50 \n60 \n#<Closure 1 subfunction of MAKE-ADDER 4060001ED4> is a CLOSURE\nFunction #<Function 1 subfunction of MAKE-ADDER 4060001CAC>\nEnvironment #(60 10)\n#<Closure 1 subfunction of MAKE-ADDER 4060001EFC> is a CLOSURE\nFunction #<Function 1 subfunction of MAKE-ADDER 4060001CAC>\nEnvironment #(77 20)\n DESCRIBE FUNCALL" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208835", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25012/" ]
208,839
<p>We are working with some legacy code that accesses a shared drive by the letter (f:\ for example). Using the UNC notation is not an option. Our Java wrapper app will run as a service, and as the first step, I would like to map the drive explicitly in the code. Has anyone done this?</p>
[ { "answer_id": 208857, "author": "Jonas K", "author_id": 26609, "author_profile": "https://Stackoverflow.com/users/26609", "pm_score": 3, "selected": false, "text": " try {\n // Execute a command without arguments\n String command = \"C:\\\\Windows\\\\system32\\\\net.exe use F: \\\\\\\\server\\\\share /user:user password\";\n Process child = Runtime.getRuntime().exec(command);\n } catch (IOException e) {\n }\n" }, { "answer_id": 208877, "author": "Jorge Ferreira", "author_id": 6508, "author_profile": "https://Stackoverflow.com/users/6508", "pm_score": 5, "selected": true, "text": "String command = \"c:\\\\windows\\\\system32\\\\net.exe use f: \\\\\\\\machine\\\\share /user:user password\";\nProcess p = Runtime.getRuntime().exec(command);\n...\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208839", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9293/" ]
208,855
<p>Let's have the following class definition:</p> <pre><code>CThread::CThread () { this-&gt;hThread = NULL; this-&gt;hThreadId = 0; this-&gt;hMainThread = ::GetCurrentThread (); this-&gt;hMainThreadId = ::GetCurrentThreadId (); this-&gt;Timeout = 2000; //milliseconds } CThread::~CThread () { //waiting for the thread to terminate if (this-&gt;hThread) { if (::WaitForSingleObject (this-&gt;hThread, this-&gt;Timeout) == WAIT_TIMEOUT) ::TerminateThread (this-&gt;hThread, 1); ::CloseHandle (this-&gt;hThread); } } //********************************************************* //working method //********************************************************* unsigned long CThread::Process (void* parameter) { //a mechanism for terminating thread should be implemented //not allowing the method to be run from the main thread if (::GetCurrentThreadId () == this-&gt;hMainThreadId) return 0; else { m_pMyPointer = new MyClass(...); // my class successfully works here in another thread return 0; } } //********************************************************* //creates the thread //********************************************************* bool CThread::CreateThread () { if (!this-&gt;IsCreated ()) { param* this_param = new param; this_param-&gt;pThread = this; this-&gt;hThread = ::CreateThread (NULL, 0, (unsigned long (__stdcall *)(void *))this-&gt;runProcess, (void *)(this_param), 0, &amp;this-&gt;hThreadId); return this-&gt;hThread ? true : false; } return false; } //********************************************************* //creates the thread //********************************************************* int CThread::runProcess (void* Param) { CThread* thread; thread = (CThread*)((param*)Param)-&gt;pThread; delete ((param*)Param); return thread-&gt;Process (0); } MyClass* CThread::getMyPointer() { return m_pMyPointer; } </code></pre> <p>In the main program, we have the following:</p> <pre><code>void main(void) { CThread thread; thread.CreateThread(); MyClass* myPointer = thread.getMyPointer(); myPointer-&gt;someMethod(); // CRASH, BOOM, BANG!!!! } </code></pre> <p>At the moment the myPointer is used ( in the main thread ) it crashes. I don't know how to get the pointer, which points to memory, allocated in another thread. Is this actually possible?</p>
[ { "answer_id": 208991, "author": "m_pGladiator", "author_id": 446104, "author_profile": "https://Stackoverflow.com/users/446104", "pm_score": -1, "selected": false, "text": "MyClass* myPointer = thread.getMyPointer(); \n\nwhile (myPointer == 0) \n{\n ::Sleep(1000);\n}\n\nmyPointer->someMethod(); // Working :)\n" }, { "answer_id": 209006, "author": "Andreas Magnusson", "author_id": 5811, "author_profile": "https://Stackoverflow.com/users/5811", "pm_score": 0, "selected": false, "text": "this->hThread = ::CreateThread (NULL, 0,&runProcess, (void *)(this_param), 0, &this->hThreadId);\n assert(::GetCurrentThreadId() == hThreadId);\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/446104/" ]
208,890
<p>So, I want to export all my contacts from Outlook as vcards. If I google that, I get a bunch of shareware programs, but I want something free that just works. </p> <p>If I'm to code it myself, I guess I should use the Microsoft.Office.Interop.Outlook assembly. Has anyone already code to convert ContactItems to vcards?</p> <p><strong>Edit:</strong> I solved it in a completely different way, see answer below, but I have marked dok1.myopenid.com's answer as accepted because it answers my original question. </p>
[ { "answer_id": 208949, "author": "DOK", "author_id": 27637, "author_profile": "https://Stackoverflow.com/users/27637", "pm_score": 2, "selected": false, "text": "Dim oPerson As New CDO.Person\nDim strm As New ADODB.Stream\n\n' Assume strURL is a valid URL to a person contact item\noPerson.DataSource.Open strURL\n\n' You can set the ADO Stream object to the returned vCard stream\nSet strm = oPerson.GetvCardStream\n\n' Save the stream to a file.\n' Note: using adSaveCreateOverwrite may cause an existing\n' contact to be overwritten.\nstrm.SaveToFile \"d:\\vcard.txt\", adSaveCreateOverwrite\n\n' You don't have to set a Stream object,\n' just use the Stream methods off GetvCardStream directly\noPerson.GetvCardStream.SaveToFile \"d:\\vcard.txt\", adSaveCreateOverwrite\n" }, { "answer_id": 221920, "author": "Jonas Lincoln", "author_id": 17436, "author_profile": "https://Stackoverflow.com/users/17436", "pm_score": 4, "selected": true, "text": "c:\\temp copy /a *.vcf c:\\allcards.vcf" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17436/" ]
208,894
<p>How should I base64 encode a PDF file for transport over XML-RPC in Python?</p>
[ { "answer_id": 208960, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 3, "selected": false, "text": "xmlrpclib Binary \nimport xmlrpclib \nserver = xmlrpclib.ServerProxy(\"http://athomas:password@localhost:8080/trunk/login/xmlrpc\") \nserver.wiki.putAttachment('WikiStart/t.py', xmlrpclib.Binary(open('t.py').read())) \n" }, { "answer_id": 210534, "author": "Tony Meyer", "author_id": 4966, "author_profile": "https://Stackoverflow.com/users/4966", "pm_score": 5, "selected": false, "text": "a = open(\"pdf_reference.pdf\", \"rb\").read().encode(\"base64\")\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/825/" ]
208,897
<p>The simple question is: how to find out the location of an executable file in a Cocoa application. </p> <p>Remember that, in many Unix-like OS people use PATH environment to assign the preferred location for their executables, especially when they have several versions of same application in their system. As a good practice, our Cocoa application should find the PREFERRED location of the executable file it needs.</p> <p>For example, there was a SVN 1.4 in Leopard default configuration at /usr/bin, and you installed a much newer version, say SVN 1.5.3 via MacPorts at /opt/local/bin. And you set your PATH using /etc/path.d or .bash_profile or .zshrc like that:</p> <p>export PATH=/opt/local/bin:$PATH</p> <p>So you can use the new version of svn instead of the old one from the system. It works well in any terminal environment. But not in Cocoa applications. Cocoa application, as far as I know, only has a default PATH environment like this:</p> <p>export PATH="/usr/bin:/bin:/usr/sbin:/sbin"</p> <p>By default it will not using the configuration in /etc/path.d, .bash_profile, .profile, .zshrc, etc.</p> <p>So how exactly can we do?</p> <p>p.s. We have <a href="http://github.com/pieter/gitx/tree/master/PBGitBinary.m" rel="noreferrer">a semi-solution here</a>, but it cannot fully satisfied the objective for this question.</p>
[ { "answer_id": 209463, "author": "Brian Webster", "author_id": 23324, "author_profile": "https://Stackoverflow.com/users/23324", "pm_score": 3, "selected": false, "text": "dscl dscl -plist localhost -read /Local/Default/Users/username UserShell -plist env -c" }, { "answer_id": 387809, "author": "Abizern", "author_id": 41116, "author_profile": "https://Stackoverflow.com/users/41116", "pm_score": 3, "selected": false, "text": "NSDictionary *environmentDict = [[NSProcessInfo processInfo] environment];\nNSString *shellString = [environmentDict objectForKey:@\"SHELL\"];\n" }, { "answer_id": 8091206, "author": "Andrey Tarantsov", "author_id": 58146, "author_profile": "https://Stackoverflow.com/users/58146", "pm_score": 3, "selected": false, "text": "// from http://cocoawithlove.com/2009/05/invoking-other-processes-in-cocoa.html\n#import \"NSTask+OneLineTasksWithOutput.h\"\n\nvoid FixUnixPath() {\n dispatch_after(dispatch_time(DISPATCH_TIME_NOW, 0.1 * NSEC_PER_SEC), dispatch_get_main_queue(), ^(void){\n NSString *userShell = [[[NSProcessInfo processInfo] environment] objectForKey:@\"SHELL\"];\n NSLog(@\"User's shell is %@\", userShell);\n\n // avoid executing stuff like /sbin/nologin as a shell\n BOOL isValidShell = NO;\n for (NSString *validShell in [[NSString stringWithContentsOfFile:@\"/etc/shells\" encoding:NSUTF8StringEncoding error:nil] componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]]) {\n if ([[validShell stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]] isEqualToString:userShell]) {\n isValidShell = YES;\n break;\n }\n }\n\n if (!isValidShell) {\n NSLog(@\"Shell %@ is not in /etc/shells, won't continue.\", userShell);\n return;\n }\n NSString *userPath = [[NSTask stringByLaunchingPath:userShell withArguments:[NSArray arrayWithObjects:@\"-c\", @\"echo $PATH\", nil] error:nil] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];\n if (userPath.length > 0 && [userPath rangeOfString:@\":\"].length > 0 && [userPath rangeOfString:@\"/usr/bin\"].length > 0) {\n // BINGO!\n NSLog(@\"User's PATH as reported by %@ is %@\", userShell, userPath);\n setenv(\"PATH\", [userPath fileSystemRepresentation], 1);\n }\n });\n}\n PATH=$PATH:$HOME/.rvm/bin for i in $PATH; echo \"PATH=$i\"; end PATH= [[NSFileManager defaultManager] fileExistsAtPath:path]" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208897", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25079/" ]
208,919
<p>I am searching for "o" then prints all lines with "o". Any suggestion/code I must apply?</p> <p>data.txt:</p> <pre><code>j,o,b: a,b,d: o,l,e: f,a,r: e,x,o: </code></pre> <p>desired output:</p> <pre><code>j,o,b: o,l,e: e,x,o: </code></pre>
[ { "answer_id": 208935, "author": "Srikanth", "author_id": 7205, "author_profile": "https://Stackoverflow.com/users/7205", "pm_score": 1, "selected": false, "text": "grep \"o\" data.txt\n" }, { "answer_id": 208936, "author": "Ed Guiness", "author_id": 4200, "author_profile": "https://Stackoverflow.com/users/4200", "pm_score": 1, "selected": false, "text": "print if /o/;\n" }, { "answer_id": 208943, "author": "Jeremy Bourque", "author_id": 2192597, "author_profile": "https://Stackoverflow.com/users/2192597", "pm_score": 2, "selected": false, "text": "grep o data.txt open IN, 'data.txt';\nmy @l = <IN>;\nclose IN;\nforeach my $l (@l) {\n $l =~ /o/ and print $l;\n}\n" }, { "answer_id": 208946, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 0, "selected": false, "text": "while (<>) { print if /o/; }\n grep 'o' data.txt\n" }, { "answer_id": 208951, "author": "jj33", "author_id": 430, "author_profile": "https://Stackoverflow.com/users/430", "pm_score": 3, "selected": false, "text": "grep o data.txt\n\nperl -ne 'print if (/o/);' <data.txt\n" }, { "answer_id": 209218, "author": "Yanick", "author_id": 10356, "author_profile": "https://Stackoverflow.com/users/10356", "pm_score": 0, "selected": false, "text": "> perl -pe'$_ x=/o/' filename\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208919", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28607/" ]
208,925
<p>I'm using MS SQL Server 2005. Is there a difference, to the SQL engine, between</p> <pre><code>SELECT * FROM MyTable; </code></pre> <p>and</p> <pre><code>SELECT ColA, ColB, ColC FROM MyTable; </code></pre> <p>When ColA, ColB, and ColC represent every column in the table?</p> <p>If they are the same, is there a reason why you should use the 2nd one anyway? I have a project that's heavy on LINQ, and I'm not sure if the standard SELECT * it generates is a bad practice, or if I should always be a .Select() on it to specify which cols I want.</p> <p>EDIT: Changed "When ColA, ColB, and ColC are all the columns to the table?" to "When ColA, ColB, and ColC represent every column in the table?" for clarity.</p>
[ { "answer_id": 208945, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 6, "selected": true, "text": "Select col1, col2 from Table" }, { "answer_id": 208962, "author": "TcKs", "author_id": 20382, "author_profile": "https://Stackoverflow.com/users/20382", "pm_score": 2, "selected": false, "text": "SELECT * FROM myTable\n SELECT Column1, Column2, Column3 FROM myTable\n" }, { "answer_id": 208965, "author": "Scott Dorman", "author_id": 1559, "author_profile": "https://Stackoverflow.com/users/1559", "pm_score": 1, "selected": false, "text": "SELECT * FROM MyTable SELECT ColA, ColB, ColC FROM MyTable SELECT * SELECT ColA, ColB, ColC" }, { "answer_id": 208973, "author": "Jim", "author_id": 681, "author_profile": "https://Stackoverflow.com/users/681", "pm_score": 2, "selected": false, "text": "SELECT *\nFROM myTable\n rs = executeSql(\"SELECT * FROM myTable\")\nwhile (rs.read())\n Print \"Col A\" + rs[0]\n Print \"Col B\" + rs[1]\n Print \"Col C\" + rs[2]\n" }, { "answer_id": 208981, "author": "Scott Cowan", "author_id": 253, "author_profile": "https://Stackoverflow.com/users/253", "pm_score": 1, "selected": false, "text": "SELECT * FROM MyTable\n SELECT Col1,Col2,Col3 FROM MyTable\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17803/" ]
208,959
<p>I'm in the process of creating a class that stores metadata about a particular data source. The metadata is structured in a tree, very similar to how XML is structured. The metadata values can be integer, decimal, or string values.</p> <p>I'm curious if there is a good way in C++ to store variant data for a situation like this. I'd like for the variant to use standard libraries, so I'm avoiding the COM, Ole, and SQL VARIANT types that are available.</p> <p>My current solution looks something like this:</p> <pre><code>enum MetaValueType { MetaChar, MetaString, MetaShort, MetaInt, MetaFloat, MetaDouble }; union MetaUnion { char cValue; short sValue; int iValue; float fValue; double dValue; }; class MetaValue { ... private: MetaValueType ValueType; std::string StringValue; MetaUnion VariantValue; }; </code></pre> <p>The MetaValue class has various Get functions for obtaining the currently stored variant value, but it ends up making every query for a value a big block of if/else if statements to figure out which value I'm looking for.</p> <p>I've also explored storing the value as only a string, and performing conversions to get different variant types out, but as far as I've seen this leads to a bunch of internal string parsing and error handling which isn't pretty, opens up a big old can of precision and data loss issues with floating point values, and still doesn't eliminate the query if/else if issue stated above.</p> <p>Has anybody implemented or seen something that's cleaner to use for a C++ variant data type using standard libraries?</p>
[ { "answer_id": 208968, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 6, "selected": true, "text": "std::variant std::any" }, { "answer_id": 1739889, "author": "Fox", "author_id": 134793, "author_profile": "https://Stackoverflow.com/users/134793", "pm_score": 4, "selected": false, "text": "Derived create template <typename _T> Base * Factory::create (); Derived<_T> Variant Base * getType() isEmpty()" }, { "answer_id": 42210654, "author": "Matt Klein", "author_id": 1672027, "author_profile": "https://Stackoverflow.com/users/1672027", "pm_score": 3, "selected": false, "text": "std::variant" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21254/" ]
208,969
<p>Is it possible to encode an assignment into an expression tree?</p>
[ { "answer_id": 209002, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "int x;\nExpression<Func<int,int>> foo = (x=y); // Assign to x and return value\n CS0832: An expression tree may not contain an assignment operator\n" }, { "answer_id": 466266, "author": "Jirapong", "author_id": 28843, "author_profile": "https://Stackoverflow.com/users/28843", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing Microsoft.Scripting.Ast;\nusing Microsoft.Linq.Expressions;\nusing System.Reflection;\n\nnamespace dlr_sample\n{\n class Program\n {\n static void Main(string[] args)\n {\n List<Expression> statements = new List<Expression>();\n\n ParameterExpression x = Expression.Variable(typeof(int), \"r\");\n ParameterExpression y = Expression.Variable(typeof(int), \"y\");\n\n statements.Add(\n Expression.Assign(\n x,\n Expression.Constant(1)\n )\n );\n\n statements.Add(\n Expression.Assign(\n y,\n x\n )\n );\n\n MethodInfo cw = typeof(Console).GetMethod(\"WriteLine\", new Type[] { typeof(int) });\n\n statements.Add(\n Expression.Call(\n cw,\n y\n )\n );\n\n LambdaExpression lambda = Expression.Lambda(Expression.Scope(Expression.Block(statements), x, y));\n\n lambda.Compile().DynamicInvoke();\n Console.ReadLine();\n }\n }\n}\n" }, { "answer_id": 3972359, "author": "stakx - no longer contributing", "author_id": 240733, "author_profile": "https://Stackoverflow.com/users/240733", "pm_score": 2, "selected": false, "text": "Expression.Assign public static class AssignmentExpression\n{\n public static Expression Create(Expression left, Expression right)\n {\n return\n Expression.Call(\n null,\n typeof(AssignmentExpression)\n .GetMethod(\"AssignTo\", BindingFlags.NonPublic | BindingFlags.Static)\n .MakeGenericMethod(left.Type),\n left,\n right);\n }\n\n private static void AssignTo<T>(ref T left, T right) // note the 'ref', which is\n { // important when assigning\n left = right; // to value types!\n }\n}\n AssignmentExpression.Create() Expression.Assign()" }, { "answer_id": 4131653, "author": "Mark", "author_id": 64084, "author_profile": "https://Stackoverflow.com/users/64084", "pm_score": 3, "selected": false, "text": "/// <summary>\n/// Provides extensions for converting lambda functions into assignment actions\n/// </summary>\npublic static class ExpressionExtenstions\n{\n /// <summary>\n /// Converts a field/property retrieve expression into a field/property assign expression\n /// </summary>\n /// <typeparam name=\"TInstance\">The type of the instance.</typeparam>\n /// <typeparam name=\"TProp\">The type of the prop.</typeparam>\n /// <param name=\"fieldGetter\">The field getter.</param>\n /// <returns></returns>\n public static Expression<Action<TInstance, TProp>> ToFieldAssignExpression<TInstance, TProp>\n (\n this Expression<Func<TInstance, TProp>> fieldGetter\n )\n {\n if (fieldGetter == null)\n throw new ArgumentNullException(\"fieldGetter\");\n\n if (fieldGetter.Parameters.Count != 1 || !(fieldGetter.Body is MemberExpression))\n throw new ArgumentException(\n @\"Input expression must be a single parameter field getter, e.g. g => g._fieldToSet or function(g) g._fieldToSet\");\n\n var parms = new[]\n {\n fieldGetter.Parameters[0],\n Expression.Parameter(typeof (TProp), \"value\")\n };\n\n Expression body = Expression.Call(AssignmentHelper<TProp>.MethodInfoSetValue,\n new[] {fieldGetter.Body, parms[1]});\n\n return Expression.Lambda<Action<TInstance, TProp>>(body, parms);\n }\n\n\n public static Action<TInstance, TProp> ToFieldAssignment<TInstance, TProp>\n (\n this Expression<Func<TInstance, TProp>> fieldGetter\n )\n {\n return fieldGetter.ToFieldAssignExpression().Compile();\n }\n\n #region Nested type: AssignmentHelper\n\n private class AssignmentHelper<T>\n {\n internal static readonly MethodInfo MethodInfoSetValue =\n typeof (AssignmentHelper<T>).GetMethod(\"SetValue\", BindingFlags.NonPublic | BindingFlags.Static);\n\n private static void SetValue(ref T target, T value)\n {\n target = value;\n }\n }\n\n #endregion\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208969", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26054/" ]
208,977
<p>When I launch CruiseControl.NET with a particular configuration file I receive the following error:</p> <blockquote> <p>ThoughtWorks.CruiseControl.Core.Config.ConfigurationException: Duplicate node detected</p> </blockquote> <p>What does this mean, and what causes it?</p>
[ { "answer_id": 209002, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "int x;\nExpression<Func<int,int>> foo = (x=y); // Assign to x and return value\n CS0832: An expression tree may not contain an assignment operator\n" }, { "answer_id": 466266, "author": "Jirapong", "author_id": 28843, "author_profile": "https://Stackoverflow.com/users/28843", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing Microsoft.Scripting.Ast;\nusing Microsoft.Linq.Expressions;\nusing System.Reflection;\n\nnamespace dlr_sample\n{\n class Program\n {\n static void Main(string[] args)\n {\n List<Expression> statements = new List<Expression>();\n\n ParameterExpression x = Expression.Variable(typeof(int), \"r\");\n ParameterExpression y = Expression.Variable(typeof(int), \"y\");\n\n statements.Add(\n Expression.Assign(\n x,\n Expression.Constant(1)\n )\n );\n\n statements.Add(\n Expression.Assign(\n y,\n x\n )\n );\n\n MethodInfo cw = typeof(Console).GetMethod(\"WriteLine\", new Type[] { typeof(int) });\n\n statements.Add(\n Expression.Call(\n cw,\n y\n )\n );\n\n LambdaExpression lambda = Expression.Lambda(Expression.Scope(Expression.Block(statements), x, y));\n\n lambda.Compile().DynamicInvoke();\n Console.ReadLine();\n }\n }\n}\n" }, { "answer_id": 3972359, "author": "stakx - no longer contributing", "author_id": 240733, "author_profile": "https://Stackoverflow.com/users/240733", "pm_score": 2, "selected": false, "text": "Expression.Assign public static class AssignmentExpression\n{\n public static Expression Create(Expression left, Expression right)\n {\n return\n Expression.Call(\n null,\n typeof(AssignmentExpression)\n .GetMethod(\"AssignTo\", BindingFlags.NonPublic | BindingFlags.Static)\n .MakeGenericMethod(left.Type),\n left,\n right);\n }\n\n private static void AssignTo<T>(ref T left, T right) // note the 'ref', which is\n { // important when assigning\n left = right; // to value types!\n }\n}\n AssignmentExpression.Create() Expression.Assign()" }, { "answer_id": 4131653, "author": "Mark", "author_id": 64084, "author_profile": "https://Stackoverflow.com/users/64084", "pm_score": 3, "selected": false, "text": "/// <summary>\n/// Provides extensions for converting lambda functions into assignment actions\n/// </summary>\npublic static class ExpressionExtenstions\n{\n /// <summary>\n /// Converts a field/property retrieve expression into a field/property assign expression\n /// </summary>\n /// <typeparam name=\"TInstance\">The type of the instance.</typeparam>\n /// <typeparam name=\"TProp\">The type of the prop.</typeparam>\n /// <param name=\"fieldGetter\">The field getter.</param>\n /// <returns></returns>\n public static Expression<Action<TInstance, TProp>> ToFieldAssignExpression<TInstance, TProp>\n (\n this Expression<Func<TInstance, TProp>> fieldGetter\n )\n {\n if (fieldGetter == null)\n throw new ArgumentNullException(\"fieldGetter\");\n\n if (fieldGetter.Parameters.Count != 1 || !(fieldGetter.Body is MemberExpression))\n throw new ArgumentException(\n @\"Input expression must be a single parameter field getter, e.g. g => g._fieldToSet or function(g) g._fieldToSet\");\n\n var parms = new[]\n {\n fieldGetter.Parameters[0],\n Expression.Parameter(typeof (TProp), \"value\")\n };\n\n Expression body = Expression.Call(AssignmentHelper<TProp>.MethodInfoSetValue,\n new[] {fieldGetter.Body, parms[1]});\n\n return Expression.Lambda<Action<TInstance, TProp>>(body, parms);\n }\n\n\n public static Action<TInstance, TProp> ToFieldAssignment<TInstance, TProp>\n (\n this Expression<Func<TInstance, TProp>> fieldGetter\n )\n {\n return fieldGetter.ToFieldAssignExpression().Compile();\n }\n\n #region Nested type: AssignmentHelper\n\n private class AssignmentHelper<T>\n {\n internal static readonly MethodInfo MethodInfoSetValue =\n typeof (AssignmentHelper<T>).GetMethod(\"SetValue\", BindingFlags.NonPublic | BindingFlags.Static);\n\n private static void SetValue(ref T target, T value)\n {\n target = value;\n }\n }\n\n #endregion\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208977", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13172/" ]
208,978
<p>I'm trying to write an audio analysis application, and I need to identify local maxima in a 2D array which represents a spectrogram. I've already got an open source library that can generate the spectrogram using Fast Fourier Transforms, but I was wondering if anybody knew of any good libraries to help me with actually finding the maxima? I'm not quite sure what to search Google for - the best I could think of was "numerical library" but that hasn't got me very far.</p> <p>Preferably in C, but I'm open to other suggestions.</p>
[ { "answer_id": 209002, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "int x;\nExpression<Func<int,int>> foo = (x=y); // Assign to x and return value\n CS0832: An expression tree may not contain an assignment operator\n" }, { "answer_id": 466266, "author": "Jirapong", "author_id": 28843, "author_profile": "https://Stackoverflow.com/users/28843", "pm_score": 4, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing Microsoft.Scripting.Ast;\nusing Microsoft.Linq.Expressions;\nusing System.Reflection;\n\nnamespace dlr_sample\n{\n class Program\n {\n static void Main(string[] args)\n {\n List<Expression> statements = new List<Expression>();\n\n ParameterExpression x = Expression.Variable(typeof(int), \"r\");\n ParameterExpression y = Expression.Variable(typeof(int), \"y\");\n\n statements.Add(\n Expression.Assign(\n x,\n Expression.Constant(1)\n )\n );\n\n statements.Add(\n Expression.Assign(\n y,\n x\n )\n );\n\n MethodInfo cw = typeof(Console).GetMethod(\"WriteLine\", new Type[] { typeof(int) });\n\n statements.Add(\n Expression.Call(\n cw,\n y\n )\n );\n\n LambdaExpression lambda = Expression.Lambda(Expression.Scope(Expression.Block(statements), x, y));\n\n lambda.Compile().DynamicInvoke();\n Console.ReadLine();\n }\n }\n}\n" }, { "answer_id": 3972359, "author": "stakx - no longer contributing", "author_id": 240733, "author_profile": "https://Stackoverflow.com/users/240733", "pm_score": 2, "selected": false, "text": "Expression.Assign public static class AssignmentExpression\n{\n public static Expression Create(Expression left, Expression right)\n {\n return\n Expression.Call(\n null,\n typeof(AssignmentExpression)\n .GetMethod(\"AssignTo\", BindingFlags.NonPublic | BindingFlags.Static)\n .MakeGenericMethod(left.Type),\n left,\n right);\n }\n\n private static void AssignTo<T>(ref T left, T right) // note the 'ref', which is\n { // important when assigning\n left = right; // to value types!\n }\n}\n AssignmentExpression.Create() Expression.Assign()" }, { "answer_id": 4131653, "author": "Mark", "author_id": 64084, "author_profile": "https://Stackoverflow.com/users/64084", "pm_score": 3, "selected": false, "text": "/// <summary>\n/// Provides extensions for converting lambda functions into assignment actions\n/// </summary>\npublic static class ExpressionExtenstions\n{\n /// <summary>\n /// Converts a field/property retrieve expression into a field/property assign expression\n /// </summary>\n /// <typeparam name=\"TInstance\">The type of the instance.</typeparam>\n /// <typeparam name=\"TProp\">The type of the prop.</typeparam>\n /// <param name=\"fieldGetter\">The field getter.</param>\n /// <returns></returns>\n public static Expression<Action<TInstance, TProp>> ToFieldAssignExpression<TInstance, TProp>\n (\n this Expression<Func<TInstance, TProp>> fieldGetter\n )\n {\n if (fieldGetter == null)\n throw new ArgumentNullException(\"fieldGetter\");\n\n if (fieldGetter.Parameters.Count != 1 || !(fieldGetter.Body is MemberExpression))\n throw new ArgumentException(\n @\"Input expression must be a single parameter field getter, e.g. g => g._fieldToSet or function(g) g._fieldToSet\");\n\n var parms = new[]\n {\n fieldGetter.Parameters[0],\n Expression.Parameter(typeof (TProp), \"value\")\n };\n\n Expression body = Expression.Call(AssignmentHelper<TProp>.MethodInfoSetValue,\n new[] {fieldGetter.Body, parms[1]});\n\n return Expression.Lambda<Action<TInstance, TProp>>(body, parms);\n }\n\n\n public static Action<TInstance, TProp> ToFieldAssignment<TInstance, TProp>\n (\n this Expression<Func<TInstance, TProp>> fieldGetter\n )\n {\n return fieldGetter.ToFieldAssignExpression().Compile();\n }\n\n #region Nested type: AssignmentHelper\n\n private class AssignmentHelper<T>\n {\n internal static readonly MethodInfo MethodInfoSetValue =\n typeof (AssignmentHelper<T>).GetMethod(\"SetValue\", BindingFlags.NonPublic | BindingFlags.Static);\n\n private static void SetValue(ref T target, T value)\n {\n target = value;\n }\n }\n\n #endregion\n}\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208978", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4397/" ]
208,993
<p>I have an asp.net page which sends content of a file to the client, so the browser shows the save as dialog to download the file. This page is displayed in a popup and when the user clicks the save button, it closes automatically and the download starts.</p> <p>On windows server 2003, it works fine. On vista with other browsers, also works fine. But when I try with IE7 &amp; Vista, the popup opens, and closes after about a second without displaying the file download dialog. How can I solve this?</p> <p>The code I use for response generation is:</p> <pre><code>FileStream fileStream = new FileStream(filePath, FileMode.Open); int fileSize = (int)fileStream.Length; byte[] buffer = new byte[fileSize]; fileStream.Read(buffer, 0, (int)fileSize); fileStream.Close(); Response.Clear(); Response.Buffer = true; Response.BufferOutput = true; Response.ContentType = "application / octet - stream"; Response.AddHeader("Content-Length", buffer.Length.ToString()); Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); Response.AddHeader("Extension", Path.GetExtension(filename)); Response.ContentEncoding = System.Text.Encoding.GetEncoding("windows-1254"); Response.BinaryWrite(buffer); Response.Flush(); Response.End(); </code></pre> <p>And I am opening the popup with this javascript:</p> <pre><code>window.open ('Download.aspx?filename=somefile.ext','downloadWindow','location=0,status=0,scrollbars=0,width=1,height=1'); </code></pre> <p><strong>EDIT:</strong> I corrected the spaces but unfortunately they are not the problem.</p> <p><strong>EDIT 2:</strong>: Seems that this problem is not related to Vista but IE only. I also discovered that it works fine when the project is run on the development server locally but when working as connected to publish server, it fails to download the file.</p>
[ { "answer_id": 208999, "author": "swilliams", "author_id": 736, "author_profile": "https://Stackoverflow.com/users/736", "pm_score": 3, "selected": false, "text": "ContentType application/octet-stream" }, { "answer_id": 209009, "author": "TheSmurf", "author_id": 1975282, "author_profile": "https://Stackoverflow.com/users/1975282", "pm_score": 1, "selected": false, "text": "Response.ContentType = \"application/x-download\";\nResponse.AddHeader(\"Content-Disposition\", \"attachment; filename=\" + fileName);\nResponse.CacheControl = \"public\";\nResponse.OutputStream.Write(byteArr, 0, byteArr.Length);\nResponse.End();\n" }, { "answer_id": 709003, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Response.ContentType = \"text/txt\";\nResponse.AppendHeader(\"Content-Disposition\", \"attachment; filename=\"+DownloadFileName);\nResponse.Write(MyFileContent_Text_);\nResponse.End();\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208993", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31505/" ]
208,998
<pre><code>something.each do |x| #lots of stuff end if some_condition </code></pre>
[ { "answer_id": 209012, "author": "workmad3", "author_id": 16035, "author_profile": "https://Stackoverflow.com/users/16035", "pm_score": 2, "selected": false, "text": "if some_condition\n" }, { "answer_id": 209419, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 3, "selected": false, "text": "bail_out if reqd_param.nil?\n\nif its_gonna_be_long then\n long_exec stmt1\n long_exec stmt2\n ....\nend\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/208998", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20714/" ]
209,005
<p>I am trying to create a MATLAB class with a member variable that's being updated as a result of a method invocation, but when I try to change the property within the class it (apperently, from what I understood from MATLAB's memory management) creates a copy of the object and then modifies it, leaving the original object's property untouched.</p> <pre><code>classdef testprop properties numRequests=0; end methods function Request(this, val) disp(val); this.numRequests=this.numRequests+1; end end end </code></pre> <p>.</p> <pre><code>&gt;&gt; a=testprop; &gt;&gt; a.Request(9); &gt;&gt; a.Request(5); &gt;&gt; a.numRequests ans = 0 </code></pre>
[ { "answer_id": 209159, "author": "Azim J", "author_id": 4612, "author_profile": "https://Stackoverflow.com/users/4612", "pm_score": 5, "selected": false, "text": ">> a=testprop\n>> a.Request(5); % will NOT change the value of a.numRequests.\n5\n\n>> a.Request(5) \n5\n\n>> a.numRequests\nans = \n 0\n\n>> a=a.Request; % However, this will work but as you it makes a copy of variable, a.\n5\n\n>> a=a.Request; \n5\n\n>> a.numRequests\nans =\n 2\n Request function this = Request(this, val)`\n classdef testprop < handle\n >> a.Request(5);\n>> a.Request(5);\n>> a.numRequests\nans = \n 2\n" }, { "answer_id": 278302, "author": "Marc", "author_id": 8478, "author_profile": "https://Stackoverflow.com/users/8478", "pm_score": 3, "selected": false, "text": "struct" }, { "answer_id": 673190, "author": "Kamran Bigdely", "author_id": 81306, "author_profile": "https://Stackoverflow.com/users/81306", "pm_score": 3, "selected": false, "text": "a=a.Request(1)\n function this = Request(this, val)\n >> a = testprop;\n>> a = a.Request(1); \n>> a.numRequests\n\nans = 1\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209005", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
209,015
<p>I have a colleague who insists that his code doesn't need comments, it's &quot;self documenting.&quot;</p> <p>I've reviewed his code, and while it's clearer than code which I've seen others produce, I still disagree that self-documenting code is as complete and useful as well commented and documented code.</p> <p>Help me understand <strong>his</strong> point of view.</p> <ul> <li>What is self documenting code</li> <li>Can it really replace well commented and documented code</li> <li>Are there situations where it's better than well documented and commented code</li> <li>Are there examples where code cannot possibly be self-documenting without comments</li> </ul> <p>Maybe it's just my own limitations, but I don't see how it can be a good practice.</p> <p>This is not meant to be an argument - please don't bring up reasons why well commented and documented code is high priority - there are many resources showing this, but they aren't convincing to my peer. I believe I need to more fully understand his perspective to convince him otherwise. Start a new question if you must, but don't argue here.</p> <p>Also, those of you who are arguing against self documenting code -this is primarily to help me understand the perspective (ie, positive aspects) of self-documenting code evangelists.</p>
[ { "answer_id": 209087, "author": "ddimitrov", "author_id": 18187, "author_profile": "https://Stackoverflow.com/users/18187", "pm_score": 3, "selected": false, "text": "/**\n * Sets the value of foobar.\n *\n * @foobar is the new vaue of foobar.\n */\n public void setFoobar(Object foobar) {\n this.foobar = foobar;\n }\n /**\n * The serialization of the foobar object is used to synchronize the qux task.\n * The default value is unique instance, override if needed.\n */\n public void setFoobar(Object foobar) {\n this.foobar = foobar;\n }\n" }, { "answer_id": 209088, "author": "Miguel Ping", "author_id": 22992, "author_profile": "https://Stackoverflow.com/users/22992", "pm_score": 0, "selected": false, "text": "//iterate from 0 to 100\nfor(int i=0; i < 100; i++) {\n println i\n}\n int calc(int a, int b) {\n return sqrt(a*a + b*b); //pythagoras theorem\n}\n" }, { "answer_id": 209089, "author": "ine", "author_id": 4965, "author_profile": "https://Stackoverflow.com/users/4965", "pm_score": 9, "selected": false, "text": "float a, b, c; a=9.81; b=5; c= .5*a*(b^2);\n const float gravitationalForce = 9.81;\nfloat timeInSeconds = 5;\nfloat displacement = (1 / 2) * gravitationalForce * (timeInSeconds ^ 2);\n /* compute displacement with Newton's equation x = vₒt + ½at² */\nconst float gravitationalForce = 9.81;\nfloat timeInSeconds = 5;\nfloat displacement = (1 / 2) * gravitationalForce * (timeInSeconds ^ 2);\n float computeDisplacement(float timeInSeconds) {\n const float gravitationalForce = 9.81;\n float displacement = (1 / 2) * gravitationalForce * (timeInSeconds ^ 2);\n return displacement;\n}\n const float a = 9.81; //gravitational force\nfloat b = 5; //time in seconds\nfloat c = (1/2)*a*(b^2) //multiply the time and gravity together to get displacement.\n" }, { "answer_id": 209109, "author": "Tyler Jensen", "author_id": 28617, "author_profile": "https://Stackoverflow.com/users/28617", "pm_score": 1, "selected": false, "text": "//For example, the above text deals with what is a useful comment\n" }, { "answer_id": 209146, "author": "Steven Huwig", "author_id": 28604, "author_profile": "https://Stackoverflow.com/users/28604", "pm_score": 4, "selected": false, "text": "print \"Hello, World!\"\n factorial n = product [1..n]\n from BeautifulSoup import BeautifulSoup, Tag\n\ndef replace_a_href_with_span(soup):\n links = soup.findAll(\"a\")\n for link in links:\n tag = Tag(soup, \"span\", [(\"class\", \"looksLikeLink\")])\n tag.contents = link.contents\n link.replaceWith(tag)\n" }, { "answer_id": 210414, "author": "Mike Burton", "author_id": 22225, "author_profile": "https://Stackoverflow.com/users/22225", "pm_score": 4, "selected": false, "text": "/* compute displacement with Newton's equation x = v0t + ½at^2 */\nconst float gravitationalForce = 9.81;\nfloat timeInSeconds = 5;\nfloat displacement = (1 / 2) * gravitationalForce * (timeInSeconds ^ 2);\n const float accelerationDueToGravity = 9.81;\nfloat timeInSeconds = 5;\nfloat displacement = NewtonianPhysics.CalculateDisplacement(accelerationDueToGravity, timeInSeconds);\n" }, { "answer_id": 210913, "author": "Pavel Feldman", "author_id": 5507, "author_profile": "https://Stackoverflow.com/users/5507", "pm_score": 2, "selected": false, "text": "public Result whatYouWantToDo(){\n howYouDoItStep1();\n howYouDoItStep2();\n return resultOfWhatYouHavDone;\n}\n" }, { "answer_id": 211427, "author": "CaRDiaK", "author_id": 15628, "author_profile": "https://Stackoverflow.com/users/15628", "pm_score": 1, "selected": false, "text": "' check database is available\n ' if it is then allow the procedure\n ' if it isnt roll back and tidy up \n' move onto something else\n ' check database is available\n if checkDBStateResult(currentDB) = Open then \n ' if it is then allow the procedure\n proc.Ok = True \n else\n ' if it isnt roll back\n proc.Ok = False\n CleanUp()\n end if\n" }, { "answer_id": 306870, "author": "jsfain", "author_id": 39466, "author_profile": "https://Stackoverflow.com/users/39466", "pm_score": 1, "selected": false, "text": "> from BeautifulSoup import\n> BeautifulSoup, Tag def\n> replace_a_href_with_span(soup):\n> links = soup.findAll(\"a\")\n> for link in links:\n> tag = Tag(soup, \"span\", [(\"class\", \"looksLikeLink\")])\n> tag.contents = link.contents\n> link.replaceWith(tag)\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209015", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2915/" ]
209,023
<p>I have a Google App Engine that has a form. When the user clicks on the submit button, AJAX operation will be called, and the server will output something to append to the end of the very page where it comes from. How, I have a Django template, and I intend to use jquery. I have the following view:</p> <pre><code>&lt;html&gt; &lt;head&gt; &lt;title&gt;&lt;/title&gt; &lt;script type="text/javascript" src="scripts/jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="scripts/scripts.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; welcome &lt;form id="SubmitForm" action="/" method="POST"&gt; &lt;input type="file" name="vsprojFiles" /&gt; &lt;br/&gt; &lt;input type="submit" id="SubmitButton"/&gt; &lt;/form&gt; &lt;div id="Testing"&gt; {{thebest}} &lt;/div&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Here's the script in scripts.js:</p> <pre><code>$(function() { $("#SubmitForm").click(submitMe); }); var submitMe = function(){ //alert('no way'); var f = $('#SubmitForm'); var action = f.attr("action"); var serializedForm = f.serialize(); $.ajax( { type: 'post', data: serializedForm, url: form_action, success: function( result ) { $('#SubmitForm').after( "&lt;div&gt;&lt;tt&gt;" + result + "&lt;/tt&gt;&lt;/div&gt;" ); } } ); }; </code></pre> <p>And here's my controller code:</p> <pre><code>from google.appengine.api import users from google.appengine.ext import webapp from google.appengine.ext import db from google.appengine.ext.webapp import template from google.appengine.api.urlfetch_errors import * import cgi import wsgiref.handlers import os import sys import re import urllib from django.utils import simplejson class MainPage(webapp.RequestHandler): def get(self): path = os.path.join(os.path.dirname(__file__), 'Index.html') template_values={'thebest': 'thebest'} tmplRender =template.render(path, template_values) self.response.out.write(tmplRender) pass def Post(self): print &gt;&gt;sys.__stderr__,'me posting' result = 'grsgres' self.response.out.write(simplejson.dumps(result)) </code></pre> <p>As you can see, when the user clicks on the submitbutton, the controller method Mainpage.post will be called.</p> <p>Now I want to display the content of the 'result' variable right after the form, how can I do it?</p>
[ { "answer_id": 266862, "author": "Seamus", "author_id": 30443, "author_profile": "https://Stackoverflow.com/users/30443", "pm_score": 2, "selected": false, "text": "//...\n success: function( result ) { \n console.log( result );\n $('#SubmitForm').after( \"<div><tt>\" + \n// ...\n" }, { "answer_id": 832625, "author": "Rasiel", "author_id": 2041708, "author_profile": "https://Stackoverflow.com/users/2041708", "pm_score": 1, "selected": false, "text": "success: function(json){\n $('#gallons_cont').html(json['gallons']);\n $('#area_cont').html(json['area']);\n $('#usage_cont').html(json['usage'])\n $('#results_json').show('slow'); \n },\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209023", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3834/" ]
209,029
<p>I have an <code>input type="image"</code>. This acts like the cell notes in Microsoft Excel. If someone enters a number into the text box that this <code>input-image</code> is paired with, I setup an event handler for the <code>input-image</code>. Then when the user clicks the <code>image</code>, they get a little popup to add some notes to the data.</p> <p>My problem is that when a user enters a zero into the text box, I need to disable the <code>input-image</code>'s event handler. I have tried the following, but to no avail.</p> <pre><code>$('#myimage').click(function { return false; }); </code></pre>
[ { "answer_id": 209044, "author": "John Boker", "author_id": 2847, "author_profile": "https://Stackoverflow.com/users/2847", "pm_score": 5, "selected": false, "text": "$(\"#myimage\").unbind(\"click\");\n" }, { "answer_id": 209079, "author": "Mnebuerquo", "author_id": 5114, "author_profile": "https://Stackoverflow.com/users/5114", "pm_score": 5, "selected": false, "text": "$('#myimage').unbind('click');\n" }, { "answer_id": 210345, "author": "samjudson", "author_id": 1908, "author_profile": "https://Stackoverflow.com/users/1908", "pm_score": 12, "selected": true, "text": ".bind() .unbind() $('#myimage').click(function() { return false; }); // Adds another click event\n$('#myimage').off('click');\n$('#myimage').on('click.mynamespace', function() { /* Do stuff */ });\n$('#myimage').off('click.mynamespace');\n $('#myimage').click(function() { return false; }); // Adds another click event\n $('#myimage').unbind('click');\n $('#myimage').bind('click.mynamespace', function() { /* Do stuff */ });\n $('#myimage').unbind('click.mynamespace');\n" }, { "answer_id": 1173434, "author": "MacAnthony", "author_id": 73901, "author_profile": "https://Stackoverflow.com/users/73901", "pm_score": 6, "selected": false, "text": "live() $('#myimage:not(.disabled)').live('click', myclickevent);\n\n$('#mydisablebutton').click( function () { $('#myimage').addClass('disabled'); });\n #mydisablebutton #myimage .live()" }, { "answer_id": 3169337, "author": "jquery_user", "author_id": 382419, "author_profile": "https://Stackoverflow.com/users/382419", "pm_score": 3, "selected": false, "text": "function userPageLock(){\n $(\"body\").bind(\"ajaxComplete.lockpage\", function(){\n $(\"body\").unbind(\"ajaxComplete.lockpage\");\n executePageLock(); \n });\n}; \n\nfunction executePageLock(){\n //do something\n}\n" }, { "answer_id": 6952895, "author": "hayesgm", "author_id": 320471, "author_profile": "https://Stackoverflow.com/users/320471", "pm_score": 5, "selected": false, "text": " $('.myLink').bind('click', function() {\n //do some things\n\n $(this).unbind('click', arguments.callee); //unbind *just this handler*\n });\n" }, { "answer_id": 9909931, "author": "dwhittenburg", "author_id": 234246, "author_profile": "https://Stackoverflow.com/users/234246", "pm_score": 5, "selected": false, "text": ".prop(\"onclick\", null).attr(\"onclick\", null)\n" }, { "answer_id": 11207888, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "$('#container').on('click','span',function(eo){\n alert(1);\n\n $(this).off(); //seams easy, but does not work\n\n $('#container').off('click','span'); //clears click event for every span\n\n $(this).on(\"click\",function(){return false;}); //this works.\n\n});​\n" }, { "answer_id": 17123667, "author": "Somnath Kharat", "author_id": 2194674, "author_profile": "https://Stackoverflow.com/users/2194674", "pm_score": 2, "selected": false, "text": "$('#myimage').removeAttr(\"click\");\n" }, { "answer_id": 21270340, "author": "davaus", "author_id": 1722805, "author_profile": "https://Stackoverflow.com/users/1722805", "pm_score": 4, "selected": false, "text": "onclick <input id=\"addreport\" type=\"button\" value=\"Add New Report\" onclick=\"openAdd()\" />\n .off() .unbind() $(\"#addreport\").on(\"click\", \"\", function (e) {\n openAdd();\n});\n $(\"#addreport\").off(\"click\")\n" }, { "answer_id": 21576228, "author": "alexpls", "author_id": 1432982, "author_profile": "https://Stackoverflow.com/users/1432982", "pm_score": 3, "selected": false, "text": "$( \"#foo\" ).off( \".myNamespace\" );" }, { "answer_id": 21721908, "author": "Avatar", "author_id": 1066234, "author_profile": "https://Stackoverflow.com/users/1066234", "pm_score": 1, "selected": false, "text": "on() $(document).on(\"click\", \".button\", function() {\n doSomething();\n});\n // prevent another click on the button by assigning another class\n$(\".button\").attr(\"class\",\"buttonOff\");\n" }, { "answer_id": 25617462, "author": "Ishan Liyanage", "author_id": 2334422, "author_profile": "https://Stackoverflow.com/users/2334422", "pm_score": 2, "selected": false, "text": "onclick html removeAttr ($(this).removeAttr('onclick')) unbind($(this).unbind('click'))" }, { "answer_id": 27743898, "author": "Shahrukh Azeem", "author_id": 4000669, "author_profile": "https://Stackoverflow.com/users/4000669", "pm_score": 3, "selected": false, "text": "$(element).prop('onclick', null);" }, { "answer_id": 34411440, "author": "mysticmo", "author_id": 4022034, "author_profile": "https://Stackoverflow.com/users/4022034", "pm_score": 1, "selected": false, "text": "(function($){\n\n $(\"#btn_add\").on(\"click\",function(){\n $(\"#btn_click\").on(\"click\",added_handler);\n alert(\"Added new handler to button 1\");\n });\n\n \n \n $(\"#btn_remove\").on(\"click\",function(){\n $(\"#btn_click\").off(\"click\",added_handler);\n alert(\"Removed new handler to button 1\");\n });\n\n \n function fixed_handler(){\n alert(\"Fixed handler\");\n }\n \n function added_handler(){\n alert(\"new handler\");\n }\n \n $(\"#btn_click\").on(\"click\",fixed_handler);\n $(\"#btn_fixed\").on(\"click\",fixed_handler);\n \n \n})(jQuery); <script src=\"https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js\"></script>\n<button id=\"btn_click\">Button 1</button>\n <button id=\"btn_add\">Add Handler</button>\n <button id=\"btn_remove\">Remove Handler</button>\n <button id=\"btn_fixed\">Fixed Handler</button>" }, { "answer_id": 38051238, "author": "Ilia", "author_id": 1455661, "author_profile": "https://Stackoverflow.com/users/1455661", "pm_score": 3, "selected": false, "text": ".on() $('body').on('click', '.dynamicTarget', function () {\n // Code goes here\n});\n unbind() .off() $(\"body\").undelegate(\".dynamicTarget\", \"click\")\n" }, { "answer_id": 39332690, "author": "Silviu Preda", "author_id": 1996226, "author_profile": "https://Stackoverflow.com/users/1996226", "pm_score": 2, "selected": false, "text": "var myElement = document.getElementById(\"your_ID\");\nmyElement.onclick = null;\n function eh(event){...}\nvar myElement = document.getElementById(\"your_ID\");\nmyElement.addEventListener(\"click\",eh); // add event handler\nmyElement.removeEventListener(\"click\",eh); //remove it\n" }, { "answer_id": 47767192, "author": "Aakash", "author_id": 4742733, "author_profile": "https://Stackoverflow.com/users/4742733", "pm_score": 3, "selected": false, "text": "remove event-handlers HTML structure event handlers element child nodes jQuery's clone() var original, clone;\n// element with id my-div and its child nodes have some event-handlers\noriginal = $('#my-div');\nclone = original.clone();\n//\noriginal.replaceWith(clone);\n clone original event-handlers" }, { "answer_id": 56319115, "author": "ow3n", "author_id": 441878, "author_profile": "https://Stackoverflow.com/users/441878", "pm_score": 4, "selected": false, "text": "$(document).on() // add the listener\n$(document).on('click','.element',function(){\n // stuff\n});\n\n// remove the listener\n$(document).off(\"click\", \".element\");\n\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209029", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13800/" ]
209,043
<p>I am used to using Atlas. Recently i have started transitioning to jQuery and sometimes prototype. The project that i'm currently working on is using prototype.</p> <p>In Prototype, is there an easy way to get the browser name and version? I've looked over the API documentation and can't seem to find it.</p>
[ { "answer_id": 209537, "author": "Remy Sharp", "author_id": 22617, "author_profile": "https://Stackoverflow.com/users/22617", "pm_score": 2, "selected": false, "text": "var Browser = Class.create({\n initialize: function() {\n var userAgent = navigator.userAgent.toLowerCase();\n this.version = (userAgent.match( /.+(?:rv|it|ra|ie)[\\/: ]([\\d.]+)/ ) || [])[1];\n this.webkit = /webkit/.test( userAgent );\n this.opera = /opera/.test( userAgent );\n this.msie = /msie/.test( userAgent ) && !/opera/.test( userAgent );\n this.mozilla = /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent );\n }\n});\n" }, { "answer_id": 238803, "author": "Grant Hutchins", "author_id": 6304, "author_profile": "https://Stackoverflow.com/users/6304", "pm_score": 3, "selected": false, "text": "prototype.js var Prototype = {\n Browser: {\n IE: !!(window.attachEvent &&\n navigator.userAgent.indexOf('Opera') === -1),\n Opera: navigator.userAgent.indexOf('Opera') > -1,\n WebKit: navigator.userAgent.indexOf('AppleWebKit/') > -1,\n Gecko: navigator.userAgent.indexOf('Gecko') > -1 && \n navigator.userAgent.indexOf('KHTML') === -1,\n MobileSafari: !!navigator.userAgent.match(/Apple.*Mobile.*Safari/)\n },\n\n BrowserFeatures: {\n XPath: !!document.evaluate,\n SelectorsAPI: !!document.querySelector,\n ElementExtensions: !!window.HTMLElement,\n SpecificElementExtensions: \n document.createElement('div')['__proto__'] &&\n document.createElement('div')['__proto__'] !== \n document.createElement('form')['__proto__']\n },\n}\n Prototype.Browser.IE Prototype.BrowserFeatures.XPath" }, { "answer_id": 626281, "author": "sepehr", "author_id": 65732, "author_profile": "https://Stackoverflow.com/users/65732", "pm_score": 4, "selected": false, "text": "Prototype.Browser.IE6 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf(\"MSIE\")+5)) == 6;\nPrototype.Browser.IE7 = Prototype.Browser.IE && parseInt(navigator.userAgent.substring(navigator.userAgent.indexOf(\"MSIE\")+5)) == 7;\nPrototype.Browser.IE8 = Prototype.Browser.IE && !Prototype.Browser.IE6 && !Prototype.Browser.IE7;\n" }, { "answer_id": 1825409, "author": "toutatis", "author_id": 222017, "author_profile": "https://Stackoverflow.com/users/222017", "pm_score": 2, "selected": false, "text": "var Prototype = { ... };\n // extension\nif (Prototype.Browser.IE) {\n if (/MSIE (\\d+\\.\\d+);/.test(navigator.userAgent)) {\n Prototype.BrowserFeatures['Version'] = new Number(RegExp.$1);\n }\n}\n if (Prototype.Browser.IE && Prototype.BrowserFeatures['Version'] == 8) { ... }\n" }, { "answer_id": 4770543, "author": "Mandeep", "author_id": 481027, "author_profile": "https://Stackoverflow.com/users/481027", "pm_score": 2, "selected": false, "text": "Object.extend(Prototype.Browser, {\n ie6: (/MSIE (\\d+\\.\\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 6 ? true : false) : false,\n ie7: (/MSIE (\\d+\\.\\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 7 ? true : false) : false,\n ie8: (/MSIE (\\d+\\.\\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 8 ? true : false) : false,\n ie9: (/MSIE (\\d+\\.\\d+);/.test(navigator.userAgent)) ? (Number(RegExp.$1) == 9 ? true : false) : false\n});\n" }, { "answer_id": 9438123, "author": "Developer_From_India", "author_id": 1231662, "author_profile": "https://Stackoverflow.com/users/1231662", "pm_score": 0, "selected": false, "text": " <script type=\"text/JavaScript\">\n\n function getBrowserVersion()\n {\n var msg = \"Not Recognised Browser\";\n\n if (/Firefox[\\/\\s](\\d+\\.\\d+)/.test(navigator.userAgent))\n {\n var ffversion = new Number(RegExp.$1)\n\n for (var i = 1; i < 20; i++)\n {\n if (ffversion == i)\n {\n msg = \"FF\" + i + \"x\";\n break;\n }\n }\n }\n else if (/MSIE (\\d+\\.\\d+);/.test(navigator.userAgent))\n {\n var ieversion = new Number(RegExp.$1)\n\n for (var i = 1; i < 20; i++)\n {\n if (ieversion == i)\n {\n msg = \"IE\" + i + \"x\";\n break;\n }\n }\n }\n\n alert(msg); // return msg; \n }\n\n </script>\n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209043", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6350/" ]
209,067
<p>Since Access 2003 doesn't have the control anchoring functionality as exists in 2007, I was wondering if anyone has or is aware of some VBA script, or a freeware control, that can give this functionality?</p>
[ { "answer_id": 209827, "author": "Godeke", "author_id": 28006, "author_profile": "https://Stackoverflow.com/users/28006", "pm_score": 4, "selected": true, "text": "resizeRatio = currentFormWidth / baseFormWidth\n\ncontrol.left = baseLeft * resizeRatio\ncontrol.width = baseWidth * resizeRatio\n resizeRatio = (currentFormWidth - labelsAreaWidth) / (baseFormWidth - labelsAreaWidth)\n\ncontrol.left = (baseLeft - labelsAreaWidth) * resizeRatio + labelsAreaWidth\ncontrol.width = baseWidth * resizeRatio \n" } ]
2008/10/16
[ "https://Stackoverflow.com/questions/209067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8678/" ]