qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
215,742
<p><em>By Logic Programming I mean the a sub-paradigm of declarative programming languages. Don't confuse this question with "What problems can you solve with if-then-else?"</em></p> <p>A language like Prolog is very fascinating, and it's worth learning for the sake of learning, but I have to wonder what class of real-world problems is best expressed and solved by such a language. Are there better languages? Does logic programming exist by another name in more trendy programming languages? Is the cynical version of the answer a variant of the <a href="http://www.paulgraham.com/pypar.html" rel="noreferrer">Python Paradox</a>?</p>
[ { "answer_id": 216302, "author": "Aleksandar Dimitrov", "author_id": 11797, "author_profile": "https://Stackoverflow.com/users/11797", "pm_score": 6, "selected": true, "text": "make/0 edit(1) foobar/2 ?- edit(foobar).\n" } ]
2008/10/18
[ "https://Stackoverflow.com/questions/215742", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18446/" ]
215,745
<p>Are there any other ways to avoid LazyInitializationExceptions in a Hibernate web application besides using the OpenSessionInView pattern? Are there any downsides to using OpenSessionInView?</p>
[ { "answer_id": 215806, "author": "abahgat", "author_id": 27565, "author_profile": "https://Stackoverflow.com/users/27565", "pm_score": 4, "selected": true, "text": "FetchMode.JOIN Hibernate.initialize(property)" } ]
2008/10/18
[ "https://Stackoverflow.com/questions/215745", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18995/" ]
215,748
<p>I'm currently working on project with Haskell, and have found myself some trouble. I'm supposed to read and insert into a list each line in a "dictionary.txt" file, but I can't seem to do so. I've got this code:</p> <pre><code>main = do let list = [] loadNums "dictionary.txt" list loadNums location list = do inh &lt;- openFile location ReadMode mainloop inh list hClose inh mainloop inh list = do ineof &lt;- hIsEOF inh if ineof then return () else do inpStr &lt;- hGetLine inh inpStr:list mainloop inh list </code></pre> <p>It is supposed to get every line (I know it does get every line, since replacing the "inpStr:list" with a "putStrLn inpStr" works correctly, displaying all lines), and insert it into a list but I get the following error:</p> <pre><code>Couldn't match expected type `IO' against inferred type `[]' </code></pre> <p>Probably because the hGetLine isn't a String, but a IO String, which I have no idea how to handle in order to obtain a proper string I can insert in my list. I have no idea how this could be solved, or what the problem is exactly, but if anyone has any idea of how to properly get every line in a file into a list, I'd appreciate it.</p> <p>Thanks in advance!</p>
[ { "answer_id": 215796, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 5, "selected": true, "text": "let list' = inpStr:list\n" }, { "answer_id": 215812, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": false, "text": "getLines = liftM lines . readFile\n\nmain = do\n list <- getLines \"dictionary.txt\"\n mapM_ putStrLn list\n" } ]
2008/10/18
[ "https://Stackoverflow.com/questions/215748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9506/" ]
215,752
<p>While working on a C++ project, I was looking for a third party library for something that is not my core business. I found a really good library, doing exactly what's needed, but it is written in Python. I decided to experiment with embedding Python code in C++, using the Boost.Python library.</p> <p>The C++ code looks something like this:</p> <pre><code>#include &lt;string&gt; #include &lt;iostream&gt; #include &lt;boost/python.hpp&gt; using namespace boost::python; int main(int, char **) { Py_Initialize(); try { object module((handle&lt;&gt;(borrowed(PyImport_AddModule("__main__"))))); object name_space = module.attr("__dict__"); object ignored = exec("from myModule import MyFunc\n" "MyFunc(\"some_arg\")\n", name_space); std::string res = extract&lt;std::string&gt;(name_space["result"]); } catch (error_already_set) { PyErr_Print(); } Py_Finalize(); return 0; } </code></pre> <p>A (very) simplified version of the Python code looks like this:</p> <pre><code>import thirdparty def MyFunc(some_arg): result = thirdparty.go() print result </code></pre> <p>Now the problem is this: 'MyFunc' executes fine, i can see the print of 'result'. What i cannot do is read 'result' back from the C++ code. The extract command never finds 'result' in any namespace. I tried defining 'result' as a global, i even tried returning a tuple, but i cannot get it to work.</p>
[ { "answer_id": 215843, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 1, "selected": false, "text": "PyObject_CallObject(<py function>, <args>) PyRun_String(<expression>, Py_eval_input, <globals>, <locals>)" }, { "answer_id": 215874, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 4, "selected": true, "text": "return print MyModule.py import thirdparty\n\ndef MyFunc(some_arg):\n result = thirdparty.go()\n return result\n #include <Python.h>\n\nint\nmain(int argc, char *argv[])\n{\n PyObject *pName, *pModule, *pFunc;\n PyObject *pArgs, *pArg, *pResult;\n int i;\n\n Py_Initialize();\n pName = PyString_FromString(\"MyModule.py\");\n /* Error checking of pName left out as exercise */\n\n pModule = PyImport_Import(pName);\n Py_DECREF(pName);\n\n if (pModule != NULL) {\n pFunc = PyObject_GetAttrString(pModule, \"MyFunc\");\n /* pFunc is a new reference */\n\n if (pFunc) {\n pArgs = PyTuple_New(0);\n pArg = PyString_FromString(\"some parameter\")\n /* pArg reference stolen here: */\n PyTuple_SetItem(pArgs, 0, pArg);\n pResult = PyObject_CallObject(pFunc, pArgs);\n Py_DECREF(pArgs);\n if (pResult != NULL) {\n printf(\"Result of call: %s\\n\", PyString_AsString(pResult));\n Py_DECREF(pResult);\n }\n else {\n Py_DECREF(pFunc);\n Py_DECREF(pModule);\n PyErr_Print();\n fprintf(stderr,\"Call failed\\n\");\n return 1;\n }\n }\n else {\n if (PyErr_Occurred())\n PyErr_Print();\n fprintf(stderr, \"Cannot find function\");\n }\n Py_XDECREF(pFunc);\n Py_DECREF(pModule);\n }\n else {\n PyErr_Print();\n fprintf(stderr, \"Failed to load module\");\n return 1;\n }\n Py_Finalize();\n return 0;\n}\n" }, { "answer_id": 216224, "author": "yoav.aviram", "author_id": 25287, "author_profile": "https://Stackoverflow.com/users/25287", "pm_score": 2, "selected": false, "text": "import thirdparty\n\ndef MyFunc(some_arg):\n result = thirdparty.go()\n return result\n #include <string>\n#include <iostream>\n#include <boost/python.hpp>\n\nusing namespace boost::python;\n\nint main(int, char **) \n{\n Py_Initialize();\n\n try \n {\n object module = import(\"__main__\");\n object name_space = module.attr(\"__dict__\");\n exec_file(\"MyModule.py\", name_space, name_space);\n\n object MyFunc = name_space[\"MyFunc\"];\n object result = MyFunc(\"some_args\");\n\n // result is a dictionary\n std::string val = extract<std::string>(result[\"val\"]);\n } \n catch (error_already_set) \n {\n PyErr_Print();\n }\n\n Py_Finalize();\n return 0;\n}\n" } ]
2008/10/18
[ "https://Stackoverflow.com/questions/215752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25287/" ]
215,753
<p>I was watching a tutorial on Rails and was very impressed that you could so easily create an editing system for a class just by defining it.</p> <p>Can this be done in ASP.NET?</p> <p>I know there are ORMs out there, but do they come with an editing system?</p> <p>To explain what I mean by an editing system, consider a class for defining people</p> <pre><code>class Person { string First_Name; string Last_Name } </code></pre> <p>And then perhaps with one bold stroke something like this:</p> <pre><code>CreateEditAbleClass(Person) </code></pre> <p>You would get the functionality below in a browser:</p> <p><a href="http://www.yart.com.au/images/orm_editor.jpg" rel="nofollow noreferrer">http://www.yart.com.au/images/orm_editor.jpg</a></p> <p>And this functionality would extend to all the UML definitions – inheritance, association, aggregation etc. In addition, there would be a simple way of adding customisable validation and so forth.</p> <p>I currently use DataGrids and a lot of manual coding to achieve these results.</p>
[ { "answer_id": 215843, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 1, "selected": false, "text": "PyObject_CallObject(<py function>, <args>) PyRun_String(<expression>, Py_eval_input, <globals>, <locals>)" }, { "answer_id": 215874, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 4, "selected": true, "text": "return print MyModule.py import thirdparty\n\ndef MyFunc(some_arg):\n result = thirdparty.go()\n return result\n #include <Python.h>\n\nint\nmain(int argc, char *argv[])\n{\n PyObject *pName, *pModule, *pFunc;\n PyObject *pArgs, *pArg, *pResult;\n int i;\n\n Py_Initialize();\n pName = PyString_FromString(\"MyModule.py\");\n /* Error checking of pName left out as exercise */\n\n pModule = PyImport_Import(pName);\n Py_DECREF(pName);\n\n if (pModule != NULL) {\n pFunc = PyObject_GetAttrString(pModule, \"MyFunc\");\n /* pFunc is a new reference */\n\n if (pFunc) {\n pArgs = PyTuple_New(0);\n pArg = PyString_FromString(\"some parameter\")\n /* pArg reference stolen here: */\n PyTuple_SetItem(pArgs, 0, pArg);\n pResult = PyObject_CallObject(pFunc, pArgs);\n Py_DECREF(pArgs);\n if (pResult != NULL) {\n printf(\"Result of call: %s\\n\", PyString_AsString(pResult));\n Py_DECREF(pResult);\n }\n else {\n Py_DECREF(pFunc);\n Py_DECREF(pModule);\n PyErr_Print();\n fprintf(stderr,\"Call failed\\n\");\n return 1;\n }\n }\n else {\n if (PyErr_Occurred())\n PyErr_Print();\n fprintf(stderr, \"Cannot find function\");\n }\n Py_XDECREF(pFunc);\n Py_DECREF(pModule);\n }\n else {\n PyErr_Print();\n fprintf(stderr, \"Failed to load module\");\n return 1;\n }\n Py_Finalize();\n return 0;\n}\n" }, { "answer_id": 216224, "author": "yoav.aviram", "author_id": 25287, "author_profile": "https://Stackoverflow.com/users/25287", "pm_score": 2, "selected": false, "text": "import thirdparty\n\ndef MyFunc(some_arg):\n result = thirdparty.go()\n return result\n #include <string>\n#include <iostream>\n#include <boost/python.hpp>\n\nusing namespace boost::python;\n\nint main(int, char **) \n{\n Py_Initialize();\n\n try \n {\n object module = import(\"__main__\");\n object name_space = module.attr(\"__dict__\");\n exec_file(\"MyModule.py\", name_space, name_space);\n\n object MyFunc = name_space[\"MyFunc\"];\n object result = MyFunc(\"some_args\");\n\n // result is a dictionary\n std::string val = extract<std::string>(result[\"val\"]);\n } \n catch (error_already_set) \n {\n PyErr_Print();\n }\n\n Py_Finalize();\n return 0;\n}\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24696/" ]
215,767
<p>If you have something like:</p> <pre><code>val myStuff = Array(Person("joe",40), Person("mary", 35)) </code></pre> <p>How do you create an XML value with that data as nodes? I know how to use { braces } in an XML expression to put a value, but this is a collection of values. Do I need to iterate explicitly or is there something better?</p> <pre><code>val myXml = &lt;people&gt;{ /* what here?! */ }&lt;/people&gt; </code></pre> <p>The resulting value should be something like:</p> <pre><code>&lt;people&gt;&lt;person&gt;&lt;name&gt;joe&lt;/name&gt;&lt;age&gt;40&lt;/age&gt;&lt;/person&gt; &lt;person&gt;&lt;name&gt;mary&lt;/name&gt;&lt;age&gt;39&lt;/age&gt;&lt;/person&gt;&lt;/people&gt; </code></pre>
[ { "answer_id": 215860, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 5, "selected": true, "text": "class Person(name : String, age : Int){\n def toXml() = <person><name>{ name }</name><age>{ age }</age></person>\n}\n\nobject xml {\n val people = List(\n new Person(\"Alice\", 16),\n new Person(\"Bob\", 64)\n )\n\n val data = <people>{ people.map(p => p.toXml()) }</people>\n\n def main(args : Array[String]){\n println(data)\n }\n}\n <people><person><name>Alice</name><age>16</age></person><person><name>Bob</name><age>64</age></person></people>\n <people>\n <person>\n <name>Alice</name>\n <age>16</age>\n </person>\n <person>\n <name>Bob</name>\n <age>64</age>\n </person>\n</people>\n" }, { "answer_id": 319216, "author": "hishadow", "author_id": 7188, "author_profile": "https://Stackoverflow.com/users/7188", "pm_score": 3, "selected": false, "text": "import scala.xml\n\ncase class Person(val name: String, val age: Int) {\n def toXml(): xml.Elem =\n <person><name>{ name }</name><age>{ age }</age></person>\n}\n\ndef peopleToXml(people: List[Person]): xml.Elem = {\n <people>{\n for {person <- people if person.age > 39}\n yield person.toXml\n }</people>\n}\n\nval data = List(Person(\"joe\",40),Person(\"mary\", 35))\nprintln(peopleToXml(data))\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17138/" ]
215,770
<p>I'm a very novice OCaml programmer so please forgive me if this is a stupid/obvious question. There's <em>a lot</em> to absorb and I may have missed this in the documentation.</p> <p>I have a base of code that's starting to look like this:</p> <pre><code>let update_x p x = add_delta p; p.x &lt;- x; refresh p let update_y p y = add_delta p; p.y &lt;- y; refresh p let update_z p z = add_delta p; p.z &lt;- z; refresh p </code></pre> <p>The duplication is starting to bug me because I <em>want</em> to write something like this:</p> <pre><code>let update_scalar p scalar value = add_delta p; magic_reflection (p, scalar) &lt;- value; refresh p </code></pre> <p>This way when I update x I can simply call:</p> <pre><code>update_scalar p 'x' value </code></pre> <p>This calls out "macros!" to me but I don't believe OCaml has a macro system. What else can I do?</p>
[ { "answer_id": 215884, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 2, "selected": true, "text": "UPDATE_FIELD x f y\n x.f <- y\n" }, { "answer_id": 264390, "author": "zrr", "author_id": 34515, "author_profile": "https://Stackoverflow.com/users/34515", "pm_score": 3, "selected": false, "text": "let update_gen set p x =\n add_delta p;\n set p x;\n refresh p\n\nlet update_x = update_gen (fun p v -> p.x <- v)\nlet update_y = update_gen (fun p v -> p.y <- v)\nlet update_z = update_gen (fun p v -> p.z <- v)\n" }, { "answer_id": 4782410, "author": "ygrek", "author_id": 118799, "author_profile": "https://Stackoverflow.com/users/118799", "pm_score": 0, "selected": false, "text": "open Printf\n\ntype t = { mutable x : float; mutable y : float; mutable z : float; mutable t : int; }\n\nlet add_delta p = p.t <- p.t + 1\nlet refresh p = printf \"%d) %.2f %.2f %.2f\\n\" p.t p.x p.y p.z\n\nDEFINE UPD(x) = fun p v ->\n add_delta p;\n p.x <- v;\n refresh p\n\nlet update_x = UPD(x)\nlet update_y = UPD(y)\nlet update_z = UPD(z)\n\nlet () =\n let p = { x = 0.; y = 0.; z = 0.; t = 0; } in\n update_x p 0.1;\n update_y p 0.3;\n update_z p 2.0\n ocamlfind ocamlc -package camlp4.macro -syntax camlp4o q.ml -o q\n camlp4o Camlp4MacroParser.cmo q.ml\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18446/" ]
215,799
<p>I'm looking it over and it seems to be that it is fundamentally broken.</p> <ul> <li>Only 5 instance methods aren't marked obsolete. </li> <li>There doesn't appear to be any built-in way to parse query-string variables.</li> <li>There are no methods to mutate the Uri, for example appending a new query variable.</li> <li>HttpUtility works on strings, not URIs</li> </ul> <p>So is there anything it is good for? Should I really be using this instead of just strings?</p>
[ { "answer_id": 215864, "author": "Jason Whitehorn", "author_id": 27860, "author_profile": "https://Stackoverflow.com/users/27860", "pm_score": 3, "selected": false, "text": "Uri link = new Uri(new Uri(webSiteAddress), linkPulledFromSite);\nstring absoluteUrl = link.AbsoluteUri;\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215799", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5274/" ]
215,810
<p>I've got an unmanaged Linux VPS running ubuntu that I'm using for the web server for a personal website. I'd like to get a barebones email server up and running. All the installation guides I've found so far are for a full-fledged email server with a webmail interface and everything. That's a lot more than I need. There's only two things I need:</p> <ul> <li>My web application needs to be able to send email. Specifically, it'll be emailing me when an exception occurs.</li> <li>I want all email sent to [anything]@domain.com forwarded to my personal gmail account. The server doesn't even need to retain the email or anything.</li> </ul> <p>I want to reserve resources for the actual web app, so I don't want to install anything I won't need for this.</p>
[ { "answer_id": 215858, "author": "Terry G Lorber", "author_id": 809, "author_profile": "https://Stackoverflow.com/users/809", "pm_score": 0, "selected": false, "text": "sudo apt-get install postfix\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215810", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29262/" ]
215,820
<p>Years ago when I was working with C# I could easily create a temporary file and get its name with this function:</p> <pre><code>Path.GetTempFileName(); </code></pre> <p>This function would create a file with a unique name in the temporary directory and return the full path to that file. </p> <p>In the Cocoa API's, the closest thing I can find is:</p> <pre><code>NSTemporaryDirectory </code></pre> <p>Am I missing something obvious or is there no built in way to do this?</p>
[ { "answer_id": 215927, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 4, "selected": false, "text": "unistd.h [NSTemporaryDirectory() stringByAppendingPathComponent: [NSString stringWithFormat: @\"%.0f.%@\", [NSDate timeIntervalSinceReferenceDate] * 1000.0, @\"txt\"]];\n" }, { "answer_id": 216411, "author": "alextgordon", "author_id": 1165750, "author_profile": "https://Stackoverflow.com/users/1165750", "pm_score": 0, "selected": false, "text": "NSTask uuidgen NSTemporaryDirectory()" }, { "answer_id": 4001613, "author": "Philipp", "author_id": 230475, "author_profile": "https://Stackoverflow.com/users/230475", "pm_score": 4, "selected": false, "text": "NSFileManager NSTemporary() @interface NSFileManager (TemporaryDirectory)\n\n-(NSString *) createTemporaryDirectory;\n\n@end\n @implementation NSFileManager (TemporaryDirectory)\n\n-(NSString *) createTemporaryDirectory {\n // Create a unique directory in the system temporary directory\n NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString];\n NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:guid];\n if (![self createDirectoryAtPath:path withIntermediateDirectories:NO attributes:nil error:nil]) {\n return nil;\n }\n return path;\n}\n\n@end\n createFileAtPath:contents:attributes: createDirectoryAtPath:" }, { "answer_id": 8307013, "author": "muzz", "author_id": 665366, "author_profile": "https://Stackoverflow.com/users/665366", "pm_score": 4, "selected": false, "text": "- (NSString *)pathForTemporaryFileWithPrefix:(NSString *)prefix\n{\n NSString * result;\n CFUUIDRef uuid;\n CFStringRef uuidStr;\n\n uuid = CFUUIDCreate(NULL);\n assert(uuid != NULL);\n\n uuidStr = CFUUIDCreateString(NULL, uuid);\n assert(uuidStr != NULL);\n\n result = [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@\"%@-%@\", prefix, uuidStr]];\n assert(result != nil);\n\n CFRelease(uuidStr);\n CFRelease(uuid);\n\n return result;\n}\n" }, { "answer_id": 24602733, "author": "SwiftArchitect", "author_id": 218152, "author_profile": "https://Stackoverflow.com/users/218152", "pm_score": 0, "selected": false, "text": "- (NSString *)createTemporaryFile:(NSData *)contents {\n // Create a unique file in the system temporary directory\n NSString *guid = [[NSProcessInfo processInfo] globallyUniqueString];\n NSString *path = [NSTemporaryDirectory() stringByAppendingPathComponent:guid];\n if(![self createFileAtPath:path contents:contents attributes:nil]) {\n return nil;\n }\n return path;\n}\n" }, { "answer_id": 24755281, "author": "fzwo", "author_id": 534888, "author_profile": "https://Stackoverflow.com/users/534888", "pm_score": 4, "selected": false, "text": "NSString *tempFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSUUID UUID] UUIDString]];\n" }, { "answer_id": 31205436, "author": "Bart van Kuik", "author_id": 1085556, "author_profile": "https://Stackoverflow.com/users/1085556", "pm_score": 3, "selected": false, "text": "import Foundation\n\nfunc pathForTemporaryFile(with prefix: String) -> URL {\n let uuid = UUID().uuidString\n let pathComponent = \"\\(prefix)-\\(uuid)\"\n var tempPath = URL(fileURLWithPath: NSTemporaryDirectory())\n tempPath.appendPathComponent(pathComponent)\n return tempPath\n}\n\nlet url = pathForTemporaryFile(with: \"blah\")\nprint(url)\n// file:///var/folders/42/fg3l5j123z6668cgt81dhks80000gn/T/johndoe.KillerApp/blah-E1DCE512-AC4B-4EAB-8838-547C0502E264\n let prefix = \"blah\"\nlet url2 = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(\"\\(prefix)-\\(UUID())\")\nprint(url2)\n" }, { "answer_id": 44595622, "author": "Ssswift", "author_id": 7419656, "author_profile": "https://Stackoverflow.com/users/7419656", "pm_score": 2, "selected": false, "text": "FileManager url(for:in:appropriateFor:create:) SearchPathDirectory .cachesDirectory .itemReplacementDirectory" }, { "answer_id": 61499755, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "NSTemporaryDirectory URL FileManager let tmpURL = FileManager\n .default\n .temporaryDirectory\n .appendingPathComponent(UUID().uuidString)\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28106/" ]
215,854
<p>When using XmlDocument.Load , I am finding that if the document refers to a DTD, a connection is made to the provided URI. Is there any way to prevent this from happening?</p>
[ { "answer_id": 215892, "author": "muratgu", "author_id": 26224, "author_profile": "https://Stackoverflow.com/users/26224", "pm_score": 1, "selected": false, "text": "XMLReader ValidationType None" }, { "answer_id": 216207, "author": "Richard Nienaber", "author_id": 9539, "author_profile": "https://Stackoverflow.com/users/9539", "pm_score": 2, "selected": false, "text": "XmlDocument doc = new XmlDocument();\nusing (StringReader sr = new StringReader(xml))\n using (XmlReader reader = XmlReader.Create(sr, new XmlReaderSettings()))\n {\n doc.Load(reader);\n }\n" }, { "answer_id": 216327, "author": "spender", "author_id": 14357, "author_profile": "https://Stackoverflow.com/users/14357", "pm_score": 3, "selected": false, "text": "settings.ProhibitDtd = true;\n settings.ValidationType = ValidationType.None;\n" }, { "answer_id": 216747, "author": "Richard Nienaber", "author_id": 9539, "author_profile": "https://Stackoverflow.com/users/9539", "pm_score": 6, "selected": true, "text": " XmlReaderSettings settings = new XmlReaderSettings();\n settings.XmlResolver = null;\n settings.DtdProcessing = DtdProcessing.Parse;\n XmlDocument doc = new XmlDocument();\n using (StringReader sr = new StringReader(xml))\n using (XmlReader reader = XmlReader.Create(sr, settings))\n {\n doc.Load(reader);\n }\n" }, { "answer_id": 5052595, "author": "Gunther Schadow", "author_id": 558744, "author_profile": "https://Stackoverflow.com/users/558744", "pm_score": 3, "selected": false, "text": "&amp;" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14357/" ]
215,883
<p>I have an s-expression bound to a variable in Common Lisp:</p> <pre><code>(defvar x '(+ a 2)) </code></pre> <p>Now I want to create a function that when called, evaluates the expression in the scope in which it was defined. I've tried this:</p> <pre><code>(let ((a 4)) (lambda () (eval x))) </code></pre> <p>and</p> <pre><code>(let ((a 4)) (eval `(lambda () ,x))) </code></pre> <p>But both of these create a problem: EVAL will evaluate the code at the top level, so I can't capture variables contained in the expression. Note that I cannot put the LET form in the EVAL. Is there any solution?</p> <p>EDIT: So if there is not solution to the EVAL problem, how else can it be done?</p> <p>EDIT: There was a question about what exactly I am try to do. I am writing a compiler. I want to accept an s-expression with variables closed in the lexical environment where the expression is defined. It may indeed be better to write it as a macro.</p>
[ { "answer_id": 215922, "author": "sanxiyn", "author_id": 18382, "author_profile": "https://Stackoverflow.com/users/18382", "pm_score": 2, "selected": false, "text": "(ext:eval-env x (ext:the-environment))\n" }, { "answer_id": 218755, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 0, "selected": false, "text": "(eval ...) *evalhook*" }, { "answer_id": 219575, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 2, "selected": false, "text": "(defvar *a*)\n(defvar *x* '(+ *a* 2)) ;'\n\n(let ((a 10))\n ;; ...\n (let ((*a* a))\n (eval *x*)))\n" }, { "answer_id": 614707, "author": "Rainer Joswig", "author_id": 69545, "author_profile": "https://Stackoverflow.com/users/69545", "pm_score": 4, "selected": true, "text": "(defvar *x* '(+ a 2))\n\n(let ((a 4))\n (eval `(let ((a ,a))\n ,*x*)))\n" }, { "answer_id": 616214, "author": "dmitry_vk", "author_id": 35054, "author_profile": "https://Stackoverflow.com/users/35054", "pm_score": 0, "selected": false, "text": "(defvar *fn* (compile nil '(lambda () (+ a 2)))\n(progv '(a) '(4) (funcall *fn*))\n=>\n6\n (defvar *fn* (compile nil '(lambda (a) (+ a 2))))\n(funcall *fn* 4)\n=>\n6\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7492/" ]
215,885
<p>If I add an after_save callback to an ActiveRecord model, and on that callback I use update_attribute to change the object, the callback is called again, and so a 'stack overflow' occurs (hehe, couldn't resist).</p> <p>Is it possible to avoid this behavior, maybe disabling the callback during it's execution? Or is there another approach?</p> <p>Thanks!</p>
[ { "answer_id": 215888, "author": "Terry G Lorber", "author_id": 809, "author_profile": "https://Stackoverflow.com/users/809", "pm_score": 3, "selected": false, "text": "send(name.to_s + '=', value)\n" }, { "answer_id": 216762, "author": "Patrick McKenzie", "author_id": 15046, "author_profile": "https://Stackoverflow.com/users/15046", "pm_score": 2, "selected": false, "text": "def before_save\n @attempted_save_level ||= 0\n @attempted_save_level += 1\nend\n\ndef after_save\n if (@attempted_save_level == 1) \n #fill in logic here\n\n save #fires before_save, incrementing save_level to 2, then after_save, which returns without taking action\n\n #fill in logic here \n\n end\n @attempted_save_level -= 1 # reset the \"prevent infinite recursion\" flag \nend\n" }, { "answer_id": 219563, "author": "scottd", "author_id": 5935, "author_profile": "https://Stackoverflow.com/users/5935", "pm_score": 3, "selected": false, "text": "def your_after_save_func\n YourModel.without_callbacks(:your_after_save_func) do\n Your updates/changes\n end\nend\n" }, { "answer_id": 1262964, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "Class Foo << ActiveRecord::Base \n after_save :init_bar_attr, :if => \"bar_attr.nil?\" # just make sure this is false after the callback runs\n\n def init_bar_attr \n self.bar_attr = \"my id is: #{self.id}\" \n\n # careful now, let's save only if we're sure the triggering condition will fail \n self.save if bar_attr\n end\n" }, { "answer_id": 1528584, "author": "Walt Jones", "author_id": 95806, "author_profile": "https://Stackoverflow.com/users/95806", "pm_score": 3, "selected": false, "text": "update_without_callbacks" }, { "answer_id": 13794468, "author": "Brendon Muir", "author_id": 129798, "author_profile": "https://Stackoverflow.com/users/129798", "pm_score": 0, "selected": false, "text": "gsub attr_accessor :original_public_path\nafter_save :replace_public_path, :if => :original_public_path\n\nprivate\n\ndef replace_public_path\n self.overview = overview.gsub(original_public_path, public_path)\n self.original_public_path = nil\n\n save\nend\n :if" }, { "answer_id": 29657526, "author": "Mike", "author_id": 36316, "author_profile": "https://Stackoverflow.com/users/36316", "pm_score": 2, "selected": false, "text": "#update_column" }, { "answer_id": 39825914, "author": "Rajesh Paul", "author_id": 2758467, "author_profile": "https://Stackoverflow.com/users/2758467", "pm_score": 0, "selected": false, "text": "after_save if after_save :after_save_callback, if: Proc.new {\n //your logic when to call the callback\n }\n after_save :after_save_callback, if: :call_if_condition\n\ndef call_if_condition\n //condition for when to call the :after_save_callback method\nend\n call_if_condition after_save_callback" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16957/" ]
215,891
<p>For performance reasons, I draw the strings for my UITableViewCell in a custom view that overrides its drawRect method to draw strings directly in the view rectangle using NSString:drawInRect. This is similar to Apple's TableViewSuite Example 5-CustomTableViewCell.</p> <p>However, when I invoke setEditing on the cell to bring up the delete button, the view ends up with a squeezed appearance after the animation completes. To demonstrate this, invoke setEditing:YES on the CustomTableViewCell example mentioned above and observe the distortion. Is there any way around this or should I just revert back to using UILabels for my text?</p>
[ { "answer_id": 216382, "author": "rustyshelf", "author_id": 6044, "author_profile": "https://Stackoverflow.com/users/6044", "pm_score": 2, "selected": false, "text": "-(void)_refreshTableAndCells{\n //refresh the table\n [myCustomTableView reloadData];\n //refresh all the visible cells\n for (UITableViewCell *cell in myCustomTableView.visibleCells){\n LocationCellView *locationCell = [cell.contentView.subviews objectAtIndex:0];\n [locationCell setNeedsDisplay];\n }\n\n}\n" }, { "answer_id": 411657, "author": "lukhnos", "author_id": 51440, "author_profile": "https://Stackoverflow.com/users/51440", "pm_score": 0, "selected": false, "text": "UIViewContentModeLeft UIViewContentModeScaleToFill" }, { "answer_id": 453983, "author": "wka", "author_id": 56273, "author_profile": "https://Stackoverflow.com/users/56273", "pm_score": 4, "selected": true, "text": "contentMode UIViewContentModeLeft" }, { "answer_id": 1455601, "author": "Sam Soffes", "author_id": 118631, "author_profile": "https://Stackoverflow.com/users/118631", "pm_score": 1, "selected": false, "text": "UITableView layoutSubviews - (void)layoutSubviews {\n [super layoutSubviews];\n\n CGFloat editingPadding = 5.0;\n self.textLabel = CGRectMake((self.editing ? self.textLabel.frame.origin.x + editingPadding : self.textLabel.frame.origin.x), self.textLabel.origin.y, (self.editing ? self.textLabel.frame.size.width - editingPadding : self.textLabel.frame.size.width), self.textLabel.frame.size.height);\n}\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1967/" ]
215,896
<p>I'm writing a PHP script and the script outputs a simple text file log of the operations it performs. How would I use PHP to delete the first several lines from this file when it reaches a certain file size?</p> <p>Ideally, I would like it to keep the first two lines (date/time created and blank) and start deleting from line 3 and delete X amount of lines. I already know about the <code>filesize()</code> function, so I'll be using that to check the file size.</p> <p>Example log text:</p> <pre><code>*** LOG FILE CREATED ON 2008-10-18 AT 03:06:29 *** 2008-10-18 @ 03:06:29 CREATED: gallery/thumbs 2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_9423.JPG to gallery/IMG_9423.jpg 2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_9188.JPG to gallery/IMG_9188.jpg 2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_9236.JPG to gallery/IMG_9236.jpg 2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_9228.JPG to gallery/IMG_9228.jpg 2008-10-18 @ 03:08:03 RENAMED: gallery/IMG_3104.JPG to gallery/IMG_3104.jpg 2008-10-18 @ 03:08:03 RENAMED: gallery/First dance02.JPG to gallery/First dance02.jpg 2008-10-18 @ 03:08:03 RENAMED: gallery/BandG02.JPG to gallery/BandG02.jpg 2008-10-18 @ 03:08:03 RENAMED: gallery/official03.JPG to gallery/official03.jpg 2008-10-18 @ 03:08:03 RENAMED: gallery/Wedding32.JPG to gallery/Wedding32.jpg 2008-10-18 @ 03:08:03 RENAMED: gallery/Gettaway car16.JPG to gallery/Gettaway car16.jpg 2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/Afterparty05.jpg 2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/IMG_9254.jpg 2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/IMG_9175.jpg 2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/official05.jpg 2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/First dance01.jpg 2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/Wedding29.jpg 2008-10-18 @ 03:08:04 CREATED: gallery/thumbs/men walking.jpg </code></pre>
[ { "answer_id": 215898, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 0, "selected": false, "text": "open original file IN for reading\ncreate new output file OUT\nread the first two lines from IN\nwrite these lines to OUT\nfor each line to skip:\n read a line from IN\nfor the remainder of the file:\n read a line from IN\n write the line to OUT\nclose IN\nclose OUT\ndelete IN\nrename OUT to IN\n" }, { "answer_id": 215899, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 0, "selected": false, "text": "split" }, { "answer_id": 215901, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "$fle = file_get_contents(\"filename\");\n// skip X many newlines, overwriting the contents of the string with \"\"\n// http://us3.php.net/manual/en/function.file-put-contents.php\nfile_put_contents(\"filename\", $fle);\n" }, { "answer_id": 215909, "author": "bbxbby", "author_id": 29230, "author_profile": "https://Stackoverflow.com/users/29230", "pm_score": 3, "selected": true, "text": "$x_amount_of_lines = 30;\n$log = 'path/to/log.txt';\nif (filesize($log) >= $max_size)) {\n $file = file($log);\n $line = $file[0];\n $file = array_splice($file, 2, $x_amount_of_lines);\n $file = array_splice($file, 0, 0, array($line, \"\\n\")); // put the first line back in\n ...\n}\n" }, { "answer_id": 215916, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "$X = 100; // Number of lines to remove\n\n$lines = file('log.txt');\n$first_line = $lines[0];\n$lines = array_slice($lines, $X + 2);\n$lines = array_merge(array($first_line, \"\\n\"), $lines);\n\n// Write to file\n$file = fopen('log.txt', 'w');\nfwrite($file, implode('', $lines));\nfclose($file);\n" }, { "answer_id": 216353, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 5, "selected": false, "text": "<?php\n\n$line_to_strip = 5;\n$new_file = new SplFileObject('test2.log', 'w');\n\nforeach (new LimitIterator(new SplFileObject('test.log'), $line_to_strip) as $line)\n $new_file->fwrite($line); \n\n?>\n" }, { "answer_id": 45090213, "author": "ummdorian", "author_id": 3486547, "author_profile": "https://Stackoverflow.com/users/3486547", "pm_score": 1, "selected": false, "text": "<?php\n//--------------------------------\n// FUNCTION TO TRUNCATE LOG FILES\n//--------------------------------\nfunction trim_log_to_length($path,$numHeaderRows,$numRowsToKeep){\n $file = file($path);\n $headerRows = array_slice($file,0,$numHeaderRows);\n // if this file is long enough were we should be truncating it\n if(count($file) - $numRowsToKeep > $numHeaderRows){\n // figure out the rows we wanna keep\n $dataRowsToKeep = array_slice($file,count($file)-$numRowsToKeep,$numRowsToKeep);\n // write the file\n $newFileRows = array_merge($headerRows,$dataRowsToKeep);\n file_put_contents($path, implode($newFileRows));\n }\n}\n?>\n" }, { "answer_id": 47984317, "author": "Darshan Jadiye", "author_id": 6789971, "author_profile": "https://Stackoverflow.com/users/6789971", "pm_score": 0, "selected": false, "text": "$content = file('file.txt');\narray_splice($content, 0, 5); // this line will delete first 5 lines //change asper your requirement \nfile_put_contents('file.txt', $content);\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27025/" ]
215,908
<h3>Note</h3> <p>This is not a REBOL-specific question. You can answer it in any language.</p> <h3>Background</h3> <p>The <a href="http://www.rebol.com" rel="nofollow noreferrer">REBOL</a> language supports the creation of domain-specific languages known as "dialects" in REBOL <em>parlance</em>. I've created such a dialect for list comprehensions, which aren't natively supported in REBOL.</p> <p>A good cartesian product algorithm is needed for list comprehensions.</p> <h3>The Problem</h3> <p>I've used meta-programming to solve this, by dynamically creating and then executing a sequence of nested <code>foreach</code> statements. It works beautifully. However, because it's dynamic, the code is not very readable. REBOL doesn't do recursion well. It rapidly runs out of stack space and crashes. So a recursive solution is out of the question.</p> <p>In sum, I want to replace my meta-programming with a readable, non-recursive, "inline" algorithm, if possible. The solution can be in any language, as long as I can reproduce it in REBOL. (I can read just about any programming language: C#, C, C++, Perl, Oz, Haskell, Erlang, whatever.)</p> <p>I should stress that this algorithm needs to support an arbitrary number of sets to be "joined", since list comprehension can involve any number of sets.</p>
[ { "answer_id": 215952, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 4, "selected": true, "text": "#!/usr/bin/perl\n\nuse strict;\nuse warnings;\n\nmy @list1 = qw(1 2);\nmy @list2 = qw(3 4);\nmy @list3 = qw(5 6);\n\n# Calculate the Cartesian Product\nmy @cp = cart_prod(\\@list1, \\@list2, \\@list3);\n\n# Print the result\nforeach my $elem (@cp) {\n print join(' ', @$elem), \"\\n\";\n}\n\nsub cart_prod {\n my @sets = @_;\n my @result;\n my $result_elems = 1;\n\n # Calculate the number of elements needed in the result\n map { $result_elems *= scalar @$_ } @sets;\n return undef if $result_elems == 0;\n\n # Go through each set and add the appropriate element\n # to each element of the result\n my $scale_factor = $result_elems;\n foreach my $set (@sets)\n {\n my $set_elems = scalar @$set; # Elements in this set\n $scale_factor /= $set_elems;\n foreach my $i (0 .. $result_elems - 1) {\n # Calculate the set element to place in this position\n # of the result set.\n my $pos = $i / $scale_factor % $set_elems;\n push @{$result[$i]}, $$set[ $pos ];\n }\n }\n\n return @result;\n}\n 1 3 5\n1 3 6\n1 4 5\n1 4 6\n2 3 5\n2 3 6\n2 4 5\n2 4 6\n" }, { "answer_id": 216246, "author": "Gregory Higley", "author_id": 27779, "author_profile": "https://Stackoverflow.com/users/27779", "pm_score": 0, "selected": false, "text": "1 4 6\n2 5 6\n3 4 6\n1 5 6\n2 4 6\n3 5 6\n" }, { "answer_id": 1467360, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "cartesian: func [\n d [block! ] \n /local len set i res\n\n][\n d: copy d\n len: 1\n res: make block! foreach d d [len: len * length? d]\n len: length? d\n until [\n set: clear []\n loop i: len [insert set d/:i/1 i: i - 1]\n res: change/only res copy set\n loop i: len [\n unless tail? d/:i: next d/:i [break]\n if i = 1 [break]\n d/:i: head d/:i\n i: i - 1\n ]\n tail? d/1\n ]\n head res\n]\n" }, { "answer_id": 1835581, "author": "mpapec", "author_id": 223226, "author_profile": "https://Stackoverflow.com/users/223226", "pm_score": 1, "selected": false, "text": "use strict;\n\nprint \"@$_\\n\" for getCartesian(\n [qw(1 2)],\n [qw(3 4)],\n [qw(5 6)],\n);\n\nsub getCartesian {\n#\n my @input = @_;\n my @ret = map [$_], @{ shift @input };\n\n for my $a2 (@input) {\n @ret = map {\n my $v = $_;\n map [@$v, $_], @$a2;\n }\n @ret;\n }\n return @ret;\n}\n 1 3 5\n1 3 6\n1 4 5\n1 4 6\n2 3 5\n2 3 6\n2 4 5\n2 4 6\n" }, { "answer_id": 2365962, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "import java.util.*;\n\npublic class CartesianProduct {\n\n private List <List <String>> ls = new ArrayList <List <String>> ();\n private List <String> ls1 = new ArrayList <String> ();\n private List <String> ls2 = new ArrayList <String> ();\n private List <String> ls3 = new ArrayList <String> ();\n private List <String> ls4 = new ArrayList <String> ();\n\n public List <String> generateCartesianProduct () {\n List <String> set1 = null;\n List <String> set2 = null;\n\n ls1.add (\"a\");\n ls1.add (\"b\");\n ls1.add (\"c\");\n\n ls2.add (\"a2\");\n ls2.add (\"b2\");\n ls2.add (\"c2\");\n\n ls3.add (\"a3\");\n ls3.add (\"b3\");\n ls3.add (\"c3\");\n ls3.add (\"d3\");\n\n ls4.add (\"a4\");\n ls4.add (\"b4\");\n\n ls.add (ls1);\n ls.add (ls2);\n ls.add (ls3);\n ls.add (ls4);\n\n boolean subsetAvailabe = true;\n int setCount = 0;\n\n try{ \n set1 = augmentSet (ls.get (setCount++), ls.get (setCount));\n } catch (IndexOutOfBoundsException ex) {\n if (set1 == null) {\n set1 = ls.get(0);\n }\n return set1;\n }\n\n do {\n try {\n setCount++; \n set1 = augmentSet(set1,ls.get(setCount));\n } catch (IndexOutOfBoundsException ex) {\n subsetAvailabe = false;\n }\n } while (subsetAvailabe);\n return set1;\n }\n\n public List <String> augmentSet (List <String> set1, List <String> set2) {\n\n List <String> augmentedSet = new ArrayList <String> (set1.size () * set2.size ());\n for (String elem1 : set1) {\n for(String elem2 : set2) {\n augmentedSet.add (elem1 + \",\" + elem2);\n }\n }\n set1 = null; set2 = null;\n return augmentedSet;\n }\n\n public static void main (String [] arg) {\n CartesianProduct cp = new CartesianProduct ();\n List<String> cartesionProduct = cp.generateCartesianProduct ();\n for (String val : cartesionProduct) {\n System.out.println (val);\n }\n }\n}\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27779/" ]
215,913
<p>I have ran into an odd problem with the ActionLink method in ASP.NET MVC Beta. When using the Lambda overload from the MVC futures I cannot seem to specify a parameter pulled from ViewData.</p> <p>When I try this:</p> <pre><code>&lt;%= Html.ActionLink&lt;PhotoController&gt;(p =&gt; p.Upload(((string)ViewData["groupName"])), "upload new photo") %&gt; </code></pre> <p>The HTML contains a link with an empty URL.</p> <pre><code> &lt;a href=""&gt;upload new photo&lt;/a&gt; </code></pre> <p>However if I hard code the parameter, like this:</p> <pre><code>&lt;%= Html.ActionLink&lt;PhotoController&gt;(p =&gt; p.Upload("groupA"), "upload new photo") %&gt; </code></pre> <p>The output contains an actual URL.</p> <pre><code> &lt;a href="/group/groupA/Photo/Upload"&gt;upload new photo&lt;/a&gt; </code></pre> <p>I assume this probably has something to do with the visibility and availability of the ViewData, and it not being there when the Lambda gets evaluated by the internals of the framework. But that is just a guess.</p> <p>Am I doing something incorrect in the first sample to cause this, or is this some short of bug? </p> <p><strong>Update</strong>: I am using the latest version of the MVC futures. It has been pointed out that this works for some people. Since it doesn't work for me this makes me think that it is something specific to what I am doing. Does anybody have any suggestion for what to look at next, because this one really has me stumped.</p>
[ { "answer_id": 216398, "author": "Schotime", "author_id": 29376, "author_profile": "https://Stackoverflow.com/users/29376", "pm_score": 2, "selected": false, "text": "<%= Html.ActionLink<HomeController>(x=>x.Search((string)ViewData[\"search\"]), \"search?\") %>\n" }, { "answer_id": 217335, "author": "Jason Whitehorn", "author_id": 27860, "author_profile": "https://Stackoverflow.com/users/27860", "pm_score": 1, "selected": true, "text": "<%= Html.ActionLink<PhotoController>(p => p.Upload(null), \"upload new photo\") %>\n routes.MapRoute(\n \"Group\", \n \"group/{groupname}/{controller}/{action}/{id}\",\n new {controller = \"Photos\", action = \"View\", Id = \"\"});\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27860/" ]
215,954
<p>Does anyone know of any notepad++ plugin that saves a version of whatever I'm working on periodically? Ideally, it would save many versions with the automatic version number and the date in the title, and perhaps store them in a zipped archive to save space.</p> <p>Does something like this exist already, or shold I attempt to write such a plugin myself?</p> <p>Thanks,<br> Cameron</p> <p>P.S. It should be freeware or (preferably) open-source.</p>
[ { "answer_id": 216024, "author": "Blorgbeard", "author_id": 369, "author_profile": "https://Stackoverflow.com/users/369", "pm_score": 3, "selected": false, "text": "hg commit" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21475/" ]
215,959
<p>What's the best way to get a nice clean URL structure like stack overflow has? </p> <p>Do I need to use IIS for this? Or is there a way I can do it with some sort of mapping file in asp .net?</p> <p>The site I want this for has hundreds of pages, and is already deployed.<br> I would like a method that requires the least amount of changes possible. </p> <p>Note: </p> <ul> <li>I <strong>do not</strong> want suggestions on how to make the URLs friendly</li> <li>I <strong>do</strong> want suggestions on how to best manage these friendly URLs and how to create the mappings. </li> </ul> <p>I basically want to have each path that ends with aspx have no aspx extension and instead look like it is a folder with an index.aspx inside of it. </p> <p><a href="http://www.blahblahblahblahblah7CEE53E1.com/test.aspx" rel="nofollow noreferrer">http://www.blahblahblahblahblah7CEE53E1.com/test.aspx</a></p> <p>-></p> <p><a href="http://www.blahblahblahblahblah7CEE53E1.com/test/" rel="nofollow noreferrer">http://www.blahblahblahblahblah7CEE53E1.com/test/</a></p> <p>EDIT: I'm running IIS 6.0</p>
[ { "answer_id": 216334, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 3, "selected": true, "text": "<system.web>\n <urlMappings enabled=\"true\">\n <add url=\"~/test/\" mappedUrl=\"~/test.aspx\"/>\n </urlMappings>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
215,961
<p>I am implementing a BFS, and what it is going to do is go through an ordered tree to find the shortest solution to a puzzle.</p> <p>What i will be doing is creating a Snapshot object that holds the current position of each piece in a puzzle. I will add this Snapshot object into the queue and check if it is the solution. However, I am creating these snapshots on the fly. So is there some kind of way that will automatically generate the names of the Snapshot objects when they are put into the queue?</p> <p>or do i have to keep track of how many declarations i have made and just hard code it by saying...</p> <p>Snapshot snapshot2; Snapshot snapshot3; Snapshot snapshot4; etc..</p>
[ { "answer_id": 215995, "author": "Tomek", "author_id": 29326, "author_profile": "https://Stackoverflow.com/users/29326", "pm_score": 0, "selected": false, "text": "for (int i-0; i < constraint; i++)\nPiece \"Piece\"+i = new Piece();\n" }, { "answer_id": 216813, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 2, "selected": true, "text": "#define S(variable) snapshot#variable\n Snapshot S(1)\nSnapshot S(2)\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29326/" ]
215,963
<p>I've read the documentation on <a href="http://msdn.microsoft.com/en-us/library/ms776420(VS.85).aspx" rel="noreferrer">WideCharToMultiByte</a>, but I'm stuck on this parameter:</p> <pre><code>lpMultiByteStr [out] Pointer to a buffer that receives the converted string. </code></pre> <p>I'm not quite sure how to properly initialize the variable and feed it into the function</p>
[ { "answer_id": 215973, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 4, "selected": false, "text": "#include <string>\n\nstd::string wstrtostr(const std::wstring &wstr)\n{\n // Convert a Unicode string to an ASCII string\n std::string strTo;\n char *szTo = new char[wstr.length() + 1];\n szTo[wstr.size()] = '\\0';\n WideCharToMultiByte(CP_ACP, 0, wstr.c_str(), -1, szTo, (int)wstr.length(), NULL, NULL);\n strTo = szTo;\n delete[] szTo;\n return strTo;\n}\n\nstd::wstring strtowstr(const std::string &str)\n{\n // Convert an ASCII string to a Unicode String\n std::wstring wstrTo;\n wchar_t *wszTo = new wchar_t[str.length() + 1];\n wszTo[str.size()] = L'\\0';\n MultiByteToWideChar(CP_ACP, 0, str.c_str(), -1, wszTo, (int)str.length());\n wstrTo = wszTo;\n delete[] wszTo;\n return wstrTo;\n}\n //pX is an out parameter, it fills your variable with 10.\nvoid fillXWith10(int *pX)\n{\n *pX = 10;\n}\n\nint main(int argc, char ** argv)\n{\n int X;\n fillXWith10(&X);\n return 0;\n}\n" }, { "answer_id": 216879, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": false, "text": "#include <windows.h>\n#include <stdio.h>\n#include <wchar.h>\n#include <string.h>\n\n/* string consisting of several Asian characters */\nwchar_t wcsString[] = L\"\\u9580\\u961c\\u9640\\u963f\\u963b\\u9644\";\n\nint main() \n{\n\n size_t wcsChars = wcslen( wcsString);\n\n size_t sizeRequired = WideCharToMultiByte( 950, 0, wcsString, -1, \n NULL, 0, NULL, NULL);\n\n printf( \"Wide chars in wcsString: %u\\n\", wcsChars);\n printf( \"Bytes required for CP950 encoding (excluding NUL terminator): %u\\n\",\n sizeRequired-1);\n\n sizeRequired = WideCharToMultiByte( CP_UTF8, 0, wcsString, -1,\n NULL, 0, NULL, NULL);\n printf( \"Bytes required for UTF8 encoding (excluding NUL terminator): %u\\n\",\n sizeRequired-1);\n}\n Wide chars in wcsString: 6\nBytes required for CP950 encoding (excluding NUL terminator): 12\nBytes required for UTF8 encoding (excluding NUL terminator): 18\n" }, { "answer_id": 3999597, "author": "tfinniga", "author_id": 9042, "author_profile": "https://Stackoverflow.com/users/9042", "pm_score": 7, "selected": false, "text": "// Convert a wide Unicode string to an UTF8 string\nstd::string utf8_encode(const std::wstring &wstr)\n{\n if( wstr.empty() ) return std::string();\n int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);\n std::string strTo( size_needed, 0 );\n WideCharToMultiByte (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL);\n return strTo;\n}\n\n// Convert an UTF8 string to a wide Unicode String\nstd::wstring utf8_decode(const std::string &str)\n{\n if( str.empty() ) return std::wstring();\n int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0);\n std::wstring wstrTo( size_needed, 0 );\n MultiByteToWideChar (CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed);\n return wstrTo;\n}\n" }, { "answer_id": 66978733, "author": "WBuck", "author_id": 3358499, "author_profile": "https://Stackoverflow.com/users/3358499", "pm_score": 0, "selected": false, "text": "C WideCharToMultiByte MultiByteToWideChar null -1 null null wchar_t* utf8_decode( const char* str, int nbytes ) { \n int nchars = 0;\n if ( ( nchars = MultiByteToWideChar( CP_UTF8, \n MB_ERR_INVALID_CHARS, str, nbytes, NULL, 0 ) ) == 0 ) {\n return NULL;\n }\n\n wchar_t* wstr = NULL;\n if ( !( wstr = malloc( ( ( size_t )nchars + 1 ) * sizeof( wchar_t ) ) ) ) {\n return NULL;\n }\n\n wstr[ nchars ] = L'\\0';\n if ( MultiByteToWideChar( CP_UTF8, MB_ERR_INVALID_CHARS, \n str, nbytes, wstr, ( size_t )nchars ) == 0 ) {\n free( wstr );\n return NULL;\n }\n return wstr;\n} \n\n\nchar* utf8_encode( const wchar_t* wstr, int nchars ) {\n int nbytes = 0;\n if ( ( nbytes = WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, \n wstr, nchars, NULL, 0, NULL, NULL ) ) == 0 ) {\n return NULL;\n }\n\n char* str = NULL;\n if ( !( str = malloc( ( size_t )nbytes + 1 ) ) ) {\n return NULL;\n }\n\n str[ nbytes ] = '\\0';\n if ( WideCharToMultiByte( CP_UTF8, WC_ERR_INVALID_CHARS, \n wstr, nchars, str, nbytes, NULL, NULL ) == 0 ) {\n free( str );\n return NULL;\n }\n return str;\n}\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23120/" ]
215,971
<p>It seems <a href="http://openlaszlo.org/" rel="nofollow noreferrer">OpenLaszlo</a> can <a href="http://www.antunkarlovac.com/blog/2008/02/19/writing-an-openlaszlo-air-application/" rel="nofollow noreferrer">run on AIR</a>. What's less obvious is whether OpenLaszlo apps can use the AIR-specific APIs, like file system access. If so, how exactly is this done?</p>
[ { "answer_id": 3404703, "author": "raju-bitter", "author_id": 410652, "author_profile": "https://Stackoverflow.com/users/410652", "pm_score": 1, "selected": false, "text": "<canvas bgcolor=\"#ffffff\" debug=\"false\" height=\"100%\" width=\"100%\">\n\n <passthrough when=\"$as3\">\n import flash.events.Event;\n import flash.desktop.NativeApplication;\n </passthrough>\n\n <handler name=\"oninit\">\n NativeApplication.nativeApplication.addEventListener(Event.DEACTIVATE, __onDeactivate);\n NativeApplication.nativeApplication.addEventListener(Event.ACTIVATE, __onActivate);\n </handler>\n\n <method name=\"__onActivate\" args=\"ev\">\n Debug.info(\"onActivate\");\n Debug.info(\"frame rate is \" + this.getDisplayObject().stage.frameRate)\n </method>\n\n <method name=\"__onDeactivate\" args=\"ev\">\n Debug.info(\"onDeactivate\");\n Debug.info(\"frame rate is \" + this.getDisplayObject().stage.frameRate)\n </method>\n\n <view width=\"80%\" height=\"50%\" bgcolor=\"red\" clickable=\"true\">\n <passthrough>\n import flash.desktop.NativeApplication;\n </passthrough>\n <handler name=\"onclick\">\n NativeApplication.nativeApplication.exit();\n </handler>\n </view>\n\n</canvas>\n if ($as3) {\n // Insert some code for the SWFx runtime or AIR applications only\n}\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215971", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13041/" ]
215,988
<p>What is the Win32 API call to determine the system-wide font (in particular the color) for say Menus.</p> <p>This would be equivalent to going into Appearance Settings - Advanced - and then choosing Menu as the item to look at.</p> <p>I can use GetSysColor to find the colors of various system-wide window elements, but cannot find the equivalent for fonts.</p>
[ { "answer_id": 35338788, "author": "CodesInChaos", "author_id": 445517, "author_profile": "https://Stackoverflow.com/users/445517", "pm_score": 3, "selected": false, "text": "SystemParametersInfo SystemParametersInfo(SPI_GETNONCLIENTMETRICS, ...) NONCLIENTMETRICS LOGFONT lfCaptionFont lfSmCaptionFont lfMenuFont lfStatusFont lfMessageFont SystemParametersInfo(SPI_GETICONTITLELOGFONT, ...) LOGFONT System.System.Drawing.SystemFonts System.Windows.SystemFonts" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215988", "https://Stackoverflow.com", "https://Stackoverflow.com/users/410357/" ]
216,000
<p>I was trying to compile a program using an external compiled object coreset.o. I wrote the public01.c test file and my functions are in computation.c, both of which compiles. However its failing on linking it together. What might be the problem?</p> <pre><code>gcc -o public01.x public01.o computation.o coreset.o ld: fatal: file coreset.o: wrong ELF class: ELFCLASS64 ld: fatal: File processing errors. No output written to public01.x collect2: ld returned 1 exit status </code></pre>
[ { "answer_id": 8795449, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "sudo apt-get install ia32-libs \n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9628/" ]
216,007
<p>My PHP/MS Sql Server 2005/win 2003 Application occasionally becomes very unresponsive, the memory/cpu usage does not spike. If i try to open any new connection from sql management studio, then the it just hangs at the open connection dialog box. how to deterime the total number of active connections ms sql server 2005</p>
[ { "answer_id": 216020, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 9, "selected": true, "text": "SELECT \n DB_NAME(dbid) as DBName, \n COUNT(dbid) as NumberOfConnections,\n loginame as LoginName\nFROM\n sys.sysprocesses\nWHERE \n dbid > 0\nGROUP BY \n dbid, loginame\n SELECT \n COUNT(dbid) as TotalConnections\nFROM\n sys.sysprocesses\nWHERE \n dbid > 0\n sp_who2 'Active'\n" }, { "answer_id": 216268, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 3, "selected": false, "text": "using // Execute stored proc to read data from repository\nusing (SqlConnection conn = new SqlConnection(this.connectionString))\n{\n using (SqlCommand cmd = conn.CreateCommand())\n {\n cmd.CommandText = \"LoadFromRepository\";\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.Parameters.AddWithValue(\"@ID\", fileID);\n\n conn.Open();\n using (SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection))\n {\n if (rdr.Read())\n {\n filename = SaveToFileSystem(rdr, folderfilepath);\n }\n }\n }\n}\n" }, { "answer_id": 20545488, "author": "Mina Gabriel", "author_id": 1410185, "author_profile": "https://Stackoverflow.com/users/1410185", "pm_score": 0, "selected": false, "text": " DECLARE @temp TABLE(spid int , ecid int, status varchar(50),\n loginname varchar(50), \n hostname varchar(50),\nblk varchar(50), dbname varchar(50), cmd varchar(50), request_id int) \nINSERT INTO @temp \n\nEXEC sp_who\n\nSELECT COUNT(*) FROM @temp WHERE dbname = 'DB NAME'\n" }, { "answer_id": 38260330, "author": "Tarun Harkinia", "author_id": 1778982, "author_profile": "https://Stackoverflow.com/users/1778982", "pm_score": 0, "selected": false, "text": "SELECT DB_NAME(dbid) as DBName, hostname ,COUNT(dbid) as NumberOfConnections\nFROM sys.sysprocesses with (nolock) \nWHERE dbid > 0 \nand len(hostname) > 0 \n--and DB_NAME(dbid)='master' /* Open this line to filter Database by Name */\nGroup by DB_NAME(dbid),hostname\norder by DBName\n" }, { "answer_id": 40597699, "author": "sqldba.today", "author_id": 7158880, "author_profile": "https://Stackoverflow.com/users/7158880", "pm_score": 2, "selected": false, "text": "SELECT \n DB_NAME(dbid) as DBName, \n COUNT(dbid) as NumberOfConnections,\n loginame as LoginName\nFROM\n sys.sysprocesses with (nolock)\nWHERE \n dbid > 0\n and ecid=0\nGROUP BY \n dbid, loginame\n" }, { "answer_id": 41815139, "author": "realstrategos", "author_id": 3246002, "author_profile": "https://Stackoverflow.com/users/3246002", "pm_score": 3, "selected": false, "text": "SELECT \nDB_NAME(dbid) as DBName, \nCOUNT(dbid) as NumberOfConnections,\nloginame as LoginName, hostname, hostprocess\nFROM\nsys.sysprocesses with (nolock)\nWHERE \ndbid > 0\nGROUP BY \ndbid, loginame, hostname, hostprocess\n" }, { "answer_id": 59692933, "author": "FatemehEbrahimiNik", "author_id": 5305781, "author_profile": "https://Stackoverflow.com/users/5305781", "pm_score": 0, "selected": false, "text": "SELECT\n[DATABASE] = DB_NAME(DBID), \nOPNEDCONNECTIONS =COUNT(DBID),\n[USER] =LOGINAME\nFROM SYS.SYSPROCESSES\nGROUP BY DBID, LOGINAME\nORDER BY DB_NAME(DBID), LOGINAME\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
216,008
<p>It just happens to me about one code design question. Say, I have one "template" method that invokes some functions that may "alter". A intuitive design is to follow "Template Design Pattern". Define the altering functions to be "virtual" functions to be overridden in subclasses. Or, I can just use delegate functions without "virtual". The delegate functions is injected so that they can be customized too. </p> <p>Originally, I thought the second "delegate" way would be faster than "virtual" way, but some coding snippet proves it is not correct.</p> <p>In below code, the first DoSomething method follows "template pattern". It calls on the virtual method IsTokenChar. The second DoSomthing method doesn't depend on virtual function. Instead, it has a pass-in delegate. In my computer, the first DoSomthing is always faster than the second. The result is like 1645:1780.</p> <p>"Virtual invocation" is dynamic binding and should be more time-costing than direct delegation invocation, right? but the result shows it is not.</p> <p>Anybody can explain this? </p> <pre><code>using System; using System.Diagnostics; class Foo { public virtual bool IsTokenChar(string word) { return String.IsNullOrEmpty(word); } // this is a template method public int DoSomething(string word) { int trueCount = 0; for (int i = 0; i &lt; repeat; ++i) { if (IsTokenChar(word)) { ++trueCount; } } return trueCount; } public int DoSomething(Predicate&lt;string&gt; predicator, string word) { int trueCount = 0; for (int i = 0; i &lt; repeat; ++i) { if (predicator(word)) { ++trueCount; } } return trueCount; } private int repeat = 200000000; } class Program { static void Main(string[] args) { Foo f = new Foo(); { Stopwatch sw = Stopwatch.StartNew(); f.DoSomething(null); sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); } { Stopwatch sw = Stopwatch.StartNew(); f.DoSomething(str =&gt; String.IsNullOrEmpty(str), null); sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); } } } </code></pre>
[ { "answer_id": 216053, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "this this" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
216,019
<p>I have a .ini file with sensitive information in my php wab app. I denied access to it using a .htaccess file:</p> <pre><code>&lt;files my.ini&gt; order deny,allow deny from all &lt;/files&gt; </code></pre> <p>I don't have access to folders outside of htdocs, so I can't move the .ini file out of browsable territory.</p> <p>Is my solution safe?</p>
[ { "answer_id": 20445807, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "my.ini -> changes to my.ini.php\n ;<?php\n;die(); // For further security\n;/*\n [category]\n name=\"value\"\n\n;*/\n ;*/" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
216,030
<p>Is there a better way to do the following:</p> <pre><code>$array = array('test1', 'test2', 'test3', 'test4', 'test5'); // do a bunch of other stuff, probably a loop $array[] = 'test6'; end($array); echo key($array); // gives me 6 </code></pre> <p>This will give the key of the most recently add array element.</p> <p>Is there a better way to do this?</p>
[ { "answer_id": 216039, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 4, "selected": true, "text": "$end = end(array_keys($array));\n function array_last_key($array) {\n end($array);\n return key($array);\n}\n" }, { "answer_id": 216096, "author": "Keith Twombley", "author_id": 23866, "author_profile": "https://Stackoverflow.com/users/23866", "pm_score": 0, "selected": false, "text": "$last_added = count($array)-1;\n $array = array('test1', 'test2', 'test3', 'test4', 'test5');\n// do a bunch of other stuff, probably a loop\n$new_key = generate_key();\n$array[$new_key] = 'test6';\necho $new_key; // gives me blahblahfoobar123\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
216,037
<p>I've been thinking a lot lately about how to go about doing functional programming in C (<em>not</em> C++). Obviously, C is a procedural language and doesn't really support functional programming natively.</p> <p>Are there any compiler/language extensions that add some functional programming constructs to the language? GCC provides <a href="http://gcc.gnu.org/onlinedocs/gcc/Nested-Functions.html" rel="noreferrer">nested functions</a> as a language extension; nested functions can access variables from the parent stack frame, but this is still a long way away from mature closures.</p> <p>For example, one thing that I think could be really useful in C is that anywhere where a function pointer is expected, you could be able to pass a lambda expression, creating a closure which decays into a function pointer. C++0x is going to include lambda expressions (which I think is awesome); however, I'm looking for tools applicable to straight C.</p> <p>[Edit] To clarify, I'm not trying to solve a particular problem in C that would be more suited to functional programming; I'm merely curious about what tools are out there if I wanted to do so.</p>
[ { "answer_id": 216782, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 6, "selected": true, "text": "callback = alloc_callback(&function, data) callback(arg1, ...) function(data, arg1, ...)" }, { "answer_id": 3378514, "author": "Joe D", "author_id": 292979, "author_profile": "https://Stackoverflow.com/users/292979", "pm_score": 7, "selected": false, "text": "#define lambda(return_type, function_body) \\\n ({ \\\n return_type anon_func_name_ function_body \\\n anon_func_name_; \\\n })\n int (*max)(int, int) = lambda (int, (int x, int y) { return x > y ? x : y; });\n" }, { "answer_id": 45719313, "author": "Viktor Shepel", "author_id": 8244545, "author_profile": "https://Stackoverflow.com/users/8244545", "pm_score": 4, "selected": false, "text": "/* \n * with constraints desribed above we could have\n * good approximation of FP style in plain C\n */\n\nint increment_int(int x) {\n return x + 1;\n}\n\nWRAP_PLAIN_FUNCTION_TO_FIRST_CLASS(increment, increment_int);\n\nmap(increment, list(number(0), number(1)); // --> list(1, 2)\n\n\n/* composition of first class function is also possible */\n\nfunction_t* computation = compose(\n increment,\n increment,\n increment\n);\n\n*(int*) call(computation, number(1)) == 4;\n struct list_t {\n void* head;\n struct list_t* tail;\n};\n\nstruct function_t {\n void* (*thunk)(list_t*);\n struct list_t* arguments;\n}\n\nvoid* apply(struct function_t* fn, struct list_t* arguments) {\n return fn->thunk(concat(fn->arguments, arguments));\n}\n\n/* expansion of WRAP_PLAIN_FUNCTION_TO_FIRST_CLASS */\nvoid* increment_thunk(struct list_t* arguments) {\n int x_arg = *(int*) arguments->head;\n int value = increment_int(x_arg);\n int* number = malloc(sizeof *number);\n\n return number ? (*number = value, number) : NULL;\n}\n\nstruct function_t* increment = &(struct function_t) {\n increment_thunk,\n NULL\n};\n\n/* call(increment, number(1)) expands to */\napply(increment, &(struct list_t) { number(1), NULL });\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9530/" ]
216,049
<p>Sometimes you're developing and you decide to commit, forgetting you created a few files on your project. Then a few days down the line your buddy gets your build out of Subversion and complains that some files appear to be missing. You realize, ah crap, I forgot to add those files!</p> <p>How can I get a list of the files that are not under version control from Subversion so I'm sure I've added everything to the repository?</p>
[ { "answer_id": 216052, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 8, "selected": true, "text": "svn status svn status | grep ^?\n svn:ignore svn status" }, { "answer_id": 1082146, "author": "Damian Powell", "author_id": 30321, "author_profile": "https://Stackoverflow.com/users/30321", "pm_score": 4, "selected": false, "text": "(svn stat) -match '^\\?'\n (svn stat \"--no-ignore\") -match '^[I?]' -replace '^.\\s+','' | rm\n" }, { "answer_id": 7231214, "author": "bleater", "author_id": 316487, "author_profile": "https://Stackoverflow.com/users/316487", "pm_score": 6, "selected": false, "text": "ignore svn status svn status --no-ignore\n" }, { "answer_id": 13569623, "author": "crig", "author_id": 1131057, "author_profile": "https://Stackoverflow.com/users/1131057", "pm_score": 4, "selected": false, "text": "svn stat | find \"?\"\n" }, { "answer_id": 32780710, "author": "user2710797", "author_id": 2710797, "author_profile": "https://Stackoverflow.com/users/2710797", "pm_score": 1, "selected": false, "text": "svn status | awk '/^?/ {print $2}'\n svn status svn status svn propset svn:ignore \"PATH OR PATERN\"\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8123/" ]
216,068
<p>I am parsing an input text file. If I grab the input one line at a time using getline(), is there a way that I can search through the string to get an integer? I was thinking something similar to getNextInt() in Java. </p> <p>I know there has to be 2 numbers in that input line; however, these values will be separated by one or more white space characters, so I can't just go to a specific position.</p>
[ { "answer_id": 216072, "author": "Eclipse", "author_id": 8701, "author_profile": "https://Stackoverflow.com/users/8701", "pm_score": 3, "selected": true, "text": "int i1, i2;\nstringstream ss(lineFromGetLine);\nss >> i1 >> i2;\n int i1, i2;\ntheFileStream >> i1 >> i2;\n" }, { "answer_id": 216097, "author": "Tomek", "author_id": 29326, "author_profile": "https://Stackoverflow.com/users/29326", "pm_score": 0, "selected": false, "text": "while (!inFile.eof()) {\n getline (inFile,inputLine);\n stringstream ss(inputLine);\n ss >> rows >> columns;\n}\n" }, { "answer_id": 216770, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "while(inFile >> rows >> columns)\n{\n // Successfully read rows and columns\n\n // Now remove the extra stuff on the line you do not want.\n inFile.ignore( std::numeric_limits<std::streamsize>::max(), '\\n' );\n}\n while(inFile.eof())\n while(inFile.eof()) // Should probably test good()\n{\n getLine(inFile,inputline);\n if(inFile.eof()) // should probably test good()\n {\n break;\n }\n}\n" }, { "answer_id": 1958370, "author": "Tronic", "author_id": 238233, "author_profile": "https://Stackoverflow.com/users/238233", "pm_score": 0, "selected": false, "text": "while (std::getline(...))" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29326/" ]
216,070
<p>I'm trying to create a POST request, unfortunately the body of the POST never seems to be sent.</p> <p>Below is the code that I'm using. The code is invoked when a user clicks on a link, not a form "submit" button. It runs without error, invokes the servlet that is being called but, as I mentioned earlier, the body of the POST never seems to be sent.</p> <p>I can validate that the request body is never sent since I have access to the servlet being called.</p> <p>I've tried using "parameters" in replace of "requestBody." I've also tried using a parameter string (x=a?y=b). I've also validated that "ckULK" does contain a valid value.</p> <p>Any ideas?</p> <pre><code>new Ajax.Request(sURL, { method: 'POST' , contentType: "text/x-json" , requestBody: {ulk:ckULK} , onFailure: function(transport) { vJSONResp = transport.responseText; var JSON = eval( "(" + vJSONResp + ")" ); updateStatus(JSON.code + ": " + JSON.message); } // End onFailure , onSuccess: function(transport) { if (200 == transport.status) { vJSONResp = transport.responseText; } else { log.value += "\n" + transport.status; } } // End onSuccess }); // End Ajax.request </code></pre>
[ { "answer_id": 216074, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 4, "selected": true, "text": "parameters requestBody new Ajax.Request(sURL,\n{\n method: 'POST',\n parameters: 'hello=world&test=yes',\n onFailure: function(transport) {\n vJSONResp = transport.responseText;\n var JSON = eval( \"(\" + vJSONResp + \")\" );\n updateStatus(JSON.code + \": \" + JSON.message);\n },\n onSuccess: function(transport) {\n if (200 == transport.status) {\n vJSONResp = transport.responseText;\n } else {\n log.value += \"\\n\" + transport.status;\n }\n }\n});\n" }, { "answer_id": 217730, "author": "aemkei", "author_id": 28150, "author_profile": "https://Stackoverflow.com/users/28150", "pm_score": 1, "selected": false, "text": "parameters new Ajax.Request(url, {\n method: 'POST', \n parameters: {\n hello: \"world\", test: \"test\"\n },\n onSuccess: function(transport){\n var data = transport.responseText.evalJSON();\n }\n});\n" }, { "answer_id": 11447751, "author": "Grzegorz Gierlik", "author_id": 1483, "author_profile": "https://Stackoverflow.com/users/1483", "pm_score": 0, "selected": false, "text": "contentType Ajax.Request contentType Ajax.Request parameters postBody parameters" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4962/" ]
216,076
<p>Is it possible to scale a UIView down to 0 (width and height is 0) using CGAffineTransformMakeScale?</p> <p>view.transform = CGAffineTransformMakeScale(0.0f, 0.0f);</p> <p>Why would this throw an error of &quot;<code>&lt;Error&gt;: CGAffineTransformInvert: singular matrix.</code>&quot; ?</p> <br /> <br /> <p><em>Update: There is another way of scaling down a UIView to 0</em></p> <pre><code>[UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.3]; view.frame = CGRectMake(view.center.x, view.center.y, 0, 0); [UIView commitAnimations]; </code></pre>
[ { "answer_id": 216322, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 3, "selected": false, "text": " 0 0 0\n 0 0 0\n 0 0 1\n" }, { "answer_id": 7869373, "author": "Mike Smith", "author_id": 1009954, "author_profile": "https://Stackoverflow.com/users/1009954", "pm_score": 1, "selected": false, "text": "CGAffineTransform transform = myView.transform;\nmyView.transform = CGAffineTransformScale(transform. 0.0f, 0.0f);\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1987/" ]
216,083
<p>Looking for code samples to access a memory map file in C#</p>
[ { "answer_id": 4818216, "author": "Mubashar", "author_id": 806076, "author_profile": "https://Stackoverflow.com/users/806076", "pm_score": 1, "selected": false, "text": "CSFileMappingClient\nCSFileMappingServer\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216083", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
216,093
<p>I am working on a desktop application in PyGTK and seem to be bumping up against some limitations of my file organization. Thus far I've structured my project this way:</p> <ul> <li>application.py - holds the primary application class (most functional routines)</li> <li>gui.py - holds a loosely coupled GTK gui implementation. Handles signal callbacks, etc.</li> <li>command.py - holds command line automation functions not dependent on data in the application class</li> <li>state.py - holds the state data persistence class</li> </ul> <p>This has served fairly well so far, but at this point application.py is starting to get rather long. I have looked at numerous other PyGTK applications and they seem to have similar structural issues. At a certain point the primary module starts to get very long and there is not obvious way of breaking the code out into narrower modules without sacrificing clarity and object orientation.</p> <p>I have considered making the GUI the primary module and having seperate modules for the toolbar routines, the menus routines, etc, but at that point I believe I will lose most of the benefits of OOP and end up with an everything-references-everything scenario.</p> <p>Should I just deal with having a very long central module or is there a better way of structuring the project so that I don't have to rely on the class browser so much?</p> <p><strong>EDIT I</strong></p> <p>Ok, so point taken regarding all the MVC stuff. I do have a rough approximation of MVC in my code, but admittedly I could probably gain some mileage by further segregating the model and controller. However, I am reading over python-gtkmvc's documentation (which is a great find by the way, thank you for referencing it) and my impression is that its not going to solve my problem so much as just formalize it. My application is a single glade file, generally a single window. So no matter how tightly I define the MVC roles of the modules I'm still going to have one controller module doing most everything, which is pretty much what I have now. Admittedly I'm a little fuzzy on proper MVC implementation and I'm going to keep researching, but it doesn't look to me like this architecture is going to get any more stuff out of my main file, its just going to rename that file to controller.py.</p> <p>Should I be thinking about separate Controller/View pairs for seperate sections of the window (the toolbar, the menus, etc)? Perhaps that is what I'm missing here. It seems that this is what S. Lott is referring to in his second bullet point.</p> <p>Thanks for the responses so far.</p>
[ { "answer_id": 216113, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 0, "selected": false, "text": "myapp/\n application/\n gui/\n command/\n state/\n __init__.py" }, { "answer_id": 216145, "author": "Jaime Soriano", "author_id": 28855, "author_profile": "https://Stackoverflow.com/users/28855", "pm_score": 4, "selected": true, "text": "wader/\n cli/\n common/\n contrib/\n gtk/\n controllers/\n models/\n views/\n test/\n utils/\n" }, { "answer_id": 219737, "author": "bouvard", "author_id": 24608, "author_profile": "https://Stackoverflow.com/users/24608", "pm_score": 0, "selected": false, "text": "glade_top_widget_name" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24608/" ]
216,094
<p>I'm trying to get my head around SPL iterators and I've come up with 2 ways to handle it. I see the first version to be less complicated but the second version has composition feel to it (I think).</p> <p>What am I not seeing is which one is preferable over the other? Or am I just over complicating this?</p> <p>Here are my thoughts:</p> <p>The object implements an iterator:</p> <pre><code>class BoxOfChocolates implements Iterator { private $id private $name; // e.g. Valentine's Heart Box private $maker; // e.g. Hersheys private $items; // array public function getChocolates() { $query = ... foreach($rows as $row) { $this-&gt;_items[] = new Chocolate() ... } } // ... necessary iterator implementation stuff } </code></pre> <p>The object contains an iterate-able object:</p> <pre><code>class BoxOfChocolates { private $id; private $name; private $maker; private $items; // chocolates object public function getChocolates() { $this-&gt;items = new Chocolates(); $this-&gt;items-&gt;getChocolates(); } } class Chocolates implements Iterator { private $items; public function getChocolates() { $query = ... foreach($rows as $row) { $this-&gt;_items[] = new Chocolate() ... } } // ... necessary iterator implementation stuff } </code></pre>
[ { "answer_id": 217090, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 2, "selected": false, "text": "IteratorAggregate IteratorAggregate getIterator() Iterator getChocolated() IteratorAggregate foreach class BoxOfChocolates implements IteratorAggregate\n\n private $chocolates = array();\n\n public function getIterator() {\n return new ArrayIterator(new ArrayObject($this->chocolates)));\n }\n\n}\n $box = new BoxOfChocolates();\nforeach ($box as $chocolate) { ... }\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29230/" ]
216,102
<p>I do the following in command line:</p> <p>1) wget <a href="ftp://mirrors.kernel.org/gnu/gcc/gcc-3.4.6/gcc-3.4.6.tar.bz2" rel="nofollow noreferrer">ftp://mirrors.kernel.org/gnu/gcc/gcc-3.4.6/gcc-3.4.6.tar.bz2</a></p> <p>2) tar -jxf gcc-3.4.6.tar.bz2</p> <p>3) cd gcc-3.4.6</p> <p>4) cd libstdc++-v3</p> <p>5) ./configure</p> <p>And I get the following error:</p> <p>configure: error: cannot find install-sh or install.sh in ./../..</p> <p>There is actually an "install-sh" file in the gcc-3.4.6 directory, but that's one directory up the current, not two.</p> <p>The configure script should look for install-sh in "./.." insted of "./../.." ??</p> <p>What's wrong??</p>
[ { "answer_id": 2345565, "author": "Eric", "author_id": 165082, "author_profile": "https://Stackoverflow.com/users/165082", "pm_score": 1, "selected": false, "text": "config/autorun.sh\n./configure <options>\nmake\nmake install\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216102", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25700/" ]
216,119
<p>I want to have a function that will return the reverse of a list that it is given -- using recursion. How can I do that?</p>
[ { "answer_id": 216136, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 5, "selected": true, "text": "mylist = [1, 2, 3, 4, 5]\nbackwards = lambda l: (backwards (l[1:]) + l[:1] if l else []) \nprint backwards (mylist)\n" }, { "answer_id": 216168, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 4, "selected": false, "text": "def rev(l):\n if len(l) == 0: return []\n return [l[-1]] + rev(l[:-1])\n def rev(l):\n if not l: return []\n return [l[-1]] + rev(l[:-1])\n def rev(l):\n return [l[-1]] + rev(l[:-1]) if l else []\n def rev(l, k):\n if len(l) == 0: return k([])\n def b(res):\n return k([l[-1]] + res)\n return rev(l[:-1],b)\n\n\n>>> rev([1, 2, 3, 4, 5], lambda x: x)\n[5, 4, 3, 2, 1]\n" }, { "answer_id": 217204, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 2, "selected": false, "text": "def reverse(l, first=0, last=-1):\n if first >= len(l)/2: return\n l[first], l[last] = l[last], l[first]\n reverse(l, first+1, last-1)\n\nmylist = [1,2,3,4,5]\nprint mylist\nreverse(mylist)\nprint mylist\n" }, { "answer_id": 2105565, "author": "steve", "author_id": 255334, "author_profile": "https://Stackoverflow.com/users/255334", "pm_score": 1, "selected": false, "text": "def reverse(q):\n if len(q) != 0:\n temp = q.pop(0)\n reverse(q)\n q.append(temp)\n return q\n" }, { "answer_id": 35097940, "author": "Francis Phiri", "author_id": 4696434, "author_profile": "https://Stackoverflow.com/users/4696434", "pm_score": 2, "selected": false, "text": "def revList(alist):\n if len(alist) == 1: \n return alist #base case\n else:\n return revList(alist[1:]) + [alist[0]]\n\nprint revList([1,2,3,4])\n#prints [4,3,2,1]\n" }, { "answer_id": 35679380, "author": "Shrikant Singh", "author_id": 4337792, "author_profile": "https://Stackoverflow.com/users/4337792", "pm_score": 0, "selected": false, "text": "def reverseList(listName,newList = None):\nif newList == None:\n newList = []\nif len(listName)>0:\n newList.append((listName.pop()))\n return reverseList(listName, newList)\nelse:\n return newList\n" }, { "answer_id": 39977940, "author": "Aaditya Ura", "author_id": 5904928, "author_profile": "https://Stackoverflow.com/users/5904928", "pm_score": 0, "selected": false, "text": "def hello(x,d=[]):\n d.append(x[-1])\n if len(x)<=1:\n s=\"\".join(d)\n print(s)\n\n else:\n return hello(x[:-1])\n\nhello(\"word\")\n x[-1] # last item in the array\nx[-2:] # last two items in the array\nx[:-2] # everything except the last two items\n hello(x[:-1]) x[:-1]" }, { "answer_id": 39978152, "author": "Riccardo Petraglia", "author_id": 6769931, "author_profile": "https://Stackoverflow.com/users/6769931", "pm_score": -1, "selected": false, "text": "a = [1,2,3,4,5]\na = [a[i] for i in xrange(len(a)-1, -1, -1)] # now a is reversed!\n" }, { "answer_id": 40209266, "author": "Padmal", "author_id": 4968539, "author_profile": "https://Stackoverflow.com/users/4968539", "pm_score": 0, "selected": false, "text": "A = [1, 2, [31, 32], 4, [51, [521, [12, 25, [4, 78, 45], 456, [444, 111]],522], 53], 6]\n\ndef reverseList(L):\n\n # Empty list\n if len(L) == 0:\n return\n\n # List with one element\n if len(L) == 1:\n\n # Check if that's a list\n if isinstance(L[0], list):\n return [reverseList(L[0])]\n else:\n return L\n\n # List has more elements\n else:\n # Get the reversed version of first list as well as the first element\n return reverseList(L[1:]) + reverseList(L[:1])\n\nprint A\nprint reverseList(A)\n" }, { "answer_id": 42645088, "author": "Giwi", "author_id": 7671524, "author_profile": "https://Stackoverflow.com/users/7671524", "pm_score": 1, "selected": false, "text": " def reverse (n):\n if not n: return []\n return [n.pop()]+reverse(n)\n" }, { "answer_id": 45164573, "author": "Aran", "author_id": 3840847, "author_profile": "https://Stackoverflow.com/users/3840847", "pm_score": 3, "selected": false, "text": "if len(l) == 0: #base case\n return []\n recursive(l) #recursion case\n l = [1,2,4,6]\ndef recursive(l):\n if len(l) == 0:\n return [] # base case\n else:\n return [l.pop()] + recursive(l) # recusrive case\n\n\nprint recursive(l)\n\n>[6,4,2,1]\n" }, { "answer_id": 58619797, "author": "Kenneth Chang", "author_id": 5638346, "author_profile": "https://Stackoverflow.com/users/5638346", "pm_score": 2, "selected": false, "text": "def reverseList(lst):\n #your code here\n if not lst:\n return []\n return [lst[-1]] + reverseList(lst[:-1])\n\n\nprint(reverseList([1, 2, 3, 4, 5]))\n" }, { "answer_id": 64957363, "author": "anmol_gorakshakar", "author_id": 14222462, "author_profile": "https://Stackoverflow.com/users/14222462", "pm_score": -1, "selected": false, "text": "l1=[1,2,3,4]\nl1 = np.array(l1)\nassert l1[::-1]==[4,3,2,1]\n l1 = [*l1]\n" }, { "answer_id": 66724905, "author": "Hammad Ahmed", "author_id": 14153396, "author_profile": "https://Stackoverflow.com/users/14153396", "pm_score": -1, "selected": false, "text": "def reverse_array(arr, index):\n if index == len(arr):\n return\n\n if type(arr[index]) == type([]):\n reverse_array(arr[index], 0)\n\n current = arr[index]\n reverse_array(arr, index + 1)\n arr[len(arr) - 1 - index] = current\n return arr\n\nif __name__ == '__main__':\n print(reverse_array([[4, 5, 6, [4, 4, [5, 6, 7], 8], 8, 7]], 0))\n" }, { "answer_id": 67794251, "author": "Mohit Ranjan", "author_id": 12171344, "author_profile": "https://Stackoverflow.com/users/12171344", "pm_score": -1, "selected": false, "text": "def disp_array_reverse(inp, idx=0):\n if idx >= len(inp):\n return\n disp_array_reverse(inp, idx+1)\n print(inp[idx])\n" }, { "answer_id": 67961184, "author": "Lokesh Rajawat", "author_id": 16216340, "author_profile": "https://Stackoverflow.com/users/16216340", "pm_score": 0, "selected": false, "text": "rev lks=[2,7,3,1,9,6,5]\ndef rev(lks):\n if len(lks)<2:\n return lks\n return [lks[-1]]+rev(lks[1:-1])+[lks[0]]\nprint(rev(lks))\n" }, { "answer_id": 68056830, "author": "0x5961736972", "author_id": 13597101, "author_profile": "https://Stackoverflow.com/users/13597101", "pm_score": 0, "selected": false, "text": "import time\nimport sys\n\nsys.setrecursionlimit(10**6)\n\n\ndef reverse(ls1):\n if len(ls1) <= 1:\n return ls1\n else:\n ls1[0], ls1[-1] = ls1[-1], ls1[0]\n return [ls1[0]] + reverse(ls1[1:-1]) + [ls1[-1]]\n\n\nls = [*range(2000)]\nstart_time = time.time()\nprint(reverse(ls))\nstop_time = time.time()\nprint(f\"Total time taken: {(stop_time - start_time) * 1000} msec.\")\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11324/" ]
216,124
<p>Say I have a struct "s" with an int pointer member variable "i". I allocate memory on the heap for i in the default constructor of s. Later in some other part of the code I pass an instance of s by value to some function. Am I doing a shallow copy here? Assume I didn't implement any copy constructors or assignment operators or anything for s... just the default constructor.</p>
[ { "answer_id": 216152, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 2, "selected": false, "text": "s i i" }, { "answer_id": 216154, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 4, "selected": true, "text": "// memory leak (note that the pointer is never deleted)\nclass A\n{\n B *_b;\n public:\n A()\n : _b(new B)\n {\n }\n};\n\n// dangling ptr (who deletes the instance?)\nclass A\n{\n B *_b;\n public:\n A()\n ... (same as above)\n\n ~A()\n {\n delete _b;\n }\n};\n class A\n{\n B *_b;\n public:\n A()\n ... (same as above)\n\n ~A()\n ...\n\n A(const A &rhs)\n : _b(new B(rhs._b))\n {\n }\n\n A &operator=(const A &rhs)\n {\n B *b=new B(rhs._b);\n delete _b;\n _b=b;\n return *this;\n};\n class A : public boost::noncopyable\n{\n ...\n};\n // uses shared_ptr - note that you don't need a copy constructor or op= - \n// shared_ptr uses reference counting so the _b instance is shared and only\n// deleted when the last reference is gone - admire the simplicity!\n// it is almost exactly the same as the \"memory leak\" version, but there is no leak\nclass A\n{\n boost::shared_ptr<B> _b;\n public:\n A()\n : _b(new B)\n {\n }\n};\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
216,138
<p>Are any of you aware of a library that helps you build/manipulate SQL queries, that supports JOIN's?</p> <p>It would give a lot of flexibility i'd think if you have something where you could return an object, that has some query set, and still be able to apply JOIN's to it, subqueries and such.</p> <p>I've search around, and have only found SQL Builder, which seems very basic, and doesn't support joins. Which would be a major feature that would really make it useful.</p>
[ { "answer_id": 216149, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": false, "text": "$q = Doctrine_Query::create();\n$q->from('User u')\n->leftJoin('u.Group g')\n->innerJoin('u.Phonenumber p WITH u.id > 3')\n->leftJoin('u.Email e');\n\n$users = $q->execute();\n $c = new Criteria(AuthorPeer::DATABASE_NAME);\n\n$c->addJoin(AuthorPeer::ID, BookPeer::AUTHOR_ID, Criteria::INNER_JOIN);\n$c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::INNER_JOIN);\n$c->add(PublisherPeer::NAME, 'Some Name');\n\n$authors = AuthorPeer::doSelect($c);\n" }, { "answer_id": 216381, "author": "James Hall", "author_id": 7496, "author_profile": "https://Stackoverflow.com/users/7496", "pm_score": 1, "selected": false, "text": "app/model/post.php:\n\nclass Post extends AppModel {\n var $hasMany = array('Comment');\n}\n\napp/controller/posts_controller.php:\n\nfunction view($id) {\n $this->set('post', $this->Post->read(null, $id));\n}\n\napp/views/posts/view.ctp:\n\n<h2><?php echo $post['Post']['title']?></h2>\n<p><?php echo $post['Post']['body']; /* Might want Textile/Markdown here */ ?></p>\n<h3>Comments</h3>\n<?php foreach($post['Comment'] as $comment) { ?>\n <p><?php echo $comment['body']?></p>\n <p class=\"poster\"><?php echo $comment['name']?></p>\n<?php } ?>\n posts:\nid INT\nbody TEXT\ncreated DATETIME\n\ncomments:\nid INT\nbody TEXT\nname VARCHAR\npost_id INT\n" }, { "answer_id": 218999, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 2, "selected": false, "text": "// Build this query:\n// SELECT p.\"product_id\", p.\"product_name\", l.*\n// FROM \"products\" AS p JOIN \"line_items\" AS l\n// ON p.product_id = l.product_id\n$select = $db->select()\n ->from(array('p' => 'products'), array('product_id', 'product_name'))\n ->join(array('l' => 'line_items'), 'p.product_id = l.product_id');\n" }, { "answer_id": 8080803, "author": "anonymous", "author_id": 1039918, "author_profile": "https://Stackoverflow.com/users/1039918", "pm_score": 1, "selected": false, "text": " foreach(_from('users u')\n ->columns(\"up.email_address AS EmailAddress\", \"u.user_name AS u.UserName\")\n ->left('userprofiles up', _eq('u.id', _var('up.id')))\n ->where(_and()->add(_eq('u.is_active',1)))\n ->limit(0,10)\n ->order(\"UserName\")\n ->execute(\"myConnection\") as $user){\n\n echo sprintf(\n '<a href=\"mailto:%s\">%s</a><br/>', \n $user->EmailAdress, \n $user->UserName\n );\n }\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20538/" ]
216,141
<p>The point of this question is to create the shortest <b>not abusively slow</b> Sudoku solver. This is defined as: <b>don't recurse when there are spots on the board which can only possibly be one digit</b>.</p> <p>Here is the shortest I have so far in python:</p> <pre><code>r=range(81) s=range(1,10) def R(A): bzt={} for i in r: if A[i]!=0: continue; h={} for j in r: h[A[j]if(j/9==i/9 or j%9==i%9 or(j/27==i/27)and((j%9/3)==(i%9/3)))else 0]=1 bzt[9-len(h)]=h,i for l,(h,i)in sorted(bzt.items(),key=lambda x:x[0]): for j in s: if j not in h: A[i]=j if R(A):return 1 A[i]=0;return 0 print A;return 1 R(map(int, "080007095010020000309581000500000300400000006006000007000762409000050020820400060")) </code></pre> <p>The last line I take to be part of the cmd line input, it can be changed to:</p> <pre><code>import sys; R(map(int, sys.argv[1]); </code></pre> <p>This is similar to other sudoku golf challenges, except that I want to eliminate unnecessary recursion. Any language is acceptable. The challenge is on!</p>
[ { "answer_id": 216603, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 2, "selected": false, "text": "r=range(81);s=range(1,10)\ndef R(A):\n z={}\n for i in r:\n if A[i]!=0:continue\n h={}\n for j in r:h[A[j]if j/9==i/9 or j%9==i%9 or j/27==i/27 and j%9/3==i%9/3 else 0]=1\n z[9-len(h)]=h,i\n for l,(h,i)in sorted(z.items(),cmp,lambda x:x[0]):\n for j in s:\n if j not in h:\n A[i]=j\n if R(A):return A\n A[i]=0;return[]\n return A\n\nprint R(map(int, \"080007095010020000309581000500000300400000006006000007000762409000050020820400060\"))\n" }, { "answer_id": 217114, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": true, "text": "h[ [0,A[j]][j/9.. rest of boolean condition] 0*A[j] 1*A[j] A[j] 9 or 9or j not in h (j in h)-1 r=range(81)\ndef R(A):\n z={} \n for i in r:\n if 0==A[i]:h=dict((A[j]*(j/9==i/9or j%9==i%9or j/27==i/27and j%9/3==i%9/3),1)for j in r);z[9-len(h)]=h,i\n for l in sorted(z):\n h,i=z[l]\n for j in r[1:10]:\n if(j in h)-1:\n A[i]=j\n if R(A):return A\n A[i]=0;return[]\n return A\n" }, { "answer_id": 217569, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 2, "selected": false, "text": "r=range(81)\ndef R(A):\n if(0in A)-1:yield A;return\n def H(i):h=set(A[j]for j in r if j/9==i/9or j%9==i%9or j/27==i/27and j%9/3==i%9/3);return len(h),h,i\n l,h,i=max(H(i)for i in r if not A[i])\n for j in r[1:10]:\n if(j in h)-1:\n A[i]=j\n for S in R(A):yield S\n A[i]=0\n sixsol = map(int, \"300000080001093000040780003093800012000040000520006790600021040000530900030000051\")\nfor S in R(sixsol):\n print S\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
216,155
<p>I want to allow users to paste <code>&lt;embed&gt;</code> and <code>&lt;object&gt;</code> HTML fragments (video players) via an HTML form. The server-side code is PHP. How can I protect against malicious pasted code, JavaScript, etc? I could parse the pasted code, but I'm not sure I could account for all variations. Is there a better way?</p>
[ { "answer_id": 216157, "author": "Paolo Bergantino", "author_id": 16417, "author_profile": "https://Stackoverflow.com/users/16417", "pm_score": 3, "selected": true, "text": "EMBED OBJECT [embed url=\"http://www.whatever.com/myvideo.whatever\" ...] <EMBED> $youtube = '<object width=\"425\" height=\"344\"><param name=\"movie\" value=\"http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1\"></param> </param><embed src=\"http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" width=\"425\" height=\"344\"></embed></object>';\n\n$blip = '<embed src=\"http://blip.tv/play/AZ_iEoaIfA\" type=\"application/x-shockwave-flash\" width=\"640\" height=\"510\" allowscriptaccess=\"always\" allowfullscreen=\"true\"></embed>';\n\npreg_match_all(\"/([A-Za-z]*)\\=\\\"(.+?)\\\"/\", $youtube, $matches1);\npreg_match_all(\"/([A-Za-z]*)\\=\\\"(.+?)\\\"/\", $blip, $matches2);\nprint '<pre>' . print_r($matches1, true). '</pre>';\nprint '<pre>' . print_r($matches2, true). '</pre>';\n Array\n(\n[0] => Array\n (\n [0] => width=\"425\"\n [1] => height=\"344\"\n [2] => name=\"movie\"\n [3] => value=\"http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1\"\n [4] => src=\"http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1\"\n [5] => type=\"application/x-shockwave-flash\"\n [6] => allowfullscreen=\"true\"\n [7] => width=\"425\"\n [8] => height=\"344\"\n )\n\n[1] => Array\n (\n [0] => width\n [1] => height\n [2] => name\n [3] => value\n [4] => src\n [5] => type\n [6] => allowfullscreen\n [7] => width\n [8] => height\n )\n\n[2] => Array\n (\n [0] => 425\n [1] => 344\n [2] => movie\n [3] => http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1\n [4] => http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1\n [5] => application/x-shockwave-flash\n [6] => true\n [7] => 425\n [8] => 344\n )\n)\n\nArray\n(\n[0] => Array\n (\n [0] => src=\"http://blip.tv/play/AZ_iEoaIfA\"\n [1] => type=\"application/x-shockwave-flash\"\n [2] => width=\"640\"\n [3] => height=\"510\"\n [4] => allowscriptaccess=\"always\"\n [5] => allowfullscreen=\"true\"\n )\n\n[1] => Array\n (\n [0] => src\n [1] => type\n [2] => width\n [3] => height\n [4] => allowscriptaccess\n [5] => allowfullscreen\n )\n\n[2] => Array\n (\n [0] => http://blip.tv/play/AZ_iEoaIfA\n [1] => application/x-shockwave-flash\n [2] => 640\n [3] => 510\n [4] => always\n [5] => true\n )\n)\n is_numeric htmlentities <embed> <object>" }, { "answer_id": 216167, "author": "Doug Kaye", "author_id": 17307, "author_profile": "https://Stackoverflow.com/users/17307", "pm_score": 0, "selected": false, "text": "<embed src=\"http://blip.tv/play/AZ_iEoaIfA\" type=\"application/x-shockwave-flash\" \n width=\"640\" height=\"510\" allowscriptaccess=\"always\" allowfullscreen=\"true\"></embed>\n <object width=\"425\" height=\"344\">\n <param name=\"movie\" value=\"http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1\"></param>\n <param name=\"allowFullScreen\" value=\"true\"></param>\n <embed src=\"http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1\"\n type=\"application/x-shockwave-flash\" allowfullscreen=\"true\"\n width=\"425\" height=\"344\"></embed>\n</object>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17307/" ]
216,173
<p>Is there anything in the header of an HTTP request that would allow me to differentiate between an AJAX call and a direct browser request from a given client? Are the user agent strings usually the same regardless?</p>
[ { "answer_id": 216183, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 6, "selected": true, "text": "xmlHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
216,182
<p>When should I continue to make derived classes, and when should I just add conditionals to my code? eg for a missile</p> <pre><code>class Object; class Projectile : public Object; class Missile : public Projectile; class MissileGuided : public Missile; </code></pre> <p>Or should I implement that last one in the missile's code?</p> <pre><code>void Missile::Update() { if(homing &amp;&amp; ObjectExists(Target)) TurnTowards(Target.Pos) Pos += Motion; } </code></pre> <p>I'm thinking that for all the finer details the second one is better, because you start getting combinations of things (eg some missiles may not show on the radar, some may be destroyable, some may acquire new targets if the original is destroyed or out of range, etc)</p> <p>However then the same could be said for regular projectiles sharing properties of missiles in some cases (eg may be destroyable, large projectiles may show on radar, etc)</p> <p>And then further I could say that projectiles share properties with ships (both move, on collision they do damage, may show on radar, may be destroyable...)</p> <p>And then everything ends up back as like 3 classes:</p> <pre><code>class Entity; class Object : public Entity; class Effect : public Entity; </code></pre> <p>Where is a good point to draw the line between creating derived classes, and implementing the features in the method with flags or something?</p>
[ { "answer_id": 216194, "author": "Vlad Gudim", "author_id": 22088, "author_profile": "https://Stackoverflow.com/users/22088", "pm_score": 4, "selected": true, "text": "interface INavigable {\n Course calcCourse (Position current, Destination dest);\n}\n\n\nClass GeoStationaryRocketCPU implements INavigable {\n Course calcCourse (Position current, Destination dest) {\n return dest.getShortestRouteTo (current).getCourse();\n };\n\n}\n\nClass GuidedMissileCPU implements INavigable {\n Course calcCourse (Position current, Destination dest) {\n return dest.getLowestAltRouteTo (current).getCourse();\n };\n\n}\n\n\n\nclass Missile {\n INavigable CPU;\n\n void setCPU (INavigable CPU) {\n this.CPU = CPU;\n }\n\n void fly ()\n {\n\n ...\n course = this.CPU.calcCourse (pos, dest);\n ...\n }\n\n}\n" }, { "answer_id": 216237, "author": "milot", "author_id": 22637, "author_profile": "https://Stackoverflow.com/users/22637", "pm_score": 1, "selected": false, "text": " public abstract class Database\n {\n public virtual void Connect();\n public virtual int GetNumberOfTables();\n\n }\n public class SQLServerDatabase : Database\n {\n public override void Connect()\n {\n // SQL Implementation\n }\n\n public override int GetNumberOfTables()\n {\n // SQL Implementation\n } \n\n }\n\n\n public class OracleDatabase : Database\n {\n public override void Connect()\n {\n // Oracle Implementation\n }\n\n public override int GetNumberOfTables()\n {\n // Oracle Implementation\n } \n }\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6266/" ]
216,185
<p>Suppose to have a code like this:</p> <pre><code>&lt;div class="notSelected"&gt; &lt;label&gt;Name &lt;input type="text" name="name" id="name" /&gt; &lt;/label&gt; &lt;div class="description"&gt; Tell us what's your name to make us able to fake to be your friend when sending you an email. &lt;/div&gt; &lt;/div&gt; </code></pre> <p>Now suppose I've something like this (it's just an example) for each element of a form. I'd like to change the style from notSelected to Selected when:</p> <ul> <li>User focus on the input element</li> <li>User move the mouse over a notSelected div</li> </ul> <p>When he change focus the Selected div should became notSelected again.</p> <p>I'd like to do something like this to increment the size of the text of the selected div. Anyway it could be cool make other changes too so I'd prefer to change the class attribute.</p> <p>What is the best way to do something like this in JavaScript? Is there any JavaScript framework that can boost me doing this thing? So it will be easy to add effects like fading etc...</p> <p>I downloaded MooTools but with a fast read of the docs I did not see how to do this without having a specific ID for any of the forms div, but is the first time I use it. I've no problem using any other framework, but if you suggest one, please write also what should I look for specifically.</p>
[ { "answer_id": 216214, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 4, "selected": true, "text": "<div class=\"selectable\"> (=off) vs. <div class=\"selectable selected\"> (=on)\n $(document).ready(function(){\n\n // handle mouseover and mouseout of the parent div\n $(\"div.selectable\").mouseover(\n function() { \n $(this).addClass(\"selected\").addClass(\"mouseIsOver\");\n }\n ).mouseout(\n function() { \n $(this).removeClass(\"selected\").removeClass(\"mouseIsOver\");\n }\n );\n\n // handle focus and blur of the contained input elememt,\n // unless it has already been selected by mouse move\n $(\"div.selectable input\").focus(\n function() {\n $(this).parents(\"div.selectable\").not(\".mouseIsOver\").addClass(\"selected\");\n }\n ).blur(\n function() {\n $(this).parents(\"div.selectable\").not(\".mouseIsOver\").removeClass(\"selected\");\n }\n );\n});\n" }, { "answer_id": 216371, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": ".selectable { /* basic styles … */ }\n.selectable:hover { /* hover styles … */ }\n.selectable:active { /* focus styles … */ }\n" }, { "answer_id": 216498, "author": "whalesalad", "author_id": 21022, "author_profile": "https://Stackoverflow.com/users/21022", "pm_score": 1, "selected": false, "text": "<label for=\"username\">Username</label>\n<input type=\"text\" name=\"username\" value=\"Enter your username...\" id=\"username\" />\n" }, { "answer_id": 216563, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "$(\"div.selectable\").mouseover(function ()\n{\n // ...\n}).mouseout(function ()\n{\n // ...\n});\n" }, { "answer_id": 217966, "author": "whalesalad", "author_id": 21022, "author_profile": "https://Stackoverflow.com/users/21022", "pm_score": 0, "selected": false, "text": "$(element).hover(function(){ /* mouseover */ }, function(){ /* mouseout */ });\n $('ul#nav li').hover(function() {\n $(this).addClass('highlight');\n}, function() {\n $(this).removeClass('highlight');\n});\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21384/" ]
216,197
<p>I was using mysql++ library and compiling with GCC 3.3.4.<br> That GCC version had some bugs so I upgraded to GCC 3.4.6.<br> After upgrading GCC I rebuilt mysql++ and recompiled my program. But now I get a segmentation fault error.</p> <p>I get the following message:</p> <blockquote> <p>./mysqlTest: Symbol `_ZTVSt15basic_stringbufIcSt11char_traitsIcESaIcEE' has different size in shared object, consider re-linking.<br> Segmentation fault</p> </blockquote> <p>Is there anything I have to rebuild, relink or whatever so my apps work again ??<br> What about the mysql C API ?? mysql++ is a wrapper around it.<br> Should the mysql C API be rebuilt or something??</p> <p>please help, I dont know what to do. I need to make this work.</p>
[ { "answer_id": 216213, "author": "Mihai Limbășan", "author_id": 14444, "author_profile": "https://Stackoverflow.com/users/14444", "pm_score": 3, "selected": true, "text": "ldd ldd" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216197", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25700/" ]
216,202
<p>I have a command that runs fine if I ssh to a machine and run it, but fails when I try to run it using a remote ssh command like : </p> <pre><code>ssh user@IP &lt;command&gt; </code></pre> <p>Comparing the output of "env" using both methods resutls in different environments. When I manually login to the machine and run env, I get much more environment variables then when I run :</p> <pre><code>ssh user@IP "env" </code></pre> <p>Any idea why ?</p>
[ { "answer_id": 1472444, "author": "Ian Vaughan", "author_id": 119790, "author_profile": "https://Stackoverflow.com/users/119790", "pm_score": 7, "selected": false, "text": "ssh user@host \"source /etc/profile; /path/script.sh\" ~/.bash_profile ~/.bashrc" }, { "answer_id": 4173699, "author": "tomaszbak", "author_id": 478584, "author_profile": "https://Stackoverflow.com/users/478584", "pm_score": 6, "selected": false, "text": "#If not running interactively, don't do anything\n[ -z \"$PS1\" ] && return\n" }, { "answer_id": 9993668, "author": "dpedro", "author_id": 1310457, "author_profile": "https://Stackoverflow.com/users/1310457", "pm_score": 7, "selected": false, "text": "vi ~/.ssh/environment\n VAR1=VALUE1\nVAR2=VALUE2\n sshd PermitUserEnvironment=yes" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13523/" ]
216,203
<p>I have a 'framework' in Flex which loads and destroys child 'sections', which are instances of module classes. These have a lot of webservice and animation in them and are part of a public facing site.</p> <p>Before I remove a section from the screen I call a 'hideSection()' interface method on the instance. In this method I fade out any controls, or return false if the section wants to prevent itself from being closed. Currently it also stops any Timer instances running.</p> <p>The problem is that even with the section object removed from the stage there may be outstanding things left to happen. For instance I may have an effect running where effectEnded triggers something, or perhaps a slow webservice request might timeout and cause a error to popup.</p> <p>Because of the way the garbage collector works - sometimes that object object gets killed off sooner, and other times later. I'm trying to minimize bad things happening once a section has been closed.</p> <p>I've come up with the following possible solution. Wondered if there was a better one. </p> <ul> <li>Have a _disposed property which is set to true. Inside any event handler that could possibly have undesired behavior (after the section is closed) I would just say <code>if (_disposed) { return; }</code>.</li> <li>May also be necessary to implement an 'IDisposable' interface, like in .NET.</li> </ul> <p>Is this really my only option - or can i somehow expedite the garbage collection. Could garbage collection even happen if there were effects still running?</p> <p>I'm also curious as to whether I should set things to _null, especially timers. Or is it sufficient to just stop() a timer to get it to be garbage collected if there are no references left to it.</p>
[ { "answer_id": 216477, "author": "moritzstefaner", "author_id": 23069, "author_profile": "https://Stackoverflow.com/users/23069", "pm_score": 0, "selected": false, "text": "removeEventListener(this, listenerFunction, eventType);\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216203", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24727/" ]
216,206
<p>Does anybody know any resources on this subject?</p> <p>I'm developing an embedded application for 2x16 LCD display. Ideally I would like to have a general (display independent) framework, that could be used virtually on any display - one or more segment(s) LED, 1x16, 2x16 LCD, etc. Also would like to learn about general guidelines for such small user interfaces.</p> <p>EDIT: I'm interested in high-level functionality, how to organize the user interface - the menus, options and the user input. We don't dicuss the LCD controller issues here.</p>
[ { "answer_id": 216215, "author": "Steve Moyer", "author_id": 17008, "author_profile": "https://Stackoverflow.com/users/17008", "pm_score": 2, "selected": false, "text": "<command>[<address>][<data>] a\n ---\nf| g |b\n ---\ne| |c\n ---\n d\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1692070/" ]
216,209
<p>I'm looking for the best way to tell if an <code>&lt;mx:Image&gt;</code> has already fired the 'Event.COMPLETE' event. I want to do something if it has shown, or attach an event handler if it hasnt yet.</p> <p>something like :</p> <pre><code>if (newBackground.percentLoaded &lt; 100) </code></pre> <p>or</p> <pre><code>if (newBackground.content != null) </code></pre> <p>i was originally doing <code>newBackground.content != null</code>, but that had some cross domain issues because the sandbox wont let me access content apparently!</p> <p>i'm even a little weary of using <code>percentLoaded &lt; 100</code> in case of possible race conditions.</p> <p>yes i am familiar with <code>showEffect</code>, but that not what I want for this.</p>
[ { "answer_id": 216264, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 2, "selected": true, "text": "Event.COMPLETE mx.controls.Image \"loadingCompleted\" \"complete\" false true Event.COMPLETE" }, { "answer_id": 216696, "author": "RickDT", "author_id": 5421, "author_profile": "https://Stackoverflow.com/users/5421", "pm_score": 1, "selected": false, "text": "// this will not race \nif (myImage.bytesLoaded < myImage.bytesTotal) \n{ \n myImage.addEventListener(Event.COMPLETE, handleImageComplete); \n} \nelse \n{ \n // it's already done, do whatever you need to with it... \n}\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24727/" ]
216,212
<p>What are the best practices and rules-of-thumb to follow while maintaining code? Is it good practice to have only the production ready code in the development branch, or should untested latest code be available in the development branch?</p> <p>How do you guys maintain your development code and production code?</p> <p>Edit - Supplementary question - Does your development team follow "commit-as-soon-as-possible-and-often-even-if-the-code-contains-minor-bugs-or-is-incomplete" protocol or "commit-ONLY-perfect-code" protocol while committing code to DEVELOPMENT branch? </p>
[ { "answer_id": 216228, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 8, "selected": true, "text": "master master dev next maintenance hot-fix dev master dev master dev master rocketraman/gitworkflow" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2220518/" ]
216,233
<p>I wrote a program which includes writing and reading from database. When I run the app and try to perform writing I call the following method:</p> <pre><code>public static void AddMessage(string callID, string content) { string select = "INSERT INTO Sporocilo (oznaka_klica, smer, vsebina, prebrano, cas_zapisa) VALUES (@callId, 0, @content, 0, @insertTime)"; SqlCommand cmd = new SqlCommand(select, conn); cmd.Parameters.AddWithValue("callId", callID.ToString()); cmd.Parameters.AddWithValue("content", content); cmd.Parameters.AddWithValue("insertTime", "10.10.2008"); try { conn.Open(); cmd.ExecuteScalar(); } catch(Exception ex) { string sDummy = ex.ToString(); } finally { conn.Close(); } } </code></pre> <p>After the method call I read all the records from the table and display them in the form. The record inserted before refresh could be seen but then when I exit the app and look at the table I don't see the record.</p> <p>Does anyone know what could cause such behavior?</p>
[ { "answer_id": 216262, "author": "Russ Cam", "author_id": 1831, "author_profile": "https://Stackoverflow.com/users/1831", "pm_score": 0, "selected": false, "text": "public static int AddMessage(string callID, string content)\n {\n Int32 newProdID = 0\n string select =\n \"INSERT INTO Sporocilo (oznaka_klica, smer, vsebina, prebrano, cas_zapisa) VALUES (@callId, 0, @content, 0, @insertTime); SELECT CAST(scope_identity() AS int);\";\n SqlCommand cmd = new SqlCommand(select, conn);\n cmd.Parameters.AddWithValue(\"callId\", callID.ToString());\n cmd.Parameters.AddWithValue(\"content\", content);\n cmd.Parameters.AddWithValue(\"insertTime\", \"10.10.2008\");\n try\n {\n conn.Open();\n newProdID = (Int32)cmd.ExecuteScalar();\n }\n catch(Exception ex)\n {\n string sDummy = ex.ToString();\n }\n finally\n {\n conn.Close();\n }\n return (int)newProdID\n }\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
216,255
<p>I am writing a small program. The interface I am writing to control each repository that is made defines a method of Save(IPublicObject). I am using LINQ for the SQL Version of the repository CRUD. My question is this. I would like to have only the one method which accepts the interface type. I want to think how I can best locate the Save action for the inherited type I then pass in. </p> <p>In the book I am reading Patterns of Enterprise Application Architecture. I am leaning on the Inheritance Maping. So I create a derived object of </p> <pre><code>public class ConcretePublicObjectOne : IPublicObject{} </code></pre> <p>I want to then pass this into the Save Function of the respository. It is at this point where I am trying to think how best to say, ok we need to use "WHAT?" Save Method etc...</p> <p>Should I use a registry, configuration setting mapping the types?</p>
[ { "answer_id": 216388, "author": "Aleris", "author_id": 20417, "author_profile": "https://Stackoverflow.com/users/20417", "pm_score": 0, "selected": false, "text": "Repository.Save(publicObject)\n public class Repository {\n public void Save(IPublicObject publicObject) {\n publicObject.Save();\n }\n}\n public interface IPublicObject {\n void Save();\n}\n" }, { "answer_id": 216485, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "GetTable<T>() static void Save<T>(T item)\n where T : class, IPublicObject\n {\n using (DataContext ctx = GetDataContext())\n {\n Table<T> table = ctx.GetTable<T>();\n // for insert...\n table.InsertOnSubmit(item);\n // for update...\n table.Attach(item, true);\n // for delete...\n table.DeleteOnSubmit(item);\n\n ctx.SubmitChanges();\n\n }\n }\n T Foo foo = new Foo();\n Save(foo); // <Foo> is inferred\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67959/" ]
216,259
<p>Is there a max length for an array in C++?</p> <p>Is it a C++ limit or does it depend on my machine? Is it tweakable? Does it depend on the type the array is made of?</p> <p>Can I break that limit somehow or do I have to search for a better way of storing information? And what should be the simplest way?</p> <p>What I have to do is storing long long int on an array, I'm working in a Linux environment. My question is: what do I have to do if I need to store an array of N long long integers with N > 10 digits?</p> <p>I need this because I'm writing some cryptographic algorithm (as for example the p-Pollard) for school, and hit this wall of integers and length of arrays representation.</p>
[ { "answer_id": 216266, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 8, "selected": true, "text": "std::size_t vector<int> vector<char> int char vector<char> vector<int> int[] char[] allocator vector allocator" }, { "answer_id": 216269, "author": "Tarski", "author_id": 27653, "author_profile": "https://Stackoverflow.com/users/27653", "pm_score": 2, "selected": false, "text": " int myArray[SIZE] \n" }, { "answer_id": 216731, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 8, "selected": false, "text": "int* a1 = new int[SIZE]; // SIZE limited only by OS/Hardware\n int a2[SIZE]; // SIZE limited by COMPILER to the size of the stack frame\n" }, { "answer_id": 33325127, "author": "Three", "author_id": 3517001, "author_profile": "https://Stackoverflow.com/users/3517001", "pm_score": 0, "selected": false, "text": "long long** a = new long long*[x];\nfor (unsigned i = 0; i < x; i++) a[i] = new long long[y];\n" }, { "answer_id": 37248341, "author": "Artur Opalinski", "author_id": 6308879, "author_profile": "https://Stackoverflow.com/users/6308879", "pm_score": 2, "selected": false, "text": "int t[N] malloc() new static int t[N] size_t size_t typedef" }, { "answer_id": 38838114, "author": "Dmitry Torba", "author_id": 6664305, "author_profile": "https://Stackoverflow.com/users/6664305", "pm_score": 2, "selected": false, "text": "import os\n\ncpp_source = 'int a[{}]; int main() {{ return 0; }}'\n\ndef check_if_array_size_compiles(size):\n # Write to file 1.cpp\n f = open(name='1.cpp', mode='w')\n f.write(cpp_source.format(m))\n f.close()\n # Attempt to compile\n os.system('g++ 1.cpp 2> errors')\n # Read the errors files\n errors = open('errors', 'r').read()\n # Return if there is no errors\n return len(errors) == 0\n\n# Make a binary search. Try to create array with size m and\n# adjust the r and l border depending on wheather we succeeded\n# or not\nl = 0\nr = 10 ** 50\nwhile r - l > 1:\n m = (r + l) // 2\n if check_if_array_size_compiles(m):\n l = m\n else:\n r = m\n\nanswer = l + check_if_array_size_compiles(r)\nprint '{} is the maximum avaliable length'.format(answer)\n" }, { "answer_id": 52544668, "author": "kayleeFrye_onDeck", "author_id": 3543437, "author_profile": "https://Stackoverflow.com/users/3543437", "pm_score": 3, "selected": false, "text": "unsigned __int64 max_ints[255999996]{0};\n unsigned __int64 max_ints[255999997]{0};\n Error C1126 automatic allocation exceeds 2G 255999996 7 dc int main()\n{\n int max_ints[257400]{ 0 };\n return 0;\n}\n int main()\n{\n int max_ints[257500]{ 0 };\n return 0;\n}\n Exception thrown at 0x00007FF7DC6B1B38 in memchk.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x000000AA8DE03000). Unhandled exception at 0x00007FF7DC6B1B38 in memchk.exe: 0xC00000FD: Stack overflow (parameters: 0x0000000000000001, 0x000000AA8DE03000). int main()\n{\n int maxish_ints[257000]{ 0 };\n int more_ints[400]{ 0 };\n return 0;\n} \n int main()\n{\n int maxish_ints[257000]{ 0 };\n int more_ints[500]{ 0 };\n return 0;\n} \n" }, { "answer_id": 60627363, "author": "Joseph Wood", "author_id": 4408538, "author_profile": "https://Stackoverflow.com/users/4408538", "pm_score": 2, "selected": false, "text": "std::vector max_size() #include <iostream>\n#include <vector>\n#include <string>\n#include <limits>\n\ntemplate <typename T>\nstd::string mx(T e) {\n std::vector<T> v;\n return std::to_string(v.max_size());\n}\n\nstd::size_t maxColWidth(std::vector<std::string> v) {\n std::size_t maxWidth = 0;\n\n for (const auto &s: v)\n if (s.length() > maxWidth)\n maxWidth = s.length();\n\n // Add 2 for space on each side\n return maxWidth + 2;\n}\n\nconstexpr long double maxStdSize_t = std::numeric_limits<std::size_t>::max();\n\n// cs stands for compared to std::size_t\ntemplate <typename T>\nstd::string cs(T e) {\n std::vector<T> v;\n long double maxSize = v.max_size();\n long double quotient = maxStdSize_t / maxSize;\n return std::to_string(quotient);\n}\n\nint main() {\n bool v0 = 0;\n char v1 = 0;\n\n int8_t v2 = 0;\n int16_t v3 = 0;\n int32_t v4 = 0;\n int64_t v5 = 0;\n\n uint8_t v6 = 0;\n uint16_t v7 = 0;\n uint32_t v8 = 0;\n uint64_t v9 = 0;\n\n std::size_t v10 = 0;\n double v11 = 0;\n long double v12 = 0;\n\n std::vector<std::string> types = {\"data types\", \"bool\", \"char\", \"int8_t\", \"int16_t\",\n \"int32_t\", \"int64_t\", \"uint8_t\", \"uint16_t\",\n \"uint32_t\", \"uint64_t\", \"size_t\", \"double\",\n \"long double\"};\n\n std::vector<std::string> sizes = {\"approx max array length\", mx(v0), mx(v1), mx(v2),\n mx(v3), mx(v4), mx(v5), mx(v6), mx(v7), mx(v8),\n mx(v9), mx(v10), mx(v11), mx(v12)};\n\n std::vector<std::string> quotients = {\"max std::size_t / max array size\", cs(v0),\n cs(v1), cs(v2), cs(v3), cs(v4), cs(v5), cs(v6),\n cs(v7), cs(v8), cs(v9), cs(v10), cs(v11), cs(v12)};\n\n std::size_t max1 = maxColWidth(types);\n std::size_t max2 = maxColWidth(sizes);\n std::size_t max3 = maxColWidth(quotients);\n\n for (std::size_t i = 0; i < types.size(); ++i) {\n while (types[i].length() < (max1 - 1)) {\n types[i] = \" \" + types[i];\n }\n\n types[i] += \" \";\n\n for (int j = 0; sizes[i].length() < max2; ++j)\n sizes[i] = (j % 2 == 0) ? \" \" + sizes[i] : sizes[i] + \" \";\n\n for (int j = 0; quotients[i].length() < max3; ++j)\n quotients[i] = (j % 2 == 0) ? \" \" + quotients[i] : quotients[i] + \" \";\n\n std::cout << \"|\" << types[i] << \"|\" << sizes[i] << \"|\" << quotients[i] << \"|\\n\";\n }\n\n std::cout << std::endl;\n\n std::cout << \"N.B. max std::size_t is: \" <<\n std::numeric_limits<std::size_t>::max() << std::endl;\n\n return 0;\n}\n | data types | approx max array length | max std::size_t / max array size |\n| bool | 9223372036854775807 | 2.000000 |\n| char | 9223372036854775807 | 2.000000 |\n| int8_t | 9223372036854775807 | 2.000000 |\n| int16_t | 9223372036854775807 | 2.000000 |\n| int32_t | 4611686018427387903 | 4.000000 |\n| int64_t | 2305843009213693951 | 8.000000 |\n| uint8_t | 9223372036854775807 | 2.000000 |\n| uint16_t | 9223372036854775807 | 2.000000 |\n| uint32_t | 4611686018427387903 | 4.000000 |\n| uint64_t | 2305843009213693951 | 8.000000 |\n| size_t | 2305843009213693951 | 8.000000 |\n| double | 2305843009213693951 | 8.000000 |\n| long double | 1152921504606846975 | 16.000000 |\n\nN.B. max std::size_t is: 18446744073709551615\n | data types | approx max array length | max std::size_t / max array size |\n| bool | 9223372036854775744 | 2.000000 |\n| char | 18446744073709551615 | 1.000000 |\n| int8_t | 18446744073709551615 | 1.000000 |\n| int16_t | 9223372036854775807 | 2.000000 |\n| int32_t | 4611686018427387903 | 4.000000 |\n| int64_t | 2305843009213693951 | 8.000000 |\n| uint8_t | 18446744073709551615 | 1.000000 |\n| uint16_t | 9223372036854775807 | 2.000000 |\n| uint32_t | 4611686018427387903 | 4.000000 |\n| uint64_t | 2305843009213693951 | 8.000000 |\n| size_t | 2305843009213693951 | 8.000000 |\n| double | 2305843009213693951 | 8.000000 |\n| long double | 1152921504606846975 | 16.000000 |\n\nN.B. max std::size_t is: 18446744073709551615\n char gcc std::size_t prog.cpp: In function ‘int main()’:\nprog.cpp:5:61: error: size of array is too large\n char* a1 = new char[std::numeric_limits<std::size_t>::max()];\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22963/" ]
216,278
<p>Out style:</p> <pre><code>bool result; if(something.TryParse(val, out result)) { DoSomething(result); } </code></pre> <p>Nullable style:</p> <pre><code>bool? result = something.TryParse2(val); if(result.HasValue) { DoSomething(result.Value); } </code></pre>
[ { "answer_id": 216656, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 0, "selected": false, "text": "\nvar result = Int32.TryParse(\"123\");\n" }, { "answer_id": 216892, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 2, "selected": false, "text": "something result;\nif (something.TryParse(val, out result))\n{\n DoSomething(result);\n}\n bool result;\nif (bool.TryParse(value, out result))\n{\n DoSomething(result);\n}\n Nullable<something> result = something.TryParse2(val);\nif(result.HasValue)\n{\n DoSomething(result.Value);\n}\n bool? result = bool.TryParse2(val);\nif (result.HasValue)\n{\n DoSomething(result);\n}\n TryParse2 TryParse2 Try bool result bool TryParse TryParse" }, { "answer_id": 217661, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 0, "selected": false, "text": "TryParse" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16526/" ]
216,294
<p>I've been playing with some algorithms on the internet for a while and I can't seem to get them to work, so I'm tossing the question out here;</p> <p>I am attempting to render a velocity vector line from a point. Drawing the line isn't difficult: just insert a line with length <code>velocity.length</code> into the graph. This puts the line centered at the point in the y-axis direction. We need to get this now in the proper rotation and translation.</p> <p>The translational vector is not difficult to calculate: it is half the velocity vector. The rotational matrix, however, is being exceedingly elusive to me. Given a directional vector <code>&lt;x, y, z&gt;</code>, what's the matrix I need?</p> <p><b>Edit 1:</b> Look; if you don't understand the question, you probably won't be able to give me an answer.</p> <p>Here is what I currently have:</p> <pre> Vector3f translation = new Vector3f(); translation.scale(1f/2f, body.velocity); Vector3f vec_z = (Vector3f) body.velocity.clone(); vec_z.normalize(); Vector3f vec_y; // reference vector, will correct later if (vec_z.x == 0 && vec_z.z == 0) { vec_y = new Vector3f(-vec_z.y, 0f, 0f); // could be optimized } else { vec_y = new Vector3f(0f, 1f, 0f); } Vector3f vec_x = new Vector3f(); vec_x.cross(vec_y, vec_z); vec_z.normalize(); vec_y.cross(vec_x, vec_z); vec_y.normalize(); vec_y.negate(); Matrix3f rotation = new Matrix3f( vec_z.z, vec_z.x, vec_z.y, vec_x.z, vec_x.x, vec_x.y, vec_y.z, vec_y.x, vec_y.y ); arrowTransform3D.set(rotation, translation, 1f);</pre> <p>based off of <a href="http://www.gamedev.net/reference/articles/article665.asp" rel="nofollow noreferrer">this article</a>. And yes, I've tried the standard rotation matrix (vec_x.x, vec_y.x, etc) and it didn't work. I've been rotating the columns and rows to see if there's any effect.</p> <p><b>Edit 2:</b></p> <p>Apologies about the rude wording of my comments.</p> <p>So it looks like there were a combination of two errors; one of which House MD pointed out (really bad naming of variables: <code>vec_z</code> was actually <code>vec_y</code>, and so on), and the other was that I needed to invert the matrix before passing it off to the rendering engine (transposing was close!). So the modified code is:</p> <pre> Vector3f vec_y = (Vector3f) body.velocity.clone(); vec_y.normalize(); Vector3f vec_x; // reference vector, will correct later if (vec_y.x == 0 && vec_y.z == 0) { vec_x = new Vector3f(-vec_y.y, 0f, 0f); // could be optimized } else { vec_x = new Vector3f(0f, 1f, 0f); } Vector3f vec_z = new Vector3f(); vec_z.cross(vec_x, vec_y); vec_z.normalize(); vec_x.cross(vec_z, vec_y); vec_x.normalize(); vec_x.negate(); Matrix3f rotation = new Matrix3f( vec_x.x, vec_x.y, vec_x.z, vec_y.x, vec_y.y, vec_y.z, vec_z.x, vec_z.y, vec_z.z ); rotation.invert();</pre>
[ { "answer_id": 216319, "author": "House MD", "author_id": 29163, "author_profile": "https://Stackoverflow.com/users/29163", "pm_score": 1, "selected": true, "text": "z_vec" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23845/" ]
216,315
<p>As it was made clear in my <a href="https://stackoverflow.com/questions/212009/do-i-have-to-explicitly-call-systemexit-in-a-webstart-application">recent question</a>, Swing applications need to explicitly call System.exit() when they are ran using the Sun Webstart launcher (at least as of Java SE 6).</p> <p>I want to restrict this hack as much as possible and I am looking for a reliable way to detect whether the application is running under Webstart. Right now I am checking that the value of the system property "webstart.version" is not null, but I couldn't find any guarantees in the documentation that this property should be set by future versions/alternative implementations.</p> <p>Are there any better ways (preferably ones that do not ceate a dependency on the the webstart API?)</p>
[ { "answer_id": 216412, "author": "Oleg Barshay", "author_id": 2043539, "author_profile": "https://Stackoverflow.com/users/2043539", "pm_score": 2, "selected": false, "text": "private boolean isRunningJavaWebStart() {\n return System.getProperty(\"javawebstart.version\", null) != null;\n}\n private boolean isRunningJavaWebStart() {\n try {\n DownloadService ds = (DownloadService) ServiceManager.lookup(\"javax.jnlp.DownloadService\");\n return ds != null;\n } catch (UnavailableServiceException e) {\n return false;\n }\n}\n" }, { "answer_id": 16200769, "author": "jla", "author_id": 101151, "author_profile": "https://Stackoverflow.com/users/101151", "pm_score": 5, "selected": true, "text": "private boolean isRunningJavaWebStart() {\n boolean hasJNLP = false;\n try {\n Class.forName(\"javax.jnlp.ServiceManager\");\n hasJNLP = true;\n } catch (ClassNotFoundException ex) {\n hasJNLP = false;\n }\n return hasJNLP;\n}\n private boolean isRunningJavaWebStart() {\n try {\n ServiceManager.getServiceNames();\n return ds != null;\n } catch (NoClassDefFoundError e) {\n return false;\n }\n}\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18187/" ]
216,333
<p>When i use any of the other strongly typed HTML helpers after typing for example </p> <pre><code>Html.Actionlink&lt;HomeController&gt;(x=&gt;x. </code></pre> <p>This pops up intellisense on the methods that the HomeController class has. However for the example above, this does not happen. Only after inserting the link text (second parameter) and going back to the lambda expression does the intellisense work.</p> <p>Are other people experiencing these issues?</p> <p><strong>Update</strong> This issue is still in ASP.NET MVC RC</p>
[ { "answer_id": 216618, "author": "Paco", "author_id": 13376, "author_profile": "https://Stackoverflow.com/users/13376", "pm_score": 1, "selected": false, "text": "Html.Actionlink<YourControllerType>(x=>x.\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29376/" ]
216,341
<p>I want to apply a function to all columns in a matrix with MATLAB. For example, I'd like to be able to call smooth on every column of a matrix, instead of having smooth treat the matrix as a vector (which is the default behaviour if you call <code>smooth(matrix)</code>).</p> <p>I'm sure there must be a more idiomatic way to do this, but I can't find it, so I've defined a <code>map_column</code> function:</p> <pre><code>function result = map_column(m, func) result = m; for col = 1:size(m,2) result(:,col) = func(m(:,col)); end end </code></pre> <p>which I can call with:</p> <pre><code>smoothed = map_column(input, @(c) (smooth(c, 9))); </code></pre> <p>Is there anything wrong with this code? How could I improve it?</p>
[ { "answer_id": 216468, "author": "bastibe", "author_id": 1034, "author_profile": "https://Stackoverflow.com/users/1034", "pm_score": 0, "selected": false, "text": "m(:,:) = m(:)" }, { "answer_id": 216504, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 2, "selected": false, "text": "smoothed = smooth(input', 9)';\n" }, { "answer_id": 230817, "author": "Tim Whitcomb", "author_id": 24895, "author_profile": "https://Stackoverflow.com/users/24895", "pm_score": 3, "selected": false, "text": "function result = map_column(m, func)\n result = [];\n for m_col = m\n result = horzcat(result, func(m_col));\n end\n f = func(m_col);\nresult = horzcat(result, f(:));\n" }, { "answer_id": 739400, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "A = randn(10,5);\n cellfun(@std,mat2cell(A,size(A,1),ones(1,size(A,2))))\n\nans =\n 0.78681 1.1473 0.89789 0.66635 1.3482\n cellfun std(A,[],1)\n\nans =\n 0.78681 1.1473 0.89789 0.66635 1.3482\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3829/" ]
216,360
<p>What I'd like to accomplish is to present charts on webpages. For example aspx pages gridviews that present a two column table are able to be copied &amp; placed into Excel then a chart created. The pages I currently use most are ASP.NET 3.0 or SharePoint team sites with stored procedures. People are very interested in how people perform chats in webpages. </p> <p>Thanks in advance, Catto</p>
[ { "answer_id": 216379, "author": "Tim C", "author_id": 7585, "author_profile": "https://Stackoverflow.com/users/7585", "pm_score": 1, "selected": false, "text": "<v:shape\n fillcolor=\"green\"\n style=\"position:relative;top:1;left:1;width:200;height:200\"\n path = \"m 1,1 l 1,200, 200,200, 200,1 x e\">\n</v:shape>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216360", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17877/" ]
216,391
<p>I was just wondering, if by moving complex if else statements and the resulting html markup to the code behind violates some 'MVC' law?</p> <p>It seems like a great option when faced with inline if else statements that can become extremely unreadable.</p>
[ { "answer_id": 216866, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 2, "selected": true, "text": "HtmlHelper Html.MoneyTextBox() Html.OptionGroup() Html.Pager<T> public class CustomerInfo\n{\n public Customer Customer { get; set; }\n public bool IsEditable { get; set; } // e.g. based on current user/role\n public bool NeedFullAddress { get; set; } // e.g. based on requested action \n public bool IsEligibleForSomething { get; set; } // e.g. based on business rule\n} \n" }, { "answer_id": 217610, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 2, "selected": false, "text": "<%if (ViewData[\"something\"] == \"foo\") {%>\n <%=Html.ActionLink(\"Save\", \"Save\") %> \n<%}%>\n<%if (ViewData[\"somethingElse\"] == \"bar\") {%>\n <%=Html.ActionLink(\"Delete\", \"Delete\") %> \n<%}%>\n <%foreach (var command in (IList<ICommand>)ViewData[\"commands\"]) {%>\n <%=Html.ActionLink(command) %>\n<%}%>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29376/" ]
216,401
<p>Is there a way to set a different value for service startup timeout per service? I can change it using the ServicesPipeTimeout registry key, but it's per machine (<a href="http://support.microsoft.com/kb/824344" rel="noreferrer">http://support.microsoft.com/kb/824344</a>).</p> <p>At the moment the only thing I thought about was to do all the time-consuming startup actions in a different thread.</p>
[ { "answer_id": 909588, "author": "Hinek", "author_id": 20580, "author_profile": "https://Stackoverflow.com/users/20580", "pm_score": 6, "selected": false, "text": "protected override void OnStart()\n{\n this.RequestAdditionalTime(10000);\n // do your stuff\n}\n" }, { "answer_id": 30475302, "author": "LuckyLikey", "author_id": 4099159, "author_profile": "https://Stackoverflow.com/users/4099159", "pm_score": 2, "selected": false, "text": " protected override void OnStart(string[] args)\n {\n var task = new Task(() =>\n {\n // Do stuff\n });\n base.OnStart(args);\n task.Start();\n }\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216401", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19956/" ]
216,409
<p>I have a very strange problem, when I try to <code>var_dump</code> (or <code>print_r</code>) a Doctrine Object, my Apache responses with an empty blank page (200 OK header). I can <code>var_dump</code> a normal php var like:</p> <pre><code>$dummy = array("a" =&gt; 1, "b" =&gt;2); </code></pre> <p>And it works fine. But I can't with any object from any Doctrine class, (like a result from <code>$connection-&gt;query()</code>, or an instance of a class from my object model with Doctrine).</p> <p>Anybody knows why this happens?</p>
[ { "answer_id": 216427, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": true, "text": "print_r() ini_set('memory_limit', '256M'); var_dump print_r var_dump" }, { "answer_id": 3799164, "author": "Julien", "author_id": 457589, "author_profile": "https://Stackoverflow.com/users/457589", "pm_score": 3, "selected": false, "text": "toArray Doctrine_Record var_dump($doctrine_record->toArray());\n" }, { "answer_id": 8646048, "author": "Mariano Argañaraz", "author_id": 1117787, "author_profile": "https://Stackoverflow.com/users/1117787", "pm_score": 6, "selected": false, "text": "var_dump \\Doctrine\\Common\\Util\\Debug::dump()" }, { "answer_id": 8797559, "author": "E Ciotti", "author_id": 415032, "author_profile": "https://Stackoverflow.com/users/415032", "pm_score": 0, "selected": false, "text": "function var_dump_improved()\n{\n foreach (func_get_args() as $arg) {\n if ($args instanceof Doctrine_Collection) {\n print_r($arg);\n } else if ( $arg instanceof Traversable || is_array($arg) ) {\n // do a foreach and recall var_dump_improved on subelements\n } else if (...) {\n // other types\n } \n } \n}\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
216,426
<p>As I understand it, when asked to reserve a larger block of memory, the realloc() function will do one of three different things:</p> <p><code><pre> if free contiguous block exists grow current block else if sufficient memory allocate new memory copy old memory to new free old memory else return null </pre></code></p> <p>Growing the current block is a very cheap operation, so this is behaviour I'd like to take advantage of. However, if I'm reallocating memory because I want to (for example) insert a char at the start of an existing string, I don't want realloc() to copy the memory. I'll end up copying the entire string with realloc(), then copying it again manually to free up the first array element.</p> <p>Is it possible to determine what realloc() will do? If so, is it possible to achieve in a cross-platform way?</p>
[ { "answer_id": 216462, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 4, "selected": true, "text": "realloc() malloc()" }, { "answer_id": 216492, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "realloc() realloc() realloc() void *ptr = malloc(1024);\n...\nif ((ptr = realloc(ptr, 2048)) == 0)\n{\n /* Oops - cannot free original memory allocation any more! */\n}\n" }, { "answer_id": 242362, "author": "Jacob Krall", "author_id": 3140, "author_profile": "https://Stackoverflow.com/users/3140", "pm_score": 0, "selected": false, "text": "char* buf = malloc(1024);\nchar* start = buf + 1024 - 3;\nstart[0]='t';\nstart[1]='o';\nstart[2]='\\0';\n start-=2;\nif(start < buf) \n DO_MEMORY_STUFF(start, buf);//time to reallocate!\nstart[0]='o';\nstart[1]='n';\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2289/" ]
216,428
<p>Highly embedded (limited code and ram size) projects pose unique challenges for code organization.</p> <p>I have seen quite a few projects with no organization at all. (Mostly by hardware engineers who, in my experience are not typically concerned with non-functional aspects of code.)</p> <p>However, I have been trying to organize my code accordingly:</p> <ol> <li>hardware specific (drivers, initialization)</li> <li>application specific (not likely to be reused)</li> <li>reusable, hardware independent</li> </ol> <p>For each module I try to keep the purpose to one of these three types.</p> <p>Due to limited size of embedded projects and the emphasis on performance, it is often keep this organization.</p> <p>For some context, my current project is a limited DSP application on a MSP430 with 8k flash and 256 bytes ram.</p>
[ { "answer_id": 216532, "author": "Jason Cohen", "author_id": 4926, "author_profile": "https://Stackoverflow.com/users/4926", "pm_score": 2, "selected": false, "text": "#include" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/445087/" ]
216,430
<p>We have several websites on different domains and I'd like to be able to track users' movements on these sites.</p> <ul> <li>Obviously cookies are not feasable, because they don't cross domain borders. </li> <li>I could look at a combination of IP address and User Agent, but there are some cases where that does not work.</li> <li>I don't want to use flash or other plugins.</li> </ul> <p>Any ideas? Or am I doomed to rely on the IP/User_Agent combination?</p>
[ { "answer_id": 29267318, "author": "Neil McGuigan", "author_id": 223478, "author_profile": "https://Stackoverflow.com/users/223478", "pm_score": 3, "selected": false, "text": "If getCookie(\"c\") == null then setCookie(\"c\", \"anyValue\") uaid GET http://child.com/any-page getCookie(\"c\") is not null getCookie(\"uaid\") is null http://parent.com/give-me-a-uaid?returnTo=http://child.com/any-page http://parent.com/give-me-a-uaid uaid http://child.com/any-page?uaid=valueOfParentsUAIDCookie uaid valueOfParentsUAIDCookie http://child.com/any-page" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216430", "https://Stackoverflow.com", "https://Stackoverflow.com/users/999/" ]
216,450
<p>I have a C++ library and a C++ application trying to use functions and classes exported from the library. The library builds fine and the application compiles but fails to link. The errors I get follow this form:</p> <blockquote> <p>app-source-file.cpp:(.text+0x2fdb): undefined reference to `lib-namespace::GetStatusStr(int)'</p> </blockquote> <p>Classes in the library seem to be resolved just fine by the linker, but free functions and exported data (like a cosine lookup table) invariably result in the above error.</p> <p>I am using Ubuntu 8.04 (Hardy), and it is up to date with the latest Ubuntu packages.</p> <p>The command to link the library is (with other libraries removed):</p> <pre><code>g++ -fPIC -Wall -O3 -shared -Wl,-soname,lib-in-question.so -o ~/project/lib/release/lib-in-question.so </code></pre> <p>The command to link the application is (with other libraries removed):</p> <pre><code>g++ -fPIC -Wall -O3 -L~/project/lib/release -llib-in-question -o ~/project/release/app-in-question </code></pre> <p>Finally, it appears (as best as I can tell) that the symbols in question are being exported properly:</p> <pre><code>nm -D ~/project/lib/release/lib-in-question.so | grep GetStatusStr --&gt; U _ZN3lib-namespace12GetStatusStrEi </code></pre>
[ { "answer_id": 216488, "author": "Christian.K", "author_id": 21567, "author_profile": "https://Stackoverflow.com/users/21567", "pm_score": 2, "selected": false, "text": "g++ -fPIC -Wall -O3 -L~/project/lib/release -lfoobar\n g++ -fPIC -Wall -O3 ~/project/lib/release/libfoobar.so\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16429/" ]
216,463
<p>I would like to use a TypeCoverter to regionalise output for enums in an assembly that is a PIA loaded into Excel.</p> <p>I can run this and it works on an assembly in a test project I created with an explicitly referenceed assembly, however when running a project that has been built as an Excel PIA. If I try: _ public enum MyEnum ItemA ItemB end enum</p> <p>and in code myE = MyEnum.ItemA Dim converter As System.ComponentModel.TypeConverter = TypeDescriptor.GetConverter(myE)</p> <p>In the immediate window ? converter.ToString() goves "System.ComponentModel.EnumConverter"</p> <p>whereas in my other project (also a strongly signed assembly, but referenced directly from a newly created stub windows form project), I get</p> <p>? converter.ToString "ClassLibrary1.LocalizedEnumConverter"</p> <p>so it look like the LocalizedEnumConverter is not being bound to the enum - any ideas? Is this because of the way Excel loads the assembly, and is there a way arounfd this?</p>
[ { "answer_id": 216488, "author": "Christian.K", "author_id": 21567, "author_profile": "https://Stackoverflow.com/users/21567", "pm_score": 2, "selected": false, "text": "g++ -fPIC -Wall -O3 -L~/project/lib/release -lfoobar\n g++ -fPIC -Wall -O3 ~/project/lib/release/libfoobar.so\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6684/" ]
216,470
<ul> <li>Is there a key shortcut for this in XCode?</li> <li>Can I implement an Applescript for this and run it within XCode?</li> </ul>
[ { "answer_id": 2879198, "author": "rsfinn", "author_id": 34498, "author_profile": "https://Stackoverflow.com/users/34498", "pm_score": 1, "selected": false, "text": "[Foo alloc]<cursor>\n [Foo alloc] init<cursor>\n [[Foo alloc] init]<cursor>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216470", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
216,478
<p>We're getting ready to translate our PHP website into various languages, and the gettext support in PHP looks like the way to go.</p> <p>All the tutorials I see recommend using the english text as the message ID, i.e.</p> <p>gettext("Hi there!")</p> <p>But is that really a good idea? Let's say someone in marketing wants to change the text to "Hi there, y'all!". Then don't you have to update all the language files because that string -- which is actually the message ID -- has changed?</p> <p>Is it better to have some kind of generic ID, like "hello.message", and an english translations file?</p>
[ { "answer_id": 216807, "author": "chroder", "author_id": 18802, "author_profile": "https://Stackoverflow.com/users/18802", "pm_score": 5, "selected": true, "text": "welcome_back_1 welcome back, %1" }, { "answer_id": 35101069, "author": "Timo Huovinen", "author_id": 175071, "author_profile": "https://Stackoverflow.com/users/175071", "pm_score": 2, "selected": false, "text": "gettext _(id, backup_text, context)\n\n_('ABOUT_ME', 'About Me', 'HOMEPAGE')\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216478", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29394/" ]
216,480
<p>Somewhat-simplified example situation: I have entities A and B which are incredibly "heavy" domain objects. Loading one from the database is a pretty big deal. Then I have an entity C, which is a very simple object that has a label string, one A, and one B -- both lazy.</p> <p>I'm doing some low-level querying to create huge lists of C, so I know exactly what IDs I need to save for C.A and C.B, but I <em>don't</em> want to load up entire objects and set them to the properties, because the overhead is insane.</p> <p>Instead, I want to just insert the IDs directly into my C entities, and then let the A and B properties on it be fully loaded later only if needed.</p> <p>I see the <code>&lt;sql-insert/&gt;</code> tag in the documentation, but the section is <em>really</em> sparse. </p> <p>Is there any way to do what I want to do inside the NHibernate framework, or should I just do raw SQL? I'm trying to keep database portability if possible, which makes me shy away from the raw option. Seems like there's got to be a better way I'm missing.</p>
[ { "answer_id": 216807, "author": "chroder", "author_id": 18802, "author_profile": "https://Stackoverflow.com/users/18802", "pm_score": 5, "selected": true, "text": "welcome_back_1 welcome back, %1" }, { "answer_id": 35101069, "author": "Timo Huovinen", "author_id": 175071, "author_profile": "https://Stackoverflow.com/users/175071", "pm_score": 2, "selected": false, "text": "gettext _(id, backup_text, context)\n\n_('ABOUT_ME', 'About Me', 'HOMEPAGE')\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216480", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27614/" ]
216,484
<p>I have a groovy script with an unknown number of variables in context at runtime, how do I find them all and print the name and value of each?</p>
[ { "answer_id": 216507, "author": "Ted Naleid", "author_id": 8912, "author_profile": "https://Stackoverflow.com/users/8912", "pm_score": 6, "selected": true, "text": "foo = \"abc\"\nbar = \"def\"\n\nif (true) {\n baz = \"ghi\"\n this.binding.variables.each {k,v -> println \"$k = $v\"}\n}\n foo = abc \n baz = ghi \n args = {} \n bar = def\n" }, { "answer_id": 65493646, "author": "Amerousful", "author_id": 7512201, "author_profile": "https://Stackoverflow.com/users/7512201", "pm_score": 0, "selected": false, "text": "dump() String dump()\nGenerates a detailed dump string of an object showing its class, hashCode and fields.\n class MyClass {\n def foo = \"abc\"\n def bar = \"def\"\n}\n\n\nprintln(new MyClass().dump())\n <MyClass@1fa268de foo=abc bar=def>" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031/" ]
216,510
<p>I understand that <code>inline</code> by itself is a suggestion to the compiler, and at its discretion it may or may not inline the function, and it will also produce linkable object code.</p> <p>I think that <code>static inline</code> does the same (may or may not inline) but will not produce linkable object code when inlined (since no other module could link to it).</p> <p>Where does <code>extern inline</code> fit into the picture?</p> <p>Assume I want to replace a preprocessor macro by an inline function and require that this function gets inlined (e.g., because it uses the <code>__FILE__</code> and <code>__LINE__</code> macros which should resolve for the caller but not this called function). That is, I want to see a compiler or linker error in case the function does not get inlined. Does <code>extern inline</code> do this? (I assume that, if it does not, there is no way to achieve this behavior other than sticking with a macro.)</p> <p>Are there differences between C++ and C?</p> <p>Are there differences between different compiler vendors and versions?</p>
[ { "answer_id": 216546, "author": "puetzk", "author_id": 14312, "author_profile": "https://Stackoverflow.com/users/14312", "pm_score": 7, "selected": false, "text": "inline static inline extern inline inline extern inline static inline inline extern inline static inline static inline extern inline" }, { "answer_id": 217032, "author": "Roddy", "author_id": 1737, "author_profile": "https://Stackoverflow.com/users/1737", "pm_score": 4, "selected": false, "text": "inline void printLocation()\n{\n cout <<\"You're at \" __FILE__ \", line number\" __LINE__;\n}\n\n{\n...\n printLocation();\n...\n printLocation();\n...\n printLocation();\n #define PRINT_LOCATION {cout <<\"You're at \" __FILE__ \", line number\" __LINE__}\n\n...\n PRINT_LOCATION;\n...\n PRINT_LOCATION;\n...\n" }, { "answer_id": 11836282, "author": "enthusiasticgeek", "author_id": 264683, "author_profile": "https://Stackoverflow.com/users/264683", "pm_score": 2, "selected": false, "text": "//(c) 2012 enthusiasticgeek (LOGGING example for StackOverflow)\n\n#ifdef __cplusplus\n\n#include <cstdio>\n#include <cstring>\n\n#else\n\n#include <stdio.h>\n#include <string.h>\n\n#endif\n\n//=========== MACRO MAGIC BEGINS ============\n\n//Trim full file path\n#define __SFILE__ (strrchr(__FILE__,'/') ? strrchr(__FILE__,'/')+1 : __FILE__ )\n\n#define STRINGIFY_N(x) #x\n#define TOSTRING_N(x) STRINGIFY_N(x)\n#define _LINE (TOSTRING_N(__LINE__))\n\n#define LOG(x, s...) printf(\"(%s:%s:%s)\" x \"\\n\" , __SFILE__, __func__, _LINE, ## s);\n\n//=========== MACRO MAGIC ENDS ============\n\nint main (int argc, char** argv) {\n\n LOG(\"Greetings StackOverflow! - from enthusiasticgeek\\n\");\n\n return 0;\n}\n" }, { "answer_id": 51229603, "author": "o11c", "author_id": 1405588, "author_profile": "https://Stackoverflow.com/users/1405588", "pm_score": 2, "selected": false, "text": "__attribute__((always_inline)) alloca __forceinline __attribute__((weak))\nvoid foo(void);\ninline void foo(void) { ... }\n __declspec(selectany) __attribute__((gnu_inline))\nextern inline void foo(void) { ... }\n __declspec(dllimport) void foo(void);\ninline void foo(void) { ... }\n void foo(void) { ... }\n __declspec(dllexport) static inline void foo(void) { ... }\n static void foo(void) #include #define extern \"C\" __attribute__((noinline)) __declspec(noinline) __attribute__((flatten)) noinline [[msvc::forceinline_calls]]" }, { "answer_id": 73669629, "author": "SMMB", "author_id": 12497970, "author_profile": "https://Stackoverflow.com/users/12497970", "pm_score": 0, "selected": false, "text": "__FILE__ __LINE__ inline __FILE__ __LINE__ inline static static inline __FILE__ __LINE__ static inline inline" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216510", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
216,513
<p>Just getting started with Linq to SQL so forgive the newbie question. I'm trying to reproduce the following (working) query in Linq to SQL (VB.NET):</p> <pre><code>Select f.Title, TotalArea = Sum(c.Area) From Firms f Left Join Concessions c on c.FirmID = f.FirmID Group By f.Title Order by Sum(c.Area) DESC </code></pre> <p>(A Firm has many Concessions; a Concession has an area in hectares. I want a list of Firms starting with the ones that have the greatest total area of all their concessions.)</p> <p>I'm imagining something like this as the Linq to SQL equivalent (<strong>pseudo-code</strong>)</p> <pre><code>From f As Firm In Db.Firms _ Order By f.Concessions.Sum(Area) </code></pre> <p>... but that's not right. Can anyone point me in the right direction?</p>
[ { "answer_id": 216573, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 6, "selected": true, "text": "From c In Concessions _\nJoin f In Firms on f.FirmID equals c.FirmID _\nGroup by f.Title _\nInto TotalArea = sum(c.OfficialArea) _\nOrder by TotalArea Descending _\nSelect Title, TotalArea\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
216,523
<p>I want to ask a question about how you would approach a simple object-oriented design problem. I have a few ideas of my own about what the best way of tackling this scenario, but I would be interested in hearing some opinions from the Stack Overflow community. Links to relevant online articles are also appreciated. I'm using C#, but the question is not language specific.</p> <p>Suppose I am writing a video store application whose database has a <code>Person</code> table, with <code>PersonId</code>, <code>Name</code>, <code>DateOfBirth</code> and <code>Address</code> fields. It also has a <code>Staff</code> table, which has a link to a <code>PersonId</code>, and a <code>Customer</code> table which also links to <code>PersonId</code>.</p> <p>A simple object oriented approach would be to say that a <code>Customer</code> "is a" <code>Person</code> and therefore create classes a bit like this:</p> <pre><code>class Person { public int PersonId { get; set; } public string Name { get; set; } public DateTime DateOfBirth { get; set; } public string Address { get; set; } } class Customer : Person { public int CustomerId { get; set; } public DateTime JoinedDate { get; set; } } class Staff : Person { public int StaffId { get; set; } public string JobTitle { get; set; } } </code></pre> <p>Now we can write a function say to send emails to all customers:</p> <pre><code>static void SendEmailToCustomers(IEnumerable&lt;Person&gt; everyone) { foreach(Person p in everyone) if(p is Customer) SendEmail(p); } </code></pre> <p>This system works fine until we have someone who is both a customer and a member of staff. Assuming that we don't really want our <code>everyone</code> list to have the same person in twice, once as a <code>Customer</code> and once as a <code>Staff</code>, do we make an arbitrary choice between:</p> <pre><code>class StaffCustomer : Customer { ... </code></pre> <p>and </p> <pre><code>class StaffCustomer : Staff { ... </code></pre> <p>Obviously only the first of these two would not break the <code>SendEmailToCustomers</code> function.</p> <p>So what would you do? </p> <ul> <li>Make the <code>Person</code> class have optional references to a <code>StaffDetails</code> and <code>CustomerDetails</code> class? </li> <li>Create a new class that contained a <code>Person</code>, plus optional <code>StaffDetails</code> and <code>CustomerDetails</code>? </li> <li>Make everything an interface (e.g. <code>IPerson</code>, <code>IStaff</code>, <code>ICustomer</code>) and create three classes that implemented the appropriate interfaces? </li> <li>Take another completely different approach?</li> </ul>
[ { "answer_id": 216765, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 3, "selected": false, "text": "# --------- PERSON ----------------\n\nclass Person:\n def __init__(self, personId, name, dateOfBirth, address):\n self.personId = personId\n self.name = name\n self.dateOfBirth = dateOfBirth\n self.address = address\n self.roles = []\n\n def addRole(self, role):\n self.roles.append(role)\n\n def interestedIn(self, subject):\n for role in self.roles:\n if role.interestedIn(subject):\n return True\n return False\n\n def sendEmail(self, email):\n # send the email\n print \"Sent email to\", self.name\n\n# --------- ROLE ----------------\n\nNEW_DVDS = 1\nNEW_SCHEDULE = 2\n\nclass Role:\n def __init__(self):\n self.interests = []\n\n def interestedIn(self, subject):\n return subject in self.interests\n\nclass CustomerRole(Role):\n def __init__(self, customerId, joinedDate):\n self.customerId = customerId\n self.joinedDate = joinedDate\n self.interests.append(NEW_DVDS)\n\nclass StaffRole(Role):\n def __init__(self, staffId, jobTitle):\n self.staffId = staffId\n self.jobTitle = jobTitle\n self.interests.append(NEW_SCHEDULE)\n\n# --------- NOTIFY STUFF ----------------\n\ndef notifyNewDVDs(emailWithTitles):\n for person in persons:\n if person.interestedIn(NEW_DVDS):\n person.sendEmail(emailWithTitles)\n\n" }, { "answer_id": 17682137, "author": "jeremy", "author_id": 2588246, "author_profile": "https://Stackoverflow.com/users/2588246", "pm_score": -1, "selected": false, "text": "class Person {\n public int PersonId { get; set; }\n public string Name { get; set; }\n public DateTime DateOfBirth { get; set; }\n public string Address { get; set; }\n}\n\nclass Customer{\n public Person PersonInfo;\n public int CustomerId { get; set; }\n public DateTime JoinedDate { get; set; }\n}\n\nclass Staff {\n public Person PersonInfo;\n public int StaffId { get; set; }\n public string JobTitle { get; set; }\n}\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7532/" ]
216,536
<p>I'm relatively new to web application programming so I hope this question isn't too basic for everyone. </p> <p>I created a HTML page with a FORM containing a dojox datagrid (v1.2) filled with rows of descriptions for different grocery items. After the user selects the item he's interested in, he will click on the "Submit" button. </p> <p>At this point, I can get the javascript function to store the item ID number as a javascript variable BUT I don't know how to pass this ID onto the subsequent HTML page.</p> <p>Should I just pass the ID as an URL query string parameter? Are there any other better ways?</p> <p>EDIT: The overall process is like a shopping cart. The user will select the item from the grid and then on the next page the user will fill out some details and then checkout.</p> <p>I should also mention that I'm using grails so this is happening in a GSP page but currently it only contains HTML.</p>
[ { "answer_id": 216785, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 3, "selected": true, "text": "<html>\n <head>\n </head>\n <body>\n <script type=\"text/javascript\">\n function updateSelectedItemId() {\n document.myForm.selectedItemId.value = 2;\n alert(document.myForm.selectedItemId.value);\n\n // For you this would place the selected item id in the hidden\n // field in stead of 2, and submit the form in stead of alert\n }\n </script>\n\n Your grid comes here; it need not be in the form\n\n <form name=\"myForm\">\n <input type=\"hidden\" name=\"selectedItemId\" value=\"XXX\">\n The submit button must be in the form.\n <input type=\"button\" value=\"changeSelectedItem\" onClick=\"updateSelectedItemId()\">\n </form>\n </body>\n</html>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27163/" ]
216,538
<p>What is the best way to format a decimal if I only want decimal displayed if it is not an integer.</p> <p>Eg:</p> <pre><code>decimal amount = 1000M decimal vat = 12.50M </code></pre> <p>When formatted I want:</p> <pre><code>Amount: 1000 (not 1000.0000) Vat: 12.5 (not 12.50) </code></pre>
[ { "answer_id": 216550, "author": "Richard Nienaber", "author_id": 9539, "author_profile": "https://Stackoverflow.com/users/9539", "pm_score": 6, "selected": true, "text": " decimal one = 1000M;\n decimal two = 12.5M;\n\n Console.WriteLine(one.ToString(\"0.##\"));\n Console.WriteLine(two.ToString(\"0.##\"));\n" }, { "answer_id": 216705, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 5, "selected": false, "text": "decimal one = 1000M; \ndecimal two = 12.5M; \ndecimal three = 12.567M; \nConsole.WriteLine(one.ToString(\"G\")); \nConsole.WriteLine(two.ToString(\"G\"));\nConsole.WriteLine(three.ToString(\"G\"));\n decimal d = 0.0000000000000000000012M;\nConsole.WriteLine(d.ToString(\"G\")); // Uses fixed-point notation\nConsole.WriteLine(d.ToString(\"G29\"); // Uses scientific notation\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8547/" ]
216,542
<p>I need to figure out a way uniquely identify each computer which visits the web site I am creating. Does anybody have any advice on how to achieve this?</p> <p>Because i want the solution to work on all machines and all browsers (within reason) I am trying to create a solution using javascript.</p> <p>Cookies will not do.</p> <p>I need the ability to basically create a guid which is unique to a computer and repeatable, assuming no hardware changes have happened to the computer. Directions i am thinking of are getting the MAC of the network card and other information of this nature which will id the machine visiting the web site.</p>
[ { "answer_id": 12162449, "author": "Steve Wortham", "author_id": 102896, "author_profile": "https://Stackoverflow.com/users/102896", "pm_score": 3, "selected": false, "text": "__utma getUniqueId()" }, { "answer_id": 16376795, "author": "Mr Programmer", "author_id": 530410, "author_profile": "https://Stackoverflow.com/users/530410", "pm_score": -1, "selected": false, "text": "www.supertorrents.org" }, { "answer_id": 41575609, "author": "Walter", "author_id": 6158977, "author_profile": "https://Stackoverflow.com/users/6158977", "pm_score": 7, "selected": false, "text": "sesssion:\n sessionID: string\n // Global session data goes here\n \n computers: [{\n BrowserID: string\n ComputerID: string\n FingerprintID: string\n userID: string\n authToken: string\n ipAddresses: [\"203.525....\", \"203.525...\", ...]\n // Computer session data goes here\n }, ...]\n username password email sessionID document.cookie window.localStorage Browser|BrowserVersion|OS|OSVersion|Processor|MozzilaMajorVersion|GeckoMajorVersion getISP(requestIP)|getHTTPSClientKey() FingerPrint.get() BrowserID|ComputerID|randombytes(256) __utma getCookie(__utma).uniqueid window.localStorage var now = new Date();\nvar window.__sid = \"SessionID\"; // Server generated\n\nsetCookie(\"sid\", window.__sid, now.setFullYear(now.getFullYear() + 1, now.getMonth(), now.getDate() - 1));\n\nif( \"localStorage\" in window ) {\n window.localStorage.setItem(\"sid\", window.__sid);\n}\n window.__sid || window.localStorage.getItem(\"sid\") || getCookie(\"sid\") || \"\" SessionID setHeaders({\n \"ETag\": SessionID,\n \"Last-Modified\": new Date(0).toUTCString(),\n \"Cache-Control\": \"private, max-age=31536000, s-max-age=31536000, must-revalidate\"\n})\n Last-Modified Cache-Control If-Modified-Since If-None-Match 304 Not Modified $sid = getHeader(\"If-None-Match\") ?: getHeader(\"if-none-match\") ?: getHeader(\"IF-NONE-MATCH\") ?: \"\"; \n$ifModifiedSince = hasHeader(\"If-Modified-Since\") ?: hasHeader(\"if-modified-since\") ?: hasHeader(\"IF-MODIFIED-SINCE\");\n\nif( validateSession($sid) ) {\n if( sessionExists($sid) ) {\n continueSession($sid);\n send304();\n } else {\n startSession($sid);\n send304();\n }\n} else if( $ifModifiedSince ) {\n send304();\n} else {\n startSession();\n send200();\n}\n tracking.js 304 Not Modified tracking.js tracking.js tracking.js 304 Not Modified tracking.js tracking.js SessionID SessionID BrowserID|ComputerID|randomBytes(256)\n Timestamp|BrowserID|ComputerID|encrypt(randomBytes(256), hk)|sign(Timestamp|BrowserID|ComputerID|randomBytes(256), hk)\n hk = sign(Timestamp|BrowserID|ComputerID, serverKey) SessionID if( getTimestamp($sid) is older than 1 year ) return false;\nif( getBrowserID($sid) !== createBrowserID($_Request, $_Server) ) return false;\nif( getComputerID($sid) !== createComputerID($_Request, $_Server) return false;\n\n$hk = sign(getTimestamp($sid) + getBrowserID($sid) + getComputerID($sid), $SERVER[\"key\"]);\n\nif( !verify(getTimestamp($sid) + getBrowserID($sid) + getComputerID($sid) + decrypt(getRandomBytes($sid), hk), getSignature($sid), $hk) ) return false;\n\nreturn true; \n ComputerID BrowserID SessionID GoogleID FingerprintID if( GoogleID != getStoredGoodleID($sid) ) return false;\nif( byte_difference(FingerPrintID, getStoredFingerprint($sid) > 10%) return false;\n" }, { "answer_id": 49251772, "author": "Toolkit", "author_id": 631527, "author_profile": "https://Stackoverflow.com/users/631527", "pm_score": 2, "selected": false, "text": "new Fingerprint2().get(function(result, components) {\n console.log(result) // a hash, representing your device fingerprint\n console.log(components) // an array of FP components\n //submit hash and JSON object to the server \n})\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3746/" ]
216,588
<p>I am displaying a scrolled data table in a web page. This table has several thousands of dynamic rows, so it is loaded from the server (via AJAX).</p> <p>The user can scroll up and down, so what I need is to <strong>detect when the user reaches the end of the scrollbar</strong> (that is, the last row at the bottom of the table) in order to request and show more data.</p> <p>You can find this effect in google reader, when you scroll down to the last post in a given feed, google requests and shows new posts in a transparent way, but I can't figure out how they achieve it.</p> <p>By the way, right now I am using a <a href="http://developer.yahoo.com/yui/datatable/" rel="noreferrer">YUI Datatable</a></p>
[ { "answer_id": 216607, "author": "Yuval Adam", "author_id": 24545, "author_profile": "https://Stackoverflow.com/users/24545", "pm_score": 2, "selected": false, "text": "$wnd.onscroll = function() {\n if (($wnd.height - $wnd.scrollTop) < SOME_MARGIN) then doSomething();\n};\n" }, { "answer_id": 216613, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "scrollY content scrollY" }, { "answer_id": 216706, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 3, "selected": true, "text": "$(\".yui-dt-bd\").scroll(load_more);\n\nfunction load_more() { \n if ($(this).scrollend()) {\n alert(\"SCROLL END REACHED !\");\n // TODO load more data\n }\n}\n\n$.fn.scrollend = function() {\n return this[0].scrollHeight - this[0].scrollTop - this.height() <= 0;\n}\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12388/" ]
216,600
<p>How would I go about adding <code>enctype="multipart/form-data"</code> to a form that is generated by using <code>&lt;% Html.BeginForm(); %&gt;</code>?</p>
[ { "answer_id": 216604, "author": "liggett78", "author_id": 19762, "author_profile": "https://Stackoverflow.com/users/19762", "pm_score": 9, "selected": true, "text": "Html.BeginForm(\n action, controller, FormMethod.Post, new { enctype=\"multipart/form-data\"})\n null Html.BeginForm(\n null, null, FormMethod.Post, new { enctype=\"multipart/form-data\"})\n" }, { "answer_id": 304310, "author": "dp.", "author_id": 29092, "author_profile": "https://Stackoverflow.com/users/29092", "pm_score": 4, "selected": false, "text": "<% using (Html.BeginForm<SomeController>(x=> x.SomeAction(), \n FormMethod.Post, \n new { enctype = \"multipart/form-data\" })) \n { %>\n" }, { "answer_id": 7796172, "author": "Nick Olsen", "author_id": 489213, "author_profile": "https://Stackoverflow.com/users/489213", "pm_score": 4, "selected": false, "text": "public static MvcForm BeginMultipartForm(this HtmlHelper htmlHelper)\n{\n return htmlHelper.BeginForm(null, null, FormMethod.Post, \n new Dictionary<string, object>() { { \"enctype\", \"multipart/form-data\" } });\n}\n <% using(Html.BeginMultipartForm()) { %>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1469/" ]
216,612
<p>Does anyone know of a good dictionary API or ruby library to lookup the definitions of words?</p> <p>I'm thinking it should work something like:</p> <ol> <li>I call get_definition(word)</li> <li>It returns the definition for that word (ideally in some way to easily format the definition for display.</li> </ol> <p>Thanks</p>
[ { "answer_id": 216630, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 4, "selected": false, "text": "http://dictionary.cambridge.org/learnenglish/results.asp?searchword=SEARCH_PHRASE&dict=L\n /* BC double-click pop-up dictionary */\nvar NS = (navigator.appName == \"Netscape\" || navigator.product == 'Gecko') ? 1 : 0;\nif (NS) document.captureEvents(Event.DBLCLICK);\ndocument.ondblclick = dict;\nvar dictvar;\n\nfunction dict() {\n if (NS) {\n t = document.getSelection();\n pass_to_dictionary(t);\n } else {\n t = document.selection.createRange();\n if(document.selection.type == 'Text' && t.text != '') {\n document.selection.empty();\n pass_to_dictionary(t.text);\n }\n }\n}\n\nfunction pass_to_dictionary(text) {\n //alert(text);\n if (text > '') {\n window.open('http://dictionary.cambridge.org/learnenglish/results.asp?searchword='+text+ '&dict=L', 'dict_win', 'width=650,height=400,resizable=yes,scrollbars=yes');\n }\n}\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216612", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16876/" ]
216,616
<p>How can I construct the following string in an Excel formula:</p> <blockquote> <p>Maurice &quot;The Rocket&quot; Richard</p> </blockquote> <p>If I'm using single quotes, it's trivial: <code>=&quot;Maurice 'The Rocket' Richard&quot;</code> but what about double quotes?</p>
[ { "answer_id": 216623, "author": "YonahW", "author_id": 3821, "author_profile": "https://Stackoverflow.com/users/3821", "pm_score": 10, "selected": true, "text": "= \"Maurice \"\"The Rocket\"\" Richard\"\n" }, { "answer_id": 218474, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 7, "selected": false, "text": "CHAR = \"Maurice \" & CHAR(34) & \"Rocket\" & CHAR(34) & \" Richard\"\n" }, { "answer_id": 3503439, "author": "eric", "author_id": 422946, "author_profile": "https://Stackoverflow.com/users/422946", "pm_score": 1, "selected": false, "text": ".Formula = \"=THEFORMULAFUNCTION(\"STUFF\")\" .Formula = \"=THEFORMULAFUNCTION(CHAR(34) & STUFF & CHAR(34))\"" }, { "answer_id": 11138160, "author": "JimmyPena", "author_id": 190829, "author_profile": "https://Stackoverflow.com/users/190829", "pm_score": 3, "selected": false, "text": "Function Quote(inputText As String) As String\n Quote = Chr(34) & inputText & Chr(34)\nEnd Function\n =\"Maurice \"&Quote(\"Rocket\")&\" Richard\"" }, { "answer_id": 12737549, "author": "Adel", "author_id": 1721591, "author_profile": "https://Stackoverflow.com/users/1721591", "pm_score": 5, "selected": false, "text": "\" \" \" x \" \" \" \"x\" =CONCATENATE(\"\"\"x\"\"\",\" hi\") \n" }, { "answer_id": 14859919, "author": "Sam", "author_id": 2069425, "author_profile": "https://Stackoverflow.com/users/2069425", "pm_score": 0, "selected": false, "text": " THEFORMULAFUNCTION \"STUFF\"\n THEFORMULAFUNCTION \"STUFF\"\n" }, { "answer_id": 25291785, "author": "tandy", "author_id": 762082, "author_profile": "https://Stackoverflow.com/users/762082", "pm_score": 3, "selected": false, "text": "=CONCATENATE(\"'{\"\"service\"\": { \"\"field\"\": \"&A2&\"}}'\")\n" }, { "answer_id": 31747473, "author": "Dave", "author_id": 2773402, "author_profile": "https://Stackoverflow.com/users/2773402", "pm_score": 2, "selected": false, "text": " Joe = \"Hi there, \" & Chr(34) & \"Joe\" & Chr(34)\n ActiveCell.Value = Joe\n Hi there, \"joe\"\n" }, { "answer_id": 36169987, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "\"\" 'formula to insert into C1 - =IF(A1<>\"\", B1, \"\")\nrange(\"C1\").formula = \"=IF(A1<>\"\"\"\", B1, \"\"\"\")\" '<~quote chars doubled up\nrange(\"C1\").formula = \"=IF(A1<>TEXT(,), B1, TEXT(,))\" '<~with TEXT(,) instead\n TEXT(,) \"\" 'formula to insert into D1 - =IFERROR(VLOOKUP(A1, B:C, 2, FALSE)&\"\", \"\")\nrange(\"D1\").formula = \"=IFERROR(VLOOKUP(A1, B:C, 2, FALSE)&\"\"\"\", \"\"\"\")\"\nrange(\"D1\").formula = \"=IFERROR(VLOOKUP(A1, B:C, 2, FALSE)&TEXT(,), TEXT(,))\"\n TEXT(,) \"\"" }, { "answer_id": 36476205, "author": "Karthick Gunasekaran", "author_id": 2231100, "author_profile": "https://Stackoverflow.com/users/2231100", "pm_score": 1, "selected": false, "text": "=\"Maurice \"&\"\"\"TheRocker\"\"\"&\" Richard\"\n" }, { "answer_id": 44043792, "author": "Zon", "author_id": 1112963, "author_profile": "https://Stackoverflow.com/users/1112963", "pm_score": 2, "selected": false, "text": "\" A | B | C | D\n1 \" | text | \" | =CONCATENATE(A1; B1; C1);\n\nD1 displays \"text\"\n" }, { "answer_id": 71477835, "author": "Nathan SR", "author_id": 16923394, "author_profile": "https://Stackoverflow.com/users/16923394", "pm_score": -1, "selected": false, "text": "= \"Maurice \" & \"\"\"\" & \"The Rocket\" & \"\"\"\" & \" Richard\"\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
216,657
<p>I have a table called logs which has a datetime field. I want to select the date and count of rows based on a particular date format. </p> <p>How do I do this using SQLAlchemy?</p>
[ { "answer_id": 216730, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "SELECT date_formatter(datetime_field, \"format-specification\") AS dt_field, COUNT(*)\n FROM logs\n GROUP BY date_formatter(datetime_field, \"format-specification\")\n ORDER BY 1;\n SELECT dt_field, COUNT(*)\n FROM (SELECT date_formatter(datetime_field, \"format-specification\") AS dt_field\n FROM logs) AS necessary\n GROUP BY dt_field\n ORDER BY dt_field;\n" }, { "answer_id": 216757, "author": "Simon", "author_id": 22404, "author_profile": "https://Stackoverflow.com/users/22404", "pm_score": 1, "selected": false, "text": "query = select([logs.c.datetime, func.count(logs.c.datetime)]).group_by(logs.c.datetime)\nresults = session.execute(query).fetchall()\nresults = [(t[0].strftime(\"...\"), t[1]) for t in results]\n" }, { "answer_id": 218974, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "my_table = metadata.tables['my_table']\nfoo = my_table.c['foo']\nthe_date = func.date_trunc('month', my_table.c['when'])\nstmt = select(foo, the_date).group_by(the_date)\nengine.execute(stmt)\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
216,673
<p>When I worked on the <a href="http://framework.zend.com/manual/en/zend.db.html" rel="noreferrer">Zend Framework's database component</a>, we tried to abstract the functionality of the <code>LIMIT</code> clause supported by MySQL, PostgreSQL, and SQLite. That is, creating a query could be done this way:</p> <pre><code>$select = $db-&gt;select(); $select-&gt;from('mytable'); $select-&gt;order('somecolumn'); $select-&gt;limit(10, 20); </code></pre> <p>When the database supports <code>LIMIT</code>, this produces an SQL query like the following:</p> <pre><code>SELECT * FROM mytable ORDER BY somecolumn LIMIT 10, 20 </code></pre> <p>This was more complex for brands of database that don't support <code>LIMIT</code> (that clause is not part of the standard SQL language, by the way). If you can generate row numbers, make the whole query a derived table, and in the outer query use <code>BETWEEN</code>. This was the solution for Oracle and IBM DB2. Microsoft SQL Server 2005 has a similar row-number function, so one can write the query this way:</p> <pre><code>SELECT z2.* FROM ( SELECT ROW_NUMBER OVER(ORDER BY id) AS zend_db_rownum, z1.* FROM ( ...original SQL query... ) z1 ) z2 WHERE z2.zend_db_rownum BETWEEN @offset+1 AND @offset+@count; </code></pre> <p>However, Microsoft SQL Server 2000 doesn't have the <code>ROW_NUMBER()</code> function.</p> <p>So my question is, can you come up with a way to emulate the <code>LIMIT</code> functionality in Microsoft SQL Server 2000, solely using SQL? Without using cursors or T-SQL or a stored procedure. It has to support both arguments for <code>LIMIT</code>, both count and offset. Solutions using a temporary table are also not acceptable.</p> <p><strong>Edit:</strong></p> <p>The most common solution for MS SQL Server 2000 seems to be like the one below, for example to get rows 50 through 75:</p> <pre><code>SELECT TOP 25 * FROM ( SELECT TOP 75 * FROM table ORDER BY BY field ASC ) a ORDER BY field DESC; </code></pre> <p>However, this doesn't work if the total result set is, say 60 rows. The inner query returns 60 rows because that's in the top 75. Then the outer query returns rows 35-60, which doesn't fit in the desired "page" of 50-75. Basically, this solution works unless you need the last "page" of a result set that doesn't happen to be a multiple of the page size.</p> <p><strong>Edit:</strong></p> <p>Another solution works better, but only if you can assume the result set includes a column that is unique:</p> <pre><code>SELECT TOP n * FROM tablename WHERE key NOT IN ( SELECT TOP x key FROM tablename ORDER BY key ); </code></pre> <p><strong>Conclusion:</strong></p> <p>No general-purpose solution seems to exist for emulating <code>LIMIT</code> in MS SQL Server 2000. A good solution exists if you can use the <code>ROW_NUMBER()</code> function in MS SQL Server 2005.</p>
[ { "answer_id": 720280, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "SELECT TOP n *\nFROM tablename\nWHERE key NOT IN (\n SELECT TOP x key\n FROM tablename\n ORDER BY key\n DESC\n);\n" }, { "answer_id": 1032469, "author": "Florian Fankhauser", "author_id": 104976, "author_profile": "https://Stackoverflow.com/users/104976", "pm_score": 3, "selected": false, "text": "select * from (\n SELECT top 75 COL1, COL2\n FROM MYTABLE order by COL3\n) as foo\nexcept\nselect * from (\n SELECT top 50 COL1, COL2\n FROM MYTABLE order by COL3\n) as bar\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20860/" ]
216,674
<p>What is the best way to manage the JavaScript files and the functions/objects context in an ASP.NET MVC app?</p>
[ { "answer_id": 216729, "author": "Moran Helman", "author_id": 1409636, "author_profile": "https://Stackoverflow.com/users/1409636", "pm_score": 0, "selected": false, "text": "mainApp = function(){\n\n return {\n\n init: function(){\n\n },\n\n function1: function(){\n\n }\n\n };\n\n};\n" }, { "answer_id": 217238, "author": "VirtuosiMedia", "author_id": 13281, "author_profile": "https://Stackoverflow.com/users/13281", "pm_score": 1, "selected": false, "text": "var className = new Class ({\n\n Implements: [Events, Options],\n\n options: {\n option1: 'option1',\n option2: 'option2'\n },\n\n initialize: function(options){\n this.setOptions(options);\n },\n\n function1: function(){\n\n },\n\n function2: function(){\n\n }\n});\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216674", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1409636/" ]
216,710
<p>When I run the following, PowerShell hangs waiting for the dialog to close, even though the dialog is never displayed:</p> <pre><code>[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) $d = New-Object Windows.Forms.OpenFileDialog $d.ShowDialog( ) </code></pre> <p>Calling <code>ShowDialog</code> on a <code>Windows.Forms.Form</code> works fine. I also tried creating a <code>Form</code> and passing it as the parent to <code>$d.ShowDialog</code>, but the result was no different.</p>
[ { "answer_id": 216738, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 5, "selected": true, "text": "[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' )\n$d = New-Object Windows.Forms.OpenFileDialog\n$d.ShowHelp = $true\n$d.ShowDialog( )\n" }, { "answer_id": 216769, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 2, "selected": false, "text": "[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' )\n\n$ofn = New-Object System.Windows.Forms.OpenFileDialog\n\n$outer = New-Object System.Windows.Forms.Form\n$outer.StartPosition = [Windows.Forms.FormStartPosition] \"Manual\"\n$outer.Location = New-Object System.Drawing.Point -100, -100\n$outer.Size = New-Object System.Drawing.Size 10, 10\n$outer.add_Shown( { \n $outer.Activate();\n $ofn.ShowDialog( $outer );\n $outer.Close();\n } )\n$outer.ShowDialog()\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2495/" ]
216,716
<p>In a <a href="https://stackoverflow.com/questions/215933/gcc-compiler-error-on-windows-xp">recent issue</a>, I've found that DJGPP can only accept the DOS command line character limit. To work around this limitation, I've decided to try to write a makefile to allow me to <a href="http://www.delorie.com/djgpp/v2faq/faq16_4.html" rel="nofollow noreferrer">pass longer strings</a>. In the process of hacking together a makefile and testing it, I've come across a strange error. The makefile is as follows:</p> <pre><code>AS := nasm CC := gcc LD := ld TARGET := $(shell basename $(CURDIR)) BUILD := build SOURCES := source CFLAGS := -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-functions \ -nostdinc -fno-builtin -I./include ASFLAGS := -f aout export OUTPUT := $(CURDIR)/$(TARGET) CFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.c))) SFILES := $(foreach dir,$(SOURCES),$(notdir $(wildcard $(dir)/*.s))) SOBJS := $(SFILES:.s=.o) COBJS := $(CFILES:.c=.o) OBJS := $(SOBJS) $(COBJS) build : $(TARGET).img $(TARGET).img : $(TARGET).bin concat.py $(TARGET).bin : $(OBJS) $(LD) -T link.ld -o $@ $^ $(SOBJS) : %.o : %.asm $(AS) $(ASFLAGS) $&lt; -o $@ $(COBJS) : %.o : %.c $(CC) -c $&lt; $(CFLAGS) -o $@ </code></pre> <p>When attempting to run it, I receive this error:</p> <pre>make: *** No rule to make target `consoleio.c', needed by `consoleio.o'. Stop.</pre> <p>What I don't understand is why it's trying to find a rule for .c files. From what I understand, if the file is there, it should just use it. How do I make make not need a rule for .c files?</p>
[ { "answer_id": 216767, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": ".s .asm %.o : %.asm" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1256/" ]
216,748
<p>What are the pros and cons of using nested public C++ classes and enumerations? For example, suppose you have a class called <code>printer</code>, and this class also stores information on output trays, you could have:</p> <pre><code>class printer { public: std::string name_; enum TYPE { TYPE_LOCAL, TYPE_NETWORK, }; class output_tray { ... }; ... }; printer prn; printer::TYPE type; printer::output_tray tray; </code></pre> <p>Alternatively:</p> <pre><code>class printer { public: std::string name_; ... }; enum PRINTER_TYPE { PRINTER_TYPE_LOCAL, PRINTER_TYPE_NETWORK, }; class output_tray { ... }; printer prn; PRINTER_TYPE type; output_tray tray; </code></pre> <p>I can see the benefits of nesting private enums/classes, but when it comes to public ones, the office is split - it seems to be more of a style choice.</p> <p>So, which do you prefer and why?</p>
[ { "answer_id": 216760, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 7, "selected": true, "text": "class A\n{\n public :\n class B { /* etc. */ } ;\n\n // etc.\n} ;\n class A\n{\n public :\n class B ;\n\n // etc.\n} ;\n\nclass A::B\n{\n public :\n\n // etc.\n} ;\n // collision\nenum Value { empty = 7, undefined, defined } ;\nenum Glass { empty = 42, half, full } ;\n\n// empty is from Value or Glass?\n namespace Value { enum type { empty = 7, undefined, defined } ; }\nnamespace Glass { enum type { empty = 42, half, full } ; }\n\n// Value::type e = Value::empty ;\n// Glass::type f = Glass::empty ;\n enum class Value { empty, undefined, defined } ;\nenum class Glass { empty, half, full } ;\n\n// Value e = Value::empty ;\n// Glass f = Glass::empty ;\n" }, { "answer_id": 18552979, "author": "Oswald", "author_id": 534124, "author_profile": "https://Stackoverflow.com/users/534124", "pm_score": 2, "selected": false, "text": "friend friend" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
216,749
<p>I have a WPF project defined like this:</p> <pre> MyApp.sln MyAppWPF MyApp.Domain </pre> <p>In one of my xaml files in the MyAppWPF project I'm trying to reference a class defined in MyApp.Domain project. I have a <strong>project reference</strong> in MyAppWPF to MyApp.Domain. I am trying to create the reference like this:</p> <pre> &lt;Window x:Class="MyAppWPF.Window1" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" xmlns:local="clr-namespace:MyApp.Domain;assembly=MyApp.Domain" Title="Window1" Height="305" Width="485"> &lt;Window.Resources> &lt;local:MyClass x:Key="mine" /> &lt;/Window.Resources> &lt;/Window&gt; </pre> <p>I get an error saying the assembly cannot be found, however I can create an instance of the class I want to reference in the code behind, so I know I've got it referenced correctly.</p> <p>How do I do this? Do I need a strong name, or reference the dll directly instead of using a project reference?</p>
[ { "answer_id": 28754607, "author": "Kaitlin Hipkin", "author_id": 4548035, "author_profile": "https://Stackoverflow.com/users/4548035", "pm_score": 1, "selected": false, "text": "assembly=MyApp.Domain xmlns:local=\"clr-namespace:MyApp.Domain\"" }, { "answer_id": 31970937, "author": "dotNET", "author_id": 1137199, "author_profile": "https://Stackoverflow.com/users/1137199", "pm_score": 2, "selected": false, "text": ";assembly= xmlns:local=\"clr-namespace:YourProjectNameSpace;assembly=\" \n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16501/" ]
216,766
<p>File formats I would like to play include .wav, .mp3, .midi.</p> <p>I have tried using the Wireless Toolkit classes with no success. I have also tried using the AudioClip class that is part of the Samsung SDK; again with</p>
[ { "answer_id": 223691, "author": "Irfan Mulic", "author_id": 27016, "author_profile": "https://Stackoverflow.com/users/27016", "pm_score": 3, "selected": true, "text": "// Code starts here put this into midlet run() method\n\npublic void run()\n{\n try\n {\n InputStream is = getClass().getResourceAsStream(\"your_audio_file.mp3\");\n player = Manager.createPlayer(is,\"audio/mpeg\");\n\n// if \"audio/mpeg\" doesn't work try \"audio/mp3\"\n\n player.realize(); \n player.prefetch();\n player.start();\n }\n catch(Exception e)\n {}\n}\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9771/" ]
216,771
<p>I know that this is a simple question for PHP guys but I don't know the language and just need to do a simple "get" from another web page when my page is hit. i.e. signal the other page that this page has been hit.</p> <p>EDIT: curl is not available to me.</p>
[ { "answer_id": 216774, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 4, "selected": true, "text": "file_get_contents('http://www.example.org');\n" }, { "answer_id": 216776, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "file_get_contents('http://...'); fopen() curl_init" }, { "answer_id": 216786, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "file_get_contents() fopen()" }, { "answer_id": 217855, "author": "Ryan McCue", "author_id": 2575, "author_profile": "https://Stackoverflow.com/users/2575", "pm_score": 2, "selected": false, "text": "file_get_contents fopen fsockopen() fopen" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
216,781
<p>I have a java webapp that has to be deployed on either Win or Linux machines. I now want to add log4j for logging and I'd like to use a relative path for the log file as I don't want to change the file path on every deployment. The container will most likely be Tomcat but not necessarily.</p> <p>What's the best way of doing this?</p>
[ { "answer_id": 216805, "author": "Steve K", "author_id": 739, "author_profile": "https://Stackoverflow.com/users/739", "pm_score": 7, "selected": false, "text": "log4j.rootCategory=DEBUG,errorfile\n\nlog4j.appender.errorfile.File=${catalina.home}/logs/LogFilename.log\n ${catalina.home} ${catalina.base} export JAVA_OPTS=\"-Dcustom.logging.root=/var/log/webapps\"\n log4j.rootCategory=DEBUG,errorfile\n\nlog4j.appender.errorfile.File=${custom.logging.root}/LogFilename.log\n" }, { "answer_id": 218037, "author": "Iker Jimenez", "author_id": 2697, "author_profile": "https://Stackoverflow.com/users/2697", "pm_score": 7, "selected": true, "text": "public void contextInitialized(ServletContextEvent event) {\n ServletContext context = event.getServletContext();\n System.setProperty(\"rootPath\", context.getRealPath(\"/\"));\n}\n log4j.appender.file.File=${rootPath}WEB-INF/logs/MyLog.log\n" }, { "answer_id": 320412, "author": "Dimitri De Franciscis", "author_id": 11988, "author_profile": "https://Stackoverflow.com/users/11988", "pm_score": 4, "selected": false, "text": "log4j.rootLogger=ERROR, stdout, rollingFile\n\nlog4j.appender.stdout=org.apache.log4j.ConsoleAppender\nlog4j.appender.stdout.layout=org.apache.log4j.PatternLayout\nlog4j.appender.stdout.layout.ConversionPattern=%d %p [%c] - <%m>%n\n\nlog4j.appender.rollingFile=org.apache.log4j.RollingFileAppender\nlog4j.appender.rollingFile.File=${myWebapp-instance-root}/WEB-INF/logs/application.log\nlog4j.appender.rollingFile.MaxFileSize=512KB\nlog4j.appender.rollingFile.MaxBackupIndex=10\nlog4j.appender.rollingFile.layout=org.apache.log4j.PatternLayout\nlog4j.appender.rollingFile.layout.ConversionPattern=%d %p [%c] - %m%n\nlog4j.appender.rollingFile.Encoding=UTF-8\n <context-param>\n <param-name>log4jConfigLocation</param-name>\n <param-value>/WEB-INF/classes/log4j-myapp.properties</param-value>\n</context-param>\n <context-param>\n <param-name>webAppRootKey</param-name>\n <param-value>myWebapp-instance-root</param-value>\n</context-param>\n <listener>\n <listener-class>org.springframework.web.util.Log4jConfigListener</listener-class>\n</listener>\n" }, { "answer_id": 2009711, "author": "lizi", "author_id": 312292, "author_profile": "https://Stackoverflow.com/users/312292", "pm_score": 3, "selected": false, "text": "ServletContext ServletContext" }, { "answer_id": 16067924, "author": "alex.antaniuk", "author_id": 1889743, "author_profile": "https://Stackoverflow.com/users/1889743", "pm_score": 1, "selected": false, "text": "<profiles>\n <profile>\n <id>linux</id>\n <activation>\n <os>\n <family>unix</family>\n </os>\n </activation>\n <properties>\n <logDirectory>/var/log/tomcat6</logDirectory>\n </properties>\n </profile>\n <profile>\n <id>windows</id>\n <activation>\n <os>\n <family>windows</family>\n </os>\n </activation>\n <properties>\n <logDirectory>${catalina.home}/logs</logDirectory>\n </properties>\n </profile>\n</profiles>\n logDirectory logDirectory log4j.properties log4j.appender.FILE=org.apache.log4j.RollingFileAppender\nlog4j.appender.FILE.File=${logDirectory}/mylog.log\nlog4j.appender.FILE.MaxFileSize=30MB\nlog4j.appender.FILE.MaxBackupIndex=10\nlog4j.appender.FILE.layout=org.apache.log4j.PatternLayout\nlog4j.appender.FILE.layout.ConversionPattern=%d{ISO8601} [%x] %-5p [%t] [%c{1}] %m%n\n" }, { "answer_id": 32379393, "author": "starikoff", "author_id": 2369544, "author_profile": "https://Stackoverflow.com/users/2369544", "pm_score": 1, "selected": false, "text": "System.setProperty(...) org.apache.log4j.PropertyConfigurator.configure(Properties) System WEB-INF/ log4j-no-autoload.properties src/main/resources WEB-INF/classes log4j.appender.MyAppFileAppender = org.apache.log4j.FileAppender\nlog4j.appender.MyAppFileAppender.file = ${webAppRoot}/WEB-INF/logs/my-app.log\n...\n @WebListener\npublic class ContextListener implements ServletContextListener {\n @Override\n public void contextInitialized(final ServletContextEvent event) {\n Properties props = new Properties();\n InputStream strm =\n ContextListener.class.getClassLoader()\n .getResourceAsStream(\"log4j-no-autoload.properties\");\n try {\n props.load(strm);\n } catch (IOException propsLoadIOE) {\n throw new Error(\"can't load logging config file\", propsLoadIOE);\n } finally {\n try {\n strm.close();\n } catch (IOException configCloseIOE) {\n throw new Error(\"error closing logging config file\", configCloseIOE);\n }\n }\n props.put(\"webAppRoot\", event.getServletContext().getRealPath(\"/\"));\n PropertyConfigurator.configure(props);\n // from now on, I can use LoggerFactory.getLogger(...)\n }\n ...\n}\n" }, { "answer_id": 43460319, "author": "Dimitar II", "author_id": 4399576, "author_profile": "https://Stackoverflow.com/users/4399576", "pm_score": 1, "selected": false, "text": "appender.file.fileName = ${sys:user.dir}/log/application.log\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2697/" ]
216,790
<p>What's the best way to get the last inserted id using sqlite from Java? Google is giving me different answers--some say select the last-insert-rowid; others say call statement.getGeneratedKeys(). What's the best route to take? (I just want to return the id, not use it for other inserts or anything.)</p>
[ { "answer_id": 217391, "author": "Brian", "author_id": 700, "author_profile": "https://Stackoverflow.com/users/700", "pm_score": 5, "selected": true, "text": "getGeneratedKeys() getGeneratedKeys()" }, { "answer_id": 621896, "author": "David Citron", "author_id": 5309, "author_profile": "https://Stackoverflow.com/users/5309", "pm_score": 5, "selected": false, "text": "java.sql.Statement.getGeneratedKeys() sqlite3_last_insert_rowid() last_insert_rowid() SELECT function-name();\n last_insert_rowid() SELECT ResultSet getGeneratedKeys() throws SQLException {\n if (getGeneratedKeys == null) getGeneratedKeys = conn.prepareStatement(\n \"select last_insert_rowid();\");\n return getGeneratedKeys.executeQuery();\n}\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216790", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29173/" ]
216,796
<p>For homework, I was given the following 8 code fragments to analyze and give a Big-Oh notation for the running time. Can anybody please tell me if I'm on the right track? </p> <pre><code>//Fragment 1 for(int i = 0; i &lt; n; i++) sum++; </code></pre> <p>I'm thinking O(N) for fragment 1</p> <pre><code>//Fragment 2 for(int i = 0; i &lt; n; i+=2) sum++; </code></pre> <p>O(N) for fragment 2 as well</p> <pre><code>//Fragment 3 for(int i = 0; i &lt; n; i++) for( int j = 0; j &lt; n; j++) sum++; </code></pre> <p>O(N^2) for fragment 3</p> <pre><code>//Fragment 4 for(int i = 0; i &lt; n; i+=2) sum++; for(int j = 0; j &lt; n; j++) sum++; </code></pre> <p>O(N) for fragment 4</p> <pre><code>//Fragment 5 for(int i = 0; i &lt; n; i++) for( int j = 0; j &lt; n * n; j++) sum++; </code></pre> <p>O(N^2) for fragment 5 but the n * n is throwing me off a bit so I'm not quite sure</p> <pre><code>//Fragment 6 for(int i = 0; i &lt; n; i++) for( int j = 0; j &lt; i; j++) sum++; </code></pre> <p>O(N^2) for fragment 6 as well</p> <pre><code>//Fragment 7 for(int i = 0; i &lt; n; i++) for( int j = 0; j &lt; n * n; j++) for(int k = 0; k &lt; j; k++) sum++; </code></pre> <p>O(N^3) for fragment 7 but once again the n * n is throwing me off</p> <pre><code>//Fragment 8 for(int i = 1; i &lt; n; i = i * 2) sum++; </code></pre> <p>O(N) for fragment 8</p>
[ { "answer_id": 8121746, "author": "Arnab Datta", "author_id": 528617, "author_profile": "https://Stackoverflow.com/users/528617", "pm_score": 0, "selected": false, "text": "for(i = 0; i < n; i++) {\n for(j = 0; j < 100; j++){....}\n}\n ..." } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14013/" ]
216,817
<p>Similar to <a href="https://stackoverflow.com/questions/216710/call-openfiledialog-from-powershell">this question</a>, after running the following code the browser dialog does appear with all the correct buttons, but the selection area that usally displays available folders is missing:</p> <pre><code>[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) $d = New-Object Windows.Forms.FolderBrowserDialog $d.ShowDialog( ) </code></pre>
[ { "answer_id": 217527, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 5, "selected": true, "text": "$app = new-object -com Shell.Application\n$folder = $app.BrowseForFolder(0, \"Select Folder\", 0, \"C:\\\")\nif ($folder.Self.Path -ne \"\") {write-host \"You selected \" $folder.Self.Path}\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2495/" ]
216,818
<p>I have a button that adds an already defined usercontrol programtically. I am rebuilding each control on Postback and they show up fine. If I put text in the textbox it shows up fine, however my images are losing their url. Any idea why or how I can fix this?</p> <p>I tried adding AJAX updatepanel to see if that would help, but it does not.</p> <p>To further explain - I have a button that after clicks set the url of the image - I also put this value in the textbox just to see if the same thing happens - after postback, my textbox still has the value, but the image does not - and all of my other ASP.Net images lose their image and they are defined right on the controls (ie: ImageUrl)</p> <p>--- update OK, I have found some more insight to my issue - some solutions but still one problem remains.</p> <p>The reason the images were loosing their url is because they were and not ASP.Net images - ASP.Net remembers the values when they are recreated on postback - however the Main image that im changing via javascript looses its value - I'm very certain this is because of using javascript to change it, on post back it reverts back to the previous value... so for a solution I will try to stuff it in a hidden value, then use that value on postback to define the ImageUrl of the image... </p>
[ { "answer_id": 216872, "author": "Jason Stevenson", "author_id": 13368, "author_profile": "https://Stackoverflow.com/users/13368", "pm_score": 1, "selected": false, "text": "<img> <asp:Image>" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216818", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26685/" ]
216,819
<p>I keep wondering how does a debugger work? Particulary the one that can be 'attached' to already running executable. I understand that compiler translates code to machine language, but then how does debugger 'know' what it is being attached to?</p>
[ { "answer_id": 216954, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 5, "selected": false, "text": "ptrace" }, { "answer_id": 21746853, "author": "Jonathon Reinhart", "author_id": 119527, "author_profile": "https://Stackoverflow.com/users/119527", "pm_score": 6, "selected": false, "text": "CC int3 WriteProcessMemory int3 CC TF EFLAGS CONTEXT INT 1 CC" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216819", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29430/" ]
216,822
<p>There are some cool and exciting features in .NET 3.5/C# 3.0, and with those features comes some darn interesting ways to write the exact same line of code.</p> <p>Using the above stated tool set (and by extension .NET 2.0 stuff), what are the different ways the below code snippet could reasonably be rewritten? </p> <pre><code> string uploadDirectory = "c:\\some\\path\\"; if (Directory.Exists(uploadDirectory)) { string[] files = Directory.GetFiles(uploadDirectory); foreach (string filename in files) { if (File.GetLastWriteTime(filename).AddHours(12) &lt; DateTime.Now) { File.Delete(filename); } } } </code></pre>
[ { "answer_id": 216828, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 4, "selected": true, "text": "if (Directory.Exists(uploadDirectory)) \n Directory.GetFiles(uploadDirectory)\n .Where(f => File.GetLastWriteTime(file) < DateTime.Now.AddHours(-12))\n .Each(f => File.Delete(f));\n var di = new DirectoryInfo(uploadDirectory);\nif (di.Exists()) {\n di.GetFiles()\n .Where(f => f.LastWriteTime < DateTime.Now.AddHours(-12))\n .Each(f=> f.Delete());\n}\n void Each<T>(this IEnumerable e, Action<T> action) {\n foreach (T t in e) {\n action(t);\n }\n}\n di.GetFiles().Select(f => new() {\n Delete = f.LastWriteTime < DateTime.Now.AddHours(-12) ? f.Delete : () => { }\n}).Delete();\n" }, { "answer_id": 216836, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "static void Main()\n{\n string uploadDirectory = \"c:\\\\some\\\\path\\\\\";\n if (Directory.Exists(uploadDirectory))\n {\n var files = from filename in Directory.GetFiles(uploadDirectory)\n where File.GetLastWriteTime(filename) < DateTime.Now.AddHours(-12)\n select filename;\n files.ForEach(File.Delete); \n }\n}\nstatic void ForEach<T>(this IEnumerable<T> items, Action<T> action)\n{\n foreach (T item in items)\n {\n action(item);\n }\n}\n DateTime Expression" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27860/" ]
216,823
<p>I'm currently using the following code to right-trim all the <code>std::strings</code> in my programs:</p> <pre><code>std::string s; s.erase(s.find_last_not_of(" \n\r\t")+1); </code></pre> <p>It works fine, but I wonder if there are some end-cases where it might fail?</p> <p>Of course, answers with elegant alternatives and also left-trim solution are welcome.</p>
[ { "answer_id": 216829, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 4, "selected": false, "text": "string::npos string::npos string::size_type" }, { "answer_id": 216883, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 9, "selected": false, "text": "#include <boost/algorithm/string.hpp>\n\nstd::string str(\"hello world! \");\nboost::trim_right(str);\n str \"hello world!\" trim_left trim _copy trim_copy _if trim_copy_if" }, { "answer_id": 216946, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 4, "selected": false, "text": "std::string choppa(const std::string &t, const std::string &ws)\n{\n std::string str = t;\n size_t found;\n found = str.find_last_not_of(ws);\n if (found != std::string::npos)\n str.erase(found+1);\n else\n str.clear(); // str is all whitespace\n\n return str;\n}\n" }, { "answer_id": 217605, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 10, "selected": false, "text": "#include <algorithm> \n#include <cctype>\n#include <locale>\n\n// trim from start (in place)\nstatic inline void ltrim(std::string &s) {\n s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) {\n return !std::isspace(ch);\n }));\n}\n\n// trim from end (in place)\nstatic inline void rtrim(std::string &s) {\n s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) {\n return !std::isspace(ch);\n }).base(), s.end());\n}\n\n// trim from both ends (in place)\nstatic inline void trim(std::string &s) {\n rtrim(s);\n ltrim(s);\n}\n\n// trim from start (copying)\nstatic inline std::string ltrim_copy(std::string s) {\n ltrim(s);\n return s;\n}\n\n// trim from end (copying)\nstatic inline std::string rtrim_copy(std::string s) {\n rtrim(s);\n return s;\n}\n\n// trim from both ends (copying)\nstatic inline std::string trim_copy(std::string s) {\n trim(s);\n return s;\n}\n #include <algorithm> \n#include <functional> \n#include <cctype>\n#include <locale>\n\n// trim from start\nstatic inline std::string &ltrim(std::string &s) {\n s.erase(s.begin(), std::find_if(s.begin(), s.end(),\n std::not1(std::ptr_fun<int, int>(std::isspace))));\n return s;\n}\n\n// trim from end\nstatic inline std::string &rtrim(std::string &s) {\n s.erase(std::find_if(s.rbegin(), s.rend(),\n std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());\n return s;\n}\n\n// trim from both ends\nstatic inline std::string &trim(std::string &s) {\n return ltrim(rtrim(s));\n}\n std::ptr_fun std::isspace #include <algorithm> \n#include <functional> \n#include <cctype>\n#include <locale>\n\n// trim from start (in place)\nstatic inline void ltrim(std::string &s) {\n s.erase(s.begin(), std::find_if(s.begin(), s.end(),\n std::not1(std::ptr_fun<int, int>(std::isspace))));\n}\n\n// trim from end (in place)\nstatic inline void rtrim(std::string &s) {\n s.erase(std::find_if(s.rbegin(), s.rend(),\n std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end());\n}\n\n// trim from both ends (in place)\nstatic inline void trim(std::string &s) {\n rtrim(s);\n ltrim(s);\n}\n\n// trim from start (copying)\nstatic inline std::string ltrim_copy(std::string s) {\n ltrim(s);\n return s;\n}\n\n// trim from end (copying)\nstatic inline std::string rtrim_copy(std::string s) {\n rtrim(s);\n return s;\n}\n\n// trim from both ends (copying)\nstatic inline std::string trim_copy(std::string s) {\n trim(s);\n return s;\n}\n" }, { "answer_id": 347974, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 6, "selected": false, "text": "std::strings // trim trailing spaces\nsize_t endpos = str.find_last_not_of(\" \\t\");\nsize_t startpos = str.find_first_not_of(\" \\t\");\nif( std::string::npos != endpos )\n{\n str = str.substr( 0, endpos+1 );\n str = str.substr( startpos );\n}\nelse {\n str.erase(std::remove(std::begin(str), std::end(str), ' '), std::end(str));\n}\n // trim leading spaces\nsize_t startpos = str.find_first_not_of(\" \\t\");\nif( string::npos != startpos )\n{\n str = str.substr( startpos );\n}\n" }, { "answer_id": 1792361, "author": "Corwin Joy", "author_id": 150709, "author_profile": "https://Stackoverflow.com/users/150709", "pm_score": 2, "selected": false, "text": "string trim(char const *str)\n{\n // Trim leading non-letters\n while(!isalnum(*str)) str++;\n\n // Trim trailing non-letters\n end = str + strlen(str) - 1;\n while(end > str && !isalnum(*end)) end--;\n\n return string(str, end+1);\n}\n" }, { "answer_id": 2919237, "author": "tzaman", "author_id": 257465, "author_profile": "https://Stackoverflow.com/users/257465", "pm_score": 2, "selected": false, "text": "std::stringstream trimmer;\ntrimmer << str;\ntrimmer >> str;\n" }, { "answer_id": 3177560, "author": "Michaël Schoonbrood", "author_id": 383432, "author_profile": "https://Stackoverflow.com/users/383432", "pm_score": 5, "selected": false, "text": "std::stringstream trimmer;\ntrimmer << str;\nstr.clear();\ntrimmer >> str;\n" }, { "answer_id": 3559481, "author": "Brian", "author_id": 429872, "author_profile": "https://Stackoverflow.com/users/429872", "pm_score": 1, "selected": false, "text": "static inline std::string &trimAll(std::string &s)\n{ \n if(s.size() == 0)\n {\n return s;\n }\n\n int val = 0;\n for (int cur = 0; cur < s.size(); cur++)\n {\n if(s[cur] != ' ' && std::isalnum(s[cur]))\n {\n s[val] = s[cur];\n val++;\n }\n }\n s.resize(val);\n return s;\n}\n" }, { "answer_id": 6500499, "author": "user818330", "author_id": 818330, "author_profile": "https://Stackoverflow.com/users/818330", "pm_score": 6, "selected": false, "text": "inline std::string trim(std::string& str)\n{\n str.erase(str.find_last_not_of(' ')+1); //suffixing spaces\n str.erase(0, str.find_first_not_of(' ')); //prefixing spaces\n return str;\n}\n" }, { "answer_id": 15649849, "author": "Brian W.", "author_id": 977913, "author_profile": "https://Stackoverflow.com/users/977913", "pm_score": 1, "selected": false, "text": "string strip(const string& s, const string& chars=\" \") {\n size_t begin = 0;\n size_t end = s.size()-1;\n for(; begin < s.size(); begin++)\n if(chars.find_first_of(s[begin]) == string::npos)\n break;\n for(; end > begin; end--)\n if(chars.find_first_of(s[end]) == string::npos)\n break;\n return s.substr(begin, end-begin+1);\n}\n" }, { "answer_id": 16743707, "author": "DavidRR", "author_id": 1497596, "author_profile": "https://Stackoverflow.com/users/1497596", "pm_score": 4, "selected": false, "text": "const std::string StringUtils::WHITESPACE = \" \\n\\r\\t\";\n\nstd::string StringUtils::Trim(const std::string& s)\n{\n return TrimRight(TrimLeft(s));\n}\n\nstd::string StringUtils::TrimLeft(const std::string& s)\n{\n size_t startpos = s.find_first_not_of(StringUtils::WHITESPACE);\n return (startpos == std::string::npos) ? \"\" : s.substr(startpos);\n}\n\nstd::string StringUtils::TrimRight(const std::string& s)\n{\n size_t endpos = s.find_last_not_of(StringUtils::WHITESPACE);\n return (endpos == std::string::npos) ? \"\" : s.substr(0, endpos+1);\n}\n" }, { "answer_id": 17976541, "author": "David G", "author_id": 1435420, "author_profile": "https://Stackoverflow.com/users/1435420", "pm_score": 6, "selected": false, "text": "#include <cctype>\n#include <string>\n#include <algorithm>\n\ninline std::string trim(const std::string &s)\n{\n auto wsfront=std::find_if_not(s.begin(),s.end(),[](int c){return std::isspace(c);});\n auto wsback=std::find_if_not(s.rbegin(),s.rend(),[](int c){return std::isspace(c);}).base();\n return (wsback<=wsfront ? std::string() : std::string(wsfront,wsback));\n}\n wsfront find_if_not std::string::const_reverse_iterator auto inline std::string trim(const std::string &s)\n{\n auto wsfront=std::find_if_not(s.begin(),s.end(),[](int c){return std::isspace(c);});\n return std::string(wsfront,std::find_if_not(s.rbegin(),std::string::const_reverse_iterator(wsfront),[](int c){return std::isspace(c);}).base());\n}\n" }, { "answer_id": 18465058, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 3, "selected": false, "text": "std::string ltrim(const std::string& s)\n{\n static const std::regex lws{\"^[[:space:]]*\", std::regex_constants::extended};\n return std::regex_replace(s, lws, \"\");\n}\n\nstd::string rtrim(const std::string& s)\n{\n static const std::regex tws{\"[[:space:]]*$\", std::regex_constants::extended};\n return std::regex_replace(s, tws, \"\");\n}\n\nstd::string trim(const std::string& s)\n{\n return ltrim(rtrim(s));\n}\n" }, { "answer_id": 19167699, "author": "Duncan", "author_id": 945011, "author_profile": "https://Stackoverflow.com/users/945011", "pm_score": 2, "selected": false, "text": "#include <iostream>\n#include <string>\n#include <regex>\n\nstd::string ltrim( std::string str ) {\n return std::regex_replace( str, std::regex(\"^\\\\s+\"), std::string(\"\") );\n}\n\nstd::string rtrim( std::string str ) {\n return std::regex_replace( str, std::regex(\"\\\\s+$\"), std::string(\"\") );\n}\n\nstd::string trim( std::string str ) {\n return ltrim( rtrim( str ) );\n}\n\nint main() {\n\n std::string str = \" \\t this is a test string \\n \";\n std::cout << \"-\" << trim( str ) << \"-\\n\";\n return 0;\n\n}\n" }, { "answer_id": 19941683, "author": "synaptik", "author_id": 1325279, "author_profile": "https://Stackoverflow.com/users/1325279", "pm_score": 3, "selected": false, "text": "void trim(string& s) {\n while(s.compare(0,1,\" \")==0)\n s.erase(s.begin()); // remove leading whitespaces\n while(s.size()>0 && s.compare(s.size()-1,1,\" \")==0)\n s.erase(s.end()-1); // remove trailing whitespaces\n}\n" }, { "answer_id": 20023250, "author": "Jorma Rebane", "author_id": 1951829, "author_profile": "https://Stackoverflow.com/users/1951829", "pm_score": 3, "selected": false, "text": "inline const char* trim_start(const char* str)\n{\n while (memchr(\" \\t\\n\\r\", *str, 4)) ++str;\n return str;\n}\ninline const char* trim_end(const char* end)\n{\n while (memchr(\" \\t\\n\\r\", end[-1], 4)) --end;\n return end;\n}\ninline std::string trim(const char* buffer, int len) // trim a buffer (input?)\n{\n return std::string(trim_start(buffer), trim_end(buffer + len));\n}\ninline void trim_inplace(std::string& str)\n{\n str.assign(trim_start(str.c_str()),\n trim_end(str.c_str() + str.length()));\n}\n\nint main()\n{\n char str [] = \"\\t \\nhello\\r \\t \\n\";\n\n string trimmed = trim(str, strlen(str));\n cout << \"'\" << trimmed << \"'\" << endl;\n\n system(\"pause\");\n return 0;\n}\n" }, { "answer_id": 20262860, "author": "Alexander Drichel", "author_id": 1872824, "author_profile": "https://Stackoverflow.com/users/1872824", "pm_score": 0, "selected": false, "text": "std::string trim( std::string && str )\n{\n size_t end = str.find_last_not_of( \" \\n\\r\\t\" );\n if ( end != std::string::npos )\n str.resize( end + 1 );\n\n size_t start = str.find_first_not_of( \" \\n\\r\\t\" );\n if ( start != std::string::npos )\n str = str.substr( start );\n\n return std::move( str );\n}\n" }, { "answer_id": 21698913, "author": "Pushkoff", "author_id": 2090997, "author_profile": "https://Stackoverflow.com/users/2090997", "pm_score": 5, "selected": false, "text": "std::string trim(const std::string &s)\n{\n std::string::const_iterator it = s.begin();\n while (it != s.end() && isspace(*it))\n it++;\n\n std::string::const_reverse_iterator rit = s.rbegin();\n while (rit.base() != it && isspace(*rit))\n rit++;\n\n return std::string(it, rit.base());\n}\n" }, { "answer_id": 22816847, "author": "Bondolin", "author_id": 1399272, "author_profile": "https://Stackoverflow.com/users/1399272", "pm_score": 0, "selected": false, "text": "string trimBegin(string str)\n{\n string whites = \"\\t\\r\\n \";\n int i = 0;\n while (whites.find(str[i++]) != whites::npos);\n str.erase(0, i);\n return str;\n}\n" }, { "answer_id": 23485459, "author": "vmrob", "author_id": 1843978, "author_profile": "https://Stackoverflow.com/users/1843978", "pm_score": 3, "selected": false, "text": "trim trim_in_place trim #include <string>\n\n// modifies input string, returns input\n\nstd::string& trim_left_in_place(std::string& str) {\n size_t i = 0;\n while(i < str.size() && isspace(str[i])) { ++i; };\n return str.erase(0, i);\n}\n\nstd::string& trim_right_in_place(std::string& str) {\n size_t i = str.size();\n while(i > 0 && isspace(str[i - 1])) { --i; };\n return str.erase(i, str.size());\n}\n\nstd::string& trim_in_place(std::string& str) {\n return trim_left_in_place(trim_right_in_place(str));\n}\n\n// returns newly created strings\n\nstd::string trim_right(std::string str) {\n return trim_right_in_place(str);\n}\n\nstd::string trim_left(std::string str) {\n return trim_left_in_place(str);\n}\n\nstd::string trim(std::string str) {\n return trim_left_in_place(trim_right_in_place(str));\n}\n\n#include <cassert>\n\nint main() {\n\n std::string s1(\" \\t\\r\\n \");\n std::string s2(\" \\r\\nc\");\n std::string s3(\"c \\t\");\n std::string s4(\" \\rc \");\n\n assert(trim(s1) == \"\");\n assert(trim(s2) == \"c\");\n assert(trim(s3) == \"c\");\n assert(trim(s4) == \"c\");\n\n assert(s1 == \" \\t\\r\\n \");\n assert(s2 == \" \\r\\nc\");\n assert(s3 == \"c \\t\");\n assert(s4 == \" \\rc \");\n\n assert(trim_in_place(s1) == \"\");\n assert(trim_in_place(s2) == \"c\");\n assert(trim_in_place(s3) == \"c\");\n assert(trim_in_place(s4) == \"c\");\n\n assert(s1 == \"\");\n assert(s2 == \"c\");\n assert(s3 == \"c\");\n assert(s4 == \"c\"); \n}\n" }, { "answer_id": 25385766, "author": "Galik", "author_id": 3807729, "author_profile": "https://Stackoverflow.com/users/3807729", "pm_score": 6, "selected": false, "text": "const char* ws = \" \\t\\n\\r\\f\\v\";\n\n// trim from end of string (right)\ninline std::string& rtrim(std::string& s, const char* t = ws)\n{\n s.erase(s.find_last_not_of(t) + 1);\n return s;\n}\n\n// trim from beginning of string (left)\ninline std::string& ltrim(std::string& s, const char* t = ws)\n{\n s.erase(0, s.find_first_not_of(t));\n return s;\n}\n\n// trim from both ends of string (right then left)\ninline std::string& trim(std::string& s, const char* t = ws)\n{\n return ltrim(rtrim(s, t), t);\n}\n" }, { "answer_id": 27788112, "author": "mbgda", "author_id": 4421195, "author_profile": "https://Stackoverflow.com/users/4421195", "pm_score": 3, "selected": false, "text": "void TrimString(std::string & str)\n{ \n if(str.empty())\n return;\n\n const auto pStr = str.c_str();\n\n size_t front = 0;\n while(front < str.length() && std::isspace(int(pStr[front]))) {++front;}\n\n size_t back = str.length();\n while(back > front && std::isspace(int(pStr[back-1]))) {--back;}\n\n if(0 == front)\n {\n if(back < str.length())\n {\n str.resize(back - front);\n }\n }\n else if(back <= front)\n {\n str.clear();\n }\n else\n {\n str = std::move(std::string(str.begin()+front, str.begin()+back));\n }\n}\n" }, { "answer_id": 29185584, "author": "Clay Freeman", "author_id": 1114073, "author_profile": "https://Stackoverflow.com/users/1114073", "pm_score": 3, "selected": false, "text": "std::isgraph #include <algorithm>\n#include <functional>\n#include <string>\n\n/**\n * @brief Left Trim\n *\n * Trims whitespace from the left end of the provided std::string\n *\n * @param[out] s The std::string to trim\n *\n * @return The modified std::string&\n */\nstd::string& ltrim(std::string& s) {\n s.erase(s.begin(), std::find_if(s.begin(), s.end(),\n std::ptr_fun<int, int>(std::isgraph)));\n return s;\n}\n\n/**\n * @brief Right Trim\n *\n * Trims whitespace from the right end of the provided std::string\n *\n * @param[out] s The std::string to trim\n *\n * @return The modified std::string&\n */\nstd::string& rtrim(std::string& s) {\n s.erase(std::find_if(s.rbegin(), s.rend(),\n std::ptr_fun<int, int>(std::isgraph)).base(), s.end());\n return s;\n}\n\n/**\n * @brief Trim\n *\n * Trims whitespace from both ends of the provided std::string\n *\n * @param[out] s The std::string to trim\n *\n * @return The modified std::string&\n */\nstd::string& trim(std::string& s) {\n return ltrim(rtrim(s));\n}\n std::iswgraph std::wstring std::basic_string" }, { "answer_id": 32071000, "author": "jha-G", "author_id": 4373992, "author_profile": "https://Stackoverflow.com/users/4373992", "pm_score": 3, "selected": false, "text": "std::string & trim(std::string & str)\n{\n return ltrim(rtrim(str));\n}\n std::string & ltrim(std::string & str)\n{\n auto it = std::find_if( str.begin() , str.end() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );\n str.erase( str.begin() , it);\n return str; \n}\n\nstd::string & rtrim(std::string & str)\n{\n auto it = std::find_if( str.rbegin() , str.rend() , [](char ch){ return !std::isspace<char>(ch , std::locale::classic() ) ; } );\n str.erase( it.base() , str.end() );\n return str; \n}\n std::string trim_copy(std::string const & str)\n{\n auto s = str;\n return ltrim(rtrim(s));\n}\n" }, { "answer_id": 33061006, "author": "Floella", "author_id": 2011041, "author_profile": "https://Stackoverflow.com/users/2011041", "pm_score": 0, "selected": false, "text": "void trim(string &str){\n int i=0;\n\n //left trim\n while (isspace(str[i])!=0)\n i++;\n str = str.substr(i,str.length()-i);\n\n //right trim\n i=str.length()-1;\n while (isspace(str[i])!=0)\n i--;\n str = str.substr(0,i+1);\n}\n" }, { "answer_id": 33099753, "author": "freeboy1015", "author_id": 1210337, "author_profile": "https://Stackoverflow.com/users/1210337", "pm_score": 4, "selected": false, "text": "s.erase(0, s.find_first_not_of(\" \\n\\r\\t\")); \ns.erase(s.find_last_not_of(\" \\n\\r\\t\")+1); \n" }, { "answer_id": 33129986, "author": "GutiMac", "author_id": 4211031, "author_profile": "https://Stackoverflow.com/users/4211031", "pm_score": 3, "selected": false, "text": "static void trim(std::string &s) {\n s.erase(s.begin(), std::find_if_not(s.begin(), s.end(), [](char c){ return std::isspace(c); }));\n s.erase(std::find_if_not(s.rbegin(), s.rend(), [](char c){ return std::isspace(c); }).base(), s.end());\n}\n" }, { "answer_id": 34112965, "author": "Developer Formerly Known as V", "author_id": 3578493, "author_profile": "https://Stackoverflow.com/users/3578493", "pm_score": -1, "selected": false, "text": "std::string trim(std::string str) {\n if(str.length() == 0) return str;\n\n int beg = 0, end = str.length() - 1;\n while (str[beg] == ' ') {\n beg++;\n }\n\n while (str[end] == ' ') {\n end--;\n }\n\n return str.substr(beg, end - beg + 1);\n}\n" }, { "answer_id": 35117930, "author": "Brent Bradburn", "author_id": 86967, "author_profile": "https://Stackoverflow.com/users/86967", "pm_score": 3, "selected": false, "text": "back() pop_back() while ( !s.empty() && isspace(s.back()) ) s.pop_back();\n" }, { "answer_id": 35320881, "author": "user1438233", "author_id": 1438233, "author_profile": "https://Stackoverflow.com/users/1438233", "pm_score": 0, "selected": false, "text": "int i{};\nstring s = \" h e ll \\t\\n o\";\nstring trim = \" \\n\\t\";\n\nwhile ((i = s.find_first_of(trim)) != -1)\n s.erase(i,1);\n\ncout << s;\n hello\n" }, { "answer_id": 36000453, "author": "elxala", "author_id": 573554, "author_profile": "https://Stackoverflow.com/users/573554", "pm_score": 1, "selected": false, "text": "std::string & trimMe (std::string & str)\n{\n // right trim\n while (str.length () > 0 && (str [str.length ()-1] == ' ' || str [str.length ()-1] == '\\t'))\n str.erase (str.length ()-1, 1);\n\n // left trim\n while (str.length () > 0 && (str [0] == ' ' || str [0] == '\\t'))\n str.erase (0, 1);\n return str;\n}\n" }, { "answer_id": 36169979, "author": "Kemin Zhou", "author_id": 2407363, "author_profile": "https://Stackoverflow.com/users/2407363", "pm_score": 2, "selected": false, "text": "string trimSpace(const string &str) {\n if (str.empty()) return str;\n string::size_type i,j;\n i=0;\n while (i<str.size() && isspace(str[i])) ++i;\n if (i == str.size())\n return string(); // empty string\n j = str.size() - 1;\n //while (j>0 && isspace(str[j])) --j; // the j>0 check is not needed\n while (isspace(str[j])) --j\n return str.substr(i, j-i+1);\n}\n" }, { "answer_id": 39252644, "author": "nulleight", "author_id": 789371, "author_profile": "https://Stackoverflow.com/users/789371", "pm_score": 2, "selected": false, "text": "size_t beg = s.find_first_not_of(\" \\r\\n\");\nreturn (beg == string::npos) ? \"\" : in.substr(beg, s.find_last_not_of(\" \\r\\n\") - beg);\n" }, { "answer_id": 41039262, "author": "cute_ptr", "author_id": 7152606, "author_profile": "https://Stackoverflow.com/users/7152606", "pm_score": 2, "selected": false, "text": "std:: const iterator algorithm #include <string>\n#include <cctype> // for isspace\nusing namespace std;\n\n\n// Left trim the given string (\" hello! \" --> \"hello! \")\nstring left_trim(string str) {\n int numStartSpaces = 0;\n for (int i = 0; i < str.length(); i++) {\n if (!isspace(str[i])) break;\n numStartSpaces++;\n }\n return str.substr(numStartSpaces);\n}\n\n// Right trim the given string (\" hello! \" --> \" hello!\")\nstring right_trim(string str) {\n int numEndSpaces = 0;\n for (int i = str.length() - 1; i >= 0; i--) {\n if (!isspace(str[i])) break;\n numEndSpaces++;\n }\n return str.substr(0, str.length() - numEndSpaces);\n}\n\n// Left and right trim the given string (\" hello! \" --> \"hello!\")\nstring trim(string str) {\n return right_trim(left_trim(str));\n}\n" }, { "answer_id": 51177287, "author": "Slesa", "author_id": 1136884, "author_profile": "https://Stackoverflow.com/users/1136884", "pm_score": -1, "selected": false, "text": "CString tmp(line.c_str());\ntmp = tmp.Trim().MakeLower();\nstring buffer = tmp;\n" }, { "answer_id": 51274774, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "void trim(std::string &line){\n\n auto val = line.find_last_not_of(\" \\n\\r\\t\") + 1;\n\n if(val == line.size() || val == std::string::npos){\n val = line.find_first_not_of(\" \\n\\r\\t\");\n line = line.substr(val);\n }\n else\n line.erase(val);\n}\n" }, { "answer_id": 52524877, "author": "UnSat", "author_id": 3195698, "author_profile": "https://Stackoverflow.com/users/3195698", "pm_score": 0, "selected": false, "text": "void trim(std::string& s) { \n if (s.empty()) \n return; \n\n int l = 0, r = s.size() - 1; \n\n while (l < s.size() && std::isspace(s[l++])); // l points to first non-whitespace char. \n while (r >= 0 && std::isspace(s[r--])); // r points to last non-whitespace char. \n\n if (l > r) \n s = \"\"; \n else { \n l--; \n r++; \n int wi = 0; \n while (l <= r) \n s[wi++] = s[l++]; \n s.erase(wi); \n } \n return; \n} \n" }, { "answer_id": 54364173, "author": "Phidelux", "author_id": 1067846, "author_profile": "https://Stackoverflow.com/users/1067846", "pm_score": 5, "selected": false, "text": "std::string_view trim(std::string_view s)\n{\n s.remove_prefix(std::min(s.find_first_not_of(\" \\t\\r\\v\\n\"), s.size()));\n s.remove_suffix(std::min(s.size() - s.find_last_not_of(\" \\t\\r\\v\\n\") - 1, s.size()));\n\n return s;\n}\n std::string_view ltrim(std::string_view s)\n{\n s.remove_prefix(std::distance(s.cbegin(), std::find_if(s.cbegin(), s.cend(),\n [](int c) {return !std::isspace(c);})));\n\n return s;\n}\n\nstd::string_view rtrim(std::string_view s)\n{\n s.remove_suffix(std::distance(s.crbegin(), std::find_if(s.crbegin(), s.crend(),\n [](int c) {return !std::isspace(c);})));\n\n return s;\n}\n\nstd::string_view trim(std::string_view s)\n{\n return ltrim(rtrim(s));\n}\n" }, { "answer_id": 57830674, "author": "Jackt", "author_id": 6406645, "author_profile": "https://Stackoverflow.com/users/6406645", "pm_score": 1, "selected": false, "text": "str = \" aaa \";\nint len = str.length();\n// rtrim\nwhile(str[len-1] == ' ') { str.erase(--len,1); }\n// ltrim\nwhile(str[0] == ' ') { str.erase(0,1); }\n" }, { "answer_id": 58773060, "author": "Sadidul Islam", "author_id": 5884380, "author_profile": "https://Stackoverflow.com/users/5884380", "pm_score": 3, "selected": false, "text": "#include <string>\n#include <regex>\n\nstring trim(string str){\n return regex_replace(str, regex(\"(^[ ]+)|([ ]+$)\"),\"\");\n}\n" }, { "answer_id": 60243752, "author": "BullyWiiPlaza", "author_id": 3764804, "author_profile": "https://Stackoverflow.com/users/3764804", "pm_score": 0, "selected": false, "text": "Boost std::string trim(const std::string& input) {\n std::stringstream string_stream;\n for (const auto character : input) {\n if (!isspace(character)) {\n string_stream << character;\n }\n }\n\n return string_stream.str();\n}\n" }, { "answer_id": 62920164, "author": "Anil Gupta", "author_id": 6463728, "author_profile": "https://Stackoverflow.com/users/6463728", "pm_score": 0, "selected": false, "text": "std::string text = \"Let me split this into words\";\n\nstd::istringstream iss(text);\nstd::vector<std::string> results((std::istream_iterator<std::string>(iss)),\n std::istream_iterator<std::string>());\n" }, { "answer_id": 63270770, "author": "antb52", "author_id": 4383009, "author_profile": "https://Stackoverflow.com/users/4383009", "pm_score": 0, "selected": false, "text": "auto no_space = [](char ch) -> bool {\n return !std::isspace<char>(ch, std::locale::classic());\n};\nauto ltrim = [](std::string& s) -> std::string& {\n s.erase(s.begin(), std::find_if(s.begin(), s.end(), no_space));\n return s;\n};\nauto rtrim = [](std::string& s) -> std::string& {\n s.erase(std::find_if(s.rbegin(), s.rend(), no_space).base(), s.end());\n return s;\n};\nauto trim_copy = [](std::string s) -> std::string& { return ltrim(rtrim(s)); };\nauto trim = [](std::string& s) -> std::string& { return ltrim(rtrim(s)); };\n" }, { "answer_id": 63495628, "author": "ragnarius", "author_id": 165729, "author_profile": "https://Stackoverflow.com/users/165729", "pm_score": 0, "selected": false, "text": "string trim(const std::string &str){\n string result = \"\";\n size_t endIndex = str.size();\n while (endIndex > 0 && isblank(str[endIndex-1]))\n endIndex -= 1;\n for (size_t i=0; i<endIndex ; i+=1){\n char ch = str[i];\n if (!isblank(ch) || result.size()>0)\n result += ch;\n }\n return result;\n}\n" }, { "answer_id": 65404298, "author": "Arty", "author_id": 941531, "author_profile": "https://Stackoverflow.com/users/941531", "pm_score": 3, "selected": false, "text": "str.erase(0, str.find_first_not_of(\"\\t\\n\\v\\f\\r \")); // left trim\nstr.erase(str.find_last_not_of(\"\\t\\n\\v\\f\\r \") + 1); // right trim\n" }, { "answer_id": 65730279, "author": "Matthias", "author_id": 232175, "author_profile": "https://Stackoverflow.com/users/232175", "pm_score": 0, "selected": false, "text": "std::string trimSpaces(const std::string& str)\n{\n int start, len;\n \n for (start = 0; start < str.size() && str[start] == ' '; start++);\n for (len = str.size() - start; len > 0 && str[start + len - 1] == ' '; len--);\n \n return str.substr(start, len);\n}\n" }, { "answer_id": 72318641, "author": "Soumadip Dey", "author_id": 10439615, "author_profile": "https://Stackoverflow.com/users/10439615", "pm_score": 1, "selected": false, "text": "void trim(string& str){\n while(str[0] == ' ') str.erase(str.begin());\n while(str[str.size() - 1] == ' ') str.pop_back();\n}\n" }, { "answer_id": 72545246, "author": "aiocat", "author_id": 19097062, "author_profile": "https://Stackoverflow.com/users/19097062", "pm_score": -1, "selected": false, "text": "#define TRIM_CHARACTERS \" \\t\\n\\r\\f\\v\"\n#define TRIM_STRING(given) \\\n given.erase(given.find_last_not_of(TRIM_CHARACTERS) + 1); \\\n given.erase(0, given.find_first_not_of(TRIM_CHARACTERS));\n #include <iostream>\n#include <string>\n\n#define TRIM_CHARACTERS \" \\t\\n\\r\\f\\v\"\n#define TRIM_STRING(given) \\\n given.erase(given.find_last_not_of(TRIM_CHARACTERS) + 1); \\\n given.erase(0, given.find_first_not_of(TRIM_CHARACTERS));\n\nint main(void) {\n std::string text(\" hello world!! \\t \\r\");\n TRIM_STRING(text);\n std::cout << text; // \"hello world!!\"\n}\n" }, { "answer_id": 73835621, "author": "Soup Endless", "author_id": 2170898, "author_profile": "https://Stackoverflow.com/users/2170898", "pm_score": 1, "selected": false, "text": "std::find_if_not // returns number of spaces removed\nstd::size_t RoundTrim(std::string& s)\n{\n auto const beforeTrim{ s.size() };\n\n auto isSpace{ [](auto const& e) { return std::isspace(e); } };\n\n s.erase(cbegin(s), std::find_if_not(cbegin(s), cend(s), isSpace));\n s.erase(std::find_if_not(crbegin(s), crend(s), isSpace).base(), end(s));\n\n return beforeTrim - s.size();\n};\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14690/" ]
216,833
<p>I have a ASP.NET <code>GridView</code> with a column mapped to a boolean. I want do display "Yes"/"No" instead of "True"/"False". Well actually I want "Ja"/"Nej" (in Danish).</p> <p>Is this possible? </p> <pre><code>&lt;asp:gridview id="GridView1" runat="server" autogeneratecolumns="false"&gt; &lt;columns&gt; ... &lt;asp:boundfield headertext="Active" datafield="Active" dataformatstring="{0:Yes/No}" /&gt; ... &lt;/columns&gt; &lt;/asp:gridview&gt; </code></pre>
[ { "answer_id": 216851, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 3, "selected": false, "text": "<script runat=\"server\">\n TResult Eval<T, TResult>(string field, Func<T, TResult> converter) {\n object o = DataBinder.Eval(Container.DataItem, field);\n if (converter == null) {\n return (TResult)o;\n }\n return converter((T)o);\n }\n</script>\n\n<asp:TemplateField>\n <ItemTemplate>\n <%# Eval<bool, string>(\"Active\", b => b ? \"Yes\" : \"No\") %>\n </ItemTemplate>\n</asp:TemplateField>\n" }, { "answer_id": 216854, "author": "Paco", "author_id": 13376, "author_profile": "https://Stackoverflow.com/users/13376", "pm_score": 2, "selected": false, "text": "ItemDataBound" }, { "answer_id": 315174, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 8, "selected": true, "text": "<asp:TemplateField HeaderText=\"Active\" SortExpression=\"Active\">\n <ItemTemplate><%#IIf(Boolean.Parse(Eval(\"Active\").ToString()), \"Yes\", \"No\")%></ItemTemplate>\n</asp:TemplateField>\n <asp:TemplateField HeaderText=\"Active\" SortExpression=\"Active\">\n <ItemTemplate><%# (Boolean.Parse(Eval(\"Active\").ToString())) ? \"Yes\" : \"No\" %></ItemTemplate>\n</asp:TemplateField>\n" }, { "answer_id": 315274, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 4, "selected": false, "text": "public string YesNo(bool active) \n{\n return active ? \"Yes\" : \"No\";\n}\n TemplateField Bind <%# YesNo(Active) %>\n" }, { "answer_id": 356867, "author": "Corey Coto", "author_id": 45071, "author_profile": "https://Stackoverflow.com/users/45071", "pm_score": 3, "selected": false, "text": "/// <summary>\n/// Adds \"mixins\" to the Boolean class.\n/// </summary>\npublic static class BooleanMixins\n{\n /// <summary>\n /// Converts the value of this instance to its equivalent string representation (either \"Yes\" or \"No\").\n /// </summary>\n /// <param name=\"boolean\"></param>\n /// <returns>string</returns>\n public static string ToYesNoString(this Boolean boolean)\n {\n return boolean ? \"Yes\" : \"No\";\n }\n}\n" }, { "answer_id": 4392051, "author": "Shaun3180", "author_id": 244105, "author_profile": "https://Stackoverflow.com/users/244105", "pm_score": 2, "selected": false, "text": "public string ConvertNullableBoolToYesNo(object pBool)\n{\n if (pBool != null)\n {\n return (bool)pBool ? \"Yes\" : \"No\";\n }\n else\n {\n return \"No\";\n }\n}\n <%# ConvertNullableBoolToYesNo(Eval(\"YOUR_FIELD\"))%>\n" }, { "answer_id": 16651591, "author": "joeysasa", "author_id": 2402057, "author_profile": "https://Stackoverflow.com/users/2402057", "pm_score": 0, "selected": false, "text": "Protected Sub grid_RowDataBound(sender As Object, e As System.Web.UI.WebControls.GridViewRowEventArgs) Handles grid.RowDataBound\n If e.Row.RowType = DataControlRowType.DataRow Then\n If e.Row.Cells(3).Text = \"True\" Then\n e.Row.Cells(3).Text = \"Si\"\n Else\n e.Row.Cells(3).Text = \"No\"\n End If\n End If\nEnd Sub\n cells(3)" }, { "answer_id": 23664672, "author": "Chtioui Malek", "author_id": 1254684, "author_profile": "https://Stackoverflow.com/users/1254684", "pm_score": 1, "selected": false, "text": "<ItemTemplate>\n <%# Boolean.Parse(Eval(\"Active\").ToString()) ? \"Yes\" : \"No\" %>\n</ItemTemplate>\n" }, { "answer_id": 47767424, "author": "SabineMueller", "author_id": 4308699, "author_profile": "https://Stackoverflow.com/users/4308699", "pm_score": 0, "selected": false, "text": "Format(aBoolean, \"YES/NO\")\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8547/" ]