qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
99,211
<p>I am trying to get Haml to work with my Ruby on Rails project. I am new to Ruby on Rails and I really like it. However, when I attempt to add an <code>aplication.html.haml</code> or <code>index.html.haml</code> for a view, I just receive errors.</p> <p>I am using NetBeans as my IDE.</p>
[ { "answer_id": 105542, "author": "Ryan McGeary", "author_id": 8985, "author_profile": "https://Stackoverflow.com/users/8985", "pm_score": 5, "selected": false, "text": "Gemfile gem \"haml\"\n bundle install `-- app\n `-- views\n |-- layouts\n | `-- application.html.haml\n `-- users\n |-- edit.html.haml\n |-- index.html.haml\n |-- new.html.haml\n `-- show.html.haml\n" }, { "answer_id": 106547, "author": "Pete", "author_id": 13472, "author_profile": "https://Stackoverflow.com/users/13472", "pm_score": 3, "selected": false, "text": "gem list --local | grep haml\n sudo gem install haml\n # cd ../\n# haml --rails <yourproject>\n" }, { "answer_id": 774022, "author": "gdelfino", "author_id": 93947, "author_profile": "https://Stackoverflow.com/users/93947", "pm_score": 4, "selected": false, "text": "$ haml\n%p \n %span Hello World!\n <p>\n <span>Hello World!</span>\n</p>\n" }, { "answer_id": 1610001, "author": "railsuser1984", "author_id": 194909, "author_profile": "https://Stackoverflow.com/users/194909", "pm_score": 1, "selected": false, "text": "sudo ln haml /usr/bin/\n" }, { "answer_id": 2888046, "author": "kch", "author_id": 13989, "author_profile": "https://Stackoverflow.com/users/13989", "pm_score": 6, "selected": false, "text": "gem \"haml\", '3.0.25' Gemfile haml --rails ." }, { "answer_id": 5034759, "author": "bowsersenior", "author_id": 457819, "author_profile": "https://Stackoverflow.com/users/457819", "pm_score": 6, "selected": false, "text": "gem 'haml' Gemfile haml erb config/application.rb config.generators do |g|\n g.template_engine :haml\n\n # you can also specify a different test framework or ORM here\n # g.test_framework :rspec\n # g.orm :mongoid\nend \n" }, { "answer_id": 10503861, "author": "Matthias", "author_id": 600104, "author_profile": "https://Stackoverflow.com/users/600104", "pm_score": 5, "selected": false, "text": "gem \"haml\"\n gem 'haml-rails', :group => :development\n $ bundle install\n" }, { "answer_id": 10509600, "author": "chris raethke", "author_id": 43672, "author_profile": "https://Stackoverflow.com/users/43672", "pm_score": 0, "selected": false, "text": "$ powder restart\n" }, { "answer_id": 62284685, "author": "hsul4n", "author_id": 8009543, "author_profile": "https://Stackoverflow.com/users/8009543", "pm_score": 0, "selected": false, "text": "haml Gemfile" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
99,242
<p>For RMI on server-side, do we need to start <code>rmiregistry</code> program, or just call <code>LocateRegistry.createRegistry</code>? If both are possible, what are the advantages and disadvantages?</p>
[ { "answer_id": 99286, "author": "user17250", "author_id": 17250, "author_profile": "https://Stackoverflow.com/users/17250", "pm_score": 4, "selected": true, "text": "rmiregistry LocateRegistry.createRegistry rmiregistry createRegistry" }, { "answer_id": 985871, "author": "William Wong", "author_id": 115872, "author_profile": "https://Stackoverflow.com/users/115872", "pm_score": 2, "selected": false, "text": "abstract public class CodeBaseResolver { \n static public String resolveCodeBaseForClass(Class<?> clazz) {\n Assert.notNull(clazz);\n final CodeSource codeSource = clazz.getProtectionDomain().getCodeSource();\n if (codeSource != null) {\n return codeSource.getLocation().toString();\n } else {\n return \"\";\n }\n }\n}\n\npublic class SystemPropertyConfigurer {\n private Map<String, String> systemProperties;\n public void setSystemProperties(Map<String, String> systemProperties) {\n this.systemProperties = systemProperties;\n }\n\n @PostConstruct\n void init() throws BeansException {\n if (systemProperties == null || systemProperties.isEmpty()) {\n return;\n }\n for (Map.Entry<String, String> entry : systemProperties.entrySet()) {\n final String key = entry.getKey();\n final String value = SystemPropertyUtils.resolvePlaceholders(entry.getValue());\n System.setProperty(key, value);\n }\n }\n}\n\n\n<bean id=\"springCodeBase\" class=\"org.springframework.beans.factory.config.MethodInvokingFactoryBean\">\n <property name=\"staticMethod\" value=\"xx.CodeBaseResolver.resolveCodeBaseForClass\" />\n <property name=\"arguments\">\n <list>\n <value>org.springframework.remoting.rmi.RmiInvocationWrapper_Stub</value>\n </list>\n </property>\n</bean>\n\n<bean id=\"springCodeBaseConfigurer\" class=\"xx.SystemPropertyConfigurer\"\n depends-on=\"springCodeBase\">\n <property name=\"systemProperties\">\n <map>\n <entry key=\"java.rmi.server.codebase\" value-ref=\"springCodeBase\" />\n </map>\n </property>\n</bean>\n\n<bean id=\"rmiServiceExporter\" class=\"org.springframework.remoting.rmi.RmiServiceExporter\" depends-on=\"springCodeBaseConfigurer\">\n <property name=\"serviceName\" value=\"XXX\" />\n <property name=\"service\" ref=\"XXX\" />\n <property name=\"serviceInterface\" value=\"XXX\" />\n <property name=\"registryPort\" value=\"${remote.rmi.port}\" />\n</bean>\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11238/" ]
99,279
<p>I want to parse a web page in Groovy and extract all of the href links and the associated text with it.</p> <p>If the page contained these links:</p> <pre><code>&lt;a href="http://www.google.com"&gt;Google&lt;/a&gt;&lt;br /&gt; &lt;a href="http://www.apple.com"&gt;Apple&lt;/a&gt; </code></pre> <p>the output would be:</p> <pre><code>Google, http://www.google.com&lt;br /&gt; Apple, http://www.apple.com </code></pre> <p>I'm looking for a Groovy answer. AKA. The easy way!</p>
[ { "answer_id": 99362, "author": "J D OConal", "author_id": 17023, "author_profile": "https://Stackoverflow.com/users/17023", "pm_score": 0, "selected": false, "text": "(html =~ /<a.*href='(.*?)'.*>(.*?)<\\/a>/).each { url, text -> \n // do something with url and text\n}\n" }, { "answer_id": 100197, "author": "yann.kmm", "author_id": 15780, "author_profile": "https://Stackoverflow.com/users/15780", "pm_score": 2, "selected": false, "text": "<html>\n <body>\n <a href=\"1.html\">1</a>\n <a href=\"2.html\">2</a>\n <a href=\"3.html\">3</a>\n </body>\n</html>\n" }, { "answer_id": 163795, "author": "John Flinchbaugh", "author_id": 12591, "author_profile": "https://Stackoverflow.com/users/12591", "pm_score": 5, "selected": true, "text": "input = \"\"\"<html><body>\n<a href = \"http://www.hjsoft.com/\">John</a>\n<a href = \"http://www.google.com/\">Google</a>\n<a href = \"http://www.stackoverflow.com/\">StackOverflow</a>\n</body></html>\"\"\"\n\ndoc = new XmlSlurper().parseText(input)\ndoc.depthFirst().collect { it }.findAll { it.name() == \"a\" }.each {\n println \"${it.text()}, ${it.@href.text()}\"\n}\n" }, { "answer_id": 10024482, "author": "Sree", "author_id": 1294908, "author_profile": "https://Stackoverflow.com/users/1294908", "pm_score": 0, "selected": false, "text": "<a href=\"www.google.com\"> new URL(url).eachLine{\n (it =~ /.*<A HREF=\"(.*?)\">/).each{\n // process hrefs\n }\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99279", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
99,297
<p>We all know what virtual functions are in C++, but how are they implemented at a deep level?</p> <p>Can the vtable be modified or even directly accessed at runtime?</p> <p>Does the vtable exist for all classes, or only those that have at least one virtual function? </p> <p>Do abstract classes simply have a NULL for the function pointer of at least one entry?</p> <p>Does having a single virtual function slow down the whole class? Or only the call to the function that is virtual? And does the speed get affected if the virtual function is actually overwritten or not, or does this have no effect so long as it is virtual.</p>
[ { "answer_id": 99739, "author": "Andrew Stein", "author_id": 13029, "author_profile": "https://Stackoverflow.com/users/13029", "pm_score": 0, "selected": false, "text": "class B { ~B() = 0; }; // Abstract Base class\nclass D : public B { ~D() {} }; // Concrete Derived class\n\nD* pD = new D();\nB* pB = pD;\n" }, { "answer_id": 101890, "author": "puetzk", "author_id": 14312, "author_profile": "https://Stackoverflow.com/users/14312", "pm_score": 5, "selected": false, "text": "IHuman::PlayPiano() class A {\n public:\n virtual int f1() = 0;\n};\nclass B : public A {\n public:\n virtual int f1() { return 1; }\n virtual int f2() { return 2; }\n};\nclass C : public A {\n public:\n virtual int f1() { return -1; }\n virtual int f2() { return -2; }\n};\n\nA *x = new B;\nA *y = new C;\nA *z = new C;\n std::swap(*(void **)x, *(void **)y);\n// Now x is a C, and y is a B! Hope they used the same layout of members!\n int f3(A*) { return 0; }\n\nmprotect(*(void **)x,8,PROT_READ|PROT_WRITE|PROT_EXEC);\n// Or VirtualProtect on win32; this part's very OS-specific\n(*(int (***)(A *)x)[0] = f3;\n// Now C::f1() returns 0 (remember we made x into a C above)\n// so x->f1() and z->f1() both return 0\n" }, { "answer_id": 102380, "author": "jheriko", "author_id": 17604, "author_profile": "https://Stackoverflow.com/users/17604", "pm_score": 2, "selected": false, "text": "class Foo\n{\nprotected:\n void(*)(Foo*) MyFunc;\npublic:\n Foo() { MyFunc = 0; }\n void ReplciatedVirtualFunctionCall()\n {\n MyFunc(*this);\n }\n...\n};\n\nclass Bar : public Foo\n{\nprivate:\n static void impl1(Foo* f)\n {\n ...\n }\npublic:\n Bar() { MyFunc = impl1; }\n...\n};\n\nclass Baz : public Foo\n{\nprivate:\n static void impl2(Foo* f)\n {\n ...\n }\npublic:\n Baz() { MyFunc = impl2; }\n...\n};\n" }, { "answer_id": 29546612, "author": "MvG", "author_id": 1468366, "author_profile": "https://Stackoverflow.com/users/1468366", "pm_score": 4, "selected": false, "text": "char struct Foo { virtual ~Foo(); virtual int a() { return 1; } };\nstruct Bar: public Foo { int a() { return 2; } };\nvoid f(Foo& arg) {\n Foo x; x.a(); // non-virtual: always calls Foo::a()\n Bar y; y.a(); // non-virtual: always calls Bar::a()\n arg.a(); // virtual: must dispatch via vtable\n Foo z = arg; // copy constructor Foo::Foo(const Foo&) will convert to Foo\n z.a(); // non-virtual Foo::a, since z is a Foo, even if arg was not\n}\n typedef struct Foo_t Foo; // forward declaration\nstruct slotsFoo { // list all virtual functions of Foo\n const void *parentVtable; // (single) inheritance\n void (*destructor)(Foo*); // virtual destructor Foo::~Foo\n int (*a)(Foo*); // virtual function Foo::a\n};\nstruct Foo_t { // class Foo\n const struct slotsFoo* vtable; // each instance points to vtable\n};\nvoid destructFoo(Foo* self) { } // Foo::~Foo\nint aFoo(Foo* self) { return 1; } // Foo::a()\nconst struct slotsFoo vtableFoo = { // only one constant table\n 0, // no parent class\n destructFoo,\n aFoo\n};\nvoid constructFoo(Foo* self) { // Foo::Foo()\n self->vtable = &vtableFoo; // object points to class vtable\n}\nvoid copyConstructFoo(Foo* self,\n Foo* other) { // Foo::Foo(const Foo&)\n self->vtable = &vtableFoo; // don't copy from other!\n}\n typedef struct Bar_t { // class Bar\n Foo base; // inherit all members of Foo\n} Bar;\nvoid destructBar(Bar* self) { } // Bar::~Bar\nint aBar(Bar* self) { return 2; } // Bar::a()\nconst struct slotsFoo vtableBar = { // one more constant table\n &vtableFoo, // can dynamic_cast to Foo\n (void(*)(Foo*)) destructBar, // must cast type to avoid errors\n (int(*)(Foo*)) aBar\n};\nvoid constructBar(Bar* self) { // Bar::Bar()\n self->base.vtable = &vtableBar; // point to Bar vtable\n}\n void f(Foo* arg) { // same functionality as above\n Foo x; constructFoo(&x); aFoo(&x);\n Bar y; constructBar(&y); aBar(&y);\n arg->vtable->a(arg); // virtual function call\n Foo z; copyConstructFoo(&z, arg);\n aFoo(&z);\n destructFoo(&z);\n destructBar(&y);\n destructFoo(&x);\n}\n arg Foo* arg->vtable Bar vtable vtable vtable base.vtable" }, { "answer_id": 29627052, "author": "Ethouris", "author_id": 657412, "author_profile": "https://Stackoverflow.com/users/657412", "pm_score": 2, "selected": false, "text": "abort() final virtual bool HasHoof() { return false; } bool Horse::HasHoof() { return true; } if (anim->HasHoof()) if(dynamic_cast<Horse*>(anim)) dynamic_cast" }, { "answer_id": 41710947, "author": "Dmytro", "author_id": 2012715, "author_profile": "https://Stackoverflow.com/users/2012715", "pm_score": 0, "selected": false, "text": "#ifndef CCPOLITE_H\n#define CCPOLITE_H\n\n/* the vtable or interface */\ntypedef struct {\n void (*Greet)(void *);\n void (*Thank)(void *);\n} ICCPolite;\n\n/**\n * the actual \"object\" literal as C++ sees it; public variables be here too \n * all CPolite objects use(are instances of) this struct's structure.\n */\ntypedef struct {\n ICCPolite *vtbl;\n} CPolite;\n\n#endif /* CCPOLITE_H */\n /** \n * unconventionally include me after defining OBJECT_NAME to automate\n * static(allocation-less) construction.\n *\n * note: I assume CPOLITE_H is included; since if I use anonymous structs\n * for each object, they become incompatible and cause compile time errors\n * when trying to do stuff like assign, or pass functions.\n * this is similar to how you can't pass void * to windows functions that\n * take handles; these handles use anonymous structs to make \n * HWND/HANDLE/HINSTANCE/void*/etc not automatically convertible, and\n * require a cast.\n */\n#ifndef OBJECT_NAME\n #error CCPolite> constructor requires object name.\n#endif\n\nCPolite OBJECT_NAME = {\n &CCPolite_Vtbl\n};\n\n/* ensure no global scope pollution */\n#undef OBJECT_NAME\n #include <stdio.h>\n#include \"CCPolite.h\"\n\n// | A Greeter is capable of greeting; nothing else.\nstruct IGreeter\n{\n virtual void Greet() = 0;\n};\n\n// | A Thanker is capable of thanking; nothing else.\nstruct IThanker\n{\n virtual void Thank() = 0;\n};\n\n// | A Polite is something that implements both IGreeter and IThanker\n// | Note that order of implementation DOES MATTER.\nstruct IPolite1 : public IGreeter, public IThanker{};\nstruct IPolite2 : public IThanker, public IGreeter{};\n\n// | implementation if IPolite1; implements IGreeter BEFORE IThanker\nstruct CPolite1 : public IPolite1\n{\n void Greet()\n {\n puts(\"hello!\");\n }\n\n void Thank()\n {\n puts(\"thank you!\");\n }\n};\n\n// | implementation if IPolite1; implements IThanker BEFORE IGreeter\nstruct CPolite2 : public IPolite2\n{\n void Greet()\n {\n puts(\"hi!\");\n }\n\n void Thank()\n {\n puts(\"ty!\");\n }\n};\n\n// | imposter Polite's Greet implementation.\nstatic void CCPolite_Greet(void *)\n{\n puts(\"HI I AM C!!!!\");\n}\n\n// | imposter Polite's Thank implementation.\nstatic void CCPolite_Thank(void *)\n{\n puts(\"THANK YOU, I AM C!!\");\n}\n\n// | vtable of the imposter Polite.\nICCPolite CCPolite_Vtbl = {\n CCPolite_Thank,\n CCPolite_Greet \n};\n\nCPolite CCPoliteObj = {\n &CCPolite_Vtbl\n};\n\nint main(int argc, char **argv)\n{\n puts(\"\\npart 1\");\n CPolite1 o1;\n o1.Greet();\n o1.Thank();\n\n puts(\"\\npart 2\"); \n CPolite2 o2; \n o2.Greet();\n o2.Thank(); \n\n puts(\"\\npart 3\"); \n CPolite1 *not1 = (CPolite1 *)&o2;\n CPolite2 *not2 = (CPolite2 *)&o1;\n not1->Greet();\n not1->Thank();\n not2->Greet();\n not2->Thank();\n\n puts(\"\\npart 4\"); \n CPolite1 *fake = (CPolite1 *)&CCPoliteObj;\n fake->Thank();\n fake->Greet();\n\n puts(\"\\npart 5\"); \n CPolite2 *fake2 = (CPolite2 *)fake;\n fake2->Thank();\n fake2->Greet();\n\n puts(\"\\npart 6\"); \n #define OBJECT_NAME fake3\n #include \"CCPolite_constructor.h\"\n fake = (CPolite1 *)&fake3;\n fake->Thank();\n fake->Greet();\n\n puts(\"\\npart 7\"); \n #define OBJECT_NAME fake4\n #include \"CCPolite_constructor.h\"\n fake2 = (CPolite2 *)&fake4;\n fake2->Thank();\n fake2->Greet(); \n\n return 0;\n}\n part 1\nhello!\nthank you!\n\npart 2\nhi!\nty!\n\npart 3\nty!\nhi!\nthank you!\nhello!\n\npart 4\nHI I AM C!!!!\nTHANK YOU, I AM C!!\n\npart 5\nTHANK YOU, I AM C!!\nHI I AM C!!!!\n\npart 6\nHI I AM C!!!!\nTHANK YOU, I AM C!!\n\npart 7\nTHANK YOU, I AM C!!\nHI I AM C!!!!\n" }, { "answer_id": 51541779, "author": "Xeverous", "author_id": 4818802, "author_profile": "https://Stackoverflow.com/users/4818802", "pm_score": 2, "selected": false, "text": "void* .* ->* * -> #include <iostream>\n#include <vector>\n#include <memory>\n\nstruct vtable; // forward declare, we need just name\n\nclass animal\n{\npublic:\n const std::string& get_name() const { return name; }\n\n // these will be abstract\n bool has_tail() const;\n bool has_wings() const;\n void sound() const;\n\nprotected: // we do not want animals to be created directly\n animal(const vtable* vtable_ptr, std::string name)\n : vtable_ptr(vtable_ptr), name(std::move(name)) { }\n\nprivate:\n friend vtable; // just in case for non-public methods\n\n const vtable* const vtable_ptr;\n std::string name;\n};\n\nclass cat : public animal\n{\npublic:\n cat(std::string name);\n\n // functions to bind dynamically\n bool has_tail() const { return true; }\n bool has_wings() const { return false; }\n void sound() const\n {\n std::cout << get_name() << \" does meow\\n\"; \n }\n};\n\nclass dog : public animal\n{\npublic:\n dog(std::string name);\n\n // functions to bind dynamically\n bool has_tail() const { return true; }\n bool has_wings() const { return false; }\n void sound() const\n {\n std::cout << get_name() << \" does whoof\\n\"; \n }\n};\n\nclass parrot : public animal\n{\npublic:\n parrot(std::string name);\n\n // functions to bind dynamically\n bool has_tail() const { return false; }\n bool has_wings() const { return true; }\n void sound() const\n {\n std::cout << get_name() << \" does crrra\\n\"; \n }\n};\n\n// now the magic - pointers to member functions!\nstruct vtable\n{\n bool (animal::* const has_tail)() const;\n bool (animal::* const has_wings)() const;\n void (animal::* const sound)() const;\n\n // constructor\n vtable (\n bool (animal::* const has_tail)() const,\n bool (animal::* const has_wings)() const,\n void (animal::* const sound)() const\n ) : has_tail(has_tail), has_wings(has_wings), sound(sound) { }\n};\n\n// global vtable objects\nconst vtable vtable_cat(\n static_cast<bool (animal::*)() const>(&cat::has_tail),\n static_cast<bool (animal::*)() const>(&cat::has_wings),\n static_cast<void (animal::*)() const>(&cat::sound));\nconst vtable vtable_dog(\n static_cast<bool (animal::*)() const>(&dog::has_tail),\n static_cast<bool (animal::*)() const>(&dog::has_wings),\n static_cast<void (animal::*)() const>(&dog::sound));\nconst vtable vtable_parrot(\n static_cast<bool (animal::*)() const>(&parrot::has_tail),\n static_cast<bool (animal::*)() const>(&parrot::has_wings),\n static_cast<void (animal::*)() const>(&parrot::sound));\n\n// set vtable pointers in constructors\ncat::cat(std::string name) : animal(&vtable_cat, std::move(name)) { }\ndog::dog(std::string name) : animal(&vtable_dog, std::move(name)) { }\nparrot::parrot(std::string name) : animal(&vtable_parrot, std::move(name)) { }\n\n// implement dynamic dispatch\nbool animal::has_tail() const\n{\n return (this->*(vtable_ptr->has_tail))();\n}\n\nbool animal::has_wings() const\n{\n return (this->*(vtable_ptr->has_wings))();\n}\n\nvoid animal::sound() const\n{\n (this->*(vtable_ptr->sound))();\n}\n\nint main()\n{\n std::vector<std::unique_ptr<animal>> animals;\n animals.push_back(std::make_unique<cat>(\"grumpy\"));\n animals.push_back(std::make_unique<cat>(\"nyan\"));\n animals.push_back(std::make_unique<dog>(\"doge\"));\n animals.push_back(std::make_unique<parrot>(\"party\"));\n\n for (const auto& a : animals)\n a->sound();\n\n // note: destructors are not dispatched virtually\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
99,299
<p>For example, referencing something as System.Data.Datagrid as opposed to just Datagrid. Please provide examples and explanation. Thanks.</p>
[ { "answer_id": 99329, "author": "Statement", "author_id": 2166173, "author_profile": "https://Stackoverflow.com/users/2166173", "pm_score": 2, "selected": false, "text": "using Datagrid = System.Data.Datagrid;\n" }, { "answer_id": 99335, "author": "Orion Adrian", "author_id": 7756, "author_profile": "https://Stackoverflow.com/users/7756", "pm_score": 2, "selected": false, "text": "global::System.Data.DataGrid DataGrid" }, { "answer_id": 99346, "author": "bkane", "author_id": 17097, "author_profile": "https://Stackoverflow.com/users/17097", "pm_score": 1, "selected": false, "text": "struct A {\n int A::b; // warning!\n}\n" }, { "answer_id": 99354, "author": "lesscode", "author_id": 18482, "author_profile": "https://Stackoverflow.com/users/18482", "pm_score": 2, "selected": false, "text": "using _Interop = Some.Interop.Namespace;\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99299", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13578/" ]
99,302
<p>Would it be useful to include the class name and variable name in any NullPointerException message? I know that it might not always be possible because of changes made by a JIT but is seems like the info should be available often (class members, etc).</p> <p>From: <a href="http://jamesjava.blogspot.com/2005/04/what-was-null.html" rel="nofollow noreferrer">http://jamesjava.blogspot.com/2005/04/what-was-null.html</a></p>
[ { "answer_id": 99360, "author": "Soumitra", "author_id": 10844, "author_profile": "https://Stackoverflow.com/users/10844", "pm_score": -1, "selected": false, "text": "NullPointerException null Log4J" }, { "answer_id": 99512, "author": "Roy Tang", "author_id": 18494, "author_profile": "https://Stackoverflow.com/users/18494", "pm_score": 0, "selected": false, "text": "exception.getMessage()" }, { "answer_id": 100520, "author": "Aleksandar Dimitrov", "author_id": 11797, "author_profile": "https://Stackoverflow.com/users/11797", "pm_score": 0, "selected": false, "text": "null null null Segmentation fault strace javac javac" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99302", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6770/" ]
99,315
<p>What if a Java allow both static and dynamic types. That might allow the best of both worlds. i.e.:</p> <pre><code>String str = "Hello"; var temp = str; temp = 10; temp = temp * 5; </code></pre> <ol> <li>Would that be possible?</li> <li>Would that be beneficial?</li> <li>Do any languages currently support both and how well does it work out?</li> </ol> <p>Here is a better example (generics can't be used but the program does know the type):</p> <pre><code>var username = HttpServletRequest.getSession().getAttribute("username");//Returns a String if(username.length() == 0) { //Error } </code></pre>
[ { "answer_id": 99333, "author": "jon", "author_id": 12215, "author_profile": "https://Stackoverflow.com/users/12215", "pm_score": 1, "selected": false, "text": "String str = \"Hello\";\nObject temp = str;\ntemp = 10;\n" }, { "answer_id": 99376, "author": "Lou Franco", "author_id": 3937, "author_profile": "https://Stackoverflow.com/users/3937", "pm_score": 0, "selected": false, "text": "public void f(var o)\n{\n o.method();\n}\n" }, { "answer_id": 100366, "author": "jb.", "author_id": 7918, "author_profile": "https://Stackoverflow.com/users/7918", "pm_score": 0, "selected": false, "text": "void doSth(Object foo) throws Exception{\n Method m = foo.getClass().getMethod(\"foo\", String.class);\n m.invoke(foo, \"baz\"); \n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6770/" ]
99,318
<blockquote> <p><strong>Possible Duplicate:</strong><br> <a href="https://stackoverflow.com/questions/1217088/what-does-mapname-mean-in-ruby">What does map(&amp;:name) mean in Ruby?</a> </p> </blockquote> <p>I was watching a railscast and saw this code.</p> <pre><code>[Category, Product].(&amp;:delete_all) </code></pre> <p>In regards to clearing a database.</p> <p>I asked about the line in IRC and was told </p> <pre><code>(&amp;:delete_all) </code></pre> <p>was a shortcut for </p> <pre><code>{|model| model.delete_all} </code></pre> <p>I tested this with the following</p> <pre><code>class ClassOne def class_method puts 1 end end class ClassTwo def class_method puts 2 end end [ClassOne, ClassTwo].each(&amp;:class_method) </code></pre> <p>I received an error saying</p> <pre><code>Wrong Argument type Symbol (expected Proc) </code></pre> <p>I also tried</p> <pre><code>one = ClassOne.new two = ClassTwo.new [one, two].each(&amp;:class_method) </code></pre> <p>But that still failed.</p> <p>If I modified it to read</p> <pre><code>[one, two].each{|model| model.class_method} </code></pre> <p>Everything worked as expected.</p> <p>So, what does <code>&amp;:delete_all</code> actually do? The docs say <code>delete_all</code> is a method, so I am confused as to what is going on here.</p>
[ { "answer_id": 99336, "author": "Alex M", "author_id": 9652, "author_profile": "https://Stackoverflow.com/users/9652", "pm_score": 5, "selected": true, "text": "class Symbol\n def to_proc\n proc { |obj, *args| obj.send(self, *args) }\n end\nend\n ActiveSupport" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99318", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9450/" ]
99,350
<p>Is there an easy way to marshal a PHP associative array to and from XML? For example, I have the following array:</p> <pre><code>$items = array("1", "2", array( "item3.1" =&gt; "3.1", "item3.2" =&gt; "3.2" "isawesome" =&gt; true ) ); </code></pre> <p>How would I turn it into something similar to the following XML in as few lines as possible, then back again?</p> <pre><code>&lt;items&gt; &lt;item&gt;1&lt;/item&gt; &lt;item&gt;2&lt;/item&gt; &lt;item&gt; &lt;item3_1&gt;3.1&lt;/item3_1&gt; &lt;item3_2&gt;3.2&lt;/item3_2&gt; &lt;isawesome&gt;true&lt;/isawesome&gt; &lt;/item&gt; &lt;/items&gt; </code></pre> <p>I don't really care if I have to change the array structure a bit or if the XML that comes out is different to the above example. I've been trying to work with PHP's <a href="http://php.net/manual/en/book.xmlreader.php" rel="noreferrer">XMLReader</a> and <a href="http://php.net/manual/en/book.xmlwriter.php" rel="noreferrer">XMLWriter</a>, but the documentation is so poor and the code I've produced as a consequence looks nothing like what I feel it should look like:</p> <pre><code>$xml = SomeXMLWriter::writeArrayToXml($items); $array = SomeXMLWriter::writeXmlToArray($xml); </code></pre> <p>Does it really have to be any harder than that to get a basic, raw XML dump of a PHP array without writing my own custom class?</p> <p>I try to avoid PEAR. In addition to the configuration headaches I've had with it, I've never stuck with any of the packages I've ever used from it.</p>
[ { "answer_id": 100287, "author": "DreamWerx", "author_id": 15487, "author_profile": "https://Stackoverflow.com/users/15487", "pm_score": 2, "selected": false, "text": "<items>\n <item id=\"1\"/>\n <item id=\"2\"/>\n <item id=\"3\">\n <subitems> \n <item id=\"3.1\"/>\n <item id=\"3.2\" isawesome=\"true\"/>\n </subitems>\n </item>\n</items>\n" }, { "answer_id": 125761, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "$oXml->AddChild(\"file:///user/data.xml\") $oXml->AddChild(\"<more><xml>yes</xml></more>\"); $oArray->flip()->Reverse()->Walk(/*callback*/); $oArray[key] $oXml->AsArray(); $oArray->AsXml();" }, { "answer_id": 1243839, "author": "Conrad", "author_id": 131678, "author_profile": "https://Stackoverflow.com/users/131678", "pm_score": 4, "selected": true, "text": "/**\n * Build A XML Data Set\n *\n * @param array $data Associative Array containing values to be parsed into an XML Data Set(s)\n * @param string $startElement Root Opening Tag, default fx_request\n * @param string $xml_version XML Version, default 1.0\n * @param string $xml_encoding XML Encoding, default UTF-8\n * @return string XML String containig values\n * @return mixed Boolean false on failure, string XML result on success\n */\npublic function buildXMLData($data, $startElement = 'fx_request', $xml_version = '1.0', $xml_encoding = 'UTF-8') {\n if(!is_array($data)) {\n $err = 'Invalid variable type supplied, expected array not found on line '.__LINE__.\" in Class: \".__CLASS__.\" Method: \".__METHOD__;\n trigger_error($err);\n if($this->_debug) echo $err;\n return false; //return false error occurred\n }\n $xml = new XmlWriter();\n $xml->openMemory();\n $xml->startDocument($xml_version, $xml_encoding);\n $xml->startElement($startElement);\n\n /**\n * Write XML as per Associative Array\n * @param object $xml XMLWriter Object\n * @param array $data Associative Data Array\n */\n function write(XMLWriter $xml, $data) {\n foreach($data as $key => $value) {\n if(is_array($value)) {\n $xml->startElement($key);\n write($xml, $value);\n $xml->endElement();\n continue;\n }\n $xml->writeElement($key, $value);\n }\n }\n write($xml, $data);\n\n $xml->endElement();//write end element\n //Return the XML results\n return $xml->outputMemory(true); \n}\n" }, { "answer_id": 6237999, "author": "gskluzacek", "author_id": 784078, "author_profile": "https://Stackoverflow.com/users/784078", "pm_score": 2, "selected": false, "text": "\n<?php\n\n$xml_req1 = <<<XML\n<?xml version=\"1.0\"?>\n<Vastera:CustomerValidation_RequestInfo\n xmlns:Vastera=\"http://ndc-ah-prd.am.mot.com:10653/MotVastera_CustomerValidation/MC000078/Docs/\">\n <PartnerID>5550000100-003</PartnerID>\n <PartnerType>PTNR_INTER_CONSIGNEE</PartnerType>\n <OperatingUnit>100</OperatingUnit>\n <Status>ACTIVE</Status>\n <CustomerSeqNumber>111</CustomerSeqNumber>\n <CustomerName>Greg Co</CustomerName>\n <Address1>123 Any Ln</Address1>\n <Address2>?</Address2>\n <Address3>?</Address3>\n <Address4>?</Address4>\n <Address5>?</Address5>\n <City>Someplace</City>\n <PostalCode>603021</PostalCode>\n <State>CA</State>\n <CountryCode>US</CountryCode>\n <TaxReference>222</TaxReference>\n <PartyRelated>Y</PartyRelated>\n <BusinessUnit>GSBU</BusinessUnit>\n <Region>GSRGN</Region>\n <LocationName>DBA Mac Head Computing</LocationName>\n <LoadOnly>N</LoadOnly>\n <VSTM>333</VSTM>\n <MilitaryCustomerFlag>Y</MilitaryCustomerFlag>\n <USFederalGovernmentCustomer>Y</USFederalGovernmentCustomer>\n <Non-USGovernmentCustomer>Y</Non-USGovernmentCustomer>\n <Vastera:EPCIActivity>\n <EPCIActivityNuclearCode>NUCLEAR</EPCIActivityNuclearCode>\n <EPCIActivityNuclearValue>N</EPCIActivityNuclearValue>\n <EPCIActivityNuclearApproveDate>2011-05-16:07:19:37</EPCIActivityNuclearApproveDate>\n <EPCIActivityNuclearExpireDate>2056-12-31:12:00:00</EPCIActivityNuclearExpireDate>\n <EPCIActivityNuclearCountry>US</EPCIActivityNuclearCountry>\n <EPCIActivityChemBioCode>CHEM_BIO</EPCIActivityChemBioCode>\n <EPCIActivityChemBioValue>N</EPCIActivityChemBioValue>\n <EPCIActivityChemBioApproveDate>2011-05-16:07:19:37</EPCIActivityChemBioApproveDate>\n <EPCIActivityChemBioExpireDate>2056-12-31:12:00:00</EPCIActivityChemBioExpireDate>\n <EPCIActivityChemBioCountry>US</EPCIActivityChemBioCountry>\n <EPCIActivityMissileCode>MISSILE</EPCIActivityMissileCode>\n <EPCIActivityMissileValue>N</EPCIActivityMissileValue>\n <EPCIActivityMissileApproveDate>2011-05-16:07:19:37</EPCIActivityMissileApproveDate>\n <EPCIActivityMissileExpireDate>2056-12-31:12:00:00</EPCIActivityMissileExpireDate>\n <EPCIActivityMissileCountry>US</EPCIActivityMissileCountry>\n </Vastera:EPCIActivity>\n <SourceSystem>GSB2BSS</SourceSystem>\n <CreatedDate>2011-05-16:07:18:55</CreatedDate>\n <CreatedBy>c18530</CreatedBy>\n <LastModifiedDate>2011-05-16:07:18:55</LastModifiedDate>\n <LastModifiedBy>c18530</LastModifiedBy>\n <ContactName>Greg, \"Da Man\" Skluacek</ContactName>\n <ContactTitle>Head Honcho</ContactTitle>\n <ContactPhone>555-555-5555</ContactPhone>\n <ContactFax>666-666-6666</ContactFax>\n <ContactEmail>gskluzacek@gregco.com</ContactEmail>\n <ContactWeb>www.gregco.com</ContactWeb>\n</Vastera:CustomerValidation_RequestInfo>\nXML;\n\n$xml_req2 = <<<XML\n<?xml version=\"1.0\"?>\n<order>\n <orderNumber>123</orderNumber>\n <customerAddress>\n <type>Ship To</type>\n <name>Bob McFly</name>\n <addr1>123 Lincoln St</addr1>\n <city>Chicago</city>\n <state>IL</state>\n <zip>60001</zip>\n </customerAddress>\n <customerAddress>\n <type>Bill To</type>\n <name>McFly Products Inc.</name>\n <addr1>P.O. Box 6695</addr1>\n <city>New York</city>\n <state>NY</state>\n <zip>99081-6695</zip>\n </customerAddress>\n <item>\n <line>1</line>\n <part>123001A</part>\n <qty>5</qty>\n <price>10.25</price>\n </item>\n <item>\n <line>2</line>\n <part>456002B</part>\n <qty>3</qty>\n <price>20.50</price>\n </item>\n <item>\n <line>3</line>\n <part>789003C</part>\n <qty>1</qty>\n <price>41.00</price>\n </item>\n <orderSubTotal>133.25</orderSubTotal>\n <tax>6.66</tax>\n <shipping>10.00</shipping>\n <orderTotal>149.91</orderTotal>\n</order>\nXML;\n\n$doc = new DOMDocument();\n$doc->preserveWhiteSpace = false;\n$doc->loadXML($xml_req1);\n\n$arr = xml_to_arr($doc->documentElement);\n\nprint \"\\n\\n----\\n\\n\";\n\nprint_r($arr);\n\nprint \"\\n\\n----\\n\\n\";\n\n$doc2 = new DOMDocument();\n$doc2->preserveWhiteSpace = false;\n$doc2->loadXML($xml_req2);\n\n$arr2 = xml_to_arr($doc2->documentElement);\n\nprint \"\\n\\n----\\n\\n\";\n\nprint_r($arr2);\n\nprint \"\\n\\n----\\n\\n\";\n\nexit;\n\nfunction xml_to_arr($curr_node) {\n $val_array = array();\n $typ_array = array();\n\n foreach($curr_node->childNodes as $node) {\n if ($node->nodeType == XML_ELEMENT_NODE) {\n\n $val = xml_to_arr($node);\n\n if (array_key_exists($node->tagName, $val_array)) {\n\n if (!is_array($val_array[$node->tagName]) || $type_array[$node->tagName] == 'hash') {\n $existing_val = $val_array[$node->tagName];\n unset($val_array[$node->tagName]);\n $val_array[$node->tagName][0] = $existing_val;\n $type_array[$node->tagName] = 'array';\n }\n $val_array[$node->tagName][] = $val;\n\n } else {\n\n $val_array[$node->tagName] = $val;\n if (is_array($val)) {\n $type_array[$node->tagName] = 'hash';\n }\n\n } // end if array key exists\n\n } // end if elment node\n }// end for each\n\n if (count($val_array) == 0) {\n return $curr_node->nodeValue;\n } else {\n return $val_array;\n }\n\n} // end function xml to arr\n\n?>\n \n----\n\nArray\n(\n [PartnerID] => 5550000100-003\n [PartnerType] => PTNR_INTER_CONSIGNEE\n [OperatingUnit] => 100\n [Status] => ACTIVE\n [CustomerSeqNumber] => 111\n [CustomerName] => Greg Co\n [Address1] => 123 Any Ln\n [Address2] => ?\n [Address3] => ?\n [Address4] => ?\n [Address5] => ?\n [City] => Somplace\n [PostalCode] => 60123\n [State] => CA\n [CountryCode] => US\n [TaxReference] => 222\n [PartyRelated] => Y\n [BusinessUnit] => GSBU\n [Region] => GSRGN\n [LocationName] => DBA Mac Head Computing\n [LoadOnly] => N\n [VSTM] => 333\n [MilitaryCustomerFlag] => Y\n [USFederalGovernmentCustomer] => Y\n [Non-USGovernmentCustomer] => Y\n [Vastera:EPCIActivity] => Array\n (\n [EPCIActivityNuclearCode] => NUCLEAR\n [EPCIActivityNuclearValue] => N\n [EPCIActivityNuclearApproveDate] => 2011-05-16:07:19:37\n [EPCIActivityNuclearExpireDate] => 2056-12-31:12:00:00\n [EPCIActivityNuclearCountry] => US\n [EPCIActivityChemBioCode] => CHEM_BIO\n [EPCIActivityChemBioValue] => N\n [EPCIActivityChemBioApproveDate] => 2011-05-16:07:19:37\n [EPCIActivityChemBioExpireDate] => 2056-12-31:12:00:00\n [EPCIActivityChemBioCountry] => US\n [EPCIActivityMissileCode] => MISSILE\n [EPCIActivityMissileValue] => N\n [EPCIActivityMissileApproveDate] => 2011-05-16:07:19:37\n [EPCIActivityMissileExpireDate] => 2056-12-31:12:00:00\n [EPCIActivityMissileCountry] => US\n )\n\n [SourceSystem] => GSB2BSS\n [CreatedDate] => 2011-05-16:07:18:55\n [CreatedBy] => c18530\n [LastModifiedDate] => 2011-05-16:07:18:55\n [LastModifiedBy] => c18530\n [ContactName] => Greg, \"Da Man\" Skluacek\n [ContactTitle] => Head Honcho\n [ContactPhone] => 555-555-5555\n [ContactFax] => 666-666-6666\n [ContactEmail] => gskluzacek@gregco.com\n [ContactWeb] => www.gregco.com\n)\n\n----\n\nArray\n(\n [orderNumber] => 123\n [customerAddress] => Array\n (\n [0] => Array\n (\n [type] => Ship To\n [name] => Bob McFly\n [addr1] => 123 Lincoln St\n [city] => Chicago\n [state] => IL\n [zip] => 60001\n )\n\n [1] => Array\n (\n [type] => Bill To\n [name] => McFly Products Inc.\n [addr1] => P.O. Box 6695\n [city] => New York\n [state] => NY\n [zip] => 99081-6695\n )\n\n )\n\n [item] => Array\n (\n [0] => Array\n (\n [line] => 1\n [part] => 123001A\n [qty] => 5\n [price] => 10.25\n )\n\n [1] => Array\n (\n [line] => 2\n [part] => 456002B\n [qty] => 3\n [price] => 20.50\n )\n\n [2] => Array\n (\n [line] => 3\n [part] => 789003C\n [qty] => 1\n [price] => 41.00\n )\n\n )\n\n [orderSubTotal] => 133.25\n [tax] => 6.66\n [shipping] => 10.00\n [orderTotal] => 149.91\n)\n\n--------\n" }, { "answer_id": 6880640, "author": "Ángel López", "author_id": 379027, "author_profile": "https://Stackoverflow.com/users/379027", "pm_score": 2, "selected": false, "text": "/**\n * Build A XML Data Set\n *\n * @param array $data Associative Array containing values to be parsed into an XML Data Set(s)\n * @param string $startElement Root Opening Tag, default fx_request\n * @param string $xml_version XML Version, default 1.0\n * @param string $xml_encoding XML Encoding, default UTF-8\n * @return string XML String containig values\n * @return mixed Boolean false on failure, string XML result on success\n */\npublic static function arrayToXML($data, $startElement = 'fx_request', $xml_version = '1.0', $xml_encoding = 'UTF-8'){\n if(!is_array($data)){\n $err = 'Invalid variable type supplied, expected array not found on line '.__LINE__.\" in Class: \".__CLASS__.\" Method: \".__METHOD__;\n trigger_error($err);\n if($this->_debug) echo $err;\n return false; //return false error occurred\n }\n $xml = new XmlWriter();\n $xml->openMemory();\n $xml->startDocument($xml_version, $xml_encoding);\n $xml->startElement($startElement);\n\n /**\n * Write XML as per Associative Array\n * @param object $xml XMLWriter Object\n * @param array $data Associative Data Array\n */\n function write(XMLWriter $xml, $data){\n foreach($data as $key => $value){\n if (is_array($value) && isset($value[0])){\n foreach($value as $itemValue){\n //$xml->writeElement($key, $itemValue);\n\n if(is_array($itemValue)){\n $xml->startElement($key);\n write($xml, $itemValue);\n $xml->endElement();\n continue;\n } \n\n if (!is_array($itemValue)){\n $xml->writeElement($key, $itemValue.\"\");\n }\n }\n }else if(is_array($value)){\n $xml->startElement($key);\n write($xml, $value);\n $xml->endElement();\n continue;\n } \n\n if (!is_array($value)){\n $xml->writeElement($key, $value.\"\");\n }\n }\n }\n write($xml, $data);\n\n $xml->endElement();//write end element\n //returns the XML results\n return $xml->outputMemory(true);\n}\n $mArray[\"invitations\"][\"user\"][0][\"name\"] = \"paco\";\n$mArray[\"invitations\"][\"user\"][0][\"amigos\"][0] = 82;\n$mArray[\"invitations\"][\"user\"][0][\"amigos\"][1] = 29;\n$mArray[\"invitations\"][\"user\"][0][\"amigos\"][2] = 6;\n\n$mArray[\"invitations\"][\"user\"][1][\"name\"] = \"jose\";\n$mArray[\"invitations\"][\"user\"][1][\"amigos\"][0] = 43;\n$mArray[\"invitations\"][\"user\"][1][\"amigos\"][1][\"tuyos\"] = 32;\n$mArray[\"invitations\"][\"user\"][1][\"amigos\"][1][\"mios\"] = 79;\n$mArray[\"invitations\"][\"user\"][1][\"amigos\"][2] = 11;\n\n$mArray[\"invitations\"][\"user\"][2][\"name\"] = \"luis\";\n$mArray[\"invitations\"][\"user\"][2][\"amigos\"][0] = 65;\n <invitations>\n<user>\n <name>paco</name>\n <amigos>82</amigos>\n <amigos>29</amigos>\n <amigos>6</amigos>\n</user>\n<user>\n <name>jose</name>\n <amigos>43</amigos>\n <amigos>\n <tuyos>32</tuyos>\n <mios>79</mios>\n </amigos>\n <amigos>11</amigos>\n</user>\n<user>\n <name>luis</name>\n <amigos>65</amigos>\n</user>\n" }, { "answer_id": 7331866, "author": "xrado", "author_id": 345085, "author_profile": "https://Stackoverflow.com/users/345085", "pm_score": 2, "selected": false, "text": "class Xml {\n\n public static function from_array($arr, $xml = NULL)\n {\n $first = $xml;\n if($xml === NULL) $xml = new SimpleXMLElement('<root/>');\n foreach ($arr as $k => $v) \n {\n is_array($v)\n ? self::from_array($v, $xml->addChild($k))\n : $xml->addChild($k, $v);\n }\n return ($first === NULL) ? $xml->asXML() : $xml;\n }\n\n public static function to_array($xml)\n {\n $xml = simplexml_load_string($xml);\n $json = json_encode($xml);\n return json_decode($json,TRUE);\n }\n\n}\n\n$xml = xml::from_array($array);\n$array = xml::to_array($xml);\n" }, { "answer_id": 7404818, "author": "tomas", "author_id": 942915, "author_profile": "https://Stackoverflow.com/users/942915", "pm_score": 0, "selected": false, "text": "<?\n$data_array = (array) simplexml_load_string($xml_string);\n?>\n" }, { "answer_id": 17050255, "author": "Dan James", "author_id": 2475599, "author_profile": "https://Stackoverflow.com/users/2475599", "pm_score": 1, "selected": false, "text": "/**\n * Build an XML Data Set\n *\n * @param array $data Associative Array containing values to be parsed into an XML Data Set(s)\n * @param string $startElement Root Opening Tag, default fx_request\n * @param string $xml_version XML Version, default 1.0\n * @param string $xml_encoding XML Encoding, default UTF-8\n * @return string XML String containig values\n * @return mixed Boolean false on failure, string XML result on success\n */\nfunction arrayToXML($data, $startElement = 'fx_request', $xml_version = '1.0', $xml_encoding = 'UTF-8'){\n if(!is_array($data)){\n $err = 'Invalid variable type supplied, expected array not found on line '.__LINE__.\" in Class: \".__CLASS__.\" Method: \".__METHOD__;\n trigger_error($err);\n //if($this->_debug) echo $err;\n return false; //return false error occurred\n }\n $xml = new XmlWriter();\n $xml->openMemory();\n $xml->startDocument($xml_version, $xml_encoding);\n $xml->startElement($startElement);\n\n /**\n * Write keys in $data prefixed with @ as XML attributes, if $data is an array. When an @ prefixed key is found, a '' key is expected to indicate the element itself.\n * @param object $xml XMLWriter Object\n * @param array $data with attributes filtered out\n */\n function writeAttr(XMLWriter $xml, $data) {\n if(is_array($data)) {\n $nonAttributes = array();\n foreach($data as $key => $val) {\n //handle an attribute with elements\n if($key[0] == '@') {\n $xml->writeAttribute(substr($key, 1), $val);\n } else if($key == '') {\n if(is_array($val)) $nonAttributes = $val;\n else $xml->text(\"$val\");\n }\n\n //ignore normal elements\n else $nonAttributes[$key] = $val;\n }\n return $nonAttributes;\n }\n else return $data;\n }\n\n /**\n * Write XML as per Associative Array\n * @param object $xml XMLWriter Object\n * @param array $data Associative Data Array\n */\n function writeEl(XMLWriter $xml, $data) {\n foreach($data as $key => $value) {\n if(is_array($value) && isset($value[0])) { //numeric array\n foreach($value as $itemValue){\n if(is_array($itemValue)) {\n $xml->startElement($key);\n $itemValue = writeAttr($xml, $itemValue);\n writeEl($xml, $itemValue);\n $xml->endElement();\n } else {\n $itemValue = writeAttr($xml, $itemValue);\n $xml->writeElement($key, \"$itemValue\");\n }\n }\n } else if(is_array($value)) { //associative array\n $xml->startElement($key);\n $value = writeAttr($xml, $value);\n writeEl($xml, $value);\n $xml->endElement();\n } else { //scalar\n $value = writeAttr($xml, $value);\n $xml->writeElement($key, \"$value\");\n }\n }\n }\n writeEl($xml, $data);\n\n $xml->endElement();//write end element\n //returns the XML results\n return $xml->outputMemory(true);\n}\n $mArray[\"invitations\"][\"user\"][0][\"@name\"] = \"paco\";\n$mArray[\"invitations\"][\"user\"][0][\"\"][\"amigos\"][0] = 82;\n$mArray[\"invitations\"][\"user\"][0][\"\"][\"amigos\"][1] = 29;\n$mArray[\"invitations\"][\"user\"][0][\"\"][\"amigos\"][2] = 6;\n\n$mArray[\"invitations\"][\"user\"][1][\"@name\"] = \"jose\";\n$mArray[\"invitations\"][\"user\"][1][\"\"][\"amigos\"][0] = 43;\n$mArray[\"invitations\"][\"user\"][1][\"\"][\"amigos\"][1][\"tuyos\"] = 32;\n$mArray[\"invitations\"][\"user\"][1][\"\"][\"amigos\"][1][\"mios\"] = 79;\n$mArray[\"invitations\"][\"user\"][1][\"\"][\"amigos\"][2] = 11;\n\n$mArray[\"invitations\"][\"user\"][2][\"@name\"] = \"luis\";\n$mArray[\"invitations\"][\"user\"][2][\"\"][\"amigos\"][0] = 65;\n <invitations>\n <user name=\"paco\">\n <amigos>82</amigos>\n <amigos>29</amigos>\n <amigos>6</amigos>\n </user>\n <user name=\"jose\">\n <amigos>43</amigos>\n <amigos>\n <tuyos>32</tuyos>\n <mios>79</mios>\n </amigos>\n <amigos>11</amigos>\n </user>\n <user name=\"luis\">\n <amigos>65</amigos>\n </user>\n</invitations>\n" }, { "answer_id": 17906457, "author": "Andrey Vorobyev", "author_id": 1091104, "author_profile": "https://Stackoverflow.com/users/1091104", "pm_score": 0, "selected": false, "text": "/**\n * Write XML as per Associative Array\n * @param object $xml XMLWriter Object\n * @param array $data Associative Data Array\n */\nfunction writeXmlRecursive(XMLWriter $xml, $data){\n foreach($data as $key => $value){\n if (is_array($value) && isset($value[0])){\n $xml->startElement($key);\n foreach($value as $itemValue){\n\n if(is_array($itemValue)){\n writeXmlRecursive($xml, $itemValue);\n }\n else\n {\n $xml->writeElement($key, $itemValue.\"\");\n }\n }\n $xml->endElement();\n\n }else if(is_array($value)){\n $xml->startElement($key);\n writeXmlRecursive($xml, $value);\n $xml->endElement();\n continue;\n }\n\n if (!is_array($value)){\n $xml->writeElement($key, $value.\"\");\n }\n }\n}\n <items>\n<item>\n <id_site>59332</id_site>\n <id>33</id>\n <code>196429985</code>\n <tombid>23</tombid>\n <tombcode>196429985</tombcode>\n <religion></religion>\n <lastname>lastname</lastname>\n <firstname>name</firstname>\n <patronymicname>patronymicname</patronymicname>\n <sex>1</sex>\n <birthday>2</birthday>\n <birthmonth>4</birthmonth>\n <birthyear>1946</birthyear>\n <deathday>13</deathday>\n <deathmonth>5</deathmonth>\n <deathyear>2006</deathyear>\n <s_comments></s_comments>\n <graveyard>17446</graveyard>\n <latitude></latitude>\n <longitude></longitude>\n <images>\n <image>\n <siteId>52225</siteId>\n <fileId>62</fileId>\n <prefix>0</prefix>\n <path>path</path>\n </image>\n <image>\n <siteId>52226</siteId>\n <fileId>63</fileId>\n <prefix>0</prefix>\n <path>path</path>\n </image>\n </images>\n </item>\n<items>\n" }, { "answer_id": 24468165, "author": "jmarceli", "author_id": 2041318, "author_profile": "https://Stackoverflow.com/users/2041318", "pm_score": 1, "selected": false, "text": "// Based on: http://stackoverflow.com/questions/99350/passing-php-associative-arrays-to-and-from-xml\nclass ArrayToXML {\n private $version;\n private $encoding;\n /*\n * Construct ArrayToXML object with selected version and encoding \n *\n * for available values check XmlWriter docs http://www.php.net/manual/en/function.xmlwriter-start-document.php\n * @param string $xml_version XML Version, default 1.0\n * @param string $xml_encoding XML Encoding, default UTF-8\n */\n public function __construct($xmlVersion = '1.0', $xmlEncoding = 'UTF-8') {\n $this->version = $xmlVersion;\n $this->encoding = $xmlEncoding;\n }\n /**\n * Build an XML Data Set\n *\n * @param array $data Associative Array containing values to be parsed into an XML Data Set(s)\n * @param string $startElement Root Opening Tag, default data\n * @return string XML String containig values\n * @return mixed Boolean false on failure, string XML result on success\n */\n public function buildXML($data, $startElement = 'data'){\n if(!is_array($data)){\n $err = 'Invalid variable type supplied, expected array not found on line '.__LINE__.\" in Class: \".__CLASS__.\" Method: \".__METHOD__;\n trigger_error($err);\n //if($this->_debug) echo $err;\n return false; //return false error occurred\n }\n $xml = new XmlWriter();\n $xml->openMemory();\n $xml->startDocument($this->version, $this->encoding);\n $xml->startElement($startElement);\n $this->writeEl($xml, $data);\n $xml->endElement();//write end element\n //returns the XML results\n return $xml->outputMemory(true);\n }\n /**\n * Write keys in $data prefixed with @ as XML attributes, if $data is an array. \n * When an @ prefixed key is found, a '%' key is expected to indicate the element itself, \n * and '#' prefixed key indicates CDATA content\n *\n * @param object $xml XMLWriter Object\n * @param array $data with attributes filtered out\n */\n protected function writeAttr(XMLWriter $xml, $data) {\n if(is_array($data)) {\n $nonAttributes = array();\n foreach($data as $key => $val) {\n //handle an attribute with elements\n if($key[0] == '@') {\n $xml->writeAttribute(substr($key, 1), $val);\n } else if($key[0] == '%') {\n if(is_array($val)) $nonAttributes = $val;\n else $xml->text($val);\n } elseif($key[0] == '#') {\n if(is_array($val)) $nonAttributes = $val;\n else {\n $xml->startElement(substr($key, 1));\n $xml->writeCData($val);\n $xml->endElement();\n }\n }\n //ignore normal elements\n else $nonAttributes[$key] = $val;\n }\n return $nonAttributes;\n }\n else return $data;\n }\n /**\n * Write XML as per Associative Array\n *\n * @param object $xml XMLWriter Object\n * @param array $data Associative Data Array\n */\n protected function writeEl(XMLWriter $xml, $data) {\n foreach($data as $key => $value) {\n if(is_array($value) && !$this->isAssoc($value)) { //numeric array\n foreach($value as $itemValue){\n if(is_array($itemValue)) {\n $xml->startElement($key);\n $itemValue = $this->writeAttr($xml, $itemValue);\n $this->writeEl($xml, $itemValue);\n $xml->endElement();\n } else {\n $itemValue = $this->writeAttr($xml, $itemValue);\n $xml->writeElement($key, \"$itemValue\");\n }\n }\n } else if(is_array($value)) { //associative array\n $xml->startElement($key);\n $value = $this->writeAttr($xml, $value);\n $this->writeEl($xml, $value);\n $xml->endElement();\n } else { //scalar\n $value = $this->writeAttr($xml, $value);\n $xml->writeElement($key, \"$value\");\n }\n }\n }\n /*\n * Check if array is associative with string based keys\n * FROM: http://stackoverflow.com/questions/173400/php-arrays-a-good-way-to-check-if-an-array-is-associative-or-sequential/4254008#4254008\n *\n * @param array $array Array to check\n */\n protected function isAssoc($array) {\n return (bool)count(array_filter(array_keys($array), 'is_string'));\n }\n}\n ArrayToXML $xml = new ArrayToXML();\nprint $xml->buildXML($input);\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99350", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15004/" ]
99,353
<p>How to test if a line segment intersects an axis-aligned rectange in 2D? The segment is defined with its two ends: p1, p2. The rectangle is defined with top-left and bottom-right points.</p>
[ { "answer_id": 99568, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 0, "selected": false, "text": "y = (Point2.Y - Point1.Y) / (Point2.X - Point1.X)\n X1 <= x <= X2 & \nY1 <= y <= Y2\n" }, { "answer_id": 100165, "author": "metamal", "author_id": 14385, "author_profile": "https://Stackoverflow.com/users/14385", "pm_score": 5, "selected": false, "text": " bool SegmentIntersectRectangle(double a_rectangleMinX,\n double a_rectangleMinY,\n double a_rectangleMaxX,\n double a_rectangleMaxY,\n double a_p1x,\n double a_p1y,\n double a_p2x,\n double a_p2y)\n {\n // Find min and max X for the segment\n\n double minX = a_p1x;\n double maxX = a_p2x;\n\n if(a_p1x > a_p2x)\n {\n minX = a_p2x;\n maxX = a_p1x;\n }\n\n // Find the intersection of the segment's and rectangle's x-projections\n\n if(maxX > a_rectangleMaxX)\n {\n maxX = a_rectangleMaxX;\n }\n\n if(minX < a_rectangleMinX)\n {\n minX = a_rectangleMinX;\n }\n\n if(minX > maxX) // If their projections do not intersect return false\n {\n return false;\n }\n\n // Find corresponding min and max Y for min and max X we found before\n\n double minY = a_p1y;\n double maxY = a_p2y;\n\n double dx = a_p2x - a_p1x;\n\n if(Math::Abs(dx) > 0.0000001)\n {\n double a = (a_p2y - a_p1y) / dx;\n double b = a_p1y - a * a_p1x;\n minY = a * minX + b;\n maxY = a * maxX + b;\n }\n\n if(minY > maxY)\n {\n double tmp = maxY;\n maxY = minY;\n minY = tmp;\n }\n\n // Find the intersection of the segment's and rectangle's y-projections\n\n if(maxY > a_rectangleMaxY)\n {\n maxY = a_rectangleMaxY;\n }\n\n if(minY < a_rectangleMinY)\n {\n minY = a_rectangleMinY;\n }\n\n if(minY > maxY) // If Y-projections do not intersect return false\n {\n return false;\n }\n\n return true;\n }\n" }, { "answer_id": 5386963, "author": "Craigo", "author_id": 418057, "author_profile": "https://Stackoverflow.com/users/418057", "pm_score": 2, "selected": false, "text": "java.awt.geom.Rectangle2D.intersectsLine(double x1, double y1, double x2, double y2)\n /**\n * Code copied from {@link java.awt.geom.Rectangle2D#intersectsLine(double, double, double, double)}\n */\npublic class RectangleLineIntersectTest {\n private static final int OUT_LEFT = 1;\n private static final int OUT_TOP = 2;\n private static final int OUT_RIGHT = 4;\n private static final int OUT_BOTTOM = 8;\n\n private static int outcode(double pX, double pY, double rectX, double rectY, double rectWidth, double rectHeight) {\n int out = 0;\n if (rectWidth <= 0) {\n out |= OUT_LEFT | OUT_RIGHT;\n } else if (pX < rectX) {\n out |= OUT_LEFT;\n } else if (pX > rectX + rectWidth) {\n out |= OUT_RIGHT;\n }\n if (rectHeight <= 0) {\n out |= OUT_TOP | OUT_BOTTOM;\n } else if (pY < rectY) {\n out |= OUT_TOP;\n } else if (pY > rectY + rectHeight) {\n out |= OUT_BOTTOM;\n }\n return out;\n }\n\n public static boolean intersectsLine(double lineX1, double lineY1, double lineX2, double lineY2, double rectX, double rectY, double rectWidth, double rectHeight) {\n int out1, out2;\n if ((out2 = outcode(lineX2, lineY2, rectX, rectY, rectWidth, rectHeight)) == 0) {\n return true;\n }\n while ((out1 = outcode(lineX1, lineY1, rectX, rectY, rectWidth, rectHeight)) != 0) {\n if ((out1 & out2) != 0) {\n return false;\n }\n if ((out1 & (OUT_LEFT | OUT_RIGHT)) != 0) {\n double x = rectX;\n if ((out1 & OUT_RIGHT) != 0) {\n x += rectWidth;\n }\n lineY1 = lineY1 + (x - lineX1) * (lineY2 - lineY1) / (lineX2 - lineX1);\n lineX1 = x;\n } else {\n double y = rectY;\n if ((out1 & OUT_BOTTOM) != 0) {\n y += rectHeight;\n }\n lineX1 = lineX1 + (y - lineY1) * (lineX2 - lineX1) / (lineY2 - lineY1);\n lineY1 = y;\n }\n }\n return true;\n }\n}\n" }, { "answer_id": 11675405, "author": "Scott", "author_id": 821674, "author_profile": "https://Stackoverflow.com/users/821674", "pm_score": 0, "selected": false, "text": "i.e. box 1 is bounded by x1,y1 to x2,y2\nbox 2 is bounded by a1,b1 to a2,b2\n\nthe width and height of box 2 is:\nw2 = a2 - a1 (half of that is w2/2)\nh2 = b2 - b1 (half of that is h2/2)\nthe midpoints of box 2 are:\nam = a1 + w2/2\nbm = b1 + h2/2\n\nSo now you just check if\n(x1 - w2/2) < am < (x2 + w2/2) and (y1 - h2/2) < bm < (y2 + h2/2) \nthen the two overlap somewhere.\nIf you want to check also for edges intersecting to count as 'overlap' then\n change the < to <=\n (x1 - w2) < a1 < x2\n&&\n(y1 - h2) < b1 < y2\n[overlap exists]\n ( (x1-(a2-a1)) < a1 < x2 ) && ( (y1-(b2-b1)) < b1 < y2 ) [overlap exists]\n( (x1-(a2-a1)) <= a1 <= x2 ) && ( (y1-(b2-b1)) <= b1 <= y2 ) [overlap or intersect exists]\n" }, { "answer_id": 11676427, "author": "Scott", "author_id": 821674, "author_profile": "https://Stackoverflow.com/users/821674", "pm_score": 0, "selected": false, "text": "public function checkForOverlaps(BinPack_Polygon $nItem) {\n // grab some local variables for the stuff re-used over and over in loop\n $nX = $nItem->getLeft();\n $nY = $nItem->getTop();\n $nW = $nItem->getWidth();\n $nH = $nItem->getHeight();\n // loop through the stored polygons checking for overlaps\n foreach($this->packed as $_i => $pI) {\n if(((($pI->getLeft() - $nW) < $nX) && ($nX < $pI->getRight())) &&\n ((($pI->getTop() - $nH) < $nY) && ($nY < $pI->getBottom()))) {\n return false;\n }\n }\n return true;\n}\n" }, { "answer_id": 11691327, "author": "Scott", "author_id": 821674, "author_profile": "https://Stackoverflow.com/users/821674", "pm_score": 0, "selected": false, "text": "// returns 'true' on overlap checking against an array of similar objects in $this->packed\npublic function checkForOverlaps(BinPack_Polygon $nItem) {\n $nX = $nItem->getLeft();\n $nY = $nItem->getTop();\n $nW = $nItem->getWidth();\n $nH = $nItem->getHeight();\n // loop through the stored polygons checking for overlaps\n foreach($this->packed as $_i => $pI) {\n if(((($pI->getLeft() - $nW) < $nX) && ($nX < $pI->getRight())) && ((($pI->getTop() - $nH) < $nY) && ($nY < $pI->getBottom()))) {\n return true;\n }\n }\n return false;\n}\n" }, { "answer_id": 13844763, "author": "asolano", "author_id": 1898570, "author_profile": "https://Stackoverflow.com/users/1898570", "pm_score": 3, "selected": false, "text": "def _rect_collide(a, b):\n return a.x + a.w > b.x and b.x + b.w > a.x and \\\n a.y + a.h > b.y and b.y + b.h > a.y\n" }, { "answer_id": 18046673, "author": "Breck", "author_id": 131782, "author_profile": "https://Stackoverflow.com/users/131782", "pm_score": 1, "selected": false, "text": "var isRectangleIntersectedByLine = function (\n a_rectangleMinX,\n a_rectangleMinY,\n a_rectangleMaxX,\n a_rectangleMaxY,\n a_p1x,\n a_p1y,\n a_p2x,\n a_p2y) {\n\n // Find min and max X for the segment\n var minX = a_p1x\n var maxX = a_p2x\n\n if (a_p1x > a_p2x) {\n minX = a_p2x\n maxX = a_p1x\n }\n\n // Find the intersection of the segment's and rectangle's x-projections\n if (maxX > a_rectangleMaxX)\n maxX = a_rectangleMaxX\n\n if (minX < a_rectangleMinX)\n minX = a_rectangleMinX\n\n // If their projections do not intersect return false\n if (minX > maxX)\n return false\n\n // Find corresponding min and max Y for min and max X we found before\n var minY = a_p1y\n var maxY = a_p2y\n\n var dx = a_p2x - a_p1x\n\n if (Math.abs(dx) > 0.0000001) {\n var a = (a_p2y - a_p1y) / dx\n var b = a_p1y - a * a_p1x\n minY = a * minX + b\n maxY = a * maxX + b\n }\n\n if (minY > maxY) {\n var tmp = maxY\n maxY = minY\n minY = tmp\n }\n\n // Find the intersection of the segment's and rectangle's y-projections\n if(maxY > a_rectangleMaxY)\n maxY = a_rectangleMaxY\n\n if (minY < a_rectangleMinY)\n minY = a_rectangleMinY\n\n // If Y-projections do not intersect return false\n if(minY > maxY)\n return false\n\n return true\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99353", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14385/" ]
99,391
<p>When I commit I get this error from Subversion:</p> <pre><code>bash-2.05b$ svn commit -m "testing subversion, still" Adding baz svn: Commit failed (details follow): svn: MKCOL of '/viper/!svn/wrk/6b9bcd38-b2fe-0310-95ff-9d1a44098866/sandboxes/ohammersmith/trunk/baz': 405 Method Not Allowed (http://svn.example.com) </code></pre>
[ { "answer_id": 99413, "author": "Otto", "author_id": 9594, "author_profile": "https://Stackoverflow.com/users/9594", "pm_score": 8, "selected": true, "text": "svn up bash-2.05b$ svn up\nsvn: Failed to add directory 'baz': object of the same name already exists\n svn update svn update" }, { "answer_id": 37965567, "author": "Harshal Doshi Jain", "author_id": 1461781, "author_profile": "https://Stackoverflow.com/users/1461781", "pm_score": 4, "selected": false, "text": "svn update" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9594/" ]
99,395
<p>How to check if a folder (directory) exists in Cocoa using Objective-C?</p>
[ { "answer_id": 99438, "author": "Matt Dillard", "author_id": 863, "author_profile": "https://Stackoverflow.com/users/863", "pm_score": 7, "selected": true, "text": "NSFileManager fileExistsAtPath:isDirectory:" }, { "answer_id": 99465, "author": "lajos", "author_id": 3740, "author_profile": "https://Stackoverflow.com/users/3740", "pm_score": 3, "selected": false, "text": "Returns a Boolean value that indicates whether a specified file exists.\n\n- (BOOL)fileExistsAtPath:(NSString *)path isDirectory:(BOOL *)isDirectory\n\nParameters\npath\nThe path of a file or directory. If path begins with a tilde (~), it must first be expanded with stringByExpandingTildeInPath, or this method will return NO.\n\nisDirectory\nUpon return, contains YES if path is a directory or if the final path element is a symbolic link that points to a directory, otherwise contains NO. If path doesn’t exist, the return value is undefined. Pass NULL if you do not need this information.\n\nReturn Value\nYES if there is a file or directory at path, otherwise NO. If path specifies a symbolic link, this method traverses the link and returns YES or NO based on the existence of the file or directory at the link destination.\n" }, { "answer_id": 10258762, "author": "Richard Stelling", "author_id": 89035, "author_profile": "https://Stackoverflow.com/users/89035", "pm_score": 3, "selected": false, "text": "- fileExistsAtPath:isDirectory: NSString *pathToFile = @\"...\";\nBOOL isDir = NO;\nBOOL isFile = [[NSFileManager defaultManager] fileExistsAtPath:pathToFile isDirectory:&isDir];\n\nif(isFile)\n{\n //it is a file, process it here how ever you like, check isDir to see if its a directory \n}\nelse\n{\n //not a file, this is an error, handle it!\n}\n" }, { "answer_id": 15956861, "author": "Tong Liu", "author_id": 2270619, "author_profile": "https://Stackoverflow.com/users/2270619", "pm_score": 2, "selected": false, "text": "NSURL path NSString NSFileManager*fm = [NSFileManager defaultManager];\n\nNSURL* path = [[[fm URLsForDirectory:NSDocumentDirectory \n inDomains:NSUserDomainMask] objectAtIndex:0] \n URLByAppendingPathComponent:@\"photos\"];\n\nNSError *theError = nil;\nif(![fm fileExistsAtPath:[path path]]){\n NSLog(@\"dir doesn't exists\");\n}else\n NSLog(@\"dir exists\");\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99395", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
99,419
<p>An obvious answer is "an internal wiki". What are the pros and cons of a wiki used for software documentation? Any other suggestions? What are you using for your software documentation?</p> <p><a href="https://stackoverflow.com/users/6436/loren-segal">Loren Segal</a> - Unfortunately we don't have support for any doc tool to compile information from the source code comments but I agree it would be the best way to store technical documentation. My question was about every kind of documentation tho - from sysadmin type to user documentation. </p>
[ { "answer_id": 99462, "author": "Loren Segal", "author_id": 6436, "author_profile": "https://Stackoverflow.com/users/6436", "pm_score": 4, "selected": true, "text": "docs/" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99419", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8934/" ]
99,468
<p>I am retrieving multiple rows into a listview control from an ODBC source. For simple SELECTs it seems to work well with a statement attribute of SQL_SCROLLABLE. How do I do this with a UNION query (with two selects)?</p> <p>The most likely server will be MS SQL Server (probably 2005). The code is C for the Win32 API.</p> <p>This code sets (what I think is) a server side cursor which feeds data into the ODBC driver that roughly corresponds with the positional fetches of SQLFetchScroll, which is turn feeds the cache for the listview. (Sometimes using SQL_FETCH_FIRST or SQL_FETCH_LAST as well as):</p> <pre> SQLSetStmtAttr(hstmt1Fetch, SQL_ATTR_CURSOR_SCROLLABLE, (SQLPOINTER)SQL_SCROLLABLE, SQL_IS_INTEGER); SQLSetStmtAttr(hstmt1Fetch, SQL_ATTR_CURSOR_SENSITIVITY, (SQLPOINTER)SQL_INSENSITIVE, SQL_IS_INTEGER); ... retcode = SQLGetStmtAttr(hstmt1Fetch, SQL_ATTR_ROW_NUMBER, &CurrentRowNumber, SQL_IS_UINTEGER, NULL); ... retcode = SQLFetchScroll(hstmt1Fetch, SQL_FETCH_ABSOLUTE, Position); </pre> <p>(The above is is a fragment from working code for a single SELECT).</p> <p>Is this the best way to do it? Given that I need to retrieve the last row to get the number of rows and populate the end buffer is there a better way of doing it? (Can I use forward only scrolling?)</p> <p>Assuming yes to the above, how do I achieve the same result with a UNION query?</p> <p>LATE EDIT: The problem with the union query being that effectively it forces forward only scrolling which breaks SQLFetchScroll(hstmt1Fetch, SQL_FETCH_ABSOLUTE, Position). The answer is I suspect: "you can't". And it really means redesigning the DB to included either a view or a single table to replace the UNION. But I'll leave the question open in case I have missed something.</p>
[ { "answer_id": 99628, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 1, "selected": false, "text": "select some_fields from table1\nunion\nselect same_fields from table2\n" }, { "answer_id": 146031, "author": "Steven A. Lowe", "author_id": 9345, "author_profile": "https://Stackoverflow.com/users/9345", "pm_score": 0, "selected": false, "text": "ROW_NUMBER() select count(*) \nfrom (select blah UNION select blah) \n select ROW_NUMBER() as rownum,blah \nfrom (select blah UNION select blah) \nwhere rownum between minrow and maxrow \n" }, { "answer_id": 146243, "author": "HLGEM", "author_id": 9034, "author_profile": "https://Stackoverflow.com/users/9034", "pm_score": 0, "selected": false, "text": "union select * from \n(select field1, field from table1\nunion all\nslect field1, filed2 from table2) a\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99468", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3137/" ]
99,479
<p>My C(++) program, written and compiled using Visual C(++)/Visual Studio, runs fine on my own machine, but refuses to run on another machine. The error message I get is "This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem."</p>
[ { "answer_id": 108198, "author": "Scott", "author_id": 12451, "author_profile": "https://Stackoverflow.com/users/12451", "pm_score": 1, "selected": false, "text": "\\Program Files\\Microsoft Visual Studio 8\\SDK\\v2.0\\BootStrapper\\Packages\\vcredist_x86\n" }, { "answer_id": 1972195, "author": "sorin", "author_id": 99834, "author_profile": "https://Stackoverflow.com/users/99834", "pm_score": 1, "selected": false, "text": "#define _BIND_TO_CURRENT_VCLIBS_VERSION 1\n _BIND_TO_CURRENT_VCLIBS_VERSION=1" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99479", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14637/" ]
99,488
<p>If I'm writing an application that wants to communicate some information through the use of color, how can I change the background and foreground colors of a given widget? I would like to know how to do this in glade if it's possible, as well as programmatically (to a computed color).</p> <p>I want to know how to do this to a complex widget as well, for example, an <code>HBox</code> that contains a <code>VBox</code> that contains some <code>Labels</code>.</p> <p>Ideally this would also include a solution solution that allows me to <em>tint</em> the widget's existing colors, and identify the average colors of any images in use by the theme, so that I can programmatically compensate for any color choices which might make text unreadable or otherwise clashing - but I would be happy if I could just turn a button red.</p>
[ { "answer_id": 100266, "author": "Tometzky", "author_id": 15862, "author_profile": "https://Stackoverflow.com/users/15862", "pm_score": 4, "selected": true, "text": "#include <gtk/gtk.h>\n\nstatic void on_destroy(GtkWidget* widget, gpointer data)\n{\n gtk_main_quit ();\n}\n\nint main (int argc, char* argv[])\n{\n GtkWidget* window;\n GtkWidget* button;\n\n gtk_init(&argc, &argv);\n window = gtk_window_new(GTK_WINDOW_TOPLEVEL);\n g_signal_connect(G_OBJECT (window), \"destroy\",\n G_CALLBACK (on_destroy), NULL);\n button = gtk_button_new_with_label(\"Hello world!\");\n GdkColor red = {0, 0xffff, 0x0000, 0x0000};\n GdkColor green = {0, 0x0000, 0xffff, 0x0000};\n GdkColor blue = {0, 0x0000, 0x0000, 0xffff};\n gtk_widget_modify_bg(button, GTK_STATE_NORMAL, &red);\n gtk_widget_modify_bg(button, GTK_STATE_PRELIGHT, &green);\n gtk_widget_modify_bg(button, GTK_STATE_ACTIVE, &blue);\n gtk_container_add(GTK_CONTAINER(window), button);\n gtk_widget_show_all(window);\n gtk_main();\n return 0;\n}\n" }, { "answer_id": 18240336, "author": "shovon3091", "author_id": 2683628, "author_profile": "https://Stackoverflow.com/users/2683628", "pm_score": 1, "selected": false, "text": "gtk_style_context_add_class() gtk_style_context_add_region()" }, { "answer_id": 22662978, "author": "nishantbhardwaj2002", "author_id": 3340994, "author_profile": "https://Stackoverflow.com/users/3340994", "pm_score": 1, "selected": false, "text": "GdkColor color;\ngdk_color_parse(\"#00FF7F\", &color);\ngtk_widget_modify_bg(widget, GTK_STATE_NORMAL, &color);\n GdkPixbuf *image = NULL;\nGdkPixmap *background = NULL;\nGtkStyle *style = NULL;\n\nimage = gdk_pixbuf_new_from_file (\"background.jpg\", NULL);\ngdk_pixbuf_render_pixmap_and_mask (image, &background, NULL, 0);\nstyle = gtk_style_new ();\nstyle->bg_pixmap [0] = background;\n\ngtk_widget_set_style (GTK_WIDGET(widget), GTK_STYLE (style));\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99488", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13564/" ]
99,497
<p>I'm not looking so much for language-specific answers, just general models for implementing a plugin system (if you want to know, I'm using Python). I have my own idea (register callbacks, and that's about it), but I know others exist. What's normally used, and what else is reasonable?</p> <blockquote> <p>What do you mean by a plugin system? Does Dependency Injection and IOC containers sounds like a good solution?</p> </blockquote> <p>I mean, uh, well, a way to insert functionality into the base program without altering it. I didn't intend to define it when I set out. Dependency Injection doesn't <em>look</em> particularly suitable for what I'm doing, but I don't know much about them.</p>
[ { "answer_id": 99534, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 1, "selected": false, "text": "setuptools pkg_resources" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99497", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18515/" ]
99,510
<p>Does having several levels of base classes slow down a class? A derives B derives C derives D derives F derives G, ...</p> <p>Does multiple inheritance slow down a class?</p>
[ { "answer_id": 99531, "author": "Statement", "author_id": 2166173, "author_profile": "https://Stackoverflow.com/users/2166173", "pm_score": 0, "selected": false, "text": "// F is-a E,\n// E is-a D and so on\n\nA* aObject = new F(); \naObject->CallAVirtual();\n" }, { "answer_id": 99633, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "(static_cast<Base*>( this) == this)\n" }, { "answer_id": 101249, "author": "Richard Corden", "author_id": 11698, "author_profile": "https://Stackoverflow.com/users/11698", "pm_score": 0, "selected": false, "text": "dynamic_cast dynamic_cast sturct A { int i; };\nstruct B { int j; };\n\nstruct C : public A, public B { int k ; };\n\n// Let's assume that the layout of C is: { [ int i ] [ int j ] [int k ] }\n\nvoid foo (C * c) {\n A * a = c; // Probably has zero cost\n B * b = c; // Compiler needed to add sizeof(A) to 'c'\n c = static_cast<B*> (b); // Compiler needed to take sizeof(A)' from 'b'\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
99,535
<p>What tools do you use for Automated Builds / Automated Deployments? Why?</p> <p>What tools do you recommend?</p>
[ { "answer_id": 99601, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 2, "selected": false, "text": "make bash make cmd" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99535", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18475/" ]
99,542
<p>How do I correct for floating point error in the following physical simulation:</p> <ul> <li>Original point (x, y, z),</li> <li>Desired point (x', y', z') after forces are applied.</li> <li>Two triangles (A, B, C) and (B, C, D), who share edge BC</li> </ul> <p>I am using this method for collision detection:</p> <pre><code>For each Triangle If the original point is in front of the current triangle, and the desired point is behind the desired triangle: Calculate the intersection point of the ray (original-desired) and the plane (triangle's normal). If the intersection point is inside the triangle edges (!) Respond to the collision. End If End If Next Triangle </code></pre> <p>The problem I am having is that sometimes the point falls into the grey area of floating point math where it is so close to the line BC that it fails to collide with either triangle, even though technically it should always collide with one or the other since they share an edge. When this happens the point passes right between the two edge sharing triangles. I have marked one line of the code with <strong>(!)</strong> because I believe that's where I should be making a change.</p> <p>One idea that works in very limited situations is to skip the edge testing. Effectively turning the triangles into planes. This only works when my meshes are convex hulls, but I plan to create convex shapes.</p> <p>I am specifically using the dot product and triangle normals for all of my front-back testing.</p>
[ { "answer_id": 168377, "author": "user4891", "author_id": 4891, "author_profile": "https://Stackoverflow.com/users/4891", "pm_score": 0, "selected": false, "text": "double Distance(double x0, double y0, double x1, double y1)\n{\n double a, b, dx, dy;\n\n dx = abs(x1 - x0);\n dy = abs(y1 - y0);\n\n a = max(dx, dy));\n if (a == 0)\n return 0;\n b = min(dx, dy);\n\n return a * sqrt( 1 + (b*b) / (a*a) );\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2581/" ]
99,546
<p>I read this <a href="http://smartprogrammer.blogspot.com/2006/04/15-exercises-for-learning-new.html" rel="nofollow noreferrer">article</a> and try to do the exercise in D Programming Language, but encounter a problem in the first exercise.</p> <blockquote> <p>(1) Display series of numbers (1,2,3,4, 5....etc) in an infinite loop. The program should quit if someone hits a specific key (Say ESCAPE key).</p> </blockquote> <p>Of course the infinite loop is not a big problem, but the rest is. How could I grab a key hit in D/Tango? In tango FAQ it says use C function kbhit() or get(), but as I know, these are not in C standard library, and does not exist in glibc which come with my Linux machine which I use to programming.</p> <p>I know I can use some 3rd party library like <a href="http://www.gnu.org/software/ncurses/" rel="nofollow noreferrer">ncurses</a>, but it has same problem just like kbhit() or get(), it is not standard library in C or D and not pre-installed on Windows. What I hope is that I could done this exercise use just D/Tango and could run it on both Linux and Windows machine.</p> <p>How could I do it?</p>
[ { "answer_id": 100380, "author": "Brian Hsu", "author_id": 242644, "author_profile": "https://Stackoverflow.com/users/242644", "pm_score": 0, "selected": false, "text": "import tango.io.Stdout;\nimport tango.core.Thread;\n\n// Prototype for used ncurses library function.\nextern(C)\n{\n void * initscr();\n int cbreak ();\n int getch();\n int endwin();\n int noecho();\n}\n\n// A keyboard handler to quit the program when user hit ESC key.\nvoid keyboardHandler ()\n{\n initscr();\n cbreak();\n noecho();\n while (getch() != 27) {\n }\n endwin();\n}\n\n// Main Program\nvoid main ()\n{\n Thread handler = new Thread (&keyboardHandler);\n handler.start();\n\n for (int i = 0; ; i++) {\n Stdout.format (\"{}\\r\\n\", i).flush;\n\n // If keyboardHandler is not ruuning, it means user hits\n // ESC key, so we break the infinite loop.\n if (handler.isRunning == false) {\n break;\n }\n }\n\n return 0;\n}\n" }, { "answer_id": 261583, "author": "Walter Bright", "author_id": 33949, "author_profile": "https://Stackoverflow.com/users/33949", "pm_score": 3, "selected": false, "text": " import std.c.stdio;\n import std.c.linux.termios;\n\n termios ostate; /* saved tty state */\n termios nstate; /* values for editor mode */\n\n // Open stdin in raw mode\n /* Adjust output channel */\n tcgetattr(1, &ostate); /* save old state */\n tcgetattr(1, &nstate); /* get base of new state */\n cfmakeraw(&nstate);\n tcsetattr(1, TCSADRAIN, &nstate); /* set mode */\n\n // Read characters in raw mode\n c = fgetc(stdin);\n\n // Close\n tcsetattr(1, TCSADRAIN, &ostate); // return to original mode\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/242644/" ]
99,552
<p>I sometimes notice programs that crash on my computer with the error: "pure virtual function call".</p> <p>How do these programs even compile when an object cannot be created of an abstract class?</p>
[ { "answer_id": 99575, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 8, "selected": true, "text": "class Base\n{\npublic:\n Base() { reallyDoIt(); }\n void reallyDoIt() { doIt(); } // DON'T DO THIS\n virtual void doIt() = 0;\n};\n\nclass Derived : public Base\n{\n void doIt() {}\n};\n\nint main(void)\n{\n Derived d; // This will cause \"pure virtual function call\" error\n}\n" }, { "answer_id": 99622, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": -1, "selected": false, "text": "class A\n{\n A *pThis;\n public:\n A()\n : pThis(this)\n {\n }\n\n void callFoo()\n {\n pThis->foo(); // call through the pThis ptr which was initialized in the constructor\n }\n\n virtual void foo() = 0;\n};\n\nclass B : public A\n{\npublic:\n virtual void foo()\n {\n }\n};\n\nB b();\nb.callFoo();\n" }, { "answer_id": 100555, "author": "Len Holgate", "author_id": 7925, "author_profile": "https://Stackoverflow.com/users/7925", "pm_score": 6, "selected": false, "text": "int __cdecl _purecall(void)\n" }, { "answer_id": 13410826, "author": "David Lee", "author_id": 853315, "author_profile": "https://Stackoverflow.com/users/853315", "pm_score": 0, "selected": false, "text": "template <typename T>\nclass Foo {\npublic:\n Foo<T>() {};\n ~Foo<T>() {};\n\npublic:\n void SomeMethod1() { this->~Foo(); }; /* ERROR */\n};\n template <typename T>\nclass Foo {\npublic:\n Foo<T>() {};\n ~Foo<T>() {};\n\npublic:\n void _MethodThatDestructs() {};\n void SomeMethod1() { this->_MethodThatDestructs(); }; /* OK */\n};\n" }, { "answer_id": 49431746, "author": "Niki", "author_id": 1894559, "author_profile": "https://Stackoverflow.com/users/1894559", "pm_score": 0, "selected": false, "text": "extern \"C\" void _RTLENTRY _pure_error_()\n{\n //_ErrorExit(\"Pure virtual function called\");\n throw Exception(\"Pure virtual function called\");\n}\n" }, { "answer_id": 56061610, "author": "Baiyan Huang", "author_id": 70198, "author_profile": "https://Stackoverflow.com/users/70198", "pm_score": 3, "selected": false, "text": "Len Holgate #include <iostream>\n using namespace std;\n\n char pool[256];\n\n struct Base\n {\n virtual void foo() = 0;\n virtual ~Base(){};\n };\n\n struct Derived: public Base\n {\n virtual void foo() override { cout <<\"Derived::foo()\" << endl;}\n };\n\n int main()\n {\n auto* pd = new (pool) Derived();\n Base* pb = pd;\n pd->~Derived();\n pb->foo();\n }\n #0 0x00007ffff7499428 in __GI_raise (sig=sig@entry=6) at ../sysdeps/unix/sysv/linux/raise.c:54\n#1 0x00007ffff749b02a in __GI_abort () at abort.c:89\n#2 0x00007ffff7ad78f7 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6\n#3 0x00007ffff7adda46 in ?? () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6\n#4 0x00007ffff7adda81 in std::terminate() () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6\n#5 0x00007ffff7ade84f in __cxa_pure_virtual () from /usr/lib/x86_64-linux-gnu/libstdc++.so.6\n#6 0x0000000000400f82 in main () at purev.C:22\n Segmentation fault" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99552", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
99,560
<p>I am working on a Rails application that needs to handle dates and times in users' time zones. We have recently migrated it to Rails 2.1 and added time zone support, but there are numerous situations in which we use Time#utc and then compare against that time. Wouldn't that be the same as comparing against the original Time object?</p> <p>When is it appropriate to use Time#utc in Rails 2.1? When is it inappropriate?</p>
[ { "answer_id": 99942, "author": "nikz", "author_id": 3977, "author_profile": "https://Stackoverflow.com/users/3977", "pm_score": 4, "selected": true, "text": "config.time_zone = 'UTC'\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99560", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7717/" ]
99,623
<p>I'd like to be able to do some drawing to the right of the menu bar, in the nonclient area of a window. </p> <p>Is this possible, using C++ / MFC?</p>
[ { "answer_id": 99679, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 2, "selected": false, "text": "case WM_NCPAINT:\n{\n HDC hdc;\n hdc = GetDCEx(hwnd, (HRGN)wParam, DCX_WINDOW|DCX_INTERSECTRGN);\n // Paint into this DC\n ReleaseDC(hwnd, hdc);\n}\n" }, { "answer_id": 99787, "author": "Shog9", "author_id": 811, "author_profile": "https://Stackoverflow.com/users/811", "pm_score": 5, "selected": true, "text": "WM_NCPAINT // in the message map\nON_WM_NCPAINT()\n\n// ...\n\nvoid CMainFrame::OnNcPaint()\n{\n // still want the menu to be drawn, so trigger default handler first\n Default();\n\n // get menu bar bounds\n MENUBARINFO menuInfo = {sizeof(MENUBARINFO)};\n if ( GetMenuBarInfo(OBJID_MENU, 0, &menuInfo) )\n {\n CRect windowBounds;\n GetWindowRect(&windowBounds);\n CRect menuBounds(menuInfo.rcBar);\n menuBounds.OffsetRect(-windowBounds.TopLeft());\n\n // horrible, horrible icon-drawing code. Don't use this. Seriously.\n CWindowDC dc(this);\n HICON appIcon = (HICON)::LoadImage(AfxGetResourceHandle(), MAKEINTRESOURCE(IDR_MAINFRAME), IMAGE_ICON, 16, 16, LR_DEFAULTCOLOR);\n ::DrawIconEx(dc, menuBounds.right-18, menuBounds.top+2, appIcon, 0,0, 0, NULL, DI_NORMAL);\n ::DestroyIcon(appIcon);\n }\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99623", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
99,642
<p>I was curious if anyone had any problems creating unit tests around using the ResourceManager. I am using Visual Studio test edition and it appears that the satellite assemblies don't get loaded during the test. When I try to get a resource for another culture, the test always fails and the resource manager always falls back to the default culture. The exact same code runs fine within the normal application.</p>
[ { "answer_id": 62429661, "author": "jackomo", "author_id": 2393063, "author_profile": "https://Stackoverflow.com/users/2393063", "pm_score": 1, "selected": false, "text": "[DeploymentItem( @\"de-DE\\AssemblyName.resources.dll\", \"de-DE\")]\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99642", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10874/" ]
99,643
<p>After applying a CSS reset, I want to get back to 'normal' behavior for html elements like: p, h1..h6, strong, ul and li.</p> <p>Now when I say normal I mean e.g. the p element adds spacing or a carriage return like result when used, or the size of the font and boldness for a h1 tag, along with the spacing.</p> <p>I realize it is totally up to me how I want to set the style, but I want to get back to normal behavior for some of the more common elements (at least as a starting point that I can tweak later on).</p>
[ { "answer_id": 99646, "author": "da5id", "author_id": 14979, "author_profile": "https://Stackoverflow.com/users/14979", "pm_score": 3, "selected": false, "text": "* {\n padding: 0;\n margin: 0;\n}\n\nh1, h2, h3, h4, h5, h6, p, blockquote, form, label, ul, ol, dl, fieldset, address {\n margin-bottom: 1em;\n}\n" }, { "answer_id": 99693, "author": "Carl Camera", "author_id": 12804, "author_profile": "https://Stackoverflow.com/users/12804", "pm_score": 3, "selected": false, "text": "margin:0; padding:0 <link/>" }, { "answer_id": 477010, "author": "Simon_Weaver", "author_id": 16940, "author_profile": "https://Stackoverflow.com/users/16940", "pm_score": 3, "selected": false, "text": "ol li {\n /*giving OL's LIs generated numbers*/\n list-style: decimal outside; \n}\nul li {\n /*giving UL's LIs generated disc markers*/\n list-style: disc outside;\n}\ndl dd {\n /*giving UL's LIs generated numbers*/\n margin-left:1em;\n}\nth,td {\n /*borders and padding to make the table readable*/\n border:1px solid #000;\n padding:.5em;\n}\nth {\n /*distinguishing table headers from data cells*/\n font-weight:bold;\n text-align:center;\n}\n" }, { "answer_id": 1955856, "author": "robertc", "author_id": 8655, "author_profile": "https://Stackoverflow.com/users/8655", "pm_score": 2, "selected": false, "text": "h1 {\n display: block;\n font-size: 2em;\n margin: .67__qem 0 .67em 0;\n font-weight: bold\n}\n h1 {\n display: block;\n font-size: 2em;\n font-weight: bold;\n margin: .67em 0;\n}\n" }, { "answer_id": 8082601, "author": "Jake Rayson", "author_id": 889487, "author_profile": "https://Stackoverflow.com/users/889487", "pm_score": 3, "selected": false, "text": "Computed" }, { "answer_id": 13986214, "author": "Mahdi", "author_id": 1658526, "author_profile": "https://Stackoverflow.com/users/1658526", "pm_score": -1, "selected": false, "text": "ul, ol { list-style: none; } r reset ul r class=\"reset\"" }, { "answer_id": 17906592, "author": "Jukka K. Korpela", "author_id": 1084437, "author_profile": "https://Stackoverflow.com/users/1084437", "pm_score": 0, "selected": false, "text": "h1 font-size * { font-size: 100% } * input, textarea { font-size: 100% } font-size h1 h1 {\nunicode-bidi: isolate;\ndisplay: block;\nmargin-top: 0.67em;\nmargin-bottom: 0.67em;\nfont-size: 2.00em;\nfont-weight: bold;\n}\n h1 section" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99643", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1368/" ]
99,683
<p>My question is what do most developers prefer for error handling, Exceptions or Error Return Codes. Please be language(or language family) specific and why you prefer one over the other.</p> <p>I'm asking this out of curiosity. Personally I prefer Error Return Codes since they are less explosive and don't force user code to pay the exception performance penalty if they don't want to.</p> <p>update: thanks for all the answers! I must say that although I dislike the unpredictability of code flow with exceptions. The answer about return code (and their elder brother handles) do add lots of Noise to the code.</p>
[ { "answer_id": 99728, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 1, "selected": false, "text": "doFoo()" }, { "answer_id": 99740, "author": "Robert Gould", "author_id": 15124, "author_profile": "https://Stackoverflow.com/users/15124", "pm_score": 1, "selected": false, "text": "void foo()\n{\n MyPointer* p = NULL;\n try{\n p = new PointedStuff();\n //I'm a module user and I'm doing stuff that might throw or not\n\n }\n catch(...)\n {\n //should I delete the pointer?\n }\n}\n" }, { "answer_id": 99749, "author": "Daniel Bruce", "author_id": 6456, "author_profile": "https://Stackoverflow.com/users/6456", "pm_score": 2, "selected": false, "text": "if(function(call) != ERROR_CODE) {\n do_right_thing();\n}\nelse {\n handle_error();\n}\n" }, { "answer_id": 99784, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 3, "selected": false, "text": "CRetType obReturn = CODE_SUCCESS;\nobReturn = CallMyFunctionWhichReturnsCodes();\nif (obReturn == CODE_BLOW_UP)\n{\n // bail out\n goto FunctionExit;\n}\n" }, { "answer_id": 99800, "author": "Jonathan Adelson", "author_id": 8092, "author_profile": "https://Stackoverflow.com/users/8092", "pm_score": 1, "selected": false, "text": "try{} catch() {} finally {} if(){}" }, { "answer_id": 99822, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 2, "selected": false, "text": "try:\n dataobj = datastore.fetch(obj_id)\nexcept LookupError:\n # could not find object, create it.\n dataobj = datastore.create(....)\n # wrong way:\nif os.path.exists(directory_to_remove):\n # race condition is here.\n os.path.rmdir(directory_to_remove)\n\n# right way:\ntry: \n os.path.rmdir(directory_to_remove)\nexcept OSError:\n # directory didn't exist, good.\n pass\n" }, { "answer_id": 100300, "author": "noocyte", "author_id": 11220, "author_profile": "https://Stackoverflow.com/users/11220", "pm_score": 2, "selected": false, "text": "try{\n db.UpdateAll(somevalue);\n}\ncatch (Exception ex) {\n logger.Exception(ex, \"UpdateAll method failed\");\n throw;\n}\n try{\n dbHasBeenUpdated = db.UpdateAll(somevalue); // true/false\n}\ncatch (ConnectionException ex) {\n logger.Exception(ex, \"Connection failed\");\n dbHasBeenUpdated = false;\n}\n try{\n db.UpdateAll(somevalue);\n}\ncatch (Exception ex) {\n logger.Exception(ex, \"UpdateAll method failed\");\n throw;\n}\nfinally {\n db.Close();\n}\n try{\n using(IDatabase db = DatabaseFactory.CreateDatabase()) {\n db.UpdateAll(somevalue);\n }\n}\ncatch (Exception ex) {\n logger.Exception(ex, \"UpdateAll method failed\");\n throw;\n}\n try{\n try {\n IDatabase db = DatabaseFactory.CreateDatabase();\n db.UpdateAll(somevalue);\n }\n finally{\n db.Close();\n }\n}\ncatch (DatabaseAlreadyClosedException dbClosedEx) {\n logger.Exception(dbClosedEx, \"Database connection was closed already.\");\n}\ncatch (Exception ex) {\n logger.Exception(ex, \"UpdateAll method failed\");\n throw;\n}\n" }, { "answer_id": 111213, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 8, "selected": true, "text": "if(doSomething())\n{\n if(doSomethingElse())\n {\n if(doSomethingElseAgain())\n {\n // etc.\n }\n else\n {\n // react to failure of doSomethingElseAgain\n }\n }\n else\n {\n // react to failure of doSomethingElse\n }\n}\nelse\n{\n // react to failure of doSomething\n}\n try\n{\n doSomething() ;\n doSomethingElse() ;\n doSomethingElseAgain() ;\n}\ncatch(const SomethingException & e)\n{\n // react to failure of doSomething\n}\ncatch(const SomethingElseException & e)\n{\n // react to failure of doSomethingElse\n}\ncatch(const SomethingElseAgainException & e)\n{\n // react to failure of doSomethingElseAgain\n}\n CMyType o = add(a, multiply(b, c)) ;\n void doSomething(CMyObject * p, int iRandomData)\n{\n // etc.\n}\n void doSomething(CMyObject * p, int iRandomData)\n{\n if(iRandomData < 32)\n {\n MY_RAISE_ERROR(\"Hey, iRandomData \" << iRandomData << \" is lesser than 32. Aborting processing\") ;\n return ;\n }\n\n if(p == NULL)\n {\n MY_RAISE_ERROR(\"Hey, p is NULL !\\niRandomData is equal to \" << iRandomData << \". Will throw.\") ;\n throw std::some_exception() ;\n }\n\n if(! p.is Ok())\n {\n MY_RAISE_ERROR(\"Hey, p is NOT Ok!\\np is equal to \" << p->toString() << \". Will try to continue anyway\") ;\n }\n\n // etc.\n}\n" }, { "answer_id": 63397412, "author": "Nathan Long", "author_id": 4376, "author_profile": "https://Stackoverflow.com/users/4376", "pm_score": 2, "selected": false, "text": "# I care whether this succeeds. If it doesn't return :ok, raise an exception.\n:ok = File.write(path, content)\n\n# I don't care whether this succeeds. Don't check the return value.\nFile.write(path, content)\n\n# This had better not succeed - the path should be read-only to me.\n# If I get anything other than this error, raise an exception.\n{:error, :erofs} = File.write(path, content)\n\n# I want this to succeed but I can handle its failure\ncase File.write(path, content) do\n :ok => handle_success()\n error => handle_error(error)\nend\n if with with {:ok, content} <- get_content(),\n :ok <- File.write(path, content) do\n IO.puts \"everything worked, happy path code goes here\"\nelse\n # Here we can use a single catch-all failure clause\n # or match every kind of failure individually\n # or match subsets of them however we like\n _some_error => IO.puts \"one of those steps failed\"\n _other_error => IO.puts \"one of those steps failed\"\nend\n # Raises a generic MatchError because the return value isn't :ok\n:ok = File.write(path, content)\n\n# Raises a File.Error with a descriptive error message - eg, saying\n# that the file is read-only\nFile.write!(path, content)\n File.write! File.write File.write rescue" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99683", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15124/" ]
99,684
<p>The most basic task in an object oriented environment is executing a method on an object. To do this, you have to have a reference to the object on which you are invoking the method. Is the proper way to establish this reference to pass the object as a parameter to the constructor (or initializer method) of the calling object?</p> <p>If object <code> foo </code> calls into object <code> bar</code>, is it correct to say (in pseudo-code):</p> <pre><code>bar = new barClass() foo = new fooClass(bar) </code></pre> <p>What happens if you need to pass messages back and forth? Do you need a method for registering the target object?</p> <pre><code>foo = new fooClass() bar = new barClass() foo.register(bar) bar.register(foo) </code></pre> <p>Is there a pattern that addresses this?</p>
[ { "answer_id": 99921, "author": "xanadont", "author_id": 1886, "author_profile": "https://Stackoverflow.com/users/1886", "pm_score": 0, "selected": false, "text": "foo = new Foo();\nbar = Foo.Poop();\n\nfunction Foo::Poop()\n{\n bar = new Bar(this);\n myChildren.Add(bar);\n return bar;\n}\n\nbar.SayHiToParent();\nfoo.SayHiToChildren();\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99684", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8092/" ]
99,686
<p>From <a href="http://en.wikipedia.org/wiki/Generic_programming" rel="noreferrer">Wikipedia</a>: </p> <blockquote> <p>Generic programming is a style of computer programming in which algorithms are written in terms of to-be-specified-later types that are then instantiated when needed for specific types provided as parameters and was pioneered by Ada which appeared in 1983. This approach permits writing common functions or types that differ only in the set of types on which they operate when used, thus reducing duplication.</p> </blockquote> <p>Generics provide the ability to define types that are specified later. You don't have to cast items to a type to use them because they are already typed.</p> <p>Why does C# and VB have Generics? What benefit do they provide? What benefits do you find using them?</p> <p>What other languages also have generics?</p>
[ { "answer_id": 99712, "author": "Francis B.", "author_id": 17067, "author_profile": "https://Stackoverflow.com/users/17067", "pm_score": 3, "selected": false, "text": "List<MyObject>" }, { "answer_id": 126278, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 2, "selected": false, "text": "//Old and busted\npublic abstract class Enum\n{\n public static object Parse(Type enumType, string value);\n}\n//To call it:\nMyEnum x = (MyEnum) Enum.Parse(typeof(MyEnum), someString);\n //New and groovy\npublic abstract class Enum\n{\n public static T Parse<T>(string value);\n}\n\n//To call it:\nMyEnum x = Enum.Parse<MyEnum>(someString);\n" }, { "answer_id": 126294, "author": "Armin Ronacher", "author_id": 19990, "author_profile": "https://Stackoverflow.com/users/19990", "pm_score": 1, "selected": false, "text": "List<int>" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99686", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18475/" ]
99,688
<p>One of the biggest advantages of object-oriented programming is encapsulation, and one of the "truths" we've (or, at least, I've) been taught is that members should always be made private and made available via accessor and mutator methods, thus ensuring the ability to verify and validate the changes.</p> <p>I'm curious, though, how important this really is in practice. In particular, if you've got a more complicated member (such as a collection), it can be very tempting to just make it public rather than make a bunch of methods to get the collection's keys, add/remove items from the collection, etc.</p> <p>Do you follow the rule in general? Does your answer change depending on whether it's code written for yourself vs. to be used by others? Are there more subtle reasons I'm missing for this obfuscation?</p>
[ { "answer_id": 99703, "author": "SCdF", "author_id": 1666, "author_profile": "https://Stackoverflow.com/users/1666", "pm_score": 0, "selected": false, "text": "private Foo foo;\npublic Foo getFoo() {}\npublic void setFoo(Foo foo) {}\n" }, { "answer_id": 99751, "author": "Mike Stone", "author_id": 122, "author_profile": "https://Stackoverflow.com/users/122", "pm_score": 0, "selected": false, "text": "private static class SomeSmallDataStructure {\n public int someField;\n public String someOtherField;\n}\n" }, { "answer_id": 530581, "author": "Esko Luontola", "author_id": 62130, "author_profile": "https://Stackoverflow.com/users/62130", "pm_score": 0, "selected": false, "text": "x setX(String) public boolean isEmployeeStatusEnabled() {\n return pinCodeValidation.equals(PinCodeValidation.VALID);\n}\n\npublic EmployeeStatus getEmployeeStatus() {\n Employee employee;\n if (isEmployeeStatusEnabled()\n && (employee = getSelectedEmployee()) != null) {\n return employee.getStatus();\n }\n return null;\n}\n\npublic void setEmployeeStatus(EmployeeStatus status) {\n getSelectedEmployee().changeStatusTo(status, getPinCode());\n fireComponentStateChanged();\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99688", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18210/" ]
99,732
<p>Using reflection in .Net, what is the differnce between:</p> <pre><code> if (foo.IsAssignableFrom(typeof(IBar))) </code></pre> <p>And</p> <pre><code> if (foo.GetInterface(typeof(IBar).FullName) != null) </code></pre> <p>Which is more appropriate, why?<br></p> <p>When could one or the other fail?</p>
[ { "answer_id": 45838091, "author": "Holf", "author_id": 169334, "author_profile": "https://Stackoverflow.com/users/169334", "pm_score": 1, "selected": false, "text": "public interface IFoo\n{\n} \n\ninternal class Foo: IFoo\n{\n}\n var types = typeof(IFoo).Assembly.GetTypes()\n .Where(x => x.GetInterface(typeof(IFoo).FullName) != null)\n .ToList();\n var types = typeof(IFoo).Assembly.GetTypes()\n .Where(x => x.IsAssignableFrom(typeof(IFoo))\n .ToList();\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14484/" ]
99,755
<p>When working on a linx CShell u get the option to press the up / down arrows to select the last command/s typed or the Command Buffer. This even works on Windows.</p> <p>However this is not functional when working on Solaris, to which i recently switched. I am guessing that the shell is also a CShell. </p> <p>Please tell me what key combination is required to have this feature on Solaris ?</p>
[ { "answer_id": 100729, "author": "Hank Gay", "author_id": 4203, "author_profile": "https://Stackoverflow.com/users/4203", "pm_score": 2, "selected": false, "text": "sh csh tcsh root sh root passwd -e /path/to/shell_of_your_choice <loginname> passwd -e /bin/csh <loginname>" }, { "answer_id": 34173265, "author": "Sami Onur Zaim", "author_id": 2765700, "author_profile": "https://Stackoverflow.com/users/2765700", "pm_score": 0, "selected": false, "text": "HISTSIZE=1000\n HISTSIZE=1000\nHISTFILESIZE=1000\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99755", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
99,781
<p>I have a client that is asking me to give them a listing of every file and folder in the source code (and then a brief explanation of the source tree). Is there an easy way to create some sort of decently formatted list like this from a subversion repository?</p>
[ { "answer_id": 99797, "author": "Thomas", "author_id": 14637, "author_profile": "https://Stackoverflow.com/users/14637", "pm_score": 1, "selected": false, "text": "cd" }, { "answer_id": 99810, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 4, "selected": true, "text": "svn list -R http://example.com/path/to/repos\n svn list -R http://example.com/path/to/repos > file.txt\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1486/" ]
99,807
<p>Macs are renowned (or bemoaned) for having an extensive number of shortcuts. However, OS X itself pales in comparison to the shortcut lists in <a href="http://macromates.com/" rel="noreferrer">TextMate</a> and its bundles.</p> <p>What are some useful keyboard shortcuts you use?</p>
[ { "answer_id": 100528, "author": "Matt", "author_id": 15368, "author_profile": "https://Stackoverflow.com/users/15368", "pm_score": 3, "selected": false, "text": "if⇥" }, { "answer_id": 2646864, "author": "Agos", "author_id": 107613, "author_profile": "https://Stackoverflow.com/users/107613", "pm_score": 0, "selected": false, "text": "\\n <br>" }, { "answer_id": 4586495, "author": "Cory Schires", "author_id": 388061, "author_profile": "https://Stackoverflow.com/users/388061", "pm_score": 1, "selected": false, "text": "Lorem ipsum dolor sit amet, consectetur\n <p>Lorem ipsum dolor sit amet, consectetur</p>\n" }, { "answer_id": 4586587, "author": "Cory Schires", "author_id": 388061, "author_profile": "https://Stackoverflow.com/users/388061", "pm_score": 2, "selected": false, "text": "<div>Lorem ipsum dolor sit amet, consectetur\n </div> <div>Lorem ipsum dolor sit amet, consectetur</div>\n" }, { "answer_id": 4586645, "author": "Cory Schires", "author_id": 388061, "author_profile": "https://Stackoverflow.com/users/388061", "pm_score": 2, "selected": false, "text": " This is a \n few sample\n list items \n <li>This is a </li>\n <li>few sample</li>\n <li>list items</li>\n" }, { "answer_id": 4586776, "author": "Cory Schires", "author_id": 388061, "author_profile": "https://Stackoverflow.com/users/388061", "pm_score": 2, "selected": false, "text": "body { background: red; font-size: 10px; color: black; }\n body {\n background: red;\n font-size: 10px;\n color: black;\n}\n" }, { "answer_id": 4586904, "author": "Eric Van Joshnon", "author_id": 560190, "author_profile": "https://Stackoverflow.com/users/560190", "pm_score": 4, "selected": false, "text": "LongFuntionNameThatChecksStuff Lon" }, { "answer_id": 4586920, "author": "Cory Schires", "author_id": 388061, "author_profile": "https://Stackoverflow.com/users/388061", "pm_score": 2, "selected": false, "text": "body {\n background: red;\n}\n" }, { "answer_id": 4589132, "author": "Cory Schires", "author_id": 388061, "author_profile": "https://Stackoverflow.com/users/388061", "pm_score": 2, "selected": false, "text": "lorem" }, { "answer_id": 5123781, "author": "Cory Schires", "author_id": 388061, "author_profile": "https://Stackoverflow.com/users/388061", "pm_score": 2, "selected": false, "text": "{} do end do @post.each do |post|\n puts post.name\nend\n @post.each { |post| puts post.name }\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99807", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1167846/" ]
99,827
<p>I'm interested in tracing database calls made by LINQ to SQL back to the .NET code that generated the call. For instance, a DBA might have a concern that a particular cached execution plan is doing poorly. If for example a DBA were to tell a developer to address the following code...</p> <pre><code>exec sp_executesql N'SELECT [t0].[CustomerID] FROM [dbo].[Customers] AS [t0] WHERE [t0].[ContactName] LIKE @p0 ORDER BY [t0].[CompanyName]', 'N'@p0 nvarchar(2)',@p0=N'c%' </code></pre> <p>...it's not immediately obvious which LINQ statement produced the call. Sure you could search through the "Customers" class in the auto-generated data context, but that'd just be a start. With a large application this could quickly become unmanageable.</p> <p>Is there a way to attach an ID or label to SQL code generated and executed by LINQ to SQL? Thinking out loud, here's an extension function called "TagWith" that illustrates conceptually what I'm interested in doing.</p> <pre><code>var customers = from c in context.Customers where c.CompanyName.StartsWith("c") orderby c.CompanyName select c.CustomerID; foreach (var CustomerID in customers.TagWith("CustomerList4")) { Console.WriteLine(CustomerID); } </code></pre> <p>If the "CustomerList4" ID/label ends up in the automatically-generated SQL, I'd be set. Thanks.</p>
[ { "answer_id": 100528, "author": "Matt", "author_id": 15368, "author_profile": "https://Stackoverflow.com/users/15368", "pm_score": 3, "selected": false, "text": "if⇥" }, { "answer_id": 2646864, "author": "Agos", "author_id": 107613, "author_profile": "https://Stackoverflow.com/users/107613", "pm_score": 0, "selected": false, "text": "\\n <br>" }, { "answer_id": 4586495, "author": "Cory Schires", "author_id": 388061, "author_profile": "https://Stackoverflow.com/users/388061", "pm_score": 1, "selected": false, "text": "Lorem ipsum dolor sit amet, consectetur\n <p>Lorem ipsum dolor sit amet, consectetur</p>\n" }, { "answer_id": 4586587, "author": "Cory Schires", "author_id": 388061, "author_profile": "https://Stackoverflow.com/users/388061", "pm_score": 2, "selected": false, "text": "<div>Lorem ipsum dolor sit amet, consectetur\n </div> <div>Lorem ipsum dolor sit amet, consectetur</div>\n" }, { "answer_id": 4586645, "author": "Cory Schires", "author_id": 388061, "author_profile": "https://Stackoverflow.com/users/388061", "pm_score": 2, "selected": false, "text": " This is a \n few sample\n list items \n <li>This is a </li>\n <li>few sample</li>\n <li>list items</li>\n" }, { "answer_id": 4586776, "author": "Cory Schires", "author_id": 388061, "author_profile": "https://Stackoverflow.com/users/388061", "pm_score": 2, "selected": false, "text": "body { background: red; font-size: 10px; color: black; }\n body {\n background: red;\n font-size: 10px;\n color: black;\n}\n" }, { "answer_id": 4586904, "author": "Eric Van Joshnon", "author_id": 560190, "author_profile": "https://Stackoverflow.com/users/560190", "pm_score": 4, "selected": false, "text": "LongFuntionNameThatChecksStuff Lon" }, { "answer_id": 4586920, "author": "Cory Schires", "author_id": 388061, "author_profile": "https://Stackoverflow.com/users/388061", "pm_score": 2, "selected": false, "text": "body {\n background: red;\n}\n" }, { "answer_id": 4589132, "author": "Cory Schires", "author_id": 388061, "author_profile": "https://Stackoverflow.com/users/388061", "pm_score": 2, "selected": false, "text": "lorem" }, { "answer_id": 5123781, "author": "Cory Schires", "author_id": 388061, "author_profile": "https://Stackoverflow.com/users/388061", "pm_score": 2, "selected": false, "text": "{} do end do @post.each do |post|\n puts post.name\nend\n @post.each { |post| puts post.name }\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99827", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1360388/" ]
99,866
<p>I'm at the beginning/middle of a project that we chose to implement using GWT. Has anyone encountered any major pitfalls in using GWT (and GWT-EXT) that were unable to be overcome? How about from a performance perspective?</p> <p>A couple things that we've seen/heard already include:</p> <ul> <li>Google not being able to index content</li> <li>CSS and styling in general seems to be a bit flaky</li> </ul> <p>Looking for any additional feedback on these items as well. Thanks!</p>
[ { "answer_id": 99977, "author": "rustyshelf", "author_id": 6044, "author_profile": "https://Stackoverflow.com/users/6044", "pm_score": 9, "selected": true, "text": "<set-property name=\"user.agent\" value=\"gecko1_8\" />\n" }, { "answer_id": 104641, "author": "jgindin", "author_id": 17941, "author_profile": "https://Stackoverflow.com/users/17941", "pm_score": 4, "selected": false, "text": ".my-style { /* stuff that works most everywhere */ }\n\n.msie6 .my-style { /* \"override\" so that styles work on IE 6 */ }\n" }, { "answer_id": 431537, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "RootPanel.get( id ).add( widget )" }, { "answer_id": 3280983, "author": "Jla", "author_id": 255844, "author_profile": "https://Stackoverflow.com/users/255844", "pm_score": 4, "selected": false, "text": "java.util.Date java.util.Calendar" }, { "answer_id": 9905934, "author": "Gal Bracha", "author_id": 395804, "author_profile": "https://Stackoverflow.com/users/395804", "pm_score": 2, "selected": false, "text": "<set-property name=\"user.agent\" value=\"gecko1_8\" />\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99866", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18402/" ]
99,876
<p>I just wanted some opinions from people that have run Selenium (<a href="http://selenium.openqa.org" rel="nofollow noreferrer">http://selenium.openqa.org</a>) I have had a lot of experience with WaTiN and even wrote a recording suite for it. I had it producing some well-structured code but being only maintained by me it seems my company all but abandoned it. </p> <p>If you have run selenium have you had a lot of success? </p> <p>I will be using .NET 3.5, does Selenium work well with it? </p> <p>Is the code produced clean or simply a list of all the interaction? (<a href="http://blogs.conchango.com/richardgriffin/archive/2006/11/14/Testing-Design-Pattern-for-using-WATiR_2F00_N.aspx" rel="nofollow noreferrer">http://blogs.conchango.com/richardgriffin/archive/2006/11/14/Testing-Design-Pattern-for-using-WATiR_2F00_N.aspx</a>) </p> <p>How well does the distributed testing suite fair?</p> <p>Any other gripes or compliments on the system would be greatly appreciated!</p>
[ { "answer_id": 99965, "author": "marcospereira", "author_id": 4600, "author_profile": "https://Stackoverflow.com/users/4600", "pm_score": 6, "selected": true, "text": "public class GoogleTest {\n\n private Selenium selenium;\n\n @Before\n public void setUp() throws Exception {\n selenium = new DefaultSelenium(\"localhost\", 4444, \"*firefox\",\n \"http://www.google.com/webhp?hl=en\");\n selenium.start();\n }\n\n @Test\n public void codingDojoShouldBeInFirstPageOfResults() {\n GoogleHomePage home = new GoogleHomePage(selenium);\n GoogleSearchResults searchResults = home.searchFor(\"coding dojo\");\n String firstEntry = searchResults.getResult(0);\n assertEquals(\"Coding Dojo Wiki: FrontPage\", firstEntry);\n }\n\n @After\n public void tearDown() throws Exception {\n selenium.stop();\n }\n\n}\n\n\npublic class GoogleHomePage {\n\n private final Selenium selenium;\n\n public GoogleHomePage(Selenium selenium) {\n this.selenium = selenium;\n this.selenium.open(\"http://www.google.com/webhp?hl=en\");\n if (!\"Google\".equals(selenium.getTitle())) {\n throw new IllegalStateException(\"Not the Google Home Page\");\n }\n }\n\n public GoogleSearchResults searchFor(String string) {\n selenium.type(\"q\", string);\n selenium.click(\"btnG\");\n selenium.waitForPageToLoad(\"5000\");\n return new GoogleSearchResults(string, selenium);\n }\n}\n\npublic class GoogleSearchResults {\n\n private final Selenium selenium;\n\n public GoogleSearchResults(String string, Selenium selenium) {\n this.selenium = selenium;\n if (!(string + \" - Google Search\").equals(selenium.getTitle())) {\n throw new IllegalStateException(\n \"This is not the Google Results Page\");\n }\n }\n\n public String getResult(int i) {\n String nameXPath = \"xpath=id('res')/div[1]/div[\" + (i + 1) + \"]/h2/a\";\n return selenium.getText(nameXPath);\n }\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99876", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13688/" ]
99,880
<p>I need to write a function that generates an id that is unique for a given machine running a Windows OS.</p> <p>Currently, I'm using WMI to query various hardware parameters and concatenate them together and hash them to derive the unique id. My question is, what are the suggested parameters I should use? Currently, I'm using a combination of bios\cpu\disk data to generate the unique id. And am using the first result if multiple results are there for each metric.</p> <p>However, I ran into an issue where a machine that dual boots into 2 different Windows OS generates different site codes on each OS, which should ideally not happen.</p> <p>For reference, these are the metrics I'm currently using:</p> <pre><code>Win32_Processor:UniqueID,ProcessorID,Name,Manufacturer,MaxClockSpeed Win32_BIOS:Manufacturer Win32_BIOS:SMBIOSBIOSVersion,IdentificationCode,SerialNumber,ReleaseDate,Version Win32_DiskDrive:Model, Manufacturer, Signature, TotalHeads Win32_BaseBoard:Model, Manufacturer, Name, SerialNumber Win32_VideoController:DriverVersion, Name </code></pre>
[ { "answer_id": 114949, "author": "Jonas Engström", "author_id": 7634, "author_profile": "https://Stackoverflow.com/users/7634", "pm_score": 6, "selected": true, "text": "EnumSystemFirmwareEntries EnumSystemFirmwareTables GetSystemFirmwareTable" }, { "answer_id": 289806, "author": "AngelBlaZe", "author_id": 24252, "author_profile": "https://Stackoverflow.com/users/24252", "pm_score": 1, "selected": false, "text": "Name DriverVersion Clockspeed" }, { "answer_id": 820549, "author": "Fabio Ceconello", "author_id": 8999, "author_profile": "https://Stackoverflow.com/users/8999", "pm_score": 6, "selected": false, "text": "MachineGuid HKEY_LOCAL_MACHINE\\SOFTWARE\\Microsoft\\Cryptography" }, { "answer_id": 5502834, "author": "cmcginty", "author_id": 110715, "author_profile": "https://Stackoverflow.com/users/110715", "pm_score": 1, "selected": false, "text": "System.DirectoryServices" }, { "answer_id": 51161965, "author": "user2515235", "author_id": 2515235, "author_profile": "https://Stackoverflow.com/users/2515235", "pm_score": 0, "selected": false, "text": "Private Function GetUUID() As String\n Dim GetDiskUUID As String = \"get-wmiobject Win32_ComputerSystemProduct | Select-Object -ExpandProperty UUID\"\n Dim X As String = \"\"\n Dim oProcess As New Process()\n Dim oStartInfo As New ProcessStartInfo(\"powershell.exe\", GetDiskUUID)\n oStartInfo.UseShellExecute = False\n oStartInfo.RedirectStandardInput = True\n oStartInfo.RedirectStandardOutput = True\n oStartInfo.CreateNoWindow = True\n oProcess.StartInfo = oStartInfo\n oProcess.Start()\n oProcess.WaitForExit()\n X = oProcess.StandardOutput.ReadToEnd\n Return X.Trim()\nEnd Function\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99880", "https://Stackoverflow.com", "https://Stackoverflow.com/users/618/" ]
99,907
<ol> <li>In the application we have something about 30 types of objects that are created repeatedly. </li> <li>Some of them have long life (hours) some have short (milliseconds). </li> <li>Objects could be created in one thread and destroyed in another.</li> </ol> <p>Does anybody have any clue what could be good pooling technique in the sense of minimal creation/destruction latency, low lock contention and reasonable memory utilization?</p> <p>Append 1.</p> <p>1.1. Object pool/memory allocations for one type usually is not related to another type (see 1.3 for an exception)</p> <p>1.2. Memory allocation is performed for only one type (class) at time, usually for several objects at time. </p> <p>1.3. If a type aggregates another type using pointer (for some reason) these types allocated together in the one continuous piece of memory.</p> <p>Append 2.</p> <p>2.1. Using a collection with access serialization per type is known to be worse than new/delete.</p> <p>2.2. Application is used on different platforms/compilers and cannot use compiler/platform specific tricks.</p> <p>Append 3.</p> <p>It becomes obvious that the fastest (with lowest latency) implementation should organize object pooling as star-like factories network. Where the central factory is global for other thread specific factories. Regular object provision/recycling is more effective to do in a thread specific factory while the central factory could be used for object balancing between threads. </p> <p>3.1. What is the most effective way to organize communications between the central factory and thread specific factories? </p>
[ { "answer_id": 100204, "author": "Mladen Janković", "author_id": 6300, "author_profile": "https://Stackoverflow.com/users/6300", "pm_score": 0, "selected": false, "text": "Object* ObjectPool::AcquireObject()\n{\n Object* object = 0;\n lock( _stackLock );\n if( _stackIndex )\n object = _stack[ --_stackIndex ];\n unlock( _stackLock );\n if( !object )\n object = HardInit();\n SoftInit( object );\n}\n\nvoid ObjectPool::ReleaseObject(Object* object)\n{\n SoftCleanup( object );\n lock( _stackLock );\n if( _stackIndex < _maxSize )\n {\n object = _stack[ _stackIndex++ ];\n unlock( _stackLock );\n }\n else\n {\n unlock( _stack );\n HardCleanup( object );\n }\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99907", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18547/" ]
99,912
<p>I am trying to use directory services to add a directory entry to an openldap server. The examples I have seen look pretty simple, but I keep getting the error "There is an naming violation". What does this message mean? How do I resolve it?</p> <p>I have included the code, ldif file used to create the person container.</p> <pre><code>Public Function Ldap_Store_Manual_Registration(ByVal userName As String, ByVal firstMiddleName As String, ByVal lastName As String, ByVal password As String) Dim entry As DirectoryEntry = OpenLDAPconnection() 'OpenLDAPconnection() is DirectoryEntry(domainName, userId, password, AuthenticationTypes.SecureSocketsLayer) ) Dim newUser As DirectoryEntry newUser = entry.Children.Add("ou=alumni", "organizationalUnit") 'also try with newUser = entry.Children.Add("ou=alumni,o=xxxx", "organizationalUnit") , also not working SetADProperty(newUser, "objectClass", "organizationalPerson") SetADProperty(newUser, "objectClass", "person") SetADProperty(newUser, "cn", userName) SetADProperty(newUser, "sn", userName) newUser.CommitChanges() End Function Public Shared Sub SetADProperty(ByVal de As DirectoryEntry, _ ByVal pName As String, ByVal pValue As String) 'First make sure the property value isnt "nothing" If Not pValue Is Nothing Then 'Check to see if the DirectoryEntry contains this property already If de.Properties.Contains(pName) Then 'The DE contains this property 'Update the properties value de.Properties(pName)(0) = pValue Else 'Property doesnt exist 'Add the property and set it's value de.Properties(pName).Add(pValue) End If End If End Sub </code></pre> <p>The ldif file:</p> <pre><code>version: 1 dn: cn=test3,ou=alumni,o=unimelb objectClass: organizationalPerson objectClass: person objectClass: top cn: test3 sn: test3 </code></pre>
[ { "answer_id": 104942, "author": "Michael", "author_id": 13379, "author_profile": "https://Stackoverflow.com/users/13379", "pm_score": 1, "selected": false, "text": "SetADProperty(newUser, \"objectClass\", \"top\")\n organizationalPerson person" }, { "answer_id": 1195895, "author": "mellamokb", "author_id": 116614, "author_profile": "https://Stackoverflow.com/users/116614", "pm_score": 0, "selected": false, "text": "Dim entry As New DirectoryEntry(\"LDAP://ou=alumni\", etc.)\nnewUser = entry.Children.Add(\"cn=\" + userName, \"user\")\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99912", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
99,917
<p>So I was reading these Asp.Net <a href="http://www.hanselman.com/blog/ASPNETInterviewQuestions.aspx" rel="nofollow noreferrer">interview questions</a> at Scott Hanselman's blog and I came across this question. Can anyone shed some light of what he's talking about.</p>
[ { "answer_id": 100102, "author": "WebDude", "author_id": 15360, "author_profile": "https://Stackoverflow.com/users/15360", "pm_score": 0, "selected": false, "text": "ClientScript System.Web.UI.Page GetPostBackEventReference __doPostBack" }, { "answer_id": 100431, "author": "sontek", "author_id": 17176, "author_profile": "https://Stackoverflow.com/users/17176", "pm_score": 1, "selected": false, "text": "protected string GetPostBack()\n{\n return ClientScript.GetPostBackEventReference(this, null);\n}\n <a href=\"javascript:<%=GetPostBack() %>\">Click here to postback</a>\n" }, { "answer_id": 100577, "author": "Martin", "author_id": 18660, "author_profile": "https://Stackoverflow.com/users/18660", "pm_score": 2, "selected": false, "text": "<asp:LinkButton ID=\"lbEdit\" CssClass=\"button\" \n OnClientClick=\"javascript:alert('do something')\" \n onclick=\"OnEdit\" runat=\"server\">Edit</asp:LinkButton>\n OnClientClick" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99917", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1688440/" ]
99,927
<p>Can someone provide an explanation of variable scope in JS as it applies to objects, functions and closures? </p>
[ { "answer_id": 101089, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 6, "selected": true, "text": "var x = 1;\n window.x = 1;\n function fn()\n{\n var x = 1;\n}\n fn x fn function fnSequence()\n{\n var x = 1;\n return function() { return x++; }\n}\n\nvar fn1 = fnSequence();\nvar fn2 = fnSequence();\n\nWScript.Echo(fn1())\nWScript.Echo(fn2())\nWScript.Echo(fn1())\nWScript.Echo(fn2())\nWScript.Echo(fn1())\nWScript.Echo(fn1())\nWScript.Echo(fn2())\nWScript.Echo(fn2())\n WScript.Echo fnSequence x x x fnSequence fn1 fn1 x closure fn2 fn2 fnSequence fn1 x x x x fnSequence x fn2 x fn2 fn1 fn2" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/99927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/56663/" ]
100,003
<p>What are metaclasses? What are they used for?</p>
[ { "answer_id": 100037, "author": "Jerub", "author_id": 14648, "author_profile": "https://Stackoverflow.com/users/14648", "pm_score": 9, "selected": false, "text": "class type(object)\n | type(object) -> the object's type\n | type(name, bases, dict) -> a new type\n class ThisIsTheName(Bases, Are, Here):\n All_the_code_here\n def doesIs(create, a):\n dict\n def test_metaclass(name, bases, dict):\n print 'The Class Name is', name\n print 'The Class Bases are', bases\n print 'The dict has', len(dict), 'elems, the keys are', dict.keys()\n\n return \"yellow\"\n\nclass TestName(object, None, int, 1):\n __metaclass__ = test_metaclass\n foo = 1\n def baz(self, arr):\n pass\n\nprint 'TestName = ', repr(TestName)\n\n# output => \nThe Class Name is TestName\nThe Class Bases are (<type 'object'>, None, <type 'int'>, 1)\nThe dict has 4 elems, the keys are ['baz', '__module__', 'foo', '__metaclass__']\nTestName = 'yellow'\n def init_attributes(name, bases, dict):\n if 'attributes' in dict:\n for attr in dict['attributes']:\n dict[attr] = None\n\n return type(name, bases, dict)\n\nclass Initialised(object):\n __metaclass__ = init_attributes\n attributes = ['foo', 'bar', 'baz']\n\nprint 'foo =>', Initialised.foo\n# output=>\nfoo => None\n Initialised init_attributes Initialised class MetaSingleton(type):\n instance = None\n def __call__(cls, *args, **kw):\n if cls.instance is None:\n cls.instance = super(MetaSingleton, cls).__call__(*args, **kw)\n return cls.instance\n\nclass Foo(object):\n __metaclass__ = MetaSingleton\n\na = Foo()\nb = Foo()\nassert a is b\n" }, { "answer_id": 100091, "author": "Antti Rasinen", "author_id": 8570, "author_profile": "https://Stackoverflow.com/users/8570", "pm_score": 8, "selected": false, "text": "class Person(models.Model):\n first_name = models.CharField(max_length=30)\n last_name = models.CharField(max_length=30)\n" }, { "answer_id": 100146, "author": "Thomas Wouters", "author_id": 17624, "author_profile": "https://Stackoverflow.com/users/17624", "pm_score": 13, "selected": true, "text": "type type type type __init__ __new__ class class __metaclass__ __metaclass__ type.__subclasses__() type __add__ __iter__ __getattr__ def make_hook(f):\n \"\"\"Decorator to turn 'foo' method into '__foo__'\"\"\"\n f.is_hook = 1\n return f\n\nclass MyType(type):\n def __new__(mcls, name, bases, attrs):\n\n if name.startswith('None'):\n return None\n\n # Go over attributes and see if they should be renamed.\n newattrs = {}\n for attrname, attrvalue in attrs.iteritems():\n if getattr(attrvalue, 'is_hook', 0):\n newattrs['__%s__' % attrname] = attrvalue\n else:\n newattrs[attrname] = attrvalue\n\n return super(MyType, mcls).__new__(mcls, name, bases, newattrs)\n\n def __init__(self, name, bases, attrs):\n super(MyType, self).__init__(name, bases, attrs)\n\n # classregistry.register(self, self.interfaces)\n print \"Would register class %s now.\" % self\n\n def __add__(self, other):\n class AutoClass(self, other):\n pass\n return AutoClass\n # Alternatively, to autogenerate the classname as well as the class:\n # return type(self.__name__ + other.__name__, (self, other), {})\n\n def unregister(self):\n # classregistry.unregister(self)\n print \"Would unregister class %s now.\" % self\n\nclass MyObject:\n __metaclass__ = MyType\n\n\nclass NoneSample(MyObject):\n pass\n\n# Will print \"NoneType None\"\nprint type(NoneSample), repr(NoneSample)\n\nclass Example(MyObject):\n def __init__(self, value):\n self.value = value\n @make_hook\n def add(self, other):\n return self.__class__(self.value + other.value)\n\n# Will unregister the class\nExample.unregister()\n\ninst = Example(10)\n# Will fail with an AttributeError\n#inst.unregister()\n\nprint inst + inst\nclass Sibling(MyObject):\n pass\n\nExampleSibling = Example + Sibling\n# ExampleSibling is now a subclass of both Example and Sibling (with no\n# content of its own) although it will believe it's called 'AutoClass'\nprint ExampleSibling\nprint ExampleSibling.__mro__\n" }, { "answer_id": 6428779, "author": "kindall", "author_id": 416467, "author_profile": "https://Stackoverflow.com/users/416467", "pm_score": 8, "selected": false, "text": "class MyMeta(type):\n\n counter = 0\n\n def __init__(cls, name, bases, dic):\n type.__init__(cls, name, bases, dic)\n cls._order = MyMeta.counter\n MyMeta.counter += 1\n\nclass MyType(object): # Python 2\n __metaclass__ = MyMeta\n\nclass MyType(metaclass=MyMeta): # Python 3\n pass\n MyType _order" }, { "answer_id": 6581949, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 13, "selected": false, "text": ">>> class ObjectCreator(object):\n... pass\n...\n\n>>> my_object = ObjectCreator()\n>>> print(my_object)\n<__main__.ObjectCreator object at 0x8974f2c>\n class >>> class ObjectCreator(object):\n... pass\n...\n ObjectCreator >>> print(ObjectCreator) # you can print a class because it's an object\n<class '__main__.ObjectCreator'>\n>>> def echo(o):\n... print(o)\n...\n>>> echo(ObjectCreator) # you can pass a class as a parameter\n<class '__main__.ObjectCreator'>\n>>> print(hasattr(ObjectCreator, 'new_attribute'))\nFalse\n>>> ObjectCreator.new_attribute = 'foo' # you can add attributes to a class\n>>> print(hasattr(ObjectCreator, 'new_attribute'))\nTrue\n>>> print(ObjectCreator.new_attribute)\nfoo\n>>> ObjectCreatorMirror = ObjectCreator # you can assign a class to a variable\n>>> print(ObjectCreatorMirror.new_attribute)\nfoo\n>>> print(ObjectCreatorMirror())\n<__main__.ObjectCreator object at 0x8997b4c>\n class >>> def choose_class(name):\n... if name == 'foo':\n... class Foo(object):\n... pass\n... return Foo # return the class, not an instance\n... else:\n... class Bar(object):\n... pass\n... return Bar\n...\n>>> MyClass = choose_class('foo')\n>>> print(MyClass) # the function returns a class, not an instance\n<class '__main__.Foo'>\n>>> print(MyClass()) # you can create an object from this class\n<__main__.Foo object at 0x89c6d4c>\n class type >>> print(type(1))\n<type 'int'>\n>>> print(type(\"1\"))\n<type 'str'>\n>>> print(type(ObjectCreator))\n<type 'type'>\n>>> print(type(ObjectCreator()))\n<class '__main__.ObjectCreator'>\n type type type type(name, bases, attrs)\n name bases attrs >>> class MyShinyClass(object):\n... pass\n >>> MyShinyClass = type('MyShinyClass', (), {}) # returns a class object\n>>> print(MyShinyClass)\n<class '__main__.MyShinyClass'>\n>>> print(MyShinyClass()) # create an instance with the class\n<__main__.MyShinyClass object at 0x8997cec>\n MyShinyClass type >>> class Foo(object):\n... bar = True\n >>> Foo = type('Foo', (), {'bar':True})\n >>> print(Foo)\n<class '__main__.Foo'>\n>>> print(Foo.bar)\nTrue\n>>> f = Foo()\n>>> print(f)\n<__main__.Foo object at 0x8a9b84c>\n>>> print(f.bar)\nTrue\n >>> class FooChild(Foo):\n... pass\n >>> FooChild = type('FooChild', (Foo,), {})\n>>> print(FooChild)\n<class '__main__.FooChild'>\n>>> print(FooChild.bar) # bar is inherited from Foo\nTrue\n >>> def echo_bar(self):\n... print(self.bar)\n...\n>>> FooChild = type('FooChild', (Foo,), {'echo_bar': echo_bar})\n>>> hasattr(Foo, 'echo_bar')\nFalse\n>>> hasattr(FooChild, 'echo_bar')\nTrue\n>>> my_foo = FooChild()\n>>> my_foo.echo_bar()\nTrue\n >>> def echo_bar_more(self):\n... print('yet another method')\n...\n>>> FooChild.echo_bar_more = echo_bar_more\n>>> hasattr(FooChild, 'echo_bar_more')\nTrue\n class MyClass = MetaClass()\nmy_object = MyClass()\n type MyClass = type('MyClass', (), {})\n type type Type str int type __class__ >>> age = 35\n>>> age.__class__\n<type 'int'>\n>>> name = 'bob'\n>>> name.__class__\n<type 'str'>\n>>> def foo(): pass\n>>> foo.__class__\n<type 'function'>\n>>> class Bar(object): pass\n>>> b = Bar()\n>>> b.__class__\n<class '__main__.Bar'>\n __class__ __class__ >>> age.__class__.__class__\n<type 'type'>\n>>> name.__class__.__class__\n<type 'type'>\n>>> foo.__class__.__class__\n<type 'type'>\n>>> b.__class__.__class__\n<type 'type'>\n type __metaclass__ __metaclass__ class Foo(object):\n __metaclass__ = something...\n [...]\n Foo class Foo(object) Foo __metaclass__ Foo type class Foo(Bar):\n pass\n __metaclass__ Foo Foo __metaclass__ __metaclass__ __metaclass__ __metaclass__ Bar type __metaclass__ Bar.__class__ Bar __metaclass__ Bar type() type.__new__() __metaclass__ type class Foo(object, metaclass=something):\n ...\n __metaclass__ class Foo(object, metaclass=something, kwarg1=value1, kwarg2=value2):\n ...\n __metaclass__ __metaclass__ # the metaclass will automatically get passed the same argument\n# that you usually pass to `type`\ndef upper_attr(future_class_name, future_class_parents, future_class_attrs):\n \"\"\"\n Return a class object, with the list of its attribute turned\n into uppercase.\n \"\"\"\n # pick up any attribute that doesn't start with '__' and uppercase it\n uppercase_attrs = {\n attr if attr.startswith(\"__\") else attr.upper(): v\n for attr, v in future_class_attrs.items()\n }\n\n # let `type` do the class creation\n return type(future_class_name, future_class_parents, uppercase_attrs)\n\n__metaclass__ = upper_attr # this will affect all classes in the module\n\nclass Foo(): # global __metaclass__ won't work with \"object\" though\n # but we can define __metaclass__ here instead to affect only this class\n # and this will work with \"object\" children\n bar = 'bip'\n >>> hasattr(Foo, 'bar')\nFalse\n>>> hasattr(Foo, 'BAR')\nTrue\n>>> Foo.BAR\n'bip'\n # remember that `type` is actually a class like `str` and `int`\n# so you can inherit from it\nclass UpperAttrMetaclass(type):\n # __new__ is the method called before __init__\n # it's the method that creates the object and returns it\n # while __init__ just initializes the object passed as parameter\n # you rarely use __new__, except when you want to control how the object\n # is created.\n # here the created object is the class, and we want to customize it\n # so we override __new__\n # you can do some stuff in __init__ too if you wish\n # some advanced use involves overriding __call__ as well, but we won't\n # see this\n def __new__(upperattr_metaclass, future_class_name,\n future_class_parents, future_class_attrs):\n uppercase_attrs = {\n attr if attr.startswith(\"__\") else attr.upper(): v\n for attr, v in future_class_attrs.items()\n }\n return type(future_class_name, future_class_parents, uppercase_attrs)\n class UpperAttrMetaclass(type):\n def __new__(cls, clsname, bases, attrs):\n uppercase_attrs = {\n attr if attr.startswith(\"__\") else attr.upper(): v\n for attr, v in attrs.items()\n }\n return type(clsname, bases, uppercase_attrs)\n cls __new__ self type __new__ class UpperAttrMetaclass(type):\n def __new__(cls, clsname, bases, attrs):\n uppercase_attrs = {\n attr if attr.startswith(\"__\") else attr.upper(): v\n for attr, v in attrs.items()\n }\n return type.__new__(cls, clsname, bases, uppercase_attrs)\n super class UpperAttrMetaclass(type):\n def __new__(cls, clsname, bases, attrs):\n uppercase_attrs = {\n attr if attr.startswith(\"__\") else attr.upper(): v\n for attr, v in attrs.items()\n }\n\n # Python 2 requires passing arguments to super:\n return super(UpperAttrMetaclass, cls).__new__(\n cls, clsname, bases, uppercase_attrs)\n\n # Python 3 can use no-arg super() which infers them:\n return super().__new__(cls, clsname, bases, uppercase_attrs)\n class Foo(object, metaclass=MyMetaclass, kwarg1=value1):\n ...\n class MyMetaclass(type):\n def __new__(cls, clsname, bases, dct, kwargs1=default):\n ...\n __dict__ __metaclass__ UpperAttrMetaclass(type) __new__ __init__ __call__ __new__ __init__ class Person(models.Model):\n name = models.CharField(max_length=30)\n age = models.IntegerField()\n person = Person(name='bob', age='35')\nprint(person.age)\n IntegerField int models.Model __metaclass__ Person >>> class Foo(object): pass\n>>> id(Foo)\n142630324\n type type" }, { "answer_id": 21999253, "author": "Craig", "author_id": 1489354, "author_profile": "https://Stackoverflow.com/users/1489354", "pm_score": 6, "selected": false, "text": "metaclass metaclass metaclass #!/usr/bin/env python\n\n# Copyright (C) 2013-2014 Craig Phillips. All rights reserved.\n\n# This requires some explaining. The point of this metaclass excercise is to\n# create a static abstract class that is in one way or another, dormant until\n# queried. I experimented with creating a singlton on import, but that did\n# not quite behave how I wanted it to. See now here, we are creating a class\n# called GsyncOptions, that on import, will do nothing except state that its\n# class creator is GsyncOptionsType. This means, docopt doesn't parse any\n# of the help document, nor does it start processing command line options.\n# So importing this module becomes really efficient. The complicated bit\n# comes from requiring the GsyncOptions class to be static. By that, I mean\n# any property on it, may or may not exist, since they are not statically\n# defined; so I can't simply just define the class with a whole bunch of\n# properties that are @property @staticmethods.\n#\n# So here's how it works:\n#\n# Executing 'from libgsync.options import GsyncOptions' does nothing more\n# than load up this module, define the Type and the Class and import them\n# into the callers namespace. Simple.\n#\n# Invoking 'GsyncOptions.debug' for the first time, or any other property\n# causes the __metaclass__ __getattr__ method to be called, since the class\n# is not instantiated as a class instance yet. The __getattr__ method on\n# the type then initialises the class (GsyncOptions) via the __initialiseClass\n# method. This is the first and only time the class will actually have its\n# dictionary statically populated. The docopt module is invoked to parse the\n# usage document and generate command line options from it. These are then\n# paired with their defaults and what's in sys.argv. After all that, we\n# setup some dynamic properties that could not be defined by their name in\n# the usage, before everything is then transplanted onto the actual class\n# object (or static class GsyncOptions).\n#\n# Another piece of magic, is to allow command line options to be set in\n# in their native form and be translated into argparse style properties.\n#\n# Finally, the GsyncListOptions class is actually where the options are\n# stored. This only acts as a mechanism for storing options as lists, to\n# allow aggregation of duplicate options or options that can be specified\n# multiple times. The __getattr__ call hides this by default, returning the\n# last item in a property's list. However, if the entire list is required,\n# calling the 'list()' method on the GsyncOptions class, returns a reference\n# to the GsyncListOptions class, which contains all of the same properties\n# but as lists and without the duplication of having them as both lists and\n# static singlton values.\n#\n# So this actually means that GsyncOptions is actually a static proxy class...\n#\n# ...And all this is neatly hidden within a closure for safe keeping.\ndef GetGsyncOptionsType():\n class GsyncListOptions(object):\n __initialised = False\n\n class GsyncOptionsType(type):\n def __initialiseClass(cls):\n if GsyncListOptions._GsyncListOptions__initialised: return\n\n from docopt import docopt\n from libgsync.options import doc\n from libgsync import __version__\n\n options = docopt(\n doc.__doc__ % __version__,\n version = __version__,\n options_first = True\n )\n\n paths = options.pop('<path>', None)\n setattr(cls, \"destination_path\", paths.pop() if paths else None)\n setattr(cls, \"source_paths\", paths)\n setattr(cls, \"options\", options)\n\n for k, v in options.iteritems():\n setattr(cls, k, v)\n\n GsyncListOptions._GsyncListOptions__initialised = True\n\n def list(cls):\n return GsyncListOptions\n\n def __getattr__(cls, name):\n cls.__initialiseClass()\n return getattr(GsyncListOptions, name)[-1]\n\n def __setattr__(cls, name, value):\n # Substitut option names: --an-option-name for an_option_name\n import re\n name = re.sub(r'^__', \"\", re.sub(r'-', \"_\", name))\n listvalue = []\n\n # Ensure value is converted to a list type for GsyncListOptions\n if isinstance(value, list):\n if value:\n listvalue = [] + value\n else:\n listvalue = [ None ]\n else:\n listvalue = [ value ]\n\n type.__setattr__(GsyncListOptions, name, listvalue)\n\n # Cleanup this module to prevent tinkering.\n import sys\n module = sys.modules[__name__]\n del module.__dict__['GetGsyncOptionsType']\n\n return GsyncOptionsType\n\n# Our singlton abstract proxy class.\nclass GsyncOptions(object):\n __metaclass__ = GetGsyncOptionsType()\n" }, { "answer_id": 31930795, "author": "Russia Must Remove Putin", "author_id": 541136, "author_profile": "https://Stackoverflow.com/users/541136", "pm_score": 7, "selected": false, "text": ">>> Class(...)\ninstance\n Class >>> Metaclass(...)\nClass\n type >>> type('Foo', (object,), {}) # requires a name, bases, and a namespace\n<class '__main__.Foo'>\n >>> object() # instantiation of class\n<object object at 0x7f9069b4e0b0> # instance\n type >>> type('Object', (object,), {}) # instantiation of metaclass\n<class '__main__.Object'> # instance\n >>> isinstance(object, type)\nTrue\n >>> type(object) == type\nTrue\n>>> object.__class__\n<class 'type'>\n class Foo(object): \n 'demo'\n >>> Foo\n<class '__main__.Foo'>\n>>> isinstance(Foo, type), isinstance(Foo, object)\n(True, True)\n type name = 'Foo'\nbases = (object,)\nnamespace = {'__doc__': 'demo'}\nFoo = type(name, bases, namespace)\n __dict__ >>> Foo.__dict__\ndict_proxy({'__dict__': <attribute '__dict__' of 'Foo' objects>, \n'__module__': '__main__', '__weakref__': <attribute '__weakref__' \nof 'Foo' objects>, '__doc__': 'demo'})\n type __dict__ __module__ __dict__ __weakref__ __slots__ __slots__ __dict__ __weakref__ >>> Baz = type('Bar', (object,), {'__doc__': 'demo', '__slots__': ()})\n>>> Baz.__dict__\nmappingproxy({'__doc__': 'demo', '__slots__': (), '__module__': '__main__'})\n type __repr__ >>> Foo\n<class '__main__.Foo'>\n __repr__ help(repr) __repr__ obj == eval(repr(obj)) __repr__ __eq__ __repr__ class Type(type):\n def __repr__(cls):\n \"\"\"\n >>> Baz\n Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})\n >>> eval(repr(Baz))\n Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})\n \"\"\"\n metaname = type(cls).__name__\n name = cls.__name__\n parents = ', '.join(b.__name__ for b in cls.__bases__)\n if parents:\n parents += ','\n namespace = ', '.join(': '.join(\n (repr(k), repr(v) if not isinstance(v, type) else v.__name__))\n for k, v in cls.__dict__.items())\n return '{0}(\\'{1}\\', ({2}), {{{3}}})'.format(metaname, name, parents, namespace)\n def __eq__(cls, other):\n \"\"\"\n >>> Baz == eval(repr(Baz))\n True \n \"\"\"\n return (cls.__name__, cls.__bases__, cls.__dict__) == (\n other.__name__, other.__bases__, other.__dict__)\n __repr__ >>> class Bar(object): pass\n>>> Baz = Type('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})\n>>> Baz\nType('Baz', (Foo, Bar,), {'__module__': '__main__', '__doc__': None})\n __repr__ eval(repr(Class)) __repr__ __prepare__ __prepare__ from collections import OrderedDict\n\nclass OrderedType(Type):\n @classmethod\n def __prepare__(metacls, name, bases, **kwargs):\n return OrderedDict()\n def __new__(cls, name, bases, namespace, **kwargs):\n result = Type.__new__(cls, name, bases, dict(namespace))\n result.members = tuple(namespace)\n return result\n class OrderedMethodsObject(object, metaclass=OrderedType):\n def method1(self): pass\n def method2(self): pass\n def method3(self): pass\n def method4(self): pass\n >>> OrderedMethodsObject.members\n('__module__', '__qualname__', 'method1', 'method2', 'method3', 'method4')\n >>> inspect.getmro(OrderedType)\n(<class '__main__.OrderedType'>, <class '__main__.Type'>, <class 'type'>, <class 'object'>)\n repr >>> OrderedMethodsObject\nOrderedType('OrderedMethodsObject', (object,), {'method1': <function OrderedMethodsObject.method1 at 0x0000000002DB01E0>, 'members': ('__module__', '__qualname__', 'method1', 'method2', 'method3', 'method4'), 'method3': <function OrderedMet\nhodsObject.method3 at 0x0000000002DB02F0>, 'method2': <function OrderedMethodsObject.method2 at 0x0000000002DB0268>, '__module__': '__main__', '__weakref__': <attribute '__weakref__' of 'OrderedMethodsObject' objects>, '__doc__': None, '__d\nict__': <attribute '__dict__' of 'OrderedMethodsObject' objects>, 'method4': <function OrderedMethodsObject.method4 at 0x0000000002DB0378>})\n" }, { "answer_id": 35732111, "author": "Ethan Furman", "author_id": 208880, "author_profile": "https://Stackoverflow.com/users/208880", "pm_score": 7, "selected": false, "text": "__prepare__ __new__ __prepare__ OrderedDict __prepare__ dict __new__ class Meta(type):\n\n def __prepare__(metaclass, cls, bases):\n return dict()\n\n def __new__(metacls, cls, bases, clsdict):\n return super().__new__(metacls, cls, bases, clsdict)\n int str class Person:\n weight = ValidateType('weight', int)\n age = ValidateType('age', int)\n name = ValidateType('name', str)\n class Person(metaclass=Validator):\n weight = ValidateType(int)\n age = ValidateType(int)\n name = ValidateType(str)\n __prepare__ class Validator(type):\n def __new__(metacls, cls, bases, clsdict):\n # search clsdict looking for ValidateType descriptors\n for name, attr in clsdict.items():\n if isinstance(attr, ValidateType):\n attr.name = name\n attr.attr = '_' + name\n # create final class and return it\n return super().__new__(metacls, cls, bases, clsdict)\n p = Person()\np.weight = 9\nprint(p.weight)\np.weight = '9'\n 9\nTraceback (most recent call last):\n File \"simple_meta.py\", line 36, in <module>\n p.weight = '9'\n File \"simple_meta.py\", line 24, in __set__\n (self.name, self.type, value))\nTypeError: weight must be of type(s) <class 'int'> (got '9')\n class ValidateType:\n def __init__(self, type):\n self.name = None # will be set by metaclass\n self.attr = None # will be set by metaclass\n self.type = type\n def __get__(self, inst, cls):\n if inst is None:\n return self\n else:\n return inst.__dict__[self.attr]\n def __set__(self, inst, value):\n if not isinstance(value, self.type):\n raise TypeError('%s must be of type(s) %s (got %r)' %\n (self.name, self.type, value))\n else:\n inst.__dict__[self.attr] = value\n" }, { "answer_id": 38858285, "author": "Mushahid Khan", "author_id": 4636600, "author_profile": "https://Stackoverflow.com/users/4636600", "pm_score": 6, "selected": false, "text": "type metaclass metaclass type metaclass new >>> class MetaClass(type):\n... def __init__(cls, name, bases, attrs):\n... print ('class name: %s' %name )\n... print ('Defining class %s' %cls)\n... print('Bases %s: ' %bases)\n... print('Attributes')\n... for (name, value) in attrs.items():\n... print ('%s :%r' %(name, value))\n... \n\n>>> class NewClass(object, metaclass=MetaClass):\n... get_choch='dairy'\n... \nclass name: NewClass\nBases <class 'object'>: \nDefining class <class 'NewClass'>\nget_choch :'dairy'\n__module__ :'builtins'\n__qualname__ :'NewClass'\n Note: metaclass" }, { "answer_id": 40017019, "author": "Michael Ekoka", "author_id": 56974, "author_profile": "https://Stackoverflow.com/users/56974", "pm_score": 7, "selected": false, "text": "__call__() # define a class\nclass SomeClass(object):\n # ...\n # some definition here ...\n # ...\n\n# create an instance of it\ninstance = SomeClass()\n\n# then call the object as if it's a function\nresult = instance('foo', 'bar')\n __call__() class SomeClass(object):\n # ...\n # some definition here ...\n # ...\n\n def __call__(self, foo, bar):\n return bar + foo\n __call__() __call__() instance = SomeClass() __init__() __init__() __new__() __new__() __call__() class Meta_1(type):\n def __call__(cls):\n print \"Meta_1.__call__() before creating an instance of \", cls\n instance = super(Meta_1, cls).__call__()\n print \"Meta_1.__call__() about to return instance.\"\n return instance\n class Class_1(object):\n\n __metaclass__ = Meta_1\n\n def __new__(cls):\n print \"Class_1.__new__() before creating an instance.\"\n instance = super(Class_1, cls).__new__(cls)\n print \"Class_1.__new__() about to return instance.\"\n return instance\n\n def __init__(self):\n print \"entering Class_1.__init__() for instance initialization.\"\n super(Class_1,self).__init__()\n print \"exiting Class_1.__init__().\"\n Class_1 instance = Class_1()\n# Meta_1.__call__() before creating an instance of <class '__main__.Class_1'>.\n# Class_1.__new__() before creating an instance.\n# Class_1.__new__() about to return instance.\n# entering Class_1.__init__() for instance initialization.\n# exiting Class_1.__init__().\n# Meta_1.__call__() about to return instance.\n type Meta_1 type type.__call__() class type:\n def __call__(cls, *args, **kwarg):\n\n # ... maybe a few things done to cls here\n\n # then we call __new__() on the class to create an instance\n instance = cls.__new__(cls, *args, **kwargs)\n\n # ... maybe a few things done to the instance here\n\n # then we initialize the instance with its __init__() method\n instance.__init__(*args, **kwargs)\n\n # ... maybe a few more things done to instance here\n\n # then we return it\n return instance\n __call__() __new__() __init__() __call__() Class_1.__new__() Class_1.__init__() class Meta_2(type):\n singletons = {}\n\n def __call__(cls, *args, **kwargs):\n if cls in Meta_2.singletons:\n # we return the only instance and skip a call to __new__()\n # and __init__()\n print (\"{} singleton returning from Meta_2.__call__(), \"\n \"skipping creation of new instance.\".format(cls))\n return Meta_2.singletons[cls]\n\n # else if the singleton isn't present we proceed as usual\n print \"Meta_2.__call__() before creating an instance.\"\n instance = super(Meta_2, cls).__call__(*args, **kwargs)\n Meta_2.singletons[cls] = instance\n print \"Meta_2.__call__() returning new instance.\"\n return instance\n\nclass Class_2(object):\n\n __metaclass__ = Meta_2\n\n def __new__(cls, *args, **kwargs):\n print \"Class_2.__new__() before creating instance.\"\n instance = super(Class_2, cls).__new__(cls)\n print \"Class_2.__new__() returning instance.\"\n return instance\n\n def __init__(self, *args, **kwargs):\n print \"entering Class_2.__init__() for initialization.\"\n super(Class_2, self).__init__()\n print \"exiting Class_2.__init__().\"\n Class_2 a = Class_2()\n# Meta_2.__call__() before creating an instance.\n# Class_2.__new__() before creating instance.\n# Class_2.__new__() returning instance.\n# entering Class_2.__init__() for initialization.\n# exiting Class_2.__init__().\n# Meta_2.__call__() returning new instance.\n\nb = Class_2()\n# <class '__main__.Class_2'> singleton returning from Meta_2.__call__(), skipping creation of new instance.\n\nc = Class_2()\n# <class '__main__.Class_2'> singleton returning from Meta_2.__call__(), skipping creation of new instance.\n\na is b is c # True\n" }, { "answer_id": 41338238, "author": "noɥʇʎԀʎzɐɹƆ", "author_id": 1459669, "author_profile": "https://Stackoverflow.com/users/1459669", "pm_score": 6, "selected": false, "text": "type(obj) type() class Foo(object):\n __metaclass__ = MyMetaClass\n type" }, { "answer_id": 45074712, "author": "Xingzhou Liu", "author_id": 8056974, "author_profile": "https://Stackoverflow.com/users/8056974", "pm_score": 5, "selected": false, "text": "class foo:\n ...\n class somemeta(type):\n __new__(mcs, name, bases, clsdict):\n \"\"\"\n mcs: is the base metaclass, in this case type.\n name: name of the new class, as provided by the user.\n bases: tuple of base classes \n clsdict: a dictionary containing all methods and attributes defined on class\n\n you must return a class object by invoking the __new__ constructor on the base metaclass. \n ie: \n return type.__call__(mcs, name, bases, clsdict).\n\n in the following case:\n\n class foo(baseclass):\n __metaclass__ = somemeta\n\n an_attr = 12\n\n def bar(self):\n ...\n\n @classmethod\n def foo(cls):\n ...\n\n arguments would be : ( somemeta, \"foo\", (baseclass, baseofbase,..., object), {\"an_attr\":12, \"bar\": <function>, \"foo\": <bound class method>}\n\n you can modify any of these values before passing on to type\n \"\"\"\n return type.__call__(mcs, name, bases, clsdict)\n\n\n def __init__(self, name, bases, clsdict):\n \"\"\" \n called after type has been created. unlike in standard classes, __init__ method cannot modify the instance (cls) - and should be used for class validaton.\n \"\"\"\n pass\n\n\n def __prepare__():\n \"\"\"\n returns a dict or something that can be used as a namespace.\n the type will then attach methods and attributes from class definition to it.\n\n call order :\n\n somemeta.__new__ -> type.__new__ -> type.__init__ -> somemeta.__init__ \n \"\"\"\n return dict()\n\n def mymethod(cls):\n \"\"\" works like a classmethod, but for class objects. Also, my method will not be visible to instances of cls.\n \"\"\"\n pass\n" }, { "answer_id": 48222963, "author": "binbjz", "author_id": 5064780, "author_profile": "https://Stackoverflow.com/users/5064780", "pm_score": 5, "selected": false, "text": "def func(self, name='mike'):\n print('Hi, %s.' % name)\n\nHi = type('Hi', (object,), dict(hi=func))\nh = Hi()\nh.hi()\nHi, mike.\n\ntype(Hi)\ntype\n\ntype(h)\n__main__.Hi\n class ListMetaclass(type):\n def __new__(cls, name, bases, attrs):\n attrs['add'] = lambda self, value: self.append(value)\n return type.__new__(cls, name, bases, attrs)\n\nclass CustomList(list, metaclass=ListMetaclass):\n pass\n\nlst = CustomList()\nlst.add('custom_list_1')\nlst.add('custom_list_2')\n\nlst\n['custom_list_1', 'custom_list_2']\n" }, { "answer_id": 52344780, "author": "Andy Jazz", "author_id": 6599590, "author_profile": "https://Stackoverflow.com/users/6599590", "pm_score": 5, "selected": false, "text": "metaclass class metaclass __metaclass__ metaclass class MyClass:\n __metaclass__ = type\n # write here other method\n # write here one more method\n\nprint(MyClass.__metaclass__)\n class 'type'\n metaclass metaclass metaclass class MyMetaClass(type):\n __metaclass__ = type\n # you can write here any behaviour you want\n\nclass MyTestClass:\n __metaclass__ = MyMetaClass\n\nObj = MyTestClass()\nprint(Obj.__metaclass__)\nprint(MyMetaClass.__metaclass__)\n class '__main__.MyMetaClass'\nclass 'type'\n" }, { "answer_id": 59424178, "author": "Carson", "author_id": 9935654, "author_profile": "https://Stackoverflow.com/users/9935654", "pm_score": 4, "selected": false, "text": "metaclass class MetaMemberControl(type):\n __slots__ = ()\n\n @classmethod\n def __prepare__(mcs, f_cls_name, f_cls_parents, # f_cls means: future class\n meta_args=None, meta_options=None): # meta_args and meta_options is not necessarily needed, just so you know.\n f_cls_attr = dict()\n if not \"do something or if you want to define your cool stuff of dict...\":\n return dict(make_your_special_dict=None)\n else:\n return f_cls_attr\n\n def __new__(mcs, f_cls_name, f_cls_parents, f_cls_attr,\n meta_args=None, meta_options=None):\n\n original_getattr = f_cls_attr.get('__getattribute__')\n original_setattr = f_cls_attr.get('__setattr__')\n\n def init_getattr(self, item):\n if not item.startswith('_'): # you can set break points at here\n alias_name = '_' + item\n if alias_name in f_cls_attr['__slots__']:\n item = alias_name\n if original_getattr is not None:\n return original_getattr(self, item)\n else:\n return super(eval(f_cls_name), self).__getattribute__(item)\n\n def init_setattr(self, key, value):\n if not key.startswith('_') and ('_' + key) in f_cls_attr['__slots__']:\n raise AttributeError(f\"you can't modify private members:_{key}\")\n if original_setattr is not None:\n original_setattr(self, key, value)\n else:\n super(eval(f_cls_name), self).__setattr__(key, value)\n\n f_cls_attr['__getattribute__'] = init_getattr\n f_cls_attr['__setattr__'] = init_setattr\n\n cls = super().__new__(mcs, f_cls_name, f_cls_parents, f_cls_attr)\n return cls\n\n\nclass Human(metaclass=MetaMemberControl):\n __slots__ = ('_age', '_name')\n\n def __init__(self, name, age):\n self._name = name\n self._age = age\n\n def __getattribute__(self, item):\n \"\"\"\n is just for IDE recognize.\n \"\"\"\n return super().__getattribute__(item)\n\n \"\"\" with MetaMemberControl then you don't have to write as following\n @property\n def name(self):\n return self._name\n\n @property\n def age(self):\n return self._age\n \"\"\"\n\n\ndef test_demo():\n human = Human('Carson', 27)\n # human.age = 18 # you can't modify private members:_age <-- this is defined by yourself.\n # human.k = 18 # 'Human' object has no attribute 'k' <-- system error.\n age1 = human._age # It's OK, although the IDE will show some warnings. (Access to a protected member _age of a class)\n\n age2 = human.age # It's OK! see below:\n \"\"\"\n if you do not define `__getattribute__` at the class of Human,\n the IDE will show you: Unresolved attribute reference 'age' for class 'Human'\n but it's ok on running since the MetaMemberControl will help you.\n \"\"\"\n\n\nif __name__ == '__main__':\n test_demo()\n\n metaclass" }, { "answer_id": 60504738, "author": "Lars", "author_id": 1023470, "author_profile": "https://Stackoverflow.com/users/1023470", "pm_score": 4, "selected": false, "text": "__init_subclass__(cls, **kwargs)" }, { "answer_id": 68354618, "author": "Emma Brown", "author_id": 13649935, "author_profile": "https://Stackoverflow.com/users/13649935", "pm_score": 4, "selected": false, "text": "classutilities" }, { "answer_id": 68417609, "author": "Manukumar", "author_id": 14964700, "author_profile": "https://Stackoverflow.com/users/14964700", "pm_score": 4, "selected": false, "text": "Django WTForms abstract from django.db import models\n\nclass Author(models.Model):\n name = models.CharField(max_length=50)\n email = models.EmailField()\n\n class Meta:\n abstract = True\n WTForms from wtforms.form import Form\nfrom wtforms.csrf.session import SessionCSRF\nfrom wtforms.fields import StringField\n\nclass MyBaseForm(Form):\n class Meta:\n csrf = True\n csrf_class = SessionCSRF\n\n name = StringField(\"name\")\n Meta Django WTForms WTForms self.Meta.csrf csrf" }, { "answer_id": 69426577, "author": "Delta", "author_id": 16608876, "author_profile": "https://Stackoverflow.com/users/16608876", "pm_score": 2, "selected": false, "text": "Python 3.10.0rc2 (tags/v3.10.0rc2:839d789, Sep 7 2021, 18:51:45) [MSC v.1929 64 bit (AMD64)] on win32\nType \"help\", \"copyright\", \"credits\" or \"license\" for more information.\n>>> class Object:\n... pass\n... \n>>> class Meta(type):\n... test = 'Worked!!!'\n... def __repr__(self):\n... return 'This is \"Meta\" metaclass'\n... \n>>> class ObjectWithMetaClass(metaclass=Meta):\n... pass\n... \n>>> Object or type(Object())\n<class '__main__.Object'>\n>>> ObjectWithMetaClass or type(ObjectWithMetaClass())\nThis is \"Meta\" metaclass\n>>> Object.test\nAttributeError: ...\n>>> ObjectWithMetaClass.test\n'Worked!!!'\n>>> type(Object)\n<class 'type'>\n>>> type(ObjectWithMetaClass)\n<class '__main__.Meta'>\n>>> type(type(ObjectWithMetaClass))\n<class 'type'>\n>>> Object.__bases__\n(<class 'object'>,)\n>>> ObjectWithMetaClass.__bases__\n(<class 'object'>,)\n>>> type(ObjectWithMetaClass).__bases__\n(<class 'type'>,)\n>>> Object.__mro__\n(<class '__main__.Object'>, <class 'object'>)\n>>> ObjectWithMetaClass.__mro__\n(This is \"Meta\" metaclass, <class 'object'>)\n>>> \n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100003", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9951/" ]
100,007
<p>When logging with Log4Net it's very easy to put class that called the log into the log file. I've found in the past that this makes it very easy to trace through the code and see the flow through the classes. In Log4Net I use the %logger property in the conversion pattern like so: </p> <pre><code>&lt;conversionPattern value="%date [%thread] %-5level %logger [%property{NDC}] - %message%newline" /&gt; </code></pre> <p>And this gives me the output I want: </p> <p><code>2008-09-19 15:40:26,906 [3132] ERROR &lt;b&gt;Log4NetTechDemo.Tester&lt;/b&gt; [(null)] - Failed method</code></p> <p>You can see from the output that the class that has called the log is Log4NetTechDemo.Tester, so I can trace the error back to that class quite easily.</p> <p>In the Logging Applicaton Block I cannot figure out how to do this with a simple log call. Does anyone know how it can be done? If so, an example or steps to do so would be very helpful.</p>
[ { "answer_id": 100075, "author": "Tom Carr", "author_id": 14954, "author_profile": "https://Stackoverflow.com/users/14954", "pm_score": 1, "selected": false, "text": " StackTrace trace = new StackTrace(ex, true);\n StackFrame frame = trace.GetFrame(0);\n" }, { "answer_id": 100961, "author": "lotsoffreetime", "author_id": 18248, "author_profile": "https://Stackoverflow.com/users/18248", "pm_score": 4, "selected": true, "text": "public void LogSomething(string msg)\n{\n LogEntry le = new LogEntry { Message = msg };\n le.ExtendedProperties.Add(\"Called from\", new StackFrame(1).GetMethod().ReflectedType);\n Logger.Write(le);\n}\n Extended Properties: Called from - LAB_Demo.Tester\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11908/" ]
100,038
<p>How can I make a Facebook RSS application that autoupdates from the provided RSS feeds. Of course doing this is trivial for canvas applications, but I need this for showing on the Facebook Page. All the RSS apps I've taken a look at either dont update or dont work on Facebook Pages. </p> <p>Especially now that infinite session keys are deprecated (and maybe even forbidden). </p>
[ { "answer_id": 100598, "author": "Josh", "author_id": 10902, "author_profile": "https://Stackoverflow.com/users/10902", "pm_score": 0, "selected": false, "text": "fb:ref" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100038", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18219/" ]
100,045
<p>What is a good regular expression that can validate a text string to make sure it is a valid Windows filename? (AKA not have <code>\/:*?"&lt;&gt;|</code> characters).</p> <p>I'd like to use it like the following:</p> <pre><code>// Return true if string is invalid. if (Regex.IsMatch(szFileName, "&lt;your regex string&gt;")) { // Tell user to reformat their filename. } </code></pre>
[ { "answer_id": 100066, "author": "Isak Savo", "author_id": 8521, "author_profile": "https://Stackoverflow.com/users/8521", "pm_score": 7, "selected": true, "text": "if (proposedFilename.IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)\n{\n MessageBox.Show(\"The filename is invalid\");\n return;\n}\n" }, { "answer_id": 356289, "author": "Viacheslav Ivanov", "author_id": 45003, "author_profile": "https://Stackoverflow.com/users/45003", "pm_score": 0, "selected": false, "text": "if(@\"C:\\A.txt\".IndexOfAny(System.IO.Path.GetInvalidFileNameChars()) != -1)\n{\n MessageBox.Show(\"The filename is invalid\");\n return;\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100045", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13115/" ]
100,048
<p>I have two unsorted lists and I need to produce another list which is sorted and where all the elements are unique.</p> <p>The elements can occur multiple times in both lists and they are originally unsorted.</p> <p>My function looks like this:</p> <pre><code>(defun merge-lists (list-a list-b sort-fn) "Merges two lists of (x, y) coordinates sorting them and removing dupes" (let ((prev nil)) (remove-if (lambda (point) (let ((ret-val (equal point prev))) (setf prev point) ret-val)) (sort (merge 'list list-a list-b sort-fn) ;' sort-fn)))) </code></pre> <p>Is there a better way to achieve the same?</p> <p>Sample call:</p> <pre><code>[CL]&gt; (merge-lists '(9 8 4 8 9 7 2) '(1 7 3 9 2 6) #'&gt;) ==&gt; (9 8 7 6 4 3 2 1) </code></pre>
[ { "answer_id": 100109, "author": "Antti Rasinen", "author_id": 8570, "author_profile": "https://Stackoverflow.com/users/8570", "pm_score": 5, "selected": true, "text": "(defun merge-lists (list-a list-b sort-fn test-fn)\n (sort (remove-duplicates (append list-a list-b) :test test-fn) sort-fn))\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100048", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7780/" ]
100,068
<p>I'd like to know if there's an easier way to insert a record if it doesn't already exist in a table. I'm still trying to build my LINQ to SQL skills. </p> <p>Here's what I've got, but it seems like there should be an easier way.</p> <pre><code>public static TEntity InsertIfNotExists&lt;TEntity&gt; ( DataContext db, Table&lt;TEntity&gt; table, Func&lt;TEntity,bool&gt; where, TEntity record ) where TEntity : class { TEntity existing = table.SingleOrDefault&lt;TEntity&gt;(where); if (existing != null) { return existing; } else { table.InsertOnSubmit(record); // Can't use table.Context.SubmitChanges() // 'cause it's read-only db.SubmitChanges(); } return record; } </code></pre>
[ { "answer_id": 100496, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 5, "selected": true, "text": "public static void InsertIfNotExists<TEntity>\n (this Table<TEntity> table,\n TEntity entity,\n Expression<Func<TEntity,bool>> predicate)\n where TEntity : class\n{ \n if (!table.Any(predicate)) \n {\n table.InsertOnSubmit(record);\n table.Context.SubmitChanges();\n }\n }\n\n\ntable.InsertIfNotExists(entity, e=>e.BooleanProperty);\n" }, { "answer_id": 100635, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 3, "selected": false, "text": "db.SubmitChanges() InsertIfNotExists<TEntity> InsertIfNotExists<TEntity> OnLoaded public partial class MyEntity\n{\n public bool IsLoaded { get; private set; }\n partial void OnLoaded()\n {\n IsLoaded = true;\n }\n}\n if (!record.IsLoaded)\n db.InsertOnSubmit(record);\n" }, { "answer_id": 2108466, "author": "Jamal", "author_id": 143582, "author_profile": "https://Stackoverflow.com/users/143582", "pm_score": 2, "selected": false, "text": "public static void InsertIfNotExists<TEntity>\n (this Table<TEntity> table\n , TEntity entity\n ) where TEntity : class\n {\n if (!table.Contains(entity))\n {\n table.InsertOnSubmit(entity);\n\n }\n }\n" }, { "answer_id": 4799362, "author": "Michael Kropat", "author_id": 27581, "author_profile": "https://Stackoverflow.com/users/27581", "pm_score": 4, "selected": false, "text": "if (!Any()) { InsertOnSubmit(); } SubmitChanges SqlException using (var db = new DataContext()) {\n\n // Add the new (possibly duplicate) record to the data context here.\n\n try {\n db.SubmitChanges();\n } catch (SqlException ex) {\n const int violationOfPrimaryKeyContraint = 2627;\n const int violationOfUniqueConstraint = 2601;\n var duplicateRecordExceptionNumbers = new [] {\n violationOfPrimaryKeyContraint, violationOfUniqueConstraint\n };\n if (!duplicateRecordExceptionNumbers.Contains(ex.Number)) {\n throw;\n }\n }\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11574/" ]
100,081
<p>I have the following C# singleton pattern, is there any way of improving it? </p> <pre><code> public class Singleton&lt;T&gt; where T : class, new() { private static object _syncobj = new object(); private static volatile T _instance = null; public static T Instance { get { if (_instance == null) { lock (_syncobj) { if (_instance == null) { _instance = new T(); } } } return _instance; } } public Singleton() { } } </code></pre> <p>Preferred usage example: </p> <pre><code>class Foo : Singleton&lt;Foo&gt; { } </code></pre> <p><strong>Related</strong>: </p> <p><a href="https://stackoverflow.com/questions/953259/an-obvious-singleton-implementation-for-net">An obvious singleton implementation for .NET?</a></p>
[ { "answer_id": 100093, "author": "EggyBach", "author_id": 15475, "author_profile": "https://Stackoverflow.com/users/15475", "pm_score": 3, "selected": false, "text": "// Singleton PatternJudith Bishop Nov 2007\n// Generic version\n\npublic class Singleton<T> where T : class, new()\n{\n Singleton() { }\n\n class SingletonCreator\n {\n static SingletonCreator() { }\n // Private object instantiated with private constructor\n internal static readonly T instance = new T();\n }\n\n public static T UniqueInstance\n {\n get { return SingletonCreator.instance; }\n }\n}\n" }, { "answer_id": 100098, "author": "blowdart", "author_id": 2525, "author_profile": "https://Stackoverflow.com/users/2525", "pm_score": 2, "selected": false, "text": "public sealed class Singleton\n{\n private static readonly Singleton instance = new Singleton();\n\n private Singleton(){}\n\n public static Singleton Instance\n {\n get \n {\n return instance; \n }\n }\n}\n" }, { "answer_id": 100149, "author": "Jonathan Allen", "author_id": 5274, "author_profile": "https://Stackoverflow.com/users/5274", "pm_score": -1, "selected": false, "text": "static class Foo\n" }, { "answer_id": 100159, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 3, "selected": false, "text": "class Foo\n{\n public static readonly Instance = new Foo();\n private Foo() {}\n static Foo() {}\n}\n" }, { "answer_id": 292211, "author": "Wayne Bloss", "author_id": 16387, "author_profile": "https://Stackoverflow.com/users/16387", "pm_score": 2, "selected": false, "text": "class MyConcreteClass\n{\n #region Singleton Implementation\n\n public static readonly Instance = new MyConcreteClass();\n\n private MyConcreteClass(){}\n\n #endregion\n\n /// ...\n}\n" }, { "answer_id": 869526, "author": "dr. evil", "author_id": 40322, "author_profile": "https://Stackoverflow.com/users/40322", "pm_score": 1, "selected": false, "text": "Public MustInherit Class Singleton(Of T As {Class, New})\n Public Sub New()\n End Sub\n\n Private Class SingletonCreator\n Shared Sub New()\n End Sub\n Friend Shared ReadOnly Instance As New T\n End Class\n\n Public Shared ReadOnly Property Instance() As T\n Get\n Return SingletonCreator.Instance\n End Get\n End Property\nEnd Class\n" }, { "answer_id": 929408, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "\n/// <summary>Abstract base class for thread-safe singleton objects</summary>\n/// <typeparam name=\"T\">Instance type</typeparam>\npublic abstract class SingletonOnDemand<T> {\n private static object __SYNC = new object();\n private static volatile bool _IsInstanceCreated = false;\n private static T _Instance = default(T);\n\n /// <summary>Instance data</summary>\n public static T Instance {\n get {\n if (!_IsInstanceCreated)\n lock (__SYNC)\n if (!_IsInstanceCreated)\n _Instance = Activator.CreateInstance<T>();\n return _Instance;\n }\n }\n}\n" }, { "answer_id": 929441, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "\n/// <summary>Abstract base class for thread-safe singleton objects</summary>\n/// <typeparam name=\"T\">Instance type</typeparam>\npublic abstract class SingletonOnDemand<T> {\n private static object __SYNC = new object();\n private static volatile bool _IsInstanceCreated = false;\n private static T _Instance = default(T);\n\n /// <summary>Instance data</summary>\n public static T Instance {\n get {\n if (!_IsInstanceCreated)\n lock (__SYNC)\n if (!_IsInstanceCreated) {\n _Instance = Activator.CreateInstance<T>();\n _IsInstanceCreated = true;\n }\n return _Instance;\n }\n }\n}\n" }, { "answer_id": 1010662, "author": "Cade Roux", "author_id": 18255, "author_profile": "https://Stackoverflow.com/users/18255", "pm_score": 1, "selected": false, "text": "public class SingletonBase<T> where T : class\n{\n static SingletonBase()\n {\n }\n\n public static readonly T Instance = \n typeof(T).InvokeMember(typeof(T).Name, \n BindingFlags.CreateInstance | \n BindingFlags.Instance |\n BindingFlags.Public |\n BindingFlags.NonPublic, \n null, null, null) as T;\n}\n" }, { "answer_id": 1323320, "author": "haze4real", "author_id": 132225, "author_profile": "https://Stackoverflow.com/users/132225", "pm_score": 2, "selected": false, "text": "public sealed class Singleton\n{\n private static readonly Singleton _instance = new Singleton();\n\n private Singleton()\n {\n }\n\n public static Singleton Instance\n {\n get\n {\n return _instance;\n }\n }\n}\n" }, { "answer_id": 1473953, "author": "uvw", "author_id": 146204, "author_profile": "https://Stackoverflow.com/users/146204", "pm_score": 0, "selected": false, "text": "public static class LazyGlobal<T> where T : new()\n{\n public static T Instance\n {\n get { return TType.Instance; }\n }\n\n private static class TType\n {\n public static readonly T Instance = new T();\n }\n}\n\n// user code:\n{\n LazyGlobal<Foo>.Instance.Bar();\n}\n public delegate T Func<T>();\n\npublic static class CustomGlobalActivator<T>\n{\n public static Func<T> CreateInstance { get; set; }\n}\n\npublic static class LazyGlobal<T>\n{\n public static T Instance\n {\n get { return TType.Instance; }\n }\n\n private static class TType\n {\n public static readonly T Instance = CustomGlobalActivator<T>.CreateInstance();\n }\n}\n\n{\n // setup code:\n // CustomGlobalActivator<Foo>.CreateInstance = () => new Foo(instanceOf_SL_or_IoC.DoSomeMagicReturning<FooDependencies>());\n CustomGlobalActivator<Foo>.CreateInstance = () => instanceOf_SL_or_IoC.PleaseResolve<Foo>();\n // ...\n // user code:\n LazyGlobal<Foo>.Instance.Bar();\n}\n" }, { "answer_id": 1474006, "author": "JDunkerley", "author_id": 79965, "author_profile": "https://Stackoverflow.com/users/79965", "pm_score": 0, "selected": false, "text": "public static class Singleton<T>\n{\n private static object lockVar = new object();\n private static bool made;\n private static T _singleton = default(T);\n\n /// <summary>\n /// Get The Singleton\n /// </summary>\n public static T Get\n {\n get\n {\n if (!made)\n {\n lock (lockVar)\n {\n if (!made)\n {\n ConstructorInfo cInfo = typeof(T).GetConstructor(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic, null, new Type[0], null);\n if (cInfo != null)\n _singleton = (T)cInfo.Invoke(new object[0]);\n else\n throw new ArgumentException(\"Type Does Not Have A Default Constructor.\");\n made = true;\n }\n }\n }\n\n return _singleton;\n }\n }\n}\n" }, { "answer_id": 1591097, "author": "w0land", "author_id": 234186, "author_profile": "https://Stackoverflow.com/users/234186", "pm_score": 1, "selected": false, "text": "public abstract class Singleton<T> where T : class\n{\n /// <summary>\n /// Returns the singleton instance.\n /// </summary>\n public static T Instance\n {\n get\n {\n return SingletonAllocator.instance;\n }\n }\n\n internal static class SingletonAllocator\n {\n internal static T instance;\n\n static SingletonAllocator()\n {\n CreateInstance(typeof(T));\n }\n\n public static T CreateInstance(Type type)\n {\n ConstructorInfo[] ctorsPublic = type.GetConstructors(\n BindingFlags.Instance | BindingFlags.Public);\n\n if (ctorsPublic.Length > 0)\n throw new Exception(\n type.FullName + \" has one or more public constructors so the property cannot be enforced.\");\n\n ConstructorInfo ctorNonPublic = type.GetConstructor(\n BindingFlags.Instance | BindingFlags.NonPublic, null, new Type[0], new ParameterModifier[0]);\n\n if (ctorNonPublic == null)\n {\n throw new Exception(\n type.FullName + \" doesn't have a private/protected constructor so the property cannot be enforced.\");\n }\n\n try\n {\n return instance = (T)ctorNonPublic.Invoke(new object[0]);\n }\n catch (Exception e)\n {\n throw new Exception(\n \"The Singleton couldnt be constructed, check if \" + type.FullName + \" has a default constructor\", e);\n }\n }\n }\n}\n" }, { "answer_id": 6756793, "author": "Rick", "author_id": 767923, "author_profile": "https://Stackoverflow.com/users/767923", "pm_score": 1, "selected": false, "text": "public sealed class Singleton\n{ \n private Singleton() { }\n\n public static Singleton Instance\n {\n get\n {\n return SingletonCreator.instance;\n }\n }\n\n private class SingletonCreator\n {\n static SingletonCreator() { }\n internal static readonly Singleton instance = new Singleton();\n }\n}\n Singleton s1 = Singleton.Instance;\nSingleton s2 = Singleton.Instance;\nif (s1.Equals(s2))\n{\n Console.WriteLine(\"Thread-Safe Singleton objects are the same\");\n}\n public class Singleton<T>\n where T : class, new()\n{\n private Singleton() { }\n\n public static T Instance \n { \n get \n { \n return SingletonCreator.instance; \n } \n } \n\n private class SingletonCreator \n {\n static SingletonCreator() { }\n\n internal static readonly T instance = new T();\n }\n}\n class TestClass { }\n\nSingleton s1 = Singleton<TestClass>.Instance;\nSingleton s2 = Singleton<TestClass>.Instance;\nif (s1.Equals(s2))\n{\n Console.WriteLine(\"Thread-Safe Generic Singleton objects are the same\");\n}\n using System.Runtime.CompilerServices;\n[MethodImpl (MethodImplOptions.Synchronized)]\npublic static void MySynchronizedMethod()\n{\n}\n" }, { "answer_id": 7703835, "author": "101010", "author_id": 451007, "author_profile": "https://Stackoverflow.com/users/451007", "pm_score": 0, "selected": false, "text": "public class Singleton<T> where T : class\n{\n class SingletonCreator\n {\n static SingletonCreator() { }\n\n internal static readonly T Instance =\n typeof(T).InvokeMember(typeof(T).Name,\n BindingFlags.CreateInstance |\n BindingFlags.Instance |\n BindingFlags.Public |\n BindingFlags.NonPublic,\n null, null, null) as T;\n }\n\n public static T Instance\n {\n get { return SingletonCreator.Instance; }\n }\n}\n public class Foo: Singleton<Foo>\n{\n private Foo() { }\n}\n Foo.Instance.SomeMethod();\n" }, { "answer_id": 7891899, "author": "Alexandr", "author_id": 670082, "author_profile": "https://Stackoverflow.com/users/670082", "pm_score": 3, "selected": false, "text": "public class Singleton<T> where T : class, new()\n {\n Singleton (){}\n\n private static readonly Lazy<T> instance = new Lazy<T>(()=> new T());\n\n public static T Instance { get { return instance.Value; } } \n }\n" }, { "answer_id": 14446722, "author": "Saw", "author_id": 452748, "author_profile": "https://Stackoverflow.com/users/452748", "pm_score": 0, "selected": false, "text": "public class MyClass\n{\n private MyClass()\n {\n\n }\n\n static MyClass()\n {\n Instance = new MyClass();\n }\n\n public static MyClass Instance { get; private set; }\n}\n public class MyClass\n {\n private MyClass()\n {\n\n }\n\n static MyClass()\n {\n Instance = new MyClass();\n }\n\n private static MyClass instance;\n\n\n\n public static MyClass Instance\n {\n get\n {\n return instance;\n }\n private set\n {\n instance = value;\n }\n }\n }\n" }, { "answer_id": 46208920, "author": "MaurGi", "author_id": 3443489, "author_profile": "https://Stackoverflow.com/users/3443489", "pm_score": 0, "selected": false, "text": "public static class Singleton<T> \n{\n private static readonly object Sync = new object();\n\n public static T GetSingleton(ref T singletonMember, Func<T> initializer)\n {\n if (singletonMember == null)\n {\n lock (Sync)\n {\n if (singletonMember == null)\n singletonMember = initializer();\n }\n }\n return singletonMember;\n }\n}\n private static MyType _current;\npublic static MyType Current = Singleton<MyType>.GetSingleton(ref _current, () => new MyType());\n MyType.Current. ...\n" }, { "answer_id": 51169324, "author": "Eran Peled", "author_id": 5929496, "author_profile": "https://Stackoverflow.com/users/5929496", "pm_score": 0, "selected": false, "text": " private Singleton ()\n {\n Console.WriteLine(\"usage of the Singleton for the first time\");\n }\n Parallel.For(0, 10,\n index => {\n Thread tt = new Thread(new ThreadStart(Singleton.Instance.SomePrintMethod));\n tt.Start();\n });\n" }, { "answer_id": 72757098, "author": "Tore Aurstad", "author_id": 741368, "author_profile": "https://Stackoverflow.com/users/741368", "pm_score": 0, "selected": false, "text": " public sealed class Singleton<T> where T : class, new()\n {\n private static Lazy<T> InstanceProxy\n {\n get\n {\n if (_instanceObj?.IsValueCreated != true)\n {\n _instanceObj = new Lazy<T>(() => new T());\n }\n return _instanceObj;\n }\n }\n\n private static Lazy<T>? _instanceObj;\n\n\n public static T Instance { get { return InstanceProxy.Value; } } \n\n public static void Init(Lazy<T> instance)\n {\n if (_instanceObj?.IsValueCreated == true)\n {\n throw new ArgumentException($\"A Singleton for the type <T> is already set\"); \n }\n _instanceObj = instance ?? throw new ArgumentNullException(nameof(instance)); \n }\n\n private Singleton()\n { \n }\n }\n public class Aeroplane\n{\n public string? Model { get; set; }\n public string? Manufacturer { get; set; }\n public int YearBuilt { get; set; }\n public int PassengerCount { get; set; }\n}\n var aeroplane = new Aeroplane\n{\n Manufacturer = \"Boeing\",\n Model = \"747\",\n PassengerCount = 350,\n YearBuilt = 2005\n};\n\nvar aeroPlane3 = Singleton<Aeroplane>.Instance;\nvar aeroPlane4 = Singleton<Aeroplane>.Instance;\n\nConsole.WriteLine($\"Aeroplane3 and aeroplane4 is same object? {Object.ReferenceEquals(aeroPlane3, aeroPlane4)}\");\n var aeroplane2 = new Aeroplane\n{\n Manufacturer = \"Sopwith Aviation Company\",\n Model = \"Sophwith Camel\",\n PassengerCount = 1,\n YearBuilt = 1917\n};\n\nSingleton<Aeroplane>.Init(new Lazy<Aeroplane>(aeroplane2));\n var aeroplaneDefaultInstantiated = Singleton<Aeroplane>.Instance; \n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100081", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17174/" ]
100,104
<p>I've written a small hello world test app in Silverlight which i want to host on a Linux/Apache2 server. I want the data to come from MySQL (or some other linux compatible db) so that I can databind to things in the db.</p> <p>I've managed to get it working by using the <a href="http://www.mysql.com/products/connector/net/" rel="nofollow noreferrer">MySQL Connector/.NET</a>:</p> <pre><code>MySqlConnection conn = new MySqlConnection("Server=the.server.com;Database=theDb;User=myUser;Password=myPassword;"); conn.Open(); MySqlCommand command = new MySqlCommand("SELECT * FROM test;", conn); using (MySqlDataReader reader = command.ExecuteReader()) { StringBuilder sb = new StringBuilder(); while (reader.Read()) { sb.AppendLine(reader.GetString("myColumn")); } this.txtResults.Text = sb.ToString(); } </code></pre> <p>This works fine if I give the published ClickOnce app full trust (or at least SocketPermission) and <strong>run it locally</strong>. </p> <p>I want this to run on the server and I can't get it to work, always ending up with permission exception (SocketPermission is not allowed).</p> <p>The database is hosted on the same server as the silverlight app if that makes any difference.</p> <p><strong>EDIT</strong> Ok, I now understand why it's a bad idea to have db credentials in the client app (obviously). How do people do this then? How do you secure the proxy web service so that it relays data to and from the client/db in a secure way? Are there any examples out there on the web?</p> <p>Surely, I cannot be the first person who'd like to use a database to power a silverlight application?</p>
[ { "answer_id": 5463132, "author": "angularsen", "author_id": 134761, "author_profile": "https://Stackoverflow.com/users/134761", "pm_score": 2, "selected": false, "text": "<ListBox x:Name=\"TestList\" Width=\"100\" />\n public partial class Home : Page\n{\n public Home()\n {\n InitializeComponent();\n\n Loaded += Home_Loaded;\n }\n\n void Home_Loaded(object sender, RoutedEventArgs e)\n {\n var context = new FooDomainContext();\n var query = context.Load(context.GetPersonsQuery());\n TestList.ItemsSource = query.Entities;\n TestList.DisplayMemberPath = \"name\";\n }\n}\n" }, { "answer_id": 20823112, "author": "mjb", "author_id": 520848, "author_profile": "https://Stackoverflow.com/users/520848", "pm_score": 1, "selected": false, "text": "using System;\nusing System.Collections.Generic;\nusing System.Web;\nusing System.Web.Services;\n\nnamespace SilverlightApplication1.Web\n{\n /// <summary>\n /// Summary description for WebService1\n /// </summary>\n [WebService(Namespace = \"http://tempuri.org/\")]\n [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]\n [System.ComponentModel.ToolboxItem(false)]\n public class WebService1 : System.Web.Services.WebService\n {\n [WebMethod]\n public string HelloWorld()\n {\n return \"Hello World\";\n }\n }\n}\n using MySql.Data.MySqlClient; \n public string ExecuteScalar(string sql)\n{\n try\n {\n string result = \"\";\n using (MySqlConnection conn = new MySqlConnection(constr))\n {\n using (MySqlCommand cmd = new MySqlCommand())\n {\n conn.Open();\n cmd.Connection = conn;\n cmd.CommandText = sql;\n result = cmd.ExecuteScalar() + \"\";\n conn.Close();\n }\n }\n return result;\n }\n catch (Exception ex)\n {\n return ex.Message;\n }\n} \n public string ExecuteNonQuery(string sql)\n{\n try\n {\n long i = 0;\n using (MySqlConnection conn = new MySqlConnection(constr))\n {\n using (MySqlCommand cmd = new MySqlCommand())\n {\n conn.Open();\n cmd.Connection = conn;\n cmd.CommandText = sql;\n i = cmd.ExecuteNonQuery();\n conn.Close();\n }\n }\n return i + \" row(s) affected by the last command, no resultset returned.\";\n }\n catch (Exception ex)\n {\n return ex.Message;\n }\n} \n using System;\nusing System.Collections.Generic;\nusing System.Web;\nusing System.Web.Services;\nusing MySql.Data.MySqlClient;\n\nnamespace SilverlightApplication1.Web\n{\n [WebService(Namespace = \"http://tempuri.org/\")]\n [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]\n [System.ComponentModel.ToolboxItem(false)]\n public class WebService1 : System.Web.Services.WebService\n {\n string constr = \"server=localhost;user=root;pwd=1234;database=test;\";\n\n [WebMethod]\n public string ExecuteScalar(string sql)\n {\n try\n {\n string result = \"\";\n using (MySqlConnection conn = new MySqlConnection(constr))\n {\n using (MySqlCommand cmd = new MySqlCommand())\n {\n conn.Open();\n cmd.Connection = conn;\n cmd.CommandText = sql;\n result = cmd.ExecuteScalar() + \"\";\n conn.Close();\n }\n }\n return result;\n }\n catch (Exception ex)\n {\n return ex.Message;\n }\n }\n\n [WebMethod]\n public string ExecuteNonQuery(string sql)\n {\n try\n {\n long i = 0;\n using (MySqlConnection conn = new MySqlConnection(constr))\n {\n using (MySqlCommand cmd = new MySqlCommand())\n {\n conn.Open();\n cmd.Connection = conn;\n cmd.CommandText = sql;\n i = cmd.ExecuteNonQuery();\n conn.Close();\n }\n }\n return i + \" row(s) affected by the last command, no resultset returned.\";\n }\n catch (Exception ex)\n {\n return ex.Message;\n }\n } \n }\n} \n http://www.mywebsite.com/clientaccesspolicy.xml http://www.mywebsite.com/crossdomain.xml <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<access-policy>\n <cross-domain-access>\n <policy>\n <allow-from http-request-headers=\"SOAPAction\">\n <domain uri=\"*\"/>\n </allow-from>\n <grant-to>\n <resource path=\"/\" include-subpaths=\"true\"/>\n </grant-to>\n </policy>\n </cross-domain-access>\n</access-policy>\n <?xml version=\"1.0\" encoding=\"utf-8\"?>\n<access-policy>\n <cross-domain-access>\n <policy>\n <allow-from http-request-headers=\"SOAPAction\">\n <domain uri=\"http://www.myanotherwebsite.com\"/>\n </allow-from>\n <grant-to>\n <resource path=\"/\" include-subpaths=\"true\"/>\n </grant-to>\n </policy>\n </cross-domain-access>\n</access-policy>\n <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<!DOCTYPE cross-domain-policy SYSTEM \n\"http://www.macromedia.com/xml/dtds/cross-domain-policy.dtd\">\n<cross-domain-policy>\n <allow-http-request-headers-from domain=\"*\" headers=\"SOAPAction,Content-Type\"/>\n</cross-domain-policy>\n using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Net;\nusing System.Windows;\nusing System.Windows.Controls;\nusing System.Windows.Documents;\nusing System.Windows.Input;\nusing System.Windows.Media;\nusing System.Windows.Media.Animation;\nusing System.Windows.Shapes;\n\nnamespace SilverlightApplication1\n{\n public partial class MainPage : UserControl\n {\n public MainPage()\n {\n InitializeComponent();\n }\n\n private void btExecuteScalar_Click(object sender, RoutedEventArgs e)\n {\n }\n\n private void btExecuteNonQuery_Click(object sender, RoutedEventArgs e)\n {\n }\n }\n}\n public partial class MainPage : UserControl\n{\n ServiceReference1.WebService1SoapClient myService;\n\n public MainPage()\n {\n InitializeComponent();\n myService = new ServiceReference1.WebService1SoapClient();\n myService.ExecuteScalarCompleted += myService_ExecuteScalarCompleted;\n myService.ExecuteNonQueryCompleted += myService_ExecuteNonQueryCompleted;\n }\n\n void myService_ExecuteNonQueryCompleted(object sender, \n ServiceReference1.ExecuteNonQueryCompletedEventArgs e)\n {\n MessageBox.Show(e.Result);\n }\n\n void myService_ExecuteScalarCompleted(object sender, \n ServiceReference1.ExecuteScalarCompletedEventArgs e)\n {\n MessageBox.Show(e.Result);\n }\n\n private void btExecuteScalar_Click(object sender, RoutedEventArgs e)\n {\n myService.ExecuteScalarAsync(textBox1.Text);\n }\n\n private void btExecuteNonQuery_Click(object sender, RoutedEventArgs e)\n {\n myService.ExecuteNonQueryAsync(textBox1.Text);\n }\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100104", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8521/" ]
100,106
<pre><code>sub foo {[$#{$_[!$||$|]}*@{$_[!!$_^!$_]}?@{$_[!$..!!$.]}[$_[@--@+]% @{$_[$==~/(?=)//!$`]}..$#{$_[$??!!$?:!$?]},($)?!$):!!$))..$_[$--$-]%@{ $_[$]/$]]}-(!!$++!$+)]:@{$_[!!$^^^!$^^]}]} </code></pre> <p>update: I thought the word "puzzle" would imply this, but: <em>I</em> know what it does - I wrote it. If the puzzle doesn't interest you, please don't waste any time on it.</p>
[ { "answer_id": 100503, "author": "nohat", "author_id": 3101, "author_profile": "https://Stackoverflow.com/users/3101", "pm_score": 3, "selected": false, "text": "sub foo {\n my ($list1, $list2) = @_;\n my @output;\n if (@$list2 > 0) {\n my $split = $list1 % @$list2;\n @output = @$list2[$split .. $#$list2, 0 .. ($split - 1)];\n } else {\n @output = @$list2;\n }\n return \\@output;\n}\n $list1 % @$list2 $list !$| | $| @- - @+ perltidy !!$^^^!$^^ !!$^ ^ ^ !$^ ^ !!$^^ ^ !$^^" }, { "answer_id": 147257, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 3, "selected": false, "text": "perl -MO=Concise,foo,-terse,-compact obpuz.pl > obpuz.out" }, { "answer_id": 147456, "author": "Brad Gilbert", "author_id": 1337, "author_profile": "https://Stackoverflow.com/users/1337", "pm_score": 5, "selected": true, "text": "sub foo {\n [\n (\n # ($#{$_[1]})\n $#{\n $_[\n ! ( $| | $| )\n # $OUTPUT_AUTOFLUSH === $|\n # $| is usually 0\n # ! ( $| | $| )\n # ! ( 0 | 0 )\n # ! ( 0 )\n # 1\n ]\n }\n\n *\n\n # @{$_[1]}\n @{\n $_[\n !!$_ ^ !$_\n\n # !! 1 ^ ! 1\n # ! 0 ^ 0\n # 1 ^ 0\n # 1\n\n # !! 0 ^ ! 0\n # ! 1 ^ 1\n # 0 ^ 1\n # 1\n ]\n }\n )\n\n ?\n\n\n # @{$_[1]}\n @{\n $_[\n !$. . !!$.\n # $INPUT_LINE_NUMBER === $.\n # $. starts at 1\n # !$. . !!$.\n # ! 1 . !! 1\n # 0 . ! 0\n # 0 . 1\n # 01\n ]\n }\n\n [\n # $_[0]\n $_[\n # @LAST_MATCH_START - @LAST_MATCH_END\n # 0\n @- - @+\n ]\n\n %\n\n\n # @{$_[1]}\n @{\n $_[\n $= =~ /(?=)/ / !$` #( fix highlighting )`/\n # $= is usually 60\n # /(?=)/ will match, returns 1\n # $` will be ''\n # 1 / ! ''\n # 1 / ! 0\n # 1 / 1\n # 1\n ]\n }\n\n ..\n\n # $#{$_[1]}\n $#{\n $_[\n $? ? !!$? : !$?\n\n # $CHILD_ERROR === $?\n # $? ? !!$? : !$?\n\n # 0 ? !! 0 : ! 0\n # 0 ? 0 : 1\n # 1\n\n # 1 ? !! 1 : ! 1\n # 1 ? 1 : 0\n # 1\n ]\n }\n\n ,\n\n # ( 0 )\n (\n $) ? !$) : !!$)\n\n # $EFFECTIVE_GROUP_ID === $)\n\n # $) ? !$) : !!$)\n\n # 0 ? ! 0 : !! 0\n # 0 ? 1 : 0\n # 0\n\n # 1 ? ! 1 : !! 1\n # 1 ? 0 : 1\n # 0\n )\n\n ..\n\n # $_[0]\n $_[\n $- - $- # 0\n\n # $LAST_PAREN_MATCH = $-\n\n # 1 - 1 == 0\n # 5 - 5 == 0\n ]\n\n %\n\n # @{$_[1]}\n @{\n $_[\n $] / $]\n # $] === The version + patchlevel / 1000 of the Perl interpreter.\n\n # 1 / 1 == 1\n # 5 / 5 == 1\n ]\n }\n\n -\n\n # ( 1 )\n (\n !!$+ + !$+\n\n # !! 1 + ! 1\n # ! 0 + 0\n # 1 + 0\n # 1\n )\n ]\n\n :\n\n # @{$_[1]}\n @{\n $_[\n !!$^^ ^ !$^^\n\n # !! 1 ^ ! 1\n # ! 0 ^ 0\n # 1 ^ 0\n # 1\n\n # !! 0 ^ ! 0\n # ! 1 ^ 1\n # 0 ^ 1\n # 1\n ]\n }\n ]\n}\n sub foo{\n [\n (\n $#{$_[1]} * @{$_[1]}\n )\n\n ?\n\n @{$_[1]}[\n ( $_[0] % @{$_[1]} ) .. $#{$_[1]}\n\n ,\n\n 0 .. ( $_[0] % @{$_[1]} - 1 )\n ]\n\n :\n\n @{$_[1]}\n ]\n}\n sub foo{\n my( $item_0, $arr_1 ) = @_;\n my $len_1 = @$arr_1;\n\n [\n # This essentially just checks that the length of $arr_1 is greater than 1\n ( ( $len_1 -1 ) * $len_1 )\n # ( ( $len_1 -1 ) * $len_1 )\n # ( ( 5 -1 ) * 5 )\n # 4 * 5\n # 20\n # 20 ? 1 : 0 == 1\n\n # ( ( $len_1 -1 ) * $len_1 )\n # ( ( 2 -1 ) * 2 )\n # 1 * 2\n # 2\n # 2 ? 1 : 0 == 1\n\n # ( ( $len_1 -1 ) * $len_1 )\n # ( ( 1 -1 ) * 1 )\n # 0 * 1\n # 0\n # 0 ? 1 : 0 == 0\n\n # ( ( $len_1 -1 ) * $len_1 )\n # ( ( 0 -1 ) * 0 )\n # -1 * 0\n # 0\n # 0 ? 1 : 0 == 0\n\n ?\n\n @{$arr_1}[\n ( $item_0 % $len_1 ) .. ( $len_1 -1 ),\n 0 .. ( $item_0 % $len_1 - 1 )\n ]\n\n :\n\n # If we get here, @$arr_1 is either empty or has only one element\n @$arr_1\n ]\n}\n sub foo{\n my( $item_0, $arr_1 ) = @_;\n my $len_1 = @$arr_1;\n\n if( $len_1 > 1 ){\n return [\n @{$arr_1}[\n ( $item_0 % $len_1 ) .. ( $len_1 -1 ),\n 0 .. ( $item_0 % $len_1 - 1 )\n ]\n ];\n }elsif( $len_1 ){\n return [ @$arr_1 ];\n }else{\n return [];\n }\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100106", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17389/" ]
100,107
<p>I'm investigating the following <code>java.lang.VerifyError</code></p> <pre><code>java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMonthData signature: (IILjava/util/Collection;Ljava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/struts/util/MessageRe˜̴MtÌ´MÚw€mçw€mp:”MŒŒ at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357) at java.lang.Class.getConstructor0(Class.java:2671) </code></pre> <p>It occurs when the jboss server in which the servlet is deployed is started. It is compiled with jdk-1.5.0_11 and I tried to recompile it with jdk-1.5.0_15 without succes. That is the compilation runs fine but when deployed, the java.lang.VerifyError occurs.</p> <p>When I changed the method name and got the following error:</p> <pre><code>java.lang.VerifyError: (class: be/post/ehr/wfm/application/serviceorganization/report/DisplayReportServlet, method: getMD signature: (IILjava/util/Collection;Lj ava/util/Collection;Ljava/util/HashMap;Ljava/util/Collection;Ljava/util/Locale;Lorg/apache/struts/util/MessageResources┬á├ÿ├àN|├ÿ├àN├Üw┬Çm├ºw┬ÇmX#├ûM|X├öM at java.lang.Class.getDeclaredConstructors0(Native Method) at java.lang.Class.privateGetDeclaredConstructors(Class.java:2357 at java.lang.Class.getConstructor0(Class.java:2671) at java.lang.Class.newInstance0(Class.java:321) at java.lang.Class.newInstance(Class.java:303) </code></pre> <p>You can see that more of the method signature is shown.</p> <p>The actual method signature is</p> <pre><code> private PgasePdfTable getMonthData(int month, int year, Collection dayTypes, Collection calendarDays, HashMap bcSpecialDays, Collection activityPeriods, Locale locale, MessageResources resources) throws Exception { </code></pre> <p>I already tried looking at it with <code>javap</code> and that gives the method signature as it should be.</p> <p>When my other colleagues check out the code, compile it and deploy it, they have the same problem. When the build server picks up the code and deploys it on development or testing environments (HPUX), the same error occurs. Also an automated testing machine running Ubuntu shows the same error during server startup.</p> <p>The rest of the application runs okay, only that one servlet is out of order. Any ideas where to look would be helpful.</p>
[ { "answer_id": 100134, "author": "p3t0r", "author_id": 16685, "author_profile": "https://Stackoverflow.com/users/16685", "pm_score": 5, "selected": false, "text": "java.lang.VerifyError utf-8" }, { "answer_id": 101364, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 3, "selected": false, "text": "-Xverify:all" }, { "answer_id": 918001, "author": "Mike Miller", "author_id": 16138, "author_profile": "https://Stackoverflow.com/users/16138", "pm_score": 2, "selected": false, "text": "--effort=4" }, { "answer_id": 2518002, "author": "Kevin Panko", "author_id": 125389, "author_profile": "https://Stackoverflow.com/users/125389", "pm_score": 9, "selected": true, "text": "java.lang.VerifyError org.apache.* ClassNotFoundException VerifyError String List" }, { "answer_id": 16060251, "author": "18446744073709551615", "author_id": 755804, "author_profile": "https://Stackoverflow.com/users/755804", "pm_score": 2, "selected": false, "text": " catch (MagickException e)\n catch (Exception e)\n MagickException java.lang.NoClassDefFoundError" }, { "answer_id": 16634043, "author": "Michal Vician", "author_id": 915756, "author_profile": "https://Stackoverflow.com/users/915756", "pm_score": 3, "selected": false, "text": "java.lang.VerifyError" }, { "answer_id": 23325795, "author": "ViliusK", "author_id": 517381, "author_profile": "https://Stackoverflow.com/users/517381", "pm_score": 2, "selected": false, "text": "compileOptions {\n sourceCompatibility JavaVersion.VERSION_1_7\n targetCompatibility JavaVersion.VERSION_1_7\n}\n Fragment.showDialog()" }, { "answer_id": 27640213, "author": "Sandeep Jindal", "author_id": 231567, "author_profile": "https://Stackoverflow.com/users/231567", "pm_score": 0, "selected": false, "text": "cglibs hibernate" }, { "answer_id": 29471655, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 2, "selected": false, "text": "void return return; .class public Main\n.super java/lang/Object\n\n.method public static main([Ljava/lang/String;)V\n aload_0 ; Just so that we won't get another verify error for empty code.\n.end method\n javac Main.j javap -v Main public static void main(java.lang.String[]);\n descriptor: ([Ljava/lang/String;)V\n flags: ACC_PUBLIC, ACC_STATIC\n Code:\n stack=1, locals=1, args_size=1\n 0: aload_0\n java Main Error: A JNI error has occurred, please check your installation and try again\nException in thread \"main\" java.lang.VerifyError: (class: NoReturn, method: main signature: ([Ljava/lang/String;)V) Falling off the end of the code\n at java.lang.Class.getDeclaredMethods0(Native Method)\n at java.lang.Class.privateGetDeclaredMethods(Class.java:2701)\n at java.lang.Class.privateGetMethodRecursive(Class.java:3048)\n at java.lang.Class.getMethod0(Class.java:3018)\n at java.lang.Class.getMethod(Class.java:1784)\n at sun.launcher.LauncherHelper.validateMainClass(LauncherHelper.java:544)\n at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:526)\n return void return main javap javac" }, { "answer_id": 35481346, "author": "anand krish", "author_id": 2147814, "author_profile": "https://Stackoverflow.com/users/2147814", "pm_score": 0, "selected": false, "text": "compile 'com.fasterxml.jackson.core:jackson-databind:2.2.+'\ncompile 'com.fasterxml.jackson.core:jackson-core:2.2.+'\ncompile 'com.fasterxml.jackson.core:jackson-annotations:2.2.+'\n compile 'com.fasterxml.jackson.core:jackson-annotations:2.7.0-rc3'\ncompile 'com.fasterxml.jackson.core:jackson-databind:2.7.0-rc3'\n" }, { "answer_id": 48088835, "author": "Aashirwad Sinha", "author_id": 9171082, "author_profile": "https://Stackoverflow.com/users/9171082", "pm_score": -1, "selected": false, "text": "jasperreports-server-cp-6.4.0-bin\\buildomatic\\build.xml:61: The following error occurred while executing this line:\nTIB_js-jrs-cp_6.4.0_bin\\jasperreports-server-cp-6.4.0-bin\\buildomatic\\bin\\setup.xml:320: java.lang.VerifyError: (class: org/apache/commons/codec/binary/Base64OutputStream, method: <init> signature: (Ljava/io/OutputStream;ZI[B)V) Incompatible argument to function\n at com.jaspersoft.jasperserver.crypto.KeystoreManager.createKeystore(KeystoreManager.java:257)\n at com.jaspersoft.jasperserver.crypto.KeystoreManager.init(KeystoreManager.java:224)\n at com.jaspersoft.buildomatic.crypto.KeystoreTask.execute(KeystoreTask.java:64)\n at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)\n at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n at java.lang.reflect.Method.invoke(Method.java:498)\n at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)\n at org.apache.tools.ant.Task.perform(Task.java:348)\n at org.apache.tools.ant.taskdefs.Sequential.execute(Sequential.java:68)\n at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)\n at sun.reflect.GeneratedMethodAccessor4.invoke(Unknown Source)\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n at java.lang.reflect.Method.invoke(Method.java:498)\n at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)\n at org.apache.tools.ant.Task.perform(Task.java:348)\n at org.apache.tools.ant.Target.execute(Target.java:435)\n at org.apache.tools.ant.helper.ProjectHelper2.parse(ProjectHelper2.java:169)\n at org.apache.tools.ant.taskdefs.ImportTask.importResource(ImportTask.java:222)\n at org.apache.tools.ant.taskdefs.ImportTask.execute(ImportTask.java:163)\n at org.apache.tools.ant.UnknownElement.execute(UnknownElement.java:292)\n at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)\n at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)\n at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)\n at java.lang.reflect.Method.invoke(Method.java:498)\n at org.apache.tools.ant.dispatch.DispatchUtils.execute(DispatchUtils.java:106)\n at org.apache.tools.ant.Task.perform(Task.java:348)\n at org.apache.tools.ant.Target.execute(Target.java:435)\n at org.apache.tools.ant.helper.ProjectHelper2.parse(ProjectHelper2.java:180)\n at org.apache.tools.ant.ProjectHelper.configureProject(ProjectHelper.java:93)\n at org.apache.tools.ant.Main.runBuild(Main.java:826)\n at org.apache.tools.ant.Main.startAnt(Main.java:235)\n at org.apache.tools.ant.launch.Launcher.run(Launcher.java:280)\n at org.apache.tools.ant.launch.Launcher.main(Launcher.java:109)\n" }, { "answer_id": 57858197, "author": "Eduardo Morales", "author_id": 11731597, "author_profile": "https://Stackoverflow.com/users/11731597", "pm_score": 0, "selected": false, "text": "{Wildfly-home}\\modules\\system\\layers\\base\\org\\picketbox\\main \n <module name=\"sun.jdk\"/>" }, { "answer_id": 60530452, "author": "CoolMind", "author_id": 2914140, "author_profile": "https://Stackoverflow.com/users/2914140", "pm_score": 1, "selected": false, "text": "Gradle Glide Gradle classpath 'com.android.tools.build:gradle:3.5.3'" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100107", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15490/" ]
100,123
<p>I would like to create an application wide keyboard shortcut for a Java Swing application. Looping over all components and adding the shortcut on each, has focus related side effects, and seems like a brute force solution.</p> <p>Anyone has a cleaner solution?</p>
[ { "answer_id": 100754, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 5, "selected": false, "text": "JComponent.registerKeyboardAction WHEN_IN_FOCUSED_WINDOW JComponent.getInputMap(WHEN_IN_FOCUSED_WINDOW).put(keyStroke, command);\nJComponent.getActionMap().put(command,action);\n" }, { "answer_id": 8485642, "author": "daniel kullmann", "author_id": 85615, "author_profile": "https://Stackoverflow.com/users/85615", "pm_score": 3, "selected": false, "text": " JMenuItem item = new JMenuItem(action);\n KeyStroke key = KeyStroke.getKeyStroke(\n KeyEvent.VK_R, KeyEvent.CTRL_DOWN_MASK);\n item.setAccelerator(key);\n menu.add(item);\n" }, { "answer_id": 8485873, "author": "daniel kullmann", "author_id": 85615, "author_profile": "https://Stackoverflow.com/users/85615", "pm_score": 4, "selected": false, "text": "if (key == ..) then .. else if (key == ..) then .. else if (key ==..) .. /** map containing all global actions */\nprivate HashMap<KeyStroke, Action> actionMap = new HashMap<KeyStroke, Action>();\n\n/** call this somewhere in your GUI construction */\nprivate void setup() {\n KeyStroke key1 = KeyStroke.getKeyStroke(KeyEvent.VK_A, KeyEvent.CTRL_DOWN_MASK);\n actionMap.put(key1, new AbstractAction(\"action1\") {\n @Override\n public void actionPerformed(ActionEvent e) {\n System.out.println(\"Ctrl-A pressed: \" + e);\n }\n });\n // add more actions..\n\n KeyboardFocusManager kfm = KeyboardFocusManager.getCurrentKeyboardFocusManager();\n kfm.addKeyEventDispatcher( new KeyEventDispatcher() {\n\n @Override\n public boolean dispatchKeyEvent(KeyEvent e) {\n KeyStroke keyStroke = KeyStroke.getKeyStrokeForEvent(e);\n if ( actionMap.containsKey(keyStroke) ) {\n final Action a = actionMap.get(keyStroke);\n final ActionEvent ae = new ActionEvent(e.getSource(), e.getID(), null );\n SwingUtilities.invokeLater( new Runnable() {\n @Override\n public void run() {\n a.actionPerformed(ae);\n }\n } ); \n return true;\n }\n return false;\n }\n });\n}\n" }, { "answer_id": 17477921, "author": "JavaTechnical", "author_id": 2534090, "author_profile": "https://Stackoverflow.com/users/2534090", "pm_score": -1, "selected": false, "text": "ActionListener a=new ActionListener(){\n public void actionPerformed(ActionEvent ae)\n {\n // your code\n }\n};\ngetRootPane().registerKeyboardAction(a,KeyStroke.getKeyStroke(\"ctrl D\"),JComponent.WHEN_IN_FOCUSED_WINDOW);\n" }, { "answer_id": 29770031, "author": "mortalis", "author_id": 1106547, "author_profile": "https://Stackoverflow.com/users/1106547", "pm_score": 2, "selected": false, "text": "KeyboardFocusManager keyManager;\n\nkeyManager=KeyboardFocusManager.getCurrentKeyboardFocusManager();\nkeyManager.addKeyEventDispatcher(new KeyEventDispatcher() {\n\n @Override\n public boolean dispatchKeyEvent(KeyEvent e) {\n if(e.getID()==KeyEvent.KEY_PRESSED && e.getKeyCode()==27){\n System.out.println(\"Esc\");\n return true;\n }\n return false;\n }\n\n});\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100123", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18591/" ]
100,161
<p>I was happily using Eclipse 3.2 (or as happy as one can be using Eclipse) when for a forgotten reason I decided to upgrade to 3.4. I'm primarily using PyDev, Aptana, and Subclipse, very little Java development.</p> <p>I've noticed 3.4 tends to really give my laptop a hernia compared to 3.2 (vista, core2duo, 2G). Is memory usage on 3.4 actually higher than on 3.2, and if so is there a way to reduce it?</p> <p>EDIT: I tried disabling plugins (I didn't have much enabled anyway) and used the jvm monitor; the latter was interesting but I couldn't figure out how to use the info in any practical way. I'm still not able to reduce its memory footprint. I've also noticed every once in a while Eclipse just hangs for ~30 seconds, then magically comes back.</p>
[ { "answer_id": 100180, "author": "Drejc", "author_id": 6482, "author_profile": "https://Stackoverflow.com/users/6482", "pm_score": 2, "selected": false, "text": "-vmargs -XX:MaxPermSize=1024M -Xms256M -Xmx1024M\n" }, { "answer_id": 101164, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 2, "selected": false, "text": "-vmargs\n-Xms128m\n-Xmx384m\n-Xssv2m\n-XX:PermSize=128m\n-XX:MaxPermSize=128m\n-XX:CompileThreshold=5\n-XX:+UseParallelGC\n-Dcom.sun.management.jmxremote\n C:\\[jdk1.6.0_0x path]\\bin\\jconsole.exe\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100161", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13055/" ]
100,170
<p>I have a folder on my server to which I had a number of symbolic links pointing. I've since created a new folder and I want to change all those symbolic links to point to the new folder. I'd considered replacing the original folder with a symlink to the new folder, but it seems that if I continued with that practice it could get very messy very fast.</p> <p>What I've been doing is manually changing the symlinks to point to the new folder, but I may have missed a couple. </p> <p>Is there a way to check if there are any symlinks pointing to a particular folder?</p>
[ { "answer_id": 100200, "author": "skymt", "author_id": 18370, "author_profile": "https://Stackoverflow.com/users/18370", "pm_score": 7, "selected": true, "text": "find . -lname /particular/folder\n /particular/folder find . -lname '*folder'\n" }, { "answer_id": 100203, "author": "bfabry", "author_id": 924607, "author_profile": "https://Stackoverflow.com/users/924607", "pm_score": 1, "selected": false, "text": "find / -lname 'fullyqualifiedpathoffile'\n" }, { "answer_id": 100205, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 1, "selected": false, "text": "-i find -inum ls -l" }, { "answer_id": 100208, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": false, "text": "for a in `find / -type l`; do echo \"$a -> `readlink $a`\"; done | grep destfolder\n find -lname" }, { "answer_id": 3892002, "author": "no1uknow", "author_id": 470396, "author_profile": "https://Stackoverflow.com/users/470396", "pm_score": 3, "selected": false, "text": "find . -type l -printf '%p -> %l\\n'\n" }, { "answer_id": 9682527, "author": "JJK", "author_id": 1266260, "author_profile": "https://Stackoverflow.com/users/1266260", "pm_score": 3, "selected": false, "text": "symlinks" }, { "answer_id": 20904085, "author": "Lunar Mushrooms", "author_id": 986020, "author_profile": "https://Stackoverflow.com/users/986020", "pm_score": 1, "selected": false, "text": "find /foldername -type l -exec ls -lad {} \\;\n" }, { "answer_id": 68560106, "author": "Thomas Tempelmann", "author_id": 43615, "author_profile": "https://Stackoverflow.com/users/43615", "pm_score": 0, "selected": false, "text": "fts_open()" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100170", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9021/" ]
100,196
<p>What is the difference between the <a href="https://msdn.microsoft.com/en-us/library/z883w3dc(v=vs.110).aspx" rel="noreferrer">AddRange</a> and <a href="https://msdn.microsoft.com/en-us/library/bb302894(v=vs.110).aspx" rel="noreferrer">Concat</a> functions on a generic List? Is one recommended over the other?</p>
[ { "answer_id": 100239, "author": "AnthonyWJones", "author_id": 17516, "author_profile": "https://Stackoverflow.com/users/17516", "pm_score": 6, "selected": false, "text": "AddRange Concat Concat IEnumerable<T> IEnumerable<T> .ToList() AddRange IEnumerable<T> Concat .ToList Concat" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5302/" ]
100,210
<p>Given a <code>datetime.time</code> value in Python, is there a standard way to add an integer number of seconds to it, so that <code>11:34:59</code> + 3 = <code>11:35:02</code>, for example?</p> <p>These obvious ideas don't work:</p> <pre><code>&gt;&gt;&gt; datetime.time(11, 34, 59) + 3 TypeError: unsupported operand type(s) for +: 'datetime.time' and 'int' &gt;&gt;&gt; datetime.time(11, 34, 59) + datetime.timedelta(0, 3) TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta' &gt;&gt;&gt; datetime.time(11, 34, 59) + datetime.time(0, 0, 3) TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.time' </code></pre> <p>In the end I have written functions like this:</p> <pre><code>def add_secs_to_time(timeval, secs_to_add): secs = timeval.hour * 3600 + timeval.minute * 60 + timeval.second secs += secs_to_add return datetime.time(secs // 3600, (secs % 3600) // 60, secs % 60) </code></pre> <p>I can't help thinking that I'm missing an easier way to do this though.</p> <h3>Related</h3> <ul> <li><a href="https://stackoverflow.com/questions/656297/python-time-timedelta-equivalent">python time + timedelta equivalent</a></li> </ul>
[ { "answer_id": 100250, "author": "Nick Johnson", "author_id": 12030, "author_profile": "https://Stackoverflow.com/users/12030", "pm_score": 0, "selected": false, "text": "datetime.datetime datetime.timedelta time() datetime.datetime" }, { "answer_id": 100345, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 10, "selected": true, "text": "datetime timedelta time import datetime\na = datetime.datetime(100,1,1,11,34,59)\nb = a + datetime.timedelta(0,3) # days, seconds, then other fields.\nprint(a.time())\nprint(b.time())\n 11:34:59\n11:35:02\n b = a + datetime.timedelta(seconds=3)\n addSecs import datetime\n\ndef addSecs(tm, secs):\n fulldate = datetime.datetime(100, 1, 1, tm.hour, tm.minute, tm.second)\n fulldate = fulldate + datetime.timedelta(seconds=secs)\n return fulldate.time()\n\na = datetime.datetime.now().time()\nb = addSecs(a, 300)\nprint(a)\nprint(b)\n 09:11:55.775695\n 09:16:55\n" }, { "answer_id": 100404, "author": "unmounted", "author_id": 11596, "author_profile": "https://Stackoverflow.com/users/11596", "pm_score": 5, "selected": false, "text": ">>> b = a + datetime.timedelta(seconds=3000)\n>>> b\ndatetime.datetime(1, 1, 1, 12, 24, 59)\n" }, { "answer_id": 100776, "author": "Paul Stephenson", "author_id": 5536, "author_profile": "https://Stackoverflow.com/users/5536", "pm_score": 4, "selected": false, "text": "add_secs_to_time() def add_secs_to_time(timeval, secs_to_add):\n dummy_date = datetime.date(1, 1, 1)\n full_datetime = datetime.datetime.combine(dummy_date, timeval)\n added_datetime = full_datetime + datetime.timedelta(seconds=secs_to_add)\n return added_datetime.time()\n (datetime.datetime.combine(datetime.date(1, 1, 1), timeval) + datetime.timedelta(seconds=secs_to_add)).time()\n" }, { "answer_id": 101947, "author": "Eli Courtwright", "author_id": 1694, "author_profile": "https://Stackoverflow.com/users/1694", "pm_score": 6, "selected": false, "text": "from datetime import datetime, date, time, timedelta\nsometime = time(8,00) # 8am\nlater = (datetime.combine(date.today(), sometime) + timedelta(seconds=3)).time()\n" }, { "answer_id": 6839259, "author": "rescdsk", "author_id": 88198, "author_profile": "https://Stackoverflow.com/users/88198", "pm_score": 3, "selected": false, "text": "datetime.time >>> import datetime\n>>> import nptime\n>>> nptime.nptime(11, 34, 59) + datetime.timedelta(0, 3)\nnptime(11, 35, 2)\n nptime datetime.time nptime" }, { "answer_id": 46653858, "author": "Bart Van Loon", "author_id": 8485638, "author_profile": "https://Stackoverflow.com/users/8485638", "pm_score": 3, "selected": false, "text": "arrow sometime = arrow.now()\nabitlater = sometime.shift(seconds=3)\n" }, { "answer_id": 48315879, "author": "user2387567", "author_id": 2387567, "author_profile": "https://Stackoverflow.com/users/2387567", "pm_score": 4, "selected": false, "text": "datetime timedelta datetime datetime timedelta datetime timedelta datetime datetime timedelta timedelta datetime >>> from datetime import datetime, timedelta\n>>> t = datetime.now() + timedelta(seconds=3000)\n>>> print(t)\ndatetime.datetime(2018, 1, 17, 21, 47, 13, 90244)\n std::chrono::duration" }, { "answer_id": 57498235, "author": "blthayer", "author_id": 11052174, "author_profile": "https://Stackoverflow.com/users/11052174", "pm_score": 0, "selected": false, "text": "datetime.time tzinfo timetz() time() def add_timedelta_to_time(t, td):\n \"\"\"Add a timedelta object to a time object using a dummy datetime.\n\n :param t: datetime.time object.\n :param td: datetime.timedelta object.\n\n :returns: datetime.time object, representing the result of t + td.\n\n NOTE: Using a gigantic td may result in an overflow. You've been\n warned.\n \"\"\"\n # Create a dummy date object.\n dummy_date = date(year=100, month=1, day=1)\n\n # Combine the dummy date with the given time.\n dummy_datetime = datetime.combine(date=dummy_date, time=t, tzinfo=t.tzinfo)\n\n # Add the timedelta to the dummy datetime.\n new_datetime = dummy_datetime + td\n\n # Return the resulting time, including timezone information.\n return new_datetime.timetz()\n unittest import unittest\nfrom datetime import datetime, timezone, timedelta, time\n\nclass AddTimedeltaToTimeTestCase(unittest.TestCase):\n \"\"\"Test add_timedelta_to_time.\"\"\"\n\n def test_wraps(self):\n t = time(hour=23, minute=59)\n td = timedelta(minutes=2)\n t_expected = time(hour=0, minute=1)\n t_actual = add_timedelta_to_time(t=t, td=td)\n self.assertEqual(t_expected, t_actual)\n\n def test_tz(self):\n t = time(hour=4, minute=16, tzinfo=timezone.utc)\n td = timedelta(hours=10, minutes=4)\n t_expected = time(hour=14, minute=20, tzinfo=timezone.utc)\n t_actual = add_timedelta_to_time(t=t, td=td)\n self.assertEqual(t_expected, t_actual)\n\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "answer_id": 65920435, "author": "VengaVenga", "author_id": 4798335, "author_profile": "https://Stackoverflow.com/users/4798335", "pm_score": 2, "selected": false, "text": "time datetime utc import datetime as dt\n\n_now = dt.datetime.now() # or dt.datetime.now(dt.timezone.utc)\n_in_5_sec = _now + dt.timedelta(seconds=5)\n\n# get '14:39:57':\n_in_5_sec.strftime('%H:%M:%S')\n" }, { "answer_id": 71674257, "author": "Ziggity", "author_id": 17013800, "author_profile": "https://Stackoverflow.com/users/17013800", "pm_score": 1, "selected": false, "text": " new_time:time = time(\n hour=curr_time.hour + n_hours,\n minute=curr_time.minute + n_minutes,\n seconds=curr_time.second + n_seconds\n )\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5536/" ]
100,211
<p>I just installed Glassfish V2 on my local machine just to play around with it.</p> <p>I was wondering if there is a way to retrieve a param passed in by the GET HTTP method.</p> <p>For instance,</p> <pre><code>http://localhost:8080/HelloWorld/resources/helloWorld?name=ABC </code></pre> <p>How do I retrieve the "name" param in my Java code?</p>
[ { "answer_id": 100396, "author": "tgdavies", "author_id": 11002, "author_profile": "https://Stackoverflow.com/users/11002", "pm_score": 3, "selected": true, "text": "@Path(\"/helloWorld\")\n@Consumes({\"application/xml\", \"application/json\"})\n@Produces({\"application/xml\", \"application/json\"})\n@Singleton\npublic class MyService {\n @GET\n public String getRequest(@QueryParam(\"name\") String name) {\n return \"Name was \" + name;\n }\n}\n" }, { "answer_id": 100424, "author": "tim_yates", "author_id": 6509, "author_profile": "https://Stackoverflow.com/users/6509", "pm_score": 0, "selected": false, "text": "@Context\nprivate UriInfo context;\n context.getQueryParameters() ;\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100211", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4004/" ]
100,216
<p>I'm trying to integrate running Fitnesse tests from MSBuild im my nightly build on TFS.</p> <p>In an attempt to make it self contained I would like to start the seleniumRC server only when it's needed from fitness.</p> <p>I've seen that there is a "Command Line Fixture" but it's written in java can I use that?</p>
[ { "answer_id": 100647, "author": "Martin Woodward", "author_id": 6438, "author_profile": "https://Stackoverflow.com/users/6438", "pm_score": 2, "selected": true, "text": "Process process = Process.GetProcessById(ProcessId);\nprocess.Kill();\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100216", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11434/" ]
100,221
<p>Whilst refactoring some old code I realised that a particular header file was full of function declarations for functions long since removed from the .cpp file. Does anyone know of a tool that could find (and strip) these automatically?</p>
[ { "answer_id": 647548, "author": "zhaorufei", "author_id": 64469, "author_profile": "https://Stackoverflow.com/users/64469", "pm_score": 2, "selected": false, "text": "void foo(int );\n\nint main()\n{\n return 0;\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100221", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
100,228
<p>I'm trying to set up part of a schema that's like a "Sequence" where all child elements are optional, but at least one of the elements <strong>must</strong> be present, and there could be more than one of them.</p> <p>I tried doing the following, but XMLSpy complains that "The content model contains the elements &lt;element name="DateConstant"&gt; and &lt;element name="DateConstant"&gt; which cannot be uniquely determined.":</p> <pre><code> &lt;xs:choice&gt; &lt;xs:sequence&gt; &lt;xs:element name="DateConstant"/&gt; &lt;xs:element name="TimeConstant"/&gt; &lt;/xs:sequence&gt; &lt;xs:element name="DateConstant"/&gt; &lt;xs:element name="TimeConstant"/&gt; &lt;/xs:choice&gt; </code></pre> <p>Can this be done (and if so, how)?</p> <p>Some clarification: I only want to allow one of each element of the same name. There can be one "DateConstant" and/or one "TimeConstant", but not two of either. Gizmo's answer matches my requirements, but it's impractical for a larger number of elements. Hurst's answer allows two or more elements of the same name, which I don't want.</p>
[ { "answer_id": 100313, "author": "gizmo", "author_id": 9396, "author_profile": "https://Stackoverflow.com/users/9396", "pm_score": 6, "selected": true, "text": "<xs:choice>\n <xs:sequence>\n <xs:element name=\"Elem1\" />\n <xs:element name=\"Elem2\" minOccurs=\"0\" />\n <xs:element name=\"Elem3\" minOccurs=\"0\" />\n </xs:sequence>\n <xs:sequence>\n <xs:element name=\"Elem2\" />\n <xs:element name=\"Elem3\" minOccurs=\"0\" />\n </xs:sequence>\n <xs:element name=\"Elem3\" />\n</xs:choice>\n" }, { "answer_id": 100589, "author": "hurst", "author_id": 10991, "author_profile": "https://Stackoverflow.com/users/10991", "pm_score": 4, "selected": false, "text": "<xs:choice minOccurs=\"1\" maxOccurs=\"unbounded\">\n <xs:element name=\"DateConstant\" type=\"...\"/>\n <xs:element name=\"TimeConstant\" type=\"...\"/>\n</xs:choice>\n" }, { "answer_id": 14313107, "author": "Enigmatic", "author_id": 1357443, "author_profile": "https://Stackoverflow.com/users/1357443", "pm_score": 2, "selected": false, "text": "<xs:choice minOccurs=\"1\" maxOccurs=\"1\">\n <xs:sequence minOccurs=\"1\" maxOccurs=\"1\">\n <xs:element name=\"Elem1\" minOccurs=\"1\" maxOccurs=\"1\" />\n <xs:element name=\"Elem2\" minOccurs=\"0\" maxOccurs=\"1\" />\n </xs:sequence>\n <xs:sequence >\n <xs:element name=\"Elem2\" minOccurs=\"1\" maxOccurs=\"1\" />\n </xs:sequence>\n</xs:choice>\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100228", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18603/" ]
100,235
<p>For an open source project I am looking for a good, simple implementation of a Dictionary that is backed by a file. Meaning, if an application crashes or restarts the dictionary will keep its state. I would like it to update the underlying file every time the dictionary is touched. (Add a value or remove a value). A FileWatcher is not required but it could be useful. </p> <pre><code>class PersistentDictionary&lt;T,V&gt; : IDictionary&lt;T,V&gt; { public PersistentDictionary(string filename) { } } </code></pre> <p>Requirements: </p> <ul> <li>Open Source, with no dependency on native code (no sqlite) </li> <li>Ideally a very short and simple implementation</li> <li>When setting or clearing a value it should not re-write the entire underlying file, instead it should seek to the position in the file and update the value.</li> </ul> <p><strong>Similar Questions</strong> </p> <ul> <li><a href="https://stackoverflow.com/questions/108435/persistent-binary-tree-hash-table-in-net">Persistent Binary Tree / Hash table in .Net</a></li> <li><a href="https://stackoverflow.com/questions/408401/disk-backed-dictionary-cache-for-c">Disk backed dictionary/cache for c#</a></li> <li><a href="http://izlooite.blogspot.com/2011/04/persistent-dictionary.html" rel="noreferrer"><code>PersistentDictionary&lt;Key,Value&gt;</code></a></li> </ul>
[ { "answer_id": 176561, "author": "Omer van Kloeten", "author_id": 4979, "author_profile": "https://Stackoverflow.com/users/4979", "pm_score": 0, "selected": false, "text": "BinaryWriter Dictionary<TKey, TValue>" }, { "answer_id": 482984, "author": "lubos hasko", "author_id": 275, "author_profile": "https://Stackoverflow.com/users/275", "pm_score": 6, "selected": true, "text": "System.Collections.Generic" }, { "answer_id": 483292, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": -1, "selected": false, "text": "<dico> \n <dicEntry index=\"x\">\n <key>MyKey</key>\n <val type=\"string\">My val</val>\n </dicEntry>\n ...\n</dico>\n XmlDocument xdocDico = new XmlDocument();\nstring sXMLfile;\npublic loadDico(string sXMLfile, [other args...])\n{\n xdocDico.load(sXMLfile);\n // Gather whatever you need and load it into your dico\n}\npublic flushDicInXML(string sXMLfile, dictionary dicWhatever)\n{\n // Dump the dic in the XML doc & save\n}\npublic updateXMLDOM(index, key, value)\n{\n // Update a specific value of the XML DOM based on index or key\n}\n xdocDico.save(sXMLfile);" }, { "answer_id": 491543, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 1, "selected": false, "text": "varchar(max) varbinary(max) class PersistantDictionary<T,V> : Dictionary<T,V>\n where V:struct\n" }, { "answer_id": 495516, "author": "Ray Hidayat", "author_id": 49643, "author_profile": "https://Stackoverflow.com/users/49643", "pm_score": 1, "selected": false, "text": "class PersistentDictManager {\n const int SaveAllThreshold = 1000;\n\n PersistentDictManager(string logpath) {\n this.LogPath = logpath;\n this.mydictionary = new Dictionary<string, string>();\n this.LoadData();\n }\n\n public string LogPath { get; private set; }\n\n public string this[string key] {\n get{ return this.mydictionary[key]; }\n set{\n string existingvalue;\n if(!this.mydictionary.TryGetValue(key, out existingvalue)) { existingvalue = null; }\n if(string.Equals(value, existingvalue)) { return; }\n this[key] = value;\n\n // store in log\n if(existingvalue != null) { // was an update (not a create)\n if(this.IncrementSaveAll()) { return; } // because we're going to repeat a key the log\n }\n this.LogStore(key, value);\n }\n }\n\n public void Remove(string key) {\n if(!this.mydictionary.Remove(key)) { return; }\n if(this.IncrementSaveAll()) { return; } // because we're going to repeat a key in the log\n this.LogDelete(key);\n }\n\n private void CreateWriter() {\n if(this.writer == null) {\n this.writer = new BinaryWriter(File.Open(this.LogPath, FileMode.Open)); \n }\n }\n\n private bool IncrementSaveAll() {\n ++this.saveallcount;\n if(this.saveallcount >= PersistentDictManager.SaveAllThreshold) {\n this.SaveAllData();\n return true;\n }\n else { return false; }\n }\n\n private void LoadData() {\n try{\n using(BinaryReader reader = new BinaryReader(File.Open(LogPath, FileMode.Open))) {\n while(reader.PeekChar() != -1) {\n string key = reader.ReadString();\n bool isdeleted = reader.ReadBoolean();\n if(isdeleted) { this.mydictionary.Remove(key); }\n else {\n string value = reader.ReadString();\n this.mydictionary[key] = value;\n }\n }\n }\n }\n catch(FileNotFoundException) { }\n }\n\n private void LogDelete(string key) {\n this.CreateWriter();\n this.writer.Write(key);\n this.writer.Write(true); // yes, key was deleted\n }\n\n private void LogStore(string key, string value) {\n this.CreateWriter();\n this.writer.Write(key);\n this.writer.Write(false); // no, key was not deleted\n this.writer.Write(value);\n }\n\n private void SaveAllData() {\n if(this.writer != null) {\n this.writer.Close();\n this.writer = null;\n }\n using(BinaryWriter writer = new BinaryWriter(File.Open(this.LogPath, FileMode.Create))) {\n foreach(KeyValuePair<string, string> kv in this.mydictionary) {\n writer.Write(kv.Key);\n writer.Write(false); // is not deleted flag\n writer.Write(kv.Value);\n }\n }\n }\n\n private readonly Dictionary<string, string> mydictionary;\n private int saveallcount = 0;\n private BinaryWriter writer = null;\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17174/" ]
100,236
<p>How can I insert ASCII special characters (e.g. with the ASCII value 0x01) into a string?</p> <p>I ask because I am using the following:</p> <pre><code>str.Replace( "&lt;TAG1&gt;", Convert.ToChar(0x01).ToString() ); </code></pre> <p>and I feel that there must be a better way than this. Any Ideas?</p> <p>Update:</p> <p>Also If I use this methodology, do I need to worry about unicode &amp; ASCII clashing?</p>
[ { "answer_id": 100244, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 4, "selected": true, "text": "\\uXXXX using System;\nclass Uxxxx {\n public static void Main() {\n Console.WriteLine(\"\\u20AC\");\n }\n}\n" }, { "answer_id": 1176383, "author": "bzlm", "author_id": 7724, "author_profile": "https://Stackoverflow.com/users/7724", "pm_score": 1, "selected": false, "text": "0x01" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100236", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1816/" ]
100,242
<p>You can use </p> <p>SelectFolder() to get a folder</p> <p>or </p> <p>GetOpenFolderitem(filter as string) to get files</p> <p>but can you select either a folder or file? ( or for that matter selecting multiple files )</p>
[ { "answer_id": 170102, "author": "Philip Regan", "author_id": 11976, "author_profile": "https://Stackoverflow.com/users/11976", "pm_score": 4, "selected": true, "text": "OpenDialogMBS.AllowFolderSelection as Boolean\nproperty, Navigation, MBS Util Plugin (OpenDialog), class OpenDialogMBS, Plugin version: 7.5, Mac OS X: Works, Windows: Does nothing, Linux x86: Does nothing, Feedback.\n\nFunction: Whether folders can be selected.\nExample: \ndim o as OpenDialogMBS\ndim i,c as integer\ndim f as FolderItem\n\no=new OpenDialogMBS\no.ShowHiddenFiles=true\no.PromptText=\"Select one or more files/folders:\"\no.MultipleSelection=false\no.ActionButtonLabel=\"Open files/folders\"\no.CancelButtonLabel=\"no, thanks.\"\no.WindowTitle=\"This is a window title.\"\no.ClientName=\"Client Name?\"\no.AllowFolderSelection=true\no.ShowDialog\n\nc=o.FileCount\nif c>0 then\n for i=0 to c-1\n f=o.Files(i)\n\n FileList.List.AddRow f.AbsolutePath\n next\nend if\n\n\nNotes: \nDefault is false.\nSetting this to true on Windows or Linux has no effect there.\n(Read and Write property)\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10472/" ]
100,247
<p>I'm using C# in .Net 2.0, and I want to read in a PNG image file and check for the first row and first column that has non-transparent pixels. </p> <p>What assembly and/or class should I use?</p>
[ { "answer_id": 100293, "author": "Pavel Chuchuva", "author_id": 14131, "author_profile": "https://Stackoverflow.com/users/14131", "pm_score": 6, "selected": true, "text": "Bitmap bitmap = new Bitmap(@\"C:\\image.png\");\nColor clr = bitmap.GetPixel(0, 0);\n" }, { "answer_id": 3205805, "author": "ArekBulski", "author_id": 386893, "author_profile": "https://Stackoverflow.com/users/386893", "pm_score": 1, "selected": false, "text": "Bitmap bitmap = new Bitmap(\"icn_loading_animated3a.png\");\npictureBox1.Image = bitmap;\nColor pixel5by10 = bitmap.GetPixel(5, 10);\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100247", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18494/" ]
100,248
<p>AFAIK one of the objectives of Stack Overflow is to make sure anyone can come here and find <b>good</b> answers to her Perl related questions. Certainly beginners would ask what is the <a href="https://stackoverflow.com/questions/70573/best-online-%0Asource-to-learn-perl">best online source to learn Perl</a> but others might just want to ask a question.</p> <p>Probably the friendliest place is the <a href="http://perlmonks.org/" rel="nofollow noreferrer">Monastery of Perl Monks</a>. It is a web site with a rating system similar to but more simple than Stack Overflow. You can find lots of good answers there and if you don't find an answer you can always ask.</p> <p>The other big resource would be the mailing list of your local <a href="http://www.pm.org/" rel="nofollow noreferrer">Perl Mongers</a> group.</p> <p>Where do <b>you</b> go when you are looking for an answer to a Perl related question?</p>
[ { "answer_id": 105094, "author": "Drew Stephens", "author_id": 17339, "author_profile": "https://Stackoverflow.com/users/17339", "pm_score": 3, "selected": false, "text": "pd pm" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11827/" ]
100,280
<p>Has any one done this before? It would seem to me that there should be a webservice but i can't find one. I am writing an application for personal use that would just show basic info from IMDB.</p>
[ { "answer_id": 109478, "author": "Nescio", "author_id": 14484, "author_profile": "https://Stackoverflow.com/users/14484", "pm_score": 3, "selected": false, "text": "private const string UglyMovieRegex = \"(?<=5>|3>)(Cast|Director:|Fun\\\\sStuff|Genre:|Plot:|Runtime:|Tagline:|Writers:)\"\n + \"|href=\\\"[\\\\w\\\\d/]+?(Genres|name|character)/([\\\\w]+?)/\\\".*?>([.\\\\-\\\\s\\\\w]+)</a>\"\n + \"|(?<=h\\\\d>)([.\\\\w\\\\s'\\\\-\\\"]+)(?=<a\\\\sc|</d|\\\\|)\";\n\nRegex MovieData = new Regex (UglyMovieRegex, RegexOptions.Compiled | RegexOptions.Multiline | RegexOptions.Singleline );\n" }, { "answer_id": 6495599, "author": "philberndt", "author_id": 589765, "author_profile": "https://Stackoverflow.com/users/589765", "pm_score": 3, "selected": false, "text": "import urllib2\n\nmovie_id = raw_input('Enter the ID of the movie: ')\njson = urllib2.urlopen('http://imdbapi.com/?i=' + movie_id + '&r=json')\n\nprint json.read()\n" }, { "answer_id": 16121228, "author": "mb21", "author_id": 214446, "author_profile": "https://Stackoverflow.com/users/214446", "pm_score": 2, "selected": false, "text": "http://www.imdb.com/xml/find?json=1&q=Harry+Potter" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100280", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5235/" ]
100,284
<p>I'm using the .NET TWAIN code from <a href="http://www.codeproject.com/KB/dotnet/twaindotnet.aspx?msg=1007385#xx1007385xx" rel="nofollow noreferrer">http://www.codeproject.com/KB/dotnet/twaindotnet.aspx?msg=1007385#xx1007385xx</a> in my application. When I try to scan an image when the scanner is not plugged in, the application freezes.</p> <p>How can I check if the device is plugged in, using the TWAIN driver?</p>
[ { "answer_id": 156690, "author": "Veldmuis", "author_id": 18826, "author_profile": "https://Stackoverflow.com/users/18826", "pm_score": 2, "selected": false, "text": "enum AcquireResult\n{\n OK = 0,\n InitFailed = 1,\n DeviceIDFailed = 2,\n CapabilityFailed = 3,\n UserInterfaceError = 4\n}\nprivate void StartScan()\n{\n if (!_msgFilter)\n {\n _parent.Enabled = false;\n _msgFilter = true;\n Application.AddMessageFilter(this);\n }\n AcquireResult ar = _twain.Acquire();\n if (ar != AcquireResult.OK)\n {\n EndingScan();\n switch (ar)\n {\n case AcquireResult.CapabilityFailed:\n throw new Exception(\"Scanner capability setup failed\");\n case AcquireResult.DeviceIDFailed:\n throw new Exception(\"Unable to determine device identity\");\n case AcquireResult.InitFailed:\n throw new Exception(\"Scanner initialisation failed\");\n case AcquireResult.UserInterfaceError:\n throw new Exception(\"Error with the Twain user interface\");\n default:\n throw new Exception(\"Document scanning failed\");\n }\n }\n}\n" }, { "answer_id": 1036297, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "case TwainCommand.Null:\n {\n EndingScan();\n tw.CloseSrc();\n Msgbox(\"There is no device or the scannning has been cancelled.\");\n break;\n }\n" }, { "answer_id": 2705728, "author": "Mariusz Szefera", "author_id": 325058, "author_profile": "https://Stackoverflow.com/users/325058", "pm_score": -1, "selected": false, "text": "timer1.Interval = 30000;\n\nswitch (cmd)\n{\ncase TwainCommand.TransferReady:\n\n{\n..........\n}\n\ndefault:\n\n{\ntimer1.Start();\nbreak;\n}\n {\nEndingScan();\ntw.CloseSrc();\n}\n" }, { "answer_id": 27539782, "author": "Dan Elm", "author_id": 4364737, "author_profile": "https://Stackoverflow.com/users/4364737", "pm_score": 1, "selected": false, "text": "HKEY_LOCAL_MACHINE\\SYSTEM\\CurrentControlSet\\Control\\Class\\{6bdd1fc6-810f-11d0-bec7-08002be2092f} 0000 CreateFileName" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100284", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17465/" ]
100,291
<p>Imagine I have an function which goes through one million/billion strings and checks smth in them.</p> <p>f.ex:</p> <pre><code>foreach (String item in ListOfStrings) { result.add(CalculateSmth(item)); } </code></pre> <p>it consumes lot's of time, because CalculateSmth is very time consuming function.</p> <p>I want to ask: how to integrate multithreading in this kinda process?</p> <p>f.ex: I want to fire-up 5 threads and each of them returns some results, and thats goes-on till the list has items.</p> <p>Maybe anyone can show some examples or articles.. </p> <p>Forgot to mention I need it in .NET 2.0</p>
[ { "answer_id": 100307, "author": "Tobi", "author_id": 5422, "author_profile": "https://Stackoverflow.com/users/5422", "pm_score": 5, "selected": true, "text": "Parallel.Foreach (ListOfStrings, (item) => \n result.add(CalculateSmth(item));\n);\n" }, { "answer_id": 100352, "author": "noocyte", "author_id": 11220, "author_profile": "https://Stackoverflow.com/users/11220", "pm_score": 4, "selected": false, "text": "using System.Collections.Generic;\nusing System.Threading;\n\nnamespace noocyte.Threading\n{\n class CalcState\n {\n public CalcState(ManualResetEvent reset, string input) {\n Reset = reset;\n Input = input;\n }\n public ManualResetEvent Reset { get; private set; }\n public string Input { get; set; }\n }\n\n class CalculateMT\n {\n List<string> result = new List<string>();\n List<ManualResetEvent> events = new List<ManualResetEvent>();\n\n private void Calc() {\n List<string> aList = new List<string>();\n aList.Add(\"test\");\n\n foreach (var item in aList)\n {\n CalcState cs = new CalcState(new ManualResetEvent(false), item);\n events.Add(cs.Reset);\n ThreadPool.QueueUserWorkItem(new WaitCallback(Calculate), cs);\n }\n WaitHandle.WaitAll(events.ToArray());\n }\n\n private void Calculate(object s)\n {\n CalcState cs = s as CalcState;\n cs.Reset.Set();\n result.Add(cs.Input);\n }\n }\n}\n" }, { "answer_id": 100799, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 3, "selected": false, "text": "List<string> work = (some list with lots of strings)\n\n// Split the work in two\nList<string> odd = new List<string>();\nList<string> even = new List<string>();\nfor (int i = 0; i < work.Count; i++)\n{\n if (i % 2 == 0)\n {\n even.Add(work[i]);\n }\n else\n {\n odd.Add(work[i]);\n }\n}\n\n// Set up to worker delegates\nList<Foo> oddResult = new List<Foo>();\nAction oddWork = delegate { foreach (string item in odd) oddResult.Add(CalculateSmth(item)); };\n\nList<Foo> evenResult = new List<Foo>();\nAction evenWork = delegate { foreach (string item in even) evenResult.Add(CalculateSmth(item)); };\n\n// Run two delegates asynchronously\nIAsyncResult evenHandle = evenWork.BeginInvoke(null, null);\nIAsyncResult oddHandle = oddWork.BeginInvoke(null, null);\n\n// Wait for both to finish\nevenWork.EndInvoke(evenHandle);\noddWork.EndInvoke(oddHandle);\n\n// Merge the results from the two jobs\nList<Foo> allResults = new List<Foo>();\nallResults.AddRange(oddResult);\nallResults.AddRange(evenResult);\n\nreturn allResults;\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100291", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5369/" ]
100,298
<p>I have a large source repository split across multiple projects. I would like to produce a report about the health of the source code, identifying problem areas that need to be addressed.</p> <p>Specifically, I'd like to call out routines with a high cyclomatic complexity, identify repetition, and perhaps run some lint-like static analysis to spot suspicious (and thus likely erroneous) constructs.</p> <p>How might I go about constructing such a report?</p>
[ { "answer_id": 14793812, "author": "Dave Halter", "author_id": 552671, "author_profile": "https://Stackoverflow.com/users/552671", "pm_score": 5, "selected": false, "text": "radon pip pip install radon" }, { "answer_id": 39937878, "author": "Asclepius", "author_id": 832230, "author_profile": "https://Stackoverflow.com/users/832230", "pm_score": 2, "selected": false, "text": "mccabe $ pip install --upgrade mccabe\n $ python -m mccabe --min=6 path/to/myfile.py\n --min=3 68:1: 'Fetcher.fetch' 3\n48:1: 'Fetcher._read_dom_tag' 3\n103:1: 'main' 3\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100298", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14648/" ]
100,304
<p>I'm facing a problem on the Win32 API. I have a program that, when it handles <code>WM_PAINT</code> messages, it calls <code>BeginPaint</code> to clip the region and validate the update region, but the <code>BeginPaint</code> function is always generating a <code>WM_NCPAINT</code> message with the same update region, even if the touched part that needs repainting is only inside the client region. </p> <p>Do anyone has any clue why this is happening? It's on child windows with the <code>WS_CHILD</code> style.</p>
[ { "answer_id": 100340, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 0, "selected": false, "text": "WM_NCPAINT" }, { "answer_id": 100412, "author": "Edwin Jarvis", "author_id": 18623, "author_profile": "https://Stackoverflow.com/users/18623", "pm_score": 1, "selected": false, "text": "WM_NCPAINT WM_ERASEBKGND BeginPaint() WM_NCPAINT" }, { "answer_id": 100973, "author": "prakash", "author_id": 123, "author_profile": "https://Stackoverflow.com/users/123", "pm_score": 0, "selected": false, "text": "SetWindowPos SWP_DEFERERASE uFlags WM_SYNCPAINT WM_NCPAINT" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100304", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18623/" ]
100,332
<p>I'm trying to decide on the best way to store event times in a MySQL database. These should be as flexible as possible and be able to represent "single events" (starts at a certain time, does not necessarily need an end time), "all day" and "multi day" events, repeating events, repeating all day events, possibly "3rd Saturday of the month" type events etc.</p> <p>Please suggest some tried and proven database schemes.</p>
[ { "answer_id": 100453, "author": "boes", "author_id": 17746, "author_profile": "https://Stackoverflow.com/users/17746", "pm_score": 1, "selected": false, "text": "create table repeatevent (\nid int not null auto_increment, \ntype int, // 0: daily, 1:weekly, 2: monthly, ....\nstarttime datetime not null, // starttime of the first event of the repetition\nendtime datetime, // endtime of the first event of the repetition\nallday int, // 0: no, 1: yes\nuntil datetime, // endtime of the last event of the repetition\ndescription varchar(30)\n)\n\ncreate table event (\nid int not null auto_increment,\nrepeatevent null references repeatevent, // filled if created as part of a repeating event\nstarttime datetime not null,\nendtime datetime,\nallday int,\ndescription varchar(30)\n)\n" }, { "answer_id": 100619, "author": "Jeffrey04", "author_id": 5742, "author_profile": "https://Stackoverflow.com/users/5742", "pm_score": 2, "selected": false, "text": "event (event_id, # primary key\n dtstart,\n dtend,\n summary,\n categories,\n class,\n priority,\n summary,\n transp,\n created,\n calendar_id, # foreign key\n status,\n organizer_id, # foreign key\n comment,\n last_modified,\n location,\n uid);\n calendar_id calendar(calendar_id, # primary key\n name);\n organizer_id organizer(organizer_id, # primary key\n name); \n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100332", "https://Stackoverflow.com", "https://Stackoverflow.com/users/476/" ]
100,333
<p>How can you programmatically measure per-process (or better, per-thread) CPU usage under windows 95, windows 98 and windows ME?</p> <p>If it requires the DDK, where can you obtain that?</p> <p>Please note the <strong>Win9x requirement</strong>. It's easy on NT.</p> <p>EDIT: I tried installing the <a href="http://www.microsoft.com/downloads/details.aspx?familyid=98a4c5ba-337b-4e92-8c18-a63847760ea5&amp;displaylang=en" rel="nofollow noreferrer">Win95/98 version of WMI</a>, but <a href="http://msdn.microsoft.com/en-us/library/aa394372(VS.85).aspx" rel="nofollow noreferrer">Win32_Process</a>.<code>KernelModeTime</code> and <code>Win32_Process.UserModeTime</code> return <code>Null</code> (as do most <code>Win32_Process</code> properties under win9x).</p>
[ { "answer_id": 100453, "author": "boes", "author_id": 17746, "author_profile": "https://Stackoverflow.com/users/17746", "pm_score": 1, "selected": false, "text": "create table repeatevent (\nid int not null auto_increment, \ntype int, // 0: daily, 1:weekly, 2: monthly, ....\nstarttime datetime not null, // starttime of the first event of the repetition\nendtime datetime, // endtime of the first event of the repetition\nallday int, // 0: no, 1: yes\nuntil datetime, // endtime of the last event of the repetition\ndescription varchar(30)\n)\n\ncreate table event (\nid int not null auto_increment,\nrepeatevent null references repeatevent, // filled if created as part of a repeating event\nstarttime datetime not null,\nendtime datetime,\nallday int,\ndescription varchar(30)\n)\n" }, { "answer_id": 100619, "author": "Jeffrey04", "author_id": 5742, "author_profile": "https://Stackoverflow.com/users/5742", "pm_score": 2, "selected": false, "text": "event (event_id, # primary key\n dtstart,\n dtend,\n summary,\n categories,\n class,\n priority,\n summary,\n transp,\n created,\n calendar_id, # foreign key\n status,\n organizer_id, # foreign key\n comment,\n last_modified,\n location,\n uid);\n calendar_id calendar(calendar_id, # primary key\n name);\n organizer_id organizer(organizer_id, # primary key\n name); \n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15069/" ]
100,365
<p>In cake 1.2 there is a feature that allows the developer to no have to create models, but rather have cake do the detective work at run time and create the model for you. This process happens each time and is neat but in my case very hazardous. I read about this somewhere and now I'm experiencing the bad side of this.</p> <p>I've created a plugin with all the files and everything appeared to be just great. That is until i tried to use some of the model's associations and functions. Then cake claims that this model i've created doesn't exist. <strong>I've narrowed it down to cake using this auto model feature instead of throwing and error</strong>! So i have no idea what's wrong!</p> <p>Does anybody know how to disable this auto model feature? It's a good thought, but I can't seem to find where i've gone wrong with my plugin and an error would be very helpful!</p>
[ { "answer_id": 100442, "author": "Mladen Mihajlovic", "author_id": 11421, "author_profile": "https://Stackoverflow.com/users/11421", "pm_score": 1, "selected": false, "text": "var $useTable = false;\n" }, { "answer_id": 106985, "author": "SeanDowney", "author_id": 5261, "author_profile": "https://Stackoverflow.com/users/5261", "pm_score": 3, "selected": true, "text": "if (App::import($type, $plugin . $class)) {\n ${$class} =& new $class($options);\n} elseif ($type === 'Model') {\n /* Print out whatever debug info we have then exit */\n pr($objects);\n die(\"unable to find class $type, $plugin$class\");\n /* We don't want to base this on the app model */\n ${$class} =& new AppModel($options);\n}\n Cake\\Utility\\ClassRegistry.php" }, { "answer_id": 764114, "author": "dr Hannibal Lecter", "author_id": 78928, "author_profile": "https://Stackoverflow.com/users/78928", "pm_score": 0, "selected": false, "text": "* classname: BlastsController\n* filename: blasts_controller.php\n * classname: Blast\n* filename: blast.php\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
100,376
<p>Anyone know how to do picture overlay or appear on top of each other in HTML? The effect will be something like the marker/icon appear on Google Map where the user can specify the coordinate of the second picture appear on the first picture.</p> <p>Thanks.</p>
[ { "answer_id": 100417, "author": "Johannes Hädrich", "author_id": 18246, "author_profile": "https://Stackoverflow.com/users/18246", "pm_score": 6, "selected": true, "text": "<div> <div style=\"position: absolute; z-index:100\">This is in background</div> \n<div style=\"position: absolute; z-index:5000\">This is in foreground</div> \n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100376", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14790/" ]
100,411
<p>I have two webapplication, one is a simple authenticationsite which can authenticate the logged in user and <strong>redirects</strong> him then to another site.</p> <p>Therefore I have to pass ther userId (GUID) to the second application. Currently this is done via the URL but i would like to hide this id.</p> <p>Has anybody an idea how to do this properly?</p> <p>[EDIT]: I can't use the Session because of the ApplicationBoundaries (2 different Servers)</p>
[ { "answer_id": 144624, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 2, "selected": false, "text": "using System;\nusing System.Web;\nusing System.Web.Services;\nusing System.Web.Services.Protocols;\n\n[WebService(Namespace = \"http://tempuri.org/\")]\n[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]\npublic class AuthenticateUserService : System.Web.Services.WebService \n{ \n [WebMethod]\n public bool AuthenticateUser(string username, string passhash) \n {\n // Fake authentication for the example\n return (username == \"jon\" && passhash == \"SomeHashedValueOfFoobar\");\n }\n \n}\n protected void Page_Load(object sender, EventArgs e)\n{\n // Now we can easily authenticate user in our code\n AuthenticateUserService authenticationProxy = \n new AuthenticateUserService();\n bool isUserAuthenticated = \n authenticationProxy.AuthenticateUser(\"jon\", SomeHashMethod(\"foobar\"));\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100411", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17558/" ]
100,415
<p>I'm looking for an open source, cross platform (Windows &amp; Linux at least) command line tool to take some code (C++, but multiple languages would be sweet), and spit out valid a XHTML representation of that code, with syntax highlighting included.</p> <p>Ideally the XHTML should just wrap the code with <code>&lt;span&gt;</code> and <code>&lt;div&gt;</code> tags with different classes so I can supply the CSS code and change the colouration, but that's an optional extra.</p> <p>Does anyone know of such an application?</p>
[ { "answer_id": 900463, "author": "Martin Geisler", "author_id": 110204, "author_profile": "https://Stackoverflow.com/users/110204", "pm_score": 4, "selected": true, "text": "<span> from pygments import highlight\nfrom pygments.lexers import PythonLexer\nfrom pygments.formatters import HtmlFormatter\n\ncode = 'print \"Hello World\"'\nprint highlight(code, PythonLexer(), HtmlFormatter())\n <div class=\"highlight\">\n<pre><span class=\"k\">print</span> <span class=\"s\">&quot;Hello World&quot;</span></pre>\n</div>\n pygmentize" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100415", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1304/" ]
100,416
<p>In SQL Server 2000/2005,</p> <p>Is it possible to force the default value to be written to already existing rows when adding a new column to a table <strong>without</strong> using NOT NULL on the new column?</p>
[ { "answer_id": 100560, "author": "chrisb", "author_id": 8262, "author_profile": "https://Stackoverflow.com/users/8262", "pm_score": 1, "selected": false, "text": "UPDATE MyTable SET NullCol = N'some_value' WHERE NullCol IS NULL\nALTER TABLE MyTable ALTER COLUMN NullCOl NVARCHAR(20) NOT NULL\n" }, { "answer_id": 100563, "author": "boes", "author_id": 17746, "author_profile": "https://Stackoverflow.com/users/17746", "pm_score": 4, "selected": true, "text": "alter table mytable add mycolumn varchar(10) not null default ('a value')\nalter table mytable alter column mycolumn varchar(10) null\n" }, { "answer_id": 36855554, "author": "sandeep rawat", "author_id": 6085803, "author_profile": "https://Stackoverflow.com/users/6085803", "pm_score": 0, "selected": false, "text": "ALTER TABLE {TABLENAME} \n ADD {COLUMNNAME} {TYPE} {NULL|NOT NULL} \n CONSTRAINT {CONSTRAINT_NAME} DEFAULT {DEFAULT_VALUE}\n [**WITH VALUES]**" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100416", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7241/" ]
100,420
<p>Visual Studio is such a massively big product that even after years of working with it I sometimes stumble upon a new/better way to do things or things I didn't even know were possible.</p> <p>For instance-</p> <ul> <li><p><kbd>Crtl</kbd> + <kbd>R</kbd>, <kbd>Ctrl</kbd> + <kbd>W</kbd> to show white spaces. Essential for editing Python build scripts.</p></li> <li><p>Under <code>"HKEY_CURRENT_USER\Software\Microsoft\VisualStudio\8.0\Text Editor"</code> Create a String called <a href="https://stackoverflow.com/questions/84209/vertical-line-after-a-certain-amount-characters-in-visual-studio">Guides</a> with the value "RGB(255,0,0), 80" to have a red line at column 80 in the text editor.</p></li> </ul> <p>What other hidden features have you stumbled upon?</p>
[ { "answer_id": 100445, "author": "Mark Glorie", "author_id": 952, "author_profile": "https://Stackoverflow.com/users/952", "pm_score": 6, "selected": false, "text": "CTRL-K, CTRL-D\n" }, { "answer_id": 100457, "author": "Aaron Powell", "author_id": 11388, "author_profile": "https://Stackoverflow.com/users/11388", "pm_score": 6, "selected": false, "text": "using" }, { "answer_id": 100582, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "control + alt + f4" }, { "answer_id": 125717, "author": "Muxa", "author_id": 10793, "author_profile": "https://Stackoverflow.com/users/10793", "pm_score": 4, "selected": false, "text": "Ctrl + .\n" }, { "answer_id": 176763, "author": "Ferruccio", "author_id": 4086, "author_profile": "https://Stackoverflow.com/users/4086", "pm_score": 5, "selected": false, "text": "@err - display last error\n@err,hr - display last error as an HRESULT\n@exception - display current exception\n" }, { "answer_id": 276393, "author": "Emerick Rogul", "author_id": 33837, "author_profile": "https://Stackoverflow.com/users/33837", "pm_score": 3, "selected": false, "text": "variable, n\n foo foo, 256\n" }, { "answer_id": 361295, "author": "LarryF", "author_id": 18518, "author_profile": "https://Stackoverflow.com/users/18518", "pm_score": 2, "selected": false, "text": " Sub OpenASPOrCS()\n 'DESCRIPTION: Open .aspx file if in .cs file, open .cs file if in .aspx file\n On Error Resume Next\n\n ' Get current doc path\n Dim FullName\n FullName = LCase(ActiveDocument.FullName)\n If FullName = \"\" Then\n MsgBox(\"Error, not a .cs or asp file!\")\n Exit Sub\n End If\n\n ' Get current doc name\n Dim DocName\n DocName = ActiveDocument.Name\n\n Dim IsCSFile\n IsCSFile = False\n Dim fn\n Dim dn\n If (Right(FullName, 3) = \".cs\") Then\n fn = Left(FullName, Len(FullName) - 3)\n dn = Left(DocName, Len(DocName) - 3)\n IsCSFile = True\n ElseIf ((Right(FullName, 5) = \".aspx\") Or (Right(FullName, 5) = \".ascx\")) Then\n fn = FullName + \".cs\"\n dn = DocName + \".cs\"\n Else\n MsgBox(\"Error, not a .cs, or an asp file!\")\n Exit Sub\n End If\n\n Dim doc As EnvDTE.Documents\n\n DTE.ItemOperations.OpenFile(fn)\n doc.DTE.ItemOperations.OpenFile(fn)\n\n If Err.Number = 0 Then\n Exit Sub\n End If\n\n ' First check to see if the file is already open and activate it\n For Each doc In DTE.Documents()\n If doc.Name = dn Then\n doc.Active = True\n Exit Sub\n End If\n Next\n\nEnd Sub\n" }, { "answer_id": 525432, "author": "ebattulga", "author_id": 60200, "author_profile": "https://Stackoverflow.com/users/60200", "pm_score": 5, "selected": false, "text": "foreach foreach (object var in collection_to_loop)\n{\n\n}\n Button btn = new Button();\n btn.Click += \n private void Form1_Load(object sender, EventArgs e)\n{\n Button btn = new Button();\n btn.Click += new EventHandler(btn_Click); \n} \nvoid btn_Click(object sender, EventArgs e)\n{\n throw new Exception(\"The method or operation is not implemented.\");\n}\n MouseLeftButtonDown MouseLeftButtonDown=\"\" MouseLeftButtonDown=\"Button_MouseLeftButtonDown\" Button_MouseLeftButtonDown" }, { "answer_id": 1270854, "author": "Pavel Minaev", "author_id": 111335, "author_profile": "https://Stackoverflow.com/users/111335", "pm_score": 3, "selected": false, "text": "1# 1# this==1#" }, { "answer_id": 1355835, "author": "Noon Silk", "author_id": 154152, "author_profile": "https://Stackoverflow.com/users/154152", "pm_score": 3, "selected": false, "text": "ctrl-alt + mouse select\n alt + mouse select\n" }, { "answer_id": 1355852, "author": "Noon Silk", "author_id": 154152, "author_profile": "https://Stackoverflow.com/users/154152", "pm_score": 2, "selected": false, "text": "Condition (b == 0)\n" }, { "answer_id": 1422186, "author": "Pierre-Alain Vigeant", "author_id": 151488, "author_profile": "https://Stackoverflow.com/users/151488", "pm_score": 2, "selected": false, "text": "$exception" }, { "answer_id": 1707657, "author": "Himadri", "author_id": 173655, "author_profile": "https://Stackoverflow.com/users/173655", "pm_score": 0, "selected": false, "text": "protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)\n {\n //if (e.CommandName == \"sel\")\n //{\n // lblCat.Text = e.CommandArgument.ToString();\n //}\n }\n e.CommandName == \"sel\"\n\nlblCat.Text = e.Comman\n" }, { "answer_id": 2156804, "author": "Brian", "author_id": 18192, "author_profile": "https://Stackoverflow.com/users/18192", "pm_score": 2, "selected": false, "text": "$exception $user" }, { "answer_id": 3045569, "author": "Jose", "author_id": 101689, "author_profile": "https://Stackoverflow.com/users/101689", "pm_score": 1, "selected": false, "text": "Ctrl + left arrow/right arrow Ctrl + Shift + left/right arrow" }, { "answer_id": 3346978, "author": "apoorv020", "author_id": 354573, "author_profile": "https://Stackoverflow.com/users/354573", "pm_score": 2, "selected": false, "text": "Ctrl+E , Ctrl+C/U Edit.IncreaseLineIndent/Edit.DecreaseLineIndent" }, { "answer_id": 6169433, "author": "cpx", "author_id": 187543, "author_profile": "https://Stackoverflow.com/users/187543", "pm_score": 0, "selected": false, "text": "devenv /nosplash" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100420", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9611/" ]
100,435
<p>I'm using a ASP.NET menu control. I'd like the menu to look like this, where link 1 through 10 are in one sitemap file and link 11 through 20 in another. </p> <pre><code>root --link 1 (...) --link 10 --link 11 (...) --link 20 </code></pre> <p>However, sitemap file MUST have a root which I cannot seem to suppress.</p> <p>Any thoughts?</p> <p>-Edoode</p>
[ { "answer_id": 849136, "author": "Tim Scarborough", "author_id": 432226, "author_profile": "https://Stackoverflow.com/users/432226", "pm_score": 2, "selected": false, "text": "SiteMapDataSource ds = new SiteMapDataSource();\nds.SiteMapProvider = \"providername\";\nds.ShowStartingNode = false;\nTreeView1.DataSource = ds;\nTreeView1.DataBind();\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100435", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6399/" ]
100,444
<p>I'm trying to automate a gdb session using the <code>--command</code> flag. I'm trying to set a breakpoint on a function in a shared library (the Unix equivalent of a DLL) . My cmds.gdb looks like this:</p> <pre><code>set args /home/shlomi/conf/bugs/kde/font-break.txt b IA__FcFontMatch r </code></pre> <p>However, I'm getting the following:</p> <pre> shlomi:~/progs/bugs-external/kde/font-breaking$ gdb --command=cmds.gdb... GNU gdb 6.8-2mdv2009.0 (Mandriva Linux release 2009.0) Copyright (C) 2008 Free Software Foundation, Inc. License GPLv3+: GNU GPL version 3 or later This is free software: you are free to change and redistribute it. There is NO WARRANTY, to the extent permitted by law. Type "show copying" and "show warranty" for details. This GDB was configured as "i586-mandriva-linux-gnu"... (no debugging symbols found) Function "IA__FcFontMatch" not defined. Make breakpoint pending on future shared library load? (y or [n]) [answered N; input not from terminal] </pre> <p>So it doesn't set the breakpoint after all. How can I make it default to answer "y" to set breakpoints on pending future shared library load?</p> <p>I recall that I was able to do something, but cannot recall what.</p>
[ { "answer_id": 100501, "author": "Shlomi Fish", "author_id": 7709, "author_profile": "https://Stackoverflow.com/users/7709", "pm_score": 8, "selected": true, "text": "cmds.gdb set breakpoint pending on\nbreak <source file name>:<line number>\n" }, { "answer_id": 1123235, "author": "RandomNickName42", "author_id": 67819, "author_profile": "https://Stackoverflow.com/users/67819", "pm_score": 3, "selected": false, "text": "objdump -t /lib/libacl.so\nSYMBOL TABLE:\nno symbols\nobjdump -T /lib/libacl.so\n...\n00002bd0 g DF .text 000000d0 ACL_1.0 acl_delete_entry\n...\n\n\n(gdb) break 0x0002bd0 \n\n(gdb) x/20i acl_delete_entry\n0x2bd0 <acl_delete_entry>: stwu r1,-32(r1)\n0x2bd4 <acl_delete_entry+4>: mflr r0\n0x2bd8 <acl_delete_entry+8>: stw r29,20(r1)\n0x2bdc <acl_delete_entry+12>: stw r30,24(r1)\n0x2be0 <acl_delete_entry+16>: mr r29,r4\n0x2be4 <acl_delete_entry+20>: li r4,28972\n" }, { "answer_id": 11568944, "author": "äxl", "author_id": 1539082, "author_profile": "https://Stackoverflow.com/users/1539082", "pm_score": 4, "selected": false, "text": "gdb -ex \"set breakpoint pending on\" -ex \"break gdk_x_error\" -ex run --args caja --sync\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100444", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7709/" ]
100,454
<p>Does anybody know the logic behind making DataSourceSelectArguments sealed?</p> <p>I've implemented a custom DataSource (and related classes) for some custom business objects and custom WebControls. When thinking in filters (like in a grid) I discovered that the DataSourceSelectArguments is sealed. Surely, I'm missing something. (Maybe the logic is related to the fact that is nonsense to ask the DB again, just for filtering?, just a guess.)</p>
[ { "answer_id": 148825, "author": "paudirac", "author_id": 15554, "author_profile": "https://Stackoverflow.com/users/15554", "pm_score": 1, "selected": false, "text": "ListView PerformSelect DataSourceView ExecuteSelect DataSourceSelectArguments ListView DataSourceView" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100454", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15554/" ]
100,480
<p>I am looking for different ways to pause and resume programmatically a particular process via its process ID under Windows XP.</p> <p><a href="http://www.codeproject.com/KB/threads/pausep.aspx" rel="noreferrer">Process suspend/resume tool</a> does it with <code>SuspendThread</code> / <code>ResumeThread</code> but warns about multi-threaded programs and deadlock problems.</p> <p><a href="http://technet.microsoft.com/en-us/sysinternals/bb897540.aspx" rel="noreferrer">PsSuspend</a> looks okay, but I wonder if it does anything special about deadlocks or uses another method?</p> <p>Prefered languages : C++ / Python</p>
[ { "answer_id": 102214, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 3, "selected": false, "text": "logger.exe windbg.exe SuspendThread() ResumeThread()" }, { "answer_id": 14053933, "author": "Hanan N.", "author_id": 963318, "author_profile": "https://Stackoverflow.com/users/963318", "pm_score": 2, "selected": false, "text": ">>> import psutil\n>>> pid = 7012\n>>> p = psutil.Process(pid)\n>>> p.suspend()\n>>> p.resume()\n" }, { "answer_id": 61371356, "author": "Wis", "author_id": 4178053, "author_profile": "https://Stackoverflow.com/users/4178053", "pm_score": 1, "selected": false, "text": "_NtSuspendProcess _NtResumeProcess _HungWindowFromGhostWindow _NtSuspendProcess(ProcessHandle) _NtResumeProcess(ProcessHandle) ProcessHandle" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18648/" ]
100,504
<p>Say I have a table called myTable. What is the SQL command to return all of the field names of this table? If the answer is database specific then I need SQL Server right now but would be interested in seeing the solution for other database systems as well.</p>
[ { "answer_id": 100513, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 7, "selected": true, "text": "desc tablename\n show fields from tablename\n select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS \nwhere TABLE_NAME = 'tablename'\n sp_help exec sp_help 'tablename'\n" }, { "answer_id": 100515, "author": "Matt Howells", "author_id": 16881, "author_profile": "https://Stackoverflow.com/users/16881", "pm_score": 1, "selected": false, "text": "select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tablename'\n sp_help 'tablename'\n" }, { "answer_id": 100526, "author": "hollystyles", "author_id": 2083160, "author_profile": "https://Stackoverflow.com/users/2083160", "pm_score": 4, "selected": false, "text": "select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'myTable'\n exec sp_help 'myTable'\n select [name] from dbo.syscolumns where id = object_id(N'[dbo].[myTable]')\n" }, { "answer_id": 100529, "author": "Veynom", "author_id": 11670, "author_profile": "https://Stackoverflow.com/users/11670", "pm_score": 1, "selected": false, "text": "select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tablename'\n" }, { "answer_id": 100534, "author": "jules", "author_id": 18655, "author_profile": "https://Stackoverflow.com/users/18655", "pm_score": 2, "selected": false, "text": "select * from INFORMATION_SCHEMA.COLUMNS\nwhere table_name = '[table name]'\n sp_help '[table name]'\n" }, { "answer_id": 100585, "author": "Steve Obbayi", "author_id": 11190, "author_profile": "https://Stackoverflow.com/users/11190", "pm_score": 2, "selected": false, "text": "show fields from [tablename];\n" }, { "answer_id": 100792, "author": "Z99", "author_id": 18307, "author_profile": "https://Stackoverflow.com/users/18307", "pm_score": 0, "selected": false, "text": "describe tablename\n" }, { "answer_id": 100848, "author": "Rene", "author_id": 17323, "author_profile": "https://Stackoverflow.com/users/17323", "pm_score": 2, "selected": false, "text": "SELECT column_name FROM user_tab_columns WHERE table_name = 'TABLENAME'\n" }, { "answer_id": 101458, "author": "dland", "author_id": 18625, "author_profile": "https://Stackoverflow.com/users/18625", "pm_score": 2, "selected": false, "text": "select column_name from information_schema.columns where table_name = 'myTable'\n \\d myTable\n" }, { "answer_id": 104877, "author": "8jean", "author_id": 10011, "author_profile": "https://Stackoverflow.com/users/10011", "pm_score": 2, "selected": false, "text": "pragma table_info() sqlite> pragma table_info('table_name');\ncid name type notnull dflt_value pk \n---------- ---------- ---------- ---------- ---------- ----------\n0 id integer 99 1 \n1 name 0 0 \n" }, { "answer_id": 104923, "author": "Graeme Perrow", "author_id": 1821, "author_profile": "https://Stackoverflow.com/users/1821", "pm_score": 2, "selected": false, "text": "select c.column_name from systabcol c \n key join systab t on t.table_id=c.table_id \n where t.table_name='tablename'\n" }, { "answer_id": 108464, "author": "brabster", "author_id": 2362, "author_profile": "https://Stackoverflow.com/users/2362", "pm_score": 1, "selected": false, "text": "SELECT TABNAME,COLNAME from SYSCAT.COLUMNS where TABNAME='MYTABLE'\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100504", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1856916/" ]
100,533
<p>Is it possible to do like this:</p> <pre><code>interface IDBBase { DataTable getDataTableSql(DataTable curTable,IDbCommand cmd); ... } class DBBase : IDBBase { public DataTable getDataTableSql(DataTable curTable, SqlCommand cmd) { ... } } </code></pre> <p>I want to use the interface to implement to d/t providers (MS-SQL,Oracle...); in it there are some signatures to be implemented in the corresponding classes that implement it. I also tried like this:</p> <pre><code>genClass&lt;typeOj&gt; { typeOj instOj; public genClass(typeOj o) { instOj=o; } public typeOj getType() { return instOj; } </code></pre> <p>...</p> <pre><code>interface IDBBase { DataTable getDataTableSql(DataTable curTable,genClass&lt;idcommand&gt; cmd); ... } class DBBase : IDBBase { public DataTable getDataTableSql(DataTable curTable, genClass&lt;SqlCommand&gt; cmd) { ... } } </code></pre>
[ { "answer_id": 100562, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 2, "selected": false, "text": "interface IDBClass<T> where T:IDbCommand\n{\n void Test(T cmd);\n}\n\nclass DBClass:IDBClass<SqlCommand>\n{\n public void Test(SqlCommand cmd)\n {\n }\n}\n" }, { "answer_id": 100570, "author": "Brannon", "author_id": 5745, "author_profile": "https://Stackoverflow.com/users/5745", "pm_score": 1, "selected": false, "text": "DBBase IDBBase" }, { "answer_id": 100575, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 1, "selected": false, "text": "interface Interface1 { }\nclass Class1 : Interface1 {}\n\ninterface Interface2 { void Foo(Interface1 i1);}\nclass Class2 : Interface2 {void Foo(Class1 c1) {}}\n" }, { "answer_id": 100576, "author": "Ilya Ryzhenkov", "author_id": 18575, "author_profile": "https://Stackoverflow.com/users/18575", "pm_score": 2, "selected": false, "text": "class DBBase : IDBBase {\n\n DataTable IDBBase.getDataTableSql(DataTable curTable, IDbCommand cmd) {\n return getDataTableSql(curTable, (SqlCommand)cmd); // of course you should do some type checks\n }\n\n public DataTable getDataTableSql(DataTable curTable, SqlCommand cmd) {\n ...\n }\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100533", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
100,543
<p>On a class library project, I set the "Start Action" on the Debug tab of the project properties to "Start external program" (<a href="http://en.wikipedia.org/wiki/NUnit" rel="noreferrer">NUnit</a> in this case). I want to set an environment variable in the environment this program is started in. How do I do that? (Is it even possible?)</p> <p>EDIT:</p> <p>It's an environment variable that influences all .NET applications (COMplus_Version, it sets the runtime version) so setting it system wide really isn't an option.</p> <p>As a workaround I just forced NUnit to start in right .NET version (2.0) by setting it in <code>nunit.exe.config</code>, though unfortunately this also means all my .NET 1.1 unit tests are now also run in .NET 2.0. I should probably just make a copy of the executable so it can have its own configuration file...</p> <p>(I am keeping the question open (not accepting an answer) in case someone does happen to find out how (it might be useful for other purposes too after all...))</p>
[ { "answer_id": 1140232, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "_putenv() main() #if defined DEBUG_MODE / #endif _putenv(\"MYANSWER=42\");\n os.putenv('MYANSWER', '42');\n" }, { "answer_id": 9204703, "author": "tymtam", "author_id": 581076, "author_profile": "https://Stackoverflow.com/users/581076", "pm_score": 2, "selected": false, "text": "nunit-console myassembly.dll /framework:net-1.1\n" }, { "answer_id": 42321310, "author": "CRUZ", "author_id": 6814649, "author_profile": "https://Stackoverflow.com/users/6814649", "pm_score": 4, "selected": false, "text": "Environment.SetEnvironmentVariable(\"<Variable_name>\", \"<Value>\"); using System.Collections;\n foreach (DictionaryEntry de in Environment.GetEnvironmentVariables())\n Console.WriteLine(\" {0} = {1}\", de.Key, de.Value);\n" }, { "answer_id": 66760576, "author": "Wouter Vanherck", "author_id": 6761698, "author_profile": "https://Stackoverflow.com/users/6761698", "pm_score": 3, "selected": false, "text": "Properties Debug Environment variables Development Production ASPNETCORE_ENVIRONMENT" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100543", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5422/" ]
100,624
<p>How to wait for multiple child processes in Python on Windows, without active wait (polling)? Something like this <em>almost</em> works for me:</p> <pre><code>proc1 = subprocess.Popen(['python','mytest.py']) proc2 = subprocess.Popen(['python','mytest.py']) proc1.wait() print "1 finished" proc2.wait() print "2 finished" </code></pre> <p>The problem is that when <code>proc2</code> finishes before <code>proc1</code>, the parent process will still wait for <code>proc1</code>. On Unix one would use <code>waitpid(0)</code> in a loop to get the child processes' return codes as they finish - how to achieve something like this in Python on Windows?</p>
[ { "answer_id": 100886, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 5, "selected": true, "text": "import Queue, thread, subprocess\n\nresults= Queue.Queue()\ndef process_waiter(popen, description, que):\n try: popen.wait()\n finally: que.put( (description, popen.returncode) )\nprocess_count= 0\n\nproc1= subprocess.Popen( ['python', 'mytest.py'] )\nthread.start_new_thread(process_waiter,\n (proc1, \"1 finished\", results))\nprocess_count+= 1\n\nproc2= subprocess.Popen( ['python', 'mytest.py'] )\nthread.start_new_thread(process_waiter,\n (proc2, \"2 finished\", results))\nprocess_count+= 1\n\n# etc\n\nwhile process_count > 0:\n description, rc= results.get()\n print \"job\", description, \"ended with rc =\", rc\n process_count-= 1\n" }, { "answer_id": 149327, "author": "user23475", "author_id": 23475, "author_profile": "https://Stackoverflow.com/users/23475", "pm_score": 2, "selected": false, "text": "import win32process\nimport win32event\n\n# Note: CreateProcess() args are somewhat cryptic, look them up on MSDN\nproc1, thread1, pid1, tid1 = win32process.CreateProcess(...)\nproc2, thread2, pid2, tid2 = win32process.CreateProcess(...)\nthread1.close()\nthread2.close()\n\nprocesses = {proc1: \"proc1\", proc2: \"proc2\"}\n\nwhile processes:\n handles = processes.keys()\n # Note: WaitForMultipleObjects() supports at most 64 processes at a time\n index = win32event.WaitForMultipleObjects(handles, False, win32event.INFINITE)\n finished = handles[index]\n exitcode = win32process.GetExitCodeProcess(finished)\n procname = processes.pop(finished)\n finished.close()\n print \"Subprocess %s finished with exit code %d\" % (procname, exitcode)\n" }, { "answer_id": 573196, "author": "Ted Mielczarek", "author_id": 69326, "author_profile": "https://Stackoverflow.com/users/69326", "pm_score": 3, "selected": false, "text": "import ctypes, subprocess\nfrom random import randint\nSYNCHRONIZE=0x00100000\nINFINITE = -1\nnumprocs = 5\nhandles = {}\n\nfor i in xrange(numprocs):\n sleeptime = randint(5,10)\n p = subprocess.Popen([r\"c:\\msys\\1.0\\bin\\sleep.exe\", str(sleeptime)], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, shell=False)\n h = ctypes.windll.kernel32.OpenProcess(SYNCHRONIZE, False, p.pid)\n handles[h] = p.pid\n print \"Spawned Process %d\" % p.pid\n\nwhile len(handles) > 0:\n print \"Waiting for %d children...\" % len(handles)\n arrtype = ctypes.c_long * len(handles)\n handle_array = arrtype(*handles.keys())\n ret = ctypes.windll.kernel32.WaitForMultipleObjects(len(handle_array), handle_array, False, INFINITE)\n h = handle_array[ret]\n ctypes.windll.kernel32.CloseHandle(h)\n print \"Process %d done\" % handles[h]\n del handles[h]\nprint \"All done!\"\n" }, { "answer_id": 20292161, "author": "Giampaolo Rodolà", "author_id": 376587, "author_profile": "https://Stackoverflow.com/users/376587", "pm_score": 2, "selected": false, "text": ">>> import subprocess\n>>> import psutil\n>>> \n>>> proc1 = subprocess.Popen(['python','mytest.py'])\n>>> proc2 = subprocess.Popen(['python','mytest.py']) \n>>> ls = [psutil.Process(proc1.pid), psutil.Process(proc2.pid)]\n>>>\n>>> gone, alive = psutil.wait_procs(ls, timeout=3)\n >>> def on_terminate(proc):\n... print \"%s terminated\" % proc\n...\n>>> gone, alive = psutil.wait_procs(ls, timeout=3, callback=on_terminate)\n" }, { "answer_id": 64832681, "author": "Thomas Grainger", "author_id": 833093, "author_profile": "https://Stackoverflow.com/users/833093", "pm_score": 1, "selected": false, "text": "import psutil\n\nwith psutil.Popen([\"python\", \"mytest.py\"]) as proc1, psutil.Popen(\n [\"python\", \"mytest.py\"]\n) as proc2:\n gone, alive = psutil.wait_procs([proc1, proc2], timeout=3)\n def on_terminate(proc):\n print \"%s terminated\" % proc\n\ngone, alive = psutil.wait_procs(ls, timeout=3, callback=on_terminate)\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12166/" ]
100,631
<p>After our Ruby on Rails application has run for a while, it starts throwing 500s with "MySQL server has gone away". Often this happens overnight. It's started doing this recently, with no obvious change in our server configuration.</p> <pre><code> Mysql::Error: MySQL server has gone away: SELECT * FROM `widgets` </code></pre> <p>Restarting the mongrels (not the MySQL server) fixes it.</p> <p>How can we fix this?</p>
[ { "answer_id": 100703, "author": "Z99", "author_id": 18307, "author_profile": "https://Stackoverflow.com/users/18307", "pm_score": 1, "selected": false, "text": "mysql> show status;\n" }, { "answer_id": 101250, "author": "Laurie Young", "author_id": 7473, "author_profile": "https://Stackoverflow.com/users/7473", "pm_score": 6, "selected": true, "text": "if defined?(ActiveRecord)\n before_dispatch { ActiveRecord::Base.verify_active_connections! }\n to_prepare(:activerecord_instantiate_observers) {ActiveRecord::Base.instantiate_observers }\nend\n verify_active_connections! verify_active_connections! verify_active_connections!" }, { "answer_id": 101522, "author": "Dave Cheney", "author_id": 6449, "author_profile": "https://Stackoverflow.com/users/6449", "pm_score": 2, "selected": false, "text": "set-variable = wait_timeout=86400\n /etc/my.cnf" }, { "answer_id": 1175186, "author": "mixonic", "author_id": 142061, "author_profile": "https://Stackoverflow.com/users/142061", "pm_score": 6, "selected": false, "text": "production:\n # Your settings\n reconnect: true\n" }, { "answer_id": 7586762, "author": "Graeme Irwin", "author_id": 969552, "author_profile": "https://Stackoverflow.com/users/969552", "pm_score": 1, "selected": false, "text": "begin\n do_some_active_record_operation\nrescue ActiveRecord::StatementInvalid => e\n Rails.logger.debug(\"Got statement invalid #{e.message} ... trying again\")\n # Second attempt, now that db connection is re-established\n do_some_active_record_operation\nend\n" }, { "answer_id": 8220766, "author": "Ryan Allen", "author_id": 977719, "author_profile": "https://Stackoverflow.com/users/977719", "pm_score": 0, "selected": false, "text": "mysql2" }, { "answer_id": 17870784, "author": "Abdo", "author_id": 226255, "author_profile": "https://Stackoverflow.com/users/226255", "pm_score": 2, "selected": false, "text": "show variables like \"max_connections\";\n database.yml show status where variable_name = 'Threads_connected';\n Thread Thread.new do\n begin\n # Thread work here\n ensure\n begin\n if (ActiveRecord::Base.connection && ActiveRecord::Base.connection.active?)\n ActiveRecord::Base.connection.close\n end\n rescue\n end\n end\nend\n" }, { "answer_id": 21074557, "author": "Matt Connolly", "author_id": 365932, "author_profile": "https://Stackoverflow.com/users/365932", "pm_score": 3, "selected": false, "text": "ActiveRecord::Base.connection.verify!" }, { "answer_id": 23895554, "author": "Isaac Betesh", "author_id": 1633753, "author_profile": "https://Stackoverflow.com/users/1633753", "pm_score": 3, "selected": false, "text": "set global max_allowed_packet = 1048576; # 2^20 bytes (1 MB) was enough in my case\n" }, { "answer_id": 67589849, "author": "Joshua Pinter", "author_id": 293280, "author_profile": "https://Stackoverflow.com/users/293280", "pm_score": 0, "selected": false, "text": "# Clear existing connections before forking to ensure they do not get inherited.\n::ActiveRecord::Base.clear_all_connections! \n\nfork do\n # Establish a new connection for each fork.\n ::ActiveRecord::Base.establish_connection \n \n # The rest of the code for each fork...\nend\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100631", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18666/" ]
100,633
<p>Why is it bad practice to declare variables on one line?</p> <p>e.g.</p> <pre><code>private String var1, var2, var3 </code></pre> <p>instead of: </p> <pre><code>private String var1; private String var2; private String var3; </code></pre>
[ { "answer_id": 100662, "author": "David Pierre", "author_id": 18296, "author_profile": "https://Stackoverflow.com/users/18296", "pm_score": 4, "selected": false, "text": "int * i, j;\n" }, { "answer_id": 100664, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 4, "selected": true, "text": "if ((foo = some_function()) == 0) {\n //do something\n}\n" }, { "answer_id": 100674, "author": "Henrik Heimbuerger", "author_id": 6278, "author_profile": "https://Stackoverflow.com/users/6278", "pm_score": 3, "selected": false, "text": "int* var1, var2, var3;\n int* var1;\nint var2;\nint var3;\n" }, { "answer_id": 100679, "author": "Grundlefleck", "author_id": 4120, "author_profile": "https://Stackoverflow.com/users/4120", "pm_score": 2, "selected": false, "text": "public static final int NORTH = 0,\n EAST = 1,\n SOUTH = 2,\n WEST = 3;\n" }, { "answer_id": 100680, "author": "ripper234", "author_id": 11236, "author_profile": "https://Stackoverflow.com/users/11236", "pm_score": 0, "selected": false, "text": "string a,b;\nif (Foo())\n{\n a = \"Something\";\n b = \"Something else\";\n}\nelse\n{\n a = \"Some other thing\";\n b = \"Out of examples\";\n}\n" }, { "answer_id": 100701, "author": "Keith", "author_id": 905, "author_profile": "https://Stackoverflow.com/users/905", "pm_score": 3, "selected": false, "text": "//not much use\nint i, j, k;\n\n//better\nint counter, \n childCounter, \n percentComplete;\n" }, { "answer_id": 51964331, "author": "jaskirat singh", "author_id": 8074053, "author_profile": "https://Stackoverflow.com/users/8074053", "pm_score": 0, "selected": false, "text": "int i,j;\n int i;\nint j;\n int removeElement (int* A, int n1, int B) \n{\n int k=0, i;\n for(i=0;i<n1;i++)\n if(A[i]!=B)\n {\n A[k]=A[i];\n k++;\n } \n return k;\n}\n int removeElement (int* A, int n1, int B) \n{\n int k=0;\n int i;\n for(i=0;i<n1;i++)\n if(A[i]!=B)\n {\n A[k]=A[i];\n k++;\n } \n return k;\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100633", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15352/" ]
100,645
<p>Are there any tools available for calculating Cyclomatic Complexity in Javascript? </p> <p>I've found it a very helpful metric in the past while working on server side code, and would like to be able to use it for the client side Javascript I write.</p>
[ { "answer_id": 13453464, "author": "Phil Booth", "author_id": 47348, "author_profile": "https://Stackoverflow.com/users/47348", "pm_score": 5, "selected": false, "text": "npm i -g complexity-report\n" }, { "answer_id": 15815677, "author": "SavoryBytes", "author_id": 131944, "author_profile": "https://Stackoverflow.com/users/131944", "pm_score": 4, "selected": false, "text": "maxparams maxdepth maxstatements maxcomplexity /*jshint maxparams:3 */\n\nfunction login(request, onSuccess) {\n // ...\n}\n\n// JSHint: Too many parameters per function (4).\nfunction logout(request, isManual, whereAmI, onSuccess) {\n // ...\n}\n /*jshint maxdepth:2 */\n\nfunction main(meaning) {\n var day = true;\n\n if (meaning === 42) {\n while (day) {\n shuffle();\n\n if (tired) { // JSHint: Blocks are nested too deeply (3).\n sleep();\n }\n }\n }\n}\n /*jshint maxstatements:4 */\n\nfunction main() {\n var i = 0;\n var j = 0;\n\n // Function declarations count as one statement. Their bodies\n // don't get taken into account for the outer function.\n function inner() {\n var i2 = 1;\n var j2 = 1;\n\n return i2 + j2;\n }\n\n j = i + j;\n return j; // JSHint: Too many statements per function. (5)\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100645", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2932/" ]
100,661
<p>Are there any tools available for calculating the <strong>average number of lines of code per method</strong>?</p> <p>I want to know the average size of each method, not just the total number of lines in the project. The per method count will allow me to measure how simple each method is.</p> <p>This will be calculated as part of the build process, and displayed on a dashboard. The idea being that we can see if the average size of each method is increasing. And this will flag the possibility that code complexity is increasing and we may need to think about refactoring.</p>
[ { "answer_id": 100866, "author": "Marius", "author_id": 1585, "author_profile": "https://Stackoverflow.com/users/1585", "pm_score": 1, "selected": false, "text": "function calculateMethodSize(obj){\n var fcount = 0;\n var fsize = 0;\n for(i in obj){\n if(obj[i] instanceof Function){\n fcount++;\n fsize += obj[i].toString().split(\";\\n\").length;\n }else if(obj[i] instanceof Object){\n var ret = calculateMethodSize(obj[i]);\n fcount += ret.fcount;\n fsize += ret.fsize;\n }\n }\n return {fsize:fsize, fcount:fcount};\n}\nvar data = calculateMethodSize(this);\nvar average = data.fsize / data.fcount;\n" }, { "answer_id": 102370, "author": "EndangeredMassa", "author_id": 106, "author_profile": "https://Stackoverflow.com/users/106", "pm_score": 0, "selected": false, "text": "FOR each line in a javascript file (or chunk of text)\n IF the line starts with \"function \" THEN\n PUSH the first left-curly brace you find onto a stack\n WHILE the stack is non-empty\n PUSH any left-curly braces in the current line\n POP any left-curly braces when you encounter a right-curly brace\n Increment your line-count by 1\n Increment your line counter (as mentioned in the FOR loop above)\n END WHILE\n Store your total lines for this function \n ELSE\n //ignore the line because it's probably a global var or blank\n END IF\nEND FOR\n" }, { "answer_id": 1740032, "author": "just somebody", "author_id": 209605, "author_profile": "https://Stackoverflow.com/users/209605", "pm_score": 0, "selected": false, "text": "var negate = bind1st(compose, not);\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100661", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2932/" ]
100,678
<pre><code>LRESULT result = ::SendMessage(hWnd, s_MaxGetTaskInterface, (WPARAM)&amp;pUnkReturn, 0); </code></pre> <p>The value of result after the call is 0</p> <p>I expect it to return with a valid value of pUnkReturn , but it returns with a NULL value .</p> <p>Necessary Information before this call :</p> <pre><code>const UINT CMotionUtils::s_MaxGetTaskInterface = RegisterWindowMessage(_T("NI:Max:GetTaskInterface")); </code></pre> <p>The value of <code>s_MaxGetTaskInterface</code> i get here is 49896 . </p> <p>The value of hWnd is also proper . I checked that with Spy++ ( Visual Studio tool ) .</p> <p>Microft Spy++ Messages window shows me the following for this window . </p> <pre><code>&lt;00001&gt; 009F067C S message:0xC2E8 [Registered:"NI:Max:GetTaskInterface"]wParam:0224C2D0 lParam:00000000 &lt;00002&gt; 009F067C S message:0xC2E8 [Registered:"NI:Max:GetTaskInterface"]lResult:00000000 </code></pre> <p>Please help me to get a valid address stored in pUnkReturn after the call . </p>
[ { "answer_id": 100692, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 0, "selected": false, "text": "NI:Max:GetTaskInterface hWnd NI:Max:GetTaskInterface" }, { "answer_id": 100979, "author": "Alan", "author_id": 2958, "author_profile": "https://Stackoverflow.com/users/2958", "pm_score": 0, "selected": false, "text": "pUnkReturn" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100678", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
100,689
<p>I have a problem that confuses my users, being that although an item is highlighted (by the hover style) when the user mouses over it, they have to mouse over the actual item text, sometimes quite small compared to the item. Is there a way to make the whole item clickable?</p>
[ { "answer_id": 100706, "author": "David Heggie", "author_id": 4309, "author_profile": "https://Stackoverflow.com/users/4309", "pm_score": 3, "selected": true, "text": "a {\n display: block;\n width: 100%;\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100689", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
100,705
<p>I recently heard of WSDL.Exe, but I am not sure where to find this program. Does anyone know where I can find or download it?</p>
[ { "answer_id": 100787, "author": "David Bick", "author_id": 4914, "author_profile": "https://Stackoverflow.com/users/4914", "pm_score": 5, "selected": true, "text": "C:\\program files\\Microsoft Visual Studio 8\\SDK\\v2.0\\Bin" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100705", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
100,707
<p>I'm wondering, how expensive it is to have many threads in waiting state in java 1.6 x64.</p> <p>To be more specific, I'm writing application which runs across many computers and sends/receives data from one to another. I feel more comfortable to have separate thread for each connected machine and task, like 1) sending data, 2) receiving data, 3) reestablishing connection when it is dropped. So, given that there are N nodes in cluster, each machine is going to have 3 threads for each of N-1 neighbours. Typically there will be 12 machines, which comes to 33 communication threads.</p> <p>Most of those threads will be sleeping most of the time, so for optimization purposes I could reduce number of threads and give more job to each of them. Like, for example. reestablishing connection is responsibility of receiving thread. Or sending to all connected machines is done by single thread.</p> <p>So is there any significant perfomance impact on having many sleeping threads?</p>
[ { "answer_id": 100994, "author": "Bill Michell", "author_id": 7938, "author_profile": "https://Stackoverflow.com/users/7938", "pm_score": 1, "selected": false, "text": "ThreadPoolExecutor" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100707", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5507/" ]
100,721
<p>I am using <code>DirectoryInfo.GetDirectories()</code> recursively to find the all the sub-directories under a given path. However, I want to exclude the System folders and there is no clear way for that. In FindFirstFile/FindNextFile things were clearer with the attributes.</p>
[ { "answer_id": 100822, "author": "aku", "author_id": 1196, "author_profile": "https://Stackoverflow.com/users/1196", "pm_score": 4, "selected": true, "text": "static IEnumerable<string> GetNonSystemDirs(string path)\n{\n var dirs = from d in Directory.GetDirectories(path)\n let inf = new DirectoryInfo(d)\n where (inf.Attributes & FileAttributes.System) == 0\n select d;\n\n foreach (var dir in dirs)\n {\n yield return dir;\n foreach (var subDir in GetNonSystemDirs(dir))\n {\n yield return subDir;\n }\n }\n}\n" }, { "answer_id": 100877, "author": "Nathan Baulch", "author_id": 8799, "author_profile": "https://Stackoverflow.com/users/8799", "pm_score": 2, "selected": false, "text": "public static DirectoryInfo[] GetNonSystemDirectories(\n this DirectoryInfo directory,\n string searchPattern,\n SearchOption searchOption)\n{\n return directory.GetDirectories(searchPattern, searchOption)\n .Where(subDir => (subDir.Attributes & FileAttributes.System) == 0)\n .ToArray();\n}\n public static IEnumerable<DirectoryInfo> EnumerateNonSystemDirectories(\n this DirectoryInfo directory,\n string searchPattern,\n SearchOption searchOption)\n{\n return directory.EnumerateDirectories(searchPattern, searchOption)\n .Where(subDir => (subDir.Attributes & FileAttributes.System) == 0);\n}\n" }, { "answer_id": 22290845, "author": "electricalbah", "author_id": 1899556, "author_profile": "https://Stackoverflow.com/users/1899556", "pm_score": 0, "selected": false, "text": " IEnumerable<string> directories = new DirectoryInfo(path).GetDirectories().Where(a => (a.Attributes & FileAttributes.System) == 0).Select(a => a.FullName);\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
100,732
<p>I've seen several examples of code like this:</p> <pre><code>if not someobj: #do something </code></pre> <p>But I'm wondering why not doing:</p> <pre><code>if someobj == None: #do something </code></pre> <p>Is there any difference? Does one have an advantage over the other?</p>
[ { "answer_id": 100762, "author": "Sylvain Defresne", "author_id": 5353, "author_profile": "https://Stackoverflow.com/users/5353", "pm_score": 9, "selected": true, "text": "bool __nonzero__ int float bool int False __len__ list dict set tuple False True None False None __eq__ bool if __cmp__ int -1 self < other 0 self == other +1 self > other is is None getattr __getitem__ >>> class A(object):\n... def __repr__(self):\n... return 'A()'\n... def __nonzero__(self):\n... return False\n\n>>> class B(object):\n... def __repr__(self):\n... return 'B()'\n... def __len__(self):\n... return 0\n\n>>> class C(object):\n... def __repr__(self):\n... return 'C()'\n... def __cmp__(self, other):\n... return 0\n\n>>> class D(object):\n... def __repr__(self):\n... return 'D()'\n... def __eq__(self, other):\n... return True\n\n>>> for obj in ['', (), [], {}, 0, 0., A(), B(), C(), D(), None]:\n... print '%4s: bool(obj) -> %5s, obj == None -> %5s, obj is None -> %5s' % \\\n... (repr(obj), bool(obj), obj == None, obj is None)\n '': bool(obj) -> False, obj == None -> False, obj is None -> False\n (): bool(obj) -> False, obj == None -> False, obj is None -> False\n []: bool(obj) -> False, obj == None -> False, obj is None -> False\n {}: bool(obj) -> False, obj == None -> False, obj is None -> False\n 0: bool(obj) -> False, obj == None -> False, obj is None -> False\n 0.0: bool(obj) -> False, obj == None -> False, obj is None -> False\n A(): bool(obj) -> False, obj == None -> False, obj is None -> False\n B(): bool(obj) -> False, obj == None -> False, obj is None -> False\n C(): bool(obj) -> True, obj == None -> True, obj is None -> False\n D(): bool(obj) -> True, obj == None -> True, obj is None -> False\nNone: bool(obj) -> False, obj == None -> True, obj is None -> True\n" }, { "answer_id": 100764, "author": "badp", "author_id": 13992, "author_profile": "https://Stackoverflow.com/users/13992", "pm_score": 5, "selected": false, "text": "None if not False:\n print \"False is false.\"\nif not 0:\n print \"0 is false.\"\nif not []:\n print \"An empty list is false.\"\nif not ():\n print \"An empty tuple is false.\"\nif not {}:\n print \"An empty dict is false.\"\nif not \"\":\n print \"An empty string is false.\"\n False 0 () [] {} \"\" None >>> False == 0\nTrue\n>>> False == ()\nFalse\n if object: 0 () [] None {} foo = bar and spam or eggs\n if bar:\n foo = spam\nelse:\n foo = eggs\n foo = spam if bar else egg\n" }, { "answer_id": 100771, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": false, "text": "- Comparisons to singletons like None should always be done with\n 'is' or 'is not', never the equality operators.\n" }, { "answer_id": 100828, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 0, "selected": false, "text": "if (var) b bVar if (bVar == true) while (line = getNextLine())" }, { "answer_id": 100903, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 6, "selected": false, "text": "if x if not x x bool == None is None is not None - Comparisons to singletons like None should always be done with\n 'is' or 'is not', never the equality operators.\n\n Also, beware of writing \"if x\" when you really mean \"if x is not None\"\n -- e.g. when testing whether a variable or argument that defaults to\n None was set to some other value. The other value might have a type\n (such as a container) that could be false in a boolean context!\n None True False NotImplemented Ellipsis NotImplemented Ellipsis if x is True if x None" }, { "answer_id": 100974, "author": "pi.", "author_id": 15274, "author_profile": "https://Stackoverflow.com/users/15274", "pm_score": 2, "selected": false, "text": "if not spam:\n print \"Sorry. No SPAM.\"\n if spam == None:\n print \"Sorry. No SPAM here either.\"\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10708/" ]
100,774
<p>The following JavaScript supposes to read the popular tags from an XML file and applies the XSL Stylesheet and output to the browser as HTML.</p> <pre><code>function ShowPopularTags() { xml = XMLDocLoad("http://localhost/xml/tags/popular.xml?s=94987898"); xsl = XMLDocLoad("http://localhost/xml/xsl/popular-tags.xsl"); if (window.ActiveXObject) { // code for IE ex = xml.transformNode(xsl); ex = ex.replace(/\\/g, ""); document.getElementById("popularTags").innerHTML = ex; } else if (document.implementation &amp;&amp; document.implementation.createDocument) { // code for Mozilla, Firefox, Opera, etc. xsltProcessor = new XSLTProcessor(); xsltProcessor.importStylesheet(xsl); resultDocument = xsltProcessor.transformToFragment(xml, document); document.getElementById("popularTags").appendChild(resultDocument); var ihtml = document.getElementById("popularTags").innerHTML; ihtml = ihtml.replace(/\\/g, ""); document.getElementById("popularTags").innerHTML = ihtml; } } ShowPopularTags(); </code></pre> <p>The issue with this script is sometime it manages to output the resulting HTML code, sometime it doesn't. Anyone knows where is going wrong?</p>
[ { "answer_id": 101048, "author": "Twan", "author_id": 6702, "author_profile": "https://Stackoverflow.com/users/6702", "pm_score": 1, "selected": false, "text": "<BODY onLoad=\"ShowPopularTags();\">\n" }, { "answer_id": 110853, "author": "Twan", "author_id": 6702, "author_profile": "https://Stackoverflow.com/users/6702", "pm_score": 2, "selected": true, "text": "if (window.XMLHttpRequest)\n{\n oCurrentRequest = new XMLHttpRequest();\n oCurrentRequest.onreadystatechange = processReqChange;\n oCurrentRequest.open('GET', sURL, true);\n oCurrentRequest.send(null);\n}\nelse if (window.ActiveXObject)\n{\n oCurrentRequest = new ActiveXObject('Microsoft.XMLHTTP');\n if (oCurrentRequest)\n {\n oCurrentRequest.onreadystatechange = processReqChange;\n oCurrentRequest.open('GET', sURL, true);\n oCurrentRequest.send();\n }\n}\n function processReqChange()\n{\n if (oCurrentRequest.readyState == 4)\n {\n if (oCurrentRequest.status == 200)\n {\n oXMLRequest = oCurrentRequest;\n oCurrentRequest = null;\n loadXSLDoc();\n }\n }\n}\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100774", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17074/" ]
100,808
<p>I want to receive the following <code>HTTP</code> request in <code>PHP:</code></p> <pre><code>Content-type: multipart/form-data;boundary=main_boundary --main_boundary Content-type: text/xml &lt;?xml version='1.0'?&gt; &lt;content&gt; Some content goes here &lt;/content&gt; --main_boundary Content-type: multipart/mixed;boundary=sub_boundary --sub_boundary Content-type: application/octet-stream File A contents --sub_boundary Content-type: application/octet-stream File B contents --sub_boundary --main_boundary-- </code></pre> <p>(Note: I have indented the sub-parts only to make it more readable for this post.)</p> <p>I'm not very fluent in PHP and would like to get some help/pointers to figure out how to receive this kind of multipart form request in PHP code. I have once written some code where I received a standard HTML form and then I could access the form elements by using their name as index key in the <code>$HTTP_GET_VARS</code> array, but in this case there are no form element names, and the form data parts are not linear (i.e. sub parts = multilevel array).</p> <p>Grateful for any help!</p> <p>/Robert</p>
[ { "answer_id": 100874, "author": "pilsetnieks", "author_id": 6615, "author_profile": "https://Stackoverflow.com/users/6615", "pm_score": 3, "selected": true, "text": "$HTTP_GET_VARS $HTTP_POST_VARS $_GET $_POST $_FILES $_POST always_populate_raw_post_data $HTTP_RAW_POST_DATA" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100808", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7891/" ]
100,812
<p>Not for the first time, I've accidentally done "svn switch" from somewhere below the root of my project. This switches that subdirectory only, but how do I undo this?</p> <p>If I try switching the subdirectory back to the original branch I get:</p> <pre><code>"svn: Directory 'subdir\_svn' containing working copy admin area is missing" </code></pre> <p><strong>Update</strong>: I've got changes in the subdir, so I don't want to do a delete. </p> <p>In the short term I've fixed it by reapplying the changes, but I was after a way to get Subversion to re-switch back to where I came from... or is this a missing feature?</p>
[ { "answer_id": 100870, "author": "Dan", "author_id": 17121, "author_profile": "https://Stackoverflow.com/users/17121", "pm_score": -1, "selected": false, "text": "svn revert <dir>\n" }, { "answer_id": 101176, "author": "Palmin", "author_id": 5949, "author_profile": "https://Stackoverflow.com/users/5949", "pm_score": 3, "selected": false, "text": "svn switch svn://path/to/switched/dir/ subdir\n svn switch svn://url/to/orig/dir subdir\n" }, { "answer_id": 17536978, "author": "durron597", "author_id": 1768232, "author_profile": "https://Stackoverflow.com/users/1768232", "pm_score": 1, "selected": false, "text": "svn checkout <rootUrl> svn update -r HEAD --force" }, { "answer_id": 39392669, "author": "CFWhitman", "author_id": 3199068, "author_profile": "https://Stackoverflow.com/users/3199068", "pm_score": 0, "selected": false, "text": "svn switch file:///srv/svn/someproject/branch/27\n svn switch file:///srv/svn/someproject/branch/26/subdir\n" }, { "answer_id": 53404577, "author": "dash-tom-bang", "author_id": 65845, "author_profile": "https://Stackoverflow.com/users/65845", "pm_score": 0, "selected": false, "text": "cd \\d %1 %1 @echo off\nsetlocal\n\nfor /f \"tokens=*\" %%u in ('svn info --show-item url ..') do set \"PARENT_URL=%%u\"\ncall :SetDirName %CD%\nsvn switch %PARENT_URL%/%DIRNAME%\ngoto :eof\n\n:SetDirName\n set DIRNAME=%~nx1\n goto :eof\n" } ]
2008/09/19
[ "https://Stackoverflow.com/questions/100812", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17641/" ]