qid
int64
4
19.1M
question
stringlengths
18
48.3k
answers
list
date
stringlengths
10
10
metadata
list
346,169
<p>How do you decide between passing arguments to a method versus simply declaring them as object instance variables that are visible to all of the object's methods?</p> <p>I prefer keeping instance variables in a list at the end of the Class, but this list gets longer as my program grows. I figure if a variable is passed often enough it should just be visible to all methods that need it, but then I wonder, &quot;if everything is public there will be no need for passing anything at all!&quot;</p>
[ { "answer_id": 346184, "author": "ng.mangine", "author_id": 37784, "author_profile": "https://Stackoverflow.com/users/37784", "pm_score": 5, "selected": false, "text": "myCircle = myDrawing.drawCircle(center, radius);\n myCircle.move(newCenter);\nmyCircle.resize(newRadius);\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346169", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29182/" ]
346,175
<p>In 64 bit versions of windows, 32 bit software is installed in "c:\program files (x86)". This means you cannot use $(programfiles) to get the path to (32 bit) software. So I need a $(ProgramFiles32) to overcome this in my MSBuild project. I don't want to change the project depending on the os it is running on.</p> <p>I have a solution that I will post, but maybe there is a easier/better way.</p>
[ { "answer_id": 346176, "author": "wimh", "author_id": 33499, "author_profile": "https://Stackoverflow.com/users/33499", "pm_score": 4, "selected": false, "text": "<PropertyGroup>\n <ProgramFiles32 Condition=\"Exists('$(PROGRAMFILES) (x86)')\">$(PROGRAMFILES) (x86)</ProgramFiles32>\n <ProgramFiles32 Condition=\"$(ProgramFiles32) == ''\">$(PROGRAMFILES)</ProgramFiles32>\n</PropertyGroup>\n <Exec WorkingDirectory=\"src\\app1\" Command='\"$(ProgramFiles32)\\doxygen\\bin\\doxygen\" Doxyfile' />\n" }, { "answer_id": 1052245, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 3, "selected": false, "text": "\"$(MSBuildExtensionsPath32)\\..\"" }, { "answer_id": 2519388, "author": "Jedidja", "author_id": 9913, "author_profile": "https://Stackoverflow.com/users/9913", "pm_score": 1, "selected": false, "text": "<PropertyGroup>\n <OSBits Condition=\"$(ProgramW6432) != ''\">x64</OSBits>\n <OSBits Condition=\"$(OSBits) == ''\">x32</OSBits>\n</PropertyGroup>\n %ProgramW6432%" }, { "answer_id": 4380939, "author": "Rory MacLeod", "author_id": 1016, "author_profile": "https://Stackoverflow.com/users/1016", "pm_score": 4, "selected": false, "text": "$(MSBuildProgramFiles32)" }, { "answer_id": 5650767, "author": "Ruben Bartelink", "author_id": 11635, "author_profile": "https://Stackoverflow.com/users/11635", "pm_score": 7, "selected": true, "text": "$(MSBuildProgramFiles32) ToolsVersion=\"4.0\" <PropertyGroup>\n <!--MSBuild 4.0 property-->\n <ProgramFiles32>$(MSBuildProgramFiles32)</ProgramFiles32> \n <!--Use OS env var as a fallback:- 32 bit MSBuild 2.0/3.5 on x64 will use this-->\n <ProgramFiles32 Condition=\" '' == '$(ProgramFiles32)'\">$(ProgramFiles%28x86%29)</ProgramFiles32>\n\n <!-- Handle MSBuild 2.0/3.5 running in 64 bit mode - neither of the above env vars are available. http://stackoverflow.com/questions/336633\n NB this trick (Adding a literal \" (x86)\" to the 64 bit Program Files path) may or may not work on all versions/locales of Windows -->\n <ProgramFiles32 Condition =\"'$(ProgramFiles32)'=='' AND 'AMD64' == '$(PROCESSOR_ARCHITECTURE)'\">$(ProgramFiles) (x86)</ProgramFiles32>\n\n <!--Catch-all - handles .NET 2.0/3.5 non-AMD64 and .NET 2.0 on x86 -->\n <ProgramFiles32 Condition=\" '' == '$(ProgramFiles32)' \">$(ProgramFiles)</ProgramFiles32>\n</PropertyGroup>\n MSBuildProgramFiles32 <PropertyGroup> <CreateProperty>" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346175", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33499/" ]
346,189
<p>I want to use the built-in preference system for my xulrunner (Firefox) application. But I can't figure out how to easily drive the user interface based on preferences.</p> <p>The user can specify a list of home pages, and each home page will show up in a different tab. Because the tabs are in the presentation layer, I'd like to create them using a template in the xul code. Is this possible?</p> <p>I haven't seen a way to do this with xul templates. Is there an alternative templating system that would allow me to change the UI based on user preferences?</p>
[ { "answer_id": 931647, "author": "vava", "author_id": 6258, "author_profile": "https://Stackoverflow.com/users/6258", "pm_score": 0, "selected": false, "text": "\nXML.prototype.function::domNode = function domNode() {\n function addPrefix(prefix, name) {\n if (typeof(prefix) == \"undefined\" || prefix == null || prefix == \"\") {\n return name;\n } else {\n return prefix + \":\" + name;\n }\n }\n\n function recurse(xml) {\n var domNode = document.createElementNS(xml.namespace().uri, addPrefix(xml.namespace().prefix, xml.localName()));\n\n for each (let attr in xml.@*::*) {\n let attrNode = document.createAttributeNS(attr.namespace().uri, addPrefix(attr.namespace().prefix, attr.localName()));\n attrNode.nodeValue = attr;\n domNode.setAttributeNode(attrNode);\n }\n if (xml.hasComplexContent()) {\n for each (let node in xml.*) {\n domNode.appendChild(recurse(node));\n }\n } else if (xml.hasSimpleContent()) {\n domNode.appendChild(document.createTextNode(xml));\n }\n return domNode;\n }\n\n return recurse(this);\n};\n\nvar name = \"example\"\nvar xml = {name};\n\ndocument.querySelector(\"#example-statusbar-panel\").appendChild(xml.domNode());\n\n var str = serializer.serializeToString( xml.domNode() );\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346189", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37784/" ]
346,226
<p>I am totally new to XSLT and can't work out where I am going wrong with the following code.</p> <pre><code>&lt;xsl:variable name="var" select="boolean('false')"/&gt; &lt;xsl:if test="$var'"&gt;variable is true&lt;/xsl:if&gt; </code></pre> <p>It is always returning true when it is meant to be false. Why?</p>
[ { "answer_id": 346227, "author": "Yuval Adam", "author_id": 24545, "author_profile": "https://Stackoverflow.com/users/24545", "pm_score": 4, "selected": false, "text": "<xsl:variable name=\"var_false\" select=\"false()\"/>\n<xsl:variable name=\"var_true\" select=\"true()\"/>\n" }, { "answer_id": 346505, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 8, "selected": true, "text": "<xsl:variable name=\"var\" select=\"boolean('false')\"/> true() false false() boolean false() true() false() true() false() <xsl:variable name=\"vMyVar\" select=\"false()\"/> <xsl:variable name=\"vMyVar\" select=\"1 = 0\"/> false() <xsl:variable name=\"vMyVar\" as=\"xs:boolean\" select=\"false()\"/>" }, { "answer_id": 6212697, "author": "outofcoolnames", "author_id": 780866, "author_profile": "https://Stackoverflow.com/users/780866", "pm_score": 3, "selected": false, "text": "<xsl:variable name=\"vTrue\" select=\"true()\"/> \n <xsl:choose>\n <xsl:when test=\"string(Mandatory) = string($vTrue)\">\n <xsl:text>Mandatory</xsl:text>\n </xsl:when>\n <xsl:otherwise> \n </xsl:otherwise>\n </xsl:choose>\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/5838/" ]
346,230
<p>I'm using <code>urllib2</code> to read in a page. I need to do a quick regex on the source and pull out a few variables but <code>urllib2</code> presents as a file object rather than a string.</p> <p>I'm new to python so I'm struggling to see how I use a file object to do this. Is there a quick way to convert this into a string?</p>
[ { "answer_id": 346237, "author": "stesch", "author_id": 41860, "author_profile": "https://Stackoverflow.com/users/41860", "pm_score": 7, "selected": true, "text": "f dir(f) read help(f.read) f.read()" }, { "answer_id": 346260, "author": "t3rse", "author_id": 64, "author_profile": "https://Stackoverflow.com/users/64", "pm_score": 3, "selected": false, "text": "import urllib2\nimport re\nresponse = urllib2.urlopen(\"http://www.voidspace.org.uk/python/articles/urllib2.shtml\")\nhtml = response.read()\npattern = '(V.+space)'\nwordPattern = re.compile(pattern, re.IGNORECASE)\nresults = wordPattern.search(html)\nprint results.groups()\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346230", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12870/" ]
346,243
<p>If i have the following directory structure:</p> <p>Project1/bin/debug<br> Project2/xml/file.xml</p> <p>I am trying to refer to file.xml from Project1/bin/debug directory</p> <p>I am essentially trying to do the following:</p> <pre><code>string path = Environment.CurrentDirectory + @"..\..\Project2\xml\File.xml": </code></pre> <p>what is the correct syntax for this?</p>
[ { "answer_id": 346248, "author": "lubos hasko", "author_id": 275, "author_profile": "https://Stackoverflow.com/users/275", "pm_score": 2, "selected": false, "text": "System.IO.Path.GetFullPath(@\"..\\..\\Project2\\xml\\File.xml\")\n" }, { "answer_id": 346249, "author": "Blair Conrad", "author_id": 1199, "author_profile": "https://Stackoverflow.com/users/1199", "pm_score": 4, "selected": true, "text": "string path = System.IO.Path.Combine(Environment.CurrentDirectory, \n @\"..\\..\\..\\Project2\\xml\\File.xml\");\n" }, { "answer_id": 346251, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "string path = Path.Combine( Environment.CurrentDirectory,\n @\"..\\..\\..\\Project2\\xml\\File.xml\" );\n" }, { "answer_id": 346259, "author": "M4N", "author_id": 19635, "author_profile": "https://Stackoverflow.com/users/19635", "pm_score": 1, "selected": false, "text": "string path = System.IO.Path.Combine(@\"c:\\dir1\\dir2\",\n @\"..\\..\\Project2\\xml\\File.xml\");\n @\"c:\\dir1\\dir2\\dir3\\..\\..\\Project2\\xml\\File.xml\"\n public static string CombinePaths(string rootPath, string relativePath)\n{\n DirectoryInfo dir = new DirectoryInfo(rootPath);\n while (relativePath.StartsWith(\"..\\\\\"))\n {\n dir = dir.Parent;\n relativePath = relativePath.Substring(3);\n }\n return Path.Combine(dir.FullName, relativePath);\n}\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346243", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
346,267
<p>I have a string like this that I need to parse into a 2D array:</p> <pre><code> str = &quot;'813702104[813702106]','813702141[813702143]','813702172[813702174]'&quot; </code></pre> <p>the array equiv would be:</p> <pre><code>arr[0][0] = 813702104 arr[0][1] = 813702106 arr[1][0] = 813702141 arr[1][1] = 813702143 #... etc ... </code></pre> <p>I'm trying to do this by REGEX. The string above is buried in an HTML page but I can be certain it's the only string in that pattern on the page. I'm not sure if this is the best way, but it's all I've got right now.</p> <pre><code>imgRegex = re.compile(r&quot;(?:'(?P&lt;main&gt;\d+)\[(?P&lt;thumb&gt;\d+)\]',?)+&quot;) </code></pre> <p>If I run <code>imgRegex.match(str).groups()</code> I only get one result (the first couplet). How do I either get multiple matches back or a 2d match object (if such a thing exists!)?</p> <p><em>Note: Contrary to how it might look, this is <strong>not</strong> homework</em></p> <h1>Note <em>part deux</em>: The real string is embedded in a <em>large</em> HTML file and therefore splitting does not appear to be an option.</h1> <p>I'm still getting answers for this, so I thought I better edit it to show why I'm not changing the accepted answer. Splitting, though more efficient on this test string, isn't going to extract the parts from a whole HTML file. I <em>could</em> combine a regex and splitting but that seems silly.</p> <p>If you do have a better way to find the parts from a load of HTML (the pattern <code>\d+\[\d+\]</code> is unique to this string in the source), I'll happily change accepted answers. Anything else is academic.</p>
[ { "answer_id": 346276, "author": "stesch", "author_id": 41860, "author_profile": "https://Stackoverflow.com/users/41860", "pm_score": 4, "selected": true, "text": "findall finditer match findall r\"'(?P<main>\\d+)\\[(?P<thumb>\\d+)\\]',?\"\n" }, { "answer_id": 346281, "author": "gimel", "author_id": 6491, "author_profile": "https://Stackoverflow.com/users/6491", "pm_score": 1, "selected": false, "text": ">>> str = \"'813702104[813702106]','813702141[813702143]','813702172[813702174]\"\n>>> imgRegex = re.compile(r\"'(?P<main>\\d+)\\[(?P<thumb>\\d+)\\]',?\")\n>>> print imgRegex.findall(str)\n[('813702104', '813702106'), ('813702141', '813702143')]\n" }, { "answer_id": 346284, "author": "ayaz", "author_id": 23191, "author_profile": "https://Stackoverflow.com/users/23191", "pm_score": 1, "selected": false, "text": "In [19]: str = \"'813702104[813702106]','813702141[813702143]','813702172[813702174]'\"\nIn [20]: ptr = re.compile( r\"'(?P<one>\\d+)\\[(?P<two>\\d+)\\]'\" )\nIn [21]: ptr.findall( str )\nOut [23]:\n[('813702104', '813702106'),\n ('813702141', '813702143'),\n ('813702172', '813702174')]\n" }, { "answer_id": 346292, "author": "JV.", "author_id": 33612, "author_profile": "https://Stackoverflow.com/users/33612", "pm_score": 2, "selected": false, "text": "In [27]: s = \"'813702104[813702106]','813702141[813702143]','813702172[813702174]'\"\n\nIn [28]: d=[[int(each1.strip(']\\'')) for each1 in each.split('[')] for each in s.split(',')]\n\nIn [29]: d[0][1]\nOut[29]: 813702106\n\nIn [30]: d[1][0]\nOut[30]: 813702141\n\nIn [31]: d\nOut[31]: [[813702104, 813702106], [813702141, 813702143], [813702172, 813702174]]\n" }, { "answer_id": 369036, "author": "Ben Blank", "author_id": 46387, "author_profile": "https://Stackoverflow.com/users/46387", "pm_score": 1, "selected": false, "text": ">>> str = \"'813702104[813702106]','813702141[813702143]','813702172[813702174]'\"\n>>> arr = [pair for pair in str.split(\",\")]\n>>> arr\n[\"'813702104[813702106]'\", \"'813702141[813702143]'\", \"'813702172[813702174]'\"]\n >>> arr = [pair[1:-2].split(\"[\") for pair in str.split(\",\")]\n>>> arr\n>>> [['813702104', '813702106'], ['813702141', '813702143'], ['813702172', '813702174']]\n >>> arr = [[int(x) for x in pair[1:-2].split(\"[\")] for pair in str.split(\",\")]\n>>> arr\n>>> [[813702104, 813702106], [813702141, 813702143], [813702172, 813702174]]\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346267", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12870/" ]
346,268
<p>I have data that needs to be executed on a certain background thread. I have code coming from all other threads that need to call into this. does anyone have a good tutorial or best practice on having a queue for synchronization to support this threading requirement</p>
[ { "answer_id": 346312, "author": "Michael Haren", "author_id": 29, "author_profile": "https://Stackoverflow.com/users/29", "pm_score": 1, "selected": false, "text": "producer/consumer Main() TaskQueue.Dequeue() tasks TaskQueueTask Execute()" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346268", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
346,297
<p>Hi all I've just started a new project using Visual Web Developer 2008 Express and all my code behinds are not in any namespace. How can I set the default namespace for the project?</p> <p>In VisualStudioPro it used to be in project properties, the website properties in Visual Web Developer 2008 Express seem very ... express.</p> <p>Thanks,</p> <p>David.</p>
[ { "answer_id": 346493, "author": "mmx", "author_id": 33708, "author_profile": "https://Stackoverflow.com/users/33708", "pm_score": 3, "selected": true, "text": "namespace MyDefaultNamespace {\n // original code\n}\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346297", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12148/" ]
346,306
<p>I have used a static global variable and a static volatile variable in file scope, <p> both are updated by an ISR and a main loop and main loop checks the value of the variable. <p>here during optimization neither the global variable nor the volatile variable are optimized. So instead of using a volatile variable a global variable solves the problem. <p>So is it good to use global variable instead of volatile? <p>Any specific reason to use static volatile?? <p>Any example program would be appreciable. <p>Thanks in advance..</p>
[ { "answer_id": 346318, "author": "friol", "author_id": 23034, "author_profile": "https://Stackoverflow.com/users/23034", "pm_score": 4, "selected": false, "text": "#define MYPORT 0xDEADB33F\n\nvolatile char *portptr = (char*)MYPORT;\n*portptr = 'A';\n*portptr = 'B';\n" }, { "answer_id": 346397, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 5, "selected": true, "text": "static help main .c help volatile volatile && || ; .c" }, { "answer_id": 346417, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 5, "selected": false, "text": "extern const volatile volatile volatile class Gadget\n{\npublic:\n void Wait()\n {\n while (!flag_)\n {\n Sleep(1000); // sleeps for 1000 milliseconds\n }\n }\n void Wakeup()\n {\n flag_ = true;\n }\n ...\nprivate:\n bool flag_;\n};\n Sleep() Sleep() flag_ Wait() volatile flag_ volatile volatile int * int * volatile" }, { "answer_id": 6724907, "author": "Papun", "author_id": 848803, "author_profile": "https://Stackoverflow.com/users/848803", "pm_score": -1, "selected": false, "text": "{\nvolatile int a=10;\na++;\n}" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346306", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31116/" ]
346,313
<p>I'm trying to do a JOIN in Linq using lambda expressions ... and running into some problems. </p> <p>I have two entities, Comments and CommentSources. CommentSources are associated to Comments. I have the following code, which does work:</p> <pre><code>01 IQueryable&lt;Data.Comment&gt; query = ctx.DataContext.Comments; 02 03 04 if (criteria.IsDeleted == DeletedFilter.Deleted) 05 query = query.Where(row =&gt; row.DeletedBy != Guid.Empty); 06 else if (criteria.IsDeleted == DeletedFilter.NotDeleted) 07 query = query.Where(row =&gt; row.DeletedBy == Guid.Empty); 08 09 var data = query.Select(row =&gt; CommentInfo.FetchCommentInfo(row)); </code></pre> <p>I need to join CommentSources on Comments on the field, and I would like to use, if possible, something like:</p> <pre><code>01 query = query.Join(join code goes here) </code></pre> <p>How can I do this using lambdas in the expression tree?</p> <p><strong>One more thing ... how do I add a Where to the Join statement?</strong></p> <p>Instead of asking another question ... how would I do a Where clause on that Join? For example, I have a field called SourceId on the CommentSource that I would like to filter by.</p>
[ { "answer_id": 346346, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 5, "selected": true, "text": "query = query.Join(ctx.DataContext.CommentSource,\n comment => comment.CommentSourceId,\n commentSource => commentSource.Id,\n (comment, commentSource) \n => new { Comment=comment, CommentSource=commentSource });\n" }, { "answer_id": 346389, "author": "mattruma", "author_id": 1768, "author_profile": "https://Stackoverflow.com/users/1768", "pm_score": 3, "selected": false, "text": " var query = ctx.DataContext.Comments.Join(ctx.DataContext.CommentSources,\n c => c.CommentId, \n s => s.CommentId,\n (c, s) => new {Comment = c, CommentSource = s});\n\n if (criteria.SourceId != null && criteria.SourceId != Guid.Empty)\n query = query.Where(row => row.CommentSource.SourceId == criteria.SourceId);\n\n if (criteria.IsDeleted == DeletedFilter.Deleted)\n query = query.Where(row => row.Comment.DeletedBy != Guid.Empty);\n else if (criteria.IsDeleted == DeletedFilter.NotDeleted)\n query = query.Where(row => row.Comment.DeletedBy == Guid.Empty);\n\n var data = query.Select(row => CommentInfo.FetchCommentInfo(row.Comment));\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346313", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ]
346,323
<p>I'm starting to code up my own window manager, and was wondering how to use the xorg api to get from raw image data ( such as the data given by libpng ), into an Xorg Pixmap or something drawable by Xorg?</p>
[ { "answer_id": 6772012, "author": "Dave", "author_id": 852548, "author_profile": "https://Stackoverflow.com/users/852548", "pm_score": 0, "selected": false, "text": "struct Image img = get_pixels_and_geometry_from_libpng(\"filename.png\");\nXImage *img = XCreateImage(/*5000 paremeters*/);\nPixmap pixmap = XCreatePixmap(dpy, img.width, img.height, 24);\nXPutImage(dpy, pixmap, gc, 0, 0, img.width, img.height);\nXCopyArea(dpy, pixmap, window, 0, 0, img.width, img.height, x, y);\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346323", "https://Stackoverflow.com", "https://Stackoverflow.com/users/25893/" ]
346,345
<p>I have been hearing that with unit testing we can catch most of the bugs in the code and I really believe that this is true. But my question is in large projects where each class is dependent on many other classes how do you go about unit testing the class ? Stubbing out every other class doesn't make much sense because of both complexity and the time required to write the stubs. What is your opinion about it?</p>
[ { "answer_id": 346483, "author": "Jeffrey Fredrick", "author_id": 35894, "author_profile": "https://Stackoverflow.com/users/35894", "pm_score": 0, "selected": false, "text": "public int foo(A a, B b) {\n C c = a.getC();\n D d = b.getD();\n\n Bar bar = calculateBar(c, d);\n\n return calculateFoo(bar, this.baz);\n}\n\nBar calculateBar(C c, D d) {\n ...\n}\n\nint calculateFoo(Bar bar, Baz baz) {\n ...\n}\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346345", "https://Stackoverflow.com", "https://Stackoverflow.com/users/39742/" ]
346,349
<p>I want to create a program that requests from the user 10 grades and then filters them to pass and fail, then prints the number of passes and fails. I did the program but the output is wrong.</p> <pre><code>int pass,fail,grade,studentcounter; pass=0; fail=0; grade=0; studentcounter=10; while (studentcounter!=0) { printf("enter the next grade\n"); scanf("%d",grade); student--; } switch (grade) { case 1: if (grade &gt;= 50) pass++; break; case 2: if (grade &lt;= 49) fail++; break; } } printf("the number of fail is %d",fail); printf("the number of pass is %d",pass); } </code></pre> <p>The problem is that the program request the ten grades but at the end it will print the number of fail and the number of pass as zero. Why?</p>
[ { "answer_id": 346357, "author": "John T", "author_id": 36457, "author_profile": "https://Stackoverflow.com/users/36457", "pm_score": 3, "selected": true, "text": "studentcounter=0;\n\nwhile (studentcounter!=0) {\n\nprintf(\"enter the next grade\\n\");\n\nscanf(\"%d\",grade);\n\nstudent--;\n\n}\n #include <stdio.h>\n#include <stdlib.h>\n\nint main()\n{\nint pass,fail,grade,studentcounter;\n\npass=0;\nfail=0;\ngrade=0;\nstudentcounter=0;\n\nwhile (studentcounter < 10) {\n\nprintf(\"enter the next grade:\\n\");\n\nscanf(\"%d\",&grade);\n\nif (grade >= 50) {\n pass++;\n} else {\n fail++;\n}\n\nstudentcounter++;\n}\n\n\nprintf(\"the number of fail is: %d \\n\",fail);\nprintf(\"the number of pass is: %d \\n\",pass);\nreturn 0;\n}\n" }, { "answer_id": 346368, "author": "Brian C. Lane", "author_id": 27461, "author_profile": "https://Stackoverflow.com/users/27461", "pm_score": 0, "selected": false, "text": "#include <stdio.h>\n\nint main(int argc, char *argv[])\n{\n int pass = 0;\n int fail = 0;\n int grade= 0;\n int studentcounter;\n\n for (studentcounter=1; studentcounter<=10; studentcounter++ )\n {\n printf(\"Enter grade for student #%-2d :\", studentcounter);\n scanf(\"%d\",&grade);\n\n if(grade >=50)\n pass++;\n\n if(grade<=49)\n fail++;\n }\n printf(\"the number of fail is %d\\n\",fail);\n printf(\"the number of pass is %d\\n\",pass);\n}\n" }, { "answer_id": 374108, "author": "Raghu", "author_id": 41518, "author_profile": "https://Stackoverflow.com/users/41518", "pm_score": 0, "selected": false, "text": "char pass_fail = (grade >= 50)? y : n;\nswitch( pass_fail )\n{\ncase 'y': \n // print pass\n break;\ncase 'n':\n // print fail\n break;\n}\n" }, { "answer_id": 27415854, "author": "Anmol Garg", "author_id": 4348535, "author_profile": "https://Stackoverflow.com/users/4348535", "pm_score": 0, "selected": false, "text": "void main()\n{\n int pass,fail,grade,studentcounter;\n\n pass=0;\n fail=0;\n grade=0;\n studentcounter=10;\n\n while (studentcounter!=0)\n {\n printf(\"enter the next grade\\n\");\n scanf(\"%d\",grade);\n studentcounter--;\n\n switch (grade)\n {\n case 1:\n if (grade >= 50)\n pass++;\n break;\n case 2:\n if (grade <= 49)\n fail++;\n break;\n }\n\n }\n printf(\"the number of fail is %d\",fail);\n printf(\"the number of pass is %d\",pass);\n\n}\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346349", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
346,352
<p>Can somebody give some clear explanation of the meaning of the SIZE and RSS values we get from prstat in Solaris?</p> <p>I wrote a testing C++ application that allocates memory with <code>new[]</code>, fills it and frees it with <code>delete[]</code>.</p> <p>As I understood, the SIZE value should be related to how much virtual memory has been "reserved" by the process, that is memory "malloced" or "newed".</p> <p>That memory doesn't sum up in the RSS value unless I really use it (filling with some values). But then even if I free the memory, the RSS doesn't drop.</p> <p>I don't understand what semantic I can correctly assign to those 2 values.</p>
[ { "answer_id": 2023651, "author": "jlliagre", "author_id": 211665, "author_profile": "https://Stackoverflow.com/users/211665", "pm_score": 4, "selected": true, "text": "export LD_PRELOAD=libumem.so\nexport UMEM_OPTIONS=backend=mmap\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346352", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41789/" ]
346,361
<p>I'm developing a experimental <strong>Linux Kernel module</strong>, so...</p> <p>How to <strong>UDP Broadcast</strong> from Linux Kernel?</p>
[ { "answer_id": 346727, "author": "Evan Anderson", "author_id": 40764, "author_profile": "https://Stackoverflow.com/users/40764", "pm_score": 2, "selected": false, "text": "lock_sock(sock->sk);\nsock->sk->broadcast = 1;\nrelease_sock(sock->sk);\n" }, { "answer_id": 346731, "author": "Daniel Silveira", "author_id": 1100, "author_profile": "https://Stackoverflow.com/users/1100", "pm_score": 2, "selected": false, "text": "SO_BROADCAST ENOPROTOOPT //Socket creation\nsock_create(AF_INET, SOCK_DGRAM, IPPROTO_UDP, &sock);\n\n//Broadcasting\nint broadcast = 1;\nint err;\n\nif( (err = sock->ops->setsockopt(sock, SOL_SOCKET, SO_BROADCAST, (char *)&broadcast, sizeof broadcast)) < 0 )\n{\n printk(KERN_ALERT MODULE_NAME \": Could not configure broadcast, error %d\\n\", err);\n return -1;\n}\n setsockopt ENOPROTOOPT SOL_SOCKET IPPROTO_UDP SOL_SOCKET SO_BROADCAST SOL_SOCKET SOL_UDP sock_sendmsg sock->sk->sk_flags |= SO_BROADCAST;\n" }, { "answer_id": 37965574, "author": "André Müller", "author_id": 6498727, "author_profile": "https://Stackoverflow.com/users/6498727", "pm_score": 0, "selected": false, "text": "int yes = 1;\nsock_setsockopt(sock, SOL_SOCKET, SO_BROADCAST, &yes, sizeof(yes));\n\nsock->ops->connect(sock, (struct sockaddr *)&addr, sizeof(struct sockaddr), 0);\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346361", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1100/" ]
346,362
<p>I have several templates that match various nodes in an xml document. If I do just an<br> &lt;xsl:apply-templates/> it somehow recursively outputs the text of all the nodes beneath. I just want it to recursively match any template I have defined. How do I do that ? </p>
[ { "answer_id": 346396, "author": "Dirk Vollmar", "author_id": 40347, "author_profile": "https://Stackoverflow.com/users/40347", "pm_score": 2, "selected": false, "text": "<xsl:template match=\"* | /\" >\n <xsl:apply-templates mode=\"myMode\" />\n</xsl:template>\n\n<xsl:template match=\"somenode\" mode=\"myMode\">\n <!-- do something here -->\n</xsl:template>\n" }, { "answer_id": 346444, "author": "Mads Hansen", "author_id": 14419, "author_profile": "https://Stackoverflow.com/users/14419", "pm_score": 6, "selected": true, "text": "<xsl:template match=\"text()\" />\n" }, { "answer_id": 346534, "author": "Dimitre Novatchev", "author_id": 36305, "author_profile": "https://Stackoverflow.com/users/36305", "pm_score": 5, "selected": false, "text": "<xsl:apply-templates/> <xsl:apply-templates select=\"child::node()\"/> text() <xsl:template match=\"text()\" />" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346362", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43940/" ]
346,365
<p>The following is okay:</p> <pre><code>try { Console.WriteLine(&quot;Before&quot;); yield return 1; Console.WriteLine(&quot;After&quot;); } finally { Console.WriteLine(&quot;Done&quot;); } </code></pre> <p>The <code>finally</code> block runs when the whole thing has finished executing (<code>IEnumerator&lt;T&gt;</code> supports <code>IDisposable</code> to provide a way to ensure this even when the enumeration is abandoned before it finishes).</p> <p>But this is not okay:</p> <pre><code>try { Console.WriteLine(&quot;Before&quot;); yield return 1; // error CS1626: Cannot yield a value in the body of a try block with a catch clause Console.WriteLine(&quot;After&quot;); } catch (Exception e) { Console.WriteLine(e.Message); } </code></pre> <p>Suppose (for the sake of argument) that an exception is thrown by one or other of the <code>WriteLine</code> calls inside the try block. What's the problem with continuing the execution in <code>catch</code> block?</p> <p>Of course, the yield return part is (currently) unable to throw anything, but why should that stop us from having an enclosing <code>try</code>/<code>catch</code> to deal with exceptions thrown before or after a <code>yield return</code>?</p> <p><strong>Update:</strong> There's an <a href="https://web.archive.org/web/20080818052536/http://blogs.msdn.com/oldnewthing/archive/2008/08/14/8862242.aspx" rel="noreferrer">interesting comment from Eric Lippert here</a> - seems that they already have enough problems implementing the try/finally behaviour correctly!</p> <p>EDIT: The MSDN page on this error is: <a href="http://msdn.microsoft.com/en-us/library/cs1x15az.aspx" rel="noreferrer">http://msdn.microsoft.com/en-us/library/cs1x15az.aspx</a>. It doesn't explain why, though.</p>
[ { "answer_id": 346434, "author": "Mark Cidade", "author_id": 1659, "author_profile": "https://Stackoverflow.com/users/1659", "pm_score": 3, "selected": false, "text": "yield switch yield try yield yield yield" }, { "answer_id": 346772, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 7, "selected": true, "text": "try\n{\n Console.WriteLine(\"a\");\n yield return 10;\n Console.WriteLine(\"b\");\n}\ncatch (Something e)\n{\n Console.WriteLine(\"Catch block\");\n}\nConsole.WriteLine(\"Post\");\n case just_before_try_state:\n try\n {\n Console.WriteLine(\"a\");\n }\n catch (Something e)\n {\n CatchBlock();\n goto case post;\n }\n __current = 10;\n return true;\n\ncase just_after_yield_return:\n try\n {\n Console.WriteLine(\"b\");\n }\n catch (Something e)\n {\n CatchBlock();\n }\n goto case post;\n\ncase post;\n Console.WriteLine(\"Post\");\n\n\nvoid CatchBlock()\n{\n Console.WriteLine(\"Catch block\");\n}\n" }, { "answer_id": 347044, "author": "Daniel Earwicker", "author_id": 27423, "author_profile": "https://Stackoverflow.com/users/27423", "pm_score": 2, "selected": false, "text": "yield return yield return File.ReadAllText(\"c:\\\\missing.txt\").Length;\n case just_before_try_state:\n try\n {\n Console.WriteLine(\"a\");\n __current = File.ReadAllText(\"c:\\\\missing.txt\").Length;\n }\n catch (Something e)\n {\n CatchBlock();\n goto case post;\n }\n return true;\n try\n{\n Console.WriteLine(\"x\");\n\n try\n {\n Console.WriteLine(\"a\");\n yield return 10;\n Console.WriteLine(\"b\");\n }\n catch (Something e)\n {\n Console.WriteLine(\"y\");\n\n if ((DateTime.Now.Second % 2) == 0)\n throw;\n }\n}\ncatch (Something e)\n{\n Console.WriteLine(\"Catch block\");\n}\nConsole.WriteLine(\"Post\");\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346365", "https://Stackoverflow.com", "https://Stackoverflow.com/users/27423/" ]
346,372
<p>I know how I use these terms, but I'm wondering if there are accepted definitions for <strong>faking</strong>, <strong>mocking</strong>, and <strong>stubbing</strong> for unit tests? How do you define these for your tests? Describe situations where you might use each.</p> <p>Here is how I use them:</p> <p><strong>Fake</strong>: a class that implements an interface but contains fixed data and no logic. Simply returns "good" or "bad" data depending on the implementation.</p> <p><strong>Mock</strong>: a class that implements an interface and allows the ability to dynamically set the values to return/exceptions to throw from particular methods and provides the ability to check if particular methods have been called/not called.</p> <p><strong>Stub</strong>: Like a mock class, except that it doesn't provide the ability to verify that methods have been called/not called.</p> <p>Mocks and stubs can be hand generated or generated by a mocking framework. Fake classes are generated by hand. I use mocks primarily to verify interactions between my class and dependent classes. I use stubs once I have verified the interactions and am testing alternate paths through my code. I use fake classes primarily to abstract out data dependencies or when mocks/stubs are too tedious to set up each time.</p>
[ { "answer_id": 33333064, "author": "Marjan Venema", "author_id": 11225, "author_profile": "https://Stackoverflow.com/users/11225", "pm_score": 7, "selected": false, "text": "const pleaseReturn5 = 5;\nvar fake = new FakeX(pleaseReturn5);\nvar cut = new ClassUnderTest(fake);\n\ncut.SquareIt;\n\nAssert.AreEqual(25, cut.SomeProperty);\n fake Assert fake const pleaseReturn5 = 5;\nvar fake = new FakeX(pleaseReturn5);\nvar cut = new ClassUnderTest(fake);\n\ncut.SquareIt;\n\nAssert.AreEqual(25, fake.SomeProperty);\n Assert fake ActualClassUnderTest ClassUsedAsMock ActualClassUnderTest ActualClassUnderTest" }, { "answer_id": 43245008, "author": "nanospeck", "author_id": 951984, "author_profile": "https://Stackoverflow.com/users/951984", "pm_score": 4, "selected": false, "text": "if(fileName.Length<8)\n{\n try\n {\n service.LogError(\"Filename too short:\" + fileName);\n }\n catch (Exception e)\n {\n email.SendEmail(\"a\",\"subject\",e.Message);\n }\n}\n [TestFixture]\npublic class LogAnalyzer2Tests\n{\n[Test]\n public void Analyze_WebServiceThrows_SendsEmail()\n {\n StubService stubService = new StubService();\n stubService.ToThrow= new Exception(\"fake exception\");\n MockEmailService mockEmail = new MockEmailService();\n\n LogAnalyzer2 log = new LogAnalyzer2();\n log.Service = stubService\n log.Email=mockEmail;\n string tooShortFileName=\"abc.ext\";\n log.Analyze(tooShortFileName);\n\n Assert.AreEqual(\"a\",mockEmail.To); //MOCKING USED\n Assert.AreEqual(\"fake exception\",mockEmail.Body); //MOCKING USED\n Assert.AreEqual(\"subject\",mockEmail.Subject);\n }\n}\n" }, { "answer_id": 53270577, "author": "Alireza Rahmani khalili", "author_id": 2043248, "author_profile": "https://Stackoverflow.com/users/2043248", "pm_score": 2, "selected": false, "text": "public class MyUnitTest {\n\n @Test\n public void testConcatenate() {\n StubDependency stubDependency = new StubDependency();\n int result = stubDependency.toNumber(\"one\", \"two\");\n assertEquals(\"onetwo\", result);\n }\n}\n\npublic class StubDependency() {\n public int toNumber(string param) {\n if (param == “one”) {\n return 1;\n }\n if (param == “two”) {\n return 2;\n }\n }\n}\n public class MockADependency {\n\n private int ShouldCallTwice;\n private boolean ShouldCallAtEnd;\n private boolean ShouldCallFirst;\n\n public int StringToInteger(String s) {\n if (s == \"abc\") {\n return 1;\n }\n if (s == \"xyz\") {\n return 2;\n }\n return 0;\n }\n\n public void ShouldCallFirst() {\n if ((ShouldCallTwice > 0) || ShouldCallAtEnd)\n throw new AssertionException(\"ShouldCallFirst not first thod called\");\n ShouldCallFirst = true;\n }\n\n public int ShouldCallTwice(string s) {\n if (!ShouldCallFirst)\n throw new AssertionException(\"ShouldCallTwice called before ShouldCallFirst\");\n if (ShouldCallAtEnd)\n throw new AssertionException(\"ShouldCallTwice called after ShouldCallAtEnd\");\n if (ShouldCallTwice >= 2)\n throw new AssertionException(\"ShouldCallTwice called more than twice\");\n ShouldCallTwice++;\n return StringToInteger(s);\n }\n\n public void ShouldCallAtEnd() {\n if (!ShouldCallFirst)\n throw new AssertionException(\"ShouldCallAtEnd called before ShouldCallFirst\");\n if (ShouldCallTwice != 2) throw new AssertionException(\"ShouldCallTwice not called twice\");\n ShouldCallAtEnd = true;\n }\n\n}\n" }, { "answer_id": 55030455, "author": "Daniel Pryden", "author_id": 128397, "author_profile": "https://Stackoverflow.com/users/128397", "pm_score": 6, "selected": false, "text": ":memory:" }, { "answer_id": 57845735, "author": "Marat Gallyamov", "author_id": 2733017, "author_profile": "https://Stackoverflow.com/users/2733017", "pm_score": 3, "selected": false, "text": "Send IEmailSender Send emailSender.Expect(es=>es.Send(anyThing)).Return((subject,body) => \"dummyId\") TestEmailSender IEmailSender Send SentEmails SentEmails Assert.AreEqual(1, emailSender.SentEmails.Count)" }, { "answer_id": 61209739, "author": "yoAlex5", "author_id": 4770877, "author_profile": "https://Stackoverflow.com/users/4770877", "pm_score": 4, "selected": false, "text": "Unit testing Test double fake object is stub object class StubA: A {\n override func foo() -> String {\n return \"My Stub\"\n }\n}\n mock object stub object class MockA: A {\n var isFooCalled = false\n override func foo() -> String {\n isFooCalled = true\n return \"My Mock\"\n }\n}\n spy object dummy object" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346372", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12950/" ]
346,380
<p>In Ruby you can reference variables inside strings and they are interpolated at runtime. </p> <p>For example if you declare a variable <code>foo</code> equals <code>"Ted"</code> and you declare a string <code>"Hello, #{foo}"</code> it interpolates to <code>"Hello, Ted"</code>. </p> <p>I've not been able to figure out how to perform the magic <code>"#{}"</code> interpolation on data read from a file. </p> <p>In pseudo code it might look something like this:</p> <pre><code>interpolated_string = File.new('myfile.txt').read.interpolate </code></pre> <p>But that last <code>interpolate</code> method doesn't exist.</p>
[ { "answer_id": 346413, "author": "stesch", "author_id": 41860, "author_profile": "https://Stackoverflow.com/users/41860", "pm_score": 5, "selected": true, "text": "erb require 'erb'\nname = \"Rasmus\"\ntemplate_string = \"My name is <%= name %>\"\ntemplate = ERB.new template_string\nputs template.result # prints \"My name is Rasmus\"\n Kernel#eval erb" }, { "answer_id": 346432, "author": "Daniel Lucraft", "author_id": 11951, "author_profile": "https://Stackoverflow.com/users/11951", "pm_score": 5, "selected": false, "text": "he #{foo} he\n str = File.read(\"data.txt\")\nfoo = 3\nresult = eval(\"\\\"\" + str + \"\\\"\")\n result \"he 3 he\"\n" }, { "answer_id": 346950, "author": "Purfideas", "author_id": 4615, "author_profile": "https://Stackoverflow.com/users/4615", "pm_score": 3, "selected": false, "text": ">> x = 1\n=> 1\n>> File.read('temp') % [\"#{x}\", 'saddle']\n=> \"The number of horses is 1, where each horse has a saddle\\n\"\n" }, { "answer_id": 6526209, "author": "DavidG", "author_id": 277139, "author_profile": "https://Stackoverflow.com/users/277139", "pm_score": 5, "selected": false, "text": ">> mystring = \"There are %{thing1}s and %{thing2}s here.\"\n => \"There are %{thing1}s and %{thing2}s here.\"\n\n>> vars = {:thing1 => \"trees\", :thing2 => \"houses\"}\n => {:thing1=>\"trees\", :thing2=>\"houses\"}\n\n>> mystring % vars\n => \"There are trees and houses here.\" \n" }, { "answer_id": 6542196, "author": "Andrew Grimm", "author_id": 38765, "author_profile": "https://Stackoverflow.com/users/38765", "pm_score": 3, "selected": false, "text": "try = \"hello\"\nstr = \"\\#{try}!!!\"\nString.interpolate{ str } #=> \"hello!!!\"\n" }, { "answer_id": 15639452, "author": "Allan Tokuda", "author_id": 2211896, "author_profile": "https://Stackoverflow.com/users/2211896", "pm_score": 3, "selected": false, "text": "My name is %{firstname} %{lastname} and I am here to talk about %{subject} today.\n sentence = IO.read('myfile.txt') % {\n :firstname => 'Joe',\n :lastname => 'Schmoe',\n :subject => 'file interpolation'\n}\nputs sentence\n My name is Joe Schmoe and I am here to talk about file interpolation today.\n" }, { "answer_id": 39085070, "author": "G. Allen Morris III", "author_id": 1169785, "author_profile": "https://Stackoverflow.com/users/1169785", "pm_score": 1, "selected": false, "text": "# encoding: utf-8\n\nclass String\n INTERPOLATE_DELIMETER_LIST = [ '\"', \"'\", \"\\x02\", \"\\x03\", \"\\x7F\", '|', '+', '-' ]\n def interpolate(data = {})\n binding = Kernel.binding\n\n data.each do |k, v|\n binding.local_variable_set(k, v)\n end\n\n delemeter = nil\n INTERPOLATE_DELIMETER_LIST.each do |k|\n next if self.include? k\n delemeter = k\n break\n end\n raise ArgumentError, \"String contains all the reserved characters\" unless delemeter\n e = s = delemeter\n string = \"%Q#{s}\" + self + \"#{e}\"\n binding.eval string\n end\nend\n\noutput =\nbegin\n File.read(\"data.txt\").interpolate(foo: 3)\nrescue NameError => error\n puts error\nrescue ArgumentError => error\n puts error\nend\n\np output\n he #{foo} he\n \"he 3 he\"\n \"he #{bad} he\\n\"\n \"\\\"'\\u0002\\u0003\\u007F|+-\"\n" }, { "answer_id": 46968035, "author": "Hakanai", "author_id": 138513, "author_profile": "https://Stackoverflow.com/users/138513", "pm_score": 1, "selected": false, "text": "irb(main):001:0> str = '#{13*3} Music'\n=> \"\\#{13*3} Music\"\nirb(main):002:0> str.gsub(/\\#\\{(.*?)\\}/) { |match| eval($1) }\n=> \"39 Music\"\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346380", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4061/" ]
346,426
<p>I am having problems using <a href="http://code.google.com/p/django-tagging/" rel="nofollow noreferrer">django-tagging</a>. I try to follow the <a href="http://code.google.com/p/django-tagging/source/browse/trunk/docs/overview.txt" rel="nofollow noreferrer">documentation</a> but it fails at the second step</p> <blockquote> <p>Once you've installed Django Tagging and want to use it in your Django applications, do the following:</p> <ol> <li>Put <code>'tagging'</code> in your <code>INSTALLED_APPS</code> setting.</li> <li>Run the command <code>manage.py syncdb</code>.</li> </ol> <p>The <code>syncdb</code> command creates the necessary database tables and creates permission objects for all installed apps that need them.</p> </blockquote> <p>I get a python Traceback with the following error:</p> <pre><code>ImportError: cannot import name parse_lookup </code></pre> <p>The following works, so I think it is correctly installed:</p> <pre><code>&gt;&gt; import tagging &gt;&gt; tagging.VERSION (0, 2.1000000000000001, None) </code></pre> <p>What am I missing?</p>
[ { "answer_id": 346441, "author": "ayaz", "author_id": 23191, "author_profile": "https://Stackoverflow.com/users/23191", "pm_score": 0, "selected": false, "text": "In [1]: import tagging; tagging.VERSION\nOut[1]: (0, 3, 'pre')\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346426", "https://Stackoverflow.com", "https://Stackoverflow.com/users/24946/" ]
346,445
<p>I've been banging my head against for wall for a while with this one.</p> <p>I want to SSH into a set of machines and check whether they are available (accepting connections and not being used). I have created a small script, tssh, which does just that:</p> <pre><code>#!/bin/bash host=$1 timeout=${2:-1} ssh -qo "ConnectTimeout $timeout" $host "[ \`who | cut -f1 | wc -l \` -eq 0 ] &amp;&amp; exit 0 || exit 1" </code></pre> <p>This script works correctly. Returning 255 if there was a connection problem, 1 if the machine is busy and 0 if everything is good. If anyone knows a better way to do this please let me know.</p> <p>So next I try and call tssh on my set of machines using a while read loop, and this is where it all goes wrong. The loop exits as soon as tssh returns 0 and never completes the full set. </p> <pre><code>while read nu ; do tssh "MYBOXES$nu" ; done &lt; &lt;(ruby -e '(0..20).each { |i| puts i }') </code></pre> <p>At first I thought this was a subshell problem but apparently not. Any help, along with comments on style/content, would be much appreciated! I know I'm going to kick myself when I find out why...</p>
[ { "answer_id": 346455, "author": "Paul Tomblin", "author_id": 3333, "author_profile": "https://Stackoverflow.com/users/3333", "pm_score": 3, "selected": true, "text": "for nu in `ruby -e '(0..20).each { |i| puts i}'`; do\n tssh \"MYBOXES$nu\" \ndone\n" }, { "answer_id": 346473, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "xargs seq seq 0 20 | xargs -n1 tssh MYBOXES\n" }, { "answer_id": 346548, "author": "Kaii", "author_id": 43959, "author_profile": "https://Stackoverflow.com/users/43959", "pm_score": 2, "selected": false, "text": "for ((i=0; $i<=20; i++)); do\n tssh \"MYBOXES$i\"\ndone\n" }, { "answer_id": 753540, "author": "guns", "author_id": 76288, "author_profile": "https://Stackoverflow.com/users/76288", "pm_score": 2, "selected": false, "text": "for i in {0..20}; do\n # command\ndone\n" }, { "answer_id": 1396070, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "while read host; do\n ssh -n $host \"remote command\" >> output.txt\ndone << host_list_file.txt\n" }, { "answer_id": 7014997, "author": "Kevin Mullet", "author_id": 888419, "author_profile": "https://Stackoverflow.com/users/888419", "pm_score": 2, "selected": false, "text": "#!/bin/bash\n[...]\nsomething|while read host\n do\n ssh -nx ${host} fiddleAround\n done\n" }, { "answer_id": 7018714, "author": "Foo Bah", "author_id": 590042, "author_profile": "https://Stackoverflow.com/users/590042", "pm_score": 5, "selected": false, "text": "something | \nwhile read x; do \n ssh ...\ndone\n something ssh cat id_rsa.pub | ssh new_box \"cat - >> ~/.ssh/authorized_keys\"\n something read ssh -n ... cat /etc/hosts | awk '{print $2}' | while read x; do\n ssh -n $x \"do_something_on_the_machine\"\ndone\n" }, { "answer_id": 35208546, "author": "rouble", "author_id": 215120, "author_profile": "https://Stackoverflow.com/users/215120", "pm_score": 4, "selected": false, "text": "while read x; do \n # Make sure command does not hijack stdin\n echo \"\" | command $x\ndone < /path/to/some/file\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346445", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
346,446
<p>I've inherited a database that has a structure with a table of products, a table consisting of some product attributes and another table to build the relationship between these attributes and a given product.</p> <p>A user can filter the products by a combination of these attributes, meaning that if more than one attribute is selected only products with all those attributes are returned. Unfortunately, there is now an exception to this rule, whereby a user selecting one of two specific attributes needs results containing either (or both).</p> <p>The query currently looks like this (not my code):</p> <pre><code>SELECT DISTINCT p.* FROM products AS p INNER JOIN attributes a ON p.product_id=a.property_id WHERE a.attribute_id IN (1,3,7) GROUP BY p.property_id HAVING COUNT(DISTINCT a.attribute_id) = 3 </code></pre> <p>I doubt the above is a particularly efficient way of retrieving the required products, but I'm unsure how to proceed in light of the new requirement.</p> <p>I've now created some php code to construct a special query when the two "special" attributes (3 and 7) are selected:</p> <pre><code>SELECT DISTINCT p.* FROM products AS p INNER JOIN attributes a ON p.product_id=a.property_id WHERE a.attribute_id IN (1,3) OR a.attribute_id IN (1,7) GROUP BY p.property_id HAVING COUNT(DISTINCT a.attribute_id) = 2 </code></pre> <p>However, this still does not work as required - any products that share both these attributes are not returned in the result (this is obviously due to the HAVING COUNT clause, but I don't know how I go about fixing it. For clarity, the issue is if 10 products have only attribute 3 but a further five have attributes 3 and 7, the above query will only return the 10 records. </p> <p>Might it be possible to use some kind of subquery or what alternatives are there?</p>
[ { "answer_id": 346527, "author": "ʞɔıu", "author_id": 41613, "author_profile": "https://Stackoverflow.com/users/41613", "pm_score": 1, "selected": false, "text": "SELECT ... FROM products AS p \nINNER JOIN attributes a1 ON p.product_id=a1.property_id AND a1.attribute_id=1\nINNER JOIN attributes a2 ON p.product_id=a2.property_id AND a2.attribute_id=3\nINNER JOIN attributes a3 ON p.product_id=a3.property_id AND a3.attribute_id=7\n SELECT ... FROM products AS p \nINNER JOIN attributes a1 ON p.product_id=a1.property_id AND a1.attribute_id=1\nLEFT OUTER JOIN attributes a2 ON p.product_id=a2.property_id AND a2.attribute_id=3\nLEFT OUTER JOIN attributes a3 ON p.product_id=a3.property_id AND a3.attribute_id=7\nWHERE a2.attribute_id IS NOT NULL OR a3.attribute_id IS NOT NULL\n" }, { "answer_id": 361805, "author": "dotjoe", "author_id": 40822, "author_profile": "https://Stackoverflow.com/users/40822", "pm_score": 0, "selected": false, "text": "SELECT p.* FROM products \nINNER JOIN (\n SELECT a1.property_id \n FROM attributes a1 \n WHERE a1.attribute_id IN (1,3,7)\n GROUP BY a1.property_id \n HAVING COUNT(DISTINCT a1.attribute_id) = 2\n) as a ON p.product_id=a.property_id\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346446", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29538/" ]
346,449
<p>I'm looking for a free templating engine to generate simple reports. I want some basic features such as :</p> <ul> <li>Ability to Write Loops (with any IEnumerable)</li> <li>Passing Variables</li> <li>Passing Templates Files (main template, footer, header)</li> </ul> <p>I'll use this to generate reports in HTML and XML. I'm not looking for a ASP.NET Template Engine.</p> <p>This is for a WinForms applications.</p> <p>I've seen this question <a href="https://stackoverflow.com/questions/340095/can-you-recommend-a-net-template-engine">Can you recommend a .net template engine?</a>, however all of those template engines are total overkill for me and focused for ASP.NET.</p> <p>Please only recommend free libraries.</p> <p>// I'm still looking an NVelocity but it doesn't look any promising for .NET, overly complicated, when you download it's bunch of files not clear what to do, no tutorial, startup document etc.</p>
[ { "answer_id": 346520, "author": "FlySwat", "author_id": 1965, "author_profile": "https://Stackoverflow.com/users/1965", "pm_score": 3, "selected": true, "text": "<html>\n <head>\n <title>My Report</title>\n </head>\n <body>\n <% foreach (ReportRow r in ReportData) { %>\n <!-- Markup and Code for Report -->\n <% } %>\n </body>\n</html>\n" }, { "answer_id": 1979961, "author": "David Robbins", "author_id": 19799, "author_profile": "https://Stackoverflow.com/users/19799", "pm_score": 0, "selected": false, "text": "<script type=\"text/html\" id=\"item_tmpl\">\n <div id=\"<%=id%>\" class=\"<%=(i % 2 == 1 ? \" even\" : \"\")%>\">\n <div class=\"grid_1 alpha right\">\n <img class=\"righted\" src=\"<%=profile_image_url%>\"/>\n </div>\n <div class=\"grid_6 omega contents\">\n <p><b><a href=\"/<%=from_user%>\"><%=from_user%></a>:</b> <%=text%></p>\n </div>\n </div>\n</script>\n" }, { "answer_id": 2799557, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "Dear $User.FullName$,\n{%set orders=User.GetOrders() /}\nThank you for your order of $orders.Length$ items, We believe you will be very satisfied with the quality of costume pieces included in each. It is this quality that makes our imaginative play apparel so unique.\n\nWe created an account for you to track your orders. Here is the login information:\nEmail: $User.EmailAddress$\nPassword: $User.Password$\n\nFollowing is the details of your order (OrderId: $OrderId$):\n# Part ID Name Quantity Price(per unit) Sub Total\n{%set Total=0.0 /}{%foreach orderproduct,i in orders%}{%set Total = Total + orderproduct.Price * orderproduct.Quantity/}\n{%rendertemplate orderproducttemplate item=orderproduct/}{$foreach%}\n Total: $PadLeft(Format(Total,\"$$#.##\"),11)$\n\nIf you have any concern, please call us at 913-555-0115.\n\nSincerely,\n\n$CompanyName$\n\n{%template orderproducttemplate%}$PadLeft(i,4)$$PadLeft(item.PartId, 7)$ $PadRight(item.ProductName, 15)$ $PadRight(item.Quantity, 5)$ $PadLeft(Format(item.Price,\"$$#.##\"), 7)$ $PadLeft(Format(item.Price*item.Quantity,\"$$#.##\"), 12)${$template%}\n Dear John Borders,\n\nThank you for your order of 3 items, We believe you will be very satisfied with the quality of costume pieces included in each. It is this quality that makes our imaginative play apparel so unique.\n\nWe created an account for you to track your orders. Here is the login information:\nEmail: myemail@somedomain.com\nPassword: 123abc\n\nFollowing is the details of your order (OrderId: 1625DGHJ):\n# Part ID Name Quantity Price(per unit) Sub Total\n\n 0 1239 Product A 3 $104.09 $312.27\n 1 22 Product B 1 $134.09 $134.09\n 2 167 Product C 5 $14.7 $73.5\n\n Total: $519.86\n\nIf you have any concern, please call us at 913-555-0115.\n\nSincerely,\n\nMy Company Name\n class OrderProduct\n {\n private int _partId;\n private string _productName;\n private int _quantity;\n private float _price;\n\n public int PartId\n {\n get { return _partId; }\n set { _partId = value; }\n }\n\n public string ProductName\n {\n get { return _productName; }\n set { _productName = value; }\n }\n\n public int Quantity\n {\n get { return _quantity; }\n set { _quantity = value; }\n }\n\n public float Price\n {\n get { return _price; }\n set { _price = value; }\n }\n }\n\n class User\n {\n private string _fullName;\n private string _emailAddress;\n private string _password;\n\n public string FullName\n {\n get { return _fullName; }\n set { _fullName = value; }\n }\n\n public string EmailAddress\n {\n get { return _emailAddress; }\n set { _emailAddress = value; }\n }\n\n public string Password\n {\n get { return _password; }\n set { _password = value; }\n }\n\n public OrderProduct[] GetOrders()\n {\n OrderProduct[] ops = new OrderProduct[3];\n\n ops[0] = new OrderProduct();\n ops[0].PartId = 1239;\n ops[0].Price = 104.09f;\n ops[0].ProductName = \"Product A\";\n ops[0].Quantity = 3;\n\n ops[1] = new OrderProduct();\n ops[1].PartId = 22;\n ops[1].Price = 134.09f;\n ops[1].ProductName = \"Product B\";\n ops[1].Quantity = 1;\n\n ops[2] = new OrderProduct();\n ops[2].PartId = 167;\n ops[2].Price = 14.7f;\n ops[2].ProductName = \"Product C\";\n ops[2].Quantity = 5;\n\n return ops;\n }\n }\n\n private void btnRun_Click(object sender, EventArgs e)\n {\n try\n {\n dt.LoadFromString(txtSource.Text);\n dt.SetValue(\"CompanyName\", \"My Company Name\");\n\n User u = new User();\n u.EmailAddress = \"myemail@somedomain.com\";\n u.FullName = \"John Borders\";\n u.Password = \"123abc\";\n dt.SetValue(\"User\", u);\n dt.SetValue(\"OrderId\", \"1625DGHJ\");\n\n txtOutput.Text = dt.Run();\n }\n catch (Exception exc)\n {\n MessageBox.Show(\"An error occurred: \" + exc.Message);\n }\n }\n" }, { "answer_id": 2799597, "author": "Ryan Bair", "author_id": 91740, "author_profile": "https://Stackoverflow.com/users/91740", "pm_score": 2, "selected": false, "text": "<viewdata products=\"IEnumerable[[Product]]\"/>\n<ul if=\"products.Any()\">\n <li each=\"var p in products\">${p.Name}</li>\n</ul>\n<else>\n <p>No products available</p>\n</else>\n" }, { "answer_id": 35695938, "author": "ThrowingDwarf", "author_id": 5968380, "author_profile": "https://Stackoverflow.com/users/5968380", "pm_score": 0, "selected": false, "text": " <#@ template language=\"C#\" #>\n<html><body>\n<h1>Sales for Previous Month</h2>\n<table>\n <# for (int i = 1; i <= 10; i++)\n { #>\n <tr><td>Test name <#= i #> </td>\n <td>Test value <#= i * i #> </td> </tr>\n <# } #>\n </table>\nThis report is Company Confidential.\n</body></html>\n MyWebPage page = new MyWebPage();\nString pageContent = page.TransformText();\nSystem.IO.File.WriteAllText(\"outputPage.html\", pageContent);\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346449", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40322/" ]
346,467
<p>I'm trying to format numbers. Examples:</p> <pre><code>1 =&gt; 1 12 =&gt; 12 123 =&gt; 123 1234 =&gt; 1,234 12345 =&gt; 12,345 </code></pre> <p>It strikes as a fairly common thing to do but I can't figure out which filter I'm supposed to use.</p> <p>Edit: If you've a generic Python way to do this, I'm happy adding a formatted field in my model.</p>
[ { "answer_id": 346476, "author": "Oli", "author_id": 12870, "author_profile": "https://Stackoverflow.com/users/12870", "pm_score": 2, "selected": false, "text": "def format_price(self):\n import locale\n locale.setlocale(locale.LC_ALL, '')\n return locale.format('%d', self.price, True)\n" }, { "answer_id": 346633, "author": "muhuk", "author_id": 42188, "author_profile": "https://Stackoverflow.com/users/42188", "pm_score": 4, "selected": false, "text": "def int_format(value, decimal_points=3, seperator=u'.'):\n value = str(value)\n if len(value) <= decimal_points:\n return value\n # say here we have value = '12345' and the default params above\n parts = []\n while value:\n parts.append(value[-decimal_points:])\n value = value[:-decimal_points]\n # now we should have parts = ['345', '12']\n parts.reverse()\n # and the return value should be u'12.345'\n return seperator.join(parts)\n" }, { "answer_id": 347560, "author": "Ned Batchelder", "author_id": 14343, "author_profile": "https://Stackoverflow.com/users/14343", "pm_score": 10, "selected": true, "text": "{% load humanize %}\n{{ my_num|intcomma }}\n 'django.contrib.humanize' INSTALLED_APPS settings.py" }, { "answer_id": 2180209, "author": "Dave Aaron Smith", "author_id": 223268, "author_profile": "https://Stackoverflow.com/users/223268", "pm_score": 6, "selected": false, "text": "my_app/templatetags/my_filters.py from django import template\nfrom django.contrib.humanize.templatetags.humanize import intcomma\n\nregister = template.Library()\n\ndef currency(dollars):\n dollars = round(float(dollars), 2)\n return \"$%s%s\" % (intcomma(int(dollars)), (\"%0.2f\" % dollars)[-3:])\n\nregister.filter('currency', currency)\n {% load my_filters %}\n{{my_dollars | currency}}\n" }, { "answer_id": 9015743, "author": "Enis Afgan", "author_id": 523109, "author_profile": "https://Stackoverflow.com/users/523109", "pm_score": 2, "selected": false, "text": "@register.filter('intspace')\ndef intspace(value):\n \"\"\"\n Converts an integer to a string containing spaces every three digits.\n For example, 3000 becomes '3 000' and 45000 becomes '45 000'.\n See django.contrib.humanize app\n \"\"\"\n orig = force_unicode(value)\n new = re.sub(\"^(-?\\d+)(\\d{3})\", '\\g<1> \\g<2>', orig)\n if orig == new:\n return new\n else:\n return intspace(new)\n" }, { "answer_id": 10859264, "author": "Vinod Kurup", "author_id": 347942, "author_profile": "https://Stackoverflow.com/users/347942", "pm_score": 7, "selected": false, "text": "{% load humanize %}\n{{ floatvalue|floatformat:2|intcomma }}\n floatformat intcomma" }, { "answer_id": 15121424, "author": "MiniQuark", "author_id": 38626, "author_profile": "https://Stackoverflow.com/users/38626", "pm_score": 3, "selected": false, "text": "your_project/your_app/templatetags/sexify.py # -*- coding: utf-8 -*-\nfrom django import template\nfrom django.utils.translation import to_locale, get_language\nfrom babel.numbers import format_number\n\nregister = template.Library()\n\ndef sexy_number(context, number, locale = None):\n if locale is None:\n locale = to_locale(get_language())\n return format_number(number, locale = locale)\n\nregister.simple_tag(takes_context=True)(sexy_number)\n {% load sexy_number from sexify %}\n\n{% sexy_number 1234.56 %}\n {% sexy_number some_variable %}\n context" }, { "answer_id": 21868438, "author": "Felix Böhme", "author_id": 1194011, "author_profile": "https://Stackoverflow.com/users/1194011", "pm_score": 2, "selected": false, "text": "$100\n($50) # negative numbers without '-' and in parens\n {% if var >= 0 %} ${{ var|stringformat:\"d\" }}\n{% elif var < 0 %} $({{ var|stringformat:\"d\"|cut:\"-\" }})\n{% endif %}\n {{ var|stringformat:\"1.2f\"|cut:\"-\" }} $50.00" }, { "answer_id": 37607860, "author": "carton.swing", "author_id": 5765458, "author_profile": "https://Stackoverflow.com/users/5765458", "pm_score": 5, "selected": false, "text": "USE_THOUSAND_SEPARATOR = True\n >>> '{:,}'.format(1000000)\n'1,000,000'\n" }, { "answer_id": 44004477, "author": "Risadinha", "author_id": 621690, "author_profile": "https://Stackoverflow.com/users/621690", "pm_score": 2, "selected": false, "text": "{% load l10n %}\n\n{{ value|localize }}\n localize(number)" }, { "answer_id": 44865342, "author": "geckos", "author_id": 652528, "author_profile": "https://Stackoverflow.com/users/652528", "pm_score": 2, "selected": false, "text": "string.format templatetags format.py from django import template\n\nregister = template.Library()\n\n@register.filter(name='format')\ndef format(value, fmt):\n return fmt.format(value)\n {% load format %} {{ some_value|format:\"{:0.2f}\" }}" }, { "answer_id": 48752244, "author": "chidimo", "author_id": 2689562, "author_profile": "https://Stackoverflow.com/users/2689562", "pm_score": 2, "selected": false, "text": "Django 2.0.2" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346467", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12870/" ]
346,499
<p>I want to store a string in memory and read it later:</p> <pre><code>$$-&gt;desc.constant-&gt;base.id = (char*)malloc(200); sprintf($$-&gt;desc.constant-&gt;base.id, "%f", $1); printf("-&gt;%s\n", $$-&gt;desc.constant-&gt;base.id); //LINE A printf("-&gt;%i\n", $$-&gt;desc.constant); //LINE B //SOME OTHER CODE //Then, later on in a function call: printf("%i", expr-&gt;desc.constant); // LINE D printf("%s", expr-&gt;desc.constant-&gt;base.id); // LINE C </code></pre> <p>Although Line B and Line D show the same address, the printf in Line C fails with a Segmentation fault. What am I missing?</p> <p>Any help would really be appreciated!</p>
[ { "answer_id": 346507, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": true, "text": "printf(\"->%i\\n\", $$->desc.constant); //LINE B\n constant int void* printf(\"->%p\\n\", (void*)$$->desc.constant); //LINE B\n" }, { "answer_id": 346560, "author": "1800 INFORMATION", "author_id": 3146, "author_profile": "https://Stackoverflow.com/users/3146", "pm_score": 0, "selected": false, "text": "free $$->desc.constant->base.id = (char*)malloc(200);\nsprintf($$->desc.constant->base.id, \"%f\", $1);\nprintf(\"->%s\\n\", $$->desc.constant->base.id); //LINE A\nprintf(\"->%i\\n\", $$->desc.constant); //LINE B\n\n//SOME OTHER CODE\n// which happens to do\nfree($$->desc.constant->base.id);\n\nprintf(\"%i\", expr->desc.constant); // LINE D\nprintf(\"%s\", expr->desc.constant->base.id); // crash\n" }, { "answer_id": 346598, "author": "jfs", "author_id": 4279, "author_profile": "https://Stackoverflow.com/users/4279", "pm_score": 1, "selected": false, "text": "malloc sprintf snprintf \"%f\" \"%.*g\" /** $ gcc print_number.c -o print_number */\n#include <assert.h>\n#include <stdio.h>\n#include <stdlib.h>\n\n\nint main(int argc, char *argv[])\n{\n const char* number_format = \"%.*g\";\n const int ndigits = 15;\n assert(ndigits > 0);\n const int maxlen = ndigits + 8 /* -0.e+001, Infinity */ + 1 /* '\\0' */;\n\n char *str = malloc(maxlen);\n if (str == NULL) {\n fprintf(stderr, \"error: malloc\\n\");\n exit(1);\n } \n\n double number = 12345678901234567890.123456789012345678901234567890;\n /** `number = 0/0` crashes the program */;\n\n printf(\"number: %f\\t\", number);\n\n int len_wouldbe = snprintf(str, maxlen, number_format, ndigits, number);\n assert(len_wouldbe < maxlen);\n\n printf(\"%s\\n\", str);\n return 0;\n}\n number: 12345678901234567000.000000 1.23456789012346e+19\n" }, { "answer_id": 346951, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 0, "selected": false, "text": "expr->desc.constant sprintf() snprintf() $$->desc.constant $$->desc.constant->base.id base" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346499", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43960/" ]
346,506
<p>We use a modified version of the IE engine (the COM version in a C# wrapper) to display a lot of the formatted content in our application. The problem, however, is you don't have a lot of control of any printout of such documents. For example, you can't force a color printout without accessing the registry or directing the user to their Internet Explorer options. So, we've been investigating the new WPF WebBrowser control, which might better suit our purposes.</p> <p>The problem is (other than Microsoft called it the same name as the Windows Forms version of the control making Google searches less useful than I like) I can't seem to find any good guidelines on how to print the contents of the control. The Document returned from the object isn't paginated, making it hard to use with the PrintDialog. Similar, sending the Visual to PrintDialog doesn't seem like a good idea. Sizing the control properly in this context seems dubious, particularly when you consider paging. </p> <p>There has to be some good documentation on this somewhere. Can someone direct me to it or provide a good suggestion on how to do this?</p>
[ { "answer_id": 346521, "author": "mackenir", "author_id": 25457, "author_profile": "https://Stackoverflow.com/users/25457", "pm_score": 1, "selected": false, "text": "ActiveXHost" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346506", "https://Stackoverflow.com", "https://Stackoverflow.com/users/7357/" ]
346,512
<p>On AS400 in interactive SQL in a 5250 session,</p> <pre><code>select * from myfile </code></pre> <p>returns rows from one member only when myfile has more than one member.</p> <p>How can I get rows from a specific member?</p> <p>Important: in the end I'd like to do this over JDBC with jt400 so really I want a solution that'll work there.</p> <p>Thanks.</p>
[ { "answer_id": 435704, "author": "Ryan Guill", "author_id": 7186, "author_profile": "https://Stackoverflow.com/users/7186", "pm_score": 5, "selected": false, "text": "CREATE ALIAS myLibrary/myAlias FOR memberLibrary/memberFile(memberName)\n SELECT * FROM myLibrary/myAlias\n DROP ALIAS myLibrary/myAlias\n" }, { "answer_id": 17396146, "author": "naveen", "author_id": 2537489, "author_profile": "https://Stackoverflow.com/users/2537489", "pm_score": 0, "selected": false, "text": "OS/400 R430 SQL CREATE ALIAS ALIAS SQL OS/400 i5/OS interactive SQL (STRSQL) iSeries Navigator's Run SQL Scripts CREATE ALIAS MYLIB.FILE1MBR1 FOR MYLIB.MYFILE(MBR1) \nCREATE ALIAS MYLIB.FILE1MBR2 FOR MYLIB.MYFILE(MBR2)\n" }, { "answer_id": 51291314, "author": "JMerinoH", "author_id": 2908816, "author_profile": "https://Stackoverflow.com/users/2908816", "pm_score": 0, "selected": false, "text": "set schema=mylibrary;\n\ncreate alias qtemp.aliasx for table1(membera);\ncreate alias qtemp.aliasy for table2(memberb);\n\nselect * from qtemp.aliasx;\nselect * from qtemp.aliasy;\n\ndrop alias qtemp.aliasx;\ndrop alias qtemp.aliasy;\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346512", "https://Stackoverflow.com", "https://Stackoverflow.com/users/29574/" ]
346,516
<p>I am trying to add a link into the pop-up text bubble of a marker in Google Maps through the API. I have successfully run the below code:</p> <pre><code>echo '&lt;marker lat="43.91892" lng="-78.89231" html="Albertus Magnus College&amp;lt;br&amp;gt;Link to Admissions" label="Albertus Magnus College" /&gt;'; </code></pre> <p>But once I actually try to add the link it fails. Like this:</p> <pre><code>echo '&lt;marker lat="43.91892" lng="-78.89231" html="Albertus Magnus College&amp;lt;br&amp;gt;&amp;lt;a href='http://www.albertus.edu/admission/index.shtml'&amp;gt;Admissions&amp;lt;\/a&amp;gt;" label="Albertus Magnus College" /&gt;'; </code></pre> <p>Does anyone know how to successfully write this code? I am writing it into PHP because I have some other functionality that won't let me just write it in XML.</p> <p>Update: I got it to work like this for some reason...</p> <pre><code>$window2a_url = '&amp;lt;a href=&amp;apos;http://www.albertus.edu/admission/index.shtml&amp;apos;&amp;gt;Admissions'; echo '&lt;marker lat="41.331304" lng="-72.921438" html=" Albertus Magnus College&amp;lt;br&amp;gt;'; echo $window2a_url; echo '" label="Albertus Magnus College" /&gt;'; </code></pre> <p>I had to escape the apostrophes... If anyone has a more elegant solution, I am all ears!</p>
[ { "answer_id": 346564, "author": "benlumley", "author_id": 39161, "author_profile": "https://Stackoverflow.com/users/39161", "pm_score": 0, "selected": false, "text": "echo '<marker lat=\"43.91892\" lng=\"-78.89231\" html=\"Albertus Magnus College&lt;br&gt;&lt;a href=\\'http://www.albertus.edu/admission/index.shtml\\'&gt;Admissions&lt;\\/a&gt;\" label=\"Albertus Magnus College\" />';\n" }, { "answer_id": 346569, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": 0, "selected": false, "text": "echo '<marker lat=\"43.91892\" lng=\"-78.89231\" html=\"Albertus Magnus College<br><a href=\\'http://www.albertus.edu/admission/index.shtml\\'>Admissions</a>\" label=\"Albertus Magnus College\" />';\n" }, { "answer_id": 493246, "author": "JoshFinnie", "author_id": 33194, "author_profile": "https://Stackoverflow.com/users/33194", "pm_score": 2, "selected": true, "text": "$window2a_url = '&lt;a\nhref=&apos;http://www.albertus.edu/admission/index.shtml&apos;&gt;Admissions';\necho '<marker lat=\"41.331304\" lng=\"-72.921438\" html=\" Albertus Magnus College&lt;br&gt;';\necho $window2a_url;\necho '\" label=\"Albertus Magnus College\" />';\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346516", "https://Stackoverflow.com", "https://Stackoverflow.com/users/33194/" ]
346,523
<p>I have an expression tree I have created by parsing an Xml using the expression class in C#. <a href="https://stackoverflow.com/questions/344741/how-do-i-create-an-expression-tree-by-parsing-xml-in-c">See this question</a>.</p> <p>I only have Add, Subtract, Divide, Multiply, Parameters, And and Or in my Expression Tree. Is there a way to convert this ExpressionTree into a callable method? ...or do I have to emit the IL manually?</p> <p>Kind regards,</p>
[ { "answer_id": 346532, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": false, "text": "var lambda = Expression.Lambda<Func<float,int>>(body, param);\nFunc<float,int> method = lambda.Compile();\nint v = method(1.0); // test\n ParameterExpression" }, { "answer_id": 346897, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "static void Main()\n{\n // try to do \"x + (3 * x)\"\n\n var single = BuildSingle<decimal>();\n var composite = BuildComposite<decimal>();\n\n Console.WriteLine(\"{0} vs {1}\", single(13.2M), composite(13.2M));\n}\n// utility method to get the 3 as the correct type, since there is not always a \"int x T\"\nstatic Expression ConvertConstant<TSource, TDestination>(TSource value)\n{\n return Expression.Convert(Expression.Constant(value, typeof(TSource)), typeof(TDestination));\n}\n// option 1: a single expression tree; this is the most efficient\nstatic Func<T,T> BuildSingle<T>()\n{ \n var param = Expression.Parameter(typeof(T), \"x\");\n Expression body = Expression.Add(param, Expression.Multiply(\n ConvertConstant<int, T>(3), param));\n var lambda = Expression.Lambda<Func<T, T>>(body, param);\n return lambda.Compile();\n}\n// option 2: nested expression trees:\nstatic Func<T, T> BuildComposite<T>()\n{\n\n // step 1: do the multiply:\n var paramInner = Expression.Parameter(typeof(T), \"inner\");\n Expression bodyInner = Expression.Multiply(\n ConvertConstant<int, T>(3), paramInner);\n var lambdaInner = Expression.Lambda(bodyInner, paramInner);\n\n // step 2: do the add, invoking the existing tree\n var paramOuter = Expression.Parameter(typeof(T), \"outer\");\n Expression bodyOuter = Expression.Add(paramOuter, Expression.Invoke(lambdaInner, paramOuter));\n var lambdaOuter = Expression.Lambda<Func<T, T>>(bodyOuter, paramOuter);\n\n return lambdaOuter.Compile();\n}\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346523", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21586/" ]
346,531
<p>I'm migrating my WordPress blog and phpBB Forum into a new hosting server. I am using phpMyAdmin to import the SQL script from the database in the previous site. </p> <p>When I open the .sql script with Kate, it says it uses UTF8 as encoding. When I import the sql in the new server, I have the option in phpMyAdmin to choose the encoding, where utf8 is selected by default.</p> <p>Still, when I finish importing the database, I read the posts text directly in phpMyAdmin, and see characters such as "é", "ñ", etc. which haven't been "interpreted" and been replaced with weird characters insted.</p> <p>I can see my WordPress installation is not working also. Apparently there's a problem with this encoding thing, but I think the problem is in the MySQL database or phpMyAdmin and not WordPress.</p> <p>The versions of MySQL are practically the same, MySQL 5, but a different revision. Also, there was no problem when migrating the forum database, so this is even stranger...</p> <p>I'm lost as to how to fix this... Any ideas are welcome.</p>
[ { "answer_id": 346552, "author": "markus", "author_id": 11995, "author_profile": "https://Stackoverflow.com/users/11995", "pm_score": 4, "selected": true, "text": "SET NAMES 'utf8';\n" }, { "answer_id": 346715, "author": "Fernando Briano", "author_id": 1492, "author_profile": "https://Stackoverflow.com/users/1492", "pm_score": 2, "selected": false, "text": "SET character_set_client = utf8;" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346531", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1492/" ]
346,536
<p>Is there any good example to give the difference between a <code>struct</code> and a <code>union</code>? Basically I know that <code>struct</code> uses all the memory of its member and <code>union</code> uses the largest members memory space. Is there any other OS level difference? </p>
[ { "answer_id": 346541, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 11, "selected": true, "text": "union foo {\n int a; // can't use both a and b at once\n char b;\n} foo;\n\nstruct bar {\n int a; // can use both a and b simultaneously\n char b;\n} bar;\n\nunion foo x;\nx.a = 3; // OK\nx.b = 'c'; // NO! this affects the value of x.a!\n\nstruct bar y;\ny.a = 3; // OK\ny.b = 'c'; // OK\n union foo x;\nx.a = 3;\nx.b = 'c';\nprintf(\"%i, %i\\n\", x.a, x.b);\n 99, 99\n union foo x;\nx.a = 387439;\nx.b = 'c';\nprintf(\"%i, %i\\n\", x.a, x.b);\n 387427, 99\n union foo x;\nx.a = 0xDEADBEEF;\nx.b = 0x22;\nprintf(\"%x, %x\\n\", x.a, x.b);\n deadbe22, 22\n" }, { "answer_id": 346566, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 5, "selected": false, "text": "union struct union struct int union test {\n int a;\n long b;\n}; \n sizeof struct test {\n int a;\n double b;\n} * some_test_pointer;\n int* double* test int* a union a {\n int a;\n double b;\n};\n union a * v = (union a*)some_int_pointer;\n*some_int_pointer = 5;\nv->a = 10;\nreturn *some_int_pointer; \n v->a = 10; *some_int_pointer 10 5" }, { "answer_id": 346576, "author": "Piotr Lesnicki", "author_id": 38796, "author_profile": "https://Stackoverflow.com/users/38796", "pm_score": 4, "selected": false, "text": "struct" }, { "answer_id": 346579, "author": "Charlie Martin", "author_id": 35092, "author_profile": "https://Stackoverflow.com/users/35092", "pm_score": 7, "selected": false, "text": "struct foobarbazquux_t {\n int foo;\n long bar;\n double baz; \n long double quux;\n}\n (sizeof(int)+sizeof(long)+sizeof(double)+sizeof(long double)) union foobarbazquux_u {\n int foo;\n long bar;\n double baz; \n long double quux;\n}\n sizeof(union foobarbazquux_u) ≥ max((sizeof(int),sizeof(long),sizeof(double),sizeof(long double))" }, { "answer_id": 348500, "author": "cygil", "author_id": 42076, "author_profile": "https://Stackoverflow.com/users/42076", "pm_score": 6, "selected": false, "text": "struct packetheader {\n int sourceaddress;\n int destaddress;\n int messagetype;\n union request {\n char fourcc[4];\n int requestnumber;\n };\n};\n" }, { "answer_id": 14132361, "author": "Ravi Kanth", "author_id": 1944485, "author_profile": "https://Stackoverflow.com/users/1944485", "pm_score": 4, "selected": false, "text": "union SIGSELECT\n{\n SIGNAL_1 signal1;\n SIGNAL_2 signal2;\n .....\n};\n" }, { "answer_id": 18666068, "author": "Krzysztof Voss", "author_id": 405470, "author_profile": "https://Stackoverflow.com/users/405470", "pm_score": 4, "selected": false, "text": "union union float union struct float float float struct union #include <stdio.h> \n\nunion foo {\n struct float_guts {\n unsigned int fraction : 23;\n unsigned int exponent : 8;\n unsigned int sign : 1;\n } fg;\n float f;\n};\n\nvoid print_float(float f) {\n union foo ff;\n ff.f = f;\n printf(\"%f: %d 0x%X 0x%X\\n\", f, ff.fg.sign, ff.fg.exponent, ff.fg.fraction);\n\n}\n\nint main(){\n print_float(0.15625);\n return 0;\n}\n union" }, { "answer_id": 19775707, "author": "Aniket Suryavanshi", "author_id": 1136857, "author_profile": "https://Stackoverflow.com/users/1136857", "pm_score": 2, "selected": false, "text": "int main(int argc, char **argv) {\n union {\n short s;\n char c[sizeof(short)];\n } un;\n\n un.s = 0x0102;\n\n if (sizeof(short) == 2) {\n if (un.c[0] == 1 && un.c[1] == 2)\n printf(\"big-endian\\n\");\n else if (un.c[0] == 2 && un.c[1] == 1)\n printf(\"little-endian\\n\");\n else\n printf(\"unknown\\n\");\n } else\n printf(\"sizeof(short) = %d\\n\", sizeof(short));\n\n exit(0);\n}\n// Program from Unix Network Programming Vol. 1 by Stevens.\n" }, { "answer_id": 24486902, "author": "Anurag Bhakuni", "author_id": 3767017, "author_profile": "https://Stackoverflow.com/users/3767017", "pm_score": 2, "selected": false, "text": "struct emp\n{\n char x; //1 byte\n float y; //4 byte\n} e;\n union emp\n{\n char x; //1 byte\n float y; //4 byte\n} e;\n" }, { "answer_id": 24721580, "author": "Ahmed", "author_id": 3833961, "author_profile": "https://Stackoverflow.com/users/3833961", "pm_score": 2, "selected": false, "text": "#include<stdio.h>\nunion pw {\nshort int i;\nchar ch[2];\n};\nint putw(short int num, FILE *fp);\nint main (void)\n{\nFILE *fp;\nfp fopen(\"test.tmp\", \"wb \");\nputw(1000, fp); /* write the value 1000 as an integer*/\nfclose(fp);\nreturn 0;\n}\nint putw(short int num, FILE *fp)\n{\npw word;\nword.i = num;\nputc(word.c[0] , fp);\nreturn putc(word.c[1] , fp);\n} \n" }, { "answer_id": 34304980, "author": "skanda93", "author_id": 5254632, "author_profile": "https://Stackoverflow.com/users/5254632", "pm_score": 4, "selected": false, "text": "struct MAIN_STRUCT\n{\nUINT64 bufferaddr; \nunion {\n UINT32 data;\n struct INNER_STRUCT{\n UINT16 length; \n UINT8 cso; \n UINT8 cmd; \n } flags;\n } data1;\n};\n" }, { "answer_id": 48090560, "author": "Abdus Sattar Bhuiyan", "author_id": 2455407, "author_profile": "https://Stackoverflow.com/users/2455407", "pm_score": 2, "selected": false, "text": "struct s_tag\n{\n int a; \n long int b;\n} x;\n\nunion u_tag\n{\n int a; \n long int b;\n} y;\n #include<stdio.h>\nstruct s_tag\n{\n int a;\n long int b;\n} x;\nunion u_tag\n{\n int a;\n long int b;\n} y;\nint main()\n{\n printf(\"Memory allocation for structure = %d\", sizeof(x));\n printf(\"\\nMemory allocation for union = %d\", sizeof(y));\n return 0;\n}\n" }, { "answer_id": 71333564, "author": "Yuvraj Singh Jadon", "author_id": 6008082, "author_profile": "https://Stackoverflow.com/users/6008082", "pm_score": 1, "selected": false, "text": "struct car{\n char model[];\n int mileage;\n int price;\n char fuel_type[];\n};\n union verification_details{\n char account_number[10];\n char PAN[10];\n char voter_id[10];\n};\n" }, { "answer_id": 71429949, "author": "Keno", "author_id": 14458011, "author_profile": "https://Stackoverflow.com/users/14458011", "pm_score": 0, "selected": false, "text": "union union union union data\n{\n uint32_t packet;\n uint8_t packetbyte[4];\n} txdata;\n for txdata.packetbyte txdata.packet txdata txdata.packet txdata.packet = 0" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346536", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35416/" ]
346,542
<p>Thanks for reading this</p> <p>I thought I could use find(), but couldn't make it work. I know I can add IDs or classnames, but would like to know how with the current markup.</p> <p>Thanks</p> <p>Here is the HTML</p> <pre><code>&lt;input name="keywordCheckbox" type="checkbox" value="S" /&gt; &lt;input name="keywordCheckbox" type="checkbox" value="C" /&gt; &lt;input name="keywordCheckbox" type="checkbox" value="A" /&gt; </code></pre> <p>and the js</p> <pre><code>&lt;script language="Javascript" src="javascript/jquery-1.2.6.min.js"&gt;&lt;/script&gt; &lt;script type="text/JavaScript"&gt; $(function(){ $('[name="keywordCheckbox"]').bind("click", function() { if($(this).attr("checked") == true) { switch(this.value) { case "A": var $_this = $(this) ; $('[name="keywordCheckbox"]').each(function() { if($(this).val() != $($_this).val()) { $(this).attr("checked",false); } }); break ; default: DOESN'T WORK --&gt; $('[name="keywordCheckbox"]').find('[value="A"]').attr("checked", false);} } // END Switch } // END If }); // End BIND }); // End eventlistener &lt;/script&gt; </code></pre>
[ { "answer_id": 346556, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": 3, "selected": false, "text": "$(\"input[name='keywordCheckbox']\").filter(\"input[value='A']\")\n" }, { "answer_id": 346558, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 6, "selected": true, "text": " $('input[name=\"keywordCheckbox\"][value=\"A\"]').attr(\"checked\",false);\n $('input[name=\"keywordCheckbox\"][value!=\"A\"]').attr(\"checked\",false);\n $(document).ready( function() {\n $('input[name=keywordCheckbox]').bind( 'click', function() {\n if (this.checked) {\n if (this.value == 'A') { \n $('input[name=\"keywordCheckbox\"][value!=\"A\"]')\n .attr(\"checked\",false);\n }\n else {\n $('input[name=\"keywordCheckbox\"][value=\"A\"]')\n .attr(\"checked\",false);\n }\n }\n });\n});\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346542", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2755/" ]
346,544
<p>I have a remote JS that must appear in the head of the document. If the server is slow to respond or inaccessible, obviously this slows or prevents the page from loading. I have been searching for a simple way to set a limit of say 3 seconds (probably less) for it to give up and simply not load the functionality.</p> <p>Does anyone have a simple way to do this with Javascript only?</p>
[ { "answer_id": 346561, "author": "Pim Jager", "author_id": 35197, "author_profile": "https://Stackoverflow.com/users/35197", "pm_score": 2, "selected": false, "text": "<script type='text/javascript'>\nwindow.onload = function(){\n document.write(\"<script type='text/javascript' src='http://domain.com/file.js'></script>\");\n}\n</script>\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346544", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43962/" ]
346,546
<p>Not sure exactly how to word this question ... so edits are welcomed! Anyway ... here goes.</p> <p>I am currently use Crystal Reports to generated Pdfs and just stream the output to the user. My code looks like the following:</p> <pre><code>System.IO.MemoryStream stream = new System.IO.MemoryStream(); stream = (System.IO.MemoryStream)this.Report.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat); this.Response.Clear(); this.Response.Buffer = true; this.Response.ContentType = "application/pdf"; this.Response.BinaryWrite(stream.ToArray()); this.Response.End(); </code></pre> <p>After this code runs it streams the Pdf to the browser opening up Acrobat Reader. Works great! </p> <p>My problem is when the user tries to save the file it defaults to the actual file name ... in this case it defaults to CrystalReportPage.pdf. Is there anyway I can set this? If so, how? </p> <p>Any help would be appreciated.</p>
[ { "answer_id": 346550, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 5, "selected": true, "text": "Content-Disposition: inline; filename=foo.pdf\n" }, { "answer_id": 346554, "author": "mmx", "author_id": 33708, "author_profile": "https://Stackoverflow.com/users/33708", "pm_score": 3, "selected": false, "text": "System.IO.MemoryStream stream = new System.IO.MemoryStream();\n\nstream = (System.IO.MemoryStream)this.Report.ExportToStream(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat);\n\nthis.Response.Clear();\nthis.Response.Buffer = true;\nthis.Response.ContentType = \"application/pdf\";\nthis.Response.AddHeader(\"Content-Disposition\", \"attachment; filename=\\\"\"+FILENAME+\"\\\"\");\nthis.Response.BinaryWrite(stream.ToArray());\nthis.Response.End();\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346546", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1768/" ]
346,567
<p>Given a document written with normal quotes, e.g.</p> <pre><code>Ben said "buttons, dear sir". I replied "Did you say 'buttons'?" to him. </code></pre> <p>What ways can one turn these sort of things into LaTeX quotes, with the appropriate semantics. i.e.</p> <pre><code>Ben said ``buttons, dear sir''. I replied ``Did you say `buttons'?'' to him. </code></pre> <p>So that LaTeX produces:</p> <pre><code>Ben said “buttons, dear sir”. I replied “Did you say ‘buttons’?” </code></pre> <p>My first thought is to turn to a regex. However, I'm not getting any hits from Google or the regex libraries for "LaTeX quotes regular expression", and of course "TeX quotes regular expression" seems to return too many.</p> <p>Thank you.</p>
[ { "answer_id": 346606, "author": "dmckee --- ex-moderator kitten", "author_id": 2509, "author_profile": "https://Stackoverflow.com/users/2509", "pm_score": 4, "selected": true, "text": "\"'\" \"'\" \"don't\" input: text+\ntext: uquote|squote|dquote\nsquote \"'\" text \"'\"\ndquote \"\"\" text \"\"\"\nuquote: [contraction|.]+\ncontraction: [A-Za-z]+ \"'\" [A-Za-z]+\n \"'\" squote dquote" }, { "answer_id": 346607, "author": "John D. Cook", "author_id": 25188, "author_profile": "https://Stackoverflow.com/users/25188", "pm_score": 1, "selected": false, "text": "s/\"(\\w)/``$1/g;\ns/'(\\w)/`$1/g;\ns/([\\w\\.?!])\"/$1''/g;\n" }, { "answer_id": 346627, "author": "Brian M. Hunt", "author_id": 19212, "author_profile": "https://Stackoverflow.com/users/19212", "pm_score": 1, "selected": false, "text": " # A single or double quote before a word character, preceded\n # by start of line, whitespace or punctuation gets converted\n # to \"`\" or \"``\" respectively.\n\n $text =~ s{ ( ^ | [\\s\\p{IsPunct}] )( ['\"] ) (?= \\w ) }\n { $2 eq '\"' ? \"$1``\" : \"$1`\" }mgxe;\n\n # A double quote preceded by a word or punctuation character\n # and followed by whitespace or end of line gets converted to\n # \"''\". (Final single quotes are represented by themselves so\n # we don't need to worry about those.)\n\n $text =~ s{ (?<= [\\w\\p{IsPunct}] ) \" (?= \\s | $ ) }\n { \"''\" }mgxe\n" }, { "answer_id": 4476331, "author": "user1056153", "author_id": 1056153, "author_profile": "https://Stackoverflow.com/users/1056153", "pm_score": 0, "selected": false, "text": "M-x tex-set-quotes (defun tex-set-quotes () \n (interactive) \n (latex-mode) \n (while (search-forward \"\\\"\" nil t) \n (replace-match \"\" nil t) \n (tex-insert-quote nil)))\n" }, { "answer_id": 4535734, "author": "N0thing", "author_id": 158179, "author_profile": "https://Stackoverflow.com/users/158179", "pm_score": 2, "selected": false, "text": "'([ \\w-]+)'\", \" `\\\\1'\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346567", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19212/" ]
346,568
<p>On my blog, I want to display the all the posts from the last month. But if that is less than 10 posts, I want to show the ten most recent posts (in other words, there should never be less than 10 posts on the front page). I am wondering if there is a way to do this in a single query?</p> <p>Currently, I first run this query:</p> <pre><code>select count(*) from posts where timestamp &gt; ($thirty_days_ago) order by timestamp desc </code></pre> <p>If that count is greater than or equal to 10:</p> <pre><code>select * from posts where timestamp &gt; ($thirty_days_ago) order by timestamp desc </code></pre> <p>Otherwise:</p> <pre><code>select * from posts order by timestamp desc limit 10 </code></pre> <p>But this requires me to run two queries. Is there a more efficient way to do this with a single query? (I'm using MySQL.)</p>
[ { "answer_id": 346584, "author": "Bill Karwin", "author_id": 20860, "author_profile": "https://Stackoverflow.com/users/20860", "pm_score": 3, "selected": false, "text": "(SELECT * FROM posts\nWHERE `timestamp` >= NOW() - INTERVAL 30 DAY)\nUNION\n(SELECT * FROM posts\nORDER BY `timestamp` DESC\nLIMIT 10);\n timestamp +------+--------------+------------+------+---------------+------+---------+------+------+----------------+\n| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |\n+------+--------------+------------+------+---------------+------+---------+------+------+----------------+\n| 1 | PRIMARY | posts | ALL | timestamp | NULL | NULL | NULL | 20 | Using where | \n| 2 | UNION | posts | ALL | NULL | NULL | NULL | NULL | 20 | Using filesort | \n| NULL | UNION RESULT | <union1,2> | ALL | NULL | NULL | NULL | NULL | NULL | | \n+------+--------------+------------+------+---------------+------+---------+------+------+----------------+\n" }, { "answer_id": 346603, "author": "Jamal Hansen", "author_id": 2035722, "author_profile": "https://Stackoverflow.com/users/2035722", "pm_score": 0, "selected": false, "text": "select * from posts \nwhere (timestamp >= (NOW() - INTERVAL 30 DAY)) or \n(post_id in (select post_id from posts order by timestamp desc limit 10))\norder by timestamp desc\n" }, { "answer_id": 346642, "author": "Tom", "author_id": 40620, "author_profile": "https://Stackoverflow.com/users/40620", "pm_score": 1, "selected": false, "text": "COUNT SELECT COUNT UNION" }, { "answer_id": 346646, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 3, "selected": true, "text": "select * from posts order by timestamp desc limit 100\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346568", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18511/" ]
346,572
<p>We are developing a port of the GNU Assembler for a client architecture. Now the problem being faced is that:</p> <p>If an immediate operand to an instruction is an expression involving more than one relocatable symbols, how is it handled in output file in elf format. What will be the relocation information produced in such a case?</p> <p>For example:</p> <pre><code>j label1 + label2 </code></pre> <p>where label1 and label2 are defined in relocatable sections, they might be the same sections or different relocatable sections.</p>
[ { "answer_id": 346652, "author": "BCS", "author_id": 1343, "author_profile": "https://Stackoverflow.com/users/1343", "pm_score": 0, "selected": false, "text": "j" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346572", "https://Stackoverflow.com", "https://Stackoverflow.com/users/35416/" ]
346,581
<p>How can I create a empty .mdb file? I'm using ADO.NET and C#. Thanks!</p>
[ { "answer_id": 346614, "author": "MatthewMartin", "author_id": 33264, "author_profile": "https://Stackoverflow.com/users/33264", "pm_score": 4, "selected": true, "text": "COPY model.mdb newdb.mdb DEL newdb.mdb is the drop" }, { "answer_id": 346640, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 2, "selected": false, "text": "using ADOX; // add a COM reference to \"Microsoft ADO Ext. x.x for DDL and Security\" \n\nstatic void CreateMdb(string fileNameWithPath)\n{\n ADOX.Catalog cat = new ADOX.Catalog();\n string connstr = \"Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};Jet OLEDB:Engine Type=5\";\n cat.Create(String.Format(connstr, fileNameWithPath));\n cat = null;\n}\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346581", "https://Stackoverflow.com", "https://Stackoverflow.com/users/12243/" ]
346,589
<p>I am writing an application in C# which is going to do extensive calculations. Everything is going around basic struct - Value. It is basically double with some additional parameters (accuracy etc.) It has to be a struct, because there will be too many of them created to afford heap allocation. Now, I need to make sure they all are correctly initialized. I cannot declare default explicit constructor, though I am provided default constructor, which initializes everything with 0, which does not make sense in my domain.</p> <p>And there is no way to deny creating an instance without calling my constructor with parameters either...?</p> <p>Basically what I need is this test to pass:</p> <pre><code>[Test] public void HowDoesThisStructureInitializeByDefault() { Value v = new Value(); - if this did not compile - it would have been ok! Assert.AreEqual(0, v.Val); - passes Assert.AreEqual(-1, v.Accuracy); - fails } </code></pre> <p>It would be OK to throw an exception if no constructor has been explicitly called and structure is still accessed, but checking that all the time would take too much time.</p> <p>I am almost losing hope now, please help!</p>
[ { "answer_id": 346608, "author": "Aaron", "author_id": 31304, "author_profile": "https://Stackoverflow.com/users/31304", "pm_score": 0, "selected": false, "text": "new Value() new Value(10)" }, { "answer_id": 346618, "author": "tvanfosson", "author_id": 12950, "author_profile": "https://Stackoverflow.com/users/12950", "pm_score": 2, "selected": false, "text": "public static class StructFactory\n{\n public static Value DefaultValue()\n {\n Value v = new Value();\n v.Value = 0.0;\n v.Accuracy = 15; /* digits */\n return v;\n }\n}\n\n...\n\nValue v = StructFactory.DefaultValue();\n" }, { "answer_id": 346624, "author": "mackenir", "author_id": 25457, "author_profile": "https://Stackoverflow.com/users/25457", "pm_score": 2, "selected": false, "text": "struct Value\n{\n int _accuracyPlusOne;\n\n public int Accuracy\n { \n get { return _accuracyPlusOne - 1; }\n get { _accuracyPlusOne= value + 1; }\n }\n}\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346589", "https://Stackoverflow.com", "https://Stackoverflow.com/users/38325/" ]
346,594
<p>I have a client application that once in while notifies about its progress a service. The method call to the service is marked with IsOneWay=true, because the notification doesn't need any return value and I don't want to delay.</p> <p>The client may notify about errors to the service, and afterward it terminates.</p> <p>The question is: does a oneway method call returns to the caller code after it sent the message? or it queues the message and later on it is sent by another thread?</p> <p>The two processes (the client and the service) are on the same machine, and I noticed that sometimes (when the machine is overloaded) the service doesn't get the error notification. I suspect that the second option I mentioned happens, but I am not sure.</p> <p>If I am right, how can I make sure the notification is send and keep the method oneway?</p>
[ { "answer_id": 8995014, "author": "Artur A", "author_id": 304371, "author_profile": "https://Stackoverflow.com/users/304371", "pm_score": 3, "selected": false, "text": " [ServiceContract]\n public interface IService1\n {\n [OperationContract]\n void ThrowException();\n\n [OperationContract(IsOneWay=true)]\n void ThrowExceptionUseIsOneWay();\n }\n public class Service1 : WcfContracts.IService1\n{ \n public void ThrowException()\n {\n throw new Exception(\"Basic exception\");\n }\n\n public void ThrowExceptionUseIsOneWay()\n {\n throw new Exception(\"Basic exception using IsOneWay=true\");\n }\n}\n static void Main(string[] args)\n {\n ServiceHost host = new ServiceHost(typeof(Service1));\n host.Open();\n Console.WriteLine(\"host 1 opened\");\n Console.ReadKey();\n }\n <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <system.serviceModel>\n <services>\n <service behaviorConfiguration=\"behavourHttpGet\" name=\"WcfConsoleHoster.Service1\">\n <host>\n <baseAddresses>\n <add baseAddress=\"http://localhost:8732/Design_Time_Addresses/WcfConsoleHoster/Service1/\" />\n </baseAddresses>\n </host>\n <endpoint binding=\"wsHttpBinding\" contract=\"WcfContracts.IService1\" /> \n <endpoint address =\"mex\" binding=\"mexHttpBinding\" contract=\"IMetadataExchange\" />\n </service>\n </services>\n <behaviors>\n <serviceBehaviors>\n <behavior name=\"behavourHttpGet\">\n <serviceMetadata httpGetEnabled=\"true\" />\n </behavior>\n </serviceBehaviors>\n </behaviors>\n </system.serviceModel>\n</configuration>\n Console.WriteLine(\"Wcf client. Press any key to start\");\nConsole.ReadKey();\nChannelFactory<IService1> factory = new ChannelFactory<IService1>(\"Service1_Endpoint\");\nIService1 channel = factory.CreateChannel();\n//Call service method\nchannel.ThrowException();\n\nConsole.WriteLine(\"Operation executed\");\nConsole.ReadKey();\n <?xml version=\"1.0\" encoding=\"utf-8\" ?>\n<configuration>\n <system.serviceModel>\n <client>\n <endpoint name=\"Service1_Endpoint\"\n address=\"http://localhost:8732/Design_Time_Addresses/WcfConsoleHoster/Service1/\"\n binding=\"wsHttpBinding\"\n contract=\"WcfContracts.IService1\">\n </endpoint>\n </client>\n </system.serviceModel>\n</configuration>\n channel.ThrowExceptionUseIsOneWay(); IsOneWay=true Thread.Sleep() IService1 [OperationContract]\n int ThreadSleep();\n\n [OperationContract(IsOneWay=true)]\n public int ThreadSleep()\n{\n System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));\n return 1;\n}\n\npublic void ThreadSleepUseIsOneWay()\n{\n System.Threading.Thread.Sleep(TimeSpan.FromSeconds(5));\n}\n System.Diagnostics.Stopwatch stopwatch = new System.Diagnostics.Stopwatch();\nstopwatch.Start();\n//call methode\nchannel.ThreadSleep();\nstopwatch.Stop();\nConsole.WriteLine(string.Format(\"Operation executed in {0} seconds\", stopwatch.Elapsed.Seconds));\nConsole.ReadKey();\n ThreadSleep() One way method channel.ThreadSleepUseIsOneWay()" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346594", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
346,613
<p>How can you prematurely exit from a function without returning a value if it is a void function? I have a void method that needs to not execute its code if a certain condition is true. I really don't want to have to change the method to actually return a value.</p>
[ { "answer_id": 346616, "author": "mmx", "author_id": 33708, "author_profile": "https://Stackoverflow.com/users/33708", "pm_score": 9, "selected": true, "text": "return;\n if (condition) return;\n void" }, { "answer_id": 346619, "author": "jwfearn", "author_id": 10559, "author_profile": "https://Stackoverflow.com/users/10559", "pm_score": 4, "selected": false, "text": "void foo ( int i ) {\n if ( i < 0 ) return; // do nothing\n // do something\n}\n" }, { "answer_id": 346621, "author": "Stephen Caldwell", "author_id": 33437, "author_profile": "https://Stackoverflow.com/users/33437", "pm_score": 4, "selected": false, "text": "void foo() {\n /* do some stuff */\n if (!condition) {\n return;\n }\n}\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346613", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43875/" ]
346,622
<p>I'm curious about conventions for type-punning pointers/arrays in C++. Here's the use case I have at the moment:</p> <blockquote> Compute a simple 32-bit checksum over a binary blob of data by treating it as an array of 32-bit integers (we know its total length is a multiple of 4), and then summing up all values and ignoring overflow. </blockquote> <p>I would expect such an function to look like this:</p> <pre><code>uint32_t compute_checksum(const char *data, size_t size) { const uint32_t *udata = /* ??? */; uint32_t checksum = 0; for (size_t i = 0; i != size / 4; ++i) checksum += udata[i]; return udata; } </code></pre> <p>Now the question I have is, what do you consider the "best" way to convert <code>data</code> to <code>udata</code>?</p> <p>C-style cast?</p> <pre><code>udata = (const uint32_t *)data </code></pre> <p>C++ cast that assumes all pointers are convertible?</p> <pre><code>udata = reinterpret_cast&lt;const uint32_t *&gt;(data) </code></pre> <p>C++ cast that between arbitrary pointer types using intermediate <code>void*</code>?</p> <pre><code>udata = static_cast&lt;const uint32_t *&gt;(static_cast&lt;const void *&gt;(data)) </code></pre> <p>Cast through a union?</p> <pre><code>union { const uint32_t *udata; const char *cdata; }; cdata = data; // now use udata </code></pre> <p>I fully realize that this will not be a 100% portable solution, but I am only expecting to use it on a small set of platforms where I know it works (namely unaligned memory accesses and compiler assumptions on pointer aliasing). What would you recommend?</p>
[ { "answer_id": 346764, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 5, "selected": true, "text": "const char *data const uint3_t * static_cast reinterpret_cast my_reint" }, { "answer_id": 347585, "author": "Steve Jessop", "author_id": 13005, "author_profile": "https://Stackoverflow.com/users/13005", "pm_score": 3, "selected": false, "text": "#include <numeric>\n#include <vector>\n#include <cstring>\n\nuint32_t compute_checksum(const char *data, size_t size) {\n std::vector<uint32_t> intdata(size/sizeof(uint32_t));\n std::memcpy(&intdata[0], data, size);\n return std::accumulate(intdata.begin(), intdata.end(), 0);\n}\n checksum += ((data[i] && 0xFF) << shift[i % 4]);\n uint32_t compute_checksum(const char *data, size_t size) {\n uint32_t total = 0;\n for (size_t i = 0; i < size; i += sizeof(uint32_t)) {\n uint32_t thisone;\n std::memcpy(&thisone, &data[i], sizeof(uint32_t));\n total += thisone;\n }\n return total;\n}\n" }, { "answer_id": 7740316, "author": "Hybrid", "author_id": 878491, "author_profile": "https://Stackoverflow.com/users/878491", "pm_score": -1, "selected": false, "text": "// safely cast between types without breaking strict aliasing rules\ntemplate<typename ReturnType, typename OriginalType>\nReturnType Cast( OriginalType Variable )\n{\n union\n {\n OriginalType In;\n ReturnType Out;\n };\n\n In = Variable;\n return Out;\n}\n\n// example usage\nint i = 0x3f800000;\nfloat f = Cast<float>( i );\n" }, { "answer_id": 33978218, "author": "Петър Петров", "author_id": 625904, "author_profile": "https://Stackoverflow.com/users/625904", "pm_score": 0, "selected": false, "text": "#include <iostream>\n#include <string>\n#include <cstring>\n\n uint32_t compute_checksum_memcpy(const char *data, size_t size)\n {\n uint32_t checksum = 0;\n for (size_t i = 0; i != size / 4; ++i)\n {\n // memcpy may be slow, unneeded allocation\n uint32_t dest; \n memcpy(&dest,data+i,4);\n checksum += dest;\n }\n return checksum;\n }\n\n uint32_t compute_checksum_address_recast(const char *data, size_t size)\n {\n uint32_t checksum = 0;\n for (size_t i = 0; i != size / 4; ++i)\n {\n //classic old type punning\n checksum += *(uint32_t*)(data+i);\n }\n return checksum;\n }\n\n uint32_t compute_checksum_union(const char *data, size_t size)\n {\n uint32_t checksum = 0;\n for (size_t i = 0; i != size / 4; ++i)\n {\n //Syntax hell\n checksum += *((union{const char* c;uint32_t* i;}){.c=data+i}).i;\n }\n return checksum;\n }\n\n // Wrong!\n uint32_t compute_checksum_deref(const char *data, size_t size)\n {\n uint32_t checksum = 0;\n for (size_t i = 0; i != size / 4; ++i)\n {\n checksum += *&data[i];\n }\n return checksum;\n }\n\n // Wrong!\n uint32_t compute_checksum_cast(const char *data, size_t size)\n {\n uint32_t checksum = 0;\n for (size_t i = 0; i != size / 4; ++i)\n {\n checksum += *(data+i);\n }\n return checksum;\n }\n\n\nint main()\n{\n const char* data = \"ABCDEFGH\";\n std::cout << compute_checksum_memcpy(data, 8) << \" OK\\n\";\n std::cout << compute_checksum_address_recast(data, 8) << \" OK\\n\";\n std::cout << compute_checksum_union(data, 8) << \" OK\\n\";\n std::cout << compute_checksum_deref(data, 8) << \" Fail\\n\";\n std::cout << compute_checksum_cast(data, 8) << \" Fail\\n\";\n}\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346622", "https://Stackoverflow.com", "https://Stackoverflow.com/users/40620/" ]
346,644
<p>The following code will generate a link to the page I want to get to.</p> <pre><code>&lt;%= Html.ActionLink(image.Title, image.Id.ToString(), "Image") %&gt; </code></pre> <p>The following code will cause the correct url to be rendered on the page.</p> <pre><code>&lt;%= Url.Action("Index", "Image", new { id = image.Id })%&gt; </code></pre> <p>But when I try to use it in javascript it fails. (with some strange error about page inheritance)</p> <pre><code>&lt;div onclick="window.location = '&lt;%= Url.Action("Index", "Image", new { id = image.Id })%&gt;'"&gt; ... &lt;/div&gt; </code></pre> <p>Should the above code work? What is the correct way to generate the javascript attempted above?</p> <p><strong>Update</strong> There error I get is </p> <blockquote> <p>Views\Home\Index.aspx.cs(9): error ASPNET: Make sure that the class defined in this code file matches the 'inherits' attribute, and that it extends the correct base class (e.g. Page or UserControl).</p> </blockquote> <p>Looks like it indicates a bigger problem.</p> <p><strong>Fixed</strong> Thanks for your help, the code contained a div with <code>runat="server"</code>. When I removed this it runs OK. This maybe because there is no form with <code>runat="server"</code> but I would expect a different error for that.</p> <p><strong>As this question doesn't seem meaningful should I delete it?</strong></p>
[ { "answer_id": 346771, "author": "Todd Smith", "author_id": 31624, "author_profile": "https://Stackoverflow.com/users/31624", "pm_score": 0, "selected": false, "text": "<%= Url.Action(\"Image\", \"Home\", new { id = image.Id })%>\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346644", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18107/" ]
346,649
<p>I have two constructor :</p> <pre><code>function clsUsagerEmailUserName($nickName, $email) { $this-&gt;nickName = $nickName; $this-&gt;email = $email; } function clsUsagerEmailUserName($email) { $this-&gt;email = $email; } </code></pre> <p>But this is not working? What's wrong, isn't supposed to be OO at this version of PHP? (I just migrate from PHP4)</p>
[ { "answer_id": 346651, "author": "Patrick Desjardins", "author_id": 13913, "author_profile": "https://Stackoverflow.com/users/13913", "pm_score": 3, "selected": true, "text": "function __construct ($var1, $var2 = null)\n{\n if (isset($var2))\n {\n //Do one thing\n }\n else\n {\n //Do another\n }\n}\n" }, { "answer_id": 346661, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 2, "selected": false, "text": "function __construct()\n{\n switch ( func_num_args() ) {\n case 1:\n $this->email = func_get_arg(0);\n break;\n case 2:\n $this->nickName = func_get_arg(0);\n $this->email = func_get_arg(1);\n break;\n // [...]\n default:\n throw new Exception('Wrong number of values passed to constructor');\n }\n}\n" }, { "answer_id": 346662, "author": "Kaii", "author_id": 43959, "author_profile": "https://Stackoverflow.com/users/43959", "pm_score": 2, "selected": false, "text": "function clsUsagerEmailUserName($nickName, $email = NULL)\n{ \n if ($email <> NULL)\n {\n $this->nickName = $nickName;\n $this->email = $eMail;\n }\n else\n {\n $this->email = $nickName;\n }\n}\n function clsUsagerEmailUserName($email, $nickName = NULL)\n{\n $this->email = $email;\n if ($nickName <> NULL)\n $this->nickName = $nickName;\n}\n" }, { "answer_id": 356771, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "abstract class AlmostPolymorphicObject {\n public function __construct() {\n $args = func_get_args();\n $argsCount = count($args);\n $callback = array($this, '_construct'.$argsCount);\n if (!is_callable($callback)) {\n throw new Exception('no valid constructor for param count '.$argsCount);\n }\n return call_user_func_array($callback, $args);\n }\n}\n\nclass FooBar extends AlmostPolymorphicObject {\n private function _construct0() {\n }\n\n private function _construct1($var1) {\n }\n\n private function _construct2($var1, $var2) {\n }\n}\n\n$var = new FooBar(); // would run _construct0\n$var = new FooBar('var'); // would run _construct1\n$var = new FooBar('var','var'); // would run _construct2\n$var = new FooBar('var','var', 'asdasd'); // would throw error 'no valid constructor for param count 3'\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346649", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21386/" ]
346,659
<p>All of us who work with relational databases have learned (or are learning) that SQL is different. Eliciting the desired results, and doing so efficiently, involves a tedious process partly characterized by learning unfamiliar paradigms, and finding out that some of our most familiar programming patterns don't work here. What are the common antipatterns you've seen (or yourself committed)?</p>
[ { "answer_id": 346679, "author": "Amy B", "author_id": 8155, "author_profile": "https://Stackoverflow.com/users/8155", "pm_score": 7, "selected": false, "text": "SELECT *\nInsert Into blah SELECT *\n SELECT fieldlist\nInsert Into blah (fieldlist) SELECT fieldlist\n DECLARE @LoopVar int\n\nSET @LoopVar = (SELECT MIN(TheKey) FROM TheTable)\nWHILE @LoopVar is not null\nBEGIN\n -- Do Stuff with current value of @LoopVar\n ...\n --Ok, done, now get the next value\n SET @LoopVar = (SELECT MIN(TheKey) FROM TheTable\n WHERE @LoopVar < TheKey)\nEND\n --Trim the time\nConvert(Convert(theDate, varchar(10), 121), datetime)\n --Trim the time\nDateAdd(dd, DateDiff(dd, 0, theDate), 0)\n SELECT *\nFROM blah\nWHERE (blah.Name = @name OR @name is null)\n AND (blah.Purpose = @Purpose OR @Purpose is null)\n" }, { "answer_id": 346687, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 6, "selected": false, "text": "from employee t1,\ndepartment t2,\njob t3,\n...\n" }, { "answer_id": 346696, "author": "devio", "author_id": 21336, "author_profile": "https://Stackoverflow.com/users/21336", "pm_score": 3, "selected": false, "text": "img_media_type ENUM(\"UNKNOWN\", \"BITMAP\", \"DRAWING\", \"AUDIO\", \"VIDEO\", \n \"MULTIMEDIA\", \"OFFICE\", \"TEXT\", \"EXECUTABLE\", \"ARCHIVE\") default NULL,\nimg_major_mime ENUM(\"unknown\", \"application\", \"audio\", \"image\", \"text\", \n \"video\", \"message\", \"model\", \"multipart\") NOT NULL default \"unknown\",\n CONVERT(NVARCHAR, GETDATE())\n" }, { "answer_id": 346850, "author": "Juliet", "author_id": 40516, "author_profile": "https://Stackoverflow.com/users/40516", "pm_score": 8, "selected": true, "text": "SELECT\n FirstName + ' ' + LastName as \"Full Name\",\n case UserRole\n when 2 then \"Admin\"\n when 1 then \"Moderator\"\n else \"User\"\n end as \"User's Role\",\n case SignedIn\n when 0 then \"Logged in\"\n else \"Logged out\"\n end as \"User signed in?\",\n Convert(varchar(100), LastSignOn, 101) as \"Last Sign On\",\n DateDiff('d', LastSignOn, getDate()) as \"Days since last sign on\",\n AddrLine1 + ' ' + AddrLine2 + ' ' + AddrLine3 + ' ' +\n City + ', ' + State + ' ' + Zip as \"Address\",\n 'XXX-XX-' + Substring(\n Convert(varchar(9), SSN), 6, 4) as \"Social Security #\"\nFROM Users\n" }, { "answer_id": 346901, "author": "Adrian Pronk", "author_id": 41861, "author_profile": "https://Stackoverflow.com/users/41861", "pm_score": 4, "selected": false, "text": "select some_column, ...\nfrom some_table\ngroup by some_column\n" }, { "answer_id": 346908, "author": "Jonathan Leffler", "author_id": 15168, "author_profile": "https://Stackoverflow.com/users/15168", "pm_score": 2, "selected": false, "text": "DECLARE c1 CURSOR FOR SELECT Col1, Col2, Col3 FROM Table1\n\nFOREACH c1 INTO a.col1, a.col2, a.col3\n DECLARE c2 CURSOR FOR\n SELECT Item1, Item2, Item3\n FROM Table2\n WHERE Table2.Item1 = a.col2\n FOREACH c2 INTO b.item1, b.item2, b.item3\n ...process data from records a and b...\n END FOREACH\nEND FOREACH\n DECLARE c1 CURSOR FOR\n SELECT Col1, Col2, Col3, Item1, Item2, Item3\n FROM Table1, Table2\n WHERE Table2.Item1 = Table1.Col2\n -- ORDER BY Table1.Col1, Table2.Item1\n\nFOREACH c1 INTO a.col1, a.col2, a.col3, b.item1, b.item2, b.item3\n ...process data from records a and b...\nEND FOREACH\n" }, { "answer_id": 346949, "author": "Joel Coehoorn", "author_id": 3043, "author_profile": "https://Stackoverflow.com/users/3043", "pm_score": 4, "selected": false, "text": "FROM TableA, TableB WHERE FROM TableA INNER JOIN TableB ON" }, { "answer_id": 347001, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 6, "selected": false, "text": "var query = \"select COUNT(*) from Users where UserName = '\" \n + tbUser.Text \n + \"' and Password = '\" \n + tbPassword.Text +\"'\";\n" }, { "answer_id": 348485, "author": "jason saldo", "author_id": 1293, "author_profile": "https://Stackoverflow.com/users/1293", "pm_score": 3, "selected": false, "text": "SELECT \nCASE @problem \n WHEN 'Need to replace column A with this medium to large collection of strings hanging out in my code.' \n THEN 'Create a table for lookup and add to your from clause.' \n WHEN 'Scrubbing values in the result set based on some business rules.' \n THEN 'Fix the data in the database' \n WHEN 'Formating dates or numbers.' \n THEN 'Apply formating in the presentation layer.' \n WHEN 'Createing a cross tab' \n THEN 'Good, but in reporting you should probably be using cross tab, matrix or pivot templates' \nELSE 'You probably found another case for no CASE but now I have to edit my code instead of enriching the data...' END \n" }, { "answer_id": 443876, "author": "Tony Andrews", "author_id": 18747, "author_profile": "https://Stackoverflow.com/users/18747", "pm_score": 2, "selected": false, "text": "select emp.empno, dept.deptno\nfrom emp\njoin dept on dept.deptno = emp.deptno;\n" }, { "answer_id": 764805, "author": "Jasper Bekkers", "author_id": 31486, "author_profile": "https://Stackoverflow.com/users/31486", "pm_score": 4, "selected": false, "text": "SELECT FirstName + ' ' + LastName as \"Full Name\", case UserRole when 2 then \"Admin\" when 1 then \"Moderator\" else \"User\" end as \"User's Role\", case SignedIn when 0 then \"Logged in\" else \"Logged out\" end as \"User signed in?\", Convert(varchar(100), LastSignOn, 101) as \"Last Sign On\", DateDiff('d', LastSignOn, getDate()) as \"Days since last sign on\", AddrLine1 + ' ' + AddrLine2 + ' ' + AddrLine3 + ' ' + City + ', ' + State + ' ' + Zip as \"Address\", 'XXX-XX-' + Substring(Convert(varchar(9), SSN), 6, 4) as \"Social Security #\" FROM Users\n" }, { "answer_id": 770302, "author": "geofftnz", "author_id": 20122, "author_profile": "https://Stackoverflow.com/users/20122", "pm_score": 4, "selected": false, "text": "SELECT personid, firstname, lastname, age\nINTO #tmpPeople\nFROM People\nWHERE lastname like 's%'\n\nDELETE FROM #tmpPeople\nWHERE firstname = 'John'\n\nDELETE FROM #tmpPeople\nWHERE firstname = 'Jon'\n\nDELETE FROM #tmpPeople\nWHERE age > 35\n\nUPDATE People\nSET firstname = 'Fred'\nWHERE personid IN (SELECT personid from #tmpPeople)\n" }, { "answer_id": 854640, "author": "Luc M", "author_id": 14673, "author_profile": "https://Stackoverflow.com/users/14673", "pm_score": 2, "selected": false, "text": "code_1\nvalue_1\ncode_2\nvalue_2\n...\ncode_10\nvalue_10\n" }, { "answer_id": 2194302, "author": "Brian", "author_id": 700, "author_profile": "https://Stackoverflow.com/users/700", "pm_score": -1, "selected": false, "text": "select \n ...\nfrom data\nwhere RECORD.STATE IN (\n SELECT STATEID\n FROM STATE\n WHERE NAME IN\n ('Published to test',\n 'Approved for public',\n 'Published to public',\n 'Archived'\n ))\n with valid_states as (\n SELECT STATEID\n FROM STATE\n WHERE NAME IN\n ('Published to test',\n 'Approved for public',\n 'Published to public',\n 'Archived'\n )\nselect ... from data, valid_states\nwhere data.state = valid_states.state\n select \n ... \nfrom data join states using (state)\nwhere \nstates.state in ('Published to test',\n 'Approved for public',\n 'Published to public',\n 'Archived'\n )\n" }, { "answer_id": 5542789, "author": "Iwo Banas", "author_id": 330779, "author_profile": "https://Stackoverflow.com/users/330779", "pm_score": 2, "selected": false, "text": "JOIN SELECT DISTINCT CREATE VIEW my_view AS \n SELECT * FROM table1\n JOIN table2 ON (...)\n JOIN table3 ON (...);\n\n SELECT col1, col2 FROM my_view WHERE col3 = 123;\n" }, { "answer_id": 5905311, "author": "Tegiri Nenashi", "author_id": 432426, "author_profile": "https://Stackoverflow.com/users/432426", "pm_score": 2, "selected": false, "text": "CREATE OR REPLACE FORCE VIEW PRICE (PART_NUMBER, PRICE_LIST, LIST_VERSION ...)\nAS\n SELECT sp.MKT_PART_NUMBER,\n sp.PRICE_LIST,\n sp.LIST_VERSION,\n sp.MIN_PRICE,\n sp.UNIT_PRICE,\n sp.MAX_PRICE,\n...\n" }, { "answer_id": 7007339, "author": "sayap", "author_id": 422321, "author_profile": "https://Stackoverflow.com/users/422321", "pm_score": 2, "selected": false, "text": "IN (...) EXISTS" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346659", "https://Stackoverflow.com", "https://Stackoverflow.com/users/31641/" ]
346,692
<p>I have written a very simple bash script to help me migrate from dev to staging. What it does is it deletes all files in staging, copies the files over from dev to stage.</p> <p>However, the config.inc.php file needs to have the first instance of "dev" to be changed to "stage", and no other instance changed.</p> <p>Second, everytime I run it (I run the script from the dev directory), i'd like it to write a log back in the dev directory which will append the date/time stamp that I ran the staging bash script into this log.</p> <p>Thanks.</p>
[ { "answer_id": 346699, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 0, "selected": false, "text": "sed sed -i -e s/dev/stage/ config.inc.php\n -i /dev/stage/ -e" }, { "answer_id": 346704, "author": "friol", "author_id": 23034, "author_profile": "https://Stackoverflow.com/users/23034", "pm_score": 1, "selected": false, "text": "cat config.inc.php | sed 's:dev::stage' > config.inc.php.new \n echo $timestamp >> mylogfile.log\n" }, { "answer_id": 346711, "author": "hayalci", "author_id": 16084, "author_profile": "https://Stackoverflow.com/users/16084", "pm_score": 3, "selected": true, "text": "sed -i '0,/dev/ s/dev/stage/' config.inc.php\n s/\\<dev\\>/stage/ sed -i \"/\\<dev\\>/,/\\<dev\\>/ s/dev/stage/\" config.inc.php\n date >> /path/to/dev/run.log\n sed devel stagel sed dev dev 0,/dev/ 0,/\\<dev\\>/ \"s/\\<dev\\>/stage/\" sed sed '\\'' -i sed sed sed -r sed -i -r '0,/\\<dev\\>/s/\\<dev\\>/stage/' config.inc.php\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346692", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43980/" ]
346,702
<p>I'm using the urlrewriter.net as recommended in several questions in here. I'm having difficulties with displaying images and with the stylesheet.</p> <p>I read ScottGu's Blog (again as recommended in here) and in the end he does reffer to this problem and states to use ~/ for server controls etc. ("Handling CSS and Image Reference Correctly" at the end of the article).</p> <p>I tried his solution and it doesn't seem to work.</p> <p>The only thing that seems to work for me is to write the full path. For some reason, it doesn't seem to me as the right solution. It would make a serious problem developing and debugging.</p> <p>Does anyone know what can be the cause of the problem? Is there something I need to change in the web.config file?</p> <p>Thanks</p>
[ { "answer_id": 348010, "author": "Jamie", "author_id": 24559, "author_profile": "https://Stackoverflow.com/users/24559", "pm_score": 0, "selected": false, "text": "<base href=\"http://www.w3schools.com/images/\" />\n <head>" }, { "answer_id": 371786, "author": "user46702", "author_id": 46702, "author_profile": "https://Stackoverflow.com/users/46702", "pm_score": 0, "selected": false, "text": "<base id=\"BasePath\" runat=\"Server\"/ if (Request.IsSecureConnection)\n baseUrl += \"https://\";\n else\n baseUrl += \"http://\";\n baseUrl += Request.Url.Host;\n\n if (Request.Url.Port != 80)\n baseUrl += \":\" + Request.Url.Port.ToString();\n\n baseUrl += Request.RawUrl;\n\n BasePath.Attributes.Add(\"HREF\", baseUrl);\n }\n" }, { "answer_id": 428981, "author": "Eduardo Molteni", "author_id": 2385, "author_profile": "https://Stackoverflow.com/users/2385", "pm_score": 2, "selected": false, "text": "<link href=\"<%=Page.ResolveUrl(\"~/mycss.css\")%>\" type=\"text/css\" rel=\"stylesheet\" />\n" }, { "answer_id": 1081809, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "<a href=\"<% =GetBaseURL() %>/\">Home</a>\n\npublic static string GetBaseURL()\n{\n\nstring url =HttpContext.Current.Request.Url.Scheme + “://” + HttpContext.Current.Request.Url.Authority + HttpContext.Current.Request.ApplicationPath.TrimEnd(’/') + ‘/’;\n\n//EPiServer’s url start with a / so remove the url if (when) it contains one\nif(url.EndsWith(”/”))\nreturn url.Remove(url.LastIndexOf(”/”));\nelse\nreturn url;\n}\n" }, { "answer_id": 1081845, "author": "Greg B", "author_id": 1741868, "author_profile": "https://Stackoverflow.com/users/1741868", "pm_score": 0, "selected": false, "text": "Virtual Path => Physical Path\n / => /page.aspx?id=1\n /food/banana => /page.aspx?id=2\n <link rel=\"stylesheet\" href=\"css/main.css\"/>\n" }, { "answer_id": 1789113, "author": "mathijsuitmegen", "author_id": 78939, "author_profile": "https://Stackoverflow.com/users/78939", "pm_score": 0, "selected": false, "text": "<link href=\"App_Themes/darkOrange/base.css\" type=\"text/css\" rel=\"stylesheet\" />\n<link href=\"App_Themes/darkOrange/cart-checkout-order.css\" type=\"text/css\" rel=\"stylesheet\" />\n<link href=\"App_Themes/darkOrange/category.css\" type=\"text/css\" rel=\"stylesheet\" />\n...\n <link href=\"../App_Themes/darkOrange/base.css\" type=\"text/css\" rel=\"stylesheet\" />\n<link href=\"../App_Themes/darkOrange/cart-checkout-order.css\" type=\"text/css\" rel=\"stylesheet\" />\n<link href=\"../App_Themes/darkOrange/category.css\" type=\"text/css\" rel=\"stylesheet\" />\n <!--[if IE 6]>\n<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"/css/ie6.css\" />\n<![endif]-->\n <!--[if IE 6]>\n<link rel=\"stylesheet\" type=\"text/css\" media=\"screen\" href=\"/css/ie6.css\" />\n<![endif]-->\n <link href=\"App_Themes/darkOrange/css/ie6.css\" type=\"text/css\" rel=\"stylesheet\" />\n filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true', sizingMethod='crop', src='../App_Themes/darkOrange/img/transparent_image_example.png');\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346702", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
346,703
<p>Is there a compelling reason to not use <a href="http://us2.php.net/debug_backtrace" rel="noreferrer"><code>debug_backtrace</code></a> for the sole purpose of determining the calling method's class, name, and parameter list? Not for debugging purposes. It has the word "debug" in the function name, which makes me feel a little dirty to be using it in this way, but it fit the bill for what I needed to do (a single function that can be called from many places and needs to call the calling method from another system). It works, but is this still a bad idea? If so, why?</p>
[ { "answer_id": 2962151, "author": "Jauzsika", "author_id": 253377, "author_profile": "https://Stackoverflow.com/users/253377", "pm_score": 0, "selected": false, "text": "/*Called from /var/www/micimacko.php at line 28*/ SELECT count(*) FROM rofibeka;\n" }, { "answer_id": 34075506, "author": "Beracah", "author_id": 1758215, "author_profile": "https://Stackoverflow.com/users/1758215", "pm_score": 2, "selected": false, "text": "<?\nclass a {\n public $v = 'xyz';\n function __construct($x,$y)\n {\n $b = new b();\n }\n}\nclass b {\n function __construct()\n {\n $start = microtime();\n $x = debug_backtrace();\n $end = microtime();\n echo ($end-$start) . \"\\n\";\n print_r($x);\n $obj = $x[1]['object'];\n print_r($obj);\n }\n}\n$a = new a(1,2);\n?>\n" }, { "answer_id": 64047180, "author": "Johannes Reiners", "author_id": 585256, "author_profile": "https://Stackoverflow.com/users/585256", "pm_score": 1, "selected": false, "text": "debug_backtrace <?php\n\nconst DEPTH = 30;\nconst BACKTRACE = false;\n\nclass TestClass\n{\n public $a;\n public $b;\n\n public function __construct()\n {\n $foo = new Foo();\n $bar = new Bar();\n $alice = new Alice();\n\n $alice->a = $foo;\n $bar->a = $foo;\n\n $foo->a = $bar;\n $alice->b = $bar;\n\n $foo->b = $alice;\n $bar->b = $alice;\n\n $this->a = $foo;\n $this->b = $bar;\n }\n\n public function method($depth)\n {\n BACKTRACE ? debug_backtrace() : null;\n $obj = mt_rand(0,1) === 1 ? $this->a : $this->b;\n\n if ($depth > DEPTH) {\n return;\n }\n $obj->method($depth+1);\n\n }\n}\n\nclass Foo\n{\n public $a;\n public $b;\n\n public function method($depth)\n {\n BACKTRACE ? debug_backtrace() : null;\n\n $obj = mt_rand(0,1) === 1 ? $this->a : $this->b;\n\n if ($depth > DEPTH) {\n return;\n }\n $obj->method($depth+1);\n }\n}\n\nclass Bar\n{\n public $a;\n public $b;\n public function method($depth)\n {\n BACKTRACE ? debug_backtrace() : null;\n $obj = mt_rand(0,1) === 1 ? $this->a : $this->b;\n\n if ($depth > DEPTH) {\n return;\n }\n $obj->method($depth+1);\n }\n}\n\nclass Alice\n{\n public $a;\n public $b;\n\n public function method($depth)\n {\n BACKTRACE ? debug_backtrace() : null;\n\n $obj = mt_rand(0,1) === 1 ? $this->a : $this->b;\n\n if ($depth > DEPTH) {\n return;\n }\n\n $obj->method($depth+1);\n }\n}\n\n\n$test = new TestClass();\n\n$startWhole = microtime(true);\nfor($i = 0; $i < 10000;$i++) {\n $start = microtime(true);\n $test->method(0);\n $end = microtime(true);\n}\n$endWhole = microtime(true);\n$total = $endWhole - $startWhole;\n\necho 'total time: ' . $total . \"s\\n\";\n Performance (10.000 iterations / stack depth 30 / PHP 7.2):\n\nwith debug_backtrace - total time: 0.86011600494385s\nwithout: - total time: 0.043321847915649s \n debug_backtrace" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346703", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43496/" ]
346,708
<p>I'm trying to do project Euler number <a href="http://projecteuler.net/index.php?section=problems&amp;id=219" rel="nofollow noreferrer">219</a> but am failing to get a grasp of it. I'm trying to use Python which according to project Euler should be able to do it within a minute! This leads me to think that they can't possibly want me to compute each individual bitstring since that would be too slow in Python - there has to be a sub O(n) algorithm.</p> <p>I have looked at a recursive solution which stores the bitstrings possible prefixes so that it can quickly pick a new bitstring and it even considers them in groups. This only works in brute-forcing values up to a bit over 10:</p> <pre><code>cost(1) = 1 cost(2) = 5 cost(3) = 11 cost(4) = 18 cost(5) = 26 cost(6) = 35 cost(7) = 44 cost(8) = 54 cost(9) = 64 cost(10)= 74 cost(11)= 85 cost(12)= 96 </code></pre> <p>Past this, I am struggling to comprehend how reduce the problem. It is always possible to make a pattern that goes like:</p> <pre><code>1 01 001 0001 00001 00000 </code></pre> <p>But it isn't optimal for more than 7 bitstrings. Can anyone guide me in what I should be considering?</p>
[ { "answer_id": 346758, "author": "mattiast", "author_id": 8272, "author_profile": "https://Stackoverflow.com/users/8272", "pm_score": 0, "selected": false, "text": "Cost(n) = min {Cost(k)+Cost(n-k)+k+4*(n-k) | 0 < k < n}" }, { "answer_id": 346945, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "def cost(n):\n if n == 1: return 1\n\n m = None\n for k in range(1, n):\n v = cost(k)+cost(n-k)+k+4*(n-k)\n if not m or v < m: m = v\n\n return m\n\nprint(cost(6))\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346708", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
346,718
<p>I am trying to make a combined image of all images added to a modell in django with inline editing and a ForeignKey. Ive got these models (simplified):</p> <pre><code>class Modell(models.Model): title = models.CharField('beskrivelse', max_length=200) slug = models.SlugField() is_public = models.BooleanField('publisert', default=True) def __unicode__(self): return self.title def save(self, **kwargs): super(Modell, self).save(**kwargs) on_modell_saved(self) class Image(models.Model): modell = models.ForeignKey(Modell, related_name="images") image = ThumbnailImageField('bilde', upload_to=get_upload_path_image) class Meta: verbose_name = 'bilde' verbose_name_plural = 'bilder' def __unicode__(self): return str(self.image) </code></pre> <p>Then i add Image to the Modell with AdminInline, so when i save the Modell i save x number of images.</p> <p>But when I try to do something with Modell.images.all in the on_modell_saved function i cant get hold of the objects. Ive got this function that is executed at Modell.save()</p> <pre><code>def on_modell_saved(instance): for img in instance.images.all(): print img </code></pre> <p>This only prints something the second time i save the Modell and not the first time. So anybody know how to call a function after all items that you are adding with AdminInline is saved?</p>
[ { "answer_id": 346763, "author": "Daniel Naab", "author_id": 32638, "author_profile": "https://Stackoverflow.com/users/32638", "pm_score": 1, "selected": false, "text": "Modell Image Image def on_image_saved(instance):\n for img in Image.objects.filter(modell=instance.modell)\n print img\n\nclass Image(models.Model):\n modell = models.ForeignKey(Modell, related_name=\"images\")\n image = ThumbnailImageField('bilde', upload_to=get_upload_path_image)\n\n class Meta:\n verbose_name = 'bilde'\n verbose_name_plural = 'bilder'\n\n def __unicode__(self):\n return str(self.image)\n\n def save(self, **kwargs):\n super(Image, self).save(**kwargs)\n\n on_image_saved(self)\n" }, { "answer_id": 346862, "author": "muhuk", "author_id": 42188, "author_profile": "https://Stackoverflow.com/users/42188", "pm_score": 3, "selected": true, "text": "Modell Image ForeignKey Modell Image Image Modell ForeignKey Modell Modell null=True Modell.save() Image Image" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346718", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42546/" ]
346,721
<p>Would a LINQ for java be a useful tool? I have been working on a tool that will allow a Java object to map to a row in a database. </p> <ol> <li>Would this be useful for Java programmers? </li> <li>What features would be useful?</li> </ol>
[ { "answer_id": 1713619, "author": "Stephen", "author_id": 37193, "author_profile": "https://Stackoverflow.com/users/37193", "pm_score": 4, "selected": false, "text": "List(\"Paris\",\"Berlin\",\"London\",\"Tokyo\")\n .filter(c => c.endsWith(\"n\"))\n .map(c => c.length) \n// result would be length of the words that ends \n// with \"n\" letter (\"Berlin\" and \"London\").\n Array(1,2,3,4,5,6).map(x => x*x)\n import Library._\nusing(session) { \n books.insert(new Author(1, \"Michel\",\"Folco\")) \n val a = from(authors)(a=> where(a.lastName === \"Folco\") select(a)) \n}\n// but note that there is more code behind this example\n" }, { "answer_id": 2836889, "author": "ajlopez", "author_id": 61160, "author_profile": "https://Stackoverflow.com/users/61160", "pm_score": 0, "selected": false, "text": "IQueryProviders IQueryProviders" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346721", "https://Stackoverflow.com", "https://Stackoverflow.com/users/17712/" ]
346,723
<p>Say I only needed to use findall() from the re module, is it more efficient to do:</p> <pre><code>from re import findall </code></pre> <p>or </p> <pre><code>import re </code></pre> <p>Is there actually any difference in speed/memory usage etc?</p>
[ { "answer_id": 346753, "author": "Kozyarchuk", "author_id": 52490, "author_profile": "https://Stackoverflow.com/users/52490", "pm_score": 5, "selected": true, "text": "re.findall() \n" }, { "answer_id": 346967, "author": "Noah", "author_id": 28035, "author_profile": "https://Stackoverflow.com/users/28035", "pm_score": 4, "selected": false, "text": "from timeit import Timer\n\nprint Timer(\"\"\"re.findall(r\"\\d+\", \"fg12f 1414 21af 144\")\"\"\", \"import re\").timeit()\nprint Timer(\"\"\"findall(r\"\\d+\", \"fg12f 1414 21af 144\")\"\"\", \"from re import findall\").timeit()\n re.findall(): 123.444600105\nfindall(): 122.056155205\n findall() re.findall() >>> Timer(\"import re\").timeit()\n2.39156508446\n>>> Timer(\"from re import findall\").timeit()\n4.41387701035\n import re" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346723", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32933/" ]
346,730
<p>I want to change member of structure under double pointer. Do you know how?</p> <p>Example code</p> <pre><code>typedef struct { int member; } Ttype; void changeMember(Ttype **foo) { //I don`t know how to do it //maybe *foo-&gt;member = 1; } </code></pre>
[ { "answer_id": 346739, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 6, "selected": true, "text": "(*foo)->member = 1;\n" }, { "answer_id": 346740, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "(*foo)->member = 1;\n" }, { "answer_id": 346766, "author": "Zhichao", "author_id": 43443, "author_profile": "https://Stackoverflow.com/users/43443", "pm_score": 2, "selected": false, "text": "Ttype *temp = *foo;\ntemp->member = 1;\n void changeMember(Ttype *&foo) {\n foo->member = 1;\n}\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346730", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43975/" ]
346,750
<p>I'm creating a plugin to a software that skins the form I created. However, the button are not skin based on them and a standard gray button is shown. Asking on the software forum pointed me that .NET forms control are owner-draw and therefor my button won't redraw with the correct style instead of creating a non ownerdraw button.</p> <p>All controls in the system.windows.forms namespace seem to be ownerdraw.</p> <p>So how can I create a standar C++ PUSHBUTTON in .NET?</p> <p>Currently codding in C# if that helps.</p> <p>Thx</p>
[ { "answer_id": 349596, "author": "P Daddy", "author_id": 36388, "author_profile": "https://Stackoverflow.com/users/36388", "pm_score": 1, "selected": false, "text": "FlatStyle FlatStyle.System" }, { "answer_id": 350155, "author": "Pondidum", "author_id": 1500, "author_profile": "https://Stackoverflow.com/users/1500", "pm_score": 0, "selected": false, "text": "FlatStyle Flat Popup Flaststyle = Standard" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346750", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
346,757
<p>I need to implement a spell checker in C. Basically, I need all the standard operations... I need to be able to spell check a block of text, make word suggestions and dynamically add new words to the index.</p> <p>I'd kind of like to write this myself, tho I really don't know where to begin.</p>
[ { "answer_id": 346818, "author": "e.James", "author_id": 33686, "author_profile": "https://Stackoverflow.com/users/33686", "pm_score": 5, "selected": false, "text": "* A -> P -> E -> X*\n      \\\\-> P -> L -> E*\n           \\\\-> O -> I -> N -> T* -> E -> D* A -> P -> P P I E A -> P -> E" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346757", "https://Stackoverflow.com", "https://Stackoverflow.com/users/3886/" ]
346,760
<p>I want to find (not generate) 2 text strings such that, after removing all non letters and ucasing, one string can be translated to the other by simple substitution.</p> <p>The motivation for this comes from a project I known of that is testing methods for attacking cyphers via probability distributions. I'd like to find a large, coherent plain text that, once encrypted with a simple substitution cypher, can be decrypted to something else that is also coherent.</p> <p>This ends up as 2 parts, find the longest such strings in a corpus, and get that corpus.</p> <hr> <p>The first part seems to me to be amiable to some sort of attack with a B-tree keyed off the string after a substitution that makes the sequence of first occurrences sequential.</p> <pre><code>HELLOWORLDTHISISIT 1233454637819a9b98 </code></pre> <p>A little optimization based on knowing the maximum value and length of the string based on each depth of the tree and the rest is just coding.</p> <hr> <p>The Other part would be quite a bit more involved; how to generate a large corpus of text to search? some kind of internet spider would seem to be the ideal approach as it would have access to the largest amount of text but how to strip it to just the text?</p> <p>The question is; Any ideas on how to do this better?</p> <hr> <p>Edit: the cipher that was being used is an insanely basic 26 letter substitution cipher.</p> <p>p.s. this is more a thought experiment then a probable real project for me. </p>
[ { "answer_id": 348462, "author": "Darius Bacon", "author_id": 27024, "author_profile": "https://Stackoverflow.com/users/27024", "pm_score": 2, "selected": true, "text": ">>> math.log(factorial(26), 2)\n88.381953327016262\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346760", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1343/" ]
346,762
<p>In the constructor of my class, I map the current object (<em>this</em>), along with its key (a string entered as a parameter in the constructor) into a static LinkedHashMap so I can reference the object by the string anywhere I might need it later.</p> <p>Here's the code (if it helps):</p> <pre><code>public class DataEntry { /** Internal global list of DataEntry objects. */ private static LinkedHashMap _INTERNAL_LIST; /** The data entry's name. */ private String NAME; /** The value this data entry represents. */ private Object VALUE; /** Defines a DataEntry object with a name and a value. */ public DataEntry( String name, Object value ) { if( _INTERNAL_LIST == null ) { _INTERNAL_LIST = new LinkedHashMap(); } _INTERNAL_LIST.put( name, this ); NAME = name; VALUE = value; } } </code></pre> <p>The problem? Instances of this class won't get garbage collected when I'm done using them.</p> <p>I'm just curious if there's a way to have instances of this class clean themselves up when I'm done using them without having to manually call a Remove() method or something each time (to remove its reference in the internal LinkedHashMap when I'm no longer using them, I mean).</p>
[ { "answer_id": 346872, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 4, "selected": true, "text": "public static DataEntry getEntry(String name) {\n return _INTERNAL_LIST.get(name);\n}\n DataEntry VALUE DataEntry WeakReference WeakReference DataEntry ReferenceQueue remove LinkedHashMap java.util.concurrent LinkedHashMap Collections.synchronizedMap()" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346762", "https://Stackoverflow.com", "https://Stackoverflow.com/users/19825/" ]
346,770
<p>Some issues with timezones in PHP have been in the back of my mind for a while now, and I was wondering if there are better ways to handle it than what I'm currently doing.</p> <p>All of the issues revolve around reformating database stored dates:</p> <p>When dealing with a site that has to support multiple timezones (for users), to normalize the timezone offest of stored timestamps I always store it with the server timezone using the <code>CURRENT_TIMESTAMP</code> attribute or the <code>NOW()</code> function. </p> <p>This way I don't have to consider what timezone was set for PHP when the timestamp was entered (since PHP time functions are timezone aware). For each user, according to his preference I set the timezone somewhere in my bootstrap file using:</p> <pre><code>date_default_timezone_set($timezone); </code></pre> <p>When I'm looking to format dates with the php <code>date()</code> function, some form of conversion has to take place since MySQL currently stores timestamp in the format <code>Y-m-d H:i:s</code>. With no regard to timezone, you could simply run:</p> <pre><code>$date = date($format,strtotime($dbTimestamp)); </code></pre> <p>The problem with this is that <code>date()</code> and <code>strtotime()</code> are both timezone aware functions, meaning that if the PHP timezone is set differently from the server timezone, the timezone offset will apply twice (instead of once as we would like).</p> <p>To deal with this, I usually retrieve MySQL timestamps using the <code>UNIX_TIMESTAMP()</code> function which is not timezone aware, allowing my to apply <code>date()</code> directly on it - thereby applying the timezone offset only once.</p> <p>I don't really like this 'hack' as I can no longer retrieve those columns as I normally would, or use <code>*</code> to fetch all columns (sometimes it simplifies queries greatly). Also, sometimes it's simply not an option to use <code>UNIX_TIMESTAMP()</code> (especially when using with open-source packages without much abstraction for query composition).</p> <p>Another issue is when storing the timestamp, when usage of <code>CURRENT_TIMESTAMP</code> or <code>NOW()</code> is not an option - storing a PHP generated timestamp will store it with the timezone offset which I would like to avoid.</p> <p>I'm probably missing something really basic here, but so far I haven't been able to come up with a generic solution to handle those issues so I'm forced to treat them case-by-case. Your thoughts are very welcome</p>
[ { "answer_id": 346791, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "SET time_zone" }, { "answer_id": 14595648, "author": "John Conde", "author_id": 250259, "author_profile": "https://Stackoverflow.com/users/250259", "pm_score": 3, "selected": false, "text": "$datetime = new DateTime($dbTimestamp, $timezone);\necho $datetime->format('Y-m-d H:i:s');\n$datetime->setTimezone(new DateTimeZone('Pacific/Nauru'));\necho $datetime->format('Y-m-d H:i:s');\n" }, { "answer_id": 17032492, "author": "Lucian D.", "author_id": 2472348, "author_profile": "https://Stackoverflow.com/users/2472348", "pm_score": 0, "selected": false, "text": "<select name=\"timezone\" id=\"timezone\">\n <optgroup label=\"UTC -11:00\">\n <option value=\"Pacific/Midway\">UTC -11:00 Midway</option>\n <option value=\"Pacific/Niue\">UTC -11:00 Niue</option>\n <option value=\"Pacific/Pago_Pago\">UTC -11:00 Pago_Pago</option>\n </optgroup>\n <optgroup label=\"UTC -10:00\">\n <option value=\"America/Adak\">UTC -10:00 Adak</option>\n <option value=\"Pacific/Honolulu\">UTC -10:00 Honolulu</option>\n <option value=\"Pacific/Johnston\">UTC -10:00 Johnston</option>\n <option value=\"Pacific/Rarotonga\">UTC -10:00 Rarotonga</option>\n <option value=\"Pacific/Tahiti\">UTC -10:00 Tahiti</option>\n </optgroup>\n . . . . . . . . . . . . . .\n <optgroup label=\"UTC +13:00\">\n <option value=\"Pacific/Apia\">UTC +13:00 Apia</option>\n <option value=\"Pacific/Enderbury\">UTC +13:00 Enderbury</option>\n <option value=\"Pacific/Fakaofo\">UTC +13:00 Fakaofo</option>\n <option value=\"Pacific/Tongatapu\">UTC +13:00 Tongatapu</option>\n </optgroup>\n <optgroup label=\"UTC +14:00\">\n <option value=\"Pacific/Kiritimati\">UTC +14:00 Kiritimati</option>\n </optgroup>\n</select>\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346770", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10585/" ]
346,777
<p>how can I check at runtime home many parameters a method or a function have in PHP.</p> <p>example</p> <pre> class foo { function bar ( arg1, arg2 ){ ..... } } </pre> <p>I will need to know if there is a way to run something like</p> <pre> get_func_arg_number ( "foo", "bar" ) </pre> <p>and the result to be</p> <pre> 2 </pre>
[ { "answer_id": 346789, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 5, "selected": false, "text": "$method = new ReflectionMethod('foo', 'bar');\n$num = $method->getNumberOfParameters();\n" }, { "answer_id": 346943, "author": "Alan Storm", "author_id": 4668, "author_profile": "https://Stackoverflow.com/users/4668", "pm_score": 3, "selected": false, "text": "class foo {\n function bar ( $arg1, $arg2 ){\n\n }\n}\n$ReflectionFoo = new ReflectionClass('foo');\necho $ReflectionFoo->getMethod('bar')->getNumberOfParameters();\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346777", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43991/" ]
346,793
<p>The people on this website seem to know everything so I figured I would ask this just in case:</p> <p>Is there a method/function in prototype that converts a JSON object to a string that you can store in a cookie?</p> <p>If not,..i'll just use another external library.</p> <p>Thanks, Andrww</p>
[ { "answer_id": 346821, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 4, "selected": true, "text": "var data = {name: 'Violet', occupation: 'character', age: 25 };\nvar myString = Object.toJSON(data);\n// myString = '{\"name\": \"Violet\", \"occupation\": \"character\", \"age\": 25}'\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346793", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
346,811
<p>I am making a game in JAVA where I want to come up with a list of files in a certain directory in my jar so I can make sure to have a list of those classes to be used in the game.</p> <p>For example say in my jar I have a directory </p> <pre><code>mtd/entity/creep/ </code></pre> <p>I want to get a list of all the .class files in that directory <strong>using java code from another class in the jar</strong>.</p> <p>What is the best code to do so?</p>
[ { "answer_id": 346853, "author": "VonC", "author_id": 6309, "author_profile": "https://Stackoverflow.com/users/6309", "pm_score": 4, "selected": true, "text": "private static List getClassesFromJARFile(String jar, String packageName) throws Error\n{\n final List classes = new ArrayList();\n JarInputStream jarFile = null;\n try\n {\n jarFile = new JarInputStream(new FileInputStream(jar));\n JarEntry jarEntry;\n do \n { \n try\n {\n jarEntry = jarFile.getNextJarEntry();\n }\n catch(IOException ioe)\n {\n throw new CCException.Error(\"Unable to get next jar entry from jar file '\"+jar+\"'\", ioe);\n }\n if (jarEntry != null) \n {\n extractClassFromJar(jar, packageName, classes, jarEntry);\n }\n } while (jarEntry != null);\n closeJarFile(jarFile);\n }\n catch(IOException ioe)\n {\n throw new CCException.Error(\"Unable to get Jar input stream from '\"+jar+\"'\", ioe);\n }\n finally\n {\n closeJarFile(jarFile);\n }\n return classes;\n}\nprivate static void extractClassFromJar(final String jar, final String packageName, final List classes, JarEntry jarEntry) throws Error\n{\n String className = jarEntry.getName();\n if (className.endsWith(\".class\")) \n {\n className = className.substring(0, className.length() - \".class\".length());\n if (className.startsWith(packageName))\n {\n try\n {\n classes.add(Class.forName(className.replace('/', '.')));\n } catch (ClassNotFoundException cnfe)\n {\n throw new CCException.Error(\"unable to find class named \" + className.replace('/', '.') + \"' within jar '\" + jar + \"'\", cnfe);\n }\n }\n }\n}\nprivate static void closeJarFile(final JarInputStream jarFile)\n{\n if(jarFile != null) \n { \n try\n {\n jarFile.close(); \n }\n catch(IOException ioe)\n {\n mockAction();\n }\n }\n}\n" }, { "answer_id": 347028, "author": "Tom Hawtin - tackline", "author_id": 4725, "author_profile": "https://Stackoverflow.com/users/4725", "pm_score": 2, "selected": false, "text": "Class MyClass.class this.getClass() getProtectionDomain getCodeSource getLocation openConnection JarURLConnection getJarFile entries getName" }, { "answer_id": 347030, "author": "Saiyine", "author_id": 38238, "author_profile": "https://Stackoverflow.com/users/38238", "pm_score": 0, "selected": false, "text": " File jarName = null;\n try\n {\n jarName = new File (Dir.class.getProtectionDomain().getCodeSource().getLocation().toURI());\n }\n catch (Exception e)\n {\n e.printStackTrace(); \n }\n\n try \n {\n ZipFile zf=new ZipFile(jarName.getAbsoluteFile());\n Enumeration e=zf.entries();\n while (e.hasMoreElements()) \n {\n ZipEntry ze=(ZipEntry)e.nextElement();\n System.out.println(ze.getName());\n }\n zf.close();\n } catch (IOException e) \n {\n e.printStackTrace();\n }\n" }, { "answer_id": 57220669, "author": "elhoce", "author_id": 8716648, "author_profile": "https://Stackoverflow.com/users/8716648", "pm_score": 2, "selected": false, "text": "private static void listFilesFromDirectoryInsideAJar(String pathToJar,String directory,String extension) {\n try {\n JarFile jarFile = new JarFile(pathToJar);\n Enumeration<JarEntry> e = jarFile.entries();\n while (e.hasMoreElements()) {\n JarEntry candidat = e.nextElement();\n if (candidat.getName().startsWith(directory) && \n candidat.getName().endsWith(extension))\n LOG.info(candidat.getName());\n }\n } catch (IOException e) {\n LOG.error(e.getMessage(),e);\n }\n }\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346811", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43994/" ]
346,823
<p>I am trying to figure out the following problem. I am building Yet another math function grapher, The function is drawn on its predefined x,y range, that's all good.</p> <p>Now I am working on the background and the ticking of X, Y axes (if any axes are shown).</p> <p>I worked out the following. I have a fixed width of 250 p The tick gap should be between 12.5 and 50p.</p> <p>The ticks should indicate either unit or half unit range, by that i mean the following.</p> <p>x range (-5, 5): one tick = 1</p> <p>x range (-1, 1): one tick = 0.5 or 0.1 depending on the gap that each of this option would generate. </p> <p>x range (0.1, 0.3): 0.05 </p> <p>Given a Xrange How would you get the number of ticks between either full or half unit range ?</p> <p>Or maybe there are other way to approach this type of problems.</p>
[ { "answer_id": 347271, "author": "mweerden", "author_id": 4285, "author_profile": "https://Stackoverflow.com/users/4285", "pm_score": 3, "selected": true, "text": "delta = maximum - minimum\nfactor = 10**math.ceil(math.log(delta,10)) # smallest power of 10 greater than delta\nnormalised_delta = delta / factor # 0.1 <= normalised_delta < 1\nif normalised_delta/5 >= 0.1:\n step_size = 0.1\nelif normalised_delta/5 >= 0.05:\n step_size = 0.05\nelif normalised_delta/20 <= 0.01:\n step_size = 0.01\nstep_size = step_size * factor\n if normalised_delta/20 == 0.005:\n step_size = 0.005\nelif normalised_delta/20 <= 0.01:\n step_size = 0.01\nelif normalised_delta/5 >= 0.05:\n step_size = 0.05\n" }, { "answer_id": 347579, "author": "coulix", "author_id": 32032, "author_profile": "https://Stackoverflow.com/users/32032", "pm_score": 0, "selected": false, "text": "# we want largest gap\nif normalised_delta/4 >= 0.1:\n step_size = 0.1\nelif normalised_delta/4 >= 0.05:\n step_size = 0.05\nelif normalised_delta/20 <= 0.01:\n step_size = 0.01\nstep_size = step_size * factor\n\n\n## if normalised_delta/20 == 0.005:\n## step_size = 0.005\n## elif normalised_delta/20 <= 0.01:\n## step_size = 0.01\n## elif normalised_delta/4 >= 0.05:\n## step_size = 0.05\n## step_size = step_size * factor\nprint(\"step_size\", step_size)\ntotalsteps = xdelta/step_size\nprint(\"Total steps\", totalsteps)\nprint(\"Range [\", xmin, \",\", xmax, \"]\")\n\nfirstInc = next_multiple(xmin, step_size)\ncount = (250/xdelta)*(firstInc - xmin)\nprint(\"firstInc \", firstInc, 'tick at ', count)\nprint(\"start at \", firstInc - xmin, (width/totalsteps)*(firstInc - xmin))\ninc = firstInc\n\nwhile (inc <xmax):\n inc += step_size\n count += (width/totalsteps)\n print(\" inc\", inc, \"tick at \", count)\n" }, { "answer_id": 347771, "author": "coulix", "author_id": 32032, "author_profile": "https://Stackoverflow.com/users/32032", "pm_score": 0, "selected": false, "text": "normalised_delta 1.0\nstep_size 0.1\nTotal steps 10.0\nRange [ -1 , 0 ]\nfirstInc -1.0 tick at 0.0\nstart at 0.0 0.0\n inc -0.9 tick at 25.0\n inc -0.8 tick at 50.0\n inc -0.7 tick at 75.0\n inc -0.6 tick at 100.0\n inc -0.5 tick at 125.0\n inc -0.4 tick at 150.0\n inc -0.3 tick at 175.0\n inc -0.2 tick at 200.0\n inc -0.1 tick at 225.0\n inc -1.38777878078e-16 tick at 250.0\n inc 0.1 tick at 275.0\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346823", "https://Stackoverflow.com", "https://Stackoverflow.com/users/32032/" ]
346,834
<p>Does anyone have any best practices, tips &amp; tricks, or recommendations for how to create modal Alert Views with Cocoa Touch?</p> <p>I like to think there is a way to make this difficult task trivial or at least easier.</p>
[ { "answer_id": 347769, "author": "Geraud.ch", "author_id": 43954, "author_profile": "https://Stackoverflow.com/users/43954", "pm_score": 5, "selected": true, "text": "void AlertWithMessage(NSString *message)\n{\n/* open an alert with an OK button */\nUIAlertView *alert = [[UIAlertView alloc] initWithTitle:@\"Name of the Application\" \n message:message\n delegate:nil \n cancelButtonTitle:@\"OK\" \n otherButtonTitles: nil];\n[alert show];\n[alert release];\n}\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346834", "https://Stackoverflow.com", "https://Stackoverflow.com/users/23294/" ]
346,837
<p>I was curious what the differences are between the debug and release modes of the .NET compiler and came across these questions about <a href="https://stackoverflow.com/questions/90871/debug-vs-release-in-net">debug vs release in .NET</a> and <a href="https://stackoverflow.com/questions/312312/what-are-some-reasons-a-release-build-would-run-differently-than-a-debug-build">reasons that release will behave differently than debug</a>. Up to this point I really haven't paid much attention to these compiler modes. Now I will. </p> <p>My question is, assuming that I am using a testing framework (NUnit) and TDD, would I run into any issues if I simply always compiled in release mode?</p>
[ { "answer_id": 347429, "author": "Robert Rossney", "author_id": 19403, "author_profile": "https://Stackoverflow.com/users/19403", "pm_score": 1, "selected": false, "text": "ConditionalAttribute Debug" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346837", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2035722/" ]
346,842
<p>Well I have a videos website and a few of its tables are:</p> <p><strong>tags</strong></p> <pre><code>id ~ int(11), auto-increment [PRIMARY KEY] tag_name ~ varchar(255) </code></pre> <p><strong>videotags</strong></p> <pre><code>tag_id ~ int(11) [PRIMARY KEY] video_id ~ int(11) [PRIMARY KEY] </code></pre> <p><strong>videos</strong></p> <pre><code>id ~ int(11), auto-increment [PRIMARY KEY] video_name ~ varchar(255) </code></pre> <p>Now at this point the tags table has >1000 rows and the videotags table has >32000 rows. So when I run a query to display all tags from most common to least common it takes >15 seconds to execute.</p> <p>I am using PHP and my code (watered down for simplicity) is as follows:</p> <pre><code>foreach ($database-&gt;query("SELECT tag_name,COUNT(tag_id) AS 'tag_count' FROM tags LEFT OUTER JOIN videotags ON tags.id=videotags.tag_id GROUP BY tags.id ORDER BY tag_count DESC") as $tags) { echo $tags["tag_name"] . ', '; } </code></pre> <p>Now keeping in mind that this being 100% accurate isn't as important to me as it being fast. So even if the query was executed once a day and its results were used for the remainder of the day, I wouldn't care.</p> <p>I know absolutely nothing about MySQL/PHP caching so please help!</p>
[ { "answer_id": 346866, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "EXPLAIN tag_id ~ int(11) [PRIMARY KEY]\nvideo_id ~ int(11) [PRIMARY KEY]\n" }, { "answer_id": 346869, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 3, "selected": true, "text": "create index videotags_tag_id on videotags(tag_id);\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346842", "https://Stackoverflow.com", "https://Stackoverflow.com/users/428190/" ]
346,855
<p>The following loop takes about 700 seconds to run in octave and 22 seconds to run in matlab when the DJI matrix has 21000 rows. How can I increase the efficiency of this?</p> <pre> for i=1:length(DJI) DJI2(i,1)=datenum(char(DJI(i,2)),'yyyy-mm-dd'); end </pre>
[ { "answer_id": 346866, "author": "Greg", "author_id": 24181, "author_profile": "https://Stackoverflow.com/users/24181", "pm_score": 2, "selected": false, "text": "EXPLAIN tag_id ~ int(11) [PRIMARY KEY]\nvideo_id ~ int(11) [PRIMARY KEY]\n" }, { "answer_id": 346869, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 3, "selected": true, "text": "create index videotags_tag_id on videotags(tag_id);\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346855", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14744/" ]
346,858
<p>I'm trying to parse a simple string in C++. I know the string contains some text with a colon, followed immediately by a space, then a number. I'd like to extract just the number part of the string. I can't just tokenize on the space (using sstream and &lt;&lt;) because the text in front of the colon may or may not have spaces in it.</p> <p>Some example strings might be:</p> <blockquote> <p>Total disk space: 9852465</p> <p>Free disk space: 6243863</p> <p>Sectors: 4095</p> </blockquote> <p>I'd like to use the standard library, but if you have another solution you can post that too, since others with the same question might like to see different solutions.</p>
[ { "answer_id": 346867, "author": "Brian R. Bondy", "author_id": 3153, "author_profile": "https://Stackoverflow.com/users/3153", "pm_score": 5, "selected": true, "text": "std::string strInput = \"Total disk space: 9852465\";\nstd::string strNumber = \"0\";\nsize_t iIndex = strInput.rfind(\": \");\nif(iIndex != std::string::npos && strInput.length() >= 2)\n{\n strNumber = strInput.substr(iIndex + 2, strInput.length() - iIndex - 2)\n}\n" }, { "answer_id": 346875, "author": "orip", "author_id": 37020, "author_profile": "https://Stackoverflow.com/users/37020", "pm_score": 2, "selected": false, "text": "const std::string pattern(\": \");\nstd::string s(\"Sectors: 4095\");\nsize_t num_start = s.find(pattern) + pattern.size();\n" }, { "answer_id": 346878, "author": "Adam Rosenfield", "author_id": 9530, "author_profile": "https://Stackoverflow.com/users/9530", "pm_score": 3, "selected": false, "text": "int value;\nif(sscanf(mystring.c_str(), \"%*[^:]:%d\", &value) == 1)\n // parsing succeeded\nelse\n // parsing failed\n %*[^:] *" }, { "answer_id": 346879, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 2, "selected": false, "text": "std::getline string not_number;\nint number;\nif (not (getline(cin, not_number, ':') and cin >> number)) {\n cerr << \"No number found.\" << endl;\n}\n" }, { "answer_id": 346979, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 2, "selected": false, "text": "istream::ignore int number;\nstd::streamsize max = std::numeric_limits<std::streamsize>::max();\nif (!(std::cin.ignore(max, ':') >> number)) {\n std::cerr << \"No number found.\" << std::endl;\n} else {\n std::cout << \"Number found: \" << number << std::endl;\n}\n" }, { "answer_id": 347149, "author": "D.Shawley", "author_id": 41747, "author_profile": "https://Stackoverflow.com/users/41747", "pm_score": 2, "selected": false, "text": "typedef std::tr1::match_results<std::string::const_iterator> Results;\n\nstd::tr1::regex re(\":[[:space:]]+([[:digit:]]+)\", std::tr1::regex::extended);\nstd::string str(\"Sectors: 4095\");\nResults res;\n\nif (std::tr1::regex_search(str, res, re)) {\n std::cout << \"Number found: \" << res[1] << std::endl;\n} else {\n std::cerr << \"No number found.\" << std::endl;\n}\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346858", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1288/" ]
346,885
<p>I would like to keep a list of a certain class of objects in my application. But I still want the object to be garbage collected. Can you create <strong>weak references</strong> in .NET?</p> <p>For reference:</p> <ul> <li><a href="https://stackoverflow.com/questions/346762">Garbage Collecting objects which keep track of their own instances in an internal Map</a></li> <li><a href="https://stackoverflow.com/questions/258505">Create a weak reference to an object</a></li> </ul> <p>Answer From MSDN:</p> <blockquote> <p>To establish a weak reference with an object, you create a WeakReference using the instance of the object to be tracked. You then set the Target property to that object and set the object to null. For a code example, see WeakReference in the class library.</p> </blockquote>
[ { "answer_id": 346893, "author": "Konrad Rudolph", "author_id": 1968, "author_profile": "https://Stackoverflow.com/users/1968", "pm_score": 3, "selected": false, "text": "WeakReference r = new WeakReference(obj);\n System.WeakReference" }, { "answer_id": 346895, "author": "Andrew Rollings", "author_id": 40410, "author_profile": "https://Stackoverflow.com/users/40410", "pm_score": 2, "selected": false, "text": "WeakReference _weakRef = null;\n\nPerson _strongRef = null;\n Person Name Person _strongRef = p;\n\n_weakRef = new WeakReference(p1);\n _strongRef _weakRef WeakReference (p1) GC.Collect();\n p1 _weakRef if (_weakRef.IsAlive)\n WeakReference WeakReference Person p = _weakRef.Target as Person;\n p" }, { "answer_id": 356756, "author": "Binoj Antony", "author_id": 33015, "author_profile": "https://Stackoverflow.com/users/33015", "pm_score": 0, "selected": false, "text": "WeakReference ClassA objA = new ClassA();\nWeakReference wr = new WeakReference(objA);\n// do stuff \nGC.Collect();\nClassA objA2;\nif (wr.IsAlive)\n objA2 = wr.Target as ClassA; \nelse\n objA2 = new ClassA(); // create it directly if required\n WeakReference System" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346885", "https://Stackoverflow.com", "https://Stackoverflow.com/users/338/" ]
346,913
<p>I'm currently developing a little hobby project to display health information in a game on my G15 keyboard through VB.NET.</p> <p>When I use ReadProcessMemory via an API call, it keeps returning zero. The MSDN documentation referred me to use the Marshal.GetLastWin32Error() call to find out what is wrong and it returns 1400: INVALID WINDOW HANDLE.</p> <p>I am now confused about whether the first argument of the function wants a window handle or a process id. Regardless, I have tried both with FindWindow and hardcoding the process id while the application is running (getting it from task manager).</p> <p>I have tried three different games, Urban Terror, Grand Theft Auto: SA and 3D pinball for windows, getting the memory addresses from an application called Cheat Engine; they all seem to fail.</p> <p>Here is the code I'm using to do it:</p> <p>API Call:</p> <pre><code>Private Declare Function ReadProcessMemory Lib "kernel32" ( _ ByVal hProcess As Integer, _ ByVal lpBaseAddress As Integer, _ ByRef lpBuffer As Single, _ ByVal nSize As Integer, _ ByRef lpNumberOfBytesWritten As Integer _ ) As Integer </code></pre> <p>Method:</p> <pre><code>Dim address As Integer address = &amp;HA90C62&amp; Dim valueinmemory As Integer Dim proc As Process = Process.GetCurrentProcess For Each proc In Process.GetProcesses If proc.MainWindowTitle = "3D Pinball for Windows - Space Cadet" Then If ReadProcessMemory(proc.Handle.ToInt32, address, valueinmemory, 4, 0) = 0 Then MsgBox("aww") Else MsgBox(CStr(valueinmemory)) End If End If Next Dim lastError As Integer lastError = Marshal.GetLastWin32Error() MessageBox.Show(CStr(lastError)) </code></pre> <p>Could somebody please explain to me why it is not working? Thanks in advance.</p>
[ { "answer_id": 346935, "author": "arul", "author_id": 15409, "author_profile": "https://Stackoverflow.com/users/15409", "pm_score": 3, "selected": true, "text": "<DllImport(\"kernel32.dll\", SetLastError=true)> _\nPublic Shared Function ReadProcessMemory( _\nByVal hProcess As IntPtr, _\nByVal lpBaseAddress As IntPtr, _\n<Out()>ByVal lpBuffer() As Byte, _\nByVal dwSize as Integer, _\nByRef lpNumberOfBytesRead as Integer\n) As Boolean\nEnd Function\n" }, { "answer_id": 346998, "author": "RodgerB", "author_id": 20900, "author_profile": "https://Stackoverflow.com/users/20900", "pm_score": 1, "selected": false, "text": "Dim address As Integer\naddress = &HA90C62&\nDim floatvalueinmemory() As Byte\n\nDim proc As Process = Process.GetCurrentProcess\nFor Each proc In Process.GetProcesses\n If proc.MainWindowTitle = \"3D Pinball for Windows - Space Cadet\" Then\n Dim winhandle As IntPtr = OpenProcess(PROCESS_ACCESS.PROCESS_VM_READ, True, proc.Id)\n\n If ReadProcessMemory(winhandle, address, floatvalueinmemory, 4, 0) = 0 Then\n Dim lastError As Integer\n lastError = Marshal.GetLastWin32Error()\n MessageBox.Show(CStr(lastError))\n MsgBox(\"aww\")\n Else\n MsgBox(\"woo\")\n End If\n\n CloseHandle(winhandle)\n End If\nNext\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346913", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20900/" ]
346,914
<p>I'm new to ASP.NET MVC and I'm trying to get the full url to a action when working in a view. I need this to submit to a third party API as a callback. For example what I need is</p> <blockquote> <p><a href="http://myserver.com/controller/action" rel="noreferrer">http://myserver.com/controller/action</a></p> </blockquote> <p>When I use </p> <pre><code>&lt;%= Url.Action("action", "controller") %&gt; </code></pre> <p>I get </p> <blockquote> <p>/controller/action</p> </blockquote> <p>I know several ways to add the server base-path to this but I'm wondering what is the preferred way to do this in the ASP.NET MVC view?</p> <p>EDIT: Just to clarify, it's not the URL for the current view/action it's for another action in the same controller.</p>
[ { "answer_id": 346921, "author": "John Sheehan", "author_id": 1786, "author_profile": "https://Stackoverflow.com/users/1786", "pm_score": 2, "selected": false, "text": "http://<%=Request.Url.Host %><%=Url.Action(\"action\", \"controller\")%>\n" }, { "answer_id": 347566, "author": "maz", "author_id": 42278, "author_profile": "https://Stackoverflow.com/users/42278", "pm_score": 5, "selected": true, "text": "<%= Request.Url.GetLeftPart(System.UriPartial.Authority) + Url.Action(\"action\", \"controller\")%>\n" }, { "answer_id": 6783971, "author": "Marius Schulz", "author_id": 362634, "author_profile": "https://Stackoverflow.com/users/362634", "pm_score": 2, "selected": false, "text": "/// <summary>\n/// Generates a fully qualified URL to an action method by using\n/// the specified action name, controller name and route values.\n/// </summary>\n/// <param name=\"url\">The URL helper.</param>\n/// <param name=\"actionName\">The name of the action method.</param>\n/// <param name=\"controllerName\">The name of the controller.</param>\n/// <param name=\"routeValues\">The route values.</param>\n/// <returns>The absolute URL.</returns>\npublic static string AbsoluteAction(this UrlHelper url,\n string actionName, string controllerName, object routeValues = null)\n{\n string scheme = url.RequestContext.HttpContext.Request.Url.Scheme;\n\n return url.Action(actionName, controllerName, routeValues, scheme);\n}\n" }, { "answer_id": 8070130, "author": "SushiGuy", "author_id": 757931, "author_profile": "https://Stackoverflow.com/users/757931", "pm_score": 0, "selected": false, "text": "@Request.Url @*Razor tags*@\n <%=Request.Url%> <%'Classic tags%>\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346914", "https://Stackoverflow.com", "https://Stackoverflow.com/users/42278/" ]
346,926
<p>I have a website with a form that uses TinyMCE; independently, I use jQuery. When I load the form from staging server on Firefox 3 (MacOS X, Linux), TinyMCE doesn't finish loading. There is an error in Firefox console, saying that <code>t.getBody()</code> returned <code>null</code>. <code>t.getBody()</code>, as far as I understand from TinyMCE docs, is a function that returns document's body element to be inspected for some features. Problem doesn't occur when I use Safari, nor when I use Firefox with the same site running from localhost.</p> <p>Original, failing JavaScript-related code looked like this:</p> <pre><code>&lt;script type="text/javascript" src="http://static.alfa.foo.pl/json2.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://static.alfa.foo.pl/jquery.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://static.alfa.foo.pl/jquery.ui.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://static.alfa.foo.pl/tiny_mce/tiny_mce.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; tinyMCE.init({ mode:"specific_textareas", editor_selector:"mce", theme:"simple", language:"pl" }); &lt;/script&gt; &lt;script type="text/javascript" src="http://static.alfa.foo.pl/jquery.jeditable.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" src="http://static.alfa.foo.pl/jquery.tinymce.js"&gt;&lt;/script&gt; &lt;script type="text/javascript" charset="utf-8" src="http://static.alfa.foo.pl/foo.js"&gt;&lt;/script&gt; &lt;script type="text/javascript"&gt; $(document).ready(function(){ /* jQuery initialization */ }); &lt;/script&gt; </code></pre> <p>I tried changing script loading order, moving <code>tinyMCE.init()<code> call to the <code>&lt;script/&gt;</code> tag containing <code>$(document).ready()</code> call—before, after, and inside this call. No result. When <code>tinyMCE.init()<code> was called from within <code>$(document).ready()</code> handler, the browser did hang on request—looks like it was too late to call the init function.</p> <p>Then, after googling a bit about using TinyMCE together with jQuery, I changed <code>tinyMCE.init()</code> call to:</p> <pre><code>tinyMCE.init({ mode:"none", theme:"simple", language:"pl" }); </code></pre> <p>and added following jQuery call to the <code>$(document).ready()</code> handler:</p> <pre><code>$(".mce").each( function(i) { tinyMCE.execCommand("mceAddControl",true,this.id); }); </code></pre> <p>Still the same error. But, and here's where things start to look like real voodoo, when I added alert(i);</code> before the tinyMCE.execCommand()</code> call, alerts were given, and TinyMCE textareas were initialized correctly. I figured this can be a matter of delay introduced by waiting for user dismissing the alert, so I introduced a second of delay by changing the call, still within the $(document).ready()</code> handler, to following:</p> <pre>setTimeout('$(".mce").each( function(i) { tinyMCE.execCommand("mceAddControl",true,this.id); });',1000); </code></pre> <p>With the timeout, TinyMCE textareas initialize correctly, but it's duct taping around the real problem. The problem looks like an evident race condition (especially when I consider that on the same browser, but when server is on localhost, problem doesn't occur). But isn't JavaScript execution single-threaded? Could anybody please enlighten me as to what's going on here, where is the actual problem, and what can I do to have it actually fixed?</p>
[ { "answer_id": 347174, "author": "Jonathan Lonowski", "author_id": 15031, "author_profile": "https://Stackoverflow.com/users/15031", "pm_score": 3, "selected": false, "text": "tinyMCE.init(...) $(document.ready(...)); tinyMCE.init() tinyMCE setTimeout window.onload window.onload = function () {\n tinyMCE.init(...);\n\n $(document).ready(...);\n};\n <script type=\"text/javascript\">\n $(document).ready(function(){\n /* jQuery initialization */ }\n</script>\n ) ready <script type=\"text/javascript\">\n $(document).ready(function(){\n /* jQuery initialization */ })\n</script>\n" }, { "answer_id": 2297055, "author": "user146498", "author_id": 146498, "author_profile": "https://Stackoverflow.com/users/146498", "pm_score": 2, "selected": false, "text": "tinyMCE.init({\n ...\n setup : function(ed) {\n ed.onInit.add(function(ed) {\n console.log('Editor is loaded: ' + ed.id);\n });\n }\n});\n" }, { "answer_id": 6317534, "author": "Corin", "author_id": 302306, "author_profile": "https://Stackoverflow.com/users/302306", "pm_score": 1, "selected": false, "text": "jquery.tinymce.js tiny_mce.js window.tinymce tinymce undefined setTimeout jquery.js jquery.tinymce.js .tinymce(settings) textarea $('textarea').tinymce({ script_url: '/tiny_mce/tiny_mce.js' }) tiny_mce.js window.tinymce tinymce.Editor tinymce.editors .ajaxStop setTimeout" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346926", "https://Stackoverflow.com", "https://Stackoverflow.com/users/16390/" ]
346,929
<p>I am doing some calculations that require a large array to be initialized. The maximum size of the array determines the maximum size of the problem I can solve. </p> <p>Is there a way to programmatically determine how much memory is available for say, the biggest array of bytes possible?</p> <p>Thanks </p>
[ { "answer_id": 1637306, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 0, "selected": false, "text": "\nUsing pc As New System.Diagnostics.PerformanceCounter(\"Memory\", \"Available Bytes\")\n FreeBytes = pc.NextValue();\nEnd Using\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346929", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21197/" ]
346,940
<p>I have two tables on a page that I want to display side by side, and then center them within the page (actually within another div, but this is the simplest I could come up with):</p> <pre><code>&lt;style&gt; #outer { text-align: center; } #inner { text-align: left; margin: 0 auto; } .t { float: left; } table { border: 1px solid black; } #clearit { clear: left; } &lt;/style&gt; &lt;div id="outer"&gt; &lt;p&gt;Two tables, side by side, centered together within the page.&lt;/p&gt; &lt;div id="inner"&gt; &lt;div class="t"&gt; &lt;table&gt; &lt;tr&gt;&lt;th&gt;a&lt;/th&gt;&lt;th&gt;b&lt;/th&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;4&lt;/td&gt;&lt;td&gt;9&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;16&lt;/td&gt;&lt;td&gt;25&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;div class="t"&gt; &lt;table&gt; &lt;tr&gt;&lt;th&gt;a&lt;/th&gt;&lt;th&gt;b&lt;/th&gt;&lt;th&gt;c&lt;/th&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;1&lt;/td&gt;&lt;td&gt;2&lt;/td&gt;&lt;td&gt;2&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;3&lt;/td&gt;&lt;td&gt;5&lt;/td&gt;&lt;td&gt;15&lt;/td&gt;&lt;/tr&gt; &lt;tr&gt;&lt;td&gt;8&lt;/td&gt;&lt;td&gt;13&lt;/td&gt;&lt;td&gt;104&lt;/td&gt;&lt;/tr&gt; &lt;/table&gt; &lt;/div&gt; &lt;/div&gt; &lt;div id="clearit"&gt;all done.&lt;/div&gt; &lt;/div&gt; </code></pre> <p>I understand that it's something to do with the fact that the tables are floated, but I'm at a loss as to understand what I'm missing. There are many web pages that describe something like the technique I show here, but in any event it doesn't work; the tables cling stubbornly to the left hand margin.</p>
[ { "answer_id": 346956, "author": "Andrew G. Johnson", "author_id": 428190, "author_profile": "https://Stackoverflow.com/users/428190", "pm_score": 2, "selected": false, "text": "<style>\n#outer { text-align: center; }\n#inner { text-align: left; margin: 0 auto; }\n.t { float: left; }\ntable { border: 1px solid black; }\n#clearit { clear: left; }\n</style>\n <style>\n#outer { text-align: center; }\n#inner { text-align: left; margin: 0 auto; width:500px }\n.t { float: left; }\ntable { border: 1px solid black; }\n#clearit { clear: left; }\n</style>\n" }, { "answer_id": 346958, "author": "gregnostic", "author_id": 41891, "author_profile": "https://Stackoverflow.com/users/41891", "pm_score": 3, "selected": false, "text": "#inner width auto inherit margin: 0 auto; width #inner #outer" }, { "answer_id": 346977, "author": "Tim Knight", "author_id": 43043, "author_profile": "https://Stackoverflow.com/users/43043", "pm_score": 5, "selected": false, "text": "<style type=\"text/css\" media=\"screen\">\n table {\n border: 1px solid black;\n float: left;\n width: 148px;\n }\n \n #table_container {\n width: 300px;\n margin: 0 auto;\n }\n</style>\n\n<div id=\"table_container\">\n <table>\n <tr>\n <th>a</th>\n <th>b</th>\n </tr>\n <tr>\n <td>1</td>\n <td>2</td>\n </tr>\n <tr>\n <td>4</td>\n <td>9</td>\n </tr>\n <tr>\n <td>16</td>\n <td>25</td>\n </tr>\n </table>\n <table>\n <tr>\n <th>a</th>\n <th>b</th>\n </tr>\n <tr>\n <td>1</td>\n <td>2</td>\n </tr>\n <tr>\n <td>4</td>\n <td>9</td>\n </tr>\n <tr>\n <td>16</td>\n <td>25</td>\n </tr>\n </table>\n</div>" }, { "answer_id": 346990, "author": "BenMaddox", "author_id": 38698, "author_profile": "https://Stackoverflow.com/users/38698", "pm_score": 1, "selected": false, "text": "<style>\n#outer { text-align: center; }\n#inner { width:500px; text-align: left; margin: 0 auto; }\n.t { float: left; width:240px; border: 1px solid black;}\n#clearit { clear: both; }\n</style>\n" }, { "answer_id": 347506, "author": "dland", "author_id": 18625, "author_profile": "https://Stackoverflow.com/users/18625", "pm_score": 5, "selected": false, "text": "<table align=\"center\"><tr><td>\n//code for table on the left\n</td><td>\n//code for table on the right\n</td></tr></table>\n" }, { "answer_id": 1717001, "author": "Martha", "author_id": 121333, "author_profile": "https://Stackoverflow.com/users/121333", "pm_score": 4, "selected": false, "text": "#inner {text-align:center;}\n.t {display:inline-block;}\n" }, { "answer_id": 36947355, "author": "Technastar", "author_id": 6273337, "author_profile": "https://Stackoverflow.com/users/6273337", "pm_score": 1, "selected": false, "text": "<style>\n #outer {\n text-align: center;\n }\n \n #inner {\n text-align: left;\n margin: 0 auto;\n }\n \n .t {\n float: left;\n }\n \n table {\n border: 1px solid black;\n }\n \n #clearit {\n clear: left;\n }\n</style>\n\n<div id=\"outer\">\n\n <p>Two tables, side by side, centered together within the page.</p>\n\n <div id=\"inner\">\n <table style=\"margin-left: auto; margin-right: auto;\">\n <td>\n <div class=\"t\">\n <table>\n <tr>\n <th>a</th>\n <th>b</th>\n </tr>\n <tr>\n <td>1</td>\n <td>2</td>\n </tr>\n <tr>\n <td>4</td>\n <td>9</td>\n </tr>\n <tr>\n <td>16</td>\n <td>25</td>\n </tr>\n </table>\n </div>\n\n <div class=\"t\">\n <table>\n <tr>\n <th>a</th>\n <th>b</th>\n <th>c</th>\n </tr>\n <tr>\n <td>1</td>\n <td>2</td>\n <td>2</td>\n </tr>\n <tr>\n <td>3</td>\n <td>5</td>\n <td>15</td>\n </tr>\n <tr>\n <td>8</td>\n <td>13</td>\n <td>104</td>\n </tr>\n </table>\n </div>\n </td>\n </table>\n </div>\n <div id=\"clearit\">all done.</div>\n</div>" }, { "answer_id": 59173518, "author": "chindirala sampath kumar", "author_id": 4328035, "author_profile": "https://Stackoverflow.com/users/4328035", "pm_score": 0, "selected": false, "text": "<html>\n<style>\n#container {\nwidth: 50%;\nmargin: auto;\ntext-align: center;\n}\n#first {\nwidth:48%;\nfloat: left;\nheight: 200px;\nbackground-color: blue;\n}\n#second {\nwidth: 48%;\nfloat: left;\nheight: 200px;\nbackground-color: green;\n}\n#clear {\nclear: both;\n}\n#space{\nwidth: 4%;\nfloat: left;\nheight: 200px;\n}\ntable{\nborder: 1px solid black;\nmargin: 0 auto;\ntable-layout:fixed;\nwidth:100%;\ntext-align:center;\n}\n</style>\n<body>\n\n<div id = \"container\" >\n<div id=\"first\">\n <table>\n <tr>\n <th>Column1</th>\n <th>Column2</th>\n </tr>\n <tr>\n <td>Value1</td>\n <td>Value2</td>\n </tr>\n </table>\n</div>\n<div id = \"space\" >\n</div>\n<div id = \"second\" >\n<table>\n <tr>\n <th>Column1</th>\n <th>Column2</th>\n </tr>\n <tr>\n <td>Value1</td>\n <td>Value2</td>\n </tr>\n</table>\n</div>\n<div id = \"clear\" ></div>\n</div>\n\n</body>\n</html> <html>\n<style>\n#container {\nmargin:0 auto;\ntext-align: center;\n}\n#first {\nfloat: left;\n}\n#second {\nfloat: left;\n}\n#clear {\nclear: both;\n}\n#space{\nwidth:20px;\nheight:20px;\nfloat: left;\n}\n.table, .table th, .table td{\nborder: 1px solid black;\n}\n</style>\n<body>\n\n<table id = \"container\" >\n<td>\n<div id=\"first\">\n <table class=\"table\">\n <tr>\n <th>Column1</th>\n <th>Column2</th>\n </tr>\n <tr>\n <td>Value1</td>\n <td>Value2</td>\n </tr>\n </table>\n</div>\n<div id = \"space\" >\n</div>\n<div id = \"second\" >\n<table class=\"table\">\n <tr>\n <th>Column1</th>\n <th>Column2</th>\n </tr>\n <tr>\n <td>Value1</td>\n <td>Value2</td>\n </tr>\n</table>\n</div>\n<div id = \"clear\" ></div>\n</div>\n</td>\n</table>\n</body>\n</html>" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346940", "https://Stackoverflow.com", "https://Stackoverflow.com/users/18625/" ]
346,954
<p>I saw a link to find out if AD was running, but am not too sure if the same applies to AD/AM. One caveat is that I should be able to check about any AD/AM instance (any domain) assuming I have permissions.</p>
[ { "answer_id": 513873, "author": "Dscoduc", "author_id": 51949, "author_profile": "https://Stackoverflow.com/users/51949", "pm_score": 1, "selected": true, "text": "LDAP://ADAMServer:50000/DC=domain,DC=local\n HKLM\\SYSTEM\\CurrentControlSet\\Services\\ADAM_InstanceName\\Parameters\n c:\\windows\\adam\\dsdbutil.exe \"list instances\"\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346954", "https://Stackoverflow.com", "https://Stackoverflow.com/users/43999/" ]
346,957
<p>I want to write Html format, but I can not even get a simple MSDN example of it to work.</p> <p><a href="http://msdn.microsoft.com/en-us/library/tbfb3z56.aspx" rel="nofollow noreferrer">http://msdn.microsoft.com/en-us/library/tbfb3z56.aspx</a></p> <p>Does this console app, a clipboard round tripper, work for anyone?</p> <pre> using System; using System.Windows; //Need to add a PresentationCore or System.Windows.Forms reference class Program { [STAThread] static void Main( string[] args ) { Console.WriteLine( "Copy a small amount of text from a browser, then press enter." ); Console.ReadLine(); var text = Clipboard.GetText(); Console.WriteLine(); Console.WriteLine( "--->The clipboard as Text:" ); Console.WriteLine( text ); Console.WriteLine(); Console.WriteLine( "--->Rewriting clipboard with the same CF_HTML data." ); //***Here is the problem code*** var html = Clipboard.GetText( TextDataFormat.Html ); Clipboard.Clear(); Clipboard.SetText( html, TextDataFormat.Html ); var text2 = Clipboard.GetText(); Console.WriteLine(); Console.WriteLine( "--->The clipboard as Text:" ); Console.WriteLine( text2 ); var isSameText = ( text == text2 ); Console.WriteLine(); Console.WriteLine( isSameText ? "Success" : "Failure" ); Console.WriteLine(); Console.WriteLine( "Press enter to exit." ); Console.ReadLine(); } } </pre>
[ { "answer_id": 346969, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 0, "selected": false, "text": "var text2 = Clipboard.GetText(); \"\"" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346957", "https://Stackoverflow.com", "https://Stackoverflow.com/users/14841/" ]
346,960
<p>i am trying to use an ASP conditional here:</p> <pre><code>if (Request.Cookies("username")) and (Request.Cookies("password")) &lt;&gt; "" Then </code></pre> <p>And i keep getting this error:</p> <blockquote> <p>Type mismatch: '[string: ""]'</p> </blockquote> <p>Any ideas what I am getting that?</p>
[ { "answer_id": 346965, "author": "hmcclungiii", "author_id": 24333, "author_profile": "https://Stackoverflow.com/users/24333", "pm_score": 3, "selected": true, "text": "if (Request.Cookies(\"username\") <> \"\") and (Request.Cookies(\"password\") <> \"\") Then\n" }, { "answer_id": 346982, "author": "Pure.Krome", "author_id": 30674, "author_profile": "https://Stackoverflow.com/users/30674", "pm_score": -1, "selected": false, "text": "if (!string.IsNullOrEmpty(Request.Cookies(\"username\")) &&\n !string.IsNullOrEmpty(Request.Cookies(\"password\")))\n{\n // Do your stuff, here :)\n}\n string.IsNullOrEmpty string.Empty null" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346960", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
346,973
<p>Is there a simple way to tell what triggered Click event of a Button apart from setting multiple flags in Mouse/Key Up/Down event handlers? I'm currently only interested in distinguishing mouse from everything else, but it would be nice to handle Stylus and other input types if possible. Do I have to create my own button control to achieve this?</p> <p>Edit: To clarify why I care: in this particular case I'm trying to implement "next" and "previous" buttons for a sort of picture viewer. Pictures in question may be of different size and buttons' positions will change (so they are always centered below picture). It's quite annoying to follow such buttons with mouse if you need to scroll through several pictures, so I want to keep mouse position constant relative to clicked button, but only if it was clicked by mouse, not keyboard.</p> <p>Edit2: It does not matter whether the buttons are on top or down at the bottom, since the center can change anyway. "Picture viewer" here is just an abstraction and in this particular case it's important for me that top left corner of the picture retains it's position, but it's out of the scope of the question to go in details. Scaling the picture is not so trivial in this sort of application as well, so I do want to know the answer to the question I asked not going into UI implementation discussion.</p>
[ { "answer_id": 353140, "author": "Nir", "author_id": 3509, "author_profile": "https://Stackoverflow.com/users/3509", "pm_score": 4, "selected": true, "text": "if (InputManager.Current.MostRecentInputDevice is KeyboardDevice)\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/346973", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10757/" ]
347,010
<p>I currently am trying to write a Python program using scheme semantics so I can later translate it into Scheme without relying on a lot of Pythonic stuff.</p> <p>I'm trying solve the sliding puzzle problem (where you have 9 slots and 8 tiles arranged in a square) using a*, depth first, and breadth first search algorithm. I did this ~11 years ago in some AI class in Lisp, but basically at the time I had no idea about lisp, I hated it with all my heart, and only in retrospect do I realize I was programming "C" in Lisp. The prof didn't help in this matter.</p> <p>I have a python function which can swap two tiles easily: </p> <pre><code>def swap(p, (r1, c1), (r2, c2)): # Swaps *any* two locations and returns new configuration # Does not concern itself with zero location, etc # Not sure how to do this functionally p_p = p[:] temp = p_p[r1][c1] p_p[r1][c1] = p_p[r2][c2] p_p[r2][c2] = temp return p_p </code></pre> <p>I'd like to turn this into something you might find in SICP, avoiding side effects, etc. </p> <p>But this brings up a question. Everything I read in SICP is loops via recursion. I didn't see anything in accessing arrays/vectors/lists in constant time. I can imagine a loopish/recursive way to read an element, but I find it harder to imagine a way to create a new list with a certain element changed, without invoking side-effect producing things like set!, and without resorting to crazy if/then/else clauses concerning which element should be changed. This of course gets more confusing when considering a 2d array. In this case the solution with python is obvious because of its native support for multidimensional arrays.</p> <p>In C/C++/Python/Matlab/Lua/anything else, accessing lists/arrays via the [i] syntax is easy, and directly translates to a hardware-oriented pointer lookup somewhere underneath. I don't understand how scheme does this, given the atomic operations defined in the SICP version of scheme, which all seem very loop-and-search oriented. How do the vector and list array access functions work to get constant time access? (I'm a total newbie here, so I'm not ever sure what functions I'd be talking about). Is there a C or Assembly library someplace which is secretly being accessed? Are there any inherent constant-time semantics in scheme which could be used for list/array/vector access, and which would allow me a guilt-free way of using that idiom in Python for the moment? </p> <p>How would can I rewrite the above function in python using Schemish semantics? How would I rewrite the above function in Scheme?</p>
[ { "answer_id": 347059, "author": "Kyle Cronin", "author_id": 658, "author_profile": "https://Stackoverflow.com/users/658", "pm_score": 2, "selected": false, "text": "; getval\n;\n; This function takes a position (r . c) where and returns the corresponding\n; number in the 8-puzzle state. For example, if you wanted (1 . 2) from\n; ((1 2 3) (4 5 6) (7 8 9)), the value would be 6. The r and c values begin\n; at 0.\n;\n; parameters: pos The position to get\n; state The 8-puzzle state\n; returns: The value at pos in state\n(defun getval (pos state)\n (if (null state) 'no-value\n (if (= 0 (car pos))\n (if (= 0 (cdr pos))\n (caar state)\n (getval (cons (car pos) (- (cdr pos) 1)) (list (cdar state))))\n (getval (cons (- (car pos) 1) (cdr pos)) (cdr state)))))\n\n; setval\n;\n; This function returns a state where the value at pos is replaced by val.\n; Like getval, this function is zero-based. Accessing beyond the size of\n; the state is undefined (and probably broken)\n;\n; parameters: pos Position to set\n; val Value to set\n; state State to modify\n; returns: New state where pos is val\n(defun setval (pos val state)\n (if (null state) '()\n (if (= 0 (car pos))\n (if (= 0 (cdr pos))\n (cons (cons val (cdar state)) (cdr state))\n (let ((temp (setval (cons (car pos) (- (cdr pos) 1)) val\n (cons (cdar state) (cdr state)))))\n (cons (cons (caar state) (car temp)) (cdr temp))))\n (cons (car state) (setval (cons (- (car pos) 1) (cdr pos)) val (cdr state))))))\n\n; state-swap\n;\n; This function takes a state and two positions and returns a new state with\n; the values in those two positions swapped.\n;\n; parameters: state State to swap within\n; a Position to swap with b\n; b Position to swap with a\n; return: State with a swapped with b\n(defun state-swap (state a b)\n (let ((olda (getval a state)) (oldb (getval b state)))\n (setval a oldb (setval b olda state))))\n" }, { "answer_id": 348367, "author": "Brian", "author_id": 9493, "author_profile": "https://Stackoverflow.com/users/9493", "pm_score": 1, "selected": false, "text": "def swap(p, (r1,c1), (r2,c2)):\n def getitem(r,c):\n if (r,c) == (r1,c1): return p[r2][c2]\n elif (r,c) == (r2,c2): return p[r1][c1]\n return p[r][c]\n return [ [getitem(r,c) for c in range(len(p[0]))] for r in range(len(p)) ]\n def swap(f, (r1,c1), (r2,c2)):\n def getitem(r,c):\n if (r,c) == (r1,c1): return f(r2,c2)\n elif (r,c) == (r2,c2): return f(r1,c1)\n return f(r,c)\n return getitem\n\nl=[ [1,2,3], [4,5,6], [7,8,0]]\nf=lambda r,c: l[r][c] # Initial accessor function\nf=swap(f, (2,1), (2,2)) # 8 right\nf=swap(f, (1,1), (2,1)) # 5 down\nprint [[f(x,y) for y in range(3)] for x in range(3)]\n# Gives: [[1, 2, 3], [4, 0, 6], [7, 5, 8]]\n" } ]
2008/12/06
[ "https://Stackoverflow.com/questions/347010", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
347,056
<p>While there appears to some documentation on how to expose JMX through various firewall and tunneling schemes, I sort of want the opposite. I want to ensure that JMX is only accessible to local machine. Unfortunately it appears that the "out of the box" management options do not allow restricting the ports to a local interface and netstat shows them listening on any/all interfaces.</p> <p><a href="http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html#gdevf" rel="noreferrer">http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html#gdevf</a></p> <p>I have to admit I am bewildered by the layers of indirection in JMX, the RMI registry, connectors, adapters, etc.</p> <p>I would like to just turn it on and then tunnel through SSH as opposed to exposing it to the world and then having to perform arduous and superfluous user management and security configuration. It would be nice to be able to use a built in RMI registry and not have to run an external one.</p>
[ { "answer_id": 660426, "author": "Fredrik", "author_id": 59572, "author_profile": "https://Stackoverflow.com/users/59572", "pm_score": 2, "selected": false, "text": "import java.io.IOException;\nimport java.lang.management.ManagementFactory;\nimport java.net.*;\nimport java.rmi.registry.LocateRegistry;\nimport java.rmi.server.RMISocketFactory;\n\nimport javax.management.MBeanServer;\nimport javax.management.remote.*;\n\npublic class LocalJMXPort {\n public static void main(String[] args) {\n try {\n int port = 12468;\n // Create an instance of our own socket factory (see below)\n RMISocketFactory factory = new LocalHostSocketFactory();\n\n // Set it as default\n RMISocketFactory.setSocketFactory(factory);\n\n // Create our registry\n LocateRegistry.createRegistry(port);\n\n // Get the MBeanServer and setup a JMXConnectorServer\n MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();\n JMXServiceURL url = new JMXServiceURL(\"service:jmx:rmi://127.0.0.1:\"+port+\"/jndi/rmi://127.0.0.1:\"+port+\"/jmxrmi\");\n JMXConnectorServer rmiServer = JMXConnectorServerFactory.newJMXConnectorServer(url, null, mbs);\n rmiServer.start();\n\n // Say something\n System.out.println(\"Connect your jconsole to localhost:\"+port+\". Press a key to exit\");\n\n // Wait for a key press\n int in = System.in.read();\n //Exit\n System.out.println(\"Exiting\");\n System.exit(0);\n } catch(Exception ex) {\n ex.printStackTrace();\n }\n }\n\n static private class LocalHostSocketFactory extends RMISocketFactory {\n public ServerSocket createServerSocket(int port) throws IOException {\n ServerSocket ret = new ServerSocket();\n ret.bind(new InetSocketAddress(\"localhost\", port));\n return ret;\n }\n\n public Socket createSocket(String host, int port) throws IOException {\n return new Socket(host, port);\n }\n }\n}\n" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347056", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
347,078
<p>I am just learning about Unit Testing. I am using NUnit to build tests for a VB.NET project.</p> <p>The project I'm working on is part of a framework which will be used by people who build ASP.NET websites. It includes a base class (which inherits <code>System.Web.HttpApplication</code>) that users of my framework will inherit their application class from.</p> <p>The project also contains a number of composite controls.</p> <p>I can't quite work out at the moment how you would go about writing tests for either the application base class or any of the composite controls.</p> <p>In the case of the application base class, should the Unit Test project include a class which inherits from it and then test against that?</p> <p>Any pointers would be appreciated!</p> <p>Thanks.</p>
[ { "answer_id": 347104, "author": "Eugene Yokota", "author_id": 3827, "author_profile": "https://Stackoverflow.com/users/3827", "pm_score": 0, "selected": false, "text": "[Test] \npublic void TestExample() \n{ \n // First, instantiate \"Tester\" objects: \n LabelTester label = new LabelTester(\"textLabel\"); \n LinkButtonTester link = new LinkButtonTester(\"linkButton\"); \n\n // Second, visit the page being tested: \n Browser.GetPage(\"http://localhost/example/example.aspx\"); \n\n // Third, use tester objects to test the page: \n Assert.AreEqual(\"Not clicked.\", label.Text); \n link.Click(); \n Assert.AreEqual(\"Clicked once.\", label.Text); \n link.Click(); \n Assert.AreEqual(\"Clicked twice.\", label.Text); \n}\n" }, { "answer_id": 49176602, "author": "Vin Shahrdar", "author_id": 5908918, "author_profile": "https://Stackoverflow.com/users/5908918", "pm_score": 0, "selected": false, "text": "[Test]\npublic void ConditionQueryBuilderTest_RendersProperHtml()\n{\n var sw = new StringWriter();\n var queryBuilder = new ConditionQueryBuilderStub\n {\n ID = \"UnitTestbuilder\",\n QueryBuilderURL = @\"\\SomeAspxPage\\SomeWebMethod\",\n ResetQueryBuilderURL = @\"\\SomeAspxPage\\OnQueryBuilderReset\",\n FilterValuesCollection = new Dictionary<int, string> { {15, \"Some Condition\"}}\n };\n queryBuilder.RenderAllContents(new HtmlTextWriter(sw)); // This is a method in my stub that exposes RenderContents()\n\n AppendLog(sw.ToString());\n\n Assert.AreEqual(ExpectedHtml, sw.ToString());\n}\n" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347078", "https://Stackoverflow.com", "https://Stackoverflow.com/users/475/" ]
347,085
<p>I have a desktop app that needs to send data to a MySQL Server. The app will be for internal company use, but the MySQL is on a server at a hosting company.</p> <p>The data will need to be massaged a bit before being inserted and standard simple insert, delete and update.</p> <p>Which should I use PHP or Perl?</p> <p>I use PHP now for a variety of database driven web pages, but my current task has no need to any web rendering. (I know PHP could do this without an web-rendering too)</p> <p>I have used Perl in the past (maybe 4 years ago) for a data mining task and Oracle.</p> <p>What I don't know: - Can Perl work with MySQL easily? - The Perl scripts would go in cgi-bin on the webserver, correct? - Security issues with either? - Best practice in Perl for connecting to MySQL to insert data? - Where can I store the Insert, Update, Delete MySQL user name and password so it is not stolen, etc?</p> <p>What would you all choose?</p> <p>Thoughts are appreciated</p> <p>-Jason</p>
[ { "answer_id": 22475574, "author": "vogomatix", "author_id": 1421665, "author_profile": "https://Stackoverflow.com/users/1421665", "pm_score": 0, "selected": false, "text": "mysql_ PDO mysqli_" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347085", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
347,088
<p>In a PHP project I'm developing I have a couple of requests that can be either POST or GET. Currently, I'm using the $_SERVER[REQUEST_METHOD] value to determine, which request array to use. I know that $_REQUEST values can be manipulated with cookies, is the $_SERVER superglobal vulnerable to attacks? </p>
[ { "answer_id": 347130, "author": "thenickdude", "author_id": 14431, "author_profile": "https://Stackoverflow.com/users/14431", "pm_score": 0, "selected": false, "text": "post' priority over" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347088", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
347,092
<p>I am trying to have a tooltip on multiple lines. how do i do this?</p>
[ { "answer_id": 347112, "author": "JaredPar", "author_id": 23283, "author_profile": "https://Stackoverflow.com/users/23283", "pm_score": 6, "selected": true, "text": "Environment.NewLine" }, { "answer_id": 65444419, "author": "flodis", "author_id": 4299943, "author_profile": "https://Stackoverflow.com/users/4299943", "pm_score": 0, "selected": false, "text": "tipText = String.Format(\"{0:HH:mm}{3}{1:0.00}{3}{2}\", ADateTime, ADouble, AString, Environment.NewLine);\n" }, { "answer_id": 66100953, "author": "Akhrib Farouk", "author_id": 9333944, "author_profile": "https://Stackoverflow.com/users/9333944", "pm_score": 0, "selected": false, "text": " private void tooltip1_Draw(object sender, DrawToolTipEventArgs e)\n {\n e.DrawBackground();\n e.DrawBorder();\n e.DrawText(TextFormatFlags.TextBoxControl);\n }\n private void textBox22_MouseHover(object sender, EventArgs e)\n {\n tooltip1.ForeColor = Color.lime;\n tooltip1.BackColor = Color.black;\n tooltip1.Show(\"Path to a file\\nExample:\\n--check \\\"C:\\\\SomeDirectory\\\\Somefile.exe\\\"\\nNB:\\nWe don't check for the validity\", this.textBox22);\n }\n" }, { "answer_id": 68152274, "author": "Kristian Sik", "author_id": 11016690, "author_profile": "https://Stackoverflow.com/users/11016690", "pm_score": 1, "selected": false, "text": "&#xD;&#xA;" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347092", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
347,093
<p>I have been programming in Perl, off and on, for years now, although only sporadically is it my primary language. Because I often go months without writing any perl, I rely heavily on my dog-eared Camel Book to remind me how to do things. However, when I copy recipes verbatim with no understanding, this bothers me. This is one of the most vexing: On page 154 of the 3rd edition Camel, there is an example for "modifying strings <em>en passant</em>, which reads like this:</p> <pre><code>($lotr = $hobbit) =~ s/Bilbo/Frodo/g; </code></pre> <p>Q1) what is going on here? On what, exactly, is the regex operating?</p> <p>Q2) Is this near-magical syntax necessary for such a basic operation as "take a string from $a, modify it with a regex, place result in $b"?</p> <p>Q3) How do I do this operation using the loop default variable as the initial string?</p> <p>Apologies in advance to Perl dreamers for whom the above looks perfectly natural.</p>
[ { "answer_id": 347117, "author": "D.Shawley", "author_id": 41747, "author_profile": "https://Stackoverflow.com/users/41747", "pm_score": 6, "selected": true, "text": "($lotr=$hobbit) =~ s/Bilbo/Frodo/g $lotr $hobbit ($lotr = $hobbit) $lotr = $hobbit;\n$lotr =~ s/Bilbo/Frodo/g;\n $lotr $a $b $b $a $b $_ $hobbit while (<>) {\n chomp;\n ($lotr = $_) =~ s/Bilbo/Frodo/g;\n print \"\\$lotr = [$lotr]\\n\";\n print \"\\$_ = [$_]\\n\";\n}\n $_" }, { "answer_id": 347138, "author": "ysth", "author_id": 17389, "author_profile": "https://Stackoverflow.com/users/17389", "pm_score": 3, "selected": false, "text": " a = b = c; # assign value of c to b and a\n ++(b = a); # assign value of a to b, then increment b\n" }, { "answer_id": 347165, "author": "Hudson", "author_id": 14105, "author_profile": "https://Stackoverflow.com/users/14105", "pm_score": 1, "selected": false, "text": "($b) = $a =~ /(substring-to-match)/;\n$b =~ s/regex-on-susbtring/result-string/;\n" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347093", "https://Stackoverflow.com", "https://Stackoverflow.com/users/41194/" ]
347,096
<p>Consider the following code:</p> <pre><code>template &lt;int dim&gt; struct vec { vec normalize(); }; template &lt;&gt; struct vec&lt;3&gt; { vec cross_product(const vec&amp; second); vec normalize(); }; template &lt;int dim&gt; vec&lt;dim&gt; vec&lt;dim&gt;::normalize() { // code to normalize vector here return *this; } int main() { vec&lt;3&gt; direction; direction.normalize(); } </code></pre> <p>Compiling this code produces the following error:</p> <blockquote> <p>1>main.obj : error LNK2019: unresolved external symbol "public: struct vec&lt;3> __thiscall vec&lt;3>::normalize(void)" (?normalize@?$vec@$02@@QAE?AU1@XZ) referenced in function _main</p> </blockquote>
[ { "answer_id": 347103, "author": "Frank Krueger", "author_id": 338, "author_profile": "https://Stackoverflow.com/users/338", "pm_score": 1, "selected": false, "text": "template <int dim>\nstruct vec\n{\n};\n\nnamespace impl {\n template <int dim>\n vec<dim> normalize(const vec<dim>& v)\n {\n // code to normalize vector here\n return v;\n }\n}\n\ntemplate <>\nstruct vec<3>\n{\n vec cross_product(const vec& second);\n vec normalize() { return impl::normalize(*this); }\n};\n\n\nint main()\n{\n vec<3> direction;\n direction.normalize();\n}\n" }, { "answer_id": 347107, "author": "Johannes Schaub - litb", "author_id": 34509, "author_profile": "https://Stackoverflow.com/users/34509", "pm_score": 4, "selected": true, "text": "template <int dim>\nstruct vec\n{\n // leave the function undefined for everything except dim==3\n vec cross_product(const vec& second);\n vec normalize();\n};\n\ntemplate<>\nvec<3> vec<3>::cross_product(const vec& second) {\n // ...\n}\n\ntemplate <int dim>\nvec<dim> vec<dim>::normalize()\n{\n // code to normalize vector here\n return *this;\n}\n boost::enable_if template <int dim>\nstruct vec\n{\n // function can't be called for dim != 3. Error at compile-time\n template<int dim1>\n typename boost::enable_if_c< dim == dim1 && dim1 == 3, vec<dim1> >::type \n cross_product(const vec<dim1>& second) {\n // ...\n }\n vec normalize();\n\n // delegate to the template version\n void without_params() {\n // delegate\n this->without_params<dim>();\n }\n\nprivate:\n // function can't be called for dim != 3. Error at compile-time\n template<int dim1>\n typename boost::enable_if_c< dim == dim1 && dim1 == 3 >::type \n without_params() {\n // ...\n } \n};\n\ntemplate <int dim>\nvec<dim> vec<dim>::normalize()\n{\n // code to normalize vector here\n return *this;\n}\n without_parameters" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347096", "https://Stackoverflow.com", "https://Stackoverflow.com/users/2222/" ]
347,109
<p>I'm implementing unit tests for a family of functions that all share a number of invariants. For example, calling the function with two matrices produce a matrix of known shape.</p> <p>I would like to write unit tests to test the entire family of functions for this property, without having to write an individual test case for each function (particularly since more functions might be added later). </p> <p>One way to do this would be to iterate over a list of these functions:</p> <pre><code>import unittest import numpy from somewhere import the_functions from somewhere.else import TheClass class Test_the_functions(unittest.TestCase): def setUp(self): self.matrix1 = numpy.ones((5,10)) self.matrix2 = numpy.identity(5) def testOutputShape(unittest.TestCase): """Output of functions be of a certain shape""" for function in all_functions: output = function(self.matrix1, self.matrix2) fail_message = "%s produces output of the wrong shape" % str(function) self.assertEqual(self.matrix1.shape, output.shape, fail_message) if __name__ == "__main__": unittest.main() </code></pre> <p>I got the idea for this from <a href="http://www.diveintopython.net/unit_testing/romantest.html" rel="noreferrer">Dive Into Python</a>. There, it's not a list of functions being tested but a list of known input-output pairs. The problem with this approach is that if any element of the list fails the test, the later elements don't get tested.</p> <p>I looked at subclassing unittest.TestCase and somehow providing the specific function to test as an argument, but as far as I can tell that prevents us from using unittest.main() because there would be no way to pass the argument to the testcase.</p> <p>I also looked at dynamically attaching "testSomething" functions to the testcase, by using setattr with a lamdba, but the testcase did not recognize them.</p> <p>How can I rewrite this so it remains trivial to expand the list of tests, while still ensuring every test is run?</p>
[ { "answer_id": 347175, "author": "Dustin", "author_id": 39975, "author_profile": "https://Stackoverflow.com/users/39975", "pm_score": 4, "selected": true, "text": "import unittest\n\nclass UnderTest(object):\n\n def f1(self, i):\n return i + 1\n\n def f2(self, i):\n return i + 2\n\nclass TestMeta(type):\n\n def __new__(cls, name, bases, attrs):\n funcs = [t for t in dir(UnderTest) if t[0] == 'f']\n\n def doTest(t):\n def f(slf):\n ut=UnderTest()\n getattr(ut, t)(3)\n return f\n\n for f in funcs:\n attrs['test_gen_' + f] = doTest(f)\n return type.__new__(cls, name, bases, attrs)\n\nclass T(unittest.TestCase):\n\n __metaclass__ = TestMeta\n\n def testOne(self):\n self.assertTrue(True)\n\nif __name__ == '__main__':\n unittest.main()\n" }, { "answer_id": 347499, "author": "muhuk", "author_id": 42188, "author_profile": "https://Stackoverflow.com/users/42188", "pm_score": 0, "selected": false, "text": "TestSuite import unittest\nimport numpy\nimport funcs\n\n# get references to functions\n# only the functions and if their names start with \"matrixOp\"\nfunctions_to_test = [v for k,v in funcs.__dict__ if v.func_name.startswith('matrixOp')]\n\n# suplly an optional setup function\ndef setUp(self):\n self.matrix1 = numpy.ones((5,10))\n self.matrix2 = numpy.identity(5)\n\n# create tests from functions directly and store those TestCases in a TestSuite\ntest_suite = unittest.TestSuite([unittest.FunctionTestCase(f, setUp=setUp) for f in functions_to_test])\n\n\nif __name__ == \"__main__\":\nunittest.main()\n" }, { "answer_id": 347607, "author": "S.Lott", "author_id": 10661, "author_profile": "https://Stackoverflow.com/users/10661", "pm_score": 4, "selected": false, "text": "class MyTestF1( unittest.TestCase ):\n theFunction= staticmethod( f1 )\n def setUp(self):\n self.matrix1 = numpy.ones((5,10))\n self.matrix2 = numpy.identity(5)\n def testOutputShape( self ):\n \"\"\"Output of functions be of a certain shape\"\"\"\n output = self.theFunction(self.matrix1, self.matrix2)\n fail_message = \"%s produces output of the wrong shape\" % (self.theFunction.__name__,)\n self.assertEqual(self.matrix1.shape, output.shape, fail_message)\n\nclass TestF2( MyTestF1 ):\n \"\"\"Includes ALL of TestF1 tests, plus a new test.\"\"\"\n theFunction= staticmethod( f2 )\n def testUniqueFeature( self ):\n # blah blah blah\n pass\n\nclass TestF3( MyTestF1 ):\n \"\"\"Includes ALL of TestF1 tests with no additional code.\"\"\"\n theFunction= staticmethod( f3 )\n MyTestF1 unittest.main()" }, { "answer_id": 373625, "author": "Aaron Maenpaa", "author_id": 2603, "author_profile": "https://Stackoverflow.com/users/2603", "pm_score": 3, "selected": false, "text": "from binary_search import search1 as search\n\ndef test_binary_search():\n data = (\n (-1, 3, []),\n (-1, 3, [1]),\n (0, 1, [1]),\n (0, 1, [1, 3, 5]),\n (1, 3, [1, 3, 5]),\n (2, 5, [1, 3, 5]),\n (-1, 0, [1, 3, 5]),\n (-1, 2, [1, 3, 5]),\n (-1, 4, [1, 3, 5]),\n (-1, 6, [1, 3, 5]),\n (0, 1, [1, 3, 5, 7]),\n (1, 3, [1, 3, 5, 7]),\n (2, 5, [1, 3, 5, 7]),\n (3, 7, [1, 3, 5, 7]),\n (-1, 0, [1, 3, 5, 7]),\n (-1, 2, [1, 3, 5, 7]),\n (-1, 4, [1, 3, 5, 7]),\n (-1, 6, [1, 3, 5, 7]),\n (-1, 8, [1, 3, 5, 7]),\n )\n\n for result, n, ns in data:\n yield check_binary_search, result, n, ns\n\ndef check_binary_search(expected, n, ns):\n actual = search(n, ns)\n assert expected == actual\n $ nosetests -d\n...................\n----------------------------------------------------------------------\nRan 19 tests in 0.009s\n\nOK\n" }, { "answer_id": 1320299, "author": "Community", "author_id": -1, "author_profile": "https://Stackoverflow.com/users/-1", "pm_score": 1, "selected": false, "text": "__name__ # Test class that uses a metaclass\nclass TCType(type):\n def __new__(cls, name, bases, dct):\n def generate_test_method():\n def test_method(self):\n pass\n return test_method\n\n dct['test_method'] = generate_test_method()\n return type.__new__(cls, name, bases, dct)\n\nclass TestMetaclassed(object):\n __metaclass__ = TCType\n\n def test_one(self):\n pass\n def test_two(self):\n pass\n" }, { "answer_id": 1974927, "author": "Piotr Czapla", "author_id": 80869, "author_profile": "https://Stackoverflow.com/users/80869", "pm_score": 3, "selected": false, "text": "import unittest\n\nclass TestCase1(unittest.TestCase):\n def check_something(self, param1):\n self.assertTrue(param1)\n\ndef _add_test(name, param1):\n def test_method(self):\n self.check_something(param1)\n setattr(TestCase1, 'test_' + name, test_method)\n test_method.__name__ = 'test_' + name\n \nfor i in range(0, 3):\n _add_test(str(i), False)\n" }, { "answer_id": 5026270, "author": "automaciej", "author_id": 121850, "author_profile": "https://Stackoverflow.com/users/121850", "pm_score": 0, "selected": false, "text": "import unittest\n\nTEST_DATA = (\n (0, 1),\n (1, 2),\n (2, 3),\n (3, 5), # This intentionally written to fail\n)\n\n\nclass Foo(object):\n\n def f(self, n):\n return n + 1\n\n\nclass FooTestBase(object):\n \"\"\"Base class, defines a function which performs assertions.\n\n It defines a value-driven check, which is written as a typical function, and\n can be tested.\n \"\"\"\n\n def setUp(self):\n self.obj = Foo()\n\n def value_driven_test(self, number, expected):\n self.assertEquals(expected, self.obj.f(number))\n\n\nclass FooTestBaseTest(unittest.TestCase):\n \"\"\"FooTestBase has a potentially complicated, data-driven function.\n\n It needs to be tested.\n \"\"\"\n class FooTestExample(FooTestBase, unittest.TestCase):\n def runTest(self):\n return self.value_driven_test\n\n def test_value_driven_test_pass(self):\n test_base = self.FooTestExample()\n test_base.setUp()\n test_base.value_driven_test(1, 2)\n\n def test_value_driven_test_fail(self):\n test_base = self.FooTestExample()\n test_base.setUp()\n self.assertRaises(\n AssertionError,\n test_base.value_driven_test, 1, 3)\n\n\nclass DynamicTestMethodGenerator(type):\n \"\"\"Class responsible for generating dynamic test functions.\n\n It only wraps parameters for specific calls of value_driven_test. It could\n be called a form of currying.\n \"\"\"\n\n def __new__(cls, name, bases, dct):\n def generate_test_method(number, expected):\n def test_method(self):\n self.value_driven_test(number, expected)\n return test_method\n for number, expected in TEST_DATA:\n method_name = \"testNumbers_%s_and_%s\" % (number, expected)\n dct[method_name] = generate_test_method(number, expected)\n return type.__new__(cls, name, bases, dct)\n\n\nclass FooUnitTest(FooTestBase, unittest.TestCase):\n \"\"\"Combines generated and hand-written functions.\"\"\"\n\n __metaclass__ = DynamicTestMethodGenerator\n\n\nif __name__ == '__main__':\n unittest.main()\n .....F\n======================================================================\nFAIL: testNumbers_3_and_5 (__main__.FooUnitTest)\n----------------------------------------------------------------------\nTraceback (most recent call last):\n File \"dyn_unittest.py\", line 65, in test_method\n self.value_driven_test(number, expected)\n File \"dyn_unittest.py\", line 30, in value_driven_test\n self.assertEquals(expected, self.obj.f(number))\nAssertionError: 5 != 4\n\n----------------------------------------------------------------------\nRan 6 tests in 0.002s\n\nFAILED (failures=1)\n" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347109", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37984/" ]
347,111
<p>In a CF8 form, I'm using a tag such as the following:</p> <pre><code>&lt;cfinput type = "Text" name = "Num" value = "0" validate = "range,integer" range = "0,1000" validateAt="onBlur,onSubmit" required = "yes" message = "Invalid Value" &gt; </code></pre> <p>When the field loses focus (onBlur), the input is validated for only the first of the conditions in the validate parameter (it changes when I swap the order).</p> <p>This is the html / JS code that is auto generated:</p> <pre><code>&lt;input name="Num" id="Num" type="text" value="0" onblur="if( !_CF_hasValue(this, 'TEXT', false) &amp;&amp; !_CF_checkrange(this.value,0.0,1000.0, true) || !_CF_checkinteger(this.value, true) ) { _CF_onErrorAlert(new Array('Invalid Value')); }" /&gt; </code></pre> <p>OnSubmit is handled with separate autogenerated JS and works properly.</p> <p>Am I doing something wrong? Does CF8 not support validating these two conditions together?</p>
[ { "answer_id": 347409, "author": "Tomalak", "author_id": 18771, "author_profile": "https://Stackoverflow.com/users/18771", "pm_score": 3, "selected": true, "text": "if (!has_value && !in_range || !is_integer) show_error()\n if (!has_value || !in_range || !is_integer) show_error()\n && || true" }, { "answer_id": 347548, "author": "Ben Doom", "author_id": 12267, "author_profile": "https://Stackoverflow.com/users/12267", "pm_score": 0, "selected": false, "text": "^1?\\d{1,3}$\n" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347111", "https://Stackoverflow.com", "https://Stackoverflow.com/users/26428/" ]
347,132
<p>How would you append an integer to a <code>char*</code> in c++?</p>
[ { "answer_id": 347140, "author": "Paige Ruten", "author_id": 813, "author_profile": "https://Stackoverflow.com/users/813", "pm_score": 6, "selected": true, "text": "char* sprintf() char integer_string[32];\nint integer = 1234;\n\nsprintf(integer_string, \"%d\", integer);\n strcat() char other_string[64] = \"Integer: \"; // make sure you allocate enough space to append the other string\n\nstrcat(other_string, integer_string); // other_string now contains \"Integer: 1234\"\n" }, { "answer_id": 347143, "author": "Sydius", "author_id": 43496, "author_profile": "https://Stackoverflow.com/users/43496", "pm_score": 3, "selected": false, "text": "char *theString = \"Some string\";\nint theInt = 5;\nstringstream ss;\nss << theString << theInt;\n ss.str();" }, { "answer_id": 347145, "author": "Draemon", "author_id": 26334, "author_profile": "https://Stackoverflow.com/users/26334", "pm_score": 2, "selected": false, "text": "width = floor(log10(num))+1;\nresult = malloc(strlen(str)+len));\nsprintf(result, \"%s%*d\", str, width, num);\n" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347132", "https://Stackoverflow.com", "https://Stackoverflow.com/users/37875/" ]
347,142
<p>Is it common practice to keep project files (i.e. files other that source code files) in the version control repository?</p> <p>Also, are these files checked in/out on a regular basis?</p> <p>I always envisioned a SCC repository as 'clean' with only source code files.</p> <p>How do you manage the non-source code files in a repository?</p> <p>Take a Visual Studio solution, as an example. Would you "check-in" the entire Solution's directory to the SCCS or would you just add the source code files? What about when it comes time to build the Solution, then the entire solution needs to be checked out? Maybe it's best done with a manual process?</p>
[ { "answer_id": 347151, "author": "Hudson", "author_id": 14105, "author_profile": "https://Stackoverflow.com/users/14105", "pm_score": 0, "selected": false, "text": "cvs add -kb filenames\n" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347142", "https://Stackoverflow.com", "https://Stackoverflow.com/users/21826/" ]
347,156
<p>Do you put unit tests in the same project for convenience or do you put them in a separate assembly?</p> <p>If you put them in a separate assembly like we do, we end up with a number of extra projects in the solution. It's great for unit testing while coding but how do you release the application without all of these extra assemblies?</p>
[ { "answer_id": 25076422, "author": "Andrej Adamenko", "author_id": 3421814, "author_profile": "https://Stackoverflow.com/users/3421814", "pm_score": 4, "selected": false, "text": "public static class Ext\n{\n [TestCase(1.1, Result = 1)]\n [TestCase(0.9, Result = 1)]\n public static int ToRoundedInt(this double d)\n {\n return (int) Math.Round(d);\n }\n}\n TestCase" }, { "answer_id": 50453788, "author": "Teoman shipahi", "author_id": 929902, "author_profile": "https://Stackoverflow.com/users/929902", "pm_score": 2, "selected": false, "text": "Providers > DataProvider > SqlDataProvider.cs Providers > DataProvider > SqlDataProvider.Tests.cs SqlDataProvider.cs SqlDataProvider.Tests.cs .Tests .Tests" }, { "answer_id": 56646051, "author": "James Thurley", "author_id": 37725, "author_profile": "https://Stackoverflow.com/users/37725", "pm_score": 6, "selected": false, "text": " <ItemGroup Condition=\"'$(Configuration)' == 'Release'\">\n <Compile Remove=\"**\\*.Tests.cs\" />\n </ItemGroup>\n <ItemGroup Condition=\"'$(Configuration)' != 'Release'\">\n <PackageReference Include=\"nunit\" Version=\"3.11.0\" />\n <PackageReference Include=\"NUnit3TestAdapter\" Version=\"3.12.0\" />\n <PackageReference Include=\"Microsoft.NET.Test.Sdk\" Version=\"15.9.0\" />\n </ItemGroup>\n Release *.Tests.cs Release ReleaseContainingTests \"material-icon-theme.files.associations\": {\n \"*.Tests.cs\": \"test-jsx\",\n \"*.Mocks.cs\": \"merlin\",\n \"*.Interface.cs\": \"Raml\",\n}\n Program has more than one entry point defined <GenerateProgramFile>false</GenerateProgramFile> <PropertyGroup> .csproj" }, { "answer_id": 58808409, "author": "Kellen Stuart", "author_id": 5361412, "author_profile": "https://Stackoverflow.com/users/5361412", "pm_score": 0, "selected": false, "text": "nunit3-console.exe .dll .exe bin nunit3-console.exe exe dll" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347156", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
347,160
<p>In a brand new program where space isn't really that big a deal, is it better to delete a row or to disable a row by let's say a boolean "Disabled" and have the program just ignore it?</p> <p>For example, if I wanted to remove a user from a program.</p>
[ { "answer_id": 348970, "author": "Piskvor left the building", "author_id": 19746, "author_profile": "https://Stackoverflow.com/users/19746", "pm_score": 2, "selected": false, "text": "users users_deleted somedb.users somedb_deleted.users" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347160", "https://Stackoverflow.com", "https://Stackoverflow.com/users/10352/" ]
347,196
<p>I have only this in my mxml source code:</p> <pre><code>&lt;?xml version="1.0" encoding="utf-8"?&gt; &lt;mx:Canvas xmlns:mx="http://www.adobe.com/2006/mxml" xmlns:comp="components.*" width="770" height="330"&gt; &lt;mx:Label x="185.5" y="150" text="Placeholder for Future UI." fontSize="30" color="#93A8AD"/&gt; &lt;/mx:Canvas&gt; </code></pre> <p>And when I try to use the flex builder's design mode, I get the error "An unknown item is declared as the root of your MXML document. Switch to source mode to correct it." Anyone out there knows how to resolve this issue?</p> <p>One thing to note here that I've recently upgraded to flash player 10 debugger.</p>
[ { "answer_id": 2245923, "author": "pablo", "author_id": 271205, "author_profile": "https://Stackoverflow.com/users/271205", "pm_score": 0, "selected": false, "text": "<?xml..." } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347196", "https://Stackoverflow.com", "https://Stackoverflow.com/users/20165/" ]
347,210
<p>How do you execute a JavaScript function without <code>onclick</code> like &quot;Grippie&quot; in a new post on SOF, like the <code>&lt;div class=&quot;grippie&quot; style=&quot;margin-right: 59px;&quot;/</code>&gt; on Stack Overflow when you post a question or answer? I get a nice CSS cursor which lets me know of the movable edge, but how is the JavaScript which resizes the field finding out I clicked on the 'grippie'?</p> <p><strong>Edit:</strong> Thank you for the answers which lead to jQuery and describe the handler. Could I please have a simple use of the handler that determines when the element is clicked, like:</p> <pre><code>addListener('myElement',performFunction();).onclick; </code></pre> <p>or however this may work?</p>
[ { "answer_id": 352929, "author": "Supernovah", "author_id": 36076, "author_profile": "https://Stackoverflow.com/users/36076", "pm_score": 2, "selected": false, "text": "document.getElementById('ID').addEventListener('click',function();,false); \n//Problems: Has to be terminated and false/true is something tricky I don't understand yet (please see link I post)\n\ndocument.getElementById('ID').onclick = function();\n//Problems: Cannot be terminated directly and heirachy issue where function including 'this' keyword applies to the child divs or something (please again see link I post)\n\n//an iterartion of setInterval(checkFunction,interval);\n//Problems: Very very slow and in most cases requires an onClick to check for a change anyway!\n" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347210", "https://Stackoverflow.com", "https://Stackoverflow.com/users/36076/" ]
347,219
<p>I'm using an NSTimer to do some rendering in an OpenGL based iPhone app. I have a modal dialog box that pops up and requests user input. While the user is providing input I'd like to "pause" i.e. something like this:</p> <pre><code>[myNSTimer pause]; </code></pre> <p>I'm using this syntax because I've been doing things like:</p> <pre><code>[myNSTimer invalidate]; </code></pre> <p>when I want it to stop.</p> <p>How can I programmatically pause the NSTimer?</p>
[ { "answer_id": 3777774, "author": "kapesoftware", "author_id": 456090, "author_profile": "https://Stackoverflow.com/users/456090", "pm_score": 4, "selected": false, "text": "pauseStart = [[NSDate dateWithTimeIntervalSinceNow:0] retain];\npreviousFiringDate = [timer firingDate];\n[timer setFiringDate:INFINITY]\n float pauseTime = -1*[pauseStart timeIntervalSinceNow];\n[timer setFireDate:[previousFireDate initWithTimeInterval:pauseTime sinceDate:previousFireDate]];\n" }, { "answer_id": 6020729, "author": "Riley", "author_id": 756023, "author_profile": "https://Stackoverflow.com/users/756023", "pm_score": 3, "selected": false, "text": "-(void) timerToggle{\n if (theTimer == nil) {\n float theInterval = 1.0/30.0;\n theTimer = [NSTimer scheduledTimerWithTimeInterval:theInterval target:self selector:@selector(animateBall:) userInfo:nil repeats:YES];\n } else {\n [theTimer invalidate];\n theTimer = nil;\n }\n}\n" }, { "answer_id": 6765300, "author": "Thiru", "author_id": 754608, "author_profile": "https://Stackoverflow.com/users/754608", "pm_score": 5, "selected": false, "text": "NSDate *pauseStart, *previousFireDate;\n\n-(void) pauseTimer:(NSTimer *)timer { \n\n pauseStart = [[NSDate dateWithTimeIntervalSinceNow:0] retain];\n\n previousFireDate = [[timer fireDate] retain];\n\n [timer setFireDate:[NSDate distantFuture]];\n}\n\n-(void) resumeTimer:(NSTimer *)timer {\n\n float pauseTime = -1*[pauseStart timeIntervalSinceNow];\n\n [timer setFireDate:[previousFireDate initWithTimeInterval:pauseTime sinceDate:previousFireDate]];\n\n [pauseStart release];\n\n [previousFireDate release];\n}\n" }, { "answer_id": 9715299, "author": "Masud alam", "author_id": 1013962, "author_profile": "https://Stackoverflow.com/users/1013962", "pm_score": 0, "selected": false, "text": "self.startDate=[NSDate date];\nself.timeElapsedInterval=[[NSDate date] timeIntervalSinceDate:self.startDate];//This ``will be 0 //second at the start of the timer.`` \n\nmyTimer= [NSTimer scheduledTimerWithTimeInterval:1.0 target:self `selector:@selector(updateTimer) userInfo:nil repeats:YES];\n NSTimeInterval unitTime=1;\n-(void) updateTimer\n {\n if(self.timerPaused)\n {\n //Do nothing as timer is paused\n }\n else{\n self.timerElapsedInterval=timerElapsedInterval+unitInterval;\n //Then do your thing update the visual timer texfield or something.\n }\n\n }\n" }, { "answer_id": 18200462, "author": "Carl Veazey", "author_id": 475052, "author_profile": "https://Stackoverflow.com/users/475052", "pm_score": 3, "selected": false, "text": "NSTimer #import <Foundation/Foundation.h>\n\n@interface NSTimer (CVPausable)\n\n- (void)pauseOrResume;\n- (BOOL)isPaused;\n\n@end\n #import \"NSTimer+CVPausable.h\"\n#import <objc/runtime.h>\n\n@interface NSTimer (CVPausablePrivate)\n\n@property (nonatomic) NSNumber *timeDeltaNumber;\n\n@end\n\n@implementation NSTimer (CVPausablePrivate)\n\nstatic void *AssociationKey;\n\n- (NSNumber *)timeDeltaNumber\n{\n return objc_getAssociatedObject(self, AssociationKey);\n}\n\n- (void)setTimeDeltaNumber:(NSNumber *)timeDeltaNumber\n{\n objc_setAssociatedObject(self, AssociationKey, timeDeltaNumber, OBJC_ASSOCIATION_RETAIN);\n}\n\n@end\n\n\n@implementation NSTimer (CVPausable)\n\n- (void)pauseOrResume\n{\n if ([self isPaused]) {\n self.fireDate = [[NSDate date] dateByAddingTimeInterval:[self.timeDeltaNumber doubleValue]];\n self.timeDeltaNumber = nil;\n }\n else {\n NSTimeInterval interval = [[self fireDate] timeIntervalSinceNow];\n self.timeDeltaNumber = @(interval);\n self.fireDate = [NSDate distantFuture];\n }\n}\n\n- (BOOL)isPaused\n{\n return (self.timeDeltaNumber != nil);\n}\n\n@end\n" }, { "answer_id": 20164523, "author": "divyenduz", "author_id": 1366216, "author_profile": "https://Stackoverflow.com/users/1366216", "pm_score": 0, "selected": false, "text": "-(IBAction)Pause:(id)sender\n{\n static BOOL *PauseToggle;\n if(!PauseToggle)\n {\n [timer invalidate];\n timer = nil;\n PauseToggle = (BOOL *) YES;\n }\n else\n {\n timer = [NSTimer scheduledTimerWithTimeInterval:0.04 target:self selector:@selector(HeliMove) userInfo:nil repeats:YES];\n PauseToggle = (BOOL *) NO;\n }\n}\n" }, { "answer_id": 21814539, "author": "jano", "author_id": 971783, "author_profile": "https://Stackoverflow.com/users/971783", "pm_score": -1, "selected": false, "text": "#import <Foundation/Foundation.h>\n\n@interface NSTimer (Pausable)\n\n-(void)pause;\n-(void)resume;\n\n@end\n #import \"NSTimer+Pausable.h\"\n\n@implementation NSTimer (Pausable)\n\n-(void)pause\n{\n [self setFireDate:[NSDate dateWithTimeIntervalSinceNow:[NSDate distantFuture]]]; //set fireDate to far future\n}\n\n-(void)resume\n{\n [self setFireDate:[NSDate date]];\n}\n\n@end\n" }, { "answer_id": 25161359, "author": "keeshux", "author_id": 784615, "author_profile": "https://Stackoverflow.com/users/784615", "pm_score": 1, "selected": false, "text": "NSTimer" }, { "answer_id": 27753690, "author": "Toby", "author_id": 360967, "author_profile": "https://Stackoverflow.com/users/360967", "pm_score": 2, "selected": false, "text": "#import <objc/runtime.h>\n\n@interface NSTimer (PausableTimer)\n\n@property (nonatomic, retain) NSDate *pausedDate;\n\n@property (nonatomic, retain) NSDate *nextFireDate;\n\n-(void)pause;\n\n-(void)resume;\n\n@end\n @implementation NSTimer (PausableTimer)\n\nstatic char * kPausedDate = \"pausedDate\";\nstatic char * kNextFireDate = \"nextFireDate\";\n\n@dynamic pausedDate;\n@dynamic nextFireDate;\n\n-(void)pause {\n\n self.pausedDate = [NSDate date];\n\n self.nextFireDate = [self fireDate];\n\n [self setFireDate:[NSDate distantFuture]];\n}\n\n-(void)resume\n{\n float pauseTime = -1*[self.pausedDate timeIntervalSinceNow];\n\n [self setFireDate:[self.nextFireDate initWithTimeInterval:pauseTime sinceDate:self.nextFireDate]];\n}\n\n- (void)setPausedDate:(NSDate *)pausedDate\n{\n objc_setAssociatedObject(self, kPausedDate, pausedDate, OBJC_ASSOCIATION_RETAIN_NONATOMIC);\n}\n\n- (NSDate *)pausedDate\n{\n return objc_getAssociatedObject(self, kPausedDate);\n}\n\n- (void)setNextFireDate:(NSDate *)nextFireDate\n{\n objc_setAssociatedObject(self, kNextFireDate, nextFireDate, OBJC_ASSOCIATION_RETAIN_NONATOMIC);\n}\n\n- (NSDate *)nextFireDate\n{\n return objc_getAssociatedObject(self, kNextFireDate);\n}\n" }, { "answer_id": 34947293, "author": "Johnny Rockex", "author_id": 917802, "author_profile": "https://Stackoverflow.com/users/917802", "pm_score": 0, "selected": false, "text": "//set vars, fire first method on load.\nfeatureDelay = 8; //int\nfeatureInt = featureDelay-1; //int\nfeaturePaused = false; //boolean\n\n-(void)initiateFeatureTimer {\n featureTimer = [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(moveFeatureScroller) userInfo:nil repeats:true];\n [featureTimer fire];\n}\n -(void)moveFeatureScroller {\n\n if (!featurePaused){ //check boolean\n featureInt++;\n\n if (featureInt == featureDelay){\n featureInt = 0; //reset the feature int\n\n /*//scroll logic\n int nextPage = (featurePage + 1) * w;\n if (featurePage == features.count-1){ nextPage = 0; }\n [featureScroller setContentOffset:CGPointMake(nextPage, 0)]; */ \n }\n }\n}\n\n-(void)scrollViewWillBeginDragging:(UIScrollView *)scrollView {\n featurePaused = true; //pause the timer\n}\n-(void)scrollViewWillEndDragging:(UIScrollView *)scrollView withVelocity:(CGPoint)velocity targetContentOffset:(inout CGPoint *)targetContentOffset {\n featurePaused = false; //restart the timer\n featureInt = -3; //if you want to add an additional delay\n}\n" }, { "answer_id": 43347032, "author": "ooOlly", "author_id": 4665587, "author_profile": "https://Stackoverflow.com/users/4665587", "pm_score": 0, "selected": false, "text": "CADisplayLink NSTimer CADisplayLink -pause displayLink = [[CADisplayLink displayLinkWithTarget:self selector:@selector(fireMethod:)];\ndisplayLink.frameInterval = approximateVaue;//CADisplayLink's frame rate is 60 fps.\n [displayLink addToRunLoop:[NSRunLoop currentRunLoop] forMode:NSDefaultRunLoopMode];\n\n//pause\n[displayLink pause];\n" }, { "answer_id": 66480002, "author": "amleszk", "author_id": 782808, "author_profile": "https://Stackoverflow.com/users/782808", "pm_score": 0, "selected": false, "text": "pause timer.fireDate.timeIntervalSinceNow import Foundation\n\nclass PausableTimer {\n \n let timer: Timer\n var timeIntervalOnPause: TimeInterval?\n \n init(timeInterval interval: TimeInterval, repeats: Bool, block: @escaping (Timer) -> Void) {\n timer = Timer(timeInterval: interval, repeats: repeats, block: block)\n }\n \n func invalidate() {\n timer.invalidate()\n }\n \n var paused: Bool {\n timeIntervalOnPause != nil\n }\n \n func toggle() {\n if paused {\n resume()\n } else {\n pause(isFiringTimer: false)\n }\n }\n \n /// Pause the timer\n /// - Parameter isFiringTimer: pass in true if the timer is currently firing, in which case the resume time will not\n /// be relative to next fire date, but instead relative to the time interval. It's improtant that this be correct otherwise there maybe a near\n /// infinite loop firing of the `Timer`\n func pause(isFiringTimer: Bool) {\n guard timer.isValid else {\n return\n }\n timeIntervalOnPause = isFiringTimer || timer.fireDate.timeIntervalSinceReferenceDate == 0 ? timer.timeInterval : timer.fireDate.timeIntervalSinceNow\n timer.fireDate = .distantFuture\n }\n \n /// Resume the timer, if it was not paused has not effect, and causes assertion failure\n func resume() {\n guard timer.isValid else {\n return\n }\n guard let timeIntervalOnPause = timeIntervalOnPause else {\n assertionFailure(\"Resuming a timer that was never paused \\(self) - \\(self.timer)\")\n return\n }\n let relativeFireDate = Date(timeIntervalSinceNow: timeIntervalOnPause)\n timer.fireDate = relativeFireDate\n self.timeIntervalOnPause = nil\n }\n \n}\n" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347219", "https://Stackoverflow.com", "https://Stackoverflow.com/users/22471/" ]
347,226
<p>I've created a table in Microsoft Sql CE that I'm using to hold some data. I've generated an ORM via SqlMetal and I've pulled the datasource into my WPF project.</p> <p>I want to create a simple WPF form that can be used to edit a record in the table via the ORM-generated classes. I want this form to support typical OK/Cancel semantics. I've created the form in what I believe to be the typical fashion, using TwoWay databinding on the respective fields to bind against an instance of the object from the ORM. For example, given an object in the ORM that has a property "TaskName", I've included the following in my WPF form:</p> <pre><code>&lt;Label Grid.Column="0" Grid.Row="0" &gt; Name: &lt;/Label&gt; &lt;TextBox Name="txtName" Grid.Column="1" Grid.Row="0" Text="{Binding TaskName, Mode=TwoWay}" AcceptsReturn="False" MaxLines="1" /&gt; </code></pre> <p>This, combined with a DataContext assignment in code:</p> <pre><code>var newRow = new OrmGeneratedClass(); // Populate default values on newRow, e.g. detailWindow.DataContext = newRow; detailWindow.ShowDialog(); </code></pre> <p>can work reasonably well for creation of a new row. All changes made via the form are immediately reflected in the underlying OrmGeneratedClass. The problem is that there's no immediate support for canceling changes if, e.g., the OrmGeneratedClass is filled with previously saved values.</p> <p><strong>What is a good design for this scenario, or am I designing it wrong before I get to this point?</strong> I'm a newbie with WPF and the Sql Server datasource/ORM integration aspects. (This is a personal project that I'm using to learn both technologies.)</p> <p>I have a couple of thoughts and will place them in the answers</p>
[ { "answer_id": 347230, "author": "Greg D", "author_id": 6932, "author_profile": "https://Stackoverflow.com/users/6932", "pm_score": 1, "selected": false, "text": "var existingRow = GetExistingRow(someConditionOrWhatever);\ndetailWindow.DataContext = existingRow;\nif(!detailWindow.ShowDialog())\n{\n existingRow = GetExistingRow(someConditionOrWhatever);\n}\n" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347226", "https://Stackoverflow.com", "https://Stackoverflow.com/users/6932/" ]
347,235
<p>I have string which is base64 encoded. How can I search this string to check if this string contains specific sub string which is not encoded? I don't want to decode that string and then search it. </p> <p>Can I just encode that specific sub string, and search the encoded string by using the encoded sub string?</p> <p>Thanks,</p>
[ { "answer_id": 67880688, "author": "recvfrom", "author_id": 9457431, "author_profile": "https://Stackoverflow.com/users/9457431", "pm_score": 0, "selected": false, "text": "MZ PE\\x00\\x00 A Z a z 0 9 + \\ MZ M 01001101 Z 01011010 010011 010101 1010xx\nT V ???\n MZ 101000: o\n101001: p\n101010: q\n101011: r\n MZ ^TV[o-r] PE\\x00\\x00 0 % 6 == 0 8 % 6 == 2 16 % 6 == 4 24 % 6 == 0 Zero-bit shift:\nP E \\x00 \\x00\n01010000 01000101 00000000 00000000\nbecomes:\n010100 000100 010100 000000 000000 00xxxx\nU E U A A [A-P]\n\nTwo-bit shift:\n??? P E \\x00 \\x00\nxxxxxxxx 01010000 01000101 00000000 00000000\nbecomes:\nxxxxxx xx0101 000001 010100 000000 000000 0000xx\n [FVl1] B F A A [A-D]\n\nFour-bit shift:\n??? ??? P E \\x00 \\x00\nxxxxxxxx xxxxxxxx 01010000 01000101 00000000 00000000\nbecomes:\nxxxxxx xxxxxx xxxx01 010000 010001 010000 000000 000000\n [BFJNRVZdhlptx159] Q R Q A A\n ^TV[o-r][A-Za-z0-9\\+/]+(?:UEUAA[A-P]|[FVl1]BFAA[A-D]|[BFJNRVZdhlptx159]QRQAA)\n [A-Za-z0-9\\+/]+" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347235", "https://Stackoverflow.com", "https://Stackoverflow.com/users/-1/" ]
347,238
<p>There seems to be three common approaches for mapping an application end user to a database user. </p> <ol> <li><strong>One to One Mapping:</strong> Each Application user (bob, nancy and fred) also get a corresponding database user account (bob nancy and fred).</li> <li><strong>N to M mapping:</strong> Each application user is mapped to a database user that represents their role. bob and nancy are mapped to the 'clerk' database user while fred is mapped to the 'manager' database user.</li> <li><strong>N to 1 mapping:</strong> Each application user is mapped to a single database user (app_user) and identity is only managed at the application tier.</li> </ol> <p>It seems that #3 is the most common in web application development. <strong>Why is there not a greater emphasis on the other two options?</strong></p> <p>Oracle encourages techniques like #2 using its proxy authentication features for the following reason:</p> <p><strong>Limited trust model</strong>-controlling the users on whose behalf middle tiers can connect, and the roles the middle tiers can assume for the user</p> <p><strong>Scalability</strong>-by supporting lightweight user sessions and eliminating the overhead of re-authenticating clients</p> <p><strong>Accountability</strong>, by preserving the identity of the real user through to the database, and enabling auditing of actions taken on behalf of the real user</p> <p><a href="http://download.oracle.com/docs/cd/B28359_01/java.111/b31224/proxya.htm" rel="nofollow noreferrer">Oracle's Proxy Authentication documentation</a></p>
[ { "answer_id": 347438, "author": "Marc Gravell", "author_id": 23354, "author_profile": "https://Stackoverflow.com/users/23354", "pm_score": 4, "selected": true, "text": "USER_NAME() SUSER_SNAME()" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347238", "https://Stackoverflow.com", "https://Stackoverflow.com/users/700/" ]
347,242
<p>by default is a class:</p> <ol> <li>private ?</li> <li>internal ? </li> <li>sealed ?</li> </ol>
[ { "answer_id": 347395, "author": "Jon Skeet", "author_id": 22656, "author_profile": "https://Stackoverflow.com/users/22656", "pm_score": 4, "selected": false, "text": "public string Foo { get; private set; }\n" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347242", "https://Stackoverflow.com", "https://Stackoverflow.com/users/4653/" ]
347,248
<p>Can I do it with reflection or something like that?</p>
[ { "answer_id": 347323, "author": "erickson", "author_id": 3474, "author_profile": "https://Stackoverflow.com/users/3474", "pm_score": 5, "selected": false, "text": "ServiceLoader" }, { "answer_id": 30446248, "author": "Ahmad Abdelghany", "author_id": 1998422, "author_profile": "https://Stackoverflow.com/users/1998422", "pm_score": 6, "selected": false, "text": "Reflections reflections = new Reflections(\"firstdeveloper.examples.reflections\");\nSet<Class<? extends Pet>> classes = reflections.getSubTypesOf(Pet.class);\n ServiceLoader<Pet> loader = ServiceLoader.load(Pet.class);\nfor (Pet implClass : loader) {\n System.out.println(implClass.getClass().getSimpleName()); // prints Dog, Cat\n}\n Pet resources/META-INF/services examples.reflections.Pet Pet examples.reflections.Dog\nexamples.reflections.Cat\n Package[] packages = Package.getPackages();\nfor (Package p : packages) {\n MyPackageAnnotation annotation = p.getAnnotation(MyPackageAnnotation.class);\n if (annotation != null) {\n Class<?>[] implementations = annotation.implementationsOfPet();\n for (Class<?> impl : implementations) {\n System.out.println(impl.getSimpleName());\n }\n }\n}\n @Retention(RetentionPolicy.RUNTIME)\n@Target(ElementType.PACKAGE)\npublic @interface MyPackageAnnotation {\n Class<?>[] implementationsOfPet() default {};\n}\n package-info.java @MyPackageAnnotation(implementationsOfPet = {Dog.class, Cat.class})\npackage examples.reflections;\n Package.getPackages()" }, { "answer_id": 45676693, "author": "kaybee99", "author_id": 2216929, "author_profile": "https://Stackoverflow.com/users/2216929", "pm_score": 4, "selected": false, "text": "public interface ITask {\n void doStuff();\n}\n\n@Component\npublic class MyTask implements ITask {\n public void doStuff(){}\n}\n ITask @Service\npublic class TaskService {\n\n @Autowired\n private List<ITask> tasks;\n}\n" }, { "answer_id": 51625212, "author": "Luke Hutchison", "author_id": 3950982, "author_profile": "https://Stackoverflow.com/users/3950982", "pm_score": 3, "selected": false, "text": "try (ScanResult scanResult = new ClassGraph().whitelistPackages(\"x.y.z\")\n .enableClassInfo().scan()) {\n for (ClassInfo ci : scanResult.getClassesImplementing(\"x.y.z.SomeInterface\")) {\n foundImplementingClass(ci); // Do something with the ClassInfo object\n }\n}\n" }, { "answer_id": 53782825, "author": "NaN", "author_id": 1062933, "author_profile": "https://Stackoverflow.com/users/1062933", "pm_score": 2, "selected": false, "text": "public interface ITask {\n void doStuff();\n default ITask getImplementation() {\n return this;\n }\n\n}\n\n@Component\npublic class MyTask implements ITask {\n public void doStuff(){}\n}\n ITask @Service\npublic class TaskService {\n\n @Autowired(required = false)\n private List<ITask> tasks;\n\n if ( tasks != null)\n for (ITask<?> taskImpl: tasks) {\n taskImpl.doStuff();\n } \n}\n" }, { "answer_id": 54277804, "author": "verglor", "author_id": 489790, "author_profile": "https://Stackoverflow.com/users/489790", "pm_score": 3, "selected": false, "text": "my.package.MyInterface @Grab('io.github.classgraph:classgraph:4.6.18')\nimport io.github.classgraph.*\nnew ClassGraph().enableClassInfo().scan().withCloseable { scanResult ->\n scanResult.getClassesImplementing('my.package.MyInterface').findAll{!it.abstract}*.name\n}\n" } ]
2008/12/07
[ "https://Stackoverflow.com/questions/347248", "https://Stackoverflow.com", "https://Stackoverflow.com/users/1356709/" ]