qid
int64
4
8.14M
question
stringlengths
20
48.3k
answers
list
date
stringlengths
10
10
metadata
list
input
stringlengths
12
45k
output
stringlengths
2
31.8k
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": "<p>In the line where the error happens, Haskell is expecting \"IO a\", but you are giving it a []. Simplifying things a lot, on a do block on the IO monad, every line is either:</p>\n\n<ul>\n<li>Something which returns a value of the \"IO a\" type; the value of the \"a\" type within it is discarded (so the \"a\" is often \"()\")</li>\n<li>A &lt;- expression, which does the same thing but instead of discarding the value of the \"a\" type gives it the name to the left of the &lt;-</li>\n<li>A let, which does nothing more than give a name to a value</li>\n</ul>\n\n<p>In that do block, the \"hGetLine inh\" returns an \"IO String\", and the String within it is extracted and given the name inpStr. The next line, since it's neither a let or a &lt;-, should have a type \"IO a\", which it doesn't (thus causing the compiler error). What you can do instead, since you already have the String, is a let:</p>\n\n<pre><code>let list' = inpStr:list\n</code></pre>\n\n<p>This creates a new list consisting of the String followed by the original list, and gives it the name of \"list' \".</p>\n\n<p>Change the following line to use \"list' \" instead of \"list\" (thus passing it the new list). That line calls (recursively) mainloop, which will read one more line, call itself, and so on. After reading the whole file, it will return something with the \"IO ()\" type. This \"IO ()\" will be returned to the do block at loadNums. Congratulations, you just created a list with the lines read from the file, in reverse order (since you were appending to the head of the list), and then did nothing to it.</p>\n\n<p>If you want to do something to it, change the \"return ()\" to \"return list\"; the return will generate a value of type \"IO [String]\", with the list within it (return does nothing more than encapsulating the value), which you can extract at loadNums with the &lt;- syntax.</p>\n\n<p>The rest is left as an exercise to the reader.</p>\n" }, { "answer_id": 215812, "author": "ephemient", "author_id": 20713, "author_profile": "https://Stackoverflow.com/users/20713", "pm_score": 4, "selected": false, "text": "<p>Unless this is for homework or something, there's no reason to use so much effort. Reuse is lazy!</p>\n\n<pre><code>getLines = liftM lines . readFile\n\nmain = do\n list &lt;- getLines \"dictionary.txt\"\n mapM_ putStrLn list\n</code></pre>\n\n<p>But as you seem to still be learning Haskell, it is important for you to understand what CesarB has written.</p>\n" } ]
2008/10/18
[ "https://Stackoverflow.com/questions/215748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9506/" ]
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: ``` main = do let list = [] loadNums "dictionary.txt" list loadNums location list = do inh <- openFile location ReadMode mainloop inh list hClose inh mainloop inh list = do ineof <- hIsEOF inh if ineof then return () else do inpStr <- hGetLine inh inpStr:list mainloop inh list ``` 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: ``` Couldn't match expected type `IO' against inferred type `[]' ``` 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. Thanks in advance!
In the line where the error happens, Haskell is expecting "IO a", but you are giving it a []. Simplifying things a lot, on a do block on the IO monad, every line is either: * Something which returns a value of the "IO a" type; the value of the "a" type within it is discarded (so the "a" is often "()") * A <- expression, which does the same thing but instead of discarding the value of the "a" type gives it the name to the left of the <- * A let, which does nothing more than give a name to a value In that do block, the "hGetLine inh" returns an "IO String", and the String within it is extracted and given the name inpStr. The next line, since it's neither a let or a <-, should have a type "IO a", which it doesn't (thus causing the compiler error). What you can do instead, since you already have the String, is a let: ``` let list' = inpStr:list ``` This creates a new list consisting of the String followed by the original list, and gives it the name of "list' ". Change the following line to use "list' " instead of "list" (thus passing it the new list). That line calls (recursively) mainloop, which will read one more line, call itself, and so on. After reading the whole file, it will return something with the "IO ()" type. This "IO ()" will be returned to the do block at loadNums. Congratulations, you just created a list with the lines read from the file, in reverse order (since you were appending to the head of the list), and then did nothing to it. If you want to do something to it, change the "return ()" to "return list"; the return will generate a value of type "IO [String]", with the list within it (return does nothing more than encapsulating the value), which you can extract at loadNums with the <- syntax. The rest is left as an exercise to the reader.
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": 215772, "author": "Josh Segall", "author_id": 2659, "author_profile": "https://Stackoverflow.com/users/2659", "pm_score": 0, "selected": false, "text": "<p>You should be able to return the result from MyFunc, which would then end up in the variable you are currently calling \"ignored\". This eliminates the need to access it in any other way.</p>\n" }, { "answer_id": 215843, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 1, "selected": false, "text": "<p>I think what you need is either <code>PyObject_CallObject(&lt;py function&gt;, &lt;args&gt;)</code>, which returns the return value of the function you call as a PyObject, or <code>PyRun_String(&lt;expression&gt;, Py_eval_input, &lt;globals&gt;, &lt;locals&gt;)</code> which evaluates a single expression and returns its result.</p>\n" }, { "answer_id": 215874, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 4, "selected": true, "text": "<p>First of all, change your function to <code>return</code> the value. <code>print</code>ing it will complicate things since you want to get the value back. Suppose your <code>MyModule.py</code> looks like this:</p>\n\n<pre><code>import thirdparty\n\ndef MyFunc(some_arg):\n result = thirdparty.go()\n return result\n</code></pre>\n\n<p>Now, to do what you want, you have to go beyond basic embedding, as the <a href=\"http://docs.python.org/extending/embedding.html\" rel=\"noreferrer\">documentation says</a>. Here is the full code to run your function:</p>\n\n<pre><code>#include &lt;Python.h&gt;\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</code></pre>\n" }, { "answer_id": 216224, "author": "yoav.aviram", "author_id": 25287, "author_profile": "https://Stackoverflow.com/users/25287", "pm_score": 2, "selected": false, "text": "<p>Based on ΤΖΩΤΖΙΟΥ, Josh and Nosklo's answers i finally got it work using boost.python:</p>\n\n<p>Python:</p>\n\n<pre><code>import thirdparty\n\ndef MyFunc(some_arg):\n result = thirdparty.go()\n return result\n</code></pre>\n\n<p>C++:</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;iostream&gt;\n#include &lt;boost/python.hpp&gt;\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&lt;std::string&gt;(result[\"val\"]);\n } \n catch (error_already_set) \n {\n PyErr_Print();\n }\n\n Py_Finalize();\n return 0;\n}\n</code></pre>\n\n<p>Some important points:</p>\n\n<ol>\n<li>I changed 'exec' to 'exec_file' out of\nconvenience, it also works with\nplain 'exec'. </li>\n<li>The main reason it failed is that <strong>i\ndid not pass a \"local\" name_sapce to\n'exec' or 'exec_file'</strong> - this is now\nfixed by passing name_space twice.</li>\n<li>If the python function returns\nunicode strings, they are not\nconvertible to 'std::string', so i\nhad to suffix all python strings\nwith '.encode('ASCII', 'ignore')'.</li>\n</ol>\n" } ]
2008/10/18
[ "https://Stackoverflow.com/questions/215752", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25287/" ]
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. The C++ code looks something like this: ``` #include <string> #include <iostream> #include <boost/python.hpp> using namespace boost::python; int main(int, char **) { Py_Initialize(); try { object module((handle<>(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<std::string>(name_space["result"]); } catch (error_already_set) { PyErr_Print(); } Py_Finalize(); return 0; } ``` A (very) simplified version of the Python code looks like this: ``` import thirdparty def MyFunc(some_arg): result = thirdparty.go() print result ``` 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.
First of all, change your function to `return` the value. `print`ing it will complicate things since you want to get the value back. Suppose your `MyModule.py` looks like this: ``` import thirdparty def MyFunc(some_arg): result = thirdparty.go() return result ``` Now, to do what you want, you have to go beyond basic embedding, as the [documentation says](http://docs.python.org/extending/embedding.html). Here is the full code to run your function: ``` #include <Python.h> int main(int argc, char *argv[]) { PyObject *pName, *pModule, *pFunc; PyObject *pArgs, *pArg, *pResult; int i; Py_Initialize(); pName = PyString_FromString("MyModule.py"); /* Error checking of pName left out as exercise */ pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule != NULL) { pFunc = PyObject_GetAttrString(pModule, "MyFunc"); /* pFunc is a new reference */ if (pFunc) { pArgs = PyTuple_New(0); pArg = PyString_FromString("some parameter") /* pArg reference stolen here: */ PyTuple_SetItem(pArgs, 0, pArg); pResult = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pResult != NULL) { printf("Result of call: %s\n", PyString_AsString(pResult)); Py_DECREF(pResult); } else { Py_DECREF(pFunc); Py_DECREF(pModule); PyErr_Print(); fprintf(stderr,"Call failed\n"); return 1; } } else { if (PyErr_Occurred()) PyErr_Print(); fprintf(stderr, "Cannot find function"); } Py_XDECREF(pFunc); Py_DECREF(pModule); } else { PyErr_Print(); fprintf(stderr, "Failed to load module"); return 1; } Py_Finalize(); return 0; } ```
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": 215772, "author": "Josh Segall", "author_id": 2659, "author_profile": "https://Stackoverflow.com/users/2659", "pm_score": 0, "selected": false, "text": "<p>You should be able to return the result from MyFunc, which would then end up in the variable you are currently calling \"ignored\". This eliminates the need to access it in any other way.</p>\n" }, { "answer_id": 215843, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 1, "selected": false, "text": "<p>I think what you need is either <code>PyObject_CallObject(&lt;py function&gt;, &lt;args&gt;)</code>, which returns the return value of the function you call as a PyObject, or <code>PyRun_String(&lt;expression&gt;, Py_eval_input, &lt;globals&gt;, &lt;locals&gt;)</code> which evaluates a single expression and returns its result.</p>\n" }, { "answer_id": 215874, "author": "nosklo", "author_id": 17160, "author_profile": "https://Stackoverflow.com/users/17160", "pm_score": 4, "selected": true, "text": "<p>First of all, change your function to <code>return</code> the value. <code>print</code>ing it will complicate things since you want to get the value back. Suppose your <code>MyModule.py</code> looks like this:</p>\n\n<pre><code>import thirdparty\n\ndef MyFunc(some_arg):\n result = thirdparty.go()\n return result\n</code></pre>\n\n<p>Now, to do what you want, you have to go beyond basic embedding, as the <a href=\"http://docs.python.org/extending/embedding.html\" rel=\"noreferrer\">documentation says</a>. Here is the full code to run your function:</p>\n\n<pre><code>#include &lt;Python.h&gt;\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</code></pre>\n" }, { "answer_id": 216224, "author": "yoav.aviram", "author_id": 25287, "author_profile": "https://Stackoverflow.com/users/25287", "pm_score": 2, "selected": false, "text": "<p>Based on ΤΖΩΤΖΙΟΥ, Josh and Nosklo's answers i finally got it work using boost.python:</p>\n\n<p>Python:</p>\n\n<pre><code>import thirdparty\n\ndef MyFunc(some_arg):\n result = thirdparty.go()\n return result\n</code></pre>\n\n<p>C++:</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;iostream&gt;\n#include &lt;boost/python.hpp&gt;\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&lt;std::string&gt;(result[\"val\"]);\n } \n catch (error_already_set) \n {\n PyErr_Print();\n }\n\n Py_Finalize();\n return 0;\n}\n</code></pre>\n\n<p>Some important points:</p>\n\n<ol>\n<li>I changed 'exec' to 'exec_file' out of\nconvenience, it also works with\nplain 'exec'. </li>\n<li>The main reason it failed is that <strong>i\ndid not pass a \"local\" name_sapce to\n'exec' or 'exec_file'</strong> - this is now\nfixed by passing name_space twice.</li>\n<li>If the python function returns\nunicode strings, they are not\nconvertible to 'std::string', so i\nhad to suffix all python strings\nwith '.encode('ASCII', 'ignore')'.</li>\n</ol>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215753", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24696/" ]
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. Can this be done in ASP.NET? I know there are ORMs out there, but do they come with an editing system? To explain what I mean by an editing system, consider a class for defining people ``` class Person { string First_Name; string Last_Name } ``` And then perhaps with one bold stroke something like this: ``` CreateEditAbleClass(Person) ``` You would get the functionality below in a browser: <http://www.yart.com.au/images/orm_editor.jpg> 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. I currently use DataGrids and a lot of manual coding to achieve these results.
First of all, change your function to `return` the value. `print`ing it will complicate things since you want to get the value back. Suppose your `MyModule.py` looks like this: ``` import thirdparty def MyFunc(some_arg): result = thirdparty.go() return result ``` Now, to do what you want, you have to go beyond basic embedding, as the [documentation says](http://docs.python.org/extending/embedding.html). Here is the full code to run your function: ``` #include <Python.h> int main(int argc, char *argv[]) { PyObject *pName, *pModule, *pFunc; PyObject *pArgs, *pArg, *pResult; int i; Py_Initialize(); pName = PyString_FromString("MyModule.py"); /* Error checking of pName left out as exercise */ pModule = PyImport_Import(pName); Py_DECREF(pName); if (pModule != NULL) { pFunc = PyObject_GetAttrString(pModule, "MyFunc"); /* pFunc is a new reference */ if (pFunc) { pArgs = PyTuple_New(0); pArg = PyString_FromString("some parameter") /* pArg reference stolen here: */ PyTuple_SetItem(pArgs, 0, pArg); pResult = PyObject_CallObject(pFunc, pArgs); Py_DECREF(pArgs); if (pResult != NULL) { printf("Result of call: %s\n", PyString_AsString(pResult)); Py_DECREF(pResult); } else { Py_DECREF(pFunc); Py_DECREF(pModule); PyErr_Print(); fprintf(stderr,"Call failed\n"); return 1; } } else { if (PyErr_Occurred()) PyErr_Print(); fprintf(stderr, "Cannot find function"); } Py_XDECREF(pFunc); Py_DECREF(pModule); } else { PyErr_Print(); fprintf(stderr, "Failed to load module"); return 1; } Py_Finalize(); return 0; } ```
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": "<p>As it's a functional programming language Array.map is probably what you're looking for:</p>\n\n<pre><code>class Person(name : String, age : Int){\n def toXml() = &lt;person&gt;&lt;name&gt;{ name }&lt;/name&gt;&lt;age&gt;{ age }&lt;/age&gt;&lt;/person&gt;\n}\n\nobject xml {\n val people = List(\n new Person(\"Alice\", 16),\n new Person(\"Bob\", 64)\n )\n\n val data = &lt;people&gt;{ people.map(p =&gt; p.toXml()) }&lt;/people&gt;\n\n def main(args : Array[String]){\n println(data)\n }\n}\n</code></pre>\n\n<p>Results in:</p>\n\n<pre><code>&lt;people&gt;&lt;person&gt;&lt;name&gt;Alice&lt;/name&gt;&lt;age&gt;16&lt;/age&gt;&lt;/person&gt;&lt;person&gt;&lt;name&gt;Bob&lt;/name&gt;&lt;age&gt;64&lt;/age&gt;&lt;/person&gt;&lt;/people&gt;\n</code></pre>\n\n<p>A formatted result (for a better read):</p>\n\n<pre><code>&lt;people&gt;\n &lt;person&gt;\n &lt;name&gt;Alice&lt;/name&gt;\n &lt;age&gt;16&lt;/age&gt;\n &lt;/person&gt;\n &lt;person&gt;\n &lt;name&gt;Bob&lt;/name&gt;\n &lt;age&gt;64&lt;/age&gt;\n &lt;/person&gt;\n&lt;/people&gt;\n</code></pre>\n" }, { "answer_id": 319216, "author": "hishadow", "author_id": 7188, "author_profile": "https://Stackoverflow.com/users/7188", "pm_score": 3, "selected": false, "text": "<p>For completeness, you can also use for..yield (or function calls):</p>\n\n<pre><code>import scala.xml\n\ncase class Person(val name: String, val age: Int) {\n def toXml(): xml.Elem =\n &lt;person&gt;&lt;name&gt;{ name }&lt;/name&gt;&lt;age&gt;{ age }&lt;/age&gt;&lt;/person&gt;\n}\n\ndef peopleToXml(people: List[Person]): xml.Elem = {\n &lt;people&gt;{\n for {person &lt;- people if person.age &gt; 39}\n yield person.toXml\n }&lt;/people&gt;\n}\n\nval data = List(Person(\"joe\",40),Person(\"mary\", 35))\nprintln(peopleToXml(data))\n</code></pre>\n\n<p>(fixed error noted by Woody Folsom)</p>\n" }, { "answer_id": 365893, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Actually, the line yield person.toXml() does not compile for me, but yield person.toXml (without the parentheses) does. The original version complains of 'overloaded method value apply' even if I change the def of 'ToXml' to explicitly return a scala.xml.Elem</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17138/" ]
If you have something like: ``` val myStuff = Array(Person("joe",40), Person("mary", 35)) ``` 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? ``` val myXml = <people>{ /* what here?! */ }</people> ``` The resulting value should be something like: ``` <people><person><name>joe</name><age>40</age></person> <person><name>mary</name><age>39</age></person></people> ```
As it's a functional programming language Array.map is probably what you're looking for: ``` class Person(name : String, age : Int){ def toXml() = <person><name>{ name }</name><age>{ age }</age></person> } object xml { val people = List( new Person("Alice", 16), new Person("Bob", 64) ) val data = <people>{ people.map(p => p.toXml()) }</people> def main(args : Array[String]){ println(data) } } ``` Results in: ``` <people><person><name>Alice</name><age>16</age></person><person><name>Bob</name><age>64</age></person></people> ``` A formatted result (for a better read): ``` <people> <person> <name>Alice</name> <age>16</age> </person> <person> <name>Bob</name> <age>64</age> </person> </people> ```
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": "<p>No, you can't do what you want in plain OCaml. You could write a syntax extension with <a href=\"http://martin.jambon.free.fr/extend-ocaml-syntax.htm\" rel=\"nofollow noreferrer\">camlp4</a> (which is a kind of a macro system, though a different kind than you're probably accustomed to) that would transform</p>\n\n<pre><code>UPDATE_FIELD x f y\n</code></pre>\n\n<p>into</p>\n\n<pre><code>x.f &lt;- y\n</code></pre>\n\n<p>Alternatively, you could stuff things into a hash table and forgo type safety.</p>\n\n<p>NOTE: The version of camlp4 included in OCaml version 3.10 and later is different than and incompatible with the previous version. For information about the latest version, see <a href=\"http://www.ocaml-tutorial.org/camlp4_3.10\" rel=\"nofollow noreferrer\">the OCaml tutorial site</a>.</p>\n" }, { "answer_id": 264390, "author": "zrr", "author_id": 34515, "author_profile": "https://Stackoverflow.com/users/34515", "pm_score": 3, "selected": false, "text": "<p>You can't do quite what you want, but you can greatly reduce the boilerplate with a higher-order function:</p>\n\n<pre><code>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 -&gt; p.x &lt;- v)\nlet update_y = update_gen (fun p v -&gt; p.y &lt;- v)\nlet update_z = update_gen (fun p v -&gt; p.z &lt;- v)\n</code></pre>\n\n<p>OCaml does have a macro system (camlp4) and it does allow you to implement this kind of thing, with some work.</p>\n" }, { "answer_id": 4782410, "author": "ygrek", "author_id": 118799, "author_profile": "https://Stackoverflow.com/users/118799", "pm_score": 0, "selected": false, "text": "<p>As noted above ocaml has macro system. And for this task only small fraction of it is needed :</p>\n\n<pre><code>open Printf\n\ntype t = { mutable x : float; mutable y : float; mutable z : float; mutable t : int; }\n\nlet add_delta p = p.t &lt;- 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 -&gt;\n add_delta p;\n p.x &lt;- 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</code></pre>\n\n<p>Compile with:</p>\n\n<pre><code>ocamlfind ocamlc -package camlp4.macro -syntax camlp4o q.ml -o q\n</code></pre>\n\n<p>See the generated code with :</p>\n\n<pre><code>camlp4o Camlp4MacroParser.cmo q.ml\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18446/" ]
I'm a very novice OCaml programmer so please forgive me if this is a stupid/obvious question. There's *a lot* to absorb and I may have missed this in the documentation. I have a base of code that's starting to look like this: ``` let update_x p x = add_delta p; p.x <- x; refresh p let update_y p y = add_delta p; p.y <- y; refresh p let update_z p z = add_delta p; p.z <- z; refresh p ``` The duplication is starting to bug me because I *want* to write something like this: ``` let update_scalar p scalar value = add_delta p; magic_reflection (p, scalar) <- value; refresh p ``` This way when I update x I can simply call: ``` update_scalar p 'x' value ``` This calls out "macros!" to me but I don't believe OCaml has a macro system. What else can I do?
No, you can't do what you want in plain OCaml. You could write a syntax extension with [camlp4](http://martin.jambon.free.fr/extend-ocaml-syntax.htm) (which is a kind of a macro system, though a different kind than you're probably accustomed to) that would transform ``` UPDATE_FIELD x f y ``` into ``` x.f <- y ``` Alternatively, you could stuff things into a hash table and forgo type safety. NOTE: The version of camlp4 included in OCaml version 3.10 and later is different than and incompatible with the previous version. For information about the latest version, see [the OCaml tutorial site](http://www.ocaml-tutorial.org/camlp4_3.10).
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": 215845, "author": "Giao", "author_id": 14099, "author_profile": "https://Stackoverflow.com/users/14099", "pm_score": 2, "selected": false, "text": "<p>You could use <a href=\"http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/mktemp.3.html\" rel=\"nofollow noreferrer\">mktemp</a> to get a temp filename.</p>\n" }, { "answer_id": 215863, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": true, "text": "<p>A safe way is to use <a href=\"https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/mkstemp.3.html\" rel=\"nofollow noreferrer\">mkstemp(3)</a>.</p>\n" }, { "answer_id": 215927, "author": "Ben Gottlieb", "author_id": 6694, "author_profile": "https://Stackoverflow.com/users/6694", "pm_score": 4, "selected": false, "text": "<p><strong>[Note: This applies to the iPhone SDK, not the Mac OS SDK]</strong> </p>\n\n<p>From what I can tell, these functions aren't present in the SDK (the <code>unistd.h</code> file is drastically pared down when compared to the standard Mac OS X 10.5 file). I would use something along the lines of: </p>\n\n<pre><code>[NSTemporaryDirectory() stringByAppendingPathComponent: [NSString stringWithFormat: @\"%.0f.%@\", [NSDate timeIntervalSinceReferenceDate] * 1000.0, @\"txt\"]];\n</code></pre>\n\n<p>Not the prettiest, but functional</p>\n" }, { "answer_id": 216411, "author": "alextgordon", "author_id": 1165750, "author_profile": "https://Stackoverflow.com/users/1165750", "pm_score": 0, "selected": false, "text": "<p>You could use an <code>NSTask</code> to <code>uuidgen</code> to get a unique file name, then append that to a string from <code>NSTemporaryDirectory()</code>. This won't work on Cocoa Touch. It is a bit long-winded though.</p>\n" }, { "answer_id": 4001613, "author": "Philipp", "author_id": 230475, "author_profile": "https://Stackoverflow.com/users/230475", "pm_score": 4, "selected": false, "text": "<p>I created a pure Cocoa solution by way of a category on <code>NSFileManager</code> that uses a combination of <code>NSTemporary()</code> and a globally unique ID.</p>\n\n<p>Here the header file:</p>\n\n<pre><code>@interface NSFileManager (TemporaryDirectory)\n\n-(NSString *) createTemporaryDirectory;\n\n@end\n</code></pre>\n\n<p>And the implementation file:</p>\n\n<pre><code>@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</code></pre>\n\n<p>This creates a temporary directory but could be easily adapted to use <code>createFileAtPath:contents:attributes:</code> instead of <code>createDirectoryAtPath:</code> to create a file instead.</p>\n" }, { "answer_id": 8307013, "author": "muzz", "author_id": 665366, "author_profile": "https://Stackoverflow.com/users/665366", "pm_score": 4, "selected": false, "text": "<p>Apple has provided an excellent way for accessing temp directory and creating unique names for the temp files.</p>\n\n<pre><code>- (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</code></pre>\n\n<p>LINK :::: <a href=\"http://developer.apple.com/library/ios/#samplecode/SimpleURLConnections/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009245\" rel=\"noreferrer\">http://developer.apple.com/library/ios/#samplecode/SimpleURLConnections/Introduction/Intro.html#//apple_ref/doc/uid/DTS40009245</a>\nsee file :::AppDelegate.m</p>\n" }, { "answer_id": 24602733, "author": "SwiftArchitect", "author_id": 218152, "author_profile": "https://Stackoverflow.com/users/218152", "pm_score": 0, "selected": false, "text": "<p>Adding to @Philipp:</p>\n\n<pre><code>- (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</code></pre>\n" }, { "answer_id": 24755281, "author": "fzwo", "author_id": 534888, "author_profile": "https://Stackoverflow.com/users/534888", "pm_score": 4, "selected": false, "text": "<p>If targeting iOS 6.0 or Mac OS X 10.8 or higher:</p>\n\n<pre><code>NSString *tempFilePath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSUUID UUID] UUIDString]];\n</code></pre>\n" }, { "answer_id": 31205436, "author": "Bart van Kuik", "author_id": 1085556, "author_profile": "https://Stackoverflow.com/users/1085556", "pm_score": 3, "selected": false, "text": "<h1>Swift 5 and Swift 4.2</h1>\n\n<pre><code>import Foundation\n\nfunc pathForTemporaryFile(with prefix: String) -&gt; 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</code></pre>\n\n<p>Or alternatively Ssswift's oneliner:</p>\n\n<pre><code>let prefix = \"blah\"\nlet url2 = URL(fileURLWithPath: NSTemporaryDirectory()).appendingPathComponent(\"\\(prefix)-\\(UUID())\")\nprint(url2)\n</code></pre>\n" }, { "answer_id": 44595622, "author": "Ssswift", "author_id": 7419656, "author_profile": "https://Stackoverflow.com/users/7419656", "pm_score": 2, "selected": false, "text": "<p>The modern way to do this is <code>FileManager</code>'s <a href=\"https://developer.apple.com/documentation/foundation/filemanager/1407693-url\" rel=\"nofollow noreferrer\"><code>url(for:in:appropriateFor:create:)</code></a>.</p>\n\n<p>With this method, you can specify a <a href=\"https://developer.apple.com/documentation/foundation/filemanager.searchpathdirectory\" rel=\"nofollow noreferrer\"><code>SearchPathDirectory</code></a> to say exactly what kind of temporary directory you want. For example, a <code>.cachesDirectory</code> will persist between runs (as possible) and be saved in the user's library, while a <code>.itemReplacementDirectory</code> will be on the same volume as the target file.</p>\n" }, { "answer_id": 61499755, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Don't use legacy APIs like <code>NSTemporaryDirectory</code>, get a proper <code>URL</code> instead from <code>FileManager</code>.</p>\n\n<pre><code>let tmpURL = FileManager\n .default\n .temporaryDirectory\n .appendingPathComponent(UUID().uuidString)\n</code></pre>\n\n<p>You'd still have to create the directory.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215820", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28106/" ]
Years ago when I was working with C# I could easily create a temporary file and get its name with this function: ``` Path.GetTempFileName(); ``` This function would create a file with a unique name in the temporary directory and return the full path to that file. In the Cocoa API's, the closest thing I can find is: ``` NSTemporaryDirectory ``` Am I missing something obvious or is there no built in way to do this?
A safe way is to use [mkstemp(3)](https://developer.apple.com/library/archive/documentation/System/Conceptual/ManPages_iPhoneOS/man3/mkstemp.3.html).
215,851
<p>I am developing a kernel for an operating system. In order to execute it, I've decided to use GRUB. Currently, I have a script attached to GRUB's <code>stage1</code>, <code>stage2</code>, a pad file and the kernel itself together which makes it bootable. The only problem is that when I run it, you have to let GRUB know where the kernel is and how big it is manually and then boot it, like this:</p> <pre>kernel 200+KERNELSIZE boot</pre> <p><code>KERNELSIZE</code> is the size of the kernel in blocks. This is fine and alright for a start, but is it possible to get these values in the binary and make GRUB boot the kernel automatically? Any suggestions on how to accomplish that?</p>
[ { "answer_id": 217507, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": true, "text": "<p>I would imagine you could just make your own menu.lst conf file, load that at the grub shell with \"configfile /path/to/menu.lst\" and then do \"setup (hd0)\" replacing values as needed. I'm just guessing though.. no telling what the differences are on your custom setup.</p>\n" }, { "answer_id": 217519, "author": "user29480", "author_id": 29480, "author_profile": "https://Stackoverflow.com/users/29480", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://www.gnu.org/software/grub/manual/grub.html#Embedded-data\" rel=\"nofollow noreferrer\"><a href=\"http://www.gnu.org/software/grub/manual/grub.html#Embedded-data\" rel=\"nofollow noreferrer\">http://www.gnu.org/software/grub/manual/grub.html#Embedded-data</a></a> gives some general information about block list storage in GRUB. Most importantly, it mentions that block lists are stored in well defined locations in stage2.</p>\n\n<p>You will probably want to look at the GRUB source code to figure out the exact location.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215851", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1256/" ]
I am developing a kernel for an operating system. In order to execute it, I've decided to use GRUB. Currently, I have a script attached to GRUB's `stage1`, `stage2`, a pad file and the kernel itself together which makes it bootable. The only problem is that when I run it, you have to let GRUB know where the kernel is and how big it is manually and then boot it, like this: ``` kernel 200+KERNELSIZE boot ``` `KERNELSIZE` is the size of the kernel in blocks. This is fine and alright for a start, but is it possible to get these values in the binary and make GRUB boot the kernel automatically? Any suggestions on how to accomplish that?
I would imagine you could just make your own menu.lst conf file, load that at the grub shell with "configfile /path/to/menu.lst" and then do "setup (hd0)" replacing values as needed. I'm just guessing though.. no telling what the differences are on your custom setup.
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": "<p>Use an <code>XMLReader</code> to load the document and set the <code>ValidationType</code> property of the reader settings to <code>None</code>. </p>\n" }, { "answer_id": 216207, "author": "Richard Nienaber", "author_id": 9539, "author_profile": "https://Stackoverflow.com/users/9539", "pm_score": 2, "selected": false, "text": "<p>Try something like this:</p>\n\n<pre><code>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</code></pre>\n\n<p>The thing to note here is that XmlReaderSettings has the <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.prohibitdtd.aspx\" rel=\"nofollow noreferrer\">ProhibitDtd</a> property set to true by default.</p>\n" }, { "answer_id": 216327, "author": "spender", "author_id": 14357, "author_profile": "https://Stackoverflow.com/users/14357", "pm_score": 3, "selected": false, "text": "<p>The document being loaded HAS a DTD.</p>\n\n<p>With:</p>\n\n<pre><code>settings.ProhibitDtd = true;\n</code></pre>\n\n<p>I see the following exception:</p>\n\n<blockquote>\n <p>Service cannot be started. System.Xml.XmlException: For security reasons DTD is prohibited in this XML document. To enable DTD processing set the ProhibitDtd property on XmlReaderSettings to false and pass the settings into XmlReader.Create method.</p>\n</blockquote>\n\n<p>So, it looks like ProhibitDtd MUST be set to true in this instance.</p>\n\n<p>It looked like ValidationType would do the trick, but with:</p>\n\n<pre><code>settings.ValidationType = ValidationType.None;\n</code></pre>\n\n<p>I'm still seeing a connection to the DTD uri.</p>\n" }, { "answer_id": 216747, "author": "Richard Nienaber", "author_id": 9539, "author_profile": "https://Stackoverflow.com/users/9539", "pm_score": 6, "selected": true, "text": "<p>After some more digging, maybe you should set the <a href=\"http://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.xmlresolver.aspx\" rel=\"noreferrer\">XmlResolver</a> property of the XmlReaderSettings object to null.</p>\n\n<blockquote>\n <p>'The XmlResolver is used to locate and\n open an XML instance document, or to\n locate and open any external resources\n referenced by the XML instance\n document. This can include entities,\n DTD, or schemas.'</p>\n</blockquote>\n\n<p>So the code would look like this: </p>\n\n<pre><code> 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</code></pre>\n" }, { "answer_id": 5052595, "author": "Gunther Schadow", "author_id": 558744, "author_profile": "https://Stackoverflow.com/users/558744", "pm_score": 3, "selected": false, "text": "<p>This is actually a flaw in the XML specifications. The W3C is bemoaning that people all hit their servers like mad to load schemas billions of times. Unfortunately just about no standard XML library gets this right, they all hit the servers over and over again.</p>\n\n<p>The problem with DTDs is particularly serious, because DTDs may include general entity declarations (for things like <code>&amp;amp;</code> -> &amp;) which the XML file may actually rely upon. So if your parser chooses to forgo loading the DTD, and the XML makes use of general entity references, parsing may actually fail.</p>\n\n<p>The only solution to this problem would be a transparent caching entity resolver, which would put the downloaded files into some archive in the library search path, so that this archive would be dynamically created and almost automatically bundled with any software distributions made. But even in the Java world there is not one decent such EntityResolver floating about, certainly not built-in to anything from apache foundation.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215854", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14357/" ]
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?
After some more digging, maybe you should set the [XmlResolver](http://msdn.microsoft.com/en-us/library/system.xml.xmlreadersettings.xmlresolver.aspx) property of the XmlReaderSettings object to null. > > 'The XmlResolver is used to locate and > open an XML instance document, or to > locate and open any external resources > referenced by the XML instance > document. This can include entities, > DTD, or schemas.' > > > So the code would look like this: ``` XmlReaderSettings settings = new XmlReaderSettings(); settings.XmlResolver = null; settings.DtdProcessing = DtdProcessing.Parse; XmlDocument doc = new XmlDocument(); using (StringReader sr = new StringReader(xml)) using (XmlReader reader = XmlReader.Create(sr, settings)) { doc.Load(reader); } ```
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": "<p>CLISP implements an extension to evaluate a form in the lexical environment. From the fact that it is an extension, I suspect you can't do that in a standard-compliant way.</p>\n\n<pre><code>(ext:eval-env x (ext:the-environment))\n</code></pre>\n\n<p>See <a href=\"http://clisp.cons.org/impnotes.html#eval-environ\" rel=\"nofollow noreferrer\">http://clisp.cons.org/impnotes.html#eval-environ</a>.</p>\n" }, { "answer_id": 218755, "author": "dsm", "author_id": 7780, "author_profile": "https://Stackoverflow.com/users/7780", "pm_score": 0, "selected": false, "text": "<p>In Common Lisp you can define <a href=\"http://www.cvc.uab.es/~javier/CrossVisions/Help/FrameTopic487.html\" rel=\"nofollow noreferrer\">*evalhook*</a> Which allows you to pass an environment to <code>(eval ...)</code>. <code>*evalhook*</code> is platform independent.</p>\n" }, { "answer_id": 219575, "author": "Matthias Benkard", "author_id": 15517, "author_profile": "https://Stackoverflow.com/users/15517", "pm_score": 2, "selected": false, "text": "<p>What is the actual problem that you want to solve? Most likely, you're trying to tackle it the wrong way. Lexical bindings are for things that appear lexically within their scope, not for random stuff you get from outside.</p>\n\n<p>Maybe you want a dynamic closure? Such a thing doesn't exist in Common Lisp, although it does in some Lisp dialects (like Pico Lisp, as far as I understand).</p>\n\n<p>Note that you <em>can</em> do the following, which is similar:</p>\n\n<pre><code>(defvar *a*)\n(defvar *x* '(+ *a* 2)) ;'\n\n(let ((a 10))\n ;; ...\n (let ((*a* a))\n (eval *x*)))\n</code></pre>\n\n<p>I advise you to think hard about whether you really want this, though.</p>\n" }, { "answer_id": 614707, "author": "Rainer Joswig", "author_id": 69545, "author_profile": "https://Stackoverflow.com/users/69545", "pm_score": 4, "selected": true, "text": "<p>You need to create code that has the necessary bindings. Wrap a LET around your code and bind every variable you want to make available in your code:</p>\n\n<pre><code>(defvar *x* '(+ a 2))\n\n(let ((a 4))\n (eval `(let ((a ,a))\n ,*x*)))\n</code></pre>\n" }, { "answer_id": 616214, "author": "dmitry_vk", "author_id": 35054, "author_profile": "https://Stackoverflow.com/users/35054", "pm_score": 0, "selected": false, "text": "<p>It is possible to use COMPILE to compile the expression into function and then use PROGV to FUNCALL the compiled function in the environment where variables are dynamically set. Or, better, use COMPILE to compile the expression into function that accepts variables.</p>\n\n<p>Compile accepts the function definition as a list and turns it into function. In case of SBCL, this function is compiled into machine code and will execute efficiently.</p>\n\n<p>First option (using compile and progv):</p>\n\n<pre><code>(defvar *fn* (compile nil '(lambda () (+ a 2)))\n(progv '(a) '(4) (funcall *fn*))\n=&gt;\n6\n</code></pre>\n\n<p>Second option:</p>\n\n<pre><code>(defvar *fn* (compile nil '(lambda (a) (+ a 2))))\n(funcall *fn* 4)\n=&gt;\n6\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215883", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7492/" ]
I have an s-expression bound to a variable in Common Lisp: ``` (defvar x '(+ a 2)) ``` 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: ``` (let ((a 4)) (lambda () (eval x))) ``` and ``` (let ((a 4)) (eval `(lambda () ,x))) ``` 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? EDIT: So if there is not solution to the EVAL problem, how else can it be done? 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.
You need to create code that has the necessary bindings. Wrap a LET around your code and bind every variable you want to make available in your code: ``` (defvar *x* '(+ a 2)) (let ((a 4)) (eval `(let ((a ,a)) ,*x*))) ```
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": "<p>Typical operating systems don't provide the capability to insert or delete content of a file \"in-place\". What you will need to do is write a function that reads the first file, and creates a <em>new</em> output file containing the lines you want to keep. Then when you're done, delete the old file and rename the new one to the old name.</p>\n\n<p>In pseudocode:</p>\n\n<pre><code>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</code></pre>\n\n<p>The advantage of this method over some of the other ones presented is that it <em>doesn't</em> require you to read the whole file into memory first. You didn't mention how large your upper size limit was, but if it's something like 100 MB you might find that loading the file into memory is not an acceptable use of space.</p>\n" }, { "answer_id": 215899, "author": "Darryl Hein", "author_id": 5441, "author_profile": "https://Stackoverflow.com/users/5441", "pm_score": 0, "selected": false, "text": "<p>If you can run a linux command, try <code>split</code>. It allows you to split by line count to make things easy.</p>\n\n<p>Otherwise, I'm thinking you'll have to read it in and write to 2 other files.</p>\n" }, { "answer_id": 215901, "author": "warren", "author_id": 4418, "author_profile": "https://Stackoverflow.com/users/4418", "pm_score": 0, "selected": false, "text": "<p>Alternatively to <a href=\"https://stackoverflow.com/questions/215896/how-to-use-php-to-delete-x-number-of-lines-from-the-beginning-of-a-text-file#215898\">@Greg's</a> answer, you can read-in the entire file into an array, skip the first X many entries, then rewrite the array to the file.</p>\n\n<p>As an approach: <a href=\"http://us3.php.net/manual/en/function.file-get-contents.php\" rel=\"nofollow noreferrer\">http://us3.php.net/manual/en/function.file-get-contents.php</a></p>\n\n<pre><code>$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</code></pre>\n" }, { "answer_id": 215909, "author": "bbxbby", "author_id": 29230, "author_profile": "https://Stackoverflow.com/users/29230", "pm_score": 3, "selected": true, "text": "<pre><code>$x_amount_of_lines = 30;\n$log = 'path/to/log.txt';\nif (filesize($log) &gt;= $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</code></pre>\n\n<p>edit:\nwith correction from by rcar and saving the first line.</p>\n" }, { "answer_id": 215916, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 2, "selected": false, "text": "<p>You could use the <a href=\"http://php.net/file\" rel=\"nofollow noreferrer\">file()</a> function to read the file into an array of lines, then use <a href=\"http://php.net/array_slice\" rel=\"nofollow noreferrer\">array_slice()</a> to remove the first X lines.</p>\n\n<pre><code>$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</code></pre>\n" }, { "answer_id": 216353, "author": "e-satis", "author_id": 9951, "author_profile": "https://Stackoverflow.com/users/9951", "pm_score": 5, "selected": false, "text": "<h2>Use the SPL, Luke</h2>\n\n<p>PHP 5 comes with plenty of iterators goodness :</p>\n\n<pre><code>&lt;?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-&gt;fwrite($line); \n\n?&gt;\n</code></pre>\n\n<p>It's cleaner that what you can do while messing with fopen, it does not hold the entire file in memory, only one line at a time, and you can plug it and reuse the pattern anywhere since it's full OO.</p>\n" }, { "answer_id": 217468, "author": "Hannes Landeholm", "author_id": 29442, "author_profile": "https://Stackoverflow.com/users/29442", "pm_score": 2, "selected": false, "text": "<p>This is a text-book problem of log files, and I would like to propose another solution.</p>\n\n<p>The problem with the \"removing lines at the beginning of files\" approach is that adding new lines becomes extremly slow, once it has to remove the first lines for every new lines it's writing.</p>\n\n<p>Normal log file appending only involves writing a few more bytes at the end of the file in the file system (and once in a while it has to allocate a new sector, which results in extensive fragmentation - why log files usually are).</p>\n\n<p>But the big problem here is when you are removing a line in the beginning for every row written. The entire file must first be read into memory and then rewritten resulting in huge ammount of I/O to the harddrive (in comparision). To make matters worse, the \"split into PHP array and skip first rows\" solutions here are extremly slow due to the nature of PHP arrays. This is not a problem if the log file size limit is very small or if it is written to unoften, but with a lot of writes (as in the case with log files), the same huge operation has to be done a lot of times resulting in major performance drawbacks.</p>\n\n<p>This can be imagined as parking cars on a line with space for 50. Parking the first 50 cars is quick, just drive in behind the car infront and done. But when you come to 50, and the car at the front (beginning of file) must be removed you have to drive the 2'nd car to the 1'st position, 3rd to 2nd and so on, before you can drive in with the last car on the 50'th position. (And this must be repeated for <em>every</em> new car you want to park!)</p>\n\n<p>My suggestion is instead saving to diffrent log files, datewise, and then store a maximum of 30 days back etc. Thus taking advantage of the filesystem, which has already solved this problem perfectly well.</p>\n" }, { "answer_id": 45090213, "author": "ummdorian", "author_id": 3486547, "author_profile": "https://Stackoverflow.com/users/3486547", "pm_score": 1, "selected": false, "text": "<p>Here's a ready to go function</p>\n\n<pre><code>&lt;?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 &gt; $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?&gt;\n</code></pre>\n" }, { "answer_id": 47984317, "author": "Darshan Jadiye", "author_id": 6789971, "author_profile": "https://Stackoverflow.com/users/6789971", "pm_score": 0, "selected": false, "text": "<p>following code will help you to delete the number of lines from beginning of a file</p>\n\n<pre><code>$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</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215896", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27025/" ]
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? 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 `filesize()` function, so I'll be using that to check the file size. Example log text: ``` *** 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 ```
``` $x_amount_of_lines = 30; $log = 'path/to/log.txt'; if (filesize($log) >= $max_size)) { $file = file($log); $line = $file[0]; $file = array_splice($file, 2, $x_amount_of_lines); $file = array_splice($file, 0, 0, array($line, "\n")); // put the first line back in ... } ``` edit: with correction from by rcar and saving the first line.
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": "<p>How about something like this:</p>\n\n<pre><code>#!/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</code></pre>\n\n<p>Which produces the following output:</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 216246, "author": "Gregory Higley", "author_id": 27779, "author_profile": "https://Stackoverflow.com/users/27779", "pm_score": 0, "selected": false, "text": "<p><strong>EDIT:</strong> This solution doesn't work. Robert Gamble's is the correct solution.</p>\n\n<p>I brainstormed a bit and came up with this solution:</p>\n\n<p>(I know most of you won't know REBOL, but it's a fairly readable language.)</p>\n\n<pre>\nREBOL []\n\nsets: [[1 2 3] [4 5] [6]] ; Here's a set of sets\nelems: 1\nresult: copy []\nforeach set sets [elems: elems * (length? set)]\nfor n 1 elems 1 [\n row: copy []\n foreach set sets [\n index: 1 + (mod (n - 1) length? set)\n append row set/(index)\n ]\n append/only result row\n]\n\nforeach row result [\n print result\n]\n</pre>\n\n<p>This code produces:</p>\n\n<pre><code>1 4 6\n2 5 6\n3 4 6\n1 5 6\n2 4 6\n3 5 6\n</code></pre>\n\n<p>(Upon first reading the numbers above, you may think there are duplicates. I did. But there aren't.)</p>\n\n<p>Interestingly, this code uses almost the very same algorithm (1 + ((n - 1) % 9) that torpedoed my <a href=\"https://stackoverflow.com/questions/204489/calculate-the-digital-root-of-a-number\">Digital Root</a> question.</p>\n" }, { "answer_id": 218446, "author": "Gregory Higley", "author_id": 27779, "author_profile": "https://Stackoverflow.com/users/27779", "pm_score": 2, "selected": false, "text": "<p>For the sake of completeness, Here's Robert Gamble's answer translated into REBOL:</p>\n\n<pre>\nREBOL []\n\ncartesian: func [\n {Given a block of sets, returns the Cartesian product of said sets.}\n sets [block!] {A block containing one or more series! values}\n /local\n elems\n result\n row\n][\n result: copy []\n\n elems: 1\n foreach set sets [\n elems: elems * (length? set)\n ]\n\n for n 0 (elems - 1) 1 [\n row: copy []\n skip: elems\n foreach set sets [\n skip: skip / length? set\n index: (mod to-integer (n / skip) length? set) + 1 ; REBOL is 1-based, not 0-based\n append row set/(index)\n ]\n append/only result row\n ]\n\n result\n]\n\nforeach set cartesian [[1 2] [3 4] [5 6]] [\n print set\n]\n\n; This returns the same thing Robert Gamble's solution did:\n\n1 3 5\n1 3 6\n1 4 5\n1 4 6\n2 3 5\n2 3 6\n2 4 5\n2 4 6\n</pre>\n" }, { "answer_id": 1467360, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>3 times Faster and less memory used (less recycles).</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 1835581, "author": "mpapec", "author_id": 223226, "author_profile": "https://Stackoverflow.com/users/223226", "pm_score": 1, "selected": false, "text": "<pre><code>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</code></pre>\n\n<p>output</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 2365962, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Here is a Java code to generate Cartesian product for arbitrary number of sets with arbitrary number of elements.</p>\n\n<p>in this sample the list \"ls\" contains 4 sets (ls1,ls2,ls3 and ls4) as you can see \"ls\" can contain any number of sets with any number of elements.</p>\n\n<pre><code>import java.util.*;\n\npublic class CartesianProduct {\n\n private List &lt;List &lt;String&gt;&gt; ls = new ArrayList &lt;List &lt;String&gt;&gt; ();\n private List &lt;String&gt; ls1 = new ArrayList &lt;String&gt; ();\n private List &lt;String&gt; ls2 = new ArrayList &lt;String&gt; ();\n private List &lt;String&gt; ls3 = new ArrayList &lt;String&gt; ();\n private List &lt;String&gt; ls4 = new ArrayList &lt;String&gt; ();\n\n public List &lt;String&gt; generateCartesianProduct () {\n List &lt;String&gt; set1 = null;\n List &lt;String&gt; 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 &lt;String&gt; augmentSet (List &lt;String&gt; set1, List &lt;String&gt; set2) {\n\n List &lt;String&gt; augmentedSet = new ArrayList &lt;String&gt; (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&lt;String&gt; cartesionProduct = cp.generateCartesianProduct ();\n for (String val : cartesionProduct) {\n System.out.println (val);\n }\n }\n}\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215908", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27779/" ]
### Note This is not a REBOL-specific question. You can answer it in any language. ### Background The [REBOL](http://www.rebol.com) language supports the creation of domain-specific languages known as "dialects" in REBOL *parlance*. I've created such a dialect for list comprehensions, which aren't natively supported in REBOL. A good cartesian product algorithm is needed for list comprehensions. ### The Problem I've used meta-programming to solve this, by dynamically creating and then executing a sequence of nested `foreach` 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. 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.) 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.
How about something like this: ``` #!/usr/bin/perl use strict; use warnings; my @list1 = qw(1 2); my @list2 = qw(3 4); my @list3 = qw(5 6); # Calculate the Cartesian Product my @cp = cart_prod(\@list1, \@list2, \@list3); # Print the result foreach my $elem (@cp) { print join(' ', @$elem), "\n"; } sub cart_prod { my @sets = @_; my @result; my $result_elems = 1; # Calculate the number of elements needed in the result map { $result_elems *= scalar @$_ } @sets; return undef if $result_elems == 0; # Go through each set and add the appropriate element # to each element of the result my $scale_factor = $result_elems; foreach my $set (@sets) { my $set_elems = scalar @$set; # Elements in this set $scale_factor /= $set_elems; foreach my $i (0 .. $result_elems - 1) { # Calculate the set element to place in this position # of the result set. my $pos = $i / $scale_factor % $set_elems; push @{$result[$i]}, $$set[ $pos ]; } } return @result; } ``` Which produces the following output: ``` 1 3 5 1 3 6 1 4 5 1 4 6 2 3 5 2 3 6 2 4 5 2 4 6 ```
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": "<p>Have you updated your version of the Microsoft.Web.Mvc.dll where the Strongly typed actionlink resides. </p>\n\n<p>Apparently this dll has been updated for the Beta release. The function may have been slightly modified.</p>\n\n<p>I just tried this </p>\n\n<pre><code>&lt;%= Html.ActionLink&lt;HomeController&gt;(x=&gt;x.Search((string)ViewData[\"search\"]), \"search?\") %&gt;\n</code></pre>\n\n<p>and it worked fine.</p>\n" }, { "answer_id": 217335, "author": "Jason Whitehorn", "author_id": 27860, "author_profile": "https://Stackoverflow.com/users/27860", "pm_score": 1, "selected": true, "text": "<p>Ok, I figured out what my problem was.</p>\n\n<p>Apparently I was not even setting the ViewData slot that I was trying to read from in the view, resulting in it being a null value.</p>\n\n<p>So effectually I was writing:</p>\n\n<pre><code>&lt;%= Html.ActionLink&lt;PhotoController&gt;(p =&gt; p.Upload(null), \"upload new photo\") %&gt;\n</code></pre>\n\n<p>I think the ultimate kicker to this whole thing was the fact that the parameter (groupname) represents a non-defaultable value in my routing table.</p>\n\n<pre><code>routes.MapRoute(\n \"Group\", \n \"group/{groupname}/{controller}/{action}/{id}\",\n new {controller = \"Photos\", action = \"View\", Id = \"\"});\n</code></pre>\n\n<p>So according to the routing rule the property groupname has to be present, but according go the Lambda gropname was omitted (null). This resulted in the MVC framework being unable to find a route that satisfied my query, and just returning null.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27860/" ]
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. When I try this: ``` <%= Html.ActionLink<PhotoController>(p => p.Upload(((string)ViewData["groupName"])), "upload new photo") %> ``` The HTML contains a link with an empty URL. ``` <a href="">upload new photo</a> ``` However if I hard code the parameter, like this: ``` <%= Html.ActionLink<PhotoController>(p => p.Upload("groupA"), "upload new photo") %> ``` The output contains an actual URL. ``` <a href="/group/groupA/Photo/Upload">upload new photo</a> ``` 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. Am I doing something incorrect in the first sample to cause this, or is this some short of bug? **Update**: 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.
Ok, I figured out what my problem was. Apparently I was not even setting the ViewData slot that I was trying to read from in the view, resulting in it being a null value. So effectually I was writing: ``` <%= Html.ActionLink<PhotoController>(p => p.Upload(null), "upload new photo") %> ``` I think the ultimate kicker to this whole thing was the fact that the parameter (groupname) represents a non-defaultable value in my routing table. ``` routes.MapRoute( "Group", "group/{groupname}/{controller}/{action}/{id}", new {controller = "Photos", action = "View", Id = ""}); ``` So according to the routing rule the property groupname has to be present, but according go the Lambda gropname was omitted (null). This resulted in the MVC framework being unable to find a route that satisfied my query, and just returning null.
215,933
<p>I'm getting a totally bizzare error trying to compile a C program using GCC. Here is the batch file I am using:</p> <pre><code>echo Now compiling, assembling, and linking the core: nasm -f aout -o start.o start.asm gcc -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-functions -nostdinc -fno-builtin -I./include -c -o consoleio.o consoleio.c gcc -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-functions -nostdinc -fno-builtin -I./include -c -o core.o core.c gcc -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-functions -nostdinc -fno-builtin -I./include -c -o system.o system.c ld -T link.ld -o core.bin start.o core.o system.o consoleio.o echo Done! concat.py pause </code></pre> <p>Here are the error messages I am receiving when trying to run this code. All files are in the same directory, yes the PATH variable is set up correctly:</p> <pre><code>C:\Simple\core&gt;build.bat C:\Simple\core&gt;echo Now compiling, assembling, and linking the core: Now compiling, assembling, and linking the core: C:\Simple\core&gt;nasm -f aout -o start.o start.asm C:\Simple\core&gt;gcc -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-func tions -nostdinc -fno-builtin -I./include -c -o consoleio.o consoleio.c The system cannot execute the specified program. C:\Simple\core&gt;gcc -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-func tions -nostdinc -fno-builtin -I./include -c -o core.o core.c C:\Simple\core&gt;gcc -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-func tions -nostdinc -fno-builtin -I./include -c -o system.o system.c The system cannot execute the specified program. C:\Simple\core&gt;ld -T link.ld -o core.bin start.o core.o system.o consoleio.o c:/djgpp/bin/ld.exe: system.o: No such file: No such file or directory (ENOENT) C:\Simple\core&gt;echo Done! Done! C:\Simple\core&gt;concat.py Traceback (most recent call last): File "C:\Simple\core\concat.py", line 12, in &lt;module&gt; with open("core.bin", "rb") as core: IOError: [Errno 2] No such file or directory: 'core.bin' </code></pre> <p>Now, the interesting thing is the gcc command, which is the issue I'm having. (The other issues seem to be cascading from this.) When compiling core.c, the GCC command works just fine and great, and produces a .o file as expected. When attempting to compile system.c or consoleio.c, GCC fails, but in a very unexpected way: it appears as though windows cannot run the program. This makes <strong>zero</strong> sense to me. I've tried any number of things, including running these commands myself outside the window. Something about core.c is just special, and I can't figure out what the difference is. I literally copied that line and changed the filenames to create the other two lines that are failing.</p> <p>So, in short, HELP. I'm using DJGPP and GCC on windows XP, along with a python script at the end that should tie everything together. (This all worked when the project was a single source file, but attempting to split the file into separate files has caused this strange error.)</p> <p>Thanks.</p> <p>PS: Yes, we <em>are</em> using a batch file, and I know that makes some of you cringe. However, I'd really like to understand this error before moving on to a makefile if possible. ^_^</p> <p>EDIT: The accepted answer was indeed our problem, although the issue was with DJGPP, not Windows. (Windows doesn't seem to have a command limit.) The solution was to compile with MinGW instead of DJGPP, which fixed the issue right away. Thanks guys!</p>
[ { "answer_id": 215944, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 4, "selected": true, "text": "<p>The line that works is 126 characters long, the others are 130 and 136 characters long. The problem is that there is a 127-character limit. I'm not sure how to get around this, but maybe <strong>make</strong> would get around it for you?...</p>\n" }, { "answer_id": 215947, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 0, "selected": false, "text": "<p>Add -v to the gcc command line. gcc is in fact a driver, which runs several other auxiliary programs (tradicionally, the preprocessor, compiler, and assembler); -v makes it show their command lines as they are being executed, and also enables verbose mode. With this, you can see where it is failing.</p>\n" }, { "answer_id": 3013553, "author": "Rugxulo", "author_id": 363335, "author_profile": "https://Stackoverflow.com/users/363335", "pm_score": 0, "selected": false, "text": "<p>As mentioned, DJGPP make (or Bash) or even a simple response file would solve this problem, so it's a non-issue. DJGPP is still plenty good as long for what it does. (P.S. Also see the ELF port or Japheth's HX mod.)</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215933", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19521/" ]
I'm getting a totally bizzare error trying to compile a C program using GCC. Here is the batch file I am using: ``` echo Now compiling, assembling, and linking the core: nasm -f aout -o start.o start.asm gcc -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-functions -nostdinc -fno-builtin -I./include -c -o consoleio.o consoleio.c gcc -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-functions -nostdinc -fno-builtin -I./include -c -o core.o core.c gcc -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-functions -nostdinc -fno-builtin -I./include -c -o system.o system.c ld -T link.ld -o core.bin start.o core.o system.o consoleio.o echo Done! concat.py pause ``` Here are the error messages I am receiving when trying to run this code. All files are in the same directory, yes the PATH variable is set up correctly: ``` C:\Simple\core>build.bat C:\Simple\core>echo Now compiling, assembling, and linking the core: Now compiling, assembling, and linking the core: C:\Simple\core>nasm -f aout -o start.o start.asm C:\Simple\core>gcc -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-func tions -nostdinc -fno-builtin -I./include -c -o consoleio.o consoleio.c The system cannot execute the specified program. C:\Simple\core>gcc -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-func tions -nostdinc -fno-builtin -I./include -c -o core.o core.c C:\Simple\core>gcc -Wall -O -fstrength-reduce -fomit-frame-pointer -finline-func tions -nostdinc -fno-builtin -I./include -c -o system.o system.c The system cannot execute the specified program. C:\Simple\core>ld -T link.ld -o core.bin start.o core.o system.o consoleio.o c:/djgpp/bin/ld.exe: system.o: No such file: No such file or directory (ENOENT) C:\Simple\core>echo Done! Done! C:\Simple\core>concat.py Traceback (most recent call last): File "C:\Simple\core\concat.py", line 12, in <module> with open("core.bin", "rb") as core: IOError: [Errno 2] No such file or directory: 'core.bin' ``` Now, the interesting thing is the gcc command, which is the issue I'm having. (The other issues seem to be cascading from this.) When compiling core.c, the GCC command works just fine and great, and produces a .o file as expected. When attempting to compile system.c or consoleio.c, GCC fails, but in a very unexpected way: it appears as though windows cannot run the program. This makes **zero** sense to me. I've tried any number of things, including running these commands myself outside the window. Something about core.c is just special, and I can't figure out what the difference is. I literally copied that line and changed the filenames to create the other two lines that are failing. So, in short, HELP. I'm using DJGPP and GCC on windows XP, along with a python script at the end that should tie everything together. (This all worked when the project was a single source file, but attempting to split the file into separate files has caused this strange error.) Thanks. PS: Yes, we *are* using a batch file, and I know that makes some of you cringe. However, I'd really like to understand this error before moving on to a makefile if possible. ^\_^ EDIT: The accepted answer was indeed our problem, although the issue was with DJGPP, not Windows. (Windows doesn't seem to have a command limit.) The solution was to compile with MinGW instead of DJGPP, which fixed the issue right away. Thanks guys!
The line that works is 126 characters long, the others are 130 and 136 characters long. The problem is that there is a 127-character limit. I'm not sure how to get around this, but maybe **make** would get around it for you?...
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": 215983, "author": "Gulzar Nazim", "author_id": 4337, "author_profile": "https://Stackoverflow.com/users/4337", "pm_score": 2, "selected": false, "text": "<p>from what I understand, you are looking for a tool to help you with mappings.</p>\n\n<p>If that is the case, you can try the \"<a href=\"http://learn.iis.net/page.aspx/497/user-friendly-url---rule-template/\" rel=\"nofollow noreferrer\">user friendly url - rule template</a>\" feature of url rewrite module (iis7)</p>\n\n<p>Rule templates are used to provide a simple way of creating one or more rewrite rules for a certain scenario. URL rewriter module includes several rule templates for some common usage scenarios. In addition to that URL rewrite module UI provides a framework for plugging in custom rule templates. </p>\n" }, { "answer_id": 216056, "author": "Ben Robbins", "author_id": 1880, "author_profile": "https://Stackoverflow.com/users/1880", "pm_score": 2, "selected": false, "text": "<p>Stackoverflow uses <a href=\"http://msdn.microsoft.com/en-us/library/system.web.routing.aspx\" rel=\"nofollow noreferrer\" title=\"routing\">System.Web.Routing</a>. It's originally from asp.net MVC but usable in any asp.net app. I'm not sure how easy or hard it would be to retrofit routing into an existing app though. </p>\n" }, { "answer_id": 216320, "author": "Schotime", "author_id": 29376, "author_profile": "https://Stackoverflow.com/users/29376", "pm_score": 2, "selected": false, "text": "<p>I have been using a tool called <a href=\"http://www.codeplex.com/IIRF\" rel=\"nofollow noreferrer\">Ionic Rewriter</a></p>\n\n<p>It will use regular expression to rewrite your extensionless URLs to physical URLs for processing. The user only sees the extensionless one however the webserver sees the .aspx etc one.</p>\n\n<p>It seems to work extremely well and is very easy to configure.</p>\n" }, { "answer_id": 216334, "author": "Cristian Libardo", "author_id": 16526, "author_profile": "https://Stackoverflow.com/users/16526", "pm_score": 3, "selected": true, "text": "<p>Perhaps <a href=\"http://weblogs.asp.net/scottgu/archive/2005/11/14/430493.aspx\" rel=\"nofollow noreferrer\">urlMappings</a> could work for you:</p>\n\n<pre><code>&lt;system.web&gt;\n &lt;urlMappings enabled=\"true\"&gt;\n &lt;add url=\"~/test/\" mappedUrl=\"~/test.aspx\"/&gt;\n &lt;/urlMappings&gt;\n</code></pre>\n\n<p>To make it work on IIS6 you to enable wildcard mappings.</p>\n" }, { "answer_id": 1076879, "author": "Ayyash", "author_id": 63202, "author_profile": "https://Stackoverflow.com/users/63202", "pm_score": 1, "selected": false, "text": "<p>i dont know if IIS6.0 supports it or not, but i use web.sitemap, i add an attribute with every node that equals the pretty name i want, then with Application_onBegin I map the pretty url of the request to the one in the sitemap...</p>\n\n<p>you asked for the best way, but I dont think there is one \"best\" way, Ive seen people feed the pretty names from an xml file, others rely on IIS7.0 rewrite feature</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3153/" ]
What's the best way to get a nice clean URL structure like stack overflow has? 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? The site I want this for has hundreds of pages, and is already deployed. I would like a method that requires the least amount of changes possible. Note: * I **do not** want suggestions on how to make the URLs friendly * I **do** want suggestions on how to best manage these friendly URLs and how to create the mappings. 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. <http://www.blahblahblahblahblah7CEE53E1.com/test.aspx> -> <http://www.blahblahblahblahblah7CEE53E1.com/test/> EDIT: I'm running IIS 6.0
Perhaps [urlMappings](http://weblogs.asp.net/scottgu/archive/2005/11/14/430493.aspx) could work for you: ``` <system.web> <urlMappings enabled="true"> <add url="~/test/" mappedUrl="~/test.aspx"/> </urlMappings> ``` To make it work on IIS6 you to enable wildcard mappings.
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": 215970, "author": "Jeff Linahan", "author_id": 2222, "author_profile": "https://Stackoverflow.com/users/2222", "pm_score": 0, "selected": false, "text": "<p>You could use a queue from the standard template library, then create a function that creates a Snapshot object and puts in into the queue. Give this function a static variable which gets incremented every time it is called and written into an id field of the snapshot.</p>\n\n<p><a href=\"http://www.csci.csusb.edu/dick/samples/stl.html\" rel=\"nofollow noreferrer\">http://www.csci.csusb.edu/dick/samples/stl.html</a></p>\n\n<p><a href=\"http://www.cppreference.com/wiki/stl/queue/start\" rel=\"nofollow noreferrer\">http://www.cppreference.com/wiki/stl/queue/start</a></p>\n" }, { "answer_id": 215990, "author": "ray", "author_id": 3879, "author_profile": "https://Stackoverflow.com/users/3879", "pm_score": 0, "selected": false, "text": "<p>I think we need more information for this. If you're simply popping these out of a queue, why do you care what they are named? Objects in a queue are not normally numbered, unless you're implementing it in an array.</p>\n" }, { "answer_id": 215995, "author": "Tomek", "author_id": 29326, "author_profile": "https://Stackoverflow.com/users/29326", "pm_score": 0, "selected": false, "text": "<p>Sorry, the whole queue thing kinda causes uneeded confusion. </p>\n\n<p>Let's take another example. So for this puzzle, the number of pieces in the puzzle are specified by the user. The way I am designing the program is that each Piece of the puzzle is it's own object.</p>\n\n<p>So when I go about creating these Pieces, can I use some kind of variable naming schemes to go about naming these Pieces. so something like this just as an example...</p>\n\n<pre><code>for (int i-0; i &lt; constraint; i++)\nPiece \"Piece\"+i = new Piece();\n</code></pre>\n" }, { "answer_id": 216004, "author": "ray", "author_id": 3879, "author_profile": "https://Stackoverflow.com/users/3879", "pm_score": 0, "selected": false, "text": "<p>You cannot dynamically create variable names in C++, at least not without some (imaginary?) add-on.</p>\n\n<p>edit: As an aside, I did an assignment that I assume is similar to yours in an AI class, where we covered basics like BFS, DFS, and A*. Not once was it necessary to have uniquely named objects for the \"snapshots\", and I used queues.</p>\n\n<p>edit2: and if you need to keep track of how many Snapshots you have, create a count variable that increments every time you create the object.</p>\n" }, { "answer_id": 216005, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 2, "selected": false, "text": "<p>I think you're asking how do you create and keep lots of objects when you don't know how many there will be.</p>\n\n<p>You need to create an array of the objects. Then you can access them as snapshot[1], snapshot[2]... snapshot[i].</p>\n" }, { "answer_id": 216813, "author": "gbjbaanb", "author_id": 13744, "author_profile": "https://Stackoverflow.com/users/13744", "pm_score": 2, "selected": true, "text": "<p>There is a way - you use the <a href=\"http://msdn.microsoft.com/en-us/library/09dwwt6y(VS.80).aspx\" rel=\"nofollow noreferrer\">Preprocessor's Token-Pasting Operator</a>. This allows you to create a name based on a variable, so you'd specify:</p>\n\n<pre><code>#define S(variable) snapshot#variable\n</code></pre>\n\n<p>and you'd be able to create variables named snapshot1, snapshot2 etc:</p>\n\n<pre><code>Snapshot S(1)\nSnapshot S(2)\n</code></pre>\n\n<p>However, I'm not sure this is what you really want, I've maybe used this technique once in practise, and that was for a code generator.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215961", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29326/" ]
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. 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? or do i have to keep track of how many declarations i have made and just hard code it by saying... Snapshot snapshot2; Snapshot snapshot3; Snapshot snapshot4; etc..
There is a way - you use the [Preprocessor's Token-Pasting Operator](http://msdn.microsoft.com/en-us/library/09dwwt6y(VS.80).aspx). This allows you to create a name based on a variable, so you'd specify: ``` #define S(variable) snapshot#variable ``` and you'd be able to create variables named snapshot1, snapshot2 etc: ``` Snapshot S(1) Snapshot S(2) ``` However, I'm not sure this is what you really want, I've maybe used this technique once in practise, and that was for a code generator.
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": "<p>You use the lpMultiByteStr [out] parameter by creating a new char array. You then pass this char array in to get it filled. You only need to initialize the length of the string + 1 so that you can have a null terminated string after the conversion.</p>\n\n<p>Here are a couple of useful helper functions for you, they show the usage of all parameters.</p>\n\n<pre><code>#include &lt;string&gt;\n\nstd::string wstrtostr(const std::wstring &amp;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 &amp;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</code></pre>\n\n<p>--</p>\n\n<p>Anytime in documentation when you see that it has a parameter which is a pointer to a type, and they tell you it is an out variable, you will want to create that type, and then pass in a pointer to it. The function will use that pointer to fill your variable. </p>\n\n<p>So you can understand this better:</p>\n\n<pre><code>//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(&amp;X);\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 216879, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 5, "selected": false, "text": "<p>Elaborating on the <a href=\"https://stackoverflow.com/a/215973/50049\">answer</a> provided by Brian R. Bondy: Here's an example that shows why you can't simply size the output buffer to the number of wide characters in the source string:</p>\n\n<pre><code>#include &lt;windows.h&gt;\n#include &lt;stdio.h&gt;\n#include &lt;wchar.h&gt;\n#include &lt;string.h&gt;\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</code></pre>\n\n<p>And the output:</p>\n\n<pre><code>Wide chars in wcsString: 6\nBytes required for CP950 encoding (excluding NUL terminator): 12\nBytes required for UTF8 encoding (excluding NUL terminator): 18\n</code></pre>\n" }, { "answer_id": 3999597, "author": "tfinniga", "author_id": 9042, "author_profile": "https://Stackoverflow.com/users/9042", "pm_score": 7, "selected": false, "text": "<p>Here's a couple of functions (based on Brian Bondy's example) that use WideCharToMultiByte and MultiByteToWideChar to convert between std::wstring and std::string using utf8 to not lose any data.</p>\n\n<pre><code>// Convert a wide Unicode string to an UTF8 string\nstd::string utf8_encode(const std::wstring &amp;wstr)\n{\n if( wstr.empty() ) return std::string();\n int size_needed = WideCharToMultiByte(CP_UTF8, 0, &amp;wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL);\n std::string strTo( size_needed, 0 );\n WideCharToMultiByte (CP_UTF8, 0, &amp;wstr[0], (int)wstr.size(), &amp;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 &amp;str)\n{\n if( str.empty() ) return std::wstring();\n int size_needed = MultiByteToWideChar(CP_UTF8, 0, &amp;str[0], (int)str.size(), NULL, 0);\n std::wstring wstrTo( size_needed, 0 );\n MultiByteToWideChar (CP_UTF8, 0, &amp;str[0], (int)str.size(), &amp;wstrTo[0], size_needed);\n return wstrTo;\n}\n</code></pre>\n" }, { "answer_id": 66978733, "author": "WBuck", "author_id": 3358499, "author_profile": "https://Stackoverflow.com/users/3358499", "pm_score": 0, "selected": false, "text": "<p>Here is a <code>C</code> implementation of both <code>WideCharToMultiByte</code> and <code>MultiByteToWideChar</code>.\nIn both cases I ensure to tack a <code>null</code> character to the end of the destination buffers.</p>\n<blockquote>\n<p>MultiByteToWideChar does not null-terminate an output string if the input string length is explicitly specified without a terminating null character.</p>\n</blockquote>\n<p>And</p>\n<blockquote>\n<p>WideCharToMultiByte does not null-terminate an output string if the input string length is explicitly specified without a terminating null character.</p>\n</blockquote>\n<p>Even if someone specifies <code>-1</code> and passes in a <code>null</code> terminated string I still allocate enough space for an additional <code>null</code> character because for my use case this was not an issue.</p>\n<pre><code>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</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/215963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23120/" ]
I've read the documentation on [WideCharToMultiByte](http://msdn.microsoft.com/en-us/library/ms776420(VS.85).aspx), but I'm stuck on this parameter: ``` lpMultiByteStr [out] Pointer to a buffer that receives the converted string. ``` I'm not quite sure how to properly initialize the variable and feed it into the function
Here's a couple of functions (based on Brian Bondy's example) that use WideCharToMultiByte and MultiByteToWideChar to convert between std::wstring and std::string using utf8 to not lose any data. ``` // Convert a wide Unicode string to an UTF8 string std::string utf8_encode(const std::wstring &wstr) { if( wstr.empty() ) return std::string(); int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL); std::string strTo( size_needed, 0 ); WideCharToMultiByte (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL); return strTo; } // Convert an UTF8 string to a wide Unicode String std::wstring utf8_decode(const std::string &str) { if( str.empty() ) return std::wstring(); int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0); std::wstring wstrTo( size_needed, 0 ); MultiByteToWideChar (CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed); return wstrTo; } ```
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": 216009, "author": "zxcv", "author_id": 9628, "author_profile": "https://Stackoverflow.com/users/9628", "pm_score": 2, "selected": false, "text": "<p>It turns out the compiler version I was using did not match the compiled version done with the coreset.o. </p>\n\n<p>One was 32bit the other was 64bit. I'll leave this up in case anyone else runs into a similar problem.</p>\n" }, { "answer_id": 216010, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 6, "selected": true, "text": "<p>I think that coreset.o was compiled for 64-bit, and you are linking it with a 32-bit computation.o.</p>\n\n<p>You can try to recompile computation.c with the '-m64' flag of <a href=\"http://www.manpagez.com/man/1/gcc-3.3/\" rel=\"noreferrer\">gcc(1)</a></p>\n" }, { "answer_id": 216011, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 2, "selected": false, "text": "<p>It looks like the object file was compiled on a 64-bit toolchain, and you're using a 32-bit toolchain. Have you tried recompiling the object file in 32-bit mode?</p>\n" }, { "answer_id": 216090, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 3, "selected": false, "text": "<p>You can specify '-m32' or '-m64' to select the compilation mode.</p>\n\n<p>When dealing with autoconf (configure) scripts, I usually set CC=\"gcc -m64\" (or CC=\"gcc -m32\") in the environment so that everything is compiled with the correct bittiness. At least, usually...people find endless ways to make that not quite work, but my batting average is very high (way over 95%) with it.</p>\n" }, { "answer_id": 8795449, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<pre><code>sudo apt-get install ia32-libs \n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216000", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9628/" ]
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? ``` 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 ```
I think that coreset.o was compiled for 64-bit, and you are linking it with a 32-bit computation.o. You can try to recompile computation.c with the '-m64' flag of [gcc(1)](http://www.manpagez.com/man/1/gcc-3.3/)
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": "<p>This shows the number of connections per each DB:</p>\n\n<pre><code>SELECT \n DB_NAME(dbid) as DBName, \n COUNT(dbid) as NumberOfConnections,\n loginame as LoginName\nFROM\n sys.sysprocesses\nWHERE \n dbid &gt; 0\nGROUP BY \n dbid, loginame\n</code></pre>\n\n<p>And this gives the total:</p>\n\n<pre><code>SELECT \n COUNT(dbid) as TotalConnections\nFROM\n sys.sysprocesses\nWHERE \n dbid &gt; 0\n</code></pre>\n\n<p>If you need more detail, run:</p>\n\n<pre><code>sp_who2 'Active'\n</code></pre>\n\n<p><strong>Note:</strong> The SQL Server account used needs the 'sysadmin' role (otherwise it will just show a single row and a count of 1 as the result)</p>\n" }, { "answer_id": 216122, "author": "jwalkerjr", "author_id": 689, "author_profile": "https://Stackoverflow.com/users/689", "pm_score": 1, "selected": false, "text": "<p>If your PHP app is holding open many SQL Server connections, then, as you may know, you have a problem with your app's database code. It should be releasing/disposing those connections after use and using connection pooling. Have a look here for a decent article on the topic...</p>\n\n<p><a href=\"http://www.c-sharpcorner.com/UploadFile/dsdaf/ConnPooling07262006093645AM/ConnPooling.aspx\" rel=\"nofollow noreferrer\">http://www.c-sharpcorner.com/UploadFile/dsdaf/ConnPooling07262006093645AM/ConnPooling.aspx</a></p>\n" }, { "answer_id": 216268, "author": "Mitch Wheat", "author_id": 16076, "author_profile": "https://Stackoverflow.com/users/16076", "pm_score": 3, "selected": false, "text": "<p>As @jwalkerjr mentioned, you should be disposing of connections in code (if connection pooling is enabled, they are just returned to the connection pool). The prescribed way to do this is using the '<code>using</code>' statement:</p>\n\n\n\n<pre class=\"lang-c# prettyprint-override\"><code>// 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</code></pre>\n" }, { "answer_id": 20545488, "author": "Mina Gabriel", "author_id": 1410185, "author_profile": "https://Stackoverflow.com/users/1410185", "pm_score": 0, "selected": false, "text": "<p>see <a href=\"http://msdn.microsoft.com/en-us/library/ms174313.aspx\" rel=\"nofollow\">sp_who</a> it gives you more details than just seeing the number of connections </p>\n\n<p>in your case i would do something like this </p>\n\n<pre><code> 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</code></pre>\n" }, { "answer_id": 38260330, "author": "Tarun Harkinia", "author_id": 1778982, "author_profile": "https://Stackoverflow.com/users/1778982", "pm_score": 0, "selected": false, "text": "<p><strong>MS SQL knowledge based - How to know open SQL database connection(s) and occupied on which host.</strong></p>\n\n<p>Using below query you will find list database, Host name and total number of open connection count, based on that you will have idea, which host has occupied SQL connection. </p>\n\n<pre><code>SELECT DB_NAME(dbid) as DBName, hostname ,COUNT(dbid) as NumberOfConnections\nFROM sys.sysprocesses with (nolock) \nWHERE dbid &gt; 0 \nand len(hostname) &gt; 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</code></pre>\n" }, { "answer_id": 40597699, "author": "sqldba.today", "author_id": 7158880, "author_profile": "https://Stackoverflow.com/users/7158880", "pm_score": 2, "selected": false, "text": "<p>I know this is old, but thought it would be a good idea to update. If an accurate count is needed, then column ECID should probably be filtered as well. A SPID with parallel threads can show up multiple times in sysprocesses and filtering ECID=0 will return the primary thread for each SPID.</p>\n\n<pre><code>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 &gt; 0\n and ecid=0\nGROUP BY \n dbid, loginame\n</code></pre>\n" }, { "answer_id": 41815139, "author": "realstrategos", "author_id": 3246002, "author_profile": "https://Stackoverflow.com/users/3246002", "pm_score": 3, "selected": false, "text": "<p>Use this to get an accurate count for each connection pool (assuming each user/host process uses the same connection string)</p>\n\n<pre><code>SELECT \nDB_NAME(dbid) as DBName, \nCOUNT(dbid) as NumberOfConnections,\nloginame as LoginName, hostname, hostprocess\nFROM\nsys.sysprocesses with (nolock)\nWHERE \ndbid &gt; 0\nGROUP BY \ndbid, loginame, hostname, hostprocess\n</code></pre>\n" }, { "answer_id": 59692933, "author": "FatemehEbrahimiNik", "author_id": 5305781, "author_profile": "https://Stackoverflow.com/users/5305781", "pm_score": 0, "selected": false, "text": "<pre><code>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</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216007", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
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
This shows the number of connections per each DB: ``` SELECT DB_NAME(dbid) as DBName, COUNT(dbid) as NumberOfConnections, loginame as LoginName FROM sys.sysprocesses WHERE dbid > 0 GROUP BY dbid, loginame ``` And this gives the total: ``` SELECT COUNT(dbid) as TotalConnections FROM sys.sysprocesses WHERE dbid > 0 ``` If you need more detail, run: ``` sp_who2 'Active' ``` **Note:** The SQL Server account used needs the 'sysadmin' role (otherwise it will just show a single row and a count of 1 as the result)
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": 216022, "author": "Daniel Plaisted", "author_id": 1509, "author_profile": "https://Stackoverflow.com/users/1509", "pm_score": 1, "selected": false, "text": "<p>It is possible that since you don't have any methods that override the virtual method that the JIT is able to recognize this and use a direct call instead.</p>\n\n<p>For something like this it's generally better to test it out as you have done than try to guess what the performance will be. If you want to know more about how delegate invocation works, I suggest the excellent book \"CLR Via C#\" by Jeffrey Richter.</p>\n" }, { "answer_id": 216051, "author": "Yes Fish...", "author_id": 29343, "author_profile": "https://Stackoverflow.com/users/29343", "pm_score": 0, "selected": false, "text": "<p>virtual overrides have some sort of redirection table or something which is hardcoded and fully optimized at compile time. It's set in stone, very fast.</p>\n\n<p>Delegates are dynamic which will always have an overhead and they seem to be objects too so that adds up.</p>\n\n<p>You shouldn't worry about these small performance differences (unless developing performance critical software for the military), for most purposes good code structure wins over optimization.</p>\n" }, { "answer_id": 216053, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "<p>I doubt it accounts for all of your difference, but one thing off the top of my head that may account for some of the difference is that virtual method dispatch already has the <code>this</code> pointer ready to go. When calling through a delegate the <code>this</code> pointer has to be fetched from the delegate.</p>\n\n<p>Note that according to <a href=\"http://www.sturmnet.org/blog/archives/2005/09/01/\" rel=\"nofollow noreferrer\">this blog article</a> the difference was even greater in .NET v1.x.</p>\n" }, { "answer_id": 216081, "author": "Franci Penov", "author_id": 17028, "author_profile": "https://Stackoverflow.com/users/17028", "pm_score": 3, "selected": false, "text": "<p>A virtual call is dereferencing two pointers at a well-known offset in the memory. It's not actually dynamic binding; there is no code at runtime to reflect over the metadata to discover the right method. The compiler generates couple of instructions to do the call, based on the this pointer. in fact, the virtual call is a single IL instruction.</p>\n\n<p>A predicate call is creating an anonymous class to encapsulate the predicate. That class has to be instantiated and there is some code generated to actually check whether the predicate function pointer is null or not.</p>\n\n<p>I would suggest you look at the IL constructs for both. Compile a simplified version of your source above with a single call to each of the two DoSomthing. Then use ILDASM to see what is the actual code for each pattern.</p>\n\n<p>(And I am sure I'll get downvoted for not using the right terminology :-))</p>\n" }, { "answer_id": 216118, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "<p>Think about what's required in each case:</p>\n\n<p><strong>Virtual call</strong><br/></p>\n\n<ul>\n<li>Check for nullity</li>\n<li>Navigate from object pointer to type pointer</li>\n<li>Look up method address in instruction table</li>\n<li>(Not sure - even Richter doesn't cover this) Go to base type if method isn't overridden? Recurse until we find the right method address. (I don't think so - see edit at bottom.)</li>\n<li>Push original object pointer onto stack (\"this\")</li>\n<li>Call method</li>\n</ul>\n\n<p><strong>Delegate call</strong><br /></p>\n\n<ul>\n<li>Check for nullity</li>\n<li>Navigate from object pointer to array of invocations (all delegates are potentially multicast)</li>\n<li>Loop over array, and for each invocation:\n\n<ul>\n<li>Fetch method address</li>\n<li>Work out whether or not to pass the target as first argument</li>\n<li>Push arguments onto stack (may have been done already - not sure)</li>\n<li>Optionally (depending on whether the invocation is open or closed) push the invocation target onto the stack</li>\n<li>Call method</li>\n</ul></li>\n</ul>\n\n<p>There may be some optimisation so that there's no looping involved in the single-call case, but even so that will take a very quick check.</p>\n\n<p>But basically there's just as much indirection involved with a delegate. Given the bit I'm unsure of in the virtual method call, it's possible that a call to an unoverridden virtual method in a massively deep type hierarchy would be slower... I'll give it a try and edit with the answer.</p>\n\n<p>EDIT: I've tried playing around with both the depth of inheritance hierarchy (up to 20 levels), the point of \"most derived overriding\" and the declared variable type - and none of them seems to make a difference.</p>\n\n<p>EDIT: I've just tried the original program using an interface (which is passed in) - that ends up having about the same performance as the delegate.</p>\n" }, { "answer_id": 518663, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "<p>Just wanted to add a few corrections to john skeet's response:</p>\n\n<p>A virtual method call does not need to do a null check (automatically handled with hardware traps).</p>\n\n<p>It also does not need to walk up inheritance chain to find non-overriden methods (that's what the virtual method table is for).</p>\n\n<p>A virtual method call is essentially one extra level of indirection when invoking. It is slower than a normal call because of the table look-up and subsequent function pointer call.</p>\n\n<p>A delegate call also involves an extra level of indirection.</p>\n\n<p>Calls to a delegate do not involve putting arguments in an array unless you are performing a dynamic invoke using the DynamicInvoke method.</p>\n\n<p>A delegate call involves the calling method calling a compiler generated Invoke method on the delegate type in question. A call to predicator(value) is turned into predicator.Invoke(value).</p>\n\n<p>The Invoke method in turn is implemented by the JIT to call the function pointer(s) (stored internally in the delegate object).</p>\n\n<p>In your example, the delegate you passed should have been implemented as a compiler generated static method as the implementation does not access any instance variables or locals so therefore the need to access the \"this\" pointer from the heap should not be an issue.</p>\n\n<p>The performance difference between delegate and virtual function calls should be mostly the same and your performance tests show that they are very close.</p>\n\n<p>The difference could be due to the need to additional checks+branches because of multicast (as suggested by John). Another reason could be that the JIT compiler does not inline the Delegate.Invoke method and the implementation of Delegate.Invoke does not handle arguments as well as the implementation when performming virtual method calls. </p>\n" }, { "answer_id": 1046955, "author": "Kenneth Xu", "author_id": 111877, "author_profile": "https://Stackoverflow.com/users/111877", "pm_score": 2, "selected": false, "text": "<p>Test result worth 1000 of words: <a href=\"http://kennethxu.blogspot.com/2009/05/strong-typed-high-performance_15.html\" rel=\"nofollow noreferrer\">http://kennethxu.blogspot.com/2009/05/strong-typed-high-performance_15.html</a></p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216008", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26349/" ]
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. Originally, I thought the second "delegate" way would be faster than "virtual" way, but some coding snippet proves it is not correct. 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. "Virtual invocation" is dynamic binding and should be more time-costing than direct delegation invocation, right? but the result shows it is not. Anybody can explain this? ``` 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 < repeat; ++i) { if (IsTokenChar(word)) { ++trueCount; } } return trueCount; } public int DoSomething(Predicate<string> predicator, string word) { int trueCount = 0; for (int i = 0; i < 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 => String.IsNullOrEmpty(str), null); sw.Stop(); Console.WriteLine(sw.ElapsedMilliseconds); } } } ```
Think about what's required in each case: **Virtual call** * Check for nullity * Navigate from object pointer to type pointer * Look up method address in instruction table * (Not sure - even Richter doesn't cover this) Go to base type if method isn't overridden? Recurse until we find the right method address. (I don't think so - see edit at bottom.) * Push original object pointer onto stack ("this") * Call method **Delegate call** * Check for nullity * Navigate from object pointer to array of invocations (all delegates are potentially multicast) * Loop over array, and for each invocation: + Fetch method address + Work out whether or not to pass the target as first argument + Push arguments onto stack (may have been done already - not sure) + Optionally (depending on whether the invocation is open or closed) push the invocation target onto the stack + Call method There may be some optimisation so that there's no looping involved in the single-call case, but even so that will take a very quick check. But basically there's just as much indirection involved with a delegate. Given the bit I'm unsure of in the virtual method call, it's possible that a call to an unoverridden virtual method in a massively deep type hierarchy would be slower... I'll give it a try and edit with the answer. EDIT: I've tried playing around with both the depth of inheritance hierarchy (up to 20 levels), the point of "most derived overriding" and the declared variable type - and none of them seems to make a difference. EDIT: I've just tried the original program using an interface (which is passed in) - that ends up having about the same performance as the delegate.
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": 216059, "author": "Jeremy Cantrell", "author_id": 18866, "author_profile": "https://Stackoverflow.com/users/18866", "pm_score": 2, "selected": false, "text": "<p>The file will not be visible from apache. Obviously the best option is to put it outside of your site's root. If you can't do that, .htaccess files (or similar directives in your apache configs) is pretty much your only option.</p>\n" }, { "answer_id": 216144, "author": "Bob Fanger", "author_id": 19165, "author_profile": "https://Stackoverflow.com/users/19165", "pm_score": 4, "selected": true, "text": "<p>The .htaccess will block access from the web. However, if you're using a shared hosting environment, it might be possible for other users to access your ini. If its on a (virtual private) server and you're the only user for that server you're safe.</p>\n\n<p>In case of shared hosting it depends on server configuration.\nFor more info read: <a href=\"http://www.hostreview.com/guides/Technical_Support/articles/PHPSecurityinSharedEnvironment.html\" rel=\"noreferrer\">PHP Security in a shared hosting environment</a></p>\n\n<p>You can temporarily install <a href=\"http://phpshell.sourceforge.net/\" rel=\"noreferrer\">PHPShell</a> and browse through the server filesystem to check if your server is vulnerable. (requires some commandline knowledge)</p>\n" }, { "answer_id": 20445807, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>Another good solution and my personal favourite (especially when developing code that might not remain under my stringent .htaccess control) is securing the actual .ini file. Thanks to a kind soul <a href=\"http://php.net/manual/en/function.parse-ini-file.php\" rel=\"nofollow noreferrer\">here - user notes: pd at frozen-bits dot de</a>, what I do is:</p>\n<pre><code>my.ini -&gt; changes to my.ini.php\n</code></pre>\n<p>my.ini.php starts off:</p>\n<pre><code>;&lt;?php\n;die(); // For further security\n;/*\n [category]\n name=&quot;value&quot;\n\n;*/\n</code></pre>\n<p>Works perfectly! Access the file directly and all you see is ';' <em><strong>and</strong></em> it is a valid, parseable .ini file. What's not to like :)</p>\n<p>A few notes on actual implementation (apologies if this counts as &quot;overshare&quot; but maybe save someone some time):</p>\n<ol>\n<li>This file makes my IDE very Upset and it keeps trying to auto-reformat which then makes PHP Upset. Blessings be on Notepad++.</li>\n<li>Don't forget the closing <code>;*/</code>. It still works if you leave it out but PHP warns you that it is about to become Upset.</li>\n</ol>\n<p>Sorted.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216019", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3740/" ]
I have a .ini file with sensitive information in my php wab app. I denied access to it using a .htaccess file: ``` <files my.ini> order deny,allow deny from all </files> ``` I don't have access to folders outside of htdocs, so I can't move the .ini file out of browsable territory. Is my solution safe?
The .htaccess will block access from the web. However, if you're using a shared hosting environment, it might be possible for other users to access your ini. If its on a (virtual private) server and you're the only user for that server you're safe. In case of shared hosting it depends on server configuration. For more info read: [PHP Security in a shared hosting environment](http://www.hostreview.com/guides/Technical_Support/articles/PHPSecurityinSharedEnvironment.html) You can temporarily install [PHPShell](http://phpshell.sourceforge.net/) and browse through the server filesystem to check if your server is vulnerable. (requires some commandline knowledge)
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": "<p>You could also do:</p>\n\n<pre><code>$end = end(array_keys($array));\n</code></pre>\n\n<p>But I think your way makes it clear what you want to do, so you could whip something up like:</p>\n\n<pre><code>function array_last_key($array) {\n end($array);\n return key($array);\n}\n</code></pre>\n\n<p>That's about it.</p>\n" }, { "answer_id": 216040, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 0, "selected": false, "text": "<p>There is no special function for this in PHP, so I think your way is the most efficent way of doing this. For readability you might want to put it in a function called something like array_last_key().</p>\n" }, { "answer_id": 216096, "author": "Keith Twombley", "author_id": 23866, "author_profile": "https://Stackoverflow.com/users/23866", "pm_score": 0, "selected": false, "text": "<p>If you can guarantee that your array won't have any non-numerical keys and that you aren't going to be deleting any keys, then the last element added to your array's key will be</p>\n\n<pre><code>$last_added = count($array)-1;\n</code></pre>\n\n<p>If you really need to keep track of the latest added key, you may want to come up with a scheme to come up with your own keys that are guaranteed to be unique. this way you'll always have the latest added key since you generated it.</p>\n\n<pre><code>$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</code></pre>\n" }, { "answer_id": 219330, "author": "gradbot", "author_id": 17919, "author_profile": "https://Stackoverflow.com/users/17919", "pm_score": 0, "selected": false, "text": "<p>Simply put no. Both end and key are Big O(1) time. Any other way slows your code down and adds complexity.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216030", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5441/" ]
Is there a better way to do the following: ``` $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 ``` This will give the key of the most recently add array element. Is there a better way to do this?
You could also do: ``` $end = end(array_keys($array)); ``` But I think your way makes it clear what you want to do, so you could whip something up like: ``` function array_last_key($array) { end($array); return key($array); } ``` That's about it.
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": "<p>Use the <a href=\"http://svnbook.red-bean.com/en/1.0/re26.html\" rel=\"noreferrer\"><code>svn status</code></a> command:</p>\n\n<pre><code>svn status | grep ^?\n</code></pre>\n\n<p>Files that are not versioned are indicated with a ? at the start of the line.</p>\n\n<p>If you find that you always have some specific files that should not be added to the repository (for example, generated binaries), you should set up the <a href=\"http://svnbook.red-bean.com/en/1.1/ch07s02.html\" rel=\"noreferrer\"><code>svn:ignore</code></a> property on the containing directory so these files won't keep showing up when using <code>svn status</code>.</p>\n" }, { "answer_id": 1082146, "author": "Damian Powell", "author_id": 30321, "author_profile": "https://Stackoverflow.com/users/30321", "pm_score": 4, "selected": false, "text": "<p>If you're running on Windows, you could do something similar to <a href=\"https://stackoverflow.com/users/893/greg-hewgill\">Greg Hewgill</a>'s answer using PowerShell.</p>\n\n<pre><code>(svn stat) -match '^\\?'\n</code></pre>\n\n<p>This could be extended pretty easily to find all unversioned and ignored files and delete them.</p>\n\n<pre><code>(svn stat \"--no-ignore\") -match '^[I?]' -replace '^.\\s+','' | rm\n</code></pre>\n\n<p>Hope that's helpful to someone!</p>\n" }, { "answer_id": 7231214, "author": "bleater", "author_id": 316487, "author_profile": "https://Stackoverflow.com/users/316487", "pm_score": 6, "selected": false, "text": "<p>If some files have had <a href=\"http://svnbook.red-bean.com/en/1.0/ch07s02.html#svn-ch-7-sect-2.3.3\" rel=\"noreferrer\"><code>ignore</code></a> added to their status, they won't show up in <code>svn status</code>. You'll need:</p>\n\n<pre><code>svn status --no-ignore\n</code></pre>\n" }, { "answer_id": 13569623, "author": "crig", "author_id": 1131057, "author_profile": "https://Stackoverflow.com/users/1131057", "pm_score": 4, "selected": false, "text": "<p>Or from the Windows command line:</p>\n\n<pre><code>svn stat | find \"?\"\n</code></pre>\n" }, { "answer_id": 32780710, "author": "user2710797", "author_id": 2710797, "author_profile": "https://Stackoverflow.com/users/2710797", "pm_score": 1, "selected": false, "text": "<p>You can use this command to list all paths for not-versioned files:</p>\n\n<pre><code>svn status | awk '/^?/ {print $2}'\n</code></pre>\n\n<p>The first part will do an <code>svn status</code>, and then it will redirect the output to <a href=\"http://en.wikipedia.org/wiki/AWK\" rel=\"nofollow noreferrer\">AWK</a> which will do simple filter \"first character should be '?'\" then it will print the second parameter \"which is the file path\".</p>\n\n<p><code>svn status</code> will always <em>not</em> print ignored files. You can add a file or path by adding that path using</p>\n\n<pre><code>svn propset svn:ignore \"PATH OR PATERN\"\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216049", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8123/" ]
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! 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?
Use the [`svn status`](http://svnbook.red-bean.com/en/1.0/re26.html) command: ``` svn status | grep ^? ``` Files that are not versioned are indicated with a ? at the start of the line. If you find that you always have some specific files that should not be added to the repository (for example, generated binaries), you should set up the [`svn:ignore`](http://svnbook.red-bean.com/en/1.1/ch07s02.html) property on the containing directory so these files won't keep showing up when using `svn status`.
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": "<p>If the only thing in there is whitespace and integers, just try something like this:</p>\n\n<pre><code>int i1, i2;\nstringstream ss(lineFromGetLine);\nss &gt;&gt; i1 &gt;&gt; i2;\n</code></pre>\n\n<p>or easier:</p>\n\n<pre><code>int i1, i2;\ntheFileStream &gt;&gt; i1 &gt;&gt; i2;\n</code></pre>\n" }, { "answer_id": 216087, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "<p>It's more than a little bit C-ish, but you could use sscanf() on the C string representation. Or you could use strtol() or relatives - also on the C string representation.</p>\n\n<p>A more C++-ish way would probably use a string stream and an extractor.</p>\n" }, { "answer_id": 216097, "author": "Tomek", "author_id": 29326, "author_profile": "https://Stackoverflow.com/users/29326", "pm_score": 0, "selected": false, "text": "<p>I tried:</p>\n\n<pre><code>while (!inFile.eof()) {\n getline (inFile,inputLine);\n stringstream ss(inputLine);\n ss &gt;&gt; rows &gt;&gt; columns;\n}\n</code></pre>\n\n<p>and I got the following error:</p>\n\n<p>\"term does not evaluate to a function taking 1 arguments\" at line</p>\n\n<p>ss(inputLine);</p>\n\n<p>edit: so you have to declare the string stream at the moment you give it the paramater. Correctoed code edited above.</p>\n" }, { "answer_id": 216770, "author": "Martin York", "author_id": 14065, "author_profile": "https://Stackoverflow.com/users/14065", "pm_score": 3, "selected": false, "text": "<p>There are a couple of things to consider:<br/>\nLets assume you have two numbers on each line followed by text you don't care about.</p>\n\n<pre><code>while(inFile &gt;&gt; rows &gt;&gt; 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&lt;std::streamsize&gt;::max(), '\\n' );\n}\n</code></pre>\n\n<p>Also note if the only thing separating the integer values is \"white space\" then you don't even need to use the ignore() line.</p>\n\n<p>The above while() works because: The operator >> returns a stream object (reference). Because the stream object is being used in a boolean context the compiler will try and convert it into a bool and the stream object has a cast operator that does that conversion (by calling good() on the stream).</p>\n\n<p>The important thing to note is <b>NOT</b> to use the line</p>\n\n<pre><code>while(inFile.eof())\n</code></pre>\n\n<p>If you do use this then you fall into the trap of the last line problem. If you have read all the data eof() is still false (as it is not true until you try and read past EOF). So there is no data left in the file but you still enter the loop body. In your code the getline() is then executed and fails (no more data), EOF is now set. What the rest of the loop does will depend on how and where inLine is defined.</p>\n\n<p>You can use this test as above. But you must also be willing to test the stream is OK after you have used it.</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 1958370, "author": "Tronic", "author_id": 238233, "author_profile": "https://Stackoverflow.com/users/238233", "pm_score": 0, "selected": false, "text": "<p>Never use .eof() for testing whether you can read nor for testing whether the previous read failed. Both approaches will fail in certain situations because:</p>\n\n<ul>\n<li>EOF is not set even when there are no characters left, if no read past the end has been attempted yet (e.g. after a getline of the last line, if there was a newline character at the end)</li>\n<li>EOF is set even after a successful read if the read operation had to peek for the next character after the end to determine that it should stop reading (e.g. after a geline of the last line, if there was no newline character at the end)</li>\n</ul>\n\n<p>In general you should ONLY use .eof() after a failed read to check if the failure was caused by end of input.</p>\n\n<p>Use <code>while (std::getline(...))</code> for looping over lines.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216068", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29326/" ]
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. 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.
If the only thing in there is whitespace and integers, just try something like this: ``` int i1, i2; stringstream ss(lineFromGetLine); ss >> i1 >> i2; ``` or easier: ``` int i1, i2; theFileStream >> i1 >> i2; ```
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": "<p>These are the kind of situations where Firebug and Firefox are really helpful. I suggest you install Firebug if you don't have it and check the request that is being sent.</p>\n\n<p>You also definitely need to stick to <code>parameters</code> instead of <code>requestBody</code>.</p>\n\n<p>This:</p>\n\n<pre><code>new Ajax.Request(sURL,\n{\n method: 'POST',\n parameters: 'hello=world&amp;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</code></pre>\n\n<p>Should definitely work.</p>\n" }, { "answer_id": 217730, "author": "aemkei", "author_id": 28150, "author_profile": "https://Stackoverflow.com/users/28150", "pm_score": 1, "selected": false, "text": "<p>Simply pass the data as <strong><code>parameters</code></strong> to the Ajax Request constructor:</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 11447751, "author": "Grzegorz Gierlik", "author_id": 1483, "author_profile": "https://Stackoverflow.com/users/1483", "pm_score": 0, "selected": false, "text": "<p>When I hit this problem the solution was to remove <code>contentType</code> from <code>Ajax.Request</code> options. </p>\n\n<p>In <a href=\"https://stackoverflow.com/a/216074/1483\">answer</a> by <a href=\"https://stackoverflow.com/users/16417/paolo-bergantino\">Paolo Bergantino</a> <code>contentType</code> is not defined in <code>Ajax.Request</code> options.</p>\n\n<p>From unknown reasons params defined in <code>parameters</code> wasn't sent (FF didn't show them and my server saw empty POST body).</p>\n\n<p>One of my coworkers suggested to use <code>postBody</code> instead of <code>parameters</code> but I didn't try it.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4962/" ]
I'm trying to create a POST request, unfortunately the body of the POST never seems to be sent. 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. I can validate that the request body is never sent since I have access to the servlet being called. 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. Any ideas? ``` 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 ```
These are the kind of situations where Firebug and Firefox are really helpful. I suggest you install Firebug if you don't have it and check the request that is being sent. You also definitely need to stick to `parameters` instead of `requestBody`. This: ``` new Ajax.Request(sURL, { method: 'POST', parameters: 'hello=world&test=yes', onFailure: function(transport) { vJSONResp = transport.responseText; var JSON = eval( "(" + vJSONResp + ")" ); updateStatus(JSON.code + ": " + JSON.message); }, onSuccess: function(transport) { if (200 == transport.status) { vJSONResp = transport.responseText; } else { log.value += "\n" + transport.status; } } }); ``` Should definitely work.
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": "<p>I'm not sure it's possible to do this; you'll start running into divide-by-zero issues. If you try to do this, you'll be creating a transform that looks like:</p>\n\n<p><code><pre>\n 0 0 0\n 0 0 0\n 0 0 1\n</pre></code></p>\n\n<p>Which, when applied to ANY other transform, will produce the above transform. </p>\n\n<p>Why not just hide the view (if you want to scale it out of sight) or set the scaling factor to something like 0.001 (if you want to scale it in)?</p>\n" }, { "answer_id": 216396, "author": "Jason Harris", "author_id": 1345109, "author_profile": "https://Stackoverflow.com/users/1345109", "pm_score": 4, "selected": true, "text": "<p>There are lots of times when the underlying frameworks need to invert your transform matrix. The inverse of a matrix is some matrix M' such that the product of your matrix M and the inverse matrix M' is the identify matrix 1.</p>\n\n<p>1 = M * M'</p>\n\n<p>The zero matrix does not have an inverse, hence the error message.</p>\n" }, { "answer_id": 7869373, "author": "Mike Smith", "author_id": 1009954, "author_profile": "https://Stackoverflow.com/users/1009954", "pm_score": 1, "selected": false, "text": "<p>you could try:</p>\n\n<pre><code>CGAffineTransform transform = myView.transform;\nmyView.transform = CGAffineTransformScale(transform. 0.0f, 0.0f);\n</code></pre>\n\n<p>or inline the whole thing.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216076", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1987/" ]
Is it possible to scale a UIView down to 0 (width and height is 0) using CGAffineTransformMakeScale? view.transform = CGAffineTransformMakeScale(0.0f, 0.0f); Why would this throw an error of "`<Error>: CGAffineTransformInvert: singular matrix.`" ? *Update: There is another way of scaling down a UIView to 0* ``` [UIView beginAnimations:nil context:nil]; [UIView setAnimationDuration:0.3]; view.frame = CGRectMake(view.center.x, view.center.y, 0, 0); [UIView commitAnimations]; ```
There are lots of times when the underlying frameworks need to invert your transform matrix. The inverse of a matrix is some matrix M' such that the product of your matrix M and the inverse matrix M' is the identify matrix 1. 1 = M \* M' The zero matrix does not have an inverse, hence the error message.
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": 216098, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "<p>This has likely nothing to do with PyGTK, but rather a general code organization issue. You would probably benefit from applying some MVC (Model-View-Controller) design patterns. See <a href=\"http://en.wikipedia.org/wiki/Design_Patterns\" rel=\"nofollow noreferrer\">Design Patterns</a>, for example.</p>\n" }, { "answer_id": 216113, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 0, "selected": false, "text": "<p>Python 2.6 supports <a href=\"http://docs.python.org/whatsnew/2.6.html#pep-366-explicit-relative-imports-from-a-main-module\" rel=\"nofollow noreferrer\">explicit relative imports</a>, which make using packages even easier than previous versions.\nI suggest you look into breaking your app into smaller modules inside a package.\nYou can organize your application like this:</p>\n\n<pre><code>myapp/\n application/\n gui/\n command/\n state/\n</code></pre>\n\n<p>Where each directory has its own <code>__init__.py</code>. You can have a look at any python app or even standard library modules for examples.</p>\n" }, { "answer_id": 216145, "author": "Jaime Soriano", "author_id": 28855, "author_profile": "https://Stackoverflow.com/users/28855", "pm_score": 4, "selected": true, "text": "<p>In the project <a href=\"http://wader-project.org\" rel=\"noreferrer\">Wader</a> we use <a href=\"http://pygtkmvc.sourceforge.net/\" rel=\"noreferrer\">python gtkmvc</a>, that makes much easier to apply the MVC patterns when using pygtk and glade, you can see the file organization of our project in the <a href=\"http://trac.wader-project.org/browser/trunk/wader\" rel=\"noreferrer\">svn repository</a>:</p>\n\n<pre><code>wader/\n cli/\n common/\n contrib/\n gtk/\n controllers/\n models/\n views/\n test/\n utils/\n</code></pre>\n" }, { "answer_id": 216386, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 2, "selected": false, "text": "<p>&quot;holds the primary application class (most functional routines)&quot;</p>\n<p>As in singular -- one class?</p>\n<p>I'm not surprised that the <strong>One Class Does Everything</strong> design isn't working. It might not be what I'd call object-oriented. It doesn't sound like it follows the typical MVC design pattern if your functionality is piling up in a single class.</p>\n<p>What's in this massive class? I suggest that you can probably refactor this into pieces. You have two candidate dimensions for refactoring your application class -- if, indeed, I've guessed right that you've put everything into a single class.</p>\n<ol>\n<li><p>Before doing anything else, refactor into components that parallel the Real World Entities. It's not clear what's in your &quot;state.py&quot; -- wether this is a proper model of real-world entities, or just mappings between persistent storage and some murky data structure in the application. Most likely you'd move processing out of your application and into your model (possibly state.py, possibly a new module that is a proper model.)</p>\n<p>Break your model into pieces. It will help organize the control and view elements. The most common MVC mistake is to put too much in control and nothing in the model.</p>\n</li>\n<li><p>Later, once your model is doing most of the work, you can look at refactor into components that parallel the GUI presentation. Various top-level frames, for example, should probably have separate cotrol objects. It's not clear what's in &quot;GUI.py&quot; -- this might be a proper view. What appears to be missing is a Control component.</p>\n</li>\n</ol>\n" }, { "answer_id": 219737, "author": "bouvard", "author_id": 24608, "author_profile": "https://Stackoverflow.com/users/24608", "pm_score": 0, "selected": false, "text": "<p>So having not heard back regarding my edit to the original question, I have done some more research and the conclusion I seem to be coming to is that <em>yes</em>, I should break the interface out into several views, each with its own controller. Python-gtkmvc provides the ability to this by providing a <code>glade_top_widget_name</code> parameter to the View constructor. This all seems to make a good deal of sense although it is going to require a large refactoring of my existing codebase which I may or may not be willing to undertake in the near-term (I know, I know, I <em>should</em>.) Moreover, I'm left to wonder whether should just have a single Model object (my application is fairly simple--no more than twenty-five state vars) or if I should break it out into multiple models and have to deal with controllers observing multiple models and chaining notifications across them. (Again, I know I really <em>should</em> do the latter.) If anyone has any further insight, I still don't really feel like I've gotten an answer to the original question, although I have a direction to head in now.</p>\n\n<p>(Moreover it seems like their ought to be other architectural choices at hand, given that up until now I had not seen a single Python application coded in the MVC style, but then again many Python applications tend to have the exact problem I've described above.)</p>\n" }, { "answer_id": 252361, "author": "Ali Afshar", "author_id": 28380, "author_profile": "https://Stackoverflow.com/users/28380", "pm_score": 2, "selected": false, "text": "<p>Sorry to answer so late. <a href=\"http://async.com.br/projects/kiwi\" rel=\"nofollow noreferrer\">Kiwi</a> seems to me a far better solution than gtkmvc. It is my first dependency for any pygtk project.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24608/" ]
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: * application.py - holds the primary application class (most functional routines) * gui.py - holds a loosely coupled GTK gui implementation. Handles signal callbacks, etc. * command.py - holds command line automation functions not dependent on data in the application class * state.py - holds the state data persistence class 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. 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. 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? **EDIT I** 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. 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. Thanks for the responses so far.
In the project [Wader](http://wader-project.org) we use [python gtkmvc](http://pygtkmvc.sourceforge.net/), that makes much easier to apply the MVC patterns when using pygtk and glade, you can see the file organization of our project in the [svn repository](http://trac.wader-project.org/browser/trunk/wader): ``` wader/ cli/ common/ contrib/ gtk/ controllers/ models/ views/ test/ utils/ ```
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": 216099, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>It depends on the situation. Is the box of chocolates going t0 contain multiple collections? If so you need to have the collections be members.</p>\n\n<p>Think of it this way. Is a box of chocolates a collection (i.e. PersonList) or something that owns a collection (i.e. a car may own a collection of it's last owners).</p>\n\n<p>I think this falls under the first group</p>\n\n<p>:)</p>\n" }, { "answer_id": 216107, "author": "Owen", "author_id": 4853, "author_profile": "https://Stackoverflow.com/users/4853", "pm_score": 1, "selected": false, "text": "<p>i'd suggest the first group too, assuming your chocolate metaphor is pretty accurate to the actual class.</p>\n\n<p>a box of chocolates really is your collection of chocolates, and as such it makes sense to want to iterate over the chocolates within that box. adding a separate chocolate list doesn't really add any value, and just seems to add an unnecessary layer.</p>\n" }, { "answer_id": 216303, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "<p>Well, I don't know PHP, so I can't properly answer the question, but I'll try relating it to an area that I do know.</p>\n\n<p>In C#, there are two interfaces: IEnumerable and IEnumerator. In your example, BoxOfChocolates would be Enumerable, Chocolates would be an Enumerator.</p>\n\n<p>Enumerables merely have a method which returns an Enumerator. Enumerators have a concept of a current item, and a means of moving to the next item. In most cases, the Enumerator class isn't \"seen\". For example, in the line \"foreach(Chocolate item in boxOfChoclates)\" boxOfChocolates is a Enumerable; the Enumerator object is completely hidden by the foreach.</p>\n" }, { "answer_id": 216326, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 0, "selected": false, "text": "<p>Quite simply the container is the place to implement the iterator.</p>\n" }, { "answer_id": 216344, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 0, "selected": false, "text": "<p>I think you should keep your collections separate from your iterators. I would agree with @James Curran that collections often have iterators -- in fact, they could have several. For instance, you may want an iterator that skips candy with nuts (though the typical case is to want one that reverses the ordering). In this case the meaning of the next() method changes. To handle that, implement iterators in separate classes that contain their own iteration semantics. Provide methods in the collection to obtain iterators of the proper sort. It's really an issue of separation of concerns. The collection doesn't care how the user iterates over it, that is the iterator's concern.</p>\n" }, { "answer_id": 217090, "author": "Michał Niedźwiedzki", "author_id": 2169, "author_profile": "https://Stackoverflow.com/users/2169", "pm_score": 2, "selected": false, "text": "<p>bbxbby, the best solution is usually the simplest one. You are definitely not overcomplicating things creating separate iterator object. In fact, PHP supports and encourages such aggregation providing <code>IteratorAggregate</code> interface. Objects implementing <code>IteratorAggregate</code> must contain <code>getIterator()</code> method returning <code>Iterator</code>. It is really what your <code>getChocolated()</code> method does. The nice thing about <code>IteratorAggregate</code> is that you can pass an object of it directly to <code>foreach</code> loop. Your code might look like like this one when using it:</p>\n\n<pre><code>class BoxOfChocolates implements IteratorAggregate\n\n private $chocolates = array();\n\n public function getIterator() {\n return new ArrayIterator(new ArrayObject($this-&gt;chocolates)));\n }\n\n}\n</code></pre>\n\n<p>And then, somewhere in the code:</p>\n\n<pre><code>$box = new BoxOfChocolates();\nforeach ($box as $chocolate) { ... }\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216094", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29230/" ]
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). What am I not seeing is which one is preferable over the other? Or am I just over complicating this? Here are my thoughts: The object implements an iterator: ``` 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->_items[] = new Chocolate() ... } } // ... necessary iterator implementation stuff } ``` The object contains an iterate-able object: ``` class BoxOfChocolates { private $id; private $name; private $maker; private $items; // chocolates object public function getChocolates() { $this->items = new Chocolates(); $this->items->getChocolates(); } } class Chocolates implements Iterator { private $items; public function getChocolates() { $query = ... foreach($rows as $row) { $this->_items[] = new Chocolate() ... } } // ... necessary iterator implementation stuff } ```
It depends on the situation. Is the box of chocolates going t0 contain multiple collections? If so you need to have the collections be members. Think of it this way. Is a box of chocolates a collection (i.e. PersonList) or something that owns a collection (i.e. a car may own a collection of it's last owners). I think this falls under the first group :)
216,109
<p>I get this message:</p> <blockquote> <p>Cannot find the X.509 certificate using the following search criteria: StoreName 'My', StoreLocation 'LocalMachine', FindType 'FindBySubjectDistinguishedName', FindValue 'CN=HighBall'.</p> </blockquote> <p>My web.config setup looks like this;</p> <p>Authentication is set like...</p> <pre><code>&lt;authentication mode="Windows" /&gt; </code></pre> <p>The bindings are set for wsHttpBinging</p> <p> </p> <p>and my Service behavior is set as such...</p> <pre><code>&lt;behavior name="HighBall.Services.ServiceVerificationBehavior"&gt; &lt;serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="HighBallRoleProvider" /&gt; &lt;serviceMetadata httpGetEnabled="true" /&gt; &lt;serviceDebug includeExceptionDetailInFaults="true" /&gt; &lt;serviceCredentials&gt; &lt;serviceCertificate findValue="CN=HighBall" /&gt; &lt;userNameAuthentication userNamePasswordValidationMode="MembershipProvider" membershipProviderName="HighBallMembershipProvider" /&gt; &lt;/serviceCredentials&gt; &lt;/behavior&gt; </code></pre> <p>I've tried to figure out a way to verify what, how, and where to certificate is stored but am not sure how to do this. If anyone has any ideas on this error message I'd greatly appreciate the assist.</p>
[ { "answer_id": 216148, "author": "VP.", "author_id": 18642, "author_profile": "https://Stackoverflow.com/users/18642", "pm_score": 3, "selected": true, "text": "<p>Check the other post about the tool that you asked about. Verify your \"my\" storage and check if the CN=\"HighBall\". I guess your CN is not just \"HighBall\", probably it has a top level domain. I think it's easier to look for the certificate serial number, i think it's faster than for it's canonical name and error prone.</p>\n\n<p>Regards,</p>\n\n<p>Victor</p>\n" }, { "answer_id": 216216, "author": "Richard Nienaber", "author_id": 9539, "author_profile": "https://Stackoverflow.com/users/9539", "pm_score": 3, "selected": false, "text": "<p>Remember that ASP.NET runs as a different user. It may need to be assigned access to the certificate.</p>\n" }, { "answer_id": 6676085, "author": "Lauri I", "author_id": 824931, "author_profile": "https://Stackoverflow.com/users/824931", "pm_score": 0, "selected": false, "text": "<p>Try to use Certificate Manager (with MMC) to see installed certificates. Instructions for XP: <a href=\"http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/sag_cmprocsfind.mspx?mfr=true\" rel=\"nofollow\">manage certificates for a computer</a>, probably similar with Vista and 7 as well.</p>\n\n<p>I was having problems with service unable to find the x509 certificate, but by using the Certificate Manager I found out that \"Install PFX\" command from Windows Explorer had not installed the certificate at all! This was fixed by importing the certificate from Certificate Manager.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29345/" ]
I get this message: > > Cannot find the X.509 certificate using the following search criteria: StoreName 'My', StoreLocation 'LocalMachine', FindType 'FindBySubjectDistinguishedName', FindValue 'CN=HighBall'. > > > My web.config setup looks like this; Authentication is set like... ``` <authentication mode="Windows" /> ``` The bindings are set for wsHttpBinging and my Service behavior is set as such... ``` <behavior name="HighBall.Services.ServiceVerificationBehavior"> <serviceAuthorization principalPermissionMode="UseAspNetRoles" roleProviderName="HighBallRoleProvider" /> <serviceMetadata httpGetEnabled="true" /> <serviceDebug includeExceptionDetailInFaults="true" /> <serviceCredentials> <serviceCertificate findValue="CN=HighBall" /> <userNameAuthentication userNamePasswordValidationMode="MembershipProvider" membershipProviderName="HighBallMembershipProvider" /> </serviceCredentials> </behavior> ``` I've tried to figure out a way to verify what, how, and where to certificate is stored but am not sure how to do this. If anyone has any ideas on this error message I'd greatly appreciate the assist.
Check the other post about the tool that you asked about. Verify your "my" storage and check if the CN="HighBall". I guess your CN is not just "HighBall", probably it has a top level domain. I think it's easier to look for the certificate serial number, i think it's faster than for it's canonical name and error prone. Regards, Victor
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": 216123, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 0, "selected": false, "text": "<p>Take the first element, reverse the rest of the list recursively, and append the first element at the end of the list.</p>\n" }, { "answer_id": 216132, "author": "Ignacio Vazquez-Abrams", "author_id": 20862, "author_profile": "https://Stackoverflow.com/users/20862", "pm_score": 3, "selected": false, "text": "<p>The trick is to join <em>after</em> recursing:</p>\n\n<pre>\ndef backwards(l):\n if not l:\n return\n x, y = l[0], l[1:]\n return backwards(y) + [x]\n</pre>\n" }, { "answer_id": 216136, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 5, "selected": true, "text": "<p>Append the first element of the list to a reversed sublist:</p>\n\n<pre><code>mylist = [1, 2, 3, 4, 5]\nbackwards = lambda l: (backwards (l[1:]) + l[:1] if l else []) \nprint backwards (mylist)\n</code></pre>\n" }, { "answer_id": 216168, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 4, "selected": false, "text": "<p>A bit more explicit:</p>\n\n<pre><code>def rev(l):\n if len(l) == 0: return []\n return [l[-1]] + rev(l[:-1])\n</code></pre>\n\n<hr>\n\n<p>This turns into:</p>\n\n<pre><code>def rev(l):\n if not l: return []\n return [l[-1]] + rev(l[:-1])\n</code></pre>\n\n<p>Which turns into:</p>\n\n<pre><code>def rev(l):\n return [l[-1]] + rev(l[:-1]) if l else []\n</code></pre>\n\n<p>Which is the same as another answer.</p>\n\n<hr>\n\n<p>Tail recursive / CPS style (which python doesn't optimize for anyway):</p>\n\n<pre><code>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&gt;&gt;&gt; rev([1, 2, 3, 4, 5], lambda x: x)\n[5, 4, 3, 2, 1]\n</code></pre>\n" }, { "answer_id": 216184, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I know it's not a helpful answer (though this question has been already answered), but in any real code, please don't do that. Python cannot optimize tail-calls, has slow function calls and has a fixed recursion depth, so there are at least 3 reasons why to do it iteratively instead.</p>\n" }, { "answer_id": 217204, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 2, "selected": false, "text": "<p>This one reverses in place. (Of course an iterative version would be better, but it has to be recursive, hasn't it?)</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 2105565, "author": "steve", "author_id": 255334, "author_profile": "https://Stackoverflow.com/users/255334", "pm_score": 1, "selected": false, "text": "<pre><code>def reverse(q):\n if len(q) != 0:\n temp = q.pop(0)\n reverse(q)\n q.append(temp)\n return q\n</code></pre>\n" }, { "answer_id": 35097940, "author": "Francis Phiri", "author_id": 4696434, "author_profile": "https://Stackoverflow.com/users/4696434", "pm_score": 2, "selected": false, "text": "<pre><code>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</code></pre>\n" }, { "answer_id": 35679380, "author": "Shrikant Singh", "author_id": 4337792, "author_profile": "https://Stackoverflow.com/users/4337792", "pm_score": 0, "selected": false, "text": "<pre><code>def reverseList(listName,newList = None):\nif newList == None:\n newList = []\nif len(listName)&gt;0:\n newList.append((listName.pop()))\n return reverseList(listName, newList)\nelse:\n return newList\n</code></pre>\n\n<p>print reverseList([1,2,3,4])\n[4,3,2,1]</p>\n" }, { "answer_id": 39977940, "author": "Aaditya Ura", "author_id": 5904928, "author_profile": "https://Stackoverflow.com/users/5904928", "pm_score": 0, "selected": false, "text": "<p>Using Mutable default argument and recursion :</p>\n\n<pre><code>def hello(x,d=[]):\n d.append(x[-1])\n if len(x)&lt;=1:\n s=\"\".join(d)\n print(s)\n\n else:\n return hello(x[:-1])\n\nhello(\"word\")\n</code></pre>\n\n<h1>additional info</h1>\n\n<pre><code>x[-1] # last item in the array\nx[-2:] # last two items in the array\nx[:-2] # everything except the last two items\n</code></pre>\n\n<p>Recursion part is <code>hello(x[:-1])</code> where its calling hello function again after <code>x[:-1]</code> </p>\n" }, { "answer_id": 39978152, "author": "Riccardo Petraglia", "author_id": 6769931, "author_profile": "https://Stackoverflow.com/users/6769931", "pm_score": -1, "selected": false, "text": "<p>Why not:</p>\n\n<pre><code>a = [1,2,3,4,5]\na = [a[i] for i in xrange(len(a)-1, -1, -1)] # now a is reversed!\n</code></pre>\n" }, { "answer_id": 40209266, "author": "Padmal", "author_id": 4968539, "author_profile": "https://Stackoverflow.com/users/4968539", "pm_score": 0, "selected": false, "text": "<p>This will reverse a nested lists also!</p>\n\n<pre><code>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</code></pre>\n\n<p><a href=\"http://padmalblog.blogspot.com/2016/10/algorithm-assignments.html#more\" rel=\"nofollow\">Padmal's BLOG</a></p>\n" }, { "answer_id": 42645088, "author": "Giwi", "author_id": 7671524, "author_profile": "https://Stackoverflow.com/users/7671524", "pm_score": 1, "selected": false, "text": "<p>looks simpler:</p>\n\n<pre><code> def reverse (n):\n if not n: return []\n return [n.pop()]+reverse(n)\n</code></pre>\n" }, { "answer_id": 45164573, "author": "Aran", "author_id": 3840847, "author_profile": "https://Stackoverflow.com/users/3840847", "pm_score": 3, "selected": false, "text": "<p>Use the Divide &amp; conquer strategy. D&amp;C algorithms are recursive algorithms.\nTo solve this problem using D&amp;C, there are two steps:</p>\n\n<ol>\n<li>Figure out the base case. This should be the simplest possible case.</li>\n<li>Divide or decrease your problem until it becomes the base case.</li>\n</ol>\n\n<p>Step 1: Figure out the base case. What’s the simplest list you could\nget? If you get an list with 0 or 1 element, that’s pretty easy to sum up.</p>\n\n<pre><code>if len(l) == 0: #base case\n return []\n</code></pre>\n\n<p>Step 2: You need to move closer to an empty list with every recursive\ncall</p>\n\n<pre><code>recursive(l) #recursion case\n</code></pre>\n\n<p>for example</p>\n\n<pre><code>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&gt;[6,4,2,1]\n</code></pre>\n\n<p>Source : Grokking Algorithms</p>\n" }, { "answer_id": 58619797, "author": "Kenneth Chang", "author_id": 5638346, "author_profile": "https://Stackoverflow.com/users/5638346", "pm_score": 2, "selected": false, "text": "<h1>A recursive function to reverse a list.</h1>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 64957363, "author": "anmol_gorakshakar", "author_id": 14222462, "author_profile": "https://Stackoverflow.com/users/14222462", "pm_score": -1, "selected": false, "text": "<p>if it is a list of numbers easiest way to reverse it would be. This would also work for strings but not recommended.</p>\n<pre><code>l1=[1,2,3,4]\nl1 = np.array(l1)\nassert l1[::-1]==[4,3,2,1]\n</code></pre>\n<p>if you do not want to keep it as a numpy array then you can pass it into a list as</p>\n<pre><code>l1 = [*l1]\n</code></pre>\n<p>again I do not recommend it for list of strings but you could if you really wanted to.</p>\n" }, { "answer_id": 66724905, "author": "Hammad Ahmed", "author_id": 14153396, "author_profile": "https://Stackoverflow.com/users/14153396", "pm_score": -1, "selected": false, "text": "<pre><code>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</code></pre>\n" }, { "answer_id": 67794251, "author": "Mohit Ranjan", "author_id": 12171344, "author_profile": "https://Stackoverflow.com/users/12171344", "pm_score": -1, "selected": false, "text": "<pre class=\"lang-python prettyprint-override\"><code>def disp_array_reverse(inp, idx=0):\n if idx &gt;= len(inp):\n return\n disp_array_reverse(inp, idx+1)\n print(inp[idx])\n</code></pre>\n" }, { "answer_id": 67961184, "author": "Lokesh Rajawat", "author_id": 16216340, "author_profile": "https://Stackoverflow.com/users/16216340", "pm_score": 0, "selected": false, "text": "<p>You can reduce the recursion depth by half by swapping the first and last elements at once and calling <code>rev</code> recursively on the middle of the list:</p>\n<pre><code>lks=[2,7,3,1,9,6,5]\ndef rev(lks):\n if len(lks)&lt;2:\n return lks\n return [lks[-1]]+rev(lks[1:-1])+[lks[0]]\nprint(rev(lks))\n</code></pre>\n" }, { "answer_id": 68056830, "author": "0x5961736972", "author_id": 13597101, "author_profile": "https://Stackoverflow.com/users/13597101", "pm_score": 0, "selected": false, "text": "<p>The answer you're looking for is inside the function. The rest of the stuff is just to see (or if you want to compare) the time taken by the different algorithms.</p>\n<pre><code>import time\nimport sys\n\nsys.setrecursionlimit(10**6)\n\n\ndef reverse(ls1):\n if len(ls1) &lt;= 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&quot;Total time taken: {(stop_time - start_time) * 1000} msec.&quot;)\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216119", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11324/" ]
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?
Append the first element of the list to a reversed sublist: ``` mylist = [1, 2, 3, 4, 5] backwards = lambda l: (backwards (l[1:]) + l[:1] if l else []) print backwards (mylist) ```
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": 216128, "author": "Don Neufeld", "author_id": 13097, "author_profile": "https://Stackoverflow.com/users/13097", "pm_score": 3, "selected": false, "text": "<p>Yes, that's a shallow copy. You now have two copies of s (one in the caller, one on the stack as a parameter), each which contain a pointer to that same block of memory.</p>\n" }, { "answer_id": 216152, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 2, "selected": false, "text": "<p>You will have two copies of the <code>s</code> struct, each of which will have their own <code>i</code> pointer, but both <code>i</code> pointers will have the same value pointing to the same address in memory - so yes, it will be a shallow copy.</p>\n" }, { "answer_id": 216154, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 4, "selected": true, "text": "<p>To follow up on what @[don.neufeld.myopenid.com] said, it is not only a shallow copy, but it is either (take your pick) a memory leak or a dangling pointer.</p>\n\n<pre><code>// 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</code></pre>\n\n<p>To resolve this, there are several methods.</p>\n\n<p><strong>Always implement a copy constructor and operator= in classes that use raw memory pointers.</strong></p>\n\n<pre><code>class A\n{\n B *_b;\n public:\n A()\n ... (same as above)\n\n ~A()\n ...\n\n A(const A &amp;rhs)\n : _b(new B(rhs._b))\n {\n }\n\n A &amp;operator=(const A &amp;rhs)\n {\n B *b=new B(rhs._b);\n delete _b;\n _b=b;\n return *this;\n};\n</code></pre>\n\n<p>Needless to say, this is a major pain and there are quite a few subtleties to get right. I'm not even totally sure I did it right here and I've done it a few times. Don't forget you have to copy all of the members - if you add some new ones later on, don't forget to add them in too!</p>\n\n<p><strong>Make the copy constructor and operator= private in your class.</strong> This is the \"lock the door\" solution. It is simple and effective, but sometimes over-protective.</p>\n\n<pre><code>class A : public boost::noncopyable\n{\n ...\n};\n</code></pre>\n\n<p><strong>Never use raw pointers.</strong> This is simple and effective. There are lots of options here:</p>\n\n<ul>\n<li>Use string classes instead of raw char pointers</li>\n<li>Use std::auto_ptr, boost::shared_ptr, boost::scoped_ptr etc</li>\n</ul>\n\n<p>Example:</p>\n\n<pre><code>// 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&lt;B&gt; _b;\n public:\n A()\n : _b(new B)\n {\n }\n};\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216124", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
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.
To follow up on what @[don.neufeld.myopenid.com] said, it is not only a shallow copy, but it is either (take your pick) a memory leak or a dangling pointer. ``` // memory leak (note that the pointer is never deleted) class A { B *_b; public: A() : _b(new B) { } }; // dangling ptr (who deletes the instance?) class A { B *_b; public: A() ... (same as above) ~A() { delete _b; } }; ``` To resolve this, there are several methods. **Always implement a copy constructor and operator= in classes that use raw memory pointers.** ``` class A { B *_b; public: A() ... (same as above) ~A() ... A(const A &rhs) : _b(new B(rhs._b)) { } A &operator=(const A &rhs) { B *b=new B(rhs._b); delete _b; _b=b; return *this; }; ``` Needless to say, this is a major pain and there are quite a few subtleties to get right. I'm not even totally sure I did it right here and I've done it a few times. Don't forget you have to copy all of the members - if you add some new ones later on, don't forget to add them in too! **Make the copy constructor and operator= private in your class.** This is the "lock the door" solution. It is simple and effective, but sometimes over-protective. ``` class A : public boost::noncopyable { ... }; ``` **Never use raw pointers.** This is simple and effective. There are lots of options here: * Use string classes instead of raw char pointers * Use std::auto\_ptr, boost::shared\_ptr, boost::scoped\_ptr etc Example: ``` // uses shared_ptr - note that you don't need a copy constructor or op= - // shared_ptr uses reference counting so the _b instance is shared and only // deleted when the last reference is gone - admire the simplicity! // it is almost exactly the same as the "memory leak" version, but there is no leak class A { boost::shared_ptr<B> _b; public: A() : _b(new B) { } }; ```
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": "<p>Maybe you can try an <a href=\"http://en.wikipedia.org/wiki/Object-relational_mapping\" rel=\"noreferrer\">ORM</a>, like <a href=\"http://propel.phpdb.org/trac/\" rel=\"noreferrer\">Propel</a> or <a href=\"http://www.doctrine-project.org/\" rel=\"noreferrer\">Doctrine</a>, they have a nice programmatic query language, and they return you arrays of objects that represent rows in your database...</p>\n\n<p>For example with Doctrine you can do joins like this:</p>\n\n<pre><code>$q = Doctrine_Query::create();\n$q-&gt;from('User u')\n-&gt;leftJoin('u.Group g')\n-&gt;innerJoin('u.Phonenumber p WITH u.id &gt; 3')\n-&gt;leftJoin('u.Email e');\n\n$users = $q-&gt;execute();\n</code></pre>\n\n<p>And with Propel:</p>\n\n<pre><code>$c = new Criteria(AuthorPeer::DATABASE_NAME);\n\n$c-&gt;addJoin(AuthorPeer::ID, BookPeer::AUTHOR_ID, Criteria::INNER_JOIN);\n$c-&gt;addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::INNER_JOIN);\n$c-&gt;add(PublisherPeer::NAME, 'Some Name');\n\n$authors = AuthorPeer::doSelect($c);\n</code></pre>\n\n<p>and you can do a lot more with both...</p>\n" }, { "answer_id": 216311, "author": "andyuk", "author_id": 2108, "author_profile": "https://Stackoverflow.com/users/2108", "pm_score": 0, "selected": false, "text": "<p>I would advise using a PHP framework such as Symfony which uses Propel by default and can use Doctrine if you wish.</p>\n\n<p>CakePHP also uses an ORM, but I don't know which one.</p>\n" }, { "answer_id": 216381, "author": "James Hall", "author_id": 7496, "author_profile": "https://Stackoverflow.com/users/7496", "pm_score": 1, "selected": false, "text": "<p>I highly recommend CakePHP. It creates joins for you automatically, based on the associations between tables.</p>\n\n<p>Say if you were writing a blog:</p>\n\n<pre><code>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-&gt;set('post', $this-&gt;Post-&gt;read(null, $id));\n}\n\napp/views/posts/view.ctp:\n\n&lt;h2&gt;&lt;?php echo $post['Post']['title']?&gt;&lt;/h2&gt;\n&lt;p&gt;&lt;?php echo $post['Post']['body']; /* Might want Textile/Markdown here */ ?&gt;&lt;/p&gt;\n&lt;h3&gt;Comments&lt;/h3&gt;\n&lt;?php foreach($post['Comment'] as $comment) { ?&gt;\n &lt;p&gt;&lt;?php echo $comment['body']?&gt;&lt;/p&gt;\n &lt;p class=\"poster\"&gt;&lt;?php echo $comment['name']?&gt;&lt;/p&gt;\n&lt;?php } ?&gt;\n</code></pre>\n\n<p>That would be all you have to write to view a blog post, your database schema is read and cached. As long as you keep it consistent with the conventions, you don't have to tell cake anything about how your table is set up.</p>\n\n<pre><code>posts:\nid INT\nbody TEXT\ncreated DATETIME\n\ncomments:\nid INT\nbody TEXT\nname VARCHAR\npost_id INT\n</code></pre>\n\n<p>It has adapters to support MySQL, MSSQL, PostgreSQL, SQLite, Oracle and others. You can also wrap webservices as models, and even get it to do joins between data in your database and remote data! It's very clever stuff.</p>\n\n<p>Hope this helps :)</p>\n" }, { "answer_id": 218999, "author": "Stefan Gehrig", "author_id": 11354, "author_profile": "https://Stackoverflow.com/users/11354", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://framework.zend.com/manual/en/zend.db.select.html\" rel=\"nofollow noreferrer\">Zend_Db_Select</a> from the <a href=\"http://framework.zend.com/manual/en/zend.db.html\" rel=\"nofollow noreferrer\">Zend_Db</a> package of the <a href=\"http://framework.zend.com/\" rel=\"nofollow noreferrer\">Zend Framework</a> can do such things as:</p>\n\n<pre><code>// 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-&gt;select()\n -&gt;from(array('p' =&gt; 'products'), array('product_id', 'product_name'))\n -&gt;join(array('l' =&gt; 'line_items'), 'p.product_id = l.product_id');\n</code></pre>\n\n<p>(from <a href=\"http://framework.zend.com/manual/en/zend.db.select.html#zend.db.select.building.join\" rel=\"nofollow noreferrer\">Example 11.54. Example of the join() method</a> in the Zend Framework Manual)</p>\n\n<p>If you don't like to run a full-blown ORM package, this could be the way to go.</p>\n" }, { "answer_id": 8080803, "author": "anonymous", "author_id": 1039918, "author_profile": "https://Stackoverflow.com/users/1039918", "pm_score": 1, "selected": false, "text": "<p>superfast SQLObject based IteratorQuery from pastaPHP<br/> \niterates over resource</p>\n\n<pre><code> foreach(_from('users u')\n -&gt;columns(\"up.email_address AS EmailAddress\", \"u.user_name AS u.UserName\")\n -&gt;left('userprofiles up', _eq('u.id', _var('up.id')))\n -&gt;where(_and()-&gt;add(_eq('u.is_active',1)))\n -&gt;limit(0,10)\n -&gt;order(\"UserName\")\n -&gt;execute(\"myConnection\") as $user){\n\n echo sprintf(\n '&lt;a href=\"mailto:%s\"&gt;%s&lt;/a&gt;&lt;br/&gt;', \n $user-&gt;EmailAdress, \n $user-&gt;UserName\n );\n }\n</code></pre>\n" }, { "answer_id": 19596542, "author": "Timo Huovinen", "author_id": 175071, "author_profile": "https://Stackoverflow.com/users/175071", "pm_score": 0, "selected": false, "text": "<p>This seems to be a SQL builder with complex join support: <a href=\"http://laravel.com/docs/queries\" rel=\"nofollow\">http://laravel.com/docs/queries</a></p>\n" }, { "answer_id": 21612394, "author": "Aaron", "author_id": 28950, "author_profile": "https://Stackoverflow.com/users/28950", "pm_score": 1, "selected": false, "text": "<p>FluentPDO looks nice if you're already using PDO: <a href=\"https://github.com/envms/fluentpdo\" rel=\"nofollow noreferrer\">https://github.com/envms/fluentpdo</a></p>\n" }, { "answer_id": 26819394, "author": "Charlie", "author_id": 1291481, "author_profile": "https://Stackoverflow.com/users/1291481", "pm_score": 0, "selected": false, "text": "<p>I use the query builder from the <em>phptoolcase library</em>, it uses pdo connector, has join support.</p>\n\n<p><a href=\"http://phptoolcase.com/guides/ptc-qb-guide.html\" rel=\"nofollow\">http://phptoolcase.com/guides/ptc-qb-guide.html</a></p>\n\n<p>You can use it with the connection manager fro the library to setup multiple database connection very quickly.</p>\n" }, { "answer_id": 29664398, "author": "c9s", "author_id": 780629, "author_profile": "https://Stackoverflow.com/users/780629", "pm_score": 0, "selected": false, "text": "<p>Try magsql <a href=\"https://github.com/maghead/magsql\" rel=\"nofollow noreferrer\">https://github.com/maghead/magsql</a>, a SQL builder designed for performance written in PHP, comes with join support and cross-platform SQL generation.</p>\n\n<p>It's currently used in the fastest pure PHP orm \"maghead\"</p>\n" }, { "answer_id": 29931078, "author": "Günce Bektaş", "author_id": 2350880, "author_profile": "https://Stackoverflow.com/users/2350880", "pm_score": -1, "selected": false, "text": "<p>You can use lenkorm it's very easy:</p>\n\n<p>select('contents)->left('categories ON categories.category.id = contents.category_id)->where('content_id = 1')->result();</p>\n\n<p>or you can use as: </p>\n\n<p>select('contents)->left('categories->using(categoru_id)->where('content_id = 1')->result();</p>\n\n<p><a href=\"https://github.com/guncebektas/lenkorm\" rel=\"nofollow\">Download it from github</a></p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216138", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20538/" ]
Are any of you aware of a library that helps you build/manipulate SQL queries, that supports JOIN's? 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. 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.
Maybe you can try an [ORM](http://en.wikipedia.org/wiki/Object-relational_mapping), like [Propel](http://propel.phpdb.org/trac/) or [Doctrine](http://www.doctrine-project.org/), they have a nice programmatic query language, and they return you arrays of objects that represent rows in your database... For example with Doctrine you can do joins like this: ``` $q = Doctrine_Query::create(); $q->from('User u') ->leftJoin('u.Group g') ->innerJoin('u.Phonenumber p WITH u.id > 3') ->leftJoin('u.Email e'); $users = $q->execute(); ``` And with Propel: ``` $c = new Criteria(AuthorPeer::DATABASE_NAME); $c->addJoin(AuthorPeer::ID, BookPeer::AUTHOR_ID, Criteria::INNER_JOIN); $c->addJoin(BookPeer::PUBLISHER_ID, PublisherPeer::ID, Criteria::INNER_JOIN); $c->add(PublisherPeer::NAME, 'Some Name'); $authors = AuthorPeer::doSelect($c); ``` and you can do a lot more with both...
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": "<p>I've just trimmed the python a bit here:</p>\n\n<pre><code>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</code></pre>\n\n<p>This is a hefty 410 characters, 250 if you don't count whitespace. If you just turn it into perl you'll undoubtedly be better than mine!</p>\n" }, { "answer_id": 217114, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 3, "selected": true, "text": "<p>I haven't really made much of a change - the algorithm is identical, but here are a few further micro-optimisations you can make to your python code.</p>\n\n<ul>\n<li><p>No need for !=0, 0 is false in a boolean context.</p></li>\n<li><p>a if c else b is more expensive than using [a,b][c] if you don't need short-circuiting, hence you can use <code>h[ [0,A[j]][j/9.. rest of boolean condition]</code>. Even better is to exploit the fact that you want 0 in the false case, and so multiply by the boolean value (treated as either <code>0*A[j]</code> (ie. 0) or <code>1*A[j]</code> (ie. <code>A[j]</code>).</p></li>\n<li><p>You can omit spaces between digits and identifiers. eg \"<code>9 or</code>\" -> \"<code>9or</code>\"</p></li>\n<li><p>You can omit the key to sorted(). Since you're sorting on the first element, a normal sort will produce effectively the same order (unless you're relying on stability, which it doesn't look like)</p></li>\n<li><p>You can save a couple of bytes by omitting the .items() call, and just assign h,i in the next line to z[l]</p></li>\n<li><p>You only use s once - no point in using a variable. You can also avoid using range() by selecting the appropriate slice of r instead (r[1:10])</p></li>\n<li><p><code>j not in h</code> can become <code>(j in h)-1</code> (relying on True == 1 in integer context)</p></li>\n<li><p><strong>[Edit]</strong> You can also replace the first for loop's construction of h with a dict constructor and a generator expression. This lets you compress the logic onto one line, saving 10 bytes in total.</p></li>\n</ul>\n\n<p>More generally, you probably want to think about ways to change the algorithm to reduce the levels of nesting. Every level gives an additional byte per line within in python, which accumulates.</p>\n\n<p>Here's what I've got so far (I've switched to 1 space per indent so that you can get an accurate picture of required characters. Currently it's weighing in at <strike>288</strike> 278, which is still pretty big.</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 217569, "author": "Claudiu", "author_id": 15055, "author_profile": "https://Stackoverflow.com/users/15055", "pm_score": 2, "selected": false, "text": "<pre><code>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</code></pre>\n\n<p>269 characters, and it finds all solutions. Usage (not counted in char count):</p>\n\n<pre><code>sixsol = map(int, \"300000080001093000040780003093800012000040000520006790600021040000530900030000051\")\nfor S in R(sixsol):\n print S\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216141", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
The point of this question is to create the shortest **not abusively slow** Sudoku solver. This is defined as: **don't recurse when there are spots on the board which can only possibly be one digit**. Here is the shortest I have so far in python: ``` 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")) ``` The last line I take to be part of the cmd line input, it can be changed to: ``` import sys; R(map(int, sys.argv[1]); ``` This is similar to other sudoku golf challenges, except that I want to eliminate unnecessary recursion. Any language is acceptable. The challenge is on!
I haven't really made much of a change - the algorithm is identical, but here are a few further micro-optimisations you can make to your python code. * No need for !=0, 0 is false in a boolean context. * a if c else b is more expensive than using [a,b][c] if you don't need short-circuiting, hence you can use `h[ [0,A[j]][j/9.. rest of boolean condition]`. Even better is to exploit the fact that you want 0 in the false case, and so multiply by the boolean value (treated as either `0*A[j]` (ie. 0) or `1*A[j]` (ie. `A[j]`). * You can omit spaces between digits and identifiers. eg "`9 or`" -> "`9or`" * You can omit the key to sorted(). Since you're sorting on the first element, a normal sort will produce effectively the same order (unless you're relying on stability, which it doesn't look like) * You can save a couple of bytes by omitting the .items() call, and just assign h,i in the next line to z[l] * You only use s once - no point in using a variable. You can also avoid using range() by selecting the appropriate slice of r instead (r[1:10]) * `j not in h` can become `(j in h)-1` (relying on True == 1 in integer context) * **[Edit]** You can also replace the first for loop's construction of h with a dict constructor and a generator expression. This lets you compress the logic onto one line, saving 10 bytes in total. More generally, you probably want to think about ways to change the algorithm to reduce the levels of nesting. Every level gives an additional byte per line within in python, which accumulates. Here's what I've got so far (I've switched to 1 space per indent so that you can get an accurate picture of required characters. Currently it's weighing in at 288 278, which is still pretty big. ``` r=range(81) def R(A): z={} for i in r: 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 for l in sorted(z): h,i=z[l] for j in r[1:10]: if(j in h)-1: A[i]=j if R(A):return A A[i]=0;return[] return A ```
216,150
<p>Where do you draw the line to stop making abstractions and to start writing sane code? There are tons of examples of 'enterprise code' such as the dozen-file "FizzBuzz" program... even something simple such as an RTS game can have something like:</p> <pre><code>class Player {} ;/// contains Weapons class Weapons{} ;/// contains BulletTypes class BulletType{} ;///contains descriptions of Bullets class Bullet{} ;///extends PlaceableObject and RenderableObject which can be placed/drawn respectively class PlaceableObject{} ;///has x,y,z, coords class RenderableObject{} ;///an object with a draw() command class MovingObject{}; ///an object with a move() function </code></pre> <p>etc... and it can turn into a nightmare. This can be drawn to its logical extreme, much like functional programming can be drawn to the extreme where you can create a language with only variables, function application, and anonymous function definitions (although I must admit that is slightly more elegant)... </p> <p>Any sane advice on this topic?</p>
[ { "answer_id": 216169, "author": "Paweł Hajdan", "author_id": 9403, "author_profile": "https://Stackoverflow.com/users/9403", "pm_score": 5, "selected": true, "text": "<ol>\n<li><strong>YAGNI (You Ain't Gotta Need It).</strong> Don't create abstractions you don't see immediate use for or a sensible reason. This way you have a simple thing that may become more complex, instead of a complicated things that you would strive to make simpler, but lose.</li>\n<li>Make sure the abstractions make sense. If they're too far from reality, too hard to justify... forget it.</li>\n<li>Let the solution feel natural. Work on it until it does. Then for an unfamiliar person the solution should seem so obvious, that he screams \"how could you have done it differently?\".</li>\n<li><strong>Don't try to predict the future.</strong> You can't. If you try to cover all 10 possible cases, you will soon discover 11th and more, and it will be more difficult to implement it because of previous 10, not encountered in practice. <strong>Make it simple and easy to adapt.</strong> Software needs to be changed, but ease of adaptation (agility) is often much better strategy than trying to cover all maybe-possible cases up-front.</li>\n</ol>\n" }, { "answer_id": 216218, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 0, "selected": false, "text": "<p>I believe that the criteria may be deduced from a clear definition of what abstraction is.</p>\n\n<p>You are referring to abstraction within the Object-Oriented programing paradigm, where you have at your disposal the three principles: <a href=\"https://stackoverflow.com/questions/99688\">'abstraction' - 'encapsulation' - 'information hiding or visibility'</a>.</p>\n\n<p><strong>Abstraction is the process of choosing which attributes of the object are relevant to your system, and which must be completely ignored.</strong></p>\n\n<p>That means, the abstraction limit does not concern so much the <em>number</em> of concepts you define (Player, Weapons, Bullets, ...), but <em>what you choose to put inside</em> those concepts.</p>\n\n<p>It is basically <em>triage</em>, where you will consider only from a concept what is useful to the services you need to define.</p>\n\n<p>So <strong><em>a good criteria to start writing sane code might be the APIs</em></strong>, as the eclipse program suggest: <strong><a href=\"http://www.eclipse.org/eclipse/development/apis/API-First.pdf\" rel=\"nofollow noreferrer\">API first</a></strong>.</p>\n\n<p>Indeed, \"Good APIs require design iteration\", meaning the list of objects you mentioning in your question will be refined as the API needed is itself refined.</p>\n\n<p>Plus, APIs mean to have well-defined component boundaries and dependencies (as in 'Core - Player - vs. UI - RenderableObject - '), meaning the very detailed list you mentioning can not be viewed as a long endless list of concepts, but must be clearly grouped into different <strong><em>functional perimeters</em></strong> (or functional components), from an applicative architecture.</p>\n\n<p>Since APIs exist to serve the needs of clients, you will keep those objects only because they make sense for the client. The others objects should be in 'internal' packages and never be referred directly by any other parts of your application.</p>\n\n<p>With that in mind, <a href=\"https://stackoverflow.com/questions/216150#216169\">@phjr advices</a> make perfect sense ;)</p>\n" }, { "answer_id": 216318, "author": "Richard Harrison", "author_id": 19624, "author_profile": "https://Stackoverflow.com/users/19624", "pm_score": 2, "selected": false, "text": "<p>Perhaps this question should be <strong>where to start abstracting</strong>.</p>\n\n<p>The example you quote is a classic example of not enough thought about what the objects actually are, as they are all pretty much the same - and probably would be better expressed as a single \"GameObject\".</p>\n\n<p>I also avoid sub classing by object properties. For StaticGameObject and DynamicGameObject may seem logica, but are probably better represented by container placement - i.e. two lists one for static objects and one for dynamic, thus allowing other logic to define the actions rather than the object itself being responsible for controlling something outside of it's scope.</p>\n\n<p>Sometimes it is harder to work out what is shared by a group of things that you want to represent in a object - but it is worth doing.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216150", "https://Stackoverflow.com", "https://Stackoverflow.com/users/15055/" ]
Where do you draw the line to stop making abstractions and to start writing sane code? There are tons of examples of 'enterprise code' such as the dozen-file "FizzBuzz" program... even something simple such as an RTS game can have something like: ``` class Player {} ;/// contains Weapons class Weapons{} ;/// contains BulletTypes class BulletType{} ;///contains descriptions of Bullets class Bullet{} ;///extends PlaceableObject and RenderableObject which can be placed/drawn respectively class PlaceableObject{} ;///has x,y,z, coords class RenderableObject{} ;///an object with a draw() command class MovingObject{}; ///an object with a move() function ``` etc... and it can turn into a nightmare. This can be drawn to its logical extreme, much like functional programming can be drawn to the extreme where you can create a language with only variables, function application, and anonymous function definitions (although I must admit that is slightly more elegant)... Any sane advice on this topic?
1. **YAGNI (You Ain't Gotta Need It).** Don't create abstractions you don't see immediate use for or a sensible reason. This way you have a simple thing that may become more complex, instead of a complicated things that you would strive to make simpler, but lose. 2. Make sure the abstractions make sense. If they're too far from reality, too hard to justify... forget it. 3. Let the solution feel natural. Work on it until it does. Then for an unfamiliar person the solution should seem so obvious, that he screams "how could you have done it differently?". 4. **Don't try to predict the future.** You can't. If you try to cover all 10 possible cases, you will soon discover 11th and more, and it will be more difficult to implement it because of previous 10, not encountered in practice. **Make it simple and easy to adapt.** Software needs to be changed, but ease of adaptation (agility) is often much better strategy than trying to cover all maybe-possible cases up-front.
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": "<p>I'm not really sure what parameters <code>EMBED</code> and <code>OBJECT</code> take as I've never really dealt with putting media on a page (which is actually kind of shocking to think about) but I would take a BB Code approach to it and do something like <code>[embed url=\"http://www.whatever.com/myvideo.whatever\" ...]</code> and then you can parse out the URL and anything else, make sure they are legit and make your own <code>&lt;EMBED&gt;</code> tag.</p>\n\n<p><strong>edit:</strong> Alright, something like this should be fine:</p>\n\n<pre><code>$youtube = '&lt;object width=\"425\" height=\"344\"&gt;&lt;param name=\"movie\" value=\"http://www.youtube.com/v/Z75QSExE0jU&amp;hl=en&amp;fs=1\"&gt;&lt;/param&gt; &lt;/param&gt;&lt;embed src=\"http://www.youtube.com/v/Z75QSExE0jU&amp;hl=en&amp;fs=1\" type=\"application/x-shockwave-flash\" allowfullscreen=\"true\" width=\"425\" height=\"344\"&gt;&lt;/embed&gt;&lt;/object&gt;';\n\n$blip = '&lt;embed src=\"http://blip.tv/play/AZ_iEoaIfA\" type=\"application/x-shockwave-flash\" width=\"640\" height=\"510\" allowscriptaccess=\"always\" allowfullscreen=\"true\"&gt;&lt;/embed&gt;';\n\npreg_match_all(\"/([A-Za-z]*)\\=\\\"(.+?)\\\"/\", $youtube, $matches1);\npreg_match_all(\"/([A-Za-z]*)\\=\\\"(.+?)\\\"/\", $blip, $matches2);\nprint '&lt;pre&gt;' . print_r($matches1, true). '&lt;/pre&gt;';\nprint '&lt;pre&gt;' . print_r($matches2, true). '&lt;/pre&gt;';\n</code></pre>\n\n<p>This will output:</p>\n\n<pre><code>Array\n(\n[0] =&gt; Array\n (\n [0] =&gt; width=\"425\"\n [1] =&gt; height=\"344\"\n [2] =&gt; name=\"movie\"\n [3] =&gt; value=\"http://www.youtube.com/v/Z75QSExE0jU&amp;hl=en&amp;fs=1\"\n [4] =&gt; src=\"http://www.youtube.com/v/Z75QSExE0jU&amp;hl=en&amp;fs=1\"\n [5] =&gt; type=\"application/x-shockwave-flash\"\n [6] =&gt; allowfullscreen=\"true\"\n [7] =&gt; width=\"425\"\n [8] =&gt; height=\"344\"\n )\n\n[1] =&gt; Array\n (\n [0] =&gt; width\n [1] =&gt; height\n [2] =&gt; name\n [3] =&gt; value\n [4] =&gt; src\n [5] =&gt; type\n [6] =&gt; allowfullscreen\n [7] =&gt; width\n [8] =&gt; height\n )\n\n[2] =&gt; Array\n (\n [0] =&gt; 425\n [1] =&gt; 344\n [2] =&gt; movie\n [3] =&gt; http://www.youtube.com/v/Z75QSExE0jU&amp;hl=en&amp;fs=1\n [4] =&gt; http://www.youtube.com/v/Z75QSExE0jU&amp;hl=en&amp;fs=1\n [5] =&gt; application/x-shockwave-flash\n [6] =&gt; true\n [7] =&gt; 425\n [8] =&gt; 344\n )\n)\n\nArray\n(\n[0] =&gt; Array\n (\n [0] =&gt; src=\"http://blip.tv/play/AZ_iEoaIfA\"\n [1] =&gt; type=\"application/x-shockwave-flash\"\n [2] =&gt; width=\"640\"\n [3] =&gt; height=\"510\"\n [4] =&gt; allowscriptaccess=\"always\"\n [5] =&gt; allowfullscreen=\"true\"\n )\n\n[1] =&gt; Array\n (\n [0] =&gt; src\n [1] =&gt; type\n [2] =&gt; width\n [3] =&gt; height\n [4] =&gt; allowscriptaccess\n [5] =&gt; allowfullscreen\n )\n\n[2] =&gt; Array\n (\n [0] =&gt; http://blip.tv/play/AZ_iEoaIfA\n [1] =&gt; application/x-shockwave-flash\n [2] =&gt; 640\n [3] =&gt; 510\n [4] =&gt; always\n [5] =&gt; true\n )\n)\n</code></pre>\n\n<p>From then on it's pretty straight forward. For things like width/height you can verify them with <a href=\"http://www.php.net/is_numeric\" rel=\"nofollow noreferrer\"><code>is_numeric</code></a> and with the rest you can run the values through <a href=\"http://www.php.net/htmlentities\" rel=\"nofollow noreferrer\"><code>htmlentities</code></a> and construct your own <code>&lt;embed&gt;</code> tag from the information. I am pretty certain this would be safe. You can even make the full-fledged <code>&lt;object&gt;</code> one like YouTube (which I assume works in more places) with links from blip.tv, since you would have all the required data.</p>\n\n<p>I am sure you may see some quirks with links from other video-sharing websites but this will hopefully get you started. Good luck.</p>\n" }, { "answer_id": 216167, "author": "Doug Kaye", "author_id": 17307, "author_profile": "https://Stackoverflow.com/users/17307", "pm_score": 0, "selected": false, "text": "<p>Here's an example of pasted code from blip.tv:</p>\n\n<pre><code>&lt;embed src=\"http://blip.tv/play/AZ_iEoaIfA\" type=\"application/x-shockwave-flash\" \n width=\"640\" height=\"510\" allowscriptaccess=\"always\" allowfullscreen=\"true\"&gt;&lt;/embed&gt;\n</code></pre>\n\n<p>Here's an example of what you might get from YouTube:</p>\n\n<pre><code>&lt;object width=\"425\" height=\"344\"&gt;\n &lt;param name=\"movie\" value=\"http://www.youtube.com/v/Z75QSExE0jU&amp;hl=en&amp;fs=1\"&gt;&lt;/param&gt;\n &lt;param name=\"allowFullScreen\" value=\"true\"&gt;&lt;/param&gt;\n &lt;embed src=\"http://www.youtube.com/v/Z75QSExE0jU&amp;hl=en&amp;fs=1\"\n type=\"application/x-shockwave-flash\" allowfullscreen=\"true\"\n width=\"425\" height=\"344\"&gt;&lt;/embed&gt;\n&lt;/object&gt;\n</code></pre>\n" }, { "answer_id": 216196, "author": "bobince", "author_id": 18936, "author_profile": "https://Stackoverflow.com/users/18936", "pm_score": 1, "selected": false, "text": "<p>Your chances of detecting malicious code reliably by scanning inputted HTML are about nil. There are so many possible ways to inject script (including browser-specific malformed HTML), you won't be able to pick them all out. If big webmail providers are still after years finding new exploits there is no chance you'll be able to do it.</p>\n\n<p>Whitelisting is better than blacklisting. So you could instead require the input to be XHTML, and parse it using a standard XML parser. Then walk through the DOM and check that each of the elements and attributes is known-good, and if everything's OK, serialise back to XHTML, which, coming from a known-good DOM, should not be malformed. A proper XML parser with Unicode support should also filter out nasty 'overlong UTF-8 sequences' (a security hole affecting IE6 and older Operas) for free.</p>\n\n<p>However... if you allow embed/objects from any domain, you are already allowing full script access to your page from an external domains, so HTML injection is the least of your worries. Plug-ins such as Flash are likely to be able to execute JavaScript without any kind of trickery being necessary.</p>\n\n<p>So you should be limiting the source of objects to predetermined known-good domains. And if you're already doing that, it's probably easier to just allow the user to choose a video provider and clip ID, and then convert that into the proper, known-good embedding code for that provider. For example if you are using a bbcode-like markup, the traditional way to let users include a YouTube clip would be something [youtube]Dtzs7DSh[/youtube].</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216155", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17307/" ]
I want to allow users to paste `<embed>` and `<object>` 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?
I'm not really sure what parameters `EMBED` and `OBJECT` take as I've never really dealt with putting media on a page (which is actually kind of shocking to think about) but I would take a BB Code approach to it and do something like `[embed url="http://www.whatever.com/myvideo.whatever" ...]` and then you can parse out the URL and anything else, make sure they are legit and make your own `<EMBED>` tag. **edit:** Alright, something like this should be fine: ``` $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>'; $blip = '<embed src="http://blip.tv/play/AZ_iEoaIfA" type="application/x-shockwave-flash" width="640" height="510" allowscriptaccess="always" allowfullscreen="true"></embed>'; preg_match_all("/([A-Za-z]*)\=\"(.+?)\"/", $youtube, $matches1); preg_match_all("/([A-Za-z]*)\=\"(.+?)\"/", $blip, $matches2); print '<pre>' . print_r($matches1, true). '</pre>'; print '<pre>' . print_r($matches2, true). '</pre>'; ``` This will output: ``` Array ( [0] => Array ( [0] => width="425" [1] => height="344" [2] => name="movie" [3] => value="http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1" [4] => src="http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1" [5] => type="application/x-shockwave-flash" [6] => allowfullscreen="true" [7] => width="425" [8] => height="344" ) [1] => Array ( [0] => width [1] => height [2] => name [3] => value [4] => src [5] => type [6] => allowfullscreen [7] => width [8] => height ) [2] => Array ( [0] => 425 [1] => 344 [2] => movie [3] => http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1 [4] => http://www.youtube.com/v/Z75QSExE0jU&hl=en&fs=1 [5] => application/x-shockwave-flash [6] => true [7] => 425 [8] => 344 ) ) Array ( [0] => Array ( [0] => src="http://blip.tv/play/AZ_iEoaIfA" [1] => type="application/x-shockwave-flash" [2] => width="640" [3] => height="510" [4] => allowscriptaccess="always" [5] => allowfullscreen="true" ) [1] => Array ( [0] => src [1] => type [2] => width [3] => height [4] => allowscriptaccess [5] => allowfullscreen ) [2] => Array ( [0] => http://blip.tv/play/AZ_iEoaIfA [1] => application/x-shockwave-flash [2] => 640 [3] => 510 [4] => always [5] => true ) ) ``` From then on it's pretty straight forward. For things like width/height you can verify them with [`is_numeric`](http://www.php.net/is_numeric) and with the rest you can run the values through [`htmlentities`](http://www.php.net/htmlentities) and construct your own `<embed>` tag from the information. I am pretty certain this would be safe. You can even make the full-fledged `<object>` one like YouTube (which I assume works in more places) with links from blip.tv, since you would have all the required data. I am sure you may see some quirks with links from other video-sharing websites but this will hopefully get you started. Good luck.
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": 216180, "author": "Wilco", "author_id": 5291, "author_profile": "https://Stackoverflow.com/users/5291", "pm_score": 0, "selected": false, "text": "<p>After some research, it looks like the best approach would be to simply specify a custom user agent string when making AJAX calls and then checking for this custom user agent string on the server.</p>\n" }, { "answer_id": 216183, "author": "Paul Dixon", "author_id": 6521, "author_profile": "https://Stackoverflow.com/users/6521", "pm_score": 6, "selected": true, "text": "<p>If you use Prototype, jQuery, Mootools or YUI you should find a <strong>X-Requested-With:XMLHttpRequest</strong> header which will do the trick for you. It should be possible to insert whatever header you like with other libraries.</p>\n\n<p>At the lowest level, given a <a href=\"http://www.w3.org/TR/XMLHttpRequest\" rel=\"noreferrer\">XMLHttpRequest</a> or XMLHTTP object, you can set this header with the <a href=\"http://www.w3.org/TR/XMLHttpRequest/#setrequestheader\" rel=\"noreferrer\">setRequestHeader</a> method as follows:</p>\n\n<pre><code>xmlHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest');\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216173", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5291/" ]
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?
If you use Prototype, jQuery, Mootools or YUI you should find a **X-Requested-With:XMLHttpRequest** header which will do the trick for you. It should be possible to insert whatever header you like with other libraries. At the lowest level, given a [XMLHttpRequest](http://www.w3.org/TR/XMLHttpRequest) or XMLHTTP object, you can set this header with the [setRequestHeader](http://www.w3.org/TR/XMLHttpRequest/#setrequestheader) method as follows: ``` xmlHttpRequest.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); ```
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": "<p>You may want to consider using <strong>strategy pattern</strong> instead of both approaches and encapsulate behaviours within external classes. Then the behaviours can be injected into the Missile class to make it GuidedMissile or SpaceRocket or whatever else you need. </p>\n\n<p>This way excessive branching of logic within the Missile class could be avoided and you would not need to go into logical complexities associated with the deep inheritance.</p>\n\n<p>Wikipedia has a collection of samples of the pattern usage in several languages:\n<a href=\"http://en.wikipedia.org/wiki/Strategy_pattern\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Strategy_pattern</a></p>\n\n<pre><code>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</code></pre>\n\n<hr>\n\n<p>As suggested by another collegue, you could consider using Decorator pattern as well. Just to highlight couple of design issues that might be important in your context if you were to take that route:</p>\n\n<ol>\n<li>To replace just a certain aspect of object's behaviour you'd need to decorate the entire class. </li>\n<li>If the public interface of the decorated class (let say missile) to be ever changed (even some functionality unrelated to its navigation aspect) you would have to change all of the decorating classes (i.e. GuidedMissile, Rocket, FireworkRocket etc) to pass on the interface.</li>\n<li>In Decorator you would expect that a decorator would add functionality, not replace it. It works by adding invoking its functions then calling the base class method. In the scenario above this would lead to being able to have a GuidedMissileCPU that decorates a GeoStationaryRocketCPU -- clearly this is not what you want. You want it to choose a different navigation strategy not layer navigation strategies on top of one another.</li>\n</ol>\n\n<p>Nonetheless, when provided with a ready-made immutable implementation of Missile decoration could be the key to \"unlocking\" it and implementing the strategy pattern, to provide the Missile with all sorts of required behaviours.</p>\n" }, { "answer_id": 216237, "author": "milot", "author_id": 22637, "author_profile": "https://Stackoverflow.com/users/22637", "pm_score": 1, "selected": false, "text": "<p>Inheritance depends on the language/technology you are using, for example in C++ you can derive a class from multiple classes but such construct is not available in Java, C#, PHP etc. but instead you have abstract classes and interfaces, what I am trying to say is that if you have a class for example your company's software will use multiple database management systems and its up to you to design an independent set of classes for such a construct, and you can do it by using an abstract class and implement polymorphism to your set for example:</p>\n\n<pre><code> public abstract class Database\n {\n public virtual void Connect();\n public virtual int GetNumberOfTables();\n\n }\n</code></pre>\n\n<p>and then you can derive a class for specific SQL Server or Oracle implementation</p>\n\n<pre><code> 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</code></pre>\n\n<p>In such a construct you can use inheritance, but avoiding the class logic complexity as I saw in your example above.</p>\n\n<p>As for conditionals you can use to test if you destroyed the object or garbage collector set the object in the finalization queue that it is not available to you any longer.</p>\n" }, { "answer_id": 216238, "author": "ema", "author_id": 19520, "author_profile": "https://Stackoverflow.com/users/19520", "pm_score": 1, "selected": false, "text": "<p>I think that in this case you should the Decorator Pattern.\nEvery new functionality you add is a decoration on the original Missile class.\nFor example you could create a new decorated Missile class that can be Guided (GuidedMissile) and that can go underwater (UnderwaterMissile) simply decorating tha Missile class.\nThe good is that the Decorator Pattern works at runtime and you don't need to build all that classes with static behaviour but you can compose the needed behaviour at runtime.\nHave a look here:\n<a href=\"http://en.wikipedia.org/wiki/Decorator_pattern\" rel=\"nofollow noreferrer\">http://en.wikipedia.org/wiki/Decorator_pattern</a>\n<a href=\"http://www.dofactory.com/Patterns/PatternDecorator.aspx\" rel=\"nofollow noreferrer\">http://www.dofactory.com/Patterns/PatternDecorator.aspx</a></p>\n" }, { "answer_id": 216290, "author": "Sergey", "author_id": 29363, "author_profile": "https://Stackoverflow.com/users/29363", "pm_score": 0, "selected": false, "text": "<p>Just ask yourself, how it would be easier to:</p>\n\n<ol>\n<li>read and understand the code (the small project part and the whole project)</li>\n<li>change the code in the future (be very careful when predicting future needs, usually it's better not to adapt your code for \"may-be\" changes in advance)</li>\n</ol>\n\n<p>Also there are some really rare cases when class hierarchy can seriously affect the performance.</p>\n\n<p>So make derived classes when it's better for above criteria.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216182", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6266/" ]
When should I continue to make derived classes, and when should I just add conditionals to my code? eg for a missile ``` class Object; class Projectile : public Object; class Missile : public Projectile; class MissileGuided : public Missile; ``` Or should I implement that last one in the missile's code? ``` void Missile::Update() { if(homing && ObjectExists(Target)) TurnTowards(Target.Pos) Pos += Motion; } ``` 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) 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) 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...) And then everything ends up back as like 3 classes: ``` class Entity; class Object : public Entity; class Effect : public Entity; ``` Where is a good point to draw the line between creating derived classes, and implementing the features in the method with flags or something?
You may want to consider using **strategy pattern** instead of both approaches and encapsulate behaviours within external classes. Then the behaviours can be injected into the Missile class to make it GuidedMissile or SpaceRocket or whatever else you need. This way excessive branching of logic within the Missile class could be avoided and you would not need to go into logical complexities associated with the deep inheritance. Wikipedia has a collection of samples of the pattern usage in several languages: <http://en.wikipedia.org/wiki/Strategy_pattern> ``` interface INavigable { Course calcCourse (Position current, Destination dest); } Class GeoStationaryRocketCPU implements INavigable { Course calcCourse (Position current, Destination dest) { return dest.getShortestRouteTo (current).getCourse(); }; } Class GuidedMissileCPU implements INavigable { Course calcCourse (Position current, Destination dest) { return dest.getLowestAltRouteTo (current).getCourse(); }; } class Missile { INavigable CPU; void setCPU (INavigable CPU) { this.CPU = CPU; } void fly () { ... course = this.CPU.calcCourse (pos, dest); ... } } ``` --- As suggested by another collegue, you could consider using Decorator pattern as well. Just to highlight couple of design issues that might be important in your context if you were to take that route: 1. To replace just a certain aspect of object's behaviour you'd need to decorate the entire class. 2. If the public interface of the decorated class (let say missile) to be ever changed (even some functionality unrelated to its navigation aspect) you would have to change all of the decorating classes (i.e. GuidedMissile, Rocket, FireworkRocket etc) to pass on the interface. 3. In Decorator you would expect that a decorator would add functionality, not replace it. It works by adding invoking its functions then calling the base class method. In the scenario above this would lead to being able to have a GuidedMissileCPU that decorates a GeoStationaryRocketCPU -- clearly this is not what you want. You want it to choose a different navigation strategy not layer navigation strategies on top of one another. Nonetheless, when provided with a ready-made immutable implementation of Missile decoration could be the key to "unlocking" it and implementing the strategy pattern, to provide the Missile with all sorts of required behaviours.
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": "<p>I would recommend a look at jQuery for your task. It is quite easy to learn and produces nice effects quickly. But your described effect alone, pure JavaScript would also be enough.</p>\n\n<p>Make your DIVs always have a class called \"selectable\". You can toggle other CSS classes later on. Create a CSS class named \"selected\" and give it the desired look.</p>\n\n<pre><code>&lt;div class=\"selectable\"&gt; (=off) vs. &lt;div class=\"selectable selected\"&gt; (=on)\n</code></pre>\n\n<p>Then add something like this to the scripts section of your document:</p>\n\n<pre><code>$(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</code></pre>\n\n<p>This is untested so there might be a glitch in it, but it will give you the general idea where to start.</p>\n\n<p>P.S: Changing text size on mouse move may not be the best of all ideas. It leads to rearranging the page layout which is annoying for the user.</p>\n" }, { "answer_id": 216371, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "<p>There's also a pure CSS solution to this problem. However, it doesn't work in MSIE 6. Technically, it works similar to Tomalek's solution but instead of using JavaScript to toggle the element's class, it uses CSS to toggle its style:</p>\n\n<pre><code>.selectable { /* basic styles … */ }\n.selectable:hover { /* hover styles … */ }\n.selectable:active { /* focus styles … */ }\n</code></pre>\n" }, { "answer_id": 216498, "author": "whalesalad", "author_id": 21022, "author_profile": "https://Stackoverflow.com/users/21022", "pm_score": 1, "selected": false, "text": "<p>This is somewhat unrelated, but the label tag does not enclose the input tag. You give the label tag a \"for\" attribute which corresponds to the ID of the input element. Example,</p>\n\n<pre><code>&lt;label for=\"username\"&gt;Username&lt;/label&gt;\n&lt;input type=\"text\" name=\"username\" value=\"Enter your username...\" id=\"username\" /&gt;\n</code></pre>\n" }, { "answer_id": 216563, "author": "cllpse", "author_id": 20946, "author_profile": "https://Stackoverflow.com/users/20946", "pm_score": 2, "selected": false, "text": "<p><strong>@Tomalak:</strong></p>\n\n<p>Why are you querying the DOM four times?</p>\n\n<p>A small edit, but a huge speed-benefit:</p>\n\n<pre><code>$(\"div.selectable\").mouseover(function ()\n{\n // ...\n}).mouseout(function ()\n{\n // ...\n});\n</code></pre>\n" }, { "answer_id": 217966, "author": "whalesalad", "author_id": 21022, "author_profile": "https://Stackoverflow.com/users/21022", "pm_score": 0, "selected": false, "text": "<p>Yet another unrelated-to-the-original-question answer but... jQuery also has an alternative syntax for doing mouseover/mouseout stuff called hover.</p>\n\n<pre><code>$(element).hover(function(){ /* mouseover */ }, function(){ /* mouseout */ });\n</code></pre>\n\n<p>Example,</p>\n\n<pre><code>$('ul#nav li').hover(function() {\n $(this).addClass('highlight');\n}, function() {\n $(this).removeClass('highlight');\n});\n</code></pre>\n\n<p>Sorry for those double $'s, I can't seem to figure out how to escape that.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21384/" ]
Suppose to have a code like this: ``` <div class="notSelected"> <label>Name <input type="text" name="name" id="name" /> </label> <div class="description"> Tell us what's your name to make us able to fake to be your friend when sending you an email. </div> </div> ``` 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: * User focus on the input element * User move the mouse over a notSelected div When he change focus the Selected div should became notSelected again. 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. 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... 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.
I would recommend a look at jQuery for your task. It is quite easy to learn and produces nice effects quickly. But your described effect alone, pure JavaScript would also be enough. Make your DIVs always have a class called "selectable". You can toggle other CSS classes later on. Create a CSS class named "selected" and give it the desired look. ``` <div class="selectable"> (=off) vs. <div class="selectable selected"> (=on) ``` Then add something like this to the scripts section of your document: ``` $(document).ready(function(){ // handle mouseover and mouseout of the parent div $("div.selectable").mouseover( function() { $(this).addClass("selected").addClass("mouseIsOver"); } ).mouseout( function() { $(this).removeClass("selected").removeClass("mouseIsOver"); } ); // handle focus and blur of the contained input elememt, // unless it has already been selected by mouse move $("div.selectable input").focus( function() { $(this).parents("div.selectable").not(".mouseIsOver").addClass("selected"); } ).blur( function() { $(this).parents("div.selectable").not(".mouseIsOver").removeClass("selected"); } ); }); ``` This is untested so there might be a glitch in it, but it will give you the general idea where to start. P.S: Changing text size on mouse move may not be the best of all ideas. It leads to rearranging the page layout which is annoying for the user.
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": 216204, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 9, "selected": true, "text": "<p>There are different types of shells. The SSH command execution shell is a non-interactive shell, whereas your normal shell is either a login shell or an interactive shell. Description follows, from man bash:</p>\n\n<pre>\n A login shell is one whose first character of argument\n zero is a -, or one started with the --login option.\n\n An interactive shell is one started without non-option\n arguments and without the -c option whose standard input\n and error are both connected to terminals (as determined\n by isatty(3)), or one started with the -i option. PS1 is\n set and $- includes i if bash is interactive, allowing a\n shell script or a startup file to test this state.\n\n The following paragraphs describe how bash executes its\n startup files. If any of the files exist but cannot be\n read, bash reports an error. Tildes are expanded in file\n names as described below under Tilde Expansion in the\n EXPANSION section.\n\n When bash is invoked as an interactive login shell, or as\n a non-interactive shell with the --login option, it first\n reads and executes commands from the file /etc/profile, if\n that file exists. After reading that file, it looks for\n ~/.bash_profile, ~/.bash_login, and ~/.profile, in that\n order, and reads and executes commands from the first one\n that exists and is readable. The --noprofile option may\n be used when the shell is started to inhibit this behav­\n ior.\n\n When a login shell exits, bash reads and executes commands\n from the file ~/.bash_logout, if it exists.\n\n When an interactive shell that is not a login shell is\n started, bash reads and executes commands from ~/.bashrc,\n if that file exists. This may be inhibited by using the\n --norc option. The --rcfile file option will force bash\n to read and execute commands from file instead of\n ~/.bashrc.\n\n When bash is started non-interactively, to run a shell\n script, for example, it looks for the variable BASH_ENV in\n the environment, expands its value if it appears there,\n and uses the expanded value as the name of a file to read\n and execute. Bash behaves as if the following command\n were executed:\n if [ -n \"$BASH_ENV\" ]; then . \"$BASH_ENV\"; fi\n but the value of the PATH variable is not used to search\n for the file name.\n\n</pre>\n" }, { "answer_id": 1472444, "author": "Ian Vaughan", "author_id": 119790, "author_profile": "https://Stackoverflow.com/users/119790", "pm_score": 7, "selected": false, "text": "<p>How about sourcing the profile before running the command?</p>\n\n<p><code>ssh user@host \"source /etc/profile; /path/script.sh\"</code></p>\n\n<p>You might find it best to change that to <code>~/.bash_profile</code>, <code>~/.bashrc</code>, or whatever.</p>\n\n<p>(As <a href=\"http://www.linuxquestions.org/questions/linux-enterprise-47/simple-rsh-issue-621882/?posted=1#post3695616\" rel=\"noreferrer\">here (linuxquestions.org)</a>)</p>\n" }, { "answer_id": 4173699, "author": "tomaszbak", "author_id": 478584, "author_profile": "https://Stackoverflow.com/users/478584", "pm_score": 6, "selected": false, "text": "<p>I had similar issue, but in the end I found out that ~/.bashrc was all I needed.</p>\n\n<p>However, in Ubuntu, I had to comment the line that stops processing ~/.bashrc :</p>\n\n<pre><code>#If not running interactively, don't do anything\n[ -z \"$PS1\" ] &amp;&amp; return\n</code></pre>\n" }, { "answer_id": 4608230, "author": "Chuck", "author_id": 564450, "author_profile": "https://Stackoverflow.com/users/564450", "pm_score": 2, "selected": false, "text": "<p>I found an easy resolution for this issue was to add\n source /etc/profile\nto the top of the script.sh file I was trying to run on the target system.\nOn the systems here, this caused the environmental variables which were needed by script.sh to be configured as if running from a login shell.</p>\n\n<p>In one of the prior responses it was suggested that ~/.bashr_profile etc... be used.\nI didn't spend much time on this but, the problem with this is if you ssh to a different user on the target system than the shell on the source system from which you log in it appeared to me that this causes the source system user name to be used for the ~.</p>\n" }, { "answer_id": 9288850, "author": "Michael MacDonald", "author_id": 449102, "author_profile": "https://Stackoverflow.com/users/449102", "pm_score": 2, "selected": false, "text": "<p>Just export the environment variables you want above the check for a non-interactive shell in ~/.bashrc.</p>\n" }, { "answer_id": 9993668, "author": "dpedro", "author_id": 1310457, "author_profile": "https://Stackoverflow.com/users/1310457", "pm_score": 7, "selected": false, "text": "<p>Shell environment does not load when running remote ssh command. You can edit ssh environment file:</p>\n\n<pre><code>vi ~/.ssh/environment\n</code></pre>\n\n<p>Its format is:</p>\n\n<pre><code>VAR1=VALUE1\nVAR2=VALUE2\n</code></pre>\n\n<p>Also, check <code>sshd</code> configuration for <code>PermitUserEnvironment=yes</code> option.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216202", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13523/" ]
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 : ``` ssh user@IP <command> ``` 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 : ``` ssh user@IP "env" ``` Any idea why ?
There are different types of shells. The SSH command execution shell is a non-interactive shell, whereas your normal shell is either a login shell or an interactive shell. Description follows, from man bash: ``` A login shell is one whose first character of argument zero is a -, or one started with the --login option. An interactive shell is one started without non-option arguments and without the -c option whose standard input and error are both connected to terminals (as determined by isatty(3)), or one started with the -i option. PS1 is set and $- includes i if bash is interactive, allowing a shell script or a startup file to test this state. The following paragraphs describe how bash executes its startup files. If any of the files exist but cannot be read, bash reports an error. Tildes are expanded in file names as described below under Tilde Expansion in the EXPANSION section. When bash is invoked as an interactive login shell, or as a non-interactive shell with the --login option, it first reads and executes commands from the file /etc/profile, if that file exists. After reading that file, it looks for ~/.bash_profile, ~/.bash_login, and ~/.profile, in that order, and reads and executes commands from the first one that exists and is readable. The --noprofile option may be used when the shell is started to inhibit this behav­ ior. When a login shell exits, bash reads and executes commands from the file ~/.bash_logout, if it exists. When an interactive shell that is not a login shell is started, bash reads and executes commands from ~/.bashrc, if that file exists. This may be inhibited by using the --norc option. The --rcfile file option will force bash to read and execute commands from file instead of ~/.bashrc. When bash is started non-interactively, to run a shell script, for example, it looks for the variable BASH_ENV in the environment, expands its value if it appears there, and uses the expanded value as the name of a file to read and execute. Bash behaves as if the following command were executed: if [ -n "$BASH_ENV" ]; then . "$BASH_ENV"; fi but the value of the PATH variable is not used to search for the file name. ```
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": 216260, "author": "REA_ANDREW", "author_id": 67959, "author_profile": "https://Stackoverflow.com/users/67959", "pm_score": 0, "selected": false, "text": "<p>Have you not subscribed to the Complete Event. Or the Progress Event? Are you using a Loader? I am sure in flex you can attach Event Handlers in the markup of the image for at least the Complete and progress. The Progress will give you totalBytes and bytesLoaded. </p>\n\n<p>Cheers,\n Andrew</p>\n" }, { "answer_id": 216264, "author": "hasseg", "author_id": 4111, "author_profile": "https://Stackoverflow.com/users/4111", "pm_score": 2, "selected": true, "text": "<p>I'm assuming you for some reason can't attach an <code>Event.COMPLETE</code> event listener to the Image before it starts loading. If this is the case, you could always subclass <code>mx.controls.Image</code> and add your own property <code>\"loadingCompleted\"</code> or <code>\"complete\"</code> that is initially <code>false</code> but gets set to <code>true</code> when the <code>Event.COMPLETE</code> event fires the first time.</p>\n" }, { "answer_id": 216696, "author": "RickDT", "author_id": 5421, "author_profile": "https://Stackoverflow.com/users/5421", "pm_score": 1, "selected": false, "text": "<p>There will never be a race condition on loaders in AS3 because that portion of the API is not multi-threaded. Just add your event listener before the load starts and you'll be fine. If you're using MXML, then this is all taken care of for you.</p>\n\n<p>If there is some reason why you don't have control over the Image control, then the best practice would be to compare bytesLoaded and bytesTotal.</p>\n\n<pre><code>// this will not race \nif (myImage.bytesLoaded &lt; 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</code></pre>\n" }, { "answer_id": 233042, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>Using events is the best approach. If you have a scenario where events don't do the trick, you could monitor the contentWidth and contentHeight properties of an image control. According to the doc, \"You can get the value after the updateComplete event is triggered.\" Before loading the value is NaN. It becomes a number once the content is loaded.</p>\n\n<p><a href=\"http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/controls/Image.html\" rel=\"nofollow noreferrer\">http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/mx/controls/Image.html</a></p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216209", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24727/" ]
I'm looking for the best way to tell if an `<mx:Image>` 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. something like : ``` if (newBackground.percentLoaded < 100) ``` or ``` if (newBackground.content != null) ``` i was originally doing `newBackground.content != null`, but that had some cross domain issues because the sandbox wont let me access content apparently! i'm even a little weary of using `percentLoaded < 100` in case of possible race conditions. yes i am familiar with `showEffect`, but that not what I want for this.
I'm assuming you for some reason can't attach an `Event.COMPLETE` event listener to the Image before it starts loading. If this is the case, you could always subclass `mx.controls.Image` and add your own property `"loadingCompleted"` or `"complete"` that is initially `false` but gets set to `true` when the `Event.COMPLETE` event fires the first time.
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": 216257, "author": "WW.", "author_id": 14663, "author_profile": "https://Stackoverflow.com/users/14663", "pm_score": 2, "selected": true, "text": "<p>Are you performing a commit after this? It might be running your statement but then not committing the changes and doing an implicit rollback.</p>\n\n<p>I think the exception handling looks dodgy. There is no point catching something unless you can actually handle it in some way. The top level of your framework is the place for catching and reporting unexpected exceptions.</p>\n" }, { "answer_id": 216262, "author": "Russ Cam", "author_id": 1831, "author_profile": "https://Stackoverflow.com/users/1831", "pm_score": 0, "selected": false, "text": "<p>Have you tried setting the return value of the ExecuteScalar method to an int and then checking value against the table?</p>\n\n<p><a href=\"http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx\" rel=\"nofollow noreferrer\">ExecuteScalar</a> -</p>\n\n<p><em>Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored</em></p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 216263, "author": "Niko Gamulin", "author_id": 22996, "author_profile": "https://Stackoverflow.com/users/22996", "pm_score": 0, "selected": false, "text": "<p>I found the problem. I modified the automatically generated connection string</p>\n\n<blockquote>\n <p>connectionString=\"Data\n Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|\\URSZRDB.mdf;Integrated\n Security=True;User Instance=True\"</p>\n</blockquote>\n\n<p>with</p>\n\n<blockquote>\n <p>connectionString=\"Data\n Source=.\\SQLEXPRESS;AttachDbFilename=C:\\Users\\Niko\\Documents\\Visual\n Studio 2008\\Projects\\URSZRWAPChat\\URSZRWAPChat\\URSZRDB.mdf;Integrated\n Security=True;User Instance=True\"</p>\n</blockquote>\n\n<p>and now it works. </p>\n\n<p>It's not the first time I write this kind of program and so far everything has gone well this way...</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22996/" ]
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: ``` 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(); } } ``` 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. Does anyone know what could cause such behavior?
Are you performing a commit after this? It might be running your statement but then not committing the changes and doing an implicit rollback. I think the exception handling looks dodgy. There is no point catching something unless you can actually handle it in some way. The top level of your framework is the place for catching and reporting unexpected exceptions.
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": "<p>What you wish to do is to have a:</p>\n\n<pre><code>Repository.Save(publicObject)\n</code></pre>\n\n<p>and the repository to call a method from publicObject?</p>\n\n<p>If this is the requirement then you can define the Save method in repository as:</p>\n\n<pre><code>public class Repository {\n public void Save(IPublicObject publicObject) {\n publicObject.Save();\n }\n}\n</code></pre>\n\n<p>where IPublicObject is defined as:</p>\n\n<pre><code>public interface IPublicObject {\n void Save();\n}\n</code></pre>\n\n<p>But with this approach you will have to define a save method for each entity (like ConcretePublicObjectOne in your example)</p>\n" }, { "answer_id": 216485, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 3, "selected": true, "text": "<p>For LINQ-to-SQL, the data-context already does a lot of the mapping for you. As such, I think generics might be the best way to achieve a save while still having some consideration of your interface (although I'm not quite sure what the interface is giving you in this scenario...).</p>\n\n<p>You can access the generic aspect of the data-context via <code>GetTable&lt;T&gt;()</code>:</p>\n\n<pre><code> static void Save&lt;T&gt;(T item)\n where T : class, IPublicObject\n {\n using (DataContext ctx = GetDataContext())\n {\n Table&lt;T&gt; table = ctx.GetTable&lt;T&gt;();\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</code></pre>\n\n<p>Note that type-inference should mean that you don't need to specify the <code>T</code> when saving:</p>\n\n<pre><code> Foo foo = new Foo();\n Save(foo); // &lt;Foo&gt; is inferred\n</code></pre>\n\n<p>Is that any use?</p>\n" }, { "answer_id": 217732, "author": "REA_ANDREW", "author_id": 67959, "author_profile": "https://Stackoverflow.com/users/67959", "pm_score": 0, "selected": false, "text": "<p>Marc Gravell:</p>\n\n<p>Thanks for that. As I say though I think using your example I would have to keep to the models that I get from the datacontext which kind of binds me to LINQ.</p>\n\n<p>What you have done though is exactly the kind of thing I am looking for. It finds the type based on the object, and then knows which action to commit. Using your example, could I use anonymous types to apply a transformation to my models to work with that linq code. I have different storeage mdeiums you see which I need the models to wotk with across the board. The models are kind of self contain and know nothing about anything out side of them lol.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216255", "https://Stackoverflow.com", "https://Stackoverflow.com/users/67959/" ]
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. 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 ``` public class ConcretePublicObjectOne : IPublicObject{} ``` 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... Should I use a registry, configuration setting mapping the types?
For LINQ-to-SQL, the data-context already does a lot of the mapping for you. As such, I think generics might be the best way to achieve a save while still having some consideration of your interface (although I'm not quite sure what the interface is giving you in this scenario...). You can access the generic aspect of the data-context via `GetTable<T>()`: ``` static void Save<T>(T item) where T : class, IPublicObject { using (DataContext ctx = GetDataContext()) { Table<T> table = ctx.GetTable<T>(); // for insert... table.InsertOnSubmit(item); // for update... table.Attach(item, true); // for delete... table.DeleteOnSubmit(item); ctx.SubmitChanges(); } } ``` Note that type-inference should mean that you don't need to specify the `T` when saving: ``` Foo foo = new Foo(); Save(foo); // <Foo> is inferred ``` Is that any use?
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": 216280, "author": "REA_ANDREW", "author_id": 67959, "author_profile": "https://Stackoverflow.com/users/67959", "pm_score": 0, "selected": false, "text": "<p>I would probably use the second example. Although I see both as perfectly acceptable.</p>\n" }, { "answer_id": 216282, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 2, "selected": false, "text": "<p>I think out style is more readable in general. People are less familiar with nullable types (just check the amount of questions about them here), and they'll be even less familiar with a TryParse2 which does not exist in the standard library (or however it's technically called in .NET).</p>\n" }, { "answer_id": 216284, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 4, "selected": true, "text": "<p>TryParse(val, out result) is a idiom established by the .NET framework in int.TryParse, DateTime.TryParse, etc. It is likely that people that read the code will be familiar with this idiom, so you should stick to it, unless you find a very good reason not to.</p>\n" }, { "answer_id": 216296, "author": "REA_ANDREW", "author_id": 67959, "author_profile": "https://Stackoverflow.com/users/67959", "pm_score": 0, "selected": false, "text": "<p>A nullable type has a Value property which is not nullable of the same type. This is where you do not need to convert a nullable type but rather use the value of the nullable type.</p>\n" }, { "answer_id": 216325, "author": "Schotime", "author_id": 29376, "author_profile": "https://Stackoverflow.com/users/29376", "pm_score": 0, "selected": false, "text": "<p>I have seen the out variable syntax used in many applications.</p>\n\n<p>Personally I like it too.</p>\n" }, { "answer_id": 216656, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 0, "selected": false, "text": "<p>I prefer the second example because it's a more type inference friendly style of programming. Having an out parameter prevents a developer from using type inference for a particular call. </p>\n\n<pre><code>\nvar result = Int32.TryParse(\"123\");\n</code></pre>\n" }, { "answer_id": 216892, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 2, "selected": false, "text": "<p>I don't mean to be unkind. But when you propose a change to a well-established idiom, it undermines confidence if your sample code isn't right.</p>\n\n<p>Your first example should either be:</p>\n\n<pre><code>something result;\nif (something.TryParse(val, out result))\n{\n DoSomething(result);\n}\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>bool result;\nif (bool.TryParse(value, out result))\n{\n DoSomething(result);\n}\n</code></pre>\n\n<p>Your second example should either be:</p>\n\n<pre><code>Nullable&lt;something&gt; result = something.TryParse2(val);\nif(result.HasValue)\n{\n DoSomething(result.Value);\n}\n</code></pre>\n\n<p>or:</p>\n\n<pre><code>bool? result = bool.TryParse2(val);\nif (result.HasValue)\n{\n DoSomething(result);\n}\n</code></pre>\n\n<p>If I <em>were</em> going to implement an extension method for each value type that did what your <code>TryParse2</code> seems to do, I wouldn't call it <code>TryParse2</code>. Right now, if a method's name begins with <code>Try</code>, we expect it to return a <code>bool</code> indicating whether or not it succeeded or failed. Creating this new method creates a world where that expectation is no longer valid. And before you dismiss this, think about what was going through your mind when you wrote example code that didn't work, and why you were so sure that <code>result</code> needed to be a <code>bool</code>.</p>\n\n<p>The other thing about your proposal is that it seems to be trying to solve the wrong problem. If I found myself writing a lot of <code>TryParse</code> blocks, the first question I'd ask isn't \"How can I do this in fewer lines of code?\" I'd ask, \"Why do I have parsing code scattered throughout my application?\" My first instinct would be to come up with a higher level of abstraction for what I'm really trying to do when I'm duplicating all of that <code>TryParse</code> code.</p>\n" }, { "answer_id": 217661, "author": "Jay Bazuzi", "author_id": 5314, "author_profile": "https://Stackoverflow.com/users/5314", "pm_score": 0, "selected": false, "text": "<p>I find both examples to be clunky. </p>\n\n<p>I'd choose the <code>TryParse</code> because it's an idiom that already exists in the .NET Framework.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216278", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16526/" ]
Out style: ``` bool result; if(something.TryParse(val, out result)) { DoSomething(result); } ``` Nullable style: ``` bool? result = something.TryParse2(val); if(result.HasValue) { DoSomething(result.Value); } ```
TryParse(val, out result) is a idiom established by the .NET framework in int.TryParse, DateTime.TryParse, etc. It is likely that people that read the code will be familiar with this idiom, so you should stick to it, unless you find a very good reason not to.
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": 216298, "author": "Simon", "author_id": 24039, "author_profile": "https://Stackoverflow.com/users/24039", "pm_score": 1, "selected": false, "text": "<p><a href=\"http://mathworld.wolfram.com/RotationMatrix.html\" rel=\"nofollow noreferrer\">This</a> should do you</p>\n" }, { "answer_id": 216319, "author": "House MD", "author_id": 29163, "author_profile": "https://Stackoverflow.com/users/29163", "pm_score": 1, "selected": true, "text": "<p><a href=\"https://stackoverflow.com/questions/193918/what-is-the-easiest-way-to-align-the-z-axis-with-a-vector\">Dupe.</a></p>\n\n<blockquote>\n <p>The question there involves getting a rotation to a certain axis, whereas I'm concerned with getting a rotation matrix.</p>\n</blockquote>\n\n<p>Gee, I wonder if you could turn <a href=\"http://www.google.com/search?q=angle+axis+rotation+to+matrix\" rel=\"nofollow noreferrer\">convert one to the other</a>?</p>\n\n<p>BTW, your current solution of picking an arbitrary y axis and then reorthogonalising should work fine; it looks bugged though, or at least badly written. '<code>z_vec</code>' is not a good variable-name for the y-axis. What's with the 'z,x,y' ordering, anyway?</p>\n\n<p>If it still doesn't work, try making random changes until it does - transpose the matrix, negate vectors until you have an even number of sign errors, that kind of thing.</p>\n\n<p>Also your tone of voice comes across as sort-of rude, given that you're asking strangers to spend their time helping you.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216294", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23845/" ]
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; I am attempting to render a velocity vector line from a point. Drawing the line isn't difficult: just insert a line with length `velocity.length` 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. 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 `<x, y, z>`, what's the matrix I need? **Edit 1:** Look; if you don't understand the question, you probably won't be able to give me an answer. Here is what I currently have: ``` 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); ``` based off of [this article](http://www.gamedev.net/reference/articles/article665.asp). 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. **Edit 2:** Apologies about the rude wording of my comments. So it looks like there were a combination of two errors; one of which House MD pointed out (really bad naming of variables: `vec_z` was actually `vec_y`, 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: ``` 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(); ```
[Dupe.](https://stackoverflow.com/questions/193918/what-is-the-easiest-way-to-align-the-z-axis-with-a-vector) > > The question there involves getting a rotation to a certain axis, whereas I'm concerned with getting a rotation matrix. > > > Gee, I wonder if you could turn [convert one to the other](http://www.google.com/search?q=angle+axis+rotation+to+matrix)? BTW, your current solution of picking an arbitrary y axis and then reorthogonalising should work fine; it looks bugged though, or at least badly written. '`z_vec`' is not a good variable-name for the y-axis. What's with the 'z,x,y' ordering, anyway? If it still doesn't work, try making random changes until it does - transpose the matrix, negate vectors until you have an even number of sign errors, that kind of thing. Also your tone of voice comes across as sort-of rude, given that you're asking strangers to spend their time helping you.
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": 216337, "author": "Tom", "author_id": 22850, "author_profile": "https://Stackoverflow.com/users/22850", "pm_score": 3, "selected": false, "text": "<p>Use the javax.jnlp.ServiceManager to retrieve a webstart service.\nIf it is availabe, you are running under Webstart.</p>\n\n<p>See <a href=\"http://download.java.net/jdk7/docs/jre/api/javaws/jnlp/index.html\" rel=\"noreferrer\">http://download.java.net/jdk7/docs/jre/api/javaws/jnlp/index.html</a></p>\n" }, { "answer_id": 216412, "author": "Oleg Barshay", "author_id": 2043539, "author_profile": "https://Stackoverflow.com/users/2043539", "pm_score": 2, "selected": false, "text": "<p>As you mentioned, checking the System property as follows is probably the cleanest way:</p>\n\n<pre><code>private boolean isRunningJavaWebStart() {\n return System.getProperty(\"javawebstart.version\", null) != null;\n}\n</code></pre>\n\n<p>In a production system I have used the above technique for years.</p>\n\n<p>You can also try to check to see if there are any properties that start with \"jnlpx.\" but none of those are really \"guaranteed\" to be there either as far as I know. </p>\n\n<p>An alternative could be to attempt to instantiate the DownloadService us suggested by Tom:</p>\n\n<pre><code>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</code></pre>\n\n<p>Of course that does have the downside of coupling your code to that API. </p>\n" }, { "answer_id": 216436, "author": "Paul Whelan", "author_id": 3050, "author_profile": "https://Stackoverflow.com/users/3050", "pm_score": 2, "selected": false, "text": "<p>I have no real experience with Java web start other than looking at it a few years back.</p>\n\n<p>How about start your application with a parameter that you define than you set when the app is started via Java web start.</p>\n\n<p>If you want to pass in arguments to your app, you have to add them to the start-up file (aka JNLP descriptor) using or elements.</p>\n\n<p>Then check to see if these properties are set. </p>\n\n<p>Again this is a suggestion I have not coded for JWS and it may not be this easy.</p>\n" }, { "answer_id": 16200769, "author": "jla", "author_id": 101151, "author_profile": "https://Stackoverflow.com/users/101151", "pm_score": 5, "selected": true, "text": "<p>When your code is launched via javaws, javaws.jar is loaded and the JNLP API classes that you don't want to depend on are available. Instead of testing for a system property that is not guaranteed to exist, you could instead see if a JNLP API class exists:</p>\n\n<pre><code>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</code></pre>\n\n<p>This also avoids needing to include javaws.jar on your class path when compiling.</p>\n\n<p>Alternatively you could switch to compiling with javaws.jar and catching NoClassDefFoundError instead:</p>\n\n<pre><code>private boolean isRunningJavaWebStart() {\n try {\n ServiceManager.getServiceNames();\n return ds != null;\n } catch (NoClassDefFoundError e) {\n return false;\n }\n}\n</code></pre>\n\n<p>Using ServiceManager.lookup(String) and UnavailableServiceException is trouble because both are part of the JNLP API. The ServiceManager.getServiceNames() is not documented to throw. We are specifically calling this code to check for a NoClassDefFoundError.</p>\n" }, { "answer_id": 31312271, "author": "gouessej", "author_id": 458157, "author_profile": "https://Stackoverflow.com/users/458157", "pm_score": 0, "selected": false, "text": "<p>You can check whether the current classloader is an instance of com.sun.jnlp.JNLPClassLoader (Java plugin 1) or sun.plugin2.applet.JNLP2ClassLoader (Java plugin 2). Despite the \"applet\" package, an applet using JNLP with the Java plugin 2 uses another classloader, sun.plugin2.applet.Applet2ClassLoader. It works with OpenJDK too.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216315", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18187/" ]
As it was made clear in my [recent question](https://stackoverflow.com/questions/212009/do-i-have-to-explicitly-call-systemexit-in-a-webstart-application), Swing applications need to explicitly call System.exit() when they are ran using the Sun Webstart launcher (at least as of Java SE 6). 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. Are there any better ways (preferably ones that do not ceate a dependency on the the webstart API?)
When your code is launched via javaws, javaws.jar is loaded and the JNLP API classes that you don't want to depend on are available. Instead of testing for a system property that is not guaranteed to exist, you could instead see if a JNLP API class exists: ``` private boolean isRunningJavaWebStart() { boolean hasJNLP = false; try { Class.forName("javax.jnlp.ServiceManager"); hasJNLP = true; } catch (ClassNotFoundException ex) { hasJNLP = false; } return hasJNLP; } ``` This also avoids needing to include javaws.jar on your class path when compiling. Alternatively you could switch to compiling with javaws.jar and catching NoClassDefFoundError instead: ``` private boolean isRunningJavaWebStart() { try { ServiceManager.getServiceNames(); return ds != null; } catch (NoClassDefFoundError e) { return false; } } ``` Using ServiceManager.lookup(String) and UnavailableServiceException is trouble because both are part of the JNLP API. The ServiceManager.getServiceNames() is not documented to throw. We are specifically calling this code to check for a NoClassDefFoundError.
216,324
<p>I'm creating a site where the user unfortunately has to provide a regex to be used in a MySQL WHERE clause. And of course I have to validate the user input to prevent SQL injection. The site is made in PHP, and I use the following regex to check my regex:</p> <pre><code>/^([^\\\\\']|\\\.)*$/ </code></pre> <p>This is double-escaped because of PHP's way of handling regexes. The way it's supposed to work is to only match safe regexps, without unescaped single quotes. But being mostly self-taught, I'd like to know if this is a safe way of doing it.</p>
[ { "answer_id": 216336, "author": "REA_ANDREW", "author_id": 67959, "author_profile": "https://Stackoverflow.com/users/67959", "pm_score": -1, "selected": false, "text": "<p>If it is anly for the purposes of display this reg expression then most programs simply Html Encode the value and store in the DB and then the Decode on the way out. Again only for Display purposes though, if you need to use the reg exp that is submitted this won't work. </p>\n\n<p>Also know there is a method where the person intent on injecting writes out there SQL, Converts it to varbinary and submits the exec command with the base 64 representation of the query which I have been hit with in the past.</p>\n" }, { "answer_id": 216339, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "<p>You should just pass the string through <a href=\"http://www.php.net/mysql_escape_string\" rel=\"nofollow noreferrer\">mysql_escape_string</a> or <a href=\"http://www.php.net/mysql_real_escape_string\" rel=\"nofollow noreferrer\">mysql_real_escape_string</a>.</p>\n\n<p>I'd be wary of accepting any old regex though - some of them can run for a long time and will tie up your DB server.</p>\n\n<p>From <a href=\"http://us2.php.net/manual/en/regexp.reference.php\" rel=\"nofollow noreferrer\">Pattern Syntax</a>:</p>\n\n<blockquote>\n <p>Beware of patterns that contain nested\n indefinite repeats. These can take a\n long time to run when applied to a\n string that does not match. Consider\n the pattern fragment (a+)*</p>\n \n <p>This can match \"aaaa\" in 33 different\n ways, and this number increases very\n rapidly as the string gets longer.</p>\n</blockquote>\n" }, { "answer_id": 216457, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 3, "selected": false, "text": "<p>If you use prepared statements, SQL injection will be impossible. You should always use prepared statements.</p>\n\n<p>Roborg makes an excellent point though about expensive regexes.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216324", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29373/" ]
I'm creating a site where the user unfortunately has to provide a regex to be used in a MySQL WHERE clause. And of course I have to validate the user input to prevent SQL injection. The site is made in PHP, and I use the following regex to check my regex: ``` /^([^\\\\\']|\\\.)*$/ ``` This is double-escaped because of PHP's way of handling regexes. The way it's supposed to work is to only match safe regexps, without unescaped single quotes. But being mostly self-taught, I'd like to know if this is a safe way of doing it.
If you use prepared statements, SQL injection will be impossible. You should always use prepared statements. Roborg makes an excellent point though about expensive regexes.
216,329
<p>In a PHP project I'm working on we need to create some DAL extensions to support multiple database platforms. The main pitfall we have with this is that different platforms have different syntaxes - notable MySQL and MSSQL are quite different.</p> <h2>What would be the best solution to this?</h2> <p>Here are a couple we've discussed:</p> <p><strong>Class-based SQL building</strong></p> <p>This would involve creating a class that allows you to build SQL querys bit-by-bit. For example:</p> <pre><code>$stmt = new SQL_Stmt('mysql'); $stmt-&gt;set_type('select'); $stmt-&gt;set_columns('*'); $stmt-&gt;set_where(array('id' =&gt; 4)); $stmt-&gt;set_order('id', 'desc'); $stmt-&gt;set_limit(0, 30); $stmt-&gt;exec(); </code></pre> <p>It does involve quite a lot of lines for a single query though.</p> <p><strong>SQL syntax reformatting</strong></p> <p>This option is much cleaner - it would read SQL code and reformat it based on the input and output languages. I can see this being a much slower solution as far as parsing goes however.</p>
[ { "answer_id": 216336, "author": "REA_ANDREW", "author_id": 67959, "author_profile": "https://Stackoverflow.com/users/67959", "pm_score": -1, "selected": false, "text": "<p>If it is anly for the purposes of display this reg expression then most programs simply Html Encode the value and store in the DB and then the Decode on the way out. Again only for Display purposes though, if you need to use the reg exp that is submitted this won't work. </p>\n\n<p>Also know there is a method where the person intent on injecting writes out there SQL, Converts it to varbinary and submits the exec command with the base 64 representation of the query which I have been hit with in the past.</p>\n" }, { "answer_id": 216339, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "<p>You should just pass the string through <a href=\"http://www.php.net/mysql_escape_string\" rel=\"nofollow noreferrer\">mysql_escape_string</a> or <a href=\"http://www.php.net/mysql_real_escape_string\" rel=\"nofollow noreferrer\">mysql_real_escape_string</a>.</p>\n\n<p>I'd be wary of accepting any old regex though - some of them can run for a long time and will tie up your DB server.</p>\n\n<p>From <a href=\"http://us2.php.net/manual/en/regexp.reference.php\" rel=\"nofollow noreferrer\">Pattern Syntax</a>:</p>\n\n<blockquote>\n <p>Beware of patterns that contain nested\n indefinite repeats. These can take a\n long time to run when applied to a\n string that does not match. Consider\n the pattern fragment (a+)*</p>\n \n <p>This can match \"aaaa\" in 33 different\n ways, and this number increases very\n rapidly as the string gets longer.</p>\n</blockquote>\n" }, { "answer_id": 216457, "author": "Neall", "author_id": 619, "author_profile": "https://Stackoverflow.com/users/619", "pm_score": 3, "selected": false, "text": "<p>If you use prepared statements, SQL injection will be impossible. You should always use prepared statements.</p>\n\n<p>Roborg makes an excellent point though about expensive regexes.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216329", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2025/" ]
In a PHP project I'm working on we need to create some DAL extensions to support multiple database platforms. The main pitfall we have with this is that different platforms have different syntaxes - notable MySQL and MSSQL are quite different. What would be the best solution to this? ---------------------------------------- Here are a couple we've discussed: **Class-based SQL building** This would involve creating a class that allows you to build SQL querys bit-by-bit. For example: ``` $stmt = new SQL_Stmt('mysql'); $stmt->set_type('select'); $stmt->set_columns('*'); $stmt->set_where(array('id' => 4)); $stmt->set_order('id', 'desc'); $stmt->set_limit(0, 30); $stmt->exec(); ``` It does involve quite a lot of lines for a single query though. **SQL syntax reformatting** This option is much cleaner - it would read SQL code and reformat it based on the input and output languages. I can see this being a much slower solution as far as parsing goes however.
If you use prepared statements, SQL injection will be impossible. You should always use prepared statements. Roborg makes an excellent point though about expensive regexes.
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": 216502, "author": "LBugnion", "author_id": 12233, "author_profile": "https://Stackoverflow.com/users/12233", "pm_score": 0, "selected": false, "text": "<p>In my experience, Intellisense in ASPX pages is flaky to say the least. I experienced the same as you described, as well as other unwanted effects. In some cases, Intellisense stops working at all.</p>\n" }, { "answer_id": 216506, "author": "Nick Berardi", "author_id": 17, "author_profile": "https://Stackoverflow.com/users/17", "pm_score": 0, "selected": false, "text": "<p>Until MVC there hasn't been a strong need to ASPX page intellisense for code. I expect the VS team to work on this more with 2010, but until then you issues are normal at least from what I have experienced.</p>\n" }, { "answer_id": 216618, "author": "Paco", "author_id": 13376, "author_profile": "https://Stackoverflow.com/users/13376", "pm_score": 1, "selected": false, "text": "<p>You migth forget the controller type generic parameter:</p>\n\n<pre><code>Html.Actionlink&lt;YourControllerType&gt;(x=&gt;x.\n</code></pre>\n\n<p>The controller type is needed here because views are not coupled to the controller. \nViews are coupled to the model only.</p>\n" }, { "answer_id": 489801, "author": "Haacked", "author_id": 598, "author_profile": "https://Stackoverflow.com/users/598", "pm_score": 0, "selected": false, "text": "<p>ASP.NET MVC does not contain a strongly typed action link method. Where did you get the method?</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216333", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29376/" ]
When i use any of the other strongly typed HTML helpers after typing for example ``` Html.Actionlink<HomeController>(x=>x. ``` 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. Are other people experiencing these issues? **Update** This issue is still in ASP.NET MVC RC
You migth forget the controller type generic parameter: ``` Html.Actionlink<YourControllerType>(x=>x. ``` The controller type is needed here because views are not coupled to the controller. Views are coupled to the model only.
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": "<p>If this is a common use-case for your function, it would perhaps be a good idea to make the function iterate through the columns automatically if the input is not a vector.</p>\n\n<p>This doesn't exactly solve your problem but it would simplify the functions' usage. In that case, the output should be a matrix, too.</p>\n\n<p>You can also transform the matrix to one long column by using <code>m(:,:) = m(:)</code>. However, it depends on your function if this would make sense.</p>\n" }, { "answer_id": 216504, "author": "Hallgrim", "author_id": 15454, "author_profile": "https://Stackoverflow.com/users/15454", "pm_score": 2, "selected": false, "text": "<p>Maybe you could always transform the matrix with the ' operator and then transform the result back.</p>\n\n<pre><code>smoothed = smooth(input', 9)';\n</code></pre>\n\n<p>That at least works with the fft function.</p>\n" }, { "answer_id": 230817, "author": "Tim Whitcomb", "author_id": 24895, "author_profile": "https://Stackoverflow.com/users/24895", "pm_score": 3, "selected": false, "text": "<p>The MATLAB \"for\" statement actually loops over the columns of whatever's supplied - normally, this just results in a sequence of scalars since the vector passed into for (as in your example above) is a row vector. This means that you can rewrite the above code like this:</p>\n\n<pre><code>function result = map_column(m, func)\n result = [];\n for m_col = m\n result = horzcat(result, func(m_col));\n end\n</code></pre>\n\n<p>If func does not return a column vector, then you can add something like</p>\n\n<pre><code>f = func(m_col);\nresult = horzcat(result, f(:));\n</code></pre>\n\n<p>to force it into a column.</p>\n" }, { "answer_id": 275709, "author": "Mr Fooz", "author_id": 25050, "author_profile": "https://Stackoverflow.com/users/25050", "pm_score": 3, "selected": true, "text": "<p>Your solution is fine.</p>\n\n<p>Note that horizcat exacts a substantial performance penalty for large matrices. It makes the code be O(N^2) instead of O(N). For a 100x10,000 matrix, your implementation takes 2.6s on my machine, the horizcat one takes 64.5s. For a 100x5000 matrix, the horizcat implementation takes 15.7s.</p>\n\n<p>If you wanted, you could generalize your function a little and make it be able to iterate over the final dimension or even over arbitrary dimensions (not just columns). </p>\n" }, { "answer_id": 357025, "author": "Jason S", "author_id": 44330, "author_profile": "https://Stackoverflow.com/users/44330", "pm_score": 1, "selected": false, "text": "<p>Don't forget to preallocate the result matrix if you are dealing with large matrices. Otherwise your CPU will spend lots of cycles repeatedly re-allocating the matrix every time it adds a new row/column.</p>\n" }, { "answer_id": 739400, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>A way to cause an implicit loop across the columns of a matrix is to use cellfun. That is, you must first convert the matrix to a cell array, each cell will hold one column. Then call cellfun. For example:</p>\n\n<pre><code>A = randn(10,5);\n</code></pre>\n\n<p>See that here I've computed the standard deviation for each column.</p>\n\n<pre><code>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</code></pre>\n\n<p>Of course, many functions in MATLAB are already set up to work on rows or columns of an array as the user indicates. This is true of std of course, but this is a convenient way to test that <code>cellfun</code> worked successfully.</p>\n\n<pre><code>std(A,[],1)\n\nans =\n 0.78681 1.1473 0.89789 0.66635 1.3482\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216341", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3829/" ]
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 `smooth(matrix)`). I'm sure there must be a more idiomatic way to do this, but I can't find it, so I've defined a `map_column` function: ``` function result = map_column(m, func) result = m; for col = 1:size(m,2) result(:,col) = func(m(:,col)); end end ``` which I can call with: ``` smoothed = map_column(input, @(c) (smooth(c, 9))); ``` Is there anything wrong with this code? How could I improve it?
Your solution is fine. Note that horizcat exacts a substantial performance penalty for large matrices. It makes the code be O(N^2) instead of O(N). For a 100x10,000 matrix, your implementation takes 2.6s on my machine, the horizcat one takes 64.5s. For a 100x5000 matrix, the horizcat implementation takes 15.7s. If you wanted, you could generalize your function a little and make it be able to iterate over the final dimension or even over arbitrary dimensions (not just columns).
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": 216451, "author": "mohammedn", "author_id": 29268, "author_profile": "https://Stackoverflow.com/users/29268", "pm_score": 0, "selected": false, "text": "<p>I believe as long as it's a rendering code and it's in a \"View\" not in a controller, then putting it on code behind or inline won't matter. Just make sure that you don't write this piece of the rendering code in the Controllers actions (this way you will really violate the MVC pattern).</p>\n" }, { "answer_id": 216662, "author": "MichaelGG", "author_id": 27012, "author_profile": "https://Stackoverflow.com/users/27012", "pm_score": 0, "selected": false, "text": "<p>The codebehind is part of the View -- it's up to you if you want to put things in the ASPX directly or in the codebehind. MVC doesn't mean you have to code things all ugly in the ASPX :).</p>\n" }, { "answer_id": 216866, "author": "Panos", "author_id": 8049, "author_profile": "https://Stackoverflow.com/users/8049", "pm_score": 2, "selected": true, "text": "<p>I prefer not to use the code behind class in my views. This is not because it violates MVC by default, but because I found that the \"natural\" way (at least for me) is different. </p>\n\n<p>When I face complex HTML markup that relates to purely view concerns, I usually write an extension method for <code>HtmlHelper</code> class in order to hide the complexity. Thus I have extensions like <code>Html.MoneyTextBox()</code>, <code>Html.OptionGroup()</code> and <code>Html.Pager&lt;T&gt;</code>. </p>\n\n<p>In other cases when complex conditions arise, usually I missed something from the controller. For example, all issues related to the visibility, readonly or enabled of elements usually stem from something that the controller can provide. In that case instead of passing the model to the view, I create a view model which encapsulates the model and the additional info that the controller can provide in order to simplify the HTML markup. A typical example of view model is the following:</p>\n\n<pre><code>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</code></pre>\n\n<p>That said, the code behind is part of the view, so you can use it freely, if it fits your needs better.</p>\n" }, { "answer_id": 217610, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 2, "selected": false, "text": "<p>It's not horrible to have conditionals in your view. I would keep them in the ASPX not the code behind. However, a conditional often indicates controlling behavior. Consider the following ASPX code:</p>\n\n<pre><code>&lt;%if (ViewData[\"something\"] == \"foo\") {%&gt;\n &lt;%=Html.ActionLink(\"Save\", \"Save\") %&gt; \n&lt;%}%&gt;\n&lt;%if (ViewData[\"somethingElse\"] == \"bar\") {%&gt;\n &lt;%=Html.ActionLink(\"Delete\", \"Delete\") %&gt; \n&lt;%}%&gt;\n</code></pre>\n\n<p>This set of conditionals represents controlling behavior that is being handled by the view -- i.e., in the wrong place. This behavior is not unit testable. Consider instead:</p>\n\n<pre><code>&lt;%foreach (var command in (IList&lt;ICommand&gt;)ViewData[\"commands\"]) {%&gt;\n &lt;%=Html.ActionLink(command) %&gt;\n&lt;%}%&gt;\n</code></pre>\n\n<p>In this example ActionLink is a custom extension of HtmlHelper that takes our own ICommand specification object. The controller action that renders this view populates ViewData[\"commands\"] based on various conditions. In other words, the controller does the controlling. In the unit tests for this action, we can test that the correct set of commands will be presented under various conditions.</p>\n\n<p>At first this might seem like a hassle compared with quickly throwing a few IFs into the view. The question you have to ask yourself is, \"Does this IF represent controlling behavior, and do I want to ensure does not at some point break?\"</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216391", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29376/" ]
I was just wondering, if by moving complex if else statements and the resulting html markup to the code behind violates some 'MVC' law? It seems like a great option when faced with inline if else statements that can become extremely unreadable.
I prefer not to use the code behind class in my views. This is not because it violates MVC by default, but because I found that the "natural" way (at least for me) is different. When I face complex HTML markup that relates to purely view concerns, I usually write an extension method for `HtmlHelper` class in order to hide the complexity. Thus I have extensions like `Html.MoneyTextBox()`, `Html.OptionGroup()` and `Html.Pager<T>`. In other cases when complex conditions arise, usually I missed something from the controller. For example, all issues related to the visibility, readonly or enabled of elements usually stem from something that the controller can provide. In that case instead of passing the model to the view, I create a view model which encapsulates the model and the additional info that the controller can provide in order to simplify the HTML markup. A typical example of view model is the following: ``` public class CustomerInfo { public Customer Customer { get; set; } public bool IsEditable { get; set; } // e.g. based on current user/role public bool NeedFullAddress { get; set; } // e.g. based on requested action public bool IsEligibleForSomething { get; set; } // e.g. based on business rule } ``` That said, the code behind is part of the view, so you can use it freely, if it fits your needs better.
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": "<p>I've had that sometimes when trying to <code>print_r()</code> a self-referencing object - it gets into a loop and runs out of memory. Possibly that's what's happening to you.</p>\n\n<p>Try increasing the memory limit (<code>ini_set('memory_limit', '256M');</code>) and see if that fixes it.</p>\n\n<p>Edit: I don't think there's an actual fix for this - it's PHP's internal <code>var_dump</code> / <code>print_r</code> that don't limit depth on recursion (or don't do it properly, at least). If you install the <a href=\"http://xdebug.org/\" rel=\"nofollow noreferrer\">XDebug</a> extension, this can replace the built-in <code>var_dump</code> with a version that handles recursion much better.</p>\n" }, { "answer_id": 3799164, "author": "Julien", "author_id": 457589, "author_profile": "https://Stackoverflow.com/users/457589", "pm_score": 3, "selected": false, "text": "<p>Use the <code>toArray</code> method of the <code>Doctrine_Record</code> class</p>\n\n<pre><code>var_dump($doctrine_record-&gt;toArray());\n</code></pre>\n\n<p>will only display the DB fields and avoid dumping the complete Doctrine internals (which contains self reference/recursion btw)</p>\n" }, { "answer_id": 8646048, "author": "Mariano Argañaraz", "author_id": 1117787, "author_profile": "https://Stackoverflow.com/users/1117787", "pm_score": 6, "selected": false, "text": "<p>Lazy load proxies always contain an instance of Doctrine’s EntityManager and all its dependencies.</p>\n\n<p>Therefore a <code>var_dump</code> will possibly dump a very large recursive structure which is impossible to render and read. You have to use <code>\\Doctrine\\Common\\Util\\Debug::dump()</code> to restrict the dumping to a human readable level. Note that the default depth for this function is set to 2 (it's the second parameter) </p>\n" }, { "answer_id": 8797559, "author": "E Ciotti", "author_id": 415032, "author_profile": "https://Stackoverflow.com/users/415032", "pm_score": 0, "selected": false, "text": "<p>You can use toArray if you are sure the object is an instance of Doctrine_Collection.\nXdebug does not help with doctrine records.</p>\n\n<p>The way I suggest is implementing a custom recursive function to print object, that use Doctrine_Record::toArray() when neeeded</p>\n\n<pre><code>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</code></pre>\n\n<p>Some recursive function to debug with max nesting levels are here</p>\n\n<p><a href=\"http://php.net/manual/en/function.var-dump.php\" rel=\"nofollow\">http://php.net/manual/en/function.var-dump.php</a></p>\n\n<p>Look at the comments, look for \"recursion\"</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216409", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
I have a very strange problem, when I try to `var_dump` (or `print_r`) a Doctrine Object, my Apache responses with an empty blank page (200 OK header). I can `var_dump` a normal php var like: ``` $dummy = array("a" => 1, "b" =>2); ``` And it works fine. But I can't with any object from any Doctrine class, (like a result from `$connection->query()`, or an instance of a class from my object model with Doctrine). Anybody knows why this happens?
I've had that sometimes when trying to `print_r()` a self-referencing object - it gets into a loop and runs out of memory. Possibly that's what's happening to you. Try increasing the memory limit (`ini_set('memory_limit', '256M');`) and see if that fixes it. Edit: I don't think there's an actual fix for this - it's PHP's internal `var_dump` / `print_r` that don't limit depth on recursion (or don't do it properly, at least). If you install the [XDebug](http://xdebug.org/) extension, this can replace the built-in `var_dump` with a version that handles recursion much better.
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": 216435, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 0, "selected": false, "text": "<p>No <strike>- and if you think about it, it can't work. Between you checking what it's going to do and actually doing it, another process could allocate memory.</strike>\nIn a multi-threaded application this can't work. Between you checking what it's going to do and actually doing it, another thread could allocate memory.</p>\n\n<p>If you're worried about this sort of thing, it might be time to look at the data structures you're using to see if you can fix the problem there. Depending on how these strings are constructed, you can do so quite efficiently with a well designed buffer.</p>\n" }, { "answer_id": 216442, "author": "Ilya", "author_id": 6807, "author_profile": "https://Stackoverflow.com/users/6807", "pm_score": 0, "selected": false, "text": "<p>I don't think it's possible in cross platform way.\n<a href=\"http://www.google.com/codesearch?hl=en&amp;q=show:4f2oPw-25m8:NZvFhxd9P74:55xbVtXJ6eg&amp;sa=N&amp;ct=rd&amp;cs_p=http://freshmeat.net/redir/uclibc/20616/url_bz2/uClibc-0.9.28.1.tar.bz2&amp;cs_f=uClibc-0.9.29/libc/stdlib/malloc/realloc.c\" rel=\"nofollow noreferrer\">Here</a> is the code for ulibc implementation that might give you a clue how to do itin platform dependent way, actually it's better to find glibc source but this one was on top of google search :) </p>\n" }, { "answer_id": 216462, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 4, "selected": true, "text": "<p><code>realloc()</code>'s behavior is likely dependent on its specific implementation. And basing your code on that would be a terrible hack which, to say the least, violates encapsulation.</p>\n\n<p>A better solution for your specific example is:</p>\n\n<ol>\n<li>Find the size of the current buffer\n\n<ul>\n<li>Allocate a new buffer (with <code>malloc()</code>), greater than the previous one</li>\n<li>Copy the prefix you want to the new buffer</li>\n<li>Copy the string in the previous buffer to the new buffer, starting after the prefix</li>\n<li>Release the previous buffer</li>\n</ul></li>\n</ol>\n" }, { "answer_id": 216491, "author": "Jouni K. Seppänen", "author_id": 26575, "author_profile": "https://Stackoverflow.com/users/26575", "pm_score": 0, "selected": false, "text": "<p>If <a href=\"http://www.gnu.org/software/libc/manual/html_node/Obstacks.html#Obstacks\" rel=\"nofollow noreferrer\">obstacks</a> are a good match for your memory allocation needs, you can use their <a href=\"http://www.gnu.org/software/libc/manual/html_node/Extra-Fast-Growing.html#Extra-Fast-Growing\" rel=\"nofollow noreferrer\">fast growing</a> functionality. Obstacks are a feature of glibc, but they are also available in the <a href=\"http://gcc.gnu.org/onlinedocs/libiberty/\" rel=\"nofollow noreferrer\">libiberty</a> library, which is fairly portable.</p>\n" }, { "answer_id": 216492, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "<p>As noted in the comments, case 3 in the question (no memory) is wrong; <code>realloc()</code> will return NULL if there is no memory available [question now fixed].</p>\n\n<p>Steve McConnell in 'Code Complete' points out that if you save the return value from <code>realloc()</code> in the only copy of the original pointer when <code>realloc()</code> fails, you've just leaked memory. That is:</p>\n\n<pre><code>void *ptr = malloc(1024);\n...\nif ((ptr = realloc(ptr, 2048)) == 0)\n{\n /* Oops - cannot free original memory allocation any more! */\n}\n</code></pre>\n\n<p>Different implementations of realloc() will behave differently. The only safe thing to assume is that the data will <em>always</em> be moved - that you will always get a new address when you realloc() memory.</p>\n\n<p>As someone else pointed out, if you are concerned about this, maybe it is time to look at your algorithms.</p>\n" }, { "answer_id": 242328, "author": "Artelius", "author_id": 31945, "author_profile": "https://Stackoverflow.com/users/31945", "pm_score": 1, "selected": false, "text": "<p>Would storing your string backwards help?</p>\n\n<p>Otherwise...\njust malloc() more space than you need, and when you run out of room, copy to a new buffer. A simple technique is to double the space each time; this works pretty well because the larger the string (i.e. the more time copying to a new buffer will takes) the less often it needs to occur.</p>\n\n<p>Using this method you can also right-justify your string in the buffer, so it's easy to add characters to the start.</p>\n" }, { "answer_id": 242362, "author": "Jacob Krall", "author_id": 3140, "author_profile": "https://Stackoverflow.com/users/3140", "pm_score": 0, "selected": false, "text": "<p>Why not keep some empty buffer space in the left of the string, like so:</p>\n\n<pre><code>char* buf = malloc(1024);\nchar* start = buf + 1024 - 3;\nstart[0]='t';\nstart[1]='o';\nstart[2]='\\0';\n</code></pre>\n\n<p>To add \"on\" to the beginning of your string to make it \"onto\\0\":</p>\n\n<pre><code>start-=2;\nif(start &lt; buf) \n DO_MEMORY_STUFF(start, buf);//time to reallocate!\nstart[0]='o';\nstart[1]='n';\n</code></pre>\n\n<p>This way, you won't have to keep copying your buffer every single time you want to do an insertion at the beginning.</p>\n\n<p>If you have to do insertions at both the beginning and end, just have some space allocated at both ends; insertions in the middle will still need you to shuffle elements around, obviously.</p>\n" }, { "answer_id": 3878388, "author": "vy32", "author_id": 51167, "author_profile": "https://Stackoverflow.com/users/51167", "pm_score": 0, "selected": false, "text": "<p>A better approach is to use a linked list. Have each of your data objects allocated on a page, and allocate another page and have a link to it, either from the previous page or from an index page. This way you know when the next alloc fails, and you never need to copy memory.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2289/" ]
As I understand it, when asked to reserve a larger block of memory, the realloc() function will do one of three different things: ```` 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 ```` 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. Is it possible to determine what realloc() will do? If so, is it possible to achieve in a cross-platform way?
`realloc()`'s behavior is likely dependent on its specific implementation. And basing your code on that would be a terrible hack which, to say the least, violates encapsulation. A better solution for your specific example is: 1. Find the size of the current buffer * Allocate a new buffer (with `malloc()`), greater than the previous one * Copy the prefix you want to the new buffer * Copy the string in the previous buffer to the new buffer, starting after the prefix * Release the previous buffer
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": 216464, "author": "PiedPiper", "author_id": 19315, "author_profile": "https://Stackoverflow.com/users/19315", "pm_score": 4, "selected": true, "text": "<p>the U before _ZN3lib-namespace12GetStatusStrEi in the nm output shows that the symbol is <strong>undefined</strong> in the library.</p>\n\n<p>Maybe it's defined in the wrong namespace: it looks like you're calling it in lib-namepace but you might be defining it in another.</p>\n" }, { "answer_id": 216488, "author": "Christian.K", "author_id": 21567, "author_profile": "https://Stackoverflow.com/users/21567", "pm_score": 2, "selected": false, "text": "<p>It's been a while, but if you specify a lib with the -l option, then don't you have the skip the lib prefix?</p>\n\n<p>(I changed the name from \"lib-in-question.so\" to \"libfoobar.so\" for easier reading for the example below)</p>\n\n<pre><code>g++ -fPIC -Wall -O3 -L~/project/lib/release -lfoobar\n</code></pre>\n\n<p>or</p>\n\n<pre><code>g++ -fPIC -Wall -O3 ~/project/lib/release/libfoobar.so\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16429/" ]
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: > > app-source-file.cpp:(.text+0x2fdb): undefined reference to `lib-namespace::GetStatusStr(int)' > > > 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. I am using Ubuntu 8.04 (Hardy), and it is up to date with the latest Ubuntu packages. The command to link the library is (with other libraries removed): ``` g++ -fPIC -Wall -O3 -shared -Wl,-soname,lib-in-question.so -o ~/project/lib/release/lib-in-question.so ``` The command to link the application is (with other libraries removed): ``` g++ -fPIC -Wall -O3 -L~/project/lib/release -llib-in-question -o ~/project/release/app-in-question ``` Finally, it appears (as best as I can tell) that the symbols in question are being exported properly: ``` nm -D ~/project/lib/release/lib-in-question.so | grep GetStatusStr --> U _ZN3lib-namespace12GetStatusStrEi ```
the U before \_ZN3lib-namespace12GetStatusStrEi in the nm output shows that the symbol is **undefined** in the library. Maybe it's defined in the wrong namespace: it looks like you're calling it in lib-namepace but you might be defining it in another.
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": "<p>Well, if you're using a simple script (where you don't use the \"def\" keyword), the variables you define will be stored in the binding and you can get at them like this:</p>\n\n<pre><code>foo = \"abc\"\nbar = \"def\"\n\nif (true) {\n baz = \"ghi\"\n this.binding.variables.each {k,v -&gt; println \"$k = $v\"}\n}\n</code></pre>\n\n<p>Prints:</p>\n\n<pre><code> foo = abc \n baz = ghi \n args = {} \n bar = def\n</code></pre>\n\n<p>I'm not aware of an easy way to enumerate through the variables defined with the \"def\" keyword, but I'll be watching this question with interest to see if someone else knows how.</p>\n" }, { "answer_id": 293149, "author": "Urs Reupke", "author_id": 25141, "author_profile": "https://Stackoverflow.com/users/25141", "pm_score": 2, "selected": false, "text": "<p>Actually, Ted's answer will also work for 'def'ed variables.</p>\n\n<pre>\ndef foo = \"abc\"\ndef bar = \"def\"\n\nif (true) {\n baz = \"ghi\"\n this.binding.variables.each {k,v -> println \"$k = $v\"}\n}\n</pre>\n\n<p>yields</p>\n\n<pre>\nbaz = ghi\n__ = [null, null, null]\nfoo = abc\n_ = null\nbar = def\n</pre>\n\n<p>I'm not sure what the _-variables signify, but I'm sure you can work around them.</p>\n" }, { "answer_id": 65493646, "author": "Amerousful", "author_id": 7512201, "author_profile": "https://Stackoverflow.com/users/7512201", "pm_score": 0, "selected": false, "text": "<p>Groovy Object contains method - <code>dump()</code>\n<a href=\"https://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Object.html\" rel=\"nofollow noreferrer\">https://docs.groovy-lang.org/latest/html/groovy-jdk/java/lang/Object.html</a></p>\n<pre><code>String dump()\nGenerates a detailed dump string of an object showing its class, hashCode and fields.\n</code></pre>\n<p>Example:</p>\n<pre><code>class MyClass {\n def foo = &quot;abc&quot;\n def bar = &quot;def&quot;\n}\n\n\nprintln(new MyClass().dump())\n</code></pre>\n<p>stdout: <code>&lt;MyClass@1fa268de foo=abc bar=def&gt;</code></p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216484", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2031/" ]
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?
Well, if you're using a simple script (where you don't use the "def" keyword), the variables you define will be stored in the binding and you can get at them like this: ``` foo = "abc" bar = "def" if (true) { baz = "ghi" this.binding.variables.each {k,v -> println "$k = $v"} } ``` Prints: ``` foo = abc baz = ghi args = {} bar = def ``` I'm not aware of an easy way to enumerate through the variables defined with the "def" keyword, but I'll be watching this question with interest to see if someone else knows how.
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": 216527, "author": "Christian C. Salvadó", "author_id": 5445, "author_profile": "https://Stackoverflow.com/users/5445", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://msdn.microsoft.com/en-us/vbasic/bb737922.aspx\" rel=\"noreferrer\">Here</a> you can find many examples about using aggregate functions and grouping, additionally I recommend you very much <a href=\"http://www.linqpad.net/\" rel=\"noreferrer\">LinqPad</a>, it's a great tool to test your queries on the fly and it's very good way to learn LINQ, it comes preloaded with 200 examples. </p>\n" }, { "answer_id": 216573, "author": "Herb Caudill", "author_id": 239663, "author_profile": "https://Stackoverflow.com/users/239663", "pm_score": 6, "selected": true, "text": "<h2>Answer</h2>\n<p>Here's the correct Linq to SQL equivalent</p>\n<pre><code>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</code></pre>\n<p>Thanks to @CMS for pointing me to <a href=\"http://www.linqpad.net/\" rel=\"noreferrer\">LinqPad</a> - what a great tool. You just point it to your database and you're off and running. Not only are hundreds of samples included, but you can run them against included live databases. I was able to arrive at the above query in just a few minutes starting from the provided samples.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216513", "https://Stackoverflow.com", "https://Stackoverflow.com/users/239663/" ]
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): ``` 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 ``` (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.) I'm imagining something like this as the Linq to SQL equivalent (**pseudo-code**) ``` From f As Firm In Db.Firms _ Order By f.Concessions.Sum(Area) ``` ... but that's not right. Can anyone point me in the right direction?
Answer ------ Here's the correct Linq to SQL equivalent ``` From c In Concessions _ Join f In Firms on f.FirmID equals c.FirmID _ Group by f.Title _ Into TotalArea = sum(c.OfficialArea) _ Order by TotalArea Descending _ Select Title, TotalArea ``` Thanks to @CMS for pointing me to [LinqPad](http://www.linqpad.net/) - what a great tool. You just point it to your database and you're off and running. Not only are hundreds of samples included, but you can run them against included live databases. I was able to arrive at the above query in just a few minutes starting from the provided samples.
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": 216537, "author": "yfeldblum", "author_id": 12349, "author_profile": "https://Stackoverflow.com/users/12349", "pm_score": 3, "selected": false, "text": "<p>The pure approach would be: Make everything an interface. As implementation details, you may optionally use any of various forms of composition or implementation-inheritance. Since these are implementation details, they don't matter to your public API, so you are free to choose whichever makes your life simplest.</p>\n" }, { "answer_id": 216545, "author": "Foredecker", "author_id": 18256, "author_profile": "https://Stackoverflow.com/users/18256", "pm_score": 7, "selected": true, "text": "<p>Mark, This is an interesting question. You will find as many opinions on this. I don't believe there is a 'right' answer. This is a great example of where a rigid heirarchial object design can really cause problems after a system is built.</p>\n\n<p>For example, lets say you went with the \"Customer\" and \"Staff\" classes. You deploy your system and everything is happy. A few weeks later, someone points out that they are both 'on staff' and a 'customer' and they are not getting customer emails. In this case, you have a lot of code changes to make (re-design, not re-factor).</p>\n\n<p>I believe it would be overly complex and difficult to maintain if you attempt to have a set of derived classes that implement all the permutations and combination of people and their roles. This is especially true given that the above example is very simple - in most real applications, things will be more complex.</p>\n\n<p>For your example here, I would go with \"Take another completely different approach\". I would implement the Person class and include in it a collection of \"roles\". Each person could have one or more roles such as \"Customer\", \"Staff\", and \"Vendor\".</p>\n\n<p>This will make it easier to add roles as new requirements are discovered. For example, you may simply have a base \"Role\" class, and derive new roles from them. </p>\n" }, { "answer_id": 216574, "author": "Jorge Villuendas Zapatero", "author_id": 27097, "author_profile": "https://Stackoverflow.com/users/27097", "pm_score": 4, "selected": false, "text": "<p>You may want to consider using the <a href=\"http://martinfowler.com/apsupp/accountability.pdf\" rel=\"noreferrer\">Party and Accountability patterns</a></p>\n\n<p>This way Person will have a collection of Accountabilities which may be of type Customer or Staff. </p>\n\n<p>The model will also be simpler if you add more relationship types later.</p>\n" }, { "answer_id": 216620, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>We study this problem at college last year, we were learning eiffel so we used multiple inheritance. Anyway Foredecker roles alternative seems to be flexible enough.</p>\n" }, { "answer_id": 216645, "author": "Paul Croarkin", "author_id": 18995, "author_profile": "https://Stackoverflow.com/users/18995", "pm_score": 2, "selected": false, "text": "<p>I would avoid the \"is\" check (\"instanceof\" in Java). One solution is to use a <a href=\"http://en.wikipedia.org/wiki/Decorator_pattern\" rel=\"nofollow noreferrer\">Decorator Pattern</a>. You could create an EmailablePerson that decorates Person where EmailablePerson uses composition to hold a private instance of a Person and delegates all non-email methods to the Person object.</p>\n" }, { "answer_id": 216652, "author": "vj01", "author_id": 378962, "author_profile": "https://Stackoverflow.com/users/378962", "pm_score": 1, "selected": false, "text": "<p>What's wrong in sending an email to a Customer who is a Staff member? If he is a customer, then he can be sent the email. Am I wrong in thinking so? \nAnd why should you take \"everyone\" as your email list? Woudlnt it be better to have a customer list since we are dealing with \"sendEmailToCustomer\" method and not \"sendEmailToEveryone\" method?\nEven if you want to use \"everyone\" list you cannot allow duplicates in that list.</p>\n\n<p>If none of these are achievable with a lot of redisgn, I will go with the first Foredecker answer and may be you should have some roles assigned to each person.</p>\n" }, { "answer_id": 216765, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 3, "selected": false, "text": "<p>Let me know if I understood Foredecker's answer correctly. Here's my code (in Python; sorry, I don't know C#). The only difference is I wouldn't notify something if a person \"is a customer\", I would do it if one of his role \"is interested in\" that thing.\nIs this flexible enough?</p>\n\n<pre><code># --------- 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</code></pre>\n" }, { "answer_id": 216772, "author": "fizzer", "author_id": 18167, "author_profile": "https://Stackoverflow.com/users/18167", "pm_score": 1, "selected": false, "text": "<p>Your classes are just data structures: none of them has any behaviour, just getters and setters. Inheritance is inappropriate here.</p>\n" }, { "answer_id": 217895, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>A Person is a human being, whereas a Customer is just a Role that a Person may adopt from time to time. Man and Woman would be candidates to inherit Person, but Customer is a different concept.</p>\n\n<p>The Liskov substitution principle says that we must be able to use derived classes where we have references to a base class, without knowing about it. Having Customer inherit Person would violate this. A Customer might perhaps also be a role played by an Organisation. </p>\n" }, { "answer_id": 3306729, "author": "Mike D", "author_id": 398822, "author_profile": "https://Stackoverflow.com/users/398822", "pm_score": 1, "selected": false, "text": "<p>Take another completely different approach: The problem with the class StaffCustomer is that your member of staff could start off as just staff and become a customer later on so you would need to delete them as staff and create a new instance of StaffCustomer class. Perhaps a simple boolean within Staff class of 'isCustomer' would allow our everyone list (presumably compiled from getting all customers and all staff from appropriate tables) to not get the staff member as it will know it has been included already as a customer.</p>\n" }, { "answer_id": 11800574, "author": "Bogdan", "author_id": 1574794, "author_profile": "https://Stackoverflow.com/users/1574794", "pm_score": 1, "selected": false, "text": "<p>Here's some more tips:\nFrom the category of “do not even think to do this” here are some bad examples of code encountered:</p>\n\n<p>Finder method returns Object</p>\n\n<p>Problem: Depending on the number of occurrences found the finder method returns a number representing the number of occurrences – or! If only one found returns the actual object.</p>\n\n<p>Don’t do this! This is one of the worst coding practices and it introduces ambiguity and messes the code in a way that when a different developer comes into play she or he will hate you for doing this.</p>\n\n<p>Solution: If there’s a need for such 2 functionalities: counting and fetching an instance do create 2 methods one which returns the count and one which returns the instance, but never a single method doing both ways.</p>\n\n<p>Problem: A derived bad practice is when a finder method returns either the one single occurrence found either an array of occurrences if more than one found. This lazy programming style is done alot by the programmers who do the previous one in general.</p>\n\n<p>Solution: Having this on my hands I would return an array of length 1(one) if only one occurrence is found and an array with length >1 if more occurrences found. Moreover, finding no occurrences at all would return null or an array of length 0 depending on the application.</p>\n\n<p>Programming to an interface and using covariant return types</p>\n\n<p>Problem: Programming to an interface and using covariant return types and casting in the calling code.</p>\n\n<p>Solution: Use instead the same supertype defined in the interface for defining the variable which should point to the returned value. This keeps the programming to an interface approach and your code clean.</p>\n\n<p>Classes with more than 1000 lines are a lurking danger\nMethods with more than 100 lines are a lurking danger too!</p>\n\n<p>Problem: Some developers stuff too much functionality in one class/method, being too lazy to break the functionality – this leads to low cohesion and maybe to high coupling – the inverse of a very important principle in OOP!\nSolution: Avoid using too much inner/nested classes – these classes are to be used ONLY on a per need basis, you don’t have to do a habit using them! Using them could lead to more problems like limiting inheritance. Lookout for code duplicate! The same or too similar code could already exist in some supertype implementation or maybe in another class. If it’s in another class which is not a supertype you also violated the cohesion rule. Watch out for static methods – maybe you need an utility class to add! <br/>\nMore at:\n<a href=\"http://centraladvisor.com/it/oop-what-are-the-best-practices-in-oop\" rel=\"nofollow\">http://centraladvisor.com/it/oop-what-are-the-best-practices-in-oop</a></p>\n" }, { "answer_id": 17682137, "author": "jeremy", "author_id": 2588246, "author_profile": "https://Stackoverflow.com/users/2588246", "pm_score": -1, "selected": false, "text": "<p>You probably don't want to use inheritance for this. Try this instead:</p>\n\n<pre><code>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</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7532/" ]
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. Suppose I am writing a video store application whose database has a `Person` table, with `PersonId`, `Name`, `DateOfBirth` and `Address` fields. It also has a `Staff` table, which has a link to a `PersonId`, and a `Customer` table which also links to `PersonId`. A simple object oriented approach would be to say that a `Customer` "is a" `Person` and therefore create classes a bit like this: ``` 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; } } ``` Now we can write a function say to send emails to all customers: ``` static void SendEmailToCustomers(IEnumerable<Person> everyone) { foreach(Person p in everyone) if(p is Customer) SendEmail(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 `everyone` list to have the same person in twice, once as a `Customer` and once as a `Staff`, do we make an arbitrary choice between: ``` class StaffCustomer : Customer { ... ``` and ``` class StaffCustomer : Staff { ... ``` Obviously only the first of these two would not break the `SendEmailToCustomers` function. So what would you do? * Make the `Person` class have optional references to a `StaffDetails` and `CustomerDetails` class? * Create a new class that contained a `Person`, plus optional `StaffDetails` and `CustomerDetails`? * Make everything an interface (e.g. `IPerson`, `IStaff`, `ICustomer`) and create three classes that implemented the appropriate interfaces? * Take another completely different approach?
Mark, This is an interesting question. You will find as many opinions on this. I don't believe there is a 'right' answer. This is a great example of where a rigid heirarchial object design can really cause problems after a system is built. For example, lets say you went with the "Customer" and "Staff" classes. You deploy your system and everything is happy. A few weeks later, someone points out that they are both 'on staff' and a 'customer' and they are not getting customer emails. In this case, you have a lot of code changes to make (re-design, not re-factor). I believe it would be overly complex and difficult to maintain if you attempt to have a set of derived classes that implement all the permutations and combination of people and their roles. This is especially true given that the above example is very simple - in most real applications, things will be more complex. For your example here, I would go with "Take another completely different approach". I would implement the Person class and include in it a collection of "roles". Each person could have one or more roles such as "Customer", "Staff", and "Vendor". This will make it easier to add roles as new requirements are discovered. For example, you may simply have a base "Role" class, and derive new roles from them.
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": 216540, "author": "vaske", "author_id": 16039, "author_profile": "https://Stackoverflow.com/users/16039", "pm_score": 2, "selected": false, "text": "<p>It's good one, but better is to use some script language such as JSP,PHP, ASP....and you can use simple POST and GET methods. </p>\n" }, { "answer_id": 216564, "author": "pkario", "author_id": 28207, "author_profile": "https://Stackoverflow.com/users/28207", "pm_score": 2, "selected": false, "text": "<p><p>The best method (imho) is to include it in the URL\n<p>href=\"http://NewPage.htm?var=value\";\n<p>encodeUriComponent a string Value</p>\n" }, { "answer_id": 216567, "author": "Robert Elwell", "author_id": 23102, "author_profile": "https://Stackoverflow.com/users/23102", "pm_score": 1, "selected": false, "text": "<p>One way to send over variables using POST to another page is to make the link to the subsequent page a submit input on a form where the action attribute is your target page. For every variable you have, you can include using inputs of attribute type \"hidden\" in this form, making only the button visible.</p>\n\n<p>Another option is to dynamically generate links on the page with something like PHP where you basically repopulate the current GET queries. </p>\n\n<p>Finally, you can always store this information in the PHP $_SESSION array and not have to worry about continually passing these variables through site navigation.</p>\n\n<p>Your choice will depend on how many navigational options there are where you'd like to keep the same variables. It will also depend on how secure you'd like your back end to be and the amount you'd like to disclose to the advanced web user.</p>\n" }, { "answer_id": 216571, "author": "Mitch", "author_id": 393334, "author_profile": "https://Stackoverflow.com/users/393334", "pm_score": 0, "selected": false, "text": "<p>Assuming that you are limited to using html pages, I think the best approach would be to pass the id along on the query string to the next page. It is relatively easy to pull that value back off the query string on the next page. If you need to be a little more stealthy about passing the variable (or you need the variable to persist for more than one page), you could also set a cookie and retrieve it on the next page.</p>\n" }, { "answer_id": 216785, "author": "extraneon", "author_id": 24582, "author_profile": "https://Stackoverflow.com/users/24582", "pm_score": 3, "selected": true, "text": "<p>You could just use a hidden input field; that gets transmitted as part of the form.</p>\n\n<pre><code>&lt;html&gt;\n &lt;head&gt;\n &lt;/head&gt;\n &lt;body&gt;\n &lt;script type=\"text/javascript\"&gt;\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 &lt;/script&gt;\n\n Your grid comes here; it need not be in the form\n\n &lt;form name=\"myForm\"&gt;\n &lt;input type=\"hidden\" name=\"selectedItemId\" value=\"XXX\"&gt;\n The submit button must be in the form.\n &lt;input type=\"button\" value=\"changeSelectedItem\" onClick=\"updateSelectedItemId()\"&gt;\n &lt;/form&gt;\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n" }, { "answer_id": 216814, "author": "David Robbins", "author_id": 19799, "author_profile": "https://Stackoverflow.com/users/19799", "pm_score": 1, "selected": false, "text": "<p>If you are only going to need the ID on the subsequent pages, then you can pass the id as a query string parameter. </p>\n\n<p>But there will be times when you need to relay more information and passing a variety of parameters to different pages and having to maintain different sets of parameters for different pages can get a little hairy. When this is the case I'd suggest that you keep a hidden field on the form and create an argument object that stores each of your parameters. Serialize the argument object with JSON and store this in you hidden field. Post the form back to the server. When the next page loads, deserialize the object and retrieve the values you need.</p>\n" }, { "answer_id": 219193, "author": "Ed.T", "author_id": 3014, "author_profile": "https://Stackoverflow.com/users/3014", "pm_score": 0, "selected": false, "text": "<p>Since you are trying to do this in a Grails application you do have a choice of using Flash scope. This might not make any sense if you want to go directly from one HTML page to the next as the scope would be defined in a controller. If you do not need to do any sort of processing between requests, I'd suggest using a hidden form field to keep it simple.</p>\n\n<p><a href=\"http://grails.org/Controllers+-+Controller+Scopes\" rel=\"nofollow noreferrer\">http://grails.org/Controllers+-+Controller+Scopes</a></p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27163/" ]
I'm relatively new to web application programming so I hope this question isn't too basic for everyone. 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. 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. Should I just pass the ID as an URL query string parameter? Are there any other better ways? 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. I should also mention that I'm using grails so this is happening in a GSP page but currently it only contains HTML.
You could just use a hidden input field; that gets transmitted as part of the form. ``` <html> <head> </head> <body> <script type="text/javascript"> function updateSelectedItemId() { document.myForm.selectedItemId.value = 2; alert(document.myForm.selectedItemId.value); // For you this would place the selected item id in the hidden // field in stead of 2, and submit the form in stead of alert } </script> Your grid comes here; it need not be in the form <form name="myForm"> <input type="hidden" name="selectedItemId" value="XXX"> The submit button must be in the form. <input type="button" value="changeSelectedItem" onClick="updateSelectedItemId()"> </form> </body> </html> ```
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": "<pre><code> decimal one = 1000M;\n decimal two = 12.5M;\n\n Console.WriteLine(one.ToString(\"0.##\"));\n Console.WriteLine(two.ToString(\"0.##\"));\n</code></pre>\n" }, { "answer_id": 216705, "author": "Joe", "author_id": 13087, "author_profile": "https://Stackoverflow.com/users/13087", "pm_score": 5, "selected": false, "text": "<p><strong>Updated following comment by user1676558</strong></p>\n\n<p>Try this:</p>\n\n<pre><code>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</code></pre>\n\n<p>For a decimal value, the default precision for the \"G\" format specifier is 29 digits, and fixed-point notation is always used when the precision is omitted, so this is the same as \"0.#############################\". </p>\n\n<p>Unlike \"0.##\" it will display all significant decimal places (a decimal value can not have more than 29 decimal places).</p>\n\n<p>The \"G29\" format specifier is similar but can use scientific notation if more compact (see <a href=\"https://msdn.microsoft.com/en-us/library/dwhawy9k(v=vs.110).aspx#Anchor_5\" rel=\"noreferrer\">Standard numeric format strings</a>).</p>\n\n<p>Thus:</p>\n\n<pre><code>decimal d = 0.0000000000000000000012M;\nConsole.WriteLine(d.ToString(\"G\")); // Uses fixed-point notation\nConsole.WriteLine(d.ToString(\"G29\"); // Uses scientific notation\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216538", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8547/" ]
What is the best way to format a decimal if I only want decimal displayed if it is not an integer. Eg: ``` decimal amount = 1000M decimal vat = 12.50M ``` When formatted I want: ``` Amount: 1000 (not 1000.0000) Vat: 12.5 (not 12.50) ```
``` decimal one = 1000M; decimal two = 12.5M; Console.WriteLine(one.ToString("0.##")); Console.WriteLine(two.ToString("0.##")); ```
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": 216548, "author": "Steve", "author_id": 27893, "author_profile": "https://Stackoverflow.com/users/27893", "pm_score": 1, "selected": false, "text": "<p>I think cookies might be what you are looking for; this is how most websites uniquely identify visitors. </p>\n" }, { "answer_id": 216552, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 5, "selected": false, "text": "<p>It's not possible to identify the computers accessing a web site without the cooperation of their owners. If they let you, however, you can store a cookie to identify the machine when it visits your site again. The key is, the visitor is in control; they can remove the cookie and appear as a new visitor any time they wish.</p>\n" }, { "answer_id": 216570, "author": "different", "author_id": 3654, "author_profile": "https://Stackoverflow.com/users/3654", "pm_score": 1, "selected": false, "text": "<p>Cookies won't be useful for determining unique visitors. A user could clear cookies and refresh the site - he then is classed as a new user again.</p>\n\n<p>I think that the best way to go about doing this is to implement a server side solution (as you will need somewhere to store your data). Depending on the complexity of your needs for such data, you will need to determine what is classed as a unique visit. A sensible method would be to allow an IP address to return the following day and be given a unique visit. Several visits from one IP address in one day shouldn't be counted as uniques.</p>\n\n<p>Using PHP, for example, it is trivial to get the IP address of a visitor, and store it in a text file (or a sql database).</p>\n\n<p>A server side solution will work on all machines, because you are going to track the user when he first loads up your site. Don't use javascript, as that is meant for client side scripting, plus the user may have disabled it in any case.</p>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 216572, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 3, "selected": false, "text": "<p>As with the previous solutions cookies are a good method, be aware that they identify <strong>browsers</strong> though. If I visited a website in Firefox and then in Internet Explorer cookies would be stored for both attempts seperately. Some users also disable cookies (but more people disable JavaScript).</p>\n\n<p>Another method to consider would be I.P. and hostname identification (be aware these can vary for dial-up/non-static IP users, AOL also uses blanket IPs). However since this only identifies networks this might not work as well as cookies.</p>\n" }, { "answer_id": 216599, "author": "Joeri Sebrechts", "author_id": 20980, "author_profile": "https://Stackoverflow.com/users/20980", "pm_score": 5, "selected": false, "text": "<p>A possibility is using <a href=\"http://yro.slashdot.org/article.pl?sid=08/10/14/1656251&amp;from=rss\" rel=\"noreferrer\">flash cookies</a>:</p>\n\n<ul>\n<li>Ubiquitous availability (95 percent of visitors will probably have flash)</li>\n<li>You can store more data per cookie (up to 100 KB)</li>\n<li>Shared across browsers, so more likely to uniquely identify a machine</li>\n<li>Clearing the browser cookies does not remove the flash cookies.</li>\n</ul>\n\n<p>You'll need to build a small (hidden) flash movie to read and write them.</p>\n\n<p>Whatever route you pick, make sure your users opt IN to being tracked, otherwise you're invading their privacy and become one of the bad guys.</p>\n" }, { "answer_id": 216610, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 2, "selected": false, "text": "<blockquote>\n <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>\n</blockquote>\n\n<p>Isn't that a really good reason <em>not</em> to use javascript?</p>\n\n<p>As others have said - cookies are probably your best option - just be aware of the limitations.</p>\n" }, { "answer_id": 216692, "author": "John Nilsson", "author_id": 24243, "author_profile": "https://Stackoverflow.com/users/24243", "pm_score": 0, "selected": false, "text": "<p>Assuming you don't want the user to be in control, you can't. The web doesn't work like that, the best you can hope for is some heuristics.</p>\n\n<p>If it is an option to force your visitor to install some software and use TCPA you may be able to pull something off.</p>\n" }, { "answer_id": 216711, "author": "JohnnySoftware", "author_id": 29380, "author_profile": "https://Stackoverflow.com/users/29380", "pm_score": 2, "selected": false, "text": "<p>Really, what you want to do cannot be done because the protocols do not allow for this. If static IPs were universally used then you might be able to do it. They are not, so you cannot.</p>\n\n<p>If you really want to identify <em>people</em>, have them log in.</p>\n\n<p>Since they will probably be moving around to different pages on your web site, you need a way to keep track of them as they move about.</p>\n\n<p>So long as they are logged in, and you are tracking their session within your site via cookies/link-parameters/beacons/whatever, you can be pretty sure that they are using the same computer during that time.</p>\n\n<p>Ultimately, it is incorrect to say this tells you which computer they are using if your users are not using your own local network and do not have static IP addresses.</p>\n\n<p>If what you want to do is being done with the cooperation of the users and there is only one user per cookie and they use a single web browser, just use a cookie.</p>\n" }, { "answer_id": 216886, "author": "cdeszaq", "author_id": 20770, "author_profile": "https://Stackoverflow.com/users/20770", "pm_score": 4, "selected": false, "text": "<p>There is only a small amount of information that you can get via an HTTP connection.</p>\n\n<ol>\n<li><p>IP - But as others have said, this is not fixed for many, if not most Internet users due to their ISP's dynamic allocation policies.</p></li>\n<li><p>Useragent String - Nearly all browsers send what kind of browser they are with every request. However, this can be set by the user in many browsers today.</p></li>\n<li><p>Collection of request fields - There are other fields sent with each request, such as supported encodings, etc. These, if used in the aggregate can help to ID a user's machine, but again are browser dependent and can be changed.</p></li>\n<li><p>Cookies - Setting a cookie is another way to identify a machine, or more specifically a browser on a machine, but as others have said, these can be deleted, or turned off by the users, and are only applicable on a browser, not a machine.</p></li>\n</ol>\n\n<p>So, the correct response is that you cannot achieve what you would live via the HTTP over IP protocols alone. However, using a combination of cookies, as well as IP, and the fields in the HTTP request, you have a good chance at guessing, sort of, what machine it is. Users tend to use only one browser, and often from one machine, so this may be fairly relieable, but this will vary depending on the audience...techies are more likely to mess with this stuff, and use more machines/browsers. Additionally, this could even be coupled with some attempt to geo-locate the IP, and use that data as well. But in any case, there is no solution that will be correct all of the time.</p>\n" }, { "answer_id": 217306, "author": "thatisvaliant", "author_id": 3746, "author_profile": "https://Stackoverflow.com/users/3746", "pm_score": 2, "selected": false, "text": "<p>I guess the verdict is i cannot programmatically uniquely identify a computer which is visiting my web site.</p>\n\n<p>I have the following question. When i use a machine which has never visited my online banking web site i get asked for additional authentification. then, if i go back a second time to the online banking site i dont get asked the additional authentification. reading the answers to my question i decided it must be a cookie involved. therefore, i deleted all cookies in IE and relogged onto my online banking site fully expecting to be asked the authentification questions again. to my surprise i was not asked. doesnt this lead one to believe the bank is doing some kind of pc tagging which doesnt involve cookies?</p>\n\n<p>further, after much googling today i found the following company who claims to sell a solution which does uniquely identify machines which visit a web site. <a href=\"http://www.the41.com/products.asp\" rel=\"nofollow noreferrer\">http://www.the41.com/products.asp</a>.</p>\n\n<p>i appreciate all the good information if you could clarify further this conflicting information i found i would greatly appreciate it.</p>\n" }, { "answer_id": 217386, "author": "Danny Whitt", "author_id": 375, "author_profile": "https://Stackoverflow.com/users/375", "pm_score": 3, "selected": false, "text": "<p>The suggestions to use cookies aside, the only comprehensive set of identifying attributes available to interrogate are contained in the HTTP request header. So it is possible to use some subset of these to create a pseudo-unique identifier for a user agent (i.e., browser). Further, most of this information is possibly already being logged in the so-called \"access log\" of your web server software by default and, if not, can be easily configured to do so. Then, a utlity could be developed that simply scans the content of this log, creating <em>fingerprints</em> of each request comprised of, say, the IP address and User Agent string, etc. The more data available, even including the contents of specific cookies, adds to the quality of the uniqueness of this fingerprint. Though, as many others have stated already, the HTTP protocol doesn't make this 100% foolproof - at best it can only be a fairly good indicator.</p>\n" }, { "answer_id": 245197, "author": "Anirvan", "author_id": 31100, "author_profile": "https://Stackoverflow.com/users/31100", "pm_score": 3, "selected": false, "text": "<blockquote>\n <p>When i use a machine which has never visited my online banking web site i get asked for additional authentification. then, if i go back a second time to the online banking site i dont get asked the additional authentification...i deleted all cookies in IE and relogged onto my online banking site fully expecting to be asked the authentification questions again. to my surprise i was not asked. doesnt this lead one to believe the bank is doing some kind of pc tagging which doesnt involve cookies?</p>\n</blockquote>\n\n<p>This is a pretty common type of authentication used by banks.</p>\n\n<p>Say you're accessing your bank website via example-isp.com. The first time you're there, you'll be asked for your password, as well as additional authentication. Once you've passed, the bank knows that user \"thatisvaliant\" is authenticated to access the site via example-isp.com.</p>\n\n<p>In the future, it won't ask for extra authentication (beyond your password) when you're accessing the site via example-isp.com. If you try to access the bank via another-isp.com, the bank will go through the same routine again.</p>\n\n<p>So to summarize, what the bank's identifying is your ISP and/or netblock, based on your IP address. Obviously not every user at your ISP is you, which is why the bank still asks you for your password.</p>\n\n<p>Have you ever had a credit card company call to verify that things are OK when you use a credit card in a different country? Same concept.</p>\n" }, { "answer_id": 266229, "author": "Eric Hogue", "author_id": 4137, "author_profile": "https://Stackoverflow.com/users/4137", "pm_score": 2, "selected": false, "text": "<p>I would do this using a combination of cookies and flash cookies. Create a GUID and store it in a cookie. If the cookie doesn't exist, try to read it from the flash cookie. If it's still not found, create it and write it to the flash cookie. This way you can share the same GUID across browsers. </p>\n" }, { "answer_id": 3287761, "author": "Jonathan", "author_id": 6910, "author_profile": "https://Stackoverflow.com/users/6910", "pm_score": 6, "selected": false, "text": "<p>These people have developed a fingerprinting method for recognising a user with a high level of accuracy:</p>\n<p><a href=\"https://panopticlick.eff.org/static/browser-uniqueness.pdf\" rel=\"nofollow noreferrer\">https://panopticlick.eff.org/static/browser-uniqueness.pdf</a></p>\n<blockquote>\n<p>We investigate the degree to which modern web browsers\nare subject to “device fingerprinting” via the version and configuration information that they will transmit to websites upon request. We\nimplemented one possible fingerprinting algorithm, and collected these\nfingerprints from a large sample of browsers that visited our test side,\n<a href=\"https://panopticlick.eff.org/static/panopticlick.eff.org\" rel=\"nofollow noreferrer\">panopticlick.eff.org</a>. We observe that the distribution of our finger-\nprint contains at least 18.1 bits of entropy, meaning that if we pick a\nbrowser at random, at best we expect that only one in 286,777 other\nbrowsers will share its fingerprint. Among browsers that support Flash\nor Java, the situation is worse, with the average browser carrying at least\n18.8 bits of identifying information. 94.2% of browsers with Flash or Java\nwere unique in our sample.</p>\n</blockquote>\n<p>By observing returning visitors, we estimate how rapidly browser fingerprints might change over time. In our sample, fingerprints changed quite\nrapidly, but even a simple heuristic was usually able to guess when a fingerprint was an “upgraded” version of a previously observed browser’s\nfingerprint, with 99.1% of guesses correct and a false positive rate of only\n0.86%.</p>\n<blockquote>\n</blockquote>\n<p>We discuss what privacy threat browser fingerprinting poses in practice,\nand what countermeasures may be appropriate to prevent it. There is a\ntradeoff between protection against fingerprintability and certain kinds of\ndebuggability, which in current browsers is weighted heavily against privacy. Paradoxically, anti-fingerprinting privacy technologies can be self-\ndefeating if they are not used by a sufficient number of people; we show\nthat some privacy measures currently fall victim to this paradox, but\nothers do not.</p>\n" }, { "answer_id": 10574175, "author": "Brian Armstrong", "author_id": 76486, "author_profile": "https://Stackoverflow.com/users/76486", "pm_score": 4, "selected": false, "text": "<p>You may want to try setting a unique ID in an evercookie (it will work cross browser, see their FAQs):\n<a href=\"http://samy.pl/evercookie/\" rel=\"noreferrer\">http://samy.pl/evercookie/</a></p>\n\n<p>There is also a company called ThreatMetrix that is used by a lot of big companies to solve this problem:\n<a href=\"http://threatmetrix.com/our-solutions/solutions-by-product/trustdefender-id/\" rel=\"noreferrer\">http://threatmetrix.com/our-solutions/solutions-by-product/trustdefender-id/</a>\nThey are quite expensive and some of their other products aren't very good, but their device id works well.</p>\n\n<p>Finally, there is this open source jquery implementation of the panopticlick idea:\n<a href=\"https://github.com/carlo/jquery-browser-fingerprint\" rel=\"noreferrer\">https://github.com/carlo/jquery-browser-fingerprint</a>\nIt looks pretty half baked right now but could be expanded upon.</p>\n\n<p>Hope it helps!</p>\n" }, { "answer_id": 12162449, "author": "Steve Wortham", "author_id": 102896, "author_profile": "https://Stackoverflow.com/users/102896", "pm_score": 3, "selected": false, "text": "<p>There are flaws with both cookie and non-cookie approaches. But if you can forgive the shortcomings of the cookie approach, here's an idea.</p>\n\n<p>If you're already using Google Analytics on your site, then you don't need to write code to track unique users yourself. Google Analytics does that for you via the <code>__utma</code> cookie value, as described in <a href=\"https://developers.google.com/analytics/resources/concepts/gaConceptsCookies\">Google's documentation</a>. And by reusing this value you're not creating additional cookie payload, which has efficiency benefits with page requests.</p>\n\n<p>And you could write some code easily enough to access that value, or use <a href=\"http://www.dannytalk.com/read-google-analytics-cookie-script/\">this script's</a> <code>getUniqueId()</code> function.</p>\n" }, { "answer_id": 16376795, "author": "Mr Programmer", "author_id": 530410, "author_profile": "https://Stackoverflow.com/users/530410", "pm_score": -1, "selected": false, "text": "<p>My post might not be a solution, but I can provide an example, where this feature has been implemented.</p>\n\n<p>If you visit the signup page of <code>www.supertorrents.org</code> for the first time from you computer, it's fine. But if you refresh the page or open the page again, it identifies you've previously visited the page. The real beauty comes here - it identifies even if you re-install Windows or other OS.</p>\n\n<p>I read somewhere that they store the CPU ID. Although I couldn't find how do they do it, I seriously doubt it, and they might use MAC Address to do it.</p>\n\n<p>I'll definitely share if I find <em>how</em> to do it.</p>\n" }, { "answer_id": 30876378, "author": "Per Quested Aronsson", "author_id": 1158376, "author_profile": "https://Stackoverflow.com/users/1158376", "pm_score": 5, "selected": false, "text": "<p>There is a popular method called canvas fingerprinting, described in this scientific article: <a href=\"https://securehomes.esat.kuleuven.be/~gacar/persistent/the_web_never_forgets.pdf\">The Web Never Forgets:\nPersistent Tracking Mechanisms in the Wild</a>. Once you start looking for it, you'll be surprised how frequently it is used. The method creates a unique fingerprint, which is consistent for each browser/hardware combination.</p>\n\n<p>The article also reviews other persistent tracking methods, like evercookies, respawning http and Flash cookies, and cookie syncing.</p>\n\n<p><strong>More info about canvas fingerprinting here:</strong> </p>\n\n<ul>\n<li><a href=\"https://cseweb.ucsd.edu/~hovav/dist/canvas.pdf\">Pixel Perfect: Fingerprinting Canvas in HTML5</a></li>\n<li><a href=\"https://en.wikipedia.org/wiki/Canvas_fingerprinting\">https://en.wikipedia.org/wiki/Canvas_fingerprinting</a></li>\n</ul>\n" }, { "answer_id": 40449925, "author": "Mahdi Jazini", "author_id": 2758404, "author_profile": "https://Stackoverflow.com/users/2758404", "pm_score": -1, "selected": false, "text": "<p><strong>A Trick:</strong></p>\n\n<ol>\n<li><p>Create 2 Registration Pages:</p>\n\n<p><strong>First Registration Page:</strong> without any email or security check (just with username and password)</p>\n\n<p><strong>Second Registration Page:</strong> with high security level (email verification request and security image and etc.)</p></li>\n<li><p>For customer satisfaction, and easy registration, default\nregistration page should be the <strong>(First Registration Page)</strong> but in the\n<strong>(First Registration Page)</strong> there is a hidden restriction. It's IP\nRestriction. If an IP tried to register for second time, (for example less than 1 hour) instead of\nshowing the block page. you can show the <strong>(Second Registration Page)</strong>\nautomatically.</p></li>\n<li>in the <strong>(First Registration Page)</strong> you can set (for example: block 2\nattempts from 1 ip for just 1 hour or 24 hours) and after (for example) 1 hour, you can open access from that ip automatically</li>\n</ol>\n\n<p>Please note: <strong>(First Registration Page)</strong> and <strong>(Second Registration Page)</strong> should not be in separated pages. you make just 1 page. (for example: register.php) and make it smart to switch between First PHP Style and Second PHP Style</p>\n" }, { "answer_id": 41575609, "author": "Walter", "author_id": 6158977, "author_profile": "https://Stackoverflow.com/users/6158977", "pm_score": 7, "selected": false, "text": "<h1>Introduction</h1>\n<p>I don't know if there is or ever will be a way to uniquely identify machines using a browser alone. The main reasons are:</p>\n<ul>\n<li>You will need to save data on the users computer. This data can be\ndeleted by the user any time. Unless you have a way to recreate this\ndata which is unique for each and every machine then your stuck.</li>\n<li>Validation. You need to guard against spoofing, session hijacking, etc.</li>\n</ul>\n<p>Even if there are ways to track a computer without using cookies there will always be a way to bypass it and software that will do this automatically. If you really need to track something based on a computer you will have to write a native application (Apple Store / Android Store / Windows Program / etc).</p>\n<p>I might not be able to give you an answer to the question you asked but I can show you how to implement session tracking. With session tracking you try to track the browsing session instead of the computer visiting your site. By tracking the session, your database schema will look like this:</p>\n<pre><code>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: [&quot;203.525....&quot;, &quot;203.525...&quot;, ...]\n // Computer session data goes here\n }, ...]\n</code></pre>\n<p>Advantages of session based tracking:</p>\n<ol>\n<li>For logged in users, you can always generate the same session id from the users <code>username</code> / <code>password</code> / <code>email</code>.</li>\n<li>You can still track guest users using <code>sessionID</code>.</li>\n<li>Even if several people use the same computer (ie cybercafe) you can track them separately if they log in.</li>\n</ol>\n<p>Disadvantages of session based tracking:</p>\n<ol>\n<li>Sessions are browser based and not computer based. If a user uses 2 different browsers it will result in 2 different sessions. If this is a problem you can stop reading here.</li>\n<li>Sessions expire if user is not logged in. If a user is not logged in, then they will use a guest session which will be invalidated if user deletes cookies and browser cache.</li>\n</ol>\n<h1>Implementation</h1>\n<p>There are many ways of implementing this. I don't think I can cover them all I'll just list my favorite which would make this an <strong>opinionated answer</strong>. Bear that in mind.</p>\n<h2>Basics</h2>\n<p>I will track the session by using what is known as a forever cookie. This is data which will automagically recreate itself even if the user deletes his cookies or updates his browser. It will not however survive the user deleting both their cookies and their browsing cache.</p>\n<p>To implement this I will use the browsers caching mechanism (<a href=\"https://www.rfc-editor.org/rfc/rfc2616#section-13.3\" rel=\"noreferrer\">RFC</a>), WebStorage API (<a href=\"https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API\" rel=\"noreferrer\">MDN</a>) and browser cookies (<a href=\"https://www.rfc-editor.org/rfc/rfc6265\" rel=\"noreferrer\">RFC</a>, <a href=\"https://developers.google.com/analytics/devguides/collection/analyticsjs/cookie-usage\" rel=\"noreferrer\">Google Analytics</a>).</p>\n<h2>Legal</h2>\n<p>In order to utilize tracking ids you need to add them to both your privacy policy and your terms of use preferably under the sub-heading <strong>Tracking</strong>. We will use the following keys on both <code>document.cookie</code> and <code>window.localStorage</code>:</p>\n<ul>\n<li><strong>_ga</strong>: Google Analytics data</li>\n<li><strong>__utma</strong>: Google Analytics tracking cookie</li>\n<li><strong>sid</strong>: SessionID</li>\n</ul>\n<p>Make sure you include links to your Privacy policy and terms of use on all pages that use tracking.</p>\n<h2>Where do I store my session data?</h2>\n<p>You can either store your session data in your website database or on the users computer. Since I normally work on smaller sites (let than 10 thousand continuous connections) that use 3rd party applications (Google Analytics / Clicky / etc) it's best for me to store data on clients computer. This has the following advantages:</p>\n<ol>\n<li>No database lookup / overhead / load / latency / space / etc.</li>\n<li>User can delete their data whenever they want without the need to write me annoying emails.</li>\n</ol>\n<p>and disadvantages:</p>\n<ol>\n<li>Data has to be encrypted / decrypted and signed / verified which creates cpu overhead on client (not so bad) and server (bah!).</li>\n<li>Data is deleted when user deletes their cookies and cache. (this is what I want really)</li>\n<li>Data is unavailable for analytics when users go off-line. (analytics for currently browsing users only)</li>\n</ol>\n<h2>UUIDS</h2>\n<ul>\n<li><strong>BrowserID</strong>: Unique id generated from the browsers user agent string. <code>Browser|BrowserVersion|OS|OSVersion|Processor|MozzilaMajorVersion|GeckoMajorVersion</code></li>\n<li><strong>ComputerID</strong>: Generated from users IP Address and HTTPS session key.\n<code>getISP(requestIP)|getHTTPSClientKey()</code></li>\n<li><strong>FingerPrintID</strong>: JavaScript based fingerprinting based on a modified <a href=\"https://github.com/Valve/fingerprintjs2/\" rel=\"noreferrer\">fingerprint.js</a>. <code>FingerPrint.get()</code></li>\n<li><strong>SessionID</strong>: Random key generated when user 1st visits site. <code>BrowserID|ComputerID|randombytes(256)</code></li>\n<li><strong>GoogleID</strong>: Generated from <code>__utma</code> cookie. <code>getCookie(__utma).uniqueid</code></li>\n</ul>\n<h2>Mechanism</h2>\n<p>The other day I was watching the <a href=\"http://www.wendyshow.com\" rel=\"noreferrer\">wendy williams show</a> with my girlfriend and was completely horrified when the host advised her viewers to delete their browser history at least once a month. Deleting browser history normally has the following effects:</p>\n<ol>\n<li>Deletes history of visited websites.</li>\n<li>Deletes cookies and <code>window.localStorage</code> (aww man).</li>\n</ol>\n<p>Most modern browsers make this option readily available but fear not friends. For there is a solution. The browser has a caching mechanism to store scripts / images and other things. Usually even if we delete our history, this browser cache still remains. All we need is a way to store our data here. There are 2 methods of doing this. The better one is to use a SVG image and store our data inside its tags. This way data can still be extracted even if JavaScript is disabled using flash. However since that is a bit complicated I will demonstrate the other approach which uses JSONP (<a href=\"https://en.wikipedia.org/wiki/JSONP\" rel=\"noreferrer\">Wikipedia</a>)</p>\n<p><strong>example.com/assets/js/tracking.js</strong> (actually tracking.php)</p>\n<pre><code>var now = new Date();\nvar window.__sid = &quot;SessionID&quot;; // Server generated\n\nsetCookie(&quot;sid&quot;, window.__sid, now.setFullYear(now.getFullYear() + 1, now.getMonth(), now.getDate() - 1));\n\nif( &quot;localStorage&quot; in window ) {\n window.localStorage.setItem(&quot;sid&quot;, window.__sid);\n}\n</code></pre>\n<p>Now we can get our session key any time:</p>\n<p><code>window.__sid || window.localStorage.getItem(&quot;sid&quot;) || getCookie(&quot;sid&quot;) || &quot;&quot;</code></p>\n<p><strong>How do I make tracking.js stick in browser?</strong></p>\n<p>We can achieve this using <a href=\"https://www.rfc-editor.org/rfc/rfc2616#section-14.9\" rel=\"noreferrer\">Cache-Control</a>, <a href=\"https://www.rfc-editor.org/rfc/rfc2616#section-14.29\" rel=\"noreferrer\">Last-Modified</a> and <a href=\"https://www.rfc-editor.org/rfc/rfc2616#section-14.19\" rel=\"noreferrer\">ETag</a> HTTP headers. We can use the <code>SessionID</code> as value for etag header:</p>\n<pre><code>setHeaders({\n &quot;ETag&quot;: SessionID,\n &quot;Last-Modified&quot;: new Date(0).toUTCString(),\n &quot;Cache-Control&quot;: &quot;private, max-age=31536000, s-max-age=31536000, must-revalidate&quot;\n})\n</code></pre>\n<p><code>Last-Modified</code> header tells the browser that this file is basically never modified. <code>Cache-Control</code> tells proxies and gateways not to cache the document but tells the browser to cache it for 1 year.</p>\n<p>The next time the browser requests the document, it will send <code>If-Modified-Since</code> and <code>If-None-Match</code> headers. We can use these to return a <code>304 Not Modified</code> response.</p>\n<p><strong>example.com/assets/js/tracking.php</strong></p>\n<pre><code>$sid = getHeader(&quot;If-None-Match&quot;) ?: getHeader(&quot;if-none-match&quot;) ?: getHeader(&quot;IF-NONE-MATCH&quot;) ?: &quot;&quot;; \n$ifModifiedSince = hasHeader(&quot;If-Modified-Since&quot;) ?: hasHeader(&quot;if-modified-since&quot;) ?: hasHeader(&quot;IF-MODIFIED-SINCE&quot;);\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</code></pre>\n<p>Now every time the browser requests <code>tracking.js</code> our server will respond with a <code>304 Not Modified</code> result and force an execute of the local copy of <code>tracking.js</code>.</p>\n<p><strong>I still don't understand. Explain it to me</strong></p>\n<p>Lets suppose the user clears their browsing history and refreshes the page. The only thing left on the users computer is a copy of <code>tracking.js</code> in browser cache. When the browser requests <code>tracking.js</code> it recieves a <code>304 Not Modified</code> response which causes it to execute the 1st version of <code>tracking.js</code> it recieved. <code>tracking.js</code> executes and restores the <code>SessionID</code> that was deleted.</p>\n<h2>Validation</h2>\n<p>Suppose Haxor X steals our customers cookies while they are still logged in. How do we protect them? Cryptography and Browser fingerprinting to the rescue. Remember our original definition for <code>SessionID</code> was:</p>\n<pre><code>BrowserID|ComputerID|randomBytes(256)\n</code></pre>\n<p>We can change this to:</p>\n<pre><code>Timestamp|BrowserID|ComputerID|encrypt(randomBytes(256), hk)|sign(Timestamp|BrowserID|ComputerID|randomBytes(256), hk)\n</code></pre>\n<p>Where <code>hk = sign(Timestamp|BrowserID|ComputerID, serverKey)</code>.</p>\n<p>Now we can validate our <code>SessionID</code> using the following algorithm:</p>\n<pre><code>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[&quot;key&quot;]);\n\nif( !verify(getTimestamp($sid) + getBrowserID($sid) + getComputerID($sid) + decrypt(getRandomBytes($sid), hk), getSignature($sid), $hk) ) return false;\n\nreturn true; \n</code></pre>\n<p>Now in order for Haxor's attack to work they must:</p>\n<ol>\n<li>Have same <code>ComputerID</code>. That means they have to have the same ISP provider as victim (Tricky). This will give our victim the opportunity to take legal action in their own country. Haxor must also obtain HTTPS session key from victim (Hard).</li>\n<li>Have same <code>BrowserID</code>. Anyone can spoof User-Agent string (Annoying).</li>\n<li>Be able to create their own fake <code>SessionID</code> (Very Hard). Volume atacks won't work because we use a time-stamp to generate encryption / signing key so basically its like generating a new key for each session. On top of that we encrypt random bytes so a simple dictionary attack is also out of the question.</li>\n</ol>\n<p>We can improve validation by forwarding <code>GoogleID</code> and <code>FingerprintID</code> (via ajax or hidden fields) and matching against those.</p>\n<pre><code>if( GoogleID != getStoredGoodleID($sid) ) return false;\nif( byte_difference(FingerPrintID, getStoredFingerprint($sid) &gt; 10%) return false;\n</code></pre>\n" }, { "answer_id": 49251772, "author": "Toolkit", "author_id": 631527, "author_profile": "https://Stackoverflow.com/users/631527", "pm_score": 2, "selected": false, "text": "<p>You can use <a href=\"https://github.com/Valve/fingerprintjs2\" rel=\"nofollow noreferrer\">fingerprintjs2</a></p>\n\n<pre><code>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</code></pre>\n\n<p>After that you can check all your users against existing and check JSON similarity, so even if their fingerprint mutates, you still can track them</p>\n" }, { "answer_id": 66409562, "author": "partizanos", "author_id": 4061637, "author_profile": "https://Stackoverflow.com/users/4061637", "pm_score": 0, "selected": false, "text": "<p>I will give my ideas starting from simpler to more complex.\nIn all the above you can create sessions and the problem essentialy translates to match session with request.</p>\n<p>a) (difficulty: easy) use client hardware to store explicitely a session id/hash of some sort (there are quite some privace/security issues so make sure you hash anything you store ), solutions include:</p>\n<ul>\n<li>cookies storage</li>\n<li>browser storage/webDB/ (more exotic browser solutions )</li>\n<li>extensions with permission to store things in files.</li>\n</ul>\n<p>The above suffer from the fact the the user can just empty his cache in case he doesn want.</p>\n<p>b) (difficulty: medium) Login based authentication.\nMost modern web frameworks provide such solution the core idea is you let the user voluntarily identify himself, quite straghtforward but adds complexity in the architecture.</p>\n<p>The above suffer from additional complexity and making essentially non public content.</p>\n<p>c)(difficulty: hard -R&amp;D) Identification based on metadata, (browser ip/language /browser / and other privace invasice stuff so make sure you let your users know or you miay get sued )\nnon perfect solution can get more complicated (a user typing with specific frequency or using mouse with specific patterns ? you even apply ML solutions ).\nThe claimed solutions</p>\n<p>The most powerful since the user even without wanting explicitely he can be identified. It is straight invasion of privacy(see GDPR) and not perfect eg. ip can change .</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3746/" ]
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? Because i want the solution to work on all machines and all browsers (within reason) I am trying to create a solution using javascript. Cookies will not do. 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.
Introduction ============ I don't know if there is or ever will be a way to uniquely identify machines using a browser alone. The main reasons are: * You will need to save data on the users computer. This data can be deleted by the user any time. Unless you have a way to recreate this data which is unique for each and every machine then your stuck. * Validation. You need to guard against spoofing, session hijacking, etc. Even if there are ways to track a computer without using cookies there will always be a way to bypass it and software that will do this automatically. If you really need to track something based on a computer you will have to write a native application (Apple Store / Android Store / Windows Program / etc). I might not be able to give you an answer to the question you asked but I can show you how to implement session tracking. With session tracking you try to track the browsing session instead of the computer visiting your site. By tracking the session, your database schema will look like this: ``` sesssion: sessionID: string // Global session data goes here computers: [{ BrowserID: string ComputerID: string FingerprintID: string userID: string authToken: string ipAddresses: ["203.525....", "203.525...", ...] // Computer session data goes here }, ...] ``` Advantages of session based tracking: 1. For logged in users, you can always generate the same session id from the users `username` / `password` / `email`. 2. You can still track guest users using `sessionID`. 3. Even if several people use the same computer (ie cybercafe) you can track them separately if they log in. Disadvantages of session based tracking: 1. Sessions are browser based and not computer based. If a user uses 2 different browsers it will result in 2 different sessions. If this is a problem you can stop reading here. 2. Sessions expire if user is not logged in. If a user is not logged in, then they will use a guest session which will be invalidated if user deletes cookies and browser cache. Implementation ============== There are many ways of implementing this. I don't think I can cover them all I'll just list my favorite which would make this an **opinionated answer**. Bear that in mind. Basics ------ I will track the session by using what is known as a forever cookie. This is data which will automagically recreate itself even if the user deletes his cookies or updates his browser. It will not however survive the user deleting both their cookies and their browsing cache. To implement this I will use the browsers caching mechanism ([RFC](https://www.rfc-editor.org/rfc/rfc2616#section-13.3)), WebStorage API ([MDN](https://developer.mozilla.org/en-US/docs/Web/API/Web_Storage_API)) and browser cookies ([RFC](https://www.rfc-editor.org/rfc/rfc6265), [Google Analytics](https://developers.google.com/analytics/devguides/collection/analyticsjs/cookie-usage)). Legal ----- In order to utilize tracking ids you need to add them to both your privacy policy and your terms of use preferably under the sub-heading **Tracking**. We will use the following keys on both `document.cookie` and `window.localStorage`: * **\_ga**: Google Analytics data * **\_\_utma**: Google Analytics tracking cookie * **sid**: SessionID Make sure you include links to your Privacy policy and terms of use on all pages that use tracking. Where do I store my session data? --------------------------------- You can either store your session data in your website database or on the users computer. Since I normally work on smaller sites (let than 10 thousand continuous connections) that use 3rd party applications (Google Analytics / Clicky / etc) it's best for me to store data on clients computer. This has the following advantages: 1. No database lookup / overhead / load / latency / space / etc. 2. User can delete their data whenever they want without the need to write me annoying emails. and disadvantages: 1. Data has to be encrypted / decrypted and signed / verified which creates cpu overhead on client (not so bad) and server (bah!). 2. Data is deleted when user deletes their cookies and cache. (this is what I want really) 3. Data is unavailable for analytics when users go off-line. (analytics for currently browsing users only) UUIDS ----- * **BrowserID**: Unique id generated from the browsers user agent string. `Browser|BrowserVersion|OS|OSVersion|Processor|MozzilaMajorVersion|GeckoMajorVersion` * **ComputerID**: Generated from users IP Address and HTTPS session key. `getISP(requestIP)|getHTTPSClientKey()` * **FingerPrintID**: JavaScript based fingerprinting based on a modified [fingerprint.js](https://github.com/Valve/fingerprintjs2/). `FingerPrint.get()` * **SessionID**: Random key generated when user 1st visits site. `BrowserID|ComputerID|randombytes(256)` * **GoogleID**: Generated from `__utma` cookie. `getCookie(__utma).uniqueid` Mechanism --------- The other day I was watching the [wendy williams show](http://www.wendyshow.com) with my girlfriend and was completely horrified when the host advised her viewers to delete their browser history at least once a month. Deleting browser history normally has the following effects: 1. Deletes history of visited websites. 2. Deletes cookies and `window.localStorage` (aww man). Most modern browsers make this option readily available but fear not friends. For there is a solution. The browser has a caching mechanism to store scripts / images and other things. Usually even if we delete our history, this browser cache still remains. All we need is a way to store our data here. There are 2 methods of doing this. The better one is to use a SVG image and store our data inside its tags. This way data can still be extracted even if JavaScript is disabled using flash. However since that is a bit complicated I will demonstrate the other approach which uses JSONP ([Wikipedia](https://en.wikipedia.org/wiki/JSONP)) **example.com/assets/js/tracking.js** (actually tracking.php) ``` var now = new Date(); var window.__sid = "SessionID"; // Server generated setCookie("sid", window.__sid, now.setFullYear(now.getFullYear() + 1, now.getMonth(), now.getDate() - 1)); if( "localStorage" in window ) { window.localStorage.setItem("sid", window.__sid); } ``` Now we can get our session key any time: `window.__sid || window.localStorage.getItem("sid") || getCookie("sid") || ""` **How do I make tracking.js stick in browser?** We can achieve this using [Cache-Control](https://www.rfc-editor.org/rfc/rfc2616#section-14.9), [Last-Modified](https://www.rfc-editor.org/rfc/rfc2616#section-14.29) and [ETag](https://www.rfc-editor.org/rfc/rfc2616#section-14.19) HTTP headers. We can use the `SessionID` as value for etag header: ``` setHeaders({ "ETag": SessionID, "Last-Modified": new Date(0).toUTCString(), "Cache-Control": "private, max-age=31536000, s-max-age=31536000, must-revalidate" }) ``` `Last-Modified` header tells the browser that this file is basically never modified. `Cache-Control` tells proxies and gateways not to cache the document but tells the browser to cache it for 1 year. The next time the browser requests the document, it will send `If-Modified-Since` and `If-None-Match` headers. We can use these to return a `304 Not Modified` response. **example.com/assets/js/tracking.php** ``` $sid = getHeader("If-None-Match") ?: getHeader("if-none-match") ?: getHeader("IF-NONE-MATCH") ?: ""; $ifModifiedSince = hasHeader("If-Modified-Since") ?: hasHeader("if-modified-since") ?: hasHeader("IF-MODIFIED-SINCE"); if( validateSession($sid) ) { if( sessionExists($sid) ) { continueSession($sid); send304(); } else { startSession($sid); send304(); } } else if( $ifModifiedSince ) { send304(); } else { startSession(); send200(); } ``` Now every time the browser requests `tracking.js` our server will respond with a `304 Not Modified` result and force an execute of the local copy of `tracking.js`. **I still don't understand. Explain it to me** Lets suppose the user clears their browsing history and refreshes the page. The only thing left on the users computer is a copy of `tracking.js` in browser cache. When the browser requests `tracking.js` it recieves a `304 Not Modified` response which causes it to execute the 1st version of `tracking.js` it recieved. `tracking.js` executes and restores the `SessionID` that was deleted. Validation ---------- Suppose Haxor X steals our customers cookies while they are still logged in. How do we protect them? Cryptography and Browser fingerprinting to the rescue. Remember our original definition for `SessionID` was: ``` BrowserID|ComputerID|randomBytes(256) ``` We can change this to: ``` Timestamp|BrowserID|ComputerID|encrypt(randomBytes(256), hk)|sign(Timestamp|BrowserID|ComputerID|randomBytes(256), hk) ``` Where `hk = sign(Timestamp|BrowserID|ComputerID, serverKey)`. Now we can validate our `SessionID` using the following algorithm: ``` if( getTimestamp($sid) is older than 1 year ) return false; if( getBrowserID($sid) !== createBrowserID($_Request, $_Server) ) return false; if( getComputerID($sid) !== createComputerID($_Request, $_Server) return false; $hk = sign(getTimestamp($sid) + getBrowserID($sid) + getComputerID($sid), $SERVER["key"]); if( !verify(getTimestamp($sid) + getBrowserID($sid) + getComputerID($sid) + decrypt(getRandomBytes($sid), hk), getSignature($sid), $hk) ) return false; return true; ``` Now in order for Haxor's attack to work they must: 1. Have same `ComputerID`. That means they have to have the same ISP provider as victim (Tricky). This will give our victim the opportunity to take legal action in their own country. Haxor must also obtain HTTPS session key from victim (Hard). 2. Have same `BrowserID`. Anyone can spoof User-Agent string (Annoying). 3. Be able to create their own fake `SessionID` (Very Hard). Volume atacks won't work because we use a time-stamp to generate encryption / signing key so basically its like generating a new key for each session. On top of that we encrypt random bytes so a simple dictionary attack is also out of the question. We can improve validation by forwarding `GoogleID` and `FingerprintID` (via ajax or hidden fields) and matching against those. ``` if( GoogleID != getStoredGoodleID($sid) ) return false; if( byte_difference(FingerPrintID, getStoredFingerprint($sid) > 10%) return false; ```
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": "<p>I'm not familiar with the specific element you are using, but in order \n to implement this on a full size window, you can do the following:</p>\n\n<pre><code>$wnd.onscroll = function() {\n if (($wnd.height - $wnd.scrollTop) &lt; SOME_MARGIN) then doSomething();\n};\n</code></pre>\n\n<p>Where scrollTop is essentially \"how many pixels have been scrolled\".\nI assume applying this to the table you are working with will do the job.</p>\n" }, { "answer_id": 216613, "author": "Ross", "author_id": 2025, "author_profile": "https://Stackoverflow.com/users/2025", "pm_score": 0, "selected": false, "text": "<p>There is a property I noticed while reading through DOM properties in Firebug today called <code>scrollY</code> (in Firebug under the DOM tab go to <code>content</code> > <code>scrollY</code>) which appears to be the amount of pixels left to scroll on the window. Try seeing if this is also created for scrollable elements. Then you can use Yuval's function to load new data.</p>\n" }, { "answer_id": 216651, "author": "Rômulo Ceccon", "author_id": 23193, "author_profile": "https://Stackoverflow.com/users/23193", "pm_score": 2, "selected": false, "text": "<p>I've just googled for it and found this article: <a href=\"http://www.developer.com/design/article.php/3681771\" rel=\"nofollow noreferrer\">Implementing Dynamic Scroll with Ajax, JavaScript, and XML</a>. It looks like a thorough explanation.</p>\n" }, { "answer_id": 216706, "author": "Guido", "author_id": 12388, "author_profile": "https://Stackoverflow.com/users/12388", "pm_score": 3, "selected": true, "text": "<p>Thank you for your answers. That's my final working code (inspired by Greg and <a href=\"http://ajaxian.com/archives/implementing-infinite-scrolling-with-jquery\" rel=\"nofollow noreferrer\">ajaxian.com</a>), that uses some jQuery functions and works with the <a href=\"http://developer.yahoo.com/yui/datatable/\" rel=\"nofollow noreferrer\">YUI DataTable</a>.</p>\n\n<pre><code>$(\".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() &lt;= 0;\n}\n</code></pre>\n\n<p>My next step is to implement my own <a href=\"http://developer.yahoo.com/yui/paginator/\" rel=\"nofollow noreferrer\">YUI Paginator</a> to achieve a complete integration with YUI components :)</p>\n" }, { "answer_id": 217120, "author": "Kent Brewster", "author_id": 1151280, "author_profile": "https://Stackoverflow.com/users/1151280", "pm_score": 0, "selected": false, "text": "<p>Ick. Not a big fan of endless scrolling; it breaks some of the key assumptions people make about how the Web works. Please promise you will only implement it under the following conditions:</p>\n\n<p>1) you are not substituting it for a perfectly good page that loads everything in a nice long table and lets the user use Ctrl-F to search inside the page for what time Fringe comes on.</p>\n\n<p>2) you don't plan on inserting an ad at the bottom of each chunk of scrolled data.</p>\n\n<p>3) you are providing a working fallback (hey, there's that nice long table again) for blind people and people browsing the Web with JavaScript disabled.</p>\n" }, { "answer_id": 283714, "author": "Stuart Grimshaw", "author_id": 11470, "author_profile": "https://Stackoverflow.com/users/11470", "pm_score": 0, "selected": false, "text": "<p>If you're using the YUI, it has a <a href=\"http://developer.yahoo.com/yui/docs/YAHOO.widget.ScrollingDataTable.html#event_tableScrollEvent\" rel=\"nofollow noreferrer\">tableScrollEvent</a> that gets fired when the table scrolls. Couple this with the dataTable's generateRequest function and you could implement endless scrolling by watching the <a href=\"http://developer.yahoo.com/yui/docs/YAHOO.widget.ScrollingDataTable.html#event_tableScrollEvent\" rel=\"nofollow noreferrer\">tableScrollEvent</a> and starting a request when you get near the end of your dataset.</p>\n\n<p>The YUI doc's don't have a specific example for this case, but does show you <a href=\"http://developer.yahoo.com/yui/datatable/#data\" rel=\"nofollow noreferrer\">how to handle the data</a> returned by generateRequest</p>\n" }, { "answer_id": 3313710, "author": "Satyam", "author_id": 399661, "author_profile": "https://Stackoverflow.com/users/399661", "pm_score": 1, "selected": false, "text": "<p>You can see it working <a href=\"http://www.satyam.com.ar/yui/2.8.0/infinite.html\" rel=\"nofollow noreferrer\">here</a> YUI only. In contrast with one of the solutions suggested above, the scrollbar moves continuously, the position and size reflect the true size and position of the viewable area, it doesn't load the next batch when the scrollbar reaches bottom. The scrollbar reaches bottom only when the last of the whole records is at the bottom of the viewing area. Of course, this only works if you do know how many records there are.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216588", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12388/" ]
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). The user can scroll up and down, so what I need is to **detect when the user reaches the end of the scrollbar** (that is, the last row at the bottom of the table) in order to request and show more data. 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. By the way, right now I am using a [YUI Datatable](http://developer.yahoo.com/yui/datatable/)
Thank you for your answers. That's my final working code (inspired by Greg and [ajaxian.com](http://ajaxian.com/archives/implementing-infinite-scrolling-with-jquery)), that uses some jQuery functions and works with the [YUI DataTable](http://developer.yahoo.com/yui/datatable/). ``` $(".yui-dt-bd").scroll(load_more); function load_more() { if ($(this).scrollend()) { alert("SCROLL END REACHED !"); // TODO load more data } } $.fn.scrollend = function() { return this[0].scrollHeight - this[0].scrollTop - this.height() <= 0; } ``` My next step is to implement my own [YUI Paginator](http://developer.yahoo.com/yui/paginator/) to achieve a complete integration with YUI components :)
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": "<p>As part of htmlAttributes,e.g.</p>\n\n<pre><code>Html.BeginForm(\n action, controller, FormMethod.Post, new { enctype=\"multipart/form-data\"})\n</code></pre>\n\n<p>Or you can pass <code>null</code> for action and controller to get the same default target as for BeginForm() without any parameters:</p>\n\n<pre><code>Html.BeginForm(\n null, null, FormMethod.Post, new { enctype=\"multipart/form-data\"})\n</code></pre>\n" }, { "answer_id": 304310, "author": "dp.", "author_id": 29092, "author_profile": "https://Stackoverflow.com/users/29092", "pm_score": 4, "selected": false, "text": "<p>You can also use the following syntax for the strongly typed version: </p>\n\n<pre><code>&lt;% using (Html.BeginForm&lt;SomeController&gt;(x=&gt; x.SomeAction(), \n FormMethod.Post, \n new { enctype = \"multipart/form-data\" })) \n { %&gt;\n</code></pre>\n" }, { "answer_id": 7796172, "author": "Nick Olsen", "author_id": 489213, "author_profile": "https://Stackoverflow.com/users/489213", "pm_score": 4, "selected": false, "text": "<p>I know this is old but you could create a custom extension if you needed to create that form over and over:</p>\n\n<pre><code>public static MvcForm BeginMultipartForm(this HtmlHelper htmlHelper)\n{\n return htmlHelper.BeginForm(null, null, FormMethod.Post, \n new Dictionary&lt;string, object&gt;() { { \"enctype\", \"multipart/form-data\" } });\n}\n</code></pre>\n\n<p>Usage then just becomes</p>\n\n<pre><code>&lt;% using(Html.BeginMultipartForm()) { %&gt;\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216600", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1469/" ]
How would I go about adding `enctype="multipart/form-data"` to a form that is generated by using `<% Html.BeginForm(); %>`?
As part of htmlAttributes,e.g. ``` Html.BeginForm( action, controller, FormMethod.Post, new { enctype="multipart/form-data"}) ``` Or you can pass `null` for action and controller to get the same default target as for BeginForm() without any parameters: ``` Html.BeginForm( null, null, FormMethod.Post, new { enctype="multipart/form-data"}) ```
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": "<p>Have you tried escaping with an additional double-quote? By escaping a character, you are telling Excel to treat the &quot; character as literal text.</p>\n<pre class=\"lang-sql prettyprint-override\"><code>= &quot;Maurice &quot;&quot;The Rocket&quot;&quot; Richard&quot;\n</code></pre>\n" }, { "answer_id": 218474, "author": "Dave DuPlantis", "author_id": 8174, "author_profile": "https://Stackoverflow.com/users/8174", "pm_score": 7, "selected": false, "text": "<p>Alternatively, you can use the <code>CHAR</code> function:</p>\n\n<pre><code>= \"Maurice \" &amp; CHAR(34) &amp; \"Rocket\" &amp; CHAR(34) &amp; \" Richard\"\n</code></pre>\n" }, { "answer_id": 3503439, "author": "eric", "author_id": 422946, "author_profile": "https://Stackoverflow.com/users/422946", "pm_score": 1, "selected": false, "text": "<p>will this work for macros using <code>.Formula = \"=THEFORMULAFUNCTION(\"STUFF\")\"</code>\nso it would be like:\nwill this work for macros using <code>.Formula = \"=THEFORMULAFUNCTION(CHAR(34) &amp; STUFF &amp; CHAR(34))\"</code></p>\n" }, { "answer_id": 11138160, "author": "JimmyPena", "author_id": 190829, "author_profile": "https://Stackoverflow.com/users/190829", "pm_score": 3, "selected": false, "text": "<p>I use a function for this (if the workbook already has VBA).</p>\n\n<pre><code>Function Quote(inputText As String) As String\n Quote = Chr(34) &amp; inputText &amp; Chr(34)\nEnd Function\n</code></pre>\n\n<p>This is from Sue Mosher's book \"Microsoft Outlook Programming\". Then your formula would be:</p>\n\n<p><code>=\"Maurice \"&amp;Quote(\"Rocket\")&amp;\" Richard\"</code></p>\n\n<p>This is similar to what <a href=\"https://stackoverflow.com/a/218474/190829\">Dave DuPlantis</a> posted.</p>\n" }, { "answer_id": 12737549, "author": "Adel", "author_id": 1721591, "author_profile": "https://Stackoverflow.com/users/1721591", "pm_score": 5, "selected": false, "text": "<p>Three double quotes: <code>\" \" \" x \" \" \"</code> = <code>\"x\"</code> Excel will auto change to one double quote. e.g.: </p>\n\n<pre><code>=CONCATENATE(\"\"\"x\"\"\",\" hi\") \n</code></pre>\n\n<p>= \"x\" hi</p>\n" }, { "answer_id": 14859919, "author": "Sam", "author_id": 2069425, "author_profile": "https://Stackoverflow.com/users/2069425", "pm_score": 0, "selected": false, "text": "<p><strong>VBA Function</strong></p>\n\n<p>1) .Formula = \"=\"\"THEFORMULAFUNCTION \"\"&amp;(CHAR(34) &amp; \"\"STUFF\"\" &amp; CHAR(34))\"</p>\n\n<p>2) .Formula = \"THEFORMULAFUNCTION \"\"STUFF\"\"\"</p>\n\n<p>The first method uses vba to write a formula in a cell which results in the calculated value:</p>\n\n<pre><code> THEFORMULAFUNCTION \"STUFF\"\n</code></pre>\n\n<p>The second method uses vba to write a string in a cell which results in the value:</p>\n\n<pre><code> THEFORMULAFUNCTION \"STUFF\"\n</code></pre>\n\n<p><strong>Excel Result/Formula</strong></p>\n\n<p>1) =\"THEFORMULAFUNCTION \"&amp;(CHAR(34) &amp; \"STUFF\" &amp; CHAR(34))</p>\n\n<p>2) THEFORMULAFUNCTION \"STUFF\"</p>\n" }, { "answer_id": 25291785, "author": "tandy", "author_id": 762082, "author_profile": "https://Stackoverflow.com/users/762082", "pm_score": 3, "selected": false, "text": "<p>In the event that you need to do this with JSON:</p>\n\n<pre><code>=CONCATENATE(\"'{\"\"service\"\": { \"\"field\"\": \"&amp;A2&amp;\"}}'\")\n</code></pre>\n" }, { "answer_id": 31747473, "author": "Dave", "author_id": 2773402, "author_profile": "https://Stackoverflow.com/users/2773402", "pm_score": 2, "selected": false, "text": "<p>Use chr(34)\nCode:</p>\n\n<pre><code> Joe = \"Hi there, \" &amp; Chr(34) &amp; \"Joe\" &amp; Chr(34)\n ActiveCell.Value = Joe\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code> Hi there, \"joe\"\n</code></pre>\n" }, { "answer_id": 36169987, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Returning an empty or zero-length string (e.g. <code>\"\"</code>) to make a cell appear blank is a common practise in a worksheet formula but recreating that option when inserting the formula through the <a href=\"https://msdn.microsoft.com/en-us/library/office/ff838835.aspx\" rel=\"nofollow\">Range.Formula</a> or <a href=\"https://msdn.microsoft.com/en-us/library/bb213527.aspx\" rel=\"nofollow\">Range.FormulaR1C1</a> property in VBA is unwieldy due to the necessity of having to double-up the double-quote characters within a quoted string.</p>\n\n<p>The worksheet's native <a href=\"https://support.office.com/en-us/article/TEXT-function-4B46E545-E612-4C84-AC23-EDFA68007945\" rel=\"nofollow\">TEXT function</a> can produce the same result without using quotes.</p>\n\n<pre><code>'formula to insert into C1 - =IF(A1&lt;&gt;\"\", B1, \"\")\nrange(\"C1\").formula = \"=IF(A1&lt;&gt;\"\"\"\", B1, \"\"\"\")\" '&lt;~quote chars doubled up\nrange(\"C1\").formula = \"=IF(A1&lt;&gt;TEXT(,), B1, TEXT(,))\" '&lt;~with TEXT(,) instead\n</code></pre>\n\n<p>To my eye, using <code>TEXT(,)</code> in place of <code>\"\"</code> cleans up even a simple formula like the one above. The benefits become increasingly significant when used in more complicated formulas like the practise of appending an empty string to a <a href=\"https://support.office.com/en-us/article/vlookup-function-adceda66-30de-4f26-923b-7257939faa65\" rel=\"nofollow\">VLOOKUP</a> to avoid returning a zero to the cell when a lookup results in a blank or returning an empty string on no-match with <a href=\"https://support.office.com/en-us/article/IFERROR-function-F59BACDC-78BD-4924-91DF-A869D0B08CD5\" rel=\"nofollow\">IFERROR</a>.</p>\n\n<pre><code>'formula to insert into D1 - =IFERROR(VLOOKUP(A1, B:C, 2, FALSE)&amp;\"\", \"\")\nrange(\"D1\").formula = \"=IFERROR(VLOOKUP(A1, B:C, 2, FALSE)&amp;\"\"\"\", \"\"\"\")\"\nrange(\"D1\").formula = \"=IFERROR(VLOOKUP(A1, B:C, 2, FALSE)&amp;TEXT(,), TEXT(,))\"\n</code></pre>\n\n<p>With <code>TEXT(,)</code> replacing the old <code>\"\"</code> method of delivering an empty string, you might get to stop using an abacus to determine whether you have the right number of quote characters in a formula string.</p>\n" }, { "answer_id": 36476205, "author": "Karthick Gunasekaran", "author_id": 2231100, "author_profile": "https://Stackoverflow.com/users/2231100", "pm_score": 1, "selected": false, "text": "<pre><code>=\"Maurice \"&amp;\"\"\"TheRocker\"\"\"&amp;\" Richard\"\n</code></pre>\n" }, { "answer_id": 38416893, "author": "pnuts", "author_id": 1505120, "author_profile": "https://Stackoverflow.com/users/1505120", "pm_score": -1, "selected": false, "text": "<p>There is another way, though more for \" How can I construct the following string in an Excel formula: \"Maurice \"The Rocket\" Richard\" \" than \" How to create strings containing double quotes in Excel formulas? \", which is simply to use two single quotes:</p>\n\n<p><a href=\"https://i.stack.imgur.com/WCRke.jpg\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/WCRke.jpg\" alt=\"SO216616 example\"></a></p>\n\n<p>On the left is Calibri snipped from an Excel worksheet and on the right a snip from a VBA window.\nIn my view escaping as mentioned by @YonahW wins 'hands down' but two single quotes is no more typing than two doubles and the difference is reasonably apparent in VBA without additional keystrokes while, potentially, not noticeable in a spreadsheet.</p>\n" }, { "answer_id": 44043792, "author": "Zon", "author_id": 1112963, "author_profile": "https://Stackoverflow.com/users/1112963", "pm_score": 2, "selected": false, "text": "<p>Concatenate <code>\"</code> as a ceparate cell:</p>\n\n<pre><code> A | B | C | D\n1 \" | text | \" | =CONCATENATE(A1; B1; C1);\n\nD1 displays \"text\"\n</code></pre>\n" }, { "answer_id": 71477835, "author": "Nathan SR", "author_id": 16923394, "author_profile": "https://Stackoverflow.com/users/16923394", "pm_score": -1, "selected": false, "text": "<p>The following formula works on Excel as well as Numbers (on MAC) :</p>\n<pre><code>= &quot;Maurice &quot; &amp; &quot;&quot;&quot;&quot; &amp; &quot;The Rocket&quot; &amp; &quot;&quot;&quot;&quot; &amp; &quot; Richard&quot;\n</code></pre>\n<p>Use &amp; &quot;&quot;&quot;&quot; &amp; to get a single double quote surrounding your string.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2443/" ]
How can I construct the following string in an Excel formula: > > Maurice "The Rocket" Richard > > > If I'm using single quotes, it's trivial: `="Maurice 'The Rocket' Richard"` but what about double quotes?
Have you tried escaping with an additional double-quote? By escaping a character, you are telling Excel to treat the " character as literal text. ```sql = "Maurice ""The Rocket"" Richard" ```
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": "<p>I don't know SQLAlchemy, so I could be off-target. However, I think that all you need is:</p>\n\n<pre><code>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</code></pre>\n\n<p>OK, maybe you don't need the ORDER BY, and maybe it would be better to re-specify the date expression. There are likely to be alternatives, such as:</p>\n\n<pre><code>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</code></pre>\n\n<p>And so on and so forth. Basically, you format the datetime field and then proceed to do the grouping etc on the formatted value.</p>\n" }, { "answer_id": 216757, "author": "Simon", "author_id": 22404, "author_profile": "https://Stackoverflow.com/users/22404", "pm_score": 1, "selected": false, "text": "<p>Does counting yield the same result when you just group by the unformatted datetime column? If so, you could just run the query and use Python date's strftime() method afterwards. i.e.</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 218974, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "<p>I don't know of a generic SQLAlchemy answer. Most databases support some form of date formatting, typically via functions. SQLAlchemy supports calling functions via sqlalchemy.sql.func. So for example, using SQLAlchemy over a Postgres back end, and a table my_table(foo varchar(30), when timestamp) I might do something like</p>\n\n<pre><code>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</code></pre>\n\n<p>To group by date truncated to month. But keep in mind that in that example, date_trunc() is a Postgres datetime function. Other databases will be different. You didn't mention the underlyig database. If there's a database independent way to do it I've never found one. In my case I run production and test aginst Postgres and unit tests aginst SQLite and have resorted to using SQLite user defined functions in my unit tests to emulate Postgress datetime functions. </p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1448/" ]
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. How do I do this using SQLAlchemy?
I don't know of a generic SQLAlchemy answer. Most databases support some form of date formatting, typically via functions. SQLAlchemy supports calling functions via sqlalchemy.sql.func. So for example, using SQLAlchemy over a Postgres back end, and a table my\_table(foo varchar(30), when timestamp) I might do something like ``` my_table = metadata.tables['my_table'] foo = my_table.c['foo'] the_date = func.date_trunc('month', my_table.c['when']) stmt = select(foo, the_date).group_by(the_date) engine.execute(stmt) ``` To group by date truncated to month. But keep in mind that in that example, date\_trunc() is a Postgres datetime function. Other databases will be different. You didn't mention the underlyig database. If there's a database independent way to do it I've never found one. In my case I run production and test aginst Postgres and unit tests aginst SQLite and have resorted to using SQLite user defined functions in my unit tests to emulate Postgress datetime functions.
216,664
<p>I have images being sent to my database from a remote video source at about 5 frames per second as JPEG images. I am trying to figure out how to get those images into a video format so I can stream a live video feed to Silverlight.</p> <p>It seems to make sense to create a MJPEG stream but I'm having a few problems. Firstly I was trying to stream via an HTTP request so I didn't have a deal with sockets but maybe this is breaking my code.</p> <p>If I try surf to my stream from QT I get a video error, Media player shows the first frame image and Silverlight crashes :)</p> <p>Here is the code that streams - since I content type used this way can only be sent once I know that it isn't ideal and might be the root cause. All images are coming in via a LINQ2SQL object.</p> <p>I did already try simply updating the image source of an image control in Silverlight but the flicker isn't acceptable. If Silverlight doesn't support MJPEG then no point even continuing but it looks like it does. I do have access to the h.264 frames coming in but that seemed more complicated via MP4.</p> <pre><code> Response.Clear(); Response.ContentType = "multipart/x-mixed-replace; boundary=--myboundary"; ASCIIEncoding ae = new ASCIIEncoding(); HCData data = new HCData(); var videos = (from v in data.Videos select v).Take(50); // sample the first 50 frames foreach (Video frame in videos) { byte[] boundary = ae.GetBytes("\r\n--myboundary\r\nContent-Type: image/jpeg\r\nContent-Length:" + frame.VideoData.ToArray().Length + "\r\n\r\n"); var mem = new MemoryStream(boundary); mem.WriteTo(Response.OutputStream); mem = new MemoryStream(frame.VideoData.ToArray()); mem.WriteTo(Response.OutputStream); Response.Flush(); Thread.Sleep(200); } </code></pre> <p>Thanks!</p> <p>EDIT: I have the stream working in firefox so if I surf to the page I see video! but nothing else accepts the format. Not IE, SL, Media player - nothing.</p>
[ { "answer_id": 216682, "author": "dicroce", "author_id": 3886, "author_profile": "https://Stackoverflow.com/users/3886", "pm_score": 0, "selected": false, "text": "<p>First, write your mjpeg frames out to separate files. You should then be able to open these in Phototshop (this will independently verify that you are parsing the stream correctly). If this fails, by bet is that you have HTTP headers embedded in your image data.</p>\n" }, { "answer_id": 219597, "author": "John Dyer", "author_id": 2862, "author_profile": "https://Stackoverflow.com/users/2862", "pm_score": 0, "selected": false, "text": "<p>Have you looked at various web cam setups that exist on the net? A lot of them do some sort of low res update without flicker. You should be able to reverse engineer these types of sites for additional clues to your problem.</p>\n\n<p>Some sites create a GIF animation, maybe that is an option so that the user can see the past minute or so.</p>\n" }, { "answer_id": 264781, "author": "csgero", "author_id": 21764, "author_profile": "https://Stackoverflow.com/users/21764", "pm_score": 1, "selected": false, "text": "<p>I'm far from being an expert in MJPEG streaming, but looking at the source of <a href=\"http://sourceforge.net/projects/mjpg-streamer/\" rel=\"nofollow noreferrer\">mjpg-streamer</a> on sourcefourge I think you should send each frame separately, writing the boundary before and after each of them. You should of course not write the content-type in the closing boundary.</p>\n" }, { "answer_id": 266891, "author": "dviljoen", "author_id": 29021, "author_profile": "https://Stackoverflow.com/users/29021", "pm_score": 2, "selected": false, "text": "<p>I did MJPEG a long time ago (3-4 years ago) and I'm scratching my head trying to remember the details and I simply can't. But, if its possible, I would suggest finding some kind of web site that streams MJPEG content and fire up wireshark/ethereal and see what you get over the wire. My guess is you are missing some required HTTP headers that firefox is little more forgiving about.</p>\n\n<p>If you can't find a sample MJPEG stream over the internet, a lot of web cams have software that give you an MJPEG stream. The app I worked on it with was a console for multiple security cameras, so I know that is a common implementation for cams of all types (if they support a web interface).</p>\n" }, { "answer_id": 375799, "author": "QueueHammer", "author_id": 46810, "author_profile": "https://Stackoverflow.com/users/46810", "pm_score": 0, "selected": false, "text": "<p>About your edit: MJPEG is supported by Firefox and Safari. However other applications do not, like Explorer or Silverlight depending on what you are doing with it.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216664", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13714/" ]
I have images being sent to my database from a remote video source at about 5 frames per second as JPEG images. I am trying to figure out how to get those images into a video format so I can stream a live video feed to Silverlight. It seems to make sense to create a MJPEG stream but I'm having a few problems. Firstly I was trying to stream via an HTTP request so I didn't have a deal with sockets but maybe this is breaking my code. If I try surf to my stream from QT I get a video error, Media player shows the first frame image and Silverlight crashes :) Here is the code that streams - since I content type used this way can only be sent once I know that it isn't ideal and might be the root cause. All images are coming in via a LINQ2SQL object. I did already try simply updating the image source of an image control in Silverlight but the flicker isn't acceptable. If Silverlight doesn't support MJPEG then no point even continuing but it looks like it does. I do have access to the h.264 frames coming in but that seemed more complicated via MP4. ``` Response.Clear(); Response.ContentType = "multipart/x-mixed-replace; boundary=--myboundary"; ASCIIEncoding ae = new ASCIIEncoding(); HCData data = new HCData(); var videos = (from v in data.Videos select v).Take(50); // sample the first 50 frames foreach (Video frame in videos) { byte[] boundary = ae.GetBytes("\r\n--myboundary\r\nContent-Type: image/jpeg\r\nContent-Length:" + frame.VideoData.ToArray().Length + "\r\n\r\n"); var mem = new MemoryStream(boundary); mem.WriteTo(Response.OutputStream); mem = new MemoryStream(frame.VideoData.ToArray()); mem.WriteTo(Response.OutputStream); Response.Flush(); Thread.Sleep(200); } ``` Thanks! EDIT: I have the stream working in firefox so if I surf to the page I see video! but nothing else accepts the format. Not IE, SL, Media player - nothing.
I did MJPEG a long time ago (3-4 years ago) and I'm scratching my head trying to remember the details and I simply can't. But, if its possible, I would suggest finding some kind of web site that streams MJPEG content and fire up wireshark/ethereal and see what you get over the wire. My guess is you are missing some required HTTP headers that firefox is little more forgiving about. If you can't find a sample MJPEG stream over the internet, a lot of web cams have software that give you an MJPEG stream. The app I worked on it with was a console for multiple security cameras, so I know that is a common implementation for cams of all types (if they support a web interface).
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": "<pre><code>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</code></pre>\n" }, { "answer_id": 857117, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>When you need LIMIT only, ms sql has the equivalent TOP keyword, so that is clear.\nWhen you need LIMIT with OFFSET, you can try some hacks like previously described, but they all add some overhead, i.e. for ordering one way and then the other, or the expencive NOT IN operation.\nI think all those cascades are not needed. The cleanest solution in my oppinion would be just use TOP without offset on the SQL side, and then seek to the required starting record with the appropriate client method, like mssql_data_seek in php. While this isn't a pure SQL solution, I think it is the best one because it doesn't add any overhead (the skipped-over records will not be transferred on the network when you seek past them, if that is what worries you).</p>\n" }, { "answer_id": 1032469, "author": "Florian Fankhauser", "author_id": 104976, "author_profile": "https://Stackoverflow.com/users/104976", "pm_score": 3, "selected": false, "text": "<p>Here is another solution which only works in Sql Server 2005 and newer because it uses the except statement. But I share it anyway.\nIf you want to get the records 50 - 75 write:</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 6444134, "author": "Barka", "author_id": 277498, "author_profile": "https://Stackoverflow.com/users/277498", "pm_score": 0, "selected": false, "text": "<p>I would try to implement this in my ORM as it is pretty simple there. If it really needs to be in SQL Server then I would look at the code generated by linq to sql for the following linq to sql statement and go from there. The MSFT engineer who implemented that code was part of the SQL team for many years and knew what he was doing.</p>\n\n<p>var result = myDataContext.mytable.Skip(pageIndex * pageSize).Take(pageSize)</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216673", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20860/" ]
When I worked on the [Zend Framework's database component](http://framework.zend.com/manual/en/zend.db.html), we tried to abstract the functionality of the `LIMIT` clause supported by MySQL, PostgreSQL, and SQLite. That is, creating a query could be done this way: ``` $select = $db->select(); $select->from('mytable'); $select->order('somecolumn'); $select->limit(10, 20); ``` When the database supports `LIMIT`, this produces an SQL query like the following: ``` SELECT * FROM mytable ORDER BY somecolumn LIMIT 10, 20 ``` This was more complex for brands of database that don't support `LIMIT` (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 `BETWEEN`. 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: ``` 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; ``` However, Microsoft SQL Server 2000 doesn't have the `ROW_NUMBER()` function. So my question is, can you come up with a way to emulate the `LIMIT` 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 `LIMIT`, both count and offset. Solutions using a temporary table are also not acceptable. **Edit:** The most common solution for MS SQL Server 2000 seems to be like the one below, for example to get rows 50 through 75: ``` SELECT TOP 25 * FROM ( SELECT TOP 75 * FROM table ORDER BY BY field ASC ) a ORDER BY field DESC; ``` 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. **Edit:** Another solution works better, but only if you can assume the result set includes a column that is unique: ``` SELECT TOP n * FROM tablename WHERE key NOT IN ( SELECT TOP x key FROM tablename ORDER BY key ); ``` **Conclusion:** No general-purpose solution seems to exist for emulating `LIMIT` in MS SQL Server 2000. A good solution exists if you can use the `ROW_NUMBER()` function in MS SQL Server 2005.
``` SELECT TOP n * FROM tablename WHERE key NOT IN ( SELECT TOP x key FROM tablename ORDER BY key DESC ); ```
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": "<p>I was able to duplicate your problem and found a workaround. I don't know why this happens, but it has happened to others.</p>\n\n<p>If you set the ShowHelp property to $true, you will get the dialog to come up properly.</p>\n\n<p>Example:</p>\n\n<pre><code>[void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' )\n$d = New-Object Windows.Forms.OpenFileDialog\n$d.ShowHelp = $true\n$d.ShowDialog( )\n</code></pre>\n\n<p>Good Luck!</p>\n" }, { "answer_id": 216769, "author": "Charlie", "author_id": 18529, "author_profile": "https://Stackoverflow.com/users/18529", "pm_score": 2, "selected": false, "text": "<p>It appears to me that the dialog is actually opening just fine, but it's behind the powershell console window. Unfortunately it doesn't show in the taskbar, so there's no indication that it's there unless you move the powershell window or Alt+Tab. It also appears that the ShowHelp workaround didn't have any effect for me.</p>\n\n<p><strong>EDIT</strong> Here's a way to do do it using your secondary-form idea. The basic idea is to create a new form which opens the OpenFileDialog from inside its Shown event. The key is calling Activate on the form before opening the dialog, so that the form comes to the front and the dialog appears. I moved the form offscreen by setting the Location to an offscreen value, but you could alternatively set Form.Visible = $false from inside the Shown event.</p>\n\n<pre><code>[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</code></pre>\n" }, { "answer_id": 24448454, "author": "iRon", "author_id": 1701026, "author_profile": "https://Stackoverflow.com/users/1701026", "pm_score": 1, "selected": false, "text": "<p>Apparently this has something to do with Multi-Threaded Apartment (MTA) mode.\nIt appears to work fine in Single-Threaded Apartment (-STA) mode.</p>\n\n<p>See also: <a href=\"https://stackoverflow.com/questions/127188/could-you-explain-sta-and-mta\">Could you explain STA and MTA?</a></p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216710", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2495/" ]
When I run the following, PowerShell hangs waiting for the dialog to close, even though the dialog is never displayed: ``` [void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) $d = New-Object Windows.Forms.OpenFileDialog $d.ShowDialog( ) ``` Calling `ShowDialog` on a `Windows.Forms.Form` works fine. I also tried creating a `Form` and passing it as the parent to `$d.ShowDialog`, but the result was no different.
I was able to duplicate your problem and found a workaround. I don't know why this happens, but it has happened to others. If you set the ShowHelp property to $true, you will get the dialog to come up properly. Example: ``` [void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) $d = New-Object Windows.Forms.OpenFileDialog $d.ShowHelp = $true $d.ShowDialog( ) ``` Good Luck!
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": "<p>Let's try a non-comment answer...</p>\n\n<p>Possibility A:</p>\n\n<ul>\n<li>Your macro for SFILES is looking for files ending in '<code>.s</code>'.</li>\n<li>Your rule for compiling SOBJS is looking for files ending in '<code>.asm</code>'.</li>\n</ul>\n\n<p>Possibility B:</p>\n\n<ul>\n<li>Your rule for SOBJS and COBJS is in a notation I don't recognize.</li>\n<li><p>According to the GNU Make manual, you can write implicit rules as:</p>\n\n<p>%.o : %.c ; <em>command</em></p></li>\n</ul>\n\n<p>You seem to have a list of targets $(SOBJS) that depends on '<code>%.o : %.asm</code>'.\nI'm not sure how make will interpret that.</p>\n\n<p>Personally, I would not trust wild-cards in build rules. I'd much rather spend the time listing exactly which source files are needed to build the code. I don't often run into this problem as a result.</p>\n" }, { "answer_id": 216999, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 3, "selected": true, "text": "<p>What you are trying to do will not work without VPATH, and since you are still learning makefiles, I would avoid using VPATH.</p>\n\n<p>The rule is looking for \"consoleio.c\", which if I understood your makefile correctly does not exist; what exists is \"source/consoleio.c\". You probably should change it to something like \"$(SOURCES)/%.c\" instead of \"%c\".</p>\n\n<p>I didn't check your syntax for that rule, however. If it's incorrect, the builtin \"%.o: %.c\" rule will be used instead, which would have the same problem.</p>\n\n<p>The way you are doing is not the usual way I've seen, however. The usual way is to:</p>\n\n<ul>\n<li>Create an implicit rule \"%.o: %.c\" (or in your case \"%.o: $(SOURCES)/%.c\")</li>\n<li>Explicit list the dependencies for each file: \"foo.o: foo.c bar.h baz.h\" (with no command, the implicit rule has the command)</li>\n</ul>\n" }, { "answer_id": 217700, "author": "JesperE", "author_id": 13051, "author_profile": "https://Stackoverflow.com/users/13051", "pm_score": 2, "selected": false, "text": "<p>@CesarB seems to have nailed the issue, I'll just add a couple of observations.</p>\n\n<ol>\n<li><p>I'd strongly recommend against using wildcards in build rules. The build rules should clearly define exactly what is being built, and not depend on what files happen to be in the directory.</p></li>\n<li><p>I'd also recommend against using VPATH unless you are (1) building in a separate build directory, or (2) have your source files spread out over a large number of directories. If all your sources are in a single directory, using VPATH is only going to confuse.</p></li>\n<li><p>The := assignment form is usually only used when the variable evaluation is known to take long time, such as when using a $(shell ...). Otherwise, \"=\" is preferrable.</p></li>\n<li><p>Using \"export\" to propagate OUTDIR to concat.py (which I presume it is, since concat.py doesn't take any parameters) is a code smell. If possible, pass it as a parameter instead.</p></li>\n</ol>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216716", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1256/" ]
In a [recent issue](https://stackoverflow.com/questions/215933/gcc-compiler-error-on-windows-xp), 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 [pass longer strings](http://www.delorie.com/djgpp/v2faq/faq16_4.html). In the process of hacking together a makefile and testing it, I've come across a strange error. The makefile is as follows: ``` 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) $< -o $@ $(COBJS) : %.o : %.c $(CC) -c $< $(CFLAGS) -o $@ ``` When attempting to run it, I receive this error: ``` make: *** No rule to make target `consoleio.c', needed by `consoleio.o'. Stop. ``` 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?
What you are trying to do will not work without VPATH, and since you are still learning makefiles, I would avoid using VPATH. The rule is looking for "consoleio.c", which if I understood your makefile correctly does not exist; what exists is "source/consoleio.c". You probably should change it to something like "$(SOURCES)/%.c" instead of "%c". I didn't check your syntax for that rule, however. If it's incorrect, the builtin "%.o: %.c" rule will be used instead, which would have the same problem. The way you are doing is not the usual way I've seen, however. The usual way is to: * Create an implicit rule "%.o: %.c" (or in your case "%.o: $(SOURCES)/%.c") * Explicit list the dependencies for each file: "foo.o: foo.c bar.h baz.h" (with no command, the implicit rule has the command)
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": 216754, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "<p>One con that can become a big deal for large projects is that it is impossible to make a forward declaration for nested classes or enums.</p>\n" }, { "answer_id": 216760, "author": "paercebal", "author_id": 14089, "author_profile": "https://Stackoverflow.com/users/14089", "pm_score": 7, "selected": true, "text": "<h2>Nested classes</h2>\n<p>There are several side effects to classes nested inside classes that I usually consider flaws (if not pure antipatterns).</p>\n<p>Let's imagine the following code :</p>\n<pre><code>class A\n{\n public :\n class B { /* etc. */ } ;\n\n // etc.\n} ;\n</code></pre>\n<p>Or even:</p>\n<pre><code>class A\n{\n public :\n class B ;\n\n // etc.\n} ;\n\nclass A::B\n{\n public :\n\n // etc.\n} ;\n</code></pre>\n<p>So:</p>\n<ul>\n<li><b>Privilegied Access:</b> A::B has privilegied access to all members of A (methods, variables, symbols, etc.), which weakens encapsulation</li>\n<li><b>A's scope is candidate for symbol lookup:</b> code from inside B will see <b>all</b> symbols from A as possible candidates for a symbol lookup, which can confuse the code</li>\n<li><b>forward-declaration:</b> There is no way to forward-declare A::B without giving a full declaration of A</li>\n<li><b>Extensibility:</b> It is impossible to add another class A::C unless you are owner of A</li>\n<li><b>Code verbosity:</b> putting classes into classes only makes headers larger. You can still separate this into multiple declarations, but there's no way to use namespace-like aliases, imports or usings.</li>\n</ul>\n<p>As a conclusion, unless exceptions (e.g. the nested class is an intimate part of the nesting class... And even then...), I see no point in nested classes in normal code, as the flaws outweights by magnitudes the perceived advantages.</p>\n<p>Furthermore, it smells as a clumsy attempt to simulate namespacing without using C++ namespaces.</p>\n<p>On the pro-side, you isolate this code, and if private, make it unusable but from the &quot;outside&quot; class...</p>\n<h2>Nested enums</h2>\n<p>Pros: Everything.</p>\n<p>Con: Nothing.</p>\n<p>The fact is enum items will pollute the global scope:</p>\n<pre><code>// collision\nenum Value { empty = 7, undefined, defined } ;\nenum Glass { empty = 42, half, full } ;\n\n// empty is from Value or Glass?\n</code></pre>\n<p>Ony by putting each enum in a different namespace/class will enable you to avoid this collision:</p>\n<pre><code>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</code></pre>\n<p>Note that C++0x defined the class enum:</p>\n<pre><code>enum class Value { empty, undefined, defined } ;\nenum class Glass { empty, half, full } ;\n\n// Value e = Value::empty ;\n// Glass f = Glass::empty ;\n</code></pre>\n<p>exactly for this kind of problems.</p>\n" }, { "answer_id": 216761, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 2, "selected": false, "text": "<p>If you're never going to be using the dependent class for anything but working with the independent class's implementations, nested classes are fine, in my opinion.</p>\n\n<p>It's when you want to be using the \"internal\" class as an object in its own right that things can start getting a little manky and you have to start writing extractor/inserter routines. Not a pretty situation.</p>\n" }, { "answer_id": 216768, "author": "carson", "author_id": 25343, "author_profile": "https://Stackoverflow.com/users/25343", "pm_score": 2, "selected": false, "text": "<p>It seems like you should be using namespaces instead of classes to group like things that are related to each other in this way. One con that I could see in doing nested classes is you end up with a really large source file that could be hard to grok when you are searching for a section.</p>\n" }, { "answer_id": 216815, "author": "DavidG", "author_id": 25893, "author_profile": "https://Stackoverflow.com/users/25893", "pm_score": 0, "selected": false, "text": "<p>For me a big con to having it outside is that it becomes part of the global namespace. If the enum or related class only really applies to the class that it's in, then it makes sense. So in the printer case, everything that includes the printer will know about having full access to the enum PRINTER_TYPE, where it doesn't really need to know about it. I can't say i've ever used an internal class, but for an enum, this seems more logical to keep it inside. As another poster has pointed out, it's also a good idea to to use namespaces to group similar items, since clogging the global namespace can really be a bad thing. I have previously worked on projects which are massive and just bringing up an auto complete list on the global namespace takes 20 minutes. In my opinion nested enums and namespaced classes/structs are probably the cleanest approach.</p>\n" }, { "answer_id": 216937, "author": "Nick", "author_id": 26240, "author_profile": "https://Stackoverflow.com/users/26240", "pm_score": 1, "selected": false, "text": "<p>paercebal said everything I would say about nested enums.</p>\n\n<p>WRT nested classes, my common and almost sole use case for them is when I have a class which is manipulating a specific type of resource, and I need a data class which represents something specific to that resource. In your case, output_tray might be a good example, but I don't generally use nested classes if the class is going to have any methods which are going to be called from outside the containing class, or is more than primarily a data class. I generally also don't nest data classes unless the contained class is not ever directly referenced outside the containing class.</p>\n\n<p>So, for example, if I had a printer_manipulator class, it might have a contained class for printer manipulation errors, but printer itself would be a non-contained class.</p>\n\n<p>Hope this helps. :)</p>\n" }, { "answer_id": 217528, "author": "Pat Notz", "author_id": 825, "author_profile": "https://Stackoverflow.com/users/825", "pm_score": 0, "selected": false, "text": "<p>I agree with the posts advocating for embedding your enum in a class but there are cases where it makes more sense to not do that (but please, at least put it in a namespace). If multiple classes are utilizing an enum defined within a different class, then those classes are directly dependent on that other concrete class (that owns the enum). That surely represents a design flaw since that class will be responsible for that enum as well as other responsibilities.</p>\n\n<p>So, yeah, embed the enum in a class if other code only uses that enum to interface directly with that concrete class. Otherwise, find a better place to keep the enum such as a namespace.</p>\n" }, { "answer_id": 217546, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 0, "selected": false, "text": "<p>If you put the enum into a class or a namespace, intellisense will be able to give you guidance when you're trying to remember the enum names. A small thing for sure, but sometimes the small things matter.</p>\n" }, { "answer_id": 219356, "author": "Brian Stewart", "author_id": 3114, "author_profile": "https://Stackoverflow.com/users/3114", "pm_score": 0, "selected": false, "text": "<p>Visual Studio 2008 does not seem to be able to provide intellisense for nested classes, so I have switched to the PIMPL idiom in most cases where I used to have a nested class. I always put enums either in the class if it is used only by that class, or outside the class in the same namespace as the class when more than one class uses the enum.</p>\n" }, { "answer_id": 16855356, "author": "Marius Amado-Alves", "author_id": 1991046, "author_profile": "https://Stackoverflow.com/users/1991046", "pm_score": -1, "selected": false, "text": "<p>Only problem with nested classes that I bumped into yet was that C++ does not let us refer to the object of the enclosing class, in the nested class functions. We cannot say \"Enclosing::this\"</p>\n\n<p>(But maybe there's a way?)</p>\n" }, { "answer_id": 18552979, "author": "Oswald", "author_id": 534124, "author_profile": "https://Stackoverflow.com/users/534124", "pm_score": 2, "selected": false, "text": "<p>There are no pros and cons per se of using nested public C++ classes. There are only facts. Those facts are mandated by the C++ standard. Whether a fact about nested public C++ classes is a pro or a con depends on the particular problem that you are trying to solve. The example you have given does not allow a judgement about whether nested classes are appropriate or not.</p>\n\n<p>One fact about nested classes is, that they have privileged access to all members of the class that they belong to. This is a con, if the nested classes does not need such access. But if the nested class does not need such access, then it should not have been declared as a nested class. There are situations, when a class <em>A</em> wants to grant privileged access to certain other classes <em>B</em>. There are three solutions to this problem</p>\n\n<ol>\n<li>Make <em>B</em> a friend of <em>A</em></li>\n<li>Make <em>B</em> a nested class of <em>A</em></li>\n<li>Make the methods and attributes, that <em>B</em> needs, public members of <em>A</em>.</li>\n</ol>\n\n<p>In this situation, it's #3 that violates encapsulation, because <em>A</em> has control over his friends and over his nested classes, but not over classes that call his public methods or access his public attributes.</p>\n\n<p>Another fact about nested classes is, that it is impossible to add another class <em>A::C</em> as a nested class of <em>A</em> unless you are owner of <em>A</em>. However, this is perfectly reasonable, because nested classes have privileged access. If it were possible to add <em>A::C</em> as a nested class of <em>A</em>, then <em>A::C</em> could trick <em>A</em> into granting access to privileged information; and that yould violate encapsulation. It's basically the same as with the <code>friend</code> declaration: the <code>friend</code> declaration does not grant you any special privileges, that your friend is hiding from others; it allows your friends to access information that you are hiding from your non-friends. In C++, calling someone a friend is an altruistic act, not an egoistic one. The same holds for allowing a class to be a nested class.</p>\n\n<p>Som other facts about nested public classes:</p>\n\n<ul>\n<li><strong>A's scope is candidate for symbol lookup of B</strong>: If you don't want this, make <em>B</em> a friend of <em>A</em> instead of a nested class. However, there are cases where you want exactly this kind of symbol lookup.</li>\n<li><em><strong>A::B</em> cannot be forward-declared</strong>: <em>A</em> and <em>A::B</em> are tightly coupled. Being able to use <em>A::B</em> without knowing <em>A</em> would only hide this fact.</li>\n</ul>\n\n<p>To summarize this: if the tool does not fit your needs, don't blame the tool; blame yourself for using the tool; others might have different problems, for which the tool is perfect.</p>\n" }, { "answer_id": 18740671, "author": "Yaroslav Nikitenko", "author_id": 952234, "author_profile": "https://Stackoverflow.com/users/952234", "pm_score": 0, "selected": false, "text": "<p>I can see a con for nested classes, that one may better use generic programming.</p>\n\n<p>If the little class is defined outside the big one, you can make the big class a class template and use any \"little\" class you may need in the future with the big class.</p>\n\n<p>Generic programming is a powerful tool, and, IMHO, we should keep it in mind when developing extensible programs. Strange, that no one has mentioned this point.</p>\n" }, { "answer_id": 22719072, "author": "Eric G.", "author_id": 3473604, "author_profile": "https://Stackoverflow.com/users/3473604", "pm_score": 1, "selected": false, "text": "<p>Remember that you can always promote a nested class to a top-level one later, but you may not be able to do the opposite without breaking existing code. Therefore, my advice would be make it a nested class first, and if it starts to become a problem, make it a top-level class in the next version.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216748", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9236/" ]
What are the pros and cons of using nested public C++ classes and enumerations? For example, suppose you have a class called `printer`, and this class also stores information on output trays, you could have: ``` class printer { public: std::string name_; enum TYPE { TYPE_LOCAL, TYPE_NETWORK, }; class output_tray { ... }; ... }; printer prn; printer::TYPE type; printer::output_tray tray; ``` Alternatively: ``` 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; ``` 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. So, which do you prefer and why?
Nested classes -------------- There are several side effects to classes nested inside classes that I usually consider flaws (if not pure antipatterns). Let's imagine the following code : ``` class A { public : class B { /* etc. */ } ; // etc. } ; ``` Or even: ``` class A { public : class B ; // etc. } ; class A::B { public : // etc. } ; ``` So: * **Privilegied Access:** A::B has privilegied access to all members of A (methods, variables, symbols, etc.), which weakens encapsulation * **A's scope is candidate for symbol lookup:** code from inside B will see **all** symbols from A as possible candidates for a symbol lookup, which can confuse the code * **forward-declaration:** There is no way to forward-declare A::B without giving a full declaration of A * **Extensibility:** It is impossible to add another class A::C unless you are owner of A * **Code verbosity:** putting classes into classes only makes headers larger. You can still separate this into multiple declarations, but there's no way to use namespace-like aliases, imports or usings. As a conclusion, unless exceptions (e.g. the nested class is an intimate part of the nesting class... And even then...), I see no point in nested classes in normal code, as the flaws outweights by magnitudes the perceived advantages. Furthermore, it smells as a clumsy attempt to simulate namespacing without using C++ namespaces. On the pro-side, you isolate this code, and if private, make it unusable but from the "outside" class... Nested enums ------------ Pros: Everything. Con: Nothing. The fact is enum items will pollute the global scope: ``` // collision enum Value { empty = 7, undefined, defined } ; enum Glass { empty = 42, half, full } ; // empty is from Value or Glass? ``` Ony by putting each enum in a different namespace/class will enable you to avoid this collision: ``` namespace Value { enum type { empty = 7, undefined, defined } ; } namespace Glass { enum type { empty = 42, half, full } ; } // Value::type e = Value::empty ; // Glass::type f = Glass::empty ; ``` Note that C++0x defined the class enum: ``` enum class Value { empty, undefined, defined } ; enum class Glass { empty, half, full } ; // Value e = Value::empty ; // Glass f = Glass::empty ; ``` exactly for this kind of problems.
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": 216759, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 2, "selected": false, "text": "<p>Check if </p>\n\n<ol>\n<li>the fully qualified name for MyClass is MyApp.Domain.MyClass </li>\n<li>MyClass has a default public constructor (with no parameters) so that XAML can instantiate it.</li>\n</ol>\n" }, { "answer_id": 218260, "author": "Enrico Campidoglio", "author_id": 26396, "author_profile": "https://Stackoverflow.com/users/26396", "pm_score": 1, "selected": false, "text": "<p>Could be of any help?<br /><br />\n<a href=\"http://sdolha.spaces.live.com/Blog/cns!4121802308C5AB4E!3591.entry\" rel=\"nofollow noreferrer\">Visual Studio 2008 (RTM) WPF Designer Could Not Load Assembly or Dependency</a></p>\n\n<p>I assume you are using Visual Studio 2008. If you are using Visual Studio 2005, this is a known issue in the XAML designer code-named \"Cider\", which is included in the \"Visual Studio 2005 Extensions for WPF and WCF\".</p>\n" }, { "answer_id": 523794, "author": "Danny Varod", "author_id": 38368, "author_profile": "https://Stackoverflow.com/users/38368", "pm_score": 0, "selected": false, "text": "<p>If the XAML is not loose (is compiled within an assembly (DLL/EXE)<BR>\nmake sure that assembly has a reference to the assembly you are looking for<BR>\n(right click on the project --> add reference ...).<BR>\n<BR>\nIf the XAML is loose, make sure the assembly it is looking for is copied to the same directory the exe is ran from.</p>\n" }, { "answer_id": 28754607, "author": "Kaitlin Hipkin", "author_id": 4548035, "author_profile": "https://Stackoverflow.com/users/4548035", "pm_score": 1, "selected": false, "text": "<p>You only need to put the <code>assembly=MyApp.Domain</code> if you're compiling loose XAML dynamically.</p>\n\n<p>If you're just building your XAML once initially, exclude that token and just say <code>xmlns:local=\"clr-namespace:MyApp.Domain\"</code> instead.</p>\n" }, { "answer_id": 31970937, "author": "dotNET", "author_id": 1137199, "author_profile": "https://Stackoverflow.com/users/1137199", "pm_score": 2, "selected": false, "text": "<p>If it helps anyone, I was able to solve my problems by simply adding <code>;assembly=</code> at the end of the namespace declaration that referred to the containing project itself. For example:</p>\n\n<pre><code>xmlns:local=\"clr-namespace:YourProjectNameSpace;assembly=\" \n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216749", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16501/" ]
I have a WPF project defined like this: ``` MyApp.sln MyAppWPF MyApp.Domain ``` 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 **project reference** in MyAppWPF to MyApp.Domain. I am trying to create the reference like this: ``` <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"> <Window.Resources> <local:MyClass x:Key="mine" /> </Window.Resources> </Window> ``` 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. How do I do this? Do I need a strong name, or reference the dll directly instead of using a project reference?
Check if 1. the fully qualified name for MyClass is MyApp.Domain.MyClass 2. MyClass has a default public constructor (with no parameters) so that XAML can instantiate it.
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": 223635, "author": "michael aubert", "author_id": 17867, "author_profile": "https://Stackoverflow.com/users/17867", "pm_score": 1, "selected": false, "text": "<p>Without source code to review, I would suggest using the wireles toolkit (from <a href=\"http://java.sun.com)first\" rel=\"nofollow noreferrer\">http://java.sun.com)first</a>.\nIt contains the standard J2ME emulator for windows and example code that will allow you to play a wav file.\nassuming that works OK for you, try the same code on your Samsung device (of course, the location of the wav file will probably change so you have a tiny modification to make in the example code).\nAssuming that works, compare your code that doesn't with the example code.</p>\n" }, { "answer_id": 223691, "author": "Irfan Mulic", "author_id": 27016, "author_profile": "https://Stackoverflow.com/users/27016", "pm_score": 3, "selected": true, "text": "<p>If this device supports audio/mpeg you should be able to play mp3 use this code inside your midlet...</p>\n\n<p>This works on my nokia symbian phones</p>\n\n<pre><code>// 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</code></pre>\n\n<p>As for emulators my nokia experience is that I couldn't make it emulate mp3 player but when I put application on phone it works...</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216766", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9771/" ]
File formats I would like to play include .wav, .mp3, .midi. 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
If this device supports audio/mpeg you should be able to play mp3 use this code inside your midlet... This works on my nokia symbian phones ``` // Code starts here put this into midlet run() method public void run() { try { InputStream is = getClass().getResourceAsStream("your_audio_file.mp3"); player = Manager.createPlayer(is,"audio/mpeg"); // if "audio/mpeg" doesn't work try "audio/mp3" player.realize(); player.prefetch(); player.start(); } catch(Exception e) {} } ``` As for emulators my nokia experience is that I couldn't make it emulate mp3 player but when I put application on phone it works...
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": "<p>If curl wrappers are on (they are per default), you can use:</p>\n\n<pre><code>file_get_contents('http://www.example.org');\n</code></pre>\n\n<p>Note that this happens synchronous, so before the request has completed, your page won't either. It would be better to log access to a logfile (or database) and export the data occasionally. Alternatively, you could do the request after your page has completed, and output has been sent to the client.</p>\n" }, { "answer_id": 216775, "author": "Gerald", "author_id": 19404, "author_profile": "https://Stackoverflow.com/users/19404", "pm_score": 0, "selected": false, "text": "<p>You'll probably want to use <a href=\"http://us3.php.net/manual/en/curl.examples.php\" rel=\"nofollow noreferrer\">cURL</a></p>\n" }, { "answer_id": 216776, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "<p>There's numerous ways... the simplest is <code>file_get_contents('http://...');</code>\nOther functions like <code>fopen()</code> also support http: streams.</p>\n\n<p>If you need more control, I'd suggest looking at curl (see <code>curl_init</code>)</p>\n" }, { "answer_id": 216786, "author": "eyelidlessness", "author_id": 17964, "author_profile": "https://Stackoverflow.com/users/17964", "pm_score": 2, "selected": false, "text": "<p>Beware <code>file_get_contents()</code> and <code>fopen()</code>:</p>\n\n<blockquote>\n <p>If PHP has decided that filename specifies a registered protocol, and that protocol is registered as a network URL, PHP will check to make sure that allow_url_fopen is enabled. If it is switched off, PHP will emit a warning and the fopen call will fail.</p>\n</blockquote>\n" }, { "answer_id": 217855, "author": "Ryan McCue", "author_id": 2575, "author_profile": "https://Stackoverflow.com/users/2575", "pm_score": 2, "selected": false, "text": "<p>There are a number of ways to send a GET request with PHP. As mentioned above, you can use <code>file_get_contents</code>, <code>fopen</code> or cURL.</p>\n<p>You can also use the <a href=\"http://php.net/http\" rel=\"nofollow noreferrer\">HTTP extension</a>, the <code>fsockopen()</code> function or <a href=\"http://php.net/stream_get_contents\" rel=\"nofollow noreferrer\">streams</a> via <code>fopen</code>.</p>\n<p>I'd advise checking out <a href=\"http://trac.wordpress.org/browser/trunk/wp-includes/http.php\" rel=\"nofollow noreferrer\">what WordPress has done</a>, as it handles almost all possibilities.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216771", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1463/" ]
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. EDIT: curl is not available to me.
If curl wrappers are on (they are per default), you can use: ``` file_get_contents('http://www.example.org'); ``` Note that this happens synchronous, so before the request has completed, your page won't either. It would be better to log access to a logfile (or database) and export the data occasionally. Alternatively, you could do the request after your page has completed, and output has been sent to the client.
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": "<p>Tomcat sets a catalina.home system property. You can use this in your log4j properties file. Something like this:</p>\n\n<pre><code>log4j.rootCategory=DEBUG,errorfile\n\nlog4j.appender.errorfile.File=${catalina.home}/logs/LogFilename.log\n</code></pre>\n\n<p>On Debian (including Ubuntu), <code>${catalina.home}</code> will not work because that points at /usr/share/tomcat6 which has no link to /var/log/tomcat6. Here just use <code>${catalina.base}</code>.</p>\n\n<p>If your using another container, try to find a similar system property, or define your own. Setting the system property will vary by platform, and container. But for Tomcat on Linux/Unix I would create a setenv.sh in the CATALINA_HOME/bin directory. It would contain:</p>\n\n<pre><code>export JAVA_OPTS=\"-Dcustom.logging.root=/var/log/webapps\"\n</code></pre>\n\n<p>Then your log4j.properties would be:</p>\n\n<pre><code>log4j.rootCategory=DEBUG,errorfile\n\nlog4j.appender.errorfile.File=${custom.logging.root}/LogFilename.log\n</code></pre>\n" }, { "answer_id": 218037, "author": "Iker Jimenez", "author_id": 2697, "author_profile": "https://Stackoverflow.com/users/2697", "pm_score": 7, "selected": true, "text": "<p>I've finally done it in this way.</p>\n\n<p>Added a ServletContextListener that does the following:</p>\n\n<pre><code>public void contextInitialized(ServletContextEvent event) {\n ServletContext context = event.getServletContext();\n System.setProperty(\"rootPath\", context.getRealPath(\"/\"));\n}\n</code></pre>\n\n<p>Then in the log4j.properties file:</p>\n\n<pre><code>log4j.appender.file.File=${rootPath}WEB-INF/logs/MyLog.log\n</code></pre>\n\n<p>By doing it in this way Log4j will write into the right folder as long as you don't use it before the \"rootPath\" system property has been set. This means that you cannot use it from the ServletContextListener itself but you should be able to use it from anywhere else in the app.</p>\n\n<p>It should work on every web container and OS as it's not dependent on a container specific system property and it's not affected by OS specific path issues.\nTested with Tomcat and Orion web containers and on Windows and Linux and it works fine so far.</p>\n\n<p>What do you think?</p>\n" }, { "answer_id": 218800, "author": "Spencer Kormos", "author_id": 8528, "author_profile": "https://Stackoverflow.com/users/8528", "pm_score": 3, "selected": false, "text": "<p>Doesn't log4j just use the application root directory if you don't specify a root directory in your FileAppender's path property? So you should just be able to use:</p>\n\n<p>log4j.appender.file.File=logs/MyLog.log</p>\n\n<p>It's been awhile since I've done Java web development, but this seems to be the most intuitive, and also doesn't collide with other unfortunately named logs writing to the ${catalina.home}/logs directory.</p>\n" }, { "answer_id": 320412, "author": "Dimitri De Franciscis", "author_id": 11988, "author_profile": "https://Stackoverflow.com/users/11988", "pm_score": 4, "selected": false, "text": "<p>If you use Spring you can:</p>\n\n<p>1) create a log4j configuration file, e.g. \"/WEB-INF/classes/log4j-myapp.properties\"\nDO NOT name it \"log4j.properties\"</p>\n\n<p>Example:</p>\n\n<pre><code>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] - &lt;%m&gt;%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</code></pre>\n\n<p>We'll define \"myWebapp-instance-root\" later on point (3)</p>\n\n<p>2) Specify config location in web.xml:</p>\n\n<pre><code>&lt;context-param&gt;\n &lt;param-name&gt;log4jConfigLocation&lt;/param-name&gt;\n &lt;param-value&gt;/WEB-INF/classes/log4j-myapp.properties&lt;/param-value&gt;\n&lt;/context-param&gt;\n</code></pre>\n\n<p>3) Specify a <strong>unique</strong> variable name for your webapp's root, e.g. \"myWebapp-instance-root\"</p>\n\n<pre><code>&lt;context-param&gt;\n &lt;param-name&gt;webAppRootKey&lt;/param-name&gt;\n &lt;param-value&gt;myWebapp-instance-root&lt;/param-value&gt;\n&lt;/context-param&gt;\n</code></pre>\n\n<p>4) Add a Log4jConfigListener:</p>\n\n<pre><code>&lt;listener&gt;\n &lt;listener-class&gt;org.springframework.web.util.Log4jConfigListener&lt;/listener-class&gt;\n&lt;/listener&gt;\n</code></pre>\n\n<p>If you choose a different name, remember to change it in log4j-myapp.properties, too.</p>\n\n<p>See my article (Italian only... but it should be understandable):\n<a href=\"http://www.megadix.it/content/configurare-path-relativi-log4j-utilizzando-spring\" rel=\"noreferrer\">http://www.megadix.it/content/configurare-path-relativi-log4j-utilizzando-spring</a></p>\n\n<p><strong>UPDATE (2009/08/01)</strong>\nI've translated my article to English:\n<a href=\"http://www.megadix.it/node/136\" rel=\"noreferrer\">http://www.megadix.it/node/136</a></p>\n" }, { "answer_id": 2009711, "author": "lizi", "author_id": 312292, "author_profile": "https://Stackoverflow.com/users/312292", "pm_score": 3, "selected": false, "text": "<p>Just a comment on <a href=\"https://stackoverflow.com/a/218037/2279200\">Iker's</a> solution. </p>\n\n<p><code>ServletContext</code> is a good solution for your problem. But I don't think it is good for maintains. Most of the time log files are required to be saved for long time. </p>\n\n<p>Since <code>ServletContext</code> makes the file under the deployed file, it will be removed when server is redeployed. My suggest is to go with rootPath's parent folder instead of child one.</p>\n" }, { "answer_id": 4528914, "author": "user553633", "author_id": 553633, "author_profile": "https://Stackoverflow.com/users/553633", "pm_score": 1, "selected": false, "text": "<p>My suggestion is the log file should always be logged above the root context of the webApp, so in case we redeploy the webApp, we don't want to override the existing log files.</p>\n" }, { "answer_id": 16067924, "author": "alex.antaniuk", "author_id": 1889743, "author_profile": "https://Stackoverflow.com/users/1889743", "pm_score": 1, "selected": false, "text": "<p>In case you're using Maven I have a great solution for you:</p>\n\n<ol>\n<li><p>Edit your pom.xml file to include following lines:</p>\n\n<pre><code>&lt;profiles&gt;\n &lt;profile&gt;\n &lt;id&gt;linux&lt;/id&gt;\n &lt;activation&gt;\n &lt;os&gt;\n &lt;family&gt;unix&lt;/family&gt;\n &lt;/os&gt;\n &lt;/activation&gt;\n &lt;properties&gt;\n &lt;logDirectory&gt;/var/log/tomcat6&lt;/logDirectory&gt;\n &lt;/properties&gt;\n &lt;/profile&gt;\n &lt;profile&gt;\n &lt;id&gt;windows&lt;/id&gt;\n &lt;activation&gt;\n &lt;os&gt;\n &lt;family&gt;windows&lt;/family&gt;\n &lt;/os&gt;\n &lt;/activation&gt;\n &lt;properties&gt;\n &lt;logDirectory&gt;${catalina.home}/logs&lt;/logDirectory&gt;\n &lt;/properties&gt;\n &lt;/profile&gt;\n&lt;/profiles&gt;\n</code></pre>\n\n<p>Here you define <code>logDirectory</code> property specifically to OS family.</p></li>\n<li><p>Use already defined <code>logDirectory</code> property in <code>log4j.properties</code> file:</p>\n\n<pre><code>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</code></pre></li>\n<li>That's it!</li>\n</ol>\n\n<p><strong>P.S.:</strong> I'm sure this can be achieved using Ant but unfortunately I don't have enough experience with it.</p>\n" }, { "answer_id": 27021823, "author": "Wolfgang Liebich", "author_id": 3933215, "author_profile": "https://Stackoverflow.com/users/3933215", "pm_score": 2, "selected": false, "text": "<p>As a further comment on <a href=\"https://stackoverflow.com/a/218037/2279200\">https://stackoverflow.com/a/218037/2279200</a> - this may break, if the web app implicitely starts other ServletContextListener's, which may get called earlier and which already try to use log4j - in this case, the log4j configuration will be read and parsed already before the property determining the log root directory is set => the log files will appear somewhere below the current directory (the current directory when starting tomcat).</p>\n\n<p>I could only think of following solution to this problem:\n- rename your log4j.properties (or logj4.xml) file to something which log4j will not automatically read.\n- In your context filter, after setting the property, call the DOM/PropertyConfigurator helper class to ensure that your log4j-.{xml,properties} is read\n- Reset the log4j configuration (IIRC there is a method to do that)</p>\n\n<p>This is a bit brute force, but methinks it is the only way to make it watertight.</p>\n" }, { "answer_id": 32379393, "author": "starikoff", "author_id": 2369544, "author_profile": "https://Stackoverflow.com/users/2369544", "pm_score": 1, "selected": false, "text": "<p>My solution is similar to Iker Jimenez's <a href=\"https://stackoverflow.com/a/218037/2369544\">solution</a>, but instead of using <code>System.setProperty(...)</code> I use <code>org.apache.log4j.PropertyConfigurator.configure(Properties)</code>. For that I also need log4j to be unable to find its configuration on its own and I load it manually (both points described in Wolfgang Liebich's <a href=\"https://stackoverflow.com/a/27021823/2369544\">answer</a>).</p>\n\n<p>This works for Jetty and Tomcat, standalone or run from IDE, requires zero configuration, allows to put each app's logs in their own folder, no matter how many apps inside the container (which is <a href=\"https://stackoverflow.com/questions/216781/log4j-configuring-a-web-app-to-use-a-relative-path#comment4207525_218037\">the problem</a> with the <code>System</code>-based solution). This way one can also put the log4j config file anywhere inside the web app (e.g. in one project we had all config files inside <code>WEB-INF/</code>).</p>\n\n<p>Details:</p>\n\n<ol>\n<li>I have my properties in the <code>log4j-no-autoload.properties</code> file in the classpath (e.g. in my Maven project it's originally in <code>src/main/resources</code>, gets packaged into <code>WEB-INF/classes</code>),</li>\n<li><p>It has the file appender configured as e.g.:</p>\n\n<pre><code>log4j.appender.MyAppFileAppender = org.apache.log4j.FileAppender\nlog4j.appender.MyAppFileAppender.file = ${webAppRoot}/WEB-INF/logs/my-app.log\n...\n</code></pre></li>\n<li><p>And I have a context listener like this (gets much shorter with Java 7's \"try-with-resource\" syntax):</p>\n\n<pre><code>@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</code></pre></li>\n</ol>\n" }, { "answer_id": 43460319, "author": "Dimitar II", "author_id": 4399576, "author_profile": "https://Stackoverflow.com/users/4399576", "pm_score": 1, "selected": false, "text": "<p>You can specify relative path to the log file, using the <strong>work directory</strong>:</p>\n\n<pre><code>appender.file.fileName = ${sys:user.dir}/log/application.log\n</code></pre>\n\n<p>This is independent from the servlet container and does not require passing custom variable to the system environment.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216781", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2697/" ]
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. What's the best way of doing this?
I've finally done it in this way. Added a ServletContextListener that does the following: ``` public void contextInitialized(ServletContextEvent event) { ServletContext context = event.getServletContext(); System.setProperty("rootPath", context.getRealPath("/")); } ``` Then in the log4j.properties file: ``` log4j.appender.file.File=${rootPath}WEB-INF/logs/MyLog.log ``` By doing it in this way Log4j will write into the right folder as long as you don't use it before the "rootPath" system property has been set. This means that you cannot use it from the ServletContextListener itself but you should be able to use it from anywhere else in the app. It should work on every web container and OS as it's not dependent on a container specific system property and it's not affected by OS specific path issues. Tested with Tomcat and Orion web containers and on Windows and Linux and it works fine so far. What do you think?
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": 216801, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 5, "selected": true, "text": "<p>I think fragment 5 is O(n^3), and similarly fragment 7 is O(n^5)*. It also looks like O(log(n)) for fragment 8.</p>\n\n<p>For the n * n problems, you have to execute the body of the loop n * n times, so it would be O(n^2), then you compound that with the order of the other code. Fragment 8 actually doubles the counter instead of incrementing it, so the larger the problem, the less additional work you have to do, so it's O(log(n))</p>\n\n<p><strong>*edit:</strong> Fragment 7 is O(n^5), not O(n^4) as I previously thought. This is because both j <i>and k</i> go from 1 to n * n. Sorry I didn't catch this earlier.</p>\n" }, { "answer_id": 216802, "author": "smaclell", "author_id": 22914, "author_profile": "https://Stackoverflow.com/users/22914", "pm_score": 0, "selected": false, "text": "<p>You appear to be on the right track. With regards to the N*N what effect do you think it would have? It is another factor of N so it would likely be a higher order.</p>\n\n<p>Just a warning, I saw another post like this and it was extremely down voted. Be careful. <a href=\"https://stackoverflow.com/questions/216496/logic-equivalence-question\">Here</a> is the post.</p>\n" }, { "answer_id": 216824, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 2, "selected": false, "text": "<p>For case 8 try writing out the number of iterations for some values of N and see what the pattern looks like ... it isn't O(N)</p>\n" }, { "answer_id": 219366, "author": "Dave L.", "author_id": 3093, "author_profile": "https://Stackoverflow.com/users/3093", "pm_score": 3, "selected": false, "text": "<p>Fragment 7 is O(n^5), not O(n^4) as the currently accepted comment claims. Otherwise, it's correct.</p>\n" }, { "answer_id": 8121746, "author": "Arnab Datta", "author_id": 528617, "author_profile": "https://Stackoverflow.com/users/528617", "pm_score": 0, "selected": false, "text": "<p>You are on the right track, but here is a tip as to how things might get clearer along the way. Suppose you have some code :</p>\n\n<pre><code>for(i = 0; i &lt; n; i++) {\n for(j = 0; j &lt; 100; j++){....}\n}\n</code></pre>\n\n<p>Right, consider the fact that you have code at different levels. In this example, you can only see 3 levels so far :</p>\n\n<ol>\n<li>The outer for-loop that goes from 0-n</li>\n<li>Another for-loop that goes from 0-100</li>\n<li>Some code inside, that is marked as <code>...</code></li>\n</ol>\n\n<p>At no point in time should you try to calculate it all in 1 go. This is where most beginners make some kind of arithmetic error. Calculate it individually for each level and then multiply it all together.</p>\n\n<p>Good luck!</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216796", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14013/" ]
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? ``` //Fragment 1 for(int i = 0; i < n; i++) sum++; ``` I'm thinking O(N) for fragment 1 ``` //Fragment 2 for(int i = 0; i < n; i+=2) sum++; ``` O(N) for fragment 2 as well ``` //Fragment 3 for(int i = 0; i < n; i++) for( int j = 0; j < n; j++) sum++; ``` O(N^2) for fragment 3 ``` //Fragment 4 for(int i = 0; i < n; i+=2) sum++; for(int j = 0; j < n; j++) sum++; ``` O(N) for fragment 4 ``` //Fragment 5 for(int i = 0; i < n; i++) for( int j = 0; j < n * n; j++) sum++; ``` O(N^2) for fragment 5 but the n \* n is throwing me off a bit so I'm not quite sure ``` //Fragment 6 for(int i = 0; i < n; i++) for( int j = 0; j < i; j++) sum++; ``` O(N^2) for fragment 6 as well ``` //Fragment 7 for(int i = 0; i < n; i++) for( int j = 0; j < n * n; j++) for(int k = 0; k < j; k++) sum++; ``` O(N^3) for fragment 7 but once again the n \* n is throwing me off ``` //Fragment 8 for(int i = 1; i < n; i = i * 2) sum++; ``` O(N) for fragment 8
I think fragment 5 is O(n^3), and similarly fragment 7 is O(n^5)\*. It also looks like O(log(n)) for fragment 8. For the n \* n problems, you have to execute the body of the loop n \* n times, so it would be O(n^2), then you compound that with the order of the other code. Fragment 8 actually doubles the counter instead of incrementing it, so the larger the problem, the less additional work you have to do, so it's O(log(n)) **\*edit:** Fragment 7 is O(n^5), not O(n^4) as I previously thought. This is because both j *and k* go from 1 to n \* n. Sorry I didn't catch this earlier.
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": 216880, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 2, "selected": false, "text": "<p>I believe it is a problem with PowerShell running in a MTA Thread. You can run the CTP of Version 2 in a STA (single threaded apartment) mode and it will pull up the proper folder selection. It does pull the menu up behind the shell window though.</p>\n" }, { "answer_id": 217062, "author": "Steven Murawski", "author_id": 1233, "author_profile": "https://Stackoverflow.com/users/1233", "pm_score": 0, "selected": false, "text": "<p>Just FYI, if you are looking to do Windows Forms stuff, there is one product currently out that will do windows forms for PowerShell (The <a href=\"http://www.adminscripteditor.com/\" rel=\"nofollow noreferrer\">Admin Script Editor</a>) and Sapien is working on a <a href=\"http://hosted.verticalresponse.com/172892/13e80641d0/176000434/c46cbf224d/\" rel=\"nofollow noreferrer\">Forms Designer</a> (announced on the <a href=\"http://powerscripting.wordpress.com/2008/10/12/episode-45-rockin-roundtable/\" rel=\"nofollow noreferrer\">PowerScripting Podcast</a>), which might smooth out some of these issues for your script.</p>\n" }, { "answer_id": 217527, "author": "Gordon Bell", "author_id": 16473, "author_profile": "https://Stackoverflow.com/users/16473", "pm_score": 5, "selected": true, "text": "<p>I encountered this problem a while back and found the following COM workaround on the MSDN forums:</p>\n\n<pre><code>$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</code></pre>\n\n<p><a href=\"http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.dotnet.framework.windowsforms.controls&amp;tid=3607557a-43b3-40bf-8276-be00526e0520&amp;p=1\" rel=\"noreferrer\">http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.dotnet.framework.windowsforms.controls&amp;tid=3607557a-43b3-40bf-8276-be00526e0520&amp;p=1</a></p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2495/" ]
Similar to [this question](https://stackoverflow.com/questions/216710/call-openfiledialog-from-powershell), 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: ``` [void] [Reflection.Assembly]::LoadWithPartialName( 'System.Windows.Forms' ) $d = New-Object Windows.Forms.FolderBrowserDialog $d.ShowDialog( ) ```
I encountered this problem a while back and found the following COM workaround on the MSDN forums: ``` $app = new-object -com Shell.Application $folder = $app.BrowseForFolder(0, "Select Folder", 0, "C:\") if ($folder.Self.Path -ne "") {write-host "You selected " $folder.Self.Path} ``` <http://www.microsoft.com/communities/newsgroups/en-us/default.aspx?dg=microsoft.public.dotnet.framework.windowsforms.controls&tid=3607557a-43b3-40bf-8276-be00526e0520&p=1>
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": "<p>Lambda:</p>\n\n<pre><code>if (Directory.Exists(uploadDirectory)) \n Directory.GetFiles(uploadDirectory)\n .Where(f =&gt; File.GetLastWriteTime(file) &lt; DateTime.Now.AddHours(-12))\n .Each(f =&gt; File.Delete(f));\n</code></pre>\n\n<p>Edit: On 2nd thought, you can avoid the security lookups on each File access by using DirectoryInfo and FileInfo instead of the static File methods:</p>\n\n<pre><code>var di = new DirectoryInfo(uploadDirectory);\nif (di.Exists()) {\n di.GetFiles()\n .Where(f =&gt; f.LastWriteTime &lt; DateTime.Now.AddHours(-12))\n .Each(f=&gt; f.Delete());\n}\n</code></pre>\n\n<p>And for those missing their own Each method:</p>\n\n<pre><code>void Each&lt;T&gt;(this IEnumerable e, Action&lt;T&gt; action) {\n foreach (T t in e) {\n action(t);\n }\n}\n</code></pre>\n\n<p>To make this really crazy, and fit the C# 3.0 theme, let's throw in an anonymous type:</p>\n\n<pre><code>di.GetFiles().Select(f =&gt; new() {\n Delete = f.LastWriteTime &lt; DateTime.Now.AddHours(-12) ? f.Delete : () =&gt; { }\n}).Delete();\n</code></pre>\n\n<p>But that just doesn't make any sense. ;)</p>\n" }, { "answer_id": 216836, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 2, "selected": false, "text": "<p>Well, the first bit maps quite neatly to a LINQ query... but there is (deliberately) no ForEach in regular LINQ. We can annoy Eric and add one, though ;-p</p>\n\n<p>So the following uses LINQ and a custom extension method - but we could re-write the <em>exact</em> same code (i.e. the same IL) as:</p>\n\n<ul>\n<li>query syntax (as below)</li>\n<li>fluent syntax (.Where().Select() ec)</li>\n<li>explicit static (Enumerable.Where(...))</li>\n<li>lambdas vs anonymous methods vs named methods (last changes the IL)</li>\n<li>delegates with/without the abbreviated (C# 2.0) delegate \"new\" syntax</li>\n<li>generic calls with/without generic type inference (Where() vs Where&lt;T&gt;())</li>\n<li>call to File.Delete vs call to x=>File.Delete(x) etc</li>\n</ul>\n\n<p>etc</p>\n\n<pre><code>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) &lt; DateTime.Now.AddHours(-12)\n select filename;\n files.ForEach(File.Delete); \n }\n}\nstatic void ForEach&lt;T&gt;(this IEnumerable&lt;T&gt; items, Action&lt;T&gt; action)\n{\n foreach (T item in items)\n {\n action(item);\n }\n}\n</code></pre>\n\n<p>We could write the <code>DateTime</code> code with a custom <code>Expression</code>, but that would be overkill...</p>\n\n<p>However, I doubt we could ever run out of ways of writing it ;-p</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216822", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27860/" ]
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. 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? ``` 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) < DateTime.Now) { File.Delete(filename); } } } ```
Lambda: ``` if (Directory.Exists(uploadDirectory)) Directory.GetFiles(uploadDirectory) .Where(f => File.GetLastWriteTime(file) < DateTime.Now.AddHours(-12)) .Each(f => File.Delete(f)); ``` Edit: On 2nd thought, you can avoid the security lookups on each File access by using DirectoryInfo and FileInfo instead of the static File methods: ``` var di = new DirectoryInfo(uploadDirectory); if (di.Exists()) { di.GetFiles() .Where(f => f.LastWriteTime < DateTime.Now.AddHours(-12)) .Each(f=> f.Delete()); } ``` And for those missing their own Each method: ``` void Each<T>(this IEnumerable e, Action<T> action) { foreach (T t in e) { action(t); } } ``` To make this really crazy, and fit the C# 3.0 theme, let's throw in an anonymous type: ``` di.GetFiles().Select(f => new() { Delete = f.LastWriteTime < DateTime.Now.AddHours(-12) ? f.Delete : () => { } }).Delete(); ``` But that just doesn't make any sense. ;)
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": "<p>In the case of an empty string, your code assumes that adding 1 to <code>string::npos</code> gives 0. <code>string::npos</code> is of type <code>string::size_type</code>, which is unsigned. Thus, you are relying on the overflow behaviour of addition.</p>\n" }, { "answer_id": 216883, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 9, "selected": false, "text": "<p>Using <a href=\"http://www.boost.org/doc/libs/1_58_0/doc/html/string_algo/usage.html#idp424359600\" rel=\"noreferrer\">Boost's string algorithms</a> would be easiest:</p>\n\n<pre><code>#include &lt;boost/algorithm/string.hpp&gt;\n\nstd::string str(\"hello world! \");\nboost::trim_right(str);\n</code></pre>\n\n<p><code>str</code> is now <code>\"hello world!\"</code>. There's also <code>trim_left</code> and <code>trim</code>, which trims both sides.</p>\n\n<hr>\n\n<p>If you add <code>_copy</code> suffix to any of above function names e.g. <code>trim_copy</code>, the function will return a trimmed copy of the string instead of modifying it through a reference.</p>\n\n<p>If you add <code>_if</code> suffix to any of above function names e.g. <code>trim_copy_if</code>, you can trim all characters satisfying your custom predicate, as opposed to just whitespaces.</p>\n" }, { "answer_id": 216897, "author": "Steve", "author_id": 27893, "author_profile": "https://Stackoverflow.com/users/27893", "pm_score": 2, "selected": false, "text": "<p>I'm not sure if your environment is the same, but in mine, the empty string case will cause the program to abort. I would either wrap that erase call with an if(!s.empty()) or use Boost as already mentioned. </p>\n" }, { "answer_id": 216946, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 4, "selected": false, "text": "<p>Hacked off of <a href=\"http://www.cplusplus.com/reference/string/string/find_last_not_of.html\" rel=\"nofollow noreferrer\">Cplusplus.com</a></p>\n\n<pre><code>std::string choppa(const std::string &amp;t, const std::string &amp;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</code></pre>\n\n<p>This works for the null case as well. :-)</p>\n" }, { "answer_id": 217605, "author": "Evan Teran", "author_id": 13430, "author_profile": "https://Stackoverflow.com/users/13430", "pm_score": 10, "selected": false, "text": "<p><strong>EDIT</strong> Since c++17, some parts of the standard library were removed. Fortunately, starting with c++11, we have lambdas which are a superior solution.</p>\n<pre><code>#include &lt;algorithm&gt; \n#include &lt;cctype&gt;\n#include &lt;locale&gt;\n\n// trim from start (in place)\nstatic inline void ltrim(std::string &amp;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 &amp;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 &amp;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</code></pre>\n<p>Thanks to <a href=\"https://stackoverflow.com/a/44973498/524503\">https://stackoverflow.com/a/44973498/524503</a> for bringing up the modern solution.</p>\n<h2>Original answer:</h2>\n<p>I tend to use one of these 3 for my trimming needs:</p>\n<pre><code>#include &lt;algorithm&gt; \n#include &lt;functional&gt; \n#include &lt;cctype&gt;\n#include &lt;locale&gt;\n\n// trim from start\nstatic inline std::string &amp;ltrim(std::string &amp;s) {\n s.erase(s.begin(), std::find_if(s.begin(), s.end(),\n std::not1(std::ptr_fun&lt;int, int&gt;(std::isspace))));\n return s;\n}\n\n// trim from end\nstatic inline std::string &amp;rtrim(std::string &amp;s) {\n s.erase(std::find_if(s.rbegin(), s.rend(),\n std::not1(std::ptr_fun&lt;int, int&gt;(std::isspace))).base(), s.end());\n return s;\n}\n\n// trim from both ends\nstatic inline std::string &amp;trim(std::string &amp;s) {\n return ltrim(rtrim(s));\n}\n</code></pre>\n<p>They are fairly self-explanatory and work very well.</p>\n<p><strong>EDIT</strong>: BTW, I have <code>std::ptr_fun</code> in there to help disambiguate <code>std::isspace</code> because there is actually a second definition which supports locales. This could have been a cast just the same, but I tend to like this better.</p>\n<p><strong>EDIT</strong>: To address some comments about accepting a parameter by reference, modifying and returning it. I Agree. An implementation that I would likely prefer would be two sets of functions, one for in place and one which makes a copy. A better set of examples would be:</p>\n<pre><code>#include &lt;algorithm&gt; \n#include &lt;functional&gt; \n#include &lt;cctype&gt;\n#include &lt;locale&gt;\n\n// trim from start (in place)\nstatic inline void ltrim(std::string &amp;s) {\n s.erase(s.begin(), std::find_if(s.begin(), s.end(),\n std::not1(std::ptr_fun&lt;int, int&gt;(std::isspace))));\n}\n\n// trim from end (in place)\nstatic inline void rtrim(std::string &amp;s) {\n s.erase(std::find_if(s.rbegin(), s.rend(),\n std::not1(std::ptr_fun&lt;int, int&gt;(std::isspace))).base(), s.end());\n}\n\n// trim from both ends (in place)\nstatic inline void trim(std::string &amp;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</code></pre>\n<p>I am keeping the original answer above though for context and in the interest of keeping the high voted answer still available.</p>\n" }, { "answer_id": 347974, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 6, "selected": false, "text": "<p>Use the following code to right trim (trailing) spaces and tab characters from <code>std::strings</code> (<a href=\"http://ideone.com/FcTBRe\" rel=\"noreferrer\">ideone</a>):</p>\n\n<pre><code>// 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</code></pre>\n\n<p>And just to balance things out, I'll include the left trim code too (<a href=\"http://ideone.com/TdxhZm\" rel=\"noreferrer\">ideone</a>):</p>\n\n<pre><code>// trim leading spaces\nsize_t startpos = str.find_first_not_of(\" \\t\");\nif( string::npos != startpos )\n{\n str = str.substr( startpos );\n}\n</code></pre>\n" }, { "answer_id": 1792361, "author": "Corwin Joy", "author_id": 150709, "author_profile": "https://Stackoverflow.com/users/150709", "pm_score": 2, "selected": false, "text": "<p>The above methods are great, but sometimes you want to use a combination of functions for what your routine considers to be whitespace. In this case, using functors to combine operations can get messy so I prefer a simple loop I can modify for the trim. Here is a slightly modified trim function copied from the C version here on SO. In this example, I am trimming non alphanumeric characters.</p>\n\n<pre><code>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 &gt; str &amp;&amp; !isalnum(*end)) end--;\n\n return string(str, end+1);\n}\n</code></pre>\n" }, { "answer_id": 2919237, "author": "tzaman", "author_id": 257465, "author_profile": "https://Stackoverflow.com/users/257465", "pm_score": 2, "selected": false, "text": "<p>Here's what I came up with: </p>\n\n<pre><code>std::stringstream trimmer;\ntrimmer &lt;&lt; str;\ntrimmer &gt;&gt; str;\n</code></pre>\n\n<p>Stream extraction eliminates whitespace automatically, so this works like a charm.<br>\nPretty clean and elegant too, if I do say so myself. ;)</p>\n" }, { "answer_id": 3177560, "author": "Michaël Schoonbrood", "author_id": 383432, "author_profile": "https://Stackoverflow.com/users/383432", "pm_score": 5, "selected": false, "text": "<p>I like tzaman's solution, the only problem with it is that it doesn't trim a string containing only spaces.</p>\n\n<p>To correct that 1 flaw, add a str.clear() in between the 2 trimmer lines</p>\n\n<pre><code>std::stringstream trimmer;\ntrimmer &lt;&lt; str;\nstr.clear();\ntrimmer &gt;&gt; str;\n</code></pre>\n" }, { "answer_id": 3559481, "author": "Brian", "author_id": 429872, "author_profile": "https://Stackoverflow.com/users/429872", "pm_score": 1, "selected": false, "text": "<p>This version trims internal whitespace and non-alphanumerics:</p>\n\n<pre><code>static inline std::string &amp;trimAll(std::string &amp;s)\n{ \n if(s.size() == 0)\n {\n return s;\n }\n\n int val = 0;\n for (int cur = 0; cur &lt; s.size(); cur++)\n {\n if(s[cur] != ' ' &amp;&amp; std::isalnum(s[cur]))\n {\n s[val] = s[cur];\n val++;\n }\n }\n s.resize(val);\n return s;\n}\n</code></pre>\n" }, { "answer_id": 6500499, "author": "user818330", "author_id": 818330, "author_profile": "https://Stackoverflow.com/users/818330", "pm_score": 6, "selected": false, "text": "<p>Try this, it works for me.</p>\n<pre><code>inline std::string trim(std::string&amp; 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</code></pre>\n" }, { "answer_id": 15649849, "author": "Brian W.", "author_id": 977913, "author_profile": "https://Stackoverflow.com/users/977913", "pm_score": 1, "selected": false, "text": "<p>Yet another option - removes one or more characters from both ends.</p>\n\n<pre><code>string strip(const string&amp; s, const string&amp; chars=\" \") {\n size_t begin = 0;\n size_t end = s.size()-1;\n for(; begin &lt; s.size(); begin++)\n if(chars.find_first_of(s[begin]) == string::npos)\n break;\n for(; end &gt; begin; end--)\n if(chars.find_first_of(s[end]) == string::npos)\n break;\n return s.substr(begin, end-begin+1);\n}\n</code></pre>\n" }, { "answer_id": 16743707, "author": "DavidRR", "author_id": 1497596, "author_profile": "https://Stackoverflow.com/users/1497596", "pm_score": 4, "selected": false, "text": "<p>My solution based on the <a href=\"https://stackoverflow.com/a/347974/1497596\">answer by @Bill the Lizard</a>.</p>\n\n<p>Note that these functions will return the empty string if the input string contains nothing but whitespace.</p>\n\n<pre class=\"lang-cpp prettyprint-override\"><code>const std::string StringUtils::WHITESPACE = \" \\n\\r\\t\";\n\nstd::string StringUtils::Trim(const std::string&amp; s)\n{\n return TrimRight(TrimLeft(s));\n}\n\nstd::string StringUtils::TrimLeft(const std::string&amp; 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&amp; 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</code></pre>\n" }, { "answer_id": 17976541, "author": "David G", "author_id": 1435420, "author_profile": "https://Stackoverflow.com/users/1435420", "pm_score": 6, "selected": false, "text": "<p>Bit late to the party, but never mind. Now C++11 is here, we have lambdas and auto variables. So my version, which also handles all-whitespace and empty strings, is:</p>\n\n<pre><code>#include &lt;cctype&gt;\n#include &lt;string&gt;\n#include &lt;algorithm&gt;\n\ninline std::string trim(const std::string &amp;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&lt;=wsfront ? std::string() : std::string(wsfront,wsback));\n}\n</code></pre>\n\n<p>We could make a reverse iterator from <code>wsfront</code> and use that as the termination condition in the second <code>find_if_not</code> but that's only useful in the case of an all-whitespace string, and gcc 4.8 at least isn't smart enough to infer the type of the reverse iterator (<code>std::string::const_reverse_iterator</code>) with <code>auto</code>. I don't know how expensive constructing a reverse iterator is, so YMMV here. With this alteration, the code looks like this:</p>\n\n<pre><code>inline std::string trim(const std::string &amp;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</code></pre>\n" }, { "answer_id": 18465058, "author": "Some programmer dude", "author_id": 440558, "author_profile": "https://Stackoverflow.com/users/440558", "pm_score": 3, "selected": false, "text": "<p>With C++11 also came a <a href=\"http://en.cppreference.com/w/cpp/regex\" rel=\"noreferrer\">regular expression</a> module, which of course can be used to trim leading or trailing spaces.</p>\n\n<p>Maybe something like this:</p>\n\n<pre><code>std::string ltrim(const std::string&amp; 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&amp; 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&amp; s)\n{\n return ltrim(rtrim(s));\n}\n</code></pre>\n" }, { "answer_id": 19167699, "author": "Duncan", "author_id": 945011, "author_profile": "https://Stackoverflow.com/users/945011", "pm_score": 2, "selected": false, "text": "<p>What about this...?</p>\n\n<pre><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;regex&gt;\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 &lt;&lt; \"-\" &lt;&lt; trim( str ) &lt;&lt; \"-\\n\";\n return 0;\n\n}\n</code></pre>\n\n<p>Note: I'm still relatively new to C++, so please forgive me if I'm off base here.</p>\n" }, { "answer_id": 19941683, "author": "synaptik", "author_id": 1325279, "author_profile": "https://Stackoverflow.com/users/1325279", "pm_score": 3, "selected": false, "text": "<p>This is what I use. Just keep removing space from the front, and then, if there's anything left, do the same from the back.</p>\n\n<pre><code>void trim(string&amp; s) {\n while(s.compare(0,1,\" \")==0)\n s.erase(s.begin()); // remove leading whitespaces\n while(s.size()&gt;0 &amp;&amp; s.compare(s.size()-1,1,\" \")==0)\n s.erase(s.end()-1); // remove trailing whitespaces\n}\n</code></pre>\n" }, { "answer_id": 20023250, "author": "Jorma Rebane", "author_id": 1951829, "author_profile": "https://Stackoverflow.com/users/1951829", "pm_score": 3, "selected": false, "text": "<p>I guess if you start asking for the \"best way\" to trim a string, I'd say a good implementation would be one that:</p>\n\n<ol>\n<li>Doesn't allocate temporary strings</li>\n<li>Has overloads for in-place trim and copy trim</li>\n<li>Can be easily customized to accept different validation sequences / logic</li>\n</ol>\n\n<p>Obviously there are too many different ways to approach this and it definitely depends on what you actually need. However, the C standard library still has some very useful functions in &lt;string.h&gt;, like memchr. There's a reason why C is still regarded as the best language for IO - its stdlib is pure efficiency.</p>\n\n<pre><code>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&amp; 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 &lt;&lt; \"'\" &lt;&lt; trimmed &lt;&lt; \"'\" &lt;&lt; endl;\n\n system(\"pause\");\n return 0;\n}\n</code></pre>\n" }, { "answer_id": 20262860, "author": "Alexander Drichel", "author_id": 1872824, "author_profile": "https://Stackoverflow.com/users/1872824", "pm_score": 0, "selected": false, "text": "<pre><code>std::string trim( std::string &amp;&amp; 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</code></pre>\n" }, { "answer_id": 21698913, "author": "Pushkoff", "author_id": 2090997, "author_profile": "https://Stackoverflow.com/users/2090997", "pm_score": 5, "selected": false, "text": "<p><a href=\"http://ideone.com/nFVtEo\">http://ideone.com/nFVtEo</a></p>\n\n<pre><code>std::string trim(const std::string &amp;s)\n{\n std::string::const_iterator it = s.begin();\n while (it != s.end() &amp;&amp; isspace(*it))\n it++;\n\n std::string::const_reverse_iterator rit = s.rbegin();\n while (rit.base() != it &amp;&amp; isspace(*rit))\n rit++;\n\n return std::string(it, rit.base());\n}\n</code></pre>\n" }, { "answer_id": 22816847, "author": "Bondolin", "author_id": 1399272, "author_profile": "https://Stackoverflow.com/users/1399272", "pm_score": 0, "selected": false, "text": "<p>This any good? (Cause this post totally needs another answer :)</p>\n\n<pre><code>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</code></pre>\n\n<p>Similar case for the trimEnd, just reverse the polari- er, indices.</p>\n" }, { "answer_id": 23485459, "author": "vmrob", "author_id": 1843978, "author_profile": "https://Stackoverflow.com/users/1843978", "pm_score": 3, "selected": false, "text": "<p>Contributing my solution to the noise. <code>trim</code> defaults to creating a new string and returning the modified one while <code>trim_in_place</code> modifies the string passed to it. The <code>trim</code> function supports c++11 move semantics.</p>\n\n<pre><code>#include &lt;string&gt;\n\n// modifies input string, returns input\n\nstd::string&amp; trim_left_in_place(std::string&amp; str) {\n size_t i = 0;\n while(i &lt; str.size() &amp;&amp; isspace(str[i])) { ++i; };\n return str.erase(0, i);\n}\n\nstd::string&amp; trim_right_in_place(std::string&amp; str) {\n size_t i = str.size();\n while(i &gt; 0 &amp;&amp; isspace(str[i - 1])) { --i; };\n return str.erase(i, str.size());\n}\n\nstd::string&amp; trim_in_place(std::string&amp; 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 &lt;cassert&gt;\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</code></pre>\n" }, { "answer_id": 25385766, "author": "Galik", "author_id": 3807729, "author_profile": "https://Stackoverflow.com/users/3807729", "pm_score": 6, "selected": false, "text": "<p>What you are doing is fine and robust. I have used the same method for a long time and I have yet to find a faster method:</p>\n\n<pre><code>const char* ws = \" \\t\\n\\r\\f\\v\";\n\n// trim from end of string (right)\ninline std::string&amp; rtrim(std::string&amp; 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&amp; ltrim(std::string&amp; 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&amp; trim(std::string&amp; s, const char* t = ws)\n{\n return ltrim(rtrim(s, t), t);\n}\n</code></pre>\n\n<p>By supplying the characters to be trimmed you have the flexibility to trim non-whitespace characters and the efficiency to trim only the characters you want trimmed.</p>\n" }, { "answer_id": 27788112, "author": "mbgda", "author_id": 4421195, "author_profile": "https://Stackoverflow.com/users/4421195", "pm_score": 3, "selected": false, "text": "<p>For what it's worth, here is a trim implementation with an eye towards performance. It's much quicker than many other trim routines I've seen around. Instead of using iterators and std::finds, it uses raw c strings and indices. It optimizes the following special cases: size 0 string (do nothing), string with no whitespace to trim (do nothing), string with only trailing whitespace to trim (just resize the string), string that's entirely whitespace (just clear the string). And finally, in the worst case (string with leading whitespace), it does its best to perform an efficient copy construction, performing only 1 copy and then moving that copy in place of the original string.</p>\n\n<pre><code>void TrimString(std::string &amp; 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 &lt; str.length() &amp;&amp; std::isspace(int(pStr[front]))) {++front;}\n\n size_t back = str.length();\n while(back &gt; front &amp;&amp; std::isspace(int(pStr[back-1]))) {--back;}\n\n if(0 == front)\n {\n if(back &lt; str.length())\n {\n str.resize(back - front);\n }\n }\n else if(back &lt;= front)\n {\n str.clear();\n }\n else\n {\n str = std::move(std::string(str.begin()+front, str.begin()+back));\n }\n}\n</code></pre>\n" }, { "answer_id": 29185584, "author": "Clay Freeman", "author_id": 1114073, "author_profile": "https://Stackoverflow.com/users/1114073", "pm_score": 3, "selected": false, "text": "<p>My answer is an improvement upon the <a href=\"https://stackoverflow.com/a/217605/1114073\">top answer</a> for this post that trims control characters as well as spaces (0-32 and 127 on the <a href=\"http://www.asciitable.com/\" rel=\"nofollow noreferrer\">ASCII table</a>).</p>\n\n<p><a href=\"http://en.cppreference.com/w/cpp/string/byte/isgraph\" rel=\"nofollow noreferrer\"><code>std::isgraph</code></a> determines if a character has a graphical representation, so you can use this to alter Evan's answer to remove any character that doesn't have a graphical representation from either side of a string. The result is a much more elegant solution:</p>\n\n<pre><code>#include &lt;algorithm&gt;\n#include &lt;functional&gt;\n#include &lt;string&gt;\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&amp;\n */\nstd::string&amp; ltrim(std::string&amp; s) {\n s.erase(s.begin(), std::find_if(s.begin(), s.end(),\n std::ptr_fun&lt;int, int&gt;(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&amp;\n */\nstd::string&amp; rtrim(std::string&amp; s) {\n s.erase(std::find_if(s.rbegin(), s.rend(),\n std::ptr_fun&lt;int, int&gt;(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&amp;\n */\nstd::string&amp; trim(std::string&amp; s) {\n return ltrim(rtrim(s));\n}\n</code></pre>\n\n<p><strong>Note:</strong> Alternatively you should be able to use <a href=\"http://en.cppreference.com/w/cpp/string/wide/iswgraph\" rel=\"nofollow noreferrer\"><code>std::iswgraph</code></a> if you need support for wide characters, but you will also have to edit this code to enable <code>std::wstring</code> manipulation, which is something that I haven't tested (see the reference page for <a href=\"http://en.cppreference.com/w/cpp/string/basic_string\" rel=\"nofollow noreferrer\"><code>std::basic_string</code></a> to explore this option).</p>\n" }, { "answer_id": 32071000, "author": "jha-G", "author_id": 4373992, "author_profile": "https://Stackoverflow.com/users/4373992", "pm_score": 3, "selected": false, "text": "<p>An elegant way of doing it can be like</p>\n\n<pre><code>std::string &amp; trim(std::string &amp; str)\n{\n return ltrim(rtrim(str));\n}\n</code></pre>\n\n<p>And the supportive functions are implemented as:</p>\n\n<pre><code>std::string &amp; ltrim(std::string &amp; str)\n{\n auto it = std::find_if( str.begin() , str.end() , [](char ch){ return !std::isspace&lt;char&gt;(ch , std::locale::classic() ) ; } );\n str.erase( str.begin() , it);\n return str; \n}\n\nstd::string &amp; rtrim(std::string &amp; str)\n{\n auto it = std::find_if( str.rbegin() , str.rend() , [](char ch){ return !std::isspace&lt;char&gt;(ch , std::locale::classic() ) ; } );\n str.erase( it.base() , str.end() );\n return str; \n}\n</code></pre>\n\n<p>And once you've all these in place, you can write this as well:</p>\n\n<pre><code>std::string trim_copy(std::string const &amp; str)\n{\n auto s = str;\n return ltrim(rtrim(s));\n}\n</code></pre>\n" }, { "answer_id": 33061006, "author": "Floella", "author_id": 2011041, "author_profile": "https://Stackoverflow.com/users/2011041", "pm_score": 0, "selected": false, "text": "<p>I'm using this one:</p>\n\n<pre><code>void trim(string &amp;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</code></pre>\n" }, { "answer_id": 33099753, "author": "freeboy1015", "author_id": 1210337, "author_profile": "https://Stackoverflow.com/users/1210337", "pm_score": 4, "selected": false, "text": "<pre><code>s.erase(0, s.find_first_not_of(\" \\n\\r\\t\")); \ns.erase(s.find_last_not_of(\" \\n\\r\\t\")+1); \n</code></pre>\n" }, { "answer_id": 33129986, "author": "GutiMac", "author_id": 4211031, "author_profile": "https://Stackoverflow.com/users/4211031", "pm_score": 3, "selected": false, "text": "<p>Trim C++11 implementation:</p>\n\n<pre><code>static void trim(std::string &amp;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</code></pre>\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": "<p>It seems I'm really late to the party - I can't believe this was asked 7 years ago! </p>\n\n<p>Here's my take on the problem. I'm working on a project and I didn't want to go through the trouble of using Boost right now. </p>\n\n<pre><code>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</code></pre>\n\n<p>This solution will trim from the left and the right. </p>\n" }, { "answer_id": 35117930, "author": "Brent Bradburn", "author_id": 86967, "author_profile": "https://Stackoverflow.com/users/86967", "pm_score": 3, "selected": false, "text": "<p>This can be done more simply in C++11 due to the addition of <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/back\" rel=\"noreferrer\"><code>back()</code></a> and <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/pop_back\" rel=\"noreferrer\"><code>pop_back()</code></a>.</p>\n\n<pre><code>while ( !s.empty() &amp;&amp; isspace(s.back()) ) s.pop_back();\n</code></pre>\n" }, { "answer_id": 35320881, "author": "user1438233", "author_id": 1438233, "author_profile": "https://Stackoverflow.com/users/1438233", "pm_score": 0, "selected": false, "text": "<p>c++11:</p>\n\n<pre><code>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 &lt;&lt; s;\n</code></pre>\n\n<p>output:</p>\n\n<pre><code>hello\n</code></pre>\n\n<p>works fine also with empty strings</p>\n" }, { "answer_id": 36000453, "author": "elxala", "author_id": 573554, "author_profile": "https://Stackoverflow.com/users/573554", "pm_score": 1, "selected": false, "text": "<p>As I wanted to update my old C++ trim function with a C++ 11 approach I have tested a lot of the posted answers to the question. My conclusion is that I keep my old C++ solution! </p>\n\n<p>It is the fastest one by large, even adding more characters to check (e.g. \\r\\n I see no use case for \\f\\v) is still faster than the solutions using algorithm.</p>\n\n<pre><code>std::string &amp; trimMe (std::string &amp; str)\n{\n // right trim\n while (str.length () &gt; 0 &amp;&amp; (str [str.length ()-1] == ' ' || str [str.length ()-1] == '\\t'))\n str.erase (str.length ()-1, 1);\n\n // left trim\n while (str.length () &gt; 0 &amp;&amp; (str [0] == ' ' || str [0] == '\\t'))\n str.erase (0, 1);\n return str;\n}\n</code></pre>\n" }, { "answer_id": 36169979, "author": "Kemin Zhou", "author_id": 2407363, "author_profile": "https://Stackoverflow.com/users/2407363", "pm_score": 2, "selected": false, "text": "<p>Here is a straight forward implementation. For such a simple operation, you probably should not be using any special constructs. The build-in isspace() function takes care of various forms of white characters, so we should take advantage of it. You also have to consider special cases where the string is empty or simply a bunch of spaces. Trim left or right could be derived from the following code.</p>\n\n<pre><code>string trimSpace(const string &amp;str) {\n if (str.empty()) return str;\n string::size_type i,j;\n i=0;\n while (i&lt;str.size() &amp;&amp; isspace(str[i])) ++i;\n if (i == str.size())\n return string(); // empty string\n j = str.size() - 1;\n //while (j&gt;0 &amp;&amp; isspace(str[j])) --j; // the j&gt;0 check is not needed\n while (isspace(str[j])) --j\n return str.substr(i, j-i+1);\n}\n</code></pre>\n" }, { "answer_id": 39252644, "author": "nulleight", "author_id": 789371, "author_profile": "https://Stackoverflow.com/users/789371", "pm_score": 2, "selected": false, "text": "<p>Here is my version:</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 41039262, "author": "cute_ptr", "author_id": 7152606, "author_profile": "https://Stackoverflow.com/users/7152606", "pm_score": 2, "selected": false, "text": "<p>Here's a solution easy to understand for beginners not used to write <code>std::</code> everywhere and not yet familiar with <code>const</code>-correctness, <code>iterator</code>s, STL <code>algorithm</code>s, etc...</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;cctype&gt; // for isspace\nusing namespace std;\n\n\n// Left trim the given string (\" hello! \" --&gt; \"hello! \")\nstring left_trim(string str) {\n int numStartSpaces = 0;\n for (int i = 0; i &lt; 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! \" --&gt; \" hello!\")\nstring right_trim(string str) {\n int numEndSpaces = 0;\n for (int i = str.length() - 1; i &gt;= 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! \" --&gt; \"hello!\")\nstring trim(string str) {\n return right_trim(left_trim(str));\n}\n</code></pre>\n\n<p>Hope it helps...</p>\n" }, { "answer_id": 51177287, "author": "Slesa", "author_id": 1136884, "author_profile": "https://Stackoverflow.com/users/1136884", "pm_score": -1, "selected": false, "text": "<p>It is so annoying that I </p>\n\n<ul>\n<li>have to google it </li>\n<li>find out that I have to use rocket science </li>\n<li>that there is no simple trim/toupper function in string</li>\n</ul>\n\n<p>For <strong>me</strong> this is the fastest way to solve it:</p>\n\n<pre><code>CString tmp(line.c_str());\ntmp = tmp.Trim().MakeLower();\nstring buffer = tmp;\n</code></pre>\n\n<p>Ok, it is cool that I can use lambda ops, iterators, and all the stuff. But I only need to deal with a string instead of a character...</p>\n" }, { "answer_id": 51274774, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<p>I know this is a very old question, but I have added a few lines of code to yours and it trims whitespace from both ends.</p>\n\n<pre><code>void trim(std::string &amp;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</code></pre>\n" }, { "answer_id": 52524877, "author": "UnSat", "author_id": 3195698, "author_profile": "https://Stackoverflow.com/users/3195698", "pm_score": 0, "selected": false, "text": "<p>Below is one pass(may be two pass) solution. It goes over the white spaces part of string twice and non-whitespace part once.</p>\n\n<pre><code>void trim(std::string&amp; s) { \n if (s.empty()) \n return; \n\n int l = 0, r = s.size() - 1; \n\n while (l &lt; s.size() &amp;&amp; std::isspace(s[l++])); // l points to first non-whitespace char. \n while (r &gt;= 0 &amp;&amp; std::isspace(s[r--])); // r points to last non-whitespace char. \n\n if (l &gt; r) \n s = \"\"; \n else { \n l--; \n r++; \n int wi = 0; \n while (l &lt;= r) \n s[wi++] = s[l++]; \n s.erase(wi); \n } \n return; \n} \n</code></pre>\n" }, { "answer_id": 54364173, "author": "Phidelux", "author_id": 1067846, "author_profile": "https://Stackoverflow.com/users/1067846", "pm_score": 5, "selected": false, "text": "<p>With C++17 you can use <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view/remove_prefix\" rel=\"noreferrer\">basic_string_view::remove_prefix</a> and <a href=\"https://en.cppreference.com/w/cpp/string/basic_string_view/remove_suffix\" rel=\"noreferrer\">basic_string_view::remove_suffix</a>:</p>\n\n<pre><code>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</code></pre>\n\n<p>A nice alternative:</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 57830674, "author": "Jackt", "author_id": 6406645, "author_profile": "https://Stackoverflow.com/users/6406645", "pm_score": 1, "selected": false, "text": "<p>Ok this maight not be the fastest but it's... simple.</p>\n\n<pre><code>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</code></pre>\n" }, { "answer_id": 58773060, "author": "Sadidul Islam", "author_id": 5884380, "author_profile": "https://Stackoverflow.com/users/5884380", "pm_score": 3, "selected": false, "text": "<p>Here is a solution for trim with regex</p>\n\n<pre><code>#include &lt;string&gt;\n#include &lt;regex&gt;\n\nstring trim(string str){\n return regex_replace(str, regex(\"(^[ ]+)|([ ]+$)\"),\"\");\n}\n</code></pre>\n" }, { "answer_id": 60243752, "author": "BullyWiiPlaza", "author_id": 3764804, "author_profile": "https://Stackoverflow.com/users/3764804", "pm_score": 0, "selected": false, "text": "<p>The accepted answer and even <code>Boost</code>'s version did not work for me, so I wrote the following version:</p>\n\n<pre><code>std::string trim(const std::string&amp; input) {\n std::stringstream string_stream;\n for (const auto character : input) {\n if (!isspace(character)) {\n string_stream &lt;&lt; character;\n }\n }\n\n return string_stream.str();\n}\n</code></pre>\n\n<p>This will remove any whitespace character from anywhere in the string and return a new copy of the string.</p>\n" }, { "answer_id": 62920164, "author": "Anil Gupta", "author_id": 6463728, "author_profile": "https://Stackoverflow.com/users/6463728", "pm_score": 0, "selected": false, "text": "<p>I have read most of the answers but did not found anyone making use of istringstream <br></p>\n<pre><code>std::string text = &quot;Let me split this into words&quot;;\n\nstd::istringstream iss(text);\nstd::vector&lt;std::string&gt; results((std::istream_iterator&lt;std::string&gt;(iss)),\n std::istream_iterator&lt;std::string&gt;());\n</code></pre>\n<p>The result is vector of words and it can deal with the strings having internal whitespace too, Hope this helped.</p>\n" }, { "answer_id": 63270770, "author": "antb52", "author_id": 4383009, "author_profile": "https://Stackoverflow.com/users/4383009", "pm_score": 0, "selected": false, "text": "<p>why not use lambda?</p>\n<pre><code>auto no_space = [](char ch) -&gt; bool {\n return !std::isspace&lt;char&gt;(ch, std::locale::classic());\n};\nauto ltrim = [](std::string&amp; s) -&gt; std::string&amp; {\n s.erase(s.begin(), std::find_if(s.begin(), s.end(), no_space));\n return s;\n};\nauto rtrim = [](std::string&amp; s) -&gt; std::string&amp; {\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) -&gt; std::string&amp; { return ltrim(rtrim(s)); };\nauto trim = [](std::string&amp; s) -&gt; std::string&amp; { return ltrim(rtrim(s)); };\n</code></pre>\n" }, { "answer_id": 63495628, "author": "ragnarius", "author_id": 165729, "author_profile": "https://Stackoverflow.com/users/165729", "pm_score": 0, "selected": false, "text": "<p>Trims both ends.</p>\n<pre><code>string trim(const std::string &amp;str){\n string result = &quot;&quot;;\n size_t endIndex = str.size();\n while (endIndex &gt; 0 &amp;&amp; isblank(str[endIndex-1]))\n endIndex -= 1;\n for (size_t i=0; i&lt;endIndex ; i+=1){\n char ch = str[i];\n if (!isblank(ch) || result.size()&gt;0)\n result += ch;\n }\n return result;\n}\n</code></pre>\n" }, { "answer_id": 65404298, "author": "Arty", "author_id": 941531, "author_profile": "https://Stackoverflow.com/users/941531", "pm_score": 3, "selected": false, "text": "<pre class=\"lang-cpp prettyprint-override\"><code>str.erase(0, str.find_first_not_of(&quot;\\t\\n\\v\\f\\r &quot;)); // left trim\nstr.erase(str.find_last_not_of(&quot;\\t\\n\\v\\f\\r &quot;) + 1); // right trim\n</code></pre>\n<p><a href=\"https://godbolt.org/z/bas15T71E\" rel=\"nofollow noreferrer\">Try it online!</a></p>\n" }, { "answer_id": 65730279, "author": "Matthias", "author_id": 232175, "author_profile": "https://Stackoverflow.com/users/232175", "pm_score": 0, "selected": false, "text": "<p>Poor man's string trim (spaces only):</p>\n<pre><code>std::string trimSpaces(const std::string&amp; str)\n{\n int start, len;\n \n for (start = 0; start &lt; str.size() &amp;&amp; str[start] == ' '; start++);\n for (len = str.size() - start; len &gt; 0 &amp;&amp; str[start + len - 1] == ' '; len--);\n \n return str.substr(start, len);\n}\n</code></pre>\n" }, { "answer_id": 72318641, "author": "Soumadip Dey", "author_id": 10439615, "author_profile": "https://Stackoverflow.com/users/10439615", "pm_score": 1, "selected": false, "text": "<p>you can you use this function to trim you string in c++</p>\n<pre><code>void trim(string&amp; str){\n while(str[0] == ' ') str.erase(str.begin());\n while(str[str.size() - 1] == ' ') str.pop_back();\n}\n</code></pre>\n" }, { "answer_id": 72545246, "author": "aiocat", "author_id": 19097062, "author_profile": "https://Stackoverflow.com/users/19097062", "pm_score": -1, "selected": false, "text": "<p>I think using a macro is a good practice in this example: (works on C++ 98)</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#define TRIM_CHARACTERS &quot; \\t\\n\\r\\f\\v&quot;\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</code></pre>\n<p>example:</p>\n<pre class=\"lang-cpp prettyprint-override\"><code>#include &lt;iostream&gt;\n#include &lt;string&gt;\n\n#define TRIM_CHARACTERS &quot; \\t\\n\\r\\f\\v&quot;\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(&quot; hello world!! \\t \\r&quot;);\n TRIM_STRING(text);\n std::cout &lt;&lt; text; // &quot;hello world!!&quot;\n}\n</code></pre>\n" }, { "answer_id": 73835621, "author": "Soup Endless", "author_id": 2170898, "author_profile": "https://Stackoverflow.com/users/2170898", "pm_score": 1, "selected": false, "text": "<p>using <code>std::find_if_not</code> and reverse iterator (no +1/-1 adjustments) and returning number of spaces trimmed</p>\n<pre><code>// returns number of spaces removed\nstd::size_t RoundTrim(std::string&amp; s)\n{\n auto const beforeTrim{ s.size() };\n\n auto isSpace{ [](auto const&amp; 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</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14690/" ]
I'm currently using the following code to right-trim all the `std::strings` in my programs: ``` std::string s; s.erase(s.find_last_not_of(" \n\r\t")+1); ``` It works fine, but I wonder if there are some end-cases where it might fail? Of course, answers with elegant alternatives and also left-trim solution are welcome.
**EDIT** Since c++17, some parts of the standard library were removed. Fortunately, starting with c++11, we have lambdas which are a superior solution. ``` #include <algorithm> #include <cctype> #include <locale> // trim from start (in place) static inline void ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), [](unsigned char ch) { return !std::isspace(ch); })); } // trim from end (in place) static inline void rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), [](unsigned char ch) { return !std::isspace(ch); }).base(), s.end()); } // trim from both ends (in place) static inline void trim(std::string &s) { rtrim(s); ltrim(s); } // trim from start (copying) static inline std::string ltrim_copy(std::string s) { ltrim(s); return s; } // trim from end (copying) static inline std::string rtrim_copy(std::string s) { rtrim(s); return s; } // trim from both ends (copying) static inline std::string trim_copy(std::string s) { trim(s); return s; } ``` Thanks to <https://stackoverflow.com/a/44973498/524503> for bringing up the modern solution. Original answer: ---------------- I tend to use one of these 3 for my trimming needs: ``` #include <algorithm> #include <functional> #include <cctype> #include <locale> // trim from start static inline std::string &ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); return s; } // trim from end static inline std::string &rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); return s; } // trim from both ends static inline std::string &trim(std::string &s) { return ltrim(rtrim(s)); } ``` They are fairly self-explanatory and work very well. **EDIT**: BTW, I have `std::ptr_fun` in there to help disambiguate `std::isspace` because there is actually a second definition which supports locales. This could have been a cast just the same, but I tend to like this better. **EDIT**: To address some comments about accepting a parameter by reference, modifying and returning it. I Agree. An implementation that I would likely prefer would be two sets of functions, one for in place and one which makes a copy. A better set of examples would be: ``` #include <algorithm> #include <functional> #include <cctype> #include <locale> // trim from start (in place) static inline void ltrim(std::string &s) { s.erase(s.begin(), std::find_if(s.begin(), s.end(), std::not1(std::ptr_fun<int, int>(std::isspace)))); } // trim from end (in place) static inline void rtrim(std::string &s) { s.erase(std::find_if(s.rbegin(), s.rend(), std::not1(std::ptr_fun<int, int>(std::isspace))).base(), s.end()); } // trim from both ends (in place) static inline void trim(std::string &s) { rtrim(s); ltrim(s); } // trim from start (copying) static inline std::string ltrim_copy(std::string s) { ltrim(s); return s; } // trim from end (copying) static inline std::string rtrim_copy(std::string s) { rtrim(s); return s; } // trim from both ends (copying) static inline std::string trim_copy(std::string s) { trim(s); return s; } ``` I am keeping the original answer above though for context and in the interest of keeping the high voted answer still available.
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": "<p>Nope - but you could use a template column:</p>\n\n<pre><code>&lt;script runat=\"server\"&gt;\n TResult Eval&lt;T, TResult&gt;(string field, Func&lt;T, TResult&gt; 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&lt;/script&gt;\n\n&lt;asp:TemplateField&gt;\n &lt;ItemTemplate&gt;\n &lt;%# Eval&lt;bool, string&gt;(\"Active\", b =&gt; b ? \"Yes\" : \"No\") %&gt;\n &lt;/ItemTemplate&gt;\n&lt;/asp:TemplateField&gt;\n</code></pre>\n" }, { "answer_id": 216854, "author": "Paco", "author_id": 13376, "author_profile": "https://Stackoverflow.com/users/13376", "pm_score": 2, "selected": false, "text": "<p>Or you can use the <code>ItemDataBound</code> event in the code behind.</p>\n" }, { "answer_id": 315174, "author": "travis", "author_id": 1414, "author_profile": "https://Stackoverflow.com/users/1414", "pm_score": 8, "selected": true, "text": "<p>I use this code for VB:</p>\n\n<pre><code>&lt;asp:TemplateField HeaderText=\"Active\" SortExpression=\"Active\"&gt;\n &lt;ItemTemplate&gt;&lt;%#IIf(Boolean.Parse(Eval(\"Active\").ToString()), \"Yes\", \"No\")%&gt;&lt;/ItemTemplate&gt;\n&lt;/asp:TemplateField&gt;\n</code></pre>\n\n<p>And this should work for C# (untested):</p>\n\n<pre><code>&lt;asp:TemplateField HeaderText=\"Active\" SortExpression=\"Active\"&gt;\n &lt;ItemTemplate&gt;&lt;%# (Boolean.Parse(Eval(\"Active\").ToString())) ? \"Yes\" : \"No\" %&gt;&lt;/ItemTemplate&gt;\n&lt;/asp:TemplateField&gt;\n</code></pre>\n" }, { "answer_id": 315274, "author": "Rune Grimstad", "author_id": 30366, "author_profile": "https://Stackoverflow.com/users/30366", "pm_score": 4, "selected": false, "text": "<p>Add a method to your page class like this:</p>\n\n<pre><code>public string YesNo(bool active) \n{\n return active ? \"Yes\" : \"No\";\n}\n</code></pre>\n\n<p>And then in your <code>TemplateField</code> you <code>Bind</code> using this method:</p>\n\n<pre><code>&lt;%# YesNo(Active) %&gt;\n</code></pre>\n" }, { "answer_id": 356867, "author": "Corey Coto", "author_id": 45071, "author_profile": "https://Stackoverflow.com/users/45071", "pm_score": 3, "selected": false, "text": "<p>You could use a Mixin. </p>\n\n<pre><code>/// &lt;summary&gt;\n/// Adds \"mixins\" to the Boolean class.\n/// &lt;/summary&gt;\npublic static class BooleanMixins\n{\n /// &lt;summary&gt;\n /// Converts the value of this instance to its equivalent string representation (either \"Yes\" or \"No\").\n /// &lt;/summary&gt;\n /// &lt;param name=\"boolean\"&gt;&lt;/param&gt;\n /// &lt;returns&gt;string&lt;/returns&gt;\n public static string ToYesNoString(this Boolean boolean)\n {\n return boolean ? \"Yes\" : \"No\";\n }\n}\n</code></pre>\n" }, { "answer_id": 4392051, "author": "Shaun3180", "author_id": 244105, "author_profile": "https://Stackoverflow.com/users/244105", "pm_score": 2, "selected": false, "text": "<p>I had the same need as the original poster, except that my client's db schema is a nullable bit (ie, allows for True/False/NULL). Here's some code I wrote to both display Yes/No and handle potential nulls.</p>\n\n<p><strong>Code-Behind:</strong></p>\n\n<pre><code>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</code></pre>\n\n<p><strong>Front-End:</strong></p>\n\n<pre><code>&lt;%# ConvertNullableBoolToYesNo(Eval(\"YOUR_FIELD\"))%&gt;\n</code></pre>\n" }, { "answer_id": 16651591, "author": "joeysasa", "author_id": 2402057, "author_profile": "https://Stackoverflow.com/users/2402057", "pm_score": 0, "selected": false, "text": "<p>This works:</p>\n\n<pre><code>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</code></pre>\n\n<p>Where <code>cells(3)</code> is the column of the column that has the boolean field.</p>\n" }, { "answer_id": 23664672, "author": "Chtioui Malek", "author_id": 1254684, "author_profile": "https://Stackoverflow.com/users/1254684", "pm_score": 1, "selected": false, "text": "<p>This is how I've always done it:</p>\n\n<pre><code>&lt;ItemTemplate&gt;\n &lt;%# Boolean.Parse(Eval(\"Active\").ToString()) ? \"Yes\" : \"No\" %&gt;\n&lt;/ItemTemplate&gt;\n</code></pre>\n\n<p>Hope that helps.</p>\n" }, { "answer_id": 47767424, "author": "SabineMueller", "author_id": 4308699, "author_profile": "https://Stackoverflow.com/users/4308699", "pm_score": 0, "selected": false, "text": "<p>It's easy with Format()-Function</p>\n\n<pre><code>Format(aBoolean, \"YES/NO\")\n</code></pre>\n\n<p>Please find details here:\n<a href=\"https://msdn.microsoft.com/en-us/library/aa241719(v=vs.60).aspx\" rel=\"nofollow noreferrer\">https://msdn.microsoft.com/en-us/library/aa241719(v=vs.60).aspx</a></p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216833", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8547/" ]
I have a ASP.NET `GridView` 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). Is this possible? ``` <asp:gridview id="GridView1" runat="server" autogeneratecolumns="false"> <columns> ... <asp:boundfield headertext="Active" datafield="Active" dataformatstring="{0:Yes/No}" /> ... </columns> </asp:gridview> ```
I use this code for VB: ``` <asp:TemplateField HeaderText="Active" SortExpression="Active"> <ItemTemplate><%#IIf(Boolean.Parse(Eval("Active").ToString()), "Yes", "No")%></ItemTemplate> </asp:TemplateField> ``` And this should work for C# (untested): ``` <asp:TemplateField HeaderText="Active" SortExpression="Active"> <ItemTemplate><%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %></ItemTemplate> </asp:TemplateField> ```
216,865
<p>I'm wondering about the practical use of #undef in C. I'm working through K&amp;R, and am up to the preprocessor. Most of this was material I (more or less) understood, but something on page 90 (second edition) stuck out at me:</p> <blockquote> <p>Names may be undefined with <code>#undef</code>, usually to ensure that a routine is really a function, not a macro:</p> <p><code>#undef getchar</code></p> <p><code>int getchar(void) { ... }</code></p> </blockquote> <p>Is this a common practice to defend against someone <code>#define</code>-ing a macro with the same name as your function? Or is this really more of a sample that wouldn't occur in reality? (EG, no one in his right, wrong nor insane mind should be rewriting <code>getchar()</code>, so it shouldn't come up.) With your own function names, do you feel the need to do this? Does that change if you're developing a library for others to use?</p>
[ { "answer_id": 216874, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 2, "selected": false, "text": "<p>I only use it when a macro in an <code>#included</code> file is interfering with one of my functions (e.g., it has the same name). Then I <code>#undef</code> the macro so I can use my own function.</p>\n" }, { "answer_id": 216891, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 1, "selected": false, "text": "<blockquote>\n <p>Is this a common practice to defend against someone #define-ing a macro with the same name as your function? Or is this really more of a sample that wouldn't occur in reality? (EG, no one in his right, wrong nor insane mind should be rewriting getchar(), so it shouldn't come up.)</p>\n</blockquote>\n\n<p>A little of both. Good code will not require use of <code>#undef</code>, but there's lots of bad code out there you have to work with. <code>#undef</code> can prove invaluable when somebody pulls a trick like <code>#define bool int</code>.</p>\n" }, { "answer_id": 216895, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "<p>Because preprocessor <code>#define</code>s are all in one global namespace, it's easy for namespace conflicts to result, especially when using third-party libraries. For example, if you wanted to create a function named <code>OpenFile</code>, it might not compile correctly, because the header file <code>&lt;windows.h&gt;</code> defines the token <code>OpenFile</code> to map to either <code>OpenFileA</code> or <code>OpenFileW</code> (depending on if <code>UNICODE</code> is defined or not). The correct solution is to <code>#undef</code> <code>OpenFile</code> before defining your function.</p>\n" }, { "answer_id": 216922, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 1, "selected": false, "text": "<p>In addition to fixing problems with macros polluting the global namespace, another use of <code>#undef</code> is the situation where a macro might be required to have a different behavior in different places. This is not a realy common scenario, but a couple that come to mind are:</p>\n\n<ul>\n<li><p>the <code>assert</code> macro can have it's definition changed in the middle of a compilation unit for the case where you might want to perform debugging on some portion of your code but not others. In addition to <code>assert</code> itself needing to be <code>#undef</code>'ed to do this, the <code>NDEBUG</code> macro needs to be redefined to reconfigure the desired behavior of <code>assert</code></p></li>\n<li><p>I've seen a technique used to ensure that globals are defined exactly once by using a macro to declare the variables as <code>extern</code>, but the macro would be redefined to nothing for the single case where the header/declarations are used to define the variables.</p></li>\n</ul>\n\n<p>Something like (I'm not saying this is necessarily a good technique, just one I've seen in the wild):</p>\n\n<pre><code>/* globals.h */\n/* ------------------------------------------------------ */\n#undef GLOBAL\n#ifdef DEFINE_GLOBALS\n#define GLOBAL\n#else\n#define GLOBAL extern\n#endif\n\nGLOBAL int g_x;\nGLOBAL char* g_name;\n/* ------------------------------------------------------ */\n\n\n\n/* globals.c */\n/* ------------------------------------------------------ */\n#include \"some_master_header_that_happens_to_include_globals.h\"\n\n/* define the globals here (and only here) using globals.h */\n#define DEFINE_GLOBALS\n#include \"globals.h\"\n\n/* ------------------------------------------------------ */\n</code></pre>\n" }, { "answer_id": 216925, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 4, "selected": false, "text": "<p>Macros are often used to generate bulk of code. It's often a pretty localized usage and it's safe to <code>#undef</code> any helper macros at the end of the particular header in order to avoid name clashes so only the actual generated code gets imported elsewhere and the macros used to generate the code don't.</p>\n\n<p>/Edit: As an example, I've used this to generate structs for me. The following is an excerpt from an actual project:</p>\n\n<pre><code>#define MYLIB_MAKE_PC_PROVIDER(name) \\\n struct PcApi##name { \\\n many members …\n };\n\nMYLIB_MAKE_PC_PROVIDER(SA)\nMYLIB_MAKE_PC_PROVIDER(SSA)\nMYLIB_MAKE_PC_PROVIDER(AF)\n\n#undef MYLIB_MAKE_PC_PROVIDER\n</code></pre>\n" }, { "answer_id": 217221, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 5, "selected": true, "text": "<h3>What it does</h3>\n\n<p>If you read Plauger's <a href=\"https://smile.amazon.com/dp/0131315099\" rel=\"nofollow noreferrer\">The Standard C Library</a> (1992), you will see that the <code>&lt;stdio.h&gt;</code> header is allowed to provide <code>getchar()</code> and <code>getc()</code> as function-like macros (with special permission for <code>getc()</code> to evaluate its file pointer argument more than once!). However, even if it provides macros, the implementation is also obliged to provid actual functions that do the same job, primarily so that you can access a function pointer called <code>getchar()</code> or <code>getc()</code> and pass that to other functions.</p>\n\n<p>That is, by doing:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n#undef getchar\n\nextern int some_function(int (*)(void));\n\nint core_function(void)\n{\n int c = some_function(getchar);\n return(c);\n}\n</code></pre>\n\n<p>As written, the <code>core_function()</code> is pretty meaningless, but it illustrates the point. You can do the same thing with the <code>isxxxx()</code> macros in <code>&lt;ctype.h&gt;</code> too, for example.</p>\n\n<p>Normally, you don't want to do that - you don't normally want to remove the macro definition. But, when you need the real function, you can get hold of it. People who provide libraries can emulate the functionality of the standard C library to good effect.</p>\n\n<h3>Seldom needed</h3>\n\n<p>Also note that one of the reasons you seldom need to use the explicit <code>#undef</code> is because you can invoke the function instead of the macro by writing:</p>\n\n<pre><code>int c = (getchar)();\n</code></pre>\n\n<p>Because the token after <code>getchar</code> is not an <code>(</code>, it is not an invocation of the function-like macro, so it must be a reference to the function. Similarly, the first example above, would compile and run correctly even without the <code>#undef</code>.</p>\n\n<p>If you implement your own function with a macro override, you can use this to good effect, though it might be slightly confusing unless explained.</p>\n\n<pre><code>/* function.h */\n…\nextern int function(int c);\nextern int other_function(int c, FILE *fp);\n#define function(c) other_function(c, stdout);\n…\n</code></pre>\n\n\n\n<pre><code>/* function.c */\n\n…\n\n/* Provide function despite macro override */\nint (function)(int c)\n{\n return function(c, stdout);\n}\n</code></pre>\n\n<p>The function definition line doesn't invoke the macro because the token after <code>function</code> is not <code>(</code>. The <code>return</code> line does invoke the macro.</p>\n" }, { "answer_id": 217239, "author": "Dustin Getz", "author_id": 20003, "author_profile": "https://Stackoverflow.com/users/20003", "pm_score": 0, "selected": false, "text": "<h3>If a macro can be def'ed, there must be a facility to undef.</h3>\n<p>a memory tracker I use defines its own new/delete macros to track file/line information. this macro breaks the SC++L.</p>\n<pre><code>#pragma push_macro( &quot;new&quot; )\n#undef new\n#include &lt;vector&gt;\n#pragma pop_macro( &quot;new&quot; )\n</code></pre>\n<p>Regarding your more specific question: namespaces are often emul;ated in C by prefixing library functions with an identifier.</p>\n<p>Blindly undefing macros is going to add confusion, reduce maintainability, and may break things that rely on the original behavior. If you were forced, at least use push/pop to preserve the original behavior everywhere else.</p>\n" }, { "answer_id": 217986, "author": "quinmars", "author_id": 18687, "author_profile": "https://Stackoverflow.com/users/18687", "pm_score": 2, "selected": false, "text": "<p>Although I think Jonathan Leffler gave you the right answer. Here is a very rare case, where I use an #undef. Normally a macro should be reusable inside many functions; that's why you define it at the top of a file or in a header file. But sometimes you have some repetitive code inside a function that can be shortened with a macro.</p>\n\n<pre><code>\nint foo(int x, int y)\n{\n#define OUT_OF_RANGE(v, vlower, vupper) \\\n if (v &lt; vlower) {v = vlower; goto EXIT;} \\\n else if (v &gt; vupper) {v = vupper; goto EXIT;}\n\n /* do some calcs */\n x += (x + y)/2;\n OUT_OF_RANGE(x, 0, 100);\n y += (x - y)/2;\n OUT_OF_RANGE(y, -10, 50);\n\n /* do some more calcs and range checks*/\n ...\n\nEXIT:\n /* undefine OUT_OF_RANGE, because we don't need it anymore */\n#undef OUT_OF_RANGE\n ...\n return x;\n}\n</code></pre>\n\n<p>To show the reader that this macro is only useful inside of the function, it is undefined at the end. I don't want to encourage anyone to use such hackish macros. But if you have to, #undef them at the end.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216865", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14048/" ]
I'm wondering about the practical use of #undef in C. I'm working through K&R, and am up to the preprocessor. Most of this was material I (more or less) understood, but something on page 90 (second edition) stuck out at me: > > Names may be undefined with `#undef`, > usually to ensure that a routine is > really a function, not a macro: > > > `#undef getchar` > > > `int getchar(void) { ... }` > > > Is this a common practice to defend against someone `#define`-ing a macro with the same name as your function? Or is this really more of a sample that wouldn't occur in reality? (EG, no one in his right, wrong nor insane mind should be rewriting `getchar()`, so it shouldn't come up.) With your own function names, do you feel the need to do this? Does that change if you're developing a library for others to use?
### What it does If you read Plauger's [The Standard C Library](https://smile.amazon.com/dp/0131315099) (1992), you will see that the `<stdio.h>` header is allowed to provide `getchar()` and `getc()` as function-like macros (with special permission for `getc()` to evaluate its file pointer argument more than once!). However, even if it provides macros, the implementation is also obliged to provid actual functions that do the same job, primarily so that you can access a function pointer called `getchar()` or `getc()` and pass that to other functions. That is, by doing: ``` #include <stdio.h> #undef getchar extern int some_function(int (*)(void)); int core_function(void) { int c = some_function(getchar); return(c); } ``` As written, the `core_function()` is pretty meaningless, but it illustrates the point. You can do the same thing with the `isxxxx()` macros in `<ctype.h>` too, for example. Normally, you don't want to do that - you don't normally want to remove the macro definition. But, when you need the real function, you can get hold of it. People who provide libraries can emulate the functionality of the standard C library to good effect. ### Seldom needed Also note that one of the reasons you seldom need to use the explicit `#undef` is because you can invoke the function instead of the macro by writing: ``` int c = (getchar)(); ``` Because the token after `getchar` is not an `(`, it is not an invocation of the function-like macro, so it must be a reference to the function. Similarly, the first example above, would compile and run correctly even without the `#undef`. If you implement your own function with a macro override, you can use this to good effect, though it might be slightly confusing unless explained. ``` /* function.h */ … extern int function(int c); extern int other_function(int c, FILE *fp); #define function(c) other_function(c, stdout); … ``` ``` /* function.c */ … /* Provide function despite macro override */ int (function)(int c) { return function(c, stdout); } ``` The function definition line doesn't invoke the macro because the token after `function` is not `(`. The `return` line does invoke the macro.
216,870
<p>I'm using the following regex to capture a fixed width "description" field that is always 50 characters long:</p> <pre><code>(?.{50}) </code></pre> <p>My problem is that the descriptions sometimes contain a <em>lot</em> of whitespace, e.g.</p> <pre><code>"FLUID COMPRESSOR " </code></pre> <p>Can somebody provide a regex that:</p> <ol> <li>Trims all whitespace off the end</li> <li>Collapses any whitespace in between words to a <strong>single space</strong></li> </ol>
[ { "answer_id": 216877, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 1, "selected": false, "text": "<p>Is there a particular reason you are asking for a regular expression? They may not be the best tool for this task.</p>\n\n<p>A replacement like </p>\n\n<pre><code> s/[ \\t]+/ /g\n</code></pre>\n\n<p>should compress the internal whitespace (actually, it will compress leading and trailing whitespace too, but it doesn't sound like that is a problem.), and </p>\n\n<pre><code>s/[ \\t]+$/$/\n</code></pre>\n\n<p>will take care of the trailing whitespace. [I'm using <code>sed</code>ish syntax here. You didn't say what flavor you prefer.]</p>\n\n<hr>\n\n<p>Right off hand I don't see a way to do it in a single expression.</p>\n" }, { "answer_id": 216885, "author": "sk.", "author_id": 16399, "author_profile": "https://Stackoverflow.com/users/16399", "pm_score": 5, "selected": true, "text": "<p>Substitute two or more spaces for one space:</p>\n\n<pre><code>s/ +/ /g\n</code></pre>\n\n<p>Edit: for any white space (not just spaces) you can use \\s if you're using a perl-compatible regex library, and the curly brace syntax for number of occurrences, e.g.</p>\n\n<pre><code>s/\\s\\s+/ /g\n</code></pre>\n\n<p>or</p>\n\n<pre><code>s/\\s{2,}/ /g\n</code></pre>\n\n<p>Edit #2: forgot the /g global suffix, thanks JL</p>\n" }, { "answer_id": 216978, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p>Perl-variants:\n1) s/\\s+$//;\n2) s/\\s+/ /g;</p>\n" }, { "answer_id": 217399, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 3, "selected": false, "text": "<pre><code>str = Regex.Replace(str, \" +( |$)\", \"$1\");\n</code></pre>\n" }, { "answer_id": 1250923, "author": "Casey Rodarmor", "author_id": 66450, "author_profile": "https://Stackoverflow.com/users/66450", "pm_score": 1, "selected": false, "text": "<p>Since compressing whitespace and trimming whitespace around the edges are conceptually different operations, I like doing it in two steps:</p>\n\n<pre><code>re.replace(\"s/\\s+/ /g\", str.strip())\n</code></pre>\n\n<p>Not the most efficient, but quite readable.</p>\n" }, { "answer_id": 3232967, "author": "anonymous", "author_id": 389951, "author_profile": "https://Stackoverflow.com/users/389951", "pm_score": 0, "selected": false, "text": "<p>/(^[\\s\\t]+|[\\s\\t]+([\\s\\t]|$))/g replace with $2 (beginning|middle/end)</p>\n" }, { "answer_id": 5920170, "author": "nawfal", "author_id": 661933, "author_profile": "https://Stackoverflow.com/users/661933", "pm_score": 2, "selected": false, "text": "<p>C#:</p>\n\n<p>Only if you wanna trim all the white spaces - at the start, end and middle.</p>\n\n<pre><code> string x = Regex.Replace(x, @\"\\s+\", \" \").Trim();\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2773/" ]
I'm using the following regex to capture a fixed width "description" field that is always 50 characters long: ``` (?.{50}) ``` My problem is that the descriptions sometimes contain a *lot* of whitespace, e.g. ``` "FLUID COMPRESSOR " ``` Can somebody provide a regex that: 1. Trims all whitespace off the end 2. Collapses any whitespace in between words to a **single space**
Substitute two or more spaces for one space: ``` s/ +/ /g ``` Edit: for any white space (not just spaces) you can use \s if you're using a perl-compatible regex library, and the curly brace syntax for number of occurrences, e.g. ``` s/\s\s+/ /g ``` or ``` s/\s{2,}/ /g ``` Edit #2: forgot the /g global suffix, thanks JL
216,875
<p>As mentioned in many of my previous questions, I'm working through K&amp;R, and am currently into the preprocessor. One of the more interesting things &mdash; something I never knew before from any of my prior attempts to learn C &mdash; is the <code>##</code> preprocessor operator. According to K&amp;R:</p> <blockquote> <p>The preprocessor operator <code>##</code> provides a way to concatenate actual arguments during macro expansion. If a parameter in the replacement text is adjacent to a <code>##</code>, the parameter is replaced by the actual argument, the <code>##</code> and surrounding white space are removed, and the result is re-scanned. For example, the macro <code>paste</code> concatenates its two arguments:</p> <p><code>#define paste(front, back) front ## back</code></p> <p>so <code>paste(name, 1)</code> creates the token <code>name1</code>.</p> </blockquote> <p>How and why would someone use this in the real world? What are practical examples of its use, and are there gotchas to consider? </p>
[ { "answer_id": 216888, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 7, "selected": true, "text": "<p><strong>CrashRpt: Using ## to convert macro multi-byte strings to Unicode</strong></p>\n\n<p>An interesting usage in CrashRpt (crash reporting library) is the following:</p>\n\n<pre><code>#define WIDEN2(x) L ## x\n#define WIDEN(x) WIDEN2(x)\n//Note you need a WIDEN2 so that __DATE__ will evaluate first.\n</code></pre>\n\n<p>Here they want to use a two-byte string instead of a one-byte-per-char string. This probably looks like it is really pointless, but they do it for a good reason.</p>\n\n<pre><code> std::wstring BuildDate = std::wstring(WIDEN(__DATE__)) + L\" \" + WIDEN(__TIME__);\n</code></pre>\n\n<p>They use it with another macro that returns a string with the date and time.</p>\n\n<p>Putting <code>L</code> next to a <code>__ DATE __</code> would give you a compiling error.</p>\n\n<hr>\n\n<p><strong>Windows: Using ## for generic Unicode or multi-byte strings</strong></p>\n\n<p>Windows uses something like the following:</p>\n\n<pre><code>#ifdef _UNICODE\n #define _T(x) L ## x\n#else\n #define _T(x) x\n#endif\n</code></pre>\n\n<p>And <code>_T</code> is used everywhere in code</p>\n\n<hr>\n\n<p><strong>Various libraries, using for clean accessor and modifier names:</strong></p>\n\n<p>I've also seen it used in code to define accessors and modifiers:</p>\n\n<pre><code>#define MYLIB_ACCESSOR(name) (Get##name)\n#define MYLIB_MODIFIER(name) (Set##name)\n</code></pre>\n\n<p>Likewise you can use this same method for any other types of clever name creation.</p>\n\n<hr>\n\n<p><strong>Various libraries, using it to make several variable declarations at once:</strong></p>\n\n<pre><code>#define CREATE_3_VARS(name) name##1, name##2, name##3\nint CREATE_3_VARS(myInts);\nmyInts1 = 13;\nmyInts2 = 19;\nmyInts3 = 77;\n</code></pre>\n" }, { "answer_id": 216893, "author": "John Millikin", "author_id": 3560, "author_profile": "https://Stackoverflow.com/users/3560", "pm_score": 1, "selected": false, "text": "<p>I use it for adding custom prefixes to variables defined by macros. So something like:</p>\n\n<pre><code>UNITTEST(test_name)\n</code></pre>\n\n<p>expands to:</p>\n\n<pre><code>void __testframework_test_name ()\n</code></pre>\n" }, { "answer_id": 216903, "author": "qrdl", "author_id": 28494, "author_profile": "https://Stackoverflow.com/users/28494", "pm_score": 2, "selected": false, "text": "<p>You can use token pasting when you need to concatenate macro parameters with something else.</p>\n\n<p>It can be used for templates:</p>\n\n<pre><code>#define LINKED_LIST(A) struct list##_##A {\\\nA value; \\\nstruct list##_##A *next; \\\n};\n</code></pre>\n\n<p>In this case LINKED_LIST(int) would give you</p>\n\n<pre><code>struct list_int {\nint value;\nstruct list_int *next;\n};\n</code></pre>\n\n<p>Similarly you can write a function template for list traversal.</p>\n" }, { "answer_id": 216904, "author": "Vebjorn Ljosa", "author_id": 17498, "author_profile": "https://Stackoverflow.com/users/17498", "pm_score": 3, "selected": false, "text": "<p>This is useful in all kinds of situations in order not to repeat yourself needlessly. The following is an example from the Emacs source code. We would like to load a number of functions from a library. The function \"foo\" should be assigned to <code>fn_foo</code>, and so on. We define the following macro:</p>\n\n<pre><code>#define LOAD_IMGLIB_FN(lib,func) { \\\n fn_##func = (void *) GetProcAddress (lib, #func); \\\n if (!fn_##func) return 0; \\\n }\n</code></pre>\n\n<p>We can then use it:</p>\n\n<pre><code>LOAD_IMGLIB_FN (library, XpmFreeAttributes);\nLOAD_IMGLIB_FN (library, XpmCreateImageFromBuffer);\nLOAD_IMGLIB_FN (library, XpmReadFileToImage);\nLOAD_IMGLIB_FN (library, XImageFree);\n</code></pre>\n\n<p>The benefit is not having to write both <code>fn_XpmFreeAttributes</code> and <code>\"XpmFreeAttributes\"</code> (and risk misspelling one of them).</p>\n" }, { "answer_id": 216911, "author": "mcherm", "author_id": 14570, "author_profile": "https://Stackoverflow.com/users/14570", "pm_score": 2, "selected": false, "text": "<p>The main use is when you have a naming convention and you want your macro to take advantage of that naming convention. Perhaps you have several families of methods: image_create(), image_activate(), and image_release() also file_create(), file_activate(), file_release(), and mobile_create(), mobile_activate() and mobile_release().</p>\n\n<p>You could write a macro for handling object lifecycle: </p>\n\n<pre><code>#define LIFECYCLE(name, func) (struct name x = name##_create(); name##_activate(x); func(x); name##_release())\n</code></pre>\n\n<p>Of course, a sort of \"minimal version of objects\" is not the only sort of naming convention this applies to -- nearly the vast majority of naming conventions make use of a common sub-string to form the names. It could me function names (as above), or field names, variable names, or most anything else.</p>\n" }, { "answer_id": 216912, "author": "Tall Jeff", "author_id": 1553, "author_profile": "https://Stackoverflow.com/users/1553", "pm_score": 2, "selected": false, "text": "<p>I use it in C programs to help correctly enforce the prototypes for a set of methods that must conform to some sort of calling convention. In a way, this can be used for poor man's object orientation in straight C:</p>\n\n<pre><code>SCREEN_HANDLER( activeCall )\n</code></pre>\n\n<p>expands to something like this:</p>\n\n<pre><code>STATUS activeCall_constructor( HANDLE *pInst )\nSTATUS activeCall_eventHandler( HANDLE *pInst, TOKEN *pEvent );\nSTATUS activeCall_destructor( HANDLE *pInst );\n</code></pre>\n\n<p>This enforces correct parameterization for all \"derived\" objects when you do:</p>\n\n<pre><code>SCREEN_HANDLER( activeCall )\nSCREEN_HANDLER( ringingCall )\nSCREEN_HANDLER( heldCall )\n</code></pre>\n\n<p>the above in your header files, etc. It is also useful for maintenance if you even happen to want to change the definitions and/or add methods to the \"objects\".</p>\n" }, { "answer_id": 216916, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "<p><a href=\"http://sglib.sourceforge.net\" rel=\"nofollow noreferrer\">SGlib</a> uses ## to basically fudge templates in C. Because there's no function overloading, ## is used to glue the type name into the names of the generated functions. If I had a list type called list_t, then I would get functions named like sglib_list_t_concat, and so on.</p>\n" }, { "answer_id": 216927, "author": "ya23", "author_id": 29430, "author_profile": "https://Stackoverflow.com/users/29430", "pm_score": 0, "selected": false, "text": "<p>It is very useful for logging. You can do:</p>\n\n<pre><code>#define LOG(msg) log_msg(__function__, ## msg)\n</code></pre>\n\n<p>Or, if your compiler doesn't support <strong>function</strong> and <strong>func</strong>:</p>\n\n<pre><code>#define LOG(msg) log_msg(__file__, __line__, ## msg)\n</code></pre>\n\n<p>The above \"functions\" logs message and shows exactly which function logged a message.</p>\n\n<p>My C++ syntax might be not quite correct.</p>\n" }, { "answer_id": 216975, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 4, "selected": false, "text": "<p>Here's a gotcha that I ran into when upgrading to a new version of a compiler: </p>\n\n<p><strong>Unnecessary use of the token-pasting operator (<code>##</code>) is non-portable and may generate undesired whitespace, warnings, or errors.</strong> </p>\n\n<p>When the result of the token-pasting operator is not a valid preprocessor token, the token-pasting operator is unnecessary and possibly harmful. </p>\n\n<p>For example, one might try to build string literals at compile time using the token-pasting operator:</p>\n\n<pre><code>#define STRINGIFY(x) #x\n#define PLUS(a, b) STRINGIFY(a##+##b)\n#define NS(a, b) STRINGIFY(a##::##b)\nprintf(\"%s %s\\n\", PLUS(1,2), NS(std,vector));\n</code></pre>\n\n<p>On some compilers, this will output the expected result:</p>\n\n<pre><code>1+2 std::vector\n</code></pre>\n\n<p>On other compilers, this will include undesired whitespace:</p>\n\n<pre><code>1 + 2 std :: vector\n</code></pre>\n\n<p>Fairly modern versions of GCC (>=3.3 or so) will fail to compile this code:</p>\n\n<pre><code>foo.cpp:16:1: pasting \"1\" and \"+\" does not give a valid preprocessing token\nfoo.cpp:16:1: pasting \"+\" and \"2\" does not give a valid preprocessing token\nfoo.cpp:16:1: pasting \"std\" and \"::\" does not give a valid preprocessing token\nfoo.cpp:16:1: pasting \"::\" and \"vector\" does not give a valid preprocessing token\n</code></pre>\n\n<p>The solution is to omit the token-pasting operator when concatenating preprocessor tokens to C/C++ operators:</p>\n\n<pre><code>#define STRINGIFY(x) #x\n#define PLUS(a, b) STRINGIFY(a+b)\n#define NS(a, b) STRINGIFY(a::b)\nprintf(\"%s %s\\n\", PLUS(1,2), NS(std,vector));\n</code></pre>\n\n<p>The <a href=\"http://gcc.gnu.org/onlinedocs/gcc-4.3.2/cpp/Concatenation.html\" rel=\"noreferrer\">GCC CPP documentation chapter on concatenation</a> has more useful information on the token-pasting operator.</p>\n" }, { "answer_id": 216977, "author": "c0m4", "author_id": 2079, "author_profile": "https://Stackoverflow.com/users/2079", "pm_score": 2, "selected": false, "text": "<p>I use it for a home rolled assert on a non-standard C compiler for embedded:</p>\n\n<pre>\n<code>\n\n#define ASSERT(exp) if(!(exp)){ \\\n print_to_rs232(\"Assert failed: \" ## #exp );\\\n while(1){} //Let the watchdog kill us \n\n</code>\n</pre>\n" }, { "answer_id": 217086, "author": "Bill Forster", "author_id": 3955, "author_profile": "https://Stackoverflow.com/users/3955", "pm_score": 2, "selected": false, "text": "<p>A previous question on Stack&nbsp;Overflow asked for a smooth method of generating string representations for enumeration constants without a lot of error-prone retyping.</p>\n\n<p><a href=\"https://stackoverflow.com/questions/147267/easy-way-to-use-variables-of-enum-types-as-string-in-c#147582\">Link</a></p>\n\n<p>My answer to that question showed how applying little preprocessor magic lets you define your enumeration like this (for example) ...;</p>\n\n<pre><code>ENUM_BEGIN( Color )\n ENUM(RED),\n ENUM(GREEN),\n ENUM(BLUE)\nENUM_END( Color )\n</code></pre>\n\n<p>... With the benefit that the macro expansion not only defines the enumeration (in a .h file), it also defines a matching array of strings (in a .c file);</p>\n\n<pre><code>const char *ColorStringTable[] =\n{\n \"RED\",\n \"GREEN\",\n \"BLUE\"\n};\n</code></pre>\n\n<p>The name of the string table comes from pasting the macro parameter (i.e. Color) to StringTable using the ## operator. Applications (tricks?) like this are where the # and ## operators are invaluable.</p>\n" }, { "answer_id": 217181, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 6, "selected": false, "text": "<p>One thing to be aware of when you're using the token-paste ('<code>##</code>') or stringizing ('<code>#</code>') preprocessing operators is that you have to use an extra level of indirection for them to work properly in all cases.</p>\n\n<p>If you don't do this and the items passed to the token-pasting operator are macros themselves, you'll get results that are probably not what you want:</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\n#define STRINGIFY2( x) #x\n#define STRINGIFY(x) STRINGIFY2(x)\n#define PASTE2( a, b) a##b\n#define PASTE( a, b) PASTE2( a, b)\n\n#define BAD_PASTE(x,y) x##y\n#define BAD_STRINGIFY(x) #x\n\n#define SOME_MACRO function_name\n\nint main() \n{\n printf( \"buggy results:\\n\");\n printf( \"%s\\n\", STRINGIFY( BAD_PASTE( SOME_MACRO, __LINE__)));\n printf( \"%s\\n\", BAD_STRINGIFY( BAD_PASTE( SOME_MACRO, __LINE__)));\n printf( \"%s\\n\", BAD_STRINGIFY( PASTE( SOME_MACRO, __LINE__)));\n\n printf( \"\\n\" \"desired result:\\n\");\n printf( \"%s\\n\", STRINGIFY( PASTE( SOME_MACRO, __LINE__)));\n}\n</code></pre>\n\n<p>The output:</p>\n\n<pre><code>buggy results:\nSOME_MACRO__LINE__\nBAD_PASTE( SOME_MACRO, __LINE__)\nPASTE( SOME_MACRO, __LINE__)\n\ndesired result:\nfunction_name21\n</code></pre>\n" }, { "answer_id": 16648750, "author": "Keshava GN", "author_id": 2006333, "author_profile": "https://Stackoverflow.com/users/2006333", "pm_score": 1, "selected": false, "text": "<p>One important use in WinCE:</p>\n\n<pre><code>#define BITFMASK(bit_position) (((1U &lt;&lt; (bit_position ## _WIDTH)) - 1) &lt;&lt; (bit_position ## _LEFTSHIFT))\n</code></pre>\n\n<p>While defining register bit description we do following:</p>\n\n<pre><code>#define ADDR_LEFTSHIFT 0\n\n#define ADDR_WIDTH 7\n</code></pre>\n\n<p>And while using BITFMASK, simply use:</p>\n\n<pre><code>BITFMASK(ADDR)\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216875", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14048/" ]
As mentioned in many of my previous questions, I'm working through K&R, and am currently into the preprocessor. One of the more interesting things — something I never knew before from any of my prior attempts to learn C — is the `##` preprocessor operator. According to K&R: > > The preprocessor operator `##` > provides a way to concatenate actual > arguments during macro expansion. If a > parameter in the replacement text is > adjacent to a `##`, the parameter is > replaced by the actual argument, the > `##` and surrounding white space are > removed, and the result is re-scanned. > For example, the macro `paste` > concatenates its two arguments: > > > `#define paste(front, back) front ## back` > > > so `paste(name, 1)` creates the token > `name1`. > > > How and why would someone use this in the real world? What are practical examples of its use, and are there gotchas to consider?
**CrashRpt: Using ## to convert macro multi-byte strings to Unicode** An interesting usage in CrashRpt (crash reporting library) is the following: ``` #define WIDEN2(x) L ## x #define WIDEN(x) WIDEN2(x) //Note you need a WIDEN2 so that __DATE__ will evaluate first. ``` Here they want to use a two-byte string instead of a one-byte-per-char string. This probably looks like it is really pointless, but they do it for a good reason. ``` std::wstring BuildDate = std::wstring(WIDEN(__DATE__)) + L" " + WIDEN(__TIME__); ``` They use it with another macro that returns a string with the date and time. Putting `L` next to a `__ DATE __` would give you a compiling error. --- **Windows: Using ## for generic Unicode or multi-byte strings** Windows uses something like the following: ``` #ifdef _UNICODE #define _T(x) L ## x #else #define _T(x) x #endif ``` And `_T` is used everywhere in code --- **Various libraries, using for clean accessor and modifier names:** I've also seen it used in code to define accessors and modifiers: ``` #define MYLIB_ACCESSOR(name) (Get##name) #define MYLIB_MODIFIER(name) (Set##name) ``` Likewise you can use this same method for any other types of clever name creation. --- **Various libraries, using it to make several variable declarations at once:** ``` #define CREATE_3_VARS(name) name##1, name##2, name##3 int CREATE_3_VARS(myInts); myInts1 = 13; myInts2 = 19; myInts3 = 77; ```
216,890
<p>One of our providers are sometimes sending XML feeds that are tagged as UTF-8 encoded documents but includes characters that are not included in the UTF-8 charset. This causes the parser to throw an exception and stop building the DOM object when these characters are encountered:</p> <pre><code>DocumentBuilder.parse(ByteArrayInputStream bais) </code></pre> <p>throws the following exception:</p> <pre><code>org.xml.sax.SAXParseException: Invalid byte 2 of 2-byte UTF-8 sequence. </code></pre> <p>Is there a way to "capture" these problems early and avoid the exception (i.e. finding and removing those characters from the stream)? What I'm looking for is a "best effort" type of fallback for wrongly encoded documents. The correct solution would obviously be to attack the problem at the source and make sure that only correct documents are delivered, but what is a good approach when that is not possible?</p>
[ { "answer_id": 216950, "author": "CesarB", "author_id": 28258, "author_profile": "https://Stackoverflow.com/users/28258", "pm_score": 2, "selected": false, "text": "<p>You should manually take a look at the invalid documents and see what is the common problem to them. It's quite probable they are in fact in another encoding (most probably windows-1252), and the best solution then would be to take every document from the broken system and recode it to UTF-8 before parsing.</p>\n\n<p>Another possible cause is mixed encodings (the content of some elements is in one encoding and the content of other elements is in another encoding). That would be harder to fix.</p>\n\n<p>You would also need a way to know when the broken system gets fixed so you can stop using your workaround.</p>\n" }, { "answer_id": 217165, "author": "james", "author_id": 17156, "author_profile": "https://Stackoverflow.com/users/17156", "pm_score": 3, "selected": true, "text": "<p>if the problem truly is the wrong encoding (as opposed to a mixed encoding), you don't need to re-encode the document to parse it. just parse it as a Reader instead of an InputStream and the dom parser will ignore the header:</p>\n\n<pre><code>DocumentBuilder.parse(new InpputSource(new InputStreamReader(inputStream, \"&lt;real encoding&gt;\")));\n</code></pre>\n" }, { "answer_id": 217300, "author": "Watson Ladd", "author_id": 29025, "author_profile": "https://Stackoverflow.com/users/29025", "pm_score": 0, "selected": false, "text": "<p>You should tell them to send you correct UTF-8. Failing that any solution should reencode the bad characters as valid UTF-8 then pass it to the parser. The reason for this is that if the bad characters are preserved then different programs might interpret any output different ways, which can lead to security holes.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216890", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29042/" ]
One of our providers are sometimes sending XML feeds that are tagged as UTF-8 encoded documents but includes characters that are not included in the UTF-8 charset. This causes the parser to throw an exception and stop building the DOM object when these characters are encountered: ``` DocumentBuilder.parse(ByteArrayInputStream bais) ``` throws the following exception: ``` org.xml.sax.SAXParseException: Invalid byte 2 of 2-byte UTF-8 sequence. ``` Is there a way to "capture" these problems early and avoid the exception (i.e. finding and removing those characters from the stream)? What I'm looking for is a "best effort" type of fallback for wrongly encoded documents. The correct solution would obviously be to attack the problem at the source and make sure that only correct documents are delivered, but what is a good approach when that is not possible?
if the problem truly is the wrong encoding (as opposed to a mixed encoding), you don't need to re-encode the document to parse it. just parse it as a Reader instead of an InputStream and the dom parser will ignore the header: ``` DocumentBuilder.parse(new InpputSource(new InputStreamReader(inputStream, "<real encoding>"))); ```
216,894
<p>What's the best way to pipe the output from an java.io.OutputStream to a String in Java?</p> <p>Say I have the method:</p> <pre><code> writeToStream(Object o, OutputStream out) </code></pre> <p>Which writes certain data from the object to the given stream. However, I want to get this output into a String as easily as possible.</p> <p>I'm considering writing a class like this (untested):</p> <pre><code>class StringOutputStream extends OutputStream { StringBuilder mBuf; public void write(int byte) throws IOException { mBuf.append((char) byte); } public String getString() { return mBuf.toString(); } } </code></pre> <p>But is there a better way? I only want to run a test!</p>
[ { "answer_id": 216913, "author": "Horcrux7", "author_id": 12631, "author_profile": "https://Stackoverflow.com/users/12631", "pm_score": 10, "selected": true, "text": "<p>I would use a <code>ByteArrayOutputStream</code>. And on finish you can call:</p>\n\n<pre><code>new String( baos.toByteArray(), codepage );\n</code></pre>\n\n<p>or better:</p>\n\n<pre><code>baos.toString( codepage );\n</code></pre>\n\n<p>For the <code>String</code> constructor, the <code>codepage</code> can be a <code>String</code> or an instance of <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html\" rel=\"noreferrer\">java.nio.charset.Charset</a>. A possible value is <a href=\"http://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html#UTF_8\" rel=\"noreferrer\">java.nio.charset.StandardCharsets.UTF_8</a>.</p>\n\n<p>The method <code>toString()</code> accepts only a <code>String</code> as a <code>codepage</code> parameter (stand Java 8).</p>\n" }, { "answer_id": 216921, "author": "Joe Liversedge", "author_id": 4552, "author_profile": "https://Stackoverflow.com/users/4552", "pm_score": 6, "selected": false, "text": "<p>I like the Apache Commons IO library. Take a look at its version of <a href=\"https://commons.apache.org/proper/commons-io/javadocs/api-2.5/org/apache/commons/io/output/ByteArrayOutputStream.html\" rel=\"noreferrer\">ByteArrayOutputStream</a>, which has a <code>toString(String enc)</code> method as well as <code>toByteArray()</code>. Using existing and trusted components like the Commons project lets your code be smaller and easier to extend and repurpose.</p>\n" }, { "answer_id": 259952, "author": "Adrian Mouat", "author_id": 4332, "author_profile": "https://Stackoverflow.com/users/4332", "pm_score": 4, "selected": false, "text": "<p>Here's what I ended up doing:</p>\n\n<pre><code>Obj.writeToStream(toWrite, os);\ntry {\n String out = new String(os.toByteArray(), \"UTF-8\");\n assertTrue(out.contains(\"testString\"));\n} catch (UnsupportedEncondingException e) {\n fail(\"Caught exception: \" + e.getMessage());\n}\n</code></pre>\n\n<p>Where os is a <code>ByteArrayOutputStream</code>.</p>\n" }, { "answer_id": 1022434, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 5, "selected": false, "text": "<p>This worked nicely</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>OutputStream output = new OutputStream() {\n private StringBuilder string = new StringBuilder();\n\n @Override\n public void write(int b) throws IOException {\n this.string.append((char) b );\n }\n\n //Netbeans IDE automatically overrides this toString()\n public String toString() {\n return this.string.toString();\n }\n};\n</code></pre>\n\n<p>method call =>> <code>marshaller.marshal( (Object) toWrite , (OutputStream) output);</code></p>\n\n<p>then to print the string or get it just reference the \"output\" stream itself\nAs an example, to print the string out to console =>> <code>System.out.println(output);</code></p>\n\n<p>FYI: my method call <code>marshaller.marshal(Object,Outputstream)</code> is for working with XML. It is irrelevant to this topic.</p>\n\n<p>This is highly wasteful for productional use, there is a way too many conversion and it is a bit loose. This was just coded to prove to you that it is totally possible to create a custom OuputStream and output a string. But just go Horcrux7 way and all is good with merely two method calls. </p>\n\n<p>And the world lives on another day....</p>\n" }, { "answer_id": 61884063, "author": "jschnasse", "author_id": 1485527, "author_profile": "https://Stackoverflow.com/users/1485527", "pm_score": 3, "selected": false, "text": "<pre><code>baos.toString(StandardCharsets.UTF_8);\n</code></pre>\n<blockquote>\n<p>Converts the buffer's contents into a string by decoding the bytes using the named charset.</p>\n</blockquote>\n<p><a href=\"https://docs.oracle.com/en/java/javase/17/docs/api/java.base/java/io/ByteArrayOutputStream.html#toString()\" rel=\"nofollow noreferrer\">Java 17 - https://docs.oracle.com/</a></p>\n" }, { "answer_id": 73619210, "author": "Jurgen Rutten", "author_id": 14313338, "author_profile": "https://Stackoverflow.com/users/14313338", "pm_score": -1, "selected": false, "text": "<p>Here's what I did (don't use this in production, this is not great! But it makes fixing multiple errors easier.)</p>\n<ul>\n<li><p>Create a list that holds Exceptions.</p>\n</li>\n<li><p>Create a logger to log exceptions.</p>\n</li>\n<li><p>Use the code below:</p>\n<p>private static void exceptionChecker() throws Exception {\nif(exceptionList.isEmpty()) return; //nothing to do :) great news</p>\n<pre><code> //create lock for multithreading\n synchronized (System.err){\n //create new error stream\n ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();\n PrintStream errorOut = new PrintStream(byteArrayOutputStream);\n\n //save standard err out\n PrintStream standardErrOut = System.err;\n\n try{\n //set new error stream\n System.setErr(errorOut);\n\n exceptionList.forEach(exception -&gt; {\n exception.printStackTrace();\n System.err.println(&quot;&lt;----------&gt;&quot;);\n });\n\n\n } finally {\n //reset everything back to normal\n System.setErr(standardErrOut);\n\n //Log all the exceptions\n exceptionLogger.warning(byteArrayOutputStream.toString());\n\n //throw final generic exception\n throw new Exception();\n }\n }}\n</code></pre>\n</li>\n</ul>\n<p>This isn't great as you are throwing an error in the finally block and it locks on the error stream, but it works for dev purposes.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216894", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4332/" ]
What's the best way to pipe the output from an java.io.OutputStream to a String in Java? Say I have the method: ``` writeToStream(Object o, OutputStream out) ``` Which writes certain data from the object to the given stream. However, I want to get this output into a String as easily as possible. I'm considering writing a class like this (untested): ``` class StringOutputStream extends OutputStream { StringBuilder mBuf; public void write(int byte) throws IOException { mBuf.append((char) byte); } public String getString() { return mBuf.toString(); } } ``` But is there a better way? I only want to run a test!
I would use a `ByteArrayOutputStream`. And on finish you can call: ``` new String( baos.toByteArray(), codepage ); ``` or better: ``` baos.toString( codepage ); ``` For the `String` constructor, the `codepage` can be a `String` or an instance of [java.nio.charset.Charset](http://docs.oracle.com/javase/7/docs/api/java/nio/charset/Charset.html). A possible value is [java.nio.charset.StandardCharsets.UTF\_8](http://docs.oracle.com/javase/7/docs/api/java/nio/charset/StandardCharsets.html#UTF_8). The method `toString()` accepts only a `String` as a `codepage` parameter (stand Java 8).
216,959
<p>I have a web application with users and their documents. Each user can have many documents:</p> <p>user.rb: </p> <pre><code>has_many :documents </code></pre> <p>document.rb:</p> <pre><code>belongs_to :user </code></pre> <p>document_controller.rb:</p> <pre><code>def index @documents = Document.find(:all) end </code></pre> <p>I am using the restful_authentication plugin. Here is my question: How do I get the controller to only show documents that belongs to each user? Right now it shows all the documents for all the users.</p> <p>I am using the latest version of Rails.</p>
[ { "answer_id": 217011, "author": "sock", "author_id": 4028, "author_profile": "https://Stackoverflow.com/users/4028", "pm_score": 3, "selected": false, "text": "<p>You set a relationship in your User class to your Document class. This will automatically add a method to your User objects that returns a list of all documents related to a particular user:</p>\n\n<pre><code>def index\n @documents = @current_user.documents\nend\n</code></pre>\n\n<p>See the <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M001111\" rel=\"noreferrer\">documentation</a> for other automatically added methods.</p>\n" }, { "answer_id": 217018, "author": "srboisvert", "author_id": 6805, "author_profile": "https://Stackoverflow.com/users/6805", "pm_score": 3, "selected": true, "text": "<p>Take a look <a href=\"http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M000530\" rel=\"nofollow noreferrer\">here</a> in the rails API in the Association Join Models section.</p>\n\n<p>However be aware Restful authentication won't control access in order to limit the users to only their own records particularly with restful routes. They can still view other users' records by entering values in the urls once they are logged in.</p>\n\n<p>For that you might want to look into <a href=\"http://www.railslodge.com/plugins/966-restful-acl\" rel=\"nofollow noreferrer\">Restful ACL</a></p>\n" }, { "answer_id": 217698, "author": "JasonOng", "author_id": 6048, "author_profile": "https://Stackoverflow.com/users/6048", "pm_score": 2, "selected": false, "text": "<pre><code>def index\n @documents = Document.find(:all, :conditions =&gt; {:user_id =&gt; session[:user_id]})\nend\n</code></pre>\n" }, { "answer_id": 15600694, "author": "Lacloake", "author_id": 2204371, "author_profile": "https://Stackoverflow.com/users/2204371", "pm_score": 2, "selected": false, "text": "<p>Try this:</p>\n\n<pre><code>def index\n @documents = Document.where(:user_id =&gt; current_user.id)\nend\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216959", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29441/" ]
I have a web application with users and their documents. Each user can have many documents: user.rb: ``` has_many :documents ``` document.rb: ``` belongs_to :user ``` document\_controller.rb: ``` def index @documents = Document.find(:all) end ``` I am using the restful\_authentication plugin. Here is my question: How do I get the controller to only show documents that belongs to each user? Right now it shows all the documents for all the users. I am using the latest version of Rails.
Take a look [here](http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M000530) in the rails API in the Association Join Models section. However be aware Restful authentication won't control access in order to limit the users to only their own records particularly with restful routes. They can still view other users' records by entering values in the urls once they are logged in. For that you might want to look into [Restful ACL](http://www.railslodge.com/plugins/966-restful-acl)
216,963
<p>Say you have a large PHP project and suddenly, when attempting to run it, you just end up with a blank page. The script terminates and you want to find exactly where that is with as little effort as possible.</p> <p>Is there a tool/program/command/IDE that can, on PHP script termination, tell you the location of a script exit?</p> <p>Note: I can't mark my own post as "accepted answer" so look at the bottom to see my solution. If you come up with a better solution I will mark your post as the answer.</p>
[ { "answer_id": 216966, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": 0, "selected": false, "text": "<pre><code>grep -n die filename\n</code></pre>\n" }, { "answer_id": 216969, "author": "Edward Z. Yang", "author_id": 23845, "author_profile": "https://Stackoverflow.com/users/23845", "pm_score": 0, "selected": false, "text": "<p>Don't forget to grep for \"exit\" too.</p>\n" }, { "answer_id": 216979, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 0, "selected": false, "text": "<p>Add this to the top of the file:</p>\n\n<pre><code>function shutdown()\n{\n print_r(debug_backtrace());\n}\n\n\nregister_shutdown_function('shutdown');\n</code></pre>\n\n<p>See <a href=\"http://www.php.net/register_shutdown_function\" rel=\"nofollow noreferrer\">register_ shutdown_function()</a></p>\n" }, { "answer_id": 217022, "author": "troelskn", "author_id": 18180, "author_profile": "https://Stackoverflow.com/users/18180", "pm_score": 0, "selected": false, "text": "<p>You can use an interactive debugger to step through the code until you reach the exit point. Other than that, I think you're down to grep'ing the code for <code>exit|die</code>.</p>\n" }, { "answer_id": 217056, "author": "flungabunga", "author_id": 11000, "author_profile": "https://Stackoverflow.com/users/11000", "pm_score": 0, "selected": false, "text": "<p>xdebug has a nice trace feature that'll allow you to see all the entire trace of your php app execution and it should give you give clue as to where your exit is.</p>\n\n<p>but for the quick and dirty solution a grep/find as mentioned above will do rightly.</p>\n" }, { "answer_id": 217223, "author": "Hannes Landeholm", "author_id": 29442, "author_profile": "https://Stackoverflow.com/users/29442", "pm_score": 3, "selected": true, "text": "<p>With some inspiration from the nonworking but still right-direction answer from RoBorg, I used the following code in the beginning:</p>\n\n<pre><code>function shutdown() {\n global $dbg_stack_a;\n print_r($dbg_stack_a);\n}\nregister_shutdown_function('shutdown');\n</code></pre>\n\n<p>And then I made a global conditional breakpoint (global = breakpoint is evaluated on each row), exploiting the fact that it can run code trough eval(), with the following \"condition\":</p>\n\n<pre><code>eval('\nglobal $dbg_stack_a, $dbg_stack_b, $dbg_stack_c;\n$dbg_stack_a = $dbg_stack_b;\n$dbg_stack_b = $dbg_stack_c;\n$dbg_stack_c = debug_backtrace();\nreturn false;\n')\n</code></pre>\n\n<p>Probably not fast but does the trick! Using this I was able to determine the exact file and line location that raised die(). (This example works in NuSphere.)</p>\n" }, { "answer_id": 217255, "author": "Willem", "author_id": 15447, "author_profile": "https://Stackoverflow.com/users/15447", "pm_score": 0, "selected": false, "text": "<p>Also check the error___logs for \"<code>memory_limit</code>\" errors in the Apache error_log.</p>\n\n<blockquote>\n <p>Memory Limit >= 10M Warning: (Set this to 10M or larger in your php.ini file)</p>\n</blockquote>\n\n<p>In my experience, scripts suddenly end without warning or notice when this happens.</p>\n" }, { "answer_id": 217265, "author": "acrosman", "author_id": 24215, "author_profile": "https://Stackoverflow.com/users/24215", "pm_score": 0, "selected": false, "text": "<p>Make sure that errors are displayed in your development environment (not production).</p>\n" }, { "answer_id": 5120640, "author": "cweiske", "author_id": 282601, "author_profile": "https://Stackoverflow.com/users/282601", "pm_score": 4, "selected": false, "text": "<p>I use the following code and need no special debugging environment. Note that this might take really long; you can set the ticks count higher - that makes it faster, but blurry.</p>\n\n<pre><code>function shutdown_find_exit()\n{\n var_dump($GLOBALS['dbg_stack']);\n}\nregister_shutdown_function('shutdown_find_exit');\nfunction write_dbg_stack()\n{\n $GLOBALS['dbg_stack'] = debug_backtrace();\n}\nregister_tick_function('write_dbg_stack');\ndeclare(ticks=1);\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216963", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29442/" ]
Say you have a large PHP project and suddenly, when attempting to run it, you just end up with a blank page. The script terminates and you want to find exactly where that is with as little effort as possible. Is there a tool/program/command/IDE that can, on PHP script termination, tell you the location of a script exit? Note: I can't mark my own post as "accepted answer" so look at the bottom to see my solution. If you come up with a better solution I will mark your post as the answer.
With some inspiration from the nonworking but still right-direction answer from RoBorg, I used the following code in the beginning: ``` function shutdown() { global $dbg_stack_a; print_r($dbg_stack_a); } register_shutdown_function('shutdown'); ``` And then I made a global conditional breakpoint (global = breakpoint is evaluated on each row), exploiting the fact that it can run code trough eval(), with the following "condition": ``` eval(' global $dbg_stack_a, $dbg_stack_b, $dbg_stack_c; $dbg_stack_a = $dbg_stack_b; $dbg_stack_b = $dbg_stack_c; $dbg_stack_c = debug_backtrace(); return false; ') ``` Probably not fast but does the trick! Using this I was able to determine the exact file and line location that raised die(). (This example works in NuSphere.)
216,995
<p>Say I want to copy the contents of a directory excluding files and folders whose names contain the word 'Music'.</p> <pre><code>cp [exclude-matches] *Music* /target_directory </code></pre> <p>What should go in place of [exclude-matches] to accomplish this?</p>
[ { "answer_id": 217004, "author": "Daniel Bungert", "author_id": 21093, "author_profile": "https://Stackoverflow.com/users/21093", "pm_score": 2, "selected": false, "text": "<p>One solution for this can be found with find.</p>\n\n<pre><code>$ mkdir foo bar\n$ touch foo/a.txt foo/Music.txt\n$ find foo -type f ! -name '*Music*' -exec cp {} bar \\;\n$ ls bar\na.txt\n</code></pre>\n\n<p>Find has quite a few options, you can get pretty specific on what you include and exclude.</p>\n\n<p>Edit: Adam in the comments noted that this is recursive. find options mindepth and maxdepth can be useful in controlling this.</p>\n" }, { "answer_id": 217006, "author": "ejgottl", "author_id": 9808, "author_profile": "https://Stackoverflow.com/users/9808", "pm_score": 5, "selected": false, "text": "<p>Not in bash (that I know of), but:</p>\n\n<pre><code>cp `ls | grep -v Music` /target_directory\n</code></pre>\n\n<p>I know this is not exactly what you were looking for, but it will solve your example.</p>\n" }, { "answer_id": 217016, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 3, "selected": false, "text": "<p>You can also use a pretty simple <code>for</code> loop:</p>\n\n<pre><code>for f in `find . -not -name \"*Music*\"`\ndo\n cp $f /target/dir\ndone\n</code></pre>\n" }, { "answer_id": 217017, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 10, "selected": true, "text": "<p>In Bash you can do it by enabling the <code>extglob</code> option, like this (replace <code>ls</code> with <code>cp</code> and add the target directory, of course)</p>\n\n<pre><code>~/foobar&gt; shopt extglob\nextglob off\n~/foobar&gt; ls\nabar afoo bbar bfoo\n~/foobar&gt; ls !(b*)\n-bash: !: event not found\n~/foobar&gt; shopt -s extglob # Enables extglob\n~/foobar&gt; ls !(b*)\nabar afoo\n~/foobar&gt; ls !(a*)\nbbar bfoo\n~/foobar&gt; ls !(*foo)\nabar bbar\n</code></pre>\n\n<p>You can later disable extglob with</p>\n\n<pre><code>shopt -u extglob\n</code></pre>\n" }, { "answer_id": 217026, "author": "Steve", "author_id": 27893, "author_profile": "https://Stackoverflow.com/users/27893", "pm_score": 4, "selected": false, "text": "<p>If you want to avoid the mem cost of using the exec command, I believe you can do better with xargs. I think the following is a more efficient alternative to</p>\n\n<pre><code>find foo -type f ! -name '*Music*' -exec cp {} bar \\; # new proc for each exec\n\n\n\nfind . -maxdepth 1 -name '*Music*' -prune -o -print0 | xargs -0 -i cp {} dest/\n</code></pre>\n" }, { "answer_id": 217208, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 8, "selected": false, "text": "<p>The <code>extglob</code> shell option gives you more powerful pattern matching in the command line.</p>\n\n<p>You turn it on with <code>shopt -s extglob</code>, and turn it off with <code>shopt -u extglob</code>.</p>\n\n<p>In your example, you would initially do:</p>\n\n<pre><code>$ shopt -s extglob\n$ cp !(*Music*) /target_directory\n</code></pre>\n\n<p>The full available <strong>ext</strong>ended <strong>glob</strong>bing operators are (excerpt from <code>man bash</code>):</p>\n\n<blockquote>\n <p>If the extglob shell option is enabled using the shopt builtin, several extended\n pattern matching operators are recognized.<strong>A pattern-list is a list of one or more patterns separated by a |.</strong> Composite patterns may be formed using one or more of the following sub-patterns:</p>\n \n <ul>\n <li><b>?(pattern-list)</b><br>\n Matches zero or one occurrence of the given patterns </li>\n <li><b>*(pattern-list)</b><br>\n Matches zero or more occurrences of the given patterns </li>\n <li><b>+(pattern-list)</b><br>\n Matches one or more occurrences of the given patterns </li>\n <li><b>@(pattern-list)</b><br>\n Matches one of the given patterns </li>\n <li><b>!(pattern-list)</b><br>\n Matches anything except one of the given patterns</li>\n </ul>\n</blockquote>\n\n<p>So, for example, if you wanted to list all the files in the current directory that are not <code>.c</code> or <code>.h</code> files, you would do:</p>\n\n<pre><code>$ ls -d !(*@(.c|.h))\n</code></pre>\n\n<p>Of course, normal shell globing works, so the last example could also be written as:</p>\n\n<pre><code>$ ls -d !(*.[ch])\n</code></pre>\n" }, { "answer_id": 4979686, "author": "gabreal", "author_id": 614426, "author_profile": "https://Stackoverflow.com/users/614426", "pm_score": 1, "selected": false, "text": "<p>this would do it excluding exactly 'Music'</p>\n\n<pre><code>cp -a ^'Music' /target\n</code></pre>\n\n<p>this and that for excluding things like Music?* or *?Music</p>\n\n<pre><code>cp -a ^\\*?'complete' /target\ncp -a ^'complete'?\\* /target\n</code></pre>\n" }, { "answer_id": 5039641, "author": "Abid H. Mujtaba", "author_id": 622877, "author_profile": "https://Stackoverflow.com/users/622877", "pm_score": 2, "selected": false, "text": "<p>My personal preference is to use grep and the while command. This allows one to write powerful yet readable scripts ensuring that you end up doing exactly what you want. Plus by using an echo command you can perform a dry run before carrying out the actual operation. For example:</p>\n\n<pre><code>ls | grep -v \"Music\" | while read filename\ndo\necho $filename\ndone\n</code></pre>\n\n<p>will print out the files that you will end up copying. If the list is correct the next step is to simply replace the echo command with the copy command as follows:</p>\n\n<pre><code>ls | grep -v \"Music\" | while read filename\ndo\ncp \"$filename\" /target_directory\ndone\n</code></pre>\n" }, { "answer_id": 5140113, "author": "zrajm", "author_id": 351162, "author_profile": "https://Stackoverflow.com/users/351162", "pm_score": 2, "selected": false, "text": "<p>The following works lists all <code>*.txt</code> files in the current dir, except those that begin with a number.</p>\n\n<p>This works in <code>bash</code>, <code>dash</code>, <code>zsh</code> and all other POSIX compatible shells.</p>\n\n<pre><code>for FILE in /some/dir/*.txt; do # for each *.txt file\n case \"${FILE##*/}\" in # if file basename...\n [0-9]*) continue ;; # starts with digit: skip\n esac\n ## otherwise, do stuff with $FILE here\ndone\n</code></pre>\n\n<ol>\n<li><p>In line one the pattern <code>/some/dir/*.txt</code> will cause the <code>for</code> loop to iterate over all files in <code>/some/dir</code> whose name end with <code>.txt</code>.</p></li>\n<li><p>In line two a case statement is used to weed out undesired files. – The <code>${FILE##*/}</code> expression strips off any leading dir name component from the filename (here <code>/some/dir/</code>) so that patters can match against only the basename of the file. (If you're only weeding out filenames based on suffixes, you can shorten this to <code>$FILE</code> instead.)</p></li>\n<li><p>In line three, all files matching the <code>case</code> pattern <code>[0-9]*</code>) line will be skipped (the <code>continue</code> statement jumps to the next iteration of the <code>for</code> loop). – If you want to you can do something more interesting here, e.g. like skipping all files which do not start with a letter (a–z) using <code>[!a-z]*</code>, or you could use multiple patterns to skip several kinds of filenames e.g. <code>[0-9]*|*.bak</code> to skip files both <code>.bak</code> files, and files which does not start with a number.</p></li>\n</ol>\n" }, { "answer_id": 33974971, "author": "mivk", "author_id": 111036, "author_profile": "https://Stackoverflow.com/users/111036", "pm_score": 3, "selected": false, "text": "<p>In bash, an alternative to <code>shopt -s extglob</code> is the <a href=\"https://www.gnu.org/software/bash/manual/html_node/Filename-Expansion.html\" rel=\"noreferrer\"><code>GLOBIGNORE</code> variable</a>. It's not really better, but I find it easier to remember.</p>\n\n<p>An example that may be what the original poster wanted:</p>\n\n<pre><code>GLOBIGNORE=\"*techno*\"; cp *Music* /only_good_music/\n</code></pre>\n\n<p>When done, <code>unset GLOBIGNORE</code> to be able to <code>rm *techno*</code> in the source directory.</p>\n" }, { "answer_id": 42770388, "author": "James M. Lay", "author_id": 1461154, "author_profile": "https://Stackoverflow.com/users/1461154", "pm_score": 3, "selected": false, "text": "<p>A trick I haven't seen on here yet that doesn't use <code>extglob</code>, <code>find</code>, or <code>grep</code> is to treat two file lists as sets and <em>\"diff\"</em> them using <code>comm</code>:</p>\n\n<pre><code>comm -23 &lt;(ls) &lt;(ls *Music*)\n</code></pre>\n\n<p><code>comm</code> is preferable over <code>diff</code> because it doesn't have extra cruft.</p>\n\n<p>This returns all elements of set 1, <code>ls</code>, that are <em>not</em> also in set 2, <code>ls *Music*</code>. This requires both sets to be in sorted order to work properly. No problem for <code>ls</code> and glob expansion, but if you're using something like <code>find</code>, be sure to invoke <code>sort</code>.</p>\n\n<pre><code>comm -23 &lt;(find . | sort) &lt;(find . | grep -i '.jpg' | sort)\n</code></pre>\n\n<p>Potentially useful.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/216995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4812/" ]
Say I want to copy the contents of a directory excluding files and folders whose names contain the word 'Music'. ``` cp [exclude-matches] *Music* /target_directory ``` What should go in place of [exclude-matches] to accomplish this?
In Bash you can do it by enabling the `extglob` option, like this (replace `ls` with `cp` and add the target directory, of course) ``` ~/foobar> shopt extglob extglob off ~/foobar> ls abar afoo bbar bfoo ~/foobar> ls !(b*) -bash: !: event not found ~/foobar> shopt -s extglob # Enables extglob ~/foobar> ls !(b*) abar afoo ~/foobar> ls !(a*) bbar bfoo ~/foobar> ls !(*foo) abar bbar ``` You can later disable extglob with ``` shopt -u extglob ```
217,065
<p>I'm working on a sparse matrix class that <strong>needs</strong> to use an array of <code>LinkedList</code> to store the values of a matrix. Each element of the array (i.e. each <code>LinkedList</code>) represents a row of the matrix. And, each element in the <code>LinkedList</code> array represents a column and the stored value.</p> <p>In my class, I have a declaration of the array as:</p> <pre><code>private LinkedList&lt;IntegerNode&gt;[] myMatrix; </code></pre> <p>And, in my constructor for the <code>SparseMatrix</code>, I try to define:</p> <pre><code>myMatrix = new LinkedList&lt;IntegerNode&gt;[numRows]; </code></pre> <p>The error I end up getting is</p> <blockquote> <p>Cannot create a generic array of <code>LinkedList&lt;IntegerNode&gt;</code>.</p> </blockquote> <p>So, I have two issues with this:</p> <ol> <li>What am I doing wrong, and</li> <li>Why is the type acceptable in the declaration for the array if it can't be created?</li> </ol> <p><code>IntegerNode</code> is a class that I have created. And, all of my class files are packaged together.</p>
[ { "answer_id": 217093, "author": "Fredrik", "author_id": 9191, "author_profile": "https://Stackoverflow.com/users/9191", "pm_score": 7, "selected": false, "text": "<p>For some reason you have to cast the type and make the declaration like this:</p>\n\n<pre><code>myMatrix = (LinkedList&lt;IntegerNode&gt;[]) new LinkedList&lt;?&gt;[numRows];\n</code></pre>\n" }, { "answer_id": 217106, "author": "Paul Croarkin", "author_id": 18995, "author_profile": "https://Stackoverflow.com/users/18995", "pm_score": 2, "selected": false, "text": "<p>There is no generic array creation in Java 1.5 (or 1.6 as far as I can tell). See <a href=\"https://community.oracle.com/message/4829402\" rel=\"nofollow noreferrer\">https://community.oracle.com/message/4829402</a>.</p>\n" }, { "answer_id": 217110, "author": "Sergey", "author_id": 29363, "author_profile": "https://Stackoverflow.com/users/29363", "pm_score": 7, "selected": true, "text": "<p>You can't use generic array creation. It's a flaw/ feature of java generics. </p>\n\n<p>The ways without warnings are:</p>\n\n<ol>\n<li><p>Using List of Lists instead of Array of Lists: </p>\n\n<pre><code>List&lt; List&lt;IntegerNode&gt;&gt; nodeLists = new LinkedList&lt; List&lt; IntegerNode &gt;&gt;();\n</code></pre></li>\n<li><p>Declaring the special class for Array of Lists:</p>\n\n<pre><code>class IntegerNodeList {\n private final List&lt; IntegerNode &gt; nodes;\n}\n</code></pre></li>\n</ol>\n" }, { "answer_id": 217145, "author": "Dov Wasserman", "author_id": 26010, "author_profile": "https://Stackoverflow.com/users/26010", "pm_score": 3, "selected": false, "text": "<p>Aside from the syntax issues, it seems strange to me to use an array and a linked list to represent a matrix. To be able to access arbitrary cells of the matrix, you would probably want an actual array or at least an <code>ArrayList</code> to hold the rows, as <code>LinkedList</code> must traverse the whole list from the first element to any particular element, an <code>O(n)</code> operation, as opposed to the much quicker <code>O(1)</code> with <code>ArrayList</code> or an actual array.</p>\n\n<p>Since you mentioned this matrix is sparse, though, perhaps a better way to store the data is as a map of maps, where a key in the first map represents a row index, and its value is a row map whose keys are a column index, with the value being your IntegerNode class. Thus:</p>\n\n<pre><code>private Map&lt;Integer, Map&lt;Integer, IntegerNode&gt;&gt; myMatrix = new HashMap&lt;Integer, Map&lt;Integer, IntegerNode&gt;&gt;();\n\n// access a matrix cell:\nint rowIdx = 100;\nint colIdx = 30;\nMap&lt;Integer, IntegerNode&gt; row = myMatrix.get(rowIdx); // if null, create and add to matrix\nIntegerNode node = row.get(colIdx); // possibly null\n</code></pre>\n\n<p>If you need to be able to traverse the matrix row by row, you can make the row map type a <code>TreeMap</code>, and same for traversing the columns in index order, but if you don't need those cases, <code>HashMap</code> is quicker than <code>TreeMap</code>. Helper methods to get and set an arbitrary cell, handling unset null values, would be useful, of course.</p>\n" }, { "answer_id": 2559239, "author": "user306708", "author_id": 306708, "author_profile": "https://Stackoverflow.com/users/306708", "pm_score": 2, "selected": false, "text": "<blockquote>\n<p><code>myMatrix = (LinkedList&lt;IntegerNode&gt;[]) new LinkedList[numRows];</code></p>\n</blockquote>\n<p>casting this way works but still leaves you with a nasty warning:</p>\n<p>&quot;Type safety: The expression of type List[] needs unchecked conversion..&quot;</p>\n<blockquote>\n<p>Declaring a special class for Array of Lists:</p>\n<p><code>class IntegerNodeList { private final List&lt; IntegerNode &gt; nodes; }</code></p>\n</blockquote>\n<p>is a clever idea to avoid the warning. maybe a little bit nicer is to use an interface for it:</p>\n<pre><code>public interface IntegerNodeList extends List&lt;IntegerNode&gt; {}\n</code></pre>\n<p>then</p>\n<pre><code>List&lt;IntegerNode&gt;[] myMatrix = new IntegerNodeList[numRows];\n</code></pre>\n<p>compiles without warnings.</p>\n<p>doesn't look too bad, does it?</p>\n" }, { "answer_id": 5477207, "author": "Bob", "author_id": 682652, "author_profile": "https://Stackoverflow.com/users/682652", "pm_score": 2, "selected": false, "text": "<pre><code>class IntegerNodeList extends LinkedList&lt;IntegerNode&gt; {}\n\nIntegerNodeList[] myMatrix = new IntegerNodeList[numRows]; \n</code></pre>\n" }, { "answer_id": 5843737, "author": "Andrii", "author_id": 732640, "author_profile": "https://Stackoverflow.com/users/732640", "pm_score": 2, "selected": false, "text": "<pre><code>List&lt;String&gt;[] lst = new List[2];\nlst[0] = new LinkedList&lt;String&gt;();\nlst[1] = new LinkedList&lt;String&gt;();\n</code></pre>\n\n<p>No any warnings. NetBeans 6.9.1, jdk1.6.0_24</p>\n" }, { "answer_id": 12733948, "author": "Ryan", "author_id": 399887, "author_profile": "https://Stackoverflow.com/users/399887", "pm_score": 0, "selected": false, "text": "<p>If I do the following I get the error message in question</p>\n\n<pre><code>LinkedList&lt;Node&gt;[] matrix = new LinkedList&lt;Node&gt;[5];\n</code></pre>\n\n<p>But if I just remove the list type in the declaration it seems to have the desired functionality.</p>\n\n<pre><code>LinkedList&lt;Node&gt;[] matrix = new LinkedList[5];\n</code></pre>\n\n<p>Are these two declarations drastically different in a way of which I'm not aware?</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>Ah, I think I've run into this issue now.</p>\n\n<p>Iterating over the matrix and initializing the lists in a for-loop seems to work. Though it's not as ideal as some of the other solutions offered up.</p>\n\n<pre><code>for(int i=0; i &lt; matrix.length; i++){\n\n matrix[i] = new LinkedList&lt;&gt;();\n}\n</code></pre>\n" }, { "answer_id": 14797460, "author": "Yiling", "author_id": 1212682, "author_profile": "https://Stackoverflow.com/users/1212682", "pm_score": 0, "selected": false, "text": "<p>You need an array of List, one alternative is to try:</p>\n\n<pre><code>private IntegerNode[] node_array = new IntegerNode[sizeOfYourChoice];\n</code></pre>\n\n<p>Then <code>node_array[i]</code> stores the head(first) node of a <code>ArrayList&lt;IntegerNode&gt;</code> or <code>LinkedList&lt;IntegerNode&gt;</code> (whatever your favourite list implementation). </p>\n\n<p>Under this design, you lose the random access method <code>list.get(index)</code>, but then you could still traverse the list starting with the head/fist node store in the type safe array. </p>\n\n<p>This might be an acceptable design choice depending on your use case. For instance, I use this design to represent an adjacency list of graph, in most use cases, it requires traversing the adjacency list anyway for a given vertex instead of random access some vertex in the list.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/217065", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22371/" ]
I'm working on a sparse matrix class that **needs** to use an array of `LinkedList` to store the values of a matrix. Each element of the array (i.e. each `LinkedList`) represents a row of the matrix. And, each element in the `LinkedList` array represents a column and the stored value. In my class, I have a declaration of the array as: ``` private LinkedList<IntegerNode>[] myMatrix; ``` And, in my constructor for the `SparseMatrix`, I try to define: ``` myMatrix = new LinkedList<IntegerNode>[numRows]; ``` The error I end up getting is > > Cannot create a generic array of `LinkedList<IntegerNode>`. > > > So, I have two issues with this: 1. What am I doing wrong, and 2. Why is the type acceptable in the declaration for the array if it can't be created? `IntegerNode` is a class that I have created. And, all of my class files are packaged together.
You can't use generic array creation. It's a flaw/ feature of java generics. The ways without warnings are: 1. Using List of Lists instead of Array of Lists: ``` List< List<IntegerNode>> nodeLists = new LinkedList< List< IntegerNode >>(); ``` 2. Declaring the special class for Array of Lists: ``` class IntegerNodeList { private final List< IntegerNode > nodes; } ```
217,067
<p>I have a button on an ASP.Net page that will call Response.Redirect back to the same page after performing some processing in order to re-display the results of a query. However, for some reason, the page comes up blank. It seems that IsPostBack is returning true after the redirect. Anybody know why this would happen?</p> <p>The page is a custom page in Community Server. Here is the basic code:</p> <pre><code>void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string connStr = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString; SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ge_vw_NonResidents", connStr); DataTable tbl = new DataTable(); da.Fill(tbl); da.Dispose(); rptNonResidents.DataSource = tbl; rptNonResidents.DataBind(); } } void btnApprove_Command(object sender, CommandEventArgs e) { // Code removed for testing. Response.Clear(); Response.Redirect("ApproveResidents.aspx", true); Response.End(); } </code></pre>
[ { "answer_id": 217134, "author": "Mark Brackett", "author_id": 2199, "author_profile": "https://Stackoverflow.com/users/2199", "pm_score": 2, "selected": false, "text": "<p>A Response.Redirect will trigger an HTTP <em>GET</em> from the browser. As no data is posted, IsPostBack is false. You have something else going on.</p>\n\n<p>I'd suggest firing up <a href=\"http://www.fiddlertool.com/\" rel=\"nofollow noreferrer\">Fiddler</a> and looking at the sequence of requests. It should look something like:</p>\n\n<ul>\n<li>Client: HTTP POST (button click)</li>\n<li>Server: HTTP 302 (Redirect)</li>\n<li>Client: HTTP GET</li>\n<li>Server: HTTP 200 (Writes page)</li>\n</ul>\n" }, { "answer_id": 217260, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "<p>I suggest this as a better solution to your problem than attempting to redirect from the browser.</p>\n\n<pre><code>protected void Page_Load( object sender, EventArgs e )\n{\n if (!IsPosBack) {\n BuildData();\n }\n}\n\nvoid btnApprove_Command(object sender, CommandEventArgs e)\n{\n // do your stuff and clear any some controls, maybe\n\n BuildData();\n}\n\nprivate void BuildData()\n{\n string connStr = ConfigurationManager.ConnectionStrings[\"SiteSqlServer\"].ConnectionString;\n SqlDataAdapter da = new SqlDataAdapter(\"SELECT * FROM ge_vw_NonResidents\", connStr);\n DataTable tbl = new DataTable();\n da.Fill(tbl);\n da.Dispose();\n rptNonResidents.DataSource = tbl;\n rptNonResidents.DataBind();\n}\n</code></pre>\n" }, { "answer_id": 217627, "author": "Brian", "author_id": 320, "author_profile": "https://Stackoverflow.com/users/320", "pm_score": 3, "selected": true, "text": "<p>Sorry, it was an id-10-t error. My event handler wasn't getting called at all. The page had EnableViewState=\"false\". Once I changed that to true it worked.</p>\n\n<p>I also took tvanfosson suggestion. This allows me to display a confirmation message. I can easily check to see if the action has already been taken and safely ignore it. Since I'm likely the only one to ever see this screen, I'm not too concerned with usability.</p>\n" }, { "answer_id": 1706735, "author": "asf", "author_id": 207654, "author_profile": "https://Stackoverflow.com/users/207654", "pm_score": 1, "selected": false, "text": "<p>The page is posted back , that is why you're getting it as true. make sure it is false.</p>\n" }, { "answer_id": 73907810, "author": "Vishakha Suthar", "author_id": 19782028, "author_profile": "https://Stackoverflow.com/users/19782028", "pm_score": 1, "selected": false, "text": "<pre><code>Response.Redirect(url,true); \n</code></pre>\n<p>this worked for me.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/217067", "https://Stackoverflow.com", "https://Stackoverflow.com/users/320/" ]
I have a button on an ASP.Net page that will call Response.Redirect back to the same page after performing some processing in order to re-display the results of a query. However, for some reason, the page comes up blank. It seems that IsPostBack is returning true after the redirect. Anybody know why this would happen? The page is a custom page in Community Server. Here is the basic code: ``` void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { string connStr = ConfigurationManager.ConnectionStrings["SiteSqlServer"].ConnectionString; SqlDataAdapter da = new SqlDataAdapter("SELECT * FROM ge_vw_NonResidents", connStr); DataTable tbl = new DataTable(); da.Fill(tbl); da.Dispose(); rptNonResidents.DataSource = tbl; rptNonResidents.DataBind(); } } void btnApprove_Command(object sender, CommandEventArgs e) { // Code removed for testing. Response.Clear(); Response.Redirect("ApproveResidents.aspx", true); Response.End(); } ```
Sorry, it was an id-10-t error. My event handler wasn't getting called at all. The page had EnableViewState="false". Once I changed that to true it worked. I also took tvanfosson suggestion. This allows me to display a confirmation message. I can easily check to see if the action has already been taken and safely ignore it. Since I'm likely the only one to ever see this screen, I'm not too concerned with usability.
217,070
<p>Using Apache's commons-httpclient for Java, what's the best way to add query parameters to a GetMethod instance? If I'm using PostMethod, it's very straightforward:</p> <pre><code>PostMethod method = new PostMethod(); method.addParameter("key", "value"); </code></pre> <p>GetMethod doesn't have an "addParameter" method, though. I've discovered that this works:</p> <pre><code>GetMethod method = new GetMethod("http://www.example.com/page"); method.setQueryString(new NameValuePair[] { new NameValuePair("key", "value") }); </code></pre> <p>However, most of the examples I've seen either hard-code the parameters directly into the URL, e.g.:</p> <pre><code>GetMethod method = new GetMethod("http://www.example.com/page?key=value"); </code></pre> <p>or hard-code the query string, e.g.:</p> <pre><code>GetMethod method = new GetMethod("http://www.example.com/page"); method.setQueryString("?key=value"); </code></pre> <p>Is one of these patterns to be preferred? And why the API discrepancy between PostMethod and GetMethod? And what are all those other HttpMethodParams methods intended to be used for?</p>
[ { "answer_id": 217102, "author": "Ryan Guest", "author_id": 1811, "author_profile": "https://Stackoverflow.com/users/1811", "pm_score": 6, "selected": true, "text": "<p>Post methods have post parameters, but <a href=\"http://www.cs.tut.fi/~jkorpela/forms/methods.html\" rel=\"noreferrer\">get methods do not</a>.</p>\n\n<p>Query parameters are embedded in the URL. The current version of HttpClient accepts a string in the constructor. If you wanted to add the key, value pair above, you could use:</p>\n\n<pre><code>String url = \"http://www.example.com/page?key=value\";\nGetMethod method = new GetMethod(url);\n</code></pre>\n\n<p>A good starting tutorial can be found on the <a href=\"http://hc.apache.org/httpclient-3.x/tutorial.html\" rel=\"noreferrer\">Apache Jakarta Commons page</a>.</p>\n\n<p><strong>Update</strong>: As suggested in the comment, NameValuePair works.</p>\n\n<pre><code>GetMethod method = new GetMethod(\"example.com/page\"); \nmethod.setQueryString(new NameValuePair[] { \n new NameValuePair(\"key\", \"value\") \n}); \n</code></pre>\n" }, { "answer_id": 3443335, "author": "Steve Jones", "author_id": 165085, "author_profile": "https://Stackoverflow.com/users/165085", "pm_score": 4, "selected": false, "text": "<p>It's not just a matter of personal preference. The pertinent issue here is URL-encoding your parameter values, so that the values won't get corrupted or misinterpreted as extra delimiters, etc.</p>\n\n<p>As always, it is best to read the API documentation in detail:\n<a href=\"http://hc.apache.org/httpclient-3.x/apidocs/org/apache/commons/httpclient/HttpMethodBase.html#setQueryString(org.apache.commons.httpclient.NameValuePair[])\" rel=\"noreferrer\">HttpClient API Documentation</a></p>\n\n<p>Reading this, you can see that <code>setQueryString(String)</code> will NOT URL-encode or delimit your parameters &amp; values, whereas <code>setQueryString(NameValuePair[])</code> will automatically URL-encode and delimit your parameter names and values. This is the best method whenever you are using dynamic data, because it might contain ampersands, equal signs, etc.</p>\n" }, { "answer_id": 13033597, "author": "Randal Harleigh", "author_id": 1768747, "author_profile": "https://Stackoverflow.com/users/1768747", "pm_score": 3, "selected": false, "text": "<p>Try it this way:</p>\n\n<pre><code> URIBuilder builder = new URIBuilder(\"https://graph.facebook.com/oauth/access_token\")\n .addParameter(\"client_id\", application.getKey())\n .addParameter(\"client_secret\", application.getSecret())\n .addParameter(\"redirect_uri\", callbackURL)\n .addParameter(\"code\", code);\n\n HttpPost method = new HttpPost(builder.build());\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/217070", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29173/" ]
Using Apache's commons-httpclient for Java, what's the best way to add query parameters to a GetMethod instance? If I'm using PostMethod, it's very straightforward: ``` PostMethod method = new PostMethod(); method.addParameter("key", "value"); ``` GetMethod doesn't have an "addParameter" method, though. I've discovered that this works: ``` GetMethod method = new GetMethod("http://www.example.com/page"); method.setQueryString(new NameValuePair[] { new NameValuePair("key", "value") }); ``` However, most of the examples I've seen either hard-code the parameters directly into the URL, e.g.: ``` GetMethod method = new GetMethod("http://www.example.com/page?key=value"); ``` or hard-code the query string, e.g.: ``` GetMethod method = new GetMethod("http://www.example.com/page"); method.setQueryString("?key=value"); ``` Is one of these patterns to be preferred? And why the API discrepancy between PostMethod and GetMethod? And what are all those other HttpMethodParams methods intended to be used for?
Post methods have post parameters, but [get methods do not](http://www.cs.tut.fi/~jkorpela/forms/methods.html). Query parameters are embedded in the URL. The current version of HttpClient accepts a string in the constructor. If you wanted to add the key, value pair above, you could use: ``` String url = "http://www.example.com/page?key=value"; GetMethod method = new GetMethod(url); ``` A good starting tutorial can be found on the [Apache Jakarta Commons page](http://hc.apache.org/httpclient-3.x/tutorial.html). **Update**: As suggested in the comment, NameValuePair works. ``` GetMethod method = new GetMethod("example.com/page"); method.setQueryString(new NameValuePair[] { new NameValuePair("key", "value") }); ```
217,073
<p>I have a linked list that I want to sort part of, eg:</p> <pre><code>std::sort(someIterator, otherIterator, predicate); </code></pre> <p>std::sort requires random-access iterators so this approach doesn't work. There is a specialisation std::list::sort, but that can only sort the entire list. I don't think I have enough access to the list members to write something myself.</p> <p>Is there a way to do this without changing to, say, vector?</p>
[ { "answer_id": 217083, "author": "Leon Timmermans", "author_id": 4727, "author_profile": "https://Stackoverflow.com/users/4727", "pm_score": 2, "selected": false, "text": "<p>Yes, but you will have to use a <a href=\"http://en.literateprograms.org/Merge_sort_(C_Plus_Plus)\" rel=\"nofollow noreferrer\">merge sort</a>.</p>\n" }, { "answer_id": 217171, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 5, "selected": true, "text": "<p>How about unhooking the part of the list that you want sorted, into a standalone list,\nthen use the specialized list sort, then hook it back into the original list?</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/217073", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22517/" ]
I have a linked list that I want to sort part of, eg: ``` std::sort(someIterator, otherIterator, predicate); ``` std::sort requires random-access iterators so this approach doesn't work. There is a specialisation std::list::sort, but that can only sort the entire list. I don't think I have enough access to the list members to write something myself. Is there a way to do this without changing to, say, vector?
How about unhooking the part of the list that you want sorted, into a standalone list, then use the specialized list sort, then hook it back into the original list?
217,074
<p>I've been having a lot of problems trying to figure out how to use <code>scanf()</code>. It seems to work fine with integers, being fairly straight forward <code>scanf("%d", &amp;i)</code>.</p> <p>Where I am running into issues is using <code>scanf()</code> in loops trying to read input. For example:</p> <pre><code>do { printf("counter: %d: ", counter); scanf("%c %c%d", &amp;command, &amp;prefix, &amp;input); } while (command != 'q'); </code></pre> <ol> <li><p>When I enter in a validly structured input like <code>c P101</code>, it seems to loop again before prompting me. This seems to happen even with a single:</p> <pre><code>scanf("%c", &amp;c) </code></pre> <p>in a while loop. It'll do the loop twice before prompting me again. What is making it loop twice, and how do I stop it?</p></li> <li><p>When I enter in less amount of input that programmatically wouldn't have another character or number such as <code>q</code>, pressing enter seems to prompt me to enter more. How do I get <code>scanf()</code> to process both single and double character entries? </p></li> </ol>
[ { "answer_id": 217085, "author": "Andrew Edgecombe", "author_id": 11694, "author_profile": "https://Stackoverflow.com/users/11694", "pm_score": 1, "selected": false, "text": "<p>For question 1, I suspect that you've got a problem with your <code>printf()</code>, since there is no terminating \"\\n\".</p>\n\n<p>The default behavior of <code>printf</code> is to buffer output until it has a complete line. That is unless you explicitly change the buffering on <code>stdout</code>.</p>\n\n<p>For question 2, you've just hit one of the biggest problems with <code>scanf()</code>. Unless your input exactly matches the scan string that you've specified, your results are going to be nothing like what you expect.</p>\n\n<p>If you've got an option you'll have better results (and fewer security issues) by ignoring <code>scanf()</code> and doing your own parsing. For example, use <code>fgets()</code> to read an entire line into a string, and then process the individual fields of the string &mdash; maybe even using <code>sscanf()</code>.</p>\n" }, { "answer_id": 217122, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 5, "selected": true, "text": "<p>When you enter \"<code>c P101</code>\" the program actually receives \"<code>c P101\\n</code>\". Most of the conversion specifiers skip leading whitespace including newlines but <code>%c</code> does not. The first time around everything up til the \"<code>\\n</code>\" is read, the second time around the \"\\n\" is read into <code>command</code>, \"<code>c</code>\" is read into <code>prefix</code>, and \"<code>P</code>\" is left which is not a number so the conversion fails and \"<code>P101\\n</code>\" is left on the stream. The next time \"<code>P</code>\" is stored into command, \"<code>1</code>\" is stored into prefix, and <code>1</code> (from the remaining \"<code>01</code>\") is stored into input with the \"<code>\\n</code>\" still on the stream for next time. You can fix this issue by putting a space at the beginning of the format string which will skip any leading whitespace including newlines.</p>\n\n<p>A similiar thing is happening for the second case, when you enter \"<code>q</code>\", \"<code>q\\n</code>\" is entered into the stream, the first time around the \"<code>q</code>\" is read, the second time the \"<code>\\n</code>\" is read, only on the third call is the second \"<code>q</code>\" read, you can avoid the problem again by adding a space character at the beginning of the format string.</p>\n\n<p>A better way to do this would be to use something like fgets() to process a line at a time and then use sscanf() to do the parsing.</p>\n" }, { "answer_id": 217126, "author": "Federico A. Ramponi", "author_id": 18770, "author_profile": "https://Stackoverflow.com/users/18770", "pm_score": 1, "selected": false, "text": "<p>It's really broken! I didn't know it</p>\n\n<pre><code>#include &lt;stdio.h&gt;\n\nint main(void)\n{\n int counter = 1;\n char command, prefix;\n int input;\n\n do \n {\n printf(\"counter: %d: \", counter);\n scanf(\"%c %c%d\", &command, &prefix, &input);\n printf(\"---%c %c%d---\\n\", command, prefix, input);\n counter++;\n } while (command != 'q');\n}\n</code></pre>\n\n<pre><code>counter: 1: a b1\n---a b1---\ncounter: 2: c d2\n---\n c1---\ncounter: 3: e f3\n---d 21---\ncounter: 4: ---e f3---\ncounter: 5: g h4\n---\n g3---\n</code></pre>\n\n<p>The output seems to fit with Robert's answer.</p>\n" }, { "answer_id": 217142, "author": "jaircazarin-old-account", "author_id": 20915, "author_profile": "https://Stackoverflow.com/users/20915", "pm_score": 1, "selected": false, "text": "<p>Once you have the string that contains the line. i.e. \"C P101\", you can use the parsing abilities of sscanf.</p>\n\n<p>See:\n<a href=\"http://www.cplusplus.com/reference/clibrary/cstdio/sscanf.html\" rel=\"nofollow noreferrer\">http://www.cplusplus.com/reference/clibrary/cstdio/sscanf.html</a></p>\n" }, { "answer_id": 13471778, "author": "jap3r", "author_id": 1838532, "author_profile": "https://Stackoverflow.com/users/1838532", "pm_score": 0, "selected": false, "text": "<p>Perhaps using a while loop, not a do...while loop will help. This way the condition is tested before execution of the code.\nTry the following code snippet:</p>\n\n<pre><code> while(command != 'q')\n {\n //statements\n }\n</code></pre>\n\n<p>Also, if you know the string length ahead of time, 'for' loops can be much easier to work with than 'while' loops. There are also some trickier ways to dynamically determine the length as well.</p>\n\n<p>As a final rant: <code>scanf()</code> does not \"suck.\" It does what it does and that is all.</p>\n\n<p>The <a href=\"https://stackoverflow.com/questions/1694036/why-is-the-gets-function-dangerous-why-should-it-not-be-used\"><code>gets()</code> function is very dangerous</a> (though convenient for no-risk applications), since it does not natively do any checking of the input. It is VERY commonly known as a point of exploit, specifically buffer overflow attacks, overwriting space in registers not allocated for that variable. Therefore if you choose to use it, spend some time putting some solid error checking/correction in.</p>\n\n<p>However, almost invariably, either <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/fgets.html\" rel=\"nofollow noreferrer\"><code>fgets()</code></a> or POSIX <a href=\"http://pubs.opengroup.org/onlinepubs/9699919799/functions/getline.html\" rel=\"nofollow noreferrer\"><code>getline()</code></a> should be used to read the line — noting that the functions both include the newline in the input string, unlike <code>gets()</code>. You can remove the trailing newline from <code>string</code> read by either <code>fgets()</code> or <code>getline()</code> using <code>string[strcspn(string, \"\\n\")] = '\\0';</code> — this works reliably.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/217074", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9628/" ]
I've been having a lot of problems trying to figure out how to use `scanf()`. It seems to work fine with integers, being fairly straight forward `scanf("%d", &i)`. Where I am running into issues is using `scanf()` in loops trying to read input. For example: ``` do { printf("counter: %d: ", counter); scanf("%c %c%d", &command, &prefix, &input); } while (command != 'q'); ``` 1. When I enter in a validly structured input like `c P101`, it seems to loop again before prompting me. This seems to happen even with a single: ``` scanf("%c", &c) ``` in a while loop. It'll do the loop twice before prompting me again. What is making it loop twice, and how do I stop it? 2. When I enter in less amount of input that programmatically wouldn't have another character or number such as `q`, pressing enter seems to prompt me to enter more. How do I get `scanf()` to process both single and double character entries?
When you enter "`c P101`" the program actually receives "`c P101\n`". Most of the conversion specifiers skip leading whitespace including newlines but `%c` does not. The first time around everything up til the "`\n`" is read, the second time around the "\n" is read into `command`, "`c`" is read into `prefix`, and "`P`" is left which is not a number so the conversion fails and "`P101\n`" is left on the stream. The next time "`P`" is stored into command, "`1`" is stored into prefix, and `1` (from the remaining "`01`") is stored into input with the "`\n`" still on the stream for next time. You can fix this issue by putting a space at the beginning of the format string which will skip any leading whitespace including newlines. A similiar thing is happening for the second case, when you enter "`q`", "`q\n`" is entered into the stream, the first time around the "`q`" is read, the second time the "`\n`" is read, only on the third call is the second "`q`" read, you can avoid the problem again by adding a space character at the beginning of the format string. A better way to do this would be to use something like fgets() to process a line at a time and then use sscanf() to do the parsing.
217,113
<p>Long time ago, I saved a sentence from a Java reference book: <em>"Java has no mechanism to handle deadlock. it won't even know deadlock occurred." (Head First Java 2nd Edition, p.516)</em></p> <p>So, what is about it? Is there a way to catch deadlock case in Java? I mean, is there a way that our code understands a deadlock case occurred?</p>
[ { "answer_id": 217127, "author": "Steve K", "author_id": 739, "author_profile": "https://Stackoverflow.com/users/739", "pm_score": 4, "selected": false, "text": "<p><a href=\"http://java.sun.com/javase/6/docs/technotes/guides/management/jconsole.html\" rel=\"noreferrer\">JConsole</a> is able to detect deadlocks in a running application.</p>\n" }, { "answer_id": 217130, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 2, "selected": false, "text": "<p>Not exactly what you asked, but when a deadlock <em>does</em> occur, you can do a \"kill -3\" on the process id and it dumps a thread dump to stdout. Also, the 1.6 jvm has some tools to do the same thing in a gui manner.</p>\n" }, { "answer_id": 217135, "author": "Paul Croarkin", "author_id": 18995, "author_profile": "https://Stackoverflow.com/users/18995", "pm_score": 2, "selected": false, "text": "<p>If you are running from the command-line and you suspect that you are deadlocked, try ctrl+break in windows (ctrl+\\ in unix) to get a thread dump.\nSee <a href=\"http://java.sun.com/javase/6/webnotes/trouble/TSG-VM/html/gbmps.html\" rel=\"nofollow noreferrer\">http://java.sun.com/javase/6/webnotes/trouble/TSG-VM/html/gbmps.html</a></p>\n" }, { "answer_id": 217179, "author": "luke", "author_id": 25920, "author_profile": "https://Stackoverflow.com/users/25920", "pm_score": 3, "selected": false, "text": "<p>In general java does not offer deadlock detection. The synchronized keyword and built in monitors make it somewhat more difficult to reason about deadlock than in languages with explicit locking.</p>\n\n<p>I would suggest migrating to using java.util.concurrent.Lock locks and the like in order to make your locking schemes easier to reason about. In fact you could easily make your own implementation of the lock interface with deadlock detection. The algorithm is to basically traverse the lock dependency graph and look for a cycle. </p>\n" }, { "answer_id": 217440, "author": "Alex Miller", "author_id": 7671, "author_profile": "https://Stackoverflow.com/users/7671", "pm_score": 4, "selected": false, "text": "<p>JDK 5 and 6 will dump held lock information in a full thread dump (obtained with kill -3, jstack, jconsole, etc). JDK 6 even contains information about ReentrantLock and ReentrantReadWriteLock. It is possible from this information to diagnose a deadlock by finding a lock cycle: Thread A holds lock 1, Thread B holds lock 2, and either A is requesting 2 or B is requesting 1. From my experience, this is usually pretty obvious.</p>\n\n<p>Other analysis tools can actually find potential deadlocks even if they don't occur. Thread tools from vendors like OptimizeIt, JProbe, Coverity, etc are good places to look.</p>\n" }, { "answer_id": 217453, "author": "user29480", "author_id": 29480, "author_profile": "https://Stackoverflow.com/users/29480", "pm_score": 2, "selected": false, "text": "<p>Dr. Heinz Kabutz of JavaSpecialists has written an entertaining and informative <a href=\"http://www.javaspecialists.eu/archive/Issue160.html\" rel=\"nofollow noreferrer\">newsletter issue on Java deadlocks</a> and describes something called a ThreadMXBean in <a href=\"http://www.javaspecialists.eu/archive/Issue130.html\" rel=\"nofollow noreferrer\">another newsletter issue</a>. Between those, you should get a good idea of the issues and some pointers to doing your own instrumentation.</p>\n" }, { "answer_id": 217558, "author": "paxdiablo", "author_id": 14860, "author_profile": "https://Stackoverflow.com/users/14860", "pm_score": 3, "selected": false, "text": "<p>Deadlocks can be avoided if you follow a simple rule: have all threads claim and release their locks in the same order. In this way, you never get into a situation where a deadlock can occur.</p>\n\n<p>Even the dining philosophers problem can be seen as a violation of this rule as it uses relative concepts of left and right spoon which result in different threads using different allocation orders of the spoons. If the spoons were numbered uniquely and the philosophers all tried to get the lowest numbered spoon first, deadlock would be impossible.</p>\n\n<p>In my opinion, prevention is better than cure.</p>\n\n<p>This is one of the two guidelines I like to follow to ensure threads work properly. The other is ensuring each thread is <strong>solely</strong> responsible for its own execution as it's the only one fully aware of what it's doing at any point in time.</p>\n\n<p>So that means no <code>Thread.stop</code> calls, use a global flag (or message queue or something like that) to tell another thread you want action taken. Then let that thread do the actual work.</p>\n" }, { "answer_id": 217693, "author": "WMR", "author_id": 2844, "author_profile": "https://Stackoverflow.com/users/2844", "pm_score": 2, "selected": false, "text": "<p>If you are on Java 5 you can call the method <code>findMonitorDeadlockedThreads()</code> on the ThreadMXBean which you can get through a call of <code>java.lang.management.ManagementFactory.getThreadMXBean()</code>. This will find deadlocks caused by object monitors only. On Java 6 there's <code>findDeadlockedThreads()</code> which will also find deadlocks caused by \"ownable synchronizers (for example <code>ReentrandLock</code> and <code>ReentrantReadWriteLock</code>). </p>\n\n<p>Be aware that it will probably be expensive to call these methods, so they should be used for troubleshooting purposes only.</p>\n" }, { "answer_id": 217701, "author": "staffan", "author_id": 988, "author_profile": "https://Stackoverflow.com/users/988", "pm_score": 6, "selected": false, "text": "<p>Since JDK 1.5 there are very useful methods in the <code>java.lang.management</code> package to find and inspect deadlocks that occurs. See the <code>findMonitorDeadlockedThreads()</code> and <code>findDeadlockedThreads()</code> method of the <code>ThreadMXBean</code> class.</p>\n\n<p>A possible way to use this is to have a separate watchdog thread (or periodic task) that does this.</p>\n\n<p>Sample code:</p>\n\n<pre><code> ThreadMXBean tmx = ManagementFactory.getThreadMXBean();\n long[] ids = tmx.findDeadlockedThreads();\n if (ids != null) {\n ThreadInfo[] infos = tmx.getThreadInfo(ids, true, true);\n System.out.println(\"The following threads are deadlocked:\");\n for (ThreadInfo ti : infos) {\n System.out.println(ti);\n }\n }\n</code></pre>\n" }, { "answer_id": 222281, "author": "Scott Stanchfield", "author_id": 12541, "author_profile": "https://Stackoverflow.com/users/12541", "pm_score": 2, "selected": false, "text": "<p>If you're debugging in eclipse, you can pause the application (select the app in the debug view and the little || button on the debug toolbar) and then it can report deadlocks.</p>\n\n<p>See <a href=\"http://runnerwhocodes.blogspot.com/2007/10/deadlock-detection-with-eclipse.html\" rel=\"nofollow noreferrer\">http://runnerwhocodes.blogspot.com/2007/10/deadlock-detection-with-eclipse.html</a> for an example.</p>\n" }, { "answer_id": 1661294, "author": "Dave Griffiths", "author_id": 15379, "author_profile": "https://Stackoverflow.com/users/15379", "pm_score": 4, "selected": false, "text": "<p>Note that there is a type of deadlock using the concurrent package that is very hard to debug. That is where you have a ReentrantReadWriteLock and one thread grabs the read lock and then (say) tries to enter a monitor held by some other thread that is also waiting to grab the write lock. What makes it especially hard to debug is that there is no record of who has entered a read lock. It is simply a count. The thread might even have thrown an exception and died leaving the read count non-zero.</p>\n\n<p>Here is a sample deadlock that the findDeadlockedThreads method mentioned earlier won't get:</p>\n\n<pre><code>import java.util.concurrent.locks.*;\nimport java.lang.management.*;\n\npublic class LockTest {\n\n static ReentrantReadWriteLock lock = new ReentrantReadWriteLock();\n\n public static void main(String[] args) throws Exception {\n Reader reader = new Reader();\n Writer writer = new Writer();\n sleep(10);\n System.out.println(\"finding deadlocked threads\");\n ThreadMXBean tmx = ManagementFactory.getThreadMXBean();\n long[] ids = tmx.findDeadlockedThreads();\n if (ids != null) {\n ThreadInfo[] infos = tmx.getThreadInfo(ids, true, true);\n System.out.println(\"the following threads are deadlocked:\");\n for (ThreadInfo ti : infos) {\n System.out.println(ti);\n }\n }\n System.out.println(\"finished finding deadlocked threads\");\n }\n\n static void sleep(int seconds) {\n try {\n Thread.currentThread().sleep(seconds*1000);\n } catch (InterruptedException e) {}\n }\n\n static class Reader implements Runnable {\n Reader() {\n new Thread(this).start();\n }\n public void run() {\n sleep(2);\n System.out.println(\"reader thread getting lock\");\n lock.readLock().lock();\n System.out.println(\"reader thread got lock\");\n synchronized (lock) {\n System.out.println(\"reader thread inside monitor!\");\n lock.readLock().unlock();\n }\n }\n }\n\n static class Writer implements Runnable {\n Writer() {\n new Thread(this).start();\n }\n public void run() {\n synchronized (lock) {\n sleep(4);\n System.out.println(\"writer thread getting lock\");\n lock.writeLock().lock();\n System.out.println(\"writer thread got lock!\");\n }\n }\n }\n}\n</code></pre>\n" }, { "answer_id": 2897687, "author": "Saurabh M. Chande", "author_id": 349035, "author_profile": "https://Stackoverflow.com/users/349035", "pm_score": -1, "selected": false, "text": "<p>After so long, i am able to write the simplest example of Deadlock. \nComments are welcome. </p>\n\n<pre><code>Class A\n{\n synchronized void methodA(B b)\n {\n b.last();\n }\n\n synchronized void last()\n {\n SOP(“ Inside A.last()”);\n }\n}\n\nClass B\n{\n synchronized void methodB(A a)\n {\n a.last();\n }\n\n synchronized void last()\n {\n SOP(“ Inside B.last()”);\n }\n}\n\n\nClass Deadlock implements Runnable \n{\n A a = new A(); \n B b = new B();\n\n // Constructor\n Deadlock()\n {\n Thread t = new Thread(); \n t.start();\n a.methodA(b);\n }\n\n public void run()\n {\n b.methodB(a);\n }\n\n public static void main(String args[] )\n {\n new Deadlock();\n }\n}\n</code></pre>\n" }, { "answer_id": 5927441, "author": "venu", "author_id": 743871, "author_profile": "https://Stackoverflow.com/users/743871", "pm_score": -1, "selected": false, "text": "<p>you have to modify the code a little bit in the Deadlock Class </p>\n\n<pre>\n Deadlock() {\n Therad t = new Thread(this); // modified\n t.start();\n System.out.println(); //any instruction to delay\n a.methodA(b);\n}\n</pre>\n\n<p>Also the above code will not always cause a dead lock, only some times it may happen.</p>\n" }, { "answer_id": 8437590, "author": "Jeach", "author_id": 88252, "author_profile": "https://Stackoverflow.com/users/88252", "pm_score": 3, "selected": false, "text": "<p>Java can detect deadlocks (although not at run-time, it can still diagnose and report it). </p>\n\n<p>For example, when using a slightly modified version of 'Saurabh M. Chande' code bellow (changed it to Java and added some timing to guarantee a lock on each run). Once you run it and it deadlocks, if you type:</p>\n\n<pre><code>kill -3 PID # where 'PID' is the Linux process ID\n</code></pre>\n\n<p>It will generate a stack dump, which will include the following information:</p>\n\n<pre><code>Found one Java-level deadlock:\n=============================\n\"Thread-0\":\n waiting to lock monitor 0x08081670 (object 0x7f61ddb8, a Deadlock$A),\n which is held by \"main\"\n\"main\":\n waiting to lock monitor 0x080809f0 (object 0x7f61f3b0, a Deadlock$B),\n which is held by \"Thread-0\"\n</code></pre>\n" }, { "answer_id": 46292209, "author": "Amol Fasale", "author_id": 1976457, "author_profile": "https://Stackoverflow.com/users/1976457", "pm_score": 0, "selected": false, "text": "<p>Java 5 introduced ThreadMXBean - an interface that provides various monitoring methods for threads. ... The difference is that findDeadlockedThreads can also detect deadlocks caused by owner locks (java.util.concurrent), while findMonitorDeadlockedThreads can only detect monitor locks (i.e. synchronized blocks)</p>\n\n<p>Or you can detect it programatically, refer this <a href=\"https://dzone.com/articles/how-detect-java-deadlocks\" rel=\"nofollow noreferrer\">https://dzone.com/articles/how-detect-java-deadlocks</a></p>\n" }, { "answer_id": 62519467, "author": "Manas", "author_id": 6812618, "author_profile": "https://Stackoverflow.com/users/6812618", "pm_score": 2, "selected": false, "text": "<p>Java 1.8 onwards, you can easily find if your program has a deadlock by using <code>jcmd</code> command on your terminal.</p>\n<ol>\n<li>Run <code>jcmd</code> on your terminal: It lists all the programs (PID and name) which are using Java.</li>\n<li>Now, run <code>jcmd &lt;PID&gt; Thread.print</code>: This will print the thread dump on your console and will also print if your program has a deadlock.</li>\n</ol>\n<p>You can analyse your Java program with more <code>jcmd</code> options listed by command <code>jcmd &lt;PID&gt; help</code></p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/217113", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26379/" ]
Long time ago, I saved a sentence from a Java reference book: *"Java has no mechanism to handle deadlock. it won't even know deadlock occurred." (Head First Java 2nd Edition, p.516)* So, what is about it? Is there a way to catch deadlock case in Java? I mean, is there a way that our code understands a deadlock case occurred?
Since JDK 1.5 there are very useful methods in the `java.lang.management` package to find and inspect deadlocks that occurs. See the `findMonitorDeadlockedThreads()` and `findDeadlockedThreads()` method of the `ThreadMXBean` class. A possible way to use this is to have a separate watchdog thread (or periodic task) that does this. Sample code: ``` ThreadMXBean tmx = ManagementFactory.getThreadMXBean(); long[] ids = tmx.findDeadlockedThreads(); if (ids != null) { ThreadInfo[] infos = tmx.getThreadInfo(ids, true, true); System.out.println("The following threads are deadlocked:"); for (ThreadInfo ti : infos) { System.out.println(ti); } } ```
217,132
<p>So I have an Access application, and I'd like some forms to be maximised when they are opened, and others to be medium-sized when they are opened. However, if I try something like this:</p> <pre><code>Private Sub Form_Activate() DoCmd.Maximize End Sub </code></pre> <p>or</p> <pre><code>Private Sub Form_Activate() DoCmd.Restore End Sub </code></pre> <p>it has the effect of maximizing or restoring every open window, which isn't what I'm looking for.</p> <p>Is there any way around this?</p> <p>I'm using Access 2003.</p>
[ { "answer_id": 217137, "author": "tzot", "author_id": 6899, "author_profile": "https://Stackoverflow.com/users/6899", "pm_score": 2, "selected": false, "text": "<p>Access is an MDI (Multiple Document Interface) application, and this is how they work: either all sub-windows are maximized, or none.</p>\n\n<p>What you need to do, is find a way to discover the dimensions of the Access application window, and then programmatically set the form's .InsideWidth and .InsideHeight properties. The <code>Application</code> object has a <code>hwndAccessApp</code> that probably can be used with some Windows API call to find out its width and height.</p>\n\n<h3>addendum</h3>\n\n<p>Thanks to <a href=\"https://stackoverflow.com/questions/217132/controlling-size-of-forms-in-access#217772\">Philippe Grondier</a> for finding a relevant code sample, the general idea from the <a href=\"https://www.utteraccess.com/forum/setting-form-height-width-t1439577.html\" rel=\"nofollow noreferrer\">code sample</a> is:</p>\n\n<ul>\n<li>declare the following Win32 API elements:\n\n<ul>\n<li><code>struct Rect</code> (<code>Type Rect…</code> in VBA)</li>\n<li><code>const SW_SHOWNORMAL = 1</code> (for ShowWindow)</li>\n<li><code>GetParent</code> (given a hwnd, get its parent's hwnd)</li>\n<li><code>GetClientRect</code> (retrieve position and size from a hwnd)</li>\n<li><code>IsZoomed</code> (boolean; true if window is maximized)</li>\n<li><code>ShowWindow</code> (change the state of a window)</li>\n<li><code>MoveWindow</code> (to change the position and size of a window)</li>\n</ul></li>\n<li>if your form is maximized (<code>IsZoomed(frm.hWnd) = True</code>), then restore it (<code>ShowWindow frm.hWnd, SW_SHOWNORMAL</code>)</li>\n<li>get the MDI clients area from your form's hWnd (<code>GetClientRect GetParent(frm.hWnd, rect)</code>)</li>\n<li>use the rect data to change the position and size of your window (<code>MoveWindow frm.hWnd, 0, 0, rect.x2-rect.x1, rect.y2-rect.y1</code>)</li>\n</ul>\n\n<p>(The above is basically the explanation of the code sample; I didn't copy-paste the code because I wasn't sure if the author allowed it).</p>\n" }, { "answer_id": 217144, "author": "Fionnuala", "author_id": 2548, "author_profile": "https://Stackoverflow.com/users/2548", "pm_score": 0, "selected": false, "text": "<p>You can use MoveSize:</p>\n\n<pre><code>DoCmd.MoveSize 100,100\n</code></pre>\n\n<p>Further information: <a href=\"http://msdn.microsoft.com/en-us/library/aa141514(office.10).aspx\" rel=\"nofollow noreferrer\">http://msdn.microsoft.com/en-us/library/aa141514(office.10).aspx</a></p>\n" }, { "answer_id": 217772, "author": "Philippe Grondier", "author_id": 11436, "author_profile": "https://Stackoverflow.com/users/11436", "pm_score": 3, "selected": true, "text": "<p><a href=\"https://stackoverflow.com/questions/217132/controlling-size-of-forms-in-access#217137\">ΤΖΩΤΖΙΟΥ</a> is 100% right when saying that either all are maximised, or none. If you really want to manage this issue, you'll have to read a little bit <a href=\"http://www.utteraccess.com/forums/printthread.php?Cat=&amp;Board=84&amp;main=642287&amp;type=thread\" rel=\"nofollow noreferrer\"><strong>here</strong></a> (look at the code proposed and the way to call it), understand what is done, and eventually build your own solution depending on your needs. </p>\n" }, { "answer_id": 218358, "author": "Patrick Cuff", "author_id": 7903, "author_profile": "https://Stackoverflow.com/users/7903", "pm_score": 0, "selected": false, "text": "<p>There are a couple of options here: <a href=\"http://www.jamiessoftware.tk/articles/resolution.html\" rel=\"nofollow noreferrer\">http://www.jamiessoftware.tk/articles/resolution.html</a></p>\n\n<p>I used ADHResize in the past and it got the job done.</p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/217132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
So I have an Access application, and I'd like some forms to be maximised when they are opened, and others to be medium-sized when they are opened. However, if I try something like this: ``` Private Sub Form_Activate() DoCmd.Maximize End Sub ``` or ``` Private Sub Form_Activate() DoCmd.Restore End Sub ``` it has the effect of maximizing or restoring every open window, which isn't what I'm looking for. Is there any way around this? I'm using Access 2003.
[ΤΖΩΤΖΙΟΥ](https://stackoverflow.com/questions/217132/controlling-size-of-forms-in-access#217137) is 100% right when saying that either all are maximised, or none. If you really want to manage this issue, you'll have to read a little bit [**here**](http://www.utteraccess.com/forums/printthread.php?Cat=&Board=84&main=642287&type=thread) (look at the code proposed and the way to call it), understand what is done, and eventually build your own solution depending on your needs.
217,149
<p>In programming we face various situations where we are required to make use of intermediate STL containers as the following example depicts:</p> <pre><code>while(true) { set &lt; int &gt; tempSet; for (int i = 0; i &lt; n; i ++) { if (m.size() == min &amp;&amp; m.size() &lt;= max) { tempSet.insert(i); } } //Some condition testing code } </code></pre> <p>Or</p> <pre><code>set &lt; int &gt; tempSet; while(true) { for (int i = 0; i &lt; n; i ++) { if (m.size() == min &amp;&amp; m.size() &lt;= max) { tempSet.insert(i); } } tempSet.clear(); //Some condition testing code } </code></pre> <p>Which approach is better in terms of time and space complexity considering the present state of C++ compliers?</p>
[ { "answer_id": 217153, "author": "Head Geek", "author_id": 12193, "author_profile": "https://Stackoverflow.com/users/12193", "pm_score": 2, "selected": false, "text": "<p>The second may be slightly better time-wise, but the difference will be extremely minimal -- the code still has to go through and release each of the items in the set, regardless of whether it's re-creating it or clearing it.</p>\n\n<p>(Space-wise they'll be identical.)</p>\n" }, { "answer_id": 217155, "author": "EvilTeach", "author_id": 7734, "author_profile": "https://Stackoverflow.com/users/7734", "pm_score": 0, "selected": false, "text": "<p>As a general rule, there is a memory allocation cost associated with loading data into a container. It is far better to avoid paying that cost many times, by reusing a container. If you actually know how many items, or can make a good guess, you should preallocate space in the container up front.</p>\n\n<p>It is particularly noticeable if you are inserting objects into the container, because you can end up paying lots of extra construction/destruction costs, as the container realizes that it is too small, reallocates memory, and copy constructs new objects into the new memory based on the existing objects.</p>\n\n<p>Always preallocate and reuse. It saves time and memory.</p>\n" }, { "answer_id": 217156, "author": "hazzen", "author_id": 5066, "author_profile": "https://Stackoverflow.com/users/5066", "pm_score": 2, "selected": false, "text": "<p>If this is a question of <code>set/map/list</code>, it won't make any difference. If it is a question of <code>vector/hash_set/hash_map/string</code>, the second will either be faster or the same speed. Of course, this difference in speed will only be noticeable if you are doing a very large number of operations (10,000 ints pushed into a <code>vector</code> 10,000 times was about twice as fast - 3 seconds and some change vs. 7 seconds.). </p>\n\n<p>If you are doing something like storing a <code>struct/class</code> in your data structure instead of a pointer to one, this difference will be even greater because on each resize, you have to copy all of the elements.</p>\n\n<p>Again, in almost every case, it won't matter - and in the cases where it does matter, it will show up if you are optimizing, and you care about every bit of performance.</p>\n" }, { "answer_id": 217158, "author": "C. K. Young", "author_id": 13, "author_profile": "https://Stackoverflow.com/users/13", "pm_score": 3, "selected": false, "text": "<p>I say the first one is more bug-proof. You're not going to have to remember to clear it (it'll just go out of scope and be done). :-)</p>\n\n<p>Performance-wise there isn't much of a difference, but you should nevertheless measure both cases and see for yourself.</p>\n" }, { "answer_id": 217163, "author": "Jeff Linahan", "author_id": 2222, "author_profile": "https://Stackoverflow.com/users/2222", "pm_score": 0, "selected": false, "text": "<p>There is very little difference, although your second one avoids calling the constructor and destructor multiple times. On the other hand your first one is one line shorter and guarantees that the container is not visible outside the scope of the loop.</p>\n" }, { "answer_id": 217174, "author": "ejgottl", "author_id": 9808, "author_profile": "https://Stackoverflow.com/users/9808", "pm_score": 4, "selected": false, "text": "<p>The first version is correct. It is simpler in almost every way. Easier to write, easier to read, easier to understand, easier to maintain, etc....</p>\n\n<p>The second version <em>may</em> be faster, but then again it may not. You would need to show that it had a significant advantage before using it. In most non-trivial cases I would guess that there would not be a measurable performance difference between the two.</p>\n\n<p>Sometimes in embedded programming it is useful to avoid putting things on the stack; in that case the second version would be correct.</p>\n\n<p>Use the first version by default; use the second only if you can give a good reason for doing so (if the reason is performance, then you should have evidence that the benefit is significant).</p>\n" }, { "answer_id": 217175, "author": "Adam Pierce", "author_id": 5324, "author_profile": "https://Stackoverflow.com/users/5324", "pm_score": 1, "selected": false, "text": "<p>There will be very little performance difference between the two. You should make your decision based on code readability and robustness.</p>\n\n<p>I think the first example is more readable and safer - what happens in six months time when you add a condition to the loop, perhaps with a <strong>continue</strong> in there somewhere - in the second example, it will bypass the clear() and you will have a bug.</p>\n" }, { "answer_id": 217183, "author": "ypnos", "author_id": 21974, "author_profile": "https://Stackoverflow.com/users/21974", "pm_score": 1, "selected": false, "text": "<p>You are putting your set on the stack, therefor allocation cost is almost zero!</p>\n" }, { "answer_id": 217623, "author": "Paul Nathan", "author_id": 26227, "author_profile": "https://Stackoverflow.com/users/26227", "pm_score": -1, "selected": false, "text": "<p>I think you can preallocate a certain number of elements for STL containers, thus having a constant memory allocation cost if you know how many elements will be in the container.</p>\n" }, { "answer_id": 15146742, "author": "rareyesdev", "author_id": 2105988, "author_profile": "https://Stackoverflow.com/users/2105988", "pm_score": 0, "selected": false, "text": "<p>Set is usually implemented as a red black tree. Each node is allocated separately so set don't benefits from reuse. That's why both approach have almost the same performance. Calling \"tempSet.clear()\" should take approximately the same time that destroying the object. The first approach is better because it has the same performance and follows a safer programming style.</p>\n\n<p>You can find a general discussion about other containers here: <a href=\"https://stackoverflow.com/questions/15144279/reusing-a-container-or-declaring-a-new-one-each-time\">Reusing a container o creating a new one</a></p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/217149", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6561/" ]
In programming we face various situations where we are required to make use of intermediate STL containers as the following example depicts: ``` while(true) { set < int > tempSet; for (int i = 0; i < n; i ++) { if (m.size() == min && m.size() <= max) { tempSet.insert(i); } } //Some condition testing code } ``` Or ``` set < int > tempSet; while(true) { for (int i = 0; i < n; i ++) { if (m.size() == min && m.size() <= max) { tempSet.insert(i); } } tempSet.clear(); //Some condition testing code } ``` Which approach is better in terms of time and space complexity considering the present state of C++ compliers?
The first version is correct. It is simpler in almost every way. Easier to write, easier to read, easier to understand, easier to maintain, etc.... The second version *may* be faster, but then again it may not. You would need to show that it had a significant advantage before using it. In most non-trivial cases I would guess that there would not be a measurable performance difference between the two. Sometimes in embedded programming it is useful to avoid putting things on the stack; in that case the second version would be correct. Use the first version by default; use the second only if you can give a good reason for doing so (if the reason is performance, then you should have evidence that the benefit is significant).
217,177
<p>Problem : I have multiple projects checked out in my depot. I also have multiple pending numbered change lists, each change list containing checked out files specific to its project. When I check out a new file, it appears in the default change list instead of in the change list that is relevant to its project and I need to manually move it to the relevant change list. This gets real tedious real quick. </p> <p>Is there any way to automate this process? Sure, a shell script with regular expressions could work, but I want to know if there is any Perforce feature that does this. For example, is there a way to link my project folder to a numbered change list so that a newly checked out file automatically appears in the relevant change list?</p>
[ { "answer_id": 217194, "author": "Michael Burr", "author_id": 12711, "author_profile": "https://Stackoverflow.com/users/12711", "pm_score": 2, "selected": false, "text": "<p>The way I handle this is that each project I'm working on has a separate client workspace configuration.</p>\n\n<p>However, this is a 6 of one, half dozen of the other situation - now I have to manage a bunch of workspaces. The problem I run into is that when I'm working on project A and want to do something quick in project B I have to switch my workspace to do it.</p>\n\n<p>Perforce does have methods to help deal with that problem by using config files that you place in the proper parts of your directory hierarchy. See the <a href=\"http://www.perforce.com/perforce/doc.081/manuals/p4guide/02_config.html#1081890\" rel=\"nofollow noreferrer\">Perforce User's Guide, Chapter 2 - the \"Using config files\" section</a>.</p>\n" }, { "answer_id": 1028439, "author": "raven", "author_id": 4228, "author_profile": "https://Stackoverflow.com/users/4228", "pm_score": 3, "selected": true, "text": "<p>The graphical clients make this pretty easy. Dragging a file(s) or folder(s) onto a change list will check it out for you. Instead of checking them out with the context menu or Ctrl+E, which will put them in the default change list, just drag them onto the appropriate change list and they are automatically checked out where you want them to be.</p>\n\n<p>To do it from the command line, you pass the target change list number to the edit command, via the -c switch. The following command will open the file foo.txt for edit in change list number 1234:</p>\n\n<pre><code>p4 edit -c 1234 foo.txt\n</code></pre>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/217177", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13760/" ]
Problem : I have multiple projects checked out in my depot. I also have multiple pending numbered change lists, each change list containing checked out files specific to its project. When I check out a new file, it appears in the default change list instead of in the change list that is relevant to its project and I need to manually move it to the relevant change list. This gets real tedious real quick. Is there any way to automate this process? Sure, a shell script with regular expressions could work, but I want to know if there is any Perforce feature that does this. For example, is there a way to link my project folder to a numbered change list so that a newly checked out file automatically appears in the relevant change list?
The graphical clients make this pretty easy. Dragging a file(s) or folder(s) onto a change list will check it out for you. Instead of checking them out with the context menu or Ctrl+E, which will put them in the default change list, just drag them onto the appropriate change list and they are automatically checked out where you want them to be. To do it from the command line, you pass the target change list number to the edit command, via the -c switch. The following command will open the file foo.txt for edit in change list number 1234: ``` p4 edit -c 1234 foo.txt ```
217,187
<p>I am new to the world of ASP.NET and SQL server, so please pardon my ignorance ...</p> <p>If I have a data structure in C# (for e.g. let's just say, a vector that stores some strings), is it possible to store the contents of the vector as is in SQL table? I want to do this so that it fast to convert that data back into vector form as fast as possible without having to construct it element by element. Almost like writing binary data to a file and then reading it and copying it to an allocated structure in C.</p> <p>I've created a table on SQL Server 2008 for which a field is defined as VARBINARY(MAX). I thought I'd start with that.</p> <p>Could someone show me an example of how I would go about storing and retrieving a vector of, say, 10 strings, into and from that field? Is this even possible (I can't think of why not)?</p> <p>Thanks!</p>
[ { "answer_id": 217199, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 2, "selected": false, "text": "<p>If you're gonna do that (and I guess it's technically <em>possible</em>), you might just as well use a flat file: there's no point in using a relational database any more.</p>\n" }, { "answer_id": 217202, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 2, "selected": false, "text": "<p>Assuming the objects are marked with <code>[Serializable]</code> or implement <code>ISerializable</code> the the <code>BinaryFormatter</code> class gives a simple way to do this.</p>\n\n<p>If not, you're looking at (non trivial) custom code.</p>\n" }, { "answer_id": 217207, "author": "Jason Jackson", "author_id": 13103, "author_profile": "https://Stackoverflow.com/users/13103", "pm_score": 6, "selected": true, "text": "<p>First, there is the obvious route of simply creating a relational structure and mapping the object to fields in the database.</p>\n\n<p>Second, if you have an object that is serializable, you can store it in SQL server. I have done this on occasion, and have used the Text data type in SQL Server to store the XML. </p>\n\n<p><strong><em>Opinion: I prefer to store serialized objects as XML instead of binary data.</em></strong> Why? Because you can actually read what is in there (for debugging), and in SQL Server you can use XQuery to select data from the serialized object. From my experience, the performance gain of using binary data will not be worth it compared to having data that is easier to debug and can be used in a psuedo-relational fashion. Take a look at <a href=\"http://msdn.microsoft.com/en-us/library/ms345122(SQL.90).aspx\" rel=\"noreferrer\">SQL Server's XQuery capabilities</a>. Even if you don't plan on using it right away, there is no reason to put yourself in a corner.</p>\n\n<p>You might look at some examples using the <a href=\"http://msdn.microsoft.com/en-us/library/system.runtime.serialization.netdatacontractserializer.aspx\" rel=\"noreferrer\">NetDataContractSerializer</a>.</p>\n\n<p>I believe what you call a vector is a List&lt;> in C#. Take a look in System.Collections.Generic. You can use the NetDataContractSerializer to serialize a List of 3 strings like:</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\nusing System.Text;\nusing System.Runtime.Serialization;\nusing System.IO;\n\nnamespace SerializeThingy\n{\n class Program\n {\n static void Main(string[] args)\n {\n List&lt;string&gt; myList = new List&lt;string&gt;();\n myList.Add(\"One\");\n myList.Add(\"Two\");\n myList.Add(\"Three\");\n NetDataContractSerializer serializer = new NetDataContractSerializer();\n MemoryStream stream = new MemoryStream();\n serializer.Serialize(stream, myList);\n stream.Position = 0;\n Console.WriteLine(ASCIIEncoding.ASCII.GetString(stream.ToArray()));\n List&lt;string&gt; myList2 = (List&lt;string&gt;)serializer.Deserialize(stream);\n Console.WriteLine(myList2[0]);\n Console.ReadKey();\n }\n }\n}\n</code></pre>\n\n<p>This example just serializes a list, outputs the serialization to the console, and then proves it was hydrated correctly on the flip side. I think you can see that from here you could either dump the memory stream into a string and write that to the database, or use another stream type than a memory stream to do it.</p>\n\n<p>Remember to reference System.Runtime.Serialization to get access to the NetDataContractSerializer.</p>\n" }, { "answer_id": 217211, "author": "Vyrotek", "author_id": 10941, "author_profile": "https://Stackoverflow.com/users/10941", "pm_score": 3, "selected": false, "text": "<pre><code>[Serializable]\npublic struct Vector3\n{\n public double x, y, z;\n}\n\nclass Program\n{\n static void Main(string[] args)\n {\n Vector3 vector = new Vector3();\n vector.x = 1;\n vector.y = 2;\n vector.z = 3;\n\n MemoryStream memoryStream = new MemoryStream();\n BinaryFormatter binaryFormatter = new BinaryFormatter();\n binaryFormatter.Serialize(memoryStream, vector);\n string str = System.Convert.ToBase64String(memoryStream.ToArray());\n\n //Store str into the database\n }\n}\n</code></pre>\n" }, { "answer_id": 217224, "author": "Ash", "author_id": 5023, "author_profile": "https://Stackoverflow.com/users/5023", "pm_score": 2, "selected": false, "text": "<p>Here's another more general approach for generic lists. Note, the actual type stored in the list must also be serializable</p>\n\n<pre><code>using System.Runtime.Serialization.Formatters.Binary;\nusing System.IO;\nusing System.Data.SqlClient;\nusing System.Runtime.Serialization;\n\npublic byte[] SerializeList&lt;T&gt;(List&lt;T&gt; list)\n{\n\n MemoryStream ms = new MemoryStream();\n\n BinaryFormatter bf = new BinaryFormatter();\n\n bf.Serialize(ms, list);\n\n ms.Position = 0;\n\n byte[] serializedList = new byte[ms.Length];\n\n ms.Read(serializedList, 0, (int)ms.Length);\n\n ms.Close();\n\n return serializedList; \n\n} \n\npublic List&lt;T&gt; DeserializeList&lt;T&gt;(byte[] data)\n{\n try\n {\n MemoryStream ms = new MemoryStream();\n\n ms.Write(data, 0, data.Length);\n\n ms.Position = 0;\n\n BinaryFormatter bf = new BinaryFormatter();\n\n List&lt;T&gt; list = bf.Deserialize(ms) as List&lt;T&gt;;\n\n return list;\n }\n catch (SerializationException ex)\n {\n // Handle deserialization problems here.\n Debug.WriteLine(ex.ToString());\n\n return null;\n }\n\n}\n</code></pre>\n\n<p>Then in client code:</p>\n\n<pre><code>List&lt;string&gt; stringList = new List&lt;string&gt;() { \"January\", \"February\", \"March\" };\n\nbyte[] data = SerializeList&lt;string&gt;(stringList);\n</code></pre>\n\n<p>One basic way of storing/retrieving this array of bytes could be to use simple SQLClient objects:</p>\n\n<pre><code>SqlParameter param = new SqlParameter(\"columnName\", SqlDbType.Binary, data.Length);\nparam.Value = data; \n\netc...\n</code></pre>\n" }, { "answer_id": 326943, "author": "jle", "author_id": 41713, "author_profile": "https://Stackoverflow.com/users/41713", "pm_score": 0, "selected": false, "text": "<p>I have more experience with relational databases than c#, but binary serialization is an acceptable way to go, as it allows the entire object's state to be saved into the database. XML serialization is pretty much the same, although generic types are not allowed.</p>\n" }, { "answer_id": 8575757, "author": "Chuck", "author_id": 1107871, "author_profile": "https://Stackoverflow.com/users/1107871", "pm_score": 1, "selected": false, "text": "<p>There are reasons to be flexible. Rules, or guidelines, for database structure should not be allowed to impede creativity. Given the first thread here, I can see a hybrid approach for storing both serialized and constraining columns as well. Many an application could be vastly improved by keeping ones mind open to possibilities. </p>\n\n<p>Anyway, I appreciated a newbies perspective on the matter. Keeps us all fresh.. </p>\n" } ]
2008/10/19
[ "https://Stackoverflow.com/questions/217187", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25205/" ]
I am new to the world of ASP.NET and SQL server, so please pardon my ignorance ... If I have a data structure in C# (for e.g. let's just say, a vector that stores some strings), is it possible to store the contents of the vector as is in SQL table? I want to do this so that it fast to convert that data back into vector form as fast as possible without having to construct it element by element. Almost like writing binary data to a file and then reading it and copying it to an allocated structure in C. I've created a table on SQL Server 2008 for which a field is defined as VARBINARY(MAX). I thought I'd start with that. Could someone show me an example of how I would go about storing and retrieving a vector of, say, 10 strings, into and from that field? Is this even possible (I can't think of why not)? Thanks!
First, there is the obvious route of simply creating a relational structure and mapping the object to fields in the database. Second, if you have an object that is serializable, you can store it in SQL server. I have done this on occasion, and have used the Text data type in SQL Server to store the XML. ***Opinion: I prefer to store serialized objects as XML instead of binary data.*** Why? Because you can actually read what is in there (for debugging), and in SQL Server you can use XQuery to select data from the serialized object. From my experience, the performance gain of using binary data will not be worth it compared to having data that is easier to debug and can be used in a psuedo-relational fashion. Take a look at [SQL Server's XQuery capabilities](http://msdn.microsoft.com/en-us/library/ms345122(SQL.90).aspx). Even if you don't plan on using it right away, there is no reason to put yourself in a corner. You might look at some examples using the [NetDataContractSerializer](http://msdn.microsoft.com/en-us/library/system.runtime.serialization.netdatacontractserializer.aspx). I believe what you call a vector is a List<> in C#. Take a look in System.Collections.Generic. You can use the NetDataContractSerializer to serialize a List of 3 strings like: ``` using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Runtime.Serialization; using System.IO; namespace SerializeThingy { class Program { static void Main(string[] args) { List<string> myList = new List<string>(); myList.Add("One"); myList.Add("Two"); myList.Add("Three"); NetDataContractSerializer serializer = new NetDataContractSerializer(); MemoryStream stream = new MemoryStream(); serializer.Serialize(stream, myList); stream.Position = 0; Console.WriteLine(ASCIIEncoding.ASCII.GetString(stream.ToArray())); List<string> myList2 = (List<string>)serializer.Deserialize(stream); Console.WriteLine(myList2[0]); Console.ReadKey(); } } } ``` This example just serializes a list, outputs the serialization to the console, and then proves it was hydrated correctly on the flip side. I think you can see that from here you could either dump the memory stream into a string and write that to the database, or use another stream type than a memory stream to do it. Remember to reference System.Runtime.Serialization to get access to the NetDataContractSerializer.
217,213
<p>Is there a way to make <strong>awk</strong> (gawk) ignore or skip missing files? That is, files passed on the command line that no longer exist in the file system (e.g. rapidly appearing/disappearing files under /proc/[1-9]*).</p> <p>By default, a missing file is a fatal error :-(</p> <p>I would like to be able to do the equivalent of something like this:</p> <pre><code>BEGIN { MISSING_FILES_ARE_FATAL = 0 } # &lt;- Wishful thinking! { count++ } END { print count } </code></pre> <p>A wrapper script cannot check that files exist befor awk is run as they may disappear between the time they are checked and awk then tries to open them, i.e., it is a race condition. (It is also a race condition to check-and-then-open within awk, although the timing is tighter)</p>
[ { "answer_id": 217267, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 0, "selected": false, "text": "<p>In the finest of traditions, I will answer your awk question with a Perl program.</p>\n\n<pre><code>#!/usr/bin/perl -w\n\nfor my $file (@ARGV) {\n open my $fh, $file or next;\n while(&lt;$fh&gt;) {\n ...do your thing here...\n }\n}\n</code></pre>\n\n<p>(It's not awk, but it is the only solution without a race condition.)</p>\n" }, { "answer_id": 217897, "author": "Mike G.", "author_id": 18901, "author_profile": "https://Stackoverflow.com/users/18901", "pm_score": 1, "selected": false, "text": "<p>Even sticking a perl or shell wrapper around your awk script, I think there's still going to be a race condition. For example, using ADEpt's otherwise fine shell snippet:</p>\n\n<pre><code>[ -r \"$filename\" ] &amp;&amp; awk -f ... $filename\n</code></pre>\n\n<p>there's nothing preventing the process from going away between the -r and the time awk gets around to trying to open the file...</p>\n\n<p>The only answer I can think of is to use LD_PRELOAD to replace the system open call for awk, so that if the file is missing, a read file descriptor on /dev/null is opened instead.</p>\n\n<p>That might work...</p>\n" }, { "answer_id": 217927, "author": "Zsolt Botykai", "author_id": 11621, "author_profile": "https://Stackoverflow.com/users/11621", "pm_score": 1, "selected": false, "text": "<p>Well you can check with system call on the contents of <code>ARGV</code>, then process them via <code>getline</code>.</p>\n\n<pre><code> if (system(\"test -r \" ARGV[1]) == 0)\n while ( (getline aline &lt; ARGV[1]) &gt;0 )\n # process ARGV[1] via `aline` instead of $0\n</code></pre>\n\n<p>...</p>\n\n<p>Then process ARGV[2], etc\nHTH</p>\n" }, { "answer_id": 223724, "author": "ADEpt", "author_id": 10105, "author_profile": "https://Stackoverflow.com/users/10105", "pm_score": 0, "selected": false, "text": "<p>Oh, sorry. Disregard my previous answer. Here is another suggestion:</p>\n\n<pre><code>cat /proc/[1-9]* 2&gt;/dev/null | awk ....\n</code></pre>\n\n<p>Cat will gobble up all files, missing and existing alike, cat's error will be dumped to oblivion (the missing file is non-fatal error for cat), and the awk wil be able to process the result.</p>\n" }, { "answer_id": 420244, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>It looks to me that a \"MISSING_FILES_ARE_FATAL = 0\" feature will be part of the next gawk release. See the ChangeLog file of the current gawk-stable source code:</p>\n\n<p>--- snip ---</p>\n\n<p>Fri Aug 22 14:43:49 2008 Arnold D. Robbins </p>\n\n<pre><code>* io.c (nextfile): Users Strong In The Ways Of The Source can use\nnon-existant files on the command line without it being a fatal error.\n</code></pre>\n\n<p>--- snip ---</p>\n\n<p><a href=\"http://cvs.savannah.gnu.org/viewvc/gawk-stable/ChangeLog?revision=1.87&amp;root=gawk&amp;view=markup\" rel=\"nofollow noreferrer\">http://cvs.savannah.gnu.org/viewvc/gawk-stable/ChangeLog?revision=1.87&amp;root=gawk&amp;view=markup</a></p>\n\n<p>Hermann</p>\n" }, { "answer_id": 12350657, "author": "Dennis Williamson", "author_id": 26428, "author_profile": "https://Stackoverflow.com/users/26428", "pm_score": 2, "selected": false, "text": "<p>GAWK 4 has <code>BEGINFILE</code> in which you can test for <code>ERRNO</code> and do a <code>nextfile</code> if <code>ERRNO</code> is not empty (indicating that the file couldn't be opened).</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217213", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
Is there a way to make **awk** (gawk) ignore or skip missing files? That is, files passed on the command line that no longer exist in the file system (e.g. rapidly appearing/disappearing files under /proc/[1-9]\*). By default, a missing file is a fatal error :-( I would like to be able to do the equivalent of something like this: ``` BEGIN { MISSING_FILES_ARE_FATAL = 0 } # <- Wishful thinking! { count++ } END { print count } ``` A wrapper script cannot check that files exist befor awk is run as they may disappear between the time they are checked and awk then tries to open them, i.e., it is a race condition. (It is also a race condition to check-and-then-open within awk, although the timing is tighter)
GAWK 4 has `BEGINFILE` in which you can test for `ERRNO` and do a `nextfile` if `ERRNO` is not empty (indicating that the file couldn't be opened).
217,219
<p>I am using the Entity Framework and Linq to Entities. I have created a small database pattern &amp; framework to implement versioning as well as localization. Every entity now consists of two or three tables, (ie Product, ProductBase &amp; ProductLocal). </p> <p>My linq always includes the following boilerplate code:</p> <pre><code>from o in DB.Product from b in o.Base from l in o.Local WHERE o.VersionStatus == (int)VersionStatus.Active &amp;&amp; b.VersionStatus == (int)VersionStatus.Active &amp;&amp; l.VersionStatus == (int)VersionStatus.Active &amp;&amp; l.VersionLanguage == Context.CurrentLanguage select new ProductInstance { Instance = o, Base = b, Local = l } </code></pre> <p>What I would like to accomplish is to turn the above into:</p> <pre><code>(from o in DB.Product from b in o.Base from l in o.Local select new ProductInstance { Instance = o, Base = b, Local = l }).IsActive() </code></pre> <p>Or at worst, something like:</p> <pre><code>from o in DB.Product.Active() from b in o.Base.Active() from l in o.Local.Active() select new ProductInstance { Instance = o, Base = b, Local = l } </code></pre> <p>I have extended the base classes the EDM generates to implement some interfaces that enforce the properties ( IVersionStatus and/or IVersionLanguage ). Is there some way I can walk the expression tree, check if the type in the expression implements that interface, then set the VersionStatus accordingly?</p> <p>I woud love it to be as simple as the first option, just less to write and/or forget. I have seen examples that do it after the fact, after its IEnumerable, but I would rather not pull more from the database than I need to. </p> <p>Thanks for any tips! </p>
[ { "answer_id": 217277, "author": "Paul Mendoza", "author_id": 29277, "author_profile": "https://Stackoverflow.com/users/29277", "pm_score": 0, "selected": false, "text": "<p>You need to use the DataLoadOptions class so that it automatically loads the foreign key relationships you specify on that object. That will make it so that it will automatically get the linked tables that you specify which is really what you're doing.</p>\n\n<p>This page details how to do that and tells more about what I think you're looking for. </p>\n\n<p><a href=\"http://www.crazysalsadancer.com/2008/08/efficient-data-loading-with-linq-using.html\" rel=\"nofollow noreferrer\">http://www.crazysalsadancer.com/2008/08/efficient-data-loading-with-linq-using.html</a></p>\n" }, { "answer_id": 217293, "author": "Ryan M", "author_id": 29466, "author_profile": "https://Stackoverflow.com/users/29466", "pm_score": 0, "selected": false, "text": "<p>I might be wrong, but I don't think <code>DataLoadOptions</code> works with the Entity Framework.</p>\n" }, { "answer_id": 217299, "author": "Scott Wisniewski", "author_id": 1737192, "author_profile": "https://Stackoverflow.com/users/1737192", "pm_score": 2, "selected": false, "text": "<p>Yes.</p>\n\n<p>You can do this by defining an extension method named IsActive on IQueryable.\nThere is a property on IQueryable called \"Expression\" that returns an expression tree representing the chain of LINQ method calls that was generated from your query.</p>\n\n<p>In your case that will look something like this:</p>\n\n<pre><code>DB.Product.SelectMany(o=&gt;o.base, (o, b)=&gt;new{o.b}).SelectMany(item=&gt;o.local, (item, local)=&gt;new {item.o, item.b, item.local}).Select(item=&gt;new ProductInstance { Instance = item.o, Base = item.b, Local=item.Local});\n</code></pre>\n\n<p>The \"DB.Product\" is the item from the first From clause. Each remaining \"SelectMany\" call is an additional from clause. </p>\n\n<p>You can then dig into the expression trees to gather all the from clause elements. look at their types, and then finally generate an expression tree for a where clause.</p>\n\n<p>Your extension method would then return .Where off of it's IQueryable argument using the where clause that you generated.</p>\n\n<p>The resulting Where clause would then be executed on the server with the rest of the query when you try to \"foreach\" over the results.</p>\n\n<p><strong>EDIT:</strong></p>\n\n<p>Please note that if you want this to work with explicit \"Join\" clauses then you will also need to add support for the \"Join\" method in addition to \"SelectMany\".</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29466/" ]
I am using the Entity Framework and Linq to Entities. I have created a small database pattern & framework to implement versioning as well as localization. Every entity now consists of two or three tables, (ie Product, ProductBase & ProductLocal). My linq always includes the following boilerplate code: ``` from o in DB.Product from b in o.Base from l in o.Local WHERE o.VersionStatus == (int)VersionStatus.Active && b.VersionStatus == (int)VersionStatus.Active && l.VersionStatus == (int)VersionStatus.Active && l.VersionLanguage == Context.CurrentLanguage select new ProductInstance { Instance = o, Base = b, Local = l } ``` What I would like to accomplish is to turn the above into: ``` (from o in DB.Product from b in o.Base from l in o.Local select new ProductInstance { Instance = o, Base = b, Local = l }).IsActive() ``` Or at worst, something like: ``` from o in DB.Product.Active() from b in o.Base.Active() from l in o.Local.Active() select new ProductInstance { Instance = o, Base = b, Local = l } ``` I have extended the base classes the EDM generates to implement some interfaces that enforce the properties ( IVersionStatus and/or IVersionLanguage ). Is there some way I can walk the expression tree, check if the type in the expression implements that interface, then set the VersionStatus accordingly? I woud love it to be as simple as the first option, just less to write and/or forget. I have seen examples that do it after the fact, after its IEnumerable, but I would rather not pull more from the database than I need to. Thanks for any tips!
Yes. You can do this by defining an extension method named IsActive on IQueryable. There is a property on IQueryable called "Expression" that returns an expression tree representing the chain of LINQ method calls that was generated from your query. In your case that will look something like this: ``` DB.Product.SelectMany(o=>o.base, (o, b)=>new{o.b}).SelectMany(item=>o.local, (item, local)=>new {item.o, item.b, item.local}).Select(item=>new ProductInstance { Instance = item.o, Base = item.b, Local=item.Local}); ``` The "DB.Product" is the item from the first From clause. Each remaining "SelectMany" call is an additional from clause. You can then dig into the expression trees to gather all the from clause elements. look at their types, and then finally generate an expression tree for a where clause. Your extension method would then return .Where off of it's IQueryable argument using the where clause that you generated. The resulting Where clause would then be executed on the server with the rest of the query when you try to "foreach" over the results. **EDIT:** Please note that if you want this to work with explicit "Join" clauses then you will also need to add support for the "Join" method in addition to "SelectMany".
217,233
<p>I have multiple layers in an application and i find myself having to bubble up events to the GUI layer for doing status bar changes, etc . . I find myself having to write repeated coded where each layer simply subscribes to events from the lower layer and then in the call back simply raise an event up the chain. Is there a more efficient way of doing this?</p>
[ { "answer_id": 217303, "author": "Hapkido", "author_id": 27646, "author_profile": "https://Stackoverflow.com/users/27646", "pm_score": 0, "selected": false, "text": "<p>You can have a central channel that only support events. This channel must be independent so the layer only publish or subscribe to it.</p>\n" }, { "answer_id": 217366, "author": "Matt Hamilton", "author_id": 615, "author_profile": "https://Stackoverflow.com/users/615", "pm_score": 6, "selected": true, "text": "<p>If all you're doing is firing an event handler from another event handler, you can cut out the middle man and hook the event handlers directly in the add/remove blocks for the event.</p>\n\n<p>For example, if you have a UserControl with a \"SaveButtonClick\" event, and all you want to do when is call the event handler when the \"SaveButton\" on your UserControl is clicked, you can do this:</p>\n\n<pre><code>public event EventHandler SaveButtonClick\n{\n add { this.SaveButton.Click += value; }\n remove { this.SaveButton.Click -= value; }\n}\n</code></pre>\n\n<p>Now you don't need any code to fire the SaveButtonClick event - it will automatically be fired when the SaveButton.Click event is raised (ie when someone clicks that button).</p>\n" }, { "answer_id": 217668, "author": "Gishu", "author_id": 1695, "author_profile": "https://Stackoverflow.com/users/1695", "pm_score": 1, "selected": false, "text": "<p>Unless I see a bit more of the design.. it'll be hard to give a good answer.</p>\n\n<p>WPF does bubble events up (automatically) the UI Component/Control tree... this has now been built into the framework. So I guess that's the recommended way :)</p>\n\n<p>The trouble with bypassing the middle man Layer2 is that Layer1 and Layer3 now know each other... are coupled. So its a tradeoff.. if you are okay with the coupling.. eliminate the middle man / invent a specialized component with this responsibility. However if you expect Layer 3 to be hot-swappable (low coupling), I'd say continue bubbling.</p>\n" }, { "answer_id": 221970, "author": "Michael L Perry", "author_id": 7668, "author_profile": "https://Stackoverflow.com/users/7668", "pm_score": 0, "selected": false, "text": "<p>Take a look at <a href=\"http://udpatecontrols.net\" rel=\"nofollow noreferrer\">Update Controls .NET</a>. These controls discover the parts of your data model that they depend upon even through layers of business logic. You don't have to write <em>any</em> code to notify them.</p>\n" }, { "answer_id": 225083, "author": "Bevan", "author_id": 30280, "author_profile": "https://Stackoverflow.com/users/30280", "pm_score": 2, "selected": false, "text": "<p>Have a read of Jeremy Miller's blog \"The Shade Tree Developer\", especially his <a href=\"http://codebetter.com/jeremymiller/2007/07/26/the-build-your-own-cab-series-table-of-contents/\" rel=\"nofollow noreferrer\"><em>Write Your Own CAB</em> series</a> - the command pattern stuff he talks about there is probably what you need.</p>\n" }, { "answer_id": 318689, "author": "Ben", "author_id": 3786, "author_profile": "https://Stackoverflow.com/users/3786", "pm_score": 2, "selected": false, "text": "<p>Peter Rilling has posted a way of simulating Event Bubbling/Broadcasting in winforms.\nIt is simple and effective.</p>\n\n<p><a href=\"http://www.codeproject.com/KB/cs/event_broadcast.aspx\" rel=\"nofollow noreferrer\">http://www.codeproject.com/KB/cs/event_broadcast.aspx\n</a></p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217233", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
I have multiple layers in an application and i find myself having to bubble up events to the GUI layer for doing status bar changes, etc . . I find myself having to write repeated coded where each layer simply subscribes to events from the lower layer and then in the call back simply raise an event up the chain. Is there a more efficient way of doing this?
If all you're doing is firing an event handler from another event handler, you can cut out the middle man and hook the event handlers directly in the add/remove blocks for the event. For example, if you have a UserControl with a "SaveButtonClick" event, and all you want to do when is call the event handler when the "SaveButton" on your UserControl is clicked, you can do this: ``` public event EventHandler SaveButtonClick { add { this.SaveButton.Click += value; } remove { this.SaveButton.Click -= value; } } ``` Now you don't need any code to fire the SaveButtonClick event - it will automatically be fired when the SaveButton.Click event is raised (ie when someone clicks that button).
217,257
<p>I want to sort members by name in the source code. Is there any easy way to do it? </p> <p>I'm using NetBeans, but if there is another editor that can do that, just tell me the name of it.</p>
[ { "answer_id": 217272, "author": "Paul Croarkin", "author_id": 18995, "author_profile": "https://Stackoverflow.com/users/18995", "pm_score": 3, "selected": false, "text": "<p>Eclipse can do it.</p>\n" }, { "answer_id": 217289, "author": "Martin", "author_id": 24364, "author_profile": "https://Stackoverflow.com/users/24364", "pm_score": 2, "selected": false, "text": "<p>As @PaulCroarkin said - use eclipse, Or you can use <a href=\"http://jalopy.sourceforge.net/\" rel=\"nofollow noreferrer\">Jalopy</a> as part of your build which will do all manner of magical formatting to your source files in the process (whether this is a good thing or not is open to debate)</p>\n" }, { "answer_id": 223461, "author": "James Schek", "author_id": 17871, "author_profile": "https://Stackoverflow.com/users/17871", "pm_score": 0, "selected": false, "text": "<p>As of 6.0/6.1, this feature isn't available in the built-in tools. The \"Navigator\" view is intended to give you an ordered index of your members. To see the Navigator, go to Window->Navigating->Navigator or hit Control-F7.</p>\n\n<p>Consider submitting a <a href=\"http://www.netbeans.org/community/issues.html\" rel=\"nofollow noreferrer\">feature enhancement to Netbeans</a>.</p>\n" }, { "answer_id": 228489, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "<p>Netbeans lets you sort the methods in the Navigator. Personally, I never saw the point in sorting methods in the code. When possible I like to keep methods together that work together. For example, the getter() and setter(). Incremental search or being able to control-click on a method to navigate to the declaration is much more useful, IMHO. </p>\n" }, { "answer_id": 12287084, "author": "Gili", "author_id": 14731, "author_profile": "https://Stackoverflow.com/users/14731", "pm_score": 3, "selected": false, "text": "<p>This is implemented in Netbeans 7.3: <a href=\"http://netbeans.org/bugzilla/show_bug.cgi?id=212528\" rel=\"noreferrer\">http://netbeans.org/bugzilla/show_bug.cgi?id=212528</a></p>\n" }, { "answer_id": 26745787, "author": "Greg", "author_id": 4216292, "author_profile": "https://Stackoverflow.com/users/4216292", "pm_score": -1, "selected": false, "text": "<p>Here is the easy way to do it in NetBeans:</p>\n\n<ol>\n<li>Go to the Tools tab and chose Options.\nThe option Window should appear.</li>\n<li>Click on Editor and chose the Formatting Tab. </li>\n<li>Select Ordering for Category. \nOrdering is the last element from the drop down Category list.</li>\n<li>Uncheck the Sort Members By Visibility field.\nAt this point only the \"Sort Members in Groups Alphabetically\" should be checked.</li>\n<li>Click Apply and exit the Option window.\nNow you globally set to sort members alphabetically. </li>\n<li>Open or Select the source file you want to sort the members.</li>\n<li>Click the Source Tab (upper right corner) and chose Organize Members.</li>\n</ol>\n\n<p>And that is it. Your source file should have the members sorted alphabetically.</p>\n" }, { "answer_id": 27170560, "author": "Johnny Baloney", "author_id": 779449, "author_profile": "https://Stackoverflow.com/users/779449", "pm_score": 6, "selected": true, "text": "<p>In Netbeans 8.0.1:</p>\n\n<pre><code>Tools -&gt; Options -&gt; Editor -&gt; Formatting -&gt; Category: Ordering\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/7BxRT.png\" alt=\"Netbeans member sorting\"></p>\n\n<p>Then:</p>\n\n<pre><code>Source -&gt; Organize Members\n</code></pre>\n\n<p><img src=\"https://i.stack.imgur.com/MO7Dc.png\" alt=\"Netbeans member sorting\"></p>\n" }, { "answer_id": 39137469, "author": "Ted Feng", "author_id": 622496, "author_profile": "https://Stackoverflow.com/users/622496", "pm_score": 0, "selected": false, "text": "<p>For C/C++ mode, right click on the method name inside the Navigator window, then there's choice of \"Sort by Name\" or \"Sort by Source\", choose the one you like :)</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217257", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8418/" ]
I want to sort members by name in the source code. Is there any easy way to do it? I'm using NetBeans, but if there is another editor that can do that, just tell me the name of it.
In Netbeans 8.0.1: ``` Tools -> Options -> Editor -> Formatting -> Category: Ordering ``` ![Netbeans member sorting](https://i.stack.imgur.com/7BxRT.png) Then: ``` Source -> Organize Members ``` ![Netbeans member sorting](https://i.stack.imgur.com/MO7Dc.png)
217,259
<p>Often, programmers write code that generates other code.</p> <p>(The technical term is <a href="http://en.wikipedia.org/wiki/Metaprogramming" rel="nofollow noreferrer" title="Wikipedia article on metaprogramming">metaprogramming</a>, but it is more common than merely cross-compilers; think about every PHP web-page that generates HTML or every XSLT file.)</p> <p>One area I find challenging is coming up with techniques to ensure that <em>both</em> the hand-written source file, and the computer-generated object file are clearly indented to aid debugging. The two goals often seem to be competing.</p> <p>I find this particularly challenging in the PHP/HTML combination. I think that is because:</p> <ul> <li>there is sometimes more of the HTML code in the source file than the generating PHP</li> <li>HTML files tend to be longer than, say, SQL statements, and need better indenting</li> <li>HTML has space-sensitive features (e.g. between tags)</li> <li>the result is more publicly visible HTML than SQL statements, so there is more pressure to do a reasonable job.</li> </ul> <p>What techniques do you use to address this?</p> <p><hr/> Edit: I accept that there are at least three arguments to not bothering to generate pretty HTML code:</p> <ul> <li>Complexity of generating code is increased.</li> <li>Makes no difference to rendering by browser; developers can use Firebug or similar to view it nicely.</li> <li>Minor performance hit - increased download time for whitespace characters.</li> </ul> <p>I have certainly sometimes generated code without thought to the indenting (especially SQL).</p> <p>However, there are a few arguments pushing the other way:</p> <ul> <li>I find, in practice, that I <em>do</em> frequently read generated code - having extra steps to access it is inconvenient.</li> <li>HTML has some space-sensitivity issues that bite occasionally. </li> </ul> <p>For example, consider the code:</p> <pre><code>&lt;div class="foo"&gt; &lt;?php $fooHeader(); $fooBody(); $fooFooter(); ?&gt; &lt;/div&gt; </code></pre> <p>It is clearer than the following code:</p> <pre><code>&lt;div class="foo"&gt;&lt;?php $fooHeader(); $fooBody(); $fooFooter(); ?&gt;&lt;/div&gt; </code></pre> <p>However, it is also has different rendering because of the whitespace included in the HTML.</p>
[ { "answer_id": 217264, "author": "Oddthinking", "author_id": 8014, "author_profile": "https://Stackoverflow.com/users/8014", "pm_score": 2, "selected": false, "text": "<p>A technique that I use when the generating code dominates over the generated code is to pass an indent parameter around.</p>\n\n<p>e.g., in Python, generating more Python.</p>\n\n<pre><code>def generateWhileLoop(condition, block, indentPrefix = \"\"):\n print indentPrefix + \"while \" + condition + \":\"\n generateBlock(block, indentPrefix + \" \")\n</code></pre>\n\n<p>Alternatively, depending on my mood:</p>\n\n<pre><code>def generateWhileLoop(condition, block, indentLevel = 0):\n print \" \" * (indentLevel * spacesPerIndent) + \"while \" + condition + \":\"\n generateBlock(block, indentLevel + 1)\n</code></pre>\n\n<p>Note the assumption that <code>condition</code> is a short piece of text that fits on the same line, while <code>block</code> is on a separate indented line. If this code can't be sure of whether the sub-items need to be indented, this method starts to fall down.</p>\n\n<p>Also, this technique isn't nearly as useful for sprinkling relatively small amounts of PHP into HTML.</p>\n\n<p>[Edit to clarify: I wrote the question and also this answer. I wanted to seed the answers with one technique that I do use and is sometimes useful, but this technique fails me for typical PHP coding, so I am looking for other ideas like it.]</p>\n" }, { "answer_id": 217274, "author": "Greg Hewgill", "author_id": 893, "author_profile": "https://Stackoverflow.com/users/893", "pm_score": 3, "selected": true, "text": "<p>In the more general case, I have written XSLT code that generates C++ database interface code. Although at first I tried to output correctly indented code from the XSLT, this quickly became untenable. My solution was to completely ignore formatting in the XSLT output, and then run the resulting very long line of code through <a href=\"http://www.gnu.org/software/indent/\" rel=\"nofollow noreferrer\">GNU indent</a>. This produced a reasonably formatted C++ source file suitable for debugging.</p>\n\n<p>I can imagine the problem gets a lot more prickly when dealing with combined source such as HTML and PHP.</p>\n" }, { "answer_id": 217278, "author": "Watson Ladd", "author_id": 29025, "author_profile": "https://Stackoverflow.com/users/29025", "pm_score": 2, "selected": false, "text": "<p>Generate an AST then traverse it inorder and emit source code that is properly formatted.</p>\n" }, { "answer_id": 217283, "author": "Schwern", "author_id": 14660, "author_profile": "https://Stackoverflow.com/users/14660", "pm_score": 1, "selected": false, "text": "<p>I agree with oddthinking's answer.</p>\n\n<p>Sometimes it's best to solve the problem by inverting it. If you find yourself generating a whole lot of text, consider if its easier to write the text as a template with small bits of intelligent generation code. Or if you can break the problem down into a series of small templates which you assemble, and then indent each template as a whole.</p>\n" }, { "answer_id": 217296, "author": "Hannes Landeholm", "author_id": 29442, "author_profile": "https://Stackoverflow.com/users/29442", "pm_score": 1, "selected": false, "text": "<p>Making websites in PHP, I find mixing of HTML and function specific PHP problematic, it limits the overview and makes debugging harder. A solution to avoid mixing in this case is using template driven content, <a href=\"http://www.smarty.net/manual/en/\" rel=\"nofollow noreferrer\">see Smarty</a> for example. Except better intendation, templating of content is useful for other things like, for example, faster patching. If a customer requires a change in the layout, that particular layout issue can be quickly found and fixed, without bothering with the functional PHP code generating the data (and the other way around).</p>\n" }, { "answer_id": 217297, "author": "gregmac", "author_id": 7913, "author_profile": "https://Stackoverflow.com/users/7913", "pm_score": 0, "selected": false, "text": "<p>Specifically on HTML generation - why does it matter? </p>\n\n<p>You're spending a heck of a lot of time passing around indenting parameters, and trying to figure out how deeply nested you are etc.. Aside from being a general waste of time (since there is no difference in the final rendered output), how do you maintain all this stuff as you add other HTML markup and wrap pages in a div etc?</p>\n\n<p>Anyway, install <a href=\"http://www.getfirebug.com\" rel=\"nofollow noreferrer\">Firebug</a> (and <a href=\"http://www.microsoft.com/downloads/details.aspx?familyid=e59c3964-672d-4511-bb3e-2d5e1db91038&amp;displaylang=en\" rel=\"nofollow noreferrer\">IE developer toolbar</a> for testing IE afterwards) and they both show you the HTML in the nested format, AND you can just click on the page element to directly view the markup - WAY more efficient than looking at raw source HTML output. </p>\n" }, { "answer_id": 217339, "author": "Jack", "author_id": 15052, "author_profile": "https://Stackoverflow.com/users/15052", "pm_score": 2, "selected": false, "text": "<p>I have found that ignoring indenting during generation is best. I have written a generic 'code formatting' engine that post processed all code outputted. This way, I can define indenting rules and code syntax rules seperately from the generator. There are clear benefits to this separation.</p>\n" }, { "answer_id": 218270, "author": "Colonel Sponsz", "author_id": 11651, "author_profile": "https://Stackoverflow.com/users/11651", "pm_score": 0, "selected": false, "text": "<p>I the PHP/HTML situation I try to keep each code fragment consistently indented in its source code. This keeps the code readable where it really matters and <em>usually</em> has the side effect of producing HTML output that is readable. As others have said, firebug takes care of the rest.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217259", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8014/" ]
Often, programmers write code that generates other code. (The technical term is [metaprogramming](http://en.wikipedia.org/wiki/Metaprogramming "Wikipedia article on metaprogramming"), but it is more common than merely cross-compilers; think about every PHP web-page that generates HTML or every XSLT file.) One area I find challenging is coming up with techniques to ensure that *both* the hand-written source file, and the computer-generated object file are clearly indented to aid debugging. The two goals often seem to be competing. I find this particularly challenging in the PHP/HTML combination. I think that is because: * there is sometimes more of the HTML code in the source file than the generating PHP * HTML files tend to be longer than, say, SQL statements, and need better indenting * HTML has space-sensitive features (e.g. between tags) * the result is more publicly visible HTML than SQL statements, so there is more pressure to do a reasonable job. What techniques do you use to address this? --- Edit: I accept that there are at least three arguments to not bothering to generate pretty HTML code: * Complexity of generating code is increased. * Makes no difference to rendering by browser; developers can use Firebug or similar to view it nicely. * Minor performance hit - increased download time for whitespace characters. I have certainly sometimes generated code without thought to the indenting (especially SQL). However, there are a few arguments pushing the other way: * I find, in practice, that I *do* frequently read generated code - having extra steps to access it is inconvenient. * HTML has some space-sensitivity issues that bite occasionally. For example, consider the code: ``` <div class="foo"> <?php $fooHeader(); $fooBody(); $fooFooter(); ?> </div> ``` It is clearer than the following code: ``` <div class="foo"><?php $fooHeader(); $fooBody(); $fooFooter(); ?></div> ``` However, it is also has different rendering because of the whitespace included in the HTML.
In the more general case, I have written XSLT code that generates C++ database interface code. Although at first I tried to output correctly indented code from the XSLT, this quickly became untenable. My solution was to completely ignore formatting in the XSLT output, and then run the resulting very long line of code through [GNU indent](http://www.gnu.org/software/indent/). This produced a reasonably formatted C++ source file suitable for debugging. I can imagine the problem gets a lot more prickly when dealing with combined source such as HTML and PHP.
217,266
<p>If the C++ runtime msvcr80.dll is missing from a compiled library, is there any way to determine which version was used to create the library or to get it to run on a later version of msvcr80.dll?</p>
[ { "answer_id": 217279, "author": "David Segonds", "author_id": 13673, "author_profile": "https://Stackoverflow.com/users/13673", "pm_score": 3, "selected": false, "text": "<p><a href=\"http://www.dependencywalker.com/\" rel=\"noreferrer\">Dependency Walker</a> will help you answer this question.</p>\n" }, { "answer_id": 217369, "author": "bk1e", "author_id": 8090, "author_profile": "https://Stackoverflow.com/users/8090", "pm_score": 5, "selected": true, "text": "<p>The VC80 SP1 CRT redistributable package will install both the RTM and SP1 versions of the C runtime into <code>%SystemRoot%\\WinSxS</code> (assuming you're using Windows XP or Vista; Windows 2000 doesn't support side-by-side assemblies). If you have VC8 installed, the CRT redistributable package is in <code>%ProgramFiles%\\Microsoft Visual Studio 8\\VC\\redist</code>. If you don't have VC8 installed, I think you can download the CRT redistributable package from Microsoft.com. </p>\n\n<p>Also, to find out exactly what CRT version (e.g. RTM vs. SP1) is needed by a binary that was built with VC8 or VC9, you can extract the manifest:</p>\n\n<pre><code>mt.exe -inputresource:mydll.dll;#1 -out:mydll.dll.manifest\n</code></pre>\n\n<p>Look for something like this:</p>\n\n<pre><code>&lt;assemblyIdentity type=\"win32\" name=\"Microsoft.VC90.CRT\" version=\"9.0.21022.8\" processorArchitecture=\"x86\" publicKeyToken=\"1fc8b3b9a1e18e3b\"&gt;\n&lt;/assemblyIdentity&gt;\n</code></pre>\n\n<p>My executable requires CRT version 9.0.21022.8. This version number is also embedded in the <code>WinSxS</code> subdirectory names (unfortunately it's surrounded by hashes):</p>\n\n<pre><code>D:&gt;dir c:\\windows\\WinSxS\\*VC90.CRT*\n12/14/2007 02:16 AM &lt;DIR&gt; amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_750b37ff97f4f68b\n12/14/2007 02:00 AM &lt;DIR&gt; x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_bcb86ed6ac711f91\n</code></pre>\n" }, { "answer_id": 1249971, "author": "GregC", "author_id": 90475, "author_profile": "https://Stackoverflow.com/users/90475", "pm_score": 2, "selected": false, "text": "<p>If you're authoring and distributing the mentioned DLL, consider using a merge module for Visual C++ 8.0 CRT as part of your installer.</p>\n\n<p>I noticed that there is a new mt.exe tool and new Visual C++ CRT in Windows SDK 6.1. I use the merge module as a prerequisite in the InstallShield 12 installer with great success.</p>\n" } ]
2008/10/20
[ "https://Stackoverflow.com/questions/217266", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4670/" ]
If the C++ runtime msvcr80.dll is missing from a compiled library, is there any way to determine which version was used to create the library or to get it to run on a later version of msvcr80.dll?
The VC80 SP1 CRT redistributable package will install both the RTM and SP1 versions of the C runtime into `%SystemRoot%\WinSxS` (assuming you're using Windows XP or Vista; Windows 2000 doesn't support side-by-side assemblies). If you have VC8 installed, the CRT redistributable package is in `%ProgramFiles%\Microsoft Visual Studio 8\VC\redist`. If you don't have VC8 installed, I think you can download the CRT redistributable package from Microsoft.com. Also, to find out exactly what CRT version (e.g. RTM vs. SP1) is needed by a binary that was built with VC8 or VC9, you can extract the manifest: ``` mt.exe -inputresource:mydll.dll;#1 -out:mydll.dll.manifest ``` Look for something like this: ``` <assemblyIdentity type="win32" name="Microsoft.VC90.CRT" version="9.0.21022.8" processorArchitecture="x86" publicKeyToken="1fc8b3b9a1e18e3b"> </assemblyIdentity> ``` My executable requires CRT version 9.0.21022.8. This version number is also embedded in the `WinSxS` subdirectory names (unfortunately it's surrounded by hashes): ``` D:>dir c:\windows\WinSxS\*VC90.CRT* 12/14/2007 02:16 AM <DIR> amd64_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_750b37ff97f4f68b 12/14/2007 02:00 AM <DIR> x86_microsoft.vc90.crt_1fc8b3b9a1e18e3b_9.0.21022.8_none_bcb86ed6ac711f91 ```