qid int64 4 22.2M | question stringlengths 18 48.3k | answers list | date stringlengths 10 10 | metadata list |
|---|---|---|---|---|
311,504 | <p>In Firefox and Safari, pages that are centered move a few pixels when the page is long enough for the scrollbar to appear. If you navigate through a site that has long and short pages, the page seems to "jump" around.</p>
<p>IE7 tends to leave the scroll bar visible all of the time but disables it when the page is not long enough. Since the width of the HTML window never changes the centering of the page doesn't change.</p>
<p>Is there a workaround or a way to style the page so it doesn't jump around in Firefox and Safari?</p>
<p>Thanks.</p>
| [
{
"answer_id": 311514,
"author": "Pim Jager",
"author_id": 35197,
"author_profile": "https://Stackoverflow.com/users/35197",
"pm_score": 5,
"selected": true,
"text": "html{\n overflow: scroll;\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311504",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30552/"
] |
311,543 | <p>Edit:</p>
<p>I don't know what this user originally wanted, and hopefully they'll edit their question to let us know, but otherwise, let's use this question to answer (or give links to) the following common console window issues:</p>
<ul>
<li>How do you capture the output of a console application in your program (for instance, running a build process and getting the output in your IDE)?</li>
<li>How do you get your console application to hang around long enough to see the output when you hit "run" in the IDE? (ie, getch for C, some IDEs have options to set, what common/popular pause and wait for keypress routines do you use to keep the console window open long enough to see the output? This applies to lots of languages - list your method)</li>
</ul>
<p>Original question:</p>
<blockquote>
<p>How to view console application output
screen(black screen).Please mention in
detail.</p>
</blockquote>
| [
{
"answer_id": 311552,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 1,
"selected": false,
"text": "#include <iostream>\n#include <limits>\n\nint main() {\n\n // Rest of the code \n\n //Clean the stream and ask for input\n std::cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\\n' );\n std::cin.get();\n return 0;\n}\n"
},
{
"answer_id": 311557,
"author": "Adam Davis",
"author_id": 2915,
"author_profile": "https://Stackoverflow.com/users/2915",
"pm_score": 0,
"selected": false,
"text": "/* Example waits for a character input */\n#include <stdio.h>\n\nint main()\n{\n /* Put your code here */\n getchar();\n return 0;\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311543",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,576 | <p>Given say 11/13/2008 - 12/11/2008 as the value posted back in TextBox, what would be the best way to parse out the start and end date using C#?</p>
<p>I know I could use:</p>
<pre><code>DateTime startDate = Convert.ToDateTime(TextBoxDateRange.Text.Substring(0, 10));
DateTime endDate = Convert.ToDateTime(TextBoxDateRange.Text.Substring(13, 10));
</code></pre>
<p>Is there a better way?</p>
| [
{
"answer_id": 311583,
"author": "Bryan Watts",
"author_id": 37815,
"author_profile": "https://Stackoverflow.com/users/37815",
"pm_score": 4,
"selected": true,
"text": "var dates = TextBoxDateRange.Text.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries);\n\nvar startDate = DateTime.Parse(dates[0], CultureInfo.CurrentCulture);\nvar endDate = DateTime.Parse(dates[1], CultureInfo.CurrentCulture);\n"
},
{
"answer_id": 311586,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 2,
"selected": false,
"text": " CultureInfo ci = new CultureInfo(\"en-us\");\n var startDate = DateTime.Parse(components[0], ci);\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311576",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25335/"
] |
311,579 | <p>I have a web page with 3 forms on it. Not nested, just one after the other (they are almost identical, just one hidden variable that's different). A user will only fill in one form, and I'd like to validate/etc all the forms with only one JS script.</p>
<p>So how, when a user clicks the submit button of form#1, do I make my js script only deal with the fields in form1? I gather it has something to do with $(this).parents , but I am not sure what to do with it. </p>
<p>My validation script (which I used elsewhere, with only a single form) looks something like so:</p>
<pre>
<code>
$(document).ready(function(){
$("#submit").click(function(){
$(".error").hide();
var hasError = false;
var nameVal = $("#name").val();
if(nameVal == '') {
$("#name").after('Please enter your name.');
hasError = true;
}
if(hasError == false) {blah blah do all the processing stuff}
</code>
</pre>
<p>So do I need to replace things like $("#name").val() with $(this).parents('form').name.val() ? Or is there a better way to go about this?</p>
<p>Thanks!</p>
| [
{
"answer_id": 311589,
"author": "Eran Galperin",
"author_id": 10585,
"author_profile": "https://Stackoverflow.com/users/10585",
"pm_score": 9,
"selected": true,
"text": "$(\"#submit\").click(function(){\n var form = $(this).parents('form:first');\n ...\n});\n"
},
{
"answer_id": 311848,
"author": "redsquare",
"author_id": 6440,
"author_profile": "https://Stackoverflow.com/users/6440",
"pm_score": 6,
"selected": false,
"text": "this.form\n"
},
{
"answer_id": 963248,
"author": "Lathan",
"author_id": 118993,
"author_profile": "https://Stackoverflow.com/users/118993",
"pm_score": 2,
"selected": false,
"text": "var nameVal = form.inputname.val();"
},
{
"answer_id": 5636553,
"author": "TC0072",
"author_id": 616685,
"author_profile": "https://Stackoverflow.com/users/616685",
"pm_score": 6,
"selected": false,
"text": "var form = $(this).parents('form:first');\n"
},
{
"answer_id": 10634727,
"author": "charles",
"author_id": 1312690,
"author_profile": "https://Stackoverflow.com/users/1312690",
"pm_score": 2,
"selected": false,
"text": "$('#mybutton').click(function(){\n clearForm($('#mybutton').closest(\"form\"));\n });\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311579",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,588 | <p>List comprehensions can be useful in certain situations, but they can also be rather horrible to read.. As a slightly exaggerated example, how would you indent the following?</p>
<pre><code>allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) if x.type == "post" and x.deleted is not False]
</code></pre>
| [
{
"answer_id": 311590,
"author": "Eli Bendersky",
"author_id": 8206,
"author_profile": "https://Stackoverflow.com/users/8206",
"pm_score": 1,
"selected": false,
"text": "allUuids = [x.id for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) \n if (x.type == \"post\" and x.deleted is not False)]\n"
},
{
"answer_id": 311604,
"author": "orestis",
"author_id": 32617,
"author_profile": "https://Stackoverflow.com/users/32617",
"pm_score": 7,
"selected": true,
"text": "[x.id for x\n in self.db.query(schema.allPostsUuid).execute(timeout=20)\n if x.type == 'post' \n and x.deleted is not False\n and ...\n and ...]\n"
},
{
"answer_id": 311675,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "all_posts_uuid_query = self.db.query(schema.allPostsUuid)\nall_posts_uuid_list = all_posts_uuid_query.execute(timeout=20)\nall_uuid_list = [\n x.id \n for x in all_posts_uuid_list \n if (\n x.type == \"post\" \n and \n not x.deleted # <-- if you don't care about NULLs / None\n )\n]\n"
},
{
"answer_id": 311678,
"author": "jfs",
"author_id": 4279,
"author_profile": "https://Stackoverflow.com/users/4279",
"pm_score": 3,
"selected": false,
"text": "allUuids = [x.id \n for x in self.db.query(schema.allPostsUuid).execute(timeout = 20) \n if x.type == \"post\" and x.deleted is not False]\n"
},
{
"answer_id": 311680,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 2,
"selected": false,
"text": "allUuids = []\nfor x in self.db.query(schema.allPostsUuid).execute(timeout = 20) :\n if x.type == \"post\" and x.deleted is not False :\n allUuids.append(x.id)\n"
},
{
"answer_id": 34314371,
"author": "Henco",
"author_id": 1887870,
"author_profile": "https://Stackoverflow.com/users/1887870",
"pm_score": 2,
"selected": false,
"text": "yield"
},
{
"answer_id": 73263001,
"author": "Connor Kress",
"author_id": 19708043,
"author_profile": "https://Stackoverflow.com/users/19708043",
"pm_score": 0,
"selected": false,
"text": " allUuids = [\n x.id\n for x in self.db.query(schema.allPostsUuid).execute(timeout = 20)\n if x.type == \"post\"\n and x.deleted\n ]\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311588",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] |
311,599 | <p>I like generics a lot and use them whereever I can. Every now and then I need to use one of my classes in another project which has to run on an old JVM (before 5.0), needs to run on JavaME (where generics are not allowed neither) or in Microsoft J# (which has VERY poor Support for generics).</p>
<p>At the moment, I remove all generics manually, which means inserting many casts as well.</p>
<p>Since generics are said to be compile-time-only, and every piece of generic code could possibly converted to non-generic code automatically, I wonder if there is any tool which can do this for me.</p>
<p>If there is no such tool, how else could I solve the problem? Should I completely stop using generics?</p>
<p>There already are answers related to <em>bytecode compability</em>. What if I need <em>source code compability</em> for some reason?</p>
| [
{
"answer_id": 311715,
"author": "Daniel Spiewak",
"author_id": 9815,
"author_profile": "https://Stackoverflow.com/users/9815",
"pm_score": 4,
"selected": true,
"text": "java.lang.reflect.Type"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311599",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39946/"
] |
311,601 | <p>I'm working in a windows environment (my laptop!) and I need a couple of scripts that run other programs, pretty much like a windows batch file.</p>
<p>how can I run a command from python such that the program when run, will replace the script? The program is interactive (for instance, unison) and keeps printing lines and asking for user input all the time. </p>
<p>So, just running a program and printing the output won't suffice. The program has to takeover the script's input/output, pretty mcuh like running the command from a .bat file. </p>
<p>I tried os.execl but it keeps telling me "invalid arguments", also, it doesn't find the program name (doesn't search the PATH variable); I have to give it the full path ..?!</p>
<p>basically, in a batch script I can write:
unison profile</p>
<p>how can I achieve the same effect in python?</p>
<p>EDIT:</p>
<p>I found out it can be done with <code>os.system( ... )</code> and since I cannot accept my own answer, I'm closing the question.</p>
<hr>
<p>EDIT: this was supposed to be a comment, but when I posted it I didn't have much points.</p>
<p>Thanks Claudiu, that's pretty much what I want, except for a little thing: I want the function to end when the program exits, but when I try it on unison, it doesn't return control to the python script, but to the windows command line environment</p>
<pre><code>>>> os.execlp("unison")
C:\>Usage: unison [options]
or unison root1 root2 [options]
or unison profilename [options]
For a list of options, type "unison -help".
For a tutorial on basic usage, type "unison -doc tutorial".
For other documentation, type "unison -doc topics".
C:\>
C:\>
C:\>
</code></pre>
<p>how to get around this?</p>
| [
{
"answer_id": 311613,
"author": "Piotr Lesnicki",
"author_id": 38796,
"author_profile": "https://Stackoverflow.com/users/38796",
"pm_score": 4,
"selected": false,
"text": "import os\nimport subprocess\nunison = os.path.join(os.path.curdir, \"unison\")\np = subprocess.Popen(unison)\np.wait()\n"
},
{
"answer_id": 311616,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 2,
"selected": false,
"text": "os.execlp"
},
{
"answer_id": 311623,
"author": "orestis",
"author_id": 32617,
"author_profile": "https://Stackoverflow.com/users/32617",
"pm_score": 2,
"selected": false,
"text": "import subprocess\n\nproc = subprocess.Popen(['unison', 'profile'], stderr=subprocess.PIPE, \n stdout=subprocess.PIPE, stdin=subprocess.PIPE)\n\nproc.stdin.write('user input')\nprint proc.stdout.read()\n"
},
{
"answer_id": 311646,
"author": "hasen",
"author_id": 35364,
"author_profile": "https://Stackoverflow.com/users/35364",
"pm_score": 4,
"selected": true,
"text": "os.system(\"dir\")\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311601",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/35364/"
] |
311,605 | <pre><code>var A = {
x : function () { }
};
var b = function (method) {
//want to know method's "parent" here
};
b(A.x);
</code></pre>
<p>I want to know that x is defined in A when I call the b(A.x). Is this possible?</p>
| [
{
"answer_id": 311617,
"author": "Kornel",
"author_id": 27009,
"author_profile": "https://Stackoverflow.com/users/27009",
"pm_score": 2,
"selected": false,
"text": "x.parent = A;\n"
},
{
"answer_id": 311624,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 0,
"selected": false,
"text": "<html>\n<body>\n<script>\nvar A = {\n x: function (a_a, a_b) { alert(a_a + a_b); }\n};\n\nvar b = function (a_method) {\n alert(a_method.toString());\n a_method.call(this, 1, 2);\n};\n\nb(A.x);\n</script>\n"
},
{
"answer_id": 311669,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 2,
"selected": false,
"text": "var a = { name : 'a' },\n b = { name : 'b' },\n c = { name : 'c' }; \na.x = function () { alert( this.name ); };\nc.x = b.x = a.x; // a, b, and c all reference the same function\n"
},
{
"answer_id": 312220,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 2,
"selected": false,
"text": "function MyClass() {\n // Create a MyClass object\n}\nMyClass.prototype.x = function() { return 42; };\n\nvar a = new MyClass();\na.x.parent = a; // Set the parent to a\n\nvar b = new MyClass();\nb.x.parent = b; // b.x and a.x both reference the same function from MyClass.prototype\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311605",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,621 | <p>I got ahead of myself and downloaded and installed the OSX Python 2.6 package from www.python.org/download/ on my OSX 10.5.5 Intel Mac and installed the full package contents. Only after this did I come across <a href="http://wiki.python.org/moin/MacPython/Leopard" rel="nofollow noreferrer">http://wiki.python.org/moin/MacPython/Leopard</a> stating that you should do a partial install of the package to avoid interfering with the system install.</p>
<p>I'm afraid I've already overwritten the system framework through that installer and I remember reading somewhere after discovering this that I'd lose certain elements included in the OSX system install and not Python distributions.</p>
<p>Is there any way to reverse this or restore anything I may have lost? What exactly have I lost and is it going to be a problem? </p>
| [
{
"answer_id": 311682,
"author": "unmounted",
"author_id": 11596,
"author_profile": "https://Stackoverflow.com/users/11596",
"pm_score": 3,
"selected": false,
"text": "/usr/bin"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311621",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39951/"
] |
311,626 | <p>I've been thinking lately, would it be a good form of syntactic sugar in languages like Java and C#, to include a "duck" type as a method parameter type? This would look as follows:</p>
<pre><code>void myFunction(duck foo) {
foo.doStuff();
}
</code></pre>
<p>This could be syntactic sugar for invoking doStuff() via reflection, or it could be implemented differently. Foo could be any type. If foo does not have a doStuff() method, this would throw a runtime exception. The point is that you would have the benefits of the more rigid pre-specified interface paradigm (performance, error checking) when you want them, i.e. most of the time. At the same time, you'd have a simple, clean-looking backdoor to duck typing, which would allow you to cleanly make changes not foreseen in the initial design without massive refactoring. Furthermore, it would likely be 100% backwards compatible and mesh cleanly with existing language constructs. I think this might help cut down on the overengineered just-in-case programming style that leads to confusing, cluttered APIs. Do you believe that something like this would be a good or bad thing in static OO languages like C# and Java?</p>
| [
{
"answer_id": 311632,
"author": "Bryan Watts",
"author_id": 37815,
"author_profile": "https://Stackoverflow.com/users/37815",
"pm_score": 4,
"selected": true,
"text": "dynamic"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311626",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23903/"
] |
311,627 | <p>This is my code:</p>
<pre><code>import datetime
today = datetime.date.today()
print(today)
</code></pre>
<p>This prints: <code>2008-11-22</code> which is exactly what I want.</p>
<p>But, I have a list I'm appending this to and then suddenly everything goes "wonky". Here is the code:</p>
<pre><code>import datetime
mylist = []
today = datetime.date.today()
mylist.append(today)
print(mylist)
</code></pre>
<p>This prints the following: </p>
<pre><code>[datetime.date(2008, 11, 22)]
</code></pre>
<p>How can I get just a simple date like <code>2008-11-22</code>?</p>
| [
{
"answer_id": 311635,
"author": "Simon Johnson",
"author_id": 854,
"author_profile": "https://Stackoverflow.com/users/854",
"pm_score": 3,
"selected": false,
"text": "datetime"
},
{
"answer_id": 311636,
"author": "HanClinto",
"author_id": 26933,
"author_profile": "https://Stackoverflow.com/users/26933",
"pm_score": 2,
"selected": false,
"text": "import datetime\n\nmylist = []\ntoday = str(datetime.date.today())\nmylist.append(today)\n\nprint(mylist)\n"
},
{
"answer_id": 311637,
"author": "Igal Serban",
"author_id": 25737,
"author_profile": "https://Stackoverflow.com/users/25737",
"pm_score": 2,
"selected": false,
"text": "mylist.append(str(today))\n"
},
{
"answer_id": 311645,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 6,
"selected": false,
"text": "some_date.strftime('%Y-%m-%d')\n"
},
{
"answer_id": 311655,
"author": "e-satis",
"author_id": 9951,
"author_profile": "https://Stackoverflow.com/users/9951",
"pm_score": 11,
"selected": true,
"text": "print"
},
{
"answer_id": 14320620,
"author": "Daniel Magnusson",
"author_id": 63678,
"author_profile": "https://Stackoverflow.com/users/63678",
"pm_score": 9,
"selected": false,
"text": "import datetime\nprint datetime.datetime.now().strftime(\"%Y-%m-%d %H:%M\")\n"
},
{
"answer_id": 18944849,
"author": "Transformer",
"author_id": 2661703,
"author_profile": "https://Stackoverflow.com/users/2661703",
"pm_score": 8,
"selected": false,
"text": "date"
},
{
"answer_id": 20066760,
"author": "Cees Timmerman",
"author_id": 819417,
"author_profile": "https://Stackoverflow.com/users/819417",
"pm_score": 5,
"selected": false,
"text": ">>> import time\n>>> time.strftime(\"%Y-%m-%d %H:%M\")\n'2013-11-19 09:38'\n"
},
{
"answer_id": 20776958,
"author": "b1_",
"author_id": 1346222,
"author_profile": "https://Stackoverflow.com/users/1346222",
"pm_score": 5,
"selected": false,
"text": "from datetime import datetime, date\n\n\"{:%d.%m.%Y}\".format(datetime.now())\n"
},
{
"answer_id": 26989550,
"author": "Ismail Elouafiq",
"author_id": 4135450,
"author_profile": "https://Stackoverflow.com/users/4135450",
"pm_score": 2,
"selected": false,
"text": "print today"
},
{
"answer_id": 28263165,
"author": "Flame of udun",
"author_id": 2696086,
"author_profile": "https://Stackoverflow.com/users/2696086",
"pm_score": 4,
"selected": false,
"text": "datetime.date.today().isoformat()\n"
},
{
"answer_id": 29179216,
"author": "Mark S.",
"author_id": 4599654,
"author_profile": "https://Stackoverflow.com/users/4599654",
"pm_score": 1,
"selected": false,
"text": "today = datetime.date.today()"
},
{
"answer_id": 29600276,
"author": "rickydj",
"author_id": 3065652,
"author_profile": "https://Stackoverflow.com/users/3065652",
"pm_score": 3,
"selected": false,
"text": "datetime"
},
{
"answer_id": 30148084,
"author": "Raphael Amoedo",
"author_id": 4857050,
"author_profile": "https://Stackoverflow.com/users/4857050",
"pm_score": 1,
"selected": false,
"text": "import date_converter\nmy_date = date_converter.date_to_string(today, '%Y-%m-%d')\n"
},
{
"answer_id": 37902499,
"author": "Adrian Simon",
"author_id": 6483953,
"author_profile": "https://Stackoverflow.com/users/6483953",
"pm_score": 1,
"selected": false,
"text": "from datetime import datetime\nnow = datetime.now()\n\nprint '%s/%s/%s' % (now.year, now.month, now.day)\n"
},
{
"answer_id": 39891095,
"author": "Waqas Ali",
"author_id": 1900645,
"author_profile": "https://Stackoverflow.com/users/1900645",
"pm_score": 5,
"selected": false,
"text": "# convert date time to regular format.\n\nd_date = datetime.datetime.now()\nreg_format_date = d_date.strftime(\"%Y-%m-%d %I:%M:%S %p\")\nprint(reg_format_date)\n\n# some other date formats.\nreg_format_date = d_date.strftime(\"%d %B %Y %I:%M:%S %p\")\nprint(reg_format_date)\nreg_format_date = d_date.strftime(\"%Y-%m-%d %H:%M:%S\")\nprint(reg_format_date)\n"
},
{
"answer_id": 44568378,
"author": "handle",
"author_id": 1619432,
"author_profile": "https://Stackoverflow.com/users/1619432",
"pm_score": 3,
"selected": false,
"text": "datetime"
},
{
"answer_id": 44690784,
"author": "tanmayee",
"author_id": 8118958,
"author_profile": "https://Stackoverflow.com/users/8118958",
"pm_score": 0,
"selected": false,
"text": "import datetime\nimport time\n\nmonths = [\"Unknown\",\"January\",\"Febuary\",\"Marchh\",\"April\",\"May\",\"June\",\"July\",\"August\",\"September\",\"October\",\"November\",\"December\"]\ndatetimeWrite = (time.strftime(\"%d-%m-%Y \"))\ndate = time.strftime(\"%d\")\nmonth= time.strftime(\"%m\")\nchoices = {'01': 'Jan', '02':'Feb','03':'Mar','04':'Apr','05':'May','06': 'Jun','07':'Jul','08':'Aug','09':'Sep','10':'Oct','11':'Nov','12':'Dec'}\nresult = choices.get(month, 'default')\nyear = time.strftime(\"%Y\")\nDate = date+\"-\"+result+\"-\"+year\nprint Date\n"
},
{
"answer_id": 50998625,
"author": "Erix",
"author_id": 5397182,
"author_profile": "https://Stackoverflow.com/users/5397182",
"pm_score": 2,
"selected": false,
"text": "from datetime import date\n\ndef today_in_str_format():\n return str(date.today())\n\nprint (today_in_str_format())\n"
},
{
"answer_id": 52151460,
"author": "Ward Taya",
"author_id": 8816450,
"author_profile": "https://Stackoverflow.com/users/8816450",
"pm_score": 2,
"selected": false,
"text": "import datetime\nstr(datetime.date.today())\n"
},
{
"answer_id": 52685963,
"author": "U12-Forward",
"author_id": 8708364,
"author_profile": "https://Stackoverflow.com/users/8708364",
"pm_score": 0,
"selected": false,
"text": "pandas"
},
{
"answer_id": 56995157,
"author": "Liran H",
"author_id": 2884291,
"author_profile": "https://Stackoverflow.com/users/2884291",
"pm_score": 2,
"selected": false,
"text": ">>> some_date.strftime('%x')\n07/11/2019\n"
},
{
"answer_id": 70152721,
"author": "Domenico Ruggiano",
"author_id": 8551915,
"author_profile": "https://Stackoverflow.com/users/8551915",
"pm_score": 2,
"selected": false,
"text": "strftime()"
},
{
"answer_id": 71293223,
"author": "ntg",
"author_id": 508907,
"author_profile": "https://Stackoverflow.com/users/508907",
"pm_score": 1,
"selected": false,
"text": "utc_now = datetime.now()\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311627",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15250/"
] |
311,630 | <p>I have two entities Foo and Bar with a Many to Many relationship between them.</p>
<p>Let's say there is no semantic argument for why Foo might be "responsible" for the many to many relationship, but we arbitrarily decide that Foo is responsible for the relation (I.e., in NHibernate we would mark Bar as Inverse)</p>
<p>That's all well and good from a DB perspective, but my entity APIs reveal a problem.</p>
<pre><code> // Responsible for the relation
public class Foo
{
List<Bar> Bars = new List<Bar>();
public void AddBar(Bar bar)
{
Bars.Add(bar);
bar.AddFoo(this);
}
}
public class Bar
{
List<Foo> Foos = new List<Foo>();
// This shouldn't exist.
public void AddFoo(Foo foo)
{
Foos.Add(foo);
foo.AddBar(this); // Inf Recursion
}
}
</code></pre>
<p>If we've decided that Foo is responsible for this relationship, how do I update the associated collection in Bar without creating a public Bar.AddFoo() method which shouldn't even exist?</p>
<p>I feel like I should be able to maintain the integrity of my domain model without resorting to having to reload these entities from the DB after an operation such as this.</p>
<p>UPDATE: Code tweak inspired by commenter. </p>
| [
{
"answer_id": 311679,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": -1,
"selected": false,
"text": "public class Foo\n{\n List<Bar> Bars = new List<Bar>();\n\n public void AddBar(Bar bar)\n {\n Bars.Add(bar);\n Bar.AddFoo(bar,this);\n }\n}\n\npublic class Bar\n{\n List<Foo> Foos = new List<Foo>();\n\n // This shouldn't exist.\n public static void AddFoo(Bar bar, Foo foo)\n {\n bar.Foos.Add(foo);\n //foo.AddBar(this); inf recurtion\n }\n}\n"
},
{
"answer_id": 311683,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": false,
"text": "protected Set getEvents() {\n return events;\n}\n\nprotected void setEvents(Set events) {\n this.events = events;\n}\n\npublic void addToEvent(Event event) {\n this.getEvents().add(event);\n event.getParticipants().add(this);\n}\n\npublic void removeFromEvent(Event event) {\n this.getEvents().remove(event);\n event.getParticipants().remove(this);\n}\n"
},
{
"answer_id": 311701,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 2,
"selected": true,
"text": "public class Foo\n{ \n private IList<Bar> Bars {get;set;}\n\n public void AddBar(Bar bar)\n {\n Bars.Add(bar);\n bar.Foos.Add(this);\n }\n}\n\npublic class Bar\n{\n internal IList<Foo> Foos {get;set;}\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311630",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/3285/"
] |
311,644 | <p>I'm loading an html snippet using </p>
<pre><code>$("#TemplateDump").load("Themes/default.template", function() { processTemplate() })
</code></pre>
<p>The html i am loading contains</p>
<pre><code><div>
`hello ##name##, your age is ##age##.
your page is <a href="##website##">here</a>
</div>
</code></pre>
<p>I need to replace the ## placeholders with "joe","112" and "www.whatever.com". Is there a more jquery way of doing this rather than using straight javascript .replace? Are there any place holder replacement plugins around? using .replace in IE on the url placeholder just doesnt work either. Dont know why. By the way, the templates cant be changed.</p>
| [
{
"answer_id": 311679,
"author": "BCS",
"author_id": 1343,
"author_profile": "https://Stackoverflow.com/users/1343",
"pm_score": -1,
"selected": false,
"text": "public class Foo\n{\n List<Bar> Bars = new List<Bar>();\n\n public void AddBar(Bar bar)\n {\n Bars.Add(bar);\n Bar.AddFoo(bar,this);\n }\n}\n\npublic class Bar\n{\n List<Foo> Foos = new List<Foo>();\n\n // This shouldn't exist.\n public static void AddFoo(Bar bar, Foo foo)\n {\n bar.Foos.Add(foo);\n //foo.AddBar(this); inf recurtion\n }\n}\n"
},
{
"answer_id": 311683,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": false,
"text": "protected Set getEvents() {\n return events;\n}\n\nprotected void setEvents(Set events) {\n this.events = events;\n}\n\npublic void addToEvent(Event event) {\n this.getEvents().add(event);\n event.getParticipants().add(this);\n}\n\npublic void removeFromEvent(Event event) {\n this.getEvents().remove(event);\n event.getParticipants().remove(this);\n}\n"
},
{
"answer_id": 311701,
"author": "Ben Scheirman",
"author_id": 3381,
"author_profile": "https://Stackoverflow.com/users/3381",
"pm_score": 2,
"selected": true,
"text": "public class Foo\n{ \n private IList<Bar> Bars {get;set;}\n\n public void AddBar(Bar bar)\n {\n Bars.Add(bar);\n bar.Foos.Add(this);\n }\n}\n\npublic class Bar\n{\n internal IList<Foo> Foos {get;set;}\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311644",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39655/"
] |
311,656 | <p>Do you know any resources that teach to good habits of working in UNIX command line?</p>
<p>EDIT: I don't mean general books about shell or man pages. I mean the things that you can only see watching professionals working with command line. For example when changing frequently between two directories they use "pushd" command, when repeating a command they use "history". I can read about these commands but I want to make it a habit to use them effectively.</p>
| [
{
"answer_id": 311660,
"author": "flolo",
"author_id": 36472,
"author_profile": "https://Stackoverflow.com/users/36472",
"pm_score": 1,
"selected": false,
"text": "bash"
},
{
"answer_id": 311869,
"author": "Will Hartung",
"author_id": 13663,
"author_profile": "https://Stackoverflow.com/users/13663",
"pm_score": 1,
"selected": false,
"text": "cat /tmp/list"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311656",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1692070/"
] |
311,657 | <p>Is there any way to get the time down to the Millisecond in MySQL?</p>
| [
{
"answer_id": 311664,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": true,
"text": "NOW()"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311657",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17560/"
] |
311,662 | <p>I was just wondering if there are any good work-arounds for Deserializing private fields/properties using XmlSerializer.Deserialize() ?</p>
<p>Currently, I Deserialize my XML to a simple disposable type with all public properties, then I load the complex type that has private properties like this:</p>
<pre><code>ComplexType complex = new ComplexType(SimpleType);
</code></pre>
<p>and the constructor of ComplexType looks like this:</p>
<pre><code>public ComplexType(SimpleType simpleType){
this.Property1 = simpleType.Property1;
this.Property2 = simpleType.Property2;
.....
}
</code></pre>
<p>Anyone has a better way of doing this?</p>
| [
{
"answer_id": 311664,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": true,
"text": "NOW()"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311662",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37794/"
] |
311,666 | <p>I am trying to write a unix command line utility that will extract the "application" icon from a Windows Mobile executable. When I look inside the .exe with <a href="http://www.nongnu.org/icoutils/" rel="nofollow noreferrer">wrestool</a> from the icoutils package, I see multiple icon and group_icon resources. I am trying to figure out which icon the Windows Mobile Programs view would choose to display to the end user.</p>
<p>At first, I figured it would be the icon with name 32512 (IDI_APPLICATION), but then I found several Windows Mobile binaries that lacked this icon resource, but sure enough had visible icons in the Programs view.</p>
<p>Is there a simple but correct algorithm? like lowest resource id? Is there another resource in the .exe that tells me what is the application icon? Is there something obvious that I am missing?</p>
<p>Any insight would be appreciated.</p>
| [
{
"answer_id": 311664,
"author": "Greg",
"author_id": 24181,
"author_profile": "https://Stackoverflow.com/users/24181",
"pm_score": 4,
"selected": true,
"text": "NOW()"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311666",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,672 | <p>I've seen a related question on this website regarding a Linux system. I have the same question on a Windows XP OS. I bought a Winchester USB external HD, and found out from technical support that the sleep feature is in the firmware and cannot be turned off. I'm looking for an application that will automatically read/write to that drive periodically to keep that timer resetting (every 5 minutes?). Is anyone aware of a small application for Windows XP that will do that?</p>
<p>Thanks for your help.</p>
| [
{
"answer_id": 311765,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 1,
"selected": false,
"text": "@echo off\n:start\ncopy c:\\windows\\notepad.exe g:\\ (Or whatever your external drive is)\nchoice /N /D Y /T 120 (The 120 is the delay in seconds)\ngoto :start\n"
},
{
"answer_id": 11596813,
"author": "Krehator",
"author_id": 1543362,
"author_profile": "https://Stackoverflow.com/users/1543362",
"pm_score": 2,
"selected": false,
"text": ":start\n@echo off\n@cls\n@echo Keeping USB Drive Awake. Do not close this window!\n@sleep 60\n@dir E: /S /B >E:\\keepawake.txt\n@echo Drive Accessed %date% at %time% >keepawake.txt\ngoto start\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311672",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,677 | <p>can anybody please explain the following c# behaviour? I have written a small console application just to learn about CAS, but I can not seem to understand why the following lines of code work like they do:</p>
<pre><code>string[] myRoles = new string[] { "role1", "role2", "role3" };
GenericIdentity myIdentity = new GenericIdentity("myUsername", "customAuthType");
GenericPrincipal myPrincipal = new GenericPrincipal(myIdentity, myRoles);
System.Threading.Thread.CurrentPrincipal = myPrincipal;
Console.WriteLine(SecurityManager.IsGranted(new PrincipalPermission(null, "role1")));
Console.WriteLine(SecurityManager.IsGranted(new PrincipalPermission(null, "roleX")));
</code></pre>
<p>The output is "true" for both SecurityManager.IsGranted() calls.</p>
<p>If I then add the following lines:</p>
<pre><code> new PrincipalPermission(null, "role1").Demand();
new PrincipalPermission(null, "roleX").Demand();
</code></pre>
<p>the first demand call passes, but the second one (as expected) causes a SecurityException. </p>
<p>Why does not the SecurityManager.IsGranted()-call return false for the "roleX" permission?</p>
| [
{
"answer_id": 312498,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 0,
"selected": false,
"text": "SecurityManager.IsGranted"
},
{
"answer_id": 17082239,
"author": "Kiquenet",
"author_id": 206730,
"author_profile": "https://Stackoverflow.com/users/206730",
"pm_score": 2,
"selected": false,
"text": "bool isGranted = SecurityManager.IsGranted(new SecurityPermission(SecurityPermissionFlag.Infrastructure))\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311677",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,691 | <p>I feel like this is a stupid question because it seems like common sense . . . but no google search I can put together seems to be able to give me the answer! </p>
<p>I know how to get data OUT of a sqlite3 database using the .dump command. But now that I have this ASCII file titled export.sqlite3.sql . . . I can't seem to get it back INTO the database I want. </p>
<p>My goal was to transfer the data I had in one rails app to another so I didn't have to take all sorts of time creating dummy data again . . . so I dumped the data from my first app, got rid of all the CREATE TABLE statements, and made sure my schema on my second app matches . . . now I just have to get it IN there. </p>
<p>Would anyone mind helping me out? And when you find a way, will you tell me what you plugged into the google, 'cause I am beating my head open with a spoon right now over what I thought would be an easy find. </p>
| [
{
"answer_id": 311718,
"author": "Ali Afshar",
"author_id": 28380,
"author_profile": "https://Stackoverflow.com/users/28380",
"pm_score": 7,
"selected": true,
"text": "cat dumpfile.sql | sqlite3 my_database.sqlite\n"
},
{
"answer_id": 494626,
"author": "Noah",
"author_id": 12113,
"author_profile": "https://Stackoverflow.com/users/12113",
"pm_score": 6,
"selected": false,
"text": "sqlite3 my_database.sqlite < export.sqlite3.sql\n"
},
{
"answer_id": 957221,
"author": "James A. Rosen",
"author_id": 1190,
"author_profile": "https://Stackoverflow.com/users/1190",
"pm_score": 2,
"selected": false,
"text": "echo '.read export.sqlite3.sql' | sqlite3 my_database.sqlite3\n"
},
{
"answer_id": 19541608,
"author": "Java Man",
"author_id": 2722799,
"author_profile": "https://Stackoverflow.com/users/2722799",
"pm_score": -1,
"selected": false,
"text": "sqlite3 /home/ubuntu/output.sqlite < /home/ubuntu/input.sql\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311691",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34568/"
] |
311,696 | <p>According to the documentation, the <a href="http://msdn.microsoft.com/en-us/library/zy06z30k.aspx" rel="noreferrer"><code>decimal.Round</code></a> method uses a round-to-even algorithm which is not common for most applications. So I always end up writing a custom function to do the more natural round-half-up algorithm:</p>
<pre><code>public static decimal RoundHalfUp(this decimal d, int decimals)
{
if (decimals < 0)
{
throw new ArgumentException("The decimals must be non-negative",
"decimals");
}
decimal multiplier = (decimal)Math.Pow(10, decimals);
decimal number = d * multiplier;
if (decimal.Truncate(number) < number)
{
number += 0.5m;
}
return decimal.Round(number) / multiplier;
}
</code></pre>
<p>Does anybody know the reason behind this framework design decision?</p>
<p>Is there any built-in implementation of the round-half-up algorithm into the framework? Or maybe some unmanaged Windows API?</p>
<p>It could be misleading for beginners that simply write <code>decimal.Round(2.5m, 0)</code> expecting 3 as a result but getting 2 instead.</p>
| [
{
"answer_id": 311707,
"author": "Michael Stum",
"author_id": 91,
"author_profile": "https://Stackoverflow.com/users/91",
"pm_score": 7,
"selected": false,
"text": "Math.Round"
},
{
"answer_id": 6562018,
"author": "Ostemar",
"author_id": 106649,
"author_profile": "https://Stackoverflow.com/users/106649",
"pm_score": 9,
"selected": false,
"text": "MidpointRounding"
},
{
"answer_id": 43030202,
"author": "Omid Sadeghi",
"author_id": 7054090,
"author_profile": "https://Stackoverflow.com/users/7054090",
"pm_score": 0,
"selected": false,
"text": "decimal.Round(2.5m, 0,MidpointRounding.AwayFromZero)\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311696",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29407/"
] |
311,703 | <p>I am trying to test the likelihood that a particular clustering of data has occurred by chance. A robust way to do this is Monte Carlo simulation, in which the associations between data and groups are randomly reassigned a large number of times (e.g. 10,000), and a metric of clustering is used to compare the actual data with the simulations to determine a p value.</p>
<p>I've got most of this working, with pointers mapping the grouping to the data elements, so I plan to randomly reassign pointers to data. THE QUESTION: what is a fast way to sample without replacement, so that every pointer is randomly reassigned in the replicate data sets?</p>
<p>For example (these data are just a simplified example):</p>
<blockquote>
<p>Data (n=12 values) - Group A: 0.1, 0.2, 0.4 / Group B: 0.5, 0.6, 0.8 / Group C: 0.4, 0.5 / Group D: 0.2, 0.2, 0.3, 0.5</p>
</blockquote>
<p>For each replicate data set, I would have the same cluster sizes (A=3, B=3, C=2, D=4) and data values, but would reassign the values to the clusters.</p>
<p>To do this, I could generate random numbers in the range 1-12, assign the first element of group A, then generate random numbers in the range 1-11 and assign the second element in group A, and so on. The pointer reassignment is fast, and I will have pre-allocated all data structures, but the sampling without replacement seems like a problem that might have been solved many times before.</p>
<p>Logic or pseudocode preferred.</p>
| [
{
"answer_id": 311716,
"author": "John D. Cook",
"author_id": 25188,
"author_profile": "https://Stackoverflow.com/users/25188",
"pm_score": 5,
"selected": false,
"text": "void SampleWithoutReplacement\n(\n int populationSize, // size of set sampling from\n int sampleSize, // size of each sample\n vector<int> & samples // output, zero-offset indicies to selected items\n)\n{\n // Use Knuth's variable names\n int& n = sampleSize;\n int& N = populationSize;\n\n int t = 0; // total input records dealt with\n int m = 0; // number of items selected so far\n double u;\n\n while (m < n)\n {\n u = GetUniform(); // call a uniform(0,1) random number generator\n\n if ( (N - t)*u >= n - m )\n {\n t++;\n }\n else\n {\n samples[m] = t;\n t++; m++;\n }\n }\n}\n"
},
{
"answer_id": 25179870,
"author": "Alessandro Jacopson",
"author_id": 15485,
"author_profile": "https://Stackoverflow.com/users/15485",
"pm_score": 3,
"selected": false,
"text": "#include <random>\n#include <vector>\n\n// John D. Cook, https://stackoverflow.com/a/311716/15485\nvoid SampleWithoutReplacement\n(\n int populationSize, // size of set sampling from\n int sampleSize, // size of each sample\n std::vector<int> & samples // output, zero-offset indicies to selected items\n)\n{\n // Use Knuth's variable names\n int& n = sampleSize;\n int& N = populationSize;\n\n int t = 0; // total input records dealt with\n int m = 0; // number of items selected so far\n\n std::default_random_engine re;\n std::uniform_real_distribution<double> dist(0,1);\n\n while (m < n)\n {\n double u = dist(re); // call a uniform(0,1) random number generator\n\n if ( (N - t)*u >= n - m )\n {\n t++;\n }\n else\n {\n samples[m] = t;\n t++; m++;\n }\n }\n}\n\n#include <iostream>\nint main(int,char**)\n{\n const size_t sz = 10;\n std::vector< int > samples(sz);\n SampleWithoutReplacement(10*sz,sz,samples);\n for (size_t i = 0; i < sz; i++ ) {\n std::cout << samples[i] << \"\\t\";\n }\n\n return 0;\n}\n"
},
{
"answer_id": 30213994,
"author": "bluenote10",
"author_id": 1804173,
"author_profile": "https://Stackoverflow.com/users/1804173",
"pm_score": 2,
"selected": false,
"text": "iterator uniqueRandomValuesBelow*(N, M: int) =\n ## Returns a total of M unique random values i with 0 <= i < N\n ## These indices can be used to construct e.g. a random sample without replacement\n assert(M <= N)\n\n var t = 0 # total input records dealt with\n var m = 0 # number of items selected so far\n\n while (m < M):\n let u = random(1.0) # call a uniform(0,1) random number generator\n\n # meaning of the following terms:\n # (N - t) is the total number of remaining draws left (initially just N)\n # (M - m) is the number how many of these remaining draw must be positive (initially just M)\n # => Probability for next draw = (M-m) / (N-t)\n # i.e.: (required positive draws left) / (total draw left)\n #\n # This is implemented by the inequality expression below:\n # - the larger (M-m), the larger the probability of a positive draw\n # - for (N-t) == (M-m), the term on the left is always smaller => we will draw 100%\n # - for (N-t) >> (M-m), we must get a very small u\n #\n # example: (N-t) = 7, (M-m) = 5\n # => we draw the next with prob 5/7\n # lets assume the draw fails\n # => t += 1 => (N-t) = 6\n # => we draw the next with prob 5/6\n # lets assume the draw succeeds\n # => t += 1, m += 1 => (N-t) = 5, (M-m) = 4\n # => we draw the next with prob 4/5\n # lets assume the draw fails\n # => t += 1 => (N-t) = 4\n # => we draw the next with prob 4/4, i.e.,\n # we will draw with certainty from now on\n # (in the next steps we get prob 3/3, 2/2, ...)\n if (N - t)*u >= (M - m).toFloat: # this is essentially a draw with P = (M-m) / (N-t)\n # no draw -- happens mainly for (N-t) >> (M-m) and/or high u\n t += 1\n else:\n # draw t -- happens when (M-m) gets large and/or low u\n yield t # this is where we output an index, can be used to sample\n t += 1\n m += 1\n\n# example use\nfor i in uniqueRandomValuesBelow(100, 5):\n echo i\n"
},
{
"answer_id": 46807110,
"author": "Pavel Ruzankin",
"author_id": 8794687,
"author_profile": "https://Stackoverflow.com/users/8794687",
"pm_score": 2,
"selected": false,
"text": "# The Tree growing algorithm for uniform sampling without replacement\n# by Pavel Ruzankin \nquicksample = function (n,size)\n# n - the number of items to choose from\n# size - the sample size\n{\n s=as.integer(size)\n if (s>n) {\n stop(\"Sample size is greater than the number of items to choose from\")\n }\n # upv=integer(s) #level up edge is pointing to\n leftv=integer(s) #left edge is poiting to; must be filled with zeros\n rightv=integer(s) #right edge is pointig to; must be filled with zeros\n samp=integer(s) #the sample\n ordn=integer(s) #relative ordinal number\n\n ordn[1L]=1L #initial value for the root vertex\n samp[1L]=sample(n,1L) \n if (s > 1L) for (j in 2L:s) {\n curn=sample(n-j+1L,1L) #current number sampled\n curordn=0L #currend ordinal number\n v=1L #current vertice\n from=1L #how have come here: 0 - by left edge, 1 - by right edge\n repeat {\n curordn=curordn+ordn[v]\n if (curn+curordn>samp[v]) { #going down by the right edge\n if (from == 0L) {\n ordn[v]=ordn[v]-1L\n }\n if (rightv[v]!=0L) {\n v=rightv[v]\n from=1L\n } else { #creating a new vertex\n samp[j]=curn+curordn\n ordn[j]=1L\n # upv[j]=v\n rightv[v]=j\n break\n }\n } else { #going down by the left edge\n if (from==1L) {\n ordn[v]=ordn[v]+1L\n }\n if (leftv[v]!=0L) {\n v=leftv[v]\n from=0L\n } else { #creating a new vertex\n samp[j]=curn+curordn-1L\n ordn[j]=-1L\n # upv[j]=v\n leftv[v]=j\n break\n }\n }\n }\n }\n return(samp) \n}\n"
},
{
"answer_id": 67850443,
"author": "Paul Crowley",
"author_id": 123045,
"author_profile": "https://Stackoverflow.com/users/123045",
"pm_score": 1,
"selected": false,
"text": "randbelow(i)"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311703",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18484/"
] |
311,706 | <p>I recently completed development of a mid-traficked(?) website (peak 60k hits/hour), however, the site only needs to be updated once a minute - and achieving the required performance can be summed up by a single word: "caching".</p>
<p>For a site like SO where the data feeding the site changes <em>all the time</em>, I would imagine a different approach is required. </p>
<p>Page cache times presumably need to be short or non-existent, and updates need to be propogated across all the webservers very rapidly to keep all users up to date. </p>
<p>My guess is that you'd need a distributed cache to control the serving of data and pages that is updated on the order of a few seconds, with perhaps a distributed cache above the database to mediate writes?</p>
<p>Can those more experienced that I outline some of the key architectural/design principles they employ to ensure highly interactive websites like SO are performant? </p>
| [
{
"answer_id": 311716,
"author": "John D. Cook",
"author_id": 25188,
"author_profile": "https://Stackoverflow.com/users/25188",
"pm_score": 5,
"selected": false,
"text": "void SampleWithoutReplacement\n(\n int populationSize, // size of set sampling from\n int sampleSize, // size of each sample\n vector<int> & samples // output, zero-offset indicies to selected items\n)\n{\n // Use Knuth's variable names\n int& n = sampleSize;\n int& N = populationSize;\n\n int t = 0; // total input records dealt with\n int m = 0; // number of items selected so far\n double u;\n\n while (m < n)\n {\n u = GetUniform(); // call a uniform(0,1) random number generator\n\n if ( (N - t)*u >= n - m )\n {\n t++;\n }\n else\n {\n samples[m] = t;\n t++; m++;\n }\n }\n}\n"
},
{
"answer_id": 25179870,
"author": "Alessandro Jacopson",
"author_id": 15485,
"author_profile": "https://Stackoverflow.com/users/15485",
"pm_score": 3,
"selected": false,
"text": "#include <random>\n#include <vector>\n\n// John D. Cook, https://stackoverflow.com/a/311716/15485\nvoid SampleWithoutReplacement\n(\n int populationSize, // size of set sampling from\n int sampleSize, // size of each sample\n std::vector<int> & samples // output, zero-offset indicies to selected items\n)\n{\n // Use Knuth's variable names\n int& n = sampleSize;\n int& N = populationSize;\n\n int t = 0; // total input records dealt with\n int m = 0; // number of items selected so far\n\n std::default_random_engine re;\n std::uniform_real_distribution<double> dist(0,1);\n\n while (m < n)\n {\n double u = dist(re); // call a uniform(0,1) random number generator\n\n if ( (N - t)*u >= n - m )\n {\n t++;\n }\n else\n {\n samples[m] = t;\n t++; m++;\n }\n }\n}\n\n#include <iostream>\nint main(int,char**)\n{\n const size_t sz = 10;\n std::vector< int > samples(sz);\n SampleWithoutReplacement(10*sz,sz,samples);\n for (size_t i = 0; i < sz; i++ ) {\n std::cout << samples[i] << \"\\t\";\n }\n\n return 0;\n}\n"
},
{
"answer_id": 30213994,
"author": "bluenote10",
"author_id": 1804173,
"author_profile": "https://Stackoverflow.com/users/1804173",
"pm_score": 2,
"selected": false,
"text": "iterator uniqueRandomValuesBelow*(N, M: int) =\n ## Returns a total of M unique random values i with 0 <= i < N\n ## These indices can be used to construct e.g. a random sample without replacement\n assert(M <= N)\n\n var t = 0 # total input records dealt with\n var m = 0 # number of items selected so far\n\n while (m < M):\n let u = random(1.0) # call a uniform(0,1) random number generator\n\n # meaning of the following terms:\n # (N - t) is the total number of remaining draws left (initially just N)\n # (M - m) is the number how many of these remaining draw must be positive (initially just M)\n # => Probability for next draw = (M-m) / (N-t)\n # i.e.: (required positive draws left) / (total draw left)\n #\n # This is implemented by the inequality expression below:\n # - the larger (M-m), the larger the probability of a positive draw\n # - for (N-t) == (M-m), the term on the left is always smaller => we will draw 100%\n # - for (N-t) >> (M-m), we must get a very small u\n #\n # example: (N-t) = 7, (M-m) = 5\n # => we draw the next with prob 5/7\n # lets assume the draw fails\n # => t += 1 => (N-t) = 6\n # => we draw the next with prob 5/6\n # lets assume the draw succeeds\n # => t += 1, m += 1 => (N-t) = 5, (M-m) = 4\n # => we draw the next with prob 4/5\n # lets assume the draw fails\n # => t += 1 => (N-t) = 4\n # => we draw the next with prob 4/4, i.e.,\n # we will draw with certainty from now on\n # (in the next steps we get prob 3/3, 2/2, ...)\n if (N - t)*u >= (M - m).toFloat: # this is essentially a draw with P = (M-m) / (N-t)\n # no draw -- happens mainly for (N-t) >> (M-m) and/or high u\n t += 1\n else:\n # draw t -- happens when (M-m) gets large and/or low u\n yield t # this is where we output an index, can be used to sample\n t += 1\n m += 1\n\n# example use\nfor i in uniqueRandomValuesBelow(100, 5):\n echo i\n"
},
{
"answer_id": 46807110,
"author": "Pavel Ruzankin",
"author_id": 8794687,
"author_profile": "https://Stackoverflow.com/users/8794687",
"pm_score": 2,
"selected": false,
"text": "# The Tree growing algorithm for uniform sampling without replacement\n# by Pavel Ruzankin \nquicksample = function (n,size)\n# n - the number of items to choose from\n# size - the sample size\n{\n s=as.integer(size)\n if (s>n) {\n stop(\"Sample size is greater than the number of items to choose from\")\n }\n # upv=integer(s) #level up edge is pointing to\n leftv=integer(s) #left edge is poiting to; must be filled with zeros\n rightv=integer(s) #right edge is pointig to; must be filled with zeros\n samp=integer(s) #the sample\n ordn=integer(s) #relative ordinal number\n\n ordn[1L]=1L #initial value for the root vertex\n samp[1L]=sample(n,1L) \n if (s > 1L) for (j in 2L:s) {\n curn=sample(n-j+1L,1L) #current number sampled\n curordn=0L #currend ordinal number\n v=1L #current vertice\n from=1L #how have come here: 0 - by left edge, 1 - by right edge\n repeat {\n curordn=curordn+ordn[v]\n if (curn+curordn>samp[v]) { #going down by the right edge\n if (from == 0L) {\n ordn[v]=ordn[v]-1L\n }\n if (rightv[v]!=0L) {\n v=rightv[v]\n from=1L\n } else { #creating a new vertex\n samp[j]=curn+curordn\n ordn[j]=1L\n # upv[j]=v\n rightv[v]=j\n break\n }\n } else { #going down by the left edge\n if (from==1L) {\n ordn[v]=ordn[v]+1L\n }\n if (leftv[v]!=0L) {\n v=leftv[v]\n from=0L\n } else { #creating a new vertex\n samp[j]=curn+curordn-1L\n ordn[j]=-1L\n # upv[j]=v\n leftv[v]=j\n break\n }\n }\n }\n }\n return(samp) \n}\n"
},
{
"answer_id": 67850443,
"author": "Paul Crowley",
"author_id": 123045,
"author_profile": "https://Stackoverflow.com/users/123045",
"pm_score": 1,
"selected": false,
"text": "randbelow(i)"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311706",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38522/"
] |
311,710 | <p>I have a List< int[] > myList, where I know that all the int[] arrays are the same length - for the sake of argument, let us say I have 500 arrays, each is 2048 elements long. I'd like to sum all 500 of these arrays, to give me a single array, 2048 elements long, where each element is the sum of all the same positions in all the other arrays.</p>
<p>Obviously this is trivial in imperative code:</p>
<pre><code>int[] sums = new int[myList[0].Length];
foreach(int[] array in myList)
{
for(int i = 0; i < sums.Length; i++)
{
sums[i] += array[i];
}
}
</code></pre>
<p>But I was wondering if there was a nice Linq or Enumerable.xxx technique?</p>
| [
{
"answer_id": 311720,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 2,
"selected": false,
"text": "var results = myList.SelectMany(array => array.Select(\n (value, index) => new { value, index })\n .Aggregate(new int[myList[0].Length],\n (result, item) => { result[item.index] += value; return result; });\n"
},
{
"answer_id": 311739,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 5,
"selected": true,
"text": "var sums = Enumerable.Range(0, myList[0].Length)\n .Select(i => myList.Select(\n nums => nums[i]\n ).Sum()\n );\n"
},
{
"answer_id": 311808,
"author": "Neil Hewitt",
"author_id": 22178,
"author_profile": "https://Stackoverflow.com/users/22178",
"pm_score": 1,
"selected": false,
"text": "int[] sums = \n Enumerable.Range(0, listOfArrays[0].Length-1).\n Select(sumTotal => \n Enumerable.Range(0, listOfArrays.Count-1).\n Aggregate((total, listIndex) => \n total += listOfArrays[listIndex][sumTotal])).ToArray();\n"
},
{
"answer_id": 311830,
"author": "Konrad Rudolph",
"author_id": 1968,
"author_profile": "https://Stackoverflow.com/users/1968",
"pm_score": 0,
"selected": false,
"text": "var result = xs.Aggregate(\n (a, b) => Enumerable.Range(0, a.Length).Select(i => a[i] + b[i]).ToArray()\n);\n"
},
{
"answer_id": 311863,
"author": "Bryan Watts",
"author_id": 37815,
"author_profile": "https://Stackoverflow.com/users/37815",
"pm_score": 2,
"selected": false,
"text": "var myList = new List<int[]>\n{\n new int[] { 1, 2, 3, 4, 5, 6, 7, 8, 9 },\n new int[] { 10, 20, 30, 40, 50, 60, 70, 80, 90 }\n};\n\nvar sums =\n from array in myList\n from valueIndex in array.Select((value, index) => new { Value = value, Index = index })\n group valueIndex by valueIndex.Index into indexGroups\n select indexGroups.Select(indexGroup => indexGroup.Value).Sum()\n\nforeach(var sum in sums)\n{\n Console.WriteLine(sum);\n}\n\n// Prints:\n//\n// 11\n// 22\n// 33\n// 44\n// 55\n// 66\n// 77\n// 88\n// 99\n"
},
{
"answer_id": 311885,
"author": "jyoung",
"author_id": 14841,
"author_profile": "https://Stackoverflow.com/users/14841",
"pm_score": 1,
"selected": false,
"text": "var colSums = \n from col in array.Pivot()\n select col.Sum();\n"
},
{
"answer_id": 56828323,
"author": "DDRider62",
"author_id": 941768,
"author_profile": "https://Stackoverflow.com/users/941768",
"pm_score": 0,
"selected": false,
"text": "List<int[]> myListOfIntArrays = PopulateListOfArraysOf100Ints();\nint[] totals = new int[100];\nint[] allArraysSum = myListOfIntArrays.Aggregate(\n totals,\n (arrCumul, arrItem) => arrCumul.Zip(arrItem, (a, b) => a + b))\n .ToArray();\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311710",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/987/"
] |
311,725 | <p>I have a table that has, in essence, this structure:</p>
<pre> key value
------ ------
2 val1
3 val2
5 val3</pre>
<p>The keys are sequential integers from 1 up to (currently) 1 million, increasing by several thousand each day. Gaps in the keys occur when records have been deleted.</p>
<p>I'm looking for an SQL query that returns this:</p>
<pre> key value
------ ------
1
2 val1
3 val2
4
5 val3</pre>
<p>I can see how to do this with joining to a second table that has a complete list of keys. However I'd prefer a solution that uses standard SQL (no stored procedures or a second table of keys), and that will work no matter what the upper value of the key is. </p>
| [
{
"answer_id": 311746,
"author": "Bill Karwin",
"author_id": 20860,
"author_profile": "https://Stackoverflow.com/users/20860",
"pm_score": 2,
"selected": false,
"text": "CREATE TABLE n (d NUMERIC);\nINSERT INTO n VALUES (0), (1), (2), (3), (4), (5), (6), (7), (8), (9);\n"
},
{
"answer_id": 311767,
"author": "Martin",
"author_id": 37367,
"author_profile": "https://Stackoverflow.com/users/37367",
"pm_score": 0,
"selected": false,
"text": "create table seq ( i int primary key, v varchar(10) );\n\ninsert into seq values( 2, 'val1' ), (3, 'val2' ), (5, 'val3' );\n\n\nselect s.i-1 from seq s left join seq m on m.i = (s.i -1) where m.i is null;\n\n+-------+\n| s.i-1 |\n+-------+\n| 1 |\n| 4 |\n+-------+\n\n\nselect s.i+1 from seq s left join seq m on m.i = (s.i +1) where m.i is null;\n+-------+\n| s.i+1 |\n+-------+\n| 4 |\n| 6 |\n+-------+\n"
},
{
"answer_id": 311777,
"author": "Haoest",
"author_id": 10088,
"author_profile": "https://Stackoverflow.com/users/10088",
"pm_score": 0,
"selected": false,
"text": "WITH range (num) AS (\nSELECT 1 -- use your own lowerbound\nUNION ALL\nSELECT 1 + num FROM range\nWHERE num < 10 -- use your own upper bound\n)\nSELECT r.num, y.* FROM range r left join yourtable y\non r.num = y.id\n"
},
{
"answer_id": 311814,
"author": "EvilTeach",
"author_id": 7734,
"author_profile": "https://Stackoverflow.com/users/7734",
"pm_score": 1,
"selected": false,
"text": "select level\nfrom dual\nconnect by level <= 1000000\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311725",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39965/"
] |
311,730 | <p>I need a simple window with three input boxes and three labels (login name, password, and server node) and a button to execute the script. I do not want any third party programs that need to be installed on Windows. If it can be installed on Cygwin that would be great.</p>
| [
{
"answer_id": 311770,
"author": "Bryan Oakley",
"author_id": 7432,
"author_profile": "https://Stackoverflow.com/users/7432",
"pm_score": 3,
"selected": true,
"text": "package require Tk 8.5\nproc main {} {\n ttk::frame .f\n ttk::label .l1 -text \"Username:\" -anchor e\n ttk::label .l2 -text \"Password:\" -anchor e\n ttk::label .l3 -text \"Server:\" -anchor e\n ttk::entry .e1 -textvariable data(username)\n ttk::entry .e2 -textvariable data(password) -show *\n ttk::entry .e3 -textvariable data(server)\n ttk::button .b1 -text \"Submit\" -command run\n\n grid .l1 .e1 -sticky ew -in .f -padx 4\n grid .l2 .e2 -sticky ew -in .f -padx 4\n grid .l3 .e3 -sticky ew -in .f -padx 4\n grid x .b1 -sticky e -row 4 -in .f -padx 4 -pady 4\n\n grid rowconfigure .f 3 -weight 1\n grid columnconfigure .f 1 -weight 1\n\n pack .f -side top -fill both -expand true\n\n focus .e1\n}\n\nproc run {} {\n global data\n puts \"username: $data(username)\"\n puts \"password: $data(password)\"\n puts \"server: $data(server)\"\n}\n\nmain\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311730",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34531/"
] |
311,734 | <p>I am creating a custom WPF control that let's say for simplicity sake has a vertical stack panel with a "title" TextBlock, followed by a ContentPresenter. I want the font size for the "title" to be 5 Points LARGER than the size used in the content, which is inherited by whatever container the user places this control in.</p>
<p>How can I specify a font size in the control template for the header element using a relative value without exposing a property like "TitleFontSize" to the user? I want do "add 5".</p>
<p>I tried using a ScaleTransform on the header text block with mixed results (the text block scaled fine but the orientation was modified - I had the text right-justified and it moved "off the control" area when scaled). Also, I am not sure if scale transform would be approprite here. </p>
| [
{
"answer_id": 311774,
"author": "Bill",
"author_id": 17595,
"author_profile": "https://Stackoverflow.com/users/17595",
"pm_score": 4,
"selected": true,
"text": "public class FontSizeConverter : IValueConverter\n{\n\n #region IValueConverter Members\n\n public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n return (double)value + 12.0;\n }\n\n public object ConvertBack(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture)\n {\n return (double)value - 12.0;\n }\n\n #endregion\n}\n"
},
{
"answer_id": 2189445,
"author": "Thomas",
"author_id": 264921,
"author_profile": "https://Stackoverflow.com/users/264921",
"pm_score": 4,
"selected": false,
"text": "public class MathConverter : IValueConverter\n{\n public object Convert( object value, Type targetType, object parameter, CultureInfo culture )\n {\n return (double)value + double.Parse( parameter.ToString() );\n }\n\n public object ConvertBack( object value, Type targetType, object parameter, CultureInfo culture )\n {\n return null;\n }\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311734",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17595/"
] |
311,735 | <p>i need to convert pointers to long (SendMessage())
and i want to safely check if the variable is correct on the otherside. So i was thinking of doing dynamic_cast but that wont work on classes that are not virtual. Then i thought of doing typeid but that will work until i pass a derived var as its base.</p>
<p>Is there any way to check if the pointer is what i am expecting during runtime?
Is there a way i can use typeid to see if a pointer is a type derived from a particular base?</p>
| [
{
"answer_id": 311758,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 0,
"selected": false,
"text": "UINT_PTR"
},
{
"answer_id": 311764,
"author": "Rob Kennedy",
"author_id": 33732,
"author_profile": "https://Stackoverflow.com/users/33732",
"pm_score": 2,
"selected": true,
"text": "long"
},
{
"answer_id": 311843,
"author": "activout.se",
"author_id": 20444,
"author_profile": "https://Stackoverflow.com/users/20444",
"pm_score": 2,
"selected": false,
"text": "SendMessage()"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311735",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,763 | <p>I have a friend who is finishing up his masters degree in aerospace engineering. For his final project, he is on a small team tasked with writing a program for tracking weather balloons, rockets and satellites. The program receives input from a GPS device, does calculations with the data, and uses the results of those calculations to control a series of motors designed to orientate a directional communication antenna, so the balloon, rocket or satellite always stays in focus.</p>
<p>Though somewhat of a (eternal) beginner myself, I have more programming experience than my friend. So when he asked me for advice, I convinced him to write the program in Python, my language of choice.</p>
<p>At this point in the project, we are working on the code that parses the input from the GPS device. Here is some example input, with the data we need to extract in bold:</p>
<p>$GPRMC,092204.999,<strong>4250.5589,S,14718.5084,E</strong>,1,12,24.4,<strong>89.6</strong>,M,,,0000*1F
$GPRMC,093345.679,<strong>4234.7899,N,11344.2567,W</strong>,3,02,24.5,<strong>1000.23</strong>,M,,,0000*1F
$GPRMC,044584.936,<strong>1276.5539,N,88734.1543,E</strong>,2,04,33.5,<strong>600.323</strong>,M,,,*00
$GPRMC,199304.973,<strong>3248.7780,N,11355.7832,W</strong>,1,06,02.2,<strong>25722.5</strong>,M,,,*00
$GPRMC,066487.954,<strong>4572.0089,S,45572.3345,W</strong>,3,09,15.0,<strong>35000.00</strong>,M,,,*1F</p>
<p>Here is some further explanation of the data:</p>
<blockquote>
<p>"I looks like I'll need five things
out of every line. And bear in mind
that any one of these area's may be
empty. Meaning there will be just two
commas right next to each other. Such
as ',,,' There are two fields that may
be full at any time. Some of them only
have two or three options that they
may be but I don't think I should be
counting on that."</p>
</blockquote>
<p>Two days ago my friend was able to acquire the full log from the GPS receiver used to track a recent weather balloon launch. The data is quite long, so I put it all in <a href="http://pastebin.com/f5f5cf9ab" rel="noreferrer">this pastebin</a>.</p>
<p>I am still rather new with regular expressions myself, so I am looking for some assistance.</p>
| [
{
"answer_id": 311769,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 3,
"selected": false,
"text": ">>> line=\"$GPRMC,092204.999,4250.5589,S,14718.5084,E,1,12,24.4,89.6,M,,,0000*1F \"\n>>> line.split(',')\n['$GPRMC', '092204.999', '4250.5589', 'S', '14718.5084', 'E', '1', '12', '24.4', '89.6', 'M', '', '', '0000*1F ']\n>>> \n"
},
{
"answer_id": 311778,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 5,
"selected": true,
"text": ">>> line = \"$GPRMC,199304.973,3248.7780,N,11355.7832,W,1,06,02.2,25722.5,M,,,*00\"\n>>> line = line.split(\",\")\n>>> neededData = (float(line[2]), line[3], float(line[4]), line[5], float(line[9]))\n>>> print neededData\n(3248.7779999999998, 'N', 11355.7832, 'W', 25722.5)\n"
},
{
"answer_id": 311880,
"author": "Brian C. Lane",
"author_id": 27461,
"author_profile": "https://Stackoverflow.com/users/27461",
"pm_score": 2,
"selected": false,
"text": "def check_nmea0183(s):\n \"\"\"\n Check a string to see if it is a valid NMEA 0183 sentence\n \"\"\"\n if s[0] != '$':\n return False\n if s[-3] != '*':\n return False\n\n checksum = 0\n for c in s[1:-3]:\n checksum ^= ord(c)\n\n if int(s[-2:],16) != checksum:\n return False\n\n return True\n"
},
{
"answer_id": 313431,
"author": "Jerub",
"author_id": 14648,
"author_profile": "https://Stackoverflow.com/users/14648",
"pm_score": 3,
"selected": false,
"text": ">>> import csv\n>>> for line in csv.reader(open('/var/tmp/sampledata')):\n... print line\n['$GPRMC', '092204.999', '**4250.5589', 'S', '14718.5084', 'E**', '1', '12', '24.4', '**89.6**', 'M', '', '', '0000\\\\*1F']\n['$GPRMC', '093345.679', '**4234.7899', 'N', '11344.2567', 'W**', '3', '02', '24.5', '**1000.23**', 'M', '', '', '0000\\\\*1F']\n['$GPRMC', '044584.936', '**1276.5539', 'N', '88734.1543', 'E**', '2', '04', '33.5', '**600.323**', 'M', '', '', '\\\\*00']\n['$GPRMC', '199304.973', '**3248.7780', 'N', '11355.7832', 'W**', '1', '06', '02.2', '**25722.5**', 'M', '', '', '\\\\*00']\n['$GPRMC', '066487.954', '**4572.0089', 'S', '45572.3345', 'W**', '3', '09', '15.0', '**35000.00**', 'M', '', '', '\\\\*1F']\n"
},
{
"answer_id": 5203090,
"author": "PaulMcG",
"author_id": 165216,
"author_profile": "https://Stackoverflow.com/users/165216",
"pm_score": 2,
"selected": false,
"text": "\"\"\"\n Parse NMEA 0183 codes for GPS data\n http://en.wikipedia.org/wiki/NMEA_0183\n\n (data formats from http://www.gpsinformation.org/dale/nmea.htm)\n\"\"\"\nfrom pyparsing import *\n\nlead = \"$\"\ncode = Word(alphas.upper(),exact=5)\nend = \"*\"\nCOMMA = Suppress(',')\ncksum = Word(hexnums,exact=2).setParseAction(lambda t:int(t[0],16))\n\n# define basic data value forms, and attach conversion actions\nword = Word(alphanums)\nN,S,E,W = map(Keyword,\"NSEW\")\ninteger = Regex(r\"-?\\d+\").setParseAction(lambda t:int(t[0]))\nreal = Regex(r\"-?\\d+\\.\\d*\").setParseAction(lambda t:float(t[0]))\ntimestamp = Regex(r\"\\d{2}\\d{2}\\d{2}\\.\\d+\")\ntimestamp.setParseAction(lambda t: t[0][:2]+':'+t[0][2:4]+':'+t[0][4:])\ndef lonlatConversion(t):\n t[\"deg\"] = int(t.deg)\n t[\"min\"] = float(t.min)\n t[\"value\"] = ((t.deg + t.min/60.0) \n * {'N':1,'S':-1,'':1}[t.ns] \n * {'E':1,'W':-1,'':1}[t.ew])\nlat = Regex(r\"(?P<deg>\\d{2})(?P<min>\\d{2}\\.\\d+),(?P<ns>[NS])\").setParseAction(lonlatConversion)\nlon = Regex(r\"(?P<deg>\\d{3})(?P<min>\\d{2}\\.\\d+),(?P<ew>[EW])\").setParseAction(lonlatConversion)\n\n# define expression for a complete data record\nvalue = timestamp | Group(lon) | Group(lat) | real | integer | N | S | E | W | word\nitem = lead + code(\"code\") + COMMA + delimitedList(Optional(value,None))(\"datafields\") + end + cksum(\"cksum\")\n\n\ndef parseGGA(tokens):\n keys = \"time lat lon qual numsats horiz_dilut alt _ geoid_ht _ last_update_secs stnid\".split()\n for k,v in zip(keys, tokens.datafields):\n if k != '_':\n tokens[k] = v\n #~ print tokens.dump()\n\ndef parseGSA(tokens):\n keys = \"auto_manual _3dfix prn prn prn prn prn prn prn prn prn prn prn prn pdop hdop vdop\".split()\n tokens[\"prn\"] = []\n for k,v in zip(keys, tokens.datafields):\n if k != 'prn':\n tokens[k] = v\n else:\n if v is not None:\n tokens[k].append(v)\n #~ print tokens.dump()\n\ndef parseRMC(tokens):\n keys = \"time active_void lat lon speed track_angle date mag_var _ signal_integrity\".split()\n for k,v in zip(keys, tokens.datafields):\n if k != '_':\n if k == 'date' and v is not None:\n v = \"%06d\" % v\n tokens[k] = '20%s/%s/%s' % (v[4:],v[2:4],v[:2])\n else:\n tokens[k] = v\n #~ print tokens.dump()\n\n\n# process sample data\ndata = open(\"gpsstream.txt\").read().expandtabs()\n\ncount = 0\nfor i,s,e in item.scanString(data):\n # use checksum to validate input \n linebody = data[s+1:e-3]\n checksum = reduce(lambda a,b:a^b, map(ord, linebody))\n if i.cksum != checksum:\n continue\n count += 1\n\n # parse out specific data fields, depending on code field\n fn = {'GPGGA' : parseGGA, \n 'GPGSA' : parseGSA,\n 'GPRMC' : parseRMC,}[i.code]\n fn(i)\n\n # print out time/position/speed values\n if i.code == 'GPRMC':\n print \"%s %8.3f %8.3f %4d\" % (i.time, i.lat.value, i.lon.value, i.speed or 0) \n\n\nprint count\n"
},
{
"answer_id": 7214844,
"author": "jbdupont",
"author_id": 915511,
"author_profile": "https://Stackoverflow.com/users/915511",
"pm_score": 1,
"selected": false,
"text": "p = int(v[4:])\nprint \"p = \", p\nif p > 70:\n tokens[k] = '19%s/%s/%s' % (v[4:],v[2:4],v[:2])\nelse:\n tokens[k] = '20%s/%s/%s' % (v[4:],v[2:4],v[:2])\n"
},
{
"answer_id": 23948187,
"author": "Knio",
"author_id": 132076,
"author_profile": "https://Stackoverflow.com/users/132076",
"pm_score": 3,
"selected": false,
"text": ">>> import pynmea2\n>>> msg = pynmea2.parse('$GPGGA,142927.829,2831.4705,N,08041.0067,W,1,07,1.0,7.9,M,-31.2,M,0.0,0000*4F')\n>>> msg.timestamp, msg.latitude, msg.longitude, msg.altitude\n(datetime.time(14, 29, 27), 28.524508333333333, -80.683445, 7.9)\n"
},
{
"answer_id": 71198703,
"author": "Kadir Şahbaz",
"author_id": 5569709,
"author_profile": "https://Stackoverflow.com/users/5569709",
"pm_score": 1,
"selected": false,
"text": "line = \"$GPRMC,199304.973,3248.7780,N,11355.7832,W,1,06,02.2,25722.5,M,,,*00\"\nline = line.split(\",\")\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311763",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/33383/"
] |
311,768 | <p>I want to select about 4-5 rows from a table, then form a space separated string.</p>
<p>All of this is to be done in a stored procedure (SQL server 2005).</p>
<p>Is this possible?</p>
<p>I will then use this space-separated string and save it to another table.</p>
<p><b>Update</b></p>
<pre><code>SELECT *
FROM Users
WHERE userID < 10
</code></pre>
<p>output:</p>
<pre><code>john
jake
blah
sam
</code></pre>
<p>So, put this in a space separated string:</p>
<p>'john jake blah sam'</p>
<p>and save that string to another row in a table.</p>
<p>All this has to be done in a stored procedure (if possible).</p>
| [
{
"answer_id": 311780,
"author": "Micky McQuade",
"author_id": 12908,
"author_profile": "https://Stackoverflow.com/users/12908",
"pm_score": 0,
"selected": false,
"text": "DECLARE @whatever varchar(max) -- or varchar(1000) or whatever size\nSET @whatever = ''\n\nSELECT @whatever = @whatever + MyColumn + ' ' FROM MyTable\n"
},
{
"answer_id": 311793,
"author": "Ian Nelson",
"author_id": 2084,
"author_profile": "https://Stackoverflow.com/users/2084",
"pm_score": 2,
"selected": false,
"text": "DECLARE @firstnames varchar(max)\n\nSELECT \n @firstnames = COALESCE(@firstnames + ' ', '') + FirstName \nFROM \n Users \nWHERE \n UserId < 10\n\nINSERT INTO OtherTable (OtherColumn) VALUES (@firstNames)\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311768",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,775 | <p>Code like this often happens:</p>
<pre><code>l = []
while foo:
# baz
l.append(bar)
# qux
</code></pre>
<p>This is really slow if you're about to append thousands of elements to your list, as the list will have to be constantly resized to fit the new elements.</p>
<p>In Java, you can create an ArrayList with an initial capacity. If you have some idea how big your list will be, this will be a lot more efficient.</p>
<p>I understand that code like this can often be refactored into a list comprehension. If the <em>for</em>/<em>while</em> loop is very complicated, though, this is unfeasible. Is there an equivalent for us Python programmers?</p>
| [
{
"answer_id": 311783,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 7,
"selected": false,
"text": "l = [None] * 1000 # Make a list of 1000 None's\nfor i in xrange(1000):\n # baz\n l[i] = bar\n # qux\n"
},
{
"answer_id": 311785,
"author": "Piotr Lesnicki",
"author_id": 38796,
"author_profile": "https://Stackoverflow.com/users/38796",
"pm_score": -1,
"selected": false,
"text": "ScalableList"
},
{
"answer_id": 311833,
"author": "S.Lott",
"author_id": 10661,
"author_profile": "https://Stackoverflow.com/users/10661",
"pm_score": 8,
"selected": true,
"text": "def doAppend( size=10000 ):\n result = []\n for i in range(size):\n message= \"some unique object %d\" % ( i, )\n result.append(message)\n return result\n\ndef doAllocate( size=10000 ):\n result=size*[None]\n for i in range(size):\n message= \"some unique object %d\" % ( i, )\n result[i]= message\n return result\n"
},
{
"answer_id": 1602958,
"author": "Jason Wiener",
"author_id": 194046,
"author_profile": "https://Stackoverflow.com/users/194046",
"pm_score": 2,
"selected": false,
"text": "def doAppend(size=10000):\n result = []\n for i in range(size):\n message = \"some unique object %d\" % ( i, )\n result.append(message)\n return result\n\ndef doAllocate(size=10000):\n result = size*[None]\n for i in range(size):\n message = \"some unique object %d\" % ( i, )\n result[i] = message\n return result\n\ndef doGen(size=10000):\n return list(\"some unique object %d\" % ( i, ) for i in xrange(size))\n\nsize = 1000\n@print_timing\ndef testAppend():\n for i in xrange(size):\n doAppend()\n\n@print_timing\ndef testAlloc():\n for i in xrange(size):\n doAllocate()\n\n@print_timing\ndef testGen():\n for i in xrange(size):\n doGen()\n\n\ntestAppend()\ntestAlloc()\ntestGen()\n"
},
{
"answer_id": 5533598,
"author": "LRN",
"author_id": 690386,
"author_profile": "https://Stackoverflow.com/users/690386",
"pm_score": 6,
"selected": false,
"text": "pre_allocated_list = [None] * size\n"
},
{
"answer_id": 24173567,
"author": "kfsone",
"author_id": 257645,
"author_profile": "https://Stackoverflow.com/users/257645",
"pm_score": 5,
"selected": false,
"text": "x = [None] * numElements\n"
},
{
"answer_id": 40289905,
"author": "Josiah Yoder",
"author_id": 1048186,
"author_profile": "https://Stackoverflow.com/users/1048186",
"pm_score": 0,
"selected": false,
"text": "def totient(n):\n totient = 0\n\n if n == 1:\n totient = 1\n else:\n for i in range(1, n):\n if math.gcd(i, n) == 1:\n totient += 1\n return totient\n\ndef find_totients(max):\n totients = dict()\n for i in range(1,max+1):\n totients[i] = totient(i)\n\n print('Totients:')\n for i in range(1,max+1):\n print(i,totients[i])\n"
},
{
"answer_id": 41620272,
"author": "Russell Troxel",
"author_id": 7411248,
"author_profile": "https://Stackoverflow.com/users/7411248",
"pm_score": 4,
"selected": false,
"text": "NoneType"
},
{
"answer_id": 73583831,
"author": "danijar",
"author_id": 1079110,
"author_profile": "https://Stackoverflow.com/users/1079110",
"pm_score": 1,
"selected": false,
"text": "list"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311775",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
311,801 | <p>i’m trying to create a url string that works like this:</p>
<pre><code>/app/process/example.com/index.html
</code></pre>
<p>so in other words,</p>
<pre><code>/app/process/$URL
</code></pre>
<p>i then retrieve the url with </p>
<pre><code>$this->uri->segment(3);
</code></pre>
<p>the forward slashes in the URL will of course be a problem accessing uri segments, so i’ll go ahead and url encode the URL portion:</p>
<pre><code>/app/process/example.com%2Findex.html
</code></pre>
<p>.. but now I just get a 404 saying ...</p>
<pre><code>Not Found
The requested URL /app/process/example.com/index.html was not found on this server.
</code></pre>
<p>it appears that my url encoding of forward slashes breaks CI’s URI parser.</p>
<p>what can i do to get around this problem?</p>
| [
{
"answer_id": 311806,
"author": "Kyle Cronin",
"author_id": 658,
"author_profile": "https://Stackoverflow.com/users/658",
"pm_score": 1,
"selected": false,
"text": "<?php\nclass App extends Controller {\n function process($a, $b) {\n // at this point $a is \"example.com\" and $b is \"index.html\"\n }\n}\n?>\n"
},
{
"answer_id": 311879,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 3,
"selected": false,
"text": "index.php/a/b/c"
},
{
"answer_id": 349307,
"author": "Steven Oxley",
"author_id": 3831,
"author_profile": "https://Stackoverflow.com/users/3831",
"pm_score": 2,
"selected": false,
"text": "\n$uri = 'example.com/index.html';\n$pattern = '\"/\"';\n$new_uri = preg_replace($pattern, '_', $uri);\n"
},
{
"answer_id": 3320536,
"author": "Raheel Khawaja",
"author_id": 268965,
"author_profile": "https://Stackoverflow.com/users/268965",
"pm_score": 0,
"selected": false,
"text": "$config['permitted_uri_chars'] = 'a-z 0-9~%.:_\\-';\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311801",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,807 | <p>I don't think that this is specific to a language or framework, but I am using xUnit.net and C#.</p>
<p>I have a function that returns a random date in a certain range. I pass in a date, and the returning date is always in range of 1 to 40 years before the given date.</p>
<p>Now I just wonder if there is a good way to unit test this. The best approach seems to be to create a loop and let the function run i.e. 100 times and assert that every of these 100 results are in the desired range, which is my current approach.</p>
<p>I also realize that unless I am able to control my Random generator, there will not be a perfect solution (after all, the result IS random), but I wonder what approaches you take when you have to test functionality that returns a random result in a certain range?</p>
| [
{
"answer_id": 311829,
"author": "Brian Genisio",
"author_id": 36687,
"author_profile": "https://Stackoverflow.com/users/36687",
"pm_score": 6,
"selected": false,
"text": "public interface IRandomGenerator\n{\n double Generate(double max);\n}\n\npublic class SomethingThatUsesRandom\n{\n private readonly IRandomGenerator _generator;\n\n private class DefaultRandom : IRandomGenerator\n {\n public double Generate(double max)\n {\n return (new Random()).Next(max);\n }\n }\n\n public SomethingThatUsesRandom(IRandomGenerator generator)\n {\n _generator = generator;\n }\n\n public SomethingThatUsesRandom() : this(new DefaultRandom())\n {}\n\n public double MethodThatUsesRandom()\n {\n return _generator.Generate(40.0);\n }\n}\n"
},
{
"answer_id": 2181242,
"author": "user263976",
"author_id": 263976,
"author_profile": "https://Stackoverflow.com/users/263976",
"pm_score": 1,
"selected": false,
"text": "// If we are unit testing, then...\nif (defined('UNIT_TESTING') && UNIT_TESTING)\n{\n // ...make our my_rand() function deterministic to aid testing.\n function my_rand($min, $max)\n {\n return $GLOBALS['random_table'][$min][$max];\n }\n}\nelse\n{\n // ...else make our my_rand() function truly random.\n function my_rand($min = 0, $max = PHP_INT_MAX)\n {\n if ($max === PHP_INT_MAX)\n {\n $max = getrandmax();\n }\n return rand($min, $max);\n }\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311807",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/91/"
] |
311,816 | <p>When I generate CSS or JavaScript files using PHP I like to use .js.php or .css.php file extensions. so that I know what's going on.</p>
<p>Is there a way of associating these "compound" file extensions to their respective languages?</p>
| [
{
"answer_id": 375087,
"author": "itsadok",
"author_id": 7581,
"author_profile": "https://Stackoverflow.com/users/7581",
"pm_score": 3,
"selected": false,
"text": "<?php if(0) { ?><script><?php } ?>\n# code goes here\n<?php if(0) { ?></script><?php } ?>\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311816",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2443/"
] |
311,818 | <p>How should I tell SDL to maximize the application window?</p>
<p>I'm creating the window with these flags: SDL_OPENGL | SDL_HWSURFACE | SDL_DOUBLEBUF | SDL_RESIZABLE.</p>
| [
{
"answer_id": 312217,
"author": "MattyT",
"author_id": 7405,
"author_profile": "https://Stackoverflow.com/users/7405",
"pm_score": -1,
"selected": false,
"text": "flags |= SDL_FULLSCREEN;\nscreen = SDL_SetVideoMode(..., flags);\n"
},
{
"answer_id": 315226,
"author": "Judge Maygarden",
"author_id": 1491,
"author_profile": "https://Stackoverflow.com/users/1491",
"pm_score": 4,
"selected": true,
"text": "SDL_SysWMinfo info;\nSDL_VERSION(&info.version);\nSDL_GetWMInfo(&info);\nShowWindow(info.window, SW_MAXIMIZE);\n"
},
{
"answer_id": 23665159,
"author": "ColacX",
"author_id": 700735,
"author_profile": "https://Stackoverflow.com/users/700735",
"pm_score": 3,
"selected": false,
"text": "sdl_window = SDL_CreateWindow(\"title\", 10, 30, window_width, window_height, SDL_WINDOW_OPENGL | SDL_WINDOW_RESIZABLE);\nSDL_MaximizeWindow(sdl_window);\nSDL_GetWindowSize(sdl_window, &window_width, &window_height);\nsdl_gl_context = SDL_GL_CreateContext(sdl_window);\nSDL_GL_MakeCurrent(sdl_window, sdl_gl_context);\n"
},
{
"answer_id": 46038603,
"author": "kungfooman",
"author_id": 1952626,
"author_profile": "https://Stackoverflow.com/users/1952626",
"pm_score": 3,
"selected": false,
"text": "SDL_WINDOW_MAXIMIZED"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311818",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38256/"
] |
311,840 | <p>I am looking for a tool like <a href="http://linux.die.net/man/1/ltrace" rel="noreferrer">ltrace</a> or <a href="http://linux.die.net/man/1/strace" rel="noreferrer">strace</a> that can trace locally defined functions in an executable. ltrace only traces dynamic library calls and strace only traces system calls. For example, given the following C program:</p>
<pre><code>#include <stdio.h>
int triple ( int x )
{
return 3 * x;
}
int main (void)
{
printf("%d\n", triple(10));
return 0;
}
</code></pre>
<p>Running the program with <code>ltrace</code> will show the call to <code>printf</code> since that is a standard library function (which is a dynamic library on my system) and <code>strace</code> will show all the system calls from the startup code, the system calls used to implement printf, and the shutdown code, but I want something that will show me that the function <code>triple</code> was called. Assuming that the local functions have not been inlined by an optimizing compiler and that the binary has not been stripped (symbols removed), is there a tool that can do this?</p>
<p><strong>Edit</strong></p>
<p>A couple of clarifications:</p>
<ul>
<li>It is okay if the tool also provides trace information for non-local functions.</li>
<li>I don't want to have to recompile the program(s) with support for specific tools, the symbol information in the executable should be enough.</li>
<li>I would be really nice if I could use the tool to attach to existing processes like I can with ltrace/strace.</li>
</ul>
| [
{
"answer_id": 311912,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 7,
"selected": true,
"text": "#include <iostream>\n\nint fac(int n) {\n if(n == 0)\n return 1;\n return n * fac(n-1);\n}\n\nint main()\n{\n for(int i=0;i<4;i++)\n std::cout << fac(i) << std::endl;\n}\n"
},
{
"answer_id": 312058,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "$ sudo yum install frysk\n$ ftrace -sym:'*' -- ./a.out\n"
},
{
"answer_id": 312582,
"author": "philant",
"author_id": 18804,
"author_profile": "https://Stackoverflow.com/users/18804",
"pm_score": 3,
"selected": false,
"text": "-finstrument-functions"
},
{
"answer_id": 324709,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 5,
"selected": false,
"text": "$ sudo stap para-callgraph.stp 'process(\"/bin/ls\").function(\"*\")' -c /bin/ls\n0 ls(12631):->main argc=0x1 argv=0x7fff1ec3b038\n276 ls(12631): ->human_options spec=0x0 opts=0x61a28c block_size=0x61a290\n365 ls(12631): <-human_options return=0x0\n496 ls(12631): ->clone_quoting_options o=0x0\n657 ls(12631): ->xmemdup p=0x61a600 s=0x28\n815 ls(12631): ->xmalloc n=0x28\n908 ls(12631): <-xmalloc return=0x1efe540\n950 ls(12631): <-xmemdup return=0x1efe540\n990 ls(12631): <-clone_quoting_options return=0x1efe540\n1030 ls(12631): ->get_quoting_style o=0x1efe540\n"
},
{
"answer_id": 325015,
"author": "Tom",
"author_id": 40620,
"author_profile": "https://Stackoverflow.com/users/40620",
"pm_score": 2,
"selected": false,
"text": "objdump -d <program>"
},
{
"answer_id": 12389783,
"author": "Janus Troelsen",
"author_id": 309483,
"author_profile": "https://Stackoverflow.com/users/309483",
"pm_score": 4,
"selected": false,
"text": "~/Desktop/datalog-2.2/datalog"
},
{
"answer_id": 31814494,
"author": "Ciro Santilli OurBigBook.com",
"author_id": 895245,
"author_profile": "https://Stackoverflow.com/users/895245",
"pm_score": 3,
"selected": false,
"text": "int f2(int i) { return i + 2; }\nint f1(int i) { return f2(2) + i + 1; }\nint f0(int i) { return f1(1) + f2(2); }\nint pointed(int i) { return i; }\nint not_called(int i) { return 0; }\n\nint main(int argc, char **argv) {\n int (*f)(int);\n f0(1);\n f1(1);\n f = pointed;\n if (argc == 1)\n f(1);\n if (argc == 2)\n not_called(1);\n return 0;\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311840",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/25222/"
] |
311,857 | <p>I'm embedding MSBuild directly into a more complex build tool. The relevant code looks roughly like this:</p>
<pre><code>// assume 'using Microsoft.Build.BuildEngine;'
Engine e = Engine();
BuildPropertyGroup props = new BuildPropertyGroup();
props.SetProperty( "Configuration", Config.BuildConfig );
e.BuildProjectFile( projectFile, new string[] { "Build" }, props )
</code></pre>
<p>My question is how to cancel this build once it's started, without doing something drastic like terminating the thread. Also, if the project being built is a C++ project, the build will involve at least one sub-process, so canceling the thread isn't even going to really cancel the build.</p>
<p>I don't see any cancel method on the Engine class - does someone know of a way?</p>
| [
{
"answer_id": 319064,
"author": "Charlie",
"author_id": 18529,
"author_profile": "https://Stackoverflow.com/users/18529",
"pm_score": 1,
"selected": true,
"text": "CreateToolhelp32Snapshot( ToolHelp.SnapshotFlags.Process, 0 );\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311857",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18529/"
] |
311,873 | <p><strong>NOTE: the original question is moot but scan to the bottom for something relevant.</strong></p>
<p>I have a query I want to optimize that looks something like this:</p>
<pre><code>select cols from tbl where col = "some run time value" limit 1;
</code></pre>
<p>I want to know what keys are being used but whatever I pass to explain, it is able to optimize the where clause to nothing ("Impossible WHERE noticed...") because I fed it a constant.</p>
<ul>
<li>Is there a way to tell mysql to not do constant optimizations in explain?</li>
<li>Am I missing something?</li>
<li>Is there a better way to get the info I need?</li>
</ul>
<p>Edit: <code>EXPLAIN</code> seems to be giving me the query plan that will result from constant values. As the query is part of a stored procedure (and IIRC query plans in spocs are generated before they are called) this does me no good because the value are not constant. What I want is to find out what query plan the optimizer will generate when it doesn't known what the actual value will be.</p>
<p>Am I missing soemthing?</p>
<p>Edit2: Asking around elsewhere, it seems that MySQL always regenerates query plans unless you go out of your way to make it re-use them. Even in stored procedures. From this it would seem that my question is moot.</p>
<p><strong>However that doesn't make what I really wanted to know moot:</strong> <em>How do you optimize a query that contains values that are constant within any specific query but where I, the programmer, don't known in advance what value will be used?</em> -- For example say my client side code is generating a query with a number in it's <code>where</code> clause. Some times the number will result in an <em>impossible where clause</em> other times it won't. How can I use explain to examine how well optimized the query is?</p>
<p>The best approach I'm seeing right off the bat would be to run <code>EXPLAIN</code> on it for the full matrix of exist/non-exist cases. Really that isn't a very good solution as it would be both hard and error prone to do by hand.</p>
| [
{
"answer_id": 311914,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": false,
"text": "col = col"
},
{
"answer_id": 821864,
"author": "Quassnoi",
"author_id": 55159,
"author_profile": "https://Stackoverflow.com/users/55159",
"pm_score": 3,
"selected": true,
"text": "MySQL"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311873",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1343/"
] |
311,876 | <p>Hey everyone. I'm trying to make a swing GUI with a button and a label on it. im using a border layout and the label ( in the north field ) shows up fine, but the button takes up the rest of the frame (it's in the center field). any idea how to fix this?</p>
| [
{
"answer_id": 311878,
"author": "OscarRyz",
"author_id": 20654,
"author_profile": "https://Stackoverflow.com/users/20654",
"pm_score": 5,
"selected": true,
"text": "public static void main( String [] args ) {\n JLabel label = new JLabel(\"Some info\");\n JButton button = new JButton(\"Ok\");\n\n JFrame frame = ... \n\n frame.add( label, BorderLayout.NORTH );\n frame.add( button , BorderLayout.CENTER );\n ....\n\n}\n"
},
{
"answer_id": 317674,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "\n import javax.swing.*;\n\n public class TestFrame extends JFrame {\n public TestFrame() {\n JLabel label = new JLabel(\"Some info\");\n JButton button = new JButton(\"Ok\");\n Box b = new Box(BoxLayout.Y_AXIS);\n b.add(label);\n b.add(button);\n getContentPane().add(b);\n\n }\n public static void main(String[] args) {\n JFrame f = new TestFrame();\n f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);\n f.setLocationRelativeTo(null);\n f.setVisible(true);\n\n }\n }\n"
},
{
"answer_id": 15372671,
"author": "Aruman",
"author_id": 1480755,
"author_profile": "https://Stackoverflow.com/users/1480755",
"pm_score": 2,
"selected": false,
"text": "frame = new JFrame();\n... //your code here\n\n// to set absolute layout.\nframe.getContentPane().setLayout(null);\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311876",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39984/"
] |
311,882 | <p>I often hear the terms 'statically linked' and 'dynamically linked', often in reference to code written in <a href="http://en.wikipedia.org/wiki/C_%28programming_language%29" rel="noreferrer">C</a>, <a href="https://en.wikipedia.org/wiki/C++" rel="noreferrer">C++</a> or <a href="http://en.wikipedia.org/wiki/C_Sharp_%28programming_language%29" rel="noreferrer">C#</a>. What are they, what exactly are they talking about, and what are they linking?</p>
| [
{
"answer_id": 311889,
"author": "paxdiablo",
"author_id": 14860,
"author_profile": "https://Stackoverflow.com/users/14860",
"pm_score": 10,
"selected": true,
"text": "main.c"
},
{
"answer_id": 311932,
"author": "Artelius",
"author_id": 31945,
"author_profile": "https://Stackoverflow.com/users/31945",
"pm_score": 8,
"selected": false,
"text": "CALL 0x5A62"
},
{
"answer_id": 32961243,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 4,
"selected": false,
"text": "#include <stdio.h>\n\nint main(void)\n{\n printf(\"This is a string\\n\");\n return 0;\n}\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311882",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
311,883 | <p>I've got a method JSNI that calls a Java method that take a Hasmap as input.
I've tried </p>
<pre><code>handler.@com.mypackage::myMethod(Ljava/util/Hashmap;)(myHashMap);
handler.@com.mypackage::myMethod(Ljava/util/Hashmap<Ljava/lang/String,Ljava/lang/String>;)(myHashMap);
</code></pre>
<p>I'm can't seem to define the correct type signature to include the Strings or find if this usage is even allowed. </p>
<p>Since I'm doing this in gwt I though it might be the implementation of hashmap and the alternative approach I've though takes a String[][] array as input </p>
<p>I was hoping for somwthing like</p>
<p>handler.@com.mypackage::myMethod([[Ljava/lang/String;)(myArray);</p>
<p>However, I hit another issue of finding the correct JNSI sntax for the 2nd dimension of the array </p>
<p>A single dimension array ie. <code>[Ljava/lang/String;</code> is fine but I need the 2nd dimension.</p>
<p>Any help/ideas or links to good jnsi doc appreciated.</p>
| [
{
"answer_id": 318896,
"author": "sre",
"author_id": 21387,
"author_profile": "https://Stackoverflow.com/users/21387",
"pm_score": 0,
"selected": false,
"text": "handler.@com.mypackage::myMethod(Ljava/util/Hashmap;)(myHashMap);\n"
},
{
"answer_id": 332157,
"author": "Mark Renouf",
"author_id": 758,
"author_profile": "https://Stackoverflow.com/users/758",
"pm_score": 1,
"selected": false,
"text": " public void callFoo() {\n JSONObject obj = new JSONObject();\n obj.put(\"propertyName\", new JSONString(\"properyValue\"));\n JavaScriptObject jsObj = obj.getJavaScriptObject();\n\n nativeFoo(jsObj);\n }\n\n public native void nativeFoo(JavaScriptObject obj) /*-{\n $wnd.alert(obj['propertyName']);\n }-*/;\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311883",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/21387/"
] |
311,888 | <p>I have a syntax highlighting function in vb.net. I use regular expressions to match "!IF" for instance and then color it blue. This works perfect until I tried to figure out how to do comments. </p>
<p>The language I'm writing this for a comment can either be if the line starts with a single quote ' OR if anywhere in the line there is two single quotes</p>
<pre><code>'this line is a comment
!if StackOverflow = "AWESOME" ''this is also a comment
</code></pre>
<p>Now i know how to see if it starts with a single line ^' but i need to to return the string all the way to the end of the line so i can color the entire comment green and not just the single quotes.</p>
<p>You shouldn't need the code but here is a snippet just in case it helps. </p>
<pre><code> For Each pass In frmColors.lbRegExps.Items
RegExp = System.Text.RegularExpressions.Regex.Matches(LCase(rtbMain.Text), LCase(pass))
For Each RegExpMatch In RegExp
rtbMain.Select(RegExpMatch.Index, RegExpMatch.Length)
rtbMain.SelectionColor = ColorTranslator.FromHtml(frmColors.lbHexColors.Items(PassNumber))
Next
PassNumber += 1
Next
</code></pre>
| [
{
"answer_id": 311895,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 4,
"selected": true,
"text": "^(\\'[^\\r\\n]+)$|(''[^\\r\\n]+)$\n"
},
{
"answer_id": 311908,
"author": "Boaz",
"author_id": 2892,
"author_profile": "https://Stackoverflow.com/users/2892",
"pm_score": 1,
"selected": false,
"text": "\"(^'|'').*$\"\n"
}
] | 2008/11/22 | [
"https://Stackoverflow.com/questions/311888",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39143/"
] |
311,936 | <p>I've read a few instances in reading mathematics and computer science that use the equivalence symbol <strong><code>≡</code></strong>, (basically an '=' with three lines) and it always makes sense to me to read this as if it were equality. What is the difference between these two concepts?</p>
| [
{
"answer_id": 311941,
"author": "Robert Gamble",
"author_id": 25222,
"author_profile": "https://Stackoverflow.com/users/25222",
"pm_score": 3,
"selected": false,
"text": "int i = 3;\ndouble d = 3.0;\n"
},
{
"answer_id": 311942,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 5,
"selected": true,
"text": "public final class CaseInsensitiveString {\n...\n // broken\n @Override public boolean equals(Object o) {\n if (o instance of CaseInsensitiveString)\n return s.equalsIgnoreCase(\n ((CaseInsensitiveString) o).s);\n if (o instanceof String) // One-way interoperability!\n return s.equalsIgnoreCase((String) o);\n return false;\n } \n}\n"
},
{
"answer_id": 311950,
"author": "Kent Fredric",
"author_id": 15614,
"author_profile": "https://Stackoverflow.com/users/15614",
"pm_score": 2,
"selected": false,
"text": "null == 0 # true , null is equivelant to 0 ( in php ) \nnull === 0 # false, null is not equal to 0 ( in php ) \n"
},
{
"answer_id": 311997,
"author": "Purfideas",
"author_id": 4615,
"author_profile": "https://Stackoverflow.com/users/4615",
"pm_score": 2,
"selected": false,
"text": "0.9999999999999999... = 1\n"
},
{
"answer_id": 333143,
"author": "dreeves",
"author_id": 4234,
"author_profile": "https://Stackoverflow.com/users/4234",
"pm_score": 4,
"selected": false,
"text": "≡"
},
{
"answer_id": 71844213,
"author": "Bolpat",
"author_id": 3273130,
"author_profile": "https://Stackoverflow.com/users/3273130",
"pm_score": 2,
"selected": false,
"text": "x"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/311936",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/30529/"
] |
311,939 | <p>So the following rewrite rules always seem to fire. This has the effect of hiding another domain that I am hosting on the server?</p>
<p>I can't seem to figure out what's wrong and it is time to call in the experts:</p>
<pre><code>RewriteEngine on
RewriteCond %{HTTP_HOST} ^danielhonig.com
RewriteRule ^(.*)$ http://www.danielhonig.com/$1 [R=permanent,L]
RedirectMatch ^/$ http://www.danielhonig.com/gravl
Options None
</code></pre>
| [
{
"answer_id": 311945,
"author": "mthurlin",
"author_id": 39991,
"author_profile": "https://Stackoverflow.com/users/39991",
"pm_score": 2,
"selected": false,
"text": "<VirtualHost>"
},
{
"answer_id": 329778,
"author": "rojoca",
"author_id": 41967,
"author_profile": "https://Stackoverflow.com/users/41967",
"pm_score": 0,
"selected": false,
"text": "%{SERVER_NAME}"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/311939",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1129162/"
] |
311,948 | <p>How do I make gdb print functions of interest as they are called, indented according to how deep in the stack they are?</p>
<p>I want to be able to say something like (made up):</p>
<pre><code>(gdb) trace Foo* Bar* printf
</code></pre>
<p>And have gdb print all functions which begin with Foo or Bar, as they are called. Kind of like gnu cflow, except using the debugging symbols and only printing functions which actually get called, not all possible call flows.</p>
<p>Tools which won't help include cachegrind, callgrind and oprofile, which order the results by which functions were called most often. I need the order of calling preserved.</p>
<p>The wildcarding (or equivalent) is essential, as there are a lot of Foo and Bar funcs. Although I would settle for recording absolutely every function. Or, perhaps telling gdb to record all functions in a particular library.</p>
<p>Some GDB wizard must have a script for this common job!</p>
| [
{
"answer_id": 312279,
"author": "qrdl",
"author_id": 28494,
"author_profile": "https://Stackoverflow.com/users/28494",
"pm_score": 0,
"selected": false,
"text": "gdb"
},
{
"answer_id": 1500442,
"author": "alesplin",
"author_id": 135917,
"author_profile": "https://Stackoverflow.com/users/135917",
"pm_score": 3,
"selected": false,
"text": "define"
},
{
"answer_id": 14597049,
"author": "Saradhi",
"author_id": 41562,
"author_profile": "https://Stackoverflow.com/users/41562",
"pm_score": 2,
"selected": false,
"text": "rbreak"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/311948",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,949 | <p>Is there any good way to unit test destructors? Like say I have a class like this (contrived) example:</p>
<pre><code>class X
{
private:
int *x;
public:
X()
{
x = new int;
}
~X()
{
delete x;
}
int *getX() {return x;}
const int *getX() const {return x;}
};
</code></pre>
<p>Is there any good way to unit test this to make sure x gets deleted without cluttering up my hpp file with #ifdef TESTs or breaking encapsulation? The main problem that I'm seeing is that it's difficult to tell if x really got deleted, especially because the object is out of scope at the time the destructor is called.</p>
| [
{
"answer_id": 311976,
"author": "Matthew Crumley",
"author_id": 2214,
"author_profile": "https://Stackoverflow.com/users/2214",
"pm_score": 0,
"selected": false,
"text": "void testDestructor()\n{\n int *my_x;\n {\n X object;\n my_x = object.getX();\n }\n CPPUNIT_ASSERT( *my_x == 0xDDDDDDDD );\n}\n"
},
{
"answer_id": 312045,
"author": "1800 INFORMATION",
"author_id": 3146,
"author_profile": "https://Stackoverflow.com/users/3146",
"pm_score": 3,
"selected": false,
"text": "x"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/311949",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2147/"
] |
311,955 | <p>I have an application which is a relatively old. Through some minor changes, it builds nearly perfectly with Visual C++ 2008. One thing that I've noticed is that my "debug console" isn't quite working right. Basically in the past, I've use <code>AllocConsole()</code> to create a console for my debug output to go to. Then I would use <code>freopen</code> to redirect <code>stdout</code> to it. This worked perfectly with both C and C++ style IO.</p>
<p>Now, it seems that it will only work with C style IO. What is the proper way to redirect things like <code>cout</code> to a console allocated with <code>AllocConsole()</code>?</p>
<p>Here's the code which used to work:</p>
<pre><code>if(AllocConsole()) {
freopen("CONOUT$", "wt", stdout);
SetConsoleTitle("Debug Console");
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED);
}
</code></pre>
<p><strong>EDIT</strong>: one thing which occurred to me is that I could make a custom streambuf whose overflow method writes using C style IO and replace <code>std::cout</code>'s default stream buffer with it. But that seems like a cop-out. Is there a proper way to do this in 2008? Or is this perhaps something that MS overlooked?</p>
<p><strong>EDIT2</strong>: OK, so I've made an implementaiton of the idea I spelled out above. Basically it looks like this:</p>
<pre><code>class outbuf : public std::streambuf {
public:
outbuf() {
setp(0, 0);
}
virtual int_type overflow(int_type c = traits_type::eof()) {
return fputc(c, stdout) == EOF ? traits_type::eof() : c;
}
};
int APIENTRY WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPTSTR lpCmdLine, int nCmdShow) {
// create the console
if(AllocConsole()) {
freopen("CONOUT$", "w", stdout);
SetConsoleTitle("Debug Console");
SetConsoleTextAttribute(GetStdHandle(STD_OUTPUT_HANDLE), FOREGROUND_GREEN | FOREGROUND_BLUE | FOREGROUND_RED);
}
// set std::cout to use my custom streambuf
outbuf ob;
std::streambuf *sb = std::cout.rdbuf(&ob);
// do some work here
// make sure to restore the original so we don't get a crash on close!
std::cout.rdbuf(sb);
return 0;
}
</code></pre>
<p>Anyone have a better/cleaner solution than just forcing <code>std::cout</code> to be a glorified <code>fputc</code>?</p>
| [
{
"answer_id": 312980,
"author": "Dmitry Khalatov",
"author_id": 18174,
"author_profile": "https://Stackoverflow.com/users/18174",
"pm_score": 3,
"selected": false,
"text": "OutputDebugStringA"
},
{
"answer_id": 424236,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 4,
"selected": false,
"text": "cout"
},
{
"answer_id": 25927081,
"author": "Roger Sanders",
"author_id": 3418322,
"author_profile": "https://Stackoverflow.com/users/3418322",
"pm_score": 6,
"selected": true,
"text": "void BindCrtHandlesToStdHandles(bool bindStdIn, bool bindStdOut, bool bindStdErr)\n{\n // Re-initialize the C runtime \"FILE\" handles with clean handles bound to \"nul\". We do this because it has been\n // observed that the file number of our standard handle file objects can be assigned internally to a value of -2\n // when not bound to a valid target, which represents some kind of unknown internal invalid state. In this state our\n // call to \"_dup2\" fails, as it specifically tests to ensure that the target file number isn't equal to this value\n // before allowing the operation to continue. We can resolve this issue by first \"re-opening\" the target files to\n // use the \"nul\" device, which will place them into a valid state, after which we can redirect them to our target\n // using the \"_dup2\" function.\n if (bindStdIn)\n {\n FILE* dummyFile;\n freopen_s(&dummyFile, \"nul\", \"r\", stdin);\n }\n if (bindStdOut)\n {\n FILE* dummyFile;\n freopen_s(&dummyFile, \"nul\", \"w\", stdout);\n }\n if (bindStdErr)\n {\n FILE* dummyFile;\n freopen_s(&dummyFile, \"nul\", \"w\", stderr);\n }\n\n // Redirect unbuffered stdin from the current standard input handle\n if (bindStdIn)\n {\n HANDLE stdHandle = GetStdHandle(STD_INPUT_HANDLE);\n if(stdHandle != INVALID_HANDLE_VALUE)\n {\n int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT);\n if(fileDescriptor != -1)\n {\n FILE* file = _fdopen(fileDescriptor, \"r\");\n if(file != NULL)\n {\n int dup2Result = _dup2(_fileno(file), _fileno(stdin));\n if (dup2Result == 0)\n {\n setvbuf(stdin, NULL, _IONBF, 0);\n }\n }\n }\n }\n }\n\n // Redirect unbuffered stdout to the current standard output handle\n if (bindStdOut)\n {\n HANDLE stdHandle = GetStdHandle(STD_OUTPUT_HANDLE);\n if(stdHandle != INVALID_HANDLE_VALUE)\n {\n int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT);\n if(fileDescriptor != -1)\n {\n FILE* file = _fdopen(fileDescriptor, \"w\");\n if(file != NULL)\n {\n int dup2Result = _dup2(_fileno(file), _fileno(stdout));\n if (dup2Result == 0)\n {\n setvbuf(stdout, NULL, _IONBF, 0);\n }\n }\n }\n }\n }\n\n // Redirect unbuffered stderr to the current standard error handle\n if (bindStdErr)\n {\n HANDLE stdHandle = GetStdHandle(STD_ERROR_HANDLE);\n if(stdHandle != INVALID_HANDLE_VALUE)\n {\n int fileDescriptor = _open_osfhandle((intptr_t)stdHandle, _O_TEXT);\n if(fileDescriptor != -1)\n {\n FILE* file = _fdopen(fileDescriptor, \"w\");\n if(file != NULL)\n {\n int dup2Result = _dup2(_fileno(file), _fileno(stderr));\n if (dup2Result == 0)\n {\n setvbuf(stderr, NULL, _IONBF, 0);\n }\n }\n }\n }\n }\n\n // Clear the error state for each of the C++ standard stream objects. We need to do this, as attempts to access the\n // standard streams before they refer to a valid target will cause the iostream objects to enter an error state. In\n // versions of Visual Studio after 2005, this seems to always occur during startup regardless of whether anything\n // has been read from or written to the targets or not.\n if (bindStdIn)\n {\n std::wcin.clear();\n std::cin.clear();\n }\n if (bindStdOut)\n {\n std::wcout.clear();\n std::cout.clear();\n }\n if (bindStdErr)\n {\n std::wcerr.clear();\n std::cerr.clear();\n }\n}\n"
},
{
"answer_id": 39538769,
"author": "etc597",
"author_id": 6840833,
"author_profile": "https://Stackoverflow.com/users/6840833",
"pm_score": 1,
"selected": false,
"text": "if(AllocConsole())\n{\n freopen(\"CONOUT$\", \"wt\", stdout);\n freopen(\"CONIN$\", \"rt\", stdin);\n SetConsoleTitle(L\"Debug Console\");\n std::ios::sync_with_stdio(1);\n}\n"
},
{
"answer_id": 50616625,
"author": "Charlie",
"author_id": 5256963,
"author_profile": "https://Stackoverflow.com/users/5256963",
"pm_score": 0,
"selected": false,
"text": " AllocConsole(); //debug console\n std::freopen_s((FILE**)stdout, \"CONOUT$\", \"w\", stdout); //just works\n"
},
{
"answer_id": 51301529,
"author": "Alberto",
"author_id": 7790522,
"author_profile": "https://Stackoverflow.com/users/7790522",
"pm_score": 2,
"selected": false,
"text": "AllocConsole();\n\n// use static for scope\nstatic ofstream conout(\"CONOUT$\", ios::out); \n// Set std::cout stream buffer to conout's buffer (aka redirect/fdreopen)\ncout.rdbuf(conout.rdbuf());\n\ncout << \"Hello World\" << endl;\n"
},
{
"answer_id": 61504013,
"author": "Lewis Kelsey",
"author_id": 7194773,
"author_profile": "https://Stackoverflow.com/users/7194773",
"pm_score": 0,
"selected": false,
"text": "freopen(\"CONOUT$\", \"w\", stdout);"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/311955",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13430/"
] |
311,970 | <p>I am trying to create a custom accordion for my page to that display my posts. I have it in list format using HTML and I am trying to create an effect when you click each header to expand to show more information.</p>
<p>But I don't want to have say six blocks of code for six of the <code><li></code> elements I have on the page.</p>
<p>Is there a way to run it through .each(); perhaps? Instead of creating each section? Try a more dynamic approach.</p>
| [
{
"answer_id": 311977,
"author": "VonC",
"author_id": 6309,
"author_profile": "https://Stackoverflow.com/users/6309",
"pm_score": 3,
"selected": true,
"text": "<script type=\"text/javascript\" src=\"jquery.js\"></script>\n<script type=\"text/javascript\">\n$(document).ready(function()\n{\n //hide the all of the element with class msg_body\n $(\".msg_body\").hide();\n //toggle the componenet with class msg_body\n $(\".msg_head\").click(function()\n {\n $(this).next(\".msg_body\").slideToggle(600);\n });\n});\n</script>\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/311970",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,987 | <p>Hi I have a JSON object that is a 2-dimentional array and I need to pass it to PHP using Ajax.Request (only way I know how). ...Right now I manually serialized my array using a js function...and get the data in this format: s[]=1&d[]=3&[]=4 etc. ....</p>
<p>my question is: Is there a way to pass the JSON object more directly/efficientely?..instead of serializing it myself?</p>
<p>Thanks for any suggestions,
Andrew</p>
| [
{
"answer_id": 312063,
"author": "Luis Melgratti",
"author_id": 17032,
"author_profile": "https://Stackoverflow.com/users/17032",
"pm_score": 2,
"selected": false,
"text": "var myJSON= Object.toJSON(youArray);\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/311987",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
311,990 | <p>I have floated images and inset boxes at the top of a container using <code>float:right</code> (or <code>left</code>) many times. Now, I need to float a <code>div</code> to the bottom right corner of another <code>div</code> with the normal text wrap that you get with <code>float</code> (text wrapped above and to the left only).</p>
<p>I thought this must be relatively easy even though <code>float</code> has no <code>bottom</code> value but I haven't been able to do it using a number of techniques and searching the web hasn't come up with anything other than using absolute positioning but this doesn't give the correct word wrap behaviour.</p>
<p>I had thought this would be a very common design but apparently it isn't. If nobody has a suggestion I'll have to break my text up into separate boxes and align the <code>div</code> manually but that is rather precarious and I'd hate to have to do it on every page that needs it.</p>
| [
{
"answer_id": 312008,
"author": "Timothy Khouri",
"author_id": 11917,
"author_profile": "https://Stackoverflow.com/users/11917",
"pm_score": 8,
"selected": false,
"text": "position: relative"
},
{
"answer_id": 312011,
"author": "Yona",
"author_id": 40007,
"author_profile": "https://Stackoverflow.com/users/40007",
"pm_score": 4,
"selected": false,
"text": "position:relative;"
},
{
"answer_id": 2651013,
"author": "CC.",
"author_id": 318234,
"author_profile": "https://Stackoverflow.com/users/318234",
"pm_score": 2,
"selected": false,
"text": "<div class=\"article\" style=\"display: block;\">\n <h3>title</h3>\n <p>\n text content\n <a href=\"#\" style=\"display: block;float: right;\">Read More</a>\n </p>\n <div style=\"clear: both;\"></div>\n</div>\n"
},
{
"answer_id": 2746324,
"author": "Miha Eržen",
"author_id": 316425,
"author_profile": "https://Stackoverflow.com/users/316425",
"pm_score": -1,
"selected": false,
"text": "div{\n position: absolute; \n height: 100px; \n top: 100%; \n margin-top:-100px; \n}\n"
},
{
"answer_id": 2998056,
"author": "RedGen",
"author_id": 361448,
"author_profile": "https://Stackoverflow.com/users/361448",
"pm_score": 1,
"selected": false,
"text": "#parent {\n width: 780px;\n height: 250px;\n background: yellow;\n border: solid 2px red;\n}\n#child {\n position: relative;\n height: 50px;\n width: 780px;\n top: 100%;\n margin-top: -50px;\n background: blue;\n border: solid 2px green;\n}\n"
},
{
"answer_id": 3231216,
"author": "talkingD0G",
"author_id": 414130,
"author_profile": "https://Stackoverflow.com/users/414130",
"pm_score": -1,
"selected": false,
"text": "position:absolute; bottom:0;"
},
{
"answer_id": 3238489,
"author": "talkingD0G",
"author_id": 414130,
"author_profile": "https://Stackoverflow.com/users/414130",
"pm_score": 0,
"selected": false,
"text": "div {\n position: absolute; \n height: 100px; \n top: 100%; \n margin-top:-100px; \n}\n"
},
{
"answer_id": 3659887,
"author": "James L",
"author_id": 441579,
"author_profile": "https://Stackoverflow.com/users/441579",
"pm_score": 4,
"selected": false,
"text": "#div {\n left: 0;\n position: fixed;\n text-align: center;\n bottom: 0;\n width: 100%;\n}\n"
},
{
"answer_id": 3728077,
"author": "countersweet",
"author_id": 439850,
"author_profile": "https://Stackoverflow.com/users/439850",
"pm_score": 2,
"selected": false,
"text": "inline-block"
},
{
"answer_id": 8705489,
"author": "cdturner",
"author_id": 1082548,
"author_profile": "https://Stackoverflow.com/users/1082548",
"pm_score": -1,
"selected": false,
"text": "<table>\n<tr>\n <td valign=\"top\">\n this is just some random text\n <br> that should be a couple of lines long and\n <br> is at the top of where we need the bottom tag line\n </td>\n <td rowspan=\"2\">\n this<br/>\n this<br/>\n this<br/>\n this<br/>\n this<br/>\n this<br/>\n this<br/>\n this<br/>\n this<br/>\n this<br/>\n this<br/>\n is really<br/>\n tall\n </td>\n</tr>\n<tr>\n <td valign=\"bottom\">\n now this is the tagline we need on the bottom\n </td>\n</tr>\n</table>\n"
},
{
"answer_id": 9114760,
"author": "Dave Kok",
"author_id": 674737,
"author_profile": "https://Stackoverflow.com/users/674737",
"pm_score": 1,
"selected": false,
"text": "<div>\n<div style=\"float:right;height:200px;\"></div>\n<div style=\"float:right;clear:right;\">Floated content</div>\n<p>Other content</p>\n</div>\n"
},
{
"answer_id": 9330225,
"author": "drfu",
"author_id": 1216492,
"author_profile": "https://Stackoverflow.com/users/1216492",
"pm_score": -1,
"selected": false,
"text": "<style>\n.sidebar-left{float:left;width:200px}\n.content-right{float:right;width:700px}\n\n.footer{clear:both;position:relative;height:1px;width:900px}\n.bottom-element{position:absolute;top:-200px;left:0;height:200px;}\n\n</style>\n\n<div class=\"sidebar-left\"> <p>content...</p></div>\n<div class=\"content-right\"> <p>content content content content...</p></div>\n\n<div class=\"footer\">\n <div class=\"bottom-element\">bottom-element-in-sidebar</div>\n</div>\n"
},
{
"answer_id": 10451574,
"author": "Stu",
"author_id": 1375320,
"author_profile": "https://Stackoverflow.com/users/1375320",
"pm_score": 4,
"selected": false,
"text": "$(\"header .pipe\").each(function(){\n $(this).next(\".cutout\").css(\"position\",\"static\"); \n $(this).height($(this).parent().height()-$(this).next(\".cutout\").height()); \n});\n"
},
{
"answer_id": 15323617,
"author": "William Kinaan",
"author_id": 1378388,
"author_profile": "https://Stackoverflow.com/users/1378388",
"pm_score": -1,
"selected": false,
"text": "div {\n position: absolute;\n bottom: 0px;\n}\n"
},
{
"answer_id": 17841119,
"author": "sherlock42",
"author_id": 132311,
"author_profile": "https://Stackoverflow.com/users/132311",
"pm_score": 0,
"selected": false,
"text": "#outer {\n position: relative; \n}\n\n#inner {\n float:right;\n position:absolute;\n bottom:0;\n right:0;\n clear:right\n}\n\n.pipe {\n width:0px; \n float:right\n\n}\n"
},
{
"answer_id": 18171538,
"author": "Tom Groentjes",
"author_id": 1369006,
"author_profile": "https://Stackoverflow.com/users/1369006",
"pm_score": 6,
"selected": false,
"text": "-moz-transform:rotate(180deg);\n-webkit-transform:rotate(180deg);\n-o-transform:rotate(180deg);\n-ms-transform:rotate(180deg);\nfilter:progid:DXImageTransform.Microsoft.BasicImage(rotation=2);\n"
},
{
"answer_id": 24451655,
"author": "Barney Szabolcs",
"author_id": 1031191,
"author_profile": "https://Stackoverflow.com/users/1031191",
"pm_score": 1,
"selected": false,
"text": "<div class=\"elastic\">\n <div class=\"elastic_col valign-bottom\">\n bottom-aligned content.\n </div>\n</div>\n"
},
{
"answer_id": 26165954,
"author": "Kin",
"author_id": 2339596,
"author_profile": "https://Stackoverflow.com/users/2339596",
"pm_score": 1,
"selected": false,
"text": "<style>\n #footer {\n height:30px;\n margin: 0;\n clear: both;\n width:100%;\n position: relative;\n bottom:-10;\n }\n</style>\n\n<div id=\"footer\" >Sportkin - the registry for sport</div>\n"
},
{
"answer_id": 26528928,
"author": "chilicoder",
"author_id": 2196878,
"author_profile": "https://Stackoverflow.com/users/2196878",
"pm_score": 1,
"selected": false,
"text": "outer {\n position: absolute;\n bottom: 0;\n width: 100%;\n height: 100%;\n}\n.space {\n float: right;\n height: 75%; \n}\n.floateable {\n width: 40%;\n height: 25%;\n float: right;\n clear: right; \n }\n"
},
{
"answer_id": 27171341,
"author": "Thomas",
"author_id": 508127,
"author_profile": "https://Stackoverflow.com/users/508127",
"pm_score": 0,
"selected": false,
"text": "<style>\n #MainDiv\n {\n height: 300px;\n width: 300px;\n background-color: Red;\n position: relative;\n }\n\n #footerDiv\n {\n height: 50px;\n width: 300px;\n background-color: green;\n float: right;\n position: absolute;\n bottom: 0px;\n }\n </style>\n\n\n<div id=\"MainDiv\">\n <div id=\"footerDiv\">\n </div>\n</div>\n"
},
{
"answer_id": 27450933,
"author": "Salman von Abbas",
"author_id": 362006,
"author_profile": "https://Stackoverflow.com/users/362006",
"pm_score": 2,
"selected": false,
"text": ".outer {\n display: table;\n}\n\n.inner {\n height: 200px;\n display: table-cell;\n vertical-align: bottom;\n}\n\n/* Just for styling */\n.inner {\n background: #eee;\n padding: 0 20px;\n}"
},
{
"answer_id": 28509901,
"author": "Jeff",
"author_id": 4565295,
"author_profile": "https://Stackoverflow.com/users/4565295",
"pm_score": -1,
"selected": false,
"text": "<div id=\"container\">\n <div id=\"Header\"></div>\n <div id=\"Footer\"></div>\n <div id=\"Content\"></div>\n <div id=\"Sidebar\"></div>\n</div>\n"
},
{
"answer_id": 34202422,
"author": "m4n0",
"author_id": 4813913,
"author_profile": "https://Stackoverflow.com/users/4813913",
"pm_score": 2,
"selected": false,
"text": "align-self: flex-end"
},
{
"answer_id": 34960142,
"author": "Tushar Bohra",
"author_id": 5123996,
"author_profile": "https://Stackoverflow.com/users/5123996",
"pm_score": 2,
"selected": false,
"text": ".parent {\n display: flex;\n height: 100px;\n border: solid 1px #0f0f0f;\n}\n.child {\n margin-top: auto;\n border: solid 1px #000;\n width: 40px;\n word-break: break-all;\n}"
},
{
"answer_id": 37092162,
"author": "Filipe Pitacho",
"author_id": 6177367,
"author_profile": "https://Stackoverflow.com/users/6177367",
"pm_score": 3,
"selected": false,
"text": "#outer {\n width:10em;\n height:10em;\n background-color:blue;\n position:relative; \n}\n\n#inner {\n position:absolute;\n bottom:0;\n background-color:white; \n}"
},
{
"answer_id": 41294656,
"author": "olliew",
"author_id": 6145395,
"author_profile": "https://Stackoverflow.com/users/6145395",
"pm_score": -1,
"selected": false,
"text": ".invisible {\nfloat: left; \n}\n\n.bottom {\nfloat: left;\npadding-right: 35px;\npadding-top: 30px;\nclear: left;\n}\n"
},
{
"answer_id": 57353127,
"author": "rashedcs",
"author_id": 6714430,
"author_profile": "https://Stackoverflow.com/users/6714430",
"pm_score": 1,
"selected": false,
"text": "margin-top"
},
{
"answer_id": 62477307,
"author": "Vsevolod Azovsky",
"author_id": 3142281,
"author_profile": "https://Stackoverflow.com/users/3142281",
"pm_score": -1,
"selected": false,
"text": "<div class=\"block\">\n <a href=\"#\">Some Content with a very long description. Could be a Loren Ipsum or something like that.</a>\n <span>\n <span class=\"r-b\">A right-bottom-block with some information</span>\n </span>\n <span class=\"clearfix\"></span>\n</div>\n<style>\n .block {\n border: #000 solid 1px;\n }\n\n .r-b {\n border: #f00 solid 1px;\n background-color: fuchsia;\n float: right;\n width: 33%\n }\n\n .clearfix::after {\n display: block;\n clear: both;\n content: \"\";\n }\n</style>\n"
},
{
"answer_id": 62703235,
"author": "Zhiyong",
"author_id": 1350949,
"author_profile": "https://Stackoverflow.com/users/1350949",
"pm_score": 1,
"selected": false,
"text": ".speech-bubble {\n font-size: 16px;\n max-width: 240px;\n margin: 10px;\n display: inline-block;\n background-color: #ccc;\n border-radius: 5px;\n padding: 5px;\n position: relative;\n}\n\n.inline-time {\n float: right;\n padding-left: 10px;\n color: red;\n}\n\n.giant-text {\n font-size: 36px;\n}\n\n.tremendous-giant-text {\n font-size: 72px;\n}\n\n.absolute-time {\n position: absolute;\n color: green;\n right: 5px;\n bottom: 5px;\n}\n\n.hidden {\n visibility: hidden;\n}"
},
{
"answer_id": 62864841,
"author": "Mirajul Momin",
"author_id": 9274988,
"author_profile": "https://Stackoverflow.com/users/9274988",
"pm_score": 0,
"selected": false,
"text": "shape-outside"
},
{
"answer_id": 66708128,
"author": "strarsis",
"author_id": 4150808,
"author_profile": "https://Stackoverflow.com/users/4150808",
"pm_score": 0,
"selected": false,
"text": "\nconst resizeObserver = new ResizeObserver(entries => {\n if(entries.length == 0) return;\n const entry = entries[0];\n if(!entry.contentRect) return;\n\n const containerHeight = entry.contentRect.height;\n const imgHeight = imgElem.height;\n const imgOffset = containerHeight - imgHeight;\n \n imgElem.style.marginTop = imgOffset + 'px';\n});\n\nconst imgElem = document.querySelector('.image');\nresizeObserver.observe(imgElem.parentElement);\n"
},
{
"answer_id": 69749306,
"author": "PRConnect",
"author_id": 13064004,
"author_profile": "https://Stackoverflow.com/users/13064004",
"pm_score": 0,
"selected": false,
"text": "<style>\n #mainbox {border:4px solid red;width:500px;padding:10px;}\n .rightpad {float:right;clear:right;padding:0;width:0;}\n #floater {background-color:red;text-align:center;color:#FFF;width:300px;height:100px;float:right;margin-right:-10px;margin-top:10px;}\n</style>\n<script>\nwindow.onload = function() {\n var mmheight = document.getElementById(\"mainbox\").clientHeight;\n var ff = document.getElementById(\"floater\");\n var ffheight = ff.clientHeight;\n var dd = document.createElement('div');\n dd.className = \"rightpad\";\n dd.style.height = (mmheight - ffheight - 20) * 1 + \"px\";\n ff.parentNode.insertBefore(dd,ff);\n}\n</script>\n<div id=\"mainbox\">\n <div id=\"floater\" class=\"rightpad\">123</div>\n<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam posuere tellus et dolor vestibulum gravida. Donec vel nunc massa. Quisque quis varius libero. Fusce ut elementum magna. Praesent hendrerit diam sed velit rutrum mollis. Nunc pretium metus in tempus tempus. Quisque laoreet nibh eget volutpat dictum. Pellentesque libero ipsum, tristique et aliquam aliquam, accumsan sed sem. Phasellus facilisis sem eget mi tempus rhoncus.</p></div>\n"
},
{
"answer_id": 72666383,
"author": "Mykola Uspalenko",
"author_id": 8413306,
"author_profile": "https://Stackoverflow.com/users/8413306",
"pm_score": 0,
"selected": false,
"text": ".toBottomRight\n{\n display:inline-block;\n position:fixed;\n left:100%;\n top:100%;\n transform: translate(-100%, -100%);\n white-space:nowrap;\n background:red;\n}\n\n<div class=\"toBottomRight\">Bottom-Right</div>\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/311990",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/12845/"
] |
312,003 | <p>We all know that premature optimization is the root of all evil because it leads to unreadable/unmaintainable code. Even worse is pessimization, when someone implements an "optimization" because they <em>think</em> it will be faster, but it ends up being slower, as well as being buggy, unmaintainable, etc. What is the most ridiculous example of this that you've seen?</p>
| [
{
"answer_id": 312017,
"author": "Bill the Lizard",
"author_id": 1288,
"author_profile": "https://Stackoverflow.com/users/1288",
"pm_score": 6,
"selected": false,
"text": "String msg = \"Count = \" + count + \" of \" + total + \".\";\n"
},
{
"answer_id": 312059,
"author": "Dour High Arch",
"author_id": 22437,
"author_profile": "https://Stackoverflow.com/users/22437",
"pm_score": 4,
"selected": false,
"text": " 1 tuple *FindTuple( DataSet *set, int target ) {\n 2 tuple *found = null;\n 3 tuple *curr = GetFirstTupleOfSet(set);\n 4 while (curr) {\n 5 if (curr->id == target)\n 6 found = curr;\n 7 curr = GetNextTuple(curr);\n 8 }\n 9 return found;\n10 }\n"
},
{
"answer_id": 685047,
"author": "Overflown",
"author_id": 37840,
"author_profile": "https://Stackoverflow.com/users/37840",
"pm_score": 2,
"selected": false,
"text": "import java.lang.*;"
},
{
"answer_id": 686837,
"author": "Chetan S",
"author_id": 31284,
"author_profile": "https://Stackoverflow.com/users/31284",
"pm_score": 3,
"selected": false,
"text": "if (myObj) { //or its evil cousin, if (myObj != null) {\n label.text = myObj.value; \n // we know label exists because it has already been \n // checked in a big if block somewhere at the top\n}\n"
},
{
"answer_id": 687141,
"author": "KitsuneYMG",
"author_id": 86515,
"author_profile": "https://Stackoverflow.com/users/86515",
"pm_score": 4,
"selected": false,
"text": "public static String COMMA_DELIMINATOR=\",\";\npublic static String COMMA_SPACE_DELIMINATOR=\", \";\npublic static String COLIN_DELIMINATOR=\":\";\n"
},
{
"answer_id": 688777,
"author": "Abhishek",
"author_id": 65438,
"author_profile": "https://Stackoverflow.com/users/65438",
"pm_score": 2,
"selected": false,
"text": "if( CurrentUser.CurrentRole == \"Role1\" || CurrentUser.CurrentRole == \"Role2\") \n{\n// Access denied\n} \nelse\n{\n// Access granted\n}\n"
},
{
"answer_id": 689221,
"author": "Christoffer",
"author_id": 15514,
"author_profile": "https://Stackoverflow.com/users/15514",
"pm_score": 4,
"selected": false,
"text": "unsigned long isqrt(unsigned long value)\n{\n unsigned long tmp = 1, root = 0;\n #define ISQRT_INNER(shift) \\\n { \\\n if (value >= (tmp = ((root << 1) + (1 << (shift))) << (shift))) \\\n { \\\n root += 1 << shift; \\\n value -= tmp; \\\n } \\\n }\n\n // Find out how many bytes our value uses\n // so we don't do any uneeded work.\n if (value & 0xffff0000)\n {\n if ((value & 0xff000000) == 0)\n tmp = 3;\n else\n tmp = 4;\n }\n else if (value & 0x0000ff00)\n tmp = 2;\n\n switch (tmp)\n {\n case 4:\n ISQRT_INNER(15);\n ISQRT_INNER(14);\n ISQRT_INNER(13);\n ISQRT_INNER(12);\n case 3:\n ISQRT_INNER(11);\n ISQRT_INNER(10);\n ISQRT_INNER( 9);\n ISQRT_INNER( 8);\n case 2:\n ISQRT_INNER( 7);\n ISQRT_INNER( 6);\n ISQRT_INNER( 5);\n ISQRT_INNER( 4);\n case 1:\n ISQRT_INNER( 3);\n ISQRT_INNER( 2);\n ISQRT_INNER( 1);\n ISQRT_INNER( 0);\n }\n#undef ISQRT_INNER\n return root;\n}\n"
},
{
"answer_id": 690019,
"author": "Slartibartfast",
"author_id": 4433,
"author_profile": "https://Stackoverflow.com/users/4433",
"pm_score": 2,
"selected": false,
"text": "if (!loadFromDb().isEmpty) {\n resultList = loadFromDb();\n // do something with results\n}\n"
},
{
"answer_id": 692113,
"author": "Eddie",
"author_id": 57752,
"author_profile": "https://Stackoverflow.com/users/57752",
"pm_score": 4,
"selected": false,
"text": "int some_method(int input1, int input2) {\n int x;\n if (input1 == -1) {\n return 0;\n }\n if (input1 == input2) {\n return input1;\n }\n ... a long expression here ...\n return x;\n}\n"
},
{
"answer_id": 752691,
"author": "Stradas",
"author_id": 5410,
"author_profile": "https://Stackoverflow.com/users/5410",
"pm_score": 1,
"selected": false,
"text": "\nLoop \n arrayX.next_record\n if uniqueid_col = '829-39-3984'\n return col2\n end if\nend loop\n "
},
{
"answer_id": 810475,
"author": "Damovisa",
"author_id": 77546,
"author_profile": "https://Stackoverflow.com/users/77546",
"pm_score": 5,
"selected": false,
"text": "bool isFinished = GetIsFinished();\n\nswitch (isFinished)\n{\n case true:\n DoFinish();\n break;\n\n case false:\n DoNextStep();\n break;\n\n default:\n DoNextStep();\n}\n"
},
{
"answer_id": 1512050,
"author": "luft",
"author_id": 183393,
"author_profile": "https://Stackoverflow.com/users/183393",
"pm_score": 5,
"selected": false,
"text": "var stringBuilder = new StringBuilder();\nstringBuilder.Append(myObj.a + myObj.b + myObj.c + myObj.d);\nstring cat = stringBuilder.ToString();\n"
},
{
"answer_id": 4731578,
"author": "dan04",
"author_id": 287586,
"author_profile": "https://Stackoverflow.com/users/287586",
"pm_score": 3,
"selected": false,
"text": "CString"
},
{
"answer_id": 7406971,
"author": "Ville Krumlinde",
"author_id": 43673,
"author_profile": "https://Stackoverflow.com/users/43673",
"pm_score": 2,
"selected": false,
"text": "procedure sort(string[] values, string direction)\nbegin\n while not sorted do\n begin\n for every value in values\n begin\n if direction=\"Ascending\" then\n begin\n ... swap values in ascending order\n end\n else if direction=\"Descending\" then\n begin\n ... swap values in descending order\n end\n end;\n end;\nend;\n"
},
{
"answer_id": 7589310,
"author": "dhasenan",
"author_id": 311381,
"author_profile": "https://Stackoverflow.com/users/311381",
"pm_score": 2,
"selected": false,
"text": "while true; do echo 3 > /proc/sys/vm/drop_caches; sleep 3600; done\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312003",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/23903/"
] |
312,006 | <p>I have a system that creates an order and that order can be billed to a house account, sent Cash on Delivery (COD), or charged to a credit card. I've created the following tables:</p>
<p>ORDERS<br/>
order_id<br/>
billingoption_id</p>
<p>BILLINGOPTIONS<br/>
billingoption_id<br/></p>
<p>I'm unsure of how the next table should be built for the billing data. Should I build a separate table for each type of billing option (ie. COD, Credit Cards, and House Account)? Then would I have another foreign key column on the Orders table that would refer to a record for the billing data?</p>
| [
{
"answer_id": 312144,
"author": "Nicholas Piasecki",
"author_id": 32187,
"author_profile": "https://Stackoverflow.com/users/32187",
"pm_score": 4,
"selected": true,
"text": "billingoptions"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312006",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/37347/"
] |
312,009 | <p>I have two tables in a DataSet in .NET. I want to join them on an ID column. Then I want a DataGridView to display two columns from the first table and one column from the second table.</p>
<p>If it makes it easier, the relation between the two tables is one-to-one.</p>
<p>Can it be done?</p>
| [
{
"answer_id": 312686,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": " DataTable left = new DataTable\n {\n Columns = { {\"PK\", typeof(int)}, {\"Name\", typeof(string)}},\n Rows = {{1,\"abc\"},{2,\"def\"}}\n }, right = new DataTable\n {\n Columns = { { \"FK\", typeof(int) }, { \"Value\", typeof(decimal) } },\n Rows = { { 1, 123.45M }, { 2, 678.9M } }\n };\n var qry = from x in left.Rows.Cast<DataRow>()\n join y in right.Rows.Cast<DataRow>()\n on x.Field<int>(\"PK\") equals y.Field<int>(\"FK\")\n select new\n {\n Name = x.Field<string>(\"Name\"),\n Value = y.Field<decimal>(\"Value\")\n };\n var data = qry.ToList();\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312009",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/29281/"
] |
312,015 | <p>I'd like a textbox that allows for certain text within to be "constant" and uneditable while the rest of the text is editable. For instance, I'd like to define a template like this:</p>
<pre><code><Name:>[]
<Address:>[] <City>:[]
</code></pre>
<p>So that the user could later enter:</p>
<pre><code><Name:>[Stefan]
<Address:>[Nowhere] <City>:[Alaska]
</code></pre>
<p>But not:</p>
<pre><code><I'm typing here lol:>[Stefan]
<Address:>[Nowhere] <State>:[Alaska]
</code></pre>
<p>Ideally, they wouldn't even be able to put their cursor in between the <>, similar to Microsoft Word templates.</p>
<p>Any ideas? The masked textbox control seems to be along the right path, but isn't multiline and doesn't allow you to enter a variable number of characters in between the braces, for instance.</p>
<p>Thanks in advance.</p>
| [
{
"answer_id": 312023,
"author": "Frank Krueger",
"author_id": 338,
"author_profile": "https://Stackoverflow.com/users/338",
"pm_score": 3,
"selected": true,
"text": "(.*)"
},
{
"answer_id": 312668,
"author": "P Daddy",
"author_id": 36388,
"author_profile": "https://Stackoverflow.com/users/36388",
"pm_score": 1,
"selected": false,
"text": "SystemColors.Window"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312015",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13257/"
] |
312,022 | <p>is there any way to make IE6 understand double classes,
say I have a class MenuButton with a color class and possibly a clicked class;
like :</p>
<pre><code>.LeftContent a.MenuButton {..general rules..}
.LeftContent a.MenuButton.Orange {..sets background-image..}
.LeftContent a.MenuButton.Clicked {...hum ta dum...}
</code></pre>
<p>Now, IE6 understands <code><a class="MenuButton Orange"></code>, but when adding
Clicked, like <code><a class="MenuButton Orange Clicked"></code>, IE just ignores the
Clicked rule.</p>
<p>Of course, I could rewrite my CSS, and have own rules for .MenuButtonOrange<br>
and such (and it'd probably taken a lot shorter time than asking this question ;-),<br>
but golly, it just so unappealing and Web 0.9...</p>
<p>Cheers!</p>
| [
{
"answer_id": 312038,
"author": "Borgar",
"author_id": 27388,
"author_profile": "https://Stackoverflow.com/users/27388",
"pm_score": 6,
"selected": true,
"text": "Orange"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312022",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/447694/"
] |
312,024 | <p>I have a class Agent with a property Id</p>
<p>Given a collection of Agents I need to check if any of them have duplicate Ids.</p>
<p>I am currently doing this with a hash table but am trying to get Linq-ified, what's a good way of doing this?</p>
| [
{
"answer_id": 312033,
"author": "Yona",
"author_id": 40007,
"author_profile": "https://Stackoverflow.com/users/40007",
"pm_score": 1,
"selected": false,
"text": "foreach(var agent in Agents) {\n if(Agents.Count(a => a.ID == agent.ID) > 1)\n Console.WriteLine(\"Found: {0}\", agent.ID);\n}\n"
},
{
"answer_id": 312034,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 1,
"selected": false,
"text": "bool b = list.Any(i => list.Any(j => j.ID == i.ID && j != i));\n"
},
{
"answer_id": 312037,
"author": "Codewerks",
"author_id": 17729,
"author_profile": "https://Stackoverflow.com/users/17729",
"pm_score": 5,
"selected": true,
"text": " var duplicates = agents.GroupBy(a => a.ID).Where(a=>a.Count() > 1);\n\n foreach (var agent in duplicates)\n {\n Console.WriteLine(agent.Key.ToString());\n }\n"
},
{
"answer_id": 312723,
"author": "Amy B",
"author_id": 8155,
"author_profile": "https://Stackoverflow.com/users/8155",
"pm_score": 2,
"selected": false,
"text": "var duplicates = agents\n .GroupBy(a => a.ID)\n .Where(g => g.Skip(1).Any());\n"
},
{
"answer_id": 313450,
"author": "Matt Hamilton",
"author_id": 615,
"author_profile": "https://Stackoverflow.com/users/615",
"pm_score": 2,
"selected": false,
"text": "public class Foo\n{\n public int ID;\n}\n"
},
{
"answer_id": 39582921,
"author": "Niklas",
"author_id": 3956100,
"author_profile": "https://Stackoverflow.com/users/3956100",
"pm_score": 0,
"selected": false,
"text": " List<Agent> duplicates = new HashSet<Agent>(agents.Where(c => agents.Count(x => x.ID == c.ID) > 1)).ToList();\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312024",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/5056/"
] |
312,040 | <p>I'm writing a simple IDictionary abstraction in C# that wraps a
Dictionary<K, ICollection<V>>. Basically, it maps multiple values to one key. I can't decide whether to remove a key and its empty list when the last item in a values list is removed, or leave it (to avoid instantiating a new collection if the key is reused) and do checks on a key's values' Count when determining whether a key exists.</p>
| [
{
"answer_id": 312509,
"author": "Marc Gravell",
"author_id": 23354,
"author_profile": "https://Stackoverflow.com/users/23354",
"pm_score": 2,
"selected": false,
"text": "ILookup<TKey,TValue>"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312040",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18049/"
] |
312,044 | <p>I want to set the width of a TextBlock based on the width of its container, minus the margins set on the TextBlock.</p>
<p>Here is my code:</p>
<pre><code><TextBlock x:Name="txtStatusMessages"
Width="{Binding ElementName=LayoutRoot,Path=ActualWidth }"
TextWrapping="WrapWithOverflow"
Foreground="White"
Margin="5,5,5,5">This is a message
</TextBlock>
</code></pre>
<p>And that works great except for the fact that the TextBlock is 10 units too big due to the Left and Right Margins bbeing set to 5.</p>
<p>OK, so I thought... Let's use a Converter. But I don't know how to pass the ActualWidth of my container control (SEE ABOVE: LayoutRoot).</p>
<p>I know how to use converters, and even converters with parameters, just not a parameter like... Binding ElementName=LayoutRoot,Path=ActualWidth</p>
<p>For example, I can't make this work:</p>
<pre><code>Width="{Binding Converter={StaticResource PositionConverter},
ConverterParameter={Binding ElementName=LayoutRoot,Path=ActualWidth }}"
</code></pre>
<p>I hope I made this clear enough and hope that you can help because Google is no help for me tonight.</p>
| [
{
"answer_id": 312171,
"author": "Danny Varod",
"author_id": 38368,
"author_profile": "https://Stackoverflow.com/users/38368",
"pm_score": 5,
"selected": true,
"text": "Width=\"{Binding ElementName=LayoutRoot, Path=ActualWidth,\nConverter={StaticResource PositionConverter}, ConverterParameter=-5}\"\n"
},
{
"answer_id": 312206,
"author": "Gishu",
"author_id": 1695,
"author_profile": "https://Stackoverflow.com/users/1695",
"pm_score": 2,
"selected": false,
"text": "<Window x:Class=\"WpfApplication1.Window2\" ...\n xmlns:local=\"clr-namespace:WpfApplication1\"\n Title=\"Window2\" Height=\"300\" Width=\"300\">\n <Window.Resources>\n <local:WidthSansMarginConverter x:Key=\"widthConverter\" />\n </Window.Resources>\n <Grid>\n <StackPanel x:Name=\"stack\">\n <TextBlock x:Name=\"txtStatusMessages\" \n Width=\"{Binding ElementName=stack,Path=ActualWidth, \n Converter={StaticResource widthConverter}}\"\n TextWrapping=\"WrapWithOverflow\" \n Background=\"Aquamarine\" \n Margin=\"5,5,5,5\">\n This is a message\n </TextBlock>\n <TextBlock x:Name=\"txtWhatsWrongWithThis\" \n TextWrapping=\"WrapWithOverflow\" \n Background=\"Aquamarine\" \n Margin=\"5,5,5,5\">\n This is another message\n </TextBlock>\n </StackPanel>\n </Grid>\n</Window>\n"
},
{
"answer_id": 414121,
"author": "viggity",
"author_id": 4572,
"author_profile": "https://Stackoverflow.com/users/4572",
"pm_score": 0,
"selected": false,
"text": "HorizontalAlignment=\"Stretch\"\n"
},
{
"answer_id": 1205795,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "<ListView ... >\n<ListView.View>\n<GridView>\n <GridViewColumn Header=\"xyz\" >\n\n <GridViewColumn.Width>\n <MultiBinding Converter=\"{StaticResource GetWidthfromParentControl}\">\n <MultiBinding.Bindings>\n <Binding ElementName=\"lstNetwork\" Path=\"ActualWidth\"/>\n <Binding ElementName=\"MyGridView\"/>\n </MultiBinding.Bindings>\n </MultiBinding>\n </GridViewColumn.Width>\n ....\n </GridViewColumn>\n <GridViewColumn ...>\n ....\n </GridViewColumn>\n</GridView>\n</ListView.View>\n</ListView>\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312044",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/6514/"
] |
312,054 | <p>So I just spent 5 hours troubleshooting a problem which turned out to be due not only to the <a href="https://web.archive.org/web/20141209040727/http://classicasp.aspfaq.com/general/what-is-wrong-with-isnumeric.html" rel="nofollow noreferrer">old unreliable</a> <code>ISNUMERIC</code> but it looks like my problem only appears when the UDF in which <code>ISNUMERIC</code> is declared <code>WITH SCHEMABINDING</code> and is called within a stored proc (I've got a lot of work to do to distill it down into a test case, but my first need is to replace it with something reliable).</p>
<p>Any recommendations on good, efficient replacements for <code>ISNUMERIC()</code>. Obviously there really need to be variations for <code>int</code>, <code>money</code>, etc., but what are people using (preferably in T-SQL, because on this project, I'm restricted to SQL Server because this is a high-volume SQL Server to SQL Server data processing task)?</p>
| [
{
"answer_id": 312655,
"author": "HTTP 410",
"author_id": 13118,
"author_profile": "https://Stackoverflow.com/users/13118",
"pm_score": 4,
"selected": false,
"text": "NOT LIKE '%[^0-9]%'\n"
},
{
"answer_id": 312713,
"author": "Dave Markle",
"author_id": 24995,
"author_profile": "https://Stackoverflow.com/users/24995",
"pm_score": 6,
"selected": true,
"text": "SELECT CASE WHEN TRY_CAST('foo' AS INT) IS NULL THEN 0 ELSE 1 END\n\nSELECT CASE WHEN TRY_CAST(1 AS INT) IS NULL THEN 0 ELSE 1 END\n"
},
{
"answer_id": 485173,
"author": "Sam Schutte",
"author_id": 146,
"author_profile": "https://Stackoverflow.com/users/146",
"pm_score": 3,
"selected": false,
"text": "using namespace std;\n\nint checkNumber() {\n int number = 0;\n cin >> number;\n cin.ignore(numeric_limits<int>::max(), '\\n');\n\n if (!cin || cin.gcount() != 1)\n cout << \"Not a number.\";\n else\n cout << \"Your entered: \" << number;\n return 0;\n}\n"
},
{
"answer_id": 494981,
"author": "GateKiller",
"author_id": 383,
"author_profile": "https://Stackoverflow.com/users/383",
"pm_score": 1,
"selected": false,
"text": "CREATE FUNCTION dbo.isReallyNumeric \n( \n @num VARCHAR(64) \n) \nRETURNS BIT \nBEGIN \n IF LEFT(@num, 1) = '-' \n SET @num = SUBSTRING(@num, 2, LEN(@num)) \n\n DECLARE @pos TINYINT \n\n SET @pos = 1 + LEN(@num) - CHARINDEX('.', REVERSE(@num)) \n\n RETURN CASE \n WHEN PATINDEX('%[^0-9.-]%', @num) = 0 \n AND @num NOT IN ('.', '-', '+', '^') \n AND LEN(@num)>0 \n AND @num NOT LIKE '%-%' \n AND \n ( \n ((@pos = LEN(@num)+1) \n OR @pos = CHARINDEX('.', @num)) \n ) \n THEN \n 1 \n ELSE \n 0 \n END \nEND \nGO \n\nCREATE FUNCTION dbo.isReallyInteger \n( \n @num VARCHAR(64) \n) \nRETURNS BIT \nBEGIN \n IF LEFT(@num, 1) = '-' \n SET @num = SUBSTRING(@num, 2, LEN(@num)) \n\n RETURN CASE \n WHEN PATINDEX('%[^0-9-]%', @num) = 0 \n AND CHARINDEX('-', @num) <= 1 \n AND @num NOT IN ('.', '-', '+', '^') \n AND LEN(@num)>0 \n AND @num NOT LIKE '%-%' \n THEN \n 1 \n ELSE \n 0 \n END \nEND \nGO\n"
},
{
"answer_id": 1581195,
"author": "mattmc3",
"author_id": 83144,
"author_profile": "https://Stackoverflow.com/users/83144",
"pm_score": 0,
"selected": false,
"text": "create function dbo.udf_IsNumeric(@str varchar(50))\n returns int\nas\nbegin\n declare @rtn int\n select @rtn =\n case\n when ltrim(rtrim(@str)) in('.', '-', '-.', '+', '+.') then 0\n when ltrim(rtrim(@str)) like '%[^-+.0-9]%' then 0\n else isnumeric(@str)\n end\n return @rtn\nend\n"
},
{
"answer_id": 2510358,
"author": "c'est moi",
"author_id": 301104,
"author_profile": "https://Stackoverflow.com/users/301104",
"pm_score": 1,
"selected": false,
"text": "declare @test varchar(10), @num decimal\nselect @test = '0123A'\n\nbegin try\n select @num = cast(@test as decimal)\n print '1'\nend try \nbegin catch\n print '0'\nend catch\n"
},
{
"answer_id": 32990518,
"author": "CleanBold",
"author_id": 378986,
"author_profile": "https://Stackoverflow.com/users/378986",
"pm_score": 0,
"selected": false,
"text": "SELECT\n TRY_PARSE('123' as int) as '123'\n,TRY_PARSE('abc' as int) as 'abc'\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312054",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/18255/"
] |
312,055 | <p>Some repository clones I have allow me to do this:</p>
<pre><code>% git pull
% git push
</code></pre>
<p>But other repositories require me to type:</p>
<pre><code>% git pull origin master
% git push origin master
</code></pre>
<p>I think I am missing something in the latter case - does anyone know what is (not) going on here? I am using the latest git version, just obviously not using it well.</p>
| [
{
"answer_id": 312061,
"author": "Brian Gianforcaro",
"author_id": 3415,
"author_profile": "https://Stackoverflow.com/users/3415",
"pm_score": 5,
"selected": true,
"text": "[branch \"master\"]\n remote = origin\n merge = refs/heads/master\n"
},
{
"answer_id": 312267,
"author": "Aristotle Pagaltzis",
"author_id": 9410,
"author_profile": "https://Stackoverflow.com/users/9410",
"pm_score": 4,
"selected": false,
"text": "git config branch.master.remote origin\ngit config branch.master.merge refs/heads/master\n"
},
{
"answer_id": 395720,
"author": "mipadi",
"author_id": 28804,
"author_profile": "https://Stackoverflow.com/users/28804",
"pm_score": 3,
"selected": false,
"text": "git push master"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312055",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/14356/"
] |
312,091 | <p>My code opens more than 256 file handles, So When I run it on solaris machines I am ending up in "Exceeding file handlers limit" error. </p>
<p>I have two questions regarding this</p>
<p>1) Is this limit is only for 32 bit softwares or 64 bit softwares also suffer from it. I googled about it and came to know that 64 bit softwares do not have this limit.(<a href="http://developers.sun.com/solaris/articles/stdio_256.html" rel="nofollow noreferrer">http://developers.sun.com/solaris/articles/stdio_256.html</a>)
But I built 64 bit static object and when i use this it is giving the error. What actually 64 bit software means?</p>
<p>2) As given in the above link I used ulimit to increase file handlers limit (in run time, I mean just before running the command), exported extendedFile library and I am not got getting any error.What we have to do incase of Linux?</p>
<p>Thanks
D. L. Kumar</p>
| [
{
"answer_id": 312106,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 1,
"selected": false,
"text": "$ file `which ls`\n/bin/ls: ELF 64-bit LSB executable, x86-64, version 1 (SYSV), for GNU/Linux 2.6.9, dynamically linked (uses shared libs), stripped\n\n$ file my-32bit-exe\nmy-32bit-exe: ELF 32-bit LSB executable, Intel 80386, version 1 (SYSV), dynamically linked (uses shared libs), corrupted section header size\n"
},
{
"answer_id": 312177,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 1,
"selected": false,
"text": "cc -xarch=v9 ...\n"
},
{
"answer_id": 312587,
"author": "njsf",
"author_id": 4995,
"author_profile": "https://Stackoverflow.com/users/4995",
"pm_score": 0,
"selected": false,
"text": "#include <sys/resource.h>\n\nstruct rlimit rl;\ngetrlimit(RLIMIT_NOFILE,&rl);\nrl.rlim_cur = 1024; /* change it to 1024 - note has to be < than rl.rlim_max */\nsetrlimit(RLIMIT_NOFILE,&rl);\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312091",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
312,103 | <p>I know how to do this using for loops. Is it possible to do something like this using LINQ or lambdas?</p>
<pre><code>int[] a = { 10, 20, 30 };
int[] b = { 2, 4, 10 };
int[] c = a * b; //resulting array should be { 20, 80, 300 }
</code></pre>
| [
{
"answer_id": 312126,
"author": "Christian C. Salvadó",
"author_id": 5445,
"author_profile": "https://Stackoverflow.com/users/5445",
"pm_score": 2,
"selected": false,
"text": "int[] a = {10, 20, 30};\nint[] b = {2, 4, 10};\n\nif (a.Length == b.Length)\n{\n int[] result = (from i in Enumerable.Range(0, a.Length)\n let operation = a[i]*b[i]\n select operation).ToArray();\n}\n"
},
{
"answer_id": 312134,
"author": "Robert Wagner",
"author_id": 10784,
"author_profile": "https://Stackoverflow.com/users/10784",
"pm_score": 2,
"selected": false,
"text": "class Program\n{\n public static void Main(string[] args)\n {\n int[] a = { 10, 20, 30 };\n int[] b = { 2, 4, 10 };\n int[] c = a.MatrixMultiply(b);\n int[] c2 = a.Zip(b, (p1, p2) => p1 * p2);\n }\n}\n\npublic static class Extension\n{\n public static int[] MatrixMultiply(this int[] a, int[] b)\n {\n // TODO: Add guard conditions\n int[] c = new int[a.Length];\n for (int x = 0; x < a.Length; x++)\n {\n c[x] = a[x] * b[x];\n }\n return c;\n }\n\n public static R[] Zip<A, B, R>(this A[] a, B[] b, Func<A, B, R> func)\n {\n // TODO: Add guard conditions\n R[] result = new R[a.Length];\n for (int x = 0; x < a.Length; x++)\n {\n result[x] = func(a[x], b[x]);\n }\n return result;\n }\n}\n"
},
{
"answer_id": 312216,
"author": "Lance Fisher",
"author_id": 571,
"author_profile": "https://Stackoverflow.com/users/571",
"pm_score": 0,
"selected": false,
"text": "void ParMatrixMult(int size, double[,] m1, double[,] m2, double[,] result)\n{\n Parallel.For( 0, size, delegate(int i) {\n for (int j = 0; j < size; j++) {\n result[i, j] = 0;\n for (int k = 0; k < size; k++) {\n result[i, j] += m1[i, k] * m2[k, j];\n }\n }\n });\n}\n"
},
{
"answer_id": 312277,
"author": "Jon Skeet",
"author_id": 22656,
"author_profile": "https://Stackoverflow.com/users/22656",
"pm_score": 4,
"selected": true,
"text": "let"
},
{
"answer_id": 312280,
"author": "Cameron MacFarland",
"author_id": 3820,
"author_profile": "https://Stackoverflow.com/users/3820",
"pm_score": 3,
"selected": false,
"text": "int[] a = { 10, 20, 30 };\nint[] b = { 2, 4, 10 };\n\nint[] c = a.Zip(b, (a1, b1) => a1 * b1).ToArray();\n"
},
{
"answer_id": 44345292,
"author": "AlexMelw",
"author_id": 5259296,
"author_profile": "https://Stackoverflow.com/users/5259296",
"pm_score": 0,
"selected": false,
"text": "public static class TwodimensionalArrayExtensions\n{\n public static int[][] MultiplyBy(this int[][] leftMatrix, int[][] rightMatrix)\n {\n if (leftMatrix[0].Length != rightMatrix.Length)\n {\n return null; // Matrices are of incompatible dimensions\n }\n\n return leftMatrix.Select( // goes through <leftMatrix matrix> row by row\n\n (leftMatrixRow, leftMatrixRowIndexThatIsNotUsed) =>\n\n rightMatrix[0].Select( // goes through first row of <rightMatrix> cell by cell\n\n (rightFirstRow, rightMatrixColumnIndex) =>\n\n rightMatrix\n .Select(rightRow => rightRow[rightMatrixColumnIndex]) // selects column from <rightMatrix> for <rightMatrixColumnIndex>\n .Zip(leftMatrixRow, (rowCell, columnCell) => rowCell * columnCell) // does scalar product\n .Sum() // computes the sum of the products (rowCell * columnCell) sequence.\n )\n .ToArray() // the new cell within computed matrix\n )\n .ToArray(); // the computed matrix itself\n }\n}\n"
},
{
"answer_id": 67122861,
"author": "Philipp Kramer",
"author_id": 15659215,
"author_profile": "https://Stackoverflow.com/users/15659215",
"pm_score": 0,
"selected": false,
"text": "int[][] Multiply(int[][] left, int[][] right) =>\n left.Select(lr => \n right\n .Select(rr => \n lr.Zipped(rr, (l, r) => l * r).Sum())\n .ToArray())\n .ToArray();\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312103",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2470/"
] |
312,115 | <p>I'm getting some really wierd linking errors from a class I wrote. I am completely unable to find anything that will describe what is happening. </p>
<p>Visual Studio (Windows XP)</p>
<blockquote>
<p>players.obj : error LNK2019: unresolved external symbol "public: __thiscall TreeNode::TreeNode(void)" (??0?$TreeNode@VPlayer@@@@QAE@XZ) referenced in function "public: __thiscall PlayerList::PlayerList(void)" (??0PlayerList@@QAE@XZ)</p>
</blockquote>
<p>Xcode (OSX 10.5)</p>
<blockquote>
<p>Undefined symbols: "TreeNode::~TreeNode()", referenced from: PlayerList::~PlayerList()in players.o</p>
</blockquote>
<p>Header File: generics.h</p>
<pre><code>class TreeNode : public BaseNode{
public:
const static int MAX_SIZE = -1; //-1 means any size allowed.
const static int MIN_SIZE = 0;
//getters
int size() const;
vector<C*> getChildren() const;
//setters
void setChildren(vector<C*> &list);
//Serialization
virtual void display(ostream &out) const;
virtual void read(istream &in);
virtual void write(ostream &out) const;
//Overrides so SC acts like an array of sorts.
virtual C* get(int id) const;
virtual int get(C *child) const;
virtual bool has(C *child) const;
virtual C* pop(int id);
virtual void push(C *child);
virtual TreeNode& operator<< (C *child); //append
virtual void remove(int id); //Clears memory
virtual void remove(C *child); //Clears memory
//Initalizers
TreeNode();
TreeNode(istream &in);
TreeNode(long id, istream &in);
TreeNode(BaseNode* parent, istream &in);
TreeNode(long id, BaseNode* parent);
TreeNode(long id, BaseNode* parent, istream &in);
~TreeNode();
string __name__() const{ return "TreeNode"; }
protected:
void clearChildren();
void initalizeChildren();
vector<C*> _children;
};
</code></pre>
<p>Code from a subclass of TreeNode</p>
<pre><code>PlayerList::PlayerList() : TreeNode<Player>(){}
PlayerList::PlayerList(istream &in) : TreeNode<Player>(in){}
PlayerList::~PlayerList(){}
</code></pre>
| [
{
"answer_id": 312127,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 0,
"selected": false,
"text": "TreeNode::TreeNode() :\n /* initializers here */\n{\n // ...\n}\n\nTreeNode::~TreeNode()\n{\n // ...\n}\n"
},
{
"answer_id": 312402,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 5,
"selected": true,
"text": "template class TreeNode<Player>;\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312115",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16204/"
] |
312,116 | <p>I have a simple function in which an array is declared with size
depending on the parameter which is int.</p>
<pre><code> void f(int n){
char a[n];
};
int main() {
return 0;
}
</code></pre>
<p>This piece of code compiles fine on <a href="http://en.wikipedia.org/wiki/G%2B%2B" rel="noreferrer">GNU C++</a>, but not on MSVC 2005.</p>
<p>I get the following compilation errors:</p>
<pre><code> .\main.cpp(4) : error C2057: expected constant expression
.\main.cpp(4) : error C2466: cannot allocate an array of constant size 0
.\main.cpp(4) : error C2133: 'a' : unknown size
</code></pre>
<p>What can I do to correct this?</p>
<p>(I'm interested in making this work with MSVC,without using new/delete)</p>
| [
{
"answer_id": 312120,
"author": "Jim Buck",
"author_id": 2666,
"author_profile": "https://Stackoverflow.com/users/2666",
"pm_score": 3,
"selected": false,
"text": "char *a = (char *)_alloca(n);\n"
},
{
"answer_id": 312121,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 2,
"selected": false,
"text": "void f(int n) {\n boost::scoped_array<char> a(new char[n]);\n\n /* Code here. */\n}\n"
},
{
"answer_id": 312125,
"author": "Jack Klein",
"author_id": 40022,
"author_profile": "https://Stackoverflow.com/users/40022",
"pm_score": 6,
"selected": true,
"text": "new []"
},
{
"answer_id": 403242,
"author": "Joseph Garvin",
"author_id": 50385,
"author_profile": "https://Stackoverflow.com/users/50385",
"pm_score": 1,
"selected": false,
"text": "\nchar *a = new char [n];\n"
},
{
"answer_id": 2016723,
"author": "David Thornley",
"author_id": 14148,
"author_profile": "https://Stackoverflow.com/users/14148",
"pm_score": 1,
"selected": false,
"text": "vector<>"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312116",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/34051/"
] |
312,124 | <p>How do I apply a <em>repeating</em> texture that always maintains its original scale (1 pixel in the texture = 1 pixel on screen), regardless of the vertex data it is applied with.</p>
<p>I realize this is not the most usual task, but is it possible to easily set opengl to do this, or do I need to apply some kind of mask to vertex data that respects its original appearance?</p>
<p>edit: in my specific case, I'm trying to draw 2D ellipses of different sizes, with the same pixel pattern. The ellipses are made of a triangle fan, and I'm having a hard time to draw a repeating texture of any kind on it. I was hoping there was some opengl configuration combination to do this easily. Also, now I realize it's important to mention that I'm using opengles, for the iphone, so GLU is not available.</p>
| [
{
"answer_id": 312377,
"author": "Chris",
"author_id": 15578,
"author_profile": "https://Stackoverflow.com/users/15578",
"pm_score": 4,
"selected": true,
"text": "const XSize = 640, YSize = 480\nglMatrixMode (GL_PROJECTION)\nglLoadIdentity ()\nglOrtho (0, XSize, YSize, 0, 0, 1)\nglMatrixMode (GL_MODELVIEW)\nglDisable(GL_DEPTH_TEST)\nglClear(GL_COLOR_BUFFER_BIT)\n\n// Now draw with 2i or 2f vertices instead of the normal vertex3f functions.\n// And for ES, of course set up your data structures and call drawarrays ofr drawelements.\n\nSwapBuffers()\n"
},
{
"answer_id": 354140,
"author": "genpfault",
"author_id": 44729,
"author_profile": "https://Stackoverflow.com/users/44729",
"pm_score": 2,
"selected": false,
"text": "reshape()"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312124",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/36182/"
] |
312,150 | <p>Getting started with jquery and having trouble getting hello world type example going for asp.net mvc. I get a runtime error "object expected" when trying to load a page with this script. </p>
<p>A. Where should script tags be placed in a master page?
B. What might I be doing wrong? There are definitely "a" elements in my page?</p>
<pre><code><script src="../Scripts/jquery-1.2.6.min.js" type="text/javascript"></script>
<script src="../Scripts/jquery.corner.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
$("a").click(function(event) {
alert("Thanks for visiting!");
});
});
</script>
</code></pre>
| [
{
"answer_id": 312162,
"author": "Dan Esparza",
"author_id": 19020,
"author_profile": "https://Stackoverflow.com/users/19020",
"pm_score": 3,
"selected": false,
"text": "<head>"
},
{
"answer_id": 312319,
"author": "æther",
"author_id": 39899,
"author_profile": "https://Stackoverflow.com/users/39899",
"pm_score": 2,
"selected": true,
"text": "$"
},
{
"answer_id": 315477,
"author": "Todd Smith",
"author_id": 31624,
"author_profile": "https://Stackoverflow.com/users/31624",
"pm_score": 1,
"selected": false,
"text": "<script src=\"../Scripts/jquery-1.2.6.min.js\" type=\"text/javascript\"></script> \n<script src=\"../Scripts/jquery.corner.js\" type=\"text/javascript\"></script>\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312150",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
312,163 | <p>How would I go about implementation the queries required for pagination?</p>
<p>Basically, when page 1 is requested, get the first 5 entries. For page 2, get the next 5 and so on.</p>
<p>I plan to use this via the couchdb-python module, but that shouldn't make any difference to the implementation.</p>
| [
{
"answer_id": 312166,
"author": "dbr",
"author_id": 745,
"author_profile": "https://Stackoverflow.com/users/745",
"pm_score": 1,
"selected": false,
"text": "posthelper.page()"
},
{
"answer_id": 314532,
"author": "Kerr",
"author_id": 39392,
"author_profile": "https://Stackoverflow.com/users/39392",
"pm_score": 4,
"selected": false,
"text": "startkey"
},
{
"answer_id": 6475173,
"author": "AlexChaffee",
"author_id": 190135,
"author_profile": "https://Stackoverflow.com/users/190135",
"pm_score": 6,
"selected": true,
"text": "rows_per_page + 1"
},
{
"answer_id": 56641037,
"author": "Manvendra Jina",
"author_id": 2360837,
"author_profile": "https://Stackoverflow.com/users/2360837",
"pm_score": 0,
"selected": false,
"text": " var lastOffset = 0; var counter = 0;\n\n function someRecursive(lastOffset,counter) {\n\n queryView(db, whereClause).then(result => {\n var rows_per_page = 5; \n\n//formula below \nvar page = Math.floor((lastOffset == 0 ? 0: (result.offset - lastOffset) +\n\n (rows_per_page * counter)) / rows_per_page) + 1;\n\n var skip = page * rows_per_page;\n if (somerecursionexitcondition) {\n counter = lastOffset == 0 ? lastOffset: counter + 1;\n lastOffset =result.offset;\n someRecursive(lastOffset, counter).then(result => {\n resolve();\n\n });\n });\n\n }\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312163",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/745/"
] |
312,168 | <p>So I was making a class the other day and used Eclipse's method to create the equals method when I realized that it generated the following <strong>working</strong> code:</p>
<pre><code>class Test {
private int privateInt;
[...]
public boolean equals(Object obj) {
[...]
Test t = (Test) obj;
if ( t.privateInt == privateInt ) {
[...]
}
}
</code></pre>
<p>t.privateInt..???? It's suppose to be private! So I guess there is one more field visibility other than private, protected, package protected and public.</p>
<p>So what is happening here? How is this called? <strong>Where would somebody use this?</strong> Doesn't this break encapsulation? What if the class didn't have a mutator and I changed this? Does this happen to C++ as well? Is this an OO idiom? If not, then why did Java do it?</p>
<p>Generally, where can I find information about this?</p>
<p>Thank you.</p>
| [
{
"answer_id": 312178,
"author": "Michael Sharek",
"author_id": 1958,
"author_profile": "https://Stackoverflow.com/users/1958",
"pm_score": 6,
"selected": true,
"text": "if ( t.privateInt == this.privateInt )\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312168",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2644/"
] |
312,170 | <ol>
<li>VARCHAR does not store Unicode characters.</li>
<li>NVARCHAR does store Unicode characters.</li>
<li>Today's applications should always be Unicode compatible.</li>
<li>NVARCHAR takes twice the amount of space to store it.</li>
<li>Point 4 doesn't matter because storage space is extremely inexpensive.</li>
</ol>
<p>Ergo: When designing SQL Server databases today, one should always use NVARCHAR.</p>
<p>Is this sound reasoning? Does anyone disagree with any of the premises?
Are there any reasons to choose VARCHAR over NVARCHAR today?</p>
| [
{
"answer_id": 312246,
"author": "Michael Trausch",
"author_id": 26534,
"author_profile": "https://Stackoverflow.com/users/26534",
"pm_score": 2,
"selected": false,
"text": "VARCHAR"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312170",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/4639/"
] |
312,184 | <p>Extension method is a really helpful feature that you can add a lot of functions you want in any class. But I am wondering if there is any disadvantage that might bring troubles to me. Any comments or suggestions?</p>
| [
{
"answer_id": 55989940,
"author": "Mukesh Adhvaryu",
"author_id": 2226467,
"author_profile": "https://Stackoverflow.com/users/2226467",
"pm_score": 0,
"selected": false,
"text": "public interface IPointF{\n float X { get; }\n float Y { get; }\n}\n\npublic struct PointF: IPointF{\n public PointF(float x, float y){\n X=x;Y=y;\n }\n public float X { get; private set; }\n public float Y { get; private set; }\n}\n\npublic static class PointHelper{\n public static PointF ADD(this IPointF p, float val){\n return new PointF(p.x+val, p.y+val);\n }\n}\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312184",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40029/"
] |
312,185 | <p>I am new to C++ on MacOS.
I got an error when I used <code>kbhit()</code> in my program.</p>
<p>I used <code>#include<conio.h></code> but got error too, so I searched and test with <code>#include<curses.h></code> but error is still remained.</p>
| [
{
"answer_id": 312198,
"author": "Evan Teran",
"author_id": 13430,
"author_profile": "https://Stackoverflow.com/users/13430",
"pm_score": 2,
"selected": false,
"text": "int mygetch() {\n char ch;\n int error;\n static struct termios Otty, Ntty;\n\n fflush(stdout);\n tcgetattr(0, &Otty);\n Ntty = Otty;\n\n Ntty.c_iflag = 0; /* input mode */\n Ntty.c_oflag = 0; /* output mode */\n Ntty.c_lflag &= ~ICANON; /* line settings */\n\n#if 1\n /* disable echoing the char as it is typed */\n Ntty.c_lflag &= ~ECHO; /* disable echo */\n#else\n /* enable echoing the char as it is typed */\n Ntty.c_lflag |= ECHO; /* enable echo */\n#endif\n\n Ntty.c_cc[VMIN] = CMIN; /* minimum chars to wait for */\n Ntty.c_cc[VTIME] = CTIME; /* minimum wait time */\n\n#if 1\n /*\n * use this to flush the input buffer before blocking for new input\n */\n #define FLAG TCSAFLUSH\n#else\n /*\n * use this to return a char from the current input buffer, or block if\n * no input is waiting.\n */\n #define FLAG TCSANOW\n\n#endif\n\n if ((error = tcsetattr(0, FLAG, &Ntty)) == 0) {\n error = read(0, &ch, 1 ); /* get char from stdin */\n error += tcsetattr(0, FLAG, &Otty); /* restore old settings */\n }\n\n return (error == 1 ? (int) ch : -1 );\n}\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312185",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
312,187 | <p>I've seen quite a few developer job postings recently that include a sentence that reads more or less like this: "Must have experience with N-Tier architecture", or "Must be able to develop N-Tier apps".</p>
<p>This leads me to ask, what is N-Tier architecture? How does one gain experience with it?</p>
| [
{
"answer_id": 51452261,
"author": "Manjitha Teshara",
"author_id": 8077972,
"author_profile": "https://Stackoverflow.com/users/8077972",
"pm_score": 2,
"selected": false,
"text": "In a closed layer architecture, a layer can only call the next layer immediately down.\nIn an open layer architecture, a layer can call any of the layers below it.\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312187",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/8409/"
] |
312,188 | <p>I am given an integer (lets call it x) and I need to generate an array of arrays, where each subarray is a list of elements which are one of a given set of integers, and the sum of all of the elements of each subarray is x. The array of arrays needs to contain all possible distinct subarrays of this form.</p>
<p>For example, if x is 3 and the list of possible elements is {1, 2}, I'm looking to generate {{1, 2}, {2, 1}}.</p>
<p>What would be the best way to go about doing this (in pseudocode or Java)? Is this 2D array the best way to store this type of data? I couldn't think of anything better, but I'm guessing there is something out there.</p>
| [
{
"answer_id": 312209,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 0,
"selected": false,
"text": "ArrayList<E>"
},
{
"answer_id": 312237,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 1,
"selected": false,
"text": "LinkedList<HashSet<Integer>> l;\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312188",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40036/"
] |
312,213 | <p>I want to use part of the output of a command run from the command line in another xterm, or as part of a different command. For instance: </p>
<pre><code>> grep error error.log
error: can't find file ~/<some very long path>/thisfile
</code></pre>
<p>and I want to do this:</p>
<pre><code>>ls ~/<some very long path>/
</code></pre>
<p>I know two ways to do this:<br>
1. copy <code>~/<some very long path>/</code> with the mouse.<br>
2. use some combination of <code>head</code>/<code>tail</code>/<code>awk</code>/<code>sed</code>/<code>perl</code>/<code>cut</code>/etc... to extract only what I need from the output and then use <em>that</em> inside backticks.</p>
<p>Is there any way to copy text without using the mouse? The example that comes to mind is visual mode inside VIM, but I don't know how to do that inside the xterm.</p>
| [
{
"answer_id": 312215,
"author": "strager",
"author_id": 39992,
"author_profile": "https://Stackoverflow.com/users/39992",
"pm_score": 7,
"selected": true,
"text": "screen"
},
{
"answer_id": 318874,
"author": "salty-horse",
"author_id": 16081,
"author_profile": "https://Stackoverflow.com/users/16081",
"pm_score": 4,
"selected": false,
"text": "grep error error.log | xsel -bi\n"
},
{
"answer_id": 324592,
"author": "iankits",
"author_id": 24813,
"author_profile": "https://Stackoverflow.com/users/24813",
"pm_score": 1,
"selected": false,
"text": "xyz$ls /home/ankit/documents/etc/x/y/z > /dev/pts/0 \n"
},
{
"answer_id": 28716108,
"author": "Silveri",
"author_id": 690188,
"author_profile": "https://Stackoverflow.com/users/690188",
"pm_score": 3,
"selected": false,
"text": "tmux"
},
{
"answer_id": 61177064,
"author": "StefTN",
"author_id": 10310142,
"author_profile": "https://Stackoverflow.com/users/10310142",
"pm_score": 1,
"selected": false,
"text": "byobu"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312213",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/1084/"
] |
312,214 | <p>I already have a deploy.rb that can deploy my app on my production server. </p>
<p>My app contains a custom rake task (a .rake file in the lib/tasks directory). </p>
<p>I'd like to create a cap task that will remotely run that rake task.</p>
| [
{
"answer_id": 312227,
"author": "Richard Poirier",
"author_id": 26842,
"author_profile": "https://Stackoverflow.com/users/26842",
"pm_score": 6,
"selected": true,
"text": "run(\"cd #{deploy_to}/current && /usr/bin/env rake `<task_name>` RAILS_ENV=production\")\n"
},
{
"answer_id": 2192052,
"author": "Coward",
"author_id": 265273,
"author_profile": "https://Stackoverflow.com/users/265273",
"pm_score": 6,
"selected": false,
"text": "\\config\\deploy.rb"
},
{
"answer_id": 3337284,
"author": "acw",
"author_id": 291395,
"author_profile": "https://Stackoverflow.com/users/291395",
"pm_score": 1,
"selected": false,
"text": "run(\"cd #{release_path}/current && /usr/bin/rake <rake_task_name>\", :env => {'RAILS_ENV' => rails_env})\n"
},
{
"answer_id": 6351396,
"author": "Duke",
"author_id": 479017,
"author_profile": "https://Stackoverflow.com/users/479017",
"pm_score": 2,
"selected": false,
"text": "def rake(cmd, options={}, &block)\n command = \"cd #{current_release} && /usr/bin/env bundle exec rake #{cmd} RAILS_ENV=#{rails_env}\"\n run(command, options, &block)\nend\n"
},
{
"answer_id": 7229699,
"author": "Szymon Jeż",
"author_id": 408011,
"author_profile": "https://Stackoverflow.com/users/408011",
"pm_score": 3,
"selected": false,
"text": "def run_rake(task, options={}, &block)\n command = \"cd #{latest_release} && /usr/bin/env bundle exec rake #{task}\"\n run(command, options, &block)\nend\n"
},
{
"answer_id": 9058570,
"author": "Yacc",
"author_id": 368914,
"author_profile": "https://Stackoverflow.com/users/368914",
"pm_score": 3,
"selected": false,
"text": "cape"
},
{
"answer_id": 10491397,
"author": "captainpete",
"author_id": 325676,
"author_profile": "https://Stackoverflow.com/users/325676",
"pm_score": 4,
"selected": false,
"text": "require 'bundler/capistrano'"
},
{
"answer_id": 13745413,
"author": "Darme",
"author_id": 869616,
"author_profile": "https://Stackoverflow.com/users/869616",
"pm_score": 2,
"selected": false,
"text": "namespace :rake_task do\n task :invoke do\n if ENV['COMMAND'].to_s.strip == ''\n puts \"USAGE: cap rake_task:invoke COMMAND='db:migrate'\" \n else\n run \"cd #{current_path} && RAILS_ENV=production rake #{ENV['COMMAND']}\"\n end\n end \nend \n"
},
{
"answer_id": 17463330,
"author": "Sairam",
"author_id": 208928,
"author_profile": "https://Stackoverflow.com/users/208928",
"pm_score": 1,
"selected": false,
"text": "$ cap rake -s rake_task=$rake_task\n\n# Capfile \ntask :rake do\n rake = fetch(:rake, 'rake')\n rails_env = fetch(:rails_env, 'production')\n\n run \"cd '#{current_path}' && #{rake} #{rake_task} RAILS_ENV=#{rails_env}\"\nend\n"
},
{
"answer_id": 20506207,
"author": "Mirek Rusin",
"author_id": 177776,
"author_profile": "https://Stackoverflow.com/users/177776",
"pm_score": 5,
"selected": false,
"text": "desc 'Runs rake db:migrate if migrations are set'\ntask :migrate => [:set_rails_env] do\n on primary fetch(:migration_role) do\n within release_path do\n with rails_env: fetch(:rails_env) do\n execute :rake, \"db:migrate\"\n end\n end\n end\nend\n"
},
{
"answer_id": 22234123,
"author": "marinosb",
"author_id": 1063924,
"author_profile": "https://Stackoverflow.com/users/1063924",
"pm_score": 6,
"selected": false,
"text": "desc 'Invoke a rake command on the remote server'\ntask :invoke, [:command] => 'deploy:set_rails_env' do |task, args|\n on primary(:app) do\n within current_path do\n with :rails_env => fetch(:rails_env) do\n rake args[:command]\n end\n end\n end\nend\n"
},
{
"answer_id": 26007059,
"author": "Robin Clowers",
"author_id": 69047,
"author_profile": "https://Stackoverflow.com/users/69047",
"pm_score": 1,
"selected": false,
"text": "task :invoke, [:command] => 'deploy:set_rails_env' do |task, args|\n on primary(:app) do\n within current_path do\n with :rails_env => fetch(:rails_env) do\n execute :rake, \"#{args.command}[#{args.extras.join(\",\")}]\"\n end\n end\n end\nend\n"
},
{
"answer_id": 30179906,
"author": "newdark-it",
"author_id": 1431800,
"author_profile": "https://Stackoverflow.com/users/1431800",
"pm_score": 0,
"selected": false,
"text": "SSHKit.config.output_verbosity = Logger::DEBUG\n"
},
{
"answer_id": 34430541,
"author": "Abram",
"author_id": 881559,
"author_profile": "https://Stackoverflow.com/users/881559",
"pm_score": 2,
"selected": false,
"text": "task :invoke, :command do |task, args|\n on roles(:app) do\n within current_path do\n with rails_env: fetch(:rails_env) do\n execute :rake, args[:command]\n end\n end\n end\nend\n"
},
{
"answer_id": 36331449,
"author": "Sheharyar",
"author_id": 1533054,
"author_profile": "https://Stackoverflow.com/users/1533054",
"pm_score": 4,
"selected": false,
"text": "capistrano-rake"
},
{
"answer_id": 57925692,
"author": "A.Miroshnichenko",
"author_id": 8610880,
"author_profile": "https://Stackoverflow.com/users/8610880",
"pm_score": 1,
"selected": false,
"text": "namespace :deploy do\n # ....\n # @example\n # bundle exec cap uat deploy:invoke task=users:update_defaults\n desc 'Invoke rake task on the server'\n task :invoke do\n fail 'no task provided' unless ENV['task']\n\n on roles(:app) do\n within release_path do\n with rails_env: fetch(:rails_env) do\n execute :rake, ENV['task']\n end\n end\n end\n end\n\nend\n"
},
{
"answer_id": 71464570,
"author": "yosefbennywidyo",
"author_id": 6924999,
"author_profile": "https://Stackoverflow.com/users/6924999",
"pm_score": 0,
"selected": false,
"text": "namespace :rails_staging_task do\n desc \"Create custom role\"\n task :create_custom_role do\n on roles(:app), in: :sequence, wait: 5 do\n within \"#{deploy_to}/current\" do\n with rails_env: :staging do\n rake \"create_role:my_custom_role\"\n end\n end\n end\n end\n\n # other task here\nend\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312214",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/26842/"
] |
312,230 | <p>When working with PDFs, I've run across the MIME types <code>application/pdf</code> and <code>application/x-pdf</code> among others. </p>
<p>Is there a difference between these two types, and if so what is it? Is one preferred over the other?</p>
<p>I'm working on a web app which must deliver huge amounts of PDFs and I want to do it the correct way, if there is one.</p>
| [
{
"answer_id": 312258,
"author": "Chris Hanson",
"author_id": 714,
"author_profile": "https://Stackoverflow.com/users/714",
"pm_score": 12,
"selected": true,
"text": "application/pdf"
},
{
"answer_id": 34262538,
"author": "Lucky",
"author_id": 1793718,
"author_profile": "https://Stackoverflow.com/users/1793718",
"pm_score": 5,
"selected": false,
"text": "top-level type name / subtype name [ ; parameters ]\n\ntop-level type name / [ tree. ] subtype name [ +suffix ] [ ; parameters ]\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312230",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/20745/"
] |
312,245 | <p>I want to know what's the difference between string and stream in c++, and what's stringstream?</p>
| [
{
"answer_id": 312301,
"author": "orip",
"author_id": 37020,
"author_profile": "https://Stackoverflow.com/users/37020",
"pm_score": 3,
"selected": false,
"text": "istream"
},
{
"answer_id": 312309,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 2,
"selected": false,
"text": "fprintf()"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312245",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40040/"
] |
312,263 | <p>What is a good way to implement keyboard handling? In any language, where I write a keyboard-interactive program (such as a tetris game), I end up having some code that looks like this:</p>
<pre><code>for event in pygame.event.get():
if event.type == KEYDOWN:
if False: pass #make everything an elif
elif rotating: pass
elif event.key == K_q:
elif event.key == K_e:
elif event.key == K_LEFT:
curpiece.shift(-1, 0)
shadowpiece = curpiece.clone(); setupshadow(shadowpiece)
elif event.key == K_RIGHT:
curpiece.shift(1, 0)
shadowpiece = curpiece.clone(); setupshadow(shadowpiece)
</code></pre>
<p>(shortened). I don't like this, as this has to go in my main loop, and it messes with all parts of the program. This also makes it impossible to have a user config screen where they can change which key maps to which action. Is there a good pattern to do this using some form of function callbacks?</p>
| [
{
"answer_id": 312270,
"author": "andrewrk",
"author_id": 432,
"author_profile": "https://Stackoverflow.com/users/432",
"pm_score": 5,
"selected": true,
"text": "def handle_quit():\n quit()\n\ndef handle_left():\n curpiece.shift(-1, 0)\n shadowpiece = curpiece.clone(); setupshadow(shadowpiece)\n\ndef handle_right():\n curpiece.shift(1, 0)\n shadowpiece = curpiece.clone(); setupshadow(shadowpiece)\n\ndef handle_pause():\n if not paused:\n paused = True\n\nbranch = {\n K_q: handle_quit\n K_e: handle_pause\n K_LEFT: handle_left\n K_RIGHT: handle_right\n}\n\nfor event in pygame.event.get():\n if event.type == KEYDOWN:\n branch[event.key]()\n"
},
{
"answer_id": 314000,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 2,
"selected": false,
"text": "class InputHandler:\n def __init__ (self, eventDispatcher):\n self.keys = {}\n self.eventDispatcher = eventDispatcher\n def add_key_binding (self, key, event):\n self.keys.update((key, event,))\n def gather_input (self):\n for event in pygame.event.get():\n if event.type == KEYDOWN:\n event = self.keys.get(event.key, None)\n if not event is None:\n self.eventDispatcher.dispatch(event)\n\n....\ninputHandler = InputHandler(EventDispatcher)\ninputHandler.add_key_binding(K_q, \"quit_event\")\n...\ninputHandler.gather_input()\n....\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312263",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/15055/"
] |
312,273 | <p>I have a query (which was created by LINQ to SQL) to get me a list of 'site visits' that were made between a certain date range which resulted in an order (orderid is not null).</p>
<p>Theres nothing wrong with the query. I just need advice on creating the correct index for it. I was playing around trying different combinations on a production site and managed to screw things up such that a foreign key got disconnected. I fixed that after some panic - but thought I'd ask for advice now before recreating an index. </p>
<p>The table is getting close to a million rows and I need the indexes to help me out here. This query is only used for reporting so doesnt have to be extremely fast, just not delay other user's queries (which it is doing).</p>
<pre><code>SELECT TOP 1000
t0.SiteVisitId, t0.OrderId, t0.Date,
t1.Domain, t0.Referer, t0.CampaignId
FROM
SiteVisit AS t0
LEFT OUTER JOIN KnownReferer AS t1 ON t1.KnownRefererId = t0.KnownRefererId
WHERE
t0.Date <= @p0
AND t0.Date >= @p1
AND t0.OrderId IS NOT NULL
ORDER BY
t0.Date DESC
@p0='2008-11-1 23:59:59:000', @p1='2008-10-1 00:00:00:000'
</code></pre>
<p>I currently have a clustered index on <code>SiteVisitId</code>, which is my identity integer column.</p>
<p>I dont know which of the following are most likely to be most efficient:</p>
<ul>
<li>Create an index on <code>Date</code> </li>
<li>Create an index on <code>Date</code> AND a separate index on <code>OrderId</code></li>
<li>Create a 'multicolumn' index on <code>Date</code> AND <code>OrderId</code></li>
<li>Some other combination?</li>
</ul>
<p>I am also wondering whether I should create a separate bit column for <code>hasOrder</code> instead of checking if <code>OrderId IS NOT NULL</code> if that might be more efficient.</p>
<p>FYI: The KnownReferer is just a table which contains a list of 100 or so known HttpReferers so i can easily see how many hits from google, yahoo etc.</p>
| [
{
"answer_id": 312298,
"author": "Brannon",
"author_id": 5745,
"author_profile": "https://Stackoverflow.com/users/5745",
"pm_score": 2,
"selected": false,
"text": "[Date]"
},
{
"answer_id": 312338,
"author": "WW.",
"author_id": 14663,
"author_profile": "https://Stackoverflow.com/users/14663",
"pm_score": 0,
"selected": false,
"text": "(Date, OrderId, SiteVisitId, Domain, Referer, CampaignId)\n"
},
{
"answer_id": 312346,
"author": "Mitch Wheat",
"author_id": 16076,
"author_profile": "https://Stackoverflow.com/users/16076",
"pm_score": 1,
"selected": false,
"text": "using (var trans = new TransactionScope(TransactionScopeOption.Required,\n new TransactionOptions\n {\n IsolationLevel = IsolationLevel.ReadUncommitted\n }))\n{\n // Put your linq to sql query here\n}\n"
},
{
"answer_id": 312610,
"author": "Mark Brackett",
"author_id": 2199,
"author_profile": "https://Stackoverflow.com/users/2199",
"pm_score": 0,
"selected": false,
"text": "SELECT TOP 1000\n t0.SiteVisitId, t0.OrderId, t0.Date, \n t1.Domain, t0.Referer, t0.CampaignId\nFROM \n SiteVisit AS t0\nLEFT OUTER JOIN KnownReferer AS t1 ON t1.KnownRefererId = t0.KnownRefererId\nWHERE\n t0.Date <= @p0 \n AND t0.Date >= @p1\n AND t0.OrderId IS NOT NULL\nORDER BY \n t0.Date DESC\n\n@p0='2008-11-1 23:59:59:000', @p1='2008-10-1 00:00:00:000'\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312273",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/16940/"
] |
312,284 | <p>I have been trying to find information on how to retrieve attachments from a gmail account in either python or PHP, I'm hoping that someone here can be of some help, thanks.</p>
<p>Related:</p>
<ul>
<li><a href="https://stackoverflow.com/questions/348630/how-can-i-download-all-emails-with-attachments-from-gmail">How can I download all emails with attachments from Gmail?</a></li>
</ul>
| [
{
"answer_id": 312317,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 4,
"selected": true,
"text": "imaplib.IMAP4_SSL"
},
{
"answer_id": 3242719,
"author": "Rogus",
"author_id": 310221,
"author_profile": "https://Stackoverflow.com/users/310221",
"pm_score": 0,
"selected": false,
"text": "$mbox = imap_open(\"{imap.gmail.com:993/imap/ssl}INBOX\", \"username@gmail.com\", \"password\") or die(\"can't connect: \" . imap_last_error());"
},
{
"answer_id": 4573629,
"author": "andrebruton",
"author_id": 178882,
"author_profile": "https://Stackoverflow.com/users/178882",
"pm_score": 2,
"selected": false,
"text": "<?php \n\n$gmail_username = 'username@gmail.com';\n$gmail_password = 'mypassword';\n\n$imap = imap_open (\"{imap.gmail.com:993/imap/ssl}INBOX\", $gmail_username, $gmail_password) or die(\"can't connect: \" . imap_last_error());\n$savefilepath = 'path/to/images_folder/'; //absolute path to images directory\n$imagefilepath = 'images/'; //relative path to images directory\n\n$headers = imap_headers($imap);\nforeach ($headers as $mail) {\n $flags = substr($mail, 0, 4);\n //Check for unread msgs, get their UID, and queue them up\n if (strpos($flags, \"U\")) {\n preg_match('/[0-9]+/',$mail,$match);\n $new_msg[] = implode('',$match); \n }\n}\n\nif ($new_msg) {\n foreach ($new_msg as $result) {\n $structure = imap_fetchstructure($imap,$result);\n $parts = $structure->parts;\n foreach ($parts as $part) {\n if ($part->parameters[0]->attribute == \"NAME\") {\n //Generate a filename with format DATE_RANDOM#_ATTACHMENTNAME.EXT\n $savefilename = date(\"m-d-Y\") . '_' . mt_rand(rand(), 6) . '_' . $part->parameters[0]->value;\n save_attachment(imap_fetchbody($imap,$result,2),$savefilename,$savefilepath,$savethumbpath);\n imap_fetchbody($imap,$result,2); //This marks message as read\n } \n }\n }\n}\n\nimap_close($imap);\n\nfunction save_attachment( $content , $filename , $localfilepath, $thumbfilepath ) {\n if (imap_base64($content) != FALSE) { \n $file = fopen($localfilepath.$filename, 'w');\n fwrite($file, imap_base64($content));\n fclose($file);\n }\n}\n?>\n"
},
{
"answer_id": 12956451,
"author": "Will McCarty",
"author_id": 1756531,
"author_profile": "https://Stackoverflow.com/users/1756531",
"pm_score": 2,
"selected": false,
"text": "<?php \n\n$gmail_username = 'email@gmail.com';\n$gmail_password = 'password';\n$imap = imap_open (\"{imap.gmail.com:993/imap/ssl}INBOX\", $gmail_username, $gmail_password) or die(\"can't connect: \" . imap_last_error());\n$savefilepath = '//Server/share/Local/Pathname/'; //absolute path to images directory\n$imagefilepath = '/Local/Pathname/'; //relative path to images directory\n$savethumbpath = '/Local/Pathname/'; //relative path to images directory\n$headers = imap_headers($imap);\nforeach ($headers as $mail) {\n $flags = substr($mail, 0, 4);\n //Check for unread msgs, get their UID, and queue them up\n if (strpos($flags, \"U\")) {\n preg_match('/[0-9]+/',$mail,$match);\n $new_msg[] = implode('',$match); \n }\n}\nif ($new_msg) {\n foreach ($new_msg as $result) {\n $structure = imap_fetchstructure($imap,$result);\n $parts = $structure->parts;\n foreach ($parts as $part) {\n if ($part->parameters[0]->attribute == \"NAME\") {\n //Generate a filename with format DATE_RANDOM#_ATTACHMENTNAME.EXT\n $savefilename = date(\"m-d-Y\") . '_' . rand() . '_' . $part->parameters[0]->value;\n save_attachment(imap_fetchbody($imap,$result,2),$savefilename,$savefilepath,$savethumbpath);\n imap_fetchbody($imap,$result,2); //This marks message as read\n } \n }\n }\n}\n/* grab emails */\n$emails = imap_search($imap,'ALL');\n/* if emails are returned, cycle through each... */\nif($emails) {\n /* put the newest emails on top */\n $total = imap_num_msg($imap);\n /* for every email... */\n for( $i = $total; $i >= 1; $i--) {\n $headers = imap_header($imap, $i);\n $from = $headers->from[0]->mailbox . \"@\" . $headers->from[0]->host;\n echo $from . \"\\n\";\n imap_delete($imap,$i);\n imap_mail_move($imap,\"$i:$i\", \"[Gmail]/Trash\"); // Change or remove this line if you are not connecting to gmail. The path to the Trash folder in your Gmail may be different, capitalization is relevant.\n }\n}else{\n echo \"no emails\";\n}\n/* close the connection */\n imap_expunge($imap);\n imap_close($imap);\n\nfunction save_attachment( $content , $filename , $localfilepath, $thumbfilepath ) {\n if (imap_base64($content) != FALSE) { \n $file = fopen($localfilepath.$filename, 'w');\n fwrite($file, imap_base64($content));\n fclose($file);\n }\n}\n?>\n"
},
{
"answer_id": 30915656,
"author": "Pragya",
"author_id": 4980751,
"author_profile": "https://Stackoverflow.com/users/4980751",
"pm_score": 1,
"selected": false,
"text": "I recently worked on this topic and here is the code which works well. It also saves the details of the attachments in a word document with the following details:\n-> Date\n-> Time\n-> From\n-> Email ID\n-> Subject\n\n\n\n\n\n\n\n\n\n\n<?php \n\n\n /*\n * Gmail attachment extractor.\n *\n * Downloads attachments from Gmail and saves it to a file.\n * Uses PHP IMAP extension, so make sure it is enabled in your php.ini,\n * extension=php_imap.dll\n *\n */\n\n header('Content-type:application\\msword');\n header('Content-Disposition:attachment;Filename=document_name.doc');\n set_time_limit(0); \n /* connect to gmail with your credentials */\n $hostname = '{imap.googlemail.com:993/imap/ssl}INBOX';\n $username = 'email@gmail.com';\n $password = 'password';\n /* try to connect */\n $inbox = imap_open($hostname,$username,$password) or die('Cannot connect to \n Gmail: ' . imap_last_error());\n /* get all new emails. If set to 'ALL' instead \n * of 'NEW' retrieves all the emails, but can be \n * resource intensive, so the following variable, \n * $max_emails, puts the limit on the number of emails downloaded.\n * \n */\n $emails = imap_search($inbox,'ALL');\n /* useful only if the above search is set to 'ALL' */\n $max_emails = 110;\n\n\n /* if any emails found, iterate through each email */\n if($emails){\n $count = 1;\n\n /* put the newest emails on top */\n rsort($emails);\n /* for every email... */\n foreach($emails as $email_number){\n /* get information specific to this email */\n //$overview = imap_fetch_overview($inbox,$email_number,0);\n $check=imap_check($inbox);\n $result=imap_fetch_overview($inbox,\"1:{$check->Nmsgs}\",0);\n foreach($result as $overview){\n echo \"#{$overview->msgno}({$overview->date})-From: {$overview->from}\n {$overview->subject}\\n\"}\n /* get mail message */\n $message = imap_fetchbody($inbox,$email_number,2);\n /* get mail structure */\n $structure =imap_fetchstructure($inbox, $email_number);\n //$functions = array('function1' => imap_fetchstructure($inbox,\n $email_number));\n //print_r(array_keys($functions));\n $attachments = array();\n //print_r(array_keys($attachments[$i]));\n if($structure->parts[$i]->ifdparameters){\n foreach($structure->parts[$i]->dparameters as $object){\n if(strtolower($object->attribute) == 'filename'){\n $attachments[$i]['is_attachment'] = true;\n $attachments[$i]['filename'] = $object->value;\n }\n }\n }\n if($structure->parts[$i]->ifparameters) \n {\n foreach($structure->parts[$i]->parameters as $object) \n {\n if(strtolower($object->attribute) == 'name') \n {\n $attachments[$i]['is_attachment'] = true;\n $attachments[$i]['name'] = $object->value;\n }\n }\n }\n if($attachments[$i]['is_attachment']){\n $attachments[$i]['attachment']imap_fetchbody($inbox,$email_number,$i+1);\n /* 4 = QUOTED-PRINTABLE encoding */\n if($structure->parts[$i]->encoding == 3){ \n $attachments[$i]['attachment'] = base64_decode($attachments[$i] \n ['attachment']);\n }\n /* 3 = BASE64 encoding */\n elseif($structure->parts[$i]->encoding == 4){ \n $attachments[$i]['attachment'] = \n\n quoted_printable_decode($attachments[$i]['attachment']);\n }\n\n }\n }\n }\n /* iterate through each attachment and save it */\n foreach($attachments as $attachment)\n {\n if($attachment['is_attachment'] == 1){\n $filename = $attachment['name'];\n if(empty($filename)) $filename = $attachment['filename'];\n if(empty($filename)) $filename = time() . \".dat\";\n /* prefix the email number to the filename in case two emails\n * have the attachment with the same file name.\n */\n $fp = fopen($email_number . \"-\" . $filename, \"w+\");\n fwrite($fp, $attachment['attachment']);\n fclose($fp);\n }\n\n }\n\n if($count++ >= $max_emails) break;\n\n\n }\n\n } \n\n /* close the connection */\n\n imap_close($inbox);\n\n ?>\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312284",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/115/"
] |
312,286 | <p>For my programming class I have to write a linked list class. One of the functions we have to include is next(). This function would return the memory address of the next element in the list.</p>
<pre><code>#include <iostream>
using namespace std;
class Set {
private:
int num;
Set *nextval;
bool empty;
public:
Set();
<some return type> next();
};
<some return type> Set::next() {
Set *current;
current = this;
return current->next;
}
int main() {
Set a, *b, *c;
for (int i=50;i>=0;i=i-2) a.insert(i); // I've ommited since it does not pertain to my question
// Test the next_element() iterator
b = a.next();
c = b->next();
cout << "Third element of b = " << c->value() << endl;
return 0;
}
</code></pre>
<p>As you can see, I need to set the pointer <code>*b</code> and <code>*c</code> to the memory address that holds the next element in the list. My question is what kind of return type would I use? I've tried putting Set and Set* in place of but get compiler errors. Any help is greatly appreciated.</p>
| [
{
"answer_id": 312288,
"author": "luqui",
"author_id": 33796,
"author_profile": "https://Stackoverflow.com/users/33796",
"pm_score": 4,
"selected": true,
"text": "Set*"
},
{
"answer_id": 312289,
"author": "Mel Green",
"author_id": 32226,
"author_profile": "https://Stackoverflow.com/users/32226",
"pm_score": 3,
"selected": false,
"text": "Set* Set::next() {\n return nextval;\n}\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312286",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38/"
] |
312,300 | <p>On Vista, I got a problem with the application crash handler. Basically, if something unexpected occurs which cannot be captured by SEH, I get this pop-up window with "The application stopped working", blablabla, "Close program/Debug program" -- that is, after I disable the error reporting using the system control panel. With error reporting enabled, you would get a task dialog with search for solution online, close, debug.</p>
<p>This is not so funny if it happens in automated tools, and I wonder whether there is a way to get rid of it <em>totally</em>, read, if my app crashes, it just crashes to the command line or disappears but does not bring up a dialog.</p>
| [
{
"answer_id": 312366,
"author": "wimh",
"author_id": 33499,
"author_profile": "https://Stackoverflow.com/users/33499",
"pm_score": 4,
"selected": true,
"text": "SetErrorMode(SetErrorMode(0)|SEM_NOGPFAULTERRORBOX);\n"
},
{
"answer_id": 326420,
"author": "Raymond Martineau",
"author_id": 33952,
"author_profile": "https://Stackoverflow.com/users/33952",
"pm_score": 0,
"selected": false,
"text": "signal(SIGSEGV, &signal_handler);\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312300",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/39912/"
] |
312,302 | <p>If we implement a stack using arrays in C++, what is the best way to reduce the chance of an overflow condition? Also while keeping in mind the time-space trade off?</p>
| [
{
"answer_id": 312305,
"author": "Anteru",
"author_id": 39912,
"author_profile": "https://Stackoverflow.com/users/39912",
"pm_score": 3,
"selected": false,
"text": "std::vector"
},
{
"answer_id": 312410,
"author": "Johannes Schaub - litb",
"author_id": 34509,
"author_profile": "https://Stackoverflow.com/users/34509",
"pm_score": 0,
"selected": false,
"text": "-fmudflap -fmudflapth -fmudflapir"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312302",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
312,312 | <p>I have a Visual Studio 2005 C++ program that runs differently in Release mode than it does in Debug mode. In release mode, there's an (apparent) intermittent crash occurring. In debug mode, it doesn't crash. What are some reasons that a Release build would work differently than a Debug build?</p>
<p>It's also worth mentioning my program is fairly complex and uses several 3rd party libraries for XML processing, message brokering, etc...</p>
<p>Thanks in advance!</p>
| [
{
"answer_id": 312352,
"author": "peterchen",
"author_id": 31317,
"author_profile": "https://Stackoverflow.com/users/31317",
"pm_score": 8,
"selected": true,
"text": "#ifdef DEBUG\n#define Log(x) cout << #x << x << \"\\n\";\n#else \n#define Log(x)\n#endif\n\nif (foo)\n Log(x)\nif (bar)\n Run();\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312312",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/191808/"
] |
312,314 | <p>I know I can access environment variables in PowerShell using <code>$Env</code>. For example, I can access <code>FOO</code> with <code>$Env:FOO</code>.</p>
<p>I can't figure out how to access the environment variable called <code>FOO.BAR</code>.</p>
<p><code>$Env:FOO.BAR</code> doesn't work. How can I access this from within PowerShell?</p>
| [
{
"answer_id": 312327,
"author": "Jesse Weigert",
"author_id": 7618,
"author_profile": "https://Stackoverflow.com/users/7618",
"pm_score": 3,
"selected": false,
"text": "[Environment]::GetEnvironmentVariable(\"FOO.BAR\")\n"
},
{
"answer_id": 312365,
"author": "Shay Levy",
"author_id": 9833,
"author_profile": "https://Stackoverflow.com/users/9833",
"pm_score": 2,
"selected": false,
"text": "Get-WMIObject Win32_Environment -filter \"name='foo.bar'\"\n"
},
{
"answer_id": 313100,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 7,
"selected": true,
"text": "${env:variable.with.dots} = \"Hi there\"\n${env:variable.with.dots}\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312314",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/7618/"
] |
312,318 | <p>I've tried to the letter to search for mistakes in my code, but i can't myself get that autocomplete extender to work. Help wanted. </p>
<p>Here's my code: (excerpt from my aspx page) </p>
<pre><code> <asp:TextBox ID="TextBox1" Width="120px" runat="server"></asp:TextBox>
<cc1:AutoCompleteExtender ID="AutoCompleteExtender1" runat="server" TargetControlID="TextBox1" ServiceMethod="GetCompletionList" ServicePath="SearchAutoComplete.asmx" MinimumPrefixLength="1">
</cc1:AutoCompleteExtender>
</code></pre>
<p>My Webservice code: </p>
<pre><code> [WebMethod]
public static string[] GetCompletionList(string prefixText, int count)
{
List<string> returnData = new List<string>();
MySqlConnection con = new MySqlConnection(Connection.ConnectionString());
string sql = "select title from blog where title like '%" + prefixText + "%'";
MySqlCommand cmd = new MySqlCommand(sql, con);
con.Open();
MySqlDataReader reader = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (reader.Read())
{
returnData.Add(reader["title"].ToString());
}
return returnData.ToArray();
}
</code></pre>
| [
{
"answer_id": 312931,
"author": "David Hall",
"author_id": 2660,
"author_profile": "https://Stackoverflow.com/users/2660",
"pm_score": 1,
"selected": false,
"text": "GetCompletionList"
},
{
"answer_id": 314105,
"author": "Richard Ev",
"author_id": 39709,
"author_profile": "https://Stackoverflow.com/users/39709",
"pm_score": 2,
"selected": false,
"text": "GetCompletionList"
},
{
"answer_id": 1067496,
"author": "amiT jaiN",
"author_id": 113315,
"author_profile": "https://Stackoverflow.com/users/113315",
"pm_score": 1,
"selected": false,
"text": "<asp:ScriptManager ID=\"ScriptManager1\" runat=\"server\">\n<Services>\n <asp:ServiceReference Path=\"AutoComplete.asmx\" />\n </Services>\n </asp:ScriptManager>\n"
},
{
"answer_id": 8849467,
"author": "Sukanya",
"author_id": 1045045,
"author_profile": "https://Stackoverflow.com/users/1045045",
"pm_score": 1,
"selected": false,
"text": " <cc1:AutoCompleteExtender \n\n </cc1:AutoCompleteExtender> \n"
},
{
"answer_id": 17076836,
"author": "Luis Lopez",
"author_id": 2480286,
"author_profile": "https://Stackoverflow.com/users/2480286",
"pm_score": 1,
"selected": false,
"text": "'<System.Web.Script.Services.ScriptService()> _\n<WebService(Namespace:=\"http://tempuri.org/\")> _\n<WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _\n<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312318",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
312,321 | <blockquote>
<p><strong>Possible Duplicate:</strong><br>
<a href="https://stackoverflow.com/questions/71419/whats-wrong-with-delphis-with">What's wrong with Delphi's “with”</a> </p>
</blockquote>
<p>I am have a problem debugging code that uses a ‘WITH’ statement in BDS 2006
The debugger will not show the values of the variables with in a class or record.
Am I doing something wrong or does BDS 2006 have a bug ?</p>
<pre><code>type
TNumber = class
Num: Integer;
end;
implementation
{$R *.dfm}
var
MyNumber: TNumber;
procedure TForm2.FormCreate(Sender: TObject);
begin
MyNumber := TNumber.Create;
MyNumber.Num := 10; /// MyNumber.Num Can be seen with debugger
with MyNumber do
begin
Num := Num +1 ; /// Num is not seen by the debugger
MyNumber.Num := Num +1 ; /// MyNumber.Num is seen but Num is not seen by the debugger
end;
end;
</code></pre>
<p>EDIT:</p>
<p>Sure one can use the full name of the variable
But things become very messy if you have a complex structure with more than one level</p>
| [
{
"answer_id": 312407,
"author": "Cruachan",
"author_id": 7315,
"author_profile": "https://Stackoverflow.com/users/7315",
"pm_score": 5,
"selected": true,
"text": "With"
},
{
"answer_id": 312442,
"author": "Toon Krijthe",
"author_id": 18061,
"author_profile": "https://Stackoverflow.com/users/18061",
"pm_score": 3,
"selected": false,
"text": "with TMyObject.Create do\n try\n Method1(blah, blah, blah);\n Method2(blah, blah, blah);\n finally \n Free;\n end;\n"
},
{
"answer_id": 318526,
"author": "Fabricio Araujo",
"author_id": 10300,
"author_profile": "https://Stackoverflow.com/users/10300",
"pm_score": 3,
"selected": false,
"text": "var\n Sc : TE_Type;\nbegin\n Sc := A.B.C.D.E;\n sc.Method1;\n sc.Method2;\n sc.Method3;\n sc.Method4;\n sc.Method5;\n sc.Method6;\nend;\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312321",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17560/"
] |
312,322 | <p>I have a variable of type Hashmap<code><String,Integer</code>>.</p>
<p>In this, the Integer value might have to go some manipulation depending upon the value of a flag variable. I did it like this...</p>
<pre><code>Hashmapvariable.put( somestring,
if (flag_variable) {
//manipulation code goes here
new Integer(manipulated value);
} else {
new Integer(non-manipulated value);
}
);
</code></pre>
<p>But I get an error: </p>
<blockquote>
<p>Syntax error on token(s), misplaced
constructs.</p>
</blockquote>
<p>at the Hashmapvariable.put call.</p>
<p>I also get another error</p>
<blockquote>
<p>Syntax error on token ")", delete this
token.</p>
</blockquote>
<p>at the final ");" line. But I can't delete the ")" - its the closing parentheses for the put method call.</p>
<p>I don't get this. What mistake am I doing?</p>
| [
{
"answer_id": 312330,
"author": "coobird",
"author_id": 17172,
"author_profile": "https://Stackoverflow.com/users/17172",
"pm_score": 3,
"selected": true,
"text": "Integer"
},
{
"answer_id": 312334,
"author": "krosenvold",
"author_id": 23691,
"author_profile": "https://Stackoverflow.com/users/23691",
"pm_score": 3,
"selected": false,
"text": " new Integer(flag_variable ? manipulated value : non-manipulated value)\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312322",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/9195/"
] |
312,328 | <p>Pretty much as the question asks. Answers preferably in pseudo code and referenced. The correct answer should value speed over simplicity.</p>
| [
{
"answer_id": 312332,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 3,
"selected": true,
"text": "pie_p"
},
{
"answer_id": 312453,
"author": "e.James",
"author_id": 33686,
"author_profile": "https://Stackoverflow.com/users/33686",
"pm_score": 2,
"selected": false,
"text": "struct point\n{\n float x\n float y\n float z\n}\n\nstruct ray\n{\n point R1\n point R2\n}\n\nstruct polygon\n{\n point P[]\n int count\n}\n\nfloat dotProduct(point A, point B)\n{\n return A.x*B.x + A.y*B.y + A.z*B.z\n}\n\npoint crossProduct(point A, point B)\n{\n return point(A.y*B.z-A.z*B.y, A.z*B.x-A.x*B.z, A.x*B.y-A.y*B.x)\n}\n\npoint vectorSub(point A, point B)\n{\n return point(A.x-B.x, A.y-B.y, A.z-B.z) \n}\n\npoint scalarMult(float a, Point B)\n{\n return point(a*B.x, a*B.y, a*B.z)\n}\n\nbool findIntersection(ray Ray, polygon Poly, point& Answer)\n{\n point plane_normal = crossProduct(vectorSub(Poly.P[1], Poly.P[0]), vectorSub(Poly.P[2], Poly.P[0]))\n\n float denominator = dotProduct(vectorSub(Ray.R2, Poly.P[0]), plane_normal)\n\n if (denominator == 0) { return FALSE } // ray is parallel to the polygon\n\n float ray_scalar = dotProduct(vectorSub(Poly.P[0], Ray.R1), plane_normal)\n\n Answer = vectorAdd(Ray.R1, scalarMult(ray_scalar, Ray.R2))\n\n // verify that the point falls inside the polygon\n\n point test_line = vectorSub(Answer, Poly.P[0])\n point test_axis = crossProduct(plane_normal, test_line)\n\n bool point_is_inside = FALSE\n\n point test_point = vectorSub(Poly.P[1], Answer)\n bool prev_point_ahead = (dotProduct(test_line, test_point) > 0)\n bool prev_point_above = (dotProduct(test_axis, test_point) > 0)\n\n bool this_point_ahead\n bool this_point_above\n\n int index = 2;\n while (index < Poly.count)\n {\n test_point = vectorSub(Poly.P[index], Answer)\n this_point_ahead = (dotProduct(test_line, test_point) > 0)\n\n if (prev_point_ahead OR this_point_ahead)\n {\n this_point_above = (dotProduct(test_axis, test_point) > 0)\n\n if (prev_point_above XOR this_point_above)\n {\n point_is_inside = !point_is_inside\n }\n }\n\n prev_point_ahead = this_point_ahead\n prev_point_above = this_point_above\n index++\n }\n\n return point_is_inside\n}"
},
{
"answer_id": 21688645,
"author": "Trey Reynolds",
"author_id": 3159048,
"author_profile": "https://Stackoverflow.com/users/3159048",
"pm_score": 0,
"selected": false,
"text": "function Collision(PlaneOrigin,PlaneDirection,RayOrigin,RayDirection)\n return RayOrigin-RayDirection*Dot(PlaneDirection,RayOrigin-PlaneOrigin)/Dot(PlaneDirection,RayDirection)\nend\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312328",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/42413/"
] |
312,357 | <p>What platforms and tools should I use for rapid game development and prototyping?</p>
<p>Say that I have an idea for a simple game or a game mechanic that I want to try out, what are the best tools for quickly creating something playable that I can experiment with to try out the idea?</p>
<p>The platform does not necessarily have to be easy to learn, that is not the issue, but once learned it has to be quick to use.</p>
| [
{
"answer_id": 312528,
"author": "Jason Miesionczek",
"author_id": 18811,
"author_profile": "https://Stackoverflow.com/users/18811",
"pm_score": 3,
"selected": false,
"text": "public class HelloWorld extends SimpleGame{\n public static void main(String[] args) {\n HelloWorld app = new HelloWorld(); // Create Object\n // Signal to show properties dialog\n app.setConfigShowMode(ConfigShowMode.AlwaysShow);\n app.start(); // Start the program\n }\n protected void simpleInitGame() {\n // Make a box\n Box b = new Box(\"Mybox\", new Vector3f(0,0,0), new Vector3f(1,1,1));\n rootNode.attachChild(b); // Put it in the scene graph\n }\n}\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312357",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40053/"
] |
312,378 | <p>I would like to know if you guys have any suggestions about debug levels when writing an application.</p>
<p>I thought about 4 levels:</p>
<p>0 : No Debug<br>
1 : All inputs and outputs<br>
2 : "I am here" notification from significant functions with main parameters<br>
3 : All variables verbose</p>
| [
{
"answer_id": 313145,
"author": "Jonathan Leffler",
"author_id": 15168,
"author_profile": "https://Stackoverflow.com/users/15168",
"pm_score": 4,
"selected": false,
"text": "syslog"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312378",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38963/"
] |
312,379 | <p>I need to draw gridlines on the background of a canvas that will have other controls placed on it. </p>
<p>I tried creating a StreamGeometry, using that to draw lines, and getting that assigned to a DrawingBrush. However I find that if the StreamGeometry has too many lines, the program becomes sluggish after the DrawingBrush is assigned to the Canvas.</p>
<p>Is there anyway of 'pre-rendering' grid lines and having that assigned to a Canvas?</p>
<p>I tried <code>Freeze()</code>ing the brush and geometry but that didn't seem to work. What other options do I have?</p>
<p>Here's my code:</p>
<pre><code>public void RenderGrid()
{
this.UpdateGrid();
Pen grid_pen = new Pen(Brushes.Blue, 0.1);
StreamGeometry sg = new StreamGeometry();
DrawingBrush b = new DrawingBrush();
GeometryDrawing gd = new GeometryDrawing();
gd.Geometry = sg;
gd.Pen = grid_pen;
b.Drawing = gd;
StreamGeometryContext ctx = sg.Open();
foreach (double d in this.VerticalGrids)
{
ctx.BeginFigure(new Point(d, 0), true, false);
ctx.LineTo(new Point(d, this.RenderSize.Height), true,false);
}
foreach (double d in this.HorizontalGrids)
{
ctx.BeginFigure(new Point(0, d), true, false);
ctx.LineTo(new Point(this.RenderSize.Width, d),true, false);
}
ctx.Close();
sg.Freeze();
gd.Freeze();
b.Freeze();
this.Background = b;
}
</code></pre>
| [
{
"answer_id": 423429,
"author": "mcdrewski",
"author_id": 52768,
"author_profile": "https://Stackoverflow.com/users/52768",
"pm_score": 2,
"selected": false,
"text": "<DrawingBrush x:Key=\"MyBrush\" TileMode=\"Tile\" Stretch=\"Fill\" \n Viewport=\"0,0,250,250\" ViewportUnits=\"Absolute\">\n\n\nLocalValueEnumerator props = Background.GetLocalValueEnumerator();\nwhile (props.MoveNext())\n{\n DependencyProperty prop = props.Current.Property;\n if ((prop.Name == \"Viewport\") && (!prop.ReadOnly))\n {\n Background.SetValue(prop, new Rect(0, 0, m_ColumnWidth, m_RowHeight));\n }\n}\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312379",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/618/"
] |
312,400 | <p>I have the following (shortened query):</p>
<pre><code>SELECT
`Statistics`.`StatisticID`,
COUNT(DISTINCT `Flags`.`FlagType`) AS `FlagCount`
FROM `Statistics`
LEFT JOIN `Flags` ON `Statistics`.`StatisticID` = `Flags`.`StatisticID`
WHERE `FlagCount` = 0
GROUP BY `Statistics`.`StatisticID`
ORDER BY `SubmittedTime` DESC
LIMIT 0, 10
</code></pre>
<p>Now, neither <code>FlagCount = 0</code> or <code>COUNT(Flags.FlagType)</code> work in the <code>WHERE</code> clause. I thought about using a <code>SET</code> but I'm not sure how I'd add that to the query. Any ideas?</p>
<p>Thanks,</p>
| [
{
"answer_id": 312405,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 3,
"selected": false,
"text": "HAVING COUNT(DISTINCT Flags.FlagType) = 0"
},
{
"answer_id": 312408,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 0,
"selected": false,
"text": "SELECT \n `Statistics`.`StatisticID`,\n COUNT(DISTINCT `Flags`.`FlagType`) AS `FlagCount`\nFROM `Statistics`\nLEFT JOIN `Flags` ON `Statistics`.`StatisticID` = `Flags`.`StatisticID`\n And `FlagCount` = 0\nGROUP BY `Statistics`.`StatisticID`\nORDER BY `SubmittedTime` DESC\nLIMIT 0, 10\n"
},
{
"answer_id": 312432,
"author": "Ross",
"author_id": 2025,
"author_profile": "https://Stackoverflow.com/users/2025",
"pm_score": 0,
"selected": false,
"text": "HAVING"
},
{
"answer_id": 312465,
"author": "Eugene Yokota",
"author_id": 3827,
"author_profile": "https://Stackoverflow.com/users/3827",
"pm_score": 3,
"selected": true,
"text": "SELECT \n `Statistics`.`StatisticID`,\n COUNT(DISTINCT `Flags`.`FlagType`) AS `FlagCount`\nFROM `Statistics`\n LEFT JOIN `Flags` ON `Statistics`.`StatisticID` = `Flags`.`StatisticID`\nWHERE `Statistics`.`StatisticID`\n IN (SELECT `Flags`.`StatisticID` \n FROM `Flags`\n HAVING COUNT(DISTINCT `Flags`.`FlagType`) <= 3\n GROUP BY `Flags`.`StatisticID`\n )\nGROUP BY `Statistics`.`StatisticID`\nORDER BY `SubmittedTime` DESC\nLIMIT 0, 10\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312400",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/2025/"
] |
312,424 | <p>I am trying to set the <code>fieldValue</code> of the check box to a value I got from the property tag.</p>
<p>I am having trouble with the syntax.</p>
<p>This is what I have tried:</p>
<pre><code><s:form id="myForm" method="post" action="removeUser" enctype="multipart/form-data">
<s:iterator value="myList">
<tr>
<td><s:property value="id"/></td>
<td><s:property value="name"/></td>
<td><s:property value="email"/></td>
<td><s:checkbox label="delete" name="delete" fieldValue="<s:property value='id'/>"/></td>
</tr>
</s:iterator>
<s:submit id="saveForm" value="Delete users"></s:submit>
</s:form>
</code></pre>
<p>However, it keeps on returning me <code>true</code> as the <code>fieldValue</code></p>
<p>Can someone familiar with struts please help me?</p>
<p>Thanks</p>
| [
{
"answer_id": 18515194,
"author": "rohan",
"author_id": 2551459,
"author_profile": "https://Stackoverflow.com/users/2551459",
"pm_score": 0,
"selected": false,
"text": "fieldValue=\"<s:property value= \"${id }\" />\"\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312424",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/17085/"
] |
312,443 | <p>How do I split a list of arbitrary length into equal sized chunks?</p>
<hr />
<p><sub>See <a href="https://stackoverflow.com/q/434287">How to iterate over a list in chunks</a> if the data result will be used directly for a loop, and does not need to be stored.</sub></p>
<p><sub>For the same question with a string input, see <a href="https://stackoverflow.com/questions/9475241">Split string every nth character?</a>. The same techniques generally apply, though there are some variations.</sub></p>
| [
{
"answer_id": 312464,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 13,
"selected": true,
"text": "def chunks(lst, n):\n \"\"\"Yield successive n-sized chunks from lst.\"\"\"\n for i in range(0, len(lst), n):\n yield lst[i:i + n]\n"
},
{
"answer_id": 312466,
"author": "atzz",
"author_id": 23252,
"author_profile": "https://Stackoverflow.com/users/23252",
"pm_score": 6,
"selected": false,
"text": "def SplitList(mylist, chunk_size):\n return [mylist[offs:offs+chunk_size] for offs in range(0, len(mylist), chunk_size)]\n"
},
{
"answer_id": 312467,
"author": "Markus Jarderot",
"author_id": 22364,
"author_profile": "https://Stackoverflow.com/users/22364",
"pm_score": 7,
"selected": false,
"text": "def split_seq(iterable, size):\n it = iter(iterable)\n item = list(itertools.islice(it, size))\n while item:\n yield item\n item = list(itertools.islice(it, size))\n"
},
{
"answer_id": 312472,
"author": "slav0nic",
"author_id": 2201031,
"author_profile": "https://Stackoverflow.com/users/2201031",
"pm_score": 4,
"selected": false,
"text": "In [48]: chunk = lambda ulist, step: map(lambda i: ulist[i:i+step], xrange(0, len(ulist), step))\n\nIn [49]: chunk(range(1,100), 10)\nOut[49]: \n[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],\n [31, 32, 33, 34, 35, 36, 37, 38, 39, 40],\n [41, 42, 43, 44, 45, 46, 47, 48, 49, 50],\n [51, 52, 53, 54, 55, 56, 57, 58, 59, 60],\n [61, 62, 63, 64, 65, 66, 67, 68, 69, 70],\n [71, 72, 73, 74, 75, 76, 77, 78, 79, 80],\n [81, 82, 83, 84, 85, 86, 87, 88, 89, 90],\n [91, 92, 93, 94, 95, 96, 97, 98, 99]]\n"
},
{
"answer_id": 312644,
"author": "tzot",
"author_id": 6899,
"author_profile": "https://Stackoverflow.com/users/6899",
"pm_score": 8,
"selected": false,
"text": "from itertools import izip, chain, repeat\n\ndef grouper(n, iterable, padvalue=None):\n \"grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')\"\n return izip(*[chain(iterable, repeat(padvalue, n-1))]*n)\n"
},
{
"answer_id": 314771,
"author": "Corey Goldberg",
"author_id": 16148,
"author_profile": "https://Stackoverflow.com/users/16148",
"pm_score": 4,
"selected": false,
"text": "def split_seq(seq, num_pieces):\n start = 0\n for i in xrange(num_pieces):\n stop = start + len(seq[i::num_pieces])\n yield seq[start:stop]\n start = stop\n"
},
{
"answer_id": 319970,
"author": "J.T. Hurley",
"author_id": 39851,
"author_profile": "https://Stackoverflow.com/users/39851",
"pm_score": 2,
"selected": false,
"text": "def chunk(lst):\n out = []\n for x in xrange(2, len(lst) + 1):\n if not len(lst) % x:\n factor = len(lst) / x\n break\n while lst:\n out.append([lst.pop(0) for x in xrange(factor)])\n return out\n"
},
{
"answer_id": 1668586,
"author": "hcvst",
"author_id": 149268,
"author_profile": "https://Stackoverflow.com/users/149268",
"pm_score": 3,
"selected": false,
"text": ">>> def f(x, n, acc=[]): return f(x[n:], n, acc+[(x[:n])]) if x else acc\n>>> f(\"Hallo Welt\", 3)\n['Hal', 'lo ', 'Wel', 't']\n>>> \n"
},
{
"answer_id": 1751478,
"author": "oremj",
"author_id": 213231,
"author_profile": "https://Stackoverflow.com/users/213231",
"pm_score": 9,
"selected": false,
"text": "def chunks(xs, n):\n n = max(1, n)\n return (xs[i:i+n] for i in range(0, len(xs), n))\n"
},
{
"answer_id": 2270932,
"author": "Mars",
"author_id": 274094,
"author_profile": "https://Stackoverflow.com/users/274094",
"pm_score": 4,
"selected": false,
"text": "def splitter(l, n):\n i = 0\n chunk = l[:n]\n while chunk:\n yield chunk\n i += n\n chunk = l[i:i+n]\n"
},
{
"answer_id": 3125186,
"author": "Tomasz Wysocki",
"author_id": 377095,
"author_profile": "https://Stackoverflow.com/users/377095",
"pm_score": 6,
"selected": false,
"text": "def chunk(input, size):\n return map(None, *([iter(input)] * size))\n"
},
{
"answer_id": 3226719,
"author": "lebenf",
"author_id": 389280,
"author_profile": "https://Stackoverflow.com/users/389280",
"pm_score": 6,
"selected": false,
"text": "L = range(1, 1000)\nprint [L[x:x+10] for x in xrange(0, len(L), 10)]\n"
},
{
"answer_id": 5711993,
"author": "ninjagecko",
"author_id": 711085,
"author_profile": "https://Stackoverflow.com/users/711085",
"pm_score": 5,
"selected": false,
"text": "zip(*[iterable[i::3] for i in range(3)]) \n"
},
{
"answer_id": 5872632,
"author": "schwater",
"author_id": 736526,
"author_profile": "https://Stackoverflow.com/users/736526",
"pm_score": 3,
"selected": false,
"text": "import matplotlib.cbook as cbook\nsegments = cbook.pieces(np.arange(20), 3)\nfor s in segments:\n print s\n"
},
{
"answer_id": 9255750,
"author": "Rusty Rob",
"author_id": 632088,
"author_profile": "https://Stackoverflow.com/users/632088",
"pm_score": 3,
"selected": false,
"text": "def chunks(iterable,n):\n \"\"\"assumes n is an integer>0\n \"\"\"\n iterable=iter(iterable)\n while True:\n result=[]\n for i in range(n):\n try:\n a=next(iterable)\n except StopIteration:\n break\n else:\n result.append(a)\n if result:\n yield result\n else:\n break\n\ng1=(i*i for i in range(10))\ng2=chunks(g1,3)\nprint g2\n'<generator object chunks at 0x0337B9B8>'\nprint list(g2)\n'[[0, 1, 4], [9, 16, 25], [36, 49, 64], [81]]'\n"
},
{
"answer_id": 12150728,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "def chunker(iterable, chunksize):\n for i,c in enumerate(iterable[::chunksize]):\n yield iterable[i*chunksize:(i+1)*chunksize]\n\n>>> for chunk in chunker(range(0,100), 10):\n... print list(chunk)\n... \n[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\n[10, 11, 12, 13, 14, 15, 16, 17, 18, 19]\n[20, 21, 22, 23, 24, 25, 26, 27, 28, 29]\n... etc ...\n"
},
{
"answer_id": 14937534,
"author": "macm",
"author_id": 506038,
"author_profile": "https://Stackoverflow.com/users/506038",
"pm_score": 4,
"selected": false,
"text": ">>> orange = range(1, 1001)\n>>> otuples = list( zip(*[iter(orange)]*10))\n>>> print(otuples)\n[(1, 2, 3, 4, 5, 6, 7, 8, 9, 10), ... (991, 992, 993, 994, 995, 996, 997, 998, 999, 1000)]\n>>> olist = [list(i) for i in otuples]\n>>> print(olist)\n[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10], ..., [991, 992, 993, 994, 995, 996, 997, 998, 999, 1000]]\n>>> \n"
},
{
"answer_id": 16760646,
"author": "Uday Kumar",
"author_id": 2064658,
"author_profile": "https://Stackoverflow.com/users/2064658",
"pm_score": -1,
"selected": false,
"text": "[range(t,t+10) for t in range(1,1000,10)]\n\n[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10],\n [11, 12, 13, 14, 15, 16, 17, 18, 19, 20],\n [21, 22, 23, 24, 25, 26, 27, 28, 29, 30],....\n ....[981, 982, 983, 984, 985, 986, 987, 988, 989, 990],\n [991, 992, 993, 994, 995, 996, 997, 998, 999, 1000]]\n"
},
{
"answer_id": 16935535,
"author": "Moj",
"author_id": 1420757,
"author_profile": "https://Stackoverflow.com/users/1420757",
"pm_score": 9,
"selected": false,
"text": "numpy.array_split"
},
{
"answer_id": 19264525,
"author": "nikipore",
"author_id": 1464540,
"author_profile": "https://Stackoverflow.com/users/1464540",
"pm_score": 4,
"selected": false,
"text": "from itertools import islice\n\ndef chunks(n, iterable):\n iterable = iter(iterable)\n while True:\n yield tuple(islice(iterable, n)) or iterable.next()\n"
},
{
"answer_id": 20106816,
"author": "zach",
"author_id": 983191,
"author_profile": "https://Stackoverflow.com/users/983191",
"pm_score": 5,
"selected": false,
"text": "partition"
},
{
"answer_id": 20228836,
"author": "koffein",
"author_id": 2964777,
"author_profile": "https://Stackoverflow.com/users/2964777",
"pm_score": -1,
"selected": false,
"text": ">>> n = 3 # number of groups\n>>> biglist = range(30)\n>>>\n>>> [ biglist[i::n] for i in xrange(n) ]\n[[0, 3, 6, 9, 12, 15, 18, 21, 24, 27],\n [1, 4, 7, 10, 13, 16, 19, 22, 25, 28],\n [2, 5, 8, 11, 14, 17, 20, 23, 26, 29]]\n"
},
{
"answer_id": 21767522,
"author": "Russia Must Remove Putin",
"author_id": 541136,
"author_profile": "https://Stackoverflow.com/users/541136",
"pm_score": 6,
"selected": false,
"text": ">>> import statistics\n>>> statistics.variance([5,5,5,5,1]) \n3.2\n>>> statistics.variance([5,4,4,4,4]) \n0.19999999999999998\n"
},
{
"answer_id": 22045226,
"author": "senderle",
"author_id": 577088,
"author_profile": "https://Stackoverflow.com/users/577088",
"pm_score": 8,
"selected": false,
"text": "iter"
},
{
"answer_id": 22138685,
"author": "rectangletangle",
"author_id": 433417,
"author_profile": "https://Stackoverflow.com/users/433417",
"pm_score": 2,
"selected": false,
"text": "chunked"
},
{
"answer_id": 25650543,
"author": "CPBL",
"author_id": 1159005,
"author_profile": "https://Stackoverflow.com/users/1159005",
"pm_score": 2,
"selected": false,
"text": "def nChunks(l, n):\n \"\"\" Yield n successive chunks from l.\n Works for lists, pandas dataframes, etc\n \"\"\"\n newn = int(1.0 * len(l) / n + 0.5)\n for i in xrange(0, n-1):\n yield l[i*newn:i*newn+newn]\n yield l[n*newn-newn:]\n"
},
{
"answer_id": 27371167,
"author": "Be Wake Pandey",
"author_id": 4278306,
"author_profile": "https://Stackoverflow.com/users/4278306",
"pm_score": 2,
"selected": false,
"text": "chunkL = [ [i for i in L[r*k:r*(k+1)] ] for k in range(len(L)/r)] \n"
},
{
"answer_id": 28756559,
"author": "Saksham Varma",
"author_id": 4596008,
"author_profile": "https://Stackoverflow.com/users/4596008",
"pm_score": 2,
"selected": false,
"text": "l = [1,2,3,4,5,6,7,8,9,10,11,12]\nk = 5 #chunk size\nprint [tuple(l[x:y]) for (x, y) in [(x, x+k) for x in range(0, len(l), k)]]\n"
},
{
"answer_id": 28786255,
"author": "Ranaivo",
"author_id": 3202915,
"author_profile": "https://Stackoverflow.com/users/3202915",
"pm_score": 4,
"selected": false,
"text": "def chunkList(initialList, chunkSize):\n \"\"\"\n This function chunks a list into sub lists \n that have a length equals to chunkSize.\n\n Example:\n lst = [3, 4, 9, 7, 1, 1, 2, 3]\n print(chunkList(lst, 3)) \n returns\n [[3, 4, 9], [7, 1, 1], [2, 3]]\n \"\"\"\n finalList = []\n for i in range(0, len(initialList), chunkSize):\n finalList.append(initialList[i:i+chunkSize])\n return finalList\n"
},
{
"answer_id": 29009933,
"author": "Noich",
"author_id": 427653,
"author_profile": "https://Stackoverflow.com/users/427653",
"pm_score": 6,
"selected": false,
"text": "from itertools import zip_longest\n\na = range(1, 16)\ni = iter(a)\nr = list(zip_longest(i, i, i))\n>>> print(r)\n[(1, 2, 3), (4, 5, 6), (7, 8, 9), (10, 11, 12), (13, 14, 15)]\n"
},
{
"answer_id": 29707187,
"author": "Flo",
"author_id": 4307212,
"author_profile": "https://Stackoverflow.com/users/4307212",
"pm_score": 2,
"selected": false,
"text": "# Given 'l' is your list\n\nchs = 12 # Your chunksize\npartitioned = [ l[i*chs:(i*chs)+chs] for i in range((len(l) // chs)+1) ]\n"
},
{
"answer_id": 31178232,
"author": "Art B",
"author_id": 2720640,
"author_profile": "https://Stackoverflow.com/users/2720640",
"pm_score": 4,
"selected": false,
"text": "def split_list(the_list, chunk_size):\n result_list = []\n while the_list:\n result_list.append(the_list[:chunk_size])\n the_list = the_list[chunk_size:]\n return result_list\n\na_list = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]\n\nprint split_list(a_list, 3)\n"
},
{
"answer_id": 31442939,
"author": "AdvilUser",
"author_id": 105748,
"author_profile": "https://Stackoverflow.com/users/105748",
"pm_score": 3,
"selected": false,
"text": "a = [1, 2, 3, 4, 5, 6, 7, 8, 9]\nCHUNK = 4\n[a[i*CHUNK:(i+1)*CHUNK] for i in xrange((len(a) + CHUNK - 1) / CHUNK )]\n"
},
{
"answer_id": 32658232,
"author": "Mikhail Lyundin",
"author_id": 4207961,
"author_profile": "https://Stackoverflow.com/users/4207961",
"pm_score": 2,
"selected": false,
"text": "def chunked(iterable, size):\n stop = []\n it = iter(iterable)\n def _next_chunk():\n try:\n for _ in xrange(size):\n yield next(it)\n except StopIteration:\n stop.append(True)\n return\n\n while not stop:\n yield _next_chunk()\n\nfor it in chunked(xrange(16), 4):\n print list(it)\n"
},
{
"answer_id": 33180285,
"author": "Evan Zamir",
"author_id": 1245418,
"author_profile": "https://Stackoverflow.com/users/1245418",
"pm_score": 1,
"selected": false,
"text": "def pop_n_elems_from_generator(g, n):\n elems = []\n try:\n for idx in xrange(0, n):\n elems.append(g.next())\n return elems\n except StopIteration:\n return elems\n"
},
{
"answer_id": 33510840,
"author": "mazieres",
"author_id": 1565438,
"author_profile": "https://Stackoverflow.com/users/1565438",
"pm_score": 4,
"selected": false,
"text": "def chunks(li, n):\n if li == []:\n return\n yield li[:n]\n for e in chunks(li[n:], n):\n yield e\n"
},
{
"answer_id": 33517774,
"author": "Julien Palard",
"author_id": 232831,
"author_profile": "https://Stackoverflow.com/users/232831",
"pm_score": 2,
"selected": false,
"text": "Y = lambda f: (lambda x: x(x))(lambda y: f(lambda *args: y(y)(*args)))\nchunks = Y(lambda f: lambda n: [n[0][:n[1]]] + f((n[0][n[1]:], n[1])) if len(n[0]) > 0 else [])\n"
},
{
"answer_id": 34322647,
"author": "Riaz Rizvi",
"author_id": 213307,
"author_profile": "https://Stackoverflow.com/users/213307",
"pm_score": 5,
"selected": false,
"text": "[AA[i:i+SS] for i in range(len(AA))[::SS]]\n"
},
{
"answer_id": 38808533,
"author": "Claudiu",
"author_id": 15055,
"author_profile": "https://Stackoverflow.com/users/15055",
"pm_score": 3,
"selected": false,
"text": "from __future__ import division # not needed in Python 3\ndef n_even_chunks(l, n):\n \"\"\"Yield n as even chunks as possible from l.\"\"\"\n last = 0\n for i in range(1, n+1):\n cur = int(round(i * (len(l) / n)))\n yield l[last:cur]\n last = cur\n"
},
{
"answer_id": 40409475,
"author": "vishes_shell",
"author_id": 3124746,
"author_profile": "https://Stackoverflow.com/users/3124746",
"pm_score": 3,
"selected": false,
"text": "boltons"
},
{
"answer_id": 40700737,
"author": "Alex",
"author_id": 3511819,
"author_profile": "https://Stackoverflow.com/users/3511819",
"pm_score": 3,
"selected": false,
"text": "np.array_split(np.array(data), 20)"
},
{
"answer_id": 41586849,
"author": "Peter Gerdes",
"author_id": 351049,
"author_profile": "https://Stackoverflow.com/users/351049",
"pm_score": 2,
"selected": false,
"text": "g = paged_iter(list(range(50)), 11))\ni0 = next(g)\ni1 = next(g)\nlist(i1)\nlist(i0)\n"
},
{
"answer_id": 41904532,
"author": "Moinuddin Quadri",
"author_id": 2063361,
"author_profile": "https://Stackoverflow.com/users/2063361",
"pm_score": 4,
"selected": false,
"text": "get_chunks"
},
{
"answer_id": 42677465,
"author": "itub",
"author_id": 276332,
"author_profile": "https://Stackoverflow.com/users/276332",
"pm_score": 2,
"selected": false,
"text": "def chunks(l, n):\n c = itertools.count()\n return (it for _, it in itertools.groupby(l, lambda x: next(c)//n))\n"
},
{
"answer_id": 43454601,
"author": "Анатолий Панин",
"author_id": 1220682,
"author_profile": "https://Stackoverflow.com/users/1220682",
"pm_score": 3,
"selected": false,
"text": "def make_chunks(data, chunk_size): \n while data:\n chunk, data = data[:chunk_size], data[chunk_size:]\n yield chunk\n\n>>> for chunk in make_chunks([1, 2, 3, 4, 5, 6, 7], 2):\n... print chunk\n... \n[1, 2]\n[3, 4]\n[5, 6]\n[7]\n>>> \n"
},
{
"answer_id": 44959796,
"author": "Andrey Cizov",
"author_id": 1055356,
"author_profile": "https://Stackoverflow.com/users/1055356",
"pm_score": 2,
"selected": false,
"text": "import itertools\ndef split_groups(iter_in, group_size):\n return ((x for _, x in item) for _, item in itertools.groupby(enumerate(iter_in), key=lambda x: x[0] // group_size))\n"
},
{
"answer_id": 47010604,
"author": "guyskk",
"author_id": 6626292,
"author_profile": "https://Stackoverflow.com/users/6626292",
"pm_score": 2,
"selected": false,
"text": "def chunks(iterable, n):\n \"\"\"Yield successive n-sized chunks from iterable.\"\"\"\n values = []\n for i, item in enumerate(iterable, 1):\n values.append(item)\n if i % n == 0:\n yield values\n values = []\n if values:\n yield values\n"
},
{
"answer_id": 47096024,
"author": "George B",
"author_id": 1587275,
"author_profile": "https://Stackoverflow.com/users/1587275",
"pm_score": 3,
"selected": false,
"text": "def chunks(iterable, chunk_size):\n i = 0;\n while i < len(iterable):\n yield iterable[i:i+chunk_size]\n i += chunk_size\n"
},
{
"answer_id": 48135727,
"author": "Alex T",
"author_id": 3766751,
"author_profile": "https://Stackoverflow.com/users/3766751",
"pm_score": 5,
"selected": false,
"text": "import time\nbatch_size = 7\narr_len = 298937\n\n#---------slice-------------\n\nprint(\"\\r\\nslice\")\nstart = time.time()\narr = [i for i in range(0, arr_len)]\nwhile True:\n if not arr:\n break\n\n tmp = arr[0:batch_size]\n arr = arr[batch_size:-1]\nprint(time.time() - start)\n\n#-----------index-----------\n\nprint(\"\\r\\nindex\")\narr = [i for i in range(0, arr_len)]\nstart = time.time()\nfor i in range(0, round(len(arr) / batch_size + 1)):\n tmp = arr[batch_size * i : batch_size * (i + 1)]\nprint(time.time() - start)\n\n#----------batches 1------------\n\ndef batch(iterable, n=1):\n l = len(iterable)\n for ndx in range(0, l, n):\n yield iterable[ndx:min(ndx + n, l)]\n\nprint(\"\\r\\nbatches 1\")\narr = [i for i in range(0, arr_len)]\nstart = time.time()\nfor x in batch(arr, batch_size):\n tmp = x\nprint(time.time() - start)\n\n#----------batches 2------------\n\nfrom itertools import islice, chain\n\ndef batch(iterable, size):\n sourceiter = iter(iterable)\n while True:\n batchiter = islice(sourceiter, size)\n yield chain([next(batchiter)], batchiter)\n\n\nprint(\"\\r\\nbatches 2\")\narr = [i for i in range(0, arr_len)]\nstart = time.time()\nfor x in batch(arr, batch_size):\n tmp = x\nprint(time.time() - start)\n\n#---------chunks-------------\ndef chunks(l, n):\n \"\"\"Yield successive n-sized chunks from l.\"\"\"\n for i in range(0, len(l), n):\n yield l[i:i + n]\nprint(\"\\r\\nchunks\")\narr = [i for i in range(0, arr_len)]\nstart = time.time()\nfor x in chunks(arr, batch_size):\n tmp = x\nprint(time.time() - start)\n\n#-----------grouper-----------\n\nfrom itertools import zip_longest # for Python 3.x\n#from six.moves import zip_longest # for both (uses the six compat library)\n\ndef grouper(iterable, n, padvalue=None):\n \"grouper(3, 'abcdefg', 'x') --> ('a','b','c'), ('d','e','f'), ('g','x','x')\"\n return zip_longest(*[iter(iterable)]*n, fillvalue=padvalue)\n\narr = [i for i in range(0, arr_len)]\nprint(\"\\r\\ngrouper\")\nstart = time.time()\nfor x in grouper(arr, batch_size):\n tmp = x\nprint(time.time() - start)\n"
},
{
"answer_id": 49456217,
"author": "Arthur Sult",
"author_id": 3110300,
"author_profile": "https://Stackoverflow.com/users/3110300",
"pm_score": 0,
"selected": false,
"text": "def proportional_dividing(N, n):\n \"\"\"\n N - length of array (bigger number)\n n - number of chunks (smaller number)\n output - arr, containing N numbers, diveded roundly to n chunks\n \"\"\"\n arr = []\n if N == 0:\n return arr\n elif n == 0:\n arr.append(N)\n return arr\n r = N // n\n for i in range(n-1):\n arr.append(r)\n arr.append(N-r*(n-1))\n\n last_n = arr[-1]\n # last number always will be r <= last_n < 2*r\n # when last_n == r it's ok, but when last_n > r ...\n if last_n > r:\n # ... and if difference too big (bigger than 1), then\n if abs(r-last_n) > 1:\n #[2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 7] # N=29, n=12\n # we need to give unnecessary numbers to first elements back\n diff = last_n - r\n for k in range(diff):\n arr[k] += 1\n arr[-1] = r\n # and we receive [3, 3, 3, 3, 3, 2, 2, 2, 2, 2, 2, 2]\n return arr\n\ndef split_items(items, chunks):\n arr = proportional_dividing(len(items), chunks)\n splitted = []\n for chunk_size in arr:\n splitted.append(items[:chunk_size])\n items = items[chunk_size:]\n print(splitted)\n return splitted\n\nitems = [1,2,3,4,5,6,7,8,9,10,11]\nchunks = 3\nsplit_items(items, chunks)\nsplit_items(['a','b','c','d','e','f','g','h','i','g','k','l', 'm'], 3)\nsplit_items(['a','b','c','d','e','f','g','h','i','g','k','l', 'm', 'n'], 3)\nsplit_items(range(100), 4)\nsplit_items(range(99), 4)\nsplit_items(range(101), 4)\n"
},
{
"answer_id": 52022535,
"author": "pylang",
"author_id": 4531270,
"author_profile": "https://Stackoverflow.com/users/4531270",
"pm_score": 6,
"selected": false,
"text": "itertools.batched"
},
{
"answer_id": 55776536,
"author": "luckydonald",
"author_id": 3423324,
"author_profile": "https://Stackoverflow.com/users/3423324",
"pm_score": -1,
"selected": false,
"text": "import pprint\npprint.pprint(list(chunks(range(10, 75), 10)))\n[range(10, 20),\n range(20, 30),\n range(30, 40),\n range(40, 50),\n range(50, 60),\n range(60, 70),\n range(70, 75)]\n"
},
{
"answer_id": 56273344,
"author": "ajaest",
"author_id": 747616,
"author_profile": "https://Stackoverflow.com/users/747616",
"pm_score": 0,
"selected": false,
"text": "> from itertools import groupby\n> batch_no = 3\n> data = 'abcdefgh'\n\n> [\n [x[1] for x in x[1]] \n for x in \n groupby(\n sorted(\n (x[0] % batch_no, x[1]) \n for x in \n enumerate(data)\n ),\n key=lambda x: x[0]\n )\n ]\n\n[['a', 'd', 'g'], ['b', 'e', 'h'], ['c', 'f']]\n\n"
},
{
"answer_id": 56954384,
"author": "Ravi Anand",
"author_id": 2444505,
"author_profile": "https://Stackoverflow.com/users/2444505",
"pm_score": 3,
"selected": false,
"text": "pydash"
},
{
"answer_id": 57042866,
"author": "J-L",
"author_id": 8513648,
"author_profile": "https://Stackoverflow.com/users/8513648",
"pm_score": 1,
"selected": false,
"text": ".comb(n)"
},
{
"answer_id": 59163343,
"author": "Realfun",
"author_id": 93571,
"author_profile": "https://Stackoverflow.com/users/93571",
"pm_score": -1,
"selected": false,
"text": "def chunks(g, n):\n \"\"\"divide a generator 'g' into small chunks\n Yields:\n a chunk that has 'n' or less items\n \"\"\"\n n = max(1, n)\n buff = []\n for item in g:\n buff.append(item)\n if len(buff) == n:\n yield buff\n buff = []\n if buff:\n yield buff\n"
},
{
"answer_id": 59266741,
"author": "nirvana-msu",
"author_id": 5540279,
"author_profile": "https://Stackoverflow.com/users/5540279",
"pm_score": 5,
"selected": false,
"text": "import itertools\n\ndef batch(iterable, size):\n it = iter(iterable)\n while item := list(itertools.islice(it, size)):\n yield item\n"
},
{
"answer_id": 61212415,
"author": "Matheus Vinícius de Andrade",
"author_id": 5013644,
"author_profile": "https://Stackoverflow.com/users/5013644",
"pm_score": 0,
"selected": false,
"text": "def main():\n print(chunkify([1,2,3,4,5,6],2))\n\ndef chunkify(list, n):\n chunks = []\n for i in range(0, len(list), n):\n chunks.append(list[i:i+n])\n return chunks\n\nmain()\n"
},
{
"answer_id": 62216571,
"author": "alani",
"author_id": 13596037,
"author_profile": "https://Stackoverflow.com/users/13596037",
"pm_score": 1,
"selected": false,
"text": "chunker.py"
},
{
"answer_id": 62643989,
"author": "Kandarp",
"author_id": 6236853,
"author_profile": "https://Stackoverflow.com/users/6236853",
"pm_score": 2,
"selected": false,
"text": "l = [1,2,3,4,5,6,7,8,9]\nn = 3\noutList = []\nfor i in range(n, len(l) + n, n):\n outList.append(l[i-n:i])\n\nprint(outList)\n"
},
{
"answer_id": 64041110,
"author": "Arty",
"author_id": 941531,
"author_profile": "https://Stackoverflow.com/users/941531",
"pm_score": 0,
"selected": false,
"text": "chunk_iters = lambda it, n: ((e for i, g in enumerate(((f,), cit)) for j, e in zip(range((1, n - 1)[i]), g)) for cit in (iter(it),) for f in cit)\n"
},
{
"answer_id": 66734805,
"author": "Arij Aladel",
"author_id": 14494113,
"author_profile": "https://Stackoverflow.com/users/14494113",
"pm_score": 0,
"selected": false,
"text": "\nx = list(range(10, 75))\nindices = x[0::10]\nprint(\"indices: \", indices)\nxx = [x[i-10:i] for i in indices ]\nprint(\"x= \", x)\nprint (\"xx= \",xx)\n\n"
},
{
"answer_id": 66967457,
"author": "Brandt",
"author_id": 687896,
"author_profile": "https://Stackoverflow.com/users/687896",
"pm_score": 2,
"selected": false,
"text": "input_list"
},
{
"answer_id": 67181221,
"author": "Bapan Biswas",
"author_id": 10685363,
"author_profile": "https://Stackoverflow.com/users/10685363",
"pm_score": -1,
"selected": false,
"text": "from itertools import islice\nl=[1,2,3,4,5,6]\nchuncksize=input(\"Enter chunk size\")\nm=[]\nobj=iter(l)\nm.append(list(islice(l,3)))\nm.append(list(islice(l,3)))\nprint(m)\n"
},
{
"answer_id": 70381614,
"author": "Amin Rezaei",
"author_id": 8010865,
"author_profile": "https://Stackoverflow.com/users/8010865",
"pm_score": -1,
"selected": false,
"text": "tqdm"
},
{
"answer_id": 70555495,
"author": "nikicat",
"author_id": 1022684,
"author_profile": "https://Stackoverflow.com/users/1022684",
"pm_score": -1,
"selected": false,
"text": "from itertools import islice\nfrom functools import partial\n\nseq = [1,2,3,4,5,6,7]\nsize = 3\nresult = list(iter(partial(lambda it: tuple(islice(it, size)), iter(seq)), ()))\nassert result == [(1, 2, 3), (4, 5, 6), (7,)]\n"
},
{
"answer_id": 70927990,
"author": "shanu khera",
"author_id": 1494588,
"author_profile": "https://Stackoverflow.com/users/1494588",
"pm_score": 0,
"selected": false,
"text": "lst"
},
{
"answer_id": 72960641,
"author": "cottontail",
"author_id": 19123103,
"author_profile": "https://Stackoverflow.com/users/19123103",
"pm_score": 0,
"selected": false,
"text": "zip_longest(*[iter(lst)]*n, fillvalue=padvalue)"
},
{
"answer_id": 73268211,
"author": "mikey",
"author_id": 8969601,
"author_profile": "https://Stackoverflow.com/users/8969601",
"pm_score": 1,
"selected": false,
"text": "more_itertools.chunked_even"
},
{
"answer_id": 74120449,
"author": "Raymond Hettinger",
"author_id": 424499,
"author_profile": "https://Stackoverflow.com/users/424499",
"pm_score": 1,
"selected": false,
"text": "from itertools import islice, izip_longest\n\ndef batched(iterable, n):\n \"Batch data into lists of length n. The last batch may be shorter.\"\n # batched('ABCDEFG', 3) --> ABC DEF G\n it = iter(iterable)\n while True:\n batch = list(islice(it, n))\n if not batch:\n return\n yield batch\n\ndef grouper(iterable, n, *, incomplete='fill', fillvalue=None):\n \"Collect data into non-overlapping fixed-length chunks or blocks\"\n # grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx\n # grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError\n # grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF\n args = [iter(iterable)] * n\n if incomplete == 'fill':\n return zip_longest(*args, fillvalue=fillvalue)\n if incomplete == 'strict':\n return zip(*args, strict=True)\n if incomplete == 'ignore':\n return zip(*args)\n else:\n raise ValueError('Expected fill, strict, or ignore')\n"
},
{
"answer_id": 74534397,
"author": "Miroslav Savel",
"author_id": 10839776,
"author_profile": "https://Stackoverflow.com/users/10839776",
"pm_score": -1,
"selected": false,
"text": "a = [1, 2, 3, 4]\nfor i, k in more_itertools.pairwise(a):\n result += compute(i,k)\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312443",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/112415/"
] |
312,444 | <p>Greetings,</p>
<p>I'm trying to use pylucene in Python 2.6. Since there's no windows build for 2.6, I try to build the source code.</p>
<p>First of all, I build JCC (windows, using cygwin)</p>
<pre><code>python setup.py build
running build
running build_py
[...]
building 'jcc' extension
error: None
python setup.py install
running install
[...]
copying jcc\config.py -> build\lib.win32-2.6\jcc
copying jcc\classes\org\osafoundation\jcc\PythonException.class -> build\lib.win32-2.6\jcc\classes\org\osafoundation\jcc
running build_ext
building 'jcc' extension
error: None
</code></pre>
<p>Notice that it won't copy anything on my "F:\Python26\Lib\site-packages" directory. I don't know why. So that, I don't know if it's really installed or not.</p>
<p>Now, I'll make pylucene</p>
<pre><code>make
/cygdrive/f/Python26//python.exe -m jcc --shared --jar lucene-java-2.4.0/build/lucene-core-2.4.0.jar
[...]
'doc:(I)Lorg/apache/lucene/document/Document;' --version 2.4.0 --files 2 --build
f:\Python26\python.exe: No module named jcc
make: *** [compile] Error 1
</code></pre>
<p>So, it seems JCC wasn't installed at all.</p>
<p>Then, I try to copy the "jcc build" under F:\Python26\Lib\site-packages, and I try to make pylucene again:</p>
<pre><code>make
[...]
f:\Python26\python.exe: jcc is a package and cannot be directly executed
make: *** [compile] Error 1
</code></pre>
<p>Has anyone else seen this and found a workaround?</p>
| [
{
"answer_id": 2046369,
"author": "YOU",
"author_id": 213464,
"author_profile": "https://Stackoverflow.com/users/213464",
"pm_score": 1,
"selected": false,
"text": "error: None"
},
{
"answer_id": 3048703,
"author": "image72",
"author_id": 362668,
"author_profile": "https://Stackoverflow.com/users/362668",
"pm_score": 0,
"selected": false,
"text": ">>> import jcc\nTraceback (most recent call last):\n File \"<stdin>\", line 1, in <module>\n File \"D:\\Python26\\lib\\site-packages\\jcc-2.5.1-py2.6-win32.egg\\jcc\\__init__.py\"\n, line 29, in <module>\n from _jcc import initVM\nImportError: DLL load failed: 找不到指定的模块。(cant find appointed modules)\n>>>\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312444",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/40062/"
] |
312,471 | <p>I would like a Win machine to tunnel into an SSH server whenever the machine starts up. I also want the win machine to reboot the SSH program if it ever crashes. The lighterweight & more stable the SSH program, the more happier I am.</p>
<p>What options do I have with this? </p>
| [
{
"answer_id": 24726894,
"author": "Sopalajo de Arrierez",
"author_id": 1461017,
"author_profile": "https://Stackoverflow.com/users/1461017",
"pm_score": 1,
"selected": false,
"text": "C:\\>tasklist | find \"always\" /i\nAlwaysUp.exe 3112 Console 1 17.388 KB\n"
},
{
"answer_id": 55233411,
"author": "Tony",
"author_id": 2706794,
"author_profile": "https://Stackoverflow.com/users/2706794",
"pm_score": 1,
"selected": false,
"text": "# LocalPort TargetHost TargetPort SshHost SshUsername SshKeyPath \n18080 google.com 80 bastion.example.com User D:\\secure\\path\\to\\private_key.ppk\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312471",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/10352/"
] |
312,487 | <p>Need help narrowing the scope of this Regex to not return records if there is an alphanumeric character preceding the first "I"</p>
<pre><code>"I([ ]{1,2})([a-zA-Z]|\d){2,13}"
</code></pre>
<p>Want to capture I APF From this string, but not the I ARPT. </p>
<pre><code>I APF 'NAPLES MUNI ARPT. ' 42894 JEB 29785584
</code></pre>
<p>Thanks! </p>
| [
{
"answer_id": 312504,
"author": "Gareth",
"author_id": 31582,
"author_profile": "https://Stackoverflow.com/users/31582",
"pm_score": 4,
"selected": true,
"text": "\\b"
},
{
"answer_id": 312508,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 2,
"selected": false,
"text": "\\bI[ ]{1,2}[A-Za-z0-9]{2,13}\n"
},
{
"answer_id": 312667,
"author": "Tom Haigh",
"author_id": 22224,
"author_profile": "https://Stackoverflow.com/users/22224",
"pm_score": 0,
"selected": false,
"text": "(?<![a-zA-Z0-9])I([ ]{1,2})([a-zA-Z]|\\d){2,13}\n"
},
{
"answer_id": 312740,
"author": "PhiLho",
"author_id": 15459,
"author_profile": "https://Stackoverflow.com/users/15459",
"pm_score": 1,
"selected": false,
"text": "\\bI ?[A-Za-z\\d]{2,13}\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312487",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/38349/"
] |
312,491 | <p>I'm adding an existing site to SVN.</p>
<p>The files already exist on the webserver, and now identical copies (- configuration files) exist in the repository.</p>
<p>I want to convert the webserver directory into an SVN working copy, but when I run:</p>
<pre><code>svn checkout http://path.to/svn/repo/httpdocs .
</code></pre>
<p>I get the error:</p>
<blockquote>
<p>svn: Failed to add file '': object of the same name already exists</p>
</blockquote>
<p>How do I tell SVN to just overwrite those files whose contents are the same?</p>
| [
{
"answer_id": 312493,
"author": "Ned Batchelder",
"author_id": 14343,
"author_profile": "https://Stackoverflow.com/users/14343",
"pm_score": 2,
"selected": false,
"text": "old_crufty"
},
{
"answer_id": 312519,
"author": "Will Dean",
"author_id": 987,
"author_profile": "https://Stackoverflow.com/users/987",
"pm_score": 7,
"selected": true,
"text": "--force"
},
{
"answer_id": 1103483,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 3,
"selected": false,
"text": "/usr/local/www\n\nmv www temp_www\nsvn co http://www.yourrepo.com/therepo www\ncp -pR ./temp_www/* ./www\nsvn revert -R ./www/*\nsvn update\n"
},
{
"answer_id": 1255727,
"author": "Community",
"author_id": -1,
"author_profile": "https://Stackoverflow.com/users/-1",
"pm_score": 6,
"selected": false,
"text": "svn checkout --force svn://repo website.dir"
},
{
"answer_id": 10210129,
"author": "Be Kind To New Users",
"author_id": 192044,
"author_profile": "https://Stackoverflow.com/users/192044",
"pm_score": 3,
"selected": false,
"text": "rm -rf lib\nsvn up\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312491",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/13238/"
] |
312,511 | <p>I am looking to use/connect to a different database for one of my controllers and one model. I posted this hear since on the forums of CI I am getting no response.</p>
<p>I added this in database.php:</p>
<pre><code>$db['tdb']['hostname'] = "localhost";//localhost
$db['tdb']['username'] = "username";//root
$db['tdb']['password'] = "password";//empty
$db['tdb']['database'] = "databasename";
$db['tdb']['dbdriver'] = "mysql";
$db['tdb']['dbprefix'] = "";
$db['tdb']['pconnect'] = FALSE;
$db['tdb']['db_debug'] = FALSE;
$db['tdb']['cache_on'] = FALSE;
$db['tdb']['cachedir'] = "";
$db['tdb']['char_set'] = "utf8";
$db['tdb']['dbcollat'] = "utf8_general_ci";
</code></pre>
<p>This as my model:</p>
<pre><code><?php
class Tadmin_model extends Model{
function Tadmin_model(){
parent::Model();
$tdb = $this->load->database('tdb', TRUE);
}
function FInsert($usernames){
$query = $tdb->query("SELECT * FROM following");
return $query->row();
}
}
?>
</code></pre>
<p>And this is the start of my controller:</p>
<pre><code><?php
class Tadmin extends Controller{
function Tradmin(){
parent::Controller();
$this->load->model('tadmin_model');
</code></pre>
<p>And I get this error:</p>
<blockquote>
<p>A PHP Error was encountered</p>
<p>Severity: Notice</p>
<p>Message: Undefined variable: tdb</p>
<p>Filename: models/tadmin_model.php</p>
<p>Line Number: ...</p>
<p>Fatal error: Call to a member function
query() on a non-object in
/blablabla/tadmin_model.php on line
...</p>
</blockquote>
<p>What am I doing wrong here?</p>
| [
{
"answer_id": 342812,
"author": "Jim OHalloran",
"author_id": 38458,
"author_profile": "https://Stackoverflow.com/users/38458",
"pm_score": 3,
"selected": false,
"text": "<?php\n\nclass Tadmin_model extends Model{\n var $tdb;\n\n function Tadmin_model(){\n\n parent::Model();\n\n $this->tdb = $this->load->database('tdb', TRUE); \n }\n\n function FInsert($usernames){\n\n $query = $this->tdb->query(\"SELECT * FROM following\");\n\n return $query->row();\n } \n}\n\n?>\n"
},
{
"answer_id": 2224603,
"author": "Raheel Khawaja",
"author_id": 268965,
"author_profile": "https://Stackoverflow.com/users/268965",
"pm_score": 0,
"selected": false,
"text": "class Tadmin_model extends Model {\n var $tdb;\n\n function Tadmin_model() {\n parent::Model();\n $this->tdb = $this->load->database('tdb', TRUE); \n }\n}\n"
}
] | 2008/11/23 | [
"https://Stackoverflow.com/questions/312511",
"https://Stackoverflow.com",
"https://Stackoverflow.com/users/-1/"
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.