body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>This method is part of my login system. Could I improve it further?</p> <pre><code>protected function _hashPassword($password = NULL, $rounds = 1000, $i = 1) { if (! isset($password)) throw new Exception('No password set!'); $salt = 'K^^%/m&gt;(|{z= $1^&gt;%&gt;W[=4U5*p|,E'; $pepper = '08[)^,&amp;%^^...
[]
[ { "body": "<p>I would use a for loop instead of recursive calls:</p>\n\n<pre><code>protected function _hashPassword($password = NULL, $rounds = 1000) {\n if (!isset($password)) throw new Exception('No password set!');\n\n $salt = 'K^^%/m&gt;(|{z= $1^&gt;%&gt;W[=4U5*p|,E';\n $pepper = '08[)^,&amp;%^^7...
{ "AcceptedAnswerId": "6428", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-30T20:42:32.183", "Id": "6426", "Score": "4", "Tags": [ "php", "security", "recursion" ], "Title": "Recursive hashing function" }
6426
<p>I have created this class to simulate a thread-safe Singleton.</p> <p>Have I missed anything?</p> <pre><code>#include &lt;boost/thread/mutex.hpp&gt; class Singleton { public: static Singleton&amp; GetInstance() { boost::mutex::scoped_lock lock(m_mutex); static Singleton instance; return instance; ...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-30T21:15:24.670", "Id": "9971", "Score": "0", "body": "Maybe I'm missing something. Why not just declare your singleton where the mutex is declared? Then you wouldn't even *need* the mutex because you don't have a race for the constr...
[ { "body": "<p>As usual, when dealing with singletons, consider that <em>you probably shouldn't be making a singleton at all</em>.</p>\n\n<p>Read <a href=\"http://jalf.dk/singleton\" rel=\"nofollow\">this</a>, for example. A singleton is almost certainly not what you actually need, <em>even if it is implemented ...
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-30T20:59:28.170", "Id": "6427", "Score": "22", "Tags": [ "c++", "thread-safety", "singleton" ], "Title": "Thread-safe Singleton class" }
6427
<p>I have a singleton class which extends from an abstract java class. Two singleton classes extend from <code>ItemImageThreadManager</code>, the reason for this is to use shared scheduling functionality. A thread is created and passed into the <code>runThread</code> method of <code>ItemImageThreadManager</code>.</p> ...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-01T03:46:35.227", "Id": "9994", "Score": "1", "body": "> Is this good design ?\n\nNo . \n\n 1. Why do you need to two classes with same name ? It would not even compile in same package.\n 2. Why do you need Singleton ? I am not as anti...
[ { "body": "<p>As others mentioned the <code>getSingletonObject</code> should be synchronized. There is a chapter in <em>Effective Java, Second Edition</em> about singletons (<em>Item 3: Enforce the singleton property with a private constructor or an enum type</em>). It's worth to read. Anyway, try to avoid them...
{ "AcceptedAnswerId": "6482", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-30T21:41:35.283", "Id": "6431", "Score": "5", "Tags": [ "java", "design-patterns", "multithreading", "thread-safety", "singleton" ], "Title": "Singleton class extending a p...
6431
<p>Suppose we have the following program:</p> <pre><code>#include &lt;stdlib.h&gt; #include &lt;stdio.h&gt; int main() { char *user = getenv("USER"); char buffer[4096]; if (user) { snprintf(buffer, sizeof buffer, "/bin/echo %s", user); system(buffer); ...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-30T16:44:36.670", "Id": "9981", "Score": "2", "body": "Do you have actual code that compiles and demonstrates the vulnerability?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-30T16:45:28.810", "Id": "...
[ { "body": "<p>If you want to print out the value of the <code>USER</code> environment variable, you can do:</p>\n\n<pre><code>fprintf(stderr, \"%s\", getenv(\"USER\"));\n</code></pre>\n\n<p>There's no need to call <code>system();</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0"...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-11-30T16:43:29.997", "Id": "6435", "Score": "7", "Tags": [ "c", "security" ], "Title": "C system() function vulnerability" }
6435
<p>I'm an objective-c developer. But i'm getting familar with C. I wrote it for my own develpment in C. Please point on some errors!</p> <p>The point is to store/read bytes in file named "key" in cachePath directory.</p> <p><strong>Cache.h</strong></p> <pre><code>typedef const struct Cache *CacheRef; /* Returns cac...
[]
[ { "body": "<pre><code>size_t pathLength = strlen(cache-&gt;path) + strlen(key);\nchar *path = malloc(pathLength);\nstrcpy(path, cache-&gt;path);\nstrcat(path, key);\n</code></pre>\n\n<p>Try this instead:</p>\n\n<pre><code>size_t path_len = strlen(cache-&gt;path);\nsize_t key_len = strlen(key);\nsize_t total_len...
{ "AcceptedAnswerId": "6443", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-01T06:23:38.620", "Id": "6442", "Score": "3", "Tags": [ "c" ], "Title": "Working on key-value disk cache written in plain C. Is there any errors?" }
6442
<p>I am working on a program which use OLEDB to connect to a MS Access 2007 file. My program has a possibility to add and delete records from file by using SQL statements which select deleted item by ID.</p> <p>Now, I was warned that my code might cause SQL injection which would delete all entries from the file. How c...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-01T19:40:07.700", "Id": "10032", "Score": "0", "body": "Its getting better, but I'd still try to use OleDbParameter in your query generation as a good habit. (Because when you do what you do this with string instead of a number, you're...
[ { "body": "<p>Unless I misunderstand, you are using unfiltered user input from <code>txtEntryID</code>.<br>\n<strong>Never trust user input.</strong></p>\n\n<p>What if the user fills <code>txtEntryID</code> with <code>123 OR 1=1</code>?<br>\nThe query will delete everything:</p>\n\n<pre><code>DELETE FROM Person...
{ "AcceptedAnswerId": "6446", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-01T07:17:15.063", "Id": "6444", "Score": "5", "Tags": [ "c#", "security", "sql-injection", "ms-access" ], "Title": "Using OLEDB to connect to a MS Access 2007 file" }
6444
<p>I have written the below code to search for a string in a web page. This is working fine but I need suggestions on improving this code to start using this. This is written to work under IE.</p> <pre><code>$(document).ready(function() { var NotFounds = []; function countString(s) { var re = new RegExp(s, 'gi'); ...
[]
[ { "body": "<ol>\n<li><p>Instead of wrapping your code in <code>$(document).ready(function(){</code>, you should put the <code>&lt;script&gt;</code> tag at the bottom of file ( right before closing <code>&lt;/body&gt;</code> ), then you script will get executed right after the DOM is ready.</p></li>\n<li><p>Do n...
{ "AcceptedAnswerId": "6455", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-01T16:58:48.183", "Id": "6453", "Score": "2", "Tags": [ "javascript", "jquery", "strings", "search" ], "Title": "Searching for a string in a web page" }
6453
<p>In particular, I'm not happy with case 5 in the Control class. Basically, in case 5, I would like the user to attach a student from the students array onto a module from the modules array without duplication. Any suggestions/example would be very useful.</p> <p><strong>Driver Class:</strong></p> <pre><code>publi...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-01T19:04:26.990", "Id": "10038", "Score": "2", "body": "You gotta explain what the program is supposed to be doing. Also, you can use a variable for indexing in an array. That way, you'd have a bit less duplication." }, { "Cont...
[ { "body": "<ol>\n<li>There doesn't seem to be any reason for where you've split your Menu and Controller classes. Most of the menu logic is still in controller.</li>\n<li>If you ever find yourself defining variables or constants with sequential numbers like: STUDENT1, STUDENT2, STUDENT3, you are doing it wrong....
{ "AcceptedAnswerId": "6460", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-01T17:16:36.670", "Id": "6454", "Score": "6", "Tags": [ "java" ], "Title": "Student record system" }
6454
<p>I've got a simple program written in Golang that takes a map as input and tries to solve the <a href="http://en.wikipedia.org/wiki/Travelling_salesman_problem" rel="nofollow">travelling salesman problem</a> by using a genetic algorithm. My Crossover method is a real performance killer due to intense use of <code>mak...
[]
[ { "body": "<p>How about using a slice for <code>Gene.Data</code>?</p>\n\n<p>You just allocate</p>\n\n<pre><code>var allData := make([]int, nCrossover * ts.geneLength)\n</code></pre>\n\n<p>before entering the for loop and assign</p>\n\n<pre><code>newGenes[i].Data = allData[i * ts.geneLength: (i + 1) * ts.geneLen...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-01T23:34:31.147", "Id": "6464", "Score": "6", "Tags": [ "performance", "go", "traveling-salesman" ], "Title": "Solving the travelling salesman problem using a genetic algorithm" }
6464
<p>Defines a simple module for timeoutable computations, with the ability to return arbitrary intermediary results on timeout or the final value otherwise. It also allows default return values. </p> <p>The implementation uses Unix.sigalrm to define timeout intervals with second resolution. There is a small overhead o...
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-02T11:35:53.637", "Id": "6467", "Score": "19", "Tags": [ "functional-programming", "ocaml" ], "Title": "Timeoutable computations module" }
6467
<p>To fullfil a promise, I cooked the following script :</p> <pre><code>[Code] var BDS: string; // No trailing backslash path BDSCOMMONDIR: string; // No trailing backslash path BDSPROJECTSDIR: string; // No trailing backslash path BDSUSERDIR: string; // No trailing backslash path // BPLPath: string; // No...
[]
[ { "body": "<p>Some generic notes below. (I'm not sure that the codes are valid Delphi codes or not. Feel free to fix them.)</p>\n\n<p>Instead of <code>Copy(s,15+1,Length(s)-15)</code> you should create a function like this:</p>\n\n<pre><code>function ReplaceLastChars(input: string, charNum: integer): string;\nb...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-02T12:35:37.783", "Id": "6469", "Score": "2", "Tags": [ "delphi" ], "Title": "Asking for peer review of theses innosetup snippets" }
6469
<p>I have an simple algorithm which marks table rows with identical entries blue. The problem is that this solution takes a lot of time.</p> <p>Has anyone an idea how to improve the speed of this?</p> <pre><code>$(document).ready(function(){ var tableRows = $("#sortable tbody tr"); tableRows.each(function(n){ ...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-02T14:07:17.337", "Id": "10060", "Score": "2", "body": "can u please post some html of it....so we can give you ways..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-02T14:08:05.747", "Id": "10061", ...
[ { "body": "<p>Without making algorithmic changes, we can still make some performance improvements:</p>\n\n<pre><code>$(document).ready(function() {\n var $tableRows = $(\"#sortable tbody tr\");\n var $rowsToMark = $();\n\n $tableRows.each(function(n) {\n var id = this.id;\n var example = ...
{ "AcceptedAnswerId": "6578", "CommentCount": "9", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-02T14:02:23.247", "Id": "6470", "Score": "17", "Tags": [ "javascript", "performance", "jquery" ], "Title": "Mark rows with identical values in a table" }
6470
<p>I was thinking about doing <a href="http://projecteuler.net/problem=23" rel="nofollow">problem 23</a> of Project Euler. It includes the difficulty where you have to factorize primes. I had already done that in problems I solved earlier, but it was only necessary to have a prime list until a relative small number.</p...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-02T19:49:38.597", "Id": "10078", "Score": "0", "body": "possible duplicate of [Fastest way to list all primes below N in python](http://stackoverflow.com/questions/2068372/fastest-way-to-list-all-primes-below-n-in-python)" }, { ...
[ { "body": "<p>One minor improvement is to use <code>xrange</code> instead of <code>range</code>. In your case, you don't need <code>range</code>, and <code>xrange</code> has better memory performance, which might make a little difference.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3....
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-02T19:45:30.840", "Id": "6477", "Score": "3", "Tags": [ "python", "algorithm", "primes", "programming-challenge", "sieve-of-eratosthenes" ], "Title": "Sieve of Eratosthenes: ...
6477
<p>I need a Read-Write lock that is fast and generally portable on Windows machines (including XP, otherwise I'd just use the SRWLock that was introduced with Vista). I've written this custom implementation, partly as an exercise, and partly to avoid including Boost just for the one class.</p> <p>I'm an amateur, thou...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-02T23:47:04.973", "Id": "10088", "Score": "0", "body": "Why not use TBBs or boosts existing and well tested solutions?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T00:19:31.293", "Id": "10095", ...
[ { "body": "<p>This looks like a writer biased reader/writer lock. That may be fine, but beware of reader starvation if there is a high rater of writers.</p>\n\n<p>Note, also, that the Vista+ reader/writer lock is neither reader nor writer biased. I've not been able to find explicit documentation about how it de...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-02T21:47:37.030", "Id": "6483", "Score": "8", "Tags": [ "c++", "multithreading", "locking" ], "Title": "\"Fast\" Read/Write Lock" }
6483
<pre><code>function prepareEventHandlers() { var sectionButton1 = document.getElementById("sectionButton1"); var sectionButton2 = document.getElementById("sectionButton2"); var sectionButton3 = document.getElementById("sectionButton3"); var sectionButton4 = document.getElementById("sectionButton4"); ...
[]
[ { "body": "<p>Well first you should think about refactoring your code. The following </p>\n\n<pre><code>if (enabled1) {\n sectionButton1.setAttribute(\"class\", \"sectionButtonEnabled\");\n}\n</code></pre>\n\n<p>is repeated a few times with just 2 differences. The enabled flag and the button. So this coul...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-02T23:45:36.077", "Id": "6487", "Score": "5", "Tags": [ "javascript", "event-handling" ], "Title": "Mouseover effects for five buttons which may be enabled or disabled" }
6487
<p>I am still pretty new to Haskell and am working on a graph generator for undirected unlabeled graphs containing loops and I have a bottleneck in the following functions. So far, I have not given any thought to performance and just looked for correctness. </p> <p>I know this kind of question is not really popular, b...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-01T18:03:30.843", "Id": "10089", "Score": "2", "body": "Possibly the most important thing is to **figure out how to effectively measure performance**, and determine based on that data where the bottlenecks are. Haskell's performance c...
[ { "body": "<pre><code>-- for a given y = (y_1,...,y_n) and a bound m, find all vectors\n-- x = (x_1,...,x_n) such that |x| = m and x_i &lt;= y_i\nboundSequences :: (Num a, Ord a, Enum a) =&gt; a -&gt; [a] -&gt; [[a]]\nboundSequences m x | m &lt;= sum x = (fByM . sequence . ranges) x\n | otherw...
{ "AcceptedAnswerId": "6489", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-01T18:00:04.597", "Id": "6488", "Score": "10", "Tags": [ "performance", "beginner", "haskell", "graph" ], "Title": "Graph generator for undirected graphs" }
6488
<p>Is there a better way to do what I'm doing? If not, I'd like just a general review of how I did it and the usability of it (how it works and functions, not artistically how it looks).</p> <p>Here is the working <a href="http://jsfiddle.net/jzaun/Gw2QS/" rel="nofollow">JSFiddle</a>.</p> <p><strong>JavaScript</stron...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T02:32:18.530", "Id": "10097", "Score": "1", "body": "do you know what **divitis** is ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T02:34:12.177", "Id": "10098", "Score": "0", "body": "...
[ { "body": "<ul>\n<li>your tab label seems to exist within the content which it is <em>tabbing</em> .. kinda bad, don't you think.</li>\n<li>there is no point in using <code>$(document).ready()</code>, just put your script file right before <code>&lt;/body&gt;</code> , and it will already be executing, when the ...
{ "AcceptedAnswerId": "6492", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T02:18:02.630", "Id": "6491", "Score": "4", "Tags": [ "javascript", "jquery", "html", "css" ], "Title": "Usability of sliding panels" }
6491
<p>I'm learning Python 3 at the moment, so to test the skills I've learned, I am trying the puzzles at <a href="http://www.pythonchallenge.com/" rel="nofollow">Python Challenge</a>.</p> <p>I've created some code to solve the 2nd puzzle <a href="http://www.pythonchallenge.com/pc/def/map.html" rel="nofollow">here</a>. i...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T03:54:03.800", "Id": "64519", "Score": "0", "body": "Take a look at the python dictionary. Consider replacing characters?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T06:46:48.197", "Id": "1147...
[ { "body": "<p>I would do a couple of things differently.</p>\n\n<pre><code>import string\nfrom collections import deque\n\nascii1 = string.ascii_lowercase\n\n# create a deque to simplify rotation.\nd = deque(ascii1)\nd.rotate(-2)\n\nascii2 = ''.join(d)\n\nreplacements = dict(zip(ascii1, ascii2))\n\noldmessage =...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T03:49:51.177", "Id": "6493", "Score": "3", "Tags": [ "python", "python-3.x", "caesar-cipher" ], "Title": "Simplifying working Caesar cipher" }
6493
<p>I have been doing PHP for about three years now, with little direction other than the books I read and trial and error. </p> <p>I am currently coding what I hope to be a pretty nice application and I have decided to throw myself into the fire and get torn apart (haha you think this is a nice application!!)</p> <p>...
[]
[ { "body": "<p>This is <strong>not</strong> a Controller. The purpose of <a href=\"http://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller\" rel=\"nofollow\">MVC</a> is <a href=\"http://en.wikipedia.org/wiki/Separation_of_concerns\" rel=\"nofollow\">separation of concerns</a>, more specifically the se...
{ "AcceptedAnswerId": "6500", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T05:34:37.367", "Id": "6495", "Score": "1", "Tags": [ "php" ], "Title": "Am I headed in the right direction with PHP?" }
6495
<p>In the following piece of code I am adding entries to an MS Access file using OleDB. The purpose of this post is to point out my bad programming practices and if I have created any security flaws here. I was reading somewhat about SQL injection attacks, and I wonder if this code might have any potential bugs.</p> <...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-04T03:59:33.920", "Id": "10150", "Score": "1", "body": "If you're using C# you should consider LINQ-to-SQL." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-04T04:01:16.007", "Id": "10151", "Score": ...
[ { "body": "<p>I can't see any SQL vulnerabilities, but I see a few crypto mistakes.</p>\n\n<ol>\n<li>You're using the same password for the database login and the contents. You shouldn't reuse passwords, because it increases the risk of leakage.</li>\n<li>AES has two parameters: the key and the initialisation v...
{ "AcceptedAnswerId": "6531", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T05:40:27.063", "Id": "6496", "Score": "4", "Tags": [ "c#", "security", "sql-injection", "ms-access" ], "Title": "Adding entries to an MS Access file using OleDB" }
6496
<p>I'm working on some image processing code that can generate pixel values outside of the normal range of 0 to 255, and I'd like to clamp them back into the valid range. I know that there are saturating SIMD instructions that make this a moot point, but I'm trying to stay within standard C++ code for the moment.</p> ...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T06:26:26.273", "Id": "10103", "Score": "0", "body": "Does it have to be signed?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T06:27:38.347", "Id": "10104", "Score": "7", "body": "why AND...
[ { "body": "<p>Here's my attempt:</p>\n\n<pre><code>unsigned char clamp(int n){\n int a = 255;\n a -= n;\n a &gt;&gt;= 31;\n a |= n;\n n &gt;&gt;= 31;\n n = ~n;\n n &amp;= a;\n return n;\n}\n</code></pre>\n\n<p>It compiles to 7 instructions - which is the same as your current version. So ...
{ "AcceptedAnswerId": "6504", "CommentCount": "22", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T06:18:53.883", "Id": "6502", "Score": "110", "Tags": [ "c++", "performance", "image", "bitwise", "assembly" ], "Title": "Fastest way to clamp an integer to the range 0-...
6502
<p>With regards to <a href="https://stackoverflow.com/q/801993/632951">Safe Publication</a>, consider this piece of code:</p> <pre><code>public class Test { public static void main(String args[]) { ThreadB t = new ThreadB(); t.start(); t.Grab(new Bag("HI")); } } class Bag { private...
[]
[ { "body": "<p><em>Chapter 3.5. Safe Publication</em> in <a href=\"http://jcip.net/\" rel=\"nofollow\">Java Concurrency in Practice</a> contains a very similar example. To cut a long story short: it's not thread safe. ThreadB could see its <code>bag</code> reference as <code>null</code>. Furthermore, ThreadB cou...
{ "AcceptedAnswerId": "6513", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T14:42:43.287", "Id": "6509", "Score": "4", "Tags": [ "java", "thread-safety" ], "Title": "Is this proper usage of \"safe publication\"?" }
6509
<p>Suppose a series of objects (presented here as tuples):</p> <pre> "a" | 1 "a" | 2 "b" | 3 "b" | 4 "a" | 5 </pre> <p>There is no built in function (that I know of) to group by the first columns's <em>sequence</em>, that is, all the "a"'s in a row, then the "b"'s, then the one "a" alone. So that the groups become: {...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T23:22:58.807", "Id": "10147", "Score": "1", "body": "\"Pre-anticipated\"? When would you ever anticipate anything except before it happens? ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-04T17:45:10....
[ { "body": "<p>For this, I would not use LINQ at all here. There unfortunately aren't any methods available to make this task easier. In fact, I would say trying to use what currently is available makes it more complicated and inefficient than it has to. As you can see by all the helper methods and whatnot yo...
{ "AcceptedAnswerId": "6625", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-03T18:59:36.533", "Id": "6512", "Score": "8", "Tags": [ "c#", "linq", "extension-methods" ], "Title": "Grouping by sequence in LINQ" }
6512
<p>I am using the following code to rename the uploaded files for any future name clashes. Please tell if my approach is right or I should follow some other approach or approach which is better. </p> <pre><code>[HttpPost] public ActionResult Upload(HttpPostedFileBase fileData) { if (fileData != null &a...
[]
[ { "body": "<p>If you have two simultaneous file uploads db.Pictures.Count(); will return same number. So you will get a name clash.</p>\n\n<p>If db.Pictures is a database then you can create and auto increment identity field and use it to save the file.</p>\n\n<p>If there is no option with database you can use ...
{ "AcceptedAnswerId": "6522", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-04T08:09:07.023", "Id": "6521", "Score": "2", "Tags": [ "c#", "asp.net-mvc-3" ], "Title": "Renaming file in C# on Server" }
6521
<p>I have following relationship schema:</p> <pre><code>class Participation belongs_to :toon belongs_to :person validates :role, :presence =&gt; true end class Toon has_many :participations has_many :people, :through =&gt; :participations end class Person has_many :participations has_many :toons, :thr...
[]
[ { "body": "<p>I would create a scope under 'Person' for this, that way you can chain it together with other Person scopes. something like this should work (may have slight syntax errors).</p>\n\n<pre><code>scope :for_toon_with_role, lambda { |toon, role| joins(:participations).where(:participations =&gt; {:rol...
{ "AcceptedAnswerId": "6704", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-04T10:29:56.140", "Id": "6523", "Score": "2", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Named scopes for instances" }
6523
<p>This is a CRC function generated by <a href="http://www.tty1.net/pycrc/index_en.html" rel="nofollow">pyCRC</a> and changed by me:</p> <blockquote> <pre><code>static inline crc_t crc_update(crc_t crc, char const * data, long long data_le...
[]
[ { "body": "<p>The obvious way is to replace the type that changes with a templated type, like this:</p>\n\n<pre><code>template&lt;typename T&gt;\nstatic inline crc_t crc_update(crc_t crc, \n T data, \n long long data_len)\n{\...
{ "AcceptedAnswerId": "6534", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-04T14:31:58.437", "Id": "6525", "Score": "6", "Tags": [ "c++" ], "Title": "CRC function duplication – differ only in pointer vs iterator signature" }
6525
<p>I'm trying to build a superfish dropdown menu from a sql query. Working example is can be seen from here check the "emlak bul" category: <a href="http://www.bedavaemlaksitesi.com/mersinemlakrehberi210/sayfalar/HABERLER" rel="nofollow">http://www.bedavaemlaksitesi.com/mersinemlakrehberi210/sayfalar/HABERLER</a> </p> ...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-05T14:15:54.753", "Id": "10192", "Score": "0", "body": "bunun kesinlikle daha basarili yapilabilecegi kesin :) presentasyon kismini oncelikle view e almani tavsiye ederim" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDat...
[ { "body": "<p>Yes, it can definitely be improved. Here are some things to think about:</p>\n\n<h2>Data</h2>\n\n<p>The data should match your problem. Make sure it is in a format that represents your menu. A menu can be handled well with recursive functions. These are an easy way to visit each element and bu...
{ "AcceptedAnswerId": "6549", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-04T16:43:51.993", "Id": "6528", "Score": "2", "Tags": [ "php", "mysql", "php5" ], "Title": "is there a better and short way to getting that array from joined sql query and converti...
6528
<p>I've just implement direction enum</p> <pre><code>object Direction extends Enumeration { type Direction = Value val Up, Right, Down, Left = Value val pairs = HashSet() ++ List((HashSet() ++ List(Up, Down)), (HashSet() ++ List(Right, Left))) def isOpposite(one: Direction, other: Direction): Boolean = { ...
[]
[ { "body": "<p>Use an Algebraic Data Type (ADT):</p>\n\n<pre><code>abstract class Direction(val opposite: Direction)\ncase object Up extends Direction(Down)\ncase object Down extends Direction(Up)\ncase object Left extends Direction(Right)\ncase object Right extends Direction(Left)\n</code></pre>\n\n<p>or:</p>\n...
{ "AcceptedAnswerId": "6530", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-04T18:03:50.553", "Id": "6529", "Score": "3", "Tags": [ "scala", "collections", "enum" ], "Title": "Scala Direction enum with Enumeration and collection usage" }
6529
<p>Now the program works, but is it correct? Sometimes it works in C anyway. Could I improve it somehow (not numerically, just C-wise)? I need to allocate the array as I do right? Since I am returning it and not just using it inside the function.</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #inclu...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-12-07T22:50:31.680", "Id": "209305", "Score": "0", "body": "You shouldn't use a floating point comparison in the `for` loop condition. Because of rounding errors, it's essentially random how often the loop body is executed. Instead, pass ...
[ { "body": "<p>Generally, it is preferrable to put the <code>\\n</code>s at the end of the corresponding printf instead of relying on them being present on the next one.</p>\n\n<pre><code>printf(\"\\n\"); // &lt;-- you don't need to complicate your whole logic just because of this guy!\n // put ...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-04T20:48:47.000", "Id": "6532", "Score": "2", "Tags": [ "c", "array" ], "Title": "RungeKutta method in C, pointers and arrays" }
6532
<p>I first saw this gigantic if and tried to refactor it. Could only end with a endless switch statement.</p> <p>Old code -</p> <pre><code> # It is a Cause if @causality == "C" @relationship.cause_id = @issueid @relationship.issue_id = @causality_id @notice = 'New cause linked Successfully' ...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-05T03:00:59.993", "Id": "10174", "Score": "0", "body": "It looks the same at a quick glance but its not the same. Notice that @r elationship.cause_id = @ issue.id\n @ relationship.issue_id = @ causality_id is not always of that form,...
[ { "body": "<p>Ok, I am the author of the question but I have no account on CR, this is the final refactoring :)</p>\n\n<pre><code>def set_type_of_relationship(already_exists)\n args = { \n C: [nil, 'a cause', 'cause'],\n I: [:I, 'a reducer', 'reducer issue'],\n P: [:H, 'a superset'...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-05T02:04:28.713", "Id": "6537", "Score": "8", "Tags": [ "ruby", "ruby-on-rails", "comparative-review", "controller" ], "Title": "Linking issues, classifying the relationship as a...
6537
<p>Could I improve this somehow (not numerically, just C-wise)? Do I need to allocate the array since I am returning it and not just using it inside the function?</p> <pre><code>#include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;math.h&gt; /* Approximates a solution to a differential equation on the for...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-04T20:36:15.713", "Id": "10176", "Score": "2", "body": "Is this a homework?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-04T20:38:11.783", "Id": "10177", "Score": "6", "body": "I can guarante...
[ { "body": "<p>It is more usual to take a pointer to an already-allocated array, rather than allocate an array within the function itself. This allows the calling function to choose the best kind of allocation.</p>\n\n<p>When doing this you'd likely also take the number of indexes to fill as an input, deriving ...
{ "AcceptedAnswerId": null, "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-04T20:35:28.097", "Id": "6540", "Score": "2", "Tags": [ "c", "beginner", "memory-management", "mathematics" ], "Title": "Runge-Kutta 2nd order of differential equations" }
6540
<p>I'm trying to build friendly URLs like <code>/post/1/my-first-post</code>. I started out with building my links like this: </p> <pre><code>@Html.ActionLink(Model.BlogPost.Title, "Index", "Post", new { id = Model.BlogPost.Id, title = Model.FriendlyUrl }, new { }) </code></pre> <p>which were processed by this...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-04T16:52:21.323", "Id": "58733", "Score": "0", "body": "This is what you are searching for: https://www.nuget.org/packages/LowercaseDashedRoute/ And read the one-line configuration here please: https://github.com/AtaS/lowercase-dashed-...
[ { "body": "<p>Personally I think you are over thinking it. Why not just create a string extension method called FriendlyString or PrepareForUrl and then use the original route </p>\n\n<pre><code>@Html.ActionLink(Model.BlogPost.Title, \"Index\", \"Post\", new\n{\n id = Model.BlogPost.Id,\n title = Model.Blog...
{ "AcceptedAnswerId": "6570", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-05T05:32:53.613", "Id": "6543", "Score": "11", "Tags": [ "c#", "asp.net-mvc-3", "url-routing" ], "Title": "Custom route for writing friendly URLs in ASP.NET MVC 3" }
6543
<p>I think the below code is difficult to understand. I also feel it abuses Java's ternary operator. </p> <pre><code>String name = ((this.getAllNamesAsDelimitedString().contains(incomingName) ? incomingName: (CollectionsUtils.isEmptyCollection(this.getEntityOperationMap()) ? ...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-06T18:18:37.610", "Id": "10220", "Score": "3", "body": "As an aside, not directly related to the ternary operator, `Map.get` will return `null` if the map is empty, so the `CollectionsUtils.isEmptyCollection` branch is entirely unneces...
[ { "body": "<p>In my opinion I would go for more of code clarity than using cryptic Ternary operations. In cases where ternary operator statements become difficult to grasp at first glance, an if..else would be ideal. And moreover I am not aware of any performance difference in the application by using ternary o...
{ "AcceptedAnswerId": "6546", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-05T06:02:50.667", "Id": "6544", "Score": "46", "Tags": [ "java" ], "Title": "Ternary operation in Java - isn't this abuse?" }
6544
<p>Constructive criticism is required for the 2 methods below. I'm trying to develop better OO skills.</p> <pre><code> // Set up scanner to allow for searching of modules public static String searchModule() { Scanner scan; System.out.print("Search module code: "); scan = new Scanner(System.in); Strin...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-05T13:22:12.513", "Id": "10190", "Score": "0", "body": "When designing OO stuff you have to consider what parts of the code you want to allow future extensions for and what parts you want to keep rigid (and simple). For example, will y...
[ { "body": "<ol>\n<li>Since you say you're wanting to improve your OO, why are the methods static?</li>\n<li>Unless the documentation says that's a safe way to use Scanner, best to assume that it might over-read into a cache and cause problems. Create one scanner around System.in and then re-use it.</li>\n<li>Gi...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-05T11:03:25.970", "Id": "6550", "Score": "4", "Tags": [ "java", "search" ], "Title": "Search module methods" }
6550
<p>I wish to ask if the code written below has any holes (probably it will be useful for someone else). This code checks, by IP and by <code>userid</code>, if more than 5 attempts within the last 5 minutes were made to login. Every attempt to log in is stored in the <code>history</code> table (MySQL).</p> <p>The <code...
[]
[ { "body": "<p>1, You should create those indexes. <a href=\"http://dev.mysql.com/doc/refman/5.0/en/explain.html\" rel=\"nofollow\"><code>Explain</code></a> shows whether your queries use indexes or not. If you don't have yet maybe you want a cron job which regularly deletes old records from the table. It improv...
{ "AcceptedAnswerId": "6564", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-05T22:18:27.160", "Id": "6561", "Score": "2", "Tags": [ "php", "mysql", "security", "captcha" ], "Title": "Detecting if a CAPTCHA is needed" }
6561
<p>I'm working on a Python script and I was searching for a method to redirect <code>stdout</code> and <code>stderr</code> of a subprocess to the logging module. The subprocess is created using the <code>subprocess.call()</code> method.</p> <p>The difficulty I faced is that with subprocess I can redirect <code>stdout<...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-09T21:36:36.423", "Id": "10402", "Score": "0", "body": "You should use `super()` to call superclass methods. So instead of `threading.Thread.__init__(self)`, write `super(LoggerWrapper, self).__init__()`." }, { "ContentLicense"...
[ { "body": "<p>Great idea. I was having the same problem and this helped me solve it. Your method for doing cleanup though is wrong (as you mentioned it might be). Basically, you need to close the write end of the pipes after passing them to the subprocess. That way when the child process exits and closes it...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-06T13:02:29.257", "Id": "6567", "Score": "62", "Tags": [ "python", "logging", "io", "child-process" ], "Title": "Redirecting subprocesses' output (stdout and stderr) to the loggi...
6567
<p>I had an idea of checking if Entry ID already exists in database. If it doesn't there is no point of removing non existing entry.</p> <p>So when user types then each time new character is added I am opening or closing connection to my database file. This is my concern.</p> <p>But what if there might be hundredths ...
[]
[ { "body": "<p>Setting up a connection to a database on every handle of the event is going to be <strong>really</strong> slow. You would be best running an initial call to the database that retrieves the Id's stored within it and caches the results inside your code. Then, when you perform your validation, just d...
{ "AcceptedAnswerId": "6569", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-06T14:52:51.350", "Id": "6568", "Score": "3", "Tags": [ "c#", "performance" ], "Title": "Could I have any performance issues if I do ID check while using TextChanged in textbox every t...
6568
<p>The general idea is is a progress bar that updates the totals and percentage continually.</p> <p>This just gets a bit choppy when I trigger a few of these independently on the same page. I'm doing a bit of math at every step, and wonder if there is a better way to accomplish this.</p> <pre><code>$bar.animate({widt...
[]
[ { "body": "<p>Whenever the above code gets rerun you're re-instantiating those functions. So the first thing I would recommend is to define the callbacks outside of the immediate scope of whatever's re-running it so they only get instantiated once.</p>\n\n<pre><code>// In a galaxy not so far away…\nvar animatio...
{ "AcceptedAnswerId": "6595", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-06T18:45:43.427", "Id": "6572", "Score": "3", "Tags": [ "javascript", "optimization", "jquery", "performance", "animation" ], "Title": "Updating progress bar animation" }
6572
<blockquote> <p><strong><em>There's a Follow-up:</strong> <a href="https://codereview.stackexchange.com/questions/6664/game-of-life-rewritten-into-two-classes-petridish-and-cell">Game Of Life rewritten into two classes, PetriDish and Cell</a></em></p> </blockquote> <p>I wrote an implementation of the <a href="http:/...
[]
[ { "body": "<p>I'd start it with a <code>Cell</code> and a <code>Grid</code> class and probably a two-dimensional <code>Cell</code> array field in the <code>Grid</code>. <code>Cell</code> provides type-safety and more readable code while probably contains only a <code>boolean</code> flag. </p>\n\n<p>Anyway, th...
{ "AcceptedAnswerId": "6575", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-06T19:51:50.717", "Id": "6573", "Score": "2", "Tags": [ "java", "game-of-life" ], "Title": "Game Of Life implemented with for-loops and a boolean-array" }
6573
<p>I'm after a collection of opinions regarding cohesion and coupling with my application to improve OO programming.</p> <p>Control Class - Populates test data and calls main menu</p> <pre><code>import java.util.HashSet; import java.util.Set; public class Control { public void run() { // Populate Test Data ...
[]
[ { "body": "<p>What if I need to process student/module registrations using a text file instead of asking interactively? I would decouple I/O from the controller logic (StudentManager, ModuleManager, etc). </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-06T21:02:52.117", "Id": "6576", "Score": "2", "Tags": [ "java", "object-oriented", "console", "database" ], "Title": "An object-oriented student record system" }
6576
<p>I am implementing a <a href="http://en.wikipedia.org/wiki/Gap_buffer" rel="nofollow">gap buffer</a> and am trying to write a test for the insert method, the test currently looks something like this:</p> <pre><code>gapBuffer.insert('a') assertEquals(gapBuffer.getText(), "a") gapBuffer.insert('c') assertEquals(gapBuf...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T04:48:30.213", "Id": "10235", "Score": "2", "body": "what makes you think that's a problem?" } ]
[ { "body": "<p>It's usually hard to test a setter without a getter and vice versa. <a href=\"http://xunitpatterns.com/Back%20Door%20Manipulation.html\" rel=\"nofollow\">Back Door Manipulation</a> in <em>xUnit Test Patterns</em> discuss this in detail.</p>\n\n<p>Some smells from the same book/site: </p>\n\n<ul>\n...
{ "AcceptedAnswerId": "6588", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-06T22:52:32.137", "Id": "6579", "Score": "0", "Tags": [ "java", "unit-testing" ], "Title": "Unit testing where you depend on implementation of another method" }
6579
<p>I have been working lately on an educational framework project to learn more about web development and problems that arise in more complex applications. Part of the framework's principles is to be as Object Oriented as possible. For example, most data returned from queries to a data source will be returned as a pa...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T00:59:27.080", "Id": "10230", "Score": "0", "body": "Injecting is generally the way to go, but another option is defaulting the object for ObjectTypeValidator." } ]
[ { "body": "<p>Why reinvent the wheel and not build upon the <a href=\"http://www.php.net/manual/en/class.traversable.php\" rel=\"nofollow\">Traversable</a>, <a href=\"http://www.php.net/manual/en/class.arrayaccess.php\" rel=\"nofollow\">ArrayAccess</a> and <a href=\"http://www.php.net/manual/en/class.serializab...
{ "AcceptedAnswerId": "6596", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-06T23:32:43.693", "Id": "6580", "Score": "5", "Tags": [ "php" ], "Title": "PHP data structure review and critique" }
6580
<pre><code>package calc; import com.sun.tools.corba.se.idl.constExpr.Equal; //imports .equals(variable) import java.util.Scanner; //imports scanners public class Calc { public static void main(String[] args) { boolean go = true; //sets up loop while(go) //creates loop to top ...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T08:19:43.090", "Id": "10239", "Score": "1", "body": "Can you please come up with meaningful titles?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T14:02:12.013", "Id": "10247", "Score": "1", ...
[ { "body": "<p>Little things.</p>\n\n<p>You don't need the, go, variable.</p>\n\n<pre><code>while(true) {\n if(\"no\".equals(startOver))\n {\n System.out.println(\"Bye\");\n break;\n }\n}\n</code></pre>\n\n<p>Also, you could use System.out.printf, to make you code a little easier to read.</p...
{ "AcceptedAnswerId": "6587", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T00:32:15.950", "Id": "6581", "Score": "3", "Tags": [ "java", "optimization", "calculator" ], "Title": "Java console calculator" }
6581
<p>In my project, I am doing asynchronous processes in almost every classes. To explain my problem, I have created a sample:</p> <pre><code>public interface TestListener { void onResponse(Response result); void onError(Exception e); } public class AsyncTask { TestListener testListener; public AsyncTask(TestL...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T07:55:21.527", "Id": "10238", "Score": "0", "body": "Is the functionality of Test1.onResponse the same as Test2.onResponse?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T10:31:54.107", "Id": "10...
[ { "body": "<p>Naming the classes and the design (at least as far as I can see from the code you pasted) suggests that you want to use the <strong>observer pattern</strong>. The main idea of this pattern is to use listeners which implement common listener interface and register them for the specific object which...
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T07:06:06.480", "Id": "6585", "Score": "6", "Tags": [ "java", "design-patterns", "asynchronous" ], "Title": "Listener pattern implementation" }
6585
<p>So I'm doing things the BDD way, writing features first, then moving on to writing specs to add more detail to the mix as I move down the layers.</p> <p>One thing that bothered me, but isn't a big problem, is that when I got to the controller part of the stack, I have calls to the User and Todo model in my controll...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-17T02:26:28.937", "Id": "10831", "Score": "0", "body": "FWIW: A number of people have moved away from speccing controller actions to covering them with Cucumber stories. Like:" } ]
[ { "body": "<p>You <strong>SHOULD</strong> not stub anything you have no control of, since the later changes of the stuff out of control will make your tests brittle, while you can stub in this case, since you have fully control of the models</p>\n", "comments": [ { "ContentLicense": "CC BY-SA ...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T11:52:20.887", "Id": "6590", "Score": "2", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "How can I improve the isolation for this controller spec?" }
6590
<p>This checks each row for a category. It stores ONE version of the category, ignore duplications. It then counts how many times a category appears.</p> <p>There are a lot of <code>for</code> loops and a lot of table-checking. This takes time as the table is quite large. If it's possible, I would like to incorporate ...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T21:21:26.470", "Id": "10292", "Score": "0", "body": "You can always user recursion to remove for-loops. Also, while loops or do-while loops will suffice too." } ]
[ { "body": "<p>You can reduce some parts like:</p>\n\n<pre><code> for (int j = 0; j &lt; dgv.RowCount; j++)\n {\n // look at every category in the dgv and see if \n // we have a unique value in a container\n List&lt;string&gt; result = categories.FindAll(\n ...
{ "AcceptedAnswerId": "6594", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T12:21:30.733", "Id": "6592", "Score": "4", "Tags": [ "c#" ], "Title": "Searching for categories and storing them" }
6592
<p>I've modified John Resig <a href="http://ejohn.org/blog/simple-javascript-inheritance/" rel="nofollow">simple javascript inheritance framework</a>, by adding set function with setter functionality. It seems that it works. Is it written correctly? Can you see some undesired behavior? Framework:</p> <pre class="lang-...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-09T06:12:55.093", "Id": "10335", "Score": "0", "body": "Code like that is an anti pattern. It should be avoided by removing it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T11:01:36.533", "Id": "1...
[ { "body": "<p>Easy question first : <em>Is it written correctly?</em></p>\n\n<pre><code>Class.prototype.set = function(attrs) {\n for (var attr in attrs) {\n //if exist setter function this.on_change{key of wrap: function(key of wrap, new value)\n if(this.on_change[attr])this.on_change[attr].call(this,at...
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T00:27:25.983", "Id": "6598", "Score": "3", "Tags": [ "javascript" ], "Title": "Modification of javascript inheritance framework" }
6598
<p>I'm starting working with R, and found some tutorials and exercises online.</p> <p>I want to divide one variable in two, bigger and equal 79 and smaller 79.</p> <p>Perhaps because I'm used to python, my first approach was to do something like this:</p> <pre><code>z &lt;- numeric(length(faithful$waiting)) n = 0 fo...
[]
[ { "body": "<p>As you realize, your first approach works (it gives a result consistent with the criteria you specify), but it is not idiomatic R. Iterating over elements of a set/list/vector is idiomatic of python, and does have a place in R as well. However, what this approach misses is 2 aspects of R: inherent...
{ "AcceptedAnswerId": "6612", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T12:17:26.677", "Id": "6599", "Score": "4", "Tags": [ "r" ], "Title": "What is the best approach to use in R and why?" }
6599
<p>I've recently helped fellow SOFer to answer his question here: <a href="https://stackoverflow.com/a/8408106/1803692">Routing in my PHP MVC framework</a></p> <p>Then I thought </p> <blockquote> <p>Hey, why not improve this code and put in my snippets library.</p> </blockquote> <p>This is what I came up with:</p>...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T16:26:47.550", "Id": "10253", "Score": "0", "body": "Our rules require the relevant code to be contained inside the question, not on a third-party pastebin. So please edit the code into your question." }, { "ContentLicense":...
[ { "body": "<p>1, I'd remove the <code>$return</code> variable at all and change</p>\n\n<pre><code>...\n $return = $data;\n break;\n}\nreturn $return;\n</code></pre>\n\n<p>to</p>\n\n<pre><code>...\n return $data;\n}\n\nreturn FALSE;\n</code></pre>\n\n<p>2, Using the same variable name twice is hard to r...
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T16:21:06.203", "Id": "6601", "Score": "3", "Tags": [ "php", "url-routing" ], "Title": "REGEXless dispatcher" }
6601
<p>I have some static helper class:</p> <pre><code>public static class Helper { public static bool IsNull&lt;T&gt;(this T value) where T : class { return (value == null); } public static bool NotNull&lt;T&gt;(this T value) where T : class { return (!value.IsNull&lt;T&gt;()); } ...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T14:27:13.157", "Id": "10254", "Score": "0", "body": "Isn't `IsNullOrEmpty` just replacing the same exact extension?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T14:28:15.763", "Id": "10255", ...
[ { "body": "<p>This gets to be a sticky point. There are those who will argue <em>fervently</em> that an extension method should <em>never</em> work on a <code>null</code> reference, and there are those who are fine with that.</p>\n\n<p>Personally, I don't mind extension methods on <code>null</code> <em>if</em>...
{ "AcceptedAnswerId": "6603", "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T14:20:39.920", "Id": "6602", "Score": "9", "Tags": [ "c#", ".net", "extension-methods" ], "Title": "Helper class for Null and Empty checks" }
6602
<p>No one in my team knows how to write BDD tests, so I started writing some and it's quite working well. I think the time has come to improve the code quality.</p> <p>This contains a lot of duplicated code and unused features:</p> <pre><code>&lt;?php require_once ('core/v3/engine.php'); require_once 'PHPUnit/Extensi...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-22T07:32:09.850", "Id": "193741", "Score": "0", "body": "Why you don't use [behat](http://behat.org/) with gherkins syntax? It's a PHP lib which is similar to Cucumber in Ruby on Rails." } ]
[ { "body": "<p>Your switch statements will run through until they find a break statement. Having the braces {} only defines a block of code and has no effect on breaking out of the case.</p>\n\n<pre><code>switch (1)\n{\ncase 1: {\n echo 'One';\n}\ncase 2: {\n echo 'Two';\n}\ndefault: {\n echo 'Also defaul...
{ "AcceptedAnswerId": "6712", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T13:14:54.710", "Id": "6606", "Score": "3", "Tags": [ "php", "php5", "bdd", "phpunit" ], "Title": "BDD tests in PHPUnit" }
6606
<p>Okay so as I learn more about PHP and really strive to improve my code I have a few questions about a current setup of mine and how to approach it in the best way.</p> <p>I think I have all the tools necessary to get this done the right way, but I am having trouble putting them together. I am also trying to separat...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-06T22:35:00.413", "Id": "10286", "Score": "0", "body": "Bobby Tables strikes again. :) (fix that `$cabin`, imagine someone enters `'); DROP TABLE cabin_content; --`!)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": ...
[ { "body": "<p>I'm not 100% sure what you are asking.. &amp; personally i see nothing wrong with using multiple queries. But i think what you are looking for is <code>UNION</code></p>\n\n<pre><code>SELECT \n cc.cabin_name\n ,cc.peak_week\n ,cc.max_occupancy\n ,'Large' as ImageType\n ,ci.image \nFR...
{ "AcceptedAnswerId": "6610", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-06T22:12:44.607", "Id": "6607", "Score": "5", "Tags": [ "php", "sql" ], "Title": "A set of queries in PHP to show occupancy of various cabins" }
6607
<p>I am writing a file writer/reader in JavaScript; I want it to work on local files. It tries to use Firefox's XpConnect, falls back on IE activeX, falls back on Java LiveConnect, falls back on a Java class (not included here), falls back on HTML5 local filestorage. I also want to throw in there a GET driver, to commu...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-08T23:53:54.690", "Id": "10327", "Score": "0", "body": "Have you run your code through a linter such as [jshint.com](http://www.jshint.com/)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-29T04:35:57.190"...
[ { "body": "<p>First, I'll share some things I learned while <a href=\"https://github.com/TiddlyWiki/tiddlywiki/pull/94\" rel=\"nofollow noreferrer\">tweaking twFile</a>, a <a href=\"http://jquery.tiddlywiki.org/twFile.html\" rel=\"nofollow noreferrer\">local file system plug-in</a> for jQuery based on the <a hr...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-07T23:58:52.237", "Id": "6615", "Score": "5", "Tags": [ "javascript", "file", "io", "browser-storage" ], "Title": "File reader/writer using XPConnect, ActiveX, LiveConnect, Java,...
6615
<p>I've been trying to write a jQuery script where when someone clicks on the input the space clears and then if they don't type anything in, it reappears. </p> <p>This is what I came up with. Is there a better way to do this? If so why is it better?</p> <pre><code>$(document).ready(function() { // set al...
[]
[ { "body": "<p>It seems like you're trying to recreate the functionality of the <a href=\"https://developer.mozilla.org/en/HTML/Element/input#attr-placeholder\"><code>placeholder</code></a> attribute that exists in HTML5. For browsers that support it--and that's all modern browsers with the exception of IE9 (I t...
{ "AcceptedAnswerId": "6620", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-08T05:36:25.867", "Id": "6618", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "jQuery script to clear input fields" }
6618
<p>I need to use some flags in my code. To make it a bit clearer, I am looking to set the flags in some structure, and I need to match the following needs:</p> <ol> <li>The flag representation in the structureis hidden.</li> <li>The following methods are provided (or the same idea at least): <code>setFlag(structWithFl...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-09T02:17:38.210", "Id": "10331", "Score": "0", "body": "Is it ok to impose a constraint that the flag's integral value must be a power of 2?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-09T06:53:11.843",...
[ { "body": "<p>How many flags do you need? If you can settle with only 32 or 64 different flags instead of a generic-length array of flags, then it would probably be better to allocate the flags in a simple unsigned long, to save your program from all the runtime calculations.</p>\n\n<p>The main efficiency probl...
{ "AcceptedAnswerId": "6639", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-08T23:51:18.033", "Id": "6631", "Score": "5", "Tags": [ "c" ], "Title": "A better way to set flags" }
6631
<p>I was asked how this code has a security risk. Does anyone have any ideas what it is? I am new on the security topic and don't know what to look for.</p> <pre><code>String DBdriver = "com.ora.jdbc.Driver"; String DataURL = "jdbc:db://localhost:5112/users"; String loginName = "stackoverflow"; String passwd = "codeR...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-09T06:49:34.217", "Id": "10336", "Score": "12", "body": "I guess you're not acquainted with little [Bobby Tables](http://xkcd.com/327/)." } ]
[ { "body": "<p>Off the top of my head:</p>\n\n<ol>\n<li>Those parameters don't seem to be escaped before being stitched into a query (opening up SQL injection attacks)</li>\n<li>The database seems to be keeping passwords in plaintext rather than as salted hashes (which is an especially bad combo with the previou...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-09T02:46:01.580", "Id": "6632", "Score": "2", "Tags": [ "java", "security", "interview-questions" ], "Title": "What is the security issue in this code?" }
6632
<p>The problem is to find the longest words in a dictionary of legal words that can be constructed from a given list of letters.</p> <p>For example:</p> <blockquote> <pre><code>$ ./scrabble dictionary.txt i g h l p r a argil glair grail graph hilar laigh phial pilar ralph </code></pre> </blockquote> <p>More details ...
[]
[ { "body": "<p>You use too much of copying from one vector to another.\nUse filtering.</p>\n\n<p>Instead of</p>\n\n<pre><code>vector&lt;string&gt;::iterator it;\nfor (it = words.begin(); it &lt; words.end(); it++)\n</code></pre>\n\n<p>use </p>\n\n<pre><code>for (vector&lt;string&gt;::const_iterator it = words.be...
{ "AcceptedAnswerId": "6673", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-09T07:46:50.543", "Id": "6634", "Score": "4", "Tags": [ "c++", "algorithm", "c++11" ], "Title": "Longest words in dictionary that can be constructed from a list of letters" }
6634
<p>(this is a crosspost from StackOverflow, it was suggested I asked here)</p> <p><strong>Goal</strong></p> <p>I've got a DOM with about 70 elements on it (divs with some content) . I need to move and toggle the display of those divs quite a lot and also quite fast. The speed is one of the most important things. The ...
[]
[ { "body": "<ul>\n<li><p>First off...all this <code>cats =</code> and <code>return cats</code> confuses things, since you never actually replace <code>cats</code> -- the items inside are what you mess with. <code>cats = doSomethingWith(cats)</code> implies to me that <code>doSomethingWith(cats)</code> clones th...
{ "AcceptedAnswerId": "6674", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-09T12:10:49.193", "Id": "6638", "Score": "5", "Tags": [ "javascript", "algorithm", "jquery" ], "Title": "DOM-manipulation search-ordering algorithm" }
6638
<p>I have this code I used to to pull data from our IBM i into .NET into an object so it is easy to work with (avoiding DataTables).</p> <ol> <li>How can I make it better?</li> <li>How can I convert all/most of this into a generic reusable method?</li> </ol> <p>Here is an example of a method I have written:</p> <pre...
[]
[ { "body": "<p>You could receive a lambda that adds parameters.</p>\n\n<pre><code>public static DataTable GetData(string connString, string sqlStatement, Action&lt;iDB2ParameterCollection&gt; addParameters)\n{\n DataTable dt = new DataTable();\n\n using (iDB2Connection conn = new iDB2Connection(connString)...
{ "AcceptedAnswerId": "6641", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-09T14:32:21.903", "Id": "6640", "Score": "3", "Tags": [ "c#" ], "Title": "How can I convert this to a generic method?" }
6640
<p>I'm trying to work with some encryption/decryption of data. It was some hard work for me to get it working with some buffers and what not. </p> <p>This is the code I came up with:</p> <pre><code>public static string Encrypt(string dataToEncrypt, byte[] publicKeyInfo) { //// Our bytearray to hold all of our dat...
[]
[ { "body": "<p>You're using RSA as a block cipher in ECB mode. That's not how it's usually used. Unless you have a very good reason to do otherwise, you should just do one RSA encryption, of a secure random key for a block cipher (i.e. AES), and then use that key to encrypt your message.</p>\n\n<p>Since you're c...
{ "AcceptedAnswerId": "6676", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-09T18:42:40.740", "Id": "6662", "Score": "5", "Tags": [ "c#", "beginner", "strings", "cryptography" ], "Title": "Encryption/decryption of data" }
6662
<blockquote> <p><strong><em>Follow-up to:</strong> <a href="https://codereview.stackexchange.com/questions/6573/game-of-life-implemented-with-for-loops-and-a-boolean-array">Game Of Life implemented with for-loops and a boolean-array</a></em></p> </blockquote> <p>As proposed by <a href="https://codereview.stackexchan...
[]
[ { "body": "<ol>\n<li><p>Getter-setter methods in <code>PetriDish</code> and <code>Cell</code> should be declared after the constructors. (Check <a href=\"http://www.oracle.com/technetwork/java/codeconventions-141855.html#1852\" rel=\"nofollow noreferrer\">Java Coding Conventions, 3.1.3 Class and Interface Decla...
{ "AcceptedAnswerId": "6902", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-09T20:31:35.967", "Id": "6664", "Score": "3", "Tags": [ "java", "game-of-life" ], "Title": "Game Of Life rewritten into two classes, PetriDish and Cell" }
6664
<p>I wrote a Python MP3 player for Linux using PyGame, with a curses GUI and a mouse-only interface.</p> <p>It's purely for personal use. </p> <p>It hasn't been polished yet, but for now I'd like to know what I've done inefficiently so I can fill in some ignorance-holes. I know a few things could be handled more dir...
[]
[ { "body": "<pre><code>import curses\nimport pygame\n\npygame.mixer.init(frequency=22050, size=-16, channels=2, buffer=4096)\nplayer = pygame.mixer.music\n</code></pre>\n\n<p>When giving modules a shorter name, the usual method is <code>from pygame.mixer import music as player</code> It makes it a little clearer...
{ "AcceptedAnswerId": "6670", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-09T22:43:10.433", "Id": "6669", "Score": "4", "Tags": [ "python", "linux", "pygame", "audio", "curses" ], "Title": "MP3 player for Linux" }
6669
<blockquote> <p>Blackjack (twenty-one) is a casino game played with cards. The goal of the game to draw cards that total as close to 21 points as possible without going over. All face cards count as 10 points, aces count as 1 or 11, and all other cards count their numeric value.</p> <p>The game is played a...
[]
[ { "body": "<pre><code>def printIntro():\n print(\"This program simulates a bunch of blackjack games.\")\n</code></pre>\n\n<p>Python style guide recommend lowercase_with_underscores for function names</p>\n\n<pre><code>def getInputs():\n while True:\n n = eval(input(\"How many games should be simula...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T04:27:09.317", "Id": "6671", "Score": "2", "Tags": [ "python", "game", "playing-cards" ], "Title": "Blackjack casino game" }
6671
<p>I started working with R recently and need to do a simulation for 100 000 people that divides them in exposition factor for a disease, gender and presence or absence of disease. My background info is that the probability of being exposed to this risk factor is 0.15 in this population. The probability of being a wom...
[]
[ { "body": "<p>There are a few improvements to your (I'm assuming that <code>genero</code> and <code>gender</code> are the same variable).</p>\n\n<ol>\n<li>Very important. Use a space around the assignment operator! <code>x&lt;-5</code> Does this mean assign 5 to x to is <code>x</code> less than <code>-5</code><...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T10:41:42.100", "Id": "6675", "Score": "2", "Tags": [ "r", "simulation" ], "Title": "Is there a more efficient way to simulate in R, by exposition factor, gender and disease profile?" ...
6675
<p>I have an iOS app that support all orientations. I sometime notices performance issues when I rotate the device, and sometimes it crashes, badly. And it's not as smooth as other apps. This is my first app, so I'm not a pro. I have quite a lot of custom UI elements so most of my views is done programatically. The iss...
[]
[ { "body": "<p>First, there's just a couple of nit-picky things I'll comment on.</p>\n\n<hr>\n\n<p>First, I'm quite sure this is totally unnecessary:</p>\n\n<pre><code>- (BOOL)shouldAutorotateToInterfaceOrientation (UIInterfaceOrientation)interfaceOrientation {\n return YES;\n} \n</code></pre>\n\n<p>I belie...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T12:52:13.100", "Id": "6677", "Score": "5", "Tags": [ "optimization", "objective-c", "ios", "image" ], "Title": "Handling rotations in iOS painting app" }
6677
<p>Consider the following piece of code:</p> <pre><code>var result = List[Measurement]() val dbResult = conn.createStatement.executeQuery(unsentMeasurements) while(dbResult.next) { result ::= Measurement(dbResult.getString("stuff"), dbResult.getString("morestuff")) } result.reverse </code></pre> <p>Versus this:<...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-16T08:56:06.143", "Id": "10807", "Score": "0", "body": "The second example looks better to me. I can't try it out right now, but is there a possibility to use `Iterator` instead of `Stream`?" } ]
[ { "body": "<p>Of course this is not purely functional, although it represents an improvement. What would a purely functional solution look like?</p>\n\n<pre><code>trait Sql[A] { self =&gt;\n def unsafePerformIO(ds: javax.sql.DataSource): A = unsafePerformIO(ds.createConnection)\n\n def unsafePerformIO(conn: j...
{ "AcceptedAnswerId": "9242", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T13:26:36.650", "Id": "6678", "Score": "4", "Tags": [ "scala", "functional-programming" ], "Title": "Functionally retrieving rows from a database in Scala" }
6678
<p>Ext JS provides a complete object oriented framework for creating a desktop-like application that runs in a web browser. It manages object lifecycle, layouts, theming and a large library of UI widgets including charting.</p> <p>Originally built as an add-on library for YUI, it has a modular architecture that develo...
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T13:41:06.117", "Id": "6680", "Score": "0", "Tags": null, "Title": null }
6680
Ext JS is a JavaScript framework for building Rich Internet Applications (RIAs) that run in web browsers.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T13:41:06.117", "Id": "6681", "Score": "0", "Tags": null, "Title": null }
6681
<p>I wanted to do the following: </p> <ul> <li>Count the frequencies of words in a text (over 5 letters)</li> <li>Invert the map of words to frequencies, but group together words that have the same frequency in the inversion.</li> <li>Sort the inverted map by keys descending order and take the top 25.</li> </ul> <p>H...
[]
[ { "body": "<p>Well, the most obvious fix is indeed <code>map-invert-preserving-dups</code> - the whole thing could be more easily written as:</p>\n\n<pre><code>(defn map-invert-preserving-dups [m]\n (apply merge-with into\n (for [[k v] m]\n {v [k]})))\n</code></pre>\n\n<p>The <code>for</code>...
{ "AcceptedAnswerId": "6683", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T02:22:47.693", "Id": "6682", "Score": "2", "Tags": [ "regex", "clojure" ], "Title": "Clojure code adapted from map-invert" }
6682
<p>I personally want a small selector function that covers the three common cases</p> <ul> <li>getElementById</li> <li>getElementsByClassName</li> <li>getElementsByTagName</li> </ul> <p>It should support contexts and should not support <code>querySelectorAll</code> since <code>&lt;opinionated&gt;</code> QSA is slow a...
[]
[ { "body": "<p>Well , you have to keep in mind that not all browsers implement <code>getElementsByClassName</code>, not even all of ( what you would call ) \"proper browsers\".</p>\n\n<p>You should add a fallback for such a problem.</p>\n\n<p>That said, you probably could get rid of at least one <code>IF</code> ...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T16:09:34.140", "Id": "6687", "Score": "4", "Tags": [ "javascript", "optimization" ], "Title": "hand optimising javascript selector function" }
6687
<p>I was just playing around with N queen problems means accommodating N queens on N*N chees board such that no one can kill each other. I tried a simple algorithm which uses backtracking.The program is working fine till 29 queens but after 29 it is just going on and on..I am not able to decide is it due to some logic...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T08:52:13.820", "Id": "10438", "Score": "0", "body": "Why can't you tell what it's doing based on the logging you've added?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T09:09:50.010", "Id": "104...
[ { "body": "<p>I commented, but here's my observations of your code:</p>\n\n<p>It's more efficient to represent the board as an array of N ints, where B[i] is the location of the queen in the i'th column. This naturally excludes the case where there's two queens in the same column.</p>\n\n<p>Backtracking is ofte...
{ "AcceptedAnswerId": "6695", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T08:40:19.007", "Id": "6690", "Score": "5", "Tags": [ "c++", "algorithm" ], "Title": "N*N queen algorithm" }
6690
<p>I'm trying to get a better grasp on generators in Python because I don't use them enough (I think generators are cool). To do so I wrote a generator for prime numbers:</p> <pre><code>def primes(): x = 2 while True: for y in xrange(2, x/2 + 1): if x % y == 0: break ...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T20:05:39.030", "Id": "10450", "Score": "1", "body": "I can't come up with a proper answer at the moment but you should look into using memoization and a different algorithm here." } ]
[ { "body": "<p>Stylistically, using <code>itertools.count()</code> rather than implementing your own counter would be a bit cleaner.</p>\n\n<p>I also prefer using the <code>any()</code> over a generator rather than an explicit for loop with a break and else. I think it's easier to follow.</p>\n\n<p>Algorithmical...
{ "AcceptedAnswerId": "6698", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T19:35:08.033", "Id": "6696", "Score": "3", "Tags": [ "python", "performance", "primes", "generator" ], "Title": "Python prime number generator" }
6696
<p>I have run this program for five hours and it has not yet completed. I wonder if we can make changes to reduce the computation time.</p> <p>I use several for loop and this greatly increases the computation time. my goal is to compare the contents of the rows of a matrix (4435 × 2000) with 6 row vectors (1 × 2000). ...
[]
[ { "body": "<p>In Matlab, unlike C, you have to vectorize your code.\nA first step would be to understand how to use <code>find</code> like this:</p>\n\n<pre><code>i1=70:2000;\nj1=find(D1(B(v,1),i1)==L);\n</code></pre>\n\n<p>and:</p>\n\n<pre><code>if j1&gt;64 \n m_A1(i,j) = all( A(i,j-63:j)==A(...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T16:46:03.310", "Id": "6699", "Score": "0", "Tags": [ "matrix", "time-limit-exceeded", "matlab" ], "Title": "Comparing rows of a matrix with some row vectors" }
6699
<p>I am currently working on a Sudoku solver that should be able to solve a 25 x 25 grid. However, I am experiencing problems optimizing it to run quick enough to actually get a result with any grid bigger than 9 x 9. I was wondering if anyone could take a look at my code and give me some ideas on how to optimize it.</...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T02:48:12.660", "Id": "10454", "Score": "0", "body": "you don't need to use `this` unless your global variable name conflicts with a local one from a parameter. It just looks messy and doesn't do anything." }, { "ContentLicen...
[ { "body": "<p><code>isValidValue()</code> is needlessly simple – you check all 9 values for every field always. Instead, try implementing \"pencil marks\" that humans use when solving sudoku. For every field without a value, you should explicitly store which values can still be entered into this field. (In say ...
{ "AcceptedAnswerId": "6702", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T02:43:47.020", "Id": "6701", "Score": "4", "Tags": [ "java", "performance", "homework", "sudoku" ], "Title": "Sudoku Solver Optimization" }
6701
<p>This was actually asked in an interview. I have made it in the best possible way I could and would like to optimize it if there is any chance of doing it.</p> <p>The input is:</p> <pre><code>a(b(cd)e(fg)) </code></pre> <p>The output should be: </p> <pre><code> a ...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T22:25:57.063", "Id": "10466", "Score": "1", "body": "Optimize for what? With recursion your program will crash (stack overflow) if a very large tree is provided." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2...
[ { "body": "<pre><code>void tre(struct node * p) //function that I am using to convert the string to a tree\n{\n if(a[i]=='(')\n {\n</code></pre>\n\n<p>I recommend not using such short variable names</p>\n\n<pre><code> i++;\n struct node *temp=malloc(sizeof(struct node));\n ...
{ "AcceptedAnswerId": "6734", "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-10T22:16:05.533", "Id": "6705", "Score": "5", "Tags": [ "c" ], "Title": "Converting \"a(b(cd)e(fg))\" into a tree" }
6705
<p>I wrote this to pull one column of data from a csv file, divide each of the results in 2, and then format it as JSON so I can do stuff with it in a web app. It works, but it feels wonky and weird. Is there a better way to do this?</p> <pre><code>$fname = "subjects.csv"; $half = array(); $otherkeys = array(); $re...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T00:11:13.520", "Id": "10485", "Score": "0", "body": "It doesn't look like StackOverflow likes tabs in code. Interesting." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T00:44:02.700", "Id": "1048...
[ { "body": "<p>try using <a href=\"http://php.net/manual/en/function.json-encode.php\" rel=\"nofollow\">json_encode</a> instead. Just get the data you want into a php array as you are already doing.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T0...
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T00:04:22.407", "Id": "6707", "Score": "1", "Tags": [ "php", "json" ], "Title": "JSON for one column of a csv file?" }
6707
<p>I got my 1 dimensional program to work just fine so I figured I just need a few tweaks to get the 2D to work as well. It's not fully completed but it would helpful to know if I am on the right track or completely off base with where I am at.</p> <pre><code>import java.util.Scanner; import java.util.Random; public ...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T07:58:51.507", "Id": "10493", "Score": "1", "body": "If it isn't complete, it doesn't really belong here. However if you could maybe narrow your code to a specific section you'd like reviewed, then maybe we can help you." } ]
[ { "body": "<ul>\n<li>This solution is not very object oriented. That may be okay if you are a beginner, but if you know how to initialize objects, you should use that knowledge.</li>\n<li>Method names should be lowercase</li>\n<li>the Random object should be reused, make it a static member</li>\n<li>don't write...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T02:33:47.887", "Id": "6709", "Score": "3", "Tags": [ "java", "game", "minesweeper" ], "Title": "Text based 2D Minesweeper" }
6709
<p>The code reads from the screen, compares a pixel in a previously provided sample image and, if the pixels match, it records timeback seconds of video leading up to it. The output is put into a folder 'tm'. Since I do not assume the pixel to be occurring all the time, the writing process is buffered with a thread, so...
[]
[ { "body": "<pre><code>import PIL.ImageGrab\nimport PIL.Image\nimport time\nfrom collections import deque\nimport threading \nfrom numpy import *\n</code></pre>\n\n<p>Generally, <code>import *</code> is frowned upon because it makes it hard to figure out where things come frome</p>\n\n<pre><code>def get_pixel_co...
{ "AcceptedAnswerId": "6773", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T10:05:52.760", "Id": "6713", "Score": "0", "Tags": [ "python", "optimization", "image", "video" ], "Title": "Recording timeback seconds of video based on compared pixels fro...
6713
<p>I need to add a list of names and (optional) links to my ASP.net page.</p> <p>I learnt (hopefully) to use a GridView to do this, mostly working from the example given by this blog entry: <a href="http://geekswithblogs.net/dotNETvinz/archive/2010/08/03/adding-dynamic-rows-in-gridview-with-textbox-and-dropdownlist.as...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-08T09:38:40.520", "Id": "96294", "Score": "0", "body": "The KetticGridView is capable of [populating gridview with data using DataTable](http://www.kettic.com/winforms_ui/csharp_guide/gridview_populate_data_binding_datatable.shtml) to ...
[ { "body": "<p>Regarding having to get/set the value of the textboxes, you should get to know the <code>Bind</code> expression. For instance, you could have:</p>\n\n<pre><code>&lt;asp:TextBox ID=\"Name\" runat=\"server\" Text='&lt;%# Bind(\"Name\") %&gt;' /&gt; \n</code></pre>\n\n<p>For one of the \"right\" ways...
{ "AcceptedAnswerId": "6793", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T11:35:28.260", "Id": "6718", "Score": "2", "Tags": [ "c#", "asp.net" ], "Title": "Basic GridView backed with a DataTable" }
6718
<p>I'm trying to create an URL-router, where the website language is defined by the first two chars in the domain.</p> <p>Example:</p> <blockquote> <p>domain.com/en</p> </blockquote> <p>(the site will then display content in English).</p> <p>The script below is what I've come up with so far. Focus is on functiona...
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T13:29:11.887", "Id": "6719", "Score": "1", "Tags": [ "php", "optimization", "http", "url" ], "Title": "Optimizing URL router behaviour" }
6719
<p>I'm creating list of <code>Token</code>s from input <code>[Char]</code> stream using Parsec v3. The definition of <code>Token</code> looks like this:</p> <pre><code>data Token = CharKeyword | OpeningBracket | Identifier String | Natural Int </code></pre> <p>As result of calling <code>parse lexComb "" inputStream</...
[]
[ { "body": "<p>I've solved it by using <code>Text.ParserCombinators.Parsec.GeneralizedToken</code> from <a href=\"http://hackage.haskell.org/package/MissingH-1.1.1.0\" rel=\"nofollow\">MissingH</a> package:</p>\n\n<pre><code>psOpBracket = tokeng (\\x -&gt; case x of TokOpBracket -&gt; Just Nothing ; _ -&gt; Noth...
{ "AcceptedAnswerId": "6922", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T14:23:10.473", "Id": "6720", "Score": "6", "Tags": [ "haskell", "parsing", "parsec" ], "Title": "Using Parsec for lexing&parsing" }
6720
<p>I'm trying to implement simple data streamer in Python with sockets. Consider one server and one or more clients. I just want to read data from server, process it and send it to the client. Here's how I do it now:</p> <pre><code> outputsocket = socket.socket() outputsocket.bind((self.outputaddress, s...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-22T19:34:46.507", "Id": "11045", "Score": "1", "body": "You might want to put `inputsocket.close()` and `outputsocket.close()` in a `finally:` block, instead of in the exception block, as a general clean up measure." } ]
[ { "body": "<p>For the benefit of others (because this answer is two years late):</p>\n\n<p>I had to implement a socket solution rapidly to accommodate testing a feature that required them. Ended up using <a href=\"http://docs.python.org/3.3/library/socketserver.html\" rel=\"nofollow\">socketserver</a> to simpli...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T18:30:45.863", "Id": "6722", "Score": "4", "Tags": [ "python" ], "Title": "implementing simple stream processor with sockets" }
6722
<p>I have the following script and I think it's a bit inefficient. With a array from 1 to 3, this isn't a real problem, but this array can get way bigger. So how to boost it's performance/optimize this code?</p> <pre><code>&lt;?php $array = array(1, 2, 3); foreach ($array as $tabid) { echo '&lt;div id="tab'....
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T21:23:02.440", "Id": "10509", "Score": "0", "body": "I obviously have no idea how many columns TableContent has, but it's generally considered bad practice to select * in actual product code. It's more readable and (depending on how...
[ { "body": "<p>just skip the foreach and do it in 1 query, there are number of ways to do this for example by using IN\n<a href=\"http://www.techonthenet.com/sql/in.php\" rel=\"nofollow\">http://www.techonthenet.com/sql/in.php</a></p>\n\n<pre><code> $result = mysql_query(\"SELECT * FROM TabContent WHERE TabI...
{ "AcceptedAnswerId": "6725", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T19:02:36.387", "Id": "6724", "Score": "2", "Tags": [ "php", "optimization" ], "Title": "optimize my foreach" }
6724
<p>Is there a way to reduce the computation time in this program that eliminates the columns of a matrix A if for a given column the element of line 4 is equal to the element in row 5:</p> <pre><code>k=1; for i=1:4000 if A(4,i) ~= A(5,i) B(:,k)=A(:,i); k=k+1; end end </code></pre>
[]
[ { "body": "<p>In general, you speed up Matlab programs by computing whole vectors or matrices at once, rather than writing loops. In this case, you can generate a \"logical\" vector that contains <code>1</code> in each column where the corresponding column in A has different values in rows 4 and 5, and <code>0<...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T21:19:55.610", "Id": "6731", "Score": "1", "Tags": [ "performance", "matrix", "matlab" ], "Title": "Eliminating columns from a matrix where the entries in two rows are equal" }
6731
<p>I have to clean up some Javascript and I am trying to figure out a more elegant way to write this code below. It's basically looping through 3 dictionaries with the same loop structure and appending some custom HTML onto a specific <code>div</code>. I wanted to see if there is a way to avoid this repetitive code:</...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T22:02:57.680", "Id": "10513", "Score": "0", "body": "HTML String concatenation is evil." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T22:06:51.807", "Id": "10514", "Score": "0", "body": ...
[ { "body": "<p>The simplest refactor would be to simply pull out the common functionality, and pass in the array for each case, as well as a function used to create your div content from the current item in the loop. Assuming dtInt is global:</p>\n\n<pre><code>function checkDtInt(arr, funcToCreateDiv) { \n ...
{ "AcceptedAnswerId": null, "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-11T21:29:56.570", "Id": "6732", "Score": "5", "Tags": [ "javascript", "jquery", "dom" ], "Title": "Rendering three types of events as HTML elements" }
6732
<p>The situation is that its not always possible to play with the web.config or have access to IIS, that being said I had to come up with a way to catch all 404s in a .NET application, for aspx page extensions its fairly easily and the web is full of ideas... but for non aspx extensions I did the following, looking for...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-02T18:10:35.780", "Id": "10539", "Score": "0", "body": "Where is this code? Somewhere in `Global.asax`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-02T19:35:34.120", "Id": "10540", "Score": "0",...
[ { "body": "<p>An answer provided to me recently by GregB might be exactly what you need:</p>\n\n<p>What about using an HTTP Handler mapped to all requests? </p>\n\n<p>You'll need to add <a href=\"http://www.microsoft.com/technet/prodtechnol/windowsserver2003/library/iis/5c5ae5e0-f4f9-44b0-a743-f4c3a5ff68ec.mspx...
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-02T17:27:44.750", "Id": "6736", "Score": "7", "Tags": [ "c#", "asp.net" ], "Title": "Is this a good way to catch all 404s in .NET without playing with IIS configuration?" }
6736
<p>I have 2 questions about functions inside object literals. I have included the workarounds I've been using, but they seem hackish. Is there a better way to do this?</p> <pre><code>ns = { a: function (x, y) { return x+y; }, // Problem 1 // This does not work: Error: ns.b is not a function b: this.a, /...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T01:29:16.120", "Id": "10552", "Score": "2", "body": "Why was this moved to code review? It's a technical question about javascript scope and context with an extremely contrived example." }, { "ContentLicense": "CC BY-SA 3.0"...
[ { "body": "<h3>Problem 1</h3>\n\n<p>Just assign them one at a time, once the object already exists:</p>\n\n<pre><code>ns = {};\nns.a = function (x, y) { return x+y; };\nns.b = ns.a;\n</code></pre>\n\n<p>To answer specifically whether there's any other workaround if you're dead set on declaring these inside the ...
{ "AcceptedAnswerId": "6741", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T01:11:39.670", "Id": "6740", "Score": "3", "Tags": [ "javascript" ], "Title": "Functions in object literals" }
6740
<p>I need to limit method call to 80 times per second (for each <code>connectionId</code>).</p> <p>My initial version:</p> <pre><code>private const int MAX_TRANSACTIONS_PER_PERIOD = 80; private const int PERIOD_IN_MS = 1000; private Queue&lt;DateTime&gt;[] times = new Queue&lt;DateTime&gt;[10] { new Queue&lt;Date...
[]
[ { "body": "<p><code>StopWatch</code> is definitely better for timing stuff, but the semantics of the two versions are different. With <code>DateTime</code> you have this:</p>\n\n<pre><code>private int ExecTransWithStats(int connection_id, string name, string parameters_string, byte[] bytes)\n{\n DateTime now...
{ "AcceptedAnswerId": "41536", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T09:12:50.637", "Id": "6750", "Score": "5", "Tags": [ "c#", "datetime", "timer" ], "Title": "qos method call using DateTime and Stopwatch" }
6750
<p>Here is the implementation I ended up with. Please post your feedback!</p> <pre><code>#include &lt;cstdio&gt; #include &lt;cstdlib&gt; #include &lt;iostream&gt; inline void swap(int * const a, const int i, const int j) { const int tmp = a[i]; a[i] = a[j]; a[j] = tmp; } void printArray(int *a, int le...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T17:01:13.190", "Id": "10607", "Score": "4", "body": "It may be tagged C++ but this looks more like C code. You need to learn to utilize the standard library more." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "...
[ { "body": "<pre><code>#include &lt;cstdio&gt;\n#include &lt;cstdlib&gt;\n\n#include &lt;iostream&gt;\n</code></pre>\n\n<p>If you're writing C++ prefer <code>cout</code> and <code>cin</code> provided by iostream. They provide much better type-safety compared to their C counterparts. OTOH, you can still use <code...
{ "AcceptedAnswerId": "6762", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T09:31:19.773", "Id": "6751", "Score": "8", "Tags": [ "c++", "sorting", "quick-sort" ], "Title": "Quicksort in C++" }
6751
<p>Is there any possibility of refactoring this code?</p> <p>In class A:</p> <pre><code>public List&lt;Item&gt; GetItems() { var result = new List&lt;Item&gt;(); foreach(var item in repo.GetItems1()) { var x = repo.GetOtherItems1(item.Id, "param1", param2); // this part is different if (x.Value &gt; 5) ...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T11:04:27.360", "Id": "10576", "Score": "0", "body": "Is it the same repository type you are work with in both classes? Otherwise it doesn't make much sense to try and re-work." } ]
[ { "body": "<p>Create a class that holds your parameters and instead of passing individual parameters, pass in the class object. something like:</p>\n\n<pre><code>class MyClass\n{\n\n public MyClass(){}\n\n public int ItemId { get; set;} \n public string ItemParam1 {get; set;}\n ....\n}\n</code></pre...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T10:18:13.843", "Id": "6752", "Score": "7", "Tags": [ "c#" ], "Title": "Getting list items" }
6752
<p>I have a database-intensive app, almost every activity requires access to the database, both reading and writing.<br> I had a lot of problems with separate threads and activities on the stack closing connections to the database when the current activity was using it, even if I opened and closed the database immediat...
[]
[ { "body": "<p>I'm not familiar with Android, so just some generic Java notes:</p>\n\n<ol>\n<li><p><code>PrDatabaseAdapter</code> should be <code>prDatabaseAdapter</code> (with lowercase first letter). See <em>Effective Java, 2nd edition, Item 56: Adhere to generally accepted naming conventions</em> and <a href=...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T11:19:54.793", "Id": "6756", "Score": "6", "Tags": [ "java", "sql", "android", "sqlite" ], "Title": "Database interaction logic" }
6756
<p>I was trying to solve <a href="https://gist.github.com/1466664" rel="nofollow">this problem</a>. I thought of any possible relation between the number of matches among subsequent substrings, but could not find one. So, the probably naive solution that I drafted was:</p> <pre><code>#include &lt;iostream&gt; #includ...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2012-01-20T03:11:09.827", "Id": "109583", "Score": "0", "body": "Actually for this problem you could use simpler algorithm related to string pattern matching. There is an excellent video by Dan Gasfield [Linear-time pattern matching. Z-values ...
[ { "body": "<p>I think what you need is a suffix tree: <a href=\"http://en.wikipedia.org/wiki/Suffix_tree\">http://en.wikipedia.org/wiki/Suffix_tree</a>. I don't really remember much about it, except that it exists and seems relevant to the problem at hand.</p>\n\n<p>Style wise, I recommend spaces around operato...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T11:21:55.927", "Id": "6757", "Score": "7", "Tags": [ "c++", "optimization", "strings", "programming-challenge", "time-limit-exceeded" ], "Title": "Optimizing string match ...
6757
<p>I have a series of string manipulation, I realize this with the following code. I want it to be more elegant and readable such as <code>str.sub_heading().sub_codeblock()...</code>, how could I rewrite my code?</p> <pre><code>def sub_heading(str) str.gsub!(/^(#+)\w+/) {|m| m.gsub("#", "=")} str.gsub!(/^(=+)(.+)...
[]
[ { "body": "<p>You may collect the replacements in a Hash and call them on after the other.</p>\n\n<pre><code>replacements = { \n /1/ =&gt; ' one ',\n /2/ =&gt; ' two ',\n /([34])/ =&gt; ' (\\1 is three or four) ',\n}\n\ntest = '123'\nreplacements.each{|regex, repl|\n test.gsub!(regex, repl)\n}\np test\n</co...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T13:05:26.553", "Id": "6759", "Score": "2", "Tags": [ "ruby", "strings" ], "Title": "Simplify series of string manipulations in Ruby" }
6759
<p>and can I make it more efficient? It's to test the collision between a ray and a sphere.</p> <pre><code>float BoundingSphere::Intersects(Ray ray) { D3DXVECTOR3 direction = ray.Direction(); D3DXVECTOR3 vec = D3DXVECTOR3(); D3DXVECTOR3 cToO = ray.Origin() - centre; float rSquared = radius * radius; float vSquared = 0...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T17:12:00.830", "Id": "10608", "Score": "3", "body": "Did you test it? Any uni tests?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T17:49:40.753", "Id": "10609", "Score": "0", "body": "it...
[ { "body": "<p>Since there's no answer yet, I'll take a crack at it.</p>\n\n<p>My first impression is that the nesting is somewhat deep and some of the variables could be moved closer to its site of usage. Here's one possible refactor:</p>\n\n<pre><code>float BoundingSphere::Intersects(Ray ray)\n{\n D3DXVECTO...
{ "AcceptedAnswerId": "6986", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T15:29:25.597", "Id": "6764", "Score": "0", "Tags": [ "c++", "collision" ], "Title": "Does this intersection algorithm work like it's supposed to?" }
6764
<p>I have the following script to reveal sections on a page if certain text in an is clicked. How do I collapse all other sections if any one of them is selected and make it scalable for 20 items?</p> <p>The following solution looks like it needs refactoring, and also when clicking <code>icn_1</code>, for instance, a...
[]
[ { "body": "<p>First, you have multiple functions with the same name. <strong>That's not valid.</strong></p>\n\n<p>Assuming these sections are divs, to hide all of them except one, take a look at the <code>not</code> function:</p>\n\n<pre><code>function reveal1() { \n $(\"div\").not(\"#section1\").hide(\"slo...
{ "AcceptedAnswerId": "6770", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T06:15:16.550", "Id": "6766", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Show and hide elements in JQuery" }
6766
<p>I am doing a refresher on algorithms.<br> I tried to solve the problem of determining if you have 2 trees (T1 and T2), one is a subtree of the other. </p> <p>I came up with the following: </p> <pre><code>public boolean isSubtree(Node n1, Node n2){ if(n2 == null) //Empty Subtree is accepted return tr...
[]
[ { "body": "<p>The variable names n1 and n2 are poor choices. I mean, you even had to clarify what they meant in your questions. How about just picking names which indicate what they are for.</p>\n\n<p>Rather then assigning to result and returning that, just have two return statements.</p>\n\n<p>If you reverse t...
{ "AcceptedAnswerId": "6842", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T17:38:24.953", "Id": "6774", "Score": "8", "Tags": [ "java", "algorithm" ], "Title": "Check if a binary tree is a subtree of another tree" }
6774
<p>In a current project I needed to enable/disable autorotation of the UI to specific UIView's. I looked around and did not find a working solution that fitted my case and returning NO in</p> <pre><code>shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation </code></pre> <p>method did not...
[]
[ { "body": "<p>First of all you could skip storing the current view controller in a variable. And instead of checking for the correct class you could delegate your <code>shouldAutorotateToInterfaceOrientation:</code> to the current visible one in the navigation controller.</p>\n\n<pre><code>- (BOOL) shouldAutoro...
{ "AcceptedAnswerId": "8546", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T18:27:46.487", "Id": "6776", "Score": "1", "Tags": [ "objective-c", "ios" ], "Title": "Selective autorotation in a UINavigationController" }
6776
<p>I am still getting the hang of Exception Handling in PHP; Here is the scenario where I am using the convention: There are times where I have a SQL query that I need to turn into an object, so I wrote this utility class/method. </p> <pre><code>Class A { public static function getThatOneInstance(){ $sql =...
[]
[ { "body": "<p>Its kinda odd. </p>\n\n<p>I'd suggest having a second function that throws exceptions when the row is not returned. </p>\n\n<p>I'd also strongly recommend you stop using variables like $O and $r, they make your code much harder to read.</p>\n", "comments": [ { "ContentLicense": "...
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T19:06:49.660", "Id": "6778", "Score": "2", "Tags": [ "php", "exception-handling" ], "Title": "Is it acceptable to pass an Exception into a function that then may or may not throw it?"...
6778
<p>For my homework assignment I have to create a class which converts an <code>integer</code> between 0 and 9999 into the written form. For example, 713 would be written as "seven hundred thirteen."</p> <p>I wrote a few variations and I think I found the best approach. However, I was wondering if anyone had a moment t...
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-14T17:08:29.707", "Id": "10708", "Score": "0", "body": "The algorithm is close to what I recall from my library for programming contests, thus I don't think there is a better algorithm for english. However, see Omnifarious' answer for ...
[ { "body": "<p>I can't comment (not enough rep I guess), but one minor thing I noticed is that if the input number is evenly divisible by 100 or 1000, it will have a space at the end of the printed string. Example: 2000 -> \"two thousand \"</p>\n\n<p>If that is even an issue, you can either:</p>\n\n<ul>\n<li>tri...
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-12T21:17:17.037", "Id": "6780", "Score": "7", "Tags": [ "c++", "homework", "converting" ], "Title": "Converting an integer into the written form" }
6780
<pre><code>function dashesToParentheses(str) { var list = str.split('-'); return str.replace(/-/g, '(') + repeatString(')', list.length - 1); } function repeatString(str, times) { if (times == 1) return str; return new Array(times + 1).join(str); } dashesToParentheses('a-b-c') // "a(b(c))" da...
[]
[ { "body": "<p>Well, you could remove the RegExp. But whether that helps\nperformance is anyone's guess.</p>\n\n<pre><code>var d2p = function(s){\n var one=[], two=[], a=s.split('-');\n one.push(a.shift());\n a.forEach(function(part){\n one.push('(' + part);\n two.push(')');\n });\n ...
{ "AcceptedAnswerId": "6792", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2011-12-13T10:16:20.497", "Id": "6790", "Score": "7", "Tags": [ "javascript", "strings", "regex" ], "Title": "String manipulations: transform \"a-b-c\" into \"a(b(c))\"" }
6790