qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
337,856
<p>I have an Asp.net Mvc site where I want to give a separate access and user interface to different clients like: <a href="http://company1.mysite.com" rel="nofollow noreferrer">http://company1.mysite.com</a><br> <a href="http://company2.mysite.com" rel="nofollow noreferrer">http://company2.mysite.com</a><br> <a href="http://company3.mysite.com" rel="nofollow noreferrer">http://company3.mysite.com</a> </p> <p>Each client will have a different ui but practically same functionality (or with some features disabled).<br> I'd like to separate graphics for each client like logo, css and images.</p> <p>How would be the the best way to implement that?</p>
[ { "answer_id": 337862, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 0, "selected": false, "text": "If Company = A then\n UseFunctionX = true\nelse\n UseFunctionX = false\n\n//later in the code\nIf UseFunctionX then\n // do domenthing\n" }, { "answer_id": 337970, "author": "Trevor de Koekkoek", "author_id": 41783, "author_profile": "https://Stackoverflow.com/users/41783", "pm_score": 2, "selected": true, "text": "<link href=\"<%=AppHelper.GetCSSPath(\"mysite.css\")%>\" rel=\"stylesheet\" type=\"text/css\" />\n public class SubSiteViewEngine: WebFormViewEngine\n{\n\n private string GetSiteRoot() {\n // some logic to get the site root from the incoming URL\n }\n\n public SubSiteViewEngine()\n {\n\n MasterLocationFormats = new[] { \n GetSiteRoote() + \"/Views/{1}/{0}.master\", \n GetSiteRoote() + \"/Views/Shared/{0}.master\" ,\n GetSiteRoote() + \"/Views/Shared/MasterViews/{0}.master\" \n };\n ViewLocationFormats = new[] { \n GetSiteRoote() + \"/Views/{1}/{0}.aspx\", \n GetSiteRoote() + \"/Views/{1}/{0}.ascx\", \n GetSiteRoote() + \"/Views/Shared/{0}.aspx\", \n GetSiteRoote() + \"/Views/Shared/{0}.ascx\",\n GetSiteRoote() + \"/Views/Shared/Controls/{0}.ascx\" \n };\n PartialViewLocationFormats = ViewLocationFormats;\n }\n\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/337856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1929/" ]
337,863
<p>I run a subprocess using:</p> <pre><code> p = subprocess.Popen("subprocess", stdout=subprocess.PIPE, stderr=subprocess.PIPE, stdin=subprocess.PIPE) </code></pre> <p>This subprocess could either exit immediately with an error on stderr, or keep running. I want to detect either of these conditions - the latter by waiting for several seconds.</p> <p>I tried this:</p> <pre><code> SECONDS_TO_WAIT = 10 select.select([], [p.stdout, p.stderr], [p.stdout, p.stderr], SECONDS_TO_WAIT) </code></pre> <p>but it just returns:</p> <pre><code> ([],[],[]) </code></pre> <p>on either condition. What can I do?</p>
[ { "answer_id": 337912, "author": "grieve", "author_id": 34329, "author_profile": "https://Stackoverflow.com/users/34329", "pm_score": 4, "selected": false, "text": "p = subprocess.Popen(\"subprocess\", \n stdout=subprocess.PIPE, \n stderr=subprocess.PIPE, \n stdin=subprocess.PIPE)\n\ntime.sleep(SECONDS_TO_WAIT)\nretcode = p.poll()\nif retcode is not None:\n # process has terminated\n t_nought = time.time()\nseconds_passed = 0\n\nwhile(p.poll() is not None and seconds_passed < 10):\n seconds_passed = time.time() - t_nought\n\nif seconds_passed >= 10:\n #TIMED OUT\n SECONDS_TO_WAIT = 10\n select.select([p.stderr], \n [], \n [p.stdout, p.stderr],\n SECONDS_TO_WAIT)\n" }, { "answer_id": 338079, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "from twisted.internet.utils import getProcessOutputAndValue\nfrom twisted.internet import reactor \n\ndef stop(r):\n reactor.stop()\ndef eb(reason):\n reason.printTraceback()\ndef cb(result):\n stdout, stderr, exitcode = result\n # do something\ngetProcessOutputAndValue('/bin/someproc', []\n ).addCallback(cb).addErrback(eb).addBoth(stop)\nreactor.run()\n" }, { "answer_id": 339655, "author": "shsmurfy", "author_id": 2188962, "author_profile": "https://Stackoverflow.com/users/2188962", "pm_score": 1, "selected": false, "text": "from threading import Timer\nimport subprocess\n\nWAIT_TIME = 10.0\n\ndef check_cmd(cmd):\n p = subprocess.Popen(cmd,\n stdout=subprocess.PIPE, \n stderr=subprocess.PIPE)\n def _check():\n if p.poll()!=0:\n print cmd+\" did not quit within the given time period.\"\n\n # check whether the given process has exited WAIT_TIME\n # seconds from now\n Timer(WAIT_TIME, _check).start()\n\ncheck_cmd('echo')\ncheck_cmd('python')\n python did not quit within the given time period.\n" }, { "answer_id": 1035488, "author": "Darjus Loktevic", "author_id": 127836, "author_profile": "https://Stackoverflow.com/users/127836", "pm_score": 3, "selected": false, "text": "def runCmd(cmd, timeout=None):\n '''\n Will execute a command, read the output and return it back.\n\n @param cmd: command to execute\n @param timeout: process timeout in seconds\n @return: a tuple of three: first stdout, then stderr, then exit code\n @raise OSError: on missing command or if a timeout was reached\n '''\n\n ph_out = None # process output\n ph_err = None # stderr\n ph_ret = None # return code\n\n p = subprocess.Popen(cmd, shell=True,\n stdout=subprocess.PIPE,\n stderr=subprocess.PIPE)\n # if timeout is not set wait for process to complete\n if not timeout:\n ph_ret = p.wait()\n else:\n fin_time = time.time() + timeout\n while p.poll() == None and fin_time > time.time():\n time.sleep(1)\n\n # if timeout reached, raise an exception\n if fin_time < time.time():\n\n # starting 2.6 subprocess has a kill() method which is preferable\n # p.kill()\n os.kill(p.pid, signal.SIGKILL)\n raise OSError(\"Process timeout has been reached\")\n\n ph_ret = p.returncode\n\n\n ph_out, ph_err = p.communicate()\n\n return (ph_out, ph_err, ph_ret)\n" }, { "answer_id": 5955784, "author": "Evan", "author_id": 747516, "author_profile": "https://Stackoverflow.com/users/747516", "pm_score": 2, "selected": false, "text": "from threading import Timer\nfrom subprocess import Popen, PIPE\n\nproc = Popen(\"ping 127.0.0.1\", shell=True)\nt = Timer(60, proc.kill)\nt.start()\nproc.wait()\n" }, { "answer_id": 13335270, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 2, "selected": false, "text": "import subprocess as sp\n\ntry:\n sp.check_call([\"/subprocess\"], timeout=10,\n stdin=sp.DEVNULL, stdout=sp.DEVNULL, stderr=sp.DEVNULL)\nexcept sp.TimeoutError:\n # timeout (the subprocess is killed at this point)\nexcept sp.CalledProcessError:\n # subprocess failed before timeout\nelse:\n # subprocess ended successfully before timeout\n" }, { "answer_id": 15342597, "author": "Shmil The Cat", "author_id": 2157240, "author_profile": "https://Stackoverflow.com/users/2157240", "pm_score": 0, "selected": false, "text": " DEVNULL = open(os.devnull, \"wb\")\n process = Popen(\"c:/myExe.exe\", stdout=DEVNULL) # no need for stdout\n\n def kill_process():\n \"\"\" Kill process helper\"\"\"\n try:\n process.kill()\n except OSError:\n pass # Swallow the error\n\n timer = Timer(timeout_in_sec, kill_process)\n timer.start()\n\n process.wait()\n timer.cancel()\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/337863", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
337,868
<p>In short, I'd like to learn/develop an elegant method to save a binary tree to disk (a general tree, not necessarily a BST). Here is the description of my problem:</p> <p>I'm implementing a game of "20-questions". I've written a binary tree whose internal nodes are questions and leaves are answers. The left child of a node is the path you'd follow if somebody answered "yes" to your current question, while the right child is a "no" answer. Note this is not a binary <em>search</em> tree, just a binary tree whose left child is "yes" and right is "no".</p> <p>The program adds a node to a tree if it encounters a leaf that is null by asking the user to distinguish her answer from the one the computer was thinking of.</p> <p>This is neat, because the tree builds itself up as the user plays. What's not neat is that I don't have a good way of saving the tree to disk.</p> <p>I've thought about saving the tree as an array representation (for node i, left child is 2i+1, and 2i+2 right, (i-1)/2 for parent), but it's not clean and I end up with a lot of wasted space.</p> <p>Any ideas for an elegant solution to saving a sparse binary tree to disk?</p>
[ { "answer_id": 337874, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 3, "selected": false, "text": "F\n F \nB\n F \n B G\n F \n B G\nA\n" }, { "answer_id": 337921, "author": "Skizz", "author_id": 1898, "author_profile": "https://Stackoverflow.com/users/1898", "pm_score": 0, "selected": false, "text": "<node identifier>\nnode data\n[<yes child identfier>\n yes child]\n[<no child identifier>\n no child]\n<end of node identifier>\n" }, { "answer_id": 337930, "author": "slim", "author_id": 7512, "author_profile": "https://Stackoverflow.com/users/7512", "pm_score": 4, "selected": true, "text": " void encodeState(OutputStream out,Node n) {\n if(n==null) {\n out.write(\"[null]\");\n } else {\n out.write(\"{\");\n out.write(n.nodeDetails());\n encodeState(out, n.yesNode());\n encodeState(out, n.noNode());\n out.write(\"}\");\n }\n }\n" }, { "answer_id": 337932, "author": "Kent Fredric", "author_id": 15614, "author_profile": "https://Stackoverflow.com/users/15614", "pm_score": 0, "selected": false, "text": "<parent>,<relation>,<child>\n \"Is it Red\", \"yes\", \"does it have wings\" \n\"Is it Red\", \"no\" , \"does it swim\"\n [0x1111111 \"Is It Red\" => [ 'yes' => 0xF752347 , 'no' => 0xFF6F664 ], \n 0xF752347 \"does it have wings\" => [ 'yes' => 0xFFFFFFF , 'no' => 0x2222222 ], \n 0xFF6F664 \"does it swim\" => [ 'yes' => \"I Dont KNOW :( \" , ... etc etc ]\n" }, { "answer_id": 337980, "author": "Frank Ames", "author_id": 30993, "author_profile": "https://Stackoverflow.com/users/30993", "pm_score": 1, "selected": false, "text": "1,2,3,\"Does it have wings?\"\n2,0,0,\"a bird\"\n3,4,0,\"Does it purr?\"\n4,0,0,\"a cat\"\n" }, { "answer_id": 19084416, "author": "Peter Lee", "author_id": 301336, "author_profile": "https://Stackoverflow.com/users/301336", "pm_score": 0, "selected": false, "text": "void SaveBinaryTreeToStream(TreeNode* root, ostringstream& oss)\n{\n if (!root)\n {\n oss << '#';\n return;\n }\n\n oss << root->data;\n SaveBinaryTreeToStream(root->left, oss);\n SaveBinaryTreeToStream(root->right, oss);\n}\nTreeNode* LoadBinaryTreeFromStream(istringstream& iss)\n{\n if (iss.eof())\n return NULL;\n\n char c;\n if ('#' == (c = iss.get()))\n return NULL;\n\n TreeNode* root = new TreeNode(c, NULL, NULL);\n root->left = LoadBinaryTreeFromStream(iss);\n root->right = LoadBinaryTreeFromStream(iss);\n\n return root;\n}\n main() ostringstream oss;\nroot = MakeCharTree();\nPrintVTree(root);\nSaveBinaryTreeToStream(root, oss);\nClearTree(root);\ncout << oss.str() << endl;\nistringstream iss(oss.str());\ncout << iss.str() << endl;\nroot = LoadBinaryTreeFromStream(iss);\nPrintVTree(root);\nClearTree(root);\n\n/* Output:\n A\n\n B C\n\n D E F\n\n G H I\nABD#G###CEH##I##F##\nABD#G###CEH##I##F##\n A\n\n B C\n\n D E F\n\n G H I\n */\n *********************************************************************************\n ostringstream SaveBinaryTreeToStream_BFS(TreeNode* root)\n{\n ostringstream oss;\n\n if (!root)\n return oss;\n\n queue<TreeNode*> q;\n q.push(root);\n\n while (!q.empty())\n {\n TreeNode* tn = q.front(); q.pop();\n\n if (tn)\n {\n q.push(tn->left);\n q.push(tn->right);\n oss << tn->data;\n }\n else\n {\n oss << '#';\n }\n }\n\n return oss;\n}\nTreeNode* LoadBinaryTreeFromStream_BFS(istringstream& iss)\n{\n if (iss.eof())\n return NULL;\n\n TreeNode* root = new TreeNode(iss.get(), NULL, NULL);\n queue<TreeNode*> q; q.push(root); // The parents from upper level\n while (!iss.eof() && !q.empty())\n {\n TreeNode* tn = q.front(); q.pop();\n\n char c = iss.get();\n if ('#' == c)\n tn->left = NULL;\n else\n q.push(tn->left = new TreeNode(c, NULL, NULL));\n\n c = iss.get();\n if ('#' == c)\n tn->right = NULL;\n else\n q.push(tn->right = new TreeNode(c, NULL, NULL));\n }\n\n return root;\n}\n main() root = MakeCharTree();\nPrintVTree(root);\nostringstream oss = SaveBinaryTreeToStream_BFS(root);\nClearTree(root);\ncout << oss.str() << endl;\nistringstream iss(oss.str());\ncout << iss.str() << endl;\nroot = LoadBinaryTreeFromStream_BFS(iss);\nPrintVTree(root);\nClearTree(root);\n\n/* Output:\n A\n\n B C\n\n D E F\n\n G H I\nABCD#EF#GHI########\nABCD#EF#GHI########\n A\n\n B C\n\n D E F\n\n G H I\n */\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/337868", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42897/" ]
337,870
<p>I have some Python code that works correctly when I use python.exe to run it, but fails if I use pythonw.exe.</p> <pre> def runStuff(commandLine): outputFileName = 'somefile.txt' outputFile = open(outputFileName, "w") try: result = subprocess.call(commandLine, shell=True, stdout=outputFile) except: print 'Exception thrown:', str(sys.exc_info()[1]) myThread = threading.Thread(None, target=runStuff, commandLine=['whatever...']) myThread.start() </pre> <p>The message I get is:</p> <pre> Exception thrown: [Error 6] The handle is invalid </pre> <p>However, if I don't specify the 'stdout' parameter, subprocess.call() starts okay.</p> <p>I can see that pythonw.exe might be redirecting output itself, but I can't see why I'm blocked from specifying stdout for a new thread.</p>
[ { "answer_id": 337990, "author": "Piotr Lesnicki", "author_id": 38796, "author_profile": "https://Stackoverflow.com/users/38796", "pm_score": 4, "selected": true, "text": "sys.stdin sys.stdout subprocess.call() os.devnull" }, { "answer_id": 386343, "author": "Charles Anderson", "author_id": 11677, "author_profile": "https://Stackoverflow.com/users/11677", "pm_score": 3, "selected": false, "text": "def runStuff(commandLine):\n outputFileName = 'somefile.txt'\n outputFile = open(outputFileName, \"w\")\n\n if guiMode:\n result = subprocess.call(commandLine, shell=True, stdout=outputFile, stderr=subprocess.STDOUT)\n else:\n proc = subprocess.Popen(commandLine, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT, stdin=subprocess.PIPE)\n proc.stdin.close()\n proc.wait()\n result = proc.returncode\n outputFile.write(proc.stdout.read())\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/337870", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11677/" ]
337,878
<p>Using instance methods as callbacks for event handlers changes the scope of <code>this</code> from <em>"My instance"</em> to <em>"Whatever just called the callback"</em>. So my code looks like this</p> <pre><code>function MyObject() { this.doSomething = function() { ... } var self = this $('#foobar').bind('click', function(){ self.doSomethng() // this.doSomething() would not work here }) } </code></pre> <p>It works, but is that the best way to do it? It looks strange to me.</p>
[ { "answer_id": 337923, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "doSomething MyObject object(MyObject) function doSomething(){\n .........\n}\n\n$(\"#foobar\").ready('click', function(){\n\n});\n" }, { "answer_id": 337926, "author": "BenAlabaster", "author_id": 40650, "author_profile": "https://Stackoverflow.com/users/40650", "pm_score": 4, "selected": false, "text": "function MyObject(){\n var me = this;\n\n //Events\n Click = onClick; //Allows user to override onClick event with their own\n\n //Event Handlers\n onClick = function(args){\n me.MyProperty = args; //Reference me, referencing this refers to onClick\n ...\n //Do other stuff\n }\n}\n" }, { "answer_id": 337950, "author": "neonski", "author_id": 17112, "author_profile": "https://Stackoverflow.com/users/17112", "pm_score": 2, "selected": false, "text": " $('#foobar').ready('click', this.doSomething.bind(this));\n" }, { "answer_id": 338106, "author": "Eugene Lazutkin", "author_id": 26394, "author_profile": "https://Stackoverflow.com/users/26394", "pm_score": 9, "selected": true, "text": "var abc = 1; // we want to use this variable in embedded functions\n\nfunction xyz(){\n console.log(abc); // it is available here!\n function qwe(){\n console.log(abc); // it is available here too!\n }\n ...\n};\n this this // we want to use \"this\" variable in embedded functions\n\nfunction xyz(){\n // \"this\" is different here!\n console.log(this); // not what we wanted!\n function qwe(){\n // \"this\" is different here too!\n console.log(this); // not what we wanted!\n }\n ...\n};\n var abc = this; // we want to use this variable in embedded functions\n\nfunction xyz(){\n // \"this\" is different here! --- but we don't care!\n console.log(abc); // now it is the right object!\n function qwe(){\n // \"this\" is different here too! --- but we don't care!\n console.log(abc); // it is the right object here too!\n }\n ...\n};\n this arguments" }, { "answer_id": 29881419, "author": "serkan", "author_id": 703529, "author_profile": "https://Stackoverflow.com/users/703529", "pm_score": 4, "selected": false, "text": "var functionX = function() {\n var self = this;\n var functionY = function(y) {\n // If we call \"this\" in here, we get a reference to functionY,\n // but if we call \"self\" (defined earlier), we get a reference to function X.\n }\n}\n" }, { "answer_id": 33425324, "author": "aug", "author_id": 1168661, "author_profile": "https://Stackoverflow.com/users/1168661", "pm_score": 2, "selected": false, "text": "this" }, { "answer_id": 37576680, "author": "Bart Dorsey", "author_id": 1518333, "author_profile": "https://Stackoverflow.com/users/1518333", "pm_score": 2, "selected": false, "text": "bind function MyNamedMethod() {\n // You can now call methods on \"this\" here \n}\n\ndoCallBack(MyNamedMethod.bind(this)); \n doCallBack(function () {\n // You can now call methods on \"this\" here\n}.bind(this));\n var self = this this .bind(this) doCallback( () => {\n // You can reference \"this\" here now\n});\n" }, { "answer_id": 39459801, "author": "Aran Dekar", "author_id": 2071008, "author_profile": "https://Stackoverflow.com/users/2071008", "pm_score": 4, "selected": false, "text": "this.name = 'test'\nmyObject.doSomething(data => {\n console.log(this.name) // this should print out 'test'\n});\n this" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/337878", "https://Stackoverflow.com", "https://Stackoverflow.com/users/407880/" ]
337,891
<p>I've a couple of extension methods I've been developing for a couple of projects, they currently rely heavily on some AJAX to make bits and pieces work. The problem is that they require copying and pasting JavaScript files to the project you want to use it in.</p> <p>As this JavaScript file only needs to be used once (all instances of the rendered control use the same file) I'd like to do something like add the script element to the headers collection of the page it's used on via a web-resource (embedding the file as a resource in the assembly). In Web-forms this wasn't a problem - you could add a script block to the headers with a specific ID and simply check for it on page load.</p> <p>What's the MVC equivalent - is there an equivalent?</p> <p>I'd like a solution that doesn't require the consumer to copy and paste/ add lines to pages or config...any thoughts?</p>
[ { "answer_id": 337923, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "doSomething MyObject object(MyObject) function doSomething(){\n .........\n}\n\n$(\"#foobar\").ready('click', function(){\n\n});\n" }, { "answer_id": 337926, "author": "BenAlabaster", "author_id": 40650, "author_profile": "https://Stackoverflow.com/users/40650", "pm_score": 4, "selected": false, "text": "function MyObject(){\n var me = this;\n\n //Events\n Click = onClick; //Allows user to override onClick event with their own\n\n //Event Handlers\n onClick = function(args){\n me.MyProperty = args; //Reference me, referencing this refers to onClick\n ...\n //Do other stuff\n }\n}\n" }, { "answer_id": 337950, "author": "neonski", "author_id": 17112, "author_profile": "https://Stackoverflow.com/users/17112", "pm_score": 2, "selected": false, "text": " $('#foobar').ready('click', this.doSomething.bind(this));\n" }, { "answer_id": 338106, "author": "Eugene Lazutkin", "author_id": 26394, "author_profile": "https://Stackoverflow.com/users/26394", "pm_score": 9, "selected": true, "text": "var abc = 1; // we want to use this variable in embedded functions\n\nfunction xyz(){\n console.log(abc); // it is available here!\n function qwe(){\n console.log(abc); // it is available here too!\n }\n ...\n};\n this this // we want to use \"this\" variable in embedded functions\n\nfunction xyz(){\n // \"this\" is different here!\n console.log(this); // not what we wanted!\n function qwe(){\n // \"this\" is different here too!\n console.log(this); // not what we wanted!\n }\n ...\n};\n var abc = this; // we want to use this variable in embedded functions\n\nfunction xyz(){\n // \"this\" is different here! --- but we don't care!\n console.log(abc); // now it is the right object!\n function qwe(){\n // \"this\" is different here too! --- but we don't care!\n console.log(abc); // it is the right object here too!\n }\n ...\n};\n this arguments" }, { "answer_id": 29881419, "author": "serkan", "author_id": 703529, "author_profile": "https://Stackoverflow.com/users/703529", "pm_score": 4, "selected": false, "text": "var functionX = function() {\n var self = this;\n var functionY = function(y) {\n // If we call \"this\" in here, we get a reference to functionY,\n // but if we call \"self\" (defined earlier), we get a reference to function X.\n }\n}\n" }, { "answer_id": 33425324, "author": "aug", "author_id": 1168661, "author_profile": "https://Stackoverflow.com/users/1168661", "pm_score": 2, "selected": false, "text": "this" }, { "answer_id": 37576680, "author": "Bart Dorsey", "author_id": 1518333, "author_profile": "https://Stackoverflow.com/users/1518333", "pm_score": 2, "selected": false, "text": "bind function MyNamedMethod() {\n // You can now call methods on \"this\" here \n}\n\ndoCallBack(MyNamedMethod.bind(this)); \n doCallBack(function () {\n // You can now call methods on \"this\" here\n}.bind(this));\n var self = this this .bind(this) doCallback( () => {\n // You can reference \"this\" here now\n});\n" }, { "answer_id": 39459801, "author": "Aran Dekar", "author_id": 2071008, "author_profile": "https://Stackoverflow.com/users/2071008", "pm_score": 4, "selected": false, "text": "this.name = 'test'\nmyObject.doSomething(data => {\n console.log(this.name) // this should print out 'test'\n});\n this" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/337891", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5791/" ]
337,903
<p>exampl:</p> <pre><code>new Thread(new Runnable() { public void run() { while(condition) { *code that must not be interrupted* *some more code* } } }).start(); SomeOtherThread.start(); YetAntherThread.start(); </code></pre> <p>How can you ensure that <em>code that must not be interrupted</em> won't be interrupted?</p>
[ { "answer_id": 338015, "author": "Chris Conway", "author_id": 1412, "author_profile": "https://Stackoverflow.com/users/1412", "pm_score": 2, "selected": false, "text": "ReadWriteLock import java.java.util.concurrent.locks.*;\n\n// create a fair read/write lock\nfinal ReadWriteLock rwLock = new ReentrantReadWriteLock(true);\n\n// the main thread grabs the write lock to exclude other threads\nfinal Lock writeLock = rwLock.writeLock();\n\n// All other threads hold the read lock whenever they do \n// *anything* to make sure the writer is exclusive when \n// it is running. NOTE: the other threads must also \n// occasionally *drop* the lock so the writer has a chance \n// to run!\nfinal Lock readLock = rwLock.readLock();\n\nnew Thread(new Runnable() {\n public void run() {\n while(condition) {\n\n writeLock.lock();\n try {\n *code that must not be interrupted*\n } finally {\n writeLock.unlock();\n }\n\n *some more code*\n }\n }\n}).start();\n\nnew SomeOtherThread(readLock).start();\nnew YetAntherThread(readLock).start();\n" }, { "answer_id": 338694, "author": "OscarRyz", "author_id": 20654, "author_profile": "https://Stackoverflow.com/users/20654", "pm_score": 2, "selected": false, "text": "1,2,3,1,2,3,1,2,3,1,2,3,1,2,3,1,2,3\n 1,1,1,2,1,1,3,1,1,1,2,1,1,1,3,1,2,1,1,1\n public class Test {\n public static void main( String [] args ) throws InterruptedException {\n Thread one = new Thread(){\n public void run(){\n while ( true ) {\n System.out.println(\"eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee\");\n }\n }\n };\n Thread two = new Thread(){\n public void run(){\n while ( true ) {\n System.out.println(\".............................................\");\n }\n }\n };\n Thread three = new Thread(){\n public void run(){\n while ( true ) {\n System.out.println(\"------------------------------------------\");\n }\n }\n };\n\n // Try uncommenting this one by one and see the difference.\n\n //one.setPriority( Thread.MAX_PRIORITY );\n //two.setPriority( Thread.MIN_PRIORITY );\n //three.setPriority( Thread.MIN_PRIORITY );\n one.start();\n two.start();\n three.start();\n\n // The code below makes no difference\n // because \"one\" is not interruptable\n Thread.sleep( 10000 ); // This is the \"main\" thread, letting the others thread run for aprox 10 secs.\n one.interrupt(); // Nice try though.\n }\n}\n public class X{\n public static void main( String [] args ) throws InterruptedException {\n Thread a = new Thread(){ \n\n public void run(){ \n\n int i = 1 ; \n while ( true ){ \n if ( i++ % 100 == 0 ) try {\n System.out.println(\"Sleeping...\");\n Thread.sleep(500);\n } catch ( InterruptedException ie ) {\n System.out.println( \"I was interrpted from my sleep. We all shall die!! \" );\n System.exit(0);\n }\n System.out.print(\"E,\"); \n }\n }\n\n };\n a.start();\n\n\n Thread.sleep( 3000 ); // Main thread letting run \"a\" for 3 secs. \n a.interrupt(); // It will succeed only if the thread is in an interruptable state\n }\n}\n" }, { "answer_id": 21068264, "author": "Jesse Barnum", "author_id": 260516, "author_profile": "https://Stackoverflow.com/users/260516", "pm_score": 1, "selected": false, "text": "new Thread(new Runnable() {\n public void run() {\n Thread t = new Thread() {\n public void run() {\n *code that must not be interrupted*\n }\n }\n t.start(); //Nothing else holds a reference to t, so nothing call call interrupt() on it, except for your own code inside t, or malicious code that gets a list of every live thread and interrupts it.\n\n while( t.isAlive() ) {\n try {\n t.join();\n } catch( InterruptedException e ) {\n //Nope, I'm busy.\n }\n }\n\n *some more code*\n }\n }\n}).start();\n\nSomeOtherThread.start();\n\nYetAntherThread.start();\n" }, { "answer_id": 26226075, "author": "Perdi Estaquel", "author_id": 1366937, "author_profile": "https://Stackoverflow.com/users/1366937", "pm_score": 1, "selected": false, "text": "new Thread() {\n boolean[] allowInterrupts = { true };\n\n @Override\n public void run() {\n while(condition) {\n allowInterrupts[0] = false;\n *code that must not be interrupted*\n allowInterrupts[0] = true;\n *some more code*\n }\n }\n\n @Override\n public void interrupt() {\n synchronized (allowInterrupts) {\n if (allowInterrupts[0]) {\n super.interrupt();\n }\n }\n }\n}.start();\n\nSomeOtherThread.start();\n\nYetAntherThread.start();\n" }, { "answer_id": 53161582, "author": "benez", "author_id": 3583589, "author_profile": "https://Stackoverflow.com/users/3583589", "pm_score": -1, "selected": false, "text": "Thread Thread Thread Thread ExecutorService Thread" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/337903", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
337,918
<p>I have a nightly batch job that can tell if it has failed. I want it to send me an email, possibly with an attachment when it does. </p> <p>How can I send an email from a Windows Batch (.bat) file?</p>
[ { "answer_id": 337955, "author": "Svante Svenson", "author_id": 19707, "author_profile": "https://Stackoverflow.com/users/19707", "pm_score": 3, "selected": true, "text": "echo From: test@example.com>tmp.txt\necho To: test@example.com>>tmp.txt\necho Subject: hello>>tmp.txt\necho.>>tmp.txt\necho Hello world>>tmp.txt\ncopy tmp.txt \\Inetpub\\mailroot\\Pickup\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/337918", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20553/" ]
337,925
<p>I'm just wondering how other developers tackle this issue of getting 2 or 3 answers from a method.</p> <p>1) return a object[]<br> 2) return a custom class<br> 3) use an out or ref keyword on multiple variables<br> 4) write or borrow (F#) a simple Tuple&lt;> generic class<br> <a href="http://slideguitarist.blogspot.com/2008/02/whats-f-tuple.html" rel="nofollow noreferrer">http://slideguitarist.blogspot.com/2008/02/whats-f-tuple.html</a> </p> <p>I'm working on some code now that does data refreshes. From the method that does the refresh I would like to pass back (1) Refresh Start Time and (2) Refresh End Time.<br> At a later date I may want to pass back a third value.</p> <p>Thoughts? Any good practices from open source .NET projects on this topic?</p>
[ { "answer_id": 338528, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 1, "selected": false, "text": "KeyValuePair Key Value public static class KeyValuePair\n{\n public static KeyValuePair<K, V> Make(K k, V v) \n { \n return new KeyValuePair<K, V>(k, v); \n }\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/337925", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36590/" ]
337,942
<p>It should be easy, right? Have a listview, add an imagelist, add images to the imagelist, assign image index to the column you want.<br> But, it doesn't work.<br> <a href="http://support.microsoft.com/kb/314933" rel="nofollow noreferrer">Microsoft article</a> states that it is a known problem in .NET 1.1.<br> But has it been fixed since?</p>
[ { "answer_id": 338528, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 1, "selected": false, "text": "KeyValuePair Key Value public static class KeyValuePair\n{\n public static KeyValuePair<K, V> Make(K k, V v) \n { \n return new KeyValuePair<K, V>(k, v); \n }\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/337942", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28098/" ]
337,986
<p>I am from a c# background and am converting a vb.net windows forms app to c#. I have a windows form called associateForm. In code the developer references associate form like so:-</p> <pre><code>Private Sub NotifyIcon1_MouseClick(ByVal sender As System.Object, ByVal e As System.Windows.Forms.MouseEventArgs) Handles EMS.MouseDoubleClick If e.Button = Windows.Forms.MouseButtons.Left Then If associateForm.WindowState = FormWindowState.Normal And associateForm.Visible = True Then associateForm.WindowState = FormWindowState.Minimized Else associateForm.WindowState = FormWindowState.Normal End If associateForm.Show() associateForm.Focus() 'bring to front of other windows associateForm.Activate() End If End Sub </code></pre> <p>But the thing is that associateForm is not instantiated within the class where the method is being executed. Nor is the class static. Nor does there seem to be an instance of the class anywhere in code. Can anyone shine any light on why this seems to work but when i try this in C# it is not having any of it.</p>
[ { "answer_id": 338383, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "My.Forms.Formname" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/337986", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35441/" ]
337,987
<p>I'm still fairly new to ASP.NET development so bear with me.</p> <p>I'm going to start development on an updated version of an ASP.NET 1.1 website, which I will develop in ASP.NET 3.5. Currently, my development server allows me to run web sites on 1.1 and 2.0. I've had the 3.5 framework installed, but is there any other configuring/issues I should know about? This server will need to keep running the ASP.NET 1.1 web site alongside the 3.5 one I will be developing.</p> <p>Thanks in advance.</p> <p>EDIT: Although I have .NET 3.5 framework installed, when I go into IIS and create a new Virtual Directory, it only gives me the options of 1.1 or 2.0.</p>
[ { "answer_id": 338383, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "My.Forms.Formname" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/337987", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32432/" ]
337,995
<p>I often find that I do a less than complete work on a feature, especially in the Design phase. I detect several reasons:</p> <ol> <li>I'm over-optimistic</li> <li>I feel the need to provide quick solutions, so sometimes I fool myself into thinking the design is fool-proof when in fact it's still full of holes, just to get the job done faster. Of course I end up paying dearly later.</li> </ol> <p>I'm aware of this behavior of mine for some time, yet I still find I don't manage to compensate. Have you encountered similar problems? How do you approach solving them?</p>
[ { "answer_id": 338094, "author": "BIBD", "author_id": 685, "author_profile": "https://Stackoverflow.com/users/685", "pm_score": 0, "selected": false, "text": "for (i=1; i<=10; i++) {} \n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/337995", "https://Stackoverflow.com", "https://Stackoverflow.com/users/11236/" ]
338,024
<p>I can remember <em>Convert</em> class in .net which is named not in accordance with the guide lines. Any more examples?</p>
[ { "answer_id": 338042, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": true, "text": "java.lang.System.arraycopy NullPointerException NullReferenceException AppDomain Control.ID SortedList Type.MakeGenericType MethodInfo.MakeGenericMethod" }, { "answer_id": 338096, "author": "Chris Cudmore", "author_id": 18907, "author_profile": "https://Stackoverflow.com/users/18907", "pm_score": 0, "selected": false, "text": "java.util.Hashtable\n HashSet HashMap HashTable UndoableEdit" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338024", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38807/" ]
338,026
<p>I want to read a string value from the registry and concatenate it with another certain string. I'm calling RegQueryValueEx() , like this: </p> <pre><code>Dim lResult As Long Dim sLength As Long Dim sString As String sString = Space$(256) sLength = 256 lResult = RegQueryValueEx(hKey, "MyKey", 0, REG_SZ, ByVal sString, sLength) MsgBox sString &amp; "blah-blah-blah" </code></pre> <p>RegQueryValueEx() works fine, I'm getting the needed string in sString and even can display it with MsgBox. But when I try to concat it with "some_string" I get only sString showed. Plz, help me.</p> <p>Thanks</p>
[ { "answer_id": 338055, "author": "nobody", "author_id": 19405, "author_profile": "https://Stackoverflow.com/users/19405", "pm_score": 1, "selected": false, "text": "MsgBox(sString & \"blah-blah-blah\")\n Dim sDisplay as String\nsDisplay = sString & \"blah-blah\"\n\nMsgBox sDisplay\n" }, { "answer_id": 338127, "author": "Will Rickards", "author_id": 290835, "author_profile": "https://Stackoverflow.com/users/290835", "pm_score": 0, "selected": false, "text": "Public Function StringFromBuffer(ByRef strBuffer As String) As String\n' Extracts String From a Buffer (buffer is terminated with null)\n' 06/30/2000 - WSR\n\nDim lngPos As Long\n\n ' attempt to find null character in buffer\n lngPos = InStr(1, strBuffer, vbNullChar)\n\n ' if found\n If lngPos > 0 Then\n\n ' return everything before it\n StringFromBuffer = Left$(strBuffer, lngPos - 1)\n\n ' if not found\n Else\n\n ' return whole string\n StringFromBuffer = strBuffer\n\n End If ' lngPos > 0\n\nEnd Function ' StringFromBuffer\n" }, { "answer_id": 338169, "author": "Manne", "author_id": 42929, "author_profile": "https://Stackoverflow.com/users/42929", "pm_score": 3, "selected": false, "text": "sString = Left$(sString, sLength)\n" }, { "answer_id": 339897, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "sString = Left$(sString, sLength-1)\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338026", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
338,037
<p>I know that using <code>ls -l "directory/directory/filename"</code> tells me the permissions of a file. How do I do the same on a directory?</p> <p>I could obviously use <code>ls -l</code> on the directory higher in the hierarchy and then just scroll till I find it but it's such a pain. If I use <code>ls -l</code> on the actual directory, it gives the permissions/information of the files inside of it, and not of the actual directory.</p> <p>I tried this in the terminal of both Mac OS X 10.5 and Linux (Ubuntu Gutsy Gibbon), and it's the same result. Is there some sort of flag I should be using?</p>
[ { "answer_id": 338041, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 9, "selected": false, "text": "$ ls -ld directory\n -d, --directory\n list directory entries instead of contents, and do not dereference symbolic links\n" }, { "answer_id": 338062, "author": "Piotr Lesnicki", "author_id": 38796, "author_profile": "https://Stackoverflow.com/users/38796", "pm_score": 6, "selected": false, "text": "stat" }, { "answer_id": 17409455, "author": "Tony Topper", "author_id": 387866, "author_profile": "https://Stackoverflow.com/users/387866", "pm_score": 3, "selected": false, "text": "ls -lead\n" }, { "answer_id": 30079722, "author": "Taylan", "author_id": 1903743, "author_profile": "https://Stackoverflow.com/users/1903743", "pm_score": 4, "selected": false, "text": "getfacl /directory/directory/\n" }, { "answer_id": 40481498, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 4, "selected": false, "text": "ls namei getfacl stat [flying@lempstacker ~]$ ls -ldh /tmp\ndrwxrwxrwt. 23 root root 4.0K Nov 8 15:41 /tmp\n[flying@lempstacker ~]$ namei -l /tmp\nf: /tmp\ndr-xr-xr-x root root /\ndrwxrwxrwt root root tmp\n[flying@lempstacker ~]$ getfacl /tmp\ngetfacl: Removing leading '/' from absolute path names\n# file: tmp\n# owner: root\n# group: root\n# flags: --t\nuser::rwx\ngroup::rwx\nother::rwx\n\n[flying@lempstacker ~]$ \n [flying@lempstacker ~]$ stat -c \"%a\" /tmp\n1777\n[flying@lempstacker ~]$ stat -c \"%n %a\" /tmp\n/tmp 1777\n[flying@lempstacker ~]$ stat -c \"%A\" /tmp\ndrwxrwxrwt\n[flying@lempstacker ~]$ stat -c \"%n %A\" /tmp\n/tmp drwxrwxrwt\n[flying@lempstacker ~]$\n [flying@lempstacker ~]$ ls -lh /tmp/anaconda.log\n-rw-r--r-- 1 root root 0 Nov 8 08:31 /tmp/anaconda.log\n[flying@lempstacker ~]$ namei -l /tmp/anaconda.log\nf: /tmp/anaconda.log\ndr-xr-xr-x root root /\ndrwxrwxrwt root root tmp\n-rw-r--r-- root root anaconda.log\n[flying@lempstacker ~]$ getfacl /tmp/anaconda.log\ngetfacl: Removing leading '/' from absolute path names\n# file: tmp/anaconda.log\n# owner: root\n# group: root\nuser::rw-\ngroup::r--\nother::r--\n\n[flying@lempstacker ~]$\n [flying@lempstacker ~]$ stat -c \"%a\" /tmp/anaconda.log\n644\n[flying@lempstacker ~]$ stat -c \"%n %a\" /tmp/anaconda.log\n/tmp/anaconda.log 644\n[flying@lempstacker ~]$ stat -c \"%A\" /tmp/anaconda.log\n-rw-r--r--\n[flying@lempstacker ~]$ stat -c \"%n %A\" /tmp/anaconda.log\n/tmp/anaconda.log -rw-r--r--\n[flying@lempstacker ~]$\n" }, { "answer_id": 42652365, "author": "Mehul Jariwala", "author_id": 6774364, "author_profile": "https://Stackoverflow.com/users/6774364", "pm_score": 6, "selected": false, "text": "$ ls -ld directory\n ls - l d" }, { "answer_id": 52414639, "author": "Brandon Aguilar", "author_id": 5032185, "author_profile": "https://Stackoverflow.com/users/5032185", "pm_score": 3, "selected": false, "text": "stat -c '%a - %n' directory/*\n" }, { "answer_id": 64263813, "author": "Aslam Khan", "author_id": 12467056, "author_profile": "https://Stackoverflow.com/users/12467056", "pm_score": 0, "selected": false, "text": "ls –l [file_name]\n ls –l [Directory-name]\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338037", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42228/" ]
338,044
<p>Say I have two tables, a master list of students containing personal info, and a list of student enrollments in classes. The two tables share a common column, which is a string uniquely identifying the student, but it is not the primary key. </p> <p>Say I want to display all the enrollments on a page, along with some of the personal data from the student (say perhaps hometown). </p> <p>I understand that it would be a has_many relationship. The master list record has many enrollments. An enrollment belongs to a student.</p> <pre><code>class Student &lt; ActiveRecord::Base has_many :enrollments end class Enrollment &lt; ActiveRecord::Base belongs_to :student end </code></pre> <p>Is this the correct relationship between the two, and if so, how do I do a join query against the shared column?</p>
[ { "answer_id": 338165, "author": "mwilliams", "author_id": 23909, "author_profile": "https://Stackoverflow.com/users/23909", "pm_score": 3, "selected": false, "text": "Student table:\n- id\n\nEnrollment table:\n- student_id\n @student = Student.first\n@student.enrollments\n" }, { "answer_id": 339291, "author": "Tim Knight", "author_id": 43043, "author_profile": "https://Stackoverflow.com/users/43043", "pm_score": 4, "selected": true, "text": "User.find(:all, :joins => :phone_numbers, :conditions => { :phone_numbers => {:name => 'business'} })\n has_many @student.enrollments" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338044", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42914/" ]
338,056
<p>I have resource dictionary files (MenuTemplate.xaml, ButtonTemplate.xaml, etc) that I want to use in multiple separate applications. I could add them to the applications' assemblies, but it's better if I compile these resources in one single assembly and have my applications reference it, right? </p> <p>After the resource assembly is built, how can I reference it in the App.xaml of my applications? Currently I use ResourceDictionary.MergedDictionaries to merge the individual dictionary files. If I have them in an assembly, how can I reference them in xaml?</p>
[ { "answer_id": 338546, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 10, "selected": true, "text": "<ResourceDictionary Source=\"pack://application:,,,/YourAssembly;component/Subfolder/YourResourceFile.xaml\"/>\n" }, { "answer_id": 2528827, "author": "Hertzel Guinness", "author_id": 293974, "author_profile": "https://Stackoverflow.com/users/293974", "pm_score": 7, "selected": false, "text": "<Application.Resources>\n <ResourceDictionary>\n <ResourceDictionary.MergedDictionaries>\n <ResourceDictionary Source=\"pack://application:,,,/Common;component/styles.xaml\"/>\n </ResourceDictionary.MergedDictionaries>\n </ResourceDictionary>\n</Application.Resources>\n" }, { "answer_id": 10216253, "author": "Aleksandar Toplek", "author_id": 563228, "author_profile": "https://Stackoverflow.com/users/563228", "pm_score": 5, "selected": false, "text": "<ResourceDictionary Source=\"/MyAssembly;component/mytheme.xaml\" />\n" }, { "answer_id": 15713950, "author": "CharithJ", "author_id": 591656, "author_profile": "https://Stackoverflow.com/users/591656", "pm_score": 4, "selected": false, "text": "<ResourceDictionary Source=\"pack://application:,,,/\n <MyAssembly>;component/<FolderStructureInAssembly>/<ResourceFile.xaml>\"/>\n" }, { "answer_id": 36647564, "author": "Kylo Ren", "author_id": 4576125, "author_profile": "https://Stackoverflow.com/users/4576125", "pm_score": 3, "selected": false, "text": "assembly resources ResourceDictionary dictionary = new ResourceDictionary();\n dictionary.Source = new Uri(\"pack://application:,,,/WpfControlLibrary1;Component/RD1.xaml\", UriKind.Absolute);\n foreach (var item in dictionary.Values)\n {\n //operations\n }\n ResourceDictionary RD1.xaml WpfControlLibrary1 StackOverflowApp ResourceDictionary Build Action Resource Page" }, { "answer_id": 43655600, "author": "Gianluca Demarinis", "author_id": 5757328, "author_profile": "https://Stackoverflow.com/users/5757328", "pm_score": 3, "selected": false, "text": "<ResourceDictionary Source=\"ms-appx:///##Namespace.External.Assembly##/##FOLDER##/##FILE##.xaml\" />\n" }, { "answer_id": 70881471, "author": "Walter Verhoeven", "author_id": 8000382, "author_profile": "https://Stackoverflow.com/users/8000382", "pm_score": 1, "selected": false, "text": "MyCorp.Wpf.Dll\n|- Assets\n |- TextStyles.xaml\n |- Colours.axml\n <Style x:Key=\"Header\" TargetType=\"TextBlock\">\n <Setter Property=\"FontFamily\" Value=\"Sego UI Light\"/>\n <Setter Property=\"FontSize\" Value=\"46\" />\n </Style>\n \n <Style x:Key=\"Subheader\" TargetType=\"TextBlock\">\n <Setter Property=\"FontFamily\" Value=\"Sego UI Light\"/>\n <Setter Property=\"FontSize\" Value=\"32\" />\n </Style>\n <Style x:Key=\"Title\" TargetType=\"TextBlock\">\n <Setter Property=\"FontFamily\" Value=\"Sego UI SemiLight\"/>\n <Setter Property=\"FontSize\" Value=\"24\" />\n </Style>\n <Style x:Key=\"SubTitle\" TargetType=\"TextBlock\">\n <Setter Property=\"FontFamily\" Value=\"Sego UI Normal\"/>\n <Setter Property=\"FontSize\" Value=\"20\" />\n </Style>\n \n <Style x:Key=\"Base\" TargetType=\"TextBlock\">\n <Setter Property=\"FontFamily\" Value=\"Sego Semibold\"/>\n <Setter Property=\"FontSize\" Value=\"15\" />\n </Style>\n <Style x:Key=\"Body\" TargetType=\"TextBlock\">\n <Setter Property=\"FontFamily\" Value=\"Sego Normal\"/>\n <Setter Property=\"FontSize\" Value=\"15\" />\n </Style>\n <Style x:Key=\"Caption\" TargetType=\"TextBlock\">\n <Setter Property=\"FontFamily\" Value=\"Sego Normal\"/>\n <Setter Property=\"FontSize\" Value=\"12\" />\n </Style> \n\n</ResourceDictionary>\n <ResourceDictionary xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n >\n <ResourceDictionary.MergedDictionaries>\n <ResourceDictionary Source=\"/MyCorp.Wpf;component/Assets/TextStyles.xaml\"/>\n <ResourceDictionary Source=\"/MyCorp.Wpf;component/Assets/Styles.xaml\"/>\n <ResourceDictionary Source=\"/MyCorp.Wpf;component/Assets/Brushes.xaml\"/>\n <ResourceDictionary Source=\"/MyCorp.Wpf;component/Assets/ColorStyles.xaml\"/>\n </ResourceDictionary.MergedDictionaries>\n</ResourceDictionary>\n <Application x:Class=\"MyNew.App\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n StartupUri=\"MainWindow.xaml\">\n <Application.Resources>\n <ResourceDictionary>\n \n <ResourceDictionary.MergedDictionaries>\n <ResourceDictionary Source=\"ExternalResources.xaml\"/>\n </ResourceDictionary.MergedDictionaries>\n \n <BooleanToVisibilityConverter x:Key=\"VisibilityConverter\"/>\n </ResourceDictionary>\n </Application.Resources>\n</Application>\n <syncfusion:ChromelessWindow x:Class=\"IDPS.ChromelessWindow1\"\n xmlns=\"http://schemas.microsoft.com/winfx/2006/xaml/presentation\"\n xmlns:x=\"http://schemas.microsoft.com/winfx/2006/xaml\"\n xmlns:d=\"http://schemas.microsoft.com/expression/blend/2008\"\n xmlns:mc=\"http://schemas.openxmlformats.org/markup-compatibility/2006\"\n xmlns:local=\"clr-namespace:IDPS\"\n xmlns:r=\"clr-namespace:IDPS.Wpf.Properties;assembly=IDPS.Wpf\" \n xmlns:syncfusion=\"http://schemas.syncfusion.com/wpf\"\n syncfusion:SfSkinManager.Theme=\"{syncfusion:SkinManagerExtension ThemeName=FluentDark}\"\n mc:Ignorable=\"d\"\n MinHeight=\"450\" MinWidth=\"800\">\n <Grid>\n <TextBlock Text=\"Hello world\" Style=\"{StaticResource Title}\"/>\n </Grid>\n</syncfusion:ChromelessWindow>\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28029/" ]
338,063
<p>I have PDF documents from a scanner. This PDF contain forms filled out and signed by staff for a days work. I want to place a bar code or standard area for OCR text on every form type so the batch scan can be programatically broken apart into separate PDF document based on form type. </p> <p>I would like to do this in Microsoft .net 2.0</p> <p>I can purchase the require Adobe or other namespaces/dll need to accomplish the task if there are no open source namespaces/dll's available.</p>
[ { "answer_id": 338411, "author": "joshperry", "author_id": 30587, "author_profile": "https://Stackoverflow.com/users/30587", "pm_score": 1, "selected": false, "text": "string filePath = @\"c:\\file.pdf\";\n\nusing (PdfDocument ipdf = PdfReader.Open(filePath, PdfDocumentOpenMode.ReadOnly))\n{\n int i = 1;\n foreach (PdfPage page in ipdf.Pages)\n {\n using (PdfDocument opdf = new PdfDocument())\n {\n opdf.Version = ipdf.Version;\n opdf.AddPage(page);\n\n opdf.Save(\"page \" + i++ + \".pdf\");\n }\n }\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338063", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
338,075
<p>Why would the following query return "Error converting data type varchar to bigint"? Doesn't IsNumeric make the CAST safe? I've tried every numeric datatype in the cast and get the same "Error converting..." error. I don't believe the size of the resulting number is a problem because overflow is a different error.</p> <p>The interesting thing is, in management studio, the results actually show up in the results pane for a split second before the error comes back.</p> <pre><code>SELECT CAST(myVarcharColumn AS bigint) FROM myTable WHERE IsNumeric(myVarcharColumn) = 1 AND myVarcharColumn IS NOT NULL GROUP BY myVarcharColumn </code></pre> <p>Any thoughts?</p>
[ { "answer_id": 338098, "author": "Kevin Fairchild", "author_id": 3743, "author_profile": "https://Stackoverflow.com/users/3743", "pm_score": 3, "selected": false, "text": "SELECT CAST(CASE \n WHEN IsNumeric(myVarcharColumn) = 0\n THEN 0\n ELSE myVarcharColumn\n END AS BIGINT)\nFROM myTable\nWHERE IsNumeric(myVarcharColumn) = 1\n AND myVarcharColumn IS NOT NULL\nGROUP BY myVarcharColumn\n" }, { "answer_id": 338108, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "select CASE WHEN IsNumeric(mycolumn) = 1 THEN CAST(mycolumn as bigint) END\nFROM stack_table\nWHERE IsNumeric(mycolumn) = 1\nGROUP BY mycolumn\n" }, { "answer_id": 338122, "author": "George Mastros", "author_id": 1408129, "author_profile": "https://Stackoverflow.com/users/1408129", "pm_score": 7, "selected": true, "text": "Declare @Temp Table(Data VarChar(20))\n\nInsert Into @Temp Values(NULL)\nInsert Into @Temp Values('1')\nInsert Into @Temp Values('1e4')\nInsert Into @Temp Values('Not a number')\n\nSelect Cast(Data as bigint)\nFrom @Temp\nWhere IsNumeric(Data) = 1 And Data Is Not NULL\n SELECT CAST(myVarcharColumn AS bigint)\nFROM myTable\nWHERE IsNumeric(myVarcharColumn + '.0e0') = 1 AND myVarcharColumn IS NOT NULL\nGROUP BY myVarcharColumn\n" }, { "answer_id": 15833014, "author": "Arkady", "author_id": 2248877, "author_profile": "https://Stackoverflow.com/users/2248877", "pm_score": 2, "selected": false, "text": "ISNUMERIC('-')\nISNUMERIC('.')\nISNUMERIC('-$.') \n ISNUMERIC(@Value) = 1 (@Value NOT LIKE '[^0-9]') OR (@Value NOT LIKE '-[^0-9]'" }, { "answer_id": 21770230, "author": "MikeTeeVee", "author_id": 555798, "author_profile": "https://Stackoverflow.com/users/555798", "pm_score": 3, "selected": false, "text": "--NOTE: I'd recommend you use this to convert your numbers and store them in a separate table (or field).\n-- This way you may reuse them when when working with legacy/3rd-party systems, instead of running these calculations on the fly each time.\nSELECT Result.Type, Result.Value, Parsed.CleanValue, Converted.Number[Number - Decimal(38,4)],\n (CASE WHEN Result.Value IN ('0', '1', 'True', 'False') THEN CAST(Result.Value as Bit) ELSE NULL END)[Bit],--Cannot convert 1.0 to Bit, it must be in Integer format already.\n (CASE WHEN Converted.Number BETWEEN 0 AND 255 THEN CAST(Converted.Number as TinyInt) ELSE NULL END)[TinyInt],\n (CASE WHEN Converted.Number BETWEEN -32768 AND 32767 AND Result.Value LIKE '%\\%%' ESCAPE '\\' THEN CAST(Converted.Number / 100.0 as Decimal(9,4)) ELSE NULL END)[Percent],\n (CASE WHEN Converted.Number BETWEEN -32768 AND 32767 THEN CAST(Converted.Number as SmallInt) ELSE NULL END)[SmallInt],\n (CASE WHEN Converted.Number BETWEEN -214748.3648 AND 214748.3647 THEN CAST(Converted.Number as SmallMoney) ELSE NULL END)[SmallMoney],\n (CASE WHEN Converted.Number BETWEEN -2147483648 AND 2147483647 THEN CAST(Converted.Number as Int) ELSE NULL END)[Int],\n (CASE WHEN Converted.Number BETWEEN -2147483648 AND 2147483647 THEN CAST(CAST(Converted.Number as Decimal(10)) as Int) ELSE NULL END)[RoundInt],--Round Up or Down instead of Truncate.\n (CASE WHEN Converted.Number BETWEEN -922337203685477.5808 AND 922337203685477.5807 THEN CAST(Converted.Number as Money) ELSE NULL END)[Money],\n (CASE WHEN Converted.Number BETWEEN -9223372036854775808 AND 9223372036854775807 THEN CAST(Converted.Number as BigInt) ELSE NULL END)[BigInt],\n (CASE WHEN Parsed.CleanValue IN ('1', 'True', 'Yes', 'Y', 'Positive', 'Normal') THEN CAST(1 as Bit)\n WHEN Parsed.CleanValue IN ('0', 'False', 'No', 'N', 'Negative', 'Abnormal') THEN CAST(0 as Bit) ELSE NULL END)[Enum],\n --I couln't use just Parsed.CleanValue LIKE '%e%' here because that would match on \"True\" and \"Negative\", so I also had to match on only allowable characters. - 02/13/2014 - MCR.\n (CASE WHEN ISNUMERIC(Parsed.CleanValue) = 1 AND Parsed.CleanValue LIKE '%e%' THEN Parsed.CleanValue ELSE NULL END)[Exponent]\n FROM\n (\n VALUES ('Null', NULL), ('EmptyString', ''), ('Spaces', ' - 2 . 8 % '),--Tabs and spaces mess up IsNumeric().\n ('Bit', '0'), ('TinyInt', '123'), ('Int', '123456789'), ('BigInt', '1234567890123456'),\n --('VeryLong', '12345678901234567890.1234567890'),\n ('VeryBig', '-1234567890123456789012345678901234.5678'),\n ('TooBig', '-12345678901234567890123456789012345678.'),--34 (38-4) is the Longest length of an Integer supported by this query.\n ('VeryLong', '-1.2345678901234567890123456789012345678'),\n ('TooLong', '-12345678901234567890.1234567890123456789'),--38 Digits is the Longest length of a Number supported by the Decimal data type.\n ('VeryLong', '000000000000000000000000000000000000001.0000000000000000000000000000000000000'),--Works because Casting ignores leading zeroes.\n ('TooLong', '.000000000000000000000000000000000000000'),--Exceeds the 38 Digit limit for all Decimal types after the decimal-point.\n --Dot(.), Plus(+), Minus(-), Comma(,), DollarSign($), BackSlash(\\), Tab(0x09), and Letter-E(e) all yeild false-posotives with IsNumeric().\n ('Decimal', '.'), ('Decimal', '.0'), ('Decimal', '3.99'),\n ('Positive', '+'), ('Positive', '+20'),\n ('Negative', '-'), ('Negative', '-45'), ('Negative', '- 1.23'),\n ('Comma', ','), ('Comma', '1,000'),\n ('Money', '$'), ('Money', '$10'),\n ('Percent', '%'), ('Percent', '110%'),--IsNumeric will kick out Percent(%) signs.\n ('BkSlash', '\\'), ('Tab', CHAR(0x09)),--I've actually seen tab characters in our data.\n ('Exponent', 'e0'), ('Exponent', '100e-999'),--No SQL-Server datatype could hold this number, though it is real.\n ('Enum', 'True'), ('Enum', 'Negative')\n ) AS Result(Type, Value)--O is for Observation.\n CROSS APPLY\n ( --This Step is Optional. If you have Very Long numbers with tons of leading zeros, then this is useful. Otherwise is overkill if all the numbers you want have 38 or less digits.\n --Casting of trailing zeros count towards the max 38 digits Decimal can handle, yet Cast ignores leading-zeros. This also cleans up leading/trailing spaces. - 02/25/2014 - MCR.\n SELECT LTRIM(RTRIM(SUBSTRING(Result.Value, PATINDEX('%[^0]%', Result.Value + '.'), LEN(Result.Value))))[Value]\n ) AS Trimmed\n CROSS APPLY\n (\n SELECT --You will need to filter out other Non-Keyboard ASCII characters (before Space(0x20) and after Lower-Case-z(0x7A)) if you still want them to be Cast as Numbers. - 02/15/2014 - MCR.\n REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(Trimmed.Value,--LTRIM(RTRIM(Result.Value)),\n (CHAR(0x0D) + CHAR(0x0A)), ''),--Believe it or not, we have people that press carriage return after entering in the value.\n CHAR(0x09), ''),--Apparently, as people tab through controls on a page, some of them inadvertently entered Tab's for values.\n ' ', ''),--By replacing spaces for values (like '- 2' to work), you open the door to values like '00 12 3' - your choice.\n '$', ''), ',', ''), '+', ''), '%', ''), '/', '')[CleanValue]\n ) AS Parsed--P is for Parsed.\n CROSS APPLY\n ( --NOTE: I do not like my Cross-Applies to feed into each other.\n -- I'm paranoid it might affect performance, but you may move this into the select above if you like. - 02/13/2014 - MCR.\n SELECT (CASE WHEN ISNUMERIC(Parsed.CleanValue + 'e0') = 1--By concatenating 'e0', I do not need to check for: Parsed.CleanValue NOT LIKE '%e%' AND Parsed.CleanValue NOT IN ('.', '-')\n -- If you never plan to work with big numbers, then could use Decimal(19,4) would be best as it only uses 9 storage bytes compared to the 17 bytes that 38 precision requires.\n -- This might help with performance, especially when converting a lot of data.\n AND CHARINDEX('.', REPLACE(Parsed.CleanValue, '-', '')) - 1 <= (38-4)--This is the Longest Integer supported by Decimal(38,4)).\n AND LEN(REPLACE(REPLACE(Parsed.CleanValue, '-', ''), '.', '')) <= 38--When casting to a Decimal (of any Precision) you cannot exceed 38 Digits. - 02/13/2014 - MCR.\n THEN CAST(Parsed.CleanValue as Decimal(38,4))--Scale of 4 used is the max that Money has. This is the biggest number SQL Server can hold.\n ELSE NULL END)[Number]\n ) AS Converted--C is for Converted.\n SELECT ISNUMERIC('')--0. This is understandable, but your logic may want to default these to zero.\nSELECT ISNUMERIC(' ')--0. This is understandable, but your logic may want to default these to zero.\nSELECT ISNUMERIC('%')--0.\nSELECT ISNUMERIC('1%')--0.\nSELECT ISNUMERIC('e')--0.\nSELECT ISNUMERIC(' ')--1. --Tab.\nSELECT ISNUMERIC(CHAR(0x09))--1. --Tab.\nSELECT ISNUMERIC(',')--1.\nSELECT ISNUMERIC('.')--1.\nSELECT ISNUMERIC('-')--1.\nSELECT ISNUMERIC('+')--1.\nSELECT ISNUMERIC('$')--1.\nSELECT ISNUMERIC('\\')--1. '\nSELECT ISNUMERIC('e0')--1.\nSELECT ISNUMERIC('100e-999')--1. No SQL-Server datatype could hold this number, though it is real.\nSELECT ISNUMERIC('3000000000')--1. This is bigger than what an Int could hold, so code for these too.\nSELECT ISNUMERIC('1234567890123456789012345678901234567890')--1. Note: This is larger than what the biggest Decimal(38) can hold.\nSELECT ISNUMERIC('- 1')--1.\nSELECT ISNUMERIC(' 1 ')--1.\nSELECT ISNUMERIC('True')--0.\nSELECT ISNUMERIC('1/2')--0. No love for fractions.\n\nSELECT CAST('e0' as Int)--0. Surpise! Casting to Decimal errors, but for Int is gives us zero, which is wrong.\nSELECT CAST('0e0' as Int)--0. Surpise! Casting to Decimal errors, but for Int is gives us zero, which is wrong.\nSELECT CAST(CHAR(0x09) as Decimal(12,2))--Error converting data type varchar to numeric. --Tab.\nSELECT CAST(' 1' as Decimal(12,2))--Error converting data type varchar to numeric. --Tab.\nSELECT CAST(REPLACE(' 1', CHAR(0x09), '') as Decimal(12,2))--Error converting data type varchar to numeric. --Tab.\nSELECT CAST('' as Decimal(12,2))--Error converting data type varchar to numeric.\nSELECT CAST('' as Int)--0. Surpise! Casting to Decimal errors, but for Int is gives us zero, which is wrong.\nSELECT CAST(',' as Decimal(12,2))--Error converting data type varchar to numeric.\nSELECT CAST('.' as Decimal(12,2))--Error converting data type varchar to numeric.\nSELECT CAST('-' as Decimal(12,2))--Arithmetic overflow error converting varchar to data type numeric.\nSELECT CAST('+' as Decimal(12,2))--Arithmetic overflow error converting varchar to data type numeric.\nSELECT CAST('$' as Decimal(12,2))--Error converting data type varchar to numeric.\nSELECT CAST('$1' as Decimal(12,2))--Error converting data type varchar to numeric.\nSELECT CAST('1,000' as Decimal(12,2))--Error converting data type varchar to numeric.\nSELECT CAST('- 1' as Decimal(12,2))--Error converting data type varchar to numeric. (Due to spaces).\nSELECT CAST(' 1 ' as Decimal(12,2))--1.00 Leading and trailing spaces are okay.\nSELECT CAST('1.' as Decimal(12,2))--1.00\nSELECT CAST('.1' as Decimal(12,2))--0.10\nSELECT CAST('-1' as Decimal(12,2))--1.00\nSELECT CAST('+1' as Decimal(12,2))--1.00\nSELECT CAST('True' as Bit)--1\nSELECT CAST('False' as Bit)--0\n--Proof: The Casting to Decimal cannot exceed 38 Digits, even if the precision is well below 38.\nSELECT CAST('1234.5678901234567890123456789012345678' as Decimal(8,4))--1234.5679\nSELECT CAST('1234.56789012345678901234567890123456789' as Decimal(8,4))--Arithmetic overflow error converting varchar to data type numeric.\n\n--Proof: Casting of trailing zeros count towards the max 38 digits Decimal can handle, yet it ignores leading-zeros.\nSELECT CAST('.00000000000000000000000000000000000000' as Decimal(8,4))--0.0000 --38 Digits after the decimal point.\nSELECT CAST('000.00000000000000000000000000000000000000' as Decimal(8,4))--0.0000 --38 Digits after the decimal point and 3 zeros before the decimal point.\nSELECT CAST('.000000000000000000000000000000000000000' as Decimal(8,4))--Arithmetic overflow error converting varchar to data type numeric. --39 Digits after the decimal point.\nSELECT CAST('1.00000000000000000000000000000000000000' as Decimal(8,4))--Arithmetic overflow error converting varchar to data type numeric. --38 Digits after the decimal point and 1 non-zero before the decimal point.\nSELECT CAST('000000000000000000000000000000000000001.0000000000000000000000000000000000000' as Decimal(8,4))--1.0000\n\n--Caveats: When casting to an Integer:\nSELECT CAST('3.0' as Int)--Conversion failed when converting the varchar value '3.0' to data type int.\n--NOTE: When converting from character data to Int, you may want to do a double-conversion like so (if you want to Round your results first):\nSELECT CAST(CAST('3.5' as Decimal(10)) as Int)--4. Decimal(10) has no decimal precision, so it rounds it to 4 for us BEFORE converting to an Int.\nSELECT CAST(CAST('3.5' as Decimal(11,1)) as Int)--3. Decimal (11,1) HAS decimal precision, so it stays 3.5 before converting to an Int, which then truncates it.\n--These are the best ways to go if you simply want to Truncate or Round.\nSELECT CAST(CAST('3.99' as Decimal(10)) as Int)--3. Good Example of Rounding.\nSELECT CAST(FLOOR('3.99') as Int)--3. Good Example fo Truncating.\n" }, { "answer_id": 24054256, "author": "Rohit Vipin Mathews", "author_id": 1155650, "author_profile": "https://Stackoverflow.com/users/1155650", "pm_score": 2, "selected": false, "text": "ALTER Function [dbo].[IsInteger](@Value VarChar(18))\nReturns Bit\nAs \nBegin\n\n Return IsNull(\n (Select Case When CharIndex('.', @Value) > 0 \n Then 0\n Else 1\n End\n Where IsNumeric(@Value + 'e0') = 1), 0) \nEnd\n TRY_CONVERT" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338075", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22355/" ]
338,101
<p>Not many are aware of this feature, but Python's functions (and methods) can have <a href="http://www.python.org/dev/peps/pep-0232/" rel="noreferrer">attributes</a>. Behold:</p> <pre><code>&gt;&gt;&gt; def foo(x): ... pass ... &gt;&gt;&gt; foo.score = 10 &gt;&gt;&gt; dir(foo) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name', 'score'] &gt;&gt;&gt; foo.score 10 &gt;&gt;&gt; foo.score += 1 &gt;&gt;&gt; foo.score 11 </code></pre> <p>What are the possible uses and abuses of this feature in Python ? One good use I'm aware of is <a href="http://www.dabeaz.com/ply/" rel="noreferrer">PLY</a>'s usage of the docstring to associate a syntax rule with a method. But what about custom attributes ? Are there good reasons to use them ?</p>
[ { "answer_id": 338145, "author": "Martin v. Löwis", "author_id": 33006, "author_profile": "https://Stackoverflow.com/users/33006", "pm_score": 8, "selected": true, "text": "class Foo(WebService):\n @webmethod\n def bar(self, arg1, arg2):\n ...\n def webmethod(func):\n func.is_webmethod = True\n return func\n" }, { "answer_id": 338420, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 7, "selected": false, "text": "int fn(int i)\n{\n static f = 1;\n f += i;\n return f;\n}\n def fn(i):\n fn.f += i\n return fn.f\nfn.f = 1\n" }, { "answer_id": 338577, "author": "Kevin Little", "author_id": 14028, "author_profile": "https://Stackoverflow.com/users/14028", "pm_score": 4, "selected": false, "text": "#!/usr/bin/env python\n\nSW_DELTA = 0\nSW_MARK = 1\nSW_BASE = 2\n\ndef stopwatch():\n import time\n\n def _sw( action = SW_DELTA ):\n\n if action == SW_DELTA:\n return time.time() - _sw._time\n\n elif action == SW_MARK:\n _sw._time = time.time()\n return _sw._time\n\n elif action == SW_BASE:\n return _sw._time\n\n else:\n raise NotImplementedError\n\n _sw._time = time.time() # time of creation\n\n return _sw\n\n# test code\nsw=stopwatch()\nsw2=stopwatch()\nimport os\nos.system(\"sleep 1\")\nprint sw() # defaults to \"SW_DELTA\"\nsw( SW_MARK )\nos.system(\"sleep 2\")\nprint sw()\nprint sw2()\n" }, { "answer_id": 340637, "author": "defnull", "author_id": 407880, "author_profile": "https://Stackoverflow.com/users/407880", "pm_score": 6, "selected": false, "text": ">>> def FakeObject():\n... def test():\n... print \"foo\"\n... FakeObject.test = test\n... return FakeObject\n>>> x = FakeObject()\n>>> x.test()\nfoo\n" }, { "answer_id": 1533317, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 4, "selected": false, "text": "def log(msg):\n log.logfile.write(msg)\n log log.logfile logfile" }, { "answer_id": 29286574, "author": "DiogoNeves", "author_id": 258817, "author_profile": "https://Stackoverflow.com/users/258817", "pm_score": 4, "selected": false, "text": "def with_attrs(**func_attrs):\n \"\"\"Set attributes in the decorated function, at definition time.\n Only accepts keyword arguments.\n E.g.:\n @with_attrs(counter=0, something='boing')\n def count_it():\n count_it.counter += 1\n print count_it.counter\n print count_it.something\n # Out:\n # >>> 0\n # >>> 'boing'\n \"\"\"\n def attr_decorator(fn):\n @wraps(fn)\n def wrapper(*args, **kwargs):\n return fn(*args, **kwargs)\n\n for attr, value in func_attrs.iteritems():\n setattr(wrapper, attr, value)\n\n return wrapper\n\n return attr_decorator\n @with_attrs(datatype=list)\ndef factory1():\n return [1, 2, 3]\n\n@with_attrs(datatype=SomeClass)\ndef factory2():\n return SomeClass()\n\nfactories = [factory1, factory2]\n\ndef create(datatype):\n for f in factories:\n if f.datatype == datatype:\n return f()\n return None\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338101", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8206/" ]
338,103
<p>I'm running Emacs 22.1.1 and IPython 0.9.1 on OS X and I'd like to be able to run lines/methods/snippets of Python code from my current buffer on demand inside an IPython interpreter.</p> <p>What do I need to do to get this working?</p>
[ { "answer_id": 26383574, "author": "yeeking", "author_id": 1240660, "author_profile": "https://Stackoverflow.com/users/1240660", "pm_score": 2, "selected": false, "text": "(setq package-archives '((\"gnu\" . \"http://elpa.gnu.org/packages/\")\n (\"marmalade\" . \"http://marmalade-repo.org/packages/\")\n (\"melpa\" . \"http://melpa.milkbox.net/packages/\")))\n M-x package-refresh-contents\n M-x package-install <ret> ein\n git clone https://github.com/millejoh/emacs-ipython-notebook.git\n cp -r emacs-ipython-notebook/lisp ~/.emacs.d/einv2\n (add-to-list 'load-path \"~/.emacs.d/einv2\")\n (require 'ein)\n M-x package-list-packages\n M-x package-menu-mark-delete\nM-x package-menu-execute\n M-x ein:notebooklist-open\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338103", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1512/" ]
338,110
<p>My users are presented a basically a stripped down version of a spreadsheet. There are textboxes in each row in the grid. When they change a value in a textbox, I'm performing validation on their input, updating the collection that's driving the grid, and redrawing the subtotals on the page. This is all handled by the <code>OnChange</code> event of each textbox.</p> <p>When they click the <kbd>Save</kbd> button, I'm using the button's <code>OnClick</code> event to perform some final validation on the amounts, and then send their entire input to a web service, saving it.</p> <p>At least, that's what happens if they tab through the form to the <kbd>Submit</kbd> button.</p> <p>The problem is, if they enter a value, then immediately click the save button, <code>SaveForm()</code> starts executing before <code>UserInputChanged()</code> completes -- a race condition. My code does not use <code>setTimeout</code>, but I'm using it to simulate the sluggish <code>UserInputChanged</code> validation code:</p> <pre><code> &lt;script&gt; var amount = null; var currentControl = null; function UserInputChanged(control) { currentControl = control; // use setTimeout to simulate slow validation code setTimeout(ValidateAmount, 100); } function SaveForm() { // call web service to save value document.getElementById(&quot;SavedAmount&quot;).innerHTML = amount; } function ValidateAmount() { // various validationey functions here amount = currentControl.value; // save value to collection document.getElementById(&quot;Subtotal&quot;).innerHTML = amount; } &lt;/script&gt; Amount: &lt;input type=&quot;text&quot; onchange=&quot;UserInputChanged(this)&quot;&gt; Subtotal: &lt;span id=&quot;Subtotal&quot;&gt;&lt;/span&gt; &lt;button onclick=&quot;SaveForm()&quot;&gt;Save&lt;/button&gt; Saved amount: &lt;span id=&quot;SavedAmount&quot;&gt;&lt;/span&gt; </code></pre> <p>I don't think I can speed up the validation code -- it's pretty lightweight, but apparently, slow enough that code tries to call the web service before the validation is complete.</p> <p>On my machine, ~95ms is the magic number between whether the validation code executes before the save code begins. This may be higher or lower depending on the users' computer speed.</p> <p>Does anyone have any ideas how to handle this condition? A coworker suggested using a semaphore while the validation code is running and a busy loop in the save code to wait until the semaphore unlocks - but I'd like to avoid using any sort of busy loop in my code.</p>
[ { "answer_id": 338151, "author": "zaratustra", "author_id": 39702, "author_profile": "https://Stackoverflow.com/users/39702", "pm_score": 6, "selected": true, "text": "function UserInputChanged(control) {\n StillNeedsValidating = true;\n // do validation\n StillNeedsValidating = false;\n if (FormNeedsSaving) saveForm(); \n}\n\nfunction SaveForm() {\n if (StillNeedsValidating) { FormNeedsSaving=true; return; }\n // call web service to save value\n FormNeedsSaving = false;\n}\n" }, { "answer_id": 338163, "author": "Andrew Rollings", "author_id": 40410, "author_profile": "https://Stackoverflow.com/users/40410", "pm_score": 4, "selected": false, "text": "function UserInputChanged(control) {\n // --> disable button here --< \n currentControl = control;\n // use setTimeout to simulate slow validation code (production code does not use setTimeout)\n setTimeout(\"ValidateAmount()\", 100); \n}\n function ValidateAmount() {\n // various validationey functions here\n amount = currentControl.value; // save value to collection\n document.getElementById(\"Subtotal\").innerHTML = amount; // update subtotals\n // --> enable button here if validation passes --<\n}\n" }, { "answer_id": 338178, "author": "Excel Kobayashi", "author_id": 42911, "author_profile": "https://Stackoverflow.com/users/42911", "pm_score": 2, "selected": false, "text": "setTimeout() busy = false;\n\nfunction UserInputChanged(control) {\n busy = true;\n currentControl = control;\n // use setTimeout to simulate slow validation code (production code does not use setTimeout)\n setTimeout(\"ValidateAmount()\", 100); \n}\n\nfunction SaveForm() {\n if(busy) \n {\n setTimeout(\"SaveForm()\", 10);\n return;\n }\n\n // call web service to save value\n document.getElementById(\"SavedAmount\").innerHTML = amount;\n}\n\nfunction ValidateAmount() {\n // various validationey functions here\n amount = currentControl.value; // save value to collection\n document.getElementById(\"Subtotal\").innerHTML = amount; // update subtotals\n busy = false;\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338110", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13412/" ]
338,111
<p>The <a href="http://msdn.microsoft.com/en-us/vcsharp/aa336809.aspx" rel="nofollow noreferrer">C# 3.0 spec</a> has the following code example in section 10.6.1.3 "Output parameters":</p> <pre><code>using System; class Test { static void SplitPath(string path, out string dir, out string name) { int i = path.Length; while (i &gt; 0) { char ch = path[i – 1]; if (ch == '\\' || ch == '/' || ch == ':') break; i--; } dir = path.Substring(0, i); name = path.Substring(i); } static void Main() { string dir, name; SplitPath("c:\\Windows\\System\\hello.txt", out dir, out name); Console.WriteLine(dir); Console.WriteLine(name); } } </code></pre> <p>I cannot get this code to compile in VS2005/C#2.0. Did the behavior of strings in C# 3.0 change so that a string can be referred as a char[] array without explicitly converting it (the statement "ch = path[i - 1]")?</p>
[ { "answer_id": 338138, "author": "BenAlabaster", "author_id": 40650, "author_profile": "https://Stackoverflow.com/users/40650", "pm_score": 0, "selected": false, "text": "char ch = path[i - 1];\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42439/" ]
338,156
<p>Academia has it that table names should be the singular of the entity that they store attributes of. </p> <p>I dislike any T-SQL that requires square brackets around names, but I have renamed a <code>Users</code> table to the singular, forever sentencing those using the table to sometimes have to use brackets. </p> <p>My gut feel is that it is more correct to stay with the singular, but my gut feel is also that brackets indicate undesirables like column names with spaces in them etc.</p> <p>Should I stay, or should I go?</p>
[ { "answer_id": 338421, "author": "stephbu", "author_id": 12702, "author_profile": "https://Stackoverflow.com/users/12702", "pm_score": 4, "selected": false, "text": "SELECT [Name] FROM [dbo].[Customer] WHERE [Location] = 'WA'\n" }, { "answer_id": 338431, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 4, "selected": false, "text": "User Users Id ChickenId ChickensId" }, { "answer_id": 338562, "author": "Michel", "author_id": 31122, "author_profile": "https://Stackoverflow.com/users/31122", "pm_score": 4, "selected": false, "text": "tables/views SYSCAT.TABLES dbo.sysindexes ALL_TABLES information_schema.columns" }, { "answer_id": 461369, "author": "nicruo", "author_id": 56683, "author_profile": "https://Stackoverflow.com/users/56683", "pm_score": 3, "selected": false, "text": "-- Select every fields from 'user' table\nSELECT * FROM user\n -- Select every fields from 'user' table which have 21 years old\nSELECT * FROM user WHERE age = '21'\n" }, { "answer_id": 716269, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 7, "selected": false, "text": "SELECT Customer.Name, Customer.Address FROM Customer WHERE Customer.Name > \"def\"\n SELECT Customers.Name, Customers.Address FROM Customers WHERE Customers.Name > \"def\"\n" }, { "answer_id": 1783489, "author": "Vinz", "author_id": 139363, "author_profile": "https://Stackoverflow.com/users/139363", "pm_score": 2, "selected": false, "text": "Users UsersProperties" }, { "answer_id": 3738664, "author": "Randy", "author_id": 451016, "author_profile": "https://Stackoverflow.com/users/451016", "pm_score": 4, "selected": false, "text": "table.field SELECT * FROM cars WHERE color='blue'\nSELECT * FROM car WHERE color='blue'\n" }, { "answer_id": 4499407, "author": "Jacob Lorensen", "author_id": 549923, "author_profile": "https://Stackoverflow.com/users/549923", "pm_score": 5, "selected": false, "text": "AppUser AppUsers AppUserGroup AppUserGroups AppUser_AppUserGroup AppUsers AppUserGroups AppUserGroup_AppUserGroup AppUserGroups AppUserGroups" }, { "answer_id": 5841297, "author": "Nestor", "author_id": 470854, "author_profile": "https://Stackoverflow.com/users/470854", "pm_score": 11, "selected": false, "text": "Customer Customer.CustomerID CustomerAddress public Class Customer {...} SELECT FROM Customer WHERE CustomerID = 100 SELECT Customer.CustomerName FROM Customer WHERE Customer.CustomerID = 100 SELECT Customers.CustomerName FROM Customers WHERE Customers.CustomerID = 103" }, { "answer_id": 7652340, "author": "jleviaguirre", "author_id": 922290, "author_profile": "https://Stackoverflow.com/users/922290", "pm_score": 3, "selected": false, "text": "a \"student\" table can contain 0 or more students \na table of \"students\" can contain 0 or more students.\n" }, { "answer_id": 13203503, "author": "Richard", "author_id": 1795518, "author_profile": "https://Stackoverflow.com/users/1795518", "pm_score": 4, "selected": false, "text": "MS SQL Server's plural singular select OrderHeader.ID FROM OrderHeader WHERE OrderHeader.Reference = 'ABC123'\n ID" }, { "answer_id": 17393910, "author": "Angelin Nadar", "author_id": 412591, "author_profile": "https://Stackoverflow.com/users/412591", "pm_score": 2, "selected": false, "text": "I would prefer,\nUsers table => user\nRoles table => role\nusers role relationship table => user_roles\n" }, { "answer_id": 18534949, "author": "hmartinezd", "author_id": 2733189, "author_profile": "https://Stackoverflow.com/users/2733189", "pm_score": 2, "selected": false, "text": "SELECT CustomerName FROM Customers WHERE CustomerID = 100;\n SELECT * FROM Teams WHERE PlayerID = X\n SELECT * FROM Players INNER JOIN Teams ON Players.PlayerID = Teams.PlayerID WHERE Teams.TeamID = X\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/8741/" ]
338,164
<p>When running get svn fetch to pull the latest new branches from the upstream svn repository I got this error:</p> <pre><code>$ git svn fetch fatal: failed to unpack tree object 5ecb324e8b8fcb918acb253f33edc6ce49e49e0d read-tree 5ecb324e8b8fcb918acb253f33edc6ce49e49e0d: command returned error: 128 </code></pre> <p>Now every attempt at git svn on that local repo results in the same error. Originally I was running git version 1.5.6.4_0 and after the error I tried updating to 1.6.0.2_2 and the problem still persists.</p> <p>Is there any way to clean up this corruption? A fresh git svn clone of the upstream repository is fine, but I'd like to preserve my existing setup. I've looked through the docs and googled for the problem with no luck.</p>
[ { "answer_id": 344837, "author": "Paul", "author_id": 23356, "author_profile": "https://Stackoverflow.com/users/23356", "pm_score": 2, "selected": false, "text": "git fsck --unreachable HEAD $(cat .git/refs/heads/*)\n rsync" }, { "answer_id": 4504577, "author": "David Ammouial", "author_id": 400448, "author_profile": "https://Stackoverflow.com/users/400448", "pm_score": 3, "selected": false, "text": "git svn reset -r 42 git svn fetch git svn fetch --parent git svn fetch git svn fetch -r 50 git svn fetch -r 51 git svn fetch -r xx git svn fetch -r xx+1 git svn fetch" }, { "answer_id": 10894230, "author": "amaechler", "author_id": 1297609, "author_profile": "https://Stackoverflow.com/users/1297609", "pm_score": 2, "selected": false, "text": "$ rm -rf .git/svn\n$ git svn fetch\nRebuilding .git/svn/refs/remotes/trunk/.rev_map.1d5df120-ff1b-4f4f-af56-171ecbcc785d ...\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338164", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42927/" ]
338,166
<p>In a sorted table, it's common to have an up or a down arrow indicating the sort style. However, I'm having some trouble determining which direction the arrow should point. In an ASC sort, characters are sorted 1-9A-Za-z. Should the arrow point up or down?</p> <p>I've found implementations of both on the web, so that didn't help me much: <a href="http://yoast.com/articles/sortable-table/" rel="noreferrer">Up</a> and <a href="http://www.frequency-decoder.com/demo/table-sort-revisited/dynamic/" rel="noreferrer">Down</a> (you have to create the table first).</p> <p>Is there a hard and fast rule for this? I find myself able to justify both implementations. Which method do you use? Which is more intuitive to you and why?</p> <p><strong>Edit:</strong> Some of you have suggested alternate implementations like rising bars or having letters with an arrow indicating sort direction. Great suggestions. I'm definitely open to other options. The less ambiguous, the better. It might be picky, but I'd really like there to be minimal or no confusion on the part of the user.</p> <p><strong>Edit:</strong> I ended up going with the rising and falling bars for now. It's not standard, but seems less ambiguous than the triangles. The current sort column shows three bars, small to large (left to right) for ASC, the opposite for DESC. Other sortable columns have no bars by default, but hovering over any sortable column heading (including the current) shows bars depicting how the table will be sorted if that column heading is clicked.</p>
[ { "answer_id": 338272, "author": "Coderer", "author_id": 26286, "author_profile": "https://Stackoverflow.com/users/26286", "pm_score": 3, "selected": false, "text": "A |\nZ V\n Z |\nA V\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338166", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13281/" ]
338,185
<p>I have an Excel table with several items 1, 2, 3..., each of which has subitems 1.1, 1.2, etc. I'm using the list of subitems as my key column and populating the main items using vlookups, but only showing each main item once.</p> <pre><code>/| A | B | C | -+---------+----------+----------+ 1| Item1 | 1.Note | Item1.1 | 2| | | Item1.2 | 3| | | Item1.3 | 4| Item2 | 2.Note | Item2.1 | 5| | | Item2.2 | 6| | | Item2.3 | 7| | | Item2.4 | 8| Item3 | 3.Note | Item3.1 | 9| | | Item3.2 | 0| | | Item3.3 | </code></pre> <p>Column <code>C</code> is raw data; <code>A</code> and <code>B</code> are formulas.</p> <p>Column <code>B</code> has notes, so the text may be long. I want to wrap the notes to take up all the rows available. I can do this manually by selecting <code>B1:B3</code> and merging them, but then it won't update if I add items to column <code>C</code>.</p> <p>I don't care if the cells are merged or just wrapped and overlapping.</p> <p>Can this be done in formulas or VBA?</p>
[ { "answer_id": 338564, "author": "Jon Fournier", "author_id": 5106, "author_profile": "https://Stackoverflow.com/users/5106", "pm_score": 0, "selected": false, "text": "Private Sub AutoMerge()\n\nDim LastRowToMergeTo As Long\nDim i As Long\nDim LastRow As Long\n\nLastRow = Range(\"C\" & CStr(Rows.Count)).End(xlUp).Row\n\nFor i = 2 To LastRow\n\n LastRowToMergeTo = Range(\"B\" & CStr(i)).End(xlDown).Row - 1\n LastRowToMergeTo = Application.WorksheetFunction.Min(LastRowToMergeTo, LastRow)\n\n With Range(\"B\" & CStr(i) & \":B\" & CStr(LastRowToMergeTo))\n .Merge\n .WrapText = True\n .VerticalAlignment = xlVAlignTop\n End With\n\n i = LastRowToMergeTo\n\nNext i\n\nEnd Sub\n\nPrivate Sub Worksheet_Calculate()\n AutoMerge\nEnd Sub\n" }, { "answer_id": 339328, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "Public Sub AutoMerge()\n\nDim LastRowToMergeTo As Long\nDim i As Long\nDim LastRow As Long\n\nApplication.DisplayAlerts = False\n\nLastRow = Range(\"S\" & CStr(Rows.Count)).End(xlUp).Row\n\nFor i = 2 To LastRow\n\n LastRowToMergeTo = i\n Do While (Len(Range(\"D\" & CStr(LastRowToMergeTo + 1)).Value) = 0) And (LastRowToMergeTo <> LastRow)\n LastRowToMergeTo = LastRowToMergeTo + 1\n Loop\n\n With Range(\"D\" & CStr(i) & \":D\" & CStr(LastRowToMergeTo))\n .Merge\n .WrapText = True\n .VerticalAlignment = xlVAlignTop\n End With\n\n i = LastRowToMergeTo\n\nNext i\n\nApplication.DisplayAlerts = True\n\nEnd Sub\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338185", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
338,195
<p>According to <em>Cocoa Programming for Mac OS X, 3rd Edition,</em> on page 202 (chapter 13):</p> <blockquote> <p>You will be registering, reading, and setting defaults in several classes in your application. To make sure that you always use the same name, you should declare those strings in a single file and then simply #import that file into any file in which you use the names. There are several ways to do this. For example, you could use the C preprocessor’s #define command, but most Cocoa programmers use global variables for this purpose.</p> </blockquote> <p>Is this really the correct best practice? Global variables? That seems insane to me – counter to everything I’ve ever been taught.</p> <p>Would a better design be a simple Singleton class with these defined? Or is it really the correct best practice to go global? Is there a better pattern than either, given that many people consider Singletons to be globals in a pretty dress?</p>
[ { "answer_id": 338214, "author": "Grant Limberg", "author_id": 27314, "author_profile": "https://Stackoverflow.com/users/27314", "pm_score": 5, "selected": true, "text": "[myArray setObject:theObject forKey:MyGlobalVariableKeyName];\n [myArray setObject:theObject \n forKey:[[MySingletonVariableClass getInstance] myVariableKeyName];\n" }, { "answer_id": 339153, "author": "Matt Gallagher", "author_id": 36103, "author_profile": "https://Stackoverflow.com/users/36103", "pm_score": 4, "selected": false, "text": "NSApp NSKeyValueObservingOptionNew" }, { "answer_id": 339189, "author": "Barry Wark", "author_id": 2140, "author_profile": "https://Stackoverflow.com/users/2140", "pm_score": 6, "selected": false, "text": "extern NSString * const MyStringConstant;\n NSString * const MyStringConstant = @\"MyString\";\n #import \"MyConstants.h\"\n\n...\n[someObject someMethodTakingAString:MyStringConstant];\n...\n" }, { "answer_id": 8209157, "author": "unsynchronized", "author_id": 830899, "author_profile": "https://Stackoverflow.com/users/830899", "pm_score": 1, "selected": false, "text": "#define defineKeysIn_h_File(key) extern NSString * const key; \n#define defineKeysIn_m_File(key) NSString * const key = @#key; \n\n\n#define myKeyDefineKeys(defineKey) \\\n/**start of key list*/\\\ndefineKey(myKeyABC);\\\ndefineKey(myKeyXYZ);\\\ndefineKey(myKey123);\\\n/*end of key list*/\n\nmyKeyDefineKeys(defineKeysIn_h_File);\n myKeyDefineKeys(defineKeysIn_m_File);\n // playFromConsts.h\n\n\ndefine_key(AVAudioPlayer_key_player);\ndefine_key(AVAudioPlayer_key_duration);\ndefine_key(AVAudioPlayer_key_filename);\ndefine_key(AVAudioPlayer_key_filepath);\ndefine_key(AVAudioPlayer_key_fileurl);\ndefine_key(AVAudioPlayer_key_urlString);\ndefine_key(AVAudioPlayer_key_envelope);\ndefine_key(AVAudioPlayer_key_startDate);\ndefine_key(AVAudioPlayer_key_linkToPlayer);\ndefine_key(AVAudioPlayer_key_linkFromPlayer);\ndefine_key(AVAudioPlayer_key_linkToPlayerEnvelope);\ndefine_key(AVAudioPlayer_key_linkFromPlayerEnvelope);\ndefine_key(AVAudioPlayer_key_deviceStartTime);\ndefine_key(AVAudioPlayer_key_currentVolume);\ndefine_key(AVAudioPlayer_key_fadeFromVolume);\ndefine_key(AVAudioPlayer_key_fadeToVolume);\ndefine_key(AVAudioPlayer_key_fadeTime);\ndefine_key(AVAudioPlayer_key_segueTime);\n #define define_key(x) extern NSString * const x; \n#include \"playFromConsts.h\"\n#undef define_key\n #define define_key(x) NSString * const x = @#x; \n#include \"playFromConsts.h\"\n#undef define_key\n" }, { "answer_id": 9239024, "author": "Denis Mikhaylov", "author_id": 609427, "author_profile": "https://Stackoverflow.com/users/609427", "pm_score": 1, "selected": false, "text": "#define def_key(name) extern NSString *const name\n#define def_int(name, value) extern int const name\n#define def_type(type, name, value) extern type const name\n\n#include \"ConstantsDefs.h\"\n #import \"Constants.h\"\n\n#undef def_key \n#define def_key(name) NSString *const name = @#name\n\n#undef def_int\n#define def_int(name, value) int const name = value\n\n#undef def_type\n#define def_type(type, name, value) type const name = value\n\n#include \"ConstantsDefs.h\"\n def_key(kStringConstant);\ndef_int(kIntConstant, 313373);\ndef_type(float, kFloatConstant, 313373.0f);\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338195", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14048/" ]
338,206
<p>Is this functionality going to be put into a later Java version?</p> <p>Can someone explain why I can't do this, as in, the technical way Java's <code>switch</code> statement works?</p>
[ { "answer_id": 338230, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 11, "selected": true, "text": "String javac String case switch String if if-else-if switch tableswitch lookupswitch switch String lookupswitch tableswitch O(1) tableswitch O(log(n)) lookupswitch enum String valueOf enum Pill p = Pill.valueOf(str);\nswitch(p) {\n case RED: pop(); break;\n case BLUE: push(); break;\n}\n" }, { "answer_id": 338284, "author": "JeeBee", "author_id": 17832, "author_profile": "https://Stackoverflow.com/users/17832", "pm_score": 7, "selected": false, "text": "ValueEnum enumval = ValueEnum.fromString(myString);\nswitch (enumval) {\n case MILK: lap(); break;\n case WATER: sip(); break;\n case BEER: quaff(); break;\n case OTHER: \n default: dance(); break;\n}\n" }, { "answer_id": 338835, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 4, "selected": false, "text": "switch switch else if" }, { "answer_id": 7445174, "author": "Thulani Chivandikwa", "author_id": 611628, "author_profile": "https://Stackoverflow.com/users/611628", "pm_score": 7, "selected": false, "text": "public class Main {\n\n /**\n * @param args the command line arguments\n */\n public static void main(String[] args) {\n\n String current = args[0];\n Days currentDay = Days.valueOf(current.toUpperCase());\n\n switch (currentDay) {\n case MONDAY:\n case TUESDAY:\n case WEDNESDAY:\n System.out.println(\"boring\");\n break;\n case THURSDAY:\n System.out.println(\"getting better\");\n case FRIDAY:\n case SATURDAY:\n case SUNDAY:\n System.out.println(\"much better\");\n break;\n\n }\n }\n\n public enum Days {\n\n MONDAY,\n TUESDAY,\n WEDNESDAY,\n THURSDAY,\n FRIDAY,\n SATURDAY,\n SUNDAY\n }\n}\n" }, { "answer_id": 20004867, "author": "Charles Goodwin", "author_id": 546060, "author_profile": "https://Stackoverflow.com/users/546060", "pm_score": 2, "selected": false, "text": "//#switch(target)\ncase \"foo\": code;\n//#end\n" }, { "answer_id": 29531341, "author": "Gunnar Forsgren - Mobimation", "author_id": 345759, "author_profile": "https://Stackoverflow.com/users/345759", "pm_score": 4, "selected": false, "text": "String public static void main(String[] args) {\n\n switch (args[0]) {\n case \"Monday\":\n case \"Tuesday\":\n case \"Wednesday\":\n System.out.println(\"boring\");\n break;\n case \"Thursday\":\n System.out.println(\"getting better\");\n case \"Friday\":\n case \"Saturday\":\n case \"Sunday\":\n System.out.println(\"much better\");\n break;\n }\n\n}\n" }, { "answer_id": 30417153, "author": "hyper-neutrino", "author_id": 8200485, "author_profile": "https://Stackoverflow.com/users/8200485", "pm_score": 3, "selected": false, "text": "hashCode() String.hashCode() \"FB\" \"Ea\" String s = \"<Your String>\";\n\nswitch(s.hashCode()) {\ncase \"Hello\".hashCode(): break;\ncase \"Goodbye\".hashCode(): break;\n}\n int public final class Switch<T> {\n private final HashMap<T, Runnable> cases = new HashMap<T, Runnable>(0);\n\n public void addCase(T object, Runnable action) {\n this.cases.put(object, action);\n }\n\n public void SWITCH(T object) {\n for (T t : this.cases.keySet()) {\n if (object.equals(t)) { // This means that the class works with any object!\n this.cases.get(t).run();\n break;\n }\n }\n }\n}\n" }, { "answer_id": 44300104, "author": "Conete Cristian", "author_id": 6413028, "author_profile": "https://Stackoverflow.com/users/6413028", "pm_score": -1, "selected": false, "text": "String runFct = \n queryType.equals(\"eq\") ? \"method1\":\n queryType.equals(\"L_L\")? \"method2\":\n queryType.equals(\"L_R\")? \"method3\":\n queryType.equals(\"L_LR\")? \"method4\":\n \"method5\";\nMethod m = this.getClass().getMethod(runFct);\nm.invoke(this);\n" }, { "answer_id": 60135712, "author": "Iskuskov Alexander", "author_id": 7109598, "author_profile": "https://Stackoverflow.com/users/7109598", "pm_score": 0, "selected": false, "text": "case L -> break yield public static void main(String[] args) {\n switch (args[0]) {\n case \"Monday\", \"Tuesday\", \"Wednesday\" -> System.out.println(\"boring\");\n case \"Thursday\" -> System.out.println(\"getting better\");\n case \"Friday\", \"Saturday\", \"Sunday\" -> System.out.println(\"much better\");\n }\n" }, { "answer_id": 62661099, "author": "Imtiaz Shakil Siddique", "author_id": 5501699, "author_profile": "https://Stackoverflow.com/users/5501699", "pm_score": 0, "selected": false, "text": "final String LEFT = \"left\";\nfinal String RIGHT = \"right\";\nfinal String UP = \"up\";\nfinal String DOWN = \"down\";\n\nString var = ...;\n\nswitch (var) {\n case LEFT:\n case RIGHT:\n case DOWN:\n default:\n return 0;\n}\n" }, { "answer_id": 66651512, "author": "dreamcrash", "author_id": 1366871, "author_profile": "https://Stackoverflow.com/users/1366871", "pm_score": 1, "selected": false, "text": "String translation(String cat_language) {\n return switch (cat_language) {\n case \"miau miau\" -> \"I am to run\";\n case \"miauuuh\" -> \"I am to sleep\";\n case \"mi...au?\" -> \"leave me alone\";\n default -> \"eat\";\n };\n} \n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338206", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14007/" ]
338,212
<p>I've got an array of objects in json format: </p> <pre><code>[ { "name": "obj1", "list": [ "elem1", "elem2", "elem3" ] }, { "name": "obj2", "list": [ "elem4", "elem5", "elem6" ] } ] </code></pre> <p>Now I'd like to construct regexp to remove quotation marks from around elements in the "list" using javascript.<br/></p> <p>Desirable result:<br/></p> <pre><code>[{"name":"obj1", "list":[elem1, elem2, elem3]}, {"name":"obj2", "list":[elem4, elem5, elem6]}] </code></pre>
[ { "answer_id": 338585, "author": "user37125", "author_id": 37125, "author_profile": "https://Stackoverflow.com/users/37125", "pm_score": 1, "selected": false, "text": "var str = '[{\"name\":\"obj1\", \"list\":[\"elem1\", \"elem2\", \"elem3\"]},'\n + '{\"name\":\"obj2\", \"list\":[\"elem4\", \"elem5\", \"elem6\"]}]';\nstr = str.replace(/\"list\":\\[[^\\]]+\\]/g, function (match) {\n return '\"list\":' + match.substring(7, match.length).replace(/([^\\\\])\"/g, '$1');\n});\ndocument.write(str);\n" }, { "answer_id": 339062, "author": "Andrew Tetlaw", "author_id": 42274, "author_profile": "https://Stackoverflow.com/users/42274", "pm_score": 1, "selected": false, "text": "object[\"list\"][0] = document.getElementById(object[\"list\"][0])" }, { "answer_id": 347280, "author": "Alan Moore", "author_id": 20938, "author_profile": "https://Stackoverflow.com/users/20938", "pm_score": 0, "selected": false, "text": "str = str.replace(/\"(?=[^\\[]*\\])/g, '');\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338212", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
338,217
<p>I have a <code>TextCtrl</code> in my wxPython program and I'd like to set its width to exactly 3 characters. However, the only way to set its size manually accepts only numbers of pixels. Is there any way to specify characters instead of pixels?</p>
[ { "answer_id": 338287, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "wxWindow::GetTextExtent int x, y;\ntextCtrl->GetTextExtent(wxT(\"T\"), &x, &y);\ntextCtrl->SetMinSize(wxSize(x * N + 10, -1));\ntextCtrl->SetMaxSize(wxSize(x * N + 10, -1));\n\n/* re-layout the children*/\nthis->Layout(); \n\n/* alternative to Layout, will resize the parent to fit around the new \n * size of the text control. */\nthis->GetSizer()->SetSizeHints(this);\nthis->Fit();\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338217", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1694/" ]
338,225
<p>everybody; I have this problem in asp.net, I have a page where I insert and modify data, before saving I make a validation if it passes I save the data but if not I raise an exception and show it, the function goes like this;</p> <pre><code>protected void btnSave_Click(object sender, EventArgs e) { try { ... if(ValidData()) //Save ... else throw new Exception("Invalid data"); } catch(Exception ex) { // Javascript alert JSLiteral.Text = Utilities.JSAlert(ex.Message); } } </code></pre> <p>The problem is that after I raise the exception and fix the data in the page I click again the save button and it saves but before it shows me again the exception message and its annoying. Even when the data is saved I click again and it shows the message from the exception again.</p> <p>Do you know the answer for this issue?</p>
[ { "answer_id": 338249, "author": "James Curran", "author_id": 12725, "author_profile": "https://Stackoverflow.com/users/12725", "pm_score": 0, "selected": false, "text": "if(ValidData())\n{\n //Save\n}\n else\n{ // Javascript alert\n JSLiteral.Text = Utilities.JSAlert(ex.Message);\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338225", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1130097/" ]
338,242
<p>I'd like to store a simple key/value string dictionary in my web config file. Visual Studio makes it easy to store a string collection(see sample below) but I'm not sure how to do it with a dictionary collection.</p> <pre><code> &lt;ArrayOfString xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema"&gt; &lt;string&gt;value1&lt;/string&gt; &lt;string&gt;value2&lt;/string&gt; &lt;string&gt;value2&lt;/string&gt; &lt;/ArrayOfString&gt; </code></pre>
[ { "answer_id": 338248, "author": "Maxime Rouiller", "author_id": 24975, "author_profile": "https://Stackoverflow.com/users/24975", "pm_score": 3, "selected": false, "text": "<MyDictionary>\n <add name=\"Something1\" value=\"something else\"/>\n <add name=\"Something2\" value=\"something else\"/>\n <add name=\"Something3\" value=\"something else\"/>\n</MyDictionary>\n" }, { "answer_id": 338260, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 0, "selected": false, "text": "static Dictionary<string,string> ArrayToDictionary(string[] data) {\n var map = new Dictionary<string,string>();\n for ( var i= 0; i < data.Length; i+=2 ) {\n map.Add(data[i], data[i+1]);\n }\n return map;\n}\n" }, { "answer_id": 338310, "author": "Juliet", "author_id": 40516, "author_profile": "https://Stackoverflow.com/users/40516", "pm_score": 8, "selected": true, "text": "<configuration>\n <configSections>\n <section \n name=\"MyDictionary\" \n type=\"System.Configuration.NameValueFileSectionHandler,System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" />\n </configSections>\n\n <MyDictionary>\n <add key=\"name1\" value=\"value1\" />\n <add key=\"name2\" value=\"value2\" />\n <add key=\"name3\" value=\"value3\" />\n <add key=\"name4\" value=\"value4\" />\n </MyDictionary>\n</configuration>\n using System.Collections.Specialized;\nusing System.Configuration;\n\npublic string GetName1()\n{\n NameValueCollection section =\n (NameValueCollection)ConfigurationManager.GetSection(\"MyDictionary\");\n return section[\"name1\"];\n}\n" }, { "answer_id": 3294028, "author": "Factor Mystic", "author_id": 1569, "author_profile": "https://Stackoverflow.com/users/1569", "pm_score": 5, "selected": false, "text": ".config web.config <?xml version=\"1.0\"?>\n<configuration>\n <configSections>\n <!-- blah blah the default stuff here -->\n\n <!-- here, add your custom section -->\n <section name=\"DocTabMap\" type=\"System.Configuration.NameValueFileSectionHandler, System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089\" />\n </configSections>\n\n <!-- your custom section, but referenced in another file -->\n <DocTabMap file=\"CustomDocTabs.config\" />\n\n <!-- etc, remainder of default web.config is here -->\n</configuration>\n CustomDocTabs.config <?xml version=\"1.0\"?>\n<DocTabMap>\n <add key=\"A\" value=\"1\" />\n <add key=\"B\" value=\"2\" />\n <add key=\"C\" value=\"3\" />\n <add key=\"D\" value=\"4\" />\n</DocTabMap>\n NameValueCollection DocTabMap = ConfigurationManager.GetSection(\"DocTabMap\") as NameValueCollection;\nDocTabMap[\"A\"] // == \"B\"\n" }, { "answer_id": 6871881, "author": "christo", "author_id": 396481, "author_profile": "https://Stackoverflow.com/users/396481", "pm_score": 2, "selected": false, "text": "<X.Properties.Settings>\n <setting name=\"ElementsList\" serializeAs=\"Xml\">\n <value>\n <ArrayOfString xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\"\n xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\">\n <string>Element1</string>\n <string>Element2</string>\n </ArrayOfString>\n </value>\n </setting>\n</X.Properties.Settings>\n var element = Settings.Default.ElementsList[index]\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25121/" ]
338,251
<p>I am trying to port some data over from my production database to my sandbox using a query like this:</p> <pre><code>INSERT `dbsandbox`.`SomeTable`(Field1, Field2, Field3) SELECT t.Field1, t.Field2, t.Field3 FROM `dbprod`.`SomeTable` t; </code></pre> <p>When I attempt this cross-database join I get the following error:</p> <p>ERROR 1142 (42000): SELECT command denied to user 'myusername'@'server.domain.tdl' for table 'SomeTable'</p> <p>The user in question has permission to the tables in question for both databases. I have tried this in both the unix mysql client and the windows MySQL Query Browser application with the same result.</p> <p>What am I missing?</p>
[ { "answer_id": 338319, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 3, "selected": false, "text": "SELECT t.Field1, t.Field2, t.Field3\nFROM `dbprod`.`SomeTable` t;\n" }, { "answer_id": 360471, "author": "Chris", "author_id": 42937, "author_profile": "https://Stackoverflow.com/users/42937", "pm_score": 4, "selected": true, "text": "dbsandbox SomeTable SomeTable" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338251", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42937/" ]
338,258
<p>I've got two sizing issue regarding a Window I've got. The basic layout is like this</p> <pre><code>&lt;Window MaxHeight="{DynamicResource {x:Static SystemParameters.VirtualScreenHeight}}" MaxWidth="{DynamicResource {x:Static SystemParameters.VirtualScreenWidth}}" &gt; &lt;StackPanel&gt; &lt;DockPanel LastChildFill="False"&gt; &lt;StackPanel DockPanel.Dock="Left" Orientation="Horizontal"&gt; &lt;!--Some buttons--&gt; &lt;/StackPanel&gt; &lt;StackPanel DockPanel.Dock="Right" Orientation="Horizontal"&gt; &lt;!--Some buttons--&gt; &lt;/StackPanel&gt; &lt;/DockPanel&gt; &lt;ScrollViewer&gt; &lt;WrapPanel x:Name="Container"&gt; &lt;/WrapPanel&gt; &lt;/ScrollViewer&gt; &lt;/StackPanel&gt; &lt;/Window&gt; </code></pre> <p>1) How do I made the Window not get smaller horizontally than the DockPanel's width?</p> <p>2) How do I make the ScrollViewer be restricted to the limits of the Window? It is sizing itself to its contents, extending past the bounds of the Window.<br> It sort of used to work when I had </p> <pre><code>&lt;Window&gt;&lt;ScrollViewer/&gt;&lt;/Window&gt; </code></pre> <p>, but I really don't want the DockPanel inside the scroller. In the current form, it is even forcing the Window to break its MaxHeight.</p>
[ { "answer_id": 338538, "author": "Kent Boogaart", "author_id": 5380, "author_profile": "https://Stackoverflow.com/users/5380", "pm_score": 1, "selected": false, "text": "StackPanel Grid StackPanel StackPanel" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338258", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9970/" ]
338,262
<p>Today I discovered something that makes me sad: objects of type System.Generic.Collections.List don't have a number of the useful extension methods I've come to love, such as Find, FindAll, FindIndex, Exists, RemoveAll, etc. </p> <p>The object browser in VS2008 shows that those methods exist in the mscorlib version I'm using, but if I look at the assembly in ildasm they're not there.</p> <p>Am I missing something obvious here or is there some way to make them available to my Silverlight app?</p> <p>Also, I wonder if there's a good reference out there for what's different between Silverlight's runtime and the "real" one.</p> <p>Thanks!</p>
[ { "answer_id": 338339, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 1, "selected": false, "text": "Find List<T>" }, { "answer_id": 1032960, "author": "herzmeister", "author_id": 90742, "author_profile": "https://Stackoverflow.com/users/90742", "pm_score": 0, "selected": false, "text": "using System.Linq;\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338262", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22152/" ]
338,267
<p>My application needs to set cookies for specific paths in the application. For example (in php):</p> <pre><code>setcookie(*cookie_name*,*value*,*date*,"/subpath/subpath/unique_name"); setcookie(*cookie_name*,*value*,*date*,"/subpath/subpath/another unique name"); </code></pre> <p>Oddly enough, the first setcookie works fine. The second doesn't generate an error and when I view my cookies in Firefox the cookie is there with the correct values. However, I can't access it in my code. I believe the whitespaces are causing the trouble but I haven't found any documentation or specs on how cookie paths should be encoded. </p> <p>Has anyone encountered this problem before? Does anyone know how to deal with special characters in cookie paths?</p>
[ { "answer_id": 338581, "author": "OIS", "author_id": 36175, "author_profile": "https://Stackoverflow.com/users/36175", "pm_score": 0, "selected": false, "text": "setcookie(*cookie_name*,*value*,*date*, \"/subpath/subpath/another unique name/\");\nsetcookie(*cookie_name*,*value*,*date*, urlencode(\"/subpath/subpath/another unique name\"));\nsetcookie(*cookie_name*,*value*,*date*, rawurlencode(\"/subpath/subpath/another unique name\"));\n" }, { "answer_id": 338649, "author": "PhiLho", "author_id": 15459, "author_profile": "https://Stackoverflow.com/users/15459", "pm_score": 2, "selected": false, "text": "function ReadCookie(name)\n{\n name += '=';\n var parts = document.cookie.split(/;\\s*/);\n for (var i = 0; i < parts.length; i++)\n {\n var part = parts[i];\n if (part.indexOf(name) == 0)\n return part.substring(name.length)\n }\n return null;\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
338,269
<p>I have an app that display's the current time when a page opens. I would like that time to update every 30 seconds. I've read about prototype's Ajax.PeriodicalUpdater and it seems to be an answer. This is how I achieve the static time display on page load with php: </p> <pre><code> &lt;tr&gt; &lt;td&gt; &lt;input class="standard" type="text" name="start_time" value="&lt;?php echo prev_end();?&gt;"&gt; &lt;!--prev_end is last end time from database--&gt; &lt;/td&gt; &lt;td&gt; &lt;input class="standard" type="text" name="end_time" value="&lt;?php echo $now;?&gt;"&gt; &lt;!--$now = date("G:i");--&gt; &lt;/td&gt; </code></pre> <p>This is what I've attempted with prototype:</p> <pre><code>&lt;script type="javascript"&gt; new Ajax.PeriodicalUpdater("updater", "unow.php", {frequency : 30}); &lt;/script&gt; ... &lt;tr&gt; &lt;td&gt; &lt;input class="standard" type="text" name="start_time" value="&lt;?php echo prev_end();?&gt;"&gt; &lt;/td&gt; &lt;td&gt; &lt;input id="updater" class="standard" type="text" name="end_time" value=""&gt; &lt;/td&gt; </code></pre> <p>Where "unow.php" does this</p> <pre><code>&lt;?php $unow=date("G:i"); echo $unow; ?&gt; </code></pre> <p>It seems that I don't need a callback to put the value from unow.php into the input "updater" since PeriodicalUpdater calls for an element id. What am I missing?</p>
[ { "answer_id": 338364, "author": "James Orr", "author_id": 41457, "author_profile": "https://Stackoverflow.com/users/41457", "pm_score": 3, "selected": true, "text": "<html>\n<body onload=\"init();\">\n <div id=time></div>\n</body>\n</html>\n<script type=text/javascript>\n\nfunction init()\n{\n updateTime();\n window.setInterval(updateTime,30000);\n}\n\n\nfunction updateTime()\n{\n var time = document.getElementById('time');\n time.innerText = new Date().toLocaleString();\n}\n\n</script>\n" }, { "answer_id": 339279, "author": "thoughtcrimes", "author_id": 37814, "author_profile": "https://Stackoverflow.com/users/37814", "pm_score": 1, "selected": false, "text": "<html>\n<head>\n<title>Time</title>\n<script type=\"text/javascript\" src=\"time.js\">\n</head>\n<body>\n <span id=\"timeDisplay\"></span>\n</body>\n</html>\n document.observe(\"dom:loaded\", function() {\n new PeriodicalExecuter(updateTimeDisplay, 30);\n});\n\nupdateTimeDisplay = function(pe) { // accepts the PeriodicalExecuter instance\n var now = new Date();\n $('timeDisplay').innerHTML = now.toString();\n};\n" }, { "answer_id": 341615, "author": "Serxipc", "author_id": 34009, "author_profile": "https://Stackoverflow.com/users/34009", "pm_score": 1, "selected": false, "text": "<input id=\"updater\" class=\"standard\" type=\"text\" name=\"end_time\" \n value=\"\">\n <span id=\"updater\"></span>\n setInterval" }, { "answer_id": 369233, "author": "kevtrout", "author_id": 1149, "author_profile": "https://Stackoverflow.com/users/1149", "pm_score": 1, "selected": false, "text": "<head>\n<script type=\"text/javascript\">\n function startTime()\n {\n var today=new Date();\n var h=today.getHours();\n var m=today.getMinutes();\n\n // add a zero in front of numbers<10\n m=checkTime(m);\n s=checkTime(s);\n document.getElementById('endtime').value=h+\":\"+m;\n t=setTimeout('startTime()',500);\n }\n\n function checkTime(i)\n {\n if (i<10)\n {\n i=\"0\" + i;\n }\n return i;\n }\n </script>\n\n </head>\n <body onload=\"startTime()\">\n <input id=\"endtime\" class=\"standard\" type=\"text\" name=\"end_time\" value=\"\">\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338269", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1149/" ]
338,271
<pre><code> class C { public T x; }; </code></pre> <p>Is there an elegant way for the constructor of x to know <strong>implicitly</strong> in what instance of C it is constructing? <hr> I've implemented such behavior with some dirty inelegant machinery. I need this for my sqlite3 wrapper. I don't like all wrappers I've seen, their API IMO ugly and inconvenient. I want something like this:</p> <pre><code> class TestRecordset: public Recordset { public: // The order of fields declarations specifies column index of the field. // There is TestRecordset* pointer inside Field class, // but it goes here indirectly so I don't have to // re-type all the fields in the constructor initializer list. Field&lt;__int64&gt; field1; Field&lt;wstring&gt; field2; Field&lt;double&gt; field3; // have TestRecordset* pointer too so only name of parameter is specified // in TestRecordset constructor Param&lt;wstring&gt; param; virtual string get_sql() { return "SELECT 1, '1', NULL FROM test_table WHERE param=:PARAM"; } // try & unlock are there because of my dirty tricks. // I want to get rid of them. TestRecordset(wstring param_value) try : Recordset(open_database(L"test.db")), param("PARAM") { param = param_value; // I LOVE RAII but i cant use it here. // Lock is set in Recordset constructor, // not in TestRecordset constructor. unlock(this); fetch(); } catch(...) { unlock(this); throw; } }; <code></pre> <p>I want to clarify the fact - it is a part of the <i>working</i> code. You <i>can</i> do this in C++. I just want to do it in a more nice way. <hr> I've found a way to get rid of unlock and try block. I've remembered there is such a thing as thread local storage. Now I can write constructor as simple as that:</p> <pre> TestRecordset(wstring param_value): Recordset(open_database(L"test.db")), param("PARAM") { param = param_value; fetch(); } </code></pre> <p><hr> to dribeas: My objective is to avoid redundant and tedious typing. Without some tricks behind the scene I will have to type for each Field and Param:</p> <pre> TestRecordset(wstring param_value): Recordset(open_database(L"test.db")), param(this, "PARAM"), field1(this, 0), field2(this, 1), field3(this, 2) { ... } </code></pre> <p>It is redundant, ugly and inconvenient. For example, if I'll have to add new field in the middle of SELECT I'll have to rewrite all the column numbers. Some notes on your post:</p> <ol> <li>Fields and Params <i>are</i> initialized by their default constructors.</li> <li>Order of initializers in constructor is irrelevant. Fields are always initialized in order of their declaration. I've used this fact to track down column index for fields</li> <li>Base classes are constructed first. So when Fields are constructed internal field list in Recordset are ready to use by Filed default constructor.</li> <li>I CAN'T use RAII here. I need to acquire lock in Recorset constructor and release it obligatory in TestRecordset constructor <i>after all Fields are constructed</i>.</li> </ol>
[ { "answer_id": 338297, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 3, "selected": false, "text": "#define INIT_FIELDS field1(this), field2(this), field3(this)\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338271", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12151/" ]
338,273
<p>I'm just learning C with Kernighan and Ritchie's book; I'm in the basics of the fourth chapter (&quot;Functions and Program Structure&quot;). The other day I became curious about the <code>sleep()</code> function, so tried to use it like this:</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;unistd.h&gt; int main(void) { printf(&quot; I like cows.&quot;); sleep(5); return 0; } </code></pre> <p>The problem is the output of the program, it looks like it does the <code>sleep()</code> first and then the <code>printf()</code>, in other words, it waits five seconds and then prints the string. So I thought, maybe the program gets to <code>sleep()</code> so fast that it doesn't let <code>printf()</code> have his work done like I want, that is print the string and then sleep.</p> <p>How can I show the string and then put the program to sleep? The compiler is GCC 3.3.5 (propolice) in OpenBSD 4.3.</p>
[ { "answer_id": 338290, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 3, "selected": false, "text": "fflush(stdout); printf stderr stderr stdout" }, { "answer_id": 338295, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 6, "selected": false, "text": "printf() stdout sleep fflush int main(void)\n{\n printf(\" I like cows.\\n\");\n sleep(5);\n return 0;\n}\n int main(void)\n{\n printf(\" I like cows.\");\n fflush(stdout);\n sleep(5);\n return 0;\n}\n stdout fflush" }, { "answer_id": 338299, "author": "Vinko Vrsalovic", "author_id": 5190, "author_profile": "https://Stackoverflow.com/users/5190", "pm_score": 3, "selected": false, "text": "printf(\" I like cows.\\n\");\n" }, { "answer_id": 53860892, "author": "JunJie Wang", "author_id": 10278382, "author_profile": "https://Stackoverflow.com/users/10278382", "pm_score": 1, "selected": false, "text": "for (int i = 1; i <= 60; i++) {\n printf(\"%02d\", i);\n fflush(stdout);\n sleep(1);\n printf(\"\\b\\b\");\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338273", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
338,274
<p>Ok, I have the following structure. Basically a plugin architecture</p> <pre><code>// assembly 1 - Base Class which contains the contract public class BaseEntity { public string MyName() { // figure out the name of the deriving class // perhaps via reflection } } // assembly 2 - contains plugins based on the Base Class public class BlueEntity : BaseEntity {} public class YellowEntity : BaseEntity {} public class GreenEntity : BaseEntity {} // main console app List&lt;BaseEntity&gt; plugins = Factory.GetMePluginList(); foreach (BaseEntity be in plugins) { Console.WriteLine(be.MyName); } </code></pre> <p>I'd like the statement</p> <pre><code>be.MyName </code></pre> <p>to tell me whether the object is BlueEntity, YellowEntity or GreenEntity. The important thing is that the MyName property should be in the base class, because I don't want to reimplement the property in every plugin.</p> <p>Is this possible in C#?</p>
[ { "answer_id": 338298, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": -1, "selected": false, "text": "class BaseEntity {\n private readonly m_name as string;\n public Name { get { return m_name; } }\n protected BaseEntity(name as string) {\n m_name = name;\n }\n}\nclass BlueEntity : BaseEntity {\n public BlueEntity() : base(typeof(BlueEntity).Name) {}\n}\n" }, { "answer_id": 338302, "author": "Rob Prouse", "author_id": 30827, "author_profile": "https://Stackoverflow.com/users/30827", "pm_score": 1, "selected": false, "text": "foreach (BaseEntity be in plugins) {\n Console.WriteLine(be.GetType().Name);\n}\n" }, { "answer_id": 338308, "author": "Grokys", "author_id": 6448, "author_profile": "https://Stackoverflow.com/users/6448", "pm_score": 4, "selected": true, "text": "public class BaseEntity {\n public string MyName() {\n return this.GetType().Name\n }\n}\n" }, { "answer_id": 338309, "author": "Jeremiah", "author_id": 34183, "author_profile": "https://Stackoverflow.com/users/34183", "pm_score": 2, "selected": false, "text": "return MyObject.GetType().Name;\n" }, { "answer_id": 338316, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": false, "text": "public class BaseEntity {\n public string MyName() {\n return this.GetType().Name;\n }\n}\n BaseEntity.MyName\n\"BaseEntity\"\n\nBlueEntitiy.MyName\n\"BlueEntity\"\n" }, { "answer_id": 338326, "author": "Charles Bretana", "author_id": 32632, "author_profile": "https://Stackoverflow.com/users/32632", "pm_score": -1, "selected": false, "text": "string s = ToString().Split(',')[0]; // to get fully qualified class name... or,\ns = s.Substring(s.LastIndexOf(\".\")+1); // to get just the actual class name itself\n // assembly 1 - Base Class which contains the contractpublic class BaseEntity \n { \n public virtual string MyName // I changed to a property\n { \n get { return MyFullyQualifiedName.Substring(\n MyFullyQualifiedName.LastIndexOf(\".\")+1); }\n }\n public virtual string MyFullyQualifiedName // I changed to a property\n { \n get { return ToString().Split(',')[0]; }\n }\n }\n// assembly 2 - contains plugins based on the Base Class\n public class BlueEntity : BaseEntity {}\n public class YellowEntity : BaseEntity {}\n public class GreenEntity : BaseEntity {}\n // main console app\n List<BaseEntity> plugins = Factory.GetMePluginList();\n foreach (BaseEntity be in plugins) \n { Console.WriteLine(be.MyName);}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338274", "https://Stackoverflow.com", "https://Stackoverflow.com/users/9382/" ]
338,285
<p>I'm trying to prevent <code>bash</code> from saving duplicate commands to my history. Here's what I've got:</p> <pre><code>shopt -s histappend export HISTIGNORE='&amp;:ls:cd ~:cd ..:[bf]g:exit:h:history' export HISTCONTROL=erasedups export PROMPT_COMMAND='history -a' </code></pre> <p>This works fine while I'm logged in and <code>.bash_history</code> is in memory. For example:</p> <pre><code>$ history 1 vi .bashrc 2 vi .alias 3 cd /cygdrive 4 cd ~jplemme 5 vi .bashrc 6 vi .alias $ vi .bashrc $ history 1 vi .alias 2 cd /cygdrive 3 cd ~jplemme 4 vi .alias 5 vi .bashrc $ vi .alias $ history 1 cd /cygdrive 2 cd ~jplemme 3 vi .bashrc 4 vi .alias $ exit </code></pre> <p>But when I log back in, my history file looks like this:</p> <pre><code>$ history 1 vi .bashrc 2 vi .alias 3 cd /cygdrive 4 cd ~jplemme 5 vi .bashrc 6 vi .alias 7 vi .bashrc 8 vi .alias </code></pre> <p>What am I doing wrong?</p> <p>EDIT: Removing the <code>shopt</code> and <code>PROMPT_COMMAND</code> lines from <code>.bashrc</code> does not fix the problem.</p>
[ { "answer_id": 338399, "author": "Robert Gamble", "author_id": 25222, "author_profile": "https://Stackoverflow.com/users/25222", "pm_score": 3, "selected": false, "text": "export HISTCONTROL=ignoreboth\n" }, { "answer_id": 338593, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "histappend $ set | grep HIST\nHISTFILE=/Users/hop/.bash_history\nHISTFILESIZE=500\nHISTIGNORE=' *:&:?:??'\nHISTSIZE=500\n$ export HISTCONTROL=erasedups\n$ shopt | grep hist\ncmdhist on\nhistappend off\nhistreedit off\nhistverify off\nlithist off\n history -a history -w" }, { "answer_id": 4631858, "author": "Venu Anuganti", "author_id": 567679, "author_profile": "https://Stackoverflow.com/users/567679", "pm_score": 2, "selected": false, "text": "[vanuganti@ ~]$ grep HIST .alias*\n.alias:HISTCONTROL=\"erasedups\"\n.alias:HISTSIZE=20000\n.alias:HISTIGNORE=ls:ll:\"ls -altr\":\"ls -alt\":la:l:pwd:exit:mc:su:df:clear:ps:h:history:\"ls -al\"\n.alias:export HISTCONTROL HISTSIZE HISTIGNORE\n[vanuganti@ ~]$ \n [vanuganti@ ~]$ pwd\n/Users/XXX\n[vanuganti@ ~]$ pwd\n/Users/XXX\n[vanuganti@ ~]$ history | grep pwd | wc -l\n 1\n" }, { "answer_id": 4635419, "author": "jserver", "author_id": 514570, "author_profile": "https://Stackoverflow.com/users/514570", "pm_score": 2, "selected": false, "text": "alias hist=\"history -a && hist.py\"\n #!/usr/bin/env python\n\nfrom __future__ import print_function\nimport os, sys\nhome = os.getenv(\"HOME\")\nif not home :\n sys.exit(1)\nlines = open(os.path.join(home, \".bash_history\")).readlines()\nhistory = []\nfor s in lines[:: -1] :\n s = s.rstrip()\n if s not in history :\n history.append(s)\nprint('\\n'.join(history[:: -1]))\n" }, { "answer_id": 7449399, "author": "raychi", "author_id": 949370, "author_profile": "https://Stackoverflow.com/users/949370", "pm_score": 5, "selected": false, "text": "export HISTCONTROL=ignoreboth:erasedups # no duplicate entries\nshopt -s histappend # append history file\nexport PROMPT_COMMAND=\"history -a\" # update histfile after every command\n history -a erasedups ls ls ls # remove duplicates while preserving input order\nfunction dedup {\n awk '! x[$0]++' $@\n}\n\n# removes $HISTIGNORE commands from input\nfunction remove_histignore {\n if [ -n \"$HISTIGNORE\" ]; then\n # replace : with |, then * with .*\n local IGNORE_PAT=`echo \"$HISTIGNORE\" | sed s/\\:/\\|/g | sed s/\\*/\\.\\*/g`\n # negated grep removes matches\n grep -vx \"$IGNORE_PAT\" $@\n else\n cat $@\n fi\n}\n\n# clean up the history file by remove duplicates and commands matching\n# $HISTIGNORE entries\nfunction history_cleanup {\n local HISTFILE_SRC=~/.bash_history\n local HISTFILE_DST=/tmp/.$USER.bash_history.clean\n if [ -f $HISTFILE_SRC ]; then\n \\cp $HISTFILE_SRC $HISTFILE_SRC.backup\n dedup $HISTFILE_SRC | remove_histignore >| $HISTFILE_DST\n \\mv $HISTFILE_DST $HISTFILE_SRC\n chmod go-r $HISTFILE_SRC\n history -c\n history -r\n fi\n}\n history -a erasedups history -w" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338285", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1019/" ]
338,317
<p>I'm trying to build GNU grep, and when I run make, I get:</p> <pre><code>[snip] /bin/bash: line 9: makeinfo: command not found </code></pre> <p>What is makeinfo, and how do I get it?</p> <p>(This is Ubuntu, if it makes a difference)</p>
[ { "answer_id": 338384, "author": "Tuminoid", "author_id": 40657, "author_profile": "https://Stackoverflow.com/users/40657", "pm_score": 10, "selected": true, "text": "bash sudo apt-get install texinfo\n" }, { "answer_id": 19904417, "author": "kevinarpe", "author_id": 257299, "author_profile": "https://Stackoverflow.com/users/257299", "pm_score": 3, "selected": false, "text": "bash makeinfo" }, { "answer_id": 20869472, "author": "arun", "author_id": 3151317, "author_profile": "https://Stackoverflow.com/users/3151317", "pm_score": 5, "selected": false, "text": "yum install texi2html texinfo \n make all\n sudo" }, { "answer_id": 26514522, "author": "Bobby", "author_id": 4171224, "author_profile": "https://Stackoverflow.com/users/4171224", "pm_score": 3, "selected": false, "text": "apt-file search makeinfo" }, { "answer_id": 51226316, "author": "BReddy", "author_id": 4970085, "author_profile": "https://Stackoverflow.com/users/4970085", "pm_score": 2, "selected": false, "text": "sudo zypper install texinfo\n" }, { "answer_id": 57712559, "author": "mbx", "author_id": 303290, "author_profile": "https://Stackoverflow.com/users/303290", "pm_score": 1, "selected": false, "text": "apt-cache search texinfo apt-file search bin/makeinfo sudo $EDITOR /etc/apt/sources.list restricted deb http://archive.ubuntu.com/ubuntu bionic main restricted universe multiverse\ndeb http://archive.ubuntu.com/ubuntu bionic-security main\ndeb http://archive.ubuntu.com/ubuntu bionic-updates main\n sudo $EDITOR /etc/apt/sources.list non-free sudo apt-get udpate" }, { "answer_id": 57795808, "author": "Samuel Lelièvre", "author_id": 3827575, "author_profile": "https://Stackoverflow.com/users/3827575", "pm_score": 3, "selected": false, "text": "makeinfo makeinfo" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338317", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91385/" ]
338,347
<p>I've never managed to move from unit-testing to integration-testing in any graceful or automated way when it comes to network code.</p> <p><strong>So my question is</strong>: Given a simple single-threaded client/server based network application, how would you go about integrating both client and server into your currently favorite testing suite (I currently use <a href="http://check.sourceforge.net/" rel="nofollow noreferrer">check</a>).</p> <p>I am of course willing to change unit-test suite to accomplish my goal.</p> <p><strong>Edit</strong>: While I appreciate the answers, I was more looking for some magical way of integrating integration-testing into my unit-test framework (if it's possible at all). Like if <em>fork</em>() or something could be applied without getting too many side effects.</p>
[ { "answer_id": 338932, "author": "qrdl", "author_id": 28494, "author_profile": "https://Stackoverflow.com/users/28494", "pm_score": 1, "selected": false, "text": "netcat man netcat netcat netcat netcat" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338347", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40668/" ]
338,366
<p>Is there a way to have different application settings per each build configuration?</p> <p>I would like to be able to batch build a few configurations with different settings, instead of having to change the settings and build, rinse repeat.</p> <p>Thanks in advance!</p>
[ { "answer_id": 343406, "author": "Miral", "author_id": 43534, "author_profile": "https://Stackoverflow.com/users/43534", "pm_score": 3, "selected": true, "text": "public static readonly const" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338366", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42931/" ]
338,379
<p>I need to take in a Date Range from the UI, retrieve the records within that range and plot a graph. This is the relevant section in my Rails view.</p> <pre><code>&lt;span&gt; &lt;%= check_box_tag :applyRange, @params[:applyRange]%&gt; From &lt;%= select_date Time.now, :prefix=&gt;"fromDate" %&gt; To &lt;%= select_date Time.now, :prefix=&gt;"toDate" %&gt; &lt;/span&gt; </code></pre> <p>Back on the controller/action side, this is what I had to do to reconstruct the date values back (hack hack puts hack puts hack...)</p> <pre><code>fromDate = Date.civil params[:fromDate]["year"].to_i, params[:fromDate]["month"].to_i, params[:fromDate]["day"].to_i </code></pre> <p><strong>This just feels wrong</strong>. I'll probably have the fields have blanks too.. in which case to_i is bound to barf. This looks like something that must have been done a zillion times before.. So looking for a good recipe for this. I spent the better part of the last hour trying to figure out this quirky rails helper.</p>
[ { "answer_id": 343406, "author": "Miral", "author_id": 43534, "author_profile": "https://Stackoverflow.com/users/43534", "pm_score": 3, "selected": true, "text": "public static readonly const" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338379", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1695/" ]
338,385
<p>Trying to make a <a href="http://en.wikipedia.org/wiki/Web_service" rel="noreferrer">web service</a> call to an <a href="http://en.wikipedia.org/wiki/HTTP_Secure" rel="noreferrer">HTTPS</a> endpoint in my <a href="http://en.wikipedia.org/wiki/Microsoft_Silverlight" rel="noreferrer">Silverlight</a> application results in this error: "Could not find a base address that matches scheme https for the endpoint with binding WSHttpBinding. Registered base address schemes are [http]"</p> <p>The same problem as was posted here:</p> <p><a href="http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/4c19271a-f5e6-4659-9e06-b556dbdcaf82/" rel="noreferrer">http://social.msdn.microsoft.com/Forums/en-US/wcf/thread/4c19271a-f5e6-4659-9e06-b556dbdcaf82/</a></p> <p>So, one of the suggestions was this: "The other issue might be that the cert name and the machine name don't agree, and this is causing <a href="http://en.wikipedia.org/wiki/Windows_Communication_Foundation" rel="noreferrer">WCF</a> to have fits. If this is the case, you can tell WCF to skip verification of the cert."</p> <p>Well, I <strong>do</strong> get a certificate error because this is just a demo server.</p> <p>Here's how I set up my client:</p> <pre><code>BasicHttpBinding binding = new BasicHttpBinding(); binding.Security.Mode = BasicHttpSecurityMode.Transport; _ws = new AnnotationService.AnnotationClient(binding, new EndpointAddress(myAddress)); </code></pre> <p>How can I tell WCF to skip the verification?</p>
[ { "answer_id": 338575, "author": "joshperry", "author_id": 30587, "author_profile": "https://Stackoverflow.com/users/30587", "pm_score": 2, "selected": false, "text": "<bindings>\n <basicHttpBinding>\n <binding name=\"SecureTransport\">\n <security mode=\"Transport\">\n <transport clientCredentialType=\"None\"/>\n </security>\n </binding>\n </basicHttpBinding>\n</bindings>\n <endpoint address=\"\"\n binding=\"basicHttpBinding\"\n bindingConfiguration=\"SecureTransport\"\n contract=\"MyServices.IWebService\" />\n" }, { "answer_id": 479914, "author": "Enrico Campidoglio", "author_id": 26396, "author_profile": "https://Stackoverflow.com/users/26396", "pm_score": 6, "selected": true, "text": "<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<access-policy>\n <cross-domain-access>\n <policy>\n <allow-from http-request-headers=\"SOAPAction\">\n <domain uri=\"http://*\"/>\n </allow-from>\n <grant-to>\n <resource path=\"/\" include-subpaths=\"true\"/>\n </grant-to>\n </policy>\n </cross-domain-access>\n</access-policy>\n <system.serviceModel>\n <behaviors>\n <endpointBehaviors>\n <behavior name=\"DisableServiceCertificateValidation\">\n <clientCredentials>\n <serviceCertificate>\n <authentication certificateValidationMode=\"None\"\n revocationMode=\"NoCheck\" />\n </serviceCertificate>\n </clientCredentials>\n </behavior>\n </endpointBehaviors>\n </behaviors>\n <client>\n <endpoint address=\"http://localhost/MyService\"\n behaviorConfiguration=\"DisableServiceCertificateValidation\"\n binding=\"wsHttpBinding\"\n contract=\"MyNamespace.IMyService\"\n name=\"MyServiceWsHttp\" />\n </client>\n</system.serviceModel>\n <system.serviceModel>\n <behaviors>\n <endpointBehaviors>\n <behavior name=\"DisableServiceCertificateValidation\">\n <clientCredentials>\n <serviceCertificate>\n <authentication certificateValidationMode=\"Custom\"\n customCertificateValidatorType=\"MyCertificateValidator, Client\"\n revocationMode=\"NoCheck\" />\n </serviceCertificate>\n </clientCredentials>\n </behavior>\n </endpointBehaviors>\n </behaviors>\n <client>\n <endpoint address=\"http://localhost/MyService\"\n behaviorConfiguration=\"DisableServiceCertificateValidation\"\n binding=\"wsHttpBinding\"\n contract=\"MyNamespace.IMyService\"\n name=\"MyServiceWsHttp\" />\n </client>\n</system.serviceModel>\n public class MyCertificateValidator : X509CertificateValidator\n{\n public override void Validate(X509Certificate2 certificate)\n {\n // Add custom validation logic\n // Throw an exception to fail validation\n }\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338385", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28643/" ]
338,398
<p>Every now and then, I bump into syntax that I've seen before, but never used. This is one of those times.</p> <p>Can someone explain the purpose of ":this" or ":base" following a C# constructor method?</p> <p>For example:</p> <pre><code>public MyClass(SomeArg arg) : this(new SomethingElse(), arg) { } </code></pre> <p>My gut feeling is that it is used to map a default argument onto another constructor method.</p>
[ { "answer_id": 338402, "author": "MrKurt", "author_id": 35296, "author_profile": "https://Stackoverflow.com/users/35296", "pm_score": 5, "selected": true, "text": "this() base()" }, { "answer_id": 338409, "author": "Lasse V. Karlsen", "author_id": 267, "author_profile": "https://Stackoverflow.com/users/267", "pm_score": 2, "selected": false, "text": "public class Base { }\npublic class Something : Base { }\npublic class Else : Something { }\n" }, { "answer_id": 338413, "author": "Juliet", "author_id": 40516, "author_profile": "https://Stackoverflow.com/users/40516", "pm_score": 4, "selected": false, "text": "public class Test\n{\n public Test() : this(\"Called from default constructor\") { }\n public Test(String msg)\n {\n Console.WriteLine(msg);\n }\n}\n public static void Main(String[] args)\n{\n Test t1 = new Test();\n Test t2 = new Test(\"Called from Main function\");\n}\n : base(someParams)" }, { "answer_id": 338423, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "public MyClass(SomeArg arg) : this(new SomethingElse(), arg)\n public MyClass(SomethingElse arg, SomeArg arg1) : base or this or nothing\n base(....) this(....) this(....)" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338398", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1965/" ]
338,400
<p>Compiling this lines</p> <pre><code> long int sz; char tmpret[128]; //take substring of c, translate in c string, convert to int, //and multiply with 1024 sz=atoi(c.substr(0,pos).c_str())*1024; snprintf(tmpret,128,"%l",sz); </code></pre> <p>I read two warning on snprintf line:</p> <pre><code> warning: conversion lacks type at end of format warning: too many arguments for format </code></pre> <p>Why? The type is specified (long int sz, and %l in snprintf) and the argument in snprintf is only one. Can anybody help me? Thanks.</p>
[ { "answer_id": 338437, "author": "Matt Cruikshank", "author_id": 8643, "author_profile": "https://Stackoverflow.com/users/8643", "pm_score": 1, "selected": false, "text": "boost::lexical_cast<string>(sz)" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338400", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39796/" ]
338,406
<p>So I'm trying to run my first hello world prog written in C. I compiled it in eclipse and get no errors, but when I try to run it I get:</p> <p>"This application has failed to start because cygwin1.dll was not found."</p> <p>I found <a href="http://dev.eclipse.org/newslists/news.eclipse.tools.cdt/msg08271.html" rel="noreferrer">this post</a> which seems to indicate I should add it to Windows PATH, and I used <a href="http://www.computerhope.com/issues/ch000549.htm" rel="noreferrer">this</a> to do that. So now "Path" in my environment variables has ";C:\cygwin\bin\cygwin1.dll" appended to the end. Still no worky. Anyone have a clue what I might be doing wrong? My 'program' just looks like this: </p> <pre><code>#include &lt;stdio.h&gt; main() { printf("hello, world\n"); } </code></pre>
[ { "answer_id": 338412, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 5, "selected": true, "text": "\"C:\\cygwin\\bin\"" }, { "answer_id": 338462, "author": "Mihai Limbășan", "author_id": 14444, "author_profile": "https://Stackoverflow.com/users/14444", "pm_score": 4, "selected": false, "text": ".local mytest.exe mytest.exe.local" }, { "answer_id": 23146171, "author": "Martin Pfeffer", "author_id": 2533290, "author_profile": "https://Stackoverflow.com/users/2533290", "pm_score": 0, "selected": false, "text": "\"C:\\cygwin64\\bin\"" }, { "answer_id": 53600031, "author": "not2qubit", "author_id": 1147688, "author_profile": "https://Stackoverflow.com/users/1147688", "pm_score": 0, "selected": false, "text": ";C\\cygwin64\\bin PATH x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338406", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
338,427
<p>[This is for PC/Visual C++ specifically (although any other answers would be quite illuminating :))]</p> <p>How can you tell if a pointer comes from an object in the stack? For example:</p> <pre><code>int g_n = 0; void F() { int *pA = &amp;s_n; ASSERT_IS_POINTER_ON_STACK(pA); int i = 0; int *pB = &amp;i; ASSERT_IS_POINTER_ON_STACK(pB); } </code></pre> <p>so only the second assert <em>(pB)</em> should trip. I'm thinking using some inline assembly to figure out if it's within the SS segment register or something like that. Does anybody know if there's any built in functions for this, or a simple way to do this?</p> <p>Thanks! RC</p>
[ { "answer_id": 338446, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 2, "selected": false, "text": "%esp main() main() main() uint32_t GetESP(void)\n{\n uint32_t ret;\n asm\n {\n mov esp, ret\n }\n return ret;\n}\n" }, { "answer_id": 338448, "author": "Rob Walker", "author_id": 3631, "author_profile": "https://Stackoverflow.com/users/3631", "pm_score": 0, "selected": false, "text": "void* TopOfStack; // someone must populate this in the first stack frame\n\nbool IsOnTheStack(void* p)\n{\n int x;\n\n return (size_t) p < (size_t) TopOfTheStack &&\n (size_t) p > (size_t) &x;\n}\n" }, { "answer_id": 338451, "author": "Mark Ransom", "author_id": 5987, "author_profile": "https://Stackoverflow.com/users/5987", "pm_score": 2, "selected": false, "text": "static void * markerTop = NULL;\n\nint main()\n{\n char topOfStack;\n markerTop = &topOfStack;\n ...\n}\n\nbool IsOnStack(void * p)\n{\n char bottomOfStack;\n void * markerBottom = &bottomOfStack;\n return (p > markerBottom) && (p < markerTop);\n}\n" }, { "answer_id": 345579, "author": "AShelly", "author_id": 10396, "author_profile": "https://Stackoverflow.com/users/10396", "pm_score": 1, "selected": false, "text": "#define IS_POINTER_TO_STACK(vp) (*((int*)(vp)-1)==0xCCCCCCCC)\n #define ASSERT(v) printf(\"assert: %d\\n\", v); //so it doesn't really quit\nint g_n = 0;\nvoid test_indirectly(void* vp) {\n ASSERT(IS_POINTER_TO_STACK(vp));\n}\nvoid F() {\n int *pA = &g_n;\n ASSERT(IS_POINTER_TO_STACK(pA)); //0\n\n int i = 0;\n int j = 0;\n int *pB = &i;\n ASSERT(IS_POINTER_TO_STACK(pB)); //1\n ASSERT(IS_POINTER_TO_STACK(&j)); //1\n\n int *pC = (int*)malloc(sizeof(int));\n ASSERT(IS_POINTER_TO_STACK(pC)); //0\n free(pC);\n ASSERT(IS_POINTER_TO_STACK(pC)); //0\n pC = new int;\n ASSERT(IS_POINTER_TO_STACK(pC)); //0\n delete pC;\n\n char* s = \"HelloSO\";\n char w[6];\n ASSERT(IS_POINTER_TO_STACK(\"CONSTANT\")); //0\n ASSERT(IS_POINTER_TO_STACK(s)); //0\n ASSERT(IS_POINTER_TO_STACK(&w[0])); //1\n test_indirectly(&s); //1\n\n int* pD; //uninit\n ASSERT(IS_POINTER_TO_STACK(pD)); //runtime error check\n\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338427", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13004/" ]
338,428
<p>Is there a way to query against exchange 2007 to distinguish who is either an active sync or blackberry user using powershell exchange addin? </p>
[ { "answer_id": 359962, "author": "phill", "author_id": 18853, "author_profile": "https://Stackoverflow.com/users/18853", "pm_score": 0, "selected": false, "text": "'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n''\n'' DISABLEEAS.VBS\n''\n'' Disables Exchange Server 2003 Active Sync for the specified OU in the default domain\n''\n'' usage: cscript disableeas\n''\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n\n' Below are the values for the msExchOmaAdminWirelessEnable Exchange attribute that can be modified.\n' 5 = disable EAS and keep OMA enabled.(default)\n' 7 = disable all mobile features.\n' 0 = enable all mobile features. (not recommended)\n\n\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n'' Create log file instance\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n\nOn Error Resume Next\nSet objFSO = CreateObject(\"Scripting.FileSystemObject\")\nSet objLogFile = objFSO.OpenTextFile(\"c:\\disableeas.log\", 2, True, 0)\nIf Err.Number <> 0 Then\n ' Attempt to create a log file failed. \n On Error GoTo 0\n objLogFile.WriteLine \"ERROR: Failed to create a log file.Program execution halted.\"\n WScript.Echo \"ERROR: Failed to create a log file. Program execution halted.\"\n WScript.Quit\n objLogFile.Close\n Set objFSO = Nothing\nElse\n ' Successfully Created Disableeas.log file. Restore normal error handling.\n On Error GoTo 0\n objLogFile.WriteLine \"disableeas.log created successfully\"\nEnd If\n\n\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n'' Determine DNS domain name\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n\nSet objRootDSE = GetObject(\"LDAP://rootDSE\")\nstrDNSDomain = objRootDSE.Get(\"defaultNamingContext\")\nstrBaseOU = \"\" 'SPECIFY AND ORGANIZATIONAL UNIT NAME HERE. FOR EXAMPLE 'OU=Production\nIf Err.Number <> 0 Then\n ' Attempt to bind to Active Directory Failed.\n On Error GoTo 0\n objLogFile.WriteLine \"ERROR: Binding to Active Directory Failed. Program execution halted.\"\n WScript.Echo \"ERROR: Binding to Active Directory Failed. Program execution halted.\"\n WScript.Quit\n objLogFile.Close\n Set objFSO = Nothing\nElse\n ' Active Directory bind successful\n On Error GoTo 0\n objLogFile.WriteLine \"Binding to Active Directory successful\"\nEnd If \n\n\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n'' Setup ADO for Active Directory\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n\nSet objCommand = CreateObject(\"ADODB.Command\")\nSet objConnection = CreateObject(\"ADODB.Connection\")\nobjConnection.Provider = \"ADsDSOObject\"\nobjConnection.Open \"Active Directory Provider\"\nobjCommand.ActiveConnection = objConnection\nIf Err.Number <> 0 Then\n ' Attempt to search Active Directory Failed.\n On Error GoTo 0\n objLogFile.WriteLine \"ERROR: ADO Setup for Active Directory Failed. Program execution halted.\"\n WScript.Echo \"ERROR: ADO Setup for Active Directory Failed. Program execution halted.\"\n WScript.Quit\n objLogFile.Close\n Set objFSO = Nothing\nElse\n ' ADO Active Directory setup successful\n On Error GoTo 0\n objLogFile.WriteLine \"Active Directory setup successful\"\nEnd If \n\n' Test whether an OU is specified.\nIf strBaseOU <> \"\" Then\n strBase=\"<LDAP://\" & strBaseOU & \",\" & strDNSDomain & \">\"\nElse strBase=\"<LDAP://\" & strDNSDomain & \">\"\nEnd If\n'strBase=\"<LDAP://\" & strDNSDomain & \">\"\nwscript.echo strBase\n\n\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n'' Search for users with defined filters\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n\nstrFilter = \"(&(objectCategory=person)(objectClass=user)(!msExchOmaAdminWirelessEnable=5)(mail=*)(userAccountControl=66048))\"\nstrAttributes = \"distinguishedName\"\nstrQuery = strBase & \";\" & strFilter & \";\" & strAttributes & \";subtree\"\nobjCommand.CommandText = strQuery\nobjCommand.Properties(\"Page Size\") = 100\nobjCommand.Properties(\"Timeout\") = 30\nobjCommand.Properties(\"Cache Results\") = False\nSet objRecordSet = objCommand.Execute\nIf Err.Number <> 0 Then\n ' Attempt to search within defined parameters failed.\n On Error GoTo 0\n objLogFile.WriteLine \"Attempt to search within defined parameters failed. Program execution halted.\"\n WScript.Echo \"ERROR: Attempt to search within defined parameters failed. Program execution halted.\"\n WScript.Quit\n objLogFile.Close\n Set objFSO = Nothing\nElse\n ' Active Directory bind successful\n On Error GoTo 0\n objLogFile.WriteLine \"Search within defined parameters was successful\"\nEnd If \n\n\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n'' Enuerate all users\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n\nDo Until objRecordSet.EOF\n strDN = objRecordSet.Fields(\"distinguishedName\")\n Set objUser = GetObject(\"LDAP://\" & strDN)\n On Error Resume Next\n objUser.Get(\"msExchOmaAdminWirelessEnable\")\n On Error GoTo 0\n objUser.Put \"msExchOmaAdminWirelessEnable\", \"5\"\n objUser.SetInfo\n If Err.Number <> 0 Then\n On Error GoTo 0\n objLogFile.Writeline \"ERROR: Unfortunately, the required mobile attribute generated an error can could not be set. Program execution halted.\"\n WScript.Echo \"ERROR: Unfortunately, the required mobile attribute generated an error can could not be set. Program execution halted.\"\n Wscript.Quit\n objLogFile.Close\n Set objFSO = Nothing\n Else\n On Error GoTo 0\n objLogFile.Writeline \"User mobile properties successfully modified: \" & objUser.Name\n Wscript.Echo \"User mobile properties successfully modified: \" & objUser.Name\n End If\n ' End If\n objRecordSet.MoveNext\nLoop\n\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n'' Clean up\n'''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''\n\nobjLogFile.WriteLine \"End Program\"\nWscript.Echo \"End Program\"\n\nobjLogFile.Close\n" }, { "answer_id": 582656, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "Get-CASMailbox -resultsize unlimited | Where-Object {$_.ActiveSyncEnabled -eq \"True\" } | Select-Object SamAccountName,ActiveSyncEnabled" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338428", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18853/" ]
338,436
<p>Is there a command in Git to see (either dumped to stdout, or in <code>$PAGER</code> or <code>$EDITOR</code>) a particular version of a particular file?</p>
[ { "answer_id": 338470, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 11, "selected": false, "text": "git show ./ ../ $ git show REVISION:path/to/file\n REVISION <repository-root>/src/main.c $ git show HEAD~4:src/main.c\n git-show" }, { "answer_id": 13958640, "author": "Trausti Kristjansson", "author_id": 1602016, "author_profile": "https://Stackoverflow.com/users/1602016", "pm_score": 7, "selected": false, "text": "gitk /path/to/file\n" }, { "answer_id": 15277342, "author": "Jim Hunziker", "author_id": 6160, "author_profile": "https://Stackoverflow.com/users/6160", "pm_score": 8, "selected": false, "text": "git show HEAD@{2013-02-25}:./fileInCurrentDirectory.txt\n HEAD@{2013-02-25} git show $(git rev-list -1 --before=\"2013-02-26\" HEAD):./fileInCurrentDirectory.txt\n" }, { "answer_id": 23380081, "author": "Ijas Ameenudeen", "author_id": 567854, "author_profile": "https://Stackoverflow.com/users/567854", "pm_score": 6, "selected": false, "text": "git show HEAD@{2013-02-25}:./fileInCurrentDirectory.txt > old_fileInCurrentDirectory.txt\n" }, { "answer_id": 37080515, "author": "sanbor", "author_id": 967358, "author_profile": "https://Stackoverflow.com/users/967358", "pm_score": 5, "selected": false, "text": "git log -p / enter n p" }, { "answer_id": 40400259, "author": "Adrien Be", "author_id": 759452, "author_profile": "https://Stackoverflow.com/users/759452", "pm_score": 7, "selected": false, "text": "commit hash commit ID git show git show <commitHash>:/path/to/file git log /path/to/file commit hash commit 06c98... commit hash git show <commitHash>:/path/to/file commit hash path/to/file ./ git show b2f8be577166577c59b55e11cfff1404baf63a84:./flight-simulation/src/main/components/nav-horiz.html" }, { "answer_id": 47020586, "author": "Brad Parks", "author_id": 26510, "author_profile": "https://Stackoverflow.com/users/26510", "pm_score": 2, "selected": false, "text": "git_dump_all_versions_of_a_file.sh path/to/somefile.txt\n" }, { "answer_id": 53668072, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 1, "selected": false, "text": "#!/usr/bin/env python3\n\nimport argparse\nimport os\nimport subprocess\n\nparser = argparse.ArgumentParser()\nparser.add_argument('revision')\nparser.add_argument('files', nargs='+')\nargs = parser.parse_args()\ntoplevel = subprocess.check_output(['git', 'rev-parse', '--show-toplevel']).rstrip().decode()\nfor path in args.files:\n file_relative = os.path.relpath(os.path.abspath(path), toplevel)\n base, ext = os.path.splitext(path)\n new_path = base + '.old' + ext\n with open(new_path, 'w') as f:\n subprocess.call(['git', 'show', '{}:./{}'.format(args.revision, path)], stdout=f)\n git-show-save other-branch file1.c path/to/file2.cpp\n file1.old.c\npath/to/file2.old.cpp\n" }, { "answer_id": 53755845, "author": "sachin_ur", "author_id": 9449478, "author_profile": "https://Stackoverflow.com/users/9449478", "pm_score": 6, "selected": false, "text": "git show -1 filename.txt git show -2 filename.txt git show -3 fielname.txt" }, { "answer_id": 59914537, "author": "Andrew___Pls_Support_UA", "author_id": 4423545, "author_profile": "https://Stackoverflow.com/users/4423545", "pm_score": 3, "selected": false, "text": "git reflog git diff-tree --no-commit-id --name-only -r <commitHash> git diff-tree --no-commit-id --name-only -r d2f9ba4 d2f9ba4 git show <commitHash>:/path/to/file git show d2f9ba4:Src/Ext/MoreSwiftUI/ListCustom.swift Src/... git reflog git reset --hard %commit ID% git reset --hard c14809fa" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338436", "https://Stackoverflow.com", "https://Stackoverflow.com/users/91385/" ]
338,445
<p>Please can someone explain what the following statement does in SQL Server 2005:</p> <pre><code>GRANT ALL TO pax_writer </code></pre> <p>pax_writer is a database role previously created using the statement</p> <pre><code>CREATE ROLE pax_writer AUTHORIZATION dbo </code></pre>
[ { "answer_id": 338470, "author": "mipadi", "author_id": 28804, "author_profile": "https://Stackoverflow.com/users/28804", "pm_score": 11, "selected": false, "text": "git show ./ ../ $ git show REVISION:path/to/file\n REVISION <repository-root>/src/main.c $ git show HEAD~4:src/main.c\n git-show" }, { "answer_id": 13958640, "author": "Trausti Kristjansson", "author_id": 1602016, "author_profile": "https://Stackoverflow.com/users/1602016", "pm_score": 7, "selected": false, "text": "gitk /path/to/file\n" }, { "answer_id": 15277342, "author": "Jim Hunziker", "author_id": 6160, "author_profile": "https://Stackoverflow.com/users/6160", "pm_score": 8, "selected": false, "text": "git show HEAD@{2013-02-25}:./fileInCurrentDirectory.txt\n HEAD@{2013-02-25} git show $(git rev-list -1 --before=\"2013-02-26\" HEAD):./fileInCurrentDirectory.txt\n" }, { "answer_id": 23380081, "author": "Ijas Ameenudeen", "author_id": 567854, "author_profile": "https://Stackoverflow.com/users/567854", "pm_score": 6, "selected": false, "text": "git show HEAD@{2013-02-25}:./fileInCurrentDirectory.txt > old_fileInCurrentDirectory.txt\n" }, { "answer_id": 37080515, "author": "sanbor", "author_id": 967358, "author_profile": "https://Stackoverflow.com/users/967358", "pm_score": 5, "selected": false, "text": "git log -p / enter n p" }, { "answer_id": 40400259, "author": "Adrien Be", "author_id": 759452, "author_profile": "https://Stackoverflow.com/users/759452", "pm_score": 7, "selected": false, "text": "commit hash commit ID git show git show <commitHash>:/path/to/file git log /path/to/file commit hash commit 06c98... commit hash git show <commitHash>:/path/to/file commit hash path/to/file ./ git show b2f8be577166577c59b55e11cfff1404baf63a84:./flight-simulation/src/main/components/nav-horiz.html" }, { "answer_id": 47020586, "author": "Brad Parks", "author_id": 26510, "author_profile": "https://Stackoverflow.com/users/26510", "pm_score": 2, "selected": false, "text": "git_dump_all_versions_of_a_file.sh path/to/somefile.txt\n" }, { "answer_id": 53668072, "author": "Ciro Santilli OurBigBook.com", "author_id": 895245, "author_profile": "https://Stackoverflow.com/users/895245", "pm_score": 1, "selected": false, "text": "#!/usr/bin/env python3\n\nimport argparse\nimport os\nimport subprocess\n\nparser = argparse.ArgumentParser()\nparser.add_argument('revision')\nparser.add_argument('files', nargs='+')\nargs = parser.parse_args()\ntoplevel = subprocess.check_output(['git', 'rev-parse', '--show-toplevel']).rstrip().decode()\nfor path in args.files:\n file_relative = os.path.relpath(os.path.abspath(path), toplevel)\n base, ext = os.path.splitext(path)\n new_path = base + '.old' + ext\n with open(new_path, 'w') as f:\n subprocess.call(['git', 'show', '{}:./{}'.format(args.revision, path)], stdout=f)\n git-show-save other-branch file1.c path/to/file2.cpp\n file1.old.c\npath/to/file2.old.cpp\n" }, { "answer_id": 53755845, "author": "sachin_ur", "author_id": 9449478, "author_profile": "https://Stackoverflow.com/users/9449478", "pm_score": 6, "selected": false, "text": "git show -1 filename.txt git show -2 filename.txt git show -3 fielname.txt" }, { "answer_id": 59914537, "author": "Andrew___Pls_Support_UA", "author_id": 4423545, "author_profile": "https://Stackoverflow.com/users/4423545", "pm_score": 3, "selected": false, "text": "git reflog git diff-tree --no-commit-id --name-only -r <commitHash> git diff-tree --no-commit-id --name-only -r d2f9ba4 d2f9ba4 git show <commitHash>:/path/to/file git show d2f9ba4:Src/Ext/MoreSwiftUI/ListCustom.swift Src/... git reflog git reset --hard %commit ID% git reset --hard c14809fa" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3012/" ]
338,450
<p>I am trying to implement the python logging handler <code>TimedRotatingFileHandler</code>.</p> <p>When it rolls over to midnight it appends the current day in the form <code>YYYY-MM-DD</code>.</p> <pre><code>LOGGING_MSG_FORMAT = '%(name)-14s &gt; [%(levelname)s] [%(asctime)s] : %(message)s' LOGGING_DATE_FORMAT = '%Y-%m-%d %H:%M:%S' logging.basicConfig( level=logging.DEBUG, format=LOGGING_MSG_FORMAT, datefmt=LOGGING_DATE_FORMAT ) root_logger = logging.getLogger('') logger = logging.handlers.TimedRotatingFileHandler(&quot;C:\\logs\\Rotate_Test&quot;,'midnight',1) root_logger.addHandler(logger) while True: daemon_logger = logging.getLogger('TEST') daemon_logger.info(&quot;SDFKLDSKLFFJKLSDD&quot;) time.sleep(60) </code></pre> <p>The first log file created is named <code>Rotate_Test</code>, then once it rolls over to the next day it changes the file name to <code>Rotate_Test.YYYY-MM-DD</code> where <code>YYYY-MM-DD</code> is the current day.</p> <p>How can I change how it alters the filename?</p>
[ { "answer_id": 338566, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 7, "selected": true, "text": "logging/handlers.py handler = logging.handlers.TimedRotatingFileHandler(\"C:\\\\isis_ops\\\\logs\\\\Rotate_Test\",'midnight',1)\nhandler.suffix = \"%Y-%m-%d\" # or anything else that strftime will allow\nroot_logger.addHandler(handler)\n" }, { "answer_id": 340429, "author": "UberJumper", "author_id": 34395, "author_profile": "https://Stackoverflow.com/users/34395", "pm_score": 1, "selected": false, "text": "if(current_time > old_time):\n for each in logging.getLogger('Debug').handlers:\n each.stream = open(\"C:\\\\NewOutput\", 'a')\n" }, { "answer_id": 1876171, "author": "Alex The Smarter", "author_id": 228229, "author_profile": "https://Stackoverflow.com/users/228229", "pm_score": 2, "selected": false, "text": "try:\n import codecs\nexcept ImportError:\n codecs = None\nimport logging.handlers\nimport time\nimport os\n\nclass MyTimedRotatingFileHandler(logging.handlers.TimedRotatingFileHandler):\n def __init__(self,dir_log):\n self.dir_log = dir_log\n filename = self.dir_log+time.strftime(\"%m%d%Y\")+\".txt\" #dir_log here MUST be with os.sep on the end\n logging.handlers.TimedRotatingFileHandler.__init__(self,filename, when='midnight', interval=1, backupCount=0, encoding=None)\n def doRollover(self):\n \"\"\"\n TimedRotatingFileHandler remix - rotates logs on daily basis, and filename of current logfile is time.strftime(\"%m%d%Y\")+\".txt\" always\n \"\"\" \n self.stream.close()\n # get the time that this sequence started at and make it a TimeTuple\n t = self.rolloverAt - self.interval\n timeTuple = time.localtime(t)\n self.baseFilename = self.dir_log+time.strftime(\"%m%d%Y\")+\".txt\"\n if self.encoding:\n self.stream = codecs.open(self.baseFilename, 'w', self.encoding)\n else:\n self.stream = open(self.baseFilename, 'w')\n self.rolloverAt = self.rolloverAt + self.interval\n" }, { "answer_id": 32198288, "author": "Timmah", "author_id": 1625688, "author_profile": "https://Stackoverflow.com/users/1625688", "pm_score": 3, "selected": false, "text": "handler.suffix = \"%Y%m%d\"\nhandler.extMatch = re.compile(r\"^\\d{8}$\")\n" }, { "answer_id": 67213458, "author": "codswi", "author_id": 3060777, "author_profile": "https://Stackoverflow.com/users/3060777", "pm_score": 2, "selected": false, "text": "def my_namer(default_name):\n # This will be called when doing the log rotation\n # default_name is the default filename that would be assigned, e.g. Rotate_Test.txt.YYYY-MM-DD\n # Do any manipulations to that name here, for example this changes the name to Rotate_Test.YYYY-MM-DD.txt\n base_filename, ext, date = default_name.split(\".\")\n return f\"{base_filename}.{date}.{ext}\"\n\nlogger = logging.handlers.TimedRotatingFileHandler(\"C:\\\\logs\\\\Rotate_Test\",'midnight',1)\nlogger.namer = my_namer\nroot_logger.addHandler(logger)\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338450", "https://Stackoverflow.com", "https://Stackoverflow.com/users/34395/" ]
338,463
<p>I would like to compare two dates in javascript. I have been doing some research, but all I can find is how to return the current date. I want to compare 2 separate dates, not related to today. How do I do that. </p> <pre><code>var startDate = Date(document.form1.Textbox2); </code></pre>
[ { "answer_id": 338474, "author": "matt b", "author_id": 4249, "author_profile": "https://Stackoverflow.com/users/4249", "pm_score": 9, "selected": true, "text": "if (date1.getTime() > date2.getTime()) {\n alert(\"The first date is after the second date!\");\n}\n" }, { "answer_id": 338480, "author": "Will Wagner", "author_id": 25468, "author_profile": "https://Stackoverflow.com/users/25468", "pm_score": 3, "selected": false, "text": "var someDate = new Date(\"12/03/2008\");\n var someDate = new Date(document.form1.Textbox2.value);\n" }, { "answer_id": 2921118, "author": "Harsh Punnoose", "author_id": 351949, "author_profile": "https://Stackoverflow.com/users/351949", "pm_score": 0, "selected": false, "text": "if(CompareDates(smallDate,largeDate,'-') == 0) {\n alert('Selected date must be current date or previous date!');\nreturn false;\n}\n\nfunction CompareDates(smallDate,largeDate,separator) {\n var smallDateArr = Array();\n var largeDateArr = Array(); \n smallDateArr = smallDate.split(separator);\n largeDateArr = largeDate.split(separator); \n var smallDt = smallDateArr[0];\n var smallMt = smallDateArr[1];\n var smallYr = smallDateArr[2]; \n var largeDt = largeDateArr[0];\n var largeMt = largeDateArr[1];\n var largeYr = largeDateArr[2];\n\n if(smallYr>largeYr) \n return 0;\nelse if(smallYr<=largeYr && smallMt>largeMt)\n return 0;\nelse if(smallYr<=largeYr && smallMt==largeMt && smallDt>largeDt)\n return 0;\nelse \n return 1;\n} \n" }, { "answer_id": 6148942, "author": "Vladimir Shmidt", "author_id": 572612, "author_profile": "https://Stackoverflow.com/users/572612", "pm_score": 4, "selected": false, "text": "new Date('1945/05/09').valueOf() < new Date('2011/05/09').valueOf()\n" }, { "answer_id": 7186579, "author": "SHIBIN FRANCIS", "author_id": 911446, "author_profile": "https://Stackoverflow.com/users/911446", "pm_score": 0, "selected": false, "text": "function d_check() {\n var dl_sdt=document.getElementIdBy(\"date_input_Id1\").value; //date one\n var dl_endt=document.getElementIdBy(\"date_input_Id2\").value; //date two\n\n if((dl_sdt.substr(6,4)) > (dl_endt.substr(6,4))) {\n alert(\"first date is greater\");\n return false;\n }\n\n else if((((dl_sdt.substr(0,2)) > (dl_endt.\n substr(0,2)))&&(frdt(dl_sdt.substr(3,2)) > (dl_endt.substr(3,2))))||\n (((dl_sdt.substr(0,2)) > (dl_endt.substr(0,2)))&&\n ((dl_sdt.substr(3,2)) < (dl_endt.substr(3,2))))||\n (((dl_sdt.substr(0,2)) == (dl_endt.substr(0,2)))&&((dl_sdt.substr(3,2)) > \n (dl_endt.substr(3,2))))) {\n alert(\"first date is greater\");\n return false;\n }\n\n alert(\"second date is digher\");\n return true;\n}\n" }, { "answer_id": 8568299, "author": "Stephen Moreno", "author_id": 1106800, "author_profile": "https://Stackoverflow.com/users/1106800", "pm_score": 1, "selected": false, "text": "function fn_DateCompare(DateA, DateB) { // this function is good for dates > 01/01/1970\n\n var a = new Date(DateA);\n var b = new Date(DateB);\n\n var msDateA = Date.UTC(a.getFullYear(), a.getMonth()+1, a.getDate());\n var msDateB = Date.UTC(b.getFullYear(), b.getMonth()+1, b.getDate());\n\n if (parseFloat(msDateA) < parseFloat(msDateB))\n return -1; // lt\n else if (parseFloat(msDateA) == parseFloat(msDateB))\n return 0; // eq\n else if (parseFloat(msDateA) > parseFloat(msDateB))\n return 1; // gt\n else\n return null; // error\n}\n" }, { "answer_id": 10879087, "author": "priyanka gaby", "author_id": 1434522, "author_profile": "https://Stackoverflow.com/users/1434522", "pm_score": 0, "selected": false, "text": " function validateform()\n {\n if (trimAll(document.getElementById(\"<%=txtFromDate.ClientID %>\").value) != \"\") {\n if (!isDate(trimAll(document.getElementById(\"<%=txtFromDate.ClientID %>\").value)))\n msg = msg + \"<li>Please enter valid From Date in mm/dd/yyyy format\\n\";\n else {\n var toDate = new Date();\n var txtdate = document.getElementById(\"<%=txtFromDate.ClientID %>\").value;\n var d1 = new Date(txtdate)\n if (Date.parse(txtdate) > Date.parse(toDate)) { \n msg = msg + \"<li>From date must be less than or equal to today's date\\n\";\n }\n }\n}\n\n if (trimAll(document.getElementById(\"<%=txtToDate.ClientID %>\").value) != \"\") {\n if (!isDate(trimAll(document.getElementById(\"<%=txtToDate.ClientID %>\").value)))\n msg = msg + \"<li>Please enter valid To Date in mm/dd/yyyy format\\n\";\n else {\n var toDate = new Date();\n var txtdate = document.getElementById(\"<%=txtToDate.ClientID %>\").value;\n var d1 = new Date(txtdate)\n\n if (Date.parse(txtdate) > Date.parse(toDate)) {\n msg = msg + \"<li>To date must be less than or equal to today's date\\n\"; \n }\n }\n }\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338463", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
338,472
<p>I have a list box control:</p> <pre> <code> &lt;asp:ListBox runat="server" id="lbox" autoPostBack="true" /> </code> </pre> <p>The code behind resembles:</p> <pre> <code> private void Page_Load(object sender, System.EventArgs e) { lbox.SelectedIndexChanged+=new EventHandler(lbox_SelectedIndexChanged); if(!Page.IsPostBack) { LoadData(); } } private LoadData() { lbox.DataSource = foo(); lbox.DataBind(); } protected void lboxScorecard_SelectedIndexChanged(object sender, EventArgs e) { int index = (sender as ListBox).selectedIndex; } </code> </pre> <p>My problem is that when my page receives a post back (when a user makes a selection in the listbox), the selection always "jumps" to the first item in the listbox, so that the index variable in my callback function is always 0.</p> <p>Seems like this may be a viewstate problem? How can I fix it so that the selection index remains through the postback?</p> <p>There is no ajax going on, this is .NET 1.0.</p> <p>Thanks.</p> <p><strong>EDIT 1</strong> JohnIdol has gotten me a step closer, If I switch the datasource from my original DataTable to an ArrayList, then everything work properly...what would cause this?</p> <p><strong>Edit 2</strong> It turns out that my DataTable had multiple values that were the same, so that the indexes were treated as the same as all items with the same value...thanks to those who helped!</p>
[ { "answer_id": 338513, "author": "Briggie Smalls", "author_id": 9559, "author_profile": "https://Stackoverflow.com/users/9559", "pm_score": -1, "selected": false, "text": "<asp:ListBox runat=\"server\" id=\"lbox\" autoPostBack=\"true\" OnSelectedIndexChanged=\"lboxScorecard_SelectedIndexChanged\" />\n" }, { "answer_id": 338527, "author": "HectorMac", "author_id": 1400, "author_profile": "https://Stackoverflow.com/users/1400", "pm_score": 0, "selected": false, "text": "<asp:ListBox runat=\"server\" id=\"lbox\" autoPostBack=\"true\" OnSelectedIndexChanged=\"lbox_SelectedIndexChanged\" />\n protected void lbox_SelectedIndexChanged(object sender, EventArgs e)\n{\n int index = lbox.selectedIndex;\n}\n" }, { "answer_id": 338693, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 1, "selected": false, "text": "foreach (Item i in DataSet)\n{\n listBox.Items.Add(etc);\n}\n" }, { "answer_id": 8254390, "author": "Mohit", "author_id": 1063563, "author_profile": "https://Stackoverflow.com/users/1063563", "pm_score": 2, "selected": false, "text": "item.value item.text" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338472", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1638/" ]
338,482
<p>Is there a way to do your timezone offsets on the server side, by reading something in the request over http, instead of sending everything to the client and letting it deal with it?</p>
[ { "answer_id": 388219, "author": "devstuff", "author_id": 41321, "author_profile": "https://Stackoverflow.com/users/41321", "pm_score": 6, "selected": true, "text": "\n<script type=\"text/javascript\" language=\"JavaScript\">\nvar offset = new Date();\ndocument.write('<input type=\"hidden\" id=\"clientTzOffset\" name=\"clientTzOffset\" value=\"' + offset.getTimezoneOffset() + '\"/>');\n</script>\n" }, { "answer_id": 27289822, "author": "Kiran", "author_id": 2075792, "author_profile": "https://Stackoverflow.com/users/2075792", "pm_score": 0, "selected": false, "text": "private TimeZoneInfo GetRequestTimeZone()\n {\n TimeZoneInfo timeZoneInfo = null;\n DateTimeOffset localDateOffset;\n try\n {\n localDateOffset = new DateTimeOffset(Request.RequestContext.HttpContext.Timestamp, Request.RequestContext.HttpContext.Timestamp - Request.RequestContext.HttpContext.Timestamp.ToUniversalTime());\n timeZoneInfo = (from x in TimeZoneInfo.GetSystemTimeZones()\n where x.BaseUtcOffset == localDateOffset.Offset\n select x).FirstOrDefault();\n }\n catch (Exception)\n {\n }\n return timeZoneInfo;\n }\n" }, { "answer_id": 38785677, "author": "Mike Gledhill", "author_id": 391605, "author_profile": "https://Stackoverflow.com/users/391605", "pm_score": 0, "selected": false, "text": "getListOfRecords $scope.loadSomeDatabaseRecords = function () {\n\n var d = new Date()\n var timezoneOffset = d.getTimezoneOffset();\n\n return $http({\n url: 'http://localhost:15021/Service1.svc/getListOfRecords/' + timezoneOffset,\n method: 'GET',\n async: true,\n cache: false,\n headers: { 'Accept': 'application/json', 'Pragma': 'no-cache' }\n }).success(function (data) {\n $scope.listScheduleLog = data.Results;\n });\n}\n DateTime" }, { "answer_id": 63790779, "author": "Simple Code", "author_id": 8618595, "author_profile": "https://Stackoverflow.com/users/8618595", "pm_score": 0, "selected": false, "text": "var clientOffset = getCookie(\"_clientOffset\");\nvar currentOffset = new Date().getTimezoneOffset() * -1;\nvar reloadForCookieRefresh = false;\n\nif (clientOffset == undefined || clientOffset == null || clientOffset != currentOffset) {\n setCookie(\"_clientOffset\", currentOffset, 30);\n reloadForCookieRefresh = true;\n}\n\nif (reloadForCookieRefresh)\n window.location.reload();\n\nfunction setCookie(name, value, days) {\n var expires = \"\";\n if (days) {\n var date = new Date();\n date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));\n expires = \"; expires=\" + date.toUTCString();\n }\n document.cookie = name + \"=\" + (value || \"\") + expires + \"; path=/\";\n}\n\nfunction getCookie(name) {\n var nameEQ = name + \"=\";\n var ca = document.cookie.split(';');\n for (var i = 0; i < ca.length; i++) {\n var c = ca[i];\n while (c.charAt(0) == ' ') c = c.substring(1, c.length);\n if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);\n }\n return null;\n}\n public class SetCurrentRequestDataFilter : ActionFilterAttribute\n{\n public override void OnActionExecuting(ActionExecutingContext context)\n {\n // currentRequestService is registered by request using IoC container\n var currentRequestService = iocResolver.Resolve<ICurrentRequestService>();\n\n if (context.HttpContext.Request.Cookies.AllKeys.Contains(\"_clientOffset\"))\n {\n currentRequestService.ClientOffset = int.Parse(context.HttpContext.Request.Cookies.Get(\"_clientOffset\").Value);\n }\n\n }\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338482", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1220/" ]
338,483
<p>I'm on Windows Vista and IE7.</p> <p>Here's what I'd like to do:</p> <ol> <li>I have two flash files: <code>page1.swf</code> and <code>page2.swf</code>. They are just page from a magazine.</li> <li>Display <code>page1.swf</code></li> <li>Have a button that says "Change page"</li> <li>When I click the button; display <code>page2.swf</code> instead of <code>page1.swf</code> (only <code>page2.swf</code>, not both pages) That's it. </li> </ol> <p>If anyone can give me a script to do that I would greatly appreciate it.</p>
[ { "answer_id": 388219, "author": "devstuff", "author_id": 41321, "author_profile": "https://Stackoverflow.com/users/41321", "pm_score": 6, "selected": true, "text": "\n<script type=\"text/javascript\" language=\"JavaScript\">\nvar offset = new Date();\ndocument.write('<input type=\"hidden\" id=\"clientTzOffset\" name=\"clientTzOffset\" value=\"' + offset.getTimezoneOffset() + '\"/>');\n</script>\n" }, { "answer_id": 27289822, "author": "Kiran", "author_id": 2075792, "author_profile": "https://Stackoverflow.com/users/2075792", "pm_score": 0, "selected": false, "text": "private TimeZoneInfo GetRequestTimeZone()\n {\n TimeZoneInfo timeZoneInfo = null;\n DateTimeOffset localDateOffset;\n try\n {\n localDateOffset = new DateTimeOffset(Request.RequestContext.HttpContext.Timestamp, Request.RequestContext.HttpContext.Timestamp - Request.RequestContext.HttpContext.Timestamp.ToUniversalTime());\n timeZoneInfo = (from x in TimeZoneInfo.GetSystemTimeZones()\n where x.BaseUtcOffset == localDateOffset.Offset\n select x).FirstOrDefault();\n }\n catch (Exception)\n {\n }\n return timeZoneInfo;\n }\n" }, { "answer_id": 38785677, "author": "Mike Gledhill", "author_id": 391605, "author_profile": "https://Stackoverflow.com/users/391605", "pm_score": 0, "selected": false, "text": "getListOfRecords $scope.loadSomeDatabaseRecords = function () {\n\n var d = new Date()\n var timezoneOffset = d.getTimezoneOffset();\n\n return $http({\n url: 'http://localhost:15021/Service1.svc/getListOfRecords/' + timezoneOffset,\n method: 'GET',\n async: true,\n cache: false,\n headers: { 'Accept': 'application/json', 'Pragma': 'no-cache' }\n }).success(function (data) {\n $scope.listScheduleLog = data.Results;\n });\n}\n DateTime" }, { "answer_id": 63790779, "author": "Simple Code", "author_id": 8618595, "author_profile": "https://Stackoverflow.com/users/8618595", "pm_score": 0, "selected": false, "text": "var clientOffset = getCookie(\"_clientOffset\");\nvar currentOffset = new Date().getTimezoneOffset() * -1;\nvar reloadForCookieRefresh = false;\n\nif (clientOffset == undefined || clientOffset == null || clientOffset != currentOffset) {\n setCookie(\"_clientOffset\", currentOffset, 30);\n reloadForCookieRefresh = true;\n}\n\nif (reloadForCookieRefresh)\n window.location.reload();\n\nfunction setCookie(name, value, days) {\n var expires = \"\";\n if (days) {\n var date = new Date();\n date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));\n expires = \"; expires=\" + date.toUTCString();\n }\n document.cookie = name + \"=\" + (value || \"\") + expires + \"; path=/\";\n}\n\nfunction getCookie(name) {\n var nameEQ = name + \"=\";\n var ca = document.cookie.split(';');\n for (var i = 0; i < ca.length; i++) {\n var c = ca[i];\n while (c.charAt(0) == ' ') c = c.substring(1, c.length);\n if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);\n }\n return null;\n}\n public class SetCurrentRequestDataFilter : ActionFilterAttribute\n{\n public override void OnActionExecuting(ActionExecutingContext context)\n {\n // currentRequestService is registered by request using IoC container\n var currentRequestService = iocResolver.Resolve<ICurrentRequestService>();\n\n if (context.HttpContext.Request.Cookies.AllKeys.Contains(\"_clientOffset\"))\n {\n currentRequestService.ClientOffset = int.Parse(context.HttpContext.Request.Cookies.Get(\"_clientOffset\").Value);\n }\n\n }\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338483", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39973/" ]
338,499
<p>I would (as the question states) like to make an asynchronous call, preferably using ASP.net AJAX.</p> <p>The code for the WebMethod looks like this:</p> <pre><code>[WebMethod] public void SendMail(string name, string email, string subject, string body) { MailMessage toSend = new MailMessage(email, address@domain.com, subject, body); var smtp = new SmtpClient(); smtp.Send(toSend); } </code></pre> <p>The fields on the view are, not surprisingly: name, email, subject, body.</p> <p>In my attempts to do this I haven't been able to get to the WebMethod. The service reference is in place, so at least I didn't screw that up. </p> <p>Thanks for the help...</p>
[ { "answer_id": 338572, "author": "mapache", "author_id": 41422, "author_profile": "https://Stackoverflow.com/users/41422", "pm_score": 1, "selected": true, "text": "<% using (Ajax.Form(\"SendMail\", new AjaxOptions { UpdateTargetId = \"resultDiv\" })) { %>\n\n <!-- Your form elements here... -->\n\n<% } %>\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13139/" ]
338,516
<p>I am living on the other side of the world from my home (GMT+1 now, GMT+13 is home), and I miss my old terrestrial radio station. It has a Shoutcast stream, and I would like to simply delay it by 12 hours so that it is always available when I want to listen to it, in a way that would make its timezone be synchronised to my timezone.</p> <p>I envision this as a script being run on my server host.</p> <p>A naive approach would simply be to allocate enough ram in a ringbuffer to store the entire 12 hour delay, and pipe in the output from streamripper. But the stream is a 128kbps mp3, which would mean (128/8) * 60 * 60 = ~56MB per hour, or 675MB for the whole 12 hour buffer, which isn't really so practical. Plus, i might have to deal with my server host just killing the process after a certain timeout.</p> <p>So, what are some strategies that might actually be practical?</p>
[ { "answer_id": 340750, "author": "damian", "author_id": 42961, "author_profile": "https://Stackoverflow.com/users/42961", "pm_score": 0, "selected": false, "text": "#!/usr/bin/python\nimport time\nimport urllib\nimport datetime\nimport os\nimport socket\n\n# number of seconds for each file\nFILE_SECONDS = 300\n\n# run for 30 minutes\nRUN_TIME = 60*30\n\n# size in bytes of each read block\n# 16384 = 1 second\nBLOCK_SIZE = 16384\n\nMAX_TIMEOUTS = 10\n\n# where to save the files\nOUTPUT_DIRECTORY = \"dir/\"\n# URL for original stream\nURL = \"http://url/path:port\"\n\ndebug = True\nlog = None\nsocket.setdefaulttimeout(10)\n\nclass DatestampedWriter:\n\n # output_path MUST have trailing '/'\n def __init__(self, output_path, run_seconds ):\n self.path = output_path\n self.file = None\n # needs to be -1 to avoid issue when 0 is a real timestamp\n self.curr_timestamp = -1\n self.running = False\n # don't start until the _end_ of the current time block\n # so calculate an initial timestamp as (now+FILE_SECONDS)\n self.initial_timestamp = self.CalcTimestamp( FILE_SECONDS )\n self.final_timestamp = self.CalcTimestamp( run_seconds )\n if debug:\n log = open(OUTPUT_DIRECTORY+\"log_\"+str(self.initial_timestamp)+\".txt\",\"w\")\n log.write(\"initial timestamp \"+str(self.initial_timestamp)+\", final \"+str(self.final_timestamp)+\" (diff \"+str(self.final_timestamp-self.initial_timestamp)+\")\\n\")\n\n self.log = log\n\n def Shutdown(self):\n if self.file != None:\n self.file.close()\n\n # write out buf\n # returns True when we should stop\n def Write(self, buf):\n # check that we have the correct file open\n\n # get timestamp\n timestamp = self.CalcTimestamp()\n\n if not self.running :\n # should we start?\n if timestamp == self.initial_timestamp:\n if debug:\n self.log.write( \"starting running now\\n\" )\n self.log.flush()\n self.running = True\n\n # should we open a new file?\n if self.running and timestamp != self.curr_timestamp:\n if debug:\n self.log.write( \"new timestamp \"+str(timestamp)+\"\\n\" )\n self.log.flush()\n # close old file\n if ( self.file != None ):\n self.file.close()\n # time to stop?\n if ( self.curr_timestamp == self.final_timestamp ):\n if debug:\n self.log.write( \" -- time to stop\\n\" )\n self.log.flush()\n self.running = False\n return True\n # open new file\n filename = self.path+str(timestamp)+\".str\"\n #if not os.path.exists(filename):\n self.file = open(filename, \"w\")\n self.curr_timestamp = int(timestamp)\n #else:\n # uh-oh\n # if debug:\n # self.log.write(\" tried to open but failed, already there\\n\")\n # self.running = False\n\n # now write bytes\n if self.running:\n #print(\"writing \"+str(len(buf)))\n self.file.write( buf )\n\n return False\n\n def CalcTimestamp(self, seconds_offset=0):\n t = datetime.datetime.now()\n seconds = time.mktime(t.timetuple())+seconds_offset\n # FILE_SECONDS intervals, 24 hour days\n timestamp = seconds - ( seconds % FILE_SECONDS )\n timestamp = timestamp % 86400\n return int(timestamp)\n\n\nwriter = DatestampedWriter(OUTPUT_DIRECTORY, RUN_TIME)\n\nwriter_finished = False\n\n# while been running for < (RUN_TIME + 5 minutes)\nnow = time.mktime(datetime.datetime.now().timetuple())\nstop_time = now + RUN_TIME + 5*60\nwhile not writer_finished and time.mktime(datetime.datetime.now().timetuple())<stop_time:\n\n now = time.mktime(datetime.datetime.now().timetuple())\n\n # open the stream\n if debug:\n writer.log.write(\"opening stream... \"+str(now)+\"/\"+str(stop_time)+\"\\n\")\n writer.log.flush()\n try:\n u = urllib.urlopen(URL)\n except socket.timeout:\n if debug:\n writer.log.write(\"timed out, sleeping 60 seconds\\n\")\n writer.log.flush()\n time.sleep(60)\n continue\n except IOError:\n if debug:\n writer.log.write(\"IOError, sleeping 60 seconds\\n\")\n writer.log.flush()\n time.sleep(60)\n continue\n # read 1 block of input\n buf = u.read(BLOCK_SIZE)\n\n timeouts = 0\n while len(buf) > 0 and not writer_finished and now<stop_time and timeouts<MAX_TIMEOUTS:\n # write to disc\n writer_finished = writer.Write(buf)\n\n # read 1 block of input\n try:\n buf = u.read(BLOCK_SIZE)\n except socket.timeout:\n # catch exception but do nothing about it\n if debug:\n writer.log.write(\"read timed out (\"+str(timeouts)+\")\\n\")\n writer.log.flush()\n timeouts = timeouts+1\n\n now = time.mktime(datetime.datetime.now().timetuple())\n # stream has closed,\n if debug:\n writer.log.write(\"read loop bailed out: timeouts \"+str(timeouts)+\", time \"+str(now)+\"\\n\")\n writer.log.flush()\n u.close();\n # sleep 1 second before trying to open the stream again\n time.sleep(1)\n\n now = time.mktime(datetime.datetime.now().timetuple())\n\nwriter.Shutdown()\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42961/" ]
338,518
<p>In my JSP I need to test two objects using the <code>equals()</code> method. Is there a way to do this using EL, JSTL, or another tag library? I am not allowed to use scriptlets due to team rules.</p> <p>I tried to use the JSTL <code>&lt;c:if&gt;</code> tag, but it only seems to use the <code>==</code> operator.</p>
[ { "answer_id": 338671, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": true, "text": "== eq equals ${a == b}" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338518", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42962/" ]
338,537
<p>Is there a way to specify a one dimensional array in a ini file. </p> <p>so in my ini I would like to do</p> <p>someproperty = [array of something]</p> <p>I am using <code>Zend_Config_Ini</code> config adapter (I prefer ini for base configuration). </p>
[ { "answer_id": 338568, "author": "Alister Bulman", "author_id": 6216, "author_profile": "https://Stackoverflow.com/users/6216", "pm_score": 6, "selected": true, "text": "someproperty[] = a\nsomeproperty[] = b\nsomeproperty[] = c\nsomeproperty[] = d\nsomeproperty[] = e\n" }, { "answer_id": 339135, "author": "Alister Bulman", "author_id": 6216, "author_profile": "https://Stackoverflow.com/users/6216", "pm_score": 3, "selected": false, "text": "some.a[] = a\nsome.a[] = b\nsome.b[] = c\n array('some' => array('a' => array(0 => 'a',\n 1 => 'b'),\n 'b' => array(0 => 'c')\n ));\n" }, { "answer_id": 10425315, "author": "maček", "author_id": 184600, "author_profile": "https://Stackoverflow.com/users/184600", "pm_score": 3, "selected": false, "text": "foo[bar] = 5\nfoo[baz] = 6\nhello[world] = 7\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338537", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35505/" ]
338,541
<p>I'm extending the Gridview Web Control as my first attempt at creating a custom control.</p> <p>As part of the extension I am encapsulating the localization of the grid column headers within the control. Among others, I'm exposing a couple of properties to enable this feature:</p> <p>bool AutoLocalizeColumnHeaders - enables the feature</p> <p>string HeaderResourceFile - identifies a strongly typed resource class from which to get the header text</p> <p>I'm overriding the OnRowDataBound handler and getting the appropriate ResourceManager using Reflection to populate the header text. This is all working nicely but I would like to display a list of the available Strongly Typed Resource Classes in the Property window for the user to choose from, rather than them having to type in the name manually.</p> <p>I've created a TypeConverter for displaying a dropdown in which to display the available classes but can't work out how to get the list of available class names to display?</p> <p>I've been trying for quite a while now without success and am at the point of losing my sanity. I'm assuming that there must be some way to achieve this using Reflection?</p>
[ { "answer_id": 344898, "author": "Graham Watson", "author_id": 42964, "author_profile": "https://Stackoverflow.com/users/42964", "pm_score": 1, "selected": false, "text": "String[] resourceClassNames = (from type in assembly.GetTypes()\n where type.IsClass && type.Namespace.Equals(\"Resources\")\n select type.Name).ToArray();\n public override object EditValue(ITypeDescriptorContext context, \n IServiceProvider provider, object value)\n{\n // Check if all the expected parameters are here\n if (context == null || context.Instance == null || provider == null)\n {\n // returning with the received value\n return base.EditValue(context, provider, value);\n }\n\n // Create the Discovery Service which will find all of the available classes\n ITypeDiscoveryService discoveryService = (ITypeDiscoveryService)provider.GetService(typeof(ITypeDiscoveryService));\n // This service will handle the DropDown functionality in the Property Grid\n _wfes = provider.GetService(typeof(IWindowsFormsEditorService)) as IWindowsFormsEditorService;\n\n // Create the DropDown control for displaying in the Properties Grid\n System.Windows.Forms.ListBox selectionControl = new System.Windows.Forms.ListBox();\n // Attach an eventhandler to close the list after an item has been selected\n selectionControl.SelectedIndexChanged += new EventHandler(selectionControl_SelectedIndexChanged);\n // Get all of the available types\n ICollection colTypes = discoveryService.GetTypes(typeof(object), true);\n // Enumerate the types and add the strongly typed\n // resource class names to the selectionControl\n foreach (Type t in colTypes)\n {\n if (t.IsClass && t.Namespace.Equals(\"Resources\"))\n {\n selectionControl.Items.Add(t.Name);\n }\n }\n if (selectionControl.Items.Count == 0)\n {\n selectionControl.Items.Add(\"No Resources found\");\n }\n // Display the UI editor combo\n _wfes.DropDownControl(selectionControl);\n\n // Return the new property value from the UI editor combo\n if (selectionControl.SelectedItem != null)\n {\n return selectionControl.SelectedItem.ToString();\n }\n else\n {\n return base.EditValue(context, provider, value);\n }\n}\n\nvoid selectionControl_SelectedIndexChanged(object sender, EventArgs e)\n{\n _wfes.CloseDropDown();\n}\n" }, { "answer_id": 347655, "author": "Graham Watson", "author_id": 42964, "author_profile": "https://Stackoverflow.com/users/42964", "pm_score": 0, "selected": false, "text": " // Get all of the available types\n System.Collections.ICollection colTypes = discoveryService.GetTypes(typeof(object), true);\n // Enumerate the types and add the strongly typed resource class names to the selectionControl\n foreach (Type t in colTypes)\n {\n if (t.IsClass && t.Namespace.Equals(\"Resources\"))\n {\n selectionControl.Items.Add(t.Name);\n }\n }\n // Get all of the available class names from the Resources namespace\n var resourceClassNames = from Type t in discoveryService.GetTypes(typeof(object), true)\n where t.IsClass && t.Namespace.Equals(\"Resources\")\n select t.Name;\n\n selectionControl.Items.AddRange(resourceClassNames.ToArray());\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338541", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42964/" ]
338,559
<p>I want to build a toolchain from gnuarm.org from sources. I don't want to use binary version because i'm running x64 linux. Can you point me to some kind of tutorial?</p>
[ { "answer_id": 344187, "author": "Tuminoid", "author_id": 40657, "author_profile": "https://Stackoverflow.com/users/40657", "pm_score": 2, "selected": true, "text": "sudo apt-get install libx11-dev\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338559", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42968/" ]
338,561
<p>I have a Visual Studio 2005 solution (.sln) with a mix of .NET and C++ projects. What is the best way to generate the .build file I will need to run my build process with NAnt. I'm new to using NAnt, and I'm not sure how to set it up. Will I have to update the .build file manually every time there is a new source file in any of the projects? Is there a tool that will generate the files for NAnt from the .sln and studio project files?</p>
[ { "answer_id": 338599, "author": "Mike Marshall", "author_id": 29798, "author_profile": "https://Stackoverflow.com/users/29798", "pm_score": 3, "selected": true, "text": "msbuild.exe /p:Configuration=Debug /t:rebuild MySolution.sln\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338561", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1363/" ]
338,563
<p>I have a Javascript that changes the host in links to match the current development/test server.</p> <p>Here's an example:</p> <pre><code>var ndomain = document.domain; var mydomain = 'www.foo.com'; var alink = document.getElementsByTagName('a'); for (var i = 0; i &lt; alink.length; i++) { if (alink[i].href.length &gt; 0){ if (alink[i].host.substr(0, mydomain.length) == mydomain){ alink[i].host = ndomain; } } } </code></pre> <p>This changes references to <em><a href="http://www.foo.com/page.html" rel="nofollow noreferrer">http://www.foo.com/page.html</a></em> to <em><a href="http://level1.test.foo.com/page.html" rel="nofollow noreferrer">http://level1.test.foo.com/page.html</a></em>.</p> <p>This works in every browser I've tested except Safari (Mac or Win). I've searched and searched for information as to why and the closest reason I've come up with is the "same-origin policy".</p> <p>Based upon my understanding of the same-origin policy, this should work because everything is under the <em>foo.com</em> domain. Could Safari be more strict in the fact that I'm going to a two level subdomain (e.g.<em>level1.test</em>)?</p> <p>Can someone advise as to why this process doesn't work in Safari or how I can get it to work in Safari?</p> <p>TIA!</p>
[ { "answer_id": 338599, "author": "Mike Marshall", "author_id": 29798, "author_profile": "https://Stackoverflow.com/users/29798", "pm_score": 3, "selected": true, "text": "msbuild.exe /p:Configuration=Debug /t:rebuild MySolution.sln\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338563", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42969/" ]
338,567
<p>I currently have a gridview that has an asp:ButtonField as one of the columns. The event handler for the command extracts the row id of the gridview from the command argument and uses that to perform some logic. I now need to switch to using a template field for this column, and want to do something like this:</p> <pre><code>&lt;asp:TemplateField HeaderText="Action"&gt; &lt;ItemStyle HorizontalAlign="Center" /&gt; &lt;ItemTemplate&gt; &lt;asp:LinkButton CommandName="myaction" CommandArgument="&lt;%#Eval("id")%&gt;" Text="do action" runat="server"/&gt; &lt;/ItemTemplate&gt; &lt;/asp:TemplateField&gt; </code></pre> <p>My problem is with the CommandArgument attribute - I don't know how to get it to be the row id from the GridView. Eval("id") doesn't work - does anyone know what the name of the row id property is? Or a better way to do this?</p>
[ { "answer_id": 6610819, "author": "Cla", "author_id": 833151, "author_profile": "https://Stackoverflow.com/users/833151", "pm_score": 1, "selected": false, "text": "CommandArgument=\"<%# CType(Container, GridViewRow).RowIndex %>\"\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2327/" ]
338,598
<p>I have a couple of lines of trivial code such as the following:</p> <pre><code>NSData *dataReply; NSString *stringReply; dataReply = [NSURLConnection sendSynchronousRequest:request returningResponse:&amp;response error:&amp;error]; stringReply = [[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding]; </code></pre> <p>The problem here is, initWithData:encoding: does not return an instance of NSString as the documentation claims it does. I've tried doing an explicit cast using (NSString *) as well without much luck. This is giving me compiler warnings when I try to pass the stringReply to a method I've written with type mismatches. Given I treat all warnings as errors, I'd really like to understand what stringReply is being returned as and how I can enforce it to be of type NSString.</p>
[ { "answer_id": 338646, "author": "Max Stewart", "author_id": 18338, "author_profile": "https://Stackoverflow.com/users/18338", "pm_score": 0, "selected": false, "text": "const char* os = \"12345\";\nNSString* str = [[NSString alloc] initWithData:[NSData dataWithBytes:os length:5 ] encoding:NSUTF8StringEncoding]; \nNSLog(@\"%@\", str);\n" }, { "answer_id": 339132, "author": "Matt Gallagher", "author_id": 36103, "author_profile": "https://Stackoverflow.com/users/36103", "pm_score": 3, "selected": false, "text": "SomeClass *someObject;\nNSString *stringReply;\nstringReply = [[NSString alloc] initWithData:dataReply encoding:NSUTF8StringEncoding];\n[someObject methodWithString:stringReply];\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338598", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40882/" ]
338,616
<p>i have a link to a media file such as an mp3, and i want it to get downloaded when the user clicks on it, instead of just having the file get played. the page i have in mind is just a plain static html page.</p> <p>any ideas?</p>
[ { "answer_id": 338632, "author": "Stepan Mazurov", "author_id": 40786, "author_profile": "https://Stackoverflow.com/users/40786", "pm_score": 3, "selected": false, "text": "Content-disposition: attachment; filename=fname.ext" }, { "answer_id": 338644, "author": "mapache", "author_id": 41422, "author_profile": "https://Stackoverflow.com/users/41422", "pm_score": 0, "selected": false, "text": "document.execCommand('SaveAs')" }, { "answer_id": 27596602, "author": "Vivek Kumar", "author_id": 571156, "author_profile": "https://Stackoverflow.com/users/571156", "pm_score": 0, "selected": false, "text": "<a href=\"linkto.mp3\" download>Download MP3 File </a>\n" }, { "answer_id": 27596645, "author": "Makaze", "author_id": 1166904, "author_profile": "https://Stackoverflow.com/users/1166904", "pm_score": 0, "selected": false, "text": "download <a href=\"file.mp3\" download=\"Song_Name.mp3\">Download</a>\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338616", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4444/" ]
338,624
<p>I am making an HTTP connection to an IIS web server and sending a POST request with the data encoded using Transfer-Encoding: chunked. When I do this, IIS simply closes the connection, with no error message or status code. According to the <a href="https://www.rfc-editor.org/rfc/rfc2616#section-3.6.1" rel="nofollow noreferrer">HTTP 1.1 spec</a>,</p> <blockquote> <p>All HTTP/1.1 applications MUST be able to receive and decode the &quot;chunked&quot; transfer-coding</p> </blockquote> <p>so I don't understand why it's (a) not handling that encoding and (b) it's not sending back a status code. If I change the request to send the Content-Length rather than Transfer-Encoding, the query succeeds, but that's not always possible.</p> <p>When I try the same thing against Apache, I get a &quot;411 Length required&quot; status and a message saying &quot;chunked Transfer-Encoding forbidden&quot;.</p> <p>Why do these servers not support this encoding?</p>
[ { "answer_id": 1208775, "author": "rupello", "author_id": 635, "author_profile": "https://Stackoverflow.com/users/635", "pm_score": 3, "selected": false, "text": "curl <upload-url> --form \"upfile=@<local_file>\" --header \"Transfer-Encoding: chunked\"\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338624", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1821/" ]
338,628
<p>I'm trying to write a TCustomDBGrid descendant that's designed to feel like a TListBox. One of the things I want to change is the Options property's defaults. TCustomDBGrid defines Options as:</p> <pre><code>property Options: TDBGridOptions read FOptions write SetOptions default [dgEditing, dgTitles, dgIndicator, dgColumnResize, dgColLines, dgRowLines, dgTabs, dgConfirmDelete, dgCancelOnExit]; </code></pre> <p>Trying to override that in my class with</p> <pre><code> property Options: TDBGridOptions default [dgTitles, dgTabs, dgRowSelect, dgAlwaysShowSelection, dgCancelOnExit]; </code></pre> <p>doesn't work; the compiler expects <strong>read</strong> or <strong>write</strong> after the type, not <strong>default</strong>. Problem is, FOptions and SetOptions are both defined as private, not protected, in TCustomDBGrid.</p> <p>Do I have to write my own get and set methods that invoke "<strong>inherited</strong> Options", or is there a simpler way to do this?</p>
[ { "answer_id": 338640, "author": "Lars Truijens", "author_id": 1242, "author_profile": "https://Stackoverflow.com/users/1242", "pm_score": 4, "selected": true, "text": "property Options default [dgTitles, dgTabs, dgRowSelect, dgAlwaysShowSelection, dgCancelOnExit];\n" }, { "answer_id": 338831, "author": "Fabricio Araujo", "author_id": 10300, "author_profile": "https://Stackoverflow.com/users/10300", "pm_score": 2, "selected": false, "text": "constructor Create(Aowner:TComponent);\nbegin \n inherited;\n Options := [dgTitles, dgTabs, dgRowSelect, dgAlwaysShowSelection, dgCancelOnExit];\nend;\n property Options default [dgTitles, dgTabs, dgRowSelect, dgAlwaysShowSelection, \n dgCancelOnExit];\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338628", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32914/" ]
338,657
<p>I'm working on a web app that needs an ActiveX control to function. It installs just fine when the user has admin privileges, but fails to load otherwise. Is this by design and if so, is this documented somewhere? (preferably MSDN)</p>
[ { "answer_id": 7473437, "author": "taxilian", "author_id": 229998, "author_profile": "https://Stackoverflow.com/users/229998", "pm_score": 3, "selected": true, "text": "AtlSetPerUserRegistration(perUser);\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338657", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4086/" ]
338,658
<p>Can you round a .NET <code>TimeSpan</code> object?</p> <p>I have a <code>Timespan</code> value of: 00:00:00.6193789</p> <p>Is there a simple way to keep it a <code>TimeSpan</code> object but round it to something like<br> 00:00:00.62?</p>
[ { "answer_id": 338699, "author": "mapache", "author_id": 41422, "author_profile": "https://Stackoverflow.com/users/41422", "pm_score": 2, "selected": false, "text": "new TimeSpan(tmspan.Hours, tmspan.Minutes, tmspan.Seconds, (int)Math.Round(Convert.ToDouble(tmspan.Milliseconds / 10)));\n" }, { "answer_id": 338705, "author": "Will Dean", "author_id": 987, "author_profile": "https://Stackoverflow.com/users/987", "pm_score": 4, "selected": false, "text": "TimeSpan t1 = new TimeSpan(2345678);\nConsole.WriteLine(t1);\nTimeSpan t2 = new TimeSpan(t1.Ticks - (t1.Ticks % 100000));\nConsole.WriteLine(t2);\n 00:00:00.2345678\n00:00:00.2300000\n" }, { "answer_id": 2008570, "author": "Michael Sorens", "author_id": 115690, "author_profile": "https://Stackoverflow.com/users/115690", "pm_score": 6, "selected": true, "text": "int precision = 2; // Specify how many digits past the decimal point\nTimeSpan t1 = new TimeSpan(19365678); // sample input value\n\nconst int TIMESPAN_SIZE = 7; // it always has seven digits\n// convert the digitsToShow into a rounding/truncating mask\nint factor = (int)Math.Pow(10,(TIMESPAN_SIZE - precision));\n\nConsole.WriteLine(\"Input: \" + t1);\nTimeSpan truncatedTimeSpan = new TimeSpan(t1.Ticks - (t1.Ticks % factor));\nConsole.WriteLine(\"Truncated: \" + truncatedTimeSpan);\nTimeSpan roundedTimeSpan =\n new TimeSpan(((long)Math.Round((1.0*t1.Ticks/factor))*factor));\nConsole.WriteLine(\"Rounded: \" + roundedTimeSpan);\n Input: 00:00:01.9365678\nTruncated: 00:00:01.9300000\nRounded: 00:00:01.9400000\n Input: 00:00:01.9365678\nTruncated: 00:00:01.9365600\nRounded: 00:00:01.9365700\n Input: 00:00:01.9365678\nTruncated: 00:00:01\nRounded: 00:00:02\n Console.WriteLine(\"Rounded/formatted: \" + \n string.Format(\"{0:00}:{1:00}:{2:00}.{3:000}\",\n roundedTimeSpan.Hours, roundedTimeSpan.Minutes,\n roundedTimeSpan.Seconds, roundedTimeSpan.Milliseconds));\n// Input: 00:00:01.9365678\n// Truncated: 00:00:01.9300000\n// Rounded: 00:00:01.9400000\n// Rounded/formatted: 00:00:01.940\n Console.Write(new RoundedTimeSpan(19365678, 2).ToString());\n// Result = 00:00:01.94\n using System;\n\nnamespace CleanCode.Data\n{\n public struct RoundedTimeSpan\n {\n\n private const int TIMESPAN_SIZE = 7; // it always has seven digits\n\n private TimeSpan roundedTimeSpan;\n private int precision;\n\n public RoundedTimeSpan(long ticks, int precision)\n {\n if (precision < 0) { throw new ArgumentException(\"precision must be non-negative\"); }\n this.precision = precision;\n int factor = (int)System.Math.Pow(10, (TIMESPAN_SIZE - precision));\n\n // This is only valid for rounding milliseconds-will *not* work on secs/mins/hrs!\n roundedTimeSpan = new TimeSpan(((long)System.Math.Round((1.0 * ticks / factor)) * factor));\n }\n\n public TimeSpan TimeSpan { get { return roundedTimeSpan; } }\n\n public override string ToString()\n {\n return ToString(precision);\n }\n\n public string ToString(int length)\n { // this method revised 2010.01.31\n int digitsToStrip = TIMESPAN_SIZE - length;\n string s = roundedTimeSpan.ToString();\n if (!s.Contains(\".\") && length == 0) { return s; }\n if (!s.Contains(\".\")) { s += \".\" + new string('0', TIMESPAN_SIZE); }\n int subLength = s.Length - digitsToStrip;\n return subLength < 0 ? \"\" : subLength > s.Length ? s : s.Substring(0, subLength);\n }\n }\n}\n RoundedTimeSpan CleanCode.Data ToString(int)" }, { "answer_id": 24430341, "author": "Buzz", "author_id": 1303466, "author_profile": "https://Stackoverflow.com/users/1303466", "pm_score": 0, "selected": false, "text": "private const long TicksPer1000Milliseconds = 1000 * TimeSpan.TicksPerMillisecond;\n\n// Round milliseconds to nearest second\n// To round up, add the sub-second ticks required to reach the next second\n// To round down, subtract the sub-second ticks\nelapsedTime = new TimeSpan(elapsedTime.Ticks + (elapsedTime.Milliseconds >= 500 ? TicksPer1000Milliseconds - (elapsedTime.Ticks % TicksPer1000Milliseconds) : -(elapsedTime.Ticks % TicksPer1000Milliseconds)));\n" }, { "answer_id": 35503506, "author": "Gewalius", "author_id": 5950689, "author_profile": "https://Stackoverflow.com/users/5950689", "pm_score": 0, "selected": false, "text": " public static TimeSpan RoundToSeconds(this TimeSpan timespan, int seconds = 1)\n {\n long offset = (timespan.Ticks >= 0) ? TimeSpan.TicksPerSecond / 2 : TimeSpan.TicksPerSecond / -2;\n return TimeSpan.FromTicks((timespan.Ticks + offset) / TimeSpan.TicksPerSecond * TimeSpan.TicksPerSecond);\n }\n DateTime dt1 = DateTime.Now.RoundToSeconds(); // round to full seconds\nDateTime dt2 = DateTime.Now.RoundToSeconds(5 * 60); // round to full 5 minutes\n" }, { "answer_id": 37722864, "author": "cc1960", "author_id": 6444760, "author_profile": "https://Stackoverflow.com/users/6444760", "pm_score": 1, "selected": false, "text": " static TimeSpan RoundToSec(TimeSpan ts)\n {\n return TimeSpan.FromSeconds((int)(ts.TotalSeconds));\n }\n" }, { "answer_id": 39743128, "author": "ToolmakerSteve", "author_id": 199364, "author_profile": "https://Stackoverflow.com/users/199364", "pm_score": 5, "selected": false, "text": "public static TimeSpan RoundSeconds( TimeSpan span ) {\n return TimeSpan.FromSeconds( Math.Round( span.TotalSeconds ) );\n}\n public static TimeSpan RoundSeconds( TimeSpan span, int nDigits ) {\n // TimeSpan.FromSeconds rounds to nearest millisecond, so nDigits should be 3 or less - won't get good answer beyond 3 digits.\n Debug.Assert( nDigits <= 3 );\n return TimeSpan.FromSeconds( Math.Round( span.TotalSeconds, nDigits ) );\n}\n public static TimeSpan RoundSeconds( TimeSpan span, int nDigits ) {\n return TimeSpan.FromTicks( (long)( Math.Round( span.TotalSeconds, nDigits ) * TimeSpan.TicksPerSecond) );\n}\n public static string RoundSecondsAsString( TimeSpan span, int nDigits ) {\n StringBuilder sb = new StringBuilder();\n for (int i = 0; i < nDigits; i++)\n sb.Append( \"f\" );\n return span.ToString( @\"hh\\:mm\\:ss\\.\" + sb );\n}\n public static TimeSpan RoundMinutes(TimeSpan span)\n {\n return TimeSpan.FromMinutes(Math.Round(span.TotalMinutes));\n }\n DateTime dt = DateTime.Now();\nTimeSpan hhmm = RoundMinutes(dt.TimeOfDay);\n string hhmmStr = RoundMinutes(dt.TimeOfDay).ToString(@\"hh\\:mm\");\n string hhmmStr = new DateTime().Add(RoundMinutes(dt.TimeOfDay)).ToShortTimeString();\n ToShortTimeString DateTime // Rounds span to multiple of \"unitInSeconds\".\n // NOTE: This will be close to the requested multiple,\n // but is not exact when unit cannot be exactly represented by a double.\n // e.g. \"unitInSeconds = 1/30\" isn't EXACTLY 1/30,\n // so the returned value won't be exactly a multiple of 1/30.\n public static double RoundMultipleAsSeconds( TimeSpan span, double unitInSeconds )\n {\n return unitInSeconds * Math.Round( span.TotalSeconds / unitInSeconds );\n }\n\n public static TimeSpan RoundMultipleAsTimeSpan( TimeSpan span, double unitInSeconds )\n {\n return TimeSpan.FromTicks( (long)(RoundMultipleAsSeconds( span, unitInSeconds ) * TimeSpan.TicksPerSecond) );\n\n // IF USE THIS: TimeSpan.FromSeconds rounds the result to nearest millisecond.\n //return TimeSpan.FromSeconds( RoundMultipleAsSeconds( span, unitInSeconds ) );\n }\n\n // Rounds \"span / n\".\n // NOTE: This version might be a hair closer in some cases,\n // but probably not enough to matter, and can only represent units that are \"1 / N\" seconds.\n public static double RoundOneOverNAsSeconds( TimeSpan span, double n )\n {\n return Math.Round( span.TotalSeconds * n ) / n;\n }\n\n public static TimeSpan RoundOneOverNAsTimeSpan( TimeSpan span, double n )\n {\n return TimeSpan.FromTicks( (long)(RoundOneOverNAsSeconds( span, n ) * TimeSpan.TicksPerSecond) );\n\n // IF USE THIS: TimeSpan.FromSeconds rounds the result to nearest millisecond.\n //return TimeSpan.FromSeconds( RoundOneOverNAsSeconds( span, n ) );\n }\n private void Test()\n {\n long ticks = (long) (987.654321 * TimeSpan.TicksPerSecond);\n TimeSpan span = TimeSpan.FromTicks( ticks );\n TestRound( span, 30 );\n TestRound( TimeSpan.FromSeconds( 987 ), 30 );\n }\n\n private static void TestRound(TimeSpan span, int n)\n {\n var answer1 = RoundMultipleAsSeconds( span, 1.0 / n );\n var answer2 = RoundMultipleAsTimeSpan( span, 1.0 / n );\n var answer3 = RoundOneOverNAsSeconds( span, n );\n var answer4 = RoundOneOverNAsTimeSpan( span, n );\n }\n // for 987.654321 seconds:\n answer1 987.66666666666663 double\n answer2 {00:16:27.6666666} System.TimeSpan\n answer3 987.66666666666663 double\n answer4 {00:16:27.6666666} System.TimeSpan\n\n// for 987 seconds:\n answer1 987 double\n answer2 {00:16:27} System.TimeSpan\n answer3 987 double\n answer4 {00:16:27} System.TimeSpan\n" }, { "answer_id": 41193749, "author": "NetMage", "author_id": 2557128, "author_profile": "https://Stackoverflow.com/users/2557128", "pm_score": 3, "selected": false, "text": "public static TimeSpan Round(this TimeSpan ts, TimeSpan rnd) {\n if (rnd == TimeSpan.Zero)\n return ts;\n else {\n var rndTicks = rnd.Ticks;\n var ansTicks = ts.Ticks + Math.Sign(ts.Ticks) * rndTicks / 2;\n return TimeSpan.FromTicks(ansTicks - ansTicks % rndTicks);\n }\n}\npublic static TimeSpan Round(this TimeSpan ts) => ts.Round(TimeSpan.FromSeconds(1));\n public static TimeSpan RoundToFraction(this TimeSpan ts, long num, long den) => (den == 0.0) ? TimeSpan.Zero : TimeSpan.FromTicks((long)Math.Round(Math.Round((double)ts.Ticks * (double)den / num / TimeSpan.TicksPerSecond) * (double)num / den * TimeSpan.TicksPerSecond));\npublic static TimeSpan RoundToFraction(this TimeSpan ts, long den) => (den == 0.0) ? TimeSpan.Zero : TimeSpan.FromTicks((long)(Math.Round((double)ts.Ticks * den / TimeSpan.TicksPerSecond) / den * TimeSpan.TicksPerSecond));\n" }, { "answer_id": 51110795, "author": "Math M.", "author_id": 5265593, "author_profile": "https://Stackoverflow.com/users/5265593", "pm_score": 0, "selected": false, "text": "DateTime public static DateTime RoundToMinute(this DateTime date)\n {\n return DateTime.MinValue.AddMinutes(Math.Round((date - DateTime.MinValue).TotalMinutes));\n }\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338658", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36590/" ]
338,667
<p>I have to maintain a large number of classic ASP pages, many of which have tabular data with no sort capabilities at all. Whatever order the original developer used in the database query is what you're stuck with.</p> <p>I want to to tack on some basic sorting to a bunch of these pages, and I'm doing it all client side with javascript. I already have the basic script done to sort a given table on a given column in a given direction, and it works well as long as the table is limited by certain conventions we follow here.</p> <p>What I want to do for the UI is just indicate sort direction with the caret character ( <code>^</code> ) and ... what? Is there a special character that is the direct opposite of a caret? The letter <code>v</code> won't quite cut it. Alternatively, is there another character pairing I can use?</p>
[ { "answer_id": 338686, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 6, "selected": false, "text": "&caron; U+30C" }, { "answer_id": 338695, "author": "Max Lybbert", "author_id": 10593, "author_profile": "https://Stackoverflow.com/users/10593", "pm_score": 6, "selected": false, "text": "&darr" }, { "answer_id": 338715, "author": "shahkalpesh", "author_id": 23574, "author_profile": "https://Stackoverflow.com/users/23574", "pm_score": 3, "selected": false, "text": "int i = 0;\nchar c = '↑';\ni = (int)c;\nConsole.WriteLine(i); // prints 8593\n\nint j = 0;\nchar d = '↓';\nj = (int)d;\nConsole.WriteLine(j); // prints 8595\n" }, { "answer_id": 2342421, "author": "Josh Bodily", "author_id": 282115, "author_profile": "https://Stackoverflow.com/users/282115", "pm_score": 8, "selected": false, "text": "&and; &or;" }, { "answer_id": 27284717, "author": "BCLaw15", "author_id": 4322501, "author_profile": "https://Stackoverflow.com/users/4322501", "pm_score": 3, "selected": false, "text": "<sub><strong>v</strong></sub>\n" }, { "answer_id": 43644213, "author": "Stu Coston", "author_id": 7927775, "author_profile": "https://Stackoverflow.com/users/7927775", "pm_score": 0, "selected": false, "text": "<div id=\"ID\"></div>\n\n<script type=\"text/javascript\">\nvar x = document.getElementById('ID');\n\n// your \"margin-bottom\" is the negative of 1/2 of the font size (in this example the font size is 16px)\n// change the \"stroke=\" to whatever color your font is too\nx.innerHTML = document.write = '<span><svg style=\"margin-bottom: -8px; height: 30px; width: 25px;\" viewBox=\"0,0,100,50\"><path fill=\"transparent\" stroke-width=\"4\" stroke=\"black\" d=\"M20 10 L50 40 L80 10\"/></svg></span>';\n</script>\n" }, { "answer_id": 44293498, "author": "Colin D", "author_id": 2129219, "author_profile": "https://Stackoverflow.com/users/2129219", "pm_score": 3, "selected": false, "text": "<link rel=\"stylesheet\" href=\"https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css\"> <button><i class=\"fa fa-arrow-down\"></i></button>" }, { "answer_id": 44787080, "author": "nic", "author_id": 3524883, "author_profile": "https://Stackoverflow.com/users/3524883", "pm_score": 2, "selected": false, "text": "^ shift 6 shift alt i shift alt t" }, { "answer_id": 49070810, "author": "Mr. Hugo", "author_id": 2397550, "author_profile": "https://Stackoverflow.com/users/2397550", "pm_score": 2, "selected": false, "text": ".upsidedown {\ntransform:rotate(180deg); \n-webkit-transform:rotate(180deg);\n-o-transform:rotate(180deg);\n-ms-transform:rotate(180deg);\n}\n.upsidedown.caret {\ndisplay: inline-block; \nposition:relative; \nbottom: 0.15em;\n} more items <span class=\"upsidedown caret\">^</span>" }, { "answer_id": 49478600, "author": "ashleedawg", "author_id": 8112776, "author_profile": "https://Stackoverflow.com/users/8112776", "pm_score": 5, "selected": false, "text": "˅˄˅˄ n-ary logical or n-ary logical and ⋁⋀⋁⋀" }, { "answer_id": 61110709, "author": "BaseZen", "author_id": 4569307, "author_profile": "https://Stackoverflow.com/users/4569307", "pm_score": 1, "selected": false, "text": "office365icons.woff https://owa.example.com/owa/prem/15.1.1913.10/resources/styles/fonts/office365icons.woff @font-face {\n font-family: 'Office365Icons';\n src: url('/fonts/office365icons.woff') format('woff');\n font-weight: normal;\n font-style: normal;\n }\n\n span.o-icon {\n font-family: 'Office365Icons';\n font-size: 14pt;\n line-height: 21px;\n color: #666;\n }\n <span class=\"o-icon\">&#xe088;</span>\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338667", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3043/" ]
338,701
<p>Due to a weird request, I can't put <code>null</code> in a database if there is no value. I'm wondering what can I put in the store procedure for nothing instead of <code>null</code>.</p> <p>For example: </p> <pre><code>insert into blah (blah1) values (null) </code></pre> <p>Is there something like nothing or empty for "blah1" instead using <code>null</code>?</p>
[ { "answer_id": 338720, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 4, "selected": true, "text": "NULL NULL NOT NULL person_age items_in_stock" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338701", "https://Stackoverflow.com", "https://Stackoverflow.com/users/28647/" ]
338,702
<h2>How is it possible to call a client side javascript method after a <em>specific</em> update panel has been loaded?</h2> <p><strong><code>Sys.WebForms.PageRequestManager.getInstance().add_endRequest(EndRequestHandler)</code></strong> does not work for me because this will fire after ANY update panel finishes loading, and I can find no client side way to find which is the one</p> <p><strong><code>ScriptManager.GetCurrent(Page).AsyncPostBackSourceElementID AsyncPostBackSourceElementID</code></strong> does not work for me as this is a server side object, and i want Client Side</p> <p>The ClientSide .Net framework must know which UpdatePanel it is updating in order to update the correct content. Surely there is a way to hook into this event?</p> <p>Any help would be appreciated. </p>
[ { "answer_id": 338818, "author": "CountCet", "author_id": 2636656, "author_profile": "https://Stackoverflow.com/users/2636656", "pm_score": 1, "selected": false, "text": "string scriptText = \"alert('Bar!');\";\n\nScriptManager.RegisterStartupScript(this.Page, this.GetType(), \"foo\", scriptText, true);\n" }, { "answer_id": 339114, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "<script type=\"text/javascript\">\n $(document).ready(function() {\n panelsLoaded = 1;\n Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(PageLoaded)\n });\n\n function PageLoaded(sender, args) {\n console.log(\"I have occured \" + panelsLoaded++ + \" times!\");\n\n var panelsCreated = args.get_panelsCreated();\n for (var i = 0; i < panelsCreated.length; i++) {\n console.log(\"Panels Updating: \" + panelsCreated[i].id);\n }\n\n var panelsUpdated = args.get_panelsUpdated();\n for (var i = 0; i < panelsUpdated.length; i++) {\n console.log(\"Panels Updating: \" + panelsUpdated[i].id);\n }\n }\n </script>\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
338,712
<p>I have a Queue object that I need to ensure is thread-safe. Would it be better to use a lock object like this:</p> <pre><code>lock(myLockObject) { //do stuff with the queue } </code></pre> <p>Or is it recommended to use Queue.Synchronized like this:</p> <pre><code>Queue.Synchronized(myQueue).whatever_i_want_to_do(); </code></pre> <p>From reading the MSDN docs it says I should use Queue.Synchronized to make it thread-safe, but then it gives an example using a lock object. From the MSDN article:</p> <blockquote> <p>To guarantee the thread safety of the Queue, all operations must be done through this wrapper only.</p> <p>Enumerating through a collection is intrinsically not a thread-safe procedure. Even when a collection is synchronized, other threads can still modify the collection, which causes the enumerator to throw an exception. To guarantee thread safety during enumeration, you can either lock the collection during the entire enumeration or catch the exceptions resulting from changes made by other threads.</p> </blockquote> <p>If calling Synchronized() doesn't ensure thread-safety what's the point of it? Am I missing something here?</p>
[ { "answer_id": 338857, "author": "Greg Beech", "author_id": 13552, "author_profile": "https://Stackoverflow.com/users/13552", "pm_score": 5, "selected": false, "text": "Synchronized Count Dequeue Count object item;\nif (queue.Count > 0)\n{\n // at this point another thread dequeues the last item, and then\n // the next line will throw an InvalidOperationException...\n item = queue.Dequeue();\n}\n object item;\nlock (queue)\n{\n if (queue.Count > 0)\n {\n item = queue.Dequeue();\n }\n}\n" }, { "answer_id": 338989, "author": "Leonidius", "author_id": 43014, "author_profile": "https://Stackoverflow.com/users/43014", "pm_score": 3, "selected": false, "text": "object item;\nif (queue.Count > 0)\n{\n lock (queue)\n {\n if (queue.Count > 0)\n {\n item = queue.Dequeue();\n }\n }\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338712", "https://Stackoverflow.com", "https://Stackoverflow.com/users/343/" ]
338,719
<p>Can I write to the end of a 5GB file in Java? This question came up in my office and no one is sure what the answer is.</p>
[ { "answer_id": 338747, "author": "Greg Case", "author_id": 462, "author_profile": "https://Stackoverflow.com/users/462", "pm_score": 5, "selected": true, "text": "String filename;\n\nRandomAccessFile myFile = new RandomAccessFile(filename, \"rw\");\n\n// Set write pointer to the end of the file\nmyFile.seek(myFile.length());\n\n// Write to end of file here\n" }, { "answer_id": 338749, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 0, "selected": false, "text": "OutputStream in = new java.io.FileOutputStream(fileName, true);\n" }, { "answer_id": 338750, "author": "Bill the Lizard", "author_id": 1288, "author_profile": "https://Stackoverflow.com/users/1288", "pm_score": 1, "selected": false, "text": "FileWriter(File file, boolean append) \n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338719", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1447/" ]
338,732
<p>I want to be able to apply a style at runtime to an object <strong>ONLY</strong> if the current style is the default style. I don't want to override any user defined styles. Anyone know how to do this?</p>
[ { "answer_id": 338900, "author": "Jobi Joy", "author_id": 8091, "author_profile": "https://Stackoverflow.com/users/8091", "pm_score": -1, "selected": false, "text": "string styleKeyName = DefaultStyleKeyProperty.Name;\n" }, { "answer_id": 338949, "author": "Ryan Lundy", "author_id": 5486, "author_profile": "https://Stackoverflow.com/users/5486", "pm_score": 3, "selected": true, "text": "DependencyPropertyHelper.GetValueSource(\n someControl, FrameworkElement.StyleProperty).BaseValueSource \n == BaseValueSource.Default;\n static public bool HasDefaultStyle(this FrameworkElement item)\n{\n return DependencyPropertyHelper.GetValueSource(\n item, FrameworkElement.StyleProperty).BaseValueSource \n == BaseValueSource.Default;\n}\n someControl.HasDefaultStyle()" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338732", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17744/" ]
338,734
<p>I'm looking to be able to reference certain state/objects through anywhere in my application. For instance, a user logs in to their application, I need to call a web service and retrieve the users information. Then I want to be able to access this information from anywhere in the application with something like the following:</p> <pre><code>myAppDelegate *delegate = [[UIApplication sharedApplication] delegate]; user = delegate.u; </code></pre> <p>Is setting an instance variable as a User object in the app delegate and referencing it from there when needed a poor way of going about it? I typically set it there upon the user's login.</p> <p>Wanted to hear how the pros handle this one.</p>
[ { "answer_id": 338832, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 4, "selected": false, "text": "// MyCommon.h:\n@interface MyCommon\nclass MyCommon : NSObject\n{\n int user;\n};\n\n@property(assign) int user;\n\n+ (MyCommon *)singleton;\n\n@end\n\n// MyCommon.m:\n@implementation MyCommon\n\nstatic MyCommon * MyCommon_Singleton = nil;\n\n+ (MyCommon *)singleton\n{\n if (nil == MyCommon_Singleton)\n {\n MyCommon_Singleton = [[MyCommon_Singleton alloc] init];\n }\n\n return MyCommon_Singleton;\n}\n@end MyCommon int user = [MyCommon singleton].user;" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338734", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40882/" ]
338,739
<p>I have a MySQL table containing domain names:</p> <pre><code>+----+---------------+ | id | domain | +----+---------------+ | 1 | amazon.com | | 2 | google.com | | 3 | microsoft.com | | | ... | +----+---------------+ </code></pre> <p>I'd like to be able to search through this table for a full hostname (i.e. 'www.google.com'). If it were the other way round where the table contained the full URL I'd use:</p> <pre><code>SELECT * FROM table WHERE domain LIKE '%google.com%' </code></pre> <p>But the inverse is not so straightforward. My current thinking is to search for the full hostname, then progressively strip off each part of the domain, and search again. (i.e. search for 'www.google.com' then 'google.com')</p> <p>This is not particular efficient or clever, there must be a better way. I am sure it is a common problem, and no doubt easy to solve!</p>
[ { "answer_id": 338755, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 5, "selected": true, "text": "SELECT domain FROM table WHERE 'www.google.com' LIKE CONCAT('%', domain);\n SELECT domain FROM table WHERE 'www.google.com' LIKE CONCAT('%', domain, '%');\n" }, { "answer_id": 338770, "author": "Radu094", "author_id": 3263, "author_profile": "https://Stackoverflow.com/users/3263", "pm_score": 0, "selected": false, "text": "SELECT * FROM table WHERE \nsubstring('www.google.com',\nlen('www.google.com') - len([domain]) ,\nlen([domain])+1) = [domain]\n" }, { "answer_id": 338840, "author": "Chris", "author_id": 42937, "author_profile": "https://Stackoverflow.com/users/42937", "pm_score": 2, "selected": false, "text": "mysql RLIKE SELECT * FROM table WHERE 'www.google.com' RLIKE domain;\n RLIKE regex MySQL's regex" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338739", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42974/" ]
338,740
<p>Currently I have the function CreateLog() for creating a a log4net Log with name after the constructing instance's class. Typically used as in:</p> <pre><code>class MessageReceiver { protected ILog Log = Util.CreateLog(); ... } </code></pre> <p>If we remove lots of error handling the implementation boils down to: [EDIT: Please read the longer version of CreateLog further on in this post.]</p> <pre><code>public ILog CreateLog() { System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(1); System.Reflection.MethodBase method = stackFrame.GetMethod(); return CreateLogWithName(method.DeclaringType.FullName); } </code></pre> <p>Problem is that if we inheirit MessageReceiver into sub classes the log will still take its name from MessageReceiver since this is the declaring class of the method (constructor) which calls CreateLog.</p> <pre><code>class IMReceiver : MessageReceiver { ... } class EmailReceiver : MessageReceiver { ... } </code></pre> <p>Instances of both these classes would get Logs with name "MessageReceiver" while I would like them to be given names "IMReceiver" and "EmailReceiver".</p> <p>I know this can easily be done (and is done) by passing a reference to the object in creation when calling CreateLog since the GetType() method on object does what I want.</p> <p>There are some minor reasons to prefer not adding the parameter and personally I feel disturbed by not finding a solution with no extra argument.</p> <p>Is there anyone who can show me how to implement a zero argument CreateLog() that gets the name from the subclass and not the declaring class?</p> <p>EDIT:</p> <p>The CreateLog function does more than mentioned above. The reason for having one log per instance is to be able to differ between different instances in the logfile. This is enforced by the CreateLog/CreateLogWithName pair.</p> <p>Expanding on the functionality of CreateLog() to motivate its existence.</p> <pre><code>public ILog CreateLog() { System.Diagnostics.StackFrame stackFrame = new System.Diagnostics.StackFrame(1); System.Reflection.MethodBase method = stackFrame.GetMethod(); Type type = method.DeclaringType; if (method.IsStatic) { return CreateLogWithName(type.FullName); } else { return CreateLogWithName(type.FullName + "-" + GetAndInstanceCountFor(type)); } } </code></pre> <p>Also I prefer writing ILog Log = Util.CreateLog(); rather than copying in some long cryptic line from an other file whenever I write a new class. I am aware that the reflection used in Util.CreateLog is not guaranteed to work though - is System.Reflection.MethodBase.GetCurrentMethod() guaranteed to work?</p>
[ { "answer_id": 338760, "author": "Orion Edwards", "author_id": 234, "author_profile": "https://Stackoverflow.com/users/234", "pm_score": 2, "selected": true, "text": "IMReceiver CreateLog MessageReceiver MessageReceiver CreateLog IMReceiver class BaseClass{\n public Log log = Utils.CreateLog();\n}\nclass DerivedClass : BaseClass {\n public DerivedClass() {\n log = Utils.CreateLog();\n }\n}\n new BaseClass();\n# Log created for BaseClass\n\nnew DerivedClass();\n# Log created for BaseClass\n# Log created for DerivedClass\n" }, { "answer_id": 338904, "author": "Mike Two", "author_id": 23659, "author_profile": "https://Stackoverflow.com/users/23659", "pm_score": 0, "selected": false, "text": "class Program\n{\n static void Main(string[] args)\n {\n Logger logger = new Logger();\n Caller caller = new Caller();\n caller.FirstMethod(logger);\n caller.SecondMethod(logger);\n }\n}\n\npublic class Caller\n{\n public void FirstMethod(Logger logger)\n {\n Console.Out.WriteLine(\"first\");\n logger.Log();\n }\n\n public void SecondMethod(Logger logger)\n {\n Console.Out.WriteLine(\"second\");\n logger.Log();\n }\n}\n\npublic class Logger\n{\n public void Log()\n {\n StackTrace trace = new StackTrace();\n var frames = trace.GetFrames();\n Console.Out.WriteLine(frames[1].GetMethod().Name);\n }\n}\n" }, { "answer_id": 339207, "author": "Ewan Makepeace", "author_id": 9731, "author_profile": "https://Stackoverflow.com/users/9731", "pm_score": 2, "selected": false, "text": "private static ILog log = \nlog4net.LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);\n" }, { "answer_id": 643795, "author": "Conor OG", "author_id": 77824, "author_profile": "https://Stackoverflow.com/users/77824", "pm_score": 0, "selected": false, "text": " var type = new StackFrame(1).GetMethod().DeclaringType;\n foreach (var frame in new StackTrace(2).GetFrames())\n if (type != frame.GetMethod().DeclaringType.BaseType)\n break;\n else\n type = frame.GetMethod().DeclaringType;\n return CreateLogWithName(type.FullName);\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338740", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41884/" ]
338,762
<p>How do you calculate the angle between two normals in glsl? I am trying to add the fresnel effect to the outer edges of an object (combining that effect with phong shading), and I think that the angle is the only thing I am missing.</p> <p>Fragment Shader:</p> <pre><code>varying vec3 N; varying vec3 v; void main(void) { v = vec3(gl_ModelViewMatrix * gl_Vertex); N = normalize(gl_NormalMatrix * gl_Normal); gl_Position = gl_ModelViewProjectionMatrix * gl_Vertex; } </code></pre> <p>Vertex Shader:</p> <pre><code>varying vec3 N; varying vec3 v; void main(void) { vec3 L = normalize(gl_LightSource[0].position.xyz - v); vec3 E = normalize(-v); vec3 R = normalize(-reflect(L,N)); vec4 Iamb = gl_FrontLightProduct[0].ambient vec4 Idiff = gl_FrontLightProduct[0].diffuse * max(dot(N,L), 0.0); vec4 Ispec = gl_FrontLightProduct[0].specular * pow(max(dot(R,E),0.0), gl_FrontMaterial.shininess); vec4 Itot = gl_FrontLightModelProduct.sceneColor + Iamb + Idiff + Ispec; vec3 A = //calculate the angle between the lighting direction and the normal// float F = 0.33 + 0.67*(1-cos(A))*(1-cos(A))*(1-cos(A))*(1-cos(A))*(1-cos(A)); vec4 white = {1.0, 1.0, 1.0, 1.0}; gl_FragColor = F*white + (1.0-F)*Itot; } </code></pre> <p>varying vec3</p>
[ { "answer_id": 338801, "author": "David Norman", "author_id": 34502, "author_profile": "https://Stackoverflow.com/users/34502", "pm_score": 3, "selected": false, "text": "cos A = DotProduct(v1, v2) / (Length(v1) * Length(v2))\n" }, { "answer_id": 340248, "author": "NeARAZ", "author_id": 6799, "author_profile": "https://Stackoverflow.com/users/6799", "pm_score": 4, "selected": false, "text": "float oneMinusDot = 1.0 - dot(L, N);\nfloat F = pow(oneMinusDot, 5.0);\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
338,767
<p>I have a some .py files that use spaces for indentation, and I'd like to convert them to tabs.</p> <p>I could easily hack together something using regexes, but I can think of several edge cases where this approach could fail. Is there a tool that does this by parsing the file and determining the indentation level the same way the python interpreter does?</p>
[ { "answer_id": 338791, "author": "wimh", "author_id": 33499, "author_profile": "https://Stackoverflow.com/users/33499", "pm_score": 4, "selected": false, "text": ":retab" }, { "answer_id": 338929, "author": "Greg", "author_id": 13009, "author_profile": "https://Stackoverflow.com/users/13009", "pm_score": 4, "selected": false, "text": "C:\\Python24\\Tools\\Scripts\\reindent.py" }, { "answer_id": 338966, "author": "Alastair", "author_id": 31038, "author_profile": "https://Stackoverflow.com/users/31038", "pm_score": 2, "selected": false, "text": "M-x tabify tab-width M-x indent-region" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338767", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1595/" ]
338,768
<p>Python is installed in a local directory. </p> <p>My directory tree looks like this:</p> <pre><code>(local directory)/site-packages/toolkit/interface.py </code></pre> <p>My code is in here:</p> <pre><code>(local directory)/site-packages/toolkit/examples/mountain.py </code></pre> <p>To run the example, I write <code>python mountain.py</code>, and in the code I have:</p> <pre><code>from toolkit.interface import interface </code></pre> <p>And I get the error:</p> <pre><code>Traceback (most recent call last): File "mountain.py", line 28, in ? from toolkit.interface import interface ImportError: No module named toolkit.interface </code></pre> <p>I have already checked <code>sys.path</code> and there I have the directory <code>/site-packages</code>. Also, I have the file <code>__init__.py.bin</code> in the toolkit folder to indicate to Python that this is a package. I also have a <code>__init__.py.bin</code> in the examples directory.</p> <p>I do not know why Python cannot find the file when it is in <code>sys.path</code>. Any ideas? Can it be a permissions problem? Do I need some execution permission?</p>
[ { "answer_id": 338790, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 4, "selected": false, "text": "__init__.py" }, { "answer_id": 338858, "author": "igorgue", "author_id": 29253, "author_profile": "https://Stackoverflow.com/users/29253", "pm_score": 7, "selected": false, "text": "(local directory)/site-packages/toolkit\n __init__.py __init__.py" }, { "answer_id": 339220, "author": "John Fouhy", "author_id": 15154, "author_profile": "https://Stackoverflow.com/users/15154", "pm_score": 9, "selected": true, "text": "__init__.py __init__.py __init__.py.bin __init__.py" }, { "answer_id": 339333, "author": "Eduardo", "author_id": 39160, "author_profile": "https://Stackoverflow.com/users/39160", "pm_score": 5, "selected": false, "text": "__init__.py .py.bin which python" }, { "answer_id": 420458, "author": "miya", "author_id": 293, "author_profile": "https://Stackoverflow.com/users/293", "pm_score": 3, "selected": false, "text": "__init__.py" }, { "answer_id": 5199346, "author": "Renaud", "author_id": 125617, "author_profile": "https://Stackoverflow.com/users/125617", "pm_score": 5, "selected": false, "text": " .:/usr/local/lib/python\n .: .:/usr/lib/python\n .:/usr/lib/python2.6\n .:/usr/lib/python2.7 and etc.\n" }, { "answer_id": 18604658, "author": "peter karasev", "author_id": 221802, "author_profile": "https://Stackoverflow.com/users/221802", "pm_score": 2, "selected": false, "text": "python boost::Python FooLib_d.pyd FooLib.pyd CMakeLists.txt" }, { "answer_id": 23210066, "author": "Specterace", "author_id": 3539939, "author_profile": "https://Stackoverflow.com/users/3539939", "pm_score": 7, "selected": false, "text": "mountain.py toolkit.interface.py toolkit toolkit export PYTHONPATH=. toolkit" }, { "answer_id": 23964457, "author": "KrisWebDev", "author_id": 2227298, "author_profile": "https://Stackoverflow.com/users/2227298", "pm_score": 2, "selected": false, "text": "sudo setup.py install sudo chmod 755 /usr/local/lib/python2.7/dist-packages/*.so\n" }, { "answer_id": 25199209, "author": "Sayse", "author_id": 1324033, "author_profile": "https://Stackoverflow.com/users/1324033", "pm_score": 0, "selected": false, "text": "pyc *.pyc pyc" }, { "answer_id": 25699674, "author": "Mr_and_Mrs_D", "author_id": 281545, "author_profile": "https://Stackoverflow.com/users/281545", "pm_score": 3, "selected": false, "text": "Traceback (most recent call last):\n File \"bash\\bash.py\", line 454, in main\n import bosh\n File \"Wrye Bash Launcher.pyw\", line 63, in load_module\n mod = imp.load_source(fullname,filename+ext,fp)\n File \"bash\\bosh.py\", line 69, in <module>\n from game.oblivion.RecordGroups import MobWorlds, MobDials, MobICells, \\\n ImportError: No module named RecordGroups\n __init__.py" }, { "answer_id": 34102396, "author": "Rocketq", "author_id": 1739325, "author_profile": "https://Stackoverflow.com/users/1739325", "pm_score": 0, "selected": false, "text": "Import error" }, { "answer_id": 38512198, "author": "dukevin", "author_id": 255439, "author_profile": "https://Stackoverflow.com/users/255439", "pm_score": 2, "selected": false, "text": "print (sys.path)" }, { "answer_id": 41470260, "author": "MonoThreaded", "author_id": 294702, "author_profile": "https://Stackoverflow.com/users/294702", "pm_score": 5, "selected": false, "text": "PyCharm Right Click > Mark Directory as > Sources Root" }, { "answer_id": 43731647, "author": "liushuaikobe", "author_id": 1108052, "author_profile": "https://Stackoverflow.com/users/1108052", "pm_score": 3, "selected": false, "text": "sys.path from foo.bar import baz ImportError: No module named bar import foo; print foo foo foo" }, { "answer_id": 46283096, "author": "Badr Bellaj", "author_id": 5891912, "author_profile": "https://Stackoverflow.com/users/5891912", "pm_score": 4, "selected": false, "text": "python -m pip install <library-name> pip install <library-name>" }, { "answer_id": 49513126, "author": "Rich", "author_id": 358469, "author_profile": "https://Stackoverflow.com/users/358469", "pm_score": 2, "selected": false, "text": "__init__.py" }, { "answer_id": 50557536, "author": "ioaniatr", "author_id": 2173847, "author_profile": "https://Stackoverflow.com/users/2173847", "pm_score": 1, "selected": false, "text": "Booklet\n-> __init__.py\n-> Booklet.py\n-> Question.py\ndefault\n-> __init_.py\n-> main.py\n from Booklet import Question\nfrom Question import Question\nfrom Booklet.Question import Question\nfrom Booklet.Question import *\nimport Booklet.Question\n# and many othet various combinations ...\n from booklet.Booklet import Booklet\nfrom booklet.Question import Question\nfrom booklet.Question import AnotherClass\n" }, { "answer_id": 54597040, "author": "avp", "author_id": 5355272, "author_profile": "https://Stackoverflow.com/users/5355272", "pm_score": 5, "selected": false, "text": "__init__.py ImportError PYTHONPATH PYTHONPATH export PYTHONPATH=$PYTHONPATH:`pwd` (OR your project root directory)\n sys.path import sys\nsys.path.insert(0,'<project directory>') OR\nsys.path.append('<project directory>')\n" }, { "answer_id": 55141979, "author": "Scott", "author_id": 6013016, "author_profile": "https://Stackoverflow.com/users/6013016", "pm_score": 0, "selected": false, "text": "__init__.py site-packages from site-packages.toolkit.interface import interface\n" }, { "answer_id": 56093642, "author": "AKJ", "author_id": 3831854, "author_profile": "https://Stackoverflow.com/users/3831854", "pm_score": 3, "selected": false, "text": "try:\n from namespace import something \nexcept NameError:\n from .namespace import something\n" }, { "answer_id": 57613234, "author": "kev", "author_id": 9473729, "author_profile": "https://Stackoverflow.com/users/9473729", "pm_score": 5, "selected": false, "text": "pip3 install python program.py python3 program.py" }, { "answer_id": 59789980, "author": "Poli", "author_id": 12233118, "author_profile": "https://Stackoverflow.com/users/12233118", "pm_score": 1, "selected": false, "text": "dos2unix script_name pyc find . -name '*.pyc' -delete" }, { "answer_id": 60615157, "author": "Michał Zawadzki", "author_id": 8524524, "author_profile": "https://Stackoverflow.com/users/8524524", "pm_score": 1, "selected": false, "text": "sys.path.insert() module not found sys.path.insert() module not found sys.path.insert()" }, { "answer_id": 64401997, "author": "michael-slx", "author_id": 4644268, "author_profile": "https://Stackoverflow.com/users/4644268", "pm_score": 2, "selected": false, "text": "find_packages() import setuptools\n\nsetuptools.setup(\n name=\"example-pkg\",\n version=\"0.0.1\",\n author=\"Example Author\",\n author_email=\"author@example.com\",\n description=\"A small example package\",\n packages=setuptools.find_packages(),\n classifiers=[\n \"Programming Language :: Python :: 3\",\n \"Operating System :: OS Independent\",\n ],\n python_requires='>=3.6',\n)\n" }, { "answer_id": 67053868, "author": "libin", "author_id": 10252729, "author_profile": "https://Stackoverflow.com/users/10252729", "pm_score": 0, "selected": false, "text": "python3.6 conda create -n python3.6 python=3.6\npip install pandas\n ModuleNotFoundError: No module named 'pandas'\n pandas pip uninstall pandas --no-cache-dir\npip install pandas \n" }, { "answer_id": 70311337, "author": "questionto42standswithUkraine", "author_id": 11154841, "author_profile": "https://Stackoverflow.com/users/11154841", "pm_score": 0, "selected": false, "text": "apt-get python3-XYZ\n python-XYZ\n python3-XYZ python-XYZ $ apt-cache search \"python.*toolkit.*interface\"\npython3-cli-helpers - easy command-line apps with Python\npython3-exam - Python module to help write better tests\npython3-fltk - Python wrapper for the Fast Light Toolkit\npython3-mpltoolkits.basemap - matplotlib toolkit to plot on map projections (Python 3)\npython3-nltk - Python3 libraries for natural language processing\npython3-onnx - Open Neural Network Exchange (ONNX) (Python)\npython3-paraview - Parallel Visualization Application. python-support\npython3-pyswarms - research toolkit for particle swarm optimization in Python\npython3-wxgtk-media4.0 - Python 3 interface to the wxWidgets Cross-platform C++ GUI toolkit (wx.media)\npython3-wxgtk-webview4.0 - Python 3 interface to the wxWidgets Cross-platform C++ GUI toolkit (wx.html2)\npython3-wxgtk4.0 - Python 3 interface to the wxWidgets Cross-platform C++ GUI toolkit\npython3-xapian - Xapian search engine interface for Python3\nwxglade - GUI designer written in Python with wxPython\n apt-get sudo apt-get install python-flask\n sudo apt-get install python-[YOURPYTHONVERION]-[YOURERRORPACKAGE]\n" }, { "answer_id": 72045045, "author": "juanignaciosl", "author_id": 351721, "author_profile": "https://Stackoverflow.com/users/351721", "pm_score": 1, "selected": false, "text": "python myapp/app.py\n python -m myapp.app\n" }, { "answer_id": 72626476, "author": "PatrickT", "author_id": 1457380, "author_profile": "https://Stackoverflow.com/users/1457380", "pm_score": 0, "selected": false, "text": "import sys\nimport os\nwd = '/path/to/current/script/'\nsys.path.append(wd)\nos.chdir(wd)\nprint(os.getcwd())\nprint(sys.path)\n" }, { "answer_id": 73214654, "author": "nextloop", "author_id": 12387614, "author_profile": "https://Stackoverflow.com/users/12387614", "pm_score": 1, "selected": false, "text": "file.py #!/bin/python\nfrom bs4 import BeautifulSoup\n python pyyhon2 $ file $(which python)\n/sbin/python: symbolic link to python2\n file.py python3 bs4 python2 $ python file.py\n# or\n$ file.py\n# or\n$ file.py # if locate in $PATH\n error # should be to make python3 as default by symlink\n$ rm $(which python) && ln -s $(which python3) /usr/bin/python\n# or use alias\nalias python='/usr/bin.../python3'\n shebang file.py #!/usr/bin/...python3\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338768", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39160/" ]
338,772
<p>I saw this sentence in some matrials:</p> <p>"In Java, simple data types such as int and char operate just as in C."</p> <p>I am wondering that actually they are different in Java &amp; C++?</p> <p>In C++, simple variables like the primitives in Java are assigned a memory address as well, so these primitive types in C++ can have a pointer as well. However primitives in Java are not assigned a memory address like Objects are. </p> <p>Am I correct?</p> <p>Thanks!</p>
[ { "answer_id": 338797, "author": "Richard Walton", "author_id": 15075, "author_profile": "https://Stackoverflow.com/users/15075", "pm_score": -1, "selected": false, "text": "int x = 5;\nint y = x;\n\ny++;\n\n// y = 6\n// x = 5\n Object a = new Object();\nObject b = a;\n\nb.someAction();\n\n// A and B point to the same object and both have had the 'someAction()' performed\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338772", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36064/" ]
338,776
<p>I'm trying to convert an Excel document into a table in SQL 2005. I found the link below and am wondering if it looks like a solution. If so, what would the @excel_full_file_name syntax be and where would the path be relative to? </p> <p><a href="http://www.siccolo.com/Articles/SQLScripts/how-to-create-sql-to-convert-Excel_to_table.html" rel="nofollow noreferrer">http://www.siccolo.com/Articles/SQLScripts/how-to-create-sql-to-convert-Excel_to_table.html</a></p>
[ { "answer_id": 343345, "author": "Coolcoder", "author_id": 42434, "author_profile": "https://Stackoverflow.com/users/42434", "pm_score": 4, "selected": true, "text": "BULK \nINSERT YourDestinationTable\n FROM 'D:\\YourFile.csv'\n WITH\n (\n FIELDTERMINATOR = ',',\n ROWTERMINATOR = '\\n'\n )\nGO\n SELECT * FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0',\n'Excel 8.0;DATABASE=D:\\YourExcelFile.xls', 'Select * from YourExcelFile') \n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338776", "https://Stackoverflow.com", "https://Stackoverflow.com/users/13954/" ]
338,809
<p>Tip me plase, how to insert a null value into table using Trolltech Qt 4.x SQL classes? <code>QSqlQuery</code>, I guess, or something else from QtNetwork. As analog of it, in .NET there is the <code>System.DbNull</code> class, which represents sql NULL.</p> <p>And what type should I use for some object's property, that can hold both null-value and <code>QString</code>? In C# I could use <code>System.Object</code>.</p>
[ { "answer_id": 338819, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 6, "selected": true, "text": "QSqlQuery::addBindValue" }, { "answer_id": 19008310, "author": "0xF", "author_id": 2032514, "author_profile": "https://Stackoverflow.com/users/2032514", "pm_score": 1, "selected": false, "text": "QString" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338809", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41956/" ]
338,813
<p>I need a small, portable framework for logging on embedded linux. Ideally it would output to a file or a socket, and having some sort of log rotation/compression would also be nice.</p> <p>So far, I've found a lot of frameworks, but almost all of them have daunting build procedures or require the use of application frameworks (e.g. log4cxx requires the Apache Portable Runtime, which I'd rather not bother with...).</p> <p>Just looking for something simple and robust, but everything I seem to find is complicated or requires lots of secondary junk just to run.</p> <p>Suggestions? (and if the answer is roll my own, that's fine, but...it's be great to avoid that)</p>
[ { "answer_id": 338863, "author": "Ilya", "author_id": 6807, "author_profile": "https://Stackoverflow.com/users/6807", "pm_score": 0, "selected": false, "text": "DBG_E DBG_W DBG_TRACE" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338813", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
338,816
<p>The controllers in my ASP.NET MVC web app are starting to get a bit bloated with business logic. The examples on the web all show simple controller actions that simply pull data out of a repository and pass it to the view. But what if you also need to support business logic on top of that? </p> <p>Say, for instance, an action that fulfills an order also needs to send an e-mail out. Do I stick this in the controller and copy/paste this logic to any other actions that also fulfill orders? My first intuition would be to create a service like OrderFulfillerService that would take care of all this logic and have the controller action call that. However, for simple operations like retrieving a list of users or orders from the database, I would like to interact directly with the repository instead of having that call wrapped by a service.</p> <p>Is this an acceptable design pattern? Controller actions call services when they need business logic and repositories when they just need data access?</p>
[ { "answer_id": 339234, "author": "Tim Scott", "author_id": 29493, "author_profile": "https://Stackoverflow.com/users/29493", "pm_score": 1, "selected": false, "text": "public Customer GetCustomer(int id)\n{\n return customerRepository.Get(id);\n}\n" }, { "answer_id": 339359, "author": "MotoWilliams", "author_id": 2730, "author_profile": "https://Stackoverflow.com/users/2730", "pm_score": 0, "selected": false, "text": "public ActionResult Index()\n{\n var widgetContext = new WidgetDataContext();\n var widgets = from w in widgetContext.Widget\n select w;\n return View(widgets);\n}\n" }, { "answer_id": 339393, "author": "Pure.Krome", "author_id": 30674, "author_profile": "https://Stackoverflow.com/users/30674", "pm_score": 5, "selected": false, "text": "public ActionResult Index()\n{\n ProductServices productServices = new ProductServices();\n\n // top 10 products, for example.\n IList<Product> productList = productServices.GetProducts(10); \n\n // Set this data into the custom viewdata.\n ViewData.Model = new ProductViewData\n {\n ProductList = productList;\n };\n\n return View();\n} \n // Field with the reference to all product services (aka. business logic)\nprivate readonly ProductServices _productServices;\n\n// 'Greedy' constructor, which Dependency Injection auto finds and therefore\n// will use.\npublic ProductController(ProductServices productServices)\n{\n _productServices = productServices;\n}\n\npublic ActionResult Index()\n{\n // top 10 products, for example.\n // NOTE: The services instance was automagically created by the DI\n // so i din't have to worry about it NOT being instansiated.\n IList<Product> productList = _productServices.GetProducts(10); \n\n // Set this data into the custom viewdata.\n ViewData.Model = new ProductViewData\n {\n ProductList = productList;\n };\n\n return View();\n}\n public class ProductServices : IProductServices\n{\n private readonly ProductRepository _productRepository;\n public ProductServices(ProductRepository productRepository)\n {\n _productRepository = productRepository;\n }\n\n public IList<Product> GetProducts(int numberOfProducts)\n {\n // GetProducts() and OrderByMostRecent() are custom linq helpers...\n return _productRepository.GetProducts()\n .OrderByMostRecent()\n .Take(numberOfProducts)\n .ToList();\n }\n}\n public class ProductServices\n{\n public IList<Product> GetProducts(int numberOfProducts)\n {\n using (DB db = new Linq2SqlDb() )\n {\n return (from p in db.Products\n orderby p.DateCreated ascending\n select p).Take(10).ToList();\n }\n }\n}\n" }, { "answer_id": 472486, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "Customer customer = new Customer();\n Customer customer = _custRepository.GetById(1)\n Customer customer = _custRepository.GetByKey(\"AlanSmith1\")\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338816", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1574/" ]
338,817
<p>I'm generating a menu with a Repeater control bound to an XmlDataSource. </p> <pre><code>&lt;asp:Repeater ID="myRepeater" runat="server" DataSourceID="myDataSource" onitemdatabound="myRepeater_ItemDataBound" onitemcreated="myRepeater_ItemCreated"&gt; &lt;HeaderTemplate&gt; &lt;ul class="menu_list"&gt; &lt;/HeaderTemplate&gt; &lt;ItemTemplate&gt; &lt;li id="liMenu" runat="server"&gt;&lt;asp:HyperLink ID="hrefMenuItem" runat="server" Text='&lt;%# XPath("@text")%&gt;' NavigateUrl='&lt;%# XPath("@href")%&gt;'&gt;&lt;/asp:HyperLink&gt;&lt;/li&gt; &lt;/ItemTemplate&gt; &lt;FooterTemplate&gt; &lt;/ul&gt; &lt;/FooterTemplate&gt; &lt;/asp:Repeater&gt; &lt;asp:XmlDataSource runat="server" ID ="myDataSource" XPath="Menu/Items/*" EnableCaching="False" /&gt; </code></pre> <p>I'd like to be able to set the style of the containing LI based on mouseover events and currently selected menu item. I tried via the HtmlGenericControl, but I receive an error that it's readonly.</p> <pre><code>protected void myRepeater_ItemDataBound(object sender, RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { HyperLink hrefCurrentMenuLink = e.Item.FindControl("hrefMenuItem") as HyperLink; HtmlGenericControl l_genericControl = e.Item.FindControl("liMenu") as HtmlGenericControl; if ((hrefCurrentMenuLink != null) &amp;&amp; (l_genericControl != null)) { string l_currentPage = GetCurrentWebPage(); if (String.Compare(Path.GetFileNameWithoutExtension(hrefCurrentMenuLink.NavigateUrl), l_currentPage, StringComparison.OrdinalIgnoreCase) == 0) l_genericControl.Style = "on-nav"; else l_genericControl.Style = "off-nav"; l_genericControl.Attributes.Add("onmouseover", "navOn(this)"); l_genericControl.Attributes.Add("onmouseout", "navOff(this)"); } } } </code></pre> <p>Is there any way to accomplish this?</p>
[ { "answer_id": 338843, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 4, "selected": true, "text": "l_genericControl.Style.Add(\"css-name\", \"css-value\")\n l_genericControl.CssClass = \"on-nav\";\n l_genericControl.Attributes.Add(\"onmouseover\", \"this.className='on-nav';\");\nl_genericControl.Attributes.Add(\"onmouseout\", \"this.className='off-nav';\");\n l_genericControl.Attributes.Add(\"onmouseover\", \"this.style.color='red'; this.style.backgroundColor='yellow';\");\nl_genericControl.Attributes.Add(\"onmouseout\", \"this.style.color='black'; this.style.backgroundColor='none';\");\n" }, { "answer_id": 338939, "author": "Jimmy", "author_id": 4435, "author_profile": "https://Stackoverflow.com/users/4435", "pm_score": 0, "selected": false, "text": "l_genericControl.Attributes[\"class\"] = \"on-nav\";\n" }, { "answer_id": 338964, "author": "mbillard", "author_id": 810, "author_profile": "https://Stackoverflow.com/users/810", "pm_score": 0, "selected": false, "text": "l_genericControl.Style = \"off-nav\";\n // += to prevent overwriting a class you would set in the markup\nl_genericControl.CssClass += \"off-nav\";\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338817", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27870/" ]
338,824
<p>Subversion lets you embed working copies of other repositories using <a href="http://svnbook.red-bean.com/en/1.1/ch07s04.html" rel="nofollow noreferrer">externals</a>, allowing easy version control of third-party library software in your project.</p> <p>While these seem ideal for the reuse of libraries and version control of <a href="http://svnbook.red-bean.com/en/1.1/ch07s05.html" rel="nofollow noreferrer">vendor software</a>, they aren't without <a href="https://stackoverflow.com/questions/222827/how-do-you-organize-your-version-control-repository#304036">their critics</a>:</p> <blockquote> <p>Please don't use Subversion externals (or similar in other tools), they are an anti-pattern and, therefore, unnecessary</p> </blockquote> <p>Are there hidden risks in using externals? Please explain why they would they be considered an antipattern.</p>
[ { "answer_id": 345404, "author": "Rob Williams", "author_id": 26682, "author_profile": "https://Stackoverflow.com/users/26682", "pm_score": 7, "selected": true, "text": "svn:external svn:external svn:external svn:external svn:external svn:external svn:external svn:external" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338824", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20074/" ]
338,836
<p>I have a GridView with several fields, one of which can potentially have a crazy wide value in it like this:</p> <p>aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa</p> <p>If <em>that</em> sort of thing is in the field, I want it to wrap.</p> <p>I can easily insert a character in code every 50 characters or so...but what character? If I use <strong>\r\n</strong> or a <strong>space</strong> or the like, then sometimes the setting doesn't wrap (because a different row's 50 chars is wider), and I get something like this:</p> <p>mmmmmmmmmm<br> mmmmm<br> llllllllll llllllllll llll</p> <p>I don't want those spaces to show up; I just want the line to wrap there if it can, but otherwise to show nothing:</p> <p>mmmmmmmmmm<br> mmmmm<br> llllllllllllllllllllllll</p> <p>Also, I'd rather leave HtmlEncode <em>on</em> if possible. Is there a way to do this?</p>
[ { "answer_id": 338901, "author": "Matt Briggs", "author_id": 10771, "author_profile": "https://Stackoverflow.com/users/10771", "pm_score": 2, "selected": false, "text": "white-space: -moz-pre-wrap; /* Mozilla, supported since 1999 */\nwhite-space: -pre-wrap; /* Opera 4 - 6 */ \nwhite-space: -o-pre-wrap; /* Opera 7 */ \nwhite-space: pre-wrap; /* CSS3 */ \nword-wrap: break-word; /* IE 5.5+ */\n" }, { "answer_id": 6958462, "author": "Seemal Asif", "author_id": 880826, "author_profile": "https://Stackoverflow.com/users/880826", "pm_score": 0, "selected": false, "text": "ItemStyle-Wrap=\"true\" ItemStyle-Width=\"100\"\n" }, { "answer_id": 16850391, "author": "Mits", "author_id": 2439162, "author_profile": "https://Stackoverflow.com/users/2439162", "pm_score": 3, "selected": false, "text": "protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)\n {\n if (e.Row.RowType == DataControlRowType.DataRow)\n {\n e.Row.Cells[1].Attributes.Add(\"style\", \"word-break:break-all;word-wrap:break-word\");\n }\n }\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338836", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5486/" ]
338,856
<p>Is there a way that I can do a select as such</p> <pre><code>select * from attributes where product_id = 500 </code></pre> <p>would return </p> <pre><code>id name description 1 wheel round and black 2 horn makes loud noise 3 window solid object you can see through </code></pre> <p>and the query</p> <pre><code>select * from attributes where product_id = 234 </code></pre> <p>would return the same results as would any query to this table.</p> <p>Now obviously I could just remove the where clause and go about my day. But this involves editing code that I don't really want to modify so i'm trying to fix this at the database level. </p> <p>So is there a "magical" way to ignore what is in the where clause and return whatever I want using a view or something ?</p>
[ { "answer_id": 339049, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 1, "selected": false, "text": "SELECT ordinal_position, column_name, column_comment\nFROM INFORMATION_SCHEMA.columns\nWHERE table_name = 'products' AND schema_name = 'mydatabase';\n" }, { "answer_id": 339936, "author": "benlumley", "author_id": 39161, "author_profile": "https://Stackoverflow.com/users/39161", "pm_score": 2, "selected": false, "text": "OR 1=1\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338856", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5261/" ]
338,887
<p>I'm looking at some GXT code for GWT and I ran across this use of Generics that I can't find another example of in the Java tutorials. The class name is <a href="http://extjs.com/deploy/gxtdocs/com/extjs/gxt/ui/client/data/BaseModelData.html" rel="noreferrer"><code>com.extjs.gxt.ui.client.data.BaseModelData</code></a> if you want to look at all of the code. Here are the important parts:</p> <pre><code>private RpcMap map; public &lt;X&gt; X get(String property) { if (allowNestedValues &amp;&amp; NestedModelUtil.isNestedProperty(property)) { return (X)NestedModelUtil.getNestedValue(this, property); } return map == null ? null : (X) map.get(property); } </code></pre> <p><code>X</code> is defined nowhere else in the class or anywhere in the hierarchy, and when I hit "go to declaration" in eclipse it just goes to the <code>&lt;X&gt;</code> in the public method signature.</p> <p>I've tried to call this method with the following two examples to see what happens:</p> <pre><code>public Date getExpiredate() { return get("expiredate"); } public String getSubject() { return get("subject"); } </code></pre> <p>They compile and show no errors or warnings. I would think at the very least I would have to do a cast to get this to work.</p> <p>Does this mean that Generics allow a magic return value that can be anything and will just blow up at runtime? This seems counter to what generics are supposed to do. Can anyone explain this to me and possibly give me a link to some documentation that explains this a little better? I've went through Sun's 23 page pdf on generics and every example of a return value is defined either at the class level or is in one of the parameters passed in.</p>
[ { "answer_id": 338906, "author": "sblundy", "author_id": 4893, "author_profile": "https://Stackoverflow.com/users/4893", "pm_score": 5, "selected": false, "text": "<X> Collections.emptySet() public static final <T> Set<T> emptySet()\n Set<String> s = Collections.emptySet();\n Collections.<String>emptySet();\n" }, { "answer_id": 338913, "author": "Rich", "author_id": 42897, "author_profile": "https://Stackoverflow.com/users/42897", "pm_score": 2, "selected": false, "text": "public java.lang.Object get(java.lang.Object key)\n <X>" }, { "answer_id": 338917, "author": "Joachim Sauer", "author_id": 40342, "author_profile": "https://Stackoverflow.com/users/40342", "pm_score": 7, "selected": true, "text": "<X> get()" }, { "answer_id": 338955, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 2, "selected": false, "text": "public String getExpireDate() {\n return get(\"expiredate\");\n}\n" }, { "answer_id": 572940, "author": "paulmurray", "author_id": 63189, "author_profile": "https://Stackoverflow.com/users/63189", "pm_score": 0, "selected": false, "text": "<X> getProperty(String name, Class<X> clazz) {\n X foo = (X) whatever(name);\n assert clazz.isAssignableFrom(foo);\n return foo;\n}\n\nString getString(String name) {\n return getProperty(name, String.class);\n}\n\nint getInt(String name) {\n return getProperty(name, Integer.class);\n}\n" }, { "answer_id": 7570977, "author": "Kyrra", "author_id": 697255, "author_profile": "https://Stackoverflow.com/users/697255", "pm_score": 3, "selected": false, "text": "class Model {\n public <X> X get(String property) { ... }\n}\n public String myMethod(Data data) {\n Model model = new Model(data);\n return model.<String>get(\"status\");\n}\n this.<String>get(\"status\");\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338887", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42994/" ]
338,895
<p>In earlier versions of MS-DOS - I want to say version 7, but I could be wrong - there was a <code>deltree</code> command, which recursively deleted all subdirectories and files from a given path. </p> <p><code>deltree</code> no longer exists, but <code>del</code> didn't seem to inherit the ability to delete a tree. <code>del /s</code> deletes files, but not folders.</p> <p>How to you easily (i.e., in one command) delete a tree from a batch file?</p>
[ { "answer_id": 338905, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 3, "selected": false, "text": "rmdir /s /q directory\n" }, { "answer_id": 338921, "author": "Jeremiah", "author_id": 34183, "author_profile": "https://Stackoverflow.com/users/34183", "pm_score": 6, "selected": false, "text": "RMDIR /S /Q Folder2Delete\nRD /S /Q Folder2Delete\n" }, { "answer_id": 14345791, "author": "Synetech", "author_id": 119540, "author_profile": "https://Stackoverflow.com/users/119540", "pm_score": 8, "selected": true, "text": "rd /s /q rd /s /q c:\\foobar\n rd deltree windows deltree deltree deltree /y c:\\foobar\ndeltree /y c:\\baz.txt\n rd rd /s /q c:\\foobar\nrd /s /q c:\\baz.txt\n del del /f /q c:\\foobar\ndel /f /q c:\\baz.txt\n deltree rd del deltree del rd ::deltree.bat\n\n@echo off\nrd %* 2> nul\ndel %* 2> nul\n deltree.bat /s /q /f c:\\foobar\ndeltree.bat /s /q /f c:\\baz.txt\n rd del nul deltree" }, { "answer_id": 29312066, "author": "raychi", "author_id": 949370, "author_profile": "https://Stackoverflow.com/users/949370", "pm_score": 3, "selected": false, "text": "deltree v1.01 [Mar 27 2015, 16:31:02] (gcc 4.9.1)\n\nUsage: deltree [options] <path> ...\n\nOptions:\n -y yes, suppresses prompting for confirmation\n -s silent, do not display any progress dialog\n -n do nothing, simulate the operation\n -f force, no prompting/silent (for rm compatibility)\n -r ignored (for rm compatibility)\n\nDelete directories and all the subdirectories and files in it.\n deltree -rf *\n" }, { "answer_id": 37736666, "author": "Gregg", "author_id": 6317147, "author_profile": "https://Stackoverflow.com/users/6317147", "pm_score": 1, "selected": false, "text": "rd /s MY_DOOMED_DIR\n" }, { "answer_id": 42276685, "author": "Rosberg Linhares", "author_id": 2160765, "author_profile": "https://Stackoverflow.com/users/2160765", "pm_score": 3, "selected": false, "text": "powershell -Command \"Remove-Item 'PathToMyDirectory\\*' -Recurse -Force\"\n" }, { "answer_id": 51887676, "author": "Theprogrammer7018", "author_id": 10237228, "author_profile": "https://Stackoverflow.com/users/10237228", "pm_score": 0, "selected": false, "text": "cd (your directory here)\ndel *.* /f /s /q\n" }, { "answer_id": 52587085, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "cd /d Directory && rd /s /q .\\\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338895", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2197/" ]
338,927
<p>Given the following Flash method:</p> <pre><code>function sendToJava(name:String, ... args) { ExternalInterface.call("sendCommand", name, args); } </code></pre> <p>How do I ensure that ExternalInterface.call() interprets args in its expanded form? Right now, if I pass a list into "args", that list gets interpreted as a single argument of type "Object[]" by ExternalInterface.call(). When the arguments reach Java, I have no way of differentiating between multiple arguments separated by commas versus a single argument containing commas as part of its value.</p>
[ { "answer_id": 339001, "author": "Gili", "author_id": 14731, "author_profile": "https://Stackoverflow.com/users/14731", "pm_score": 1, "selected": false, "text": "function sendToJava(name:String, ... args)\n{\n // See Array.unshift()\n args.unshift(\"sendCommand\", name);\n\n // See Function.apply()\n ExternalInterface.call.array(null, args);\n}\n" }, { "answer_id": 476643, "author": "Micah", "author_id": 19964, "author_profile": "https://Stackoverflow.com/users/19964", "pm_score": 4, "selected": true, "text": "function sendToJava(name:String, ... args)\n{\n // See Array.unshift()\n args.unshift(\"sendCommand\", name);\n\n // See Function.apply()\n ExternalInterface.call.apply(null, args);\n}\n" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338927", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14731/" ]
338,928
<p>I have a php script which accesses a MSSQL2005 database, reads some data from it and sends the results in a mail. </p> <p>There are special characters in both some column names and in the fields itself. </p> <p>When I access the script through my browser (webserver iis), the query is executed correctly and the contents of the mail are correctly (for my audience) encoded. However, when I execute php from the console, the query fails (due to the special characters in the column names). If I replace the special characters in the query with calls to chr() and the character code in latin-1, the query gets executed correctly, but the results are also encoded in latin-1 and therefore not displayed correctly in the mail. Why is PHP/the MSSQL driver/… using a different encoding in the two scenarios? Is there a way around it? </p> <p>If you wonder, I need the console because I want to schedule the script using SQLAgent (or taskmanager or whatever).</p>
[ { "answer_id": 364615, "author": "david", "author_id": 27600, "author_profile": "https://Stackoverflow.com/users/27600", "pm_score": 1, "selected": false, "text": "$send_string = base64_encode(utf8_decode($database_string));\n" }, { "answer_id": 364738, "author": "lpfavreau", "author_id": 35935, "author_profile": "https://Stackoverflow.com/users/35935", "pm_score": 3, "selected": true, "text": "chcp chcp 65001" } ]
2008/12/03
[ "https://Stackoverflow.com/questions/338928", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5218/" ]