body
stringlengths
25
86.7k
comments
list
answers
list
meta_data
dict
question_id
stringlengths
1
6
<p>I'm using the repository pattern with a context and ninject as the IOC. I have a service which handles getting and setting page properties in the database.</p> <pre><code>public class MyContext : DbContext { public MyContext() : base ("DefaultConnection") { } public DbSet&lt;PageProperty&gt; PageProperties { get; set; } public DbSet&lt;Contact&gt; Contacts { get; set; } } public class DefaultRepository : IRepository { MyContext _context; public DefaultRepository(MyContext context) { _context = context; } public IQueryable&lt;PageProperty&gt; PageProperties { get { return _context.PageProperties; } } public IQueryable&lt;Contact&gt; Contacts { get { return _context.Contacts; } } } public class ModuleLoader : NinjectModule { public ModuleLoader() { } public override void Load() { var context = new MyContext(); context.Database.Initialize(false); Bind&lt;MyContext&gt;().ToConstant(context).InSingletonScope(); Bind&lt;IRepository&gt;().To&lt;DefaultRepository&gt;(); Bind&lt;IPagePropertyProvider&gt;().To&lt;DefaultPagePropertyProvider&gt;().InSingletonScope(); } } public class DefaultPagePropertyProvider : IPagePropertyProvider { IRepository _repository; object _syncLock = new object(); public DefaultPagePropertyProvider (IRepository repository) { _repository = repository; } public string GetValue(string pageName, string propertyName { lock (_syncLock) { var prop = page.PageProperties.FirstOrDefault(x =&gt; x.Property.Equals(propertyName) &amp;&amp; x.PageName.Equals(pageName)).Value; return prop; } } public void SetValue(string pageName, string propertyName, string value) { var pageProp = _repository.PageProperties.FirstOrDefault(x =&gt; x.Property.Equals(propertyName) &amp;&amp; x.PageName.Equals(pageName)); pageProp.Value = value; _repository.SaveSingleEntity(pageProp); } } </code></pre> <p>In my view I am doing 3 ajax calls, one to get a list from contacts to fill out a table, one ajax call to determine how many pages i have depending on the page size I'm using, and one ajax call to set the page size that I want to use. so a select box changes the page size (How many contacts per page: [ 30]) , a table that displays the contacts (generated from jquery which decifers json), and finally a div containing a list of page numbers to click. The workflow is, call <code>GetContacts()</code>, this function then queries the <code>PageProperties</code> to find out the page size to use, then call <code>GetPages()</code>, this function also queries <code>PageProperties</code> to find out what page size to use, <code>SetPageSize()</code> which sets the page size. So <code>GetContacts()</code> and <code>GetPages()</code> is used when a page is selected from the div, <code>SetPageSize()</code> then <code>GetContacts()</code> and <code>GetPages()</code> is called when the select box change event is fired. <code>GetContacts()</code> and <code>GetPages()</code> is only called when the first <code>SetPageSize()</code> <code>$.ajax</code> request is <code>done()</code> and there is a <code>success</code> from that function.</p> <p>Now, before I added <code>lock(syncLock)</code> in the <code>DefaultPageProperty</code> service and before I added <code>InSingletonScope</code> to both that service and the context, I was getting two errors.</p> <blockquote> <p>The connection was not closed. The connection's current state is connecting.</p> <p>An EdmType cannot be mapped to CLR classes multiple times</p> </blockquote> <p>I assumed because the connection was in a <code>connecting</code> state, that the context was being reused and reused and reused, so I thought putting that to <code>SingletonScope()</code> would mean that only one connection was made, then I thought the same about <code>DefaultPageProperty</code> and then because I was making async calls to that service, I should put a lock over the database querying.</p> <p>It works, and the problems don't exist. But I don't know if what I have done is correct within the pattern I'm using, I'm wondering if I've missed something fundamental? My question is, is this a proper/viable solution which won't create any caveats later down the road? Have I actually solved the issue or just created more?</p>
[]
[ { "body": "<p>I don't think I completely know what is going on in your code.</p>\n\n<p>but there is one thing that I think you are doing wrong.</p>\n\n<p>you are creating a connection over the web and trying to force it to stay open.</p>\n\n<p>your web application should </p>\n\n<ol>\n<li>Connect</li>\n<li>Send or receive the information that it needs</li>\n<li>Disconnect</li>\n</ol>\n\n<p>you should never leave a connection open for extended periods of time.</p>\n\n<p>every time you need something from the server, <strong>open a new connection</strong>, when you are finished <strong>close</strong> the connection.</p>\n\n<p>I may be way out of line, but that struck me as off about the way you explained that part of your application</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T12:28:35.483", "Id": "54106", "Score": "0", "body": "Yeah, I took that into account, and started doing `InTransientScope()` that way it calls up a new connection each time, and it solved all my problems :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-04T14:11:12.510", "Id": "54113", "Score": "0", "body": "so you are closing the original connection and then opening a new connection everytime?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T12:56:43.913", "Id": "54242", "Score": "0", "body": "Yeah, because the underlying connection gets created on instantiation of the context class, everytime I call that class, `transient` re instantiates a new copy" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T14:25:29.013", "Id": "54263", "Score": "0", "body": "when that context class is done it should dispose the connection before another one is even thought about. it might be personal opinion, but I don't like that part of the design, when the object does something, it should open a connection, when it is done it should close that connection. when that object needs to do something (else/again) it should open a completely new connection and close it when it is finished." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-05T16:23:35.887", "Id": "54297", "Score": "0", "body": "I believe that when the class has been finished with, it does get disposed of properly, thus the connection gets terminated correctly" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-31T19:11:09.263", "Id": "33615", "ParentId": "30082", "Score": "3" } } ]
{ "AcceptedAnswerId": "33615", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-22T14:59:36.677", "Id": "30082", "Score": "3", "Tags": [ "c#", "asp.net", "asp.net-mvc-4", "dependency-injection" ], "Title": "Multiple Ajax Requests per MVC 4 View" }
30082
<p>I have written a working code that generates a simple linked list of dates and associated holidays. I realize that I have a problem with memory leaking as I copy lists repeatedly, so I wrote a freeList function. I am just having issues determining where to place this function. </p> <pre><code>//Creates a linked list of dates/holidays #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; typedef struct hashElem{ char* date; char* holiday; struct hashElem* next; }hashElem; // Initialize list with input value hashElem* createNode(char* input_date, char* input_holiday) { hashElem* ptr = malloc(sizeof(*ptr)); if (ptr == NULL) { perror("Error"); return NULL; } ptr -&gt; date = input_date; ptr -&gt; holiday = input_holiday; ptr -&gt; next = NULL; return ptr; } void freeList(hashElem* head) { hashElem* ptr = head; while (head != NULL) { ptr = ptr-&gt;next; free(head); head = ptr; } } hashElem* addToTail(hashElem* head, char* input_date, char* input_holiday) { hashElem* ptr = malloc(sizeof(*ptr)); hashElem* temp = head; // If there is not yet a list, initialize the list with the input value if (head == NULL) return createNode(input_date, input_holiday); if (ptr == NULL) return NULL; else { ptr-&gt;date = input_date; ptr-&gt;holiday = input_holiday; ptr-&gt;next = NULL; // Find the last element of the list while (temp-&gt;next != NULL) temp = temp-&gt;next; // Add new node to the end of the list temp-&gt;next = ptr; ptr = head; //free(head); return ptr; } } hashElem* holidayList(void) { hashElem* List = NULL; List = addToTail(List, "01/01/13", "New Years Day"); List = addToTail(List, "14/02/13", "Valentine's Day"); List = addToTail(List, "26/03/13", "Start of Passover"); List = addToTail(List, "16/06/13", "Father's Day"); List = addToTail(List, "31/10/13", "Halloween"); List = addToTail(List, "28/11/13", "Thanksgiving"); List = addToTail(List, "25/12/13", "Christmas"); return List; } void printList(hashElem* head) { hashElem* ptr = head; printf("------------------------------\n"); printf("PRINTING LINKED LIST\n"); while (ptr != NULL) { printf("Date: %s, Holiday: %s\n", ptr-&gt;date, ptr-&gt;holiday); ptr = ptr-&gt;next; } printf("------------------------------\n"); } </code></pre>
[]
[ { "body": "<p>In your current code, I can't see the copying of lists repeatedly as you stated. You are using pointers here so you're not actually duplicating the list.</p>\n\n<p>The freeList function should be called once you're done using your list (the one returned by <code>holidayList()</code>).</p>\n\n<p><em>Side Note:</em>\nYou can refactor the code by utilizing <code>createNode</code> function when creating nodes and adding it to the tail.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-22T15:53:47.013", "Id": "30088", "ParentId": "30087", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-22T15:40:44.767", "Id": "30087", "Score": "1", "Tags": [ "c", "memory-management", "linked-list" ], "Title": "Working C code dealing with lists: problem with memory leak" }
30087
<p>I made this function to teach myself about hash tables. Any ideas? I commented out <code>free(addition)</code> because it was giving me a compiler error, but I need to figure out how to deallocate the memory. </p> <pre><code>#define hashSize 1000 typedef struct hashElem{ char* date; char* holiday; }hashElem; typedef struct hash{ struct hashElem element; struct hash* next; }hash; hash* hashTable[hashSize]; // Hash function size_t murmurHash(const void *keyPtr, size_t keySize) { /* DESCRIPTION: Very fast string hashing algorithm with excelleng distribution and * collision resistance. This source code has been released into the public * domain. * * NOTES: http://murmurhash.googlepages.com * * RETURNS: Hashtable index for the key * */ /* 'm' and 'r' are mixing constants generated offline. */ /* They're not really 'magic', they just happen to work well. */ const unsigned int m = 0x5bd1e995; const int r = 24; size_t hashValue = 0; /* Mix 4 bytes at a time into the hash */ const unsigned char * data = (const unsigned char *)keyPtr; while(keySize &gt;= 4) { unsigned int k = *(unsigned int *) data; k *= m; k ^= k &gt;&gt; r; k *= m; hashValue *= m; hashValue ^= k; data += 4; keySize -= 4; } /* Handle the last few bytes of the input array */ switch(keySize) { case 3: hashValue ^= data[2] &lt;&lt; 16; case 2: hashValue ^= data[1] &lt;&lt; 8; case 1: hashValue ^= data[0]; hashValue *= m; }; /* Do a few final mixes of the hash to ensure the last few */ /* bytes are well-incorporated. */ hashValue ^= hashValue &gt;&gt; 13; hashValue *= m; hashValue ^= hashValue &gt;&gt; 15; return (hashValue % hashSize); } // strlen: return length of string int strlen(char *s) { char* p = s; while (*p != '\0') ++p; return p - s; } // Add Holiday into hash table void addHoliday(char* date, char* holiday) { char* key; int keyLen; size_t keyHash; hash* addition = malloc(sizeof(*addition)); key = date; addition-&gt;element.date = key; addition-&gt;element.holiday = holiday; // Add holiday to Hash Table if (hashTable[murmurHash(key, strlen(key))] == NULL) { addition-&gt;next = NULL; hashTable[murmurHash(key, strlen(key))] = addition; } else //If there is already an element at the index, add current holiday to beginning of list { addition-&gt;next = hashTable[murmurHash(key, strlen(key))]; hashTable[murmurHash(key, strlen(key))] = addition; } //free(addition); } // If a date is entered, retrieve holiday from hash function index char* getHoliday(char* date) { return(hashTable[murmurHash(date, strlen(date))]-&gt;element.holiday); } void main(void) { addHoliday("01/01/13", "New Years Day"); printf("%s\n", getHoliday("01/01/13")); getchar(); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T06:49:25.083", "Id": "47826", "Score": "1", "body": "Is the question how to deallocate memory?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T11:41:48.520", "Id": "47834", "Score": "0", "body": "the question is for an overall code review along with some comments about any area where memory is being leaked" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T11:47:33.073", "Id": "47905", "Score": "0", "body": "possible duplicate of [Working C code dealing with lists: problem with memory leak](http://codereview.stackexchange.com/questions/30087/working-c-code-dealing-with-lists-problem-with-memory-leak)" } ]
[ { "body": "<p>For one thing, this:</p>\n\n<pre><code> // Add holiday to Hash Table\n if (hashTable[murmurHash(key, strlen(key))] == NULL)\n { \n addition-&gt;next = NULL;\n hashTable[murmurHash(key, strlen(key))] = addition; \n }\n else //If there is already an element at the index, add current holiday to beginning of list\n {\n addition-&gt;next = hashTable[murmurHash(key, strlen(key))];\n hashTable[murmurHash(key, strlen(key))] = addition;\n }\n</code></pre>\n\n<p>can simply be this:</p>\n\n<pre><code> // Add holiday to Hash Table\n size_t idx = = murmurHash(key, strlen(key));\n addition-&gt;next = hashTable[idx];\n hashTable[idx] = addition;\n</code></pre>\n\n<p>Which cuts at least one invoke of the hash function, and in the process a similar number of <code>strlen</code> invokes. There is little sense is \"checking\" for a NULL in the hash table slot, because that is precisely what you want the <code>next</code> pointer of your new node to be anyway.</p>\n\n<p>Not entirely clear either is whether you intended on your keys being <strong>unique</strong>. Both code snippets above (yours and mine) do <em>not</em> enforce unique keys. It is worth a thought to determine whether that feature is needed or not.</p>\n\n<p>And (not really) finally, try and make a habit of creating hash functions that are <em>independent</em> of the hash table size. Though that may sound odd, it makes sense from the perspective of reuse. A hash function ideally returns a \"value\". That value is then massaged (usually via a modulo with the hash table size) to drive the final key into a slot within the table constraints. But that operation is <em>separate</em> from the hash function itself, which should be restricted only by the domain of the return type. In other words, this:</p>\n\n<pre><code>size_t murmurHash(const void *key, size_t len)\n</code></pre>\n\n<p>should simply return a value between 0 and the maximum value of a <code>size_t</code> on the platform. Period. No table size should be involved in the has function itself. Just chew on data and return some <code>size_t</code>. The <em>caller</em> of the function (the inserter, the lookup, etc), then takes this value and restricts it down to the table size (usually via a modulo of some kind). This makes the invocation look something like this:</p>\n\n<pre><code> // Add holiday to Hash Table\n size_t idx = = murmurHash(key, strlen(key)) % hashSize;\n addition-&gt;next = hashTable[idx];\n hashTable[idx] = addition;\n</code></pre>\n\n<p>Though it may seem a little odd at first, it makes your hash functions <em>more robust</em>. They are not restricted by some table size. The <em>user</em> of the hash function does that step; not the function itself. This is the approach used by the standard C++ library <code>std::hash&lt;&gt;</code> template, and it is a good design to emulate.</p>\n\n<p>Best of luck.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T15:51:37.850", "Id": "35927", "ParentId": "30096", "Score": "6" } }, { "body": "<p>I agree with WhozCraig; it is not necessary to run the hash multiple times. I would add that freeing the pointer (<code>addition</code>) would result in loss of the data you just added. Your array <code>hashTable</code> is an array of pointers - it doesn't include storage for the <code>hash</code> elements themselves. Thus, you can't free any <code>hash</code> elements until you remove them from the table or are done with the table itself.</p>\n\n<p>Tearing down the table will have to go something like this:</p>\n\n<pre><code>for (int i = 0 ; i &lt; hashSize ; i++) {\n hash* ptrToFree = hashTable[i];\n while (ptrToFree != NULL) {\n hash* next = ptrToFree-&gt;next;\n mfree(ptrToFree);\n ptrToFree = next;\n }\n}\n</code></pre>\n\n<p>If you don't like iterating over all of your pointers (it <em>looks</em> time-consuming, but you're probably on the way out of your process, right?) you can keep a static list of all elements, then iterate through that.</p>\n\n<pre><code>typedef struct _HashStorage {\n struct hash element;\n struct _HashStorage * more;\n} HashStorage;\n\nHashStorage* storage = NULL;\n\nhash* newHash() {\n HashStorage* oldTop = storage;\n storage = malloc(sizeof(HashStorage));\n storage-&gt;more = oldTop;\n return (hash*) storage;\n}\n\nvoid dispose() {\n HashStorage* iterator = storage;\n while (iterator != NULL) {\n HashStorage* more = iterator-&gt;more;\n mfree(iterator);\n iterator = more;\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-22T17:55:44.280", "Id": "35937", "ParentId": "30096", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-22T18:41:53.407", "Id": "30096", "Score": "5", "Tags": [ "c", "memory-management", "hash-map" ], "Title": "Hash Table: adding and finding functions" }
30096
<p>I made a small Vim distribution that uses vundle. I decided to make a small function that checks if the repository must be updated.</p> <pre><code>"""""""""""""""""""""""""""""""""""""""""""""""""" "Update the repository """""""""""""""""""""""""""""""""""""""""""""""""" "A function to update if necessary function! Get_update() "Get the current path and change the directory to update the good "repository let l:current_path = expand("&lt;sfile&gt;:p:h") let l:path = '~/.vim-mahewin-repository' exec 'cd' l:path let l:last_local_commit = system('git rev-parse HEAD') let l:last_remote_comit = system('git ls-remote origin -h refs/heads/master |cut -f1') if l:last_local_commit != l:last_remote_comit echo 'Need to be updated, launches updated' :!git pull `git remote` `git rev-parse --abbrev-ref HEAD` endif exec 'cd' l:current_path endfunction </code></pre> <p>It's not very nice, but I have not found out how to do it better. I'm open to advice.</p>
[]
[ { "body": "<p>Your function has the side-effect of switching the directory to the file's path. To be side-effect-free, you should <code>let l:current_path = getcwd()</code> instead. Better yet, use the <code>--git-dir</code> and <code>--work-tree</code> options to <a href=\"https://www.kernel.org/pub/software/scm/git/docs/\" rel=\"nofollow\"><code>git(1)</code></a> to avoid having to <code>cd</code> at all.</p>\n\n<p>You always query the remote named <code>origin</code>, but pull from `git remote`. That inconsistent looks like a bug.</p>\n\n<p>I don't see any reason to use <code>--abbrev-ref</code> when the result is not intended for human consumption. Just use the full commit id.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T09:45:54.610", "Id": "47831", "Score": "0", "body": "Hi, thank you for your reply, I will these changes actually for remote it was a bad idea." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T06:46:19.820", "Id": "30114", "ParentId": "30097", "Score": "4" } } ]
{ "AcceptedAnswerId": "30114", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-22T19:24:05.997", "Id": "30097", "Score": "2", "Tags": [ "shell", "git", "vimscript" ], "Title": "Checking if a git repository needs to be updated" }
30097
<p>The below code uses Promises/A+ (specifically <a href="https://github.com/tildeio/rsvp.js" rel="nofollow">rsvp.js</a>) to generate a token. It does so by either taking an existing token or downloading and parsing a token from a web page. Is it possible to chain this to LoadURIPromise more cleanly? Usually one can chain together promises without causing as much indentation drift.</p> <pre><code>new RSVP.Promise(function (resolve) { if (TokenData) { resolve(TokenData); } else { LoadURIPromise(TokenURL).then(function (xmlDoc) { TokenData = xmlDoc.evaluate( '/root/theToken', xmlDoc.documentElement, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null ).singleNodeValue.textContent; resolve(TokenData); }); } }).then(function (token) { //Use Token here } </code></pre>
[]
[ { "body": "<p>I'm not familiar with the RSVP.js library. <a href=\"http://jsfiddle.net/zkfur/\" rel=\"nofollow\">I use jQuery here</a>, but the overall concept should still be (or exactly) the same:</p>\n\n<pre><code>// You can pull out your config to an array and use apply to use them\nvar config = [\n '/root/theToken',\n xmlDoc.documentElement,\n null,\n XPathResult.FIRST_ORDERED_NODE_TYPE,\n null\n];\n\n// So basically, the idea is the same, but we just pulled out some stuff\n// - A ternary instead of an if statement\n// - Removed the config to an array, and use apply to use them\n$.Deferred(function (deferred) {\n TokenData ? deferred.resolve(TokenData) : LoadURIPromise(TokenURL).done(function(xmlDoc) {\n TokenData = xmlDoc.evaluate.apply(xmlDoc,config).singleNodeValue.textContent;\n deferred.resolve(TokenData);\n });\n}).done(function (token) {\n /*We got token*/\n})\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T15:03:54.347", "Id": "48071", "Score": "2", "body": "Honestly, I find this harder to read. I'm not a fan of using the ternary operator as a replacement for conditionals except in very simple cases. Also, this has different semantics; it does not set `TokenData`." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T14:11:38.187", "Id": "30134", "ParentId": "30102", "Score": "0" } }, { "body": "<p>I have never used RSVP, I am more familiar with <a href=\"https://github.com/kriskowal/q\" rel=\"nofollow noreferrer\">Q</a>, but I believe following should do what you need:</p>\n<pre><code>var evaluate = function (xmlDoc) {\n TokenData = xmlDoc.evaluate(\n '/root/theToken',\n xmlDoc.documentElement,\n null,\n XPathResult.FIRST_ORDERED_NODE_TYPE,\n null).singleNodeValue.textContent;\n return TokenData;\n}\n\nRSVP.resolve(TokenData || LoadURIPromise(TokenURL).then(evaluate))\n .then(function (token) {\n //Use Token here\n console.info(token);\n});\n</code></pre>\n<p>Here is working <a href=\"http://jsfiddle.net/tomalec/EsRkp/2/\" rel=\"nofollow noreferrer\">jsFiddle</a></p>\n<p>BTW, do you really need <code>TokenData</code> to be global?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T17:43:35.267", "Id": "48080", "Score": "0", "body": "`TokenData` is not global. The surrounding code looks something like `Foo = function() {var TokenData; var checks = function() {/*Code in my question*/}}`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T23:25:48.797", "Id": "48441", "Score": "0", "body": "I'm not sure you are you going to use `checks`, but maybe you can also change `TokenData` to promise for token data:\n`var TokenDataPromise = LoadURIPromise(TokenURL).then(evaluate);` and shorten all that code to one line (except evaluate function)." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T17:06:33.647", "Id": "30267", "ParentId": "30102", "Score": "2" } } ]
{ "AcceptedAnswerId": "30267", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-22T20:45:44.167", "Id": "30102", "Score": "1", "Tags": [ "javascript", "promise" ], "Title": "Can this promise be chained more cleanly?" }
30102
<p>It has been mentioned in the <a href="https://github.com/bbatsov/clojure-style-guide" rel="nofollow">Clojure Style guide</a> to avoid functions longer than 10 SLOC but mine has more than 10 (47 to be exact).</p> <p>The code is an <a href="https://github.com/psibi/clj-uclassify/blob/master/src/clj_uclassify/uclassify.clj#L166" rel="nofollow">web api implementation</a> and follows like this:</p> <pre><code>(defn classify "Sends a text to a classifier and returns a classification" [keys texts classifier &amp; user-name] {:pre [(check-keys? keys)]} (let [textbase64-tag (map #(make-xml-node :textBase64 {:id (str "Text" (str (index-of % texts)))} (String. (encode (.getBytes %)) )) texts) texts-tag (make-xml-node :texts {} textbase64-tag) user-attribute (if (&gt; (count user-name) 0) { :username (first user-name) }) classify-tag (if (= (count user-name) 0) (map #(make-xml-node :classify {:id (str "Classify" %) :classifierName classifier :textId (str "Text" %) }) (range (count texts))) (map #(make-xml-node :classify {:id (str "Classify" %) :classifierName classifier :textId (str "Text" %) :username (first user-name)}) (range (count texts)))) read-calls (make-xml-node :readCalls {:readApiKey (keys :read-key)} classify-tag) uclassify-response (raw-post-request (xml/emit-str (xml-append-elements uclassify (list texts-tag read-calls))))] (if (check-response (get-response uclassify-response)) (readable-list (list (x/xml-&gt; uclassify-response :readCalls :classify :classification (x/attr :textCoverage)) (map vector (x/xml-&gt; uclassify-response :readCalls :classify :classification :class (x/attr :className)) (x/xml-&gt; uclassify-response :readCalls :classify :classification :class (x/attr :p))))) false ;; Will never reach here ))) </code></pre> <p>The code initially builds all the associated xml tags within <code>let</code> and after building them sends a request to the server and then checks out the response to see if it succeeded.</p> <p>Why I didn't handle the response in a separate function is because that it won't be reused again. Is this a good practice, any suggestions ?</p>
[]
[ { "body": "<p>There's value in factoring the logic out into one or more new functions, even if those functions are only used in a single place, because it can make the code easier to understand and modify.</p>\n\n<p>In a situation like that (when the logic won't be used elsewhere) I often use <code>letfn</code>. The <code>letfn</code> could be either internal or external to the function itself but I see that as a purely stylistic decision.</p>\n\n<p><a href=\"http://clojuredocs.org/clojure_core/clojure.core/letfn\" rel=\"nofollow\">Here's</a> the ClojureDocs page on <code>letfn</code>. See <a href=\"http://pedestal.io/\" rel=\"nofollow\">Pedestal's</a> <a href=\"https://github.com/pedestal/pedestal/blob/master/app/src/io/pedestal/app/dataflow.clj\" rel=\"nofollow\">dataflow logic</a> for a few examples of <code>letfn</code> in use.</p>\n\n<p>On the other hand, there's really no problem with having a top level function that's only used in one place. I like that <code>letfn</code> implicitly communicates the function's scope of relevance, but I don't think either way is objectively superior to the other.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T02:59:41.083", "Id": "47818", "Score": "0", "body": "While it used to be accepted style to extract functions only for reuse, I find myself more often than not doing so to break up logic. Every function you extract removes the need for a comment explaining what's going on when you use a descriptive function name. And you're more likely to update a function name when changing the logic as compared to a comment." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-22T23:23:10.473", "Id": "30108", "ParentId": "30106", "Score": "3" } } ]
{ "AcceptedAnswerId": "30108", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-22T22:34:31.360", "Id": "30106", "Score": "3", "Tags": [ "clojure" ], "Title": "Clojure function greater than 10 SLOC" }
30106
<p>The purpose of this script is to calculate the nonlinear reflection coefficient of a crystalline silicon slab.</p> <p>It takes some input files (columns of data separated by whitespace), converts that data to NumPy matrices, then operates on that data via some formulas that are coded into different functions. Finally, it spits out the final results to a file, as columns separated by whitespace.</p> <p>I inherited an old FORTRAN program that serves the same purpose. Even though it's completely illegible it is fast as a bat out of hell! It executes in ~0.020 seconds, while my script clocks in at around ~1.25 seconds.</p> <p>Please offer feedback for improving the general quality overall. I keep this code on GitHub so any and all feedback will be very helpful for me and others.</p> <pre><code>""" nrc.py is a python program designed to calculate the Nonlinear reflection coefficient for silicon surfaces. It works in conjunction with the matrix elements calculated using ABINIT, and open source ab initio software, and TINIBA, our in-house optical calculation software. The work codified in this software can be found in Phys.Rev.B66, 195329(2002). """ from math import sin, cos, radians from scipy import constants, interpolate from numpy import loadtxt, savetxt, column_stack, absolute, \ sqrt, linspace, ones, complex128 ########### user input ########### OUT = "data/nrc/" CHI1 = "data/res/chi1" ZZZ = "data/res/zzz" ZXX = "data/res/zxx" XXZ = "data/res/xxz" XXX = "data/res/xxx" # Angles THETA_RAD = radians(65) PHI_RAD = radians(30) # Misc ELEC_DENS = 1e-28 # electronic density and scaling factor (1e-7 * 1e-21) ENERGIES = linspace(0.01, 12.00, 1200) ########### functions ########### def nonlinear_reflection(): """ calls the different math functions and returns matrix, which is written to file """ onee = linspace(0.01, 12.00, 1200) twoe = 2 * onee polarization = [["p", "p"], ["p", "s"], ["s", "p"], ["s", "s"]] for state in polarization: nrc = rif_constants(onee) * absolute(fresnel_vs(state[1], twoe) * fresnel_sb(state[1], twoe) * ((fresnel_vs(state[0], onee) * fresnel_sb(state[0], onee)) ** 2) * reflection_components(state[0], state[1], onee, twoe)) ** 2 nrc = column_stack((onee, nrc)) out = OUT + "R" + state[0] + state[1] save_matrix(out, nrc) def chi_one(part, energy): """ creates spline from real part of chi1 matrix""" chi1 = load_matrix(CHI1) interpolated = \ interpolate.InterpolatedUnivariateSpline(ENERGIES, getattr(chi1, part)) return interpolated(energy) def epsilon(energy): """ combines splines for real and imaginary parts of chi1 """ chi1 = chi_one("real", energy) + 1j * chi_one("imag", energy) linear = 1 + (4 * constants.pi * chi1) return linear def wave_vector(energy): """ math for wave vectors """ k = sqrt(epsilon(energy) - (sin(THETA_RAD) ** 2)) return k def rif_constants(energy): """ math for constant term """ const = (32 * (constants.pi ** 3) * (energy ** 2)) / (ELEC_DENS * ((constants.c * 100) ** 3) * (cos(THETA_RAD) ** 2) * (constants.value("Planck constant over 2 pi in eV s") ** 2)) return const def electrostatic_units(energy): """ coefficient to convert to appropriate electrostatic units """ complex_esu = 1j * \ ((2 * constants.value("Rydberg constant times hc in eV")) ** 5) * \ ((0.53e-8 / (constants.value("lattice parameter of silicon") * 100)) ** 5) / ((2 * sqrt(3)) / ((2 * sqrt(2)) ** 2)) factor = (complex_esu * 2.08e-15 * (((constants.value("lattice parameter of silicon") * 100) / 1e-8) ** 3)) / (energy ** 3) return factor def fresnel_vs(polarization, energy): """ math for fresnel factors from vacuum to surface """ if polarization == "s": fresnel = (2 * cos(THETA_RAD)) / (cos(THETA_RAD) + wave_vector(energy)) elif polarization == "p": fresnel = (2 * cos(THETA_RAD)) / (epsilon(energy) * cos(THETA_RAD) + wave_vector(energy)) return fresnel def fresnel_sb(polarization, energy): """ math for fresnel factors from surface to bulk. Fresnel model """ if polarization == "s": fresnel = ones(1200, dtype=complex128) #fresnel = (2 * wave_vector(energy)) / (wave_vector(energy) # + wave_vector(energy)) elif polarization == "p": fresnel = 1 / epsilon(energy) #fresnel = (2 * wave_vector(energy)) / (epsilon(energy) * #wave_vector(energy) + epsilon(energy) * wave_vector(energy)) return fresnel def reflection_components(polar_in, polar_out, energy, twoenergy): """ math for different r factors. loads in different component matrices """ zzz = electrostatic_units(energy) * load_matrix(ZZZ) zxx = electrostatic_units(energy) * load_matrix(ZXX) xxz = electrostatic_units(energy) * load_matrix(XXZ) xxx = electrostatic_units(energy) * load_matrix(XXX) if polar_in == "p" and polar_out == "p": r_factor = sin(THETA_RAD) * epsilon(twoenergy) * \ (((sin(THETA_RAD) ** 2) * (epsilon(energy) ** 2) * zzz) + (wave_vector(energy) ** 2) * (epsilon(energy) ** 2) * zxx) \ + epsilon(energy) * epsilon(twoenergy) * \ wave_vector(energy) * wave_vector(twoenergy) * \ (-2 * sin(THETA_RAD) * epsilon(energy) * xxz + wave_vector(energy) * epsilon(energy) * xxx * cos(3 * PHI_RAD)) elif polar_in == "s" and polar_out == "p": r_factor = sin(THETA_RAD) * epsilon(twoenergy) * zxx - \ wave_vector(twoenergy) * epsilon(twoenergy) * \ xxx * cos(3 * PHI_RAD) elif polar_in == "p" and polar_out == "s": r_factor = -(wave_vector(energy) ** 2) * (epsilon(energy) ** 2) * \ xxx * sin(3 * PHI_RAD) elif polar_in == "s" and polar_out == "s": r_factor = xxx * sin(3 * PHI_RAD) return r_factor def load_matrix(in_file): """ loads files into matrices and extracts columns """ real, imaginary = loadtxt(in_file, unpack=True, usecols=[1, 2]) data = real + 1j * imaginary return data def save_matrix(out_file, data): """ saves matrix to file """ savetxt(out_file, data, fmt=('%5.14e'), delimiter='\t') nonlinear_reflection() </code></pre> <p>Running a script with just the import statements takes ~0.2 seconds, so that accounts for a little time.</p> <p>Here's some test data. All data is of the exact same format.</p> <blockquote> <pre><code>.1100 .38602E-04 -.11343E-02 .1200 .55456E-04 -.40092E-03 .1300 .51653E-04 -.81893E-03 .1400 .66445E-04 -.19650E-03 .1500 .52905E-04 -.15417E-02 .1600 .62693E-04 -.11310E-02 .1700 .69121E-04 -.10427E-02 .1800 .55286E-04 -.25198E-02 .1900 .70385E-04 -.16457E-02 .2000 .74872E-04 -.17719E-02 .2100 .83163E-04 -.15324E-02 .2200 .97154E-04 -.89845E-03 .2300 .85164E-04 -.18913E-02 .2400 .94601E-04 -.18361E-02 .2500 .97245E-04 -.19024E-02 .2600 .10928E-03 -.13463E-02 .2700 .11207E-03 -.16597E-02 .2800 .10805E-03 -.22026E-02 .2900 .11929E-03 -.17817E-02 .3000 .12704E-03 -.16619E-02 .3100 .11721E-03 -.26010E-02 </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T07:12:31.710", "Id": "47827", "Score": "3", "body": "It would be good to (1) [profile](http://docs.python.org/2/library/profile.html) the code, (2) time a Python script that is only `import numpy, scipy` (maybe that already takes 1.2 s?), and (3) provide test data." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T14:50:49.183", "Id": "47925", "Score": "0", "body": "Janne, thanks for the notes. I ran some sample code with just the preamble in it and it ran in ~0.2 seconds. Adding test data and looking into profiles. Thanks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T01:18:48.980", "Id": "48213", "Score": "0", "body": "There's no obvious iterations that would take up a lot of time. The iteration over polarizations is small. I'd suggest pulling the `load_matrix` calls out, so you load each data file only once. I'd also use `numpy.cos` etc (instead of `math`) but I don't think that is chewing up time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T23:55:48.107", "Id": "48749", "Score": "0", "body": "If you need some code to run really fast, just don't write it in python. There are languages that are both more readable than fortran and faster than python." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-21T20:50:05.747", "Id": "123031", "Score": "1", "body": "0.53e-8 == 5.3e-9" } ]
[ { "body": "<p>Avoid computing the same thing more than once. For example:</p>\n\n<ul>\n<li>Define global constants such as <code>SIN_THETA_RAD_SQUARED = sin(THETA_RAD) ** 2</code></li>\n<li>Load the data files just once into global constants, or into local variables in <code>nonlinear_reflection</code> and pass them to <code>reflection_components</code> as parameters.</li>\n<li>Assign <code>epsilon(energy)</code> to a local variable in <code>reflection_components</code> and use that in the lengthy expression.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-26T10:10:09.670", "Id": "36121", "ParentId": "30109", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T01:50:04.690", "Id": "30109", "Score": "5", "Tags": [ "python", "numpy", "mathematics" ], "Title": "Calculating the nonlinear reflection coefficient of a crystalline silicon slab" }
30109
<p>I am building my first real php web app. as many you know this requires building LOTS of pages.</p> <p>in attempting to streamline the repetitive stuff i placed most of my stuff within a content.php page which looks like this</p> <pre><code>?php include_once ('config3.inc');?&gt; &lt;?php if(isset($_GET['p'])){ $page = $_GET['p']; }else { $page =''; } ?&gt; &lt;!DOCTYPE html&gt; &lt;html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en"&gt; &lt;head&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;meta http-equiv="Content-Type" content="text/html; charset=utf-8" /&gt; &lt;title&gt;&lt;?php echo $_SERVER['PHP_SELF'];?&gt;&lt;/title&gt; &lt;?php include('styles.inc');?&gt; &lt;?php include('api.inc'); ?&gt; &lt;?php include('scripts.inc');?&gt; &lt;/head&gt; &lt;body&gt; &lt;div id="container"&gt; &lt;?php include ('header.inc');?&gt; &lt;div&gt;&lt;!-- Content --&gt; &lt;?php include ('./content/'.$page);?&gt; &lt;/div&gt; &lt;/div&gt;&lt;!-- end container --&gt; &lt;!-- Footer --&gt; &lt;?php include ('footer.inc');?&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>This way when I want to call up a page I go to <code>www.domain.com/content.php?p=pagename.php</code> and it will "wrap" everything in the correct style sheets container and footer etc.</p> <p>had been working well until I started making my CRUD pages requiring that pagename use <code>POST</code> data.</p> <p>Is there a better approach for this or do I need to scrap this approach entirely?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T12:58:03.017", "Id": "47841", "Score": "0", "body": "Why is this off-topic? this is working code..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T16:28:21.643", "Id": "47870", "Score": "1", "body": "I don't work with php at all, but doing an include a php page received in a parameter look not safe at all to me." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T18:22:28.257", "Id": "48083", "Score": "0", "body": "Marc-Andre I agree it would be unwise to include a file based solely upon a parameter my structure is passing it to a subfolder within my structure to prevent external includes. however i am taking a look at using some existing frameworks moving forward on this project." } ]
[ { "body": "<p>Well a more elegant approach would be to use an MVC pattern as a starter framework I would suggest you to use <a href=\"http://laravel.com/\" rel=\"nofollow\">Laravel</a> it's very clear written and also an easy catch for people who are general new to MVC. The way your currently writing the code, you include to much business logic inside of it. </p>\n\n<p>Which in the long term is terrible because the code becomes un-maintainable, for that the MVC Pattern is the best way to write clear and maintainable code, but check it out yourself. An good article to start with should be this one by Nettuts, called <a href=\"http://net.tutsplus.com/tutorials/other/mvc-for-noobs/\" rel=\"nofollow\">MVC for Noobs</a> don't get irritated by the name the article is pretty good and should get you a basic understanding of the MVC pattern.</p>\n\n<p>Hope I could be a little help :)</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T20:26:51.037", "Id": "47881", "Score": "0", "body": "Also look into TWIG. the template engine of symfony" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T13:48:20.930", "Id": "47913", "Score": "0", "body": "` because the code becomes maintainable ` I think you wanted to say not maintainable ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T18:24:26.950", "Id": "48084", "Score": "0", "body": "Thank you for your feedback, i will be looking into some frameworks." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T19:03:50.297", "Id": "30151", "ParentId": "30112", "Score": "2" } } ]
{ "AcceptedAnswerId": "30151", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T06:07:05.907", "Id": "30112", "Score": "2", "Tags": [ "php", "template" ], "Title": "Attempting to build template but Having Issue with gets and posts" }
30112
<p>After getting much improvement, it´s still one issue that concerns me. And that is the sync between my 2 threads.</p> <p>I use AutoResetEvent, but sadly, it has some delay with it, and would love to use something else if possible. Would be great if something could be connected to a Bool or the Queue i am using. Here is the Codes:</p> <pre><code> SharpDX.Windows.RenderLoop.Run(form, () =&gt; { if (Queue.TryDequeue(out TextureData)) { ........ } else { AutoReset.WaitOne(100); } }); </code></pre> <p>So there it does it´s thing, if there is something in a Queue, else it will wait on AutoReset Up till 100ms (this is to prevent the Form to totally freeze).</p> <pre><code>while (ReceiveCheck.Checked &amp;&amp; tt1.Connected) { ........... AutoReset.Set(); Queue.Enqueue(tempBytes); } </code></pre> <p>And there i simply do my work, and then tell the other thread to start, and right after i Queue my item. (why i AutoReset Before that is because of the delay, to help minimize it a bit).</p> <p>Is there a way to improve this? Would be great if the other thread could just wait until there is something in the Queue and then run.</p>
[]
[ { "body": "<ol>\n<li><p>When I tried to measure the delay of <code>AutoResetEvent</code>, I usually got less than 0.1 ms. That doesn't sounds like something you should worry about. If you're seeing larger delay, maybe it's caused by something else. It could be processing the message queue, which is what <code>RenderLoop</code> does between calls to <code>Run()</code>.</p></li>\n<li><p>Calling <code>Set()</code> before you enqueue the item is wrong, because it has a race condition: the dequeuing thread could wake up and call <code>TryDequeue()</code> before you call <code>Enqueue()</code>.</p></li>\n<li><p>In fact, the whole way you're using <code>AutoResetEvent</code> is wrong. If two items are enqueued quickly, then only one of them will be dequeued. Actually, this could be what's causing the delay you see, because it means there could be an ever-growing number of items in the queue just waiting for no good reason.</p></li>\n<li><p>A better way to write your code would be to use <code>BlockingCollection&lt;T&gt;</code> instead of <code>ConcurrentQueue&lt;T&gt;</code> (which I assume you're using now) and <code>AutoResetEvent</code>.</p></li>\n<li><p>It might be more efficient to dequeue more than one item from the queue in each call to <code>Run()</code>, if they are available. But probably only a limited amount, to make sure the message queue is processed too.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T13:11:41.400", "Id": "47842", "Score": "1", "body": "I actually found the Answer myself, and it´s the 4th of yours suggestions. IT works perfectly, as it´s pretty much ConcurrentQueue with AutoResetEvent inbuilt. So accepted Answer:)!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T12:20:16.580", "Id": "30124", "ParentId": "30115", "Score": "2" } } ]
{ "AcceptedAnswerId": "30124", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T06:48:57.783", "Id": "30115", "Score": "1", "Tags": [ "c#", "multithreading" ], "Title": "Is this a good way to syncronize my Threads?" }
30115
<p>In C# I have the following two extension methods.</p> <pre><code> public static void WaitForMilliseconds(this IWebDriver driver, int milliseconds) { var timeout = new TimeSpan(0, 0, 0, 0, milliseconds); WaitForTimeout(driver, timeout); } public static void WaitForSeconds(this IWebDriver driver, int seconds) { var timeout = new TimeSpan(0, 0, 0, seconds); WaitForTimeout(driver, timeout); } private static void WaitForTimeout(IWebDriver driver, TimeSpan timeout) { try { new WebDriverWait(driver, timeout).Until(x =&gt; false); } catch (Exception){} } </code></pre> <p>But since the class is static, I can write a private extension method to make the syntax more readable like this.</p> <pre><code> public static void WaitForMilliseconds(this IWebDriver driver, int milliseconds) { var timeout = new TimeSpan(0, 0, 0, 0, milliseconds); driver.WaitForTimeout(timeout); } public static void WaitForSeconds(this IWebDriver driver, int seconds) { var timeout = new TimeSpan(0, 0, 0, seconds); driver.WaitForTimeout(timeout); } private static void WaitForTimeout(this IWebDriver driver, TimeSpan timeout) { try { new WebDriverWait(driver, timeout).Until(x =&gt; false); } catch (Exception){} } </code></pre> <p>Is there any inherently bad code smell about private extension methods? Which would is better to use? The only issue I see is that if the code is later refactored into a class the methods will have to be rewritten.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-20T23:03:05.167", "Id": "185638", "Score": "0", "body": "The desire to improve code is implied for all questions on this site. Question titles should reflect the purpose of the code, not how you wish to have it reworked. See [ask]." } ]
[ { "body": "<p>If it helps make your code more readable and easier to maintain, I see no problem with that at all. Personally, I start with private extension methods and usually wind up promoting them into my company's public libraries when they appear to have enough utility.</p>\n\n<p>So... go for it. Just make sure it's bulletproof (i.e. remove the <code>catch</code> that's hiding exceptions, or recover from any known exceptions that you know how to) in case someone else wants them public someday.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T12:22:43.070", "Id": "30125", "ParentId": "30118", "Score": "3" } }, { "body": "<p>In my opinion, extension methods are only a <em>(pretty nice)</em> syntactic sugar for a static helper method. Under the hood, the IL translates your extension method call to a call on the static method, so really it's just an other way to write methods. </p>\n\n<p>The extension method do not have a private access to the type they are extending either, so changing a static method into an extension one will not break any encapsulation.</p>\n\n<p>As for the private keyword, it is indeed the correct accessibility level since your method will not be used outside of your class.</p>\n\n<p>According to <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/bb383977.aspx\" rel=\"nofollow\">MSDN's Guidelines</a>, the major problem of extension methods is the following :</p>\n\n<blockquote>\n <p>When using an extension method to extend a type whose source code you cannot change, you run the risk that a change in the implementation of the type will cause your extension method to break.</p>\n</blockquote>\n\n<p>Also, if someday IWebDriver defines a new method called \"WaitForTimeout\", your extension method won't be called anymore... But the risk is really pretty low.\n<br><br>\nSo if you think readability is increased by using that extension method, use it - you won't violate any principles or break anything, see it as a nice syntactic sugar.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T14:28:48.860", "Id": "47856", "Score": "1", "body": "+1. Extension methods seem to be a shortcut to actually designing classes that conform to a specified inheritance hierarchy, and as such, should be used sparingly, and with some forethought about how you are going to manage the kinds of multiple inheritance problems or brittle structure problems they create." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T14:03:44.557", "Id": "30131", "ParentId": "30118", "Score": "6" } }, { "body": "<p>The smell here should not be whether it's private, but rather an extension method called in an extension method.</p>\n\n<p>You might not even need the first two methods to be extension methods. If a fluent syntax is what you're after, you might consider moving the wait methods to your <code>WebDriverWait</code> class and changing their return types to <code>WebDriverWait</code>.</p>\n\n<p>So you would be able to accomplish this:\n<code>new WebDriverWait(driver).SetTimeout(5).SetWaitSeconds(3).SetWaitMilliseconds(100).Wait(someCondition)</code>;</p>\n\n<p>You may also be able to simplify by making a method that takes in a <code>TimeSpan</code> or do everything in milliseconds so you don't have to make methods per unit.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-08-20T22:47:10.240", "Id": "101521", "ParentId": "30118", "Score": "0" } } ]
{ "AcceptedAnswerId": "30131", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T08:07:53.633", "Id": "30118", "Score": "6", "Tags": [ "c#", "extension-methods" ], "Title": "Are private extension methods a bad thing to use?" }
30118
<p>Suppose I have following elementary DTOs, each DTO corresponding to a database table:</p> <pre><code>class Event { String name } class Player { String name } </code></pre> <p>DAOs for elementary DTOs:</p> <pre><code>class PlayerDao { def insert(Player p) { //sql to insert local members } } class EventDao { def insert(Event e) { //sql to insert local members } } </code></pre> <p>Composite DTO related to other DTOs via foreign keys:</p> <pre><code>class Game { Event e Player p Date d } </code></pre> <p>Now there are two approaches to designing the DAO for game object:</p> <p><em>Have the caller hand over entire game object to GameDao and GameDao calls other DAOs to save the child objects.</em></p> <pre><code>class GameDao { def insert(Game g) { eventDao.insert(g.e) playerDao.insert(g.p) //sql to insert local members } } class Caller { def static main(String[] a) { def g = new Game() gameDao.insert(g) } } </code></pre> <p><em>Make GameDao save only local state of object and leave the responsibility of saving related objects to caller.</em></p> <pre><code>class GameDao { def insert(Game g) { //sql to insert local members } } class Caller { def static main(String[] a) { def g = new Game() eventDao.insert(g.e) playerDao.insert(g.p) gameDao.insert(g) } } </code></pre> <p>Use of an ORM is out of question.</p> <p>Which design is better and why?</p>
[]
[ { "body": "<p>I would go for the first one, because it exposes a much simpler API to the caller.</p>\n\n<p>The day you need to add anything to your design, if it's encapsulated this way, the caller doesn't need to change a thing and it's still going to work, because the <code>Game</code> <em>knows</em> how to build itself and doesn't put that burden onto the caller.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T18:39:57.780", "Id": "30889", "ParentId": "30123", "Score": "2" } }, { "body": "<p>I would use the first one. What you have there is very close to what is called a Repository in Domain Driven Design. In DDD language Game would be an aggregate root, and the GameDAO would be a repository. DDD is a pretty big subject, more than I can really discuss in a comment. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T19:17:40.300", "Id": "30890", "ParentId": "30123", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T12:19:21.327", "Id": "30123", "Score": "3", "Tags": [ "comparative-review", "groovy", "jdbc" ], "Title": "Designing DAOs that handle composite objects" }
30123
<p>This works fine but I feel it can be better optimized.</p> <pre><code>#!/usr/bin/env py s = "1:5.9,1.5:7,2:10,4:18,8:40" load_value = raw_input("Enter a load value\n") li = s.split(',') driver = None for index,item in enumerate(li): if load_value == li[index].split(':')[1]: driver = li[index].split(':')[0] print driver if not driver: print "Could not find driver value" </code></pre> <p>Output:</p> <blockquote> <pre class="lang-none prettyprint-override"><code>Enter a load value 5.9 1 </code></pre> </blockquote>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T13:19:44.577", "Id": "47845", "Score": "0", "body": "do not call `li[index].split(':')` twice. Call it once, store the result and than use [0] and [1] on it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T13:36:21.000", "Id": "47850", "Score": "0", "body": "Don't use \"#!/usr/bin/env py\"; the name of the executable should be \"python\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T16:11:48.190", "Id": "47865", "Score": "2", "body": "What is this code supposed to do?" } ]
[ { "body": "<p>Maybe you can use <code>dict</code> instead of <code>str</code> to store the driver-load values. If the driver is the key, you can search easily.</p>\n\n<pre><code>#!/usr/bin/env py\n\ns = {'5.9':'1', '7':'1.5', '10':'2', '18':'4', '40':'8'}\nload_value = raw_input(\"Enter a load value\\n\")\ndriver = s.get(load_value)\nif driver is None:\n print \"Could not find driver value\"\nelse:\n print driver\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T13:13:06.510", "Id": "47843", "Score": "0", "body": "I am getting this value as string . Could you provide little bit more input to convert string to dict into this format" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T13:27:24.737", "Id": "47846", "Score": "0", "body": "These two lines takes the s string and creates the dict from it. pairs = dict([pair.split(':') for pair in s.split(',')])\nnew_dict = dict((v,k) for k,v in pairs.iteritems())" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T13:06:31.910", "Id": "30127", "ParentId": "30126", "Score": "3" } }, { "body": "<p>I agree with Simon that store the data in a dictionary is a better way to structure the data. That being said, I do have some comments on the code you posted.</p>\n\n<ul>\n<li>You don't need to use <code>enumerate()</code>. You are using it to get the index of the current item and just using the index to access the item from the list. Since you aren't using index for anything else, you should just use a basic for loop.</li>\n</ul>\n\n<p>Ex:</p>\n\n<pre><code>for item in li:\n print li\n</code></pre>\n\n<ul>\n<li>You are also performing the <code>split()</code> operation twice instead of storing the result in a variable that can be accessed.</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T13:13:50.370", "Id": "30128", "ParentId": "30126", "Score": "1" } }, { "body": "<p>How about doing all splitting beforehand, and replacing <code>driver</code> with a simple bool:</p>\n\n<pre><code>s = \"1:5.9,1.5:7,2:10,4:18,8:40\"\nload_value = raw_input(\"Enter a load value\\n\")\nli = [v.split(':') for v in s.split(',')]\n\nfound = False\nfor index,item in enumerate(li):\n if load_value == li[index][1]:\n print li[index][0]\n found = True\nif not found:\n print \"Could not find driver value\"\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T16:17:12.727", "Id": "30142", "ParentId": "30126", "Score": "1" } }, { "body": "<p>Python is exception friendly. You can get cleaner code like this:</p>\n\n<pre><code>#!/usr/bin/python\n\ndrivers = {'5.9':'1', '7':'1.5', '10':'2', '18':'4', '40':8}\n\nload_value = raw_input(\"Enter a load value\\n\")\ntry:\n print drivers[load_value]\nexcept KeyError:\n print 'Could not find driver value'\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-02T15:05:59.340", "Id": "112319", "Score": "0", "body": "It could even be condensed down to `print drivers.get(raw_input(\"Enter a load value\\n\"), 'Could not find driver value')`" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T17:04:16.640", "Id": "30144", "ParentId": "30126", "Score": "2" } }, { "body": "<p>My suggestion is to convert to a proper inverted map (easier to find the elements you want and faster)</p>\n\n<pre><code>#!/usr/bin/env py \ndata = \"1:5.9,1.5:7,2:10,4:18,8:40\"\nload_value = raw_input(\"Enter a load value\\n\")\n\ndriver_map = dict((t.split(':')[1],t.split(':')[0]) for t in data.split(','))\n\ndriver = driver_map[load_value]\nif driver :\n print driver\nelse :\n print \"Could not find driver value\"\n</code></pre>\n\n<p>I considered that you can't change the format of your input (since no much information is provided regarding your code input/output)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-09-02T14:47:47.320", "Id": "61790", "ParentId": "30126", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T12:50:24.903", "Id": "30126", "Score": "2", "Tags": [ "python" ], "Title": "Searching a list of pairs of numbers" }
30126
<p>I have an application which polls a bunch of servers every few minutes. To do this, it spawns one thread per server to poll (15 servers) and writes back the data to an object:</p> <pre><code>import requests import threading import time servers = ['1.1.1.1', '1.1.1.2'] class CallThreads(threading.Thread): """ Auxiliary class used to provide arguments to threads """ def __init__(self, target, *args): self.target = target self.args = args threading.Thread.__init__(self) def run (self): self.target(*self.args) class ServerResults(object): def __init__(self): self.results_list = [] def add_server(some_argument): self.results_list.append(some_argument) def poll_server(server, results): response = requests.get(server, timeout=10) results.add_server(response.status_code); def process_results(results): # Do something with the results def main(): while True: results = ServerResults() for s in servers: t = CallThreads(poll_server, s, results) t.daemon = True t.start() time.sleep(300) process_results(results.results_list) if __name__ == '__main__': main() </code></pre> <p>This is my first non-trivial Python application, so I would appreciate any critique, comments, or suggestions. Thank you!</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T14:57:23.543", "Id": "47926", "Score": "0", "body": "Is the while statement supposed to be in the `process_results` function?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T06:57:18.980", "Id": "47978", "Score": "0", "body": "Thank you Aseem. No, the `while` statement is not in the `process_results()` function. I have added a `main()` function to clarify this." } ]
[ { "body": "<p><strike>The two classes seem useless to me.</p>\n\n<p><code>ServerResults</code> only contains a list, so just use a list.</strike> <em>Edit: see comment below.</em></p>\n\n<p>The <code>CallThreads</code> class is unnecessary, this:</p>\n\n<pre><code>t = CallThreads(poll_server, s, results)\n</code></pre>\n\n<p>can be written like that:</p>\n\n<pre><code>t = Thread(target=poll_server, args=(s, results))\n</code></pre>\n\n<p>Note that you could also use the <a href=\"http://docs.python.org/3/library/functools.html#functools.partial\" rel=\"nofollow\"><code>partial</code> function</a>:</p>\n\n<pre><code>t = Thread(target=partial(poll_server, s, results))\n</code></pre>\n\n<p>or a <code>lambda</code>:</p>\n\n<pre><code>t = Thread(target=lambda: poll_server(s, results))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T09:36:39.787", "Id": "48765", "Score": "0", "body": "Thank you. `ServerResults` is actually much more than a list, I just show a list in this example code for simplicity's sake. I am interested in this `partial` function, where is this documented? Googling for `python target=partial` turns up some blog posts but no real documentation. Thanks!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T09:45:21.927", "Id": "48766", "Score": "0", "body": "Oops, I was going to put a link to the documentation but forgot. It's in the standard library: [`functools.partial`](http://docs.python.org/3/library/functools.html#functools.partial). `target` is a keyword argument of `Thread()`, you simply had to search for `python partial`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T09:56:21.780", "Id": "48768", "Score": "0", "body": "Great, thanks. I had to add `from functools import partial`. I'm still playing with it, thank you." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T17:55:14.513", "Id": "48787", "Score": "0", "body": "The code which uses target=partial [is segfaulting](http://stackoverflow.com/questions/18577851/intermittent-segmentation-fault-have-coredump?noredirect=1#comment27336518_18577851), please see the [SO question](http://stackoverflow.com/questions/18577851/intermittent-segmentation-fault-have-coredump?noredirect=1#comment27336518_18577851)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T12:11:06.240", "Id": "48828", "Score": "0", "body": "Sorry, I don't know much about debugging segfaults. Have you tried [using gdb](http://wiki.python.org/moin/DebuggingWithGdb) ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-08T10:20:26.993", "Id": "49256", "Score": "0", "body": "Thanks. I think it is something else that is causing the segfaulting, possibly in the `requests` library." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-01T23:44:52.687", "Id": "30665", "ParentId": "30129", "Score": "2" } } ]
{ "AcceptedAnswerId": "30665", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T13:23:59.837", "Id": "30129", "Score": "3", "Tags": [ "python", "multithreading" ], "Title": "Polling multiple servers" }
30129
<p>I've made the following program that takes a list of email addresses from a table in MS Access and sends each a test email.</p> <pre><code>'Send email to mailing list Function SendNotificationEmail() 'Handle any errrors On Error GoTo ErrHandler: 'Create Outlook object Dim olApp As Outlook.Application 'Namespace Dim olNS As Outlook.NameSpace Dim olFolder As Outlook.MAPIFolder 'Create a reference to the email item you will use to send the email Dim olMailItem As Outlook.MailItem Set olApp = CreateObject("Outlook.Application") Set olNS = olApp.GetNamespace("MAPI") Set olFolder = olNS.GetDefaultFolder(olFolderInbox) Set olMailItem = olFolder.Items.Add("IPM.Note") 'Create the body of the message Dim strBodyText As String strBodyText = "Test Email - DELETE ME :D" 'Open record set on Dim dbC As DAO.Database Dim rcdSet As DAO.Recordset Dim fld As DAO.field 'Used to update the table Dim strSQL As String strSQL = "SELECT DISTINCT [Email Address] FROM tblMailingList" 'Connect to current database Set dbC = CurrentDb Set rcdSet = dbC.OpenRecordset(strSQL) 'Count the number of records Dim intNumRecords As Integer 'Move to the last record in order to count all the records rcdSet.MoveLast intNumRecords = rcdSet.RecordCount - 1 'Move back rcdSet.MoveFirst 'Get data back from field birth date Set fld = rcdSet.Fields("Email Address") 'Subject olMailItem.Subject = "Mailing List Test" 'Loop through the records For i = 0 To intNumRecords 'Recipient/s olMailItem.To = fld.Value 'Body of email olMailItem.Body = strBodyText 'Automatically send the email olMailItem.Send 'Reset email item otherwise it won't work Set olMailItem = olFolder.Items.Add("IPM.Note") 'Move to the next record rcdSet.MoveNext Next 'Close record set and connection rcdSet.Close 'Empty variables Set fld = Nothing Set rcdSet = Nothing Set dbC = Nothing 'Relase all the object variables Set olMailItem = Nothing Set olFolder = Nothing Set olNS = Nothing Set olApp = Nothing ErrHandler: 'If error occurs If Err.Number &lt;&gt; 0 Then MsgBox "Error Number: " + Err.Number + ": Description: " + Err.Description End If End Function </code></pre> <p>Is my approach above correct? I had to reset the <code>olMailItem</code> in the loop otherwise it would return a <code>Type Error</code>. Is there a better approach to sending multiple emails?</p>
[ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2021-03-29T19:23:27.160", "Id": "510382", "Score": "0", "body": "You ask if this is the right approach. Why not just use MS Words mail merge to email (assuming you have word and outlook)." } ]
[ { "body": "<pre><code>Set olMailItem = Nothing\nSet olFolder = Nothing\nSet olNS = Nothing\nSet olApp = Nothing\n</code></pre>\n<p>is unnecessary. VBA is garbage collected, there's no need for this, or any of the other <code>= Nothing</code>'s you have. <a href=\"https://docs.microsoft.com/en-us/archive/blogs/ericlippert/when-are-you-required-to-set-objects-to-nothing\" rel=\"nofollow noreferrer\">Here's</a> an article from one of the MS developers about this practice. It refers to VBScript, but VBA's garbage collection algorithm is similar, and probably substantially better than VBScript's.</p>\n<p>Around</p>\n<pre><code>'Open record set on\n Dim dbC As DAO.Database\n</code></pre>\n<p>You start a new level of indentation. Why? I thought when I first read this that it was a part of the loop below.</p>\n<p>Finally, you might want to think more about your error handling (although VB's error handling isn't very fun to work with). For example, if you get an exception on <code>olMailItem.Send</code>, you might not care -- you want the script to keep going and try to send the next email, in case that was a fluke. However, if something goes wrong on <code>Set rcdSet = dbC.OpenRecordset(strSQL)</code>, you probably want the script to quit entirely, since nothing afterwards is going to be useful if you don' have anything to work on.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-08-23T17:16:00.857", "Id": "30146", "ParentId": "30130", "Score": "3" } }, { "body": "<p>Yes, I'd say your approach looks fine. If you want to see how someone else would do it, I've rewritten the code below. The differences are just style preferences, but sometimes it's nice to see how other people write the same code.</p>\n\n<p>I put all my variables at the top. If your code is so long that you can't see your variables, you probably need to split into into two or more procedures. Next, I put constants for any values that won't change. I use all caps in constants so I can recognize them.</p>\n\n<p>Depending on how many emails you send, the approach of saving them all, then sending later may or may not work. I've never benchmarked it, but it seems faster to send all at once.</p>\n\n<pre><code>Sub SendNotificationEmail()\n\n Dim olApp As Outlook.Application\n Dim olNs As Outlook.NameSpace\n Dim olMailItem As Outlook.MailItem\n Dim rsEmails As DAO.Recordset\n\n Const sBODY As String = \"Test Email - Delete Me\"\n Const sSUBJ As String = \"Mailing List Test\"\n Const sSQL As String = \"SELECT DISTINCT [EmailAddress] FROM tblMailingList;\"\n\n Set olApp = Outlook.Application\n Set olNs = olApp.GetNamespace(\"MAPI\")\n Set rsEmails = CurrentDb.OpenRecordset(sSQL)\n\n 'Create them, but don't send yet\n Do Until rsEmails.EOF\n Set olMailItem = olApp.CreateItem(0)\n With olMailItem\n .To = rsEmails.Fields(\"EmailAddress\").Value\n .Subject = sSUBJ\n .Body = sBODY\n .Save\n End With\n rsEmails.MoveNext\n Loop\n\n 'Send all the emails\n For Each olMailItem In olNs.GetDefaultFolder(olFolderDrafts).Items\n olMailItem.Send\n Next olMailItem\n\nEnd Sub\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T17:58:58.333", "Id": "30148", "ParentId": "30130", "Score": "3" } } ]
{ "AcceptedAnswerId": "30146", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T13:45:32.440", "Id": "30130", "Score": "7", "Tags": [ "vba", "email", "ms-access" ], "Title": "Sending test emails to a list of email addresses" }
30130
<p>I move back and forth between Python and C++ and I often need a nice/quick way to output STL objects to the screen for debugging purposes. I'd like the output to match the output of a comparable Python object, thus I have different templates for vectors, sets, etc...</p> <p>Is this the best way to go about this?</p> <pre><code>template &lt;class T&gt; ostream&amp; operator&lt;&lt;(ostream&amp; s, const vector&lt;T&gt; &amp;A) { if(A.empty()) return s &lt;&lt; "[]"; s &lt;&lt; "["; typename vector&lt;T&gt;::const_iterator itr_penultimate = --A.end(); typename vector&lt;T&gt;::const_iterator itr = A.begin(); while(itr != itr_penultimate) { s &lt;&lt; *itr &lt;&lt; ", "; itr++; } return s &lt;&lt; *itr &lt;&lt; "]"; } </code></pre>
[]
[ { "body": "<p>This looks fine, but perhaps a more idiomatic option would be to use <code>ostream_iterator</code>, or similar constructs with <code>std::copy</code>, to avoid the actual loop. See <a href=\"https://stackoverflow.com/questions/6692880/how-to-deal-with-last-comma-when-making-comma-separated-string\">this link</a>, for example. From the first answer:</p>\n\n<pre><code>std::ostringstream ss;\n\nstd::copy(v.begin(), v.end() - 1, std::ostream_iterator&lt;int&gt;(ss, \", \"));\nss &lt;&lt; v.back();\n\nstd::cout &lt;&lt; ss.str() &lt;&lt; \"\\n\";\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T03:29:26.407", "Id": "47891", "Score": "0", "body": "Can you give a simple example or point me in the right direction when you say \"ostream_iterator or similar constructs with copy to avoid the actual loop\"? Is this the method that uses `std::copy`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T04:13:45.760", "Id": "47893", "Score": "0", "body": "Added a quote from the link. Just surround with the outside delimiters of choice. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T04:21:31.100", "Id": "47894", "Score": "0", "body": "Thanks, just learned about `ostream_iterators` and the copy. I realize you copied the post, but isn't it better to use `std::endl` rather than `\"\\n\"` though?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T04:25:42.133", "Id": "47895", "Score": "0", "body": "Indeed - endl will flush the buffer if the stream is buffered. (Though sometimes that's a reason not to use endl - if I'm writing a bunch of formatted text, I'll prefer \\n until I get to the end of the output. So if I were breaking the above after every 80 columns, for instance, I'd probably us \"\\n\" at the end of each line, and endl at the end of the output.)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T04:44:53.607", "Id": "47897", "Score": "1", "body": "@sfjac: Based on one of the comments under that answer, the `-1` is not needed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T05:15:37.857", "Id": "47898", "Score": "0", "body": "It's needed for the desired formatting but illegal if the container is empty, as is the subsequent call to back, so the empty case is still special." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T18:44:25.697", "Id": "47952", "Score": "1", "body": "--end should be preferred as it will require a reversible container rather than a random access container. With some rather nasty looping you could even make it support forward-iterable-only containers, but since forward_list is the only one, there's probably no point." } ], "meta_data": { "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T02:25:24.533", "Id": "30159", "ParentId": "30132", "Score": "3" } }, { "body": "<p>The above answer is fine.</p>\n\n<p>The only problem I have is the extra <code>','</code> in the output:</p>\n\n<pre><code>std::cout &lt;&lt; \"[ \";\nstd::copy(data.begin(), data.end(), std::ostream_iterator&lt;int&gt;(std::cout, \", \"));\nstd::cout &lt;&lt; \" ]\\n\";\n</code></pre>\n\n<p>Generates the output:</p>\n\n<pre><code>[ 1, 2, 3, 4, 5, 6, ]\n ^ extra comma\n</code></pre>\n\n<p>You can get around this with some extra work.</p>\n\n<pre><code>auto end = data.end();\nif (!data.empty()) { --end;}\nstd::cout &lt;&lt; \"[ \";\nstd::copy(data.begin(), end, std::ostream_iterator&lt;int&gt;(std::cout, \", \"));\nif (!data.empty()) {std::cout &lt;&lt; *end;}\nstd::cout &lt;&lt; \" ]\\n\";\n</code></pre>\n\n<p>Generates the output:</p>\n\n<pre><code>[ 1, 2, 3, 4, 5, 6 ]\n</code></pre>\n\n<p>This is better but it sort of defeats the purpose of using algorithms.</p>\n\n<p>If we had used the loop it would look like this:</p>\n\n<pre><code>std::cout &lt;&lt; \"[\";\nfor(auto loop = data.begin(); loop != data.end(); ++loop)\n{\n std::cout &lt;&lt; *itr &lt;&lt; \", \";\n}\nstd::cout &lt;&lt; \"]\";\n</code></pre>\n\n<p>Of course this has the same problem as the first version of the algorithm above. So if we take that into account you can re-write like this:</p>\n\n<pre><code>std::cout &lt;&lt; \"[\";\nauto begin = data.begin();\nif (!data.empty) {std::cout &lt;&lt; *begin;++begin}\nfor(auto loop = begin; loop != data.end(); ++loop)\n{\n std::cout &lt;&lt; \", \" &lt;&lt; *loop;\n}\nstd::cout &lt;&lt; \"]\";\n</code></pre>\n\n<p>Now it works. And because it only use one test on empty is better than the altered algorithm version in my opinion. So what we really need is a version of the output iterator that does the above.</p>\n\n<pre><code>template&lt;typename T&gt;\nclass PrefexOutputIterator\n{\n std::ostream&amp; ostream;\n std::string prefix;\n bool first;\n public:\n\n typedef std::size_t difference_type;\n typedef T value_type;\n typedef T* pointer;\n typedef T reference;\n typedef std::output_iterator_tag iterator_category;\n\n PrefexOutputIterator(std::ostream&amp; o,std::string const&amp; p = \"\"): ostream(o), prefix(p), first(true) {}\n\n PrefexOutputIterator&amp; operator*() {return *this;}\n PrefexOutputIterator&amp; operator++() {return *this;}\n PrefexOutputIterator&amp; operator++(int) {return *this;}\n\n void operator=(T const&amp; value)\n {\n if (first) {ostream &lt;&lt; value;first = false;}\n else {ostream &lt;&lt; prefix &lt;&lt; value;}\n }\n};\n</code></pre>\n\n<p>Now we can use this and get the output we want:</p>\n\n<pre><code>std::cout &lt;&lt; \"[\";\nstd::copy(data.begin(), data.end(), PrefexOutputIterator&lt;int&gt;(std::cout, \", \"));\nstd::cout &lt;&lt; \"]\";\n</code></pre>\n\n<p>The output is:</p>\n\n<pre><code>[1, 2, 3, 4, 5, 6]\n</code></pre>\n\n<p>Nowadays though I seem to be using a lot of Json.\nSo now I use this template librrys: <a href=\"https://github.com/Loki-Astari/ThorsSerializer\" rel=\"nofollow\">https://github.com/Loki-Astari/ThorsSerializer</a></p>\n\n<pre><code>using ThorsAnvil::Serialize::jsonExport;\nusing ThorsAnvil::Serialize::jsonImport;\n\nstd::cout &lt;&lt; jsonExport(data) &lt;&lt; \"\\n\"; // Serialize the array as json (looks like above)\nstd::cin &gt;&gt; jsonImport(data); // Reads a json array into an array.\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T17:24:58.567", "Id": "30181", "ParentId": "30132", "Score": "8" } } ]
{ "AcceptedAnswerId": "30159", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T14:04:00.807", "Id": "30132", "Score": "3", "Tags": [ "c++", "c++11", "vectors" ], "Title": "Comma-formatted STL vectors" }
30132
<p>The following code is part of an application I maintain that has a VT100/Xterm style graphical user interface that is implemented using text (Think Midnight Commander. Retro, I know.)</p> <p>Part of the code involves producing collections of rectangles that represent regions of the screen that may require redrawing. These are then chopped up into "slices" of rectangles with a height of 1. After this, any overlapping rectangles are merged together to produce a final set of non-overlapping rectangles. The code then goes on to check to see exactly what parts of those regions have changed since the last time the client was updated and the ultimate goal is to produce the smallest amount of protocol code to the client, which is usually somewhere over the network, in order to redraw its screen.</p> <p>After profiling detected a bottleneck there, I recently attacked the part of the code that merges the rectangles together, as a full-screen redraw of all components can generate a couple of thousand of the above "slices" (which merges down to 24 quite happily). The old algorithm naively checked every element in the array with every other element, making it quadratic, whereas my new algorithm seems to be roughly linear.</p> <p>At the centre of the algorithm, however, there are three special cases for how to merge the rectangles. I am almost certain that these can be generalised into one non-branching statement, but it eludes me. I would appreciate any pointers in that direction, or any other critiques of the algorithm in general.</p> <p>(Aside: compare_slices orders by the Y co-ordinate of a rectangle's origin, then by the X co-ordinate.)</p> <pre><code>static vector&lt;rectangle&gt; merge_overlapping_slices(vector&lt;rectangle&gt; rectangles) { sort(rectangles.begin(), rectangles.end(), compare_slices); BOOST_AUTO(first_slice, rectangles.begin()); // Iterate through adjacent slices, merging any that overlap. for (; first_slice != rectangles.end(); ++first_slice) { // Skip over any slices that have been merged. if (first_slice-&gt;size.height == 0) { continue; } BOOST_AUTO(second_slice, first_slice + 1); // Iterate through all adjacent slices that share a y-coordinate // until we either run out of slices, or cannot merge a slice. for (; second_slice != rectangles.end() &amp;&amp; first_slice-&gt;origin.y == second_slice-&gt;origin.y; ++second_slice) { // If there is an overlap, then merge the slices and continue // to the next adjacent slice. if (first_slice-&gt;origin.x + first_slice-&gt;size.width &gt;= second_slice-&gt;origin.x) { // Change the first slice so that it is the union of both // slices. Note we only have to consider the x-coordinate // since we already know that both slices share the same // y-axis. s32 required_width; // !!NOTE: this is the code I would like to generalise if (first_slice-&gt;origin.x == second_slice-&gt;origin.x) { // Both slices share the same origin, so we can simply // take the width of the widest slice. required_width = (std::max)( first_slice-&gt;size.width, second_slice-&gt;size.width); } else if (first_slice-&gt;origin.x + first_slice-&gt;size.width &gt;= second_slice-&gt;origin.x + second_slice-&gt;size.width) { // The first slice completely encompasses the second, // so we can just take the width of the first slice. required_width = first_slice-&gt;size.width; } else { // The slices only partially overlap. Work out the union // of the slices. required_width = second_slice-&gt;size.width + (second_slice-&gt;origin.x - first_slice-&gt;origin.x); } first_slice-&gt;size.width = required_width; // Mark the second slice as having been merged. second_slice-&gt;size.height = 0; } // Otherwise, break out of this iteration and try to merge a // different slice. else { break; } } } // Snip out any rectangles that have been merged (have 0 height). rectangles.erase(remove_if( rectangles.begin() , rectangles.end() , has_empty_height) , rectangles.end()); return rectangles; } </code></pre>
[]
[ { "body": "<p>So I cleaned up and simplified the inner loop in the code quite a lot:</p>\n\n<pre><code>static vector&lt;rectangle&gt; merge_overlapping_slices(vector&lt;rectangle&gt; rectangles)\n{\n sort(rectangles.begin(), rectangles.end(), compare_slices);\n\n BOOST_AUTO(first_slice, rectangles.begin());\n\n // Iterate through adjacent slices, merging any that overlap.\n for (; first_slice != rectangles.end(); ++first_slice)\n {\n // Skip over any slices that have been merged.\n if (first_slice-&gt;size.height == 0)\n {\n continue;\n }\n\n BOOST_AUTO(second_slice, first_slice + 1);\n\n // Iterate through all adjacent slices that share a y-coordinate\n // until we either run out of slices, or cannot merge a slice.\n for (; \n second_slice != rectangles.end()\n &amp;&amp; first_slice-&gt;origin.y == second_slice-&gt;origin.y\n &amp;&amp; first_slice-&gt;origin.x + first_slice-&gt;size.width &gt;= second_slice-&gt;origin.x;\n ++second_slice)\n {\n // Set the width of the first slice to be equivalent to the\n // rightmost point of the two rectangles.\n first_slice-&gt;size.width = (std::max)(\n first_slice-&gt;origin.x + first_slice-&gt;size.width\n , second_slice-&gt;origin.x + second_slice-&gt;size.width)\n - first_slice-&gt;origin.x;\n\n // Mark the second slice as having been merged.\n second_slice-&gt;size.height = 0;\n }\n }\n\n // Snip out any rectangles that have been merged (have 0 height).\n rectangles.erase(remove_if(\n rectangles.begin()\n , rectangles.end()\n , has_empty_height)\n , rectangles.end());\n\n return rectangles;\n}\n</code></pre>\n\n<p>Furthermore, it occurs to me that all of the variables used in the body of the loop are already \"touched\" by the loop control. This would, according to my understanding of the situation, reduce the possible hit from branching.</p>\n\n<p>In other words, I should stop fretting about this and focus efforts elsewhere.</p>\n\n<p>(Academically, though, I'm still interested in something that would flatten the call to std::max to some basic arithmetic.)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-24T09:48:25.987", "Id": "31723", "ParentId": "30137", "Score": "4" } } ]
{ "AcceptedAnswerId": "31723", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T14:40:36.860", "Id": "30137", "Score": "3", "Tags": [ "c++", "performance", "algorithm", "computational-geometry" ], "Title": "Algorithm for merging overlapping rectangles" }
30137
<p>I wrote a script for getting the stats of codereview.SE from the front page into a file. <a href="https://github.com/anshbansal/general/blob/b444984901f01b90d88c81e6e561924970548594/Python33/Projects/codereview_stats/get_stats.py" rel="nofollow">Github link</a> if someone prefers reading there. Here is <code>data_file.txt</code>'s current contents</p> <pre><code>23-08-2013 dd-mm-yyyy, questions, answers, %answered, users, visitors/day 22-08-2013,9079,15335,88,26119,7407, 23-08-2013,9094,15354,88,26167,7585, </code></pre> <p>The first sentence contains the last date at which the data is written into the file. It is a check to make sure that I don't write the data for the same date twice in the file. Also note that there is a newline at the end which isn't being shown above.</p> <p>What I plan to do is to collect the data for many data and then use <code>matplotlib</code> to get graphs for finding out about the growth of this website. The part about plotting is currently under progress so I am not putting that here.</p> <p>The python script that I am using is below. I would like a general review of this script and any suggestions about its design in particular.</p> <pre><code>#! python3 import urllib.request import datetime FILE_NAME = 'data_file.txt' CURRENT_URL = 'http://codereview.stackexchange.com/' def today_date(): return datetime.date.today().strftime('%d-%m-%Y') def already_written(): with open(FILE_NAME, 'a+') as f: f.seek(0) first_line = f.readline() if today_date() == first_line[:-1]: return True return False def parse(line): """This separates the stat-name and associated number""" temp = [0, ''] braces = False for c in line: if c == '&lt;': braces = True elif c == '&gt;': braces = False elif braces is True or c in [' ', ',', '%']: continue elif c.isdigit(): temp[0] *= 10 temp[0] += int(c) else: temp[1] += c return temp def write_stats(): '''This writes the stats into the file''' with open(FILE_NAME, 'r') as f: data = f.readlines() with open(FILE_NAME, 'w') as f: f.write(today_date() + '\n') f.writelines(data[1:]) url_handle = urllib.request.urlopen(CURRENT_URL) write_this = today_date() + ',' for line in url_handle: temp_line = str(line)[2:-5] if 'stats-value' in temp_line and 'label' in temp_line: temp = parse(temp_line) write_this += str(temp[0]) + ',' else: write_this += '\n' f.write(write_this) def main(): if not already_written(): write_stats() if __name__ == "__main__": main() </code></pre> <p><strong>EDIT:</strong></p> <p>I think this line might need some explanation.</p> <pre><code>if 'stats-value' in temp_line and 'label' in temp_line: </code></pre> <p>I choose this for finding out the lines in the source code of the html of codereview.SE's front page. Only the 5 lines containing the stats have these 2 in it. So in front they tell me which line to parse.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T09:05:12.657", "Id": "48041", "Score": "0", "body": "If a line needs some explanation, that explanation should be right before/beside it in a comment. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T09:10:47.647", "Id": "48042", "Score": "1", "body": "@flornquake Good point but I was indirectly bumping this question :)" } ]
[ { "body": "<p>Firstly, you don't need to store the last date at the beginning of the file since it's already at the end.</p>\n\n<p>Secondly, you shouldn't compute today's date twice.</p>\n\n<p>Thirdly, you should use <a href=\"http://api.stackexchange.com/docs/info#filter=default&amp;site=codereview&amp;run=true\">Stack Exchange's API</a> instead of trying to extract information from Code Review's home page. It has everything except visitors/day.</p>\n\n<p>Fourthly, the date format <code>%Y-%m-%d</code> is better than <code>%d-%m-%Y</code> because it allows string comparison of dates.</p>\n\n<p>So, here's what I came up with:</p>\n\n<pre><code>#!/usr/bin/env python3\n\nimport datetime\nimport gzip\nimport json\nfrom urllib.request import Request, urlopen\n\nFILE_NAME = 'data_file.txt'\nAPI_URL = 'http://api.stackexchange.com/2.1/info?site=codereview'\n\ndef last(iterable, default):\n r = default\n for v in iterable:\n r = v\n return r\n\ndef main():\n today = datetime.date.today().strftime('%Y-%m-%d')\n with open(FILE_NAME, 'a+') as f:\n f.seek(0)\n last_date = last(f, '').split(',')[0]\n if last_date == today:\n return # we already have the data for today\n elif last_date &gt; today:\n raise Exception('last date is in the future')\n\n req = Request(API_URL, headers={'Accept-Encoding':'gzip'})\n r = gzip.decompress(urlopen(req).read()).decode('utf8')\n d = json.loads(r)['items'][0]\n print(today,\n d['total_questions'],\n d['total_answers'],\n d['total_unanswered'],\n d['total_users'],\n sep=',', file=f)\n\nif __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>The gzip stuff is to work around a bug in Stack Exchange's API server: it always compresses the response even if you don't ask, which is a protocol violation. Using the <a href=\"https://pypi.python.org/pypi/requests\" rel=\"nofollow\">requests library</a> might make it easier.</p>\n\n<p>The way I get the last line of the file isn't the most efficient but it should be good enough.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T20:27:14.120", "Id": "30589", "ParentId": "30139", "Score": "1" } } ]
{ "AcceptedAnswerId": "30589", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T15:16:56.133", "Id": "30139", "Score": "5", "Tags": [ "python", "python-3.x" ], "Title": "Review Python script for getting the stats of codereview.SE into a file for analysis" }
30139
<p>This is my first Python script, and I was hoping to get some feedback. I do have one specific question: is the use of <code>global</code> variables considered a bad practice? When I used them below, my programmer's instincts immediately went off as though I was creating a code-smell, mostly because it seems much less elegant than just having a <code>private String myVariable</code> at the top of a Java class. The use of <code>global myVariable</code> to force the scope seemed a bit hacky. But I don't know a single thing about Python except what I wrote below, so I could be way off.</p> <p>I also realize that the below code is more complex than it needs to be. I know that it could be written in much fewer lines of code by removing function definitions and such (in fact, my first version was only like 15 lines). But I wrote this more complicated version in order to get a handle on some of the basic concepts like sharing variables, returning from functions, etc.</p> <p>Any tips or glaring style/best-practices issues are appreciated! (I'm a style-Nazi with Java, so please, don't hold back so that I can learn!)</p> <pre><code>#!/usr/bin/python from random import randint # GLOBALS guesses = 0 the_number = 0 def checkGuess(guess): global the_number if guess &lt;= 0: return False elif guess == the_number: return True elif guess &lt; the_number: print "The number is HIGHER." elif guess &gt; the_number: print "The number is LOWER." return False def isValid(guess): return len(guess) &gt; 0 and guess.isdigit() def getInput(): global guesses input = "" while not isValid(input): input = raw_input("(#" + str(guesses) + ") Guess a number: ") if not isValid(input): print "Please guess an integer!" return int(input) def runGame(min, max): global guesses global the_number the_number = randint(min, max) guess = 0 print "I'm thinking of a number between " + str(min) + " and " + str(max) + " ..." while not checkGuess(guess): guesses = guesses + 1 guess = getInput() print "YOU WON!" def printTitle(): print "----------------------" print "----- MASTERMIND -----" print "----------------------" print "" def main(): printTitle() runGame(1, 100) main() </code></pre>
[]
[ { "body": "<p>You can solve anything without globals. If not, you are doing wrong. If you are using globals, the debugging will be a nightmare. In the <code>checkGuess()</code> you can use single ifs instead of elif. The return will terminate the function and after the first 3 check, the last one can't be anything else than grater than <code>the_number</code>.\nIf you want to check a variable not to be null/zero/empty/None, you can use simply the <code>if var:</code> condition. It will be False if <code>var</code> is null/zero/empty/None.\nIn <code>getInput()</code> you can get the first value before the loop. If you get inside the loop and you use an additional if, then there will be 2 useless condition which slow down the app (I know only a little but...).</p>\n\n<pre><code>#!/usr/bin/python\nfrom random import randint\n\n\ndef checkGuess(guess, the_number):\n if guess &lt;= 0:\n return False\n if guess == the_number:\n return True\n if guess &lt; the_number:\n print \"The number is HIGHER.\"\n else:\n print \"The number is LOWER.\"\n\n return False\n\n\ndef isValid(guess):\n return guess and guess.isdigit()\n\n\ndef getInput(guesses):\n input = raw_input(\"(#\" + str(guesses) + \") Guess a number: \")\n while not isValid(input):\n print \"Please guess an integer!\"\n input = raw_input(\"(#\" + str(guesses) + \") Guess a number: \")\n\n return int(input)\n\n\n\ndef runGame(min, max):\n the_number = randint(min, max)\n guesses = 0\n guess = 0\n\n print \"I'm thinking of a number between \" + str(min) + \" and \" + str(max) + \" ...\"\n\n while not checkGuess(guess, the_number):\n guesses += 1\n guess = getInput(guesses)\n\n print \"YOU WON!\"\n\n\ndef printTitle():\n print \"----------------------\"\n print \"----- MASTERMIND -----\"\n print \"----------------------\"\n print \n\n\nif __name__=='__main__':\n printTitle()\n runGame(1, 100)\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T19:07:47.107", "Id": "30152", "ParentId": "30150", "Score": "3" } }, { "body": "<p>Some notes:</p>\n\n<ul>\n<li><p>Mutable global state is a bad programming practice. Instead, pass values as arguments so functions are black boxes that take values (as arguments) and return values. If such a function does not perform any side-effect (print to console, write a file, ...), then it's a \"pure function\". Try to write pure functions whenever possible.</p></li>\n<li><p>Conditionals: Don't write a fallback (<code>return False</code>) where some branches get and others don't. Non-overlapping conditionals are more clear.</p></li>\n<li><p>Use <code>name_of_variable</code> and <code>name_of_function</code>. </p></li>\n<li><p>Try to use Python 3 whenever possible.</p></li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>from random import randint\nfrom itertools import count\n\ndef is_guess_correct(number, guess):\n if guess == number:\n return True\n elif guess &lt; number:\n print(\"The number is HIGHER.\")\n return False\n else:\n print(\"The number is LOWER.\")\n return False\n\ndef is_valid_guess(number_string):\n return number_string.isdigit()\n\ndef get_number(guess_iteration):\n while 1:\n number_string = input(\"({0}) Guess a number: \".format(guess_iteration))\n if is_valid_guess(number_string):\n return int(number_string)\n else:\n print(\"Please enter a valid integer!\")\n\ndef run_game(nmin, nmax):\n number = randint(nmin, nmax)\n print(\"I'm thinking of a number between {0} and {1}...\".format(nmin, nmax))\n\n for guess_iteration in count(1):\n guess = get_number(guess_iteration)\n if is_guess_correct(number, guess):\n print(\"YOU WON!\")\n break\n\nif __name__ == '__main__':\n run_game(1, 100)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T13:27:02.330", "Id": "47997", "Score": "0", "body": "Thanks for your feedback. What do you mean by \"Try to use Python 3?\" Which feature or design consideration were you referring to that looked like an earlier version?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T13:34:15.600", "Id": "47998", "Score": "0", "body": "`print` is not a statement anymore, it's a function, so I concluded you are using Python2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T15:28:41.610", "Id": "48002", "Score": "0", "body": "Got it, thanks. One more question. I'm used to `for... in...` logic iterating over each element in a set. I just want to fully understand what's happening in `for guess_iteration in count(1)`. I get that `guess_iteration` is being incremented each time the loop runs, but is `count(1)` kind of a hacky \"`while(true)`\" sort of thing? Or is the `count()` function specifically made for infinite loops that you have to `break` out of?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T15:47:18.710", "Id": "48004", "Score": "1", "body": "yes, with `count` you avoid the verbose while+counter (I wouldn't call a hack, I think it's way better because is more declarative). How it works: `count(n)` returns a iterator, check http://docs.python.org/2/library/itertools.html#itertools.count and http://stackoverflow.com/questions/19151/build-a-basic-python-iterator. Regarding the last question, `count` is a basic functional abstraction, an infinite lazy counter that comes handy in a lot of situations." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-08-23T21:54:43.227", "Id": "30156", "ParentId": "30150", "Score": "5" } }, { "body": "<p>Instead of the printTitle function which is less efficient</p>\n\n<pre><code>def printTitle():\n print \"----------------------\"\n print \"----- MASTERMIND -----\"\n print \"----------------------\"\n print \"\"\n</code></pre>\n\n<p>Just save the title to a variable and print it out or make a new file and import the variable from it.</p>\n\n<pre><code>title = \"\"\"\n----------------------\n----- MASTERMIND -----\n----------------------\n\n\"\"\"\nprint(title)\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-10T22:43:52.537", "Id": "443669", "Score": "0", "body": "Welcome to Code Review! Could you please [edit](https://codereview.stackexchange.com/posts/227814/edit) your answer and explain what benefit this would have?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2019-09-10T22:20:48.793", "Id": "227814", "ParentId": "30150", "Score": "1" } } ]
{ "AcceptedAnswerId": "30156", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T18:44:22.477", "Id": "30150", "Score": "5", "Tags": [ "python", "beginner", "number-guessing-game" ], "Title": "First Python script: number-guessing game with a global variable" }
30150
<p>This method allows me to filter by date a data structure list of hash that contains articles. I would like to have your opinion on the code:</p> <pre><code>=method article_by_date $articles-&gt;articles_by_date( month =&gt; 12 ); </code></pre> <p>Return a list of articles filter by date specified:</p> <pre><code> input: month (Int) : optional, month to match year (Int) : optional, year to match output: Hashref: Details of article =cut sub articles_by_date { state $check = compile( $invocant, slurpy Dict[ month =&gt; Optional[Int], year =&gt; Optional[Int], ] ); my ($self, $arg) = $check-&gt;(@_); my $month = $arg-&gt;{month}; my $year = $arg-&gt;{year}; if ( ! defined($year) ) { my $dt = DateTime-&gt;now; $year = $dt-&gt;year; } my $date = defined($month) ? qr/^\d\d\/$month\/$year\s\d\d:\d\d:\d\d$/ : qr/^\d\d\/\d\d\/$year\s\d\d:\d\d:\d\d$/; my @articles; foreach my $article ( @{$self-&gt;_get_or_create_cache('articles')} ) { $article-&gt;{date} =~ $date and push(@articles, $article); } return \@articles; } </code></pre>
[]
[ { "body": "<p>Most of this depends on what exactly do you want to achieve. For example, <code>@articles</code> will be a list of references to the same articles that are also referenced in <code>$self-&gt;_get_or_create_cache('articles')</code>. Depending on what you want, you might want to clone these values, instead of just pushing them to <code>@articles</code>.</p>\n\n<p>The other thing is a regex for dates. Are you certain that your dates will be, for example, 23/<strong>08</strong>/2013, and not 23/<strong>8</strong>/2013? If not, this might be better:</p>\n\n<pre><code>my $date = defined($month)\n ? qr/^\\d{1,2}\\/$month\\/$year\\s\\d{1,2}:\\d{1,2}:\\d{1,2}$/\n : qr/^\\d{1,2}\\/\\d{1,2}\\/$year\\s\\d{1,2}:\\d{1,2}:\\d{1,2}$/;\n</code></pre>\n\n<p>The same goes for the times, of course.</p>\n\n<p>Depending on how clean your input is, you might want to replace <code>$month</code> and <code>$year</code> with <code>\\Q$month\\E</code> and <code>\\Q$year\\E</code> to avoid matching special characters in those variables (i.e., that <code>.</code> is matched as a dot and not as any character).</p>\n\n<p>If it may be possible for the input to have extra spaces, you might want to add <code>\\s*</code> after <code>^</code> and before <code>$</code>, while also replacing <code>\\s</code> behind <code>$year</code> with <code>\\s+</code>.</p>\n\n<p>Day of month can be more precisely matched as <code>(0?[1-9]|[1-2]\\d|3[01])</code> (similar for months, hours, minutes, and seconds), but this makes regexes quite comples, so see if you need this.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T21:23:20.160", "Id": "30154", "ParentId": "30153", "Score": "4" } }, { "body": "<p>Your code is mostly very readable and good. I have to point out the explicit type checking – this is wonderful!</p>\n\n<h1>Minor Style Recommendations</h1>\n\n<p>There are a few style thingies where I don't really care what you do, but it is common to put a comma after the last item in a list when it is at the end of a line:</p>\n\n<pre><code> ...,\n slurpy Dict[\n month =&gt; Optional[Int],\n year =&gt; Optional[Int],\n ], # &lt;-- HERE\n );\n</code></pre>\n\n<p>Also, the </p>\n\n<pre><code>$article-&gt;{date} =~ $date\n and push(@articles, $article);\n</code></pre>\n\n<p>looks goofy:</p>\n\n<ul>\n<li><p>TIMTOWTDI, but that may look better with an <code>if</code>:</p>\n\n<pre><code>push(@articles, $article) if $article-&gt;{date} =~ $date;\n</code></pre></li>\n<li><p>I prefer to enclose regex applications in <code>/.../</code>, even when this is not syntactically neccessary: The delimiters make it visually clearer:</p>\n\n<pre><code>push(@articles, $article) if $article-&gt;{date} =~ /$date/;\n</code></pre>\n\n<p>This does not force recompilation of the regex on sufficiently modern perls (the last time I checked).</p></li>\n</ul>\n\n<h1>Naming Improvements</h1>\n\n<p>Let's move on to names. I do not know the purpose of your class. But if the class name, the object name, and all method names contain “article”, something may be wrong. (Of course <code>_get_or_create_cache</code> only contains <code>article</code> as an argument, but that seems to be effectively a part of the name).</p>\n\n<p>Assuming the purpose of the class is some collection of articles, then maybe the following may look more natural:</p>\n\n<pre><code>my $articles = Articles-&gt;new(...);\nmy $articles_from_may = $articles-&gt;at_date(month =&gt; 3); # instead of articles_by_date\n\n# instead of _get_or_create_cache('articles'):\n# array dereference overloading\nfor my $article (@$articles) {\n ...; \n}\n# or a simpler method\nfor my $article ($articles-&gt;all) {\n ...;\n}\n</code></pre>\n\n<p>But I could be misunderstanding the intentions of the class.</p>\n\n<p>As this method is all about dates, I would expect a <code>$date</code> variable to be some kind of date object or string. Nope, it is a regex. I do not know where you stand on Hungarian Notation, but sometimes it can <em>really</em> aid readability: <code>$date_rx</code> or something. Just don't overuse it.</p>\n\n<h1>Major Style Issues</h1>\n\n<p>Now on to more “serious” stuff.</p>\n\n<h2>Define-Or <code>//</code></h2>\n\n<p>Your <code>if ( ! defined($year)) ...</code> is a big waste of screen space. You can use the defined-or operator for shorter initialization:</p>\n\n<pre><code>my $year = $arg-&gt;{year} // DateTime-&gt;now-&gt;year;\n</code></pre>\n\n<h2>Regex Formatting and Correctness</h2>\n\n<p>Your two regexes are two lines of unreadable mess. The hypnotic rhythm of backslashes is only broken by the variable interpolations. But I can't tell at a glance what is happening here! We can introduce nonmatching space with the <code>/x</code> flag to make it more readable. You should also change the delimiter so that you don't have to escape the forward slashes.</p>\n\n<p>If there is any chance the date fields in your <code>$article</code> may be generated by an outside source, then the <code>\\d</code> is wrong. This character class matches all Unicode digits, or <code>[0-9]</code> in some special circumstances. Either force ASCII semantics via <code>/a</code> flag, or be explicit with your character classes.</p>\n\n<pre><code>my $time_rx = qr/ [0-9]{1,2} : [0-9]{1,2} : [0-9]{1,2} /x;\nmy $date_rx = defined($month)\n ? qr!\\A [0-9]{1,2}/$month/$year \\s+ $time_rx \\z!x\n : qr!\\A [0-9]{1,2}/[0-9]{1,2}/$year \\s+ $time_rx \\z!x;\n</code></pre>\n\n<p>You should also heed Vedran Šego's advice on this topic.</p>\n\n<h1>Bugs</h1>\n\n<h2>Regex Bug: Date Formatting</h2>\n\n<p>Now there is a subtle bug here. What happens when the date string is <code>01/02/2013 13:46:02</code> and the user calls your method like <code>month =&gt; 2</code>? The regex would match <code>01/2/2013 ...</code> but not <code>/02/</code>! This would mean that you have to <code>sprintf '%02d'</code> the stuff which you'd like to interpolate.</p>\n\n<p>This still assumes that you normalize all your dates (e.g. to UTC), so that your complete omission of time zones if forgivable. (Actually, it isn't. See below for some failure modes).</p>\n\n<h2>Rant: Correct Date Handling</h2>\n\n<h3>Articles Should Contain <code>DateTime</code>s</h3>\n\n<p>Handling dates correctly is very complex. Yes, you can achieve some kind of seemingly working code with regexes, but I wouldn't recommend this. It would be preferable for each <code>$article</code> to include a DateTime object (just create them lazily if it seems too expensive to you). Then instead of the regex application:</p>\n\n<pre><code>$article-&gt;date-&gt;year == $year &amp;&amp; $article-&gt;date-&gt;month == $month\n</code></pre>\n\n<p>This is shorter, more readable, and more correct, but more expensive than the regex solutions.</p>\n\n<h3>The Method Should Have A <code>DateTime</code> As Argument</h3>\n\n<p>This still isn't completely correct, because no timezone information for the <code>$year</code> and <code>$month</code> is available. It might be better to require the user to call your method with a <code>DateTime</code> object, which you truncate to the month. Then:</p>\n\n<pre><code>...\nmy ($self, $date) = &amp;$check;\n$date = $date-&gt;clone-&gt;truncate(to =&gt; 'month');\n...\n$article-&gt;date-&gt;year == $date-&gt;year &amp;&amp; ...\n</code></pre>\n\n<h3>Don't Guess The Year!</h3>\n\n<p>This would get rid of most bugs, and ambiguity. The latter exists because you try to <em>guess</em> a year. This can be bad UX:</p>\n\n<ul>\n<li>Assume that on Jan. 1st, I ask for all articles from December. Suprisingly, the query returns no articles, although there was a new article just yesterday!</li>\n<li>Or even better, assume that I ask for all articles from December during the last day of December. However, your program thinks it's already January, and returns an empty array.</li>\n</ul>\n\n<h3>Finally, A Solution…</h3>\n\n<p>I am not sure, but I think that</p>\n\n<pre><code>...\nmy $date_min = $date-&gt;clone-&gt;truncate(to =&gt; 'month');\nmy $date_max = $date_min-&gt;clone-&gt;add(months =&gt; 1);\n...\n$date_min &lt;= $article-&gt;date &amp;&amp; $article-&gt;date &lt; $date_max\n</code></pre>\n\n<p>might work without bugs, assuming that the DateTime your method is called with has specified a correct time zone.</p>\n\n<h1>Make <code>map</code>, not <code>for</code>.</h1>\n\n<p>Finally, your <code>foreach</code> loop is really just a <code>grep</code> in disguise. You want:</p>\n\n<pre><code>my @articles = grep { $date_min &lt;= $_-&gt;date &amp;&amp; $_-&gt;date &lt; $date_max } $self-&gt;all;\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T23:36:58.540", "Id": "47971", "Score": "0", "body": "Hi, Thank you very much for this very constructive response. It is true that I know define gold I used elsewhere but I did not think for once thank you. It is true that the regex is not always appropriate and in this case it's wrong, I'll change and I'll post my answer for another opinion. Thank you again for the great response, I like more this site, I will ask a lot of code review here. Hoping that my codes are not too bad." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T13:41:51.390", "Id": "30173", "ParentId": "30153", "Score": "4" } } ]
{ "AcceptedAnswerId": "30173", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T19:13:35.163", "Id": "30153", "Score": "2", "Tags": [ "datetime", "perl" ], "Title": "Filter by date method" }
30153
<p>I have been trying to parse results and make sure when I am doing so that I don't repeat the same data. I tried to use a few different options built into php with no luck. I did find an example of a recursive array search that seems to work but it's very intensive and adds a lot of time to the script.</p> <p><strong>What I'm needing</strong>: Does anyone know a better way to handle this without changing the array that I supply to it so something built-in like <code>in_array</code> or <code>array_search</code>?</p> <p>Array example:</p> <pre><code>array (size=3) 0 =&gt; array (size=3) 'author' =&gt; string 'Jim Beam' (length=8) 'id' =&gt; string '1' (length=1) 'md5' =&gt; string 'f2ebf4d4f333c31ef1491a377edf2cc4' (length=32) 1 =&gt; array (size=3) 'author' =&gt; string 'Jack Daniels' (length=12) 'id' =&gt; string '2' (length=1) 'md5' =&gt; string 'd1839707c130497bfd569c77f97ccac7' (length=32) 2 =&gt; array (size=3) 'author' =&gt; string 'Jose Cuervo' (length=11) 'id' =&gt; string '3' (length=1) 'md5' =&gt; string '64e989b4330cc03dea7fdf6bfe10dda1' (length=32) </code></pre> <p>Code example:</p> <pre><code>function recursive_array_search($needle,$haystack) { foreach($haystack as $key=&gt;$value) { $current_key=$key; if($needle===$value OR (is_array($value) &amp;&amp; recursive_array_search($needle,$value) !== false)) { return $current_key; } } return false; } $agentArray = array( array('author'=&gt;'Jim Beam','id'=&gt;'1','md5'=&gt;'f2ebf4d4f333c31ef1491a377edf2cc4'), array('author'=&gt;'Jack Daniels','id'=&gt;'2','md5'=&gt;'d1839707c130497bfd569c77f97ccac7'), array('author'=&gt;'Jose Cuervo','id'=&gt;'3','md5'=&gt;'64e989b4330cc03dea7fdf6bfe10dda1') ); $fakeMD5 = '84d7dc19766c446f5e4084e8fce87f82'; //StackOverflow MD5 $realMD5 = 'd1839707c130497bfd569c77f97ccac7'; //Jack Daniels MD5 echo '&lt;b&gt;In_Array:&lt;/b&gt; &lt;br/&gt;'; $faketest = in_array($fakeMD5,$agentArray); $realtest = in_array($realMD5,$agentArray); var_dump($faketest,$realtest); echo '&lt;b&gt;Search_Array:&lt;/b&gt; &lt;br/&gt;'; $faketest2 = array_search($fakeMD5,$agentArray); $realtest2 = array_search($realMD5,$agentArray); var_dump($faketest2,$realtest2); echo '&lt;b&gt;Custom Recursive Array Seach Function:&lt;/b&gt; &lt;br/&gt;'; $faketest3 = recursive_array_search($fakeMD5,$agentArray); $realtest3 = recursive_array_search($realMD5,$agentArray); var_dump($faketest3,$realtest3); </code></pre> <p>Results:</p> <pre class="lang-none prettyprint-override"><code>In_Array: Fake: boolean false Real: boolean false Search_Array: Fake: boolean false Real: boolean false Custom Recursive Array Seach Function: Fake: boolean false Real: int 1 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-22T09:38:07.303", "Id": "141789", "Score": "1", "body": "Also for PHP 5.5+ there is a simpler option, array_search($value, array_column($array, $key)); see http://stackoverflow.com/a/24527099/207603 (there is also a link to a backport for < PHP 5.5)" } ]
[ { "body": "<p>I have two comments.</p>\n\n<p>First, what is the purpose of <code>$current_key</code>? Since you're not changing it, just use <code>$key</code>.</p>\n\n<p>Second, by your usage, I'd say that</p>\n\n<pre><code>foreach ($haystack as $key =&gt; $item)\n if ($item[\"md5\"] === $needle) return $key;\nreturn false;\n</code></pre>\n\n<p>is quite enough. Of course, if the above was just an example and you really want to check all the values in (sub)arrays, then the above is O.K.</p>\n\n<p>Of course, be careful when using this function, because key <code>0</code> may be interpreted as <code>false</code>.</p>\n\n<p>A bit neater (but essentially the same) function was provided on Stack Overflow <a href=\"https://stackoverflow.com/a/4128377/1667018\">here</a>. I like the additional <code>$strict</code> argument there (which you may or may not need).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T22:25:56.040", "Id": "47884", "Score": "0", "body": "Yeah thats not my function someone added that in a different thread but I think I overlooked the simplicity of my operation. I will use your example and see if its faster!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T22:17:06.507", "Id": "30157", "ParentId": "30155", "Score": "1" } }, { "body": "<p>I will echo what Radu posted as a comment. I find a combination of <code>array_search()</code> with <code>array_column()</code> to be concise and easy to read. While foreach loops <em>can</em> perform slightly faster, using purpose-built native php functions can improve comprehension based on their names. Lines of code are reduced as well, if that is important to you, because <code>array_search()</code> bundles the array iteration, condition statement, and the return/break tasks.</p>\n\n<p>Code: (<a href=\"http://sandbox.onlinephpfunctions.com/code/479d7a101fe13ea33f98a424edc5ed43a5069f9c\" rel=\"nofollow noreferrer\">Demo</a>)</p>\n\n<pre><code>$agentArray = array(\n array('author'=&gt;'Jim Beam','id'=&gt;'1','md5'=&gt;'f2ebf4d4f333c31ef1491a377edf2cc4'),\n array('author'=&gt;'Jack Daniels','id'=&gt;'2','md5'=&gt;'d1839707c130497bfd569c77f97ccac7'),\n array('author'=&gt;'Jose Cuervo','id'=&gt;'3','md5'=&gt;'64e989b4330cc03dea7fdf6bfe10dda1')\n);\n\n$fakeMD5 = '84d7dc19766c446f5e4084e8fce87f82'; //StackOverflow MD5\n$realMD5 = 'd1839707c130497bfd569c77f97ccac7'; //Jack Daniels MD5\n\necho 'StackOverflow MD5 result: ';\nvar_export(array_search($fakeMD5,array_column($agentArray,'md5'),true)); // returns false : not found\n\necho \"\\nJack Daniels MD5 result: \";\nvar_export(array_search($realMD5,array_column($agentArray,'md5'),true)); // returns 1 : offset of the subarray\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>StackOverflow MD5 result: false\nJack Daniels MD5 result: 1\n</code></pre>\n\n<p>Now some notes about \"strict\" / \"indentical\" searching and the search results:</p>\n\n<ul>\n<li><p>I have included the third parameter <code>true</code> to the <code>array_search()</code> function. This is important if the needle (<code>$xxxxMD5</code>) comes from an untrustworthy source (e.g. user input). The reason is because if you omit the parameter then php will do a loose comparison and use \"type juggling\" (<a href=\"https://stackoverflow.com/a/44427775/2943403\">a post of mine with manual references and a demo</a>). A loose comparison when the needle is <code>0</code> will return the <code>Jim Beam</code> subarray's offset, and this is likely to be an unintended result.</p></li>\n<li><p>Similarly, when you are processing the result from the multidimensional search, take the same care to differentiate between a <code>false</code> and a <code>0</code> result. Like with <code>strpos()</code> it is best perform a strict comparison like <code>!==false</code> or <code>===false</code> depending on your usage.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2017-09-16T23:38:23.313", "Id": "175852", "ParentId": "30155", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-23T21:23:49.780", "Id": "30155", "Score": "1", "Tags": [ "php", "array" ], "Title": "Searching multidimensional arrays" }
30155
<p>Is there a better way to write it? I need the best way to write it. It is this principle? Please show me a better way</p> <p>it breaks SRP?</p> <pre><code> public class PlacementLocation { public int Row { get; set; } public int Column { get; set; } public int Location { get; set; } } public class PlacementLocations : PlacementLocation { private void SetLocationInList() { _placementLocations = new List&lt;PlacementLocation&gt; { new PlacementLocation {Column = 1, Row = 9, Location = 1}, new PlacementLocation {Column = 2, Row = 9, Location = 2}, new PlacementLocation {Column = 3, Row = 9, Location = 3}, new PlacementLocation {Column = 4, Row = 9, Location = 4}, new PlacementLocation {Column = 5, Row = 9, Location = 5}, }; } private List&lt;PlacementLocation&gt; _placementLocations; public PlacementLocations() { _placementLocations = new List&lt;PlacementLocation&gt;(); SetLocationInList(); } public Tuple&lt;int, int&gt; this[int location] { get { return new Tuple&lt;int, int&gt;(_placementLocations[location].Row, _placementLocations[location].Column); } } public int this[int row, int column] { get { PlacementLocation singleOrDefault = _placementLocations.SingleOrDefault(d =&gt; d.Column == column &amp;&amp; d.Row == row); return singleOrDefault != null ? singleOrDefault.Location : 0; } } } </code></pre> <p><strong>Update :</strong></p> <pre><code> public class PlacementLocations { #region Variables private readonly List&lt;PlacementLocation&gt; _placementLocations; #endregion #region Constructor public PlacementLocations(List&lt;PlacementLocation&gt; placementLocations) { _placementLocations = placementLocations; } #endregion #region Public Methods public Tuple&lt;int, int&gt; FindRowColumn(int location) { return GetRowColumn(location); } public int FindLocation(int row, int column) { return GetLocation(row, column); } #endregion #region Indexes public Tuple&lt;int, int&gt; this[int location] { get { return GetRowColumn(location); } } public int this[int row, int column] { get { return GetLocation(row, column); } } #endregion #region Private Methods private Tuple&lt;int, int&gt; GetRowColumn(int location) { return new Tuple&lt;int, int&gt;(_placementLocations[location].Row, _placementLocations[location].Column); } private int GetLocation(int row, int column) { PlacementLocation singleOrDefault = _placementLocations.SingleOrDefault(d =&gt; d.Column == column &amp;&amp; d.Row == row); return singleOrDefault != null ? singleOrDefault.Location : 0; } #endregion } public class LocationsFactory { public static PlacementLocations GetPredefinedLocations() { var placementLocationList = new List&lt;PlacementLocation&gt; { new PlacementLocation {Column = 1, Row = 9, Location = 1}, new PlacementLocation {Column = 2, Row = 9, Location = 2}, new PlacementLocation {Column = 3, Row = 9, Location = 3}, new PlacementLocation {Column = 4, Row = 9, Location = 4}, new PlacementLocation {Column = 5, Row = 9, Location = 5}, }; return new PlacementLocations(placementLocationList); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T14:16:09.893", "Id": "47917", "Score": "0", "body": "why have you edited the initial question code? Now it is not clear what question is about and answers below don't make any sense..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T14:24:51.220", "Id": "47918", "Score": "0", "body": "update question ." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T14:30:26.130", "Id": "47920", "Score": "0", "body": "you still haven't extracted the values from the class (what is told in answers below). What will you do if you need _another_ location values - write one more class? :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T14:32:04.390", "Id": "47921", "Score": "0", "body": "and you don't need a specific method which does just '_placementLocations = placementLocations;' - that is usually placed directly in constructor..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T14:35:58.893", "Id": "47922", "Score": "0", "body": "The question was edited. Is it correct?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T14:40:41.883", "Id": "47924", "Score": "0", "body": "At least the initial critical problems are solved." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T16:24:21.467", "Id": "47938", "Score": "0", "body": "However you added regions everywhere. IMO the best would be to put the class in a logical order where you can read it top to bottom like a short newspaper article. Regions clutter the code and impede readability." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T17:07:16.983", "Id": "47944", "Score": "0", "body": "@Pierre-Luc Pineault :Please give me more information about IMO" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T17:08:15.013", "Id": "47945", "Score": "0", "body": "@SunRise it means 'In My Opinion'" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T17:10:52.920", "Id": "47946", "Score": "0", "body": "@IharS: Do you think there is another problem?There is another critical problem?" } ]
[ { "body": "<p>Yes. Your class is not reusable, as it uses a specific initialization.</p>\n\n<p>Write a basic 'PlacementLocations' and a specialized and separate class with your initialization. Or do the initialization in the class using your PlacementLocations.</p>\n\n<p>The latter is the usual case. </p>\n\n<p>I would only recommend writing an own class with the specific initialization if these values represent something special which will be used more often.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T05:28:57.747", "Id": "30163", "ParentId": "30162", "Score": "0" } }, { "body": "<p>The inheritance doesn't make sense. 'PlacementLocations' is the object representing a collection of 'PlacementLocation' objects.</p>\n\n<pre><code>public class PlacementLocations\n{\n private List&lt;PlacementLocation&gt; _placementLocations;\n\n public PlacementLocations(List&lt;PlacementLocation&gt; locations)\n {\n _placementLocations = locations;\n }\n\n public Tuple&lt;int, int&gt; this[int location]\n {\n get { return new Tuple&lt;int, int&gt;(_placementLocations[location].Row, _placementLocations[location].Column); }\n }\n\n public int this[int row, int column]\n {\n get\n {\n PlacementLocation singleOrDefault =\n _placementLocations.SingleOrDefault(d =&gt; d.Column == column &amp;&amp; d.Row == row);\n return singleOrDefault != null ? singleOrDefault.Location : 0;\n }\n }\n}\n</code></pre>\n\n<p>Class should not contain particular initialization values: use constructor parameters instead and initialize externally:</p>\n\n<pre><code>...\n\nvar placementLocationList = new List&lt;PlacementLocation&gt;\n{\n new PlacementLocation { Column = 1, Row = 9, Location = 1 },\n new PlacementLocation { Column = 2, Row = 9, Location = 2 },\n new PlacementLocation { Column = 3, Row = 9, Location = 3 },\n new PlacementLocation { Column = 4, Row = 9, Location = 4 },\n new PlacementLocation { Column = 5, Row = 9, Location = 5 },\n};\n\nvar placementLocations = new PlacementLocations(placementLocationList);\n\n...\n</code></pre>\n\n<p><strong>Update:</strong>\nif you need predefined locations list you can use some sort of factory...</p>\n\n<pre><code>public class LocationsFactory\n{\n public static PlacementLocations GetPredefinedLocations()\n {\n var placementLocationList = new List&lt;PlacementLocation&gt;\n {\n new PlacementLocation { Column = 1, Row = 9, Location = 1 },\n new PlacementLocation { Column = 2, Row = 9, Location = 2 },\n new PlacementLocation { Column = 3, Row = 9, Location = 3 },\n new PlacementLocation { Column = 4, Row = 9, Location = 4 },\n new PlacementLocation { Column = 5, Row = 9, Location = 5 },\n };\n\n return new PlacementLocations(placementLocationList);\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T12:20:07.363", "Id": "47907", "Score": "1", "body": "If you make `PlacementLocations` implement `IEnumerable<PlacementLocation>` and add an `Add()` method, you could even write `new PlancementLocations { new PlacementLocation { Column = 1, Row = 9, Location = 1 }, … }`, or even `new PlancementLocations { { 1, 9, 1 }, … }` if that's what you prefer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T13:54:11.380", "Id": "47914", "Score": "0", "body": "Values ​​are fixed and can not be changed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T14:08:42.967", "Id": "47915", "Score": "0", "body": "@Sun Rise, As you see the Placements object doesn't have external setters. Only constructor - values won't change after initialization. You can use a factory to create predefined location sets." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T14:14:56.660", "Id": "47916", "Score": "0", "body": "I changed class. Whether this way is true? what is factory ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T14:27:24.053", "Id": "47919", "Score": "0", "body": "@Sun Rise, by factory I mean some class that will build particular 'Locations' instances for you, while the base 'Locations' class will not be tied to specific values." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T08:52:00.827", "Id": "30167", "ParentId": "30162", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T04:53:53.650", "Id": "30162", "Score": "1", "Tags": [ "c#", "beginner", "collections", "constructor" ], "Title": "Write a class with some properties and indexed" }
30162
<p>I have two threads, where one listens on TCP and the other renders in a loop:</p> <pre><code> private void checkBox1_CheckedChanged(object sender, EventArgs e) { try { if (ReceiveCheck.Checked) { tcplisten.Start(); ListenThread = new Thread(new ThreadStart(Listen)); ListenThread.Start(); RenderThread = new Thread(new ThreadStart(Render)); RenderThread.Start(); } else { tcplisten.Stop(); RenderThread.Abort(); ListenThread.Abort(); } } catch (Exception ex) { MessageBox.Show(ex.Message, "Checkbox"); } } </code></pre> <p>Is this a good way of handling the threads, to just start them and later kill them when I want to?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T11:44:14.123", "Id": "47904", "Score": "0", "body": "Can you clarify this \"To just start then, and kill them when i want to?\". Are you asking how to do this or is this a good way to do this?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T12:24:59.643", "Id": "47908", "Score": "1", "body": "Is there any reason you're not using the [**TPL**](http://msdn.microsoft.com/en-us/library/dd460717.aspx)? It's a very nice abstraction and it'll really help you in such cases." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T13:01:22.283", "Id": "47910", "Score": "0", "body": "@Aseem Bansal I am asking if it´s good." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T13:02:10.147", "Id": "47911", "Score": "0", "body": "@Benjamin Gruenbaum Never heard of, can you put an answer with what you mean, to display it?" } ]
[ { "body": "<p>No, this is absolutely not a good way. <code>Thread.Abort()</code> should never be used, because it is very hard to write correct code when an exception can happen at almost any point in your code.</p>\n\n<p>Instead, you should implement cooperative cancellation either by using a <code>volatile bool</code> flag, or, even better, <code>CancellationToken</code>.</p>\n\n<p>With that your code could look like this:</p>\n\n<pre><code>Thread ListenThread;\nThread RenderThread;\nCancellationTokenSource CTS;\n\nprivate void checkBox1_CheckedChanged(object sender, EventArgs e)\n{\n try\n {\n if (ReceiveCheck.Checked)\n {\n tcplisten.Start();\n CTS = new CancellationTokenSource();\n ListenThread = new Thread(() =&gt; Listen(CTS.Token)));\n ListenThread.Start();\n RenderThread = new Thread(() =&gt; Render(CTS.Token)));\n RenderThread.Start();\n }\n else\n {\n tcplisten.Stop();\n CTS.Cancel();\n }\n }\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message, \"Checkbox\");\n }\n}\n</code></pre>\n\n<p>Your <code>Listen()</code> and <code>Render()</code> methods would then periodically check <code>IsCancellationRequested</code> of the passed in token and return if it's <code>true</code>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T13:02:43.237", "Id": "47912", "Score": "0", "body": "Good to know. Though, never used any of those CancellationToken or volatile bool. Can you show an example?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T14:36:12.973", "Id": "47923", "Score": "0", "body": "@Zerowalker It's not complicated, see update." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T15:11:10.227", "Id": "47928", "Score": "0", "body": "I tried that, but it doesn´t work. Am i supposed to implement the IsCancellationRequested myself? in While loop or something?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T15:18:17.810", "Id": "47930", "Score": "0", "body": "@Zerowalker Like I said, you need to check `IsCancellationRequested` yourself. So, if you have a loop in your `Render()` method, then you should check it at the start of each iteration, or something like that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T15:18:27.197", "Id": "47931", "Score": "0", "body": "if i am supposed to do something like this: if (CTS.IsCancellationRequested)\n {\n break;\n } - Why can´t i just use my CheckBox value instead?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T16:26:38.477", "Id": "47939", "Score": "0", "body": "I guess teh difference is that CTS is implemented on each Thread, meaning if i create 10 threads, it will have 10 different CTS. This is good as it will prevent more threads than i want, many thanks:)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T18:27:21.287", "Id": "47950", "Score": "0", "body": "@Zerowalker If you want to cancel all the threads at once, then you can use just one CTS. And you don't want to use your checkbox because of separation of concerns. If you decide to change the checkbox to a button in the future, you don't want to modify `Listen()` and `Render()`, just the event handler." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T22:58:49.527", "Id": "47968", "Score": "0", "body": "isn´t that what you are doing? (putting the CTS in the threads)?, it works perfectly. Very true. But i wonder, is there a way to create and start a thread at the same time, or do i need to use 2 rows (trying to simplify the looks)?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T09:10:35.793", "Id": "47988", "Score": "0", "body": "I dont get how i am supposed to Dispose of the CTS though, if i dispose in the checkbox, it will dispose before the Threads are able to shut down." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T11:12:05.427", "Id": "47990", "Score": "0", "body": "@Zerowalker I think that under most circumstances, it's okay not to dispose the CTS." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T14:37:06.673", "Id": "48000", "Score": "0", "body": "Okay, well i got it working more or less, except i get a dispose error when i dispose on shutdown. So i simply tell the threads to catch and ignore that particular error, which i guess shouldn´t cause any harm." } ], "meta_data": { "CommentCount": "11", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T12:23:40.693", "Id": "30171", "ParentId": "30166", "Score": "5" } } ]
{ "AcceptedAnswerId": "30171", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T08:48:33.870", "Id": "30166", "Score": "0", "Tags": [ "c#", "multithreading", "tcp" ], "Title": "Threads listening on TCP and rendering in a loop" }
30166
<p>I've written an Entity Component System using C++ for my game engine. I'm still inexperienced so I've probably made a lot of mistakes. Thus I've decided to ask here for an honest review.</p> <p>The complete code is fairly large (although not too large IMHO) so it wouldn't quite fit here. Still if anyone here wishes to browse through it and give me some advice you can find the code on <a href="https://github.com/MrPlow442/Aquila-Entity-Component-System" rel="nofollow">GitHub</a>.</p> <p>However the point of this topic was to present a few dubious design choices and code parts which I'm not completely sure about.</p> <p><strong>DESIGN:</strong></p> <p>There are many ECS designs but I've chosen the one which was the easiest to grasp logically. Current design is based on Entities being Component containers, and Systems being Component processors. </p> <p>Basically Entity contains a unique id, a bitset which represents a "key" for systems (with each bit representing a component type) and a map of components. </p> <p>Components on the other hand contain only data, no methods besides constructors. </p> <p>And finally Systems contain a bitset which represents a "lock" where each bit represents a component which are registered(subscribed might be a better word) to the system. </p> <p>Now while I really like this design because it's easy to understand, it does contain a double nested loop, and if a component contains a collection then it leads to a triple nested loop. I'm worried that for a game which requires fast updates this might cause performance issues. Should I redesign the system? What would be a better design?</p> <p><strong>CODE:</strong></p> <p>There are many things I'm worried about in regards to code. </p> <p>First is that I've got a nested <code>for</code> -> <code>if</code> -> <code>for</code> -> <code>if</code> loop. Which, in my opinion, is an essence of bad code. And also the fact that it's also copied code (used twice).</p> <pre><code>void World::update() { for( auto&amp; ecsystem : m_systems ) { if( ecsystem.second-&gt;enabled() ) //if system is enabled { std::bitset&lt; 64 &gt;&amp; lockbits = ecsystem.second-&gt;getLockBits(); for( auto&amp; entity : m_entities ) { if( ( entity-&gt;getKeyBits() &amp; lockbits ) == lockbits ) { ecsystem.second-&gt;update( entity-&gt;getRelevantComponents( lockbits ) ); } } } } } void World::draw() { for( auto&amp; ecsystem : m_systems ) { if( ecsystem.second-&gt;enabled() ) { std::bitset&lt; 64 &gt;&amp; lockbits = ecsystem.second-&gt;getLockBits(); for( auto&amp; entity : m_entities ) { if( (entity-&gt;getKeyBits() &amp; lockbits) == lockbits ) { ecsystem.second-&gt;draw( entity-&gt;getRelevantComponents( lockbits ) ); } } } } } </code></pre> <p>Both methods (<code>update()</code> and <code>draw()</code>) must have 0 parameters (though I'm planning on adding a time step parameter to update method later on) and I thought that I might somehow create a single method which iterates over all systems and entities. But since the end call to each systems update or draw method is made from within the system itself, I can't think of a way to make the iteration more ambiguous. </p> <p>Second is that <code>getRelevantComponents</code> call. I've got a separate class called <code>ComponentProvider</code> which provides relevant components to users of the system. Basically to make sure that whoever is creating new systems can't use components which aren't registered to that system. The way <code>getRelevantComponents( bitset&lt;64&gt; lockbits )</code> works is that it creates an instance of <code>ComponentProvider</code> class, then adds the pointers of entity's relevant components and then returns that <code>ComponentProvider</code> instance.</p> <pre><code>ComponentProvider Entity::getRelevantComponents( std::bitset&lt; 64 &gt;&amp; lockBits ) { ComponentProvider provider; for( auto&amp; mapItem : m_componentMap ) { auto key = mapItem.first; if( lockBits.test( key ) ) { provider.m_relevantComponentMap.insert( std::make_pair( key, mapItem.second) ); } } return provider; } </code></pre> <p>Now what worries me the most in this code is that I'm returning an object instanced in the method itself. The result of the method call is thrown as a parameter to another method. I thought that I should make an rvalue assignment operator overload so that the values won't be copied but instead swapped, however I've been told that I should use the copy-swap idiom instead and leave it to RVO to handle the optimizations. Is that really a good idea?</p> <p>Third is the fact that I'm using shared pointers a lot. I'm afraid of shared pointer overhead as well as slowdowns since new shared pointers are being created and destroyed every update cycle. Should I use raw pointers instead and just be very careful of memory leaks?</p> <p>Fourth is that I'm using a map to contain all systems since I need to be able to remove specific systems and not allow adding more systems of the same type, but I also need to iterate over all systems each update cycle so I'm worried if it was really a good idea to use a map( instead of an unordered map since as far as I know normal map is contiguous ) instead of a vector. I've also read that unordered_map is faster than normal map in every case so I'm not sure at what I should use really.</p> <p>Those are my largest worries right now. Please let me know if my post is hard to understand and I'll try to explain things better.</p>
[]
[ { "body": "<p>With regards to returning <code>ComponentProvider</code> by value from <code>getRelevantComponents</code> if you have a move constructor defined (or the default move constructor is generated) the return is likely to be moved instead of copied and you won't have to worry about it at all.</p>\n\n<p>You might consider writing a member function for <code>entity</code> called <code>Validate</code> or similar which takes <code>std::bitset&lt;64&gt;&amp;</code> and performs the check:</p>\n\n<pre><code>bool Validate(const std::bitset&lt;64&gt;&amp; lockbits) const\n{\n return ( entity-&gt;getKeyBits() &amp; lockbits ) == lockbits;\n}\n</code></pre>\n\n<p>This will reduce code duplication ever so slightly and if your validation rules ever change you only have to change it once in the member function and not both in <code>update</code> and <code>draw</code> and anywhere else.</p>\n\n<p>I'm tempted to suggest moving your for loops into member functions in <code>ecsystem</code>, but that would require introducing a dependency between <code>ecsystem</code> and <code>entity</code> so probably isn't worth doing.</p>\n\n<p><strong>Edit</strong>\nYou can probably replace some of <code>getRelevantComponents</code> with <code>std::copy_if</code></p>\n\n<pre><code>ComponentProvider Entity::getRelevantComponents( std::bitset&lt; 64 &gt;&amp; lockBits )\n{\n ComponentProvider provider;\n\n std::copy_if(\n std::begin(m_componentMap),\n std::end(m_componentMap),\n std::begin(provider.m_relevantComponentMap),\n [&amp;lockBits](std::pair&lt;keyType, valueType&gt; &amp; mapItem)\n {\n return lockBits.test(mapItem.first);\n });\n\n return provider;\n}\n</code></pre>\n\n<p>This of course assumes that provider.m_relevantComponentMap is the same type as m_componentMap.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-14T18:50:00.390", "Id": "44384", "ParentId": "30170", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T12:14:43.117", "Id": "30170", "Score": "8", "Tags": [ "c++", "c++11", "entity-component-system" ], "Title": "Entity Component System in C++" }
30170
<p>I made this simple chat in php. You have suggestions on how I can improve it?</p> <p>This file configures the connection to the server</p> <p>This file is a simple form "login" ( only username required )</p> <pre><code> &lt;form action="chat.php" method = "post"&gt; Username: &lt;input type="text" name="nick"/&gt;&lt;br /&gt; &lt;input type="submit" name="button" value="Go"/&gt; &lt;/form&gt; &lt;?php include('connessione.php'); if(isset($_POST['button'])) { $Username = $_POST['nick']; $Username = mysql_real_escape_string($Username); $Query = "INSERT INTO users (NickName) VALUES ($Username)"; if(!$Query) { } else { "Error performing query!".mysql_error(); } } ?&gt; </code></pre> <p>This file is the chat!</p> <pre><code>&lt;script type="text/javascript" src="chat.js"&gt;&lt;/script&gt; &lt;style type="text/css"&gt; .tastiera { width:500px; height:50px; border-radius:5px; border:1px solid #999; overflow:auto; font-size:13px; .chat { width:500px; height:6000px; border-radius:5px; border:1px solid #999; overflow:auto; font-size:13px; } &lt;/style&gt; &lt;?php include('connessione.php'); session_start (); if($_SESSION['nick'] == “”){ echo "You are not authorized to enter!"; } exit(); header('Cache-Control: Private'); ?&gt; &lt;div id="CHAT"&gt;&lt;/div&gt; &lt;form action="salvataggio.php" name="inserimento" method="post" onsubmit=”javascript:location.reload();”&gt; &lt;input type="text" name="messaggio" width="500" height="50"/&gt; &lt;input type="submit" value="Chat"/&gt; &lt;/form&gt; &lt;iframe src="messaggio.php" name="MSG" id="MSG"&gt;&lt;/iframe&gt; </code></pre> <p>This Ajax file Update the chat</p> <pre><code> function Update() { return Request(); } window.setInterval("Update()", 3000) var XMLHTTP; function Request() { XMLHTTP = GetBrowser(ChangeStatus); XMLHTTP.open("GET", "ajax.php", true); XMLHTTP.send(null); } function ChangeStatus() { if (XMLHTTP.readyState == 4) { var R = document.getElementById("CHAT"); R.innerHTML = XMLHTTP.responseText; } } function GetBrowser(FindBrowser) { if (navigator.userAgent.indexOf("MSIE") != (-1)) { var Class = "Msxml2.XMLHTTP"; if (navigator.appVersion.indexOf("MSIE 5.5") != (-1)); { Class = "Microsoft.XMLHTTP"; } try { ObjXMLHTTP = new ActiveXObject(Class); ObjXMLHTTP.onreadystatechange = FindBrowser; return ObjXMLHTTP; } catch(e) { alert("attenzione: l'ActiveX non sarà eseguito!"); } } else if (navigator.userAgent.indexOf("Mozilla") != (-1)) { ObjXMLHTTP = new XMLHttpRequest(); ObjXMLHTTP.onload = FindBrowser; ObjXMLHTTP.onerror = FindBrowser; return ObjXMLHTTP; } else { alert("L'esempio non funziona con altri browser!"); } } </code></pre> <p>This file save into database the messages</p> <pre><code>&lt;?php @session_start(); if(!isset($_SESSION['nick'])){ @header('Location:prechat.php'); }else{ if(isset($_POST['messaggio'])){ include 'connessione.php'; $user = $_SESSION['nick']; $mex_chat = addslashes($_POST['messaggio']); $query = "INSERT INTO utenti (user, mex_chat) VALUES ('$user','$mex_chat')"; @mysql_query($query)or die (mysql_error()); @mysql_close(); @header('Location:chat.php'); } } </code></pre> <p>This file display the messages</p> <pre><code>$sql = "SELECT user, mex_chat FROM utenti ORDER BY id_chat DESC LIMIT 0,10"; $sql_res = @mysql_query($sql)or die (mysql_error()); if(@mysql_num_rows($sql_res)&gt;0) { while ($fetch = @mysql_fetch_array($sql_res)) { $utente = stripslashes($fetch['user_chat']); $mex_utente = stripslashes($fetch['mex_chat']); echo '&lt;b&gt;'. $utente .'&lt;/b&gt;: '. $mex_utente.'&lt;br /&gt;'; } }else{ echo 'Non sono stati ancora inseriti dei messaggi.'; } ?&gt; </code></pre> <p>What do you think? How can I improve or resolve any bugs ( if there are ) ?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T17:23:36.750", "Id": "47948", "Score": "0", "body": "If you aren't sure if this is working 100%, then come back when you have fixed it." } ]
[ { "body": "<p>If I'm reading this right, your AJAX grabs the whole chat every 3 seconds and (re)displays it. IMO, it'd be much better to send some info on the last message you have (timestamp or something), and then fetch only newer messages if there are any (via JSON; format them on the client side). That would reduce the load on the network which, given the short update interval, might be significant for both your and your users' bandwidth.</p>\n\n<p>I suggest posting messages via AJAX as well, so that the page never gets reloaded. It's more pleasant for the user (and requires less network load, if done properly).</p>\n\n<p>And, of course, <a href=\"https://stackoverflow.com/q/12859942/1667018\"><strong>lose the <code>mysql_*</code> functions!</strong></a> These are insecure and depricated, and are to be abandoned soon. I prefer PDO, but you can also go for <code>mysqli_*</code> functions. Your current code is wide open for attacks.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T20:24:31.130", "Id": "30187", "ParentId": "30176", "Score": "3" } }, { "body": "<p>Actually Vedran, mysql functions aren't insecure when done properly. in this particulary case though, he is wide open.</p>\n\n<p>should be like this</p>\n\n<pre><code> if(isset($_POST['button'])) {\n $Username = mysql_real_escape_string(strip_tags($_POST[\"Username\"]));\n $Query = \"INSERT INTO users (NickName) VALUES ($Username)\";\n if(!$Query) {\n }\n else {\n \"Error performing query!\".mysql_error();\n }\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T01:30:40.940", "Id": "56822", "Score": "0", "body": "There's three major flaws in this code: `$Username` should be quoted in the query (`VALUES (`$Username`)`), and the `if (!$Query)` isn't actually doing anything. That's checking if the string `Query` is false. The query isn't actually run anywhere in this code. The other flaw is that the strip tags doesn't make sense. Just use a white list to only allow certain characters. No point in allowing `<b>user</b>` to silently create the user `user`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-19T00:01:17.513", "Id": "57889", "Score": "0", "body": "ah, thanks. i always strip tags just in case. i do realize i'm probably alone in this, but i take the better safe than sorry approach. as far as your other concerns, i was only intending to show him the use of my_sql_real_escape_string, not necessarily moderating the syntax of his actual queries. i like to use @mysql_query for queries and the reserved variable $sql but thats an entirely different debate." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-10T00:35:40.213", "Id": "35110", "ParentId": "30176", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T09:27:59.760", "Id": "30176", "Score": "2", "Tags": [ "php", "javascript", "html", "mysql", "ajax" ], "Title": "Chat with PHP, MySql, Ajax: How to improve it?" }
30176
<p>Is there anyway to make this piece of code more elegant? It's not a nice view, but I can't really see a way to improve the looks of it or shorten it.</p> <pre><code>private void Send(CancellationToken CTSSend) { try { NativeMethods.Rect rc; NativeMethods.GetWindowRect(hwnd, out rc); IntPtr dc1; IntPtr dc2 = NativeMethods.GetWindowDC(hwnd); using (tcp = new TcpClient()) { tcp.NoDelay = true; while (!tcp.Connected &amp;&amp; !CTSSend.IsCancellationRequested) { try { if (!tcp.Connected) tcp.Connect(adress); } catch (Exception e) { if (e is SocketException) { Console.WriteLine(e.Message); } else MessageBox.Show(e.Message + " Tcp Connect : Send"); } } using (EncoderParameters JpegParam = new EncoderParameters()) using (JpegParam.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, 50L)) using (Bitmap bmp = new Bitmap(rc.Width, rc.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb)) using (Graphics g = Graphics.FromImage(bmp)) using (var ms = new MemoryStream()) using (var tcpStream = tcp.GetStream()) while (tcp.Connected &amp;&amp; !CTSSend.IsCancellationRequested) { try { dc1 = g.GetHdc(); NativeMethods.BitBlt(dc1, 0, 0, rc.Width, rc.Height, dc2, 0, 0, 13369376); g.ReleaseHdc(dc1); bmp.Save(ms, jpeg, JpegParam); if (bsize != ms.Length) { bsize = ms.Length; tcpStream.Write(BitConverter.GetBytes(bsize), 0, 4); tcpStream.Write(ms.GetBuffer(), 0, (int)bsize); } ms.SetLength(0); } catch (Exception e) { if (e is IOException) { try { connect.Invoke(new Action(() =&gt; { connect.Text = "Connect"; })); } catch (InvalidOperationException) { return; } capcon = false; } else MessageBox.Show(e.Message + ": Send Error"); } } } } catch (Exception e) { MessageBox.Show(e.Message + "SEND"); } } </code></pre> <p>I am trying to find a nice way to put TCP reconnecting in another class, but I found a limitation where I have to call <code>return</code> in the main class.</p> <pre><code>internal static void TCPReconnect(CancellationToken CTS, TcpClient tcp, IPEndPoint adress) { tcp.NoDelay = true; while (!tcp.Connected &amp;&amp; !CTS.IsCancellationRequested) { try { if (!tcp.Connected) tcp.Connect(adress); } catch (Exception e) { if (e is SocketException) { Console.WriteLine(e.Message); } else MessageBox.Show(e.Message + " Tcp Connect : Send"); } } } </code></pre> <p>So, when it fails, it goes out of the loop. I can also make it call <code>Return</code>, but it will do the same thing.</p> <p>In the class <code>Caller</code> I have to use:</p> <pre><code>FastMethods.TCPReconnect(CTS, tcp, adress); if (CTS.IsCancellationRequested) return; </code></pre> <p>As you can see, I have to recheck for CTS. Is it possible to have it inside the other class somehow?</p> <p>If I use:</p> <pre><code>if (CTS.IsCancellationRequested) return; </code></pre> <p>It will simply return to the main class and continue.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T18:54:49.580", "Id": "47953", "Score": "0", "body": "First of all, you should apply separation of concerns. Encoding images and network communication shouldn't be in the same method, probably not even in the same class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T20:11:24.880", "Id": "47956", "Score": "0", "body": "that would probably slow things down, as i am sending the image i take. If i seperate this, it would get out of order." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T23:18:23.230", "Id": "47970", "Score": "1", "body": "\"that would probably slow things down\" - A classic illustration of premature optimization mindset. The original question addresses a clear problem with the code and I assert debugging and maintenance in the current state will be much more of a problem than *presumed* performance degradation caused by refactoring. @svick's advice is sound. I suggest you start by \"extracting to methods\". As methods it is more flexible to re-work - getting to separation of concerns and manage the concern about \"out of order.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T00:12:04.290", "Id": "47972", "Score": "0", "body": "I had them in Methods before, but i don´t really like having codes all over the place when i can have then at the same place. Though if i reuse the code in alot of places, i do have them in methods. But here, there is really no reason for me to put it in a method or separate class. I can however put the Image Encoding in a separate thread." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T00:55:45.373", "Id": "47974", "Score": "0", "body": "Though, again, I can put the TCP Reconnecting in a Method, as that just takes place for no big reason." } ]
[ { "body": "<p>A couple of comments:</p>\n\n<ul>\n<li>Shortening code is not a goal - readability and maintainability is (which may, but not neccessarily, shorten it).</li>\n<li>The code mixes net code, graphics code, encoder code and UI code. Separating these into separate functions/classes will be <em>very</em> good. Just remember that (as a general rule), one function should do one thing.</li>\n<li><p>Always use braces, even when it's for a single statement where it's not required.</p>\n\n<pre><code>if (!tcp.Connected)\n{\n tcp.Connect(adress);\n}\n</code></pre></li>\n<li><p>Similarly, I'd suggest putting brackets around the <code>!xxx</code> in the if statement. Not needed, but can aid understandability.</p>\n\n<pre><code>while ((!tcp.Connected) &amp;&amp; (!CTS.IsCancellationRequested))\n</code></pre></li>\n<li>What does 13369376 represent? Define the set of constants (SRCCOPY etc) that you're using and then use those.</li>\n<li><code>TcpClient.Connect</code> is a blocking call - depending on your use, you may want to consider rewriting using <code>BeginConnect</code> instead. One problem is that when in the middle of a <code>connect</code>, you can not check <code>CTSSend</code> for a cancellation.</li>\n<li>You need to rethink your exception handling. At the moment, your code puts up a message box, requiring a response. You do not want to mix UI and non-UI code like this</li>\n<li>The exception-catching occurs in the middle of a loop, so if it happens once, it's likely to happen again and again...each time requiring acknowledgement of the message box.</li>\n<li>Catch specific exceptions (SocketException) rather than general ones (Exception). You can have multiple <code>catch</code>es if you need them.</li>\n<li>If you're using <code>bsize</code> to determine if the screen has changed, it'll be unreliable. You might end up with two images that have the same size even if the images are different.</li>\n<li>The code grabs images as quickly as possible, possibly discarding most of them (if my understanding is correct) - this seems uneccessary. Why not grab an image (say) every 1 second? In which case you can set up something like a <code>System.Timers.Timer</code> instance and get the image when that is triggered.</li>\n<li>You should probably allocate a new <code>MemoryStream</code>, rather than reusing it. If you're doing that to \"save time\", it 'probably' doesn't matter compared with the speed of network traffic and image conversion.</li>\n<li>What happens when the window size changes/minimized etc, or is it guaranteed to have a fixed size?</li>\n<li>In regards to your edit: Rather than a <code>void</code> return, either return a <code>bool</code> or (preferably) define an enum (CancelRequested, Connected) and return that.</li>\n</ul>\n\n<p>Edit in response to (first) comment:</p>\n\n<ol>\n<li>If you have 10 stacked braces at the end of the method, the method is too long. Break it up rather than remove the braces.</li>\n<li>re <code>MemoryStream</code> - it'll gain readability. One thing though that you may want to do is to set an initial capacity (say, <code>rc.Width*rc.Height</code>) - <code>MemoryStream</code> itself reallocates memory/copies data on resizing.</li>\n<li>Have you tried using a different image format, say png, rather than jpeg. It may be quicker to compress or smaller, depending on the type of image.</li>\n<li>You could also try spliting the image up into quandrants/etc, compressing &amp; sending those and reassembling them at the other side. It may be overall quicker.</li>\n<li>And of course, if you want 'quicker', always base it on actual timings rather than feelings :)</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T12:53:55.583", "Id": "47995", "Score": "0", "body": "Very well written, some nice things to think about. I though prefer to not use Brackets, as i hate when there are like 10 stacked brackets ad the end of the Method. And the MemoryStream, i see no reason remaking it if i don´t earn anyhing on it, As the thing is, i need to take images as fast as possible, and currently, The Network does Not limit it, there is always one image in, one image out, Delation only occured if i use .BMP (the images goes to fast then, and are to large, And i can´t prevent duplicated send images)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T20:31:46.173", "Id": "48006", "Score": "0", "body": "Not sure about the always use brackets suggestion. That's a bit restrictive I think, although I must admit when in doubt I would probably always use them" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T15:18:59.533", "Id": "48073", "Score": "0", "body": "Well, it´s hard to break up, as i need all of them to do one thing. It´s a very bad weird thing, for example, to use Jpeg encoding, you have to have 2 Usings, 1 for the encoding parameter, and 1 for settings that parameter. That´s just irritating, but needed., Interesting idea to divide the image, may be worth looking into." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T11:20:40.657", "Id": "30209", "ParentId": "30177", "Score": "7" } } ]
{ "AcceptedAnswerId": "30209", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T16:48:46.883", "Id": "30177", "Score": "2", "Tags": [ "c#", "tcp" ], "Title": "TCP connection and reconnection" }
30177
<p>I'd like this improved.</p> <pre><code>&lt;!DOCTYPE html&gt; &lt;html lang="en"&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;title&gt;Add New Games&lt;/title&gt; &lt;meta name="viewport" content="width=device-width, initial-scale=1.0"&gt; &lt;meta name="description" content=""&gt; &lt;meta name="author" content=""&gt; &lt;!-- Le styles --&gt; &lt;link href="css/bootstrap.css" rel="stylesheet"&gt; &lt;style&gt; body { padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */ } &lt;/style&gt; &lt;link href="css/bootstrap-responsive.css" rel="stylesheet"&gt; &lt;!-- HTML5 shim, for IE6-8 support of HTML5 elements --&gt; &lt;!--[if lt IE 9]&gt; &lt;script src="js/html5shiv.js"&gt;&lt;/script&gt; &lt;![endif]--&gt; &lt;!-- Fav and touch icons --&gt; &lt;link rel="apple-touch-icon-precomposed" sizes="144x144" href="ico/apple-touch-icon-144-precomposed.png"&gt; &lt;link rel="apple-touch-icon-precomposed" sizes="114x114" href="ico/apple-touch-icon-114-precomposed.png"&gt; &lt;link rel="apple-touch-icon-precomposed" sizes="72x72" href="ico/apple-touch-icon-72-precomposed.png"&gt; &lt;link rel="apple-touch-icon-precomposed" href="ico/apple-touch-icon-57-precomposed.png"&gt; &lt;link rel="shortcut icon" href="ico/favicon.png"&gt; &lt;/head&gt; &lt;body&gt; &lt;div class="navbar navbar-inverse navbar-fixed-top"&gt; &lt;div class="navbar-inner"&gt; &lt;div class="container"&gt; &lt;button type="button" class="btn btn-navbar" data-toggle="collapse" data-target=".nav-collapse"&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;span class="icon-bar"&gt;&lt;/span&gt; &lt;/button&gt; &lt;a class="brand" href="#"&gt;Game Admin Area&lt;/a&gt; &lt;div class="nav-collapse collapse"&gt; &lt;ul class="nav"&gt; &lt;li class="active"&gt;&lt;a href="#"&gt;Add New Games&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#about"&gt;Update Game Scores&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#contact"&gt;Reports&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/div&gt;&lt;!--/.nav-collapse --&gt; &lt;/div&gt; &lt;/div&gt; &lt;/div&gt; &lt;div class="container"&gt; &lt;h1&gt;Add New Games to Database&lt;/h1&gt; &lt;p&gt;Use the form below to quickly add upcoming games to the database.&lt;br&gt;Players will not be able to place their predictions until you inputted these games.&lt;/p&gt; &lt;?php $dbc = mysql_connect(,,); $db = mysql_select_db(); $results= mysql_query("SELECT * FROM tbl_teams"); $myHTML = ''; while($row = mysql_fetch_array($results)) { $myHTML .= '&lt;option value="'.$row['team_ID'].'"&gt;'. $row['team_name'].'&lt;/option&gt;'; } $myHTMLdate = ''; for($i = 1; $i &lt;= 14; $i ++){ $startdate = strtotime("today + $i day"); $myHTMLdate .= '&lt;option value="'.date('Y-m-d', $startdate).'"&gt;'.date('l', $startdate).', '.date('d M Y', $startdate).'&lt;/option&gt;'; } ?&gt; &lt;div id="wrapper"&gt; &lt;div class="datagrid"&gt; &lt;table class="table table-striped table-bordered table-condensed"&gt; &lt;thead&gt; &lt;tr&gt; &lt;th&gt;Game No.&lt;/th&gt; &lt;th&gt;Team 1&lt;/th&gt; &lt;th&gt;Vs.&lt;/th&gt; &lt;th&gt;Team 2&lt;/th&gt; &lt;th&gt;Game Date&lt;/th&gt; &lt;/tr&gt; &lt;/thead&gt; &lt;tbody&gt; &lt;?php for ($i=1; $i &lt;=30; $i++) { echo "&lt;tr&gt; &lt;td&gt;".$i."&lt;/td&gt; &lt;td&gt;&lt;select name='game".$i."_team1'&gt;".$myHTML."&lt;/select&gt;&lt;/td&gt; &lt;td&gt;Vs.&lt;/td&gt; &lt;td&gt;&lt;select name='game".$i."_team2'&gt;".$myHTML."&lt;/select&gt;&lt;/td&gt; &lt;td&gt;&lt;select name='game".$i."_date'&gt;".$myHTMLdate."&lt;/select&gt;&lt;/td&gt; &lt;/tr&gt;"; } ?&gt; &lt;/tbody&gt; &lt;/table&gt; &lt;button class="btn btn-large btn-primary" type="submit"&gt;Send these games to the server!&lt;/button&gt; &lt;/div&gt; &lt;/form&gt; &lt;/div&gt; &lt;!-- /container --&gt; &lt;!-- Javascript --&gt; &lt;!-- Placed at the end of the document so the pages load faster --&gt; &lt;script src="js/jquery.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap-transition.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap-alert.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap-modal.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap-dropdown.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap-scrollspy.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap-tab.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap-tooltip.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap-popover.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap-button.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap-collapse.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap-carousel.js"&gt;&lt;/script&gt; &lt;script src="js/bootstrap-typeahead.js"&gt;&lt;/script&gt; &lt;/body&gt; &lt;/html&gt; </code></pre>
[]
[ { "body": "<p>First of all, I'm not a fan of having one single page with everything -- I typically prefer to separate my HTML from my PHP.</p>\n\n<p>Putting that aside:</p>\n\n<pre><code>$dbc = mysql_connect(,,);\n</code></pre>\n\n<p>The documentation for <a href=\"http://php.net/manual/en/function.mysql-connect.php\" rel=\"nofollow\">mysql_connect</a> says:</p>\n\n<blockquote>\n <p>This extension is deprecated as of PHP 5.5.0, and will be removed in\n the future. Instead, the MySQLi or PDO_MySQL extension should be used.\n See also MySQL: choosing an API guide and related FAQ for more\n information.</p>\n</blockquote>\n\n<p>Generally speaking, when starting a new project, it's a bad idea to use deprecated APIs.</p>\n\n<p>Besides, I assume you just removed the parameters from the function and you have <code>mysql_connect(\"myserver\", \"myusername\", \"mypassword\")</code>. I wouldn't recommend having passwords in the same file as the rest of the code. Use a configuration file instead.</p>\n\n<pre><code> $myHTML .= '&lt;option value=\"'.$row['team_ID'].'\"&gt;'. $row['team_name'].'&lt;/option&gt;';\n</code></pre>\n\n<p>Are you familiar with <a href=\"http://en.wikipedia.org/wiki/Cross-site_scripting\" rel=\"nofollow\">XSS injections</a>? Is it possible someone could create a new team with a name like <code>&lt;script&gt;/*do bad stuff here*/&lt;/script&gt;</code>?</p>\n\n<p>You close a form(<code>&lt;/form&gt;</code>) but I don't see you opening it. This is not valid HTML. Did you forget to add it?</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T17:51:18.187", "Id": "30182", "ParentId": "30178", "Score": "4" } }, { "body": "<ul>\n<li>This isn't really something you did wrong, but it will make managing the site easier if you break it into chunks and include those. For example, if you broke the header, navbar, and footer out into PHP files you can include them in multiple pages and have one spot to edit them from. For example:</li>\n</ul>\n\n<p>header.php</p>\n\n<pre><code>&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n &lt;head&gt;\n &lt;meta charset=\"utf-8\"&gt;\n &lt;title&gt;Add New Games&lt;/title&gt;\n &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"&gt;\n &lt;meta name=\"description\" content=\"\"&gt;\n &lt;meta name=\"author\" content=\"\"&gt;\n\n &lt;!-- Le styles --&gt;\n &lt;link href=\"css/bootstrap.css\" rel=\"stylesheet\"&gt;\n &lt;style&gt;\n body {\n padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */\n }\n &lt;/style&gt;\n &lt;link href=\"css/bootstrap-responsive.css\" rel=\"stylesheet\"&gt;\n\n &lt;!-- HTML5 shim, for IE6-8 support of HTML5 elements --&gt;\n &lt;!--[if lt IE 9]&gt;\n &lt;script src=\"js/html5shiv.js\"&gt;&lt;/script&gt;\n &lt;![endif]--&gt;\n\n &lt;!-- Fav and touch icons --&gt;\n &lt;link rel=\"apple-touch-icon-precomposed\" sizes=\"144x144\" href=\"ico/apple-touch-icon-144-precomposed.png\"&gt;\n &lt;link rel=\"apple-touch-icon-precomposed\" sizes=\"114x114\" href=\"ico/apple-touch-icon-114-precomposed.png\"&gt;\n &lt;link rel=\"apple-touch-icon-precomposed\" sizes=\"72x72\" href=\"ico/apple-touch-icon-72-precomposed.png\"&gt;\n &lt;link rel=\"apple-touch-icon-precomposed\" href=\"ico/apple-touch-icon-57-precomposed.png\"&gt;\n &lt;link rel=\"shortcut icon\" href=\"ico/favicon.png\"&gt;\n &lt;/head&gt;\n &lt;body&gt;\n</code></pre>\n\n<p>navbar.php</p>\n\n<pre><code> &lt;div class=\"navbar navbar-inverse navbar-fixed-top\"&gt;\n &lt;div class=\"navbar-inner\"&gt;\n &lt;div class=\"container\"&gt;\n &lt;button type=\"button\" class=\"btn btn-navbar\" data-toggle=\"collapse\" data-target=\".nav-collapse\"&gt;\n &lt;span class=\"icon-bar\"&gt;&lt;/span&gt;\n &lt;span class=\"icon-bar\"&gt;&lt;/span&gt;\n &lt;span class=\"icon-bar\"&gt;&lt;/span&gt;\n &lt;/button&gt;\n &lt;a class=\"brand\" href=\"#\"&gt;Game Admin Area&lt;/a&gt;\n &lt;div class=\"nav-collapse collapse\"&gt;\n &lt;ul class=\"nav\"&gt;\n &lt;li class=\"active\"&gt;&lt;a href=\"#\"&gt;Add New Games&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#about\"&gt;Update Game Scores&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#contact\"&gt;Reports&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;&lt;!--/.nav-collapse --&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n</code></pre>\n\n<p>footer.php</p>\n\n<pre><code> &lt;!-- Javascript --&gt;\n &lt;!-- Placed at the end of the document so the pages load faster --&gt;\n &lt;script src=\"js/jquery.js\"&gt;&lt;/script&gt;\n &lt;script src=\"js/bootstrap-transition.js\"&gt;&lt;/script&gt;\n &lt;script src=\"js/bootstrap-alert.js\"&gt;&lt;/script&gt;\n &lt;script src=\"js/bootstrap-modal.js\"&gt;&lt;/script&gt;\n &lt;script src=\"js/bootstrap-dropdown.js\"&gt;&lt;/script&gt;\n &lt;script src=\"js/bootstrap-scrollspy.js\"&gt;&lt;/script&gt;\n &lt;script src=\"js/bootstrap-tab.js\"&gt;&lt;/script&gt;\n &lt;script src=\"js/bootstrap-tooltip.js\"&gt;&lt;/script&gt;\n &lt;script src=\"js/bootstrap-popover.js\"&gt;&lt;/script&gt;\n &lt;script src=\"js/bootstrap-button.js\"&gt;&lt;/script&gt;\n &lt;script src=\"js/bootstrap-collapse.js\"&gt;&lt;/script&gt;\n &lt;script src=\"js/bootstrap-carousel.js\"&gt;&lt;/script&gt;\n &lt;script src=\"js/bootstrap-typeahead.js\"&gt;&lt;/script&gt;\n\n &lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n\n<p>index.php</p>\n\n<pre><code>&lt;?php include_once('header.php'); ?&gt;\n&lt;?php include_once('navbar.php'); ?&gt;\n&lt;div class=\"container\"&gt;\n &lt;h1&gt;Add New Games to Database&lt;/h1&gt;\n &lt;p&gt;Use the form below to quickly add upcoming games to the database.&lt;br&gt;Players will not be able to place their predictions until you inputted these games.&lt;/p&gt;\n &lt;?php\n $dbc = mysql_connect(,,);\n $db = mysql_select_db();\n $results= mysql_query(\"SELECT * FROM tbl_teams\");\n\n $myHTML = '';\n while($row = mysql_fetch_array($results)) {\n $myHTML .= '&lt;option value=\"'.$row['team_ID'].'\"&gt;'. $row['team_name'].'&lt;/option&gt;';\n }\n $myHTMLdate = '';\n for($i = 1; $i &lt;= 14; $i ++){\n $startdate = strtotime(\"today + $i day\");\n $myHTMLdate .= '&lt;option value=\"'.date('Y-m-d', $startdate).'\"&gt;'.date('l', $startdate).', '.date('d M Y', $startdate).'&lt;/option&gt;';\n }\n\n ?&gt;\n &lt;div id=\"wrapper\"&gt;\n &lt;div class=\"datagrid\"&gt;\n &lt;table class=\"table table-striped table-bordered table-condensed\"&gt;\n &lt;thead&gt;\n &lt;tr&gt;\n &lt;th&gt;Game No.&lt;/th&gt;\n &lt;th&gt;Team 1&lt;/th&gt;\n &lt;th&gt;Vs.&lt;/th&gt;\n &lt;th&gt;Team 2&lt;/th&gt;\n &lt;th&gt;Game Date&lt;/th&gt;\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n &lt;?php\n for ($i=1; $i &lt;=30; $i++) {\n echo \"&lt;tr&gt;\n &lt;td&gt;\".$i.\"&lt;/td&gt;\n &lt;td&gt;&lt;select name='game\".$i.\"_team1'&gt;\".$myHTML.\"&lt;/select&gt;&lt;/td&gt;\n &lt;td&gt;Vs.&lt;/td&gt;\n &lt;td&gt;&lt;select name='game\".$i.\"_team2'&gt;\".$myHTML.\"&lt;/select&gt;&lt;/td&gt;\n &lt;td&gt;&lt;select name='game\".$i.\"_date'&gt;\".$myHTMLdate.\"&lt;/select&gt;&lt;/td&gt;\n &lt;/tr&gt;\";\n }\n ?&gt;\n &lt;/tbody&gt;\n &lt;/table&gt;\n &lt;button class=\"btn btn-large btn-primary\" type=\"submit\"&gt;Send these games to the server!&lt;/button&gt;\n &lt;/div&gt;\n &lt;/form&gt;\n &lt;/div&gt;\n&lt;!-- /container --&gt;\n\n&lt;?php include_once('footer.php'); ?&gt;\n</code></pre>\n\n<ul>\n<li><p>As luiscubal mentioned, use a different method of connecting to the\ndatabase. mysql_connect() is deprecated. <a href=\"http://php.net/manual/en/book.pdo.php\" rel=\"nofollow noreferrer\">PDO</a> and <a href=\"http://php.net/manual/en/book.mysqli.php\" rel=\"nofollow noreferrer\">mysqli</a> are\nboth good options, my personal preference is PDO though because it\nhas the ability to swap out the database type (MySQL to SQLite) and\nstill use the same method calls.</p></li>\n<li><p>Your query does a \"SELECT *\". You should consider listing out the columns so that you only pull what you need. This will keep things snappier because you won't be pulling information you don't need to render on this page. <a href=\"https://stackoverflow.com/questions/3639861/why-is-select-considered-harmful#answer-3639964\">This is a pretty good answer with some more reasons to not use \"SELECT *\"</a>, most of which are not relevant to this simple of a page. </p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T01:10:32.937", "Id": "30230", "ParentId": "30178", "Score": "2" } }, { "body": "<p>Here is some more food for thought.</p>\n\n<p><strong>Try not to create spaghetti code</strong> (database calls intermingled with html). </p>\n\n<p>It becomes very hard to maintain. I have moved your php database code to the top of the file, that way you can catch errors, and handle them before you display any html.</p>\n\n<p><strong>Splitting you file into parts</strong></p>\n\n<p>Put your database configuration into a separate file and include it. (others have mentioned this too)</p>\n\n<p>If you do repeat your navbar and header and footer on other pages, then a good idea to split files and include them, so you are not repeating code/markup again. Other have mentioned this too.</p>\n\n<p><strong>Mysql/Database</strong></p>\n\n<p>Others have mentioned that mysql is deprecated, so I am not going to revisit that.</p>\n\n<p>Use mysql_fetch_assoc not mysql_fetch_array, you can read the manual for the differences, but in your particular case mysql_fetch_array is not necessary.</p>\n\n<p>Check for mysql_error() after database calls. \nIn the code below I have thrown exceptions, that is not necessary, but does make it easy to handle all errors in one place.</p>\n\n<p>It is also quite common to catch mysql errors like this</p>\n\n<pre><code>$results= mysql_query(\"SELECT * FROM tbl_teams\") or die (mysql_error());\n</code></pre>\n\n<p><strong>html/css/js</strong></p>\n\n<p>Wrap any html you render in htmlentities() in case the data contains characters like this &lt; > as these will break your html</p>\n\n<p>Bootstrap includes a bootstrap-min.js which has all the plugins you have in 1 file, this will speed up load times. </p>\n\n<p>Also jquery-min.js will speed up load times</p>\n\n<p>Bootstrap 2 is not deprecated, but bootstrap 3 has been released, if you want to go with the latest and greatest.</p>\n\n<pre><code>&lt;?php\n\n try {\n $dbc = mysql_connect($host, $user, $pass);\n\n if (mysql_error()) {\n throw new Exception(\"Database Connection Failed: \" . mysql_error());\n }\n\n $db = mysql_select_db($dbname);\n\n if (mysql_error()) {\n throw new Exception(\"Database Select DB Failed: \" . mysql_error());\n }\n\n $results= mysql_query(\"SELECT * FROM tbl_teams\");\n\n if (mysql_error()) {\n throw new Exception(\"Database Query Failed: \" . mysql_error());\n }\n\n $myHTML = '';\n // use mysql_fetch_assoc not mysql_fetch_array\n while($row = mysql_fetch_assoc($results)) {\n\n // wrap in html entities in case team names include &lt; &gt;, etc as these will break your html\n $myHTML .= '&lt;option value=\"'.$row['team_ID'].'\"&gt;'. htmlentities($row['team_name']).'&lt;/option&gt;';\n }\n\n $myHTMLdate = '';\n for($i = 1; $i &lt;= 14; $i ++){\n $startdate = strtotime(\"today + $i day\");\n $myHTMLdate .= '&lt;option value=\"'.date('Y-m-d', $startdate).'\"&gt;'.date('l', $startdate).', '.date('d M Y', $startdate).'&lt;/option&gt;';\n }\n\n } catch (Exception $ex) {\n\n // can redirect to an error page, etc\n die (\"Application Error: \".$ex-&gt;getMessage());\n }\n\n // only presentation logic after here\n\n?&gt;\n\n&lt;!DOCTYPE html&gt;\n&lt;html lang=\"en\"&gt;\n&lt;head&gt;\n &lt;meta charset=\"utf-8\"&gt;\n &lt;title&gt;Add New Games&lt;/title&gt;\n &lt;meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\"&gt;\n &lt;meta name=\"description\" content=\"\"&gt;\n &lt;meta name=\"author\" content=\"\"&gt;\n\n &lt;!-- Le styles --&gt;\n &lt;link href=\"css/bootstrap.css\" rel=\"stylesheet\"&gt;\n &lt;style&gt;\n body {\n padding-top: 60px; /* 60px to make the container go all the way to the bottom of the topbar */\n }\n &lt;/style&gt;\n &lt;link href=\"css/bootstrap-responsive.css\" rel=\"stylesheet\"&gt;\n\n &lt;!-- HTML5 shim, for IE6-8 support of HTML5 elements --&gt;\n &lt;!--[if lt IE 9]&gt;\n &lt;script src=\"js/html5shiv.js\"&gt;&lt;/script&gt;\n &lt;![endif]--&gt;\n\n &lt;!-- Fav and touch icons --&gt;\n &lt;link rel=\"apple-touch-icon-precomposed\" sizes=\"144x144\" href=\"ico/apple-touch-icon-144-precomposed.png\"&gt;\n &lt;link rel=\"apple-touch-icon-precomposed\" sizes=\"114x114\" href=\"ico/apple-touch-icon-114-precomposed.png\"&gt;\n &lt;link rel=\"apple-touch-icon-precomposed\" sizes=\"72x72\" href=\"ico/apple-touch-icon-72-precomposed.png\"&gt;\n &lt;link rel=\"apple-touch-icon-precomposed\" href=\"ico/apple-touch-icon-57-precomposed.png\"&gt;\n &lt;link rel=\"shortcut icon\" href=\"ico/favicon.png\"&gt;\n&lt;/head&gt;\n&lt;body&gt;\n&lt;div class=\"navbar navbar-inverse navbar-fixed-top\"&gt;\n &lt;div class=\"navbar-inner\"&gt;\n &lt;div class=\"container\"&gt;\n &lt;button type=\"button\" class=\"btn btn-navbar\" data-toggle=\"collapse\" data-target=\".nav-collapse\"&gt;\n &lt;span class=\"icon-bar\"&gt;&lt;/span&gt;\n &lt;span class=\"icon-bar\"&gt;&lt;/span&gt;\n &lt;span class=\"icon-bar\"&gt;&lt;/span&gt;\n &lt;/button&gt;\n &lt;a class=\"brand\" href=\"#\"&gt;Game Admin Area&lt;/a&gt;\n &lt;div class=\"nav-collapse collapse\"&gt;\n &lt;ul class=\"nav\"&gt;\n &lt;li class=\"active\"&gt;&lt;a href=\"#\"&gt;Add New Games&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#about\"&gt;Update Game Scores&lt;/a&gt;&lt;/li&gt;\n &lt;li&gt;&lt;a href=\"#contact\"&gt;Reports&lt;/a&gt;&lt;/li&gt;\n &lt;/ul&gt;\n &lt;/div&gt;&lt;!--/.nav-collapse --&gt;\n &lt;/div&gt;\n &lt;/div&gt;\n&lt;/div&gt;\n&lt;div class=\"container\"&gt;\n &lt;h1&gt;Add New Games to Database&lt;/h1&gt;\n &lt;p&gt;Use the form below to quickly add upcoming games to the database.&lt;br&gt;Players will not be able to place their predictions until you inputted these games.&lt;/p&gt;\n &lt;div id=\"wrapper\"&gt;\n &lt;div class=\"datagrid\"&gt;\n &lt;table class=\"table table-striped table-bordered table-condensed\"&gt;\n &lt;thead&gt;\n &lt;tr&gt;\n &lt;th&gt;Game No.&lt;/th&gt;\n &lt;th&gt;Team 1&lt;/th&gt;\n &lt;th&gt;Vs.&lt;/th&gt;\n &lt;th&gt;Team 2&lt;/th&gt;\n &lt;th&gt;Game Date&lt;/th&gt;\n &lt;/tr&gt;\n &lt;/thead&gt;\n &lt;tbody&gt;\n &lt;?php\n for ($i=1; $i &lt;=30; $i++) {\n echo \"&lt;tr&gt;\n &lt;td&gt;\".$i.\"&lt;/td&gt;\n &lt;td&gt;&lt;select name='game\".$i.\"_team1'&gt;\".$myHTML.\"&lt;/select&gt;&lt;/td&gt;\n &lt;td&gt;Vs.&lt;/td&gt;\n &lt;td&gt;&lt;select name='game\".$i.\"_team2'&gt;\".$myHTML.\"&lt;/select&gt;&lt;/td&gt;\n &lt;td&gt;&lt;select name='game\".$i.\"_date'&gt;\".$myHTMLdate.\"&lt;/select&gt;&lt;/td&gt;\n &lt;/tr&gt;\";\n }\n ?&gt;\n &lt;/tbody&gt;\n &lt;/table&gt;\n &lt;button class=\"btn btn-large btn-primary\" type=\"submit\"&gt;Send these games to the server!&lt;/button&gt;\n &lt;/div&gt;\n &lt;/form&gt;\n &lt;/div&gt;\n &lt;!-- /container --&gt;\n &lt;!-- Javascript --&gt;\n &lt;!-- Placed at the end of the document so the pages load faster --&gt;\n &lt;script src=\"js/jquery.js\"&gt;&lt;/script&gt;\n\n &lt;!-- double check if this is the correct filename, but there is a minified version of the complete bootstrap js library --&gt;\n &lt;script src=\"js/bootstrap-min.js\"&gt;&lt;/script&gt;\n\n&lt;/body&gt;\n&lt;/html&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T01:49:46.710", "Id": "30232", "ParentId": "30178", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T17:02:38.317", "Id": "30178", "Score": "2", "Tags": [ "php" ], "Title": "Adding new games to a database" }
30178
<p>I would like to get some feedback on my AS3 code below. It's for an Adobe Air mobile app to preload a website in a StageWebView container. That container will be moved on screen later in the app process. My goal is to show the website content to the user as fast as possible.</p> <pre><code>// OFF SCREEN - PRELOAD var webView:StageWebView = new StageWebView(); webView.stage = this.stage; webView.viewPort = new Rectangle( -5000, 0, stage.stageWidth, stage.stageHeight); webView.loadURL("http://www.example.com/foobar.php"); // ONSCREEN function showWeb(e:Event=null){ webView.viewPort = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight); } btn.addEventListener(MouseEvent.CLICK, showWeb) </code></pre> <p>Is there something I could do better? I'm using Adobe Air 3.6 and Flash CS6.</p> <p>Thank yoo</p>
[]
[ { "body": "<p>I don't think there's anything that can be improved to your approach.</p>\n\n<p>Minor improvements do apply;</p>\n\n<pre><code>function showWeb(e:Event=null){\nwebView.viewPort = new Rectangle( 0, 0, stage.stageWidth, stage.stageHeight);\n}\n</code></pre>\n\n<p>could use some indentation,</p>\n\n<pre><code>btn.addEventListener(MouseEvent.CLICK, showWeb)\n</code></pre>\n\n<p>contains a double space and is missing a semicolon.</p>\n\n<p>But I don't think it's possible to preload the <code>StageWebView</code> via some function.</p>\n\n<p>What you DO want to take care of is any errors that might be thrown your way.</p>\n\n<p>For that, add a listener: (code from <a href=\"https://stackoverflow.com/a/14129593/540837\">this SO answer</a>)</p>\n\n<pre><code>webView.addEventListener(ErrorEvent.ERROR, onError);\nfunction onError(e:ErrorEvent):void \n{\n trace(\"Page is not available.\");\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-01-26T16:18:22.293", "Id": "78650", "ParentId": "30179", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T17:10:10.177", "Id": "30179", "Score": "3", "Tags": [ "actionscript-3" ], "Title": "Preload content in StageWebView" }
30179
This tag is for questions that came up in an interview.
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T17:52:13.467", "Id": "30184", "Score": "0", "Tags": null, "Title": null }
30184
<p>The following code would strip 0 (all numbers ending with 0, it can contain 0, eg: 105 can be is valid but 150 should be eliminated) and return a number in decimal series if all numbers ending with 0 were stripped.<br> Example : <code>0 -&gt; 1, 10 -&gt; 11, 19 -&gt; 22</code>.<br> I would just appreciate any code reviews. </p> <pre><code> public static int getStrippedNumber(int num) { int setId = (num / 10) + 1; int newNum = num + setId; int newNumSetId = (newNum / 10) + 1; int numberToReturn = num + newNumSetId; return numberToReturn % 10 ==0 ? numberToReturn + 1 : numberToReturn; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T20:28:12.933", "Id": "47957", "Score": "6", "body": "Your question is unclear. Why `19 -> 21`? What is the expected output for `100` and `998` and why?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T20:32:51.970", "Id": "47958", "Score": "0", "body": "Running this code in my head gives `0 -> 2`, `10 -> 14`, and `19 -> 23`. You should post here once you have working code so we can help you improve it. Non-working code is for Stack Overflow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T20:37:32.933", "Id": "47959", "Score": "0", "body": "Cleared your doubts and 19 returns 22." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T20:40:43.463", "Id": "47960", "Score": "2", "body": "There are no `0` in `19` then why it increases to `22`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T20:49:28.143", "Id": "47961", "Score": "0", "body": "0 10 need to go so 19 + 2, but 19 + 2 also includes 20, so 20 should go, so 22. 0->1, 8->9, 9-> 11...19->22," }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T21:09:51.547", "Id": "47962", "Score": "4", "body": "This [ideone result](http://ideone.com/3dhngE) may help future reviewer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T07:20:16.027", "Id": "47979", "Score": "1", "body": "From the ideone from @tintinmj I could finally guess the intent of the code. But from the same result I can only conclude it has a bug. Note that the output for 198 is 221, and for 199 it is also 221." } ]
[ { "body": "<p>Well... Sorry to say this, but it's crappy!</p>\n\n<ul>\n<li>The function name doesn't explain what the function does (and using your explanation above for Javadoc would only make things worse, judging from the confusion in the comments)</li>\n<li>Even knowing the implementation doesn't help, it's hard to tell if the steps performed inside the function correspond to a real-world concept or represent some algorithm</li>\n<li>it's not clear if this function makes sense for negative values, I'm pretty sure it would return unexpected values (i.e. output for <code>x</code> and <code>-x</code> would be drastically different). If the function is not defined for negative values, throw an <code>IllegalArgumentException</code> when <code>num &lt; 0</code></li>\n<li>You use confusing names for variables; I think even <code>a</code>, <code>b</code>, <code>c</code> etc. would be better than <code>num</code>, <code>newNum</code>, <code>numberToReturn</code> (nb. this last one is additionally misleading as you still process it before returning)</li>\n<li>The function seems to solve some general problem but it uses arbitrary depth: repeats the same operation twice (in lines 1&amp;2 and 3&amp;4) instead of using a loop or recursion (which would also communicate your intentions better)</li>\n</ul>\n\n<p>I know this is the part where you give your recommendations but I believe this function is broken beyond repair until you make it clear what its purpose and contract are. Remember that most real-world mathematical problems are already solved and have well-described algorithms, using well-tested solutions is always a better idea than trying to reinvent the wheel.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T02:13:52.397", "Id": "47975", "Score": "0", "body": "function is broken beyond repair ?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T23:06:13.353", "Id": "30193", "ParentId": "30186", "Score": "7" } }, { "body": "<p>Your question and output differs. Your logic is not well defined but I can't <em>downvote</em> your question cause it is a <em>working code</em>... <strong>sigh!</strong></p>\n\n<p>You said:</p>\n\n<blockquote>\n <p>The following code would strip 0 (all numbers ending with 0, it can contain 0, eg: 105 is valid but 150 should be eliminated)</p>\n</blockquote>\n\n<p>But by <a href=\"http://ideone.com/3dhngE\" rel=\"nofollow\">running your code</a> <code>105</code> goes to <code>117</code> <strong>WHY?</strong></p>\n\n<p>However from the question title (<code>code to strip 0 from decimal series</code>) and from the problem description(misleading) I think </p>\n\n<pre><code> public static int getStrippedNumber(int num) {\n return (num + 1) % 10 == 0 ? (num + 2) : (num + 1);\n }\n</code></pre>\n\n<p>is <strong><a href=\"http://ideone.com/W8v0QG\" rel=\"nofollow\">ENOUGH!!!</a></strong></p>\n\n<p>Since you didn't say anything about <em>negative</em> numbers, I'm assuming you didn't think about it. Go with @kryger's answer throw an <code>IllegalArgumentException</code> for <em>negative</em> numbers. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T07:25:46.700", "Id": "30200", "ParentId": "30186", "Score": "3" } }, { "body": "<p>I'll start by stating what I think your intent is, as it's not 100% clear from your question.</p>\n\n<p><em>Imagine the series that consists of all positive natural numbers without multiples of 10 : ℕ \\10ℕ, in order. Write a function that, given a 0-based index, returns the number at that index in the series</em></p>\n\n<p>This is what seems to correspond most, with what you have described and what your code does. However there is a discrepancy between what you say your code does, and what it actually does. According to the semantics 10 should map to 12, and this is what your code does, yet as an example you say 10 should map to 11.</p>\n\n<p>The code you have does not seem to fulfill its contract (i.e. it has a semantical bug) it starts misbehaving for iputs higher than 198. 198 gives 221 and 199 also gives 221.</p>\n\n<p>Or, of course, I am way off track...</p>\n\n<p>Code that does fulfill the contract I describe above is actually fairly simple.</p>\n\n<pre><code>public static int getStrippedNumber(int num) {\n return num + num/9 + 1;\n}\n</code></pre>\n\n<p>Borrowing from @tintinmj I have also submitted a <a href=\"http://ideone.com/vvE9Mi\">ideone</a> to demonstrate</p>\n\n<p>Of course naming this function more appropriately and having a clearer contract explanation are major points of attention. Imagine a developer trying to maintain the code, and all he has is your code and what you have documented.</p>\n\n<p>So improved this would be :</p>\n\n<pre><code>/**\n * Determines the number in the series ℕ\\10ℕ (the natural numbers without multiples of 10) at the given index.\n * @param index zero-based index\n * @return the number in the series of ℕ\\10ℕ at the given index.\n */\npublic static int getNwithout10NAtIndex(int index) {\n if (index &lt; 0) {\n throw new IllegalArgumentException();\n }\n return index + index/9 + 1;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T08:18:49.030", "Id": "30206", "ParentId": "30186", "Score": "7" } } ]
{ "AcceptedAnswerId": "30206", "CommentCount": "7", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T20:10:53.220", "Id": "30186", "Score": "1", "Tags": [ "java" ], "Title": "Code review of code to strip 0 from decimal series" }
30186
<p>Is there any way to make this work faster?</p> <p>Here is my sample code in vb.net. This adds a point on a chart at mouse position but it is quite slow.</p> <pre><code>Private Sub Chart2_MouseMove(sender As Object, e As MouseEventArgs) Handles Chart2.MouseMove Dim coord() As Double = GetAxisValuesFromMouse(e.X, e.Y) Dim test As Series Try Chart2.Series.RemoveAt(1) Catch ex As Exception End Try Dim pt As New DataPoint pt.XValue = coord(0) pt.YValues(0) = coord(1) test = New Series Chart2.Series.Add(test) Chart2.Series(test.Name).ChartType = SeriesChartType.Point Chart2.Series(test.Name).Points.Add(pt) End Sub </code></pre> <p>Function returns the coordinates of x and y axis at mouse position.</p> <pre><code>Private Function GetAxisValuesFromMouse(x As Integer, y As Integer) As Double() Dim coord(1) As Double Dim chartArea = Chart2.ChartAreas(0) coord(0) = chartArea.AxisX.PixelPositionToValue(x) coord(1) = chartArea.AxisY.PixelPositionToValue(y) Return coord End Function </code></pre> <p>Result:</p> <p><img src="https://i.stack.imgur.com/kiTzr.gif" alt="enter image description here"></p>
[]
[ { "body": "<pre><code>Try\n Chart2.Series.RemoveAt(1)\nCatch ex As Exception\nEnd Try\n</code></pre>\n\n<p>Your Try/Catch block is probably the cause of your problem. Catching exceptions is very slow. Instead you should check to see if the item exists at index 1 before you try to remove it. You should notice a huge improvement.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T20:33:54.850", "Id": "30326", "ParentId": "30188", "Score": "3" } }, { "body": "<p>Unless I'm mistaken, the <code>MouseMove</code> event fires everytime the mouse coordinates change - and when you're moving the mouse across the chart, that's a couple dozens (if not hundreds) of times in a very limited amount of time (&lt;1 second!).</p>\n\n<p>There are a couple things that stand out in your code:</p>\n\n<ul>\n<li><p>Your indentation is off. You need to give the <kbd>Tab</kbd> button the lovin' it deserves!</p></li>\n<li><p>An empty <code>Catch</code> block is bad. You're swallowing exceptions without ever knowing <em>if</em> anything has gone wrong. Don't do that!</p></li>\n<li><p><code>GetAxisValuesFromMouse</code> should be returning a <code>Point</code>, not an array of doubles. Returning a simple <code>struct</code> instead of an array can help you gain a couple cycles - my background is <a href=\"/questions/tagged/c%23\" class=\"post-tag\" title=\"show questions tagged &#39;c#&#39;\" rel=\"tag\">c#</a> so the syntax might be a little off here:</p>\n\n<pre><code>Public Structure PointD ' named after System.Drawing.PointF which is using Float/Single.\n Public X As Double\n Public Y As Double\n Public Sub New(ByVal XValue As Double, ByVal YValue As Double)\n X = XValue\n Y = YValue\n End Sub\nEnd Structure\n\nPrivate Function GetAxisValuesFromMouse(x As Integer, y As Integer) As Double()\n\n return New PointD(chartArea.AxisX.PixelPositionToValue(x), _\n chartArea.AxisY.PixelPositionToValue(y))\n\nEnd Function\n</code></pre></li>\n<li><p>The chart object is abstracting a lot of plumbing, and I suspect this plumbing is where your bottleneck is. Your code removes a series, creates a new data point, adds a new series and adds the data point to the new series; the chart probably gets redrawn when you remove the series, and again when you add it, and once more when you add the point. It would be much more efficient to <em>move the datapoint</em> instead of recreating the series everytime the mouse moves by a pixel.</p></li>\n</ul>\n\n<p>I suggest you only create the data point when you don't already have it (i.e. only once!); keep a reference to your data point, and simply change its coordinates per the mouse. If that alone doesn't do it, you'll need code that <em>finds</em> the data point and moves it. Since you're drawing the point on its own series, that shouldn't be too hard to achieve. The chart will only redraw itself when the coordinates of the point have changed, and when the mouse moves you'll only be fetching the mouse coordinates and assigning new values to the point's XY values. I'm sure this would be much faster.</p>\n\n<p>And yeah, exceptions incur some performance hit, so if your code is swallowing exceptions that is another possible bottleneck, but if you're only moving a data point around, you shouldn't have to worry about that.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-29T21:39:28.823", "Id": "38294", "ParentId": "30188", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T20:29:10.017", "Id": "30188", "Score": "5", "Tags": [ "performance", ".net", "vb.net" ], "Title": "Drawing a point on a chart" }
30188
<p>I'm looking for general feedback on how to make this useful to other people. This is a subset of underscore.js with some additions, and what I feel are improvements.</p> <p>The code passes jslint and minifies well with clousre.</p> <p>Please let me know what questions I can answer to receive a better review.</p> <pre><code>/*******************************************************************************/ (function (self, undef) { "use strict"; // holds (P)ublic properties var $P = {}, // holds p(R)ivate properties $R = {}, // native methods (alphabetical order) nativeFilter = Array.prototype.filter, nativeIsArray = Array.isArray, nativeSlice = Array.prototype.slice, nativeSome = Array.prototype.some, nativeToString = Object.prototype.toString; /******************************************************************************/ // GLOBAL MANAGEMENT $P.noConflict = (function () { // g is the single global variable $R.g = '$'; $R.previous = self[$R.g]; $P.molist = { utility: true }; return function () { var temp = self[$R.g]; self[$R.g] = $R.previous; return temp; }; }()); /******************************************************************************/ // TYPE CHECKS $P.isType = function (type, obj) { return $P.getType(obj) === type; }; // returns type in captialized string form $P.getType = function (obj) { return nativeToString.call(obj).slice(8, -1); }; $P.isFalse = function (obj) { return obj === false; }; $P.isUndefined = function (obj) { return obj === undef; }; $P.isNull = function (obj) { return obj === null; }; // detects null, and undefined $P.isGone = function (obj) { return obj == null; }; // detects null, undefined, NaN, ('' ""), 0, -0, false $P.isFalsy = function (obj) { return !obj; }; $P.isTruthy = function (obj) { return !!obj; }; // shortcut as their are only two primitive boolean values $P.isBoolean = function (obj) { return obj === true || obj === false || nativeToString.call(obj) === '[object Boolean]'; }; // delegates to native $P.isArray = nativeIsArray || function (obj) { return nativeToString.call(obj) === '[object Array]'; }; // jslint prefers {}.constructor(obj) over Object(obj) // has keys $P.isObjectAbstract = function (obj) { return !!(obj &amp;&amp; (obj === {}.constructor(obj))); }; // has a numeric length property $P.isArrayAbstract = function (obj) { return !!(obj &amp;&amp; obj.length === +obj.length); }; /******************************************************************************/ // LOOPING $P.someIndex = function (arr, func, con) { var ind, len; if (!arr || typeof func !== 'function') { // prevents type errors return false; } if (nativeSome &amp;&amp; arr.some === nativeSome) { return arr.some(func, con); } for (ind = 0, len = arr.length; ind &lt; len; ind += 1) { if (func.call(con, arr[ind], ind, arr)) { return true; } } return false; }; $P.someKey = function (obj, func, con) { var key; if (!obj || typeof func !== 'function') { // prevents type errors return false; } for (key in obj) { if (obj.hasOwnProperty(key)) { if (func.call(con, obj[key], key, obj)) { return true; } } } return false; }; // loop through space separated "tokens" in a string $P.eachString = function (str, func, con) { var regexp = /^|\s+/; if (regexp.test(str)) { $P.someIndex(str.split(regexp), func, con); } }; // does not extend through the prototype chain $P.extend = function (obj) { $P.someIndex(nativeSlice.call(arguments, 1), function (val) { $P.someKey(val, function (val_inner, key) { obj[key] = val_inner; }); }); return obj; }; $P.filter = function (arr, func, con) { var results = []; if (!arr || typeof func !== 'function') { // prevents type errors return results; } if (nativeFilter &amp;&amp; arr.filter === nativeFilter) { return arr.filter(func, con); } $P.someIndex(arr, function (val, ind, arr) { if (func.call(con, val, ind, arr)) { results.push(val); } }); return results; }; $P.extendSafe = function (obj1, obj2) { var key; for (key in obj2) { if (obj2.hasOwnProperty(key) &amp;&amp; obj1.hasOwnProperty(key)) { throw "naming collision: " + key; } obj1[key] = obj2[key]; } return obj1; }; $P.clone = function (obj) { return $P.extend({}, obj); }; /******************************************************************************/ // GENERAL $P.someIndex(['Arguments', 'Function', 'String', 'Number', 'Date', 'RegExp', 'Object'], function (val) { $P['is' + val] = function (obj) { return $P.isType(val, obj); }; }); /******************************************************************************/ // TESTING // equivalent to IIFE but "nicer" syntax $P.runTest = (function () { var tests = {}; return function (name, arr, func) { tests[name] = func.apply(this, arr); }; }()); /******************************************************************************/ // COMPLETE self[$R.g] = $P.extendSafe($P, {}); }(this)); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T21:57:44.603", "Id": "47963", "Score": "0", "body": "Welcome! We cannot look for errors for you here, but we can certainly do a general review. If you do come across errors, feel free to post them on Stack Overflow." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T21:59:37.237", "Id": "47964", "Score": "0", "body": "A general review would by smurfy!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T22:14:03.473", "Id": "47965", "Score": "0", "body": "Alright. You may need to edit out the \"look for errors\" part since that's off-topic." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T22:17:51.663", "Id": "47966", "Score": "0", "body": "Done. It has been removed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T22:18:08.220", "Id": "47967", "Score": "2", "body": "@Jamal questions do not have to be free of errors. The asker just has to *believe* the code is free of errors. The request to find errors does imply that he's not 100% sure there's no errors, but he doesn't know of any specific ones, and thus it's on topic (in my opinion anyway, and what the FAQ implies)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T23:13:09.477", "Id": "47969", "Score": "0", "body": "@Corbin: Oh yeah, I forgot about that part. Well, the explanation has already been removed." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T00:15:38.457", "Id": "47973", "Score": "0", "body": "*\"This is a subset of underscore.js with some additions.\"* - wouldn't that be called a superset by now?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T07:36:53.820", "Id": "47980", "Score": "1", "body": "@JosephtheDreamer - A superset would have to contain *all* of underscore.js. All you can really say is that their intersections and differences are not empty. :)" } ]
[ { "body": "<ul>\n<li><p>When declaring variables, I suggest going with the <code>var</code> for each approach. Helps you in avoiding missing commas. Also, it's easier to read and tell they are variables especially when there are comments in between the set.</p></li>\n<li><p>Name your variables verbosely. It can help when debugging and development. You wouldn't want to scroll up and back just to see what <code>$P</code> was. Name them like what they are. You can setup a non-verbose version like how jQuery references <code>jQuery</code> to <code>$</code>.</p></li>\n<li><p>Don't mind the variable name length during the creation of the code. In the end, you'd still be using a minifier to shrink everything to single character variable names.</p></li>\n<li><p>I suggest your <code>getType</code> be in lowercase to be consistent with the native <code>typeof</code>.</p></li>\n<li><p><code>isFalse</code>, <code>isNull</code> and <code>isGone</code> wouldn't be much of use. A direct comparison would be quicker to do and wouldn't cause that overhead of calling a function.</p></li>\n<li><p>Do note that <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Boolean#Description\">boolean promitives (<code>true</code> and <code>false</code>) are entirely different from boolean objects</a>.</p></li>\n<li><p>Make comments self explanatory. A sample of this scenario is where one asks \"What does <code>isObjectAbstract</code> and <code>isArrayAbstract</code>? There are no abstracts in JS.\" - and the comments don't really explain much.</p></li>\n<li><p>You seem to do type checks on some functions but others not.</p></li>\n<li><p>Instead of returning false on failed type checks, I suggest you throw an error instead. Return the <code>result</code> when it succeeded, <code>false</code> if it didn't (but did use the function properly), and throw an error if something is not right. Remember console errors that go like <code>\"foo is not a function\"</code> or <code>\"Accessing property bar of undefined\"</code>, same idea.</p></li>\n<li><p>Before you do regexp on stuff, try doing it without using regexp. In <code>eachString</code>, I assume you are testing for a string. You can just do a <code>typeof str === 'string' &amp;&amp; str.length</code> instead to check if it is a non-empty string.</p></li>\n<li><p>I don't see the purpose of <code>runTest</code>. It seems to just require a <code>name</code>, an <code>array</code> and a function that receives the <code>array</code>. Also, there's a potential memory \"leak\" here. Calling <code>runTest</code> stores the function's results in <code>tests</code>, however, <code>test</code> isn't accessible outside the closure. The objects and it's contents will stay there, continually accumulating, normally inaccessible indefinitely.</p></li>\n</ul>\n\n<p>Well, that's it. That's my rundown of the things in your code.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T21:33:08.187", "Id": "48011", "Score": "0", "body": "- all the functions are type checked. If not in the initial calling function, than in the function it is used in." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T20:34:56.693", "Id": "48204", "Score": "0", "body": "- typeof is actually different from the other two methods I'm familiar with, as `toString` will return an uppercase version, and so will the `constructor.name` property." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:38:22.850", "Id": "48256", "Score": "0", "body": "- underscore.js uses one line functions as well." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T01:02:02.263", "Id": "30196", "ParentId": "30189", "Score": "5" } } ]
{ "AcceptedAnswerId": "30196", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T20:56:47.643", "Id": "30189", "Score": "4", "Tags": [ "javascript" ], "Title": "General feedback on utility module" }
30189
<p>This code finds the intersections of all overlapping intervals.</p> <p>Example: if <code>[0-20]</code>, <code>[15-40]</code>, and <code>[25-50]</code> are the 3 intervals then the output should be <code>[15-20]</code> and <code>[25-40]</code>.</p> <p>I could not find an answer with complexity less than \$O(n^2)\$. Please suggest a better solution if one exists. Additionally, assume the input intervals are sorted by their start times.</p> <pre><code>public static Set&lt;OverlapCoord&gt; getOverlap(List&lt;Interval&gt; intervalList) { if (intervalList == null) { throw new NullPointerException("Input list cannot be null."); } final HashSet&lt;OverlapCoord&gt; hashSet = new HashSet&lt;OverlapCoord&gt;(); for (int i = 0; i &lt; intervalList.size() - 1; i++) { final Interval intervali = intervalList.get(i); for (int j = 0; j &lt; intervalList.size(); j++) { final Interval intervalj = intervalList.get(j); if (intervalj.getStart() &lt; intervali.getEnd() &amp;&amp; intervalj.getEnd() &gt; intervali.getStart() &amp;&amp; i != j) { hashSet.add(new OverlapCoord(Math.max(intervali.getStart(),intervalj.getStart()), Math.min(intervali.getEnd(), intervalj.getEnd()))); } } } return hashSet; } </code></pre>
[]
[ { "body": "<p>Sort the intervals by starting value, and length incremental : O(n sqrt(n))<br></p>\n\n<p>Loop the intervals and check overlaps between current and previous one. : O(n)</p>\n\n<p>Resulting complexity : O(n sqrt(n))</p>\n\n<p>You said to assume they're already sorted, but I'm not sure whether they're also sorted by length, which is needed to better handle intervals that have the same starting value. If they're also already sorted by length, then you only have the loop to check overlaps between previous and current, which would leave you with O(n) complexity.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T07:03:39.323", "Id": "30198", "ParentId": "30190", "Score": "6" } }, { "body": "<p>Because the intervals are already sorted by start time, you can begin the inner loop at <code>j = i + 1</code> and simplify the <code>if</code> test and drop the call to <code>max</code>: </p>\n\n<pre><code>if (intervalj.getStart() &lt; intervali.getEnd()) {\n hashSet.add(new OverlapCoord(intervalj.getStart(), \n Math.min(intervali.getEnd(), intervalj.getEnd())));\n}\n</code></pre>\n\n<p>However, is it possible for three intervals to overlap?</p>\n\n<pre><code>[===============]\n [=============]\n [=============]\n</code></pre>\n\n<p>If so, this will produce three overlaps:</p>\n\n<pre><code> [=======]\n [==]\n [========]\n</code></pre>\n\n<p>Is this desired? What about if the first and third intervals above butted up against each other rather than overlapping themselves?</p>\n\n<pre><code> [=======]\n [====]\n</code></pre>\n\n<p>Should all these cases be merged into the same single overlap?</p>\n\n<pre><code> [=============]\n</code></pre>\n\n<p>Here are some better variable names to consider:</p>\n\n<ul>\n<li><code>intervalList</code> -> <code>intervals</code></li>\n<li><code>hashSet</code> -> <code>overlaps</code></li>\n<li><code>intervali</code> -> <code>leftInterval</code> or <code>lowerInterval</code></li>\n<li><code>intervalj</code> -> <code>rightInterval</code> or <code>upperInterval</code></li>\n</ul>\n\n<p>I find it's best to leave the type of collection out of the name. First, it makes it easier to change later. And second, you can see it and in any IDE hover over the method to see the required type. I might even drop the <code>Interval</code> suffix from the last two above since this method only deals with intervals.</p>\n\n<p>Finally, there's no reason this method couldn't accept a <code>null</code> list. It should respond just as it does when the list is empty: return an empty set.</p>\n\n<pre><code>if (intervals == null || intervals.isEmpty()) {\n return Collections.&lt;OverlapCoord&gt;emptySet();\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T08:23:23.907", "Id": "47983", "Score": "0", "body": "Accpting `null` as valid input seems to be no more than tailoring to badly behaved clients. I would maintain `IllegalArgumentException` for null arguments, and simply fail fast." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T08:28:51.330", "Id": "47985", "Score": "0", "body": "In that case I would annotate `intervals` with `@Nonnull` and let FindBugs point out bad calls." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T08:34:28.277", "Id": "47986", "Score": "0", "body": "That assumes you control all possible clients. The annotation is fine, but any well behaved function should reject illegal input." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T21:13:19.127", "Id": "48009", "Score": "1", "body": "@bowmore - Well behaved functions should tolerate poorly behaved clients if they can instead of unnecessarily throwing exceptions at runtime." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T21:25:09.983", "Id": "48010", "Score": "1", "body": "Responding with valid output to illegal input will only lead to bugs that are harder to detect, so : [fail fast](http://martinfowler.com/ieeeSoftware/failFast.pdf)" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T07:29:14.807", "Id": "30201", "ParentId": "30190", "Score": "11" } } ]
{ "AcceptedAnswerId": "30201", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T21:04:17.880", "Id": "30190", "Score": "10", "Tags": [ "java", "optimization", "interval" ], "Title": "Find intersections of overlapping intervals" }
30190
<pre><code>private void rect_ManipulationStarting(object sender, ManipulationDeltaRoutedEventArgs e) { startingColumn = Grid.GetColumn(e.OriginalSource as Windows.UI.Xaml.Shapes.Rectangle); gLValue = headerGrid.ColumnDefinitions[startingColumn].Width.Value + e.Delta.Translation.X; if (gLValue &lt; 5) return; else { headerGrid.ColumnDefinitions[startingColumn].Width = new GridLength(gLValue); cycleThroughColumns(libraryGrid, startingColumn, gLValue); cycleThroughColumns(playlistGrid, startingColumn, gLValue); } } private void cycleThroughColumns(Grid anyGrid, int anyStartingColumn, double anyGLValue) { if (anyGrid.Children.Count &gt; 0) { if ((anyGrid.Children[0] as Grid).ColumnDefinitions.Count &gt; 0) { for (int index = 0; index &lt; anyGrid.Children.Count; index++) { (anyGrid.Children[index] as Grid).ColumnDefinitions[anyStartingColumn].Width = new GridLength(anyGLValue); } } } } </code></pre> <p>In the header there is a rectangle on each column divider, that when moved calls the event handler. Within libraryGrid and playlistGrid are grids for each row. (In each of these grids is a textblock). It's just too slow when resizing 884 columns and I was wondering if there was a way to optimize the code to speed it up. Only about 20 rows are visible to the user at one time.</p> <p>Here are changes I made using a poor-man's virtualization technique, I took the height of the scrollviewer and divided by the height of the items to get the number of items, added 2 for good measure, and now I loop through about 10-15 items first (the visible ones) before I loop through the second set, both are asynchronous, although it still has some lag it's much, much more responsive. Any further optimization ideas are also appreciated.</p> <pre><code>private void rect_ManipulationStarting(object sender, ManipulationDeltaRoutedEventArgs e) { startingColumn = Grid.GetColumn(e.OriginalSource as Windows.UI.Xaml.Shapes.Rectangle); gLValue = headerGrid.ColumnDefinitions[startingColumn].Width.Value + e.Delta.Translation.X; if (gLValue &lt; 5) return; else { headerGrid.ColumnDefinitions[startingColumn].Width = new GridLength(gLValue); cycleThroughColumns(libraryGrid, startingColumn, gLValue); cycleThroughColumns(playlistGrid, startingColumn, gLValue); } } private void cycleThroughColumnsAsync(Grid anyGrid, int anyStartingColumn, double anyGLValue, int anyVertStart, int anyVertEnd) { if (anyGrid.Children.Count &gt; 0) { if ((anyGrid.Children[0] as Grid).ColumnDefinitions.Count &gt; 0) { for (int index = anyVertStart; index &lt; anyVertEnd; index++) { if (anyGrid.Children[index] as Grid != null) { (anyGrid.Children[index] as Grid).ColumnDefinitions[anyStartingColumn].Width = new GridLength(anyGLValue); } else { break; } } } } } async private void cycleThroughColumns(Grid anyGrid, int anyStartingColumn, double anyGLValue) { int vertStart = getVertStart(anyGrid); int vertEnd = getVertEnd(vertStart, anyGrid); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.High, () =&gt; cycleThroughColumnsAsync(anyGrid, anyStartingColumn, anyGLValue, vertStart, vertEnd)); await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =&gt; cycleThroughColumnsLeftOverAsync(anyGrid, anyStartingColumn, anyGLValue, vertStart, vertEnd)); } private void cycleThroughColumnsLeftOverAsync(Grid anyGrid, int anyStartingColumn, double anyGLValue, int anyVertStart, int anyVertEnd){ for (int index = 0; index &lt; anyVertStart; index++) { if (anyGrid.Children[index] as Grid != null) { (anyGrid.Children[index] as Grid).ColumnDefinitions[anyStartingColumn].Width = new GridLength(anyGLValue); } else { break; } } for (int index = anyVertEnd; index &lt; anyGrid.Children.Count; index++) { if (anyGrid.Children[index] as Grid != null) { (anyGrid.Children[index] as Grid).ColumnDefinitions[anyStartingColumn].Width = new GridLength(anyGLValue); } else { break; } } } private int getVertStart(Grid anyGrid) { return (int)(anyGrid.Parent as ScrollViewer).VerticalOffset / 30; } private int getVertEnd(int anyVertStart, Grid anyGrid) { double numberOfRowsInView = (anyGrid.Parent as ScrollViewer).RenderSize.Height / 30; return (int)(anyVertStart + numberOfRowsInView) + 2; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T13:21:32.400", "Id": "47996", "Score": "2", "body": "A lot more information is need - Winforms or WPF? Is column virtualization enabled? Are columns Auto width or fixed width? TemplateColumn or builtin column (WPF)? Would it perhaps be reasonable to turn the table upside down, make columns to rows and rows to columns? (that might work better) If you are using WPF, then are you aware that WPF DataGrid is SLOW full stop. Asking it to handle 884 columns might be close to impossible depending on the scenario... Winforms DataGrid can certainly be faster in this case I think..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T20:08:03.713", "Id": "48005", "Score": "0", "body": "Sorry I didn't specify, it's winrt for a metro app. Columns are fixed width at the moment. I'm just using the basic Grid control, has 884 rows, each row has a grid with 7 columns. The virtualization sounds like it might help, not sure how to do that or if it's possible in the grid control. Also possibly of note, this is all from code behind, no xaml populating the rows and columns, although the parent grids are declared in xaml." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T02:06:42.480", "Id": "48022", "Score": "0", "body": "I'm trying to find information on virtualizingstackpanel, seems the internet is devoid of information relating to winrt, almost all of it is for wpf. Would placing the grid structure in a virtualizingstackpanel or placing the inner grids in many of them work? I keep getting the error \"VirtualizingStackPanel can only be used to display items within an ItemsControl,\" so I put the grids in an itemscontrol but it still is not working, I will keep trying but it's confusing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T06:25:38.403", "Id": "48028", "Score": "0", "body": "winrt is still a relatively new technology and many developers are avoiding it like the plague, thus the small amount of information. Am I correct to assume you are then developing a Win 8 Metro application? VirtualizingStackPanel is items based, not layout based which a simple Grid is. I don't know how to implement your own control from scratch to specifically use VirtualizingStackPanel, you'll have to Google it. This could perhaps be a start - [link](http://blogs.msdn.com/b/dancre/archive/2006/02/06/implementing-a-virtualized-panel-in-wpf-avalon.aspx). Otherwise GridView you can use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T04:32:35.563", "Id": "48120", "Score": "0", "body": "Thank you, I got some good information on how virtualization works now and updated the code above, although it's still lagging a bit it's a lot better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T05:59:51.473", "Id": "48121", "Score": "1", "body": "glad to hear you got to improve your code. You should post an answer yourself and describe the code changes you made so that others could learn from this as well." } ]
[ { "body": "<p>Here is the final code without any lag!</p>\n\n<pre><code> //event handler for when the rectangles are dragged left or right (resizing the columns)\n private void rect_ManipulationStarting(object sender, ManipulationDeltaRoutedEventArgs e)\n {\n startingColumn = Grid.GetColumn(e.OriginalSource as Windows.UI.Xaml.Shapes.Rectangle);\n\n gLValue = headerGrid.ColumnDefinitions[startingColumn].Width.Value + e.Delta.Translation.X;\n if (gLValue &lt; 5)\n return;\n else\n {\n headerGrid.ColumnDefinitions[startingColumn].Width = new GridLength(gLValue);\n\n cycleThroughColumns(libraryGrid, startingColumn, gLValue);\n cycleThroughColumns(playlistGrid, startingColumn, gLValue);\n } \n }\n\n //event handler called when the resizing of the columns is completed\n private void rect_ManipulationEnded(object sender, ManipulationCompletedRoutedEventArgs e)\n {\n if (gLValue &lt; 5)\n return;\n else\n {\n cycleThroughColumns2(libraryGrid, startingColumn, gLValue);\n cycleThroughColumns2(playlistGrid, startingColumn, gLValue);\n }\n }\n\n //cycles through the columns in view\n private void cycleThroughColumns(Grid anyGrid, int anyStartingColumn, double anyGLValue)\n {\n int vertStart = getVertStart(anyGrid);\n int vertEnd = getVertEnd(vertStart, anyGrid);\n cycleThroughColumns(anyGrid, anyStartingColumn, anyGLValue, vertStart, vertEnd); //not async even though the method has it in its name\n }\n\n //cycles through the columns not in view, asynchrounously\n async private void cycleThroughColumns2(Grid anyGrid, int anyStartingColumn, double anyGLValue)\n {\n int vertStart = getVertStart(anyGrid);\n int vertEnd = getVertEnd(vertStart, anyGrid);\n await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Low, () =&gt; cycleThroughColumnsLeftOverAsync(anyGrid, anyStartingColumn, anyGLValue, vertStart, vertEnd));\n }\n\n //does the work to cycle through the visible rows\n private void cycleThroughColumns(Grid anyGrid, int anyStartingColumn, double anyGLValue, int anyVertStart, int anyVertEnd)\n {\n if (anyGrid.Children.Count &gt; 0)\n {\n if ((anyGrid.Children[0] as Grid).ColumnDefinitions.Count &gt; 0)\n {\n for (int index = anyVertStart; index &lt; anyVertEnd; index++)\n {\n if (anyGrid.Children[index] as Grid != null)\n {\n (anyGrid.Children[index] as Grid).ColumnDefinitions[anyStartingColumn].Width = new GridLength(anyGLValue);\n }\n else\n {\n break;\n }\n }\n }\n }\n }\n\n //does the work to cycle through the columns from 0 to vertstart, and vertend to the end of the list\n private void cycleThroughColumnsLeftOverAsync(Grid anyGrid, int anyStartingColumn, double anyGLValue, int anyVertStart, int anyVertEnd){\n for (int index = 0; index &lt; anyVertStart; index++)\n {\n if (anyGrid.Children[index] as Grid != null)\n {\n (anyGrid.Children[index] as Grid).ColumnDefinitions[anyStartingColumn].Width = new GridLength(anyGLValue);\n }\n else\n {\n break;\n }\n }\n\n for (int index = anyVertEnd; index &lt; anyGrid.Children.Count; index++)\n {\n if (anyGrid.Children[index] as Grid != null)\n {\n (anyGrid.Children[index] as Grid).ColumnDefinitions[anyStartingColumn].Width = new GridLength(anyGLValue);\n }\n else\n {\n break;\n }\n }\n }\n\n //returns the starting row that is in view\n private int getVertStart(Grid anyGrid)\n {\n return (int)(anyGrid.Parent as ScrollViewer).VerticalOffset / ROW_HEIGHT;\n }\n\n //returns the last row that can be in view\n private int getVertEnd(int anyVertStart, Grid anyGrid)\n {\n double numberOfRowsInView = (anyGrid.Parent as ScrollViewer).RenderSize.Height / 30;\n return (int)(anyVertStart + numberOfRowsInView) + 2;\n\n }\n</code></pre>\n\n<p>I separated the cycling of the visible columns and the ones offscreen into the manipulationStarting and manipulationEnded event handlers, this sped up the performance to the point where there is effectively no lag.</p>\n\n<p>The only bug is if the user scrolls down with the mousewheel while dragging the column resizing rectangles, but I think it's acceptable, as the user only has to drag the rectangles again to fix the view.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T21:20:42.873", "Id": "30333", "ParentId": "30191", "Score": "1" } } ]
{ "AcceptedAnswerId": "30333", "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-24T22:16:53.177", "Id": "30191", "Score": "1", "Tags": [ "c#", "xaml" ], "Title": "Need help optimizing code so that resizing of 884+ columns in grid does not lag" }
30191
<p>The code I'm trying to improve modifies a URL according to the options passed in a hash:</p> <pre><code>{ :image_aspect_ratio =&gt; "square", :image_size =&gt; 50 } </code></pre> <p>or</p> <pre><code>{ :image_size =&gt; { :width =&gt; 50, :height =&gt; 60 } } </code></pre> <p>The code looks like this:</p> <pre><code>module X module Y class Z def image_url if raw_info['picture'] &amp;&amp; image_size_opts_passed? image_url_with_size_opts else raw_info['picture'] end end def image_size_opts_passed? !!(options[:image_size] || options[:image_aspect_ratio]) end def image_url_with_size_opts params_index = raw_info['picture'].index('/photo.jpg') if params_index raw_info['picture'].insert(params_index, image_params) else raw_info['picture'] end end def image_params image_params = [] if options[:image_size].is_a?(Integer) image_params &lt;&lt; "s#{options[:image_size]}" elsif options[:image_size].is_a?(Hash) image_params &lt;&lt; "w#{options[:image_size][:width]}" if options[:image_size][:width] image_params &lt;&lt; "h#{options[:image_size][:height]}" if options[:image_size][:height] end image_params &lt;&lt; 'c' if options[:image_aspect_ratio] == 'square' '/' + image_params.join('-') end </code></pre> <p>Here's the stuff I hate about this code:</p> <ol> <li><p>Lots of <code>raw_info['picture']</code> being called, but I'm not sure if using a local variable is better than accessing a hash twice.</p></li> <li><p>I'm seeing some duplication in the else branch in the <code>image_url</code> and <code>image_url_with_size_opts</code> methods but I don't know how to improve that.</p></li> <li><p>This code is all inside a class which is inside a module which is inside another module, so I'm not sure if I could also memoize the <code>image_params</code> result.</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T00:38:16.403", "Id": "48018", "Score": "0", "body": "What is `raw_info['picture']`? An object or just a plain array?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T15:53:41.487", "Id": "48947", "Score": "0", "body": "`raw_info` is a hash and `raw_info['picture']` is just a string." } ]
[ { "body": "<p>Overall, it's reasonably tight code. You've taken steps to reduce method size, which is good.</p>\n\n<p>To answer your questions specifically:</p>\n\n<ol>\n<li><p>I think an instance variable would be better, because then you can avoid the else clauses you mention in 2. Those methods can then be reduced to 1 or 2 lines.</p></li>\n<li><p>see 1. :)</p></li>\n<li><p>If you create an image or picture object, it provides a convenient place to memoize results. I'm not sure this is that important though, as it's probably not likely you'd need to generate more than one URL for a given image in a single request.</p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T15:51:27.557", "Id": "48946", "Score": "0", "body": "I made a mistake in my first question. I used the term \"instance variable\" when I meant to say \"local variable\". `raw_info` is already an instance variable (well, it's a method with a memoized result). And it's a hash. But since I'm accessing the same hash key so many times, should I move it to a local variable? Or should I create a memoized method to hold `raw_info['picture']`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T15:55:52.327", "Id": "48948", "Score": "0", "body": "Also, what do you think of `if condition ... else ... end` and `return if condition ... else_branch`? Which do you prefer?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-31T14:43:58.397", "Id": "30566", "ParentId": "30194", "Score": "2" } }, { "body": "<p>You might consider using a case statement for <code>image_params</code>:</p>\n\n<pre><code> def image_params\n image_params = []\n case options[:image_size]\n when Integer\n ....\n when Hash\n ....\n else\n ....\n end\n .....\n end\n</code></pre>\n\n<p>You'll recall this works because <code>case</code> uses <code>===</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-29T22:23:44.180", "Id": "32001", "ParentId": "30194", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T00:25:26.997", "Id": "30194", "Score": "1", "Tags": [ "optimization", "ruby", "image" ], "Title": "Modifying an image URL based on hash options" }
30194
<p>I've implemented a rate limiter for redis in Lua, and I'm wondering if anyone has any suggestions that might improve the performance.</p> <p>An example use: </p> <pre><code>eval '[sha] mykey 1234567 60000 1000 1 10' 0 </code></pre> <p>Which translates to:</p> <ul> <li>Create a hash under key <code>mykey</code></li> <li>The current ms since the last epoch is <code>1234567</code></li> <li>Limit over a period of 60s</li> <li>Each bucket should be 1s</li> <li>Increment by 1</li> <li>The maximum number of increments for this limiter is 10</li> </ul> <p>Refer to <a href="https://chris6f.com/rate-limiting-with-redis">this</a> and <a href="https://groups.google.com/forum/#!topic/redis-db/F0jQzmBJKhg">this</a> for alternative implementations.</p> <pre><code>local key = KEYS[1] local time_in_ms = tonumber(ARGV[1]) local span_ms = tonumber(ARGV[2]) local bucket_ms = tonumber(ARGV[3]) local incrby = tonumber(ARGV[4]) local throttle = tonumber(ARGV[5]) local current_bucket = math.floor((time_in_ms % span_ms) / bucket_ms) local current_count = incrby local last_bucket = tonumber(redis.call('HGET', key, 'L')) local getting = {} if nil == last_bucket then -- this is a new rate limit hash (perhaps the old one expired?) redis.call('HINCRBY', key, current_bucket, incrby) redis.call('PEXPIRE', key, span_ms) redis.call('HSET', key, 'L', current_bucket) else local bucket_count = span_ms / bucket_ms -- clear unused buckets if last_bucket ~= current_bucket then local j = current_bucket while j ~= last_bucket do redis.call('HDEL', key, j) j = ((j - 1) % bucket_count) end end -- generate an array containing all of the possible fields local i = 0 while i &lt; bucket_count do local j = i + 1 getting[j] = i i = j end -- get all of the available values at once local all = redis.call('HMGET', key, unpack(getting)) for k, v in pairs(all) do current_count = current_count + (tonumber(v) or 0) end -- stop here if the throttle value will be surpassed on this request if throttle &lt; current_count then return throttle end -- only set the 'current bucket' if we're actually incrementing it's value if last_bucket ~= current_bucket then redis.call('HSET', key, 'L', current_bucket) end redis.call('HINCRBY', key, current_bucket, incrby) redis.call('PEXPIRE', key, span_ms) end return current_count </code></pre> <p>Setup:</p> <ul> <li>Calling this using <a href="https://code.google.com/p/booksleeve/">booksleeve</a>.</li> <li>Running redis in a virtual box Ubuntu 12.04 server vm on the same machine.</li> <li>The vm has 8gb mem, access to all cores of my computer.</li> <li>My computer uses an i7 950 @ 3.07GHz.</li> </ul> <p>I'm seeing approximately <strong>4.4 async ops per ms</strong>, or <strong>4,400 ops per second</strong>.</p> <h2>Revision 1</h2> <p>Darn, I actually lied. In my original code I was returning something like <code>{ current_count, ... }</code>, but for the purposes of this post I just trimmed it down to return the value itself. (if you noticed, the variable <code>getting</code> is never used, and it was one of the items I was returning). I've actually adjusted my code to return only <code>current_count</code>, and the performance went way up! (I still think it could be faster). Here's the latest version of my code, which also makes a few other adjustments:</p> <pre><code>local key = KEYS[1] local time_in_ms = tonumber(ARGV[1]) local span_ms = tonumber(ARGV[2]) local bucket_ms = tonumber(ARGV[3]) local incrby = tonumber(ARGV[4]) local throttle = tonumber(ARGV[5]) local current_bucket = math.floor((time_in_ms % span_ms) / bucket_ms) local current_count = incrby local last_bucket = tonumber(redis.call('HGET', key, 'L')) local not_same = last_bucket ~= current_bucket if nil ~= last_bucket then local bucket_count = span_ms / bucket_ms -- clear unused buckets if not_same then local j = current_bucket while j ~= last_bucket do redis.call('HDEL', key, j) j = ((j - 1) % bucket_count) end end -- generate an array containing all of the possible fields local getting = {} local bc = bucket_count + 1 for i = 1, bc, 1 do getting[i] = i - 1 end -- get all of the available values at once local all = redis.call('HMGET', key, unpack(getting)) for k, v in pairs(all) do current_count = current_count + (tonumber(v) or 0) end -- stop here if the throttle value will be surpassed on this request if throttle &lt; current_count then return (current_count - incrby) end end -- only set the 'current bucket' if we're actually incrementing it's value if not_same then redis.call('HSET', key, 'L', current_bucket) end redis.call('HINCRBY', key, current_bucket, incrby) redis.call('PEXPIRE', key, span_ms) return current_count </code></pre> <p>With this revision, I'm now seeing approximately <strong>10.2 async ops per ms</strong>, or <strong>10,200 ops per second</strong>. (Even if I just return <code>{ current_count }</code> - an array with a single element - I see only approximately <em>6.0 async ops per ms</em>!)</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-04-13T06:49:25.993", "Id": "234239", "Score": "0", "body": "A little bit off-topic but maybe relevant for anyone using redis. Windows now has bash, meaning that [you no longer need sloppy virtual machines](http://www.hanselman.com/blog/DevelopersCanRunBashShellAndUsermodeUbuntuLinuxBinariesOnWindows10.aspx) to install things like redis." } ]
[ { "body": "<p>I run the code in my laptop. I got 16594.76 requests per second.</p>\n\n<p>Environment:</p>\n\n<ul>\n<li>Ubuntu 15.10</li>\n<li>Run Redis natively (no VM)</li>\n<li>CPU: Intel(R) Core(TM) i7-2620M CPU @ 2.70GHz</li>\n<li>Mem: 16GB</li>\n</ul>\n\n<p>After some changes I got 17825.31 requests per second.</p>\n\n<pre>\n> local all = redis.call('HMGET', key, unpack(getting))\n> for k, v in pairs(all) do\n> current_count = current_count + (tonumber(v) or 0)\n> end\n</pre>\n\n<p>HMGET returns a non-sparse array. It's possible to iterate the array using <code>ipairs</code>, which is faster than <code>pairs</code>. I removed the explicit conversion to number, as Lua will automatically coerce the types if necessary. After the changes the loop looks like:</p>\n\n<pre>\n-- get all of the available values at once\nlocal all = redis.call('HMGET', key, unpack(getting))\nfor _, v in ipairs(all) do\n current_count = current_count + (v or 0)\nend\n</pre>\n\n<p>This is the biggest improvement. Then other minor things (which probably don't improve performance):</p>\n\n<pre>\n> local bc = bucket_count + 1\n> for i = 1, bc, 1 do\n> getting[i] = i - 1\n> end\n</pre>\n\n<p>1 increment is not necessary as it's the default; <code>bc</code> is only used once, can be replaced in the loop.</p>\n\n<pre>\nfor i = 1, bucket_count + 1 do\n getting[i] = i - 1\nend\n</pre>\n\n<pre>\n> if nil ~= last_bucket then\n</pre>\n\n<p>Same as:</p>\n\n<pre>\nif last_bucket then\n</pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2016-08-23T23:04:57.733", "Id": "139472", "ParentId": "30195", "Score": "3" } } ]
{ "AcceptedAnswerId": "139472", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T00:25:58.690", "Id": "30195", "Score": "11", "Tags": [ "performance", ".net", "lua", "redis" ], "Title": "Redis rate limiting in Lua" }
30195
<p>I have created a polymorphic system, but I don't know whether this is the correct way of doing it. Am I abusing Polymorphism here? Here is the code:</p> <pre><code>class WriteObj { public string Obj1 { get; set; } public string Obj2 { get; set; } public string Obj3 { get; set; } } </code></pre> <p>The above code is a data object that I am passing around in the methods, since I would be using a List of these objects.</p> <pre><code>abstract class BaseWriter { public abstract void Write(List&lt;WriteObj&gt; writeObjList); } class ConsoleWriter : BaseWriter { public override void Write(List&lt;WriteObj&gt; writeObjList) { for (int i = 0; i &lt; writeObjList.Count; i++) { Console.Writeline("I am in Console Writer, parameter: " + writeObjList[i].Obj1); } } } class FileWriter : BaseWriter { public override void Write(List&lt;WriteObj&gt; writeObjList) { for (int i = 0; i &lt; writeObjList.Count; i++) { Console.Writeline("I write in file, parameter: " + writeObjList[i].Obj1); } } } class DatabaseWriter : BaseWriter { public override void Write(List&lt;WriteObj&gt; writeObjList) { for (int i = 0; i &lt; writeObjList.Count; i++) { Console.Writeline("I write in database, parameter: " + writeObjList[i].Obj2); } } } </code></pre> <p>In my main method I call them like:</p> <pre><code> static void main() { List&lt;WriteObj&gt; col = new List&lt;WriteObj&gt;(); col.AddRange(new WriteObj[2] { new WriteObj { Obj1 = "this is obj1 iteration 1", Obj2 = "This is obj2 iteration 1" }, new WriteObj { Obj1 = "this is obj1 iteration 2", Obj2 = "This is obj2 iteration 2" } }); //some factory will generate these concrete types, //but the sake of simplicity I am instantiating it like that. BaseWriter a = new ConsoleWriter(); a.Write(col); BaseWriter b = new FileWriter(); b.Write(col); BaseWriter c = new DatabaseWriter(); c.Write(col); } </code></pre> <p><strong>Is it Ok to pass List of WriteObj in the Write method of the respective concrete implementations?</strong></p> <p><hr> <strong>Update :</strong> I have used abstract class because it will be having some methods in it. I haven't mentioned it here for the sake of simplicity.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T09:48:35.737", "Id": "47989", "Score": "1", "body": "Seems ok. I might consider making the Writer method take a more generic parameter, perhaps ICollection or even a ReadOnlyCollection to enforce an abstraction that the method is there to write the data and not alter it?" } ]
[ { "body": "<p>Yes, I don't see a problem with that.</p>\n\n<p>If you don't have any implementation at all in the base class, consider making it an interface instead:</p>\n\n<pre><code>interface IWriter {\n void Write(List&lt;WriteObj&gt; writeObjList);\n}\n\nclass ConsoleWriter : IWriter {\n public void Write(List&lt;WriteObj&gt; writeObjList) {\n foreach (WriteObj obj in writeObjList) {\n Console.Writeline(\"I am in Console Writer, parameter: \" + obj.Obj1);\n }\n }\n}\n\netc.\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T07:50:01.707", "Id": "30204", "ParentId": "30202", "Score": "4" } }, { "body": "<p>Yes, you could take that way. I would recomend to make BaseWriter an interface IWriter too. But I have an other suggestion.</p>\n\n<pre><code>interface IWriter\n{\n void Write(List&lt;WriteObject&gt; writeObjectList);\n}\n\npublic class ConsoleWriter : IWriter\n{\n public void Write(List&lt;WriteObject&gt; writeObjectList)\n {\n // your implementation\n }\n}\n\npublic class Writer // bad name but I dont have a better now\n{\n private IWriter _writer; // or make it public and delete the constructor\n\n public Writer(IWriter writer)\n {\n _writer = writer;\n }\n\n public void Write(List&lt;WriteObject&gt; writeObjectList)\n {\n _writer.Write(writeObjectList);\n }\n}\n</code></pre>\n\n<p>In this case, you do not use polymorphism. So your design is more flexible.\nYou could change the way of writing your objects while runtime.\nGive it a try ;-)</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T18:22:29.310", "Id": "30215", "ParentId": "30202", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T07:29:53.423", "Id": "30202", "Score": "2", "Tags": [ "c#", "object-oriented", "polymorphism" ], "Title": "designing application using polymorphism" }
30202
<p>Can you please take a look at my code and improve it (if necessary)?</p> <p><a href="http://jsfiddle.net/U6R6E/" rel="nofollow">http://jsfiddle.net/U6R6E/</a></p> <p><strong>Javascript (with jQuery)</strong></p> <pre><code>function random(min, max) { return min + parseInt(Math.random() * (max - min + 1), 10); } function generatePassword() { var length = parseInt($('#pwLength').val(), 10), charset = $('#pwChars').val(), password = ""; while (length &gt; 0) { length -= 1; console.log(length); password += charset[random(0, charset.length - 1)]; } return password; } function getNewPassword() { $('#pwResult').html(generatePassword()); } $(document).ready(function () { getNewPassword(); $('#getNewPw').click(function () { getNewPassword(); return false; }); }); </code></pre> <p><strong>HTML</strong></p> <pre><code>&lt;ul&gt; &lt;input type="text" id="pwChars" value="AaBbCcDdEeFfGgHhiJjKkLMmNnoPpQqRrSsTtUuVvWwXxYyZz23456789!?$%#&amp;@+-*=_.,:;()" /&gt; &lt;li&gt;&lt;input type="text" id="pwLength" value="10" /&gt;&lt;/li&gt; &lt;li&gt;&lt;button id="getNewPw"&gt;New&lt;/button&gt;&lt;/li&gt; &lt;/ul&gt; &lt;div id="pwResult" contenteditable="true"&gt;&lt;/div&gt; </code></pre>
[]
[ { "body": "<p><code>Math.random()</code> <a href=\"http://ifsec.blogspot.com/2012/05/cross-domain-mathrandom-prediction.html\">doesn't return cryptographically secure numbers on all browsers</a>. If this is intended for production use, you'll want to use <a href=\"http://crypto.stanford.edu/sjcl/\">a library that has a secure PRNG</a>.</p>\n\n<p>If you're not going to go with Jerry's suggestion to make pronounceable passwords, I'd recommend at least getting rid of 1/l/I and O/0, which a number of password generators do by default, because people often mis-read them and then request a password reset.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-08T16:27:37.533", "Id": "70739", "Score": "0", "body": "thanks! Can you write me the steps how to install the \"Stanford Javascript Crypto Library\" in my script or maybe do it in my JSfiddle? ;)" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T19:14:19.283", "Id": "30217", "ParentId": "30211", "Score": "8" } }, { "body": "<p>Some comments on your code:</p>\n\n<ol>\n<li><p>CSS's naming convention is to use hyphens, so instead of <code>pwChars</code> you'd write <code>pw-chars</code>.</p></li>\n<li><p>You could simplify your code with a Fisher-Yates shuffle helper from <a href=\"https://stackoverflow.com/a/15752140/670396\">here</a>, then you can write your logic in a few lines, but this method requires as many distinct characters as the length needed. So if you need an 8 character password there must be at least 8 characters in the dictionary. </p>\n\n<pre><code>$('#getNewPw').click(function () {\n $('#pwResult').text(function () {\n var chars = $('#pwChars').val().split('');\n var len = $('#pwLength').val();\n return shuffle(chars).slice(0, len).join('');\n });\n}).click();\n</code></pre>\n\n<p><strong>Demo:</strong> <a href=\"http://jsfiddle.net/U6R6E/4/\" rel=\"nofollow noreferrer\">http://jsfiddle.net/U6R6E/4/</a></p></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T15:57:30.010", "Id": "70851", "Score": "0", "body": "Just on a side note: You're talking about CSS, but there is no CSS in his code. What you're talking about are HTML classes. Also there is no official naming convention for HTML ID's and classes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T20:09:18.563", "Id": "71178", "Score": "0", "body": "@kleinfreund Even though there is no CSS in the code, HTML id's are usually used for CSS (and JavaScript, of course). And even though there might not be any official naming conventions for HTML ID's and classes, `pw-chars` does seem more common than `pwChars`. I rarely see camelcasing on HTML ids and classes. (That being said, it doesn't mean that there is necessarily anything wrong with camelcasing them...)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-11T20:13:41.053", "Id": "71179", "Score": "1", "body": "@Simon This is right. Naming in HTML is usually done by dash-delimiting instead of camelcasing. Also there are rarely capital letters. I just wanted to be precise, because it's a common mistake speaking of _CSS classes_, which do not exist." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T07:09:34.603", "Id": "41276", "ParentId": "30211", "Score": "3" } }, { "body": "<p>Your code looks really good! However, since I have to nitpick...</p>\n\n<ul>\n<li><p>I would definitely save your jQuery selectors, since they are really constants. And so that you're not making globals, I'd also create a IIFE.</p></li>\n<li><p>Your random function is excellent, but <code>parseInt</code> is quite slow, there's a bit-twiddling trick you can use to convert a double to an int using <code>~~</code>, so I've changed it to that. Or use <code>Math.round()</code>.</p></li>\n</ul>\n\n<p>Everything else I would keep the same :)</p>\n\n<pre><code>(function () {\n\n var $length, $result, $new, $chars;\n\n $(document).ready(function () {\n\n $length = $('#pw-length');\n $result, = $('#pw-result');\n $new = $('#get-new-pw');\n $chars = $('#pwChars');\n\n getNewPassword();\n $new.click(function () {\n getNewPassword();\n return false;\n });\n\n });\n\n // get password\n function random(min, max) {\n return min + ~~(Math.random() * (max - min + 1));\n }\n\n [...]\n\n}());\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-09T11:26:19.563", "Id": "41282", "ParentId": "30211", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T14:33:02.820", "Id": "30211", "Score": "8", "Tags": [ "javascript", "jquery", "performance", "random" ], "Title": "Improve random password generator" }
30211
<p>This is a quick and dirty implementation of coroutines that implements yield by saving and restoring the stack to and from the heap. Here's an earlier version, which does <a href="https://github.com/danluu/setjmp-longjmp-ucontext-snippets/blob/master/coroutines.c">the most naive possible thing</a>, and just allocates enough space on the stack for every possible coroutine. The relevant bits from the current code are below, and the <a href="https://github.com/danluu/setjmp-longjmp-ucontext-snippets/blob/master/heapros.c">whole thing is here</a>.</p> <p>I'm open to feedback both on pretty much anything: completely different approaches, how to restructure this approach, bugs, idiomatic C style pointers, etc.</p> <p>An obvious performance improvement would be to use ucontext, but that seems to be deprecated and somewhat broken on Mac OS X (although it works fine on the linux distros I've tried). I'm not sure what the next step is to make this 'better'.</p> <pre class="lang-c prettyprint-override"><code>typedef void (*coroutine_cb)(); static void scheduler(coroutine_cb); static int spawn(coroutine_cb); static void yield(int); jmp_buf scheduler_jmp; void *scheduler_rbp; int coro_pid; coroutine_cb scheduler_next_coro; #define MAX_COROS 100 struct { jmp_buf jmp; void *stack; long stack_sz; } coroutines[MAX_COROS]; static void scheduler(coroutine_cb coro) { printf("starting the scheduler...\n"); static int max_pid = 1; // we move down 0x1000 to give scheduler space to call functions and allocate stack variables without having them get // overwritten by the memcpy below. Before we did this, we had to manually copy memory instead of using memcpy // because we would overwrite memcpy's stack scheduler_rbp = __builtin_frame_address(0) - 0x1000; scheduler_next_coro = coro; int value = setjmp(scheduler_jmp); // value == 0 means just starting // value == -1 means spawning new coroutine // value positive means hop back to a specific pid if (value == 0 || value == -1) { coro_pid = max_pid++; printf("about to run coro %d...\n", coro_pid); char *buf = alloca(0x2000); // was 0x1000 when we didn't allocate extra space for scheduler stack asm volatile("" :: "m" (buf)); scheduler_next_coro(); assert(0); } else { printf("jumped back to scheduler (pid --&gt; %d) (coro_pid --&gt; %d)...\n", value, coro_pid); // restore coroutine marked by value (pid) coro_pid = value; int stack_sz; stack_sz = coroutines[coro_pid].stack_sz; memcpy(scheduler_rbp - stack_sz, coroutines[coro_pid].stack, stack_sz); longjmp(coroutines[coro_pid].jmp, 1); assert(0); } } static void yield(int pid) { // take current rbp void *rbp = __builtin_frame_address(0); void *fudgy_rsp = (char *)rbp - 0x100; assert(scheduler_rbp &gt; rbp); long stack_sz = (char *)scheduler_rbp - (char *)fudgy_rsp; void *stack = malloc(stack_sz); /* * Marek: check how overflowing stack actually works, because * we're actually copying data beyond our stack frame. */ memcpy(stack, fudgy_rsp, stack_sz); coroutines[coro_pid].stack = stack; coroutines[coro_pid].stack_sz = stack_sz; if (!setjmp(coroutines[coro_pid].jmp)) { longjmp(scheduler_jmp, pid); assert(0); } else { // our stack is already good to go at this point return; } } /* * */ static int spawn(coroutine_cb coro) { scheduler_next_coro = coro; yield(-1); return 0; // need to get pid } int main() { scheduler(f); assert(0); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T21:10:24.493", "Id": "48008", "Score": "0", "body": "Apart from BSD linux." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T23:08:29.027", "Id": "48012", "Score": "0", "body": "Are you trying to implement coroutines or userland threads?" } ]
[ { "body": "<h1>Things you did well on:</h1>\n\n<ul>\n<li>Overall, this looks like a pretty decent little bit of code. It looks like some research went into this</li>\n<li>I like the comments. Everywhere I was confused on something, there was a comment to clarify. You also didn't go overboard with them!</li>\n</ul>\n\n<hr>\n\n<h1>Things you could improve on:</h1>\n\n<h3>Preprocessor:</h3>\n\n<ul>\n<li>Group all of your <code>#define</code>s at the top of your code, just after your <code>#import</code>s. Otherwise you will have to jump around your code to find them.</li>\n</ul>\n\n<h3>Initialization:</h3>\n\n<ul>\n<li><p><code>typedef</code> your <code>struct</code>s.</p>\n\n<blockquote>\n<pre><code>struct {\n jmp_buf jmp;\n void *stack;\n long stack_sz;\n} coroutines[MAX_COROS];\n</code></pre>\n</blockquote>\n\n<p>The <code>typedef</code> means you no longer have to write <code>struct</code> all over the place. That not only saves keystrokes, it also can make the code cleaner since it provides a smidgen more abstraction.</p></li>\n<li><p>You can initialize some variables right away.</p>\n\n<blockquote>\n<pre><code>int stack_sz; \nstack_sz = coroutines[coro_pid].stack_sz;\n</code></pre>\n</blockquote>\n\n<pre><code>int stack_sz = coroutines[coro_pid].stack_sz;\n</code></pre></li>\n</ul>\n\n<h3>Syntax:</h3>\n\n<ul>\n<li><p>You use <code>print()</code> where it is unneeded.</p>\n\n<blockquote>\n<pre><code>printf(\"starting the scheduler...\\n\");\n</code></pre>\n</blockquote>\n\n<p>You can use <a href=\"http://www.cplusplus.com/reference/cstdio/puts/\" rel=\"nofollow\"><code>puts()</code></a> instead.</p>\n\n<pre><code>puts(\"Starting the scheduler...\");\n</code></pre></li>\n</ul>\n\n<h3>Memory:</h3>\n\n<ul>\n<li><p>You allocated memory to <code>stack</code>, but never free it.</p>\n\n<blockquote>\n<pre><code>void *stack = malloc(stack_sz);\n</code></pre>\n</blockquote>\n\n<p>Failure to deallocate memory using free leads to buildup of non-reusable memory, which is no longer used by the program. This wastes memory resources and can lead to allocation failures when these resources are exhausted.</p>\n\n<pre><code>free(stack);\n</code></pre></li>\n</ul>\n\n<h3>Comments:</h3>\n\n<ul>\n<li><p>You could use the <code>/* ... */</code> comment format instead of the <code>// ...</code> format when commenting over multiple lines.</p>\n\n<blockquote>\n<pre><code>// value == 0 means just starting\n// value == -1 means spawning new coroutine\n// value positive means hop back to a specific pid\n</code></pre>\n</blockquote>\n\n<p>You could also condense your comments down a bit.</p>\n\n<pre><code>/* \n * If 'value' is 0, it is just starting; if -1 it is spawning.\n * If 'value' is positive, we \"hop\" to a specific PID.\n */\n</code></pre></li>\n</ul>\n\n<hr>\n\n<h1>Resources:</h1>\n\n<ul>\n<li><a href=\"https://en.wikipedia.org/wiki/Coroutine#Implementations_for_C\" rel=\"nofollow\">Coroutine implementations for C</a></li>\n<li><a href=\"http://www.chiark.greenend.org.uk/~sgtatham/coroutines.html\" rel=\"nofollow\">Coroutines in C</a></li>\n<li><a href=\"http://www.csl.mtu.edu/cs4411.ck/www/NOTES/non-local-goto/coroutine.html\" rel=\"nofollow\">Building Coroutines</a></li>\n<li><a href=\"http://swtch.com/libtask/\" rel=\"nofollow\">Libtask: a Coroutine Library for C and Unix</a> </li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-22T22:38:03.323", "Id": "199295", "Score": "0", "body": "Why is puts better than printf here?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-22T22:41:27.633", "Id": "199298", "Score": "0", "body": "@d33tah `printf()` is used to format strings for printing to the string. Since we are not formatting our string, we can avoid the processes that `printf()` would use to search for these formatting delimiters and therefore be more efficient in printing the text (miniscule, but measureable). It also avoids the need to put the `\\n` at the end of the line, which can be a common mistake." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-22T22:43:29.553", "Id": "199299", "Score": "0", "body": "On the other side, it makes it easier to add data if you leave printf instead of puts - you just add some %d for example and an extra argument. I wonder if printf is actually slower if you're not really doing anything... The only extra work I would expect it to do is format string parsing." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-22T22:47:13.187", "Id": "199300", "Score": "1", "body": "@d33tah Agreed that it would be easier, but that doesn't mean that is the best practice. `goto` makes some things easier, doesn't make that a good practice. As for it being slower, `printf()` *must* transverse the entire string to search for delimiters and then manipulate them (an O(n) operation at least), whereas printing the string without formatting it is more straightforward (should be an O(1) operation)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-22T22:49:21.867", "Id": "199301", "Score": "0", "body": "I agree on both of your points, thanks for explaining!" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T01:27:04.017", "Id": "42092", "ParentId": "30214", "Score": "7" } }, { "body": "<p>No concrete suggestion for improvement at this time, but I'd just like to point out that your use of <code>assert(0)</code> is brilliant. It emphasizes to other programmers that those positions in the code are unreachable, and enforces it during development time. Also, assertions are the right mechanism to use, since those positions in the code would only be reachable due to programmer error, not due to unanticipated runtime conditions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-19T22:21:06.860", "Id": "42205", "ParentId": "30214", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T18:13:53.777", "Id": "30214", "Score": "11", "Tags": [ "c", "stack", "concurrency" ], "Title": "How can this simple coroutine implementation be improved?" }
30214
<p>I need to bind a <code>dropdown</code> to an <code>enum</code>. For this I've made a <code>key_value_pair</code> class and I manually go through each <code>enum</code> option to add it. Is there a more elegant way to achieve this?</p> <p>HTML:</p> <pre><code>&lt;select data-bind="options: regions, value: region, optionsValue: 'key', optionsText: 'value'"&gt;&lt;/select&gt; </code></pre> <p>TypeScript:</p> <pre><code>class key_value_pair&lt;key_type, value_type&gt; { key: key_type; value: value_type; constructor(key: key_type, value: value_type) { this.key = key; this.value = value; } } class calculator { regions: KnockoutObservableArray&lt;key_value_pair&lt;number, string&gt;&gt;; region: KnockoutObservable&lt;API.region&gt;; constructor() { this.regions = ko.observableArray(); this.regions.push(new key_value_pair(API.region.US, API.region[API.region.US])); this.regions.push(new key_value_pair(API.region.Europe, API.region[API.region.Europe])); this.regions.push(new key_value_pair(API.region.Korea, API.region[API.region.Korea])); this.regions.push(new key_value_pair(API.region.Taiwan, API.region[API.region.Taiwan])); this.regions.push(new key_value_pair(API.region.China, API.region[API.region.China])); this.region = ko.observable(); } } </code></pre>
[]
[ { "body": "<p>Your solution works fine and I didn't find a better solution. I've just upgraded it little bit, by automatic fill the options, so it is usable to any <code>Enum</code> class.</p>\n\n<p><a href=\"https://stackoverflow.com/a/21294925/984081\">Here I found how to enumerate <code>Enum</code> type</a></p>\n\n<pre><code>export class SelectEditorObject\n{\n private options: KnockoutObservableArray&lt;keyValuePair&lt;number, string&gt;&gt;;\n private selection: KnockoutObservable&lt;number&gt;;\n\n constructor(e: any, value: number)\n {\n var options = SelectEditorObject.getNamesAndValues(e);\n this.selection = ko.observable&lt;number&gt;(value);\n this.options = ko.observableArray&lt;keyValuePair&lt;number, string&gt;&gt;(options);\n }\n\n public toString()\n {\n var selected = undefined;\n this.options().forEach((pair) =&gt;\n {\n if (pair.key === this.selection())\n {\n selected = pair.value;\n }\n }, this);\n return selected;\n }\n\n public getValue()\n {\n return this.selection();\n }\n\n private static getNames(e: any)\n {\n return Object.keys(e).filter(v =&gt; isNaN(parseInt(v, 10)));\n }\n\n private static getValues(e: any)\n {\n return Object.keys(e).map(v =&gt; parseInt(v, 10)).filter(v =&gt; !isNaN(v));\n }\n\n public static getNamesAndValues(e: any): Array&lt;keyValuePair&lt;number, string&gt;&gt;\n {\n return SelectEditorObject.getValues(e).map(v =&gt; { return new keyValuePair(v, e[v]) });\n }\n}\n\nexport class keyValuePair&lt;key_type, value_type&gt;\n{\n public key: key_type;\n public value: value_type;\n constructor(key: key_type, value: value_type)\n {\n this.key = key;\n this.value = value;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-08T12:48:23.043", "Id": "196083", "Score": "0", "body": "Welcome to Code Review! Your answer proposes an alternative solution without reviewing the code. Please read [the following meta](http://meta.codereview.stackexchange.com/questions/1439/how-much-can-an-answer-be-subject-to-opinion/1440#1440) to see what makes for good answers and what doesn't." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-08T15:34:33.500", "Id": "196112", "Score": "0", "body": "Sorry, I am new here and i don't understand what is wrong woth my post. I don't propose alternative solution, just improving reuseability of this class.\nWhat is, in fact, answer to original post, where author asks, if there was the better solution than go through each value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-08T15:38:39.420", "Id": "196115", "Score": "0", "body": "I should've stated that better. You answered with a re-write without stating why yours is better. Code Review is all about explaining why something is better, so a little explanation of why you made these changes would turn it into a decent answer." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-10-08T12:30:39.487", "Id": "106939", "ParentId": "30216", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T18:37:29.703", "Id": "30216", "Score": "2", "Tags": [ "enum", "typescript" ], "Title": "\"options\" binding with an enum as data source" }
30216
<p>I want to access some of the methods from outside of the plugins scope, namely <code>showPopup()</code>, <code>hidePopup()</code> and <code>updateColor(newcolor)</code>.</p> <h3>Initialization</h3> <pre><code>&lt;span class="cp"&gt;&lt;/span&gt; &lt;script&gt; var cp = $(".cp").ColorPickerSliders({ flat: true, order: { hsl: 1, preview: 2 } }); &lt;/script&gt; </code></pre> <h3>What I want to do</h3> <p>Something like</p> <pre><code>cp.updateColor('red'); </code></pre> <p>or</p> <pre><code>$(".cp").ColorPickerSliders('updateColor', 'red'); </code></pre> <p>Which one is the preferred way, and how to refactor the code to accomplish it?</p> <p>I achieved it using triggers, but don't know if it has any downsides or is a good way to do these kind of interaction. So I registered a custom event handler inside the plugin's code (Line 320, <code>triggerelement</code> is the original element the plugin is called on):</p> <pre><code>triggerelement.on('jquerycolorpickersliders.updateColor', function(e, newcolor) { updateColor(newcolor); }); </code></pre> <p>And call it using this code (where <code>cp</code> is the element the plugin is called on):</p> <pre><code>cp.trigger('jquerycolorpickersliders.updateColor', 'red'); </code></pre> <p><a href="http://jsfiddle.net/styu/5H8cA/3/" rel="nofollow noreferrer">jsFiddle</a>.</p> <p>What do you think of it? Is it an acceptable solution for the problem, or is there a better one?</p>
[]
[ { "body": "<p>Firstly, underneath everything Javascript is an event driven language so I do not think that there is anything wrong with using an event driven design pattern if you are comfortable with it. Events are a great way to be able to interlink different components of your system without exposing the inner workings of them (loose coupling) and they add queuing by default. However they are more complex, they make it hard to trace behavior which in turn can make them hard to debug.</p>\n\n<p>I think that you would get a cleaner interface by developing using something called the revealing module pattern, there is an excellent resource on various design patterns by a guy called Addy Osmani at <a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/\" rel=\"nofollow\">adyosmanio.com</a> and the revealing module pattern specifically <a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/#revealingmodulepatternjavascript\" rel=\"nofollow\">here</a>. This (or a flavor of it) is commonly used in jQuery plugin development which you can see on the jQuery <a href=\"http://learn.jquery.com/plugins/advanced-plugin-concepts/\" rel=\"nofollow\">advanced plugin development page</a> (see <strong>Keep private functions private</strong>). By following these principles you can keep the private stuff private and only expose the functions that you want the calling code to have access to.</p>\n\n<p>You mentioned specifically <code>showPopup()</code>, <code>hidePopup()</code> and <code>updateColor(newColor)</code> so a quick example of how that might look.</p>\n\n<pre><code>;(function($) {\n var ColorPickerSliders = function($element, options) {\n //if you want publicly modifiable configuration options.\n var defaults = {\n \"opacity\": 0,\n \"hsl\": 1,\n ...\n };\n\n function init() {\n ...\n }\n\n function showPopup()\n {\n ...\n }\n\n function hidePopup()\n {\n ...\n }\n\n function updateColor(newColor) {\n //uses private function\n var updatedcolor = tinyColor(newColor);\n ...\n\n }\n\n //private\n function tinyColor(newColor) {\n ...\n }\n\n //private\n function buildHtml()\n {\n ...\n }\n\n //this is the bit that makes your functions public\n //note that each function returns $element to preserve\n //chaining capabilities.\n return {\n \"showPopup\": function() {\n showPopup();\n return $element;\n },\n \"hidePopup\": function() {\n hidePopup();\n return $element;\n },\n \"updateColor\": function(newColour) {\n updateColor(newColour);\n return $element;\n }\n }\n };\n\n //the use of the data in here is to prevent the plugin being instantiated multiple times\n $.fn.colorPickerSliders = function(options) {\n return this.each(function() {\n if (!$(this).data('colorPickerSliders'))\n $(this).data('colorPickerSliders', new ColorPickerSliders(this, options));\n });\n };\n})(jQuery)\n</code></pre>\n\n<p>Using the above you can then pull the plugin api from the element using:</p>\n\n<pre><code>$yourElement.data('colorPickerSliders').showPopup();\n</code></pre>\n\n<p>And you can chain:</p>\n\n<pre><code>$yourElement.data('colorPickerSliders').showPopup().delay(1000).hidePopup();\n</code></pre>\n\n<p>For reference you can also check this excellent article from <a href=\"http://coding.smashingmagazine.com/2011/10/11/essential-jquery-plugin-patterns/\" rel=\"nofollow\">Smashing Magazine</a> (check the author) and related <a href=\"https://github.com/jquery-boilerplate/jquery-patterns/\" rel=\"nofollow\">GitHub repository</a>.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T11:18:27.697", "Id": "49204", "Score": "0", "body": "I can agree that the interface is cleaner with the revealing module pattern, yet if I take the whole plugin, the version with the triggers seems simpler to me.\nWhat I really don't like is to call .data('pluginName') to access the methods, but I think it can be avoided with a little refactoring, so I will play with it some more.\nBounty went!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T09:02:29.023", "Id": "30726", "ParentId": "30218", "Score": "3" } } ]
{ "AcceptedAnswerId": "30726", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T20:07:21.440", "Id": "30218", "Score": "1", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "jQuery Color Picker Sliders plugin" }
30218
<p>Please review my code.</p> <pre><code>public class CircularLinkedlistinsert { private Node first; private static class Node { int element; Node next; public Node(int element, Node next) { this.element = element; this.next = next; } } public void insertNodeInCircularLL(int element) { Node node = new Node(element, null); if (first == null) { first = node; first.next = first; } else { Node current = first; do { if (((current.element &lt;= element) &amp;&amp; (current.next.element &gt;= element)) || current.next == first) { node.next = current.next; current.next = node; if (element &lt; first.element) { first = node; } return; } current = current.next; } while (current != first); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T03:36:08.457", "Id": "48023", "Score": "2", "body": "You've fallen into the indentation trap. Add a return statement to the true case of the if statement and get ride of the else syntax." } ]
[ { "body": "<pre><code>public class CircularLinkedlistinsert {\n</code></pre>\n\n<p>Class names should have the first letter of each word capitalized. I'd also change the name to remove the activity and just describe the object. i.e., <code>CircularLinkedList</code>. The method names will describe whatever action is taken.</p>\n\n<pre><code>private static class Node {\n int element;\n Node next;\n</code></pre>\n\n<p>While it doesn't matter too much since this is a <code>private</code> nested class, the <code>element</code> and <code>next</code> fields should in theory be <code>private</code> as well and accessed via <code>getElement() / getNext()</code> and <code>setElement() / setNext()</code> methods. This promotes encapsulation and good object-oriented practices. (This is a purist observation, and what you've done works fine for your model.)</p>\n\n<pre><code>public void insertNodeInCircularLL(int element)\n</code></pre>\n\n<p>Again, I'd rename this method for style points. Since the entire class is a <code>CircularLinkedList</code>, we can just call this <code>insertNode()</code>, or even something as simple as <code>add()</code> or <code>put()</code>.</p>\n\n<p>The problem with the rest of the implementation, to me, is that you are using the <code>element</code> field both as the content of the <code>Node</code> and its position in the linked list. That's a problem. What if I pass in an <code>int</code> to the method that <em>isn't</em> the next logical number in the sequence? What if I pass in something like <code>-1</code>?</p>\n\n<p>It looks like, based on this if statement (<code>((current.element &lt;= element) &amp;&amp; (current.next.element &gt;= element))</code>), that you're trying to facilitate inserting a node <em>in between</em> two other nodes. I think there might be a more sane way to do it, however even if you want to continue with this approach and allow the client code to pass in an index directly, you will need to do some sanity checking of the input before processing.</p>\n\n<p>I think you need to have the <code>element</code> field be something managed internally, with only the <em>content</em> of the node passed in to the insert method. This is more of a logic error in your implementation than an issue with your coding style or practices, though.</p>\n\n<p>Two more advanced notes from this:</p>\n\n<ul>\n<li><p>If you do end up generating the IDs yourself, you ought to look into <a href=\"http://docs.oracle.com/javase/tutorial/essential/concurrency/syncmeth.html\" rel=\"nofollow\">synchronization</a> to avoid problems with multithreading.</p></li>\n<li><p>This <code>CircularLinkedList</code> can only accept nodes which hold <code>int</code> information. You could change the <code>element</code> field to be a true <code>id</code>, and then use <a href=\"http://docs.oracle.com/javase/tutorial/java/generics/\" rel=\"nofollow\">Generics</a> to make your implementation truly powerful.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T21:01:18.157", "Id": "30220", "ParentId": "30219", "Score": "4" } } ]
{ "AcceptedAnswerId": "30220", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T20:42:31.680", "Id": "30219", "Score": "3", "Tags": [ "java", "linked-list", "circular-list" ], "Title": "Insert in circular linked list" }
30219
<p>This is only my second Python script, so let me have it! If anything seems off in style or implementation, please nit pick away. I want to learn. I know it could've been done in less lines of code without making separate functions and whatnot, but I wanted to approach it like I would an actual project.</p> <pre><code>#!/bin/usr/python from sys import exit def print_help(): print("") print("--------------------------------") print(" Command | Description") print("--------------------------------") print(" -h | Print help list") print(" -x | Exit program") print("--------------------------------") print("") def is_valid_word(word): return word and word.isalpha() def is_valid_string(string): for word in string.split(" "): if not is_valid_word(word): return False return True def get_pig_latin(string): vowels = "aeiou" built = "" for word in string.split(" "): if len(word) &lt; 2 or word[0] in vowels: built += word + "tay" else: temp = word while temp[0] not in (vowels + "y"): temp = temp[1:] + temp[0] built += temp + "ay" built += " " built = built[0].upper() + built[1:] return built def print_title(): print("") print("--------------------------------") print("----- PIG LATIN TRANSLATOR -----") print("--------------------------------") print("Type -h for help") print("") def run(): commands = { "-h" : print_help, "-x" : exit } print_title() while True: input = raw_input(":: ").strip().lower() if input in commands: commands[input]() elif is_valid_string(input): print("-&gt; " + get_pig_latin(input) + "\n") else: print(" Unrecognized word or command.\n") if __name__ == "__main__": run() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T06:27:54.137", "Id": "48029", "Score": "2", "body": "@tintinmj This is Python2 not Python3. `raw_input` is in Python2 not Python3" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T07:11:12.580", "Id": "48030", "Score": "1", "body": "Simplify `is_valid_string()` with the `all()` function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T08:16:58.160", "Id": "48035", "Score": "0", "body": "`word and word.isalpha()` can be replaced with `word.isalpha()`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T12:55:33.927", "Id": "48060", "Score": "0", "body": "@AseemBansal yes I realize that later, but then I can't roll back my edit." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T13:16:04.900", "Id": "48062", "Score": "0", "body": "@AseemBansal Is there a more \"Python 3\" way of doing `raw_input()`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T15:02:29.277", "Id": "48070", "Score": "0", "body": "@JeffGohlke Are you working with Python2 or 3? This code here won't work with Python3. `raw_input` has been renamed as `input` and the `input` function from Python2 is gone. So in Python3 use `input` when you want to use `raw_input` of Python2." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T15:07:37.423", "Id": "48072", "Score": "0", "body": "@tintinmj You can edit it again in such a situation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-12T04:29:59.160", "Id": "120920", "Score": "0", "body": "@asteri if you're using Python 3 you should use `input`, if you're using Python 2, you should use `from __future__ import print_function` if you're going to wrap all your prints in parentheses (which is good, but you're not actually using the function w/o the future import)." } ]
[ { "body": "<p>Not essential but I would find it neater to make a function that translates a single word, then join those together. You should also deal with the case of a word containing no vowels or 'y', which currently gets your programme stuck in an infinite loop.</p>\n\n<pre><code>def get_pig_latin(string):\n return ' '.join(map(translate_word, string.split(' '))).upper()\n\ndef translate_word(word):\n vowels = \"aeiou\"\n if len(word) &lt; 2 or word[0] in vowels:\n return word + 'tay'\n elif contains_any(word, vowels + 'y'):\n while word[0] not in (vowels + 'y'):\n word = word[1:] + word[0]\n return word + 'ay'\n else:\n return '???'\n</code></pre>\n\n<p>Then <a href=\"http://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow\">add docstrings</a> to your functions.</p>\n\n<p>EDIT: It might be better to use a <code>for</code> loop instead...</p>\n\n<pre><code>def translate_word(word):\n if len(word) &lt; 2 or word[0] in 'aeiou':\n return word + 'tay'\n for i, ch in enumerate(word):\n if ch in 'aeiouy':\n return word[i:] + word[:i] + 'ay'\n return '???'\n</code></pre>\n\n<p>You could also consider building the string validation into your translation function with a user-defined exception:</p>\n\n<pre><code>class TranslationError(Exception):\n def __init__(self, value):\n self.value = value\n\ndef translate(word):\n if word.isalpha():\n if len(word) &lt; 2 or word[0] in 'aeiou':\n return word + 'tay'\n for i, ch in enumerate(word):\n if ch in 'aeiouy':\n return word[i:] + word[:i] + 'ay'\n # if there is no aeiouy or word is not alphabetic, raise an error\n raise TranslationError(word) \n\ndef run():\n commands = { \"-h\" : print_help, \n \"-x\" : exit }\n print_title()\n while True:\n inp = raw_input(\":: \").strip().lower()\n if inp in commands:\n commands[inp]()\n else:\n try:\n translation = ' '.join(map(translate, inp.split(' '))).upper()\n print(\"-&gt; \" + translation + \"\\n\")\n except TranslationError as e:\n print(\" Unable to translate:\" + e.value + \".\\n\")\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T21:30:34.660", "Id": "30222", "ParentId": "30221", "Score": "3" } }, { "body": "<p>Firstly there is an error in your program. </p>\n\n<pre><code>while temp[0] not in (vowels + \"y\"):\n temp = temp[1:] + temp[0]\n</code></pre>\n\n<p>If the word entered did not have any vowels then what? It is an infinite loop in that case.</p>\n\n<p>Now starting with your functions. You can use a triple quoted strings in the <code>print_help</code> function. It can be made like this. That way if you needed to change something you can do that without adding any other function call. Also it is clearer this way. The same for <code>print_title()</code> function.</p>\n\n<pre><code>def print_help():\n print(\n \"\"\"\n--------------------------------\n Command | Description\n--------------------------------\n -h | Print help list\n -x | Exit program\n--------------------------------\n\"\"\"\n )\n</code></pre>\n\n<p>About the choice of your variable names, don't use <code>string</code> and <code>input</code>. They are too general. Actually <code>input</code> is a function in Python so using that variable you made that function unusable. That is really bad. If you want such names use an underscore after there names. That may take out the problems of accidentally using in-built keywords.</p>\n\n<p>Other than that I think this is good. Calling functions by using dictionary to store their values. I learnt something.</p>\n\n<p><strong>EDIT</strong></p>\n\n<p>You are using <code>built += \" \"</code> in your function. This adds a whitespace at the end. The problem with that is that it adds a whitespace at the end of complete string also. I mean after the last word there is an extra whitespace. So you should use </p>\n\n<pre><code>built = built[0].upper() + built[1:-1]\n</code></pre>\n\n<p>to remove that extra whitespace.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T09:47:33.730", "Id": "48043", "Score": "0", "body": "A docstring is a string at the start of a function/module/etc. that describes it. What you are talking about is called a triple-quoted string." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T09:49:27.717", "Id": "48044", "Score": "0", "body": "@Stuart My bad. I used the wrong term. I edited that." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T06:48:09.077", "Id": "30245", "ParentId": "30221", "Score": "2" } } ]
{ "AcceptedAnswerId": "30222", "CommentCount": "8", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T21:07:29.323", "Id": "30221", "Score": "2", "Tags": [ "python", "pig-latin" ], "Title": "Python Pig Latin Translator" }
30221
<p>I am writing a small application that would interactively allow user for xml file manipulation with d3 interactive charts. </p> <p>My xml file has the following hierarchy : </p> <pre><code>&lt;?xml version="1.0" encoding="UTF-8" ?&gt; &lt;testcase&gt; &lt;measurement&gt; &lt;type&gt;M8015&lt;/type&gt; &lt;interval&gt;15&lt;/interval&gt; &lt;/measurement&gt; &lt;measurement&gt; &lt;type&gt;M8016&lt;/type&gt; &lt;interval&gt;15&lt;/interval&gt; &lt;/measurement&gt; &lt;measurement&gt; &lt;type&gt;M8020&lt;/type&gt; &lt;interval&gt;15&lt;/interval&gt; &lt;/measurement&gt; ... &lt;/testcase&gt; </code></pre> <p>What would be the most effective way to get the data out of xml into 2 arrays (one for x axis <code>type</code>, and one for y axis <code>interval</code>).</p> <p>I have tried the following but don't know if that's a good approach. </p> <pre><code>$(function() { var $mydata = new Array(1); $.get("./testcase.xml", function(xml) { var $chart = d3.select("body").append("div") .attr("class", "chart") .attr("id", "chart"); $(xml).find('measurement').each(function(){ var $meas = $(this); var $type = $meas.find('type').text(); var $interval = $meas.find('interval').text(); $mydata.push({'type': $type, 'interval': $interval}); }); }); </code></pre> <p>Any suggestions if that's the correct way of handling this problem ?</p>
[]
[ { "body": "<p>I suggest you use JSON when manipulating the data because it's easier and less code compared to the same XML counterpart code - and much easier.</p>\n\n<p>I can think of two ways you can do this:</p>\n\n<ul>\n<li><p>Convert your files to JSON, <em>if you can</em>.</p></li>\n<li><p>If you can't convert to JSON files, stay with what you are doing, and read the XML but convert them to JS objects before handing them over to the chart. There are XML-to-JSON libraries out there which you can use.</p></li>\n</ul>\n\n<p>A similar data structure in JSON would look like</p>\n\n<pre><code>{\n \"testcase\" : {\n \"measurement\" : [\n {\n \"type\" : \"M8015\",\n \"interval\" : 15\n },{\n \"type\" : \"M8016\",\n \"interval\" : 15\n },{\n \"type\" : \"M8020\",\n \"interval\" : 15\n }\n ]\n }\n}\n</code></pre>\n\n<p>And it's a matter of plucking out the data:</p>\n\n<pre><code>var myData = data.testcase.measurement;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T01:13:22.203", "Id": "30231", "ParentId": "30227", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T23:34:01.950", "Id": "30227", "Score": "2", "Tags": [ "javascript", "jquery", "xml", "d3.js" ], "Title": "What is the more effective way to get array of data out of xml for d3 chart?" }
30227
<p>I know my naming is not good. Please exclude variable / function renaming reviews from your comments.</p> <pre><code>import java.util.NoSuchElementException; /** * http://stackoverflow.com/questions/2216666/finding-the-intersecting-node-from-two-intersecting-linked-lists */ public class Interserction { private Node first; private Node last; private int size; public void add (int element) { final Node l = last; final Node newNode = new Node(element, null); last = newNode; if (first == null) { first = newNode; } else { l.next = newNode; } size++; } public void attach (Interserction l, int item) { if (l == null) { throw new NullPointerException("The input linkedlist is null."); } if (l.last == null) { throw new NoSuchElementException("The last element of linkedlist is null"); } if (first == null) { throw new NoSuchElementException("The linked list is empty."); } Node temp = first; int ctr = 0; while (temp != null) { if (temp.item == item) { l.last.next = temp; l.last = last; l.size = l.size + (size - ctr); // ------&gt; Will need to deep dive this a bit. return; } temp = temp.next; ctr++; } throw new IllegalArgumentException("The input item is invalid."); } public void displayList() { Node tempFirst = first; while (tempFirst != null) { System.out.print(tempFirst.item + " "); tempFirst = tempFirst.next; } } private static class Node { int item; Node next; Node(int element, Node next) { this.item = element; this.next = next; } } public int size() { return size; } private Node hop(Interserction l, int hop) { assert l != null; assert l.first != null; Node temp = l.first; int counter = 0; while (counter &lt; hop) { temp = temp.next; counter++; } return temp; } private Node getIntersectionNode(Node node1, Node node2) { assert node1 != null; assert node2 != null; while (node1 != node2) { node1 = node1.next; node2 = node2.next; } return node1; } private void verify(Interserction l) { if (l == null) { throw new NullPointerException("The input is null"); } if (last == null) { throw new NoSuchElementException("this object has null node"); } if (l.last == null) { throw new NoSuchElementException("The input object has null node"); } } public boolean doesIntersect(Interserction l) { verify(l); return last == l.last; } /** * Similar to String.compareTo line 1137. * Not using a function to get size for l. * this is again similar to anotherString.value.length in compareToFunction */ public int findIntersectionItem(Interserction l) { verify(l); /** * QQ: calling doesIntersect: * pro: code duplication prevented, eg: last == l.last is not seen in 2 places * con: exception check is redundant. * Whats the right thing. * */ if (!doesIntersect(l)) { /** * QQ: Verify this patten of state check function doesIntersect followed by an exception. */ throw new IllegalArgumentException("Input linkedlist does not intersect."); } Node intersect; // guard clause just dint feel correct here. if (l.size &gt; size) { Node begin = hop(l, l.size - size); intersect = getIntersectionNode(first, begin); } else { Node begin = hop(this, size - l.size); intersect = getIntersectionNode(begin, l.first); } // preferred single point of return. return intersect.item; } public static void main(String[] args) { Interserction i1 = new Interserction(); int[] l1 = {10, 20, 30, 40, 50, 60}; for (int i : l1) { i1.add(i); } Interserction i2 = new Interserction(); int[] l2 = {17, 18}; for (int i : l2) { i2.add(i); } i1.attach(i2, 30); // testing same length. System.out.println("Expted true, Actual: " + i1.doesIntersect(i2)); System.out.println("Expected 30, Actual: " + i1.findIntersectionItem(i2)); i1.displayList(); System.out.println(); i2.displayList(); System.out.println(); Interserction i3 = new Interserction(); int[] l3 = {18}; for (int i : l3) { i3.add(i); } i1.attach(i3, 30); // testing same length. System.out.println("Expted true, Actual: " + i1.doesIntersect(i2)); System.out.println("Expected 30, Actual: " + i1.findIntersectionItem(i3)); i1.displayList(); System.out.println(); i3.displayList(); System.out.println(); } } </code></pre>
[]
[ { "body": "<p>I suggest defining <code>getIntersectionNode()</code> right after <code>findIntersectionItem()</code>. Also, put a comment there saying that <code>getIntersectionNode()</code> only works when the two arms of the \"Y\" are the same length (which is OK because only <code>findIntersectionItem()</code> calls it responsibly).</p>\n\n<p>The first few lines of <code>attach()</code> can just call <code>verify()</code>.</p>\n\n<p>Most of your <code>while</code> loops would be better written as <code>for</code> loops, since <code>for</code> loops are more compact and provide an easily recognizable structure to anyone reading the code.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T05:39:35.683", "Id": "30242", "ParentId": "30228", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-25T23:54:53.167", "Id": "30228", "Score": "1", "Tags": [ "java", "linked-list" ], "Title": "Finding intersection of linked list" }
30228
<p>The following code gets the recipient's email address, email subject line and email body from a table. It then creates the emails and sends them to a pickup directory. There is a db connection class that I did not include here, but I invoke it in the code below.</p> <p>The code below runs fine. I am wondering if its speed can be improved, considering it will be used to send 10,000+ emails.</p> <pre><code>using System; using System.Collections; using System.Collections.Generic; using System.Text; using System.Net; using System.Net.Mail; using System.Data; using System.Data.SqlClient; using System.IO; namespace SendEmails { class SendEmail { private class EmailsList { private class listData { public string email; public string email_header; public string email_body; public string email_guid; } public void data() { SqlDataReader sqlData; ArrayList Emaillist = new ArrayList(); sqlData = new SqlCommand("SELECT email, email_header, email_body, email_guid FROM dbo.vw_emails ", con.openconnection()).ExecuteReader(); // loop through the emails table and load arraylist while (sqlData.Read()) { listData itemData = new listData(); itemData.email = sqlData[0].ToString(); itemData.email_header = sqlData[1].ToString(); itemData.email_body = sqlData[2].ToString(); itemData.email_guid = sqlData[3].ToString(); Emaillist.Add(itemData); } sqlData.Close(); con.closeconnection foreach (listData itemData in Eamillist) { //SEND EMAIL *****************************/ spSendMail(itemData.email, itemData.email_header, "me@yahoo.com", itemData.email_body, itemData.email_guid); //DO THE UPDATE *********************/ SqlCommand cmd = new SqlCommand("up_emailLog", con.openconncetion()); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@email_GUID", itemData.email_guid); cmd.CommandTimeout = 0; cmd.ExecuteNonQuery(); con.CloseConnection(); } } } static void Main(string[] args) { try { EmailsList sEmails = new EmailsList(); sEmails.data(); } catch (Exception ex) { SqlCommand cmd = new SqlCommand("INSERT INTO [dbo.Err_Log](exception, insdt) VALUES('" + ex.Message.ToString() + "','" + "','"+ DateTime.Now + "')", Con.OpenConnection()); cmd.ExecuteNonQuery(); con.CloseConnection(); } } // Send Email Method public static void spSendMail(string recipients, string subject, string from, string body, string email_guid) { try { using (MailMessage mailMessage = new MailMessage(from, recipients)) { mailMessage.Subject = subject; mailMessage.Body = body; mailMessage.IsBodyHtml = true; SmtpClient smtpClient = new SmtpClient("xxxxxx.xxxx.zo"); smtpClient.UseDefaultCredentials = true; smtpClient.DeliveryMethod = SmtpDeliveryMethod.SpecifiedPickupDirectory; smtpClient.PickupDirectoryLocation = "\\\\exchange_server\\pickup"; //Create eml file and send it to pickup directory smtpClient.Send(mailMessage); } } catch (Exception ex) { SqlCommand cmd = new SqlCommand("INSERT INTO [dbo.Err_Log](exception, communication, insdt) VALUES('" + ex.Message.ToString() +"','" + recipients.ToString() + "','" + DateTime.Now + "')", con.OpenConnection()); cmd.CommandTimeout = 0; cmd.ExecuteNonQuery(); Con.CloseConnection(); } } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-15T19:58:13.217", "Id": "101939", "Score": "0", "body": "What version of C#/.NET Framework are you using? Your code contains Framework 1.1 constructs (i.e. `ArrayList`). If you have something newer in use, use idiomatic constructs (i.e. `List<listData>`)." } ]
[ { "body": "<p>Have you done any benchmarking? </p>\n\n<p>What part is slower, the database query or the sending of the emails to exchange?</p>\n\n<p>Sending emails is generally the slowest part, but given you are using a pickup directory, that may not be the case here. If it is really slow then you could run several threads in parallel, although this would require significant alterations to your code.</p>\n\n<p>Just curious also how to do you keep track of which emails are sent?</p>\n\n<p>What happens if the process crashes halfway through, will it sent the emails to the users twice?</p>\n\n<p>Keep in mind that your mail server will be the bottleneck at the end of the day. \nIf you want the messages reliably delivered, you will need to have throttling in-place if you are sending to the likes of hotmail, gmail, etc, so regardless of the performance improvements you make in your code, the messages would still be stuck in a queue anyway.</p>\n\n<p>My C# is a bit rusty, but there are a few places where I think you could improve.</p>\n\n<p>In this function, you are recreating the SmtpClient every time, perhaps store it in an instance var instead</p>\n\n<pre><code>public static void spSendMail(string recipients, string subject, string from, string body, string email_guid)\n</code></pre>\n\n<p>I have made comments in the code below, hopefully this is of some use</p>\n\n<pre><code> public void data()\n {\n SqlDataReader sqlData;\n // ArrayList Emaillist = new ArrayList();\n SqlConnection conn;\n SqlCommand cmd;\n\n // open connection once for the entire function\n conn = con.openconnection();\n\n sqlData = new SqlCommand(\"SELECT email, email_header, email_body, email_guid FROM dbo.vw_emails \", conn).ExecuteReader();\n\n // build cmd once and reuse it\n cmd = new SqlCommand(\"up_emailLog\", conn);\n cmd.CommandType = CommandType.StoredProcedure;\n cmd.CommandTimeout = 0;\n\n // loop through the emails table and load arraylist\n\n while (sqlData.Read())\n {\n // why are we storing this in a temporary structure in memory?\n // listData itemData = new listData();\n // itemData.email = sqlData[0].ToString();\n // itemData.email_header = sqlData[1].ToString();\n // itemData.email_body = sqlData[2].ToString();\n // itemData.email_guid = sqlData[3].ToString();\n // Emaillist.Add(itemData);\n // }\n // sqlData.Close();\n // con.closeconnection\n //\n // foreach (listData itemData in Eamillist)\n // {\n //SEND EMAIL *****************************/\n spSendMail(sqlData[0].ToString(), sqlData[1].ToString(), \"me@yahoo.com\", sqlData[2].ToString(), sqlData[3].ToString());\n //DO THE UPDATE *********************/\n\n // reuse same cmd, just clear parameters\n cmd.Parameters.Clear();\n cmd.Parameters.AddWithValue(\"@email_GUID\", sqlData[3].ToString());\n cmd.ExecuteNonQuery();\n }\n\n // close connection outside of loop, so we are not constantly opening and closing\n conn.CloseConnection();\n }\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-07-15T20:00:16.773", "Id": "101940", "Score": "0", "body": "bumperbox is right, how to know which mails are sent? remember: failing with sending email to 10k+ recipients is receiving trouble from 10k+ complainers..." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T04:54:32.667", "Id": "30239", "ParentId": "30233", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T02:13:26.353", "Id": "30233", "Score": "4", "Tags": [ "c#", "performance", "email" ], "Title": "Sending emails using SMTP client" }
30233
<p>The following working code basically swaps the content of two divs. The divs are created dynamically, then the user checks which records they want to swap, and then clicks on a swap button that triggers a function to swap an inner div element.</p> <p>The part that swaps the div's seems really messy to me. I'm only a beginner/intermediate with JavaScript, so I would really appreciate some help with this.</p> <pre><code>//dynamically create the div elements $('#SwapBedsFields').html(options); for (var i = 1; i &lt;= NumberOfBeds; i++) { var RowIndex = $.inArray(i.toString(), bedNumberColumn); var ptName = 'Empty'; var UMRN = ""; var UMRNstr = ''; var pID = ''; if (RowIndex != -1) { ptName = patientNameColumn[RowIndex]; UMRN = patientUMRNColumn[RowIndex]; pID = pIDColumn[RowIndex]; UMRNstr = "(" + UMRN + ")"; }; options += '&lt;div style="white-space:nowrap; height:25px; width:100%;" id="bed-topdiv-' + i + '"&gt;&lt;input type="checkbox" style="vertical-align:middle;" name="bed-' + i + '"'; options += 'id="bed-' + i + '" /&gt;&lt;div style="display:inline; vertical-align:middle;"&gt;&amp;nbsp;Bed ' + i + ' - &lt;/div&gt;&lt;div id="bed-div-' + i + '" class="inner-bed-div-class" style="display:inline; vertical-align:middle;" bedNum=' + i + ' uMRN=' + UMRN +' &gt;' + ptName + '&amp;nbsp;' + UMRNstr + '&lt;/div&gt;&lt;/div&gt;'; }; //***THIS IS THE BIT I FIND PARTICULARLY MESSY!*** //then in another function - when the user clicks a button to swap the div elements... var selected = new Array(); var patientname1; var patientname2; var b1html; var b2html; var pt1UMRN; var pt2UMRN; $('#SwapBedsFields input:checked').each(function () { selected.push($(this).attr('name')); }); //get the html of the two bed divs patientname1 = $('#bed-div-' + selected[0].substring(4)).html(); patientname2 = $('#bed-div-' + selected[1].substring(4)).html(); pt1UMRN = $('#bed-div-' + selected[0].substring(4)).attr('umrn'); pt2UMRN = $('#bed-div-' + selected[1].substring(4)).attr('umrn'); //swap the elements around $('#bed-div-' + selected[0].substring(4)).html(patientname2); $('#bed-div-' + selected[1].substring(4)).html(patientname1); //update the umrn attribute $('#bed-div-' + selected[0].substring(4)).attr({ umrn: pt2UMRN}); $('#bed-div-' + selected[1].substring(4)).attr({ umrn: pt1UMRN }); //message the user $('#bed-topdiv-' + selected[0].substring(4)).effect("highlight", {}, 2000); $('#bed-topdiv-' + selected[1].substring(4)).effect("highlight", {}, 2000); </code></pre>
[]
[ { "body": "<p>You could improve it a little like this, at least you are not selecting the same elements over and over.</p>\n\n<p>I do think it could improve more, if you swapped the actual div's rather then the html content and umrn value.</p>\n\n<pre><code>var $bed0 = $('#bed-div-' + selected[0].substring(4));\nvar $bed1 = $('#bed-div-' + selected[1].substring(4));\n\n//get the html of the two bed divs\npatientname1 = $bed0.html();\npatientname2 = $bed1.html();\npt1UMRN = $bed0.attr('umrn');\npt2UMRN = $bed1.attr('umrn');\n\n\n//swap the elements around\n$bed0.html(patientname2);\n$bed1.html(patientname1);\n\n//update the umrn attribute\n$bed0.attr({ umrn: pt2UMRN});\n$bed1.attr({ umrn: pt1UMRN });\n\n//message the user\n$bed0.effect(\"highlight\", {}, 2000);\n$bed1.effect(\"highlight\", {}, 2000);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T05:07:49.423", "Id": "30240", "ParentId": "30235", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T02:18:10.090", "Id": "30235", "Score": "2", "Tags": [ "javascript", "jquery" ], "Title": "Swapping dynamic page div's around on button click" }
30235
<p>So I'm working on a register form and I have four fields: name, username, email and password. I pick up the values of these fields in jQuery and depending on if all the fields are filled, I pass them onto a PHP script via ajax. Is that safe for form validations? I was worried about data getting manipulated by the user.</p> <p>Further on in the php script, I check if all the posted values have data in them, only then will I proceed onto doing some validations... The validations are the parts where I'm worried that it's not the best and there are many flaws with it.</p> <pre><code>$name = $_POST['name']; $username = $_POST['username']; $email = $_POST['email']; $password = $_POST['password']; if (!preg_match("/^[A-Za-z '-]+$/i", $name)) { $errors = "Please enter a valid name."; } else if (!preg_match("/^[A-Za-z]+\s[A-Za-z]+$/", $name)) { $errors = "Please enter your first and last name."; } else if (strlen($username) &lt;= 3 || strlen($username) &gt; 15) { $errors = "Please pick a username between 4 - 15 characters. Be creative."; } else if (!preg_match("/^[A-Za-z][A-Za-z0-9_.-]{4,15}$/", $username)) { $errors = "Please pick an alphanumeric username between 4 - 15 characters."; } else if (filter_var($email, FILTER_VALIDATE_EMAIL) === false) { $errors = "Please enter a valid email."; } else if (strlen($username )&lt; 6 || strlen($username) &gt; 32) { $errors = "Your password must atleast be 6 characters."; } else { echo "valid"; } </code></pre> <p>Are these validation steps secure? Are there any loop holes that the user can manipulate the data?</p> <p>The requirements for the fields are as follows - which im not so sure i hit on the head with my code: - The username should have alphanumeric characters with underscores (optional) - the name should have BOTH the first name and the last name</p> <p>Thank you.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T07:19:09.687", "Id": "48031", "Score": "0", "body": "What are you doing with the data? Putting it into a DB? into a file? ..." } ]
[ { "body": "<p>I take it you're trying to protect yourself from XSS attacks, injection and general mallicious input. You're well on your way (but <a href=\"https://codereview.stackexchange.com/questions/29294/how-can-i-make-this-code-safer-against-xss-attacks/29295#29295\">do have a look here</a>, there are some interesting links at the bottom).</p>\n\n<p>That said, I'd say your validation needs work on a couple of (crucial) points:</p>\n\n<ul>\n<li>Don't be <em>too</em> strict: <code>/^[A-Za-z '-]+$/i</code> for a name doesn't allow <em>\"pièrre joão\"</em>, but it clearly is a name. Just match all unicode chars, and drop the <code>i</code> flag, or change <code>[A-Za-z]</code> to <code>[a-z]</code>. I'd suggest you using this code: <code>$name = trim($name); preg_match('/^[\\w \\'-]+$/u', $name)</code>. <a href=\"http://php.net/manual/en/reference.pcre.pattern.modifiers.php\" rel=\"nofollow noreferrer\">read about the <code>u</code> modifier here</a></li>\n<li>Be consistent: You're applying 2 patterns to <code>$name</code>: <code>/^[A-Za-z '-]+$/i</code> and <code>/^[A-Za-z]+\\s[A-Za-z]+$/</code> This means that, the second time dashes and accents aren't allowed. That's not good, not good at all. If needs must, <code>explode</code> the <code>$name</code> on <code>' '</code> (a space), and apply the first pattern to each name individualy. Or work on the regex some more.</li>\n<li><code>/^[A-Za-z][A-Za-z0-9_.-]{4,15}$/</code>: This doesn't allow a 4 char long username, but requers the username to be <em>at least</em> 5 chars long: <code>[a-z]</code> matches 1 char, <code>[a-z0-9_.-]{4,15}</code> <em>followed by <strong>at least</strong> 4, at most 15 chars</em>. Now that's not bad, but it's not what you want.</li>\n<li>Validate the right things: near the end, you do some checks on the password, but you're using the <code>$username</code> variable... typo?</li>\n<li>Don't limit the length of a password: <code>strlen($username) &gt; 32</code>? Why? If the client wants to use a longer (and possibly stronger) password, let them do so...<br/>\nIf you're going to do some checks on the password, at least to make sure that they're using chars, numbers <em>and</em> symbols. Not just <em>\"somealllowercasepass\"</em>, but <em>\"S0m3@llw@kkyp@55\"</em></li>\n</ul>\n\n<p>Like I said above, you're missing out on some things, too:</p>\n\n<ul>\n<li>No where are you calling <code>strip_tags</code> to ensure any markup is being removed from input</li>\n<li>The password validation isn't applied to the correct variable, and should be improved, too</li>\n<li>Your error messages are <em>waay</em> too specific. That's a bad idea! If I had bad intentions, and tried to fill in the form, each time trying some XSS trickery, and you give me feedback as in: <em>\"username mustn't contain chars like &lt;, >, /, \\, #, %\"</em>, I can move on and try to exploit the next input field, and make sure I fill in a valid username, until I find a field where you let your guard down...<br/>\nKeep your error messages general: <em>\"Not all input was correct/the expected format/met the requirements\"</em>. That should be enough. But as DmitriZaitsev says: be careful not to alienate/offend the end-users, or your queste for safety might backfire (and leave you with no data to protect). A simple way of validating the email address and not restricting the username is to use the email address as username. If google and SO do it, why can't you?</li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T09:29:18.043", "Id": "48762", "Score": "0", "body": "Great advice except the last one where I would respectfully disagree from usability point of view. It always drives me mad when sites I barely interested in start wasting my time by rejecting my usernames, passwords etc for unclear reasons. First, there is no reason for them even to use 'username' instead of emails. Second, if they really want my attention, they better tell me quickly what is wrong with credentials I am inputting. An they better not be picky before I decide the site is not worth my time. Not every site needs the same security as bank." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T09:32:30.837", "Id": "48763", "Score": "0", "body": "Here is some more explanation on the topic: [http://stackoverflow.com/questions/18356407/how-to-merge-user-data-after-login/18443311#18443311](http://stackoverflow.com/questions/18356407/how-to-merge-user-data-after-login/18443311#18443311)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T09:32:53.053", "Id": "48764", "Score": "0", "body": "@DmitriZaitsev: I've said in my answer that you shouldn't restrict usernames/passwords too much (using the email is a good idea, BTW, I'll add that to my answer). The only think I was getting at with my last comment was that, if an invalid email address was submitted, don't say: `an email must contain an @`, but just add a notice, saying: not all fields were filled in correctly. have the UI set a red border around the textfield that contains bad input, if you must" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T09:56:00.403", "Id": "48767", "Score": "0", "body": "I don't see any problem telling the user that email entered is missing @. A hacker knows this already, but a user can be rightfully confused. Whenever your message is vague, you force the user think why, instead of helping. Think of a lazy user exhausted after work or crazy party or under hangover and trying to have some fun - and now he has to play guess games with the site." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T10:21:23.210", "Id": "48769", "Score": "1", "body": "@EliasVanOotegem BTW, upvotes for this and other of your insightful code reviews" } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T07:56:20.097", "Id": "30248", "ParentId": "30237", "Score": "3" } } ]
{ "AcceptedAnswerId": "30248", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T04:04:52.910", "Id": "30237", "Score": "1", "Tags": [ "javascript", "php", "jquery", "validation" ], "Title": "Form validation - security and input specification" }
30237
<p>Previous question (without AI): <a href="https://codereview.stackexchange.com/questions/30060/tic-tac-toe-optimization">Tic-Tac-Toe optimization</a></p> <p>This new code has a main file, a base <code>game</code> class, and two derived <code>human</code> and <code>computer</code> classes.</p> <p>I welcome any suggestions for improving my code. Also, if I'm being needlessly complex on writing the code, let me know. That is my main concern.</p> <p>Here, I have the welcome screen and I present the player with options. The function <code>setcolor()</code> is defined in <code>game.h</code>, but outside the <code>game</code> class scope, so that I can use it since I've included that header file. It gives the player 3 options: human vs human, comp vs human, and exit.</p> <p><strong>tic-tac-toeV2.0.cpp</strong></p> <pre><code>#include "stdafx.h" #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;Windows.h&gt; #include "game.h" #include "human.h" #include "computer.h" #include &lt;sstream&gt; void main_play(); int main(){ SetColor(DARKGREEN); std::cout&lt;&lt;"~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~Tic-Tac-Taoe~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~"&lt;&lt;std::endl; std::cout&lt;&lt;"*By Default Player 1 is 'O' and Player 2 is 'X'\n"; std::cout&lt;&lt;"*The choice of cells is mapped out in the following legend\n\n\n"; std::cout&lt;&lt;" 1 | 2 | 3 \n____|____|____\n 4 | 5 | 6 \n____|____|____\n 7 | 8 | 9 \n | | \n\n"; std::cout&lt;&lt;"********************************************************************************\n\n\n"; SetColor(WHITE); main_play(); return 0; } void main_play(){ int choice,replay; std::cout&lt;&lt;"What do You want to Do?\n 1.Play Human vs. Human(2 Player) \n 2.Computer vs. Human(1 Player)\n 3.Exit\n\n"; std::cin&gt;&gt;choice; if(choice&lt;4){ switch(choice){ case 1: { human two_player; two_player.play(); break; } case 2: { computer one_player; one_player.play(); break; } case 3: { SetColor(GREEN); std::cout&lt;&lt;"Thank You for Playing :)\n\n"; SetColor(WHITE); return; } } SetColor(DARKTEAL); std::cout&lt;&lt;"Do You Want to Play Another Game?\n 1.Yes \n 2.No \n"; SetColor(WHITE); std::cin&gt;&gt;replay; if(replay==1){ main_play(); } else{ SetColor(GREEN); std::cout&lt;&lt;"Thank You for Playing :)\n\n"; SetColor(WHITE); return; } } SetColor(RED); std::cout&lt;&lt;"That is not a Valid Choice....\n Please Make a Valid Choice....\n\n"; SetColor(WHITE); main_play(); } </code></pre> <p>The <code>game</code> class is the base class and has functions that are necessary for both modes of play. </p> <p>It has a function for inserting human player's choice on the board. It has another function for checking if there is a win and then displays the appropriate messages. </p> <p>The win-display function displays the win situation with colored row, col or diagonal, and it uses the color converter and winner functions to do this. </p> <p>The <code>are_elements_equal()</code> function checks if all the elements in a row, col or diagonal are equal.</p> <p><strong>game.h</strong></p> <pre><code>#ifndef __GAME_H_INCLUDE #define __GAME_H_INCLUDE #include "stdafx.h" #include &lt;iostream&gt; #include &lt;string&gt; #include &lt;time.h&gt; #include &lt;map&gt; #include &lt;Windows.h&gt; #include &lt;array&gt; #include &lt;sstream&gt; enum win_associations {R1=1,R2,R3,C1,C2,C3,D1,D2}; enum state {WIN=0,DRAW,KEEP_PLAYING}; enum Color { DARKBLUE = 1, DARKGREEN, DARKTEAL, DARKRED, DARKPINK, DARKYELLOW, GRAY, DARKGRAY, BLUE, GREEN, TEAL, RED, PINK, YELLOW, WHITE }; void SetColor(Color c); class game { public: game(); bool is_the_move_valid(int); bool are_elements_equal(std::array&lt;char*,3&gt;); state state_of_game(); void display_board(); void win_display(); void color_conv(char); void Winner(char); protected: std::string player1,player2,dummy; char board[9]; char* p; std::array&lt;char*,3&gt; row1; std::array&lt;char*,3&gt; row2; std::array&lt;char*,3&gt; row3; std::array&lt;char*,3&gt; col1; std::array&lt;char*,3&gt; col2; std::array&lt;char*,3&gt; col3; std::array&lt;char*,3&gt; diag1; std::array&lt;char*,3&gt; diag2; bool board_full(); }; #endif </code></pre> <p><strong>game.cpp</strong></p> <pre><code>#include "stdafx.h" #include "game.h" #include &lt;sstream&gt; HANDLE hCon; void SetColor(Color c){ if(hCon == NULL) hCon = GetStdHandle(STD_OUTPUT_HANDLE); SetConsoleTextAttribute(hCon, c);} //constructor for the class game game::game(){ //This fills up the board array with '-' a filler character, also it looks good :) for(int k=0;k&lt;9;k++){ board[k]='-'; } //makes arrays of pointers corrsponding to rows, columns and diagonals of the board p=board; //pointer initialization row1[0]=p;row1[1]=p+1;row1[2]=p+2; //starting from here the pointers arrays corrspond to rows1,2,3:cols 1,2,3 nad diagonals 1 &amp; 2 respectively row2[0]=p+3;row2[1]=p+4;row2[2]=p+5; row3[0]=p+6;row3[1]=p+7;row3[2]=p+8; col1[0]=p;col1[1]=p+3;col1[2]=p+6; col2[0]=p+1;col2[1]=p+4;col2[2]=p+7; col3[0]=p+2;col3[1]=p+5;col3[2]=p+8; diag1[0]=p;diag1[1]=p+4;diag1[2]=p+8; diag2[0]=p+2;diag2[1]=p+4;diag2[2]=p+6; } bool game::is_the_move_valid(int move){ if(board[move]=='-'){ return true; } if(move&lt;9 &amp;&amp; board[move]!='-'){ SetColor(RED); std::cout&lt;&lt;"That Position is alraedy taken!!!\n\n"; SetColor(WHITE); } if(move&gt;9){ SetColor(RED); std::cout&lt;&lt;"That is an illegal choice!!!\n\n"; SetColor(WHITE); } return false; } bool game::are_elements_equal(std::array&lt;char*,3&gt; k){ std::array&lt;char*,3&gt;::iterator p; p=k.begin(); if(**p==**(p+1) &amp;&amp; **(p+1)==**(p+2)){ return true; } else { return false; } } state game::state_of_game(){ if( (are_elements_equal(row1)==true &amp;&amp; *row1[0]!='-') ||(are_elements_equal(row2)==true &amp;&amp; *row2[0]!='-') ||(are_elements_equal(row3)==true &amp;&amp; *row3[0]!='-') ||(are_elements_equal(col1)==true &amp;&amp; *col1[0]!='-') ||(are_elements_equal(col2)==true &amp;&amp; *col2[0]!='-') ||(are_elements_equal(col3)==true &amp;&amp; *col3[0]!='-') ||(are_elements_equal(diag1)==true &amp;&amp; *diag1[0]!='-') ||(are_elements_equal(diag2)==true &amp;&amp; *diag2[0]!='-')){ return WIN; } else if(board_full()==true){ return DRAW; } else{ return KEEP_PLAYING; } } bool game::board_full(){ for(int i=0;i&lt;9;i++){ if(board[i]=='-'){ return false; } } return true; } void game::display_board(){ std::cout&lt;&lt;" "&lt;&lt;board[0]&lt;&lt;" | "&lt;&lt;board[1]&lt;&lt;" | "&lt;&lt;board[2]&lt;&lt;" \n____|____|____\n "&lt;&lt;board[3]&lt;&lt;" | "&lt;&lt;board[4]&lt;&lt;" | "&lt;&lt;board[5]&lt;&lt;" \n____|____|____\n "&lt;&lt;board[6]&lt;&lt;" | "&lt;&lt;board[7]&lt;&lt;" | "&lt;&lt;board[8]&lt;&lt;" \n | | \n\n"; } void game::win_display(){ if(are_elements_equal(row1)==true){ std::cout&lt;&lt;" "; color_conv(board[0]); std::cout&lt;&lt;" | "; color_conv(board[1]); std::cout&lt;&lt;" | "; color_conv(board[2]); std::cout&lt;&lt;" \n____|____|____\n "&lt;&lt;board[3]&lt;&lt;" | "&lt;&lt;board[4]&lt;&lt;" | "&lt;&lt;board[5]&lt;&lt;" \n____|____|____\n "&lt;&lt;board[6]&lt;&lt;" | "&lt;&lt;board[7]&lt;&lt;" | "&lt;&lt;board[8]&lt;&lt;" \n | | \n\n"; Winner(*row1[0]); } else if(are_elements_equal(row2)==true){ std::cout&lt;&lt;" "&lt;&lt;board[0]&lt;&lt;" | "&lt;&lt;board[1]&lt;&lt;" | "&lt;&lt;board[2]&lt;&lt;" \n____|____|____\n "; color_conv(board[3]); std::cout&lt;&lt;" | "; color_conv(board[4]); std::cout&lt;&lt;" | "; color_conv(board[5]); std::cout&lt;&lt;" \n____|____|____\n "&lt;&lt;board[6]&lt;&lt;" | "&lt;&lt;board[7]&lt;&lt;" | "&lt;&lt;board[8]&lt;&lt;" \n | | \n\n"; Winner(*row2[0]); } else if(are_elements_equal(row3)==true){ std::cout&lt;&lt;" "&lt;&lt;board[0]&lt;&lt;" | "&lt;&lt;board[1]&lt;&lt;" | "&lt;&lt;board[2]&lt;&lt;" \n____|____|____\n "&lt;&lt;board[3]&lt;&lt;" | "&lt;&lt;board[4]&lt;&lt;" | "&lt;&lt;board[5]&lt;&lt;" \n____|____|____\n "; color_conv(board[6]); std::cout&lt;&lt;" | "; color_conv(board[7]); std::cout&lt;&lt;" | "; color_conv(board[8]); std::cout&lt;&lt;" \n | | \n\n"; Winner(*row3[0]); } else if(are_elements_equal(col1)==true){ std::cout&lt;&lt;" "; color_conv(board[0]); std::cout&lt;&lt;" | "&lt;&lt;board[1]&lt;&lt;" | "&lt;&lt;board[2]&lt;&lt;" \n____|____|____\n "; color_conv(board[3]); std::cout&lt;&lt;" | "&lt;&lt;board[4]&lt;&lt;" | "&lt;&lt;board[5]&lt;&lt;" \n____|____|____\n "; color_conv(board[6]); std::cout&lt;&lt;" | "&lt;&lt;board[7]&lt;&lt;" | "&lt;&lt;board[8]&lt;&lt;" \n | | \n\n"; Winner(*col1[0]); } else if(are_elements_equal(col2)==true){ std::cout&lt;&lt;" "&lt;&lt;board[0]&lt;&lt;" | "; color_conv(board[1]); std::cout&lt;&lt;" | "&lt;&lt;board[2]&lt;&lt;" \n____|____|____\n "&lt;&lt;board[3]&lt;&lt;" | "; color_conv(board[4]); std::cout&lt;&lt;" | "&lt;&lt;board[5]&lt;&lt;" \n____|____|____\n "&lt;&lt;board[6]&lt;&lt;" | "; color_conv(board[7]); std::cout&lt;&lt;" | "&lt;&lt;board[8]&lt;&lt;" \n | | \n\n"; Winner(*col2[0]); } else if(are_elements_equal(col3)==true){ std::cout&lt;&lt;" "&lt;&lt;board[0]&lt;&lt;" | "&lt;&lt;board[1]&lt;&lt;" | "; color_conv(board[2]); std::cout&lt;&lt;" \n____|____|____\n "&lt;&lt;board[3]&lt;&lt;" | "&lt;&lt;board[4]&lt;&lt;" | "; color_conv(board[5]); std::cout&lt;&lt;" \n____|____|____\n "&lt;&lt;board[6]&lt;&lt;" | "&lt;&lt;board[7]&lt;&lt;" | "; color_conv(board[8]); std::cout&lt;&lt;" \n | | \n\n"; Winner(*col3[0]); } else if(are_elements_equal(diag1)==true){ std::cout&lt;&lt;" "; color_conv(board[0]); std::cout&lt;&lt;" | "&lt;&lt;board[1]&lt;&lt;" | "&lt;&lt;board[2]&lt;&lt;" \n____|____|____\n "&lt;&lt;board[3]&lt;&lt;" | "; color_conv(board[4]); std::cout&lt;&lt;" | "&lt;&lt;board[5]&lt;&lt;" \n____|____|____\n "&lt;&lt;board[6]&lt;&lt;" | "&lt;&lt;board[7]&lt;&lt;" | "; color_conv(board[8]); std::cout&lt;&lt;" \n | | \n\n"; Winner(*diag1[0]); } else if(are_elements_equal(diag2)==true){ std::cout&lt;&lt;" "&lt;&lt;board[0]&lt;&lt;" | "&lt;&lt;board[1]&lt;&lt;" | "; color_conv(board[2]); std::cout&lt;&lt;" \n____|____|____\n "&lt;&lt;board[3]&lt;&lt;" | "; color_conv(board[4]); std::cout&lt;&lt;" | "&lt;&lt;board[5]&lt;&lt;" \n____|____|____\n "; color_conv(board[6]); std::cout&lt;&lt;" | "&lt;&lt;board[7]&lt;&lt;" | "&lt;&lt;board[8]&lt;&lt;" \n | | \n\n"; Winner(*diag2[0]); } } void game::color_conv(char c){ SetColor(TEAL); std::cout&lt;&lt;c; SetColor(WHITE); } void game::Winner(char c){ if(c=='O'){ SetColor(YELLOW); std::cout&lt;&lt;player1&lt;&lt;" Won....\n"; SetColor(WHITE); } else if(c=='X'){ SetColor(YELLOW); std::cout&lt;&lt;player2&lt;&lt;" Won....\n"; SetColor(WHITE); } } </code></pre> <p>The <code>human</code> class has one function, <code>play()</code>, which makes sure the players play in a turn-by-turn fashion. </p> <p>This is implemented by odd/even checks of the integer <code>i</code>. If a player makes an invalid move, a warning is given and the player gets another chance.</p> <p><strong>human.h</strong></p> <pre><code>#ifndef __HUMAN_H_INCLUDE #define __HUMAN_H_INCLUDE #include "game.h" #include &lt;sstream&gt; class human : public game { public: void play(); }; #endif </code></pre> <p><strong>human.cpp</strong></p> <pre><code>#include "stdafx.h" #include "human.h" #include &lt;sstream&gt; void human::play(){ int i=1,player_choice; char mark; std::string current_palyer; SetColor(DARKYELLOW); std::cout&lt;&lt;"Player 1:Enter your Name\n"; getline(std::cin, dummy);// weird problem with getline if not for this line it won't accept player1's name getline(std::cin, player1); std::cout&lt;&lt;"Player 2:Enter your Name\n"; getline(std::cin, player2); SetColor(WHITE); while(state_of_game()==KEEP_PLAYING){ if(i%2!=0){ current_palyer=player1; mark='O'; } else if(i%2==0){ current_palyer=player2; mark='X'; } std::cout&lt;&lt;current_palyer&lt;&lt;":Enter your Choice....\n"; std::cin&gt;&gt;player_choice; if(is_the_move_valid(player_choice-1)==true){ board[player_choice-1]=mark; display_board(); } else { i--; } i++; } if(state_of_game()==DRAW){ SetColor(PINK); std::cout&lt;&lt;"The Game is a Draw!!!\n"; SetColor(WHITE); } else if(state_of_game()==WIN){ win_display(); } } </code></pre> <p>This class implements AI for the computer player and the AI rules. As described by @shade:</p> <ul> <li>if there is a possibility of a win, take it</li> <li>if there is a block, take it</li> <li>if the center is available, take it</li> <li>if any of the the corners are available, take it randomly</li> <li>if any of the middle edges (i.e positions 1,3,5,7) are available, take it randomly</li> </ul> <p><strong>computer.h</strong></p> <pre><code>#ifndef __COMPUTER_H_INCLUDE #define __COMPUTER_H_INCLUDE #include "game.h" #include &lt;vector&gt; #include &lt;time.h&gt; enum specifier {CORNERS=0, MIDDLE_CORNERS}; enum status {WINS,BLOCK,NONE}; class computer : public game { protected: struct win_block_info{ bool wins; bool blocks; int place; }; struct corner_info{ bool corners; bool mid_corners; std::vector&lt;char*&gt; empty_pos; }; std::vector&lt;std::array&lt;char*,3&gt;&gt; list; std::vector&lt;status&gt; status_list; std::array&lt;char*,4&gt; corners; std::array&lt;char*,4&gt; middle_corners; public: computer(); void play(); void comp_choice(); win_block_info possible_wins_or_blocks(); corner_info corner_placement(); bool any_two_elements_equal(std::array&lt;char*,3&gt;); void test(); std::vector&lt;char*&gt; empty_places_list(specifier); ~computer(); }; #endif </code></pre> <p><strong>computer.cpp</strong></p> <pre><code>#include "stdafx.h" #include "computer.h" computer::computer(){ srand((time(NULL))); list.push_back(row1); list.push_back(row2); list.push_back(row3); list.push_back(col1); list.push_back(col2); list.push_back(col3); list.push_back(diag1); list.push_back(diag2); corners[0]=p;corners[1]=p+2;corners[2]=p+6;corners[3]=p+8; middle_corners[0]=p+1;middle_corners[1]=p+3;middle_corners[2]=p+5;middle_corners[3]=p+7; } void computer::play(){ int i=1,player_choice; char mark; SetColor(DARKYELLOW); std::cout&lt;&lt;"Player: Enter your Name\n"; getline(std::cin, dummy);// weird problem with getline if not for this line it won't accept player1's name getline(std::cin, player1); player2="Computer"; SetColor(WHITE); while(state_of_game()==KEEP_PLAYING){ if(i%2!=0){ mark='O'; std::cout&lt;&lt;player1&lt;&lt;":Enter your Choice....\n"; std::cin&gt;&gt;player_choice; if(is_the_move_valid(player_choice-1)==true){ board[player_choice-1]=mark; display_board(); } else { i--; } } else if(i%2==0){ std::cout&lt;&lt;player2&lt;&lt;":has made the Choice....\n"; comp_choice(); display_board(); } i++; } if(state_of_game()==DRAW){ SetColor(PINK); std::cout&lt;&lt;"The Game is a Draw!!!\n"; SetColor(WHITE); } else if(state_of_game()==WIN){ win_display(); } } void computer::comp_choice(){ win_block_info status; corner_info corner_status; status=possible_wins_or_blocks(); if(status.wins==true){ for(int k=0;k&lt;3;k++){ if(*list[status.place][k]=='-'){ *list[status.place][k]='X'; list.erase(list.begin()+status.place); return; } } } if(status.blocks==true){ for(int k=0;k&lt;3;k++){ if(*list[status.place][k]=='-'){ *list[status.place][k]='X'; list.erase(list.begin()+status.place); return; } } } if(board[4]=='-'){ board[4]='X'; return; } corner_status=corner_placement(); if(corner_status.corners==true){ int ran=std::rand()%corner_status.empty_pos.size(); *corner_status.empty_pos[ran]='X'; corner_status.empty_pos.clear(); return; } if(corner_status.mid_corners==true){ int ran=std::rand() % corner_status.empty_pos.size(); *corner_status.empty_pos[ran]='X'; corner_status.empty_pos.clear(); return; } } computer::win_block_info computer::possible_wins_or_blocks(){ win_block_info status; status.blocks=false; status.wins=false; status.place=10000; for(int i=0;i&lt;list.size();i++){ if(any_two_elements_equal(list[i])==true){ status.blocks=true; status.place=i; if(*list[i][0]=='X' || *list[i][1]=='X'){ status.wins=true; status.blocks=false; status.place=i; return status; } } } return status; } bool computer::any_two_elements_equal(std::array&lt;char*,3&gt; current){ if( (*current[0]==*current[1] &amp;&amp; *current[0]!='-') ||(*current[1]==*current[2] &amp;&amp; *current[1]!='-') ||(*current[2]==*current[0] &amp;&amp; *current[2]!='-')){ if(*current[0]=='-'||*current[1]=='-'||*current[2]=='-'){ return true; } } return false; } computer::corner_info computer::corner_placement(){ corner_info status; status.corners=false; status.mid_corners=false; for(int i=0;i&lt;4;i++){ if(*corners[i]=='-'){ status.corners=true; status.empty_pos.push_back(corners[i]); } } if(status.corners==true){ return status; } for(int i=0;i&lt;4;i++){ if(*middle_corners[i]=='-'){ status.mid_corners=true; status.empty_pos.push_back(corners[i]); } } return status; } void computer::test(){ std::cout&lt;&lt;possible_wins_or_blocks().wins&lt;&lt;" "&lt;&lt;possible_wins_or_blocks().place&lt;&lt;std::endl; comp_choice(); display_board(); } computer::~computer(){ list.clear(); } </code></pre>
[]
[ { "body": "<ul>\n<li><p><em>In general</em>: it's nice to organize your STL <code>#include</code>s alphabetically. In addition, the header <code>#include</code>s should be above the library ones so that there are no dependencies among them.</p></li>\n<li><p>Not a very effective <code>choice</code> as you're allowing <em>any</em> value below 4. You also need a <code>default</code> for when an invalid choice is entered. For a more readable main loop, put the <code>switch</code> in a <code>for(;;)</code>. This essentially runs the game \"forever\" until the user quits. You also don't need the <code>replay</code> since <code>choice</code> serves the same purpose.</p>\n\n<p>Here's roughly one suggestion:</p>\n\n<pre><code>void main_play()\n{\n for (;;)\n {\n std::cout &lt;&lt; \"/* displayed stuff */\";\n int choice; // move this right next to the cin\n std::cin &gt;&gt; choice;\n\n switch (choice)\n {\n case 1:\n // start game\n break;\n case 2:\n // start game\n break;\n case 3:\n // quit game\n return;\n default:\n // if the user enters an invalid value,\n // throw an exception and allow the loop\n // to restart safely for the next input\n // #include &lt;stdexcept&gt; to use this\n\n throw std::logic_error(\"Invalid Choice\");\n }\n }\n}\n</code></pre></li>\n<li><p>I'd put all the <code>enum</code>s into either the appropriate <code>class</code> or a <code>namespace</code>. Having them in global scope can cause name clashes and disorganization.</p></li>\n<li><p>You're doing a bit much to set up the board. Just make a \"2D\" <code>std::array</code>:</p>\n\n<pre><code>std::array&lt;std::array&lt;char, 3&gt;, 3&gt; board; // one array in the other\n</code></pre>\n\n<p>To ease the readability when using it, make a <code>typedef</code>:</p>\n\n<pre><code>typedef std::array&lt;std::array&lt;char, 3&gt;, 3&gt; Board;\n</code></pre></li>\n<li><p>You don't use <code>&lt;sstream&gt;</code> at all in <code>human.h</code>, so leave it out. Also, I think you've meant to use <code>&lt;string&gt;</code> instead of <code>&lt;sstream&gt;</code> in <code>human.cpp</code>.</p></li>\n<li><p>I'd put <code>~computer()</code> below <code>computer()</code> in the header and implementation.</p></li>\n<li><p>In <code>computer.h</code>: use <code>&lt;ctime&gt;</code> instead of <code>&lt;time.h&gt;</code>. The latter is a C library.</p></li>\n<li><p><strong>This one should stand out</strong>. In <code>computer.cpp</code>: move the <code>srand()</code> to <code>main()</code> and take out any other calls to this.</p>\n\n<p>Putting this here:</p>\n\n<ol>\n<li>makes it easy to keep track of the initial seeding</li>\n<li><em>prevents the \"same randomness\" from occurring at each call to <code>rand()</code></em></li>\n</ol>\n\n<p>After you do this, make these other changes:</p>\n\n<pre><code>#include &lt;ctime&gt; // move this from computer.h\n#include &lt;cstdlib&gt; // for srand()\n\n// this goes at the top of main()\n// change your current srand() to this\n// if you're using C++11, use nullptr\nstd::srand(static_cast&lt;unsigned int&gt;(std::time(NULL)));\n</code></pre>\n\n<p>If you <em>are</em> using C++11, <code>srand</code>/<code>rand</code> should not be used at all as it is <a href=\"http://channel9.msdn.com/Events/GoingNative/2013/rand-Considered-Harmful\" rel=\"nofollow\">considered harmful</a>. Instead, the <a href=\"http://en.cppreference.com/w/cpp/header/random\" rel=\"nofollow\"><code>&lt;random&gt;</code></a> library should be utilized.</p></li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T06:16:40.197", "Id": "30244", "ParentId": "30238", "Score": "6" } }, { "body": "<p>Don't use double underscore in your identifiers (<a href=\"https://stackoverflow.com/a/228797/14065\">they are reserved</a>).<br>\nDon't start macros with underscore as as identifers in the global namespace starting with an underscore are reserved.</p>\n\n<pre><code>__COMPUTER_H_INCLUDE\n</code></pre>\n\n<h3>Design</h3>\n\n<p>I don't like the design:</p>\n\n<pre><code>Game\n Human: Game\n Computer: Game\n</code></pre>\n\n<p>The problem here is that the game logic changes depending on who is playing. Thus if you have a bug in the game logic then it is spread across two classes (Human/Computer).</p>\n\n<p>I would have put all the Game logic into <code>Game</code>.<br>\nThen I would have had a class <code>Player</code> that represents the players that are passed to the game on construction. When it is a players turn you call <code>getMove()</code> on the player and it returns the next move. You can then specialize the <code>getMove()</code> for human and computer without compromising the game logic.</p>\n\n<pre><code>class Player\n{\n public:\n virtual ~Player();\n virtual int getMove(BoardState const&amp; board) = 0;\n};\nclass Human\n{\n virtual int getMove(BoardState const&amp; board)\n {\n int result;\n\n // Humans not to see board.\n std::cout &lt;&lt; board;\n\n // Get Human input\n while(!(std::cin &gt;&gt; result))\n {\n // Bad input.\n // Fix stream.\n }\n\n return result;\n }\n};\nclass ComputerWithAI_1\n{\n virtual int getMove(BoardState const&amp; board);\n};\n\n\nclass Game\n{\n public:\n Game(std::unique_ptr&lt;Player&gt; p1, std::unique_ptr&lt;Player&gt; p2)\n : player1(p1)\n , player2(p2)\n {}\n void play()\n {\n int currentPlayer = 0;\n while(state_of_game()==KEEP_PLAYING)\n {\n int move = ((currentPlayer/%2)?player1:player2)-&gt;getMove(board);\n // Validate move etc...\n // Display error message\n // Or update currentPlayer and repeat.\n }\n }\n};\n</code></pre>\n\n<h3>More General comments:</h3>\n\n<p>@Jamal: has good comments. So I am only including stuff where I disagree with him or he has not covered.</p>\n\n<p>Header files:</p>\n\n<pre><code>#include \"stdafx.h\" // has to be first\n#include &lt;iostream&gt;\n#include &lt;string&gt;\n#include &lt;Windows.h&gt;\n#include \"game.h\"\n#include \"human.h\"\n#include \"computer.h\"\n#include &lt;sstream&gt;\n</code></pre>\n\n<p>They should be ordered: Most specific first to most general last. I order mine like this:</p>\n\n<pre><code>// This is Class.cpp\n#include \"Class.h\"\n#include \"OtherMyClassIdependon1.h\"\n#include \"OtherMyClassIdependon1.h\"\n\n// Now C++ header files // Lots of people order these alphabetically\n#include &lt;string&gt; // Personally I group them\n // All the containers together.\n // All the streams together.\n // etc. Each group alphabetical.\n\n// Now C header files // Lots of people order these alphabetically\n#include &lt;unistd.h&gt;\n\n// Now System header files\n#include &lt;ICantThinkOfAnything&gt;\n</code></pre>\n\n<p>So in your case I would have done:</p>\n\n<pre><code>#include \"stdafx.h\" // has to be first\n#include \"game.h\"\n#include \"human.h\"\n#include \"computer.h\"\n// C++\n#include &lt;iostream&gt;\n#include &lt;sstream&gt;\n#include &lt;string&gt;\n// C Header\n// System Headers\n#include &lt;Windows.h&gt;\n</code></pre>\n\n<p>Common Code refactoring:</p>\n\n<pre><code>void game::Winner(char c){\n if(c=='O'){\n SetColor(YELLOW); // This is common to both conditions\n std::cout&lt;&lt;player1&lt;&lt;\" Won....\\n\";\n SetColor(WHITE); // This is common to both \n }\n else if(c=='X'){\n SetColor(YELLOW); // This is common to both \n std::cout&lt;&lt;player2&lt;&lt;\" Won....\\n\";\n SetColor(WHITE); // This is common to both \n }\n}\n</code></pre>\n\n<p>It would be easier to re-write as:</p>\n\n<pre><code>void game::Winner(char c)\n{\n SetColor(YELLOW);\n if(c=='O') {\n std::cout&lt;&lt;player1&lt;&lt;\" Won....\\n\";\n }\n else if(c=='X') {\n std::cout&lt;&lt;player2&lt;&lt;\" Won....\\n\";\n }\n SetColor(WHITE); \n}\n</code></pre>\n\n<p>The function <code>void game::win_display()</code> is a bit convoluted. You are basically doing the same thing 8 times. Just adjusting which elements are displayed in a winning colour. You could re-write like this:</p>\n\n<pre><code>void game::win_display()\n{\n bool h1,h2,h3,v1,v2,v3,d1,d2; // Init as appropriate\n\n std::cout\n &lt;&lt;\" \"&lt;&lt;Win(h1||v1||d1)&lt;&lt;board[0]&lt;&lt;\" | \"&lt;&lt;Win(h1||v2 )&lt;&lt;board[1]&lt;&lt;\" | \"&lt;&lt;Win(h1||v3||d2)&lt;&lt;board[2]\n &lt;&lt;\" \\n____|____|____\\n\"\n &lt;&lt;\" \"&lt;&lt;Win(h2||v1 )&lt;&lt;board[3]&lt;&lt;\" | \"&lt;&lt;Win(h2||v2||d1||d2)&lt;&lt;board[4]&lt;&lt;\" | \"&lt;&lt;Win(h2||v3 )&lt;&lt;board[5]\n &lt;&lt;\" \\n____|____|____\\n\"\n &lt;&lt;\" \"&lt;&lt;Win(h3||v1||d2)&lt;&lt;board[6]&lt;&lt;\" | \"&lt;&lt;Win(h3||v2 )&lt;&lt;board[7]&lt;&lt;\" | \"&lt;&lt;Win(h3||v3||d1)&lt;&lt;board[8]\n &lt;&lt;\" \\n | | \\n\\n\";\n Winner(*row1[0]);\n}\n</code></pre>\n\n<p>Now we just have to write the stream manipulator <code>win()</code> to set up the colours for the next element to be printed and set them back to <code>WHITE</code> after the element is printed.</p>\n\n<p>This is a nice trick for stream manipulators:</p>\n\n<pre><code>struct Win\n{\n Win(bool x): good(x), sptr(NULL) {}\n Win(Win const&amp; c, std::ostream&amp; s): good(c.good), sptr(&amp;s) {}\n bool good;\n std::ostream* sptr; // No ownership so pointer is OK.\n};\nWin operator&lt;&lt;(std::ostream&amp; s, Win w)\n{\n return Win(w, s); // Save the stream, as we are returning a Win object\n}\ntemplate&lt;typename T&gt;\nstd::ostream&amp; operator&lt;&lt;(Win const&amp; w, T const&amp; data)\n // ^^^^^^^^^^^^ Notice the first parameter is not a stream\n{\n std::ostream&amp; s = *(w.sptr); // Retrieve the saved stream (see above)\n if (w.good) {SetColor(TEAL);} \n s &lt;&lt; data;\n if (w.good) {SetColor(WHITE);}\n return s;\n}\n\n// SO\nstd::cout &lt;&lt; Win(true) &lt;&lt; \"X\" &lt;&lt; \"Y\";\n// ^^^^^^^^^^^^^^^^^^^^^^ Returns a \"Win\" object\n// See the first operator&lt;&lt; above.\n\n// This is equivalent to:\noperator&lt;&lt;(operator&lt;&lt;(operator&lt;&lt;(std::cout, Win(true)), \"X\"), \"Y\");\n\n// If we break this into three lines we get\nWin tmp1 = operator&lt;&lt;(std::cout, Win(true));\n// because we return a Win from `operator&lt;&lt;` when the second argument is a win!\n\n// This takes a Win as the first argument and will return the original stream.\n// But this allows us to colour any value conditionally on a win.\nstd::ostream&amp; tmp2 = operator&lt;&lt;(tmp1, \"X\");\nstd::ostream&amp; tmp3 = operator&lt;&lt;(tmp2, \"Y\");\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T13:41:01.640", "Id": "48065", "Score": "1", "body": "How about `Player &winner = (c == 'O' ? player1 : player2);`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T21:15:59.330", "Id": "48098", "Score": "0", "body": "the stream manipulators is totally new to me..gotta read up on that one ....so far i understood till the template i'll try and read as much as i can and comeback with questions....meanwhile can you point what i need to learn to understand these concepts? thank you" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T21:52:58.890", "Id": "48099", "Score": "2", "body": "@AnirudhaAdibhatla: Just remember that `operator<<` is a normal function with a funny name. That `X << Y` is short hand for: `operator<<(X,Y)`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T01:24:12.467", "Id": "48108", "Score": "0", "body": "hi can you explain what ownership of pointers is? I tried googling it but it's all kind of confusing...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T02:16:17.050", "Id": "48111", "Score": "0", "body": "hi like i mentioned i'm totally new to the everything mentioned in the stream manipulator part ....but i think i got the hang of it ...i'll explain what i understood so far step-by-step and correct where i'm wrong, also may be fill in the left out parts...." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T02:23:10.940", "Id": "48112", "Score": "0", "body": "*you created the win structure which sets its members to different values depending upon the input i.e. if input is just a bool -->set good to that bool and sptr to null and if input is another win struct-->set good to the bool of input win and sptr to address of input sptr of i/p win" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T02:23:47.007", "Id": "48113", "Score": "0", "body": "*now you overloaded the operator << so that if you get a reference and a win struct you return another win struct in such a way that it stores the address of current ostream" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T02:27:07.393", "Id": "48114", "Score": "0", "body": "*now you overloaded the operator again but this time it takes the input of a win struct(by reference to save mem(?) and const so that the i/p win struct is not modified) and the reference to incoming data which can be anything because of the template declaration before .........................now this overload takes the address from input win struct and good -->true the changes the color of the input data of template T and sets color back to white again and return the address of current ostream position" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T02:31:32.053", "Id": "48115", "Score": "0", "body": "finally when write the expression std::cout << Win(true) << \"X\" << \"Y\"; the initial std::cout << Win(true) will return a win struct object with the address of current ostream position and this inturn activates the second overloading of << which gives me the address of ostream position after inserting the colored \"X\" and now we have address of current posiyion of ostream so the program o/p \"Y\" but just in white .......right? lol it took me quite a while just to begin understanding what it was all about but luckily i came across this video which was really helpful" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T02:32:05.243", "Id": "48116", "Score": "0", "body": "here's the link to the video just in case any one wants it ......https://www.youtube.com/watch?v=_Dx_DpTIUXQ" } ], "meta_data": { "CommentCount": "10", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T12:21:02.310", "Id": "30255", "ParentId": "30238", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T04:52:50.027", "Id": "30238", "Score": "4", "Tags": [ "c++", "performance", "beginner", "game", "ai" ], "Title": "Tic-Tac-Toe optimization 2.0 with AI" }
30238
<p>How can I make it faster, more efficient, and simpler? Are there any obvious mistakes I've made, or things which will make my code "fancier"?</p> <p>It's my first time working with any form of pathfinding, so I'm sure I've made plenty of mistakes. It still works, though.</p> <p>I've ended up adding a lot of comments because I keep forgetting how my own code works.</p> <pre><code> public class AStar //Variant on Dijkstra's Algorithm - faster { public static Node[,] Grid; //Using the data type created below to make a grid, a 2 dimensional array of nodes (squares) public static List&lt;Node&gt; FindPath(Point start, Point end) //Finds the fastest route from the start to end { //Checks that we aren't trying to make a path from one place to the same place if(start.X == end.X &amp;&amp; start.Y == end.Y) { return null; } //Resets all the parent variables to clear the paths created last time for (int x = 0; x &lt;= Grid.GetUpperBound(0); x++) { for (int y = 0; y &lt;= Grid.GetUpperBound(1); y++) { Grid[x, y].Parent = null; } } List&lt;Node&gt; OpenList = new List&lt;Node&gt;(); //Nodes to be considered, ones that may be on the path List&lt;Node&gt; ClosedList = new List&lt;Node&gt;(); //Explored nodes Point CurrentPoint = new Point(0, 0); Node Current = null; List&lt;Node&gt; Path = null; OpenList.Add(Grid[start.X, start.Y]); //Add the starting point to OpenList while (OpenList.Count &gt; 0) { //Explores for the "best" choice in the Openlist Current = OpenList[0]; CurrentPoint.X = Current.X; CurrentPoint.Y = Current.Y; if (CurrentPoint == end) break; //If we have reached the end OpenList.RemoveAt(0); //Removes the starting point ClosedList.Add(Current); foreach (Node neighbour in GetNeighbours(CurrentPoint)) //Checks all the squares adjacent to the current point { //Skips fully explored nodes which have been explored fully if (ClosedList.Contains(neighbour)) continue; //Skips the node if it's a wall if (neighbour.IsWall) continue; //If parent is null, it's our first visit to the node if (neighbour.Parent == null) { neighbour.G = Current.G + 10; //10 is the cost for each horizontal or vertical node moved neighbour.Parent = Current; //Where it came from, final path can be found by linking parents //The following way of calculating the H value is called the Manhattan method, it ignores any obstacles neighbour.H = Math.Abs(neighbour.X - end.X) + Math.Abs(neighbour.Y - end.Y); //Calculates total cost by combining the X distance by the Y neighbour.H *= 10; //Then multiply H by 10 (The cost movement for each square) OpenList.Add(neighbour); } else { //Is this a more efficient route than last time? if (Current.G + 10 &lt; neighbour.G) { neighbour.Parent = Current; neighbour.G = Current.G + 10; } } } OpenList.Sort(); //This uses the IComparible interface and CompareWith() method to sort } //If we finished, end will have a parent, otherwise not Path = new List&lt;Node&gt;(); Current = Grid[end.X, end.Y]; //Current = end desination node Path.Add(Current); while (Current.Parent != null) //Won't run if end doesn't have a parent { Path.Add(Current.Parent); Current = Current.Parent; } //Path.Reverse(); //.reverse() (Above) is replaced with the below code for (int i = 0; i &lt; Path.Count() / 2; i++) { Node Temp = Path[i]; Path[i] = Path[Path.Count() - i - 1]; Path[Path.Count() - i - 1] = Temp; } //Have we found a path or used all our options? return OpenList.Count &gt; 1 ? Path : null; //Below replaced by Ternary Statement above /*if (OpenList.Count &gt; 1) return Path; else return null;*/ } private static List&lt;Node&gt; GetNeighbours(Point p) { List&lt;Node&gt; Result = new List&lt;Node&gt;(); if (p.X - 1 &gt;= 0) { Result.Add(Grid[p.X - 1, p.Y]); } if (p.X &lt; Grid.GetUpperBound(0)) { Result.Add(Grid[p.X + 1, p.Y]); } if (p.Y - 1 &gt;= 0) { Result.Add(Grid[p.X, p.Y - 1]); } if (p.Y &lt; Grid.GetUpperBound(1)) { Result.Add(Grid[p.X, p.Y + 1]); } return Result; } } public class Node : IComparable&lt;Node&gt; //Inherits from the interface IComparable, allows the nodes to be sorted using .sort() { public int X; //Position on the X axis public int Y; //Position on the Y axis public Node Parent; public bool IsWall; public int G; //The amount needed to move from the starting node to the given other public int H; //The estimated cost to move from that given node to the end point - Called Heuristic (Because it's a guess) public int F //G+H { get { return G + H; } //Automatically calculates the latest value when F is accessed } /*This must be added due to IComparable (It requires a method called "CompareTo" to work) - specifies how to sort the nodes*/ public int CompareTo(Node other) { if(this.F &lt; other.F) return -1; else if (this.F == other.F) return 0; else return 1; } public Node Clone(bool ResetGHandParent) { Node Result = new Node(); Result.X = this.X; Result.Y = this.Y; Result.IsWall = this.IsWall; if(ResetGHandParent) { Result.G = 0; Result.H = 0; Result.Parent = null; } else { Result.G = this.G; Result.H = this.H; Result.Parent = this.Parent; } return Result; } public Node Clone() { Node Result = new Node(); Result.X = this.X; Result.Y = this.Y; Result.IsWall = this.IsWall; Result.G = this.G; Result.H = this.H; return Result; } public static Node[,] MakeGrid(int Width, int Height) { //If they don't set a value for PercentWallChance, we assume they don't want any walls and set the chance to 0 return MakeGrid(Width, Height, 0); } public static Node[,] MakeGrid(int Width, int Height, int PercentWallChance) { Node[,] Result = new Node[Width,Height]; Random r = new Random(); for (int x = 0; x &lt; Width; x++) { for (int y = 0; y &lt; Height; y++) { Result[x,y] = new Node(); Result[x, y].Parent = null; Result[x, y].X = x; Result[x, y].Y = y; Result[x, y].G = 0; Result[x, y].H = 0; //This takes advantage of the fact that &lt; is a comparison operator, and will give a boolean result //r.Next(100) will generate a number from 0 to 99. //If % wallchance is 100, then r cannot NOT be less than it, and the "&lt;" will always return true (which in turn always sets IsWall to true) //If % wallchance is 0, then r literally cannot be less it, and the comparison will return false (which in turn always sets IsWall to false) Result[x, y].IsWall = r.Next(100) &lt; PercentWallChance; } } return Result; } } } </code></pre>
[]
[ { "body": "<p>Some points to consider...</p>\n\n<h3>Sorting is slow. <em>Really</em> slow.</h3>\n\n<p>At the end of your loop you call <code>OpenList.Sort()</code> to order your nodes by relative cost so that you can work on the lowest-cost nodes first. Depending on how far your search extends, this can lead to large amounts of time doing nothing but sorting the list.</p>\n\n<p>Instead of a per-iteration sort, use a collection that sorts for you on insert. This reduces the number of comparison operations, and the insert itself is usually much quicker than a shuffle.</p>\n\n<p>I've tried a few ordered list implementations, but the <code>OrderedBag&lt;T&gt;</code> class from Wintellect's <a href=\"http://powercollections.codeplex.com/\">PowerCollections</a> is my favorite.</p>\n\n<p>To give you an idea of how <em>much</em> faster this is, I generated 1,000 random <code>Node</code>s and ran them into both <code>List&lt;Node&gt;</code> with per-insert sorting and <code>OrderedBag&lt;Node&gt;</code> with automatic sort-on-insert. Here are the results:</p>\n\n<ul>\n<li><code>List&lt;Node&gt;</code> = 379.3 msec</li>\n<li><code>OrderedBag&lt;Node&gt;</code> = 4.15 msec</li>\n</ul>\n\n<p>Pretty big improvement there. And it only gets better the bigger your search area. Here's the results for 10,000 items:</p>\n\n<ul>\n<li><code>List&lt;Node&gt;</code> = 50.9 sec</li>\n<li><code>OrderedBag&lt;Node&gt;</code> = 18.6 msec</li>\n</ul>\n\n<p>Yup, that 2,500 times faster. I wasn't keen to try it at 100,000. I think you've got the picture by now :grin:</p>\n\n<p>There's an unofficial version of PowerCollections on Nuget if you aren't keen to download the source or binary distributions. Nuget is simpler, anyway.</p>\n\n<p>--Update: <code>OrderedSet&lt;T&gt;</code></p>\n\n<p>While implementing an AA-Tree class (about 20% slower in debug mode than the Wintellect <code>OrderedBag</code>) I came across a reference to <code>OrderedSet</code> being implemented as a Red-Black Tree. I threw them all together and ran the test again.</p>\n\n<p>Results:\n* List with sort-on-insert 380ms\n* OrderedBag - 40.9ms\n* AATree (my implementation) - 48.6ms\n* OrderedSet - 0.75ms</p>\n\n<p>Yes, 0.75ms.</p>\n\n<p>OK, it has some limitations, but for what you're doing it's a speedy solution that's already in the .NET framework. Refer to my <strong><em>Don't try to out-think the framework</em></strong> section below :)</p>\n\n<h3><code>List&lt;T&gt;.Contains</code> is probably not your friend</h3>\n\n<p>This line will slow you up significantly:</p>\n\n<pre><code>if (ClosedList.Contains(neighbour)) continue;\n</code></pre>\n\n<p>Since <code>ClosedList</code> is an un-ordered list, the <code>Contains</code> method is required to iterate through the list every time. It has to scan the <em>whole</em> list to find out that an item is not present, and the list just keeps on getting bigger.</p>\n\n<p>The simple answer here is to use a <code>Dictionary</code> or similar to index your items for quick lookup. You just need a per-node unique key, such as position. You could use a <code>Tuple&lt;int, int&gt;</code> as the key, but it's simple enough to bit-stuff the X and Y into a 64-bit integer and use that.</p>\n\n<p>Add this to your <code>Node</code> class:</p>\n\n<pre><code>public UInt64 Key { get { return (((UInt64)(UInt32)X) &lt;&lt; 32) | (UInt64)(UInt32)Y; } }\n</code></pre>\n\n<p>Now use a <code>Dictionary&lt;UInt64, Node&gt;</code> for your <code>ClosedList</code>:</p>\n\n<pre><code>Dictionary&lt;UInt64, Node&gt; ClosedList = new List&lt;Node&gt;();\n</code></pre>\n\n<p>Adding nodes becomes:</p>\n\n<pre><code>ClosedList[Current.Key] = Current;\n</code></pre>\n\n<p>And now you can replace that inefficient <code>Contains</code> call with:</p>\n\n<pre><code>if (ClosedList.ContainsKey(neighbour.Key)) continue;\n</code></pre>\n\n<h3>Caching is <em>GOOD</em> (sometimes)</h3>\n\n<p>If you are working in a static map that you know isn't going to change, you can get a big speed-up on subsequent path-finding from the same starting location by caching the state of your path-finding algorithm.</p>\n\n<p>What you want is a structure similar to this:</p>\n\n<pre><code>public class PathfinderState\n{\n public Node[,] Grid; // Copy of: AStar.Grid\n public OrderedBag&lt;Node&gt; OpenList; // from AStar.FindPath\n public Dictionary&lt;UInt64, Node&gt; ClosedList; // from AStar.FindPath\n}\n</code></pre>\n\n<p>This contains all the information you need to either generate a path or continue your path-finding.</p>\n\n<p>Each time you want to find a path from <code>A</code> to some arbitrary <code>B</code>:</p>\n\n<ul>\n<li>Get <code>PathfinderState</code> for point <code>A</code> from cache, or empty state if not found in cache</li>\n<li>if <code>state.CloseList</code> contains target point:\n<ul>\n<li>return path</li>\n</ul></li>\n<li>pass state to pathfinding code to continue processing until target found</li>\n<li>update state cache if necessary</li>\n<li>return path</li>\n</ul>\n\n<p>Saves a lot of time.</p>\n\n<p>There are a couple of potential problems with this:</p>\n\n<ol>\n<li>If your map changes you have to prune the cache. You might get away with keeping some of it, but mostly you have to dump the lot and start over.</li>\n<li>Memory. Lots and lots of memory.</li>\n</ol>\n\n<p>If you order your cache by last-access you can limit the memory usage a little. But if your map obstructions are going to be changing often, caching is not going to be much help.</p>\n\n<h3><a href=\"http://c2.com/cgi/wiki?PrematureOptimization\">Premature Optimization</a></h3>\n\n<p><strong>Or:</strong> <em><strong>Don't try to out-think the framework</em></strong></p>\n\n<p>We've all been guilty of this. I spent 4 hours one day coding a solution to optimize a data mining task involving several million records across ~10 tables. I was <em>so</em> pleased with my code, which ran in about 35 minutes. Then I had to change something, and after half an hour of hacking on it I threw my hands up and just used a LINQ statement. It finished the job in under 5 minutes.</p>\n\n<p>The .NET framework is a lot more mature than we give it credit for sometimes. Don't underestimate it. It's tempting to assume that the generic methods of doing things will be slow, and that we can write better code because we don't have to handle all those types and stuff.</p>\n\n<p>But the .NET framework is actually pretty well implemented. Yes, some things are slower than they could be, but those things are pretty rare these days. Most of the slow-downs are to do with making certain types thread-safe or handling edge-cases that you can safely ignore.</p>\n\n<p>It's tempting to assume the worst and write optimized code to do things that a generic function couldn't <em>possibly</em> do better. Like reversing a list:</p>\n\n<pre><code>//Path.Reverse();\n//.reverse() (Above) is replaced with the below code\nfor (int i = 0; i &lt; Path.Count() / 2; i++)\n{\n Node Temp = Path[i];\n Path[i] = Path[Path.Count() - i - 1];\n Path[Path.Count() - i - 1] = Temp;\n}\n</code></pre>\n\n<p>Okay, so this one is only done once at the end of the method, so it's no big deal. In fact this is a good reason to leave it alone - a single reverse, even a slow one, is <em>nothing</em> compared to the cost of the rest of the method.</p>\n\n<p>But is it actually faster than the built-in <code>Reverse</code> method?</p>\n\n<p>Surprisingly (to some), no.</p>\n\n<p>Take a <code>List&lt;int&gt;</code> and fill it with 1000 integers. Now reverse it 1000 times using both the built-in <code>Reverse</code> and your code above (modified to <code>int</code> instead of <code>Node</code> of course). Results on my (sadly old and under-powered) laptop:</p>\n\n<ul>\n<li><code>Reverse</code> - 83.2 msec</li>\n<li>Custom - 2488 msec</li>\n</ul>\n\n<p>So the framework's generic code is <em>30 times</em> faster than your hand-optimized code. In fact I did some tests using your code on an <code>int[]</code> array, and it's still slower (marginally) than the <code>List&lt;T&gt;.Reverse</code>. I can go into why, like the levels of indirection and processing involved in reading or writing an element in a <code>List&lt;T&gt;</code> and so on, but that's a book in itself.</p>\n\n<p>The moral: <strong>Profile, <em>then</em> optimize (and profile again).</strong></p>\n\n<ul>\n<li>First, find out where your code is spending its time.</li>\n<li>Write code that you can easily modify later, then profile where it goes slow.</li>\n<li>Find ways to fix those slow areas, and profile again.</li>\n<li>Never <em>assume</em> your replacement code is going to perform better - only profiling will tell you that.</li>\n</ul>\n\n<h3>Other Things</h3>\n\n<p>Just tell me when you've read enough. Or else I'll write a novel.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T10:10:21.450", "Id": "48045", "Score": "0", "body": "Wow! I did not expect such a large and detailed reply. I thank you massively, as this will be a huge help for my A-Level. I will definitely make use of this to improve my project. This may be asking too much, but if you could pop me an email at shivmalhotra@hotmail.co.uk I'd appreciate it. I really need some help with some of the points you raised (Not an overly experienced programmer myself). Thanks again, and if you don't want to help any further, no worries." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T10:25:55.930", "Id": "48046", "Score": "0", "body": "Also, I probably am not allowed to use other people's code - Even if I reference it. So I may have to stick with the built in types unfortunately. However, I will definitely try nevertheless" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T11:51:34.747", "Id": "48048", "Score": "0", "body": "1. I think that combining two 32-bit integers into a 64-bit integer for a key is not a clean solution, `Tuple<int, int>` (or a custom type) would be much better. 2. If you don't actually need the value, use a `HashSet` instead of `Dictionary`. The value could be either just the key, or the whole node with a custom equality comparer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T11:57:32.633", "Id": "48050", "Score": "0", "body": "@ShivamMalhotra Maybe you are expected to implement such collection yourself? Writing a [binary heap](http://en.wikipedia.org/wiki/Binary_heap) is not hard." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T13:24:14.073", "Id": "48063", "Score": "0", "body": "@svick Maybe, any good links to implementing a binary heap like the one Corey mentioned?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T13:24:49.747", "Id": "48064", "Score": "0", "body": "@svick Thanks about the HashSet, I changed it to that. Much simpler and works well." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T20:35:56.997", "Id": "48094", "Score": "0", "body": "OrderedBag<T> is a \"priority queue\" implemented with a self-balancing binary tree, and there are other implementations in C# that you could find online, as it would be an extra challenge to implement the priority queue yourself (unless you think you have the time, then go for it!)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T20:38:18.547", "Id": "48095", "Score": "0", "body": "Priority queue (aka OrderedBag) is the best friend of A*. You really gotta have a priority queue if you are doing A* and want good performance. Your only hope to stick with a simpler data structure is if you know that the grid is small that you are searching." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T21:53:16.977", "Id": "48100", "Score": "0", "body": "@svick 1. Using a 64-bit integer instead of a `Tuple<int,int>` is more of a style choice. Comparison, hashing and searching of `UInt64` values is faster than `Tuple` in a lot of cases. And I hate typing `Tuple` :grinning: 2. A `Dictionary` is conceptually closer to what I intended: a collection of objects indexed by coordinates, which I can use for fast lookups later. `HashSet` is fine for this code though." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T06:14:27.257", "Id": "48220", "Score": "0", "body": "@AndyClaw I'll have a go at making one! - Should be fun. Corey thanks for the extra info again!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T22:45:12.317", "Id": "48332", "Score": "0", "body": "@ShivamMalhotra Read up on Binary Trees - especially Red Black Trees and AA-Trees - then either implement one of those, or use an `OrderedSet<T>`. It's in the .NET framework, is fast, and will do what you need here." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T04:43:20.937", "Id": "48341", "Score": "0", "body": "@Corey Funny that you should say that. I was messing around with Red Black Trees a few weeks ago - I have a ready made class!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T14:11:17.850", "Id": "48531", "Score": "0", "body": "@Corey Did you get my email by any chance?" } ], "meta_data": { "CommentCount": "13", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T07:42:28.780", "Id": "30247", "ParentId": "30243", "Score": "12" } }, { "body": "<p>I did not read your code thoroughly . Corey already gave many detailed comments on the algorithm. I just want to comment instead of the general structure of your code. You might actually not care about this since maybe you just want your code to work. </p>\n\n<p>Basically, your code is not very object oriented. The fact that you have mostly static methods is a quick give away. I would split your file in 3 or 4 classes. Instead of the grid being of type <code>Node[,]</code>, I would defined a Grid class and I would put all relevant methods as (non-static) methods of that class. You have to do some serious thinking about which methods those would be. I might also define a Path class instead of using a <code>List&lt;Node&gt;</code>. That is only necessary if some methods can be included in that Path class. I have not read your code in enough detail to see if that is the case.</p>\n\n<p>I would not make the A-star algorithm a method of the Grid class because you might want to compare many different path finding algorithms. You could maybe define an interface with a findPath(grid, startPoint, endPoint) method.</p>\n\n<p>OO design is never trivial. As I progress on some project, I usually refactor everything every so often. I often realize my initial OO choices were wrong, so don't feel bad if you also refactor many times. You don't have to start from scratch when you refactor: it's really just copy and paste. </p>\n\n<p>The algorithm for A-star takes many screens, so I would break that method in sub-methods. The main A-star method would be composed of only 3 or 4 sub-method calls, which I would name very clearly. That is not related to OO, but I just prefer to keep my methods short for clarity. (If the different algorithms share some of the sub-methods, you could actually use OO in that case to share those sub-methods.) </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T06:13:40.173", "Id": "48219", "Score": "0", "body": "Thanks, I actually do care about my code being object-oriented! So, I am going to follow your suggestions, thanks" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T22:53:09.700", "Id": "48333", "Score": "1", "body": "OO is great, but you can have too much of a good thing. I contributed to one project where the lead was a real OO-Nazi. He rejected half of my submissions because I had methods that were more than 50 lines long and I didn't use enough interfaces. *shrug* To each their own :)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T20:09:22.587", "Id": "30274", "ParentId": "30243", "Score": "2" } } ]
{ "AcceptedAnswerId": "30247", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T06:11:41.973", "Id": "30243", "Score": "8", "Tags": [ "c#", "pathfinding" ], "Title": "How can I improve upon my A* Pathfinding code?" }
30243
<p>I have written the following program for next word prediction using n-grams. The data structure is like a trie with frequency of each word.</p> <p>Any suggestions are welcome, but I am more concerned about the <code>compareTo</code> and <code>equals</code> method, where the contract of <code>if(obj1.compareTo(other)==0)</code> then <code>(obj1.equals(obj2)</code> is not honored.</p> <p>I need the <code>compareTo()</code> method to sort the list in the end.</p> <pre><code>package com.predictor; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Set; /** * * @author Sapan Parikh */ public class WordTree implements Comparable&lt;Object&gt; { String word; Integer frequency = 1; Map&lt;WordTree, WordTree&gt; map = new HashMap&lt;&gt;(); public WordTree() { this.word = ""; } public WordTree(String word) { this.word = word; } public void addToTree(List&lt;List&lt;String&gt;&gt; ngrams) { for (List ngram : ngrams) { addNgrams(ngram); } } private void addNgrams(List&lt;String&gt; ngram) { if (ngram == null || ngram.isEmpty()) { return; } WordTree t = new WordTree(ngram.remove(0).toLowerCase()); if (this.map.containsKey(t)) { t = this.map.get(t); t.frequency++; this.map.put(t, t); } else { this.map.put(t, t); } try { this.map.get(t).addNgrams(ngram); } catch (Exception e) { e.printStackTrace(); } } public static void main(String[] args) { WordTree t = new WordTree(); t.addToTree(WordChunker.ngrams(4, "A Red-Black tree based NavigableMap implementation. The map is sorted according to the natural ordering of its keys, or by a Comparator provided at map creation time, depending on which constructor is used. Map is pretty cool too\n" + "\n")); System.out.println(t.suggestNext(chunkLastN(3, "Red-Black tree based"))); } public static List&lt;String&gt; chunkLastN(int n,String string){ List&lt;String&gt; chunks = new ArrayList&lt;&gt;(); if(string!=null &amp;&amp; string.lastIndexOf(" ")==-1){ chunks.add(string); } while(string!=null &amp;&amp; n&gt;0 &amp;&amp; string.lastIndexOf(" ")&gt;0){ chunks.add(0,string.substring(string.lastIndexOf(" ")).trim()); string = string.substring(0, string.lastIndexOf(" ")); n--; } System.out.println(chunks); return chunks; } @Override public int compareTo(Object o) { if (!(o instanceof WordTree)) { throw new ClassCastException("The object must be compared with WordTree type"); } WordTree w = (WordTree) o; if (this.frequency &lt; w.frequency) { return 1; } else if (this.frequency == w.frequency) { return 0; } else { return -1; } } public List&lt;WordTree&gt; suggestNext(List&lt;String&gt; chunks) { List&lt;String&gt; lst = new ArrayList&lt;&gt;(); if (chunks == null || chunks.isEmpty()) { return Collections.EMPTY_LIST; } else if (chunks.size() == 1) { Set&lt;WordTree&gt; keySet = this.map.get(new WordTree(chunks.remove(0))).map.keySet(); ArrayList&lt;WordTree&gt; suggestions = new ArrayList&lt;&gt;(keySet); Collections.sort(suggestions); return suggestions; } else { return this.map.get(new WordTree(chunks.remove(0))).suggestNext(chunks); } } @Override public int hashCode() { int hash = 5; hash = 61 * hash + Objects.hashCode(this.word); return hash; } @Override public boolean equals(Object obj) { if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } final WordTree other = (WordTree) obj; if (!Objects.equals(this.word, other.word)) { return false; } return true; } public void print() { System.out.println("word " + this.word + " can be followd by " + this.map.keySet()); for (Map.Entry e : this.map.entrySet()) { ((WordTree) e.getValue()).print(); } } @Override public String toString() { return " \"" + word + "\":" + frequency; //To change body of generated methods, choose Tools | Templates. } } </code></pre>
[]
[ { "body": "<p>First let answer about your concern</p>\n\n<blockquote>\n <p>I am more concerned about the compareTo and equals method where the contract of <code>if(obj1.compareTo(other)==0)</code> then <code>(obj1.equals(obj2)</code> is not honored</p>\n</blockquote>\n\n<h2><code>equals</code> Method</h2>\n\n<p>Your equals method can be minimized</p>\n\n<pre><code>public boolean equals(Object obj) {\n // It's up to you whether you will do this or not\n if(obj == null || getClass() != obj.getClass()) {\n return false;\n }\n\n final WordTree other = (WordTree) obj;\n\n if(!Objects.equals(this.word, other.word)) {\n return false;\n }\n return true;\n}\n</code></pre>\n\n<p>You are using <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Objects.html\" rel=\"nofollow noreferrer\">Objects</a> class. But this is my classical approach.</p>\n\n<pre><code>public boolean equals(Object obj) {\n if (obj == null || getClass() != obj.getClass()) {\n return false;\n }\n\n final WordTree other = (WordTree) obj;\n\n // also check the equality of frequency of two words\n // since 'frequency' is also a field\n return (!\"\".equals(word) &amp;&amp; word.equals(other.word)) &amp;&amp; \n (this.frequency == other.frequency);\n}\n</code></pre>\n\n<hr>\n\n<h2><code>compareTo</code> Method</h2>\n\n<p>Your <code>compareTo</code> method implementation is OK (if your logic says to compare two <code>WordTree</code> objects on the basis of the word <code>frequency</code>). <code>ClassCastException</code> can be easily dropped, as <code>compareTo</code> method receives generics you can change the method signature to:</p>\n\n<pre><code>public int compareTo(WordTree w) {}\n</code></pre>\n\n<p>There can be a slight optimization </p>\n\n<pre><code> if(this.frequency == w.frequency) { \n return 0;\n } \n else {\n return (this.frequency &gt; w.frequency) ? 1 : -1\n }\n</code></pre>\n\n<p>This is just a <em>micro optimization</em> and I think the compiler already makes it for you.</p>\n\n<p><strong>UPDATE after OP's comment</strong></p>\n\n<blockquote>\n <p>How would you re-write the compareTo and equals so that Map map = new HashMap&lt;>(); can be re-written as TreeMap. Right now it wont work!</p>\n</blockquote>\n\n<p>I researched and found a possible explanation from <a href=\"https://stackoverflow.com/a/13658778/2350145\">Jon Skeet's answer</a>. The problem is about inconsistency of <code>equals</code> and <code>compareTo</code> methods. The <code>compareTo</code> must return 0 if and only if <code>equals</code> returns <code>true</code>. So I'm changing my code (though I'm not sure it will work accordingly since i don't have the full code I can't test it) :</p>\n\n<pre><code>public int compareTo(WordTree w){\n if(this.frequency &gt; w.frequency) {\n return 1;\n }\n else if(this.frequency &lt; w.frequency) {\n return -1;\n }\n else {\n return this.word.compareTo(w.word);\n }\n}\n</code></pre>\n\n<hr>\n\n<h2>General Review</h2>\n\n<ul>\n<li><p>The constructors can be written as </p>\n\n<pre><code>public WordTree() {\n this(\"\");\n}\n\npublic WordTree(String word) {\n this.word = word;\n}\n</code></pre>\n\n<p>This is just a personal preference to reuse the code, but many will differ from my opinion. Do as it suits you.</p></li>\n<li><p><code>frequency</code>, <code>map</code>(rename to suite the purpose), <code>word</code> should be private fields and have getters and setters logic to access or mutate.</p>\n\n<p>This is called encapsulation and it's one of the main part of OOP languages.</p>\n\n<p>However I think <code>map</code> shouldn't have any getter and setter cause client code doesn't need to worry about <em>behind the curtain</em> map implementation.</p></li>\n<li><p>Name of the class is <code>WordTree</code> but the <code>toString()</code> method is returning the word and word-count or frequency. However I think your <code>print()</code> method achieves the <code>toString</code> behavior. Try to think of a good class name.</p></li>\n<li><p>Main method shouldn't be in an API class you should test your class from another class like <code>WordTreeTester</code> which should have the main method. </p></li>\n<li><p>A 2 cent suggestion try to <a href=\"https://stackoverflow.com/questions/211041/do-you-use-javadoc-for-every-method-you-write\">create Javadoc</a> and comment. But comment <strong>WHY</strong> are you doing not <strong>WHAT</strong> are you doing.</p></li>\n<li><p>I'm not very good in Java Collections framework but I think you should also implement <a href=\"http://docs.oracle.com/javase/7/docs/api/java/lang/Iterable.html\" rel=\"nofollow noreferrer\">Iterable interface</a>.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T16:28:13.803", "Id": "48076", "Score": "1", "body": "Objects is a class in JDK 1.7 http://docs.oracle.com/javase/7/docs/api/ How would you re-write the compareTo and equals so that Map<WordTree, WordTree> map = new HashMap<>();\n can be re-written as TreeMap. Right now it wont work!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T16:44:04.350", "Id": "48077", "Score": "0", "body": "Sorry I didn't know about `Objects` class. I edited my answer, but I don't see why you can't change `HashMap` to `TreeMap`!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T16:52:12.500", "Id": "48078", "Score": "0", "body": "Well, TreeMap seem to be using compareTo method while \"putting\" objects in the bucket so it ends up overwriting all the objects with same frequency. so in the end that Map will have one object with frequency=1 one object with freq=2 and so on" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T21:48:01.870", "Id": "59370", "Score": "0", "body": "The last part of the first `equals` method can be simplified to `Objects.equals(this.word, other.word)` :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-27T22:18:23.537", "Id": "59372", "Score": "0", "body": "@SimonAndréForsberg yes that was actually done by the OP. I like to show him the classical way, though now I think it's unnecessary." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T15:01:51.460", "Id": "30263", "ParentId": "30249", "Score": "5" } } ]
{ "AcceptedAnswerId": "30263", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T08:47:00.397", "Id": "30249", "Score": "2", "Tags": [ "java", "trie" ], "Title": "Next word prediction using n-grams" }
30249
<p>I've looked for a good method to generate an integer inside a range of values. I think using modulo is not a good method because the values are not perfectly mapped in the range. So I mapped the pseudo random generated number in the range by using double variables types.</p> <p>What do you think about this method? I know that performance is not better when using a modulo. How would you improve the method or the performance by keeping a perfect match? </p> <pre><code>quint32 randquint32(quint32 low, quint32 high) { const quint32 uint_max = 0xffffffff; if (low == 0 &amp;&amp; high == 0) { high = uint_max; if (RAND_MAX &gt; high) { return (qrand() &amp; high); } } else if (low &gt; high) { qSwap(low, high); } const quint8 numberOfBits = bitCount(RAND_MAX); quint32 myRand = 0; int i = qCeil(((double)32) / ((double)numberOfBits)); while (i--) { myRand += qrand(); if (i) { myRand &lt;&lt;= numberOfBits; } } if (low == 0 &amp;&amp; high == uint_max) { return myRand; } if (myRand == uint_max) { return high; } const double uint_max_double = (double)uint_max; double range = high - low + 1; double tmpRand = ((double)myRand) / uint_max_double * range; return qFloor(tmpRand); } quint8 bitCount(quint32 n) { quint8 count = 0; while (n) { if (n &amp; 1) { count++; } n &gt;&gt;= 1; } return count; } </code></pre> <p><strong>NEW VERSION:</strong></p> <pre><code>// count setted bits at the right of a mask quint8 bitCountRightMask(quint64 mask) { quint8 bc = 0; while (mask &amp; 1) { mask &gt;&gt;= 1; bc++; } return bc; } const quint64 uint64_max = 0xffffffffffffffff; const int bitCountRandMax = bitCountRightMask(RAND_MAX); // randomise an uint64 variable quint64 rand64() { quint64 myRand = qrand(); if (uint64_max &gt; RAND_MAX) { int i = qCeil(64 / (double)bitCountRandMax) - 1; do { myRand &lt;&lt;= bitCountRandMax; myRand += rand(); } while (i--); } return myRand; } // randomize an uint64 variable between low and high (fast method (modulo)) quint64 rand64(quint64 low, quint64 high) { if (low == 0 &amp;&amp; high == 0) { high = uint64_max - 1; } else if (low &gt; high) { qSwap(low, high); } return low + (rand64() % (high - low + 1)); } // randomize an uint64 variable between low and high (precise method (double)) quint64 prand64(quint64 low, quint64 high) { if (low == 0 &amp;&amp; high == 0) { return rand64(); } else if (low &gt; high) { qSwap(low, high); } quint64 myRand = rand64(); if (myRand == uint64_max) { return high; } static double uint64_max_double = static_cast&lt;double&gt;(uint64_max); return low + (myRand / uint64_max_double * (high - low + 1)); } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T14:54:11.637", "Id": "48069", "Score": "1", "body": "I think the initialization with `std::ceil()` could be this: `int i = std::ceil(static_cast<double>(32 / numberOfBits));`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:18:30.937", "Id": "48175", "Score": "0", "body": "Related note for the `std::ceil()` - change `int i` to `double i`: http://stackoverflow.com/questions/1253670/why-do-round-and-ceil-not-return-an-integer" } ]
[ { "body": "<p><strong>DONT DO THIS</strong></p>\n\n<pre><code>while (i--)\n{\n myRand += rand();\n if (i)\n {\n myRand &lt;&lt;= numberOfBits;\n }\n}\n</code></pre>\n\n<p>It seems like you are trying to increase the range of random numbers.<br>\nWhat you are doing is screwing up the distribution of the random numbers and thus making them less random. Have you tried plotting a histogram to show the distribution.</p>\n\n<p>Luckily for you your system probably only has 32 bit rands and thus this is not changing anything; as the loop is only done once.</p>\n\n<p><strong>ASSUMPTION HERE</strong></p>\n\n<pre><code>static const unsigned long uint_max = 0xffffffff; // assuming that long is 32 bits\n\n// long has at least 32 bits but can be larger.\n</code></pre>\n\n<p>Is this not the whole point of all the work to avoid this:</p>\n\n<pre><code> if (high &lt; RAND_MAX)\n {\n return (rand() &amp; high); // basically this is the same as using \n } // % high. You are folding at high\n // unless RAND_MAX is a multiple of high\n // then you have an uneven distribution.\n</code></pre>\n\n<p>There is plenty of documentation on the web of how to do this correctly please try and find rather than re-invent something like this. Random number generation is a non trivial task and exceedingly hard to get correct. Don't mess with it unless you have a PhD in probability.</p>\n\n<p>Rand done properly: <a href=\"https://stackoverflow.com/a/10219422/14065\">https://stackoverflow.com/a/10219422/14065</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:08:38.683", "Id": "48172", "Score": "0", "body": "No, 3 iterations for uint32 because of RAND_MAX = 0x7fffffff (15 random bits). \nNo, rand() & high is not equal to rand() % high because high is a mask here, not the high value. fail in variable name... \nSorry I converted the variable types but that was a bad idea. \nI edited the first post with the current version I use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:37:52.500", "Id": "48179", "Score": "1", "body": "@AntoineLafarge: You miss the point (and I did not say equal). It is equivalent to a `&` because you are folding around the top 16 bit. Those you are causing an uneven distribution. Different method same result (uneven distribution). Also don't assume RAND_MAX is any particular value." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T07:26:40.640", "Id": "48222", "Score": "0", "body": "Ok so you say that doing a modulo operation with superfluous bits is better than just folding this bits? \nFor the mapping I am not agree with you. \nBut I don't know for the pseudo-random generator. You must be right. \nIf I keep the superfluous bits for integrating it in the next random generated number. Does it change anything? And you, how would you generate an unsigned integer of 64 bits?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T08:38:24.440", "Id": "48227", "Score": "1", "body": "@AntoineLafarge: I am saying `masking` and `modulo` are just as bad. When you do `%` you are folding around a base 10 number when you do `&` you are folding around a base 2 number. The point is you get an **uneven distribution** unless your fold point is an exact divisor into RAND_MAX. The solution to this is well known and I provided a link." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T08:45:51.380", "Id": "48231", "Score": "1", "body": "I would not try and get a 64 bit rand (I am not a probability professor). I would look for an already implemented 64 bit random number generator that has been tested by people that know what they are doing. Maybe [boost::random](http://www.boost.org/doc/libs/1_54_0/doc/html/boost_random/reference.html#boost_random.reference.generators) has something you can use." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T09:05:35.997", "Id": "48235", "Score": "0", "body": "ok thank you very match for you replies Loki. I am creating a gambling game so your replies are useful for me." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T14:24:43.693", "Id": "30260", "ParentId": "30250", "Score": "6" } } ]
{ "AcceptedAnswerId": "30260", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T08:53:11.150", "Id": "30250", "Score": "4", "Tags": [ "c++", "random", "integer" ], "Title": "What do you think about this uint64 random generator?" }
30250
<p>I'd like to create a cookie wrapper in my application to help support a DRY approach to coding common cookie methods, provide IntelliSense for cookie-type properties (keys), and protect against typo-errors when working with cookies from multiple classes and namespaces. </p> <p>The best structure for this (that I can think of) is to apply a base class like such:</p> <pre><code>abstract class CookieBase{ protected HttpRequestBase request; protected HttpCookie cookie; protected string name; public HttpCookie Cookie { } public string Name { get; } public HttpCookie Get(){ ... } protected string GetValue(string key){ ... } public bool IsSet(){ ... } protected void SetValue(string key, string value){ ... } } </code></pre> <p>Then for each cookie-type that inherits the base class define properties for each key that should be stored in the <code>HttpCookie</code>, and define a constructor that accepts the Request object as a parameter and instantiates the Cookie property of the base class.</p> <p>Any ideas on how I might improve this design, or suggestions to alternative approaches to attaining the goals I stated at the start of this post?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T12:00:55.820", "Id": "48051", "Score": "0", "body": "Why do you have `Cookie` and `Get()` that seem to do the same thing?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T15:32:34.803", "Id": "48074", "Score": "0", "body": "@svick - that was legacy from a first attempt. I've removed the Get() method." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T19:52:30.220", "Id": "48202", "Score": "0", "body": "httpCookie has a name field. If CookieBase can have two names, one in httpCookie and one in a public property you should document their differences. Also I can't tell how the name is going to get updated." } ]
[ { "body": "<p>I am thinking that you are looking for an <code>Interface</code> rather than an <code>Abstract</code></p>\n\n<p>I am not sure what all you want to use this for, but I am thinking it might be worth looking into, especially if everything inside this class is something that you must have.\nthe only thing with an interface is that it doesn't supply any code, it just provides the template for classes that implement it. to me it just seems that what you want is in interface, but I cannot be certain that is what will work for you.</p>\n\n<p>check out <strong><a href=\"http://www.codeproject.com/Articles/11155/Abstract-Class-versus-Interface\" rel=\"nofollow\">Abstract Class versus Interface</a></strong> From CodeProject.com\nor even\n<strong><a href=\"http://msdn.microsoft.com/en-us/library/9cc659c4%28v=vs.71%29.aspx\" rel=\"nofollow\">Interfaces and Abstract Classes</a></strong> From the MSDN Website</p>\n\n<p>an Interface will Define what is needed in the class, and give some intellisense when creating the new class when inheriting the interface, and multiple interfaces can be inherited into one class whereas only one abstract class can be inherited to a class.</p>\n\n<p>again, you will have to look at the differences and see what is going to work better for you.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T10:55:34.060", "Id": "48244", "Score": "1", "body": "The abstract class is needed because the GetValue(string),IsSet(), and SetValue(string,string) methods supply routine logic that is not unique the inheriting classes." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T13:36:40.517", "Id": "48272", "Score": "0", "body": "I don't know how complex you want this to be, but maybe you could create the abstract that inherits that Interface, (not sure how this works just shooting out an idea), or you could inherit the abstract and the interface, (can't remember if you can do that or not, again just shooting ideas)" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:22:09.990", "Id": "30314", "ParentId": "30251", "Score": "1" } }, { "body": "<blockquote>\n<pre><code>abstract class CookieBase{\n</code></pre>\n</blockquote>\n\n<p>Might be just a coding style nitpick, but in C# the scope-opening brace goes on the next line, like this:</p>\n\n<pre><code>abstract class CookieBase\n{\n</code></pre>\n\n<p>Also (and this is possibly just a personal preference), when an access modifier isn't specified, it's <code>public</code> by default. This may or may not be what's intended - the intent is always clearer when the access modifiers are explicit:</p>\n\n<pre><code>public abstract class CookieBase\n{\n</code></pre>\n\n<p>I like that you're using the <code>Base</code> suffix to denote a base/abstract class - seeing <code>FooBase</code> immediately tells me that the class cannot be instantiated directly.</p>\n\n<blockquote>\n<pre><code> protected HttpRequestBase request;\n protected HttpCookie cookie;\n protected string name;\n</code></pre>\n</blockquote>\n\n<p><code>protected</code> members should follow the same casing convention as <code>public</code> members - <code>PascalCase</code>:</p>\n\n<pre><code>protected HttpRequestBase Request;\nprotected HttpCookie Cookie;\nprotected string Name;\n</code></pre>\n\n<p>Now, exposing fields is never a recommended approach. You should expose <em>properties</em>, not <em>fields</em>. Hence:</p>\n\n<pre><code>protected HttpRequestBase Request { get; set; }\nprotected HttpCookie Cookie { get; set; }\nprotected string Name { get; set; }\n</code></pre>\n\n<p>Now this causes a naming clash with some other <code>public</code> members:</p>\n\n<blockquote>\n<pre><code> public HttpCookie Cookie { }\n public string Name { get; }\n</code></pre>\n</blockquote>\n\n<p>The solution would be to make the properties <code>public</code>, with a <code>protected</code> setter (and remove the clashing <code>public</code> members):</p>\n\n<pre><code>public HttpRequestBase Request { get; protected set; }\npublic HttpCookie Cookie { get; protected set; }\npublic string Name { get; protected set; }\n</code></pre>\n\n<p>Having a method called <code>Get</code> is basically a code smell all by itself. I'd get rid of it, its functionality seems to be already implemented in the <code>Cookie</code> property:</p>\n\n<blockquote>\n<pre><code> public HttpCookie Get(){ ... }\n</code></pre>\n</blockquote>\n\n<p>The rest of your code is not quite reviewable, I'd suggest you first implement it before your post it for peer review:</p>\n\n<pre><code> protected string GetValue(string key){ ... }\n\n public bool IsSet(){ ... }\n\n protected void SetValue(string key, string value){ ... }\n}\n</code></pre>\n\n<hr>\n\n<p>Is this a good approach? Not sure. <code>abstract</code> classes define <em>abstractions</em>, but your abstract class has nothing that actually warrants being <code>abstract</code> - you have no <code>virtual</code> or <code>abstract</code> members, not even a <code>protected</code> constructor, which leads me to believe that your derived classes might look like this:</p>\n\n<pre><code>public class SomeCookie : CookieBase\n{\n}\n\npublic class AnotherCookie : CookieBase\n{\n}\n</code></pre>\n\n<p>...if that's the case, then the base class is probably a bad design and you're probably better off just calling it <code>Cookie</code> and making it a <em>normal</em> class.</p>\n\n<p>If your goal was to define an <em>abstraction</em>, @Malachi's answer is probably accurate - you'd be better off defining these members in some <code>ICookie</code> interface (which the \"normal\" <code>Cookie</code> class described above could very well be implementing).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-29T23:36:55.743", "Id": "52055", "ParentId": "30251", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T09:41:58.213", "Id": "30251", "Score": "3", "Tags": [ "c#", "asp.net-mvc-4", "http" ], "Title": "Cookie wrapper in MVC4" }
30251
<p>I recently started working on my code's cleanliness/logistics and would appreciate it if you could give me some tips on how to improve certain things.</p> <p>Here's a simple console Hangman game I've made:</p> <pre><code>#include &lt;fstream&gt; #include &lt;iostream&gt; #include &lt;stdio.h&gt; #include &lt;stdlib.h&gt; #include &lt;string&gt; #include &lt;time.h&gt; #include &lt;vector&gt; using std::cout; using std::cin; using std::endl; using std::string; using std::vector; using std::ifstream; void Clear_Screen(){ cout &lt;&lt; string(1000, '\n'); } vector&lt;string&gt; Add_Lines(unsigned short int usiLength){ vector&lt;string&gt; vecsLines_Vector; for(unsigned short int i = 0; i &lt; usiLength; i++){ vecsLines_Vector.push_back("_"); } return vecsLines_Vector; } string Output_Guesses(vector&lt;string&gt; vecsVector, unsigned short int usiLimit){ string sOutput; for(unsigned short int usiI = 0; usiI &lt; usiLimit; usiI++){ sOutput += vecsVector[usiI] + " "; } return sOutput; } int main(){ while(true){ cout &lt;&lt; "\t" &lt;&lt; " __ __ _______ __ _ _______ __ __ _______ __ _ " &lt;&lt; endl &lt;&lt; "\t" &lt;&lt; "| | | || _ || | | || || |_| || _ || | | |" &lt;&lt; endl &lt;&lt; "\t" &lt;&lt; "| |_| || |_| || |_| || ___|| || |_| || |_| |" &lt;&lt; endl &lt;&lt; "\t" &lt;&lt; "| || || || | __ | || || |" &lt;&lt; endl &lt;&lt; "\t" &lt;&lt; "| || || _ || || || || || _ |" &lt;&lt; endl &lt;&lt; "\t" &lt;&lt; "| _ || _ || | | || |_| || ||_|| || _ || | | |" &lt;&lt; endl &lt;&lt; "\t" &lt;&lt; "|__| |__||__| |__||_| |__||_______||_| |_||__| |__||_| |__|" &lt;&lt; endl &lt;&lt; endl &lt;&lt; "\t\t\t\t" &lt;&lt; "---------------" &lt;&lt; endl &lt;&lt; "\t\t\t\t" &lt;&lt; "| 1. New Game |" &lt;&lt; endl &lt;&lt; "\t\t\t\t" &lt;&lt; "| 2. Exit |" &lt;&lt; endl &lt;&lt; "\t\t\t\t" &lt;&lt; "---------------" &lt;&lt; endl &lt;&lt; "\t\t\t\t" &lt;&lt; "Selected : "; // Prevents from entering an invalid value unsigned short int usiMenu_Select = 0; do{ cin &gt;&gt; usiMenu_Select; }while(usiMenu_Select &lt; 1 || usiMenu_Select &gt; 2); // Quit Game if(usiMenu_Select == 2){ return 0; } Clear_Screen(); // Grab all the words from the dictionary and store them into a vector vector&lt;string&gt; vecsWords; unsigned int uiLength = 0; ifstream Dictionary; Dictionary.open("dictionary.txt"); if(Dictionary.is_open()){ while(Dictionary.good()){ string sWord; getline(Dictionary, sWord); vecsWords.push_back(sWord); uiLength++; } } Dictionary.close(); // Pick a random word from the dictionary vector srand (time(NULL)); const unsigned int kuiRandom_Number = rand() % uiLength; const string ksWord_Selected = vecsWords[kuiRandom_Number]; // Creates guessing lines const unsigned short int kusiWord_Length = ksWord_Selected.length(); const unsigned short int kusiTries = 6; vector&lt;string&gt; vecsGuesses = Add_Lines(kusiWord_Length); vector&lt;string&gt; vecsWrongs = Add_Lines(kusiTries); // Guessing game loop unsigned short int usiIncorrect = 0; unsigned short int usiCorrect = 0; while(usiIncorrect &lt; kusiTries){ cout &lt;&lt; "\t\t\t" &lt;&lt; "Correct : " &lt;&lt; Output_Guesses(vecsGuesses, kusiWord_Length) &lt;&lt; endl &lt;&lt; endl &lt;&lt; "\t\t\t" &lt;&lt; " Wrong : " &lt;&lt; Output_Guesses(vecsWrongs, kusiTries) &lt;&lt; endl &lt;&lt; endl &lt;&lt; "\t\t\t" &lt;&lt; " Guess : "; // Prevents from entering more than 1 character string cGuess; do{ cin &gt;&gt; cGuess; }while(cGuess.length() &gt; 1); // Checks if letter guessed is part of the word bool bValid = false; for(unsigned short int i = 0; i &lt;= kusiWord_Length; i++){ const string ksValid_Character = ksWord_Selected.substr(i,1); if(cGuess == ksValid_Character){ vecsGuesses[i] = cGuess; usiCorrect++; bValid = true; } } // Checks if answer is valid if(!bValid){ vecsWrongs[usiIncorrect] = cGuess; usiIncorrect++; } // Output end game message if(usiCorrect == kusiWord_Length){ cout &lt;&lt; "\t\t\t" &lt;&lt; " _ _ _ _ " &lt;&lt; endl &lt;&lt; "\t\t\t" &lt;&lt; "| | | |_|___ ___ ___ ___ " &lt;&lt; endl &lt;&lt; "\t\t\t" &lt;&lt; "| | | | | | | -_| _|" &lt;&lt; endl &lt;&lt; "\t\t\t" &lt;&lt; "|_____|_|_|_|_|_|___|_| " &lt;&lt; endl &lt;&lt; "\t\t\t" &lt;&lt; "Enter any keys to continue.."; cin &gt;&gt; cGuess; usiIncorrect = kusiTries; }else if(usiIncorrect == kusiTries){ cout &lt;&lt; "\t\t\t" &lt;&lt; " __ " &lt;&lt; endl &lt;&lt; "\t\t\t" &lt;&lt; "| | ___ ___ ___ ___ " &lt;&lt; endl &lt;&lt; "\t\t\t" &lt;&lt; "| |__| . |_ -| -_| _|" &lt;&lt; endl &lt;&lt; "\t\t\t" &lt;&lt; "|_____|___|___|___|_| " &lt;&lt; endl &lt;&lt; "\t\t\t" &lt;&lt; "Enter any keys to continue.."; cin &gt;&gt; cGuess; usiIncorrect = kusiTries; } Clear_Screen(); } } } </code></pre>
[]
[ { "body": "<ul>\n<li><p>You may group your STL <code>#include</code>s either alphabetically, or by groups (credit to @Loki Astari in a different answer):</p>\n\n<blockquote>\n<pre><code>// This is Class.cpp\n#include \"Class.h\"\n#include \"OtherMyClassIdependon1.h\"\n#include \"OtherMyClassIdependon1.h\"\n\n// Now C++ header files // Lots of people order these alphabetically\n#include &lt;string&gt; // Personally I group them\n // All the containers together.\n // All the streams together.\n // etc. Each group alphabetical.\n\n// Now C header files // Lots of people order these alphabetically\n#include &lt;unistd.h&gt;\n\n// Now System header files\n#include &lt;ICantThinkOfAnything&gt;\n</code></pre>\n</blockquote></li>\n<li><p>Use <code>&lt;ctime&gt;</code> instead of <code>&lt;time.h&gt;</code>. The latter is a C library and is within <code>namespace std</code>.</p></li>\n<li><p>Those <code>using</code>s at the top look tacky. I'd just put the <code>std::</code> where they're needed. This will also aid in separating the STL entities from everything else, for the sake of maintainability and name-clashing avoidance.</p></li>\n<li><p>Functions should start with a lowercase letter if a capital letter is used for types.</p>\n\n<p>Using camelCase:</p>\n\n<pre><code>void oneFunction() {}\n</code></pre>\n\n<p>Using snake_case:</p>\n\n<pre><code>void another_function() {}\n</code></pre></li>\n<li><p><code>Output_Guesses()</code> does not change the container, so pass <code>vecsVector</code> by <code>const&amp;</code>:</p>\n\n<pre><code>std::string Output_Guesses(std::vector&lt;std::string&gt; const&amp; vecsVector, /* ... */) {}\n // ^^^^^^\n</code></pre></li>\n<li><p>Move <code>std::srand()</code> to the top of <code>main()</code> for maintainability and rewrite it like this:</p>\n\n<pre><code>// use nullptr instead if you're using C++11\nstd::srand(static_cast&lt;unsigned int&gt;(std::time(NULL)));\n</code></pre>\n\n<p>Without this, <code>std::srand()</code> will return the same random number each time. The casting is also only needed if your compiler gives warnings, so be sure they're enabled.</p>\n\n<p>Also, if you have C++11, replace <code>NULL</code> with <a href=\"http://en.cppreference.com/w/cpp/language/nullptr\" rel=\"nofollow noreferrer\"><code>nullptr</code></a>.</p></li>\n<li><p>When dealing with STL containers (such as <code>std::vector</code> and <code>std::string</code>), <a href=\"https://stackoverflow.com/questions/919406/what-is-the-difference-between-accesing-vector-elements-using-an-iterator-vs-an\">use their iterators instead of indices whenever possible</a>. One occurrence of this is in <code>Add_Lines()</code>.</p></li>\n<li><p>For your \"winner\" and \"loser\" outputs, you're flushing the buffer at each line, which is what <code>std::endl</code> is doing. To make a newline without doing this, add <code>\\n</code> anywhere within the quotes. You could still put the <code>std::endl</code> at the last line of the program or wherever flushing is needed.</p></li>\n<li><p><code>while (true)</code> is okay. Another option is <code>for (;;)</code>, which also does an infinite loop until stopped (usually with a <code>break</code>).</p></li>\n<li><p>I would consider using a <code>typedef</code> for your frequently-used types such as <code>const unsigned short int</code>. For instance: if this same type is used for all of your word lengths, then name it something like <code>WordLength</code>. This is capitalized since it's a user-defined type.</p>\n\n<p>Regarding word length, prefer <a href=\"https://stackoverflow.com/questions/1181079/stringsize-type-instead-of-int\"><code>std::string::size_type</code></a>. What if you're working with a super freakishly-large string that exceeds the size of an <code>unsigned short int</code>? Having this type will guarantee that you can use such a long word without having to change all of these types.</p></li>\n<li><p>Constants could safely be put in global scope:</p>\n\n<pre><code>const unsigned short int kusiTries = 6\n</code></pre>\n\n<p>This is okay because it is <em>not</em> a global variable with <code>const</code> and cannot be modified elsewhere in the program.</p>\n\n<p>Also, refrain from using Hungarian notation in a strongly-typed language such as C++. Just a simple <code>tries</code> will suffice.</p></li>\n<li><p>With all the \"magic numbers\" you're sticking in your functions, I'd at least use <code>EXIT_SUCCESS</code> and <code>EXIT_FAILURE</code> in <code>main()</code> where necessary. As for the \"magic numbers\" themselves, prefer constants (as mentioned above).</p></li>\n<li><p>For proper inputting with <code>std::string</code>, prefer <a href=\"http://en.cppreference.com/w/cpp/string/basic_string/getline\" rel=\"nofollow noreferrer\"><code>std::getline()</code></a>:</p>\n\n<pre><code>getline(std::cin, cGuess);\n</code></pre></li>\n<li><p>For the input validation, such as for the menu, I'd recommend exception-handling (<code>try</code>/<code>catch</code>). This would prevent the program from bugging-up from bad input, and would allow recovery.</p></li>\n<li><p>Lastly (and probably most importantly): <strong>use more functions</strong>. You may still keep the program simple without using classes, and that's alright. However, when you cram everything into <code>main()</code> (or any one function for that matter), you significantly reduce your program's overall maintainability.</p>\n\n<p>Just keep the \"welcome\" stuff, menu, and game state (continue playing or not) in <code>main()</code>. Everything else should be split into functions based on purpose. It's also not practical to create a function that <em>only</em> displays something as simple as a message, unless it happens to require arguments. Also, if you're using the same block of code repeatedly (such as displaying an array), put that into a separate function.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T23:31:46.893", "Id": "48211", "Score": "0", "body": "While i agree with most of what you've said and have started using all of your tips, I'm not quite sure about the whole \"Put chunk of codes into functions to save space\". Mainly because, if i don't use this function twice, it's gonna be a waste of memory plus, it doesn't actually help because I'm just moving the chunk of code outside of main(). So my file is still gonna be a mess." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T23:48:32.047", "Id": "48212", "Score": "0", "body": "Even if it still looks like a mess, *at least* you can separate the concerns. For instance: the block following the comment `Checks if letter guessed is part of the word`. If that were in a function, you would just do a function call in its place in `main()`. If you then want to go back and improve it or add to it, you know right where it is. As for memory as a whole, creating functions doesn't have a significant effect on it. And I've already mentioned readability. It's not all about the space; functions won't always save that much. It's much about organization." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T15:21:59.830", "Id": "30264", "ParentId": "30261", "Score": "14" } } ]
{ "AcceptedAnswerId": "30264", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T14:48:22.607", "Id": "30261", "Score": "15", "Tags": [ "c++", "game", "console", "hangman" ], "Title": "Hangman game logicistics and cleanliness" }
30261
<p>In order to make cert creation with easy-rsa as practical for others, this script was created and it works so far. The questions are:</p> <ol> <li>where can it be improved?</li> <li>are there flaws that are not obvious to the author?</li> </ol> <p>The commentary is a bit extensive, but whomever will come across this in the future should be able to understand what's being done no matter how advanced.</p> <pre><code>#!/bin/bash ## ## This script automates the complete process of creating new easy-rsa client certificates. ## It includes: 1. Mounting a block device. ## 2. Generating certificates using individual timestamps. ## 3. Copying the created certs to the mounted block device. ## ## # # First we look for the usb device at sdc1 and mount it. If not present tell the pebcac the it should insert one. # all the predifined variables will end up beneath myself=auto_rsa_gen.sh # tells the script who it is export easy_rsa=../rsa_testing # tells the script where it is and exports this information for use in child processes now=$(date +"%F") ## # Show a list of available drives and ask the user for the dev he wants to mount echo "These \n$(ls /dev | grep sd) \nare the drives available. Please tell me which one you want to mount \n(hint: its usually the one having just the one additional entry. Like sdc1):" # read user input (blkdev is the variable that will hold the user inuput for further processing) read blkdev ## # I. Mount # check if de given device exists if [ -b /dev/"$blkdev" ] then # if it exists mount it to /media sudo mount /dev/$blkdev /media echo "\nDevice $blkdev has been mounted!" else # if it doesn't exist echo "Device doesn't appear to exist! Restarting" sh "$myself" # restart the script fi # Ask for an identifier to be used in the wrapper for easy-rsa cert creation echo "\nPlease provide an identifier for the certs that will be created \n(The identifier will be appended to the current date of the machine):" # read user input (ident is the variable that will hold the user input for further processing) read ident # Ask for ne number of certs to be created echo "\nHow many certificates do you want me to create?" # read user input (cnum is the variable that will hold the user input for further processing) read cnum ## # II. Wrapper for easy-rsa cert creation # # this is a while loop in case there was no input for ident. It only stop when the user hast put in something other than nothing while [ -z $ident ] do echo "\nYou did not supply an identifier. Please do so or i will terminate." read ident # read user input again done # change directory to the easy-rsa directory cd $easy_rsa # tell user what you are going to do echo "\nCreating $cnum certificates with ${now}_$ident." # load vars file . ./vars ## # II.a Generation # for loop that creates $cnum certificates and appends an incrementing number to the end of every # file name for i in $(seq -f %03g $cnum) do ${easy_rsa}/./build-batch ${now}_${ident}_$i done ## # II.b Copying # for loop that searches for all certs created with this run and copies them to /media where $blkdev is mounted find ${easy_rsa}/keys/ -name ${now}_${ident}*.crt -o -name ${now}_${ident}*.key &gt; /media/${now}_${ident} for f in $(find ${easy_rsa}/keys/ -name ${now}_${ident}*.crt -o -name ${now}_${ident}*.key ) do cp $f /media done echo "\nCopied \n$(find ${easy_rsa}/keys/ -name ${now}_${ident}*.crt -o -name ${now}_${ident}*.key) \nto /media" # unmounting $blkdev at /media umount /media echo "\nUmounted $blkdev at /media. Exiting! Bye!"ere </code></pre>
[]
[ { "body": "<p>This</p>\n\n<pre><code>myself=auto_rsa_gen.sh # tells the script who it is\n</code></pre>\n\n<p>is better done like this:</p>\n\n<pre><code>myself=\"$0\"\n</code></pre>\n\n<p>or, if you want just filename, then</p>\n\n<pre><code>myself=\"$(basename \"$0\")\"\n</code></pre>\n\n<p>because it will give you the actual name of the script, instead of being hard-coded. This also opens a nice renaming possibilities if you use symlinks.</p>\n\n<p>This part:</p>\n\n<pre><code>echo \"These \\n$(ls /dev | grep sd) \\nare the drives available. Please tell me which one you want to mount \\n(hint: its usually the one having just the one additional entry. Like sdc1):\"\n\n# read user input (blkdev is the variable that will hold the user inuput for further processing)\nread blkdev\n\n##\n# I. Mount\n# check if de given device exists\nif [ -b /dev/\"$blkdev\" ]\n then # if it exists mount it to /media\n sudo mount /dev/$blkdev /media\n echo \"\\nDevice $blkdev has been mounted!\"\n else # if it doesn't exist\n echo \"Device doesn't appear to exist! Restarting\"\n sh \"$myself\" # restart the script\n fi\n</code></pre>\n\n<p>I think is better put in a <code>while</code> loop, instead of restarting a script, like this:</p>\n\n<pre><code>while true; do\n echo \"Pick device, blah, blah,... Press Ctrl+C to abort.\"\n read blkdev\n if [ ! -b /dev/\"$blkdev\" ]; then\n echo \"The device doesn't appear to exist!\"\n continue;\n fi\n sudo mount /dev/\"$blkdev\" /media\n echo \"\\nDevice '$blkdev' has been mounted!\"\ndone\n</code></pre>\n\n<p>You might also want to check if the <code>mount</code> command succeeded.</p>\n\n<p>Also, <code>/media</code> is a standard directory for dynamic mounts. That means that your script will hide mountpoints of mounted CDs, DVDs, USB keys,... while it is running, which may be very inconvenient in some situations (for example, if you have some copying done in the background).</p>\n\n<p>Btw, <code>echo 'Line 1\\nLine 2'</code> outputs <code>Line 1\\nLine 2</code> instead of two lines (GNU bash, version 4.2.45, Fedora 19). The correct way for this is</p>\n\n<pre><code>echo -e 'Line 1\\nLine 2'\n</code></pre>\n\n<p>I assume you have <code>-e</code> aliased, or on your distribution it is on by default, or something like that. However, it is not portable, so I suggest you add <code>-e</code> where needed.</p>\n\n<p>I also have a bit of a problem with</p>\n\n<pre><code>cd $easy_rsa\n</code></pre>\n\n<p>These are my concerns:</p>\n\n<ol>\n<li><p>It has a relative path to the subdirectory. This will hardly produce satisfactory results if your script is invoked from a directory other than you intended it to be invoked from. Maybe this value should either be prompted (with <code>read</code>), or picked up from the command line?</p></li>\n<li><p>You're not checking that the directory exists. You could force the directory creation (<code>mkdir -p \"$easy_rsa\"</code>), and - on top of that - check that <code>$0</code> is true (i.e., equal to <code>0</code>) afterwards.</p></li>\n</ol>\n\n<p>In the last line</p>\n\n<pre><code>echo \"\\nUmounted $blkdev at /media. Exiting! Bye!\"ere\n</code></pre>\n\n<p>This <code>ere</code> in the end seems to be here by an error.</p>\n\n<p>I also have one general remark. Instead of writing <code>echo $something</code>, <code>cd $dir</code>, and similar commands, I suggest you use <code>echo \"$something\"</code>, <code>cd \"$dir\"</code>, etc. There is no point in thinking if one of these may contain space and, when editing your script later on, thinking about fixing this if you do include a space. It's much easier and safer to always behave as if a variable can contain a space and just include the quotation marks.</p>\n\n<p>Also, without the quotation marks, you're in trouble with all the variables that get their values from the user. The example for this is your <code>$blkdev</code> variable which you sometimes enclose in the quotation marks, but sometimes you do not (I added them in the <code>mount</code> command in my loop example above).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T18:31:42.610", "Id": "30271", "ParentId": "30262", "Score": "1" } }, { "body": "<p>I assume you are running this script on Linux.</p>\n\n<p>Prompting the user for a device to mount and unmount is a bit unusual, not to mention user unfriendly and error prone. What is your intention — to find a USB memory stick? If so, you could mitigate some of the danger by limiting the user's choices.</p>\n\n<ul>\n<li>You might only present USB block devices as options (Look for <code>/dev/disk/by-path/*-usb-*</code>.)</li>\n<li>You could look for a device with a particular volume label. (Look in <code>/dev/disk/by-label/NAME</code>.)</li>\n<li>You could check whether the device is on <a href=\"https://unix.stackexchange.com/questions/40143\">removable media</a>.</li>\n</ul>\n\n<p>Here's one way to list removable media and their partitions:</p>\n\n<pre><code>for blkdev in /sys/block/* ; do\n if [ \"`cat $blkdev/removable`\" = 1 ]; then\n for devnum in `cat \"$blkdev\"/dev \"$blkdev\"/*/dev 2&gt;/dev/null` ; do\n for node in /dev/* ; do\n [ \"`stat -c %t:%T \"$node\"`\" = \"$devnum\" ] &amp;&amp; echo \"$node\"\n done\n done\n fi\ndone\n</code></pre>\n\n<p>Instead of mounting the device at <code>/media</code>, I suggest creating a temporary directory with <code>mktemp -d</code> and mounting it there. Linux desktop environments often use subdirectories of <code>/media</code> as places where devices are <a href=\"http://linux.die.net/man/1/gnome-mount\" rel=\"nofollow noreferrer\">automatically mounted on insertion</a>.</p>\n\n<hr>\n\n<p>Restarting the script with <code>sh \"$myself\"</code> is problematic in several ways:</p>\n\n<ul>\n<li>You've hard-coded the name of the script, so it will break if anyone renames the script. You could use <code>$0</code> instead.</li>\n<li>You've assumed that <code>auto_rsa_gen.sh</code> is in the current directory.</li>\n<li>The first run is done in Bash due to the shebang line, but subsequent runs are in <code>sh</code> (usually Bash in Bourne-shell compatibility mode).</li>\n<li>You didn't use <code>exec</code>, so execution of the outer script will continue with the wrong device after the inner script completes successfully with the right device.</li>\n</ul>\n\n<p>The straightforward solution, which is to use a <code>while</code> loop, would have avoided all of those pitfalls.</p>\n\n<hr>\n\n<p>The validation of <code>$ident</code> does not happen after the prompt, but is interrupted by the prompt for <code>$cnum</code>. That's confusing to the user and to the programmer.</p>\n\n<hr>\n\n<p>You should echo the confirmation of copying within the loop:</p>\n\n<pre><code>cp \"$f\" /media/ &amp;&amp; echo \"Copied $f to /media\" \\\n || echo \"Failed to copy $f to /media\"\n</code></pre>\n\n<p>This is better because:</p>\n\n<ul>\n<li>You avoid running <code>find</code> twice, which is more efficient.</li>\n<li>You avoid running <code>find</code> twice, which is more maintainable.</li>\n<li>The confirmation message only appears if copying succeeded.</li>\n<li>It acts as a progress indicator.</li>\n</ul>\n\n<hr>\n\n<p>It is idiomatic to put the <code>do</code> at the end of the same line as <code>while</code> and <code>for</code>, like this:</p>\n\n<pre><code>while condition ; do\n stuff\ndone\n\nfor i in $list ; do\n stuff_with \"$i\"\ndone\n</code></pre>\n\n<p>Similarly, <code>then</code> follows on the same line as <code>if</code>:</p>\n\n<pre><code>if $condition ; then\n something\nelse\n something_else\nfi\n</code></pre>\n\n<p>Your indentation will make more sense if you follow these conventions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T19:52:03.957", "Id": "30325", "ParentId": "30262", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T14:53:35.097", "Id": "30262", "Score": "3", "Tags": [ "bash" ], "Title": "Automating easy-rsa cert creation with Bash script" }
30262
<p>Is there a better way to write this, as I am using the condition of the Cancellation Token to tell if it should use a byte[] from another thread or not.</p> <pre><code> SharpDX.Windows.RenderLoop.Run(form, () =&gt; { if (CTS.IsCancellationRequested) form.Dispose(); if (Queue.TryTake(out TextureData, 300)) { Stoptimer = new Stopwatch(); Stoptimer.Start(); device.BeginScene(); sprite.Begin(SpriteFlags.None); try { using (var surface = texture.GetSurfaceLevel(0)) { if (!CTS.IsCancellationRequested) Surface.FromFileInMemory(surface, TextureData, SharpDX.Direct3D9.Filter.None, 0); } sprite.Draw(texture, new ColorBGRA(0xffffffff)); } catch (Exception ex) { MessageBox.Show(ex.Message, "Rendering: Texture"); } sprite.End(); device.EndScene(); device.Present(); Stoptimer.Stop(); Console.WriteLine(Stoptimer.ElapsedTicks); } }); </code></pre> <p>The important place is here:</p> <pre><code> if (!CTS.IsCancellationRequested) Surface.FromFileInMemory(surface, TextureData, SharpDX.Direct3D9.Filter.None, 0); </code></pre> <p>As I need to recheck this, as the Cancellation can happen After it has taken the data from the Queue.</p> <p>But I wonder, is there a better way to write it?</p> <p>As you can see, I use the CTS condition 2 times, and it would be nice if I could only use it once to control the flow or something.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T17:33:09.517", "Id": "48079", "Score": "0", "body": "I think you shouldn't use `CancellationToken` here at all, since it looks like you're not actually using it for cancellation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T18:26:30.700", "Id": "48085", "Score": "0", "body": "I am, but well, it´s like this.\nI have 2 Threads, one fills a buffer, one reads it (this is the reading part). So they must be in sync more or less. So i need to be able to shut them down at the same time. And also be able to close it along with the other if the connection fails (the other thread is using TCP)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T19:03:07.267", "Id": "48088", "Score": "0", "body": "ok so the only thing that you don't want it to do if the cancellation token is activated is `Surface.FromFileInMemory(surface, TextureData, SharpDX.Direct3D9.Filter.None, 0);` because everything else there will still happen no matter what, including `sprite.Draw(texture, new ColorBGRA(0xffffffff));`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T19:04:47.163", "Id": "48089", "Score": "0", "body": "how much time is really passing between the first mention of the `cancellation token` to the one inside the double `if` block?" } ]
[ { "body": "<p><strong>EDIT</strong></p>\n\n<p>I think this is what you are looking for, it will only check once inside the using block, if you want to dispose the form if that first <code>Queue.TryTake(out TextureData, 300))</code> is false then add to the else of that statement.</p>\n\n<p>if you really want to test it at the last second you could do it like this</p>\n\n<pre><code> SharpDX.Windows.RenderLoop.Run(form, () =&gt;\n {\n if (Queue.TryTake(out TextureData, 300))\n {\n Stoptimer = new Stopwatch();\n Stoptimer.Start();\n\n device.BeginScene();\n sprite.Begin(SpriteFlags.None);\n try\n {\n using (var surface = texture.GetSurfaceLevel(0))\n {\n if (!CTS.IsCancellationRequested)\n { \n Surface.FromFileInMemory(surface, TextureData, SharpDX.Direct3D9.Filter.None, 0);\n }\n Else\n {\n\n // I imagine if you close the form that you want this stuff to \n //happen as well\n sprite.End();\n device.EndScene();\n device.Present();\n Stoptimer.Stop();\n Console.WriteLine(Stoptimer.ElapsedTicks);\n form.Dispose();\n }\n }\n sprite.Draw(texture, new ColorBGRA(0xffffffff));\n }\n\n catch (Exception ex)\n {\n MessageBox.Show(ex.Message, \"Rendering: Texture\");\n }\n\n sprite.End();\n device.EndScene();\n device.Present();\n Stoptimer.Stop();\n Console.WriteLine(Stoptimer.ElapsedTicks);\n }\n //Optional for Disposing of the form if Queue.TryTake(out TextureData, 300))\n // is false\n Else\n {\n form.Dispose();\n }\n });\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T23:40:14.237", "Id": "48105", "Score": "1", "body": "Ah good means to use the Else statement, helped me out, thanks:)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T13:20:51.050", "Id": "48161", "Score": "0", "body": "your welcome, looks like you are writing a lot of code from all the posts, glad that I can help" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T18:35:27.903", "Id": "30272", "ParentId": "30266", "Score": "1" } } ]
{ "AcceptedAnswerId": "30272", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T16:17:42.297", "Id": "30266", "Score": "2", "Tags": [ "c#", "multithreading" ], "Title": "Better way to use a Condition (CancellationToken)" }
30266
<p>I wondered if there was any better way of doing so.</p> <p>I had a hard time figuring it out (it seemed nobody else already tried to do so).</p> <pre><code>import re import string class BetterFormat(string.Formatter): """ Introduce better formatting """ def parse(self, format_string): """ Receive the string to be transformed and split its elements to facilitate the actual replacing """ # Automatically counts how many tabs are before the {} then automatically adds the new rule (defined in format_field) return [(before, identifiant, str(len(re.search('\t*$', before).group(0))) + '\t' + (param if param is not None else ''), modif) for before, identifiant, param, modif in super().parse(format_string)] def format_field(self, v, pattern): """ Receive the string to be transformed and the pattern according which it is supposed to be modified """ # Hacky way to remove a dynamic sequence of characters ([0-9]+\t) and returning it sharedData = {'numberOfTabs': 0} def extractTabs(pattern): sharedData['numberOfTabs'] = int(pattern.group(0)[:-1]) # Save the data that will be erased return "" # This will erase it pattern = re.sub('[0-9]+\t', extractTabs, pattern) if sharedData['numberOfTabs']: # If there are tabs to be added v = (sharedData['numberOfTabs'] * '\t').join(v.splitlines(True)) return super().format_field(v, pattern) css = """ /* Some multi-lines CSS All automatically indented */ """ print(BetterFormat.format(""" &lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; {css} &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- Whatever --&gt; &lt;/body&gt; &lt;/html&gt;""", css=css )) # Output &lt;html&gt; &lt;head&gt; &lt;style type="text/css"&gt; /* Some multi-line CSS All automatically indented */ &lt;/style&gt; &lt;/head&gt; &lt;body&gt; &lt;!-- Whatever --&gt; &lt;/body&gt; &lt;/html&gt; </code></pre> <p>Otherwise, previously I had to do this:</p> <pre><code># […] print(""" […] {css} […]""".format(css='\t\t\t'.join(css.splitlines(True))) ) </code></pre> <p>And just so you better understand, I first only implemented BetterFormat.format_field, then I was able to do that, but I was still required to count the number of tabulations myself:</p> <pre><code># […] print(""" […] {css:3\t} […]""".format(css=css) ) </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T20:26:35.183", "Id": "48093", "Score": "0", "body": "`parse()` is doing too much to be one-lined. List comprehension can be very useful, but not when it causes the line to be over 200 characters. This would be more legible if the line was broken down into smaller parts. Making the tuple creation a different method would be an easy piece to extract." } ]
[ { "body": "<p>Could <a href=\"http://docs.python.org/3.3/library/textwrap.html\" rel=\"nofollow\">textwrap</a> do some of the job?</p>\n\n<p>Particularly the dedent and indent function? You will still need to count the number of tabs you want, but the rest will be done. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T01:45:43.557", "Id": "30284", "ParentId": "30273", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T19:43:48.033", "Id": "30273", "Score": "2", "Tags": [ "python", "strings", "python-3.x" ], "Title": "Automatically indent a whole block of text into str.format" }
30273
<p>I currently have a solution to increment numbers within a range:</p> <pre><code>i % x + 1 </code></pre> <p><em>Where <code>x</code> is the maximum number in the range and <code>i</code> is the previous number.</em></p> <p>It is nice and simple, and gives this array: <code>1,2,3,4,1,2...</code></p> <p>I also need to do this in reverse, which should produce this array: <code>1,4,3,2,1,4,3...</code></p> <p>This is my solution:</p> <pre><code>i == 1 ? x : (i - 1 % x) </code></pre> <p>Is there a way to do it without the ternary operator?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T23:06:48.977", "Id": "48102", "Score": "0", "body": "could you give some more of the code that you use? I want to recreate and see if I can do it, I have an idea but I want to test it first" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T23:27:28.247", "Id": "48103", "Score": "1", "body": "`1,4,3,2,1,4,1`? Shouldn't it be `1,4,3,2,1,4,3`?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T01:38:07.707", "Id": "48109", "Score": "0", "body": "If you do this so often that you want to shorten it, maybe it's time for a couple of helper methods?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T06:16:24.550", "Id": "48124", "Score": "0", "body": "@svick its in a helper method - I was sure there was a pure math solution but I couldn't work it out" } ]
[ { "body": "<p>Some thoughts:</p>\n\n<pre><code>(i + x) % x == i //For i &gt;= 0 &amp;&amp; i &lt; x\n</code></pre>\n\n<p>Then</p>\n\n<pre><code>(i + x - 1) % x\n</code></pre>\n\n<p>Gives us the range from 0 to x-1.\nWe want the range from 1 to x so we change this to:</p>\n\n<pre><code>(i + x - 2) % x + 1;\n</code></pre>\n\n<p>But I don't think it's particularly readable, so your ternary code might end up being better.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T08:00:45.297", "Id": "48127", "Score": "0", "body": "Ternary is also a lot faster judging by this simple JSPerf (I'm doing it in both C# and JS) - http://jsperf.com/modulus-vs-ternary" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T17:38:50.830", "Id": "48194", "Score": "0", "body": "@Jamie: If your concern is performance, you could substract from i (and from the conditional) when it's initialized (and use decrement instead of precrement). However, even on my machine the slower version is performing over 7 million operations per second. I doubt this is going to be your bottleneck." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T17:40:16.283", "Id": "48195", "Score": "0", "body": "Very true! My main concern is not performance for something as simple as this - but seeing as ternary has both greater readability and speed it seems sensible to opt for that!" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T23:34:05.713", "Id": "30280", "ParentId": "30278", "Score": "2" } } ]
{ "AcceptedAnswerId": "30280", "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-26T22:33:07.867", "Id": "30278", "Score": "1", "Tags": [ "c#", "mathematics" ], "Title": "Simple way to decrement number within a repeating range" }
30278
<p>So I have this code that i use for addition of funds to a certain item. </p> <pre><code>def addFund fund=params[:fund] if(fund.to_i&gt;0) @fund=fund if(@item.fund+fund.to_f&gt;@item.price) #the fund added should be less than price-current fudn respond_to do |format| format.html { redirect_to @item, error: 'Fund amount should not exceed price difference' } format.json {render :json =&gt;{:status =&gt;0, :error=&gt;"Fund amount cannot be greater than price difference "}} end else #Finally do the addition @item.fund=@item.fund+fund.to_f @item.save respond_to do |format| format.html { redirect_to @item, success: 'Fund added' } format.json {render :json =&gt;{:status =&gt;1, :error=&gt;"Done"}} end end else respond_to do |format| format.html { redirect_to @item, error: 'No money specified.' } format.json {render :json =&gt;{:status =&gt;0, :error=&gt;"Money not specified"}} end end end </code></pre> <p>So this is how it works:</p> <p>First we check if the fund(POST ParameteR) is non zero <code>fund.to_i&gt;0</code> and respond accordingly giving an error message if it isn't</p> <p>@item.fund = the current funding the item has</p> <p>@item.price = the price of item</p> <p>fund = the fund to be added(POST)</p> <p>fund must be less than @item.price-@item.fund since there is no point in accepting funds greater than the price, the item can already be bought</p> <p>Then finally if all this works, then we add the funds to the item and show him a message. </p> <p>So that's pretty much it. I am thinking there has to be a way of clubbing the responses and replying at one time. I have no idea how respond_to actually works. Ruby has blocks that you won't find in java or C++ or PHP</p>
[]
[ { "body": "<p>A lot of these logic could be moved to model. Rails provides lot of helpers for validation in your model. </p>\n\n<pre><code>class Item\n validate :fund_vs_price, :fund_greater_than_zero\n\n\n def fund_vs_price\n errors.add(:fund, \"Fund amount should not exceed price difference\") if fund &gt; price\n end\n\n def fund_greater_than_zero\n errors.add(:fund, \"No money specified.\")\n end\n\n #overriding setter to do a sum every time it is assigned a value\n def fund=(value)\n write_attribute(:fund, fund.to_f + value)\n end\nend\n</code></pre>\n\n<p>With that, the controller becomes really simple.</p>\n\n<pre><code>def addFund\n @item.fund = prams[:fund]\n if @item.save\n respond_to do |format|\n\n format.html { redirect_to @item, success: 'Fund added' }\n format.json {render :json =&gt;{:status =&gt;1,\n :error=&gt;\"Done\"}}\n end\n else\n respond_to do |format|\n\n format.html { redirect_to @item, error: @item.errors[:fund].join(\"\\n\") }\n format.json {render :json =&gt;{:status =&gt;0,\n :error=&gt; @item.errors[:fund].join(\"\\n\")}}\n end\n end\n end\n</code></pre>\n\n<p>If your model becomes too big to maintain, you can always use ActiveSupport <a href=\"http://api.rubyonrails.org/classes/ActiveSupport/Concern.html\" rel=\"nofollow\">concerns</a> to separate it out into different modules. For eg, you could move everything related to validation into a separate module.</p>\n\n<p>There might be some logical errors in the above code since its not tested. But it will give you an idea</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T14:55:11.693", "Id": "31057", "ParentId": "30287", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T05:21:55.513", "Id": "30287", "Score": "0", "Tags": [ "ruby", "ruby-on-rails" ], "Title": "Ruby on rails action code could be shorter" }
30287
<p>I am developing an Android app. Due to my low experience and the requirement for network operation, my class uses a lot of <code>AsyncTask</code> instances and it grew quite large. I'd like to know how I can split this in to different classes, and generally make it better (not required).</p> <p>I am really confused in cases where I have to deal with UI elemnts.</p> <p>I wish to see some small code snippets which will demonstrate good practice. I am not asking for a full and really detailed answer, as it probably will be very long, but it would be really nice.</p> <p>(Should I add some comments?)</p> <pre><code>import java.io.BufferedOutputStream; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import org.apache.http.annotation.ThreadSafe; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import ua.mirkvartir.android.frontend.adapter.GPSTracker; import ua.mirkvartir.android.frontend.adapter.JSONParser; import ua.mirkvartir.android.frontend.adapter.UserFunctions; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.Bitmap.CompressFormat; import android.graphics.BitmapFactory; import android.net.Uri; import android.os.AsyncTask; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v4.content.CursorLoader; import android.util.Log; import android.view.View; import android.view.View.OnClickListener; import android.widget.AdapterView; import android.widget.AdapterView.OnItemSelectedListener; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.CheckBox; import android.widget.EditText; import android.widget.ImageView; import android.widget.RelativeLayout; import android.widget.Spinner; public class AddFillActivityApp extends ErrorActivity { Uri mCapturedImageURI; int gSelected; List&lt;String&gt; photos; int sourse = 3; String user_id; int dSelected; // File f; String filePath; int stSelected; int sSelected; int rSelected; EditText street; EditText price; Spinner spinPriceType; EditText flat; EditText sqTotal; EditText sqLiving; EditText sqKitchen; EditText floor; EditText floors; EditText text; EditText phone1; EditText phone2; Spinner spinBuildType; Button btnSend; Context context; String not_sourse = ""; String not_user = ""; String not_district = ""; String not_settle = ""; String not_section = ""; String not_street = ""; String not_price = ""; String not_priceFor = ""; String not_flat = ""; String not_sqTotal = ""; String not_sqLiving = ""; String not_sqKitchen = ""; String not_floor = ""; String not_floors = ""; String not_text = ""; String not_phone1 = ""; String not_phone2 = ""; String not_build_type = ""; String photo1 = ""; String photo2 = ""; String photo3 = ""; ImageView pho1; ImageView pho2; ImageView pho3; CheckBox checkbox; List&lt;Integer&gt; priceID = new ArrayList&lt;Integer&gt;(); List&lt;Integer&gt; buildTypeID = new ArrayList&lt;Integer&gt;(); List&lt;String&gt; priceField = new ArrayList&lt;String&gt;(); List&lt;String&gt; buildTypeField = new ArrayList&lt;String&gt;(); Activity app; ArrayAdapter&lt;String&gt; adapterBuild; ArrayAdapter&lt;String&gt; adapterPrice; String not_coord = ""; Uri link1 = null; Uri link2 = null; Uri link3 = null; @Override protected void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); if (savedInstanceState.containsKey("link1")) { link1 = Uri.parse(savedInstanceState.getString("link1")); } if (savedInstanceState.containsKey("link2")) { link2 = Uri.parse(savedInstanceState.getString("link2")); } if (savedInstanceState.containsKey("link3")) { link3 = Uri.parse(savedInstanceState.getString("link3")); } } @Override protected void onResume() { super.onResume(); Log.d("links", link1 + "\n" + link2 + "\n" + link3); if (link1 != null &amp;&amp; !link1.equals("")) { saveFile( decodeSampledBitmapFromResource(getRealPathFromURI(link1), 800, 800), 1); pho1.setImageBitmap(decodeSampledBitmapFromResource( getRealPathFromURI(link1), 80, 60)); } if (link2 != null &amp;&amp; !link2.equals("")) { saveFile( decodeSampledBitmapFromResource(getRealPathFromURI(link2), 800, 800), 2); pho2.setImageBitmap(decodeSampledBitmapFromResource( getRealPathFromURI(link2), 80, 60)); } if (link3 != null &amp;&amp; !link3.equals("")) { saveFile( decodeSampledBitmapFromResource(getRealPathFromURI(link3), 800, 800), 3); pho3.setImageBitmap(decodeSampledBitmapFromResource( getRealPathFromURI(link3), 80, 60)); } } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); app = this; context = this; pds.setTitle("Загружаются фото..."); setContentView(R.layout.aadd_advappartment); pho1 = (ImageView) findViewById(R.id.imagePhoto1); pho2 = (ImageView) findViewById(R.id.imagePhoto2); pho3 = (ImageView) findViewById(R.id.imagePhoto3); Button f1 = (Button) findViewById(R.id.btnPhoto1); Button f2 = (Button) findViewById(R.id.btnPhoto2); Button f3 = (Button) findViewById(R.id.btnPhoto3); ImageView back_button = (ImageView) findViewById(R.id.imageView3); checkbox = (CheckBox) findViewById(R.id.checkBox1); f1.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { addPhoto1(); } }); f2.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { addPhoto2(); } }); f3.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { addPhoto3(); } }); back_button.setOnClickListener(new OnClickListener() { public void onClick(View arg0) { delDir(); finish(); } }); Bundle ex = getIntent().getExtras(); if (ex != null) { btnSend = (Button) findViewById(R.id.btnSendAdd); gSelected = ex.getInt("Group"); sSelected = ex.getInt("Section"); dSelected = ex.getInt("District"); stSelected = ex.getInt("Settle"); rSelected = ex.getInt("Region"); user_id = ex.getString("user_id"); RelativeLayout lp = (RelativeLayout) findViewById(R.id.layoutPark); RelativeLayout la = (RelativeLayout) findViewById(R.id.layoutApp); not_sourse = "" + 3; not_user = "" + user_id; not_district = "" + dSelected; not_settle = "" + stSelected; not_section = "" + sSelected; if (gSelected == 9) { lp.setVisibility(View.VISIBLE); la.setVisibility(View.GONE); spinPriceType = (Spinner) findViewById(R.id.sppricetipe); street = (EditText) findViewById(R.id.etpAdress); FillData dat = new FillData(); dat.execute(1, gSelected, sSelected); } else { la.setVisibility(View.VISIBLE); lp.setVisibility(View.GONE); spinPriceType = (Spinner) findViewById(R.id.saPricetipe); spinBuildType = (Spinner) findViewById(R.id.saBuildType); FillData dat = new FillData(); dat.execute(1, gSelected, sSelected); adapterBuild = new ArrayAdapter&lt;String&gt;(app, android.R.layout.simple_spinner_item, buildTypeField); adapterBuild .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinBuildType.setAdapter(adapterBuild); dat = new FillData(); dat.execute(0); } adapterPrice = new ArrayAdapter&lt;String&gt;(this, android.R.layout.simple_spinner_item, priceField); adapterPrice .setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); spinPriceType.setAdapter(adapterPrice); // Listening to Login Screen link btnSend.setOnClickListener(new View.OnClickListener() { public void onClick(View view) { if (gSelected == 9) { price = (EditText) findViewById(R.id.etpPrice); flat = (EditText) findViewById(R.id.etpCarSpace); text = (EditText) findViewById(R.id.etpDescription); not_street = street.getText().toString(); not_price = price.getText().toString(); not_flat = flat.getText().toString(); not_sqTotal = ""; not_sqLiving = ""; not_sqKitchen = ""; not_floor = ""; not_floors = ""; not_text = ""; not_phone1 = ""; not_phone2 = ""; not_build_type = "0"; } else { street = (EditText) findViewById(R.id.etaAdress); price = (EditText) findViewById(R.id.etaPrice); flat = (EditText) findViewById(R.id.etaCarSpace); sqTotal = (EditText) findViewById(R.id.etaArea1); sqLiving = (EditText) findViewById(R.id.etaArea2); sqKitchen = (EditText) findViewById(R.id.etaArea3); floor = (EditText) findViewById(R.id.etaFlor); floors = (EditText) findViewById(R.id.etaHight); text = (EditText) findViewById(R.id.etaDescription); not_street = street.getText().toString(); not_price = price.getText().toString(); not_flat = flat.getText().toString(); not_sqTotal = sqTotal.getText().toString(); not_sqLiving = sqLiving.getText().toString(); not_sqKitchen = sqKitchen.getText().toString(); not_floor = floor.getText().toString(); not_floors = floors.getText().toString(); not_text = text.getText().toString(); not_phone1 = "0"; not_phone2 = "0"; } Upload upload = new Upload(); upload.execute(); } }); spinPriceType .setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView&lt;?&gt; parent, View view, int position, long id) { if (position &gt; -1 &amp;&amp; priceID != null) { not_priceFor = priceID.get(position).toString(); } } @Override public void onNothingSelected(AdapterView&lt;?&gt; arg0) { // TODO Auto-generated method stub } }); if (gSelected != 9) { spinBuildType .setOnItemSelectedListener(new OnItemSelectedListener() { @Override public void onItemSelected(AdapterView&lt;?&gt; parent, View view, int position, long id) { if (position &gt; -1 &amp;&amp; buildTypeID != null) { not_build_type = buildTypeID.get(position) .toString(); } } @Override public void onNothingSelected(AdapterView&lt;?&gt; arg0) { // TODO Auto-generated method stub } }); } } } class FillData extends AsyncTask&lt;Integer, Void, JSONArray&gt; { private int op = 0; @Override protected void onPreExecute() { pd.show(); } @Override protected JSONArray doInBackground(Integer... option) { JSONArray json = null; UserFunctions u = new UserFunctions(); op = option[0]; if (option[0] == 0) { json = u.getBt(); } else if (option[0] == 1) { String not_group = option[1].toString(); String not_section = option[2].toString(); json = u.getPriceType(not_group, not_section); } // send add return json; } @Override protected void onPostExecute(JSONArray result) { super.onPostExecute(result); pd.dismiss(); if (result == null) { onCreateDialog(LOST_CONNECTION).show(); } else if (op == 0) { if (result != null) { for (int i = 0; i &lt; result.length(); i++) { String a = "0"; String b = "0"; try { a = ((JSONObject) result.get(i)).getString("bt_id"); b = ((JSONObject) result.get(i)) .getString("bt_name"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } buildTypeID.add(Integer.parseInt(a)); buildTypeField.add(b); } runOnUiThread(new Runnable() { public void run() { adapterBuild.notifyDataSetChanged(); } }); } } else if (op == 1) { if (result != null) { for (int i = 0; i &lt; result.length(); i++) { String a = "0"; String b = "0"; try { a = ((JSONObject) result.get(i)) .getString("pricefor_id"); b = ((JSONObject) result.get(i)) .getString("pricefor_title"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } priceID.add(Integer.parseInt(a)); priceField.add(b); } runOnUiThread(new Runnable() { public void run() { adapterPrice.notifyDataSetChanged(); } }); } } } } class Upload extends AsyncTask&lt;String, Void, JSONObject&gt; { @Override protected void onPreExecute() { pds.show(); } @Override protected JSONObject doInBackground(String... params) { JSONObject json1 = null; JSONParser u = new JSONParser(); photos = new ArrayList&lt;String&gt;(); photos.add(photo1); photos.add(photo2); photos.add(photo3); List&lt;File&gt; f = new ArrayList&lt;File&gt;(); for (String p : photos) { Log.d("FilePath", p); if (!p.equals("") &amp;&amp; !p.equals("empty")) { f.add(new File(p)); } } if (f.size() &gt; 0) { json1 = u.getJSONFromUrl(f); } else { return null; } photos.clear(); return json1; } @Override protected void onPostExecute(JSONObject result) { JSONArray urls = null; SendData s; if (result != null &amp;&amp; result.has("url")) { try { urls = result.getJSONArray("url"); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } photos.clear(); if (urls != null) { for (int i = 0; i &lt; urls.length(); i++) { try { photos.add(urls.getJSONObject(i).getString( "photo_id")); } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } s = new SendData(); s.execute(not_sourse, not_user, not_district, not_settle, not_section, not_street, not_price, not_priceFor, not_flat, not_sqTotal, not_sqLiving, not_sqKitchen, not_floor, not_floors, not_text, not_phone1, not_phone2, not_build_type, "" + rSelected); } } class SendData extends AsyncTask&lt;String, Void, JSONObject&gt; { @Override protected void onPreExecute() { pd.setTitle("Создаю Объявление..."); if (checkbox.isChecked()) { runOnUiThread(new Runnable() { public void run() { GPSTracker mGPS = new GPSTracker(context); if (mGPS.canGetLocation) { double mLat = mGPS.getLatitude(); double mLong = mGPS.getLongitude(); not_coord = "" + mLong + "," + mLat; } else { // can't get the location } } }); } } @Override protected JSONObject doInBackground(String... option) { JSONObject json = null; UserFunctions u = new UserFunctions(); // publishProgress(values); String not_sourse = option[0]; String not_user = option[1]; String not_district = option[2]; String not_settle = option[3]; String not_section = option[4]; String not_street = option[5]; String not_price = option[6]; String not_priceFor = option[7]; String not_flat = option[8]; String not_sqTotal = option[9]; String not_sqLiving = option[10]; String not_sqKitchen = option[11]; String not_floor = option[12]; String not_floors = option[13]; String not_text = option[14]; String not_phone1 = option[15]; String not_phone2 = option[16]; String not_build_type = option[17]; String not_region = option[18]; json = u.sendAdd(not_sourse, not_user, not_district, not_settle, not_section, not_street, not_price, not_priceFor, not_flat, not_sqTotal, not_sqLiving, not_sqKitchen, not_floor, not_floors, not_text, not_phone1, not_phone2, not_build_type, not_region, photos, not_coord); return json; } @Override protected void onPostExecute(JSONObject result) { super.onPostExecute(result); Log.e("result", "going to result"); String not_id = "0"; pds.dismiss(); if (result == null) { Log.e("result", "null"); onCreateDialog(LOST_CONNECTION).show(); } else { Log.e("result", "not null:" + result.toString()); try { if (result != null) { not_id = result.getString("notice_id"); Intent i = new Intent(getApplicationContext(), AddToCheckActivity.class); i.putExtra("add_id", not_id); startActivity(i); link1 = null; link2 = null; link3 = null; delDir(); finish(); } } catch (JSONException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } public void addPhoto1() { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage("Выберите первое фото") .setCancelable(false) .setPositiveButton("С диска", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // do things Intent intent = new Intent(); intent.setType("image/*"); link1 = null; intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser( intent, "Select Picture"), 11); if (filePath != null) { } } }) .setNegativeButton("Сфотографировать", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // do things Calendar c = Calendar.getInstance(); ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, "zdanie " + c.getTime()); link1 = null; link1 = getContentResolver() .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); Intent intentPicture = new Intent( MediaStore.ACTION_IMAGE_CAPTURE); intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, link1); startActivityForResult(intentPicture, 12); } }); builder.create().show(); } public void addPhoto2() { AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setMessage("Выберите второе фото") .setCancelable(false) .setPositiveButton("С диска", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // do things Intent intent = new Intent(); intent.setType("image/*"); link2 = null; intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(Intent.createChooser( intent, "Select Picture"), 21); if (filePath != null) { Log.d("Execution", "CCCCMON"); } } }) .setNegativeButton("Сфотографировать", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // do things Calendar c = Calendar.getInstance(); ContentValues values = new ContentValues(); values.put(MediaStore.Images.Media.TITLE, "zdanie " + c.getTime()); link2 = null; link2 = getContentResolver() .insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); Intent intentPicture = new Intent( MediaStore.ACTION_IMAGE_CAPTURE); intentPicture.putExtra(MediaStore.EXTRA_OUTPUT, link2); startActivityForResult(intentPicture, 22); } }); builder.create().show(); } @Override protected void onSaveInstanceState(Bundle outState) { super.onSaveInstanceState(outState); if (link1 != null) { outState.putString("link1", link1.toString()); } if (link2 != null) { outState.putString("link2", link2.toString()); } if (link3 != null) { outState.putString("link3", link3.toString()); } } protected void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); String a = ""; if (data == null) { a = "null"; } else a = data.toString(); Log.d("RealPAth", "resultCode " + resultCode + " data " + a); if (requestCode == 12 &amp;&amp; resultCode == RESULT_OK) { } if (requestCode == 11 &amp;&amp; resultCode == RESULT_OK &amp;&amp; null != data) { link1 = data.getData(); String picturePath = getRealPathFromURI(link1); pho1.setImageBitmap(decodeSampledBitmapFromResource(picturePath, 80, 60)); saveFile(decodeSampledBitmapFromResource(picturePath, 800, 800), 1); } if (requestCode == 22 &amp;&amp; resultCode == RESULT_OK) { } if (requestCode == 21 &amp;&amp; resultCode == RESULT_OK &amp;&amp; null != data) { link2 = data.getData(); String picturePath = getRealPathFromURI(link2); pho2.setImageBitmap(decodeSampledBitmapFromResource(picturePath, 80, 60)); saveFile(decodeSampledBitmapFromResource(picturePath, 800, 800), 2); } if (requestCode == 32 &amp;&amp; resultCode == RESULT_OK) { } if (requestCode == 31 &amp;&amp; resultCode == RESULT_OK &amp;&amp; null != data) { link3 = data.getData(); String picturePath = getRealPathFromURI(link3); pho3.setImageBitmap(decodeSampledBitmapFromResource(picturePath, 80, 60)); saveFile(decodeSampledBitmapFromResource(picturePath, 800, 800), 3); } } public String saveFile(Bitmap bm, int id) { if (bm == null) { Log.d("bitmap", "null"); return ""; } else { String file_path = getExternalCacheDir () + "/Mk"; File dir = new File(file_path); if (!dir.exists()) { dir.mkdirs(); } File file = new File(dir, "smaller" + id +bm.getHeight()+ ".jpeg"); FileOutputStream fOut; try { fOut = new FileOutputStream(file); // bm.compress(Bitmap.CompressFormat.PNG, 85, fOut); BufferedOutputStream bos = new BufferedOutputStream(fOut); bm.compress(CompressFormat.JPEG, 85, bos); if (bos != null) { bos.flush(); bos.close(); } if (fOut != null) { fOut.flush(); fOut.close(); } if (id == 1) { photo1 = file.getPath(); } else if (id == 2) { photo2 = file.getPath(); } else if (id == 3) { photo3 = file.getPath(); } } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } return ""; } } public void photo1Clear(View v) { photo1 = ""; link1 = null; pho1.setImageResource(R.drawable.home); } public void photo2Clear(View v) { photo2 = ""; link2 = null; pho2.setImageResource(R.drawable.home); } public void photo3Clear(View v) { photo3 = ""; link3 = null; pho3.setImageResource(R.drawable.home); } public String getRealPathFromURI(Uri contentUri) { if (contentUri == null) { Log.e("RealPath", "URI: null"); } else Log.e("RealPath", "URI: " + contentUri.toString()); try { String[] proj = { MediaStore.Images.Media.DATA }; CursorLoader loader = new CursorLoader(app, contentUri, proj, null, null, null); Cursor cursor = loader.loadInBackground(); int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } catch (Exception e) { Log.e("RealPath", "exeption" + " " + e.toString()); e.printStackTrace(); } return ""; } public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height &gt; reqHeight || width &gt; reqWidth) { // Calculate ratios of height and width to requested height and // width final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // Choose the smallest ratio as inSampleSize value, this will // guarantee // a final image with both dimensions larger than or equal to the // requested height and width. inSampleSize = heightRatio &lt; widthRatio ? heightRatio : widthRatio; Log.d("bitmap", "original options: height/reqheite " + height+"///"+reqHeight + " widnth/reqwidth " + width +"///"+reqWidth + " inSampleSize " + inSampleSize); } return inSampleSize; } public static Bitmap decodeSampledBitmapFromResource(String path, int reqWidth, int reqHeight) { Log.e("PATH", path); // First decode with inJustDecodeBounds=true to check dimensions final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; Bitmap b = null; b = BitmapFactory.decodeFile(path, options); // Calculate inSampleSizeа options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight); // Decode bitmap with inSampleSize set options.inJustDecodeBounds = false; try { b = BitmapFactory.decodeFile(path, options); Log.d("bitmap", "decoded sucsessfully"); } catch (Exception e) { e.printStackTrace(); Log.d("bitmap", "decoding failed; options: " + options.toString()); } return b; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T10:04:20.750", "Id": "48138", "Score": "4", "body": "Show us the important parts you want reviewed, do not simply copy-paste the entire class. You think someone would want to read 900 lines of your code? :) I seriously doubt it." } ]
[ { "body": "<p>A few tips, but there may be more. These are just the things that immediately jumped out at me:</p>\n\n<hr>\n\n<blockquote>\n <p>Break out AsyncTasks into their own class</p>\n</blockquote>\n\n<p>With multiple tasks, it might be better to make them each their own class/file. You can call back to the main Activity with listeners. If you <em>must</em> keep them in place, at least group them together at the end of the file. There's no reason to have them right in the middle of another class, with methods on both sides.</p>\n\n<hr>\n\n<blockquote>\n <p>Combine the button listeners</p>\n</blockquote>\n\n<p>Instead of making several anonymous listeners, you can let the Activity implement the listener and have all the corresponding code in one neat method. There, you switch on button id to call individual methods to handle each. This is a personal style issue, but I think it makes it <em>much</em> more readable to have one <code>onClick()</code> function.</p>\n\n<hr>\n\n<blockquote>\n <p>Combine the <code>addPhoto()</code> methods</p>\n</blockquote>\n\n<p>The only difference I see between <code>addPhoto1()</code> and <code>addPhoto2()</code> is the request code. Combine them into one <code>addPhoto(int reqCode)</code> method. If you add more later, it will be <em>much</em> easier than copy/pasting a whole new method called <code>addPhoto7()</code>, etc.</p>\n\n<hr>\n\n<blockquote>\n <p>Learn to use <code>switch</code> more, or refactor those <code>if</code> blocks</p>\n</blockquote>\n\n<p>Big <code>if/else</code> blocks are ugly, and can sometimes be rewritten with a single <code>switch</code>. Sometimes, you need a bit more. For instance, in your <code>onActivityResult()</code> method, you can easily check <code>resultCode</code> just once, with a switch inside that. Same with the <code>data == null</code> checks.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-23T20:26:59.393", "Id": "31708", "ParentId": "30289", "Score": "12" } } ]
{ "AcceptedAnswerId": "31708", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T08:00:09.487", "Id": "30289", "Score": "4", "Tags": [ "java", "android" ], "Title": "Refactoring long class to make it more maintainable" }
30289
<p>I want to insert and edit values on the same button click. The code is working fine and I am using the same code for both insertion and deletion.</p> <pre><code>function saveToDB(){ var value= pageValidation(); if($('#jobid').val()==" "){ if(value!=false){ var data = { "names": $('#names').val(), "os": $('#OS').val(), "browser": $('#browsers').val(), "version": $('#version').val(), "scripttype": $('#testscripts').val(), "server": $('#server').val() }; $.ajax({ type: 'post', url: "/insertJobs", dataType: "json", data: data, success: function (response) { console.log("job insertion success"); console.log(response); displayjobs(); } }); } } else{ if(value!=false){ var data = { "jobid": $('#jobid').val(), "names": $('#names').val(), "os": $('#OS').val(), "browser": $('#browsers').val(), "version": $('#version').val(), "scripttype": $('#testscripts').val(), "server": $('#server').val() }; $.ajax({ type: 'post', url: "/editJobs", dataType: "json", data: data, success: function (response) { console.log("job Updated succesfully!!"); console.log(response); displayjobs(); } }); } } } </code></pre> <p>Are there any possible ways to remove duplication and compress this code?</p>
[]
[ { "body": "<p>The only difference between the two code blocks is the service endpoint and the inclusion of the ID, so you could shorten it to:</p>\n\n<pre><code>function saveToDB(){\n var jobId = $('#jobid').val(); \n var valid = pageValidation();\n var url = jobId === \" \" ? \"/insertJobs\" : \"/editJobs\" ;\n\n if(valid){\n var data = {\n \"jobid\": jobId.trim(), \n \"names\": $('#names').val(),\n \"os\": $('#OS').val(),\n \"browser\": $('#browsers').val(),\n \"version\": $('#version').val(),\n \"scripttype\": $('#testscripts').val(),\n \"server\": $('#server').val()\n };\n $.ajax({\n type: 'post',\n url: url,\n dataType: \"json\",\n data: data,\n success: function (response) {\n console.log(\"Change this message\");\n console.log(response);\n displayjobs();\n }\n });\n }\n}\n</code></pre>\n\n<p>That code assumes that the code running at <code>/insertJobs</code> will ignore the empty <code>jobid</code> value. If it won't, update the code so as not to send it.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T09:28:11.483", "Id": "30292", "ParentId": "30291", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T09:02:54.680", "Id": "30291", "Score": "0", "Tags": [ "javascript", "jquery", "beginner" ], "Title": "Saving to database" }
30291
<p>I have a function which gets called very often, for this test 30,720,000 times. It has to run in real-time, so performance is very important. Are there possible improvements?</p> <pre><code>// This function looks up in the vertice table wheter a vertice at that position already exists // - If yes, return the vertice index // - If no, create a new vertice and return the created vertice index // // @param cfg: Pointer to a chunkConfig struct // @param x: x position of the vertice // @param y: y position of the vertice inline VERTICE_INDEX GetOrCreateVertice(float x, float y, ChunkGenerator::chunkConfig *cfg) { int x_pos = int((x*POSARR_ADJ_F) + 0.5f); int y_pos = int((y*POSARR_ADJ_F) + 0.5f); int dict_index = x_pos + (y_pos * cfg-&gt;subdivisions_adj); VERTICE_INDEX dict_entry = cfg-&gt;vertice_pool.vertice_dict[dict_index]; VERTICE_INDEX current_index = cfg-&gt;vertice_pool.current_vertice_index; if (dict_entry &gt;= 0 &amp;&amp; dict_entry &lt; 65535 &amp;&amp; current_index &gt; 0) return dict_entry; LVecBase3f* offset = cfg-&gt;base_position; LVecBase2f* dim = cfg-&gt;dimensions; LVecBase2f* tex_offset = cfg-&gt;texture_offset; LVecBase2f* tex_scale = cfg-&gt;texture_scale; int pool_index = ((int)current_index) * 5; float base_scale = 1.0 / (cfg-&gt;subdivisions_f-1.0); float x_scaled = x * base_scale; float y_scaled = y * base_scale; cfg-&gt;vertice_pool.vertice_array[pool_index+0] = offset-&gt;get_x() + (x_scaled * dim-&gt;get_x()); cfg-&gt;vertice_pool.vertice_array[pool_index+1] = offset-&gt;get_y() + (y_scaled * dim-&gt;get_y()); cfg-&gt;vertice_pool.vertice_array[pool_index+2] = offset-&gt;get_z(); cfg-&gt;vertice_pool.vertice_array[pool_index+3] = tex_offset-&gt;get_x() + (x_scaled * tex_scale-&gt;get_x()); cfg-&gt;vertice_pool.vertice_array[pool_index+4] = tex_offset-&gt;get_y() + (y_scaled * tex_scale-&gt;get_y()); cfg-&gt;vertice_pool.vertice_dict[dict_index] = current_index; cfg-&gt;vertice_pool.current_vertice_index++; return current_index; } </code></pre> <p><code>LVecBase3f</code> and <code>LVecBase2f</code> are vector-types provided by the graphics-engine I use. <code>VERTICE_INDEX</code> is a <code>unsigned short</code>, <code>POSARR_ADJ</code> and <code>POSARR_ADJ_F</code> is constant <code>2</code>.</p> <p>This is the chunkConfig struct:</p> <pre><code>struct chunkConfig { int subdivisions; int subdivisions_adj; float subdivisions_f; LVecBase3f *base_position; LVecBase2f *dimensions; LVecBase2f *texture_offset; LVecBase2f *texture_scale; verticePool vertice_pool; }; struct verticePool { VERTICE_INDEX current_vertice_index; VERTICE_INDEX current_primitive_index; VERTICE_INDEX * vertice_dict; float *vertice_array; VERTICE_INDEX *primitive_array; }; </code></pre> <p>Performance result measured by very-sleepy: <a href="http://s22.postimg.org/wt24m9gzl/screenshot_130.png" rel="nofollow">link</a></p> <p>Version based on the suggestions made in the comments: <a href="http://s22.postimg.org/3lta19269/screenshot_135.png" rel="nofollow">very-sleepy</a>, <a href="http://s22.postimg.org/jp5r123pd/screenshot_136.png" rel="nofollow">AMD CodeAnalyst</a>, and the assembler for the slow-line: <a href="http://s22.postimg.org/6z1inyvr5/screenshot_137.png" rel="nofollow">generated assembler</a>, I also made some arrays global, and renamed "vertice" to "vertex".</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T10:42:04.367", "Id": "48145", "Score": "1", "body": "Why did you document parameters that don't exist?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T10:47:58.767", "Id": "48146", "Score": "0", "body": "What do those time figures mean? I seriously doubt the calculation of `dict_index` takes a whole second, assuming `subdivisions` and `POSARR_ADJ` are integers." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T10:50:13.597", "Id": "48147", "Score": "0", "body": "Oh, I missed to remove them :) I updated the question. The 1.00s for example means the three lines above took 1.00s, that's because very-sleepy samples the current execution pointer. The time-result always means the time of the lines up to the last time-result." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T10:53:24.173", "Id": "48148", "Score": "0", "body": "I have added more details :) Maybe that helps" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T11:01:20.023", "Id": "48149", "Score": "0", "body": "A maintainability rather than performance note: It might help if you used real words in your design. There is no such thing as a \"vertice\". The singular of \"vertices\" is \"vertex\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T11:05:54.000", "Id": "48150", "Score": "0", "body": "You're absolutely right, I always thought it would be \"vertice\" .. Thanks for the information :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T14:06:33.070", "Id": "48163", "Score": "0", "body": "I'm not sure I get the logic behind the code but `x * base_scale` and `y * base_scale` are used multiple times - might help to compute them only once. If `POSARR_ADJ` is constant, get rid of `cfg->subdivisions * POSARR_ADJ` too." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T14:23:56.413", "Id": "48166", "Score": "0", "body": "@bkdc I removed `x*base_scale` but I don't think I can remove `cfg->subdivisions * POSARR_ADJ` because I cast y to an int (`y_pos`) before." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T14:32:04.063", "Id": "48167", "Score": "0", "body": "@TobSpr `y` has nothing to do with `cfg->subdivisions * POSARR_ADJ` and you can leave `y` untouched. I don't know what `cfg` is but if you can change it, then it is pretty easy to define a `void set_subdivisions(whaever)` that will not only set the value for `subdivisions` but also precompute the value for `cfg->subdivisions_adj = cfg->subdivisions * POSARR_ADJ` - you can then use '`cfg->subdivisions_adj` in your function." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T14:35:41.333", "Id": "48168", "Score": "0", "body": "I have edited it, and also attached the cfg struct :) Is that what you mean?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:08:00.403", "Id": "48171", "Score": "0", "body": "@TobSpr yes. also...what's the point of `&& dict_entry < 65535`? While it won't help, performance wise, I'd go for `if (current_index > 0 && dict_entry >= 0)` - no point in doing anything if the pool is empty; `current_index` sounds a bit misleading too since it's more like a total/size/length but that's debatable." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:09:48.463", "Id": "48174", "Score": "0", "body": "I check that because a `65535` in the array means it is an invalid/uninitialized value. (I'm using memset to fill the array initial with `0xFFFF`). `current_index` is the current index in the array to write the next vertex to." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:30:53.170", "Id": "48178", "Score": "0", "body": "I also uploaded a new result based on the suggestions you made." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T10:57:58.917", "Id": "48245", "Score": "0", "body": "@TobSpr those timings are all over the place - time for a new profiler maybe? What compiler are you using? On what platform?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T11:05:54.263", "Id": "48246", "Score": "0", "body": "I'm using VS2008 on Windows 7. Are there profilers you could recommend? I was also able to increase the speed by 30% by enabling SSE2 (because of the int-casts)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T11:19:37.847", "Id": "48248", "Score": "0", "body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/10353/discussion-between-tobspr-and-bkdc)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-18T06:09:32.407", "Id": "171000", "Score": "0", "body": "Reupload images on some other hosting." } ]
[ { "body": "<p>It looks to me like your function is actually doing 2 things:</p>\n\n<ol>\n<li>It's checking to see if an entry exists in the dictionary, and if so return it</li>\n<li>If it doesn't exist, then it creates a new one</li>\n</ol>\n\n<p>So I would break it into 2 functions:</p>\n\n<pre><code>VERTICE_INDEX FindVerticeInDict(const float x, const float y, \n const ChunkGenerator::chunkConfig&amp; cfg, VERTICE_INDEX&amp; current_index);\nVERTICE_INDEX GetOrCreateVertice(const float x, const float y,\n ChunkGenerator::chunkConfig *cfg);\n</code></pre>\n\n<p>Note that I made <code>x</code> and <code>y</code> constants because they aren't changed by either function. Also, in the <code>Find</code> method, I made the <code>cfg</code> argument <code>const</code> because it's not being changed there either. It is modified in <code>GetOrCreate</code> though, so I left it as a pointer. (It could also be a non-const reference, if you prefer that style.)</p>\n\n<p>I would create a named constant for the \"entry not found\" value:</p>\n\n<pre><code>const VERTICE_INDEX ENTRY_NOT_FOUND = 0xFFFF;\n</code></pre>\n\n<p>So it would look something like this:</p>\n\n<pre><code>VERTICE_INDEX FindVerticeInDict(const float x, const float y, \n const ChunkGenerator::chunkConfig&amp; cfg, VERTICE_INDEX&amp; current_index) \n{\n int x_pos = int((x*POSARR_ADJ_F) + 0.5f);\n int y_pos = int((y*POSARR_ADJ_F) + 0.5f); \n\n int dict_index = x_pos + (y_pos * cfg.subdivisions_adj);\n\n VERTICE_INDEX dict_entry = cfg.vertice_pool.vertice_dict[dict_index];\n current_index = cfg.vertice_pool.current_vertice_index;\n\n if (dict_entry &gt;= 0 &amp;&amp; dict_entry &lt; ENTRY_NOT_FOUND &amp;&amp; current_index &gt; 0)\n return dict_entry;\n\n return ENTRY_NOT_FOUND;\n}\n</code></pre>\n\n<p>For your vertex array, you really should create a struct that contains the members you're going to use rather than looking them up in a 1D array of <code>float</code>s. It's error prone, hard-to-read, and hard-to-maintain the way you're doing it now. I'd create a struct like this:</p>\n\n<pre><code>typedef struct Vertex {\n Point3D vertex_coord; // This might be the same as LVecBase3f?\n Point2D texture_coord; // This might be the same as LVecBase2f?\n} Vertex;\n</code></pre>\n\n<p>Where <code>Point3D</code> is just:</p>\n\n<pre><code>typedef struct Point3D {\n float x;\n float y;\n float z;\n} Point3D;\n</code></pre>\n\n<p>and <code>Point2D</code> just has an <code>x</code> and <code>y</code> float values. Doing this will allow you to remove the magical <code>pool_index = ((int)current_index) * 5;</code>, and have names for the values you're writing.</p>\n\n<p>Also, you don't need to use the <code>inline</code> directive. The compiler can decide to ignore it, and it can decide to make something you didn't mark as inline inline. So there's not a lot of reason to use it.</p>\n\n<p>You can reduce the verbosity of your code, and possibly reduce the number of pointer dereferences the compiler produces by getting the address of the vertex you want and assigning all its members through that one pointer.</p>\n\n<p>Given the above, your function would now look like this:</p>\n\n<pre><code>VERTICE_INDEX GetOrCreateVertice(const float x, const float y, \n ChunkGenerator::chunkConfig *cfg) \n{\n VERTICE_INDEX current_index = 0;\n VERTICE_INDEX dict_entry = FindVerticeInDict(x, y, *cfg, current_index);\n if (dict_entry != ENTRY_NOT_FOUND)\n return dict_entry;\n\n LVecBase3f* offset = cfg-&gt;base_position;\n LVecBase2f* dim = cfg-&gt;dimensions;\n LVecBase2f* tex_offset = cfg-&gt;texture_offset;\n LVecBase2f* tex_scale = cfg-&gt;texture_scale;\n\n float base_scale = 1.0 / (cfg-&gt;subdivisions_f-1.0);\n float x_scaled = x * base_scale;\n float y_scaled = y * base_scale;\n\n Vertex* vertex = &amp;cfg-&gt;vertice_pool.vertice_arry [ current_index ];\n vertex-&gt;vertex_coord.x = offset-&gt;get_x() + (x_scaled * dim-&gt;get_x());\n vertex-&gt;vertex_coord.y = offset-&gt;get_y() + (y_scaled * dim-&gt;get_y());\n vertex-&gt;vertex_coord.z = offset-&gt;get_z();\n vertex-&gt;texture_coord.x = tex_offset-&gt;get_x() + (x_scaled * tex_scale-&gt;get_x());\n vertex-&gt;texture_coord.y = tex_offset-&gt;get_y() + (y_scaled * tex_scale-&gt;get_y());\n\n cfg-&gt;vertice_pool.vertice_dict[dict_index] = current_index;\n cfg-&gt;vertice_pool.current_vertice_index++;\n\n return current_index;\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-18T05:18:16.237", "Id": "93948", "ParentId": "30295", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "17", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T10:14:13.493", "Id": "30295", "Score": "3", "Tags": [ "c++", "performance", "coordinate-system" ], "Title": "Conditionally creating a new vertex" }
30295
<pre><code>class Youtube { private $url = null; private $id; public function __construct($url) { $this-&gt;url = $url; $this-&gt;parseUrl($url); } protected function parseUrl($url) { if (preg_match('%(?:youtube(?:-nocookie)?\.com/(?:[^/]+/.+/|(?:v|e(?:mbed)?)/|.*[?&amp;]v=)|youtu\.be/)([^"&amp;?/ ]{11})%i', $url, $match)) { $this-&gt;id = $match[1]; } else { throw new exception('Cannot find an ID!'); } } public function getVideo($width='560', $height='315') { $video = &lt;&lt;&lt;EOF &lt;iframe width="$width" height="$height" src="//www.youtube-nocookie.com/embed/$this-&gt;id" frameborder="0" allowfullscreen&gt;&lt;/iframe&gt; EOF; return $video; } } $sistar = new Youtube('http://www.youtube.com/watch?v=JtVhwsACgTw'); print $sistar-&gt;getVideo(); $twoneone = new Youtube('http://www.youtube.com/watch?v=LUrUPzLm5SI'); print $twoneone-&gt;getVideo(); </code></pre> <p>This is my first object-oriented script in PHP (I hope it's not too bad in general). I know I should do more validation and commenting within the code. Do you have any suggestions for improving the quality of the code?</p>
[]
[ { "body": "<p>I would probably put the $width and $height into the properties and not hard-coded into the method. That way you can change them as needed, instead of editing the class itself.</p>\n\n<pre><code>class Youtube {\n private $width = 123; // default value, if needed \n private $height = 456; // default value, if needed \n\n // Ctor and stuff...\n\n public function getVideo($width=null, $height=null) {\n // Code\n }\n}\n</code></pre>\n\n<p>Then you can change the dimensions on the fly:</p>\n\n<pre><code>$video = new Youtube($url);\n$video-&gt;getVideo(560, 315);\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T11:48:43.447", "Id": "30301", "ParentId": "30297", "Score": "0" } }, { "body": "<p>Personally I don't find this code usefull. I would rather go with a YoutubeVideo class and a YoutubeFactory that returns YoutubeVideo objects.</p>\n\n<p>The YoutubeVideo object then has some functions to access data from the YoutubeVideo (length,...) and present that Data. i.e. as an iframe. I would then call that method <code>toIframe($widh, $height);</code> or something along those lines</p>\n\n<p>The YoutubeFactory would parse the url and fill the youtubeVideo with all the information it needs.</p>\n\n<p>This way you have seperation of concern. YoutubeFActory handles all the business logic where as YoutubeVideo is simply a container to represent the video.</p>\n\n<p>Now you simply wrote class {} around a controller with some procedural functions.</p>\n\n<p>Using the code would look something like this:</p>\n\n<pre><code>$ytbF = new YoutubeFActory();\n\n$myVideo = $ytbF-&gt;createFromUrl('http://www.youtube.com/watch?v=JtVhwsACgTw');\n$mySecondVideo = $ytbF-&gt;createFromId('JtVhwsACgTw');\n</code></pre>\n\n<p>and then in your template you would present the video:</p>\n\n<pre><code>&lt;somehtml&gt;\n &lt;?php print $myVideo-&gt;toIframe(500,400); ?&gt;\n&lt;/somehtml&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T12:01:40.847", "Id": "30302", "ParentId": "30297", "Score": "1" } }, { "body": "<p>Pinoniq has the right idea, which can be taken a bit further:</p>\n\n<pre><code>VideoFactory $vf = new VideoFactory();\nVideo $video = $vf-&gt;createVideo( \"http://youtube.com/...\" );\n$video-&gt;setDimensions( 640, 480 );\n$video-&gt;embed();\n</code></pre>\n\n<p>Here, the <code>VideoFactory</code> can parse a URL. The <code>createVideo</code> method would return a subclass of <code>Video</code>, which is a <code>YouTubeVideo</code>. However, the implementation need not be dependent on YouTube. This allows you to also write:</p>\n\n<pre><code>VideoFactory $vf = new VideoFactory();\nVideo $video = $vf-&gt;createVideo( \"http://vimeo.com/...\" );\n$video-&gt;setDimensions( 640, 480 );\n$video-&gt;embed();\n</code></pre>\n\n<p>You'll note that the only item that changed is the URL, but both video formats can be embedded.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T15:32:48.567", "Id": "48288", "Score": "0", "body": "Is this javascript?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T15:59:32.017", "Id": "48296", "Score": "0", "body": "@Neal: Whoops! It was in Java, but now is in PHP. I should have wrote it in Haxe. ;-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T16:26:03.607", "Id": "48297", "Score": "0", "body": "Still not PHP..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T18:30:48.550", "Id": "48314", "Score": "0", "body": "This site is **not** a wiki, and whoever told you that was wrong..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T18:35:32.003", "Id": "48315", "Score": "0", "body": "@Neal: http://codereview.stackexchange.com/about - \"Our goal is to have the best answers to every question, so if you see questions or answers that can be improved, you can edit them. Use edits to fix mistakes, improve formatting, or clarify the meaning of a post.\"" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T21:58:10.970", "Id": "48327", "Score": "2", "body": "@Neal and Dave: It is possible to edit other users' posts, but only for users with at least 1000 reputation points. So Neal wouldn't be able to edit this answer, but other users with higher reputation can. Either way pointing out mistakes through comments is perfectly fine of course. I hope this clarified things." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T19:05:16.613", "Id": "30323", "ParentId": "30297", "Score": "3" } }, { "body": "<p>The constructor here is taking <code>url</code> as parameter,and it is declared as class level instance variable, so you will have access to this variable inside <code>parseUrl</code> method without passing this as an argument to the method </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T10:15:04.947", "Id": "30355", "ParentId": "30297", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T01:16:36.220", "Id": "30297", "Score": "3", "Tags": [ "php", "object-oriented" ], "Title": "Is this a qualified OOP script in PHP?" }
30297
<p>Based on the answer to <a href="https://stackoverflow.com/questions/18387417/">my previous question on Stack Overflow</a>, I put together the following Queue class. I realize there are already libraries out there to do this. However, I wanted to actually understand the concept and implementing it yourself really drives the knowledge home (it also provides much more fun and a greater sense of accomplishment!).</p> <p>But I DO want to make sure I've done this in the best way. Please see if it has any obvious issues or lacks any necessary features. A few possible improvements:</p> <ol> <li><p>Allow the list of functions passed to the constructor to be separate arguemnts, rather than an array of objects, by converting the <code>arguments</code> object into an array.</p> <p>One potential problem with this is if, in answer to #6 below, you guys feel the constructor should accept a context to be applied as <code>this</code> when calling the queued functions. To my mind, it seems more intuitive to have <code>var Queue = function( arrayOfFuncs, context ) {</code> than this:</p> <pre><code>var Queue = function() { var list = Array.prototype.slice.call( arguments ), context = this, self = this; if (typeof list[0] !== 'function') { context = list.shift(); // Context would have to be the first argument passed in } // ... }; </code></pre></li> <li><p>Similarly deal with <code>returnValue</code> as an array, so that a variable number of arguments could be passed to the callback.</p></li> <li>Adding onComplete or onError handlers, allowing easier access to the final return value.</li> <li>Add more helper functions like 'delay'. (For instance, a 'timer' method which handles an array, sending the items in the array to a specified processing function in batches. I.e. a fancy way to perform common setInterval patterns.)</li> <li>Perhaps methods to add or delete items from the queue?</li> <li>What should be passed as <code>this</code> to each function in the queue? Right now I am passing the queue itself, to allow the functions access to <code>this.paused</code> if they want to pause an interval (i.e. keep <code>return</code>ing from that interval until no longer paused)</li> </ol> <p>What else should a good queue have?</p> <pre><code>var Queue = function(queue) { var list = queue, self = this; // Use scope to allow Queue.next() to reference 'this' this.paused = false; // Ensures Queue.start() doesn't skip a currently running interval when // resuming from pause this.running = false; // Allows clearing of timeout / interval this.current = null; this.returnValue; this.next = function(returnValue) { self.running = false; if (list.length === 0) { self.returnValue = returnValue; return; } // Grab next function in queue and add returnvalue to args if needed var next = list.shift(); if (returnValue) next.args.push( returnValue ); if (self.paused) { // Stick the function back at beginning of queue to await restart list.unshift( next ); return; } else { self.running = true; // Call next function, applying the Queue as 'this' self.current = next.fn.apply(self, next.args); } }; for (var i = 0; i &lt; list.length; i++) { // Ensure there is an args array, then add Queue.next() as callback if (!list[i].args) list[i].args = []; list[i].args.push( this.next ); // Allows easier method of adding delays and pauses to queue if (typeof list[i].fn === 'string') { list[i].fn = this[ list[i].fn ]; } } }; Queue.prototype = { delay : function(time, callback, returnValue) { // Allows leaving out the args array and using default 1000ms // Remaps arguments if it has been left off if (typeof callback !== 'function') { returnValue = callback; callback = time; time = 1000; } return setTimeout( function() { callback( returnValue ); }, +time ); }, pause : function(callback, returnValue) { this.paused = true; // Allows Queue.pause() to be called either in the queue or while the // queue is running, in which case no callback need be specified if (callback) { callback( returnValue ); } }, advance : function() { // Executes queue items one at a time // Clear via both types, to ensure it's actually cleared clearInterval( this.current ); clearTimeout( this.current ); this.paused = false; this.next(); this.paused = true; }, start : function() { this.paused = false; // As stated earlier, a currently running interval will be completed // rather than skipping to the next queued function if (!this.running) this.next(); } }; function $(id) {return document.getElementById(id);} // Helper function type(from, to, callback, returnValue) { // Example async function // Shows that the return value from the first call of this function // carries through; notice 'returnValue' comes after 'callback' console.log(returnValue); var chars = from.value.split(''), self = this, interval = setInterval( function() { // If the following line is commented, it allows us to use Queue.advance() // If uncommented, we can use Queue.pause() and .start() // to pause and resume interval /* if (self.paused) return; */ to.value += chars.shift(); if (chars.length === 0) { clearInterval(interval); // Return a value by passing as param to callback callback(to.value); } }, 35); // Return an ID to allow Queue.advance() to clear the interval or timeout return interval; } window.testQueue = new Queue([ { fn: type, args: [$('textarea1'), $('textarea2')] }, { fn: 'delay', args: [3000] }, // Try with or without the args array { fn: 'pause' }, { fn: type, args: [$('textarea3'), $('textarea4')] } ]); // Start it, or use Queue.advance() from the console //testQueue.start(); // When Queue.pause() is reached in the queue, manually call Queue.start() </code></pre>
[]
[ { "body": "<p>From a once over,</p>\n\n<ul>\n<li>I would check for <code>if (self.paused) {</code> at the very beginning, otherwise you might keep pushing <code>returnValue</code> into the <code>args</code></li>\n<li>I would not assign an anonymous function herre: <code>this.next = function(returnValue) {</code> I would go for <code>this.next = function next(returnValue) {</code> this will make life easier when looking at stacktraces</li>\n<li>It does not make sense to maintain both <code>self.running</code> and <code>self.paused</code> since <code>self.running</code> will always be <code>!self.paused</code></li>\n<li>I would write <code>if (!list[i].args) list[i].args = [];</code> as<br> <code>list[i].args = list[i].args || []</code></li>\n<li>JsHint has nothing to report</li>\n</ul>\n\n<p>On the whole though, I am not sure I would use this library. I think I would go hunt for an existing queue library. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-30T16:15:31.360", "Id": "68420", "ParentId": "30298", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T01:31:56.720", "Id": "30298", "Score": "3", "Tags": [ "javascript", "asynchronous", "callback", "queue" ], "Title": "Javascript Queue for async functions" }
30298
<p>I have a situation where I have multiple objects that each needs to connect to a different MongoDB URI.</p> <p>I am currently testing this using Mongolia but the concept should be the same if I were to use the <code>collection()</code> method of MongoDB's native driver.</p> <p>Mongolia requires a <code>db</code> object when creating a new model, and since I do not have this object from start, I thought it would be better to callback the hell out of it.</p> <p>I do not wish to force all objects to connect to their databases from the start so it seems that nesting the callbacks is the way to go.</p> <pre><code>MongoClient = (require 'mongodb').MongoClient mongolia = require 'mongolia' modelFactory = (db, modelName, cb) -&gt; model = mongolia.model db, modelName cb undefined, model class SomethingWithDb tag: undefined databaseUri: undefined databaseInstance: undefined models: {} collections: {} log: (text) =&gt; console.log "[#{@tag}] #{text}" database: (cb) =&gt; if not @databaseInstance? @log 'database() &gt; Creating new database instance.' MongoClient.connect @databaseUri, {}, (err, db) =&gt; return cb err if err @log 'database() &gt; Database instance ready, returning.' @databaseInstance = db cb undefined, @databaseInstance else @log 'database() &gt; Database instance existed, returning.' cb undefined, @databaseInstance model: (modelName, cb) =&gt; if modelName not of @models @log "model(#{modelName}) &gt; Creating new model." @database (errDb, db) =&gt; return cb errDb if errDb modelFactory db, modelName, (errFactory, model) =&gt; @log "model(#{modelName}) &gt; Model created, returning." return cb errFactory if errFactory @models[modelName] = model cb undefined, model else @log "model(#{modelName}) &gt; Model existed, returning." cb undefined, @models[modelName] collection: (collectionName, cb) =&gt; if collectionName not of @collections @log "collection(#{collectionName}) &gt; Creating new collection." if not @databaseInstance? @database (errDb, db) =&gt; return cb errDb if errDb @log "collection(#{collectionName}) &gt; Collection created (new db), returning." @collections[collectionName] = db.collection collectionName cb undefined, @collections[collectionName] else @log "collection(#{collectionName}) &gt; Collection created (existing db), returning." cb undefined, @databaseInstance.collection collectionName else @log "collection(#{collectionName}) &gt; Collection existed, returning." cb undefined, @collections[collectionName] constructor: (@tag, @databaseUri, @databaseOptions) -&gt; one = new SomethingWithDb "mongodb://localhost/test-one" two = new SomethingWithDb "mongodb://localhost/test-two" one.model 'user', (errModel, user) -&gt; user.insert name: 'test', (errInsert, respInsert) -&gt; one.model 'user', (_errModel, _user) -&gt; _user.findOne name: 'test', (_errFind, _result) -&gt; console.info _result two.model 'user', (errModel, user) -&gt; user.insert name: 'test-two', (errInsert, respInsert) -&gt; user.findOne name: 'test-two', (errFind, result) -&gt; console.info result </code></pre> <p>The output is something like this:</p> <blockquote> <pre><code># [one] model(user) &gt; Creating new model. # [one] database() &gt; Creating new database instance. # [two] model(user) &gt; Creating new model. # [two] database() &gt; Creating new database instance. # [two] database() &gt; Database instance ready, returning. # [two] model(user) &gt; Model created, returning. # [one] database() &gt; Database instance ready, returning. # [one] model(user) &gt; Model created, returning. # [one] model(user) &gt; Model existed, returning. </code></pre> </blockquote> <p>I have included a <code>@collection()</code> method that is not tested but should provide a hint to other uses.</p> <p>Is the logic behind this correct or is there some better way to do this that I am not aware of? I'd be also very interested in any possible code or flow optimizations that might make this saner or more solid.</p>
[]
[]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T11:17:58.550", "Id": "30299", "Score": "1", "Tags": [ "node.js", "coffeescript", "mongodb" ], "Title": "Handling multiple Mongodb connections in Node.js (using Mongolia)" }
30299
<p>Server:</p> <pre><code>require 'socket' require 'time' require 'ap' server = TCPServer.open(1026) def process_the_request req, client # not important, disk-related process sleep 2 req.to_s + ' ' + client.peeraddr[3].to_s + ' ' + Time.now.to_s end loop do Thread.start(server.accept) do |client| request = '' ch = '' begin ch = client.getc print ch if (ch.nil? or ch.ord == 13 or ch.ord == 10) if request.length &lt; 1 break if client.eof? next end ap "request: " + request response = process_the_request request, client ap "response: " + response client.puts response request = '' break if client.eof? else request += ch end end while true #ap "thread closed" client.close end # Thread end # loop </code></pre> <p>Client:</p> <pre><code>nn='nc 127.0.0.1 1026' echo -n '1' | $nn &amp; echo '2' | $nn &amp; echo -n '3' | $nn &amp; echo '4 5 6 7' | $nn &amp; </code></pre>
[]
[ { "body": "<p>You shouldn't read from the client one byte at a time. Call <a href=\"http://www.ruby-doc.org/stdlib-1.9.3/libdoc/socket/rdoc/TCPSocket.html\" rel=\"nofollow\"><code>client.gets</code></a> to take a line at a time.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T02:18:02.430", "Id": "48338", "Score": "0", "body": "somehow client.gets not working when client breaks (e.g. when they forgot to send \\n on the last line), i ended up running too many unfinished thread" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T08:00:01.593", "Id": "30351", "ParentId": "30300", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T11:43:10.783", "Id": "30300", "Score": "1", "Tags": [ "performance", "ruby", "socket" ], "Title": "Improving performance of Ruby socket programming" }
30300
<p>The following is a new question based on answers from here: <a href="https://codereview.stackexchange.com/q/19592/3163">Small MVC for PHP</a></p> <hr> <p>I have written a small template library that I would like some critiques on, <a href="https://github.com/maniator/SmallFry/tree/cf08f80712084a220037d083330b14ba3490af8c" rel="nofollow noreferrer">located here</a>. If you are looking for where to start, check out the files in the <a href="https://github.com/maniator/SmallFry/tree/cf08f80712084a220037d083330b14ba3490af8c/lib" rel="nofollow noreferrer"><code>lib</code></a> directory.</p> <p>I would really love to hear your critiques on code quality, code clarity, and anything else that needs clarification expansion.</p> <p>I'm more interested in what I'm doing wrong than right. The README is incomplete and there is <strong>a lot</strong> more functionality than what is documented.</p> <p>Code examples (these <em>might</em> not have changed much since last year, but I was asked to add some code, so I am including the same two files as on my previous post):</p> <p><strong><a href="https://github.com/maniator/SmallFry/blob/cf08f80712084a220037d083330b14ba3490af8c/lib/Bootstrap.php" rel="nofollow noreferrer">Bootstrap.php</a>:</strong></p> <pre><code>&lt;?php /** * The main library for the framework */ namespace SmallFry\lib; class_alias('SmallFry\lib\MySQL_Interface', 'SmallFry\lib\MySQL'); // MySQL class to be deprecated /** * Description of Bootstrap * * @author nlubin */ Class Bootstrap { /** * * @var SessionManager */ private $_session; /** * * @var stdClass */ private $_path; /** * * @var AppController */ private $_controller; /** * * @var Template */ private $_template; /** * * @var Config */ private $CONFIG; /** * @param Config $CONFIG */ function __construct(Config $CONFIG) { try { $this-&gt;CONFIG = $CONFIG; $this-&gt;CONFIG-&gt;set('page_title', $this-&gt;CONFIG-&gt;get('DEFAULT_TITLE')); $this-&gt;CONFIG-&gt;set('template', $this-&gt;CONFIG-&gt;get('DEFAULT_TEMPLATE')); $this-&gt;_session = new SessionManager($this-&gt;CONFIG-&gt;get('APP_NAME')); $this-&gt;_path = $this-&gt;readPath(); $this-&gt;_controller = $this-&gt;loadController(); $this-&gt;_template = new Template($this-&gt;_path, $this-&gt;_session, $this-&gt;CONFIG); $this-&gt;_template-&gt;setController($this-&gt;_controller); $this-&gt;_controller-&gt;setPage($this-&gt;_path-&gt;page); $this-&gt;_controller-&gt;displayPage($this-&gt;_path-&gt;args); //run the page for the controller $this-&gt;_template-&gt;renderTemplate($this-&gt;_path-&gt;args); //only render template after all is said and done } catch (\Exception $e) { header("HTTP/1.1 404 Not Found"); exit; } } /** * @return \stdClass */ private function readPath(){ $default_controller = $this-&gt;CONFIG-&gt;get('DEFAULT_CONTROLLER'); $index = str_replace("/", "", \SmallFry\Config\INDEX); //use strtok to remove the query string from the end fo the request $request_uri = !isset($_SERVER["REQUEST_URI"]) ? "/" : strtok($_SERVER["REQUEST_URI"],'?');; $request_uri = str_replace("/" . $index , "/", $request_uri); $path = $request_uri ?: '/'.$default_controller; $path = str_replace("//", "/", $path); $path_info = explode("/",$path); $page = isset($path_info[2]) ? $path_info[2] : "index"; list($page, $temp) = explode('.', $page) + array("index", null); $model = $path_info[1] ?: $default_controller; $obj = (object) array( 'path_info' =&gt; $path_info, 'page' =&gt; $page, 'args' =&gt; array_slice($path_info, 3), 'route_args' =&gt; array_slice($path_info, 2), //if is a route, ignore page 'model' =&gt; $model ); return $obj; } /** * @return AppController */ private function loadController(){ //LOAD CONTROLLER $modFolders = array('images', 'js', 'css'); //load controller if(strlen($this-&gt;_path-&gt;model) == 0) $this-&gt;_path-&gt;model = $this-&gt;CONFIG-&gt;get('DEFAULT_CONTROLLER'); //find if is in modFolders: $folderIntersect = array_intersect($this-&gt;_path-&gt;path_info, $modFolders); if(count($folderIntersect) == 0){ //load it only if it is not in one of those folders $controllerName = "{$this-&gt;_path-&gt;model}Controller"; $model = $this-&gt;createModel($this-&gt;_path-&gt;model); $self = $this; $callback = function($modelName) use (&amp;$model, &amp;$self){ if(get_class($model) === "SmallFry\lib\AppModel") { //check if model DNE $newModel = $self-&gt;createModel($modelName); return $newModel; } else { //return the original model return $model; } }; $app_controller = $this-&gt;createController($controllerName, $model, $callback); if(!$app_controller) { $route = $this-&gt;CONFIG-&gt;getRoute($this-&gt;_path-&gt;model); if($route) { //try to find route $this-&gt;_path-&gt;page = $route-&gt;page; $this-&gt;_path-&gt;args = count($route-&gt;args) ? $route-&gt;args : $this-&gt;_path-&gt;route_args; $model = $this-&gt;createModel($route-&gt;model); $app_controller = $this-&gt;createController($route-&gt;controller, $model); if(!$app_controller) { //show nothing throw new \Exception("You cannot create a controller here for this route ({$route-&gt;controller})."); } } else { //show nothing throw new \Exception("That controller does not exist ({$controllerName})."); exit; } } return $app_controller; } else { //fake mod-rewrite $this-&gt;rewrite($this-&gt;_path-&gt;path_info, $folderIntersect); } //END LOAD CONTROLLER } public function createModel($model) { $useOldVersion = !$this-&gt;CONFIG-&gt;get('DB_NEW'); $mySQLClass = "SmallFry\lib\MySQL_PDO"; if($useOldVersion) { $mySQLClass = "SmallFry\lib\MySQL_Improved"; } //DB CONN $firstHandle = null; $secondHandle = null; //Primary db connection $database_info = $this-&gt;CONFIG-&gt;get('DB_INFO'); if($database_info) { $firstHandle = new $mySQLClass($database_info['host'], $database_info['login'], $database_info['password'], $database_info['database'], $this-&gt;CONFIG-&gt;get('DEBUG_QUERIES')); } else { exit("DO NOT HAVE DB INFO SET"); } //Secondary db connection $database_info = $this-&gt;CONFIG-&gt;get('SECONDARY_DB_INFO'); if($database_info) { $secondHandle = new $mySQLClass($database_info['host'], $database_info['login'], $database_info['password'], $database_info['database'], $this-&gt;CONFIG-&gt;get('DEBUG_QUERIES')); } //END DB CONN return AppModelFactory::buildModel($model, $this-&gt;CONFIG, $firstHandle, $secondHandle); } /** * @param string $controllerName * @return AppController */ private function createController($controllerName, $model, $callback = null) { $nameSpacedController = "SmallFry\\Controller\\$controllerName"; if (class_exists($nameSpacedController) &amp;&amp; is_subclass_of($nameSpacedController, __NAMESPACE__.'\AppController')) { $app_controller = new $nameSpacedController($this-&gt;_session, $this-&gt;CONFIG, $model, $callback); } else { return false; } return $app_controller; } /** * @param array $path_info * @param array $folderIntersect */ private function rewrite(array $path_info, array $folderIntersect){ $find_path = array_keys($folderIntersect); $find_length = count($find_path) - 1; $file_name = implode(DIRECTORY_SEPARATOR,array_slice($path_info, $find_path[$find_length])); $file = \SmallFry\Config\DOCROOT."webroot".DIRECTORY_SEPARATOR.$file_name; $file_extension = pathinfo($file, PATHINFO_EXTENSION); if(is_file($file)){ //if the file is a real file if($file_extension === 'php') { include("./webroot/{$file_name}"); exit; } include \SmallFry\Config\BASEROOT.DIRECTORY_SEPARATOR.'functions'.DIRECTORY_SEPARATOR.'apache_request_headers.php'; // needed for setups without `apache_request_headers` // Getting headers sent by the client. $headers = apache_request_headers(); // Checking if the client is validating his cache and if it is current. if (isset($headers['IF-MODIFIED-SINCE']) &amp;&amp; (strtotime($headers['IF-MODIFIED-SINCE']) == filemtime($file))) { // Client's cache IS current, so we just respond '304 Not Modified'. header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($file)).' GMT', true, 304); header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 3600)); header("Cache-Control: max-age=2592000"); } else { // File not cached or cache outdated, we respond '200 OK' and output the file. header('Last-Modified: '.gmdate('D, d M Y H:i:s', filemtime($file)).' GMT', true, 200); header('Expires: '.gmdate('D, d M Y H:i:s \G\M\T', time() + 3600)); header("Cache-Control: max-age=2592000"); header('Content-Length: '.filesize($file)); include \SmallFry\Config\BASEROOT.DIRECTORY_SEPARATOR.'functions'.DIRECTORY_SEPARATOR.'mime_type.php'; // needed for setups without `mime_content_type` header('Content-type: ' . mime_content_type($file)); readfile($file); } } else { throw new \Exception("File does not exist ({$file})."); } exit; } } </code></pre> <p><strong><a href="https://github.com/maniator/SmallFry/blob/cf08f80712084a220037d083330b14ba3490af8c/lib/AppController.php" rel="nofollow noreferrer">AppController.php</a>:</strong></p> <pre><code>&lt;?php namespace SmallFry\lib; /** * Description of AppController * * @author nlubin */ class AppController { private $pageOn; protected $name = __CLASS__; protected $helpers = array(); protected $validate = array(); protected $posts = array(); protected $session; protected $validator; protected $template; protected $CONFIG; /** * * @param SessionManager $SESSION * @param Config $CONFIG * @param MySQL_Interface $firstHandle * @param MySQL_Interface $secondHandle */ public function __construct(SessionManager $SESSION, Config $CONFIG, AppModel $model, $modelCallback = null) { $this-&gt;CONFIG = $CONFIG; $this-&gt;session = $SESSION; if(isset($this-&gt;modelName)) { //if the model is different than the controller name if($modelCallback !== null &amp;&amp; is_callable($modelCallback)) { $model = $modelCallback($this-&gt;modelName); //get real model } } $modelName = $model-&gt;getModelName(); $this-&gt;$modelName = $model; /* Get all posts */ $this-&gt;posts = $model-&gt;getPosts(); $view = isset($this-&gt;viewName) ? $this-&gt;viewName : $modelName; $this-&gt;CONFIG-&gt;set('view', strtolower($view)); $this-&gt;setHelpers(); if(!$this-&gt;session-&gt;get(strtolower($modelName))){ $this-&gt;session-&gt;set(strtolower($modelName), array()); } } private function getPublicMethods(){ $methods = array(); $r = new \ReflectionObject($this); $r_methods = $r-&gt;getMethods(\ReflectionMethod::IS_PUBLIC); $notAllowedMethods = array("__construct", "init", "__destruct"); //list of methods that CANNOT be a view and are `keywords` foreach($r_methods as $method){ if($method-&gt;class !== 'SmallFry\lib\AppController' &amp;&amp; !in_array($method-&gt;name, $notAllowedMethods)){ //get only public methods from extended class $methods[] = $method-&gt;name; } } return $methods; } /** * * @param Template $TEMPLATE */ public function setTemplate(Template $TEMPLATE){ $this-&gt;template = $TEMPLATE; $helpers = array(); foreach($this-&gt;helpers as $helper){ $help = "{$helper}Helper"; if(isset($this-&gt;$help)) { $helpers[$helper] = $this-&gt;$help; } } $this-&gt;template-&gt;set('helpers', (object) $helpers); } /** * Function to run before the constructor's view function */ public function init(){} //function to run right after constructor public function setPage($pageName) { $this-&gt;page = $pageName; } /** * Show the current page in the browser * * @param array $args * @return string */ public function displayPage($args) { $this-&gt;CONFIG-&gt;set('method', $this-&gt;page); $public_methods = $this-&gt;getPublicMethods(); if(in_array($this-&gt;page, $public_methods)) { call_user_func_array(array($this, $this-&gt;page), $args); } else { throw new \Exception("{$this-&gt;name}/{$this-&gt;page} does not exist."); exit; } } /** * * @return string */ function index() {} /** * * @param string $msg * @return string */ protected function getErrorPage($msg = null) { $err = '&lt;div class="error errors"&gt;%s&lt;/div&gt;'; return sprintf($err, $msg); } protected function setHelpers(){ foreach($this-&gt;helpers as $helper){ $help = "{$helper}Helper"; $nameSpacedHelper = "SmallFry\\helper\\$help"; if(class_exists($nameSpacedHelper) &amp;&amp; is_subclass_of($nameSpacedHelper, 'SmallFry\\helper\\Helper')){ $this-&gt;$help = new $nameSpacedHelper(); } } } /** * * @param array $validate * @param array $values * @param boolean $exit * @return boolean */ protected function validateForm($validate = null, $values = null, $exit = true){ $this-&gt;validator = new FormValidator(); //create new validator if($validate == null){ $validate = $this-&gt;validate; } foreach($validate as $field =&gt; $rules){ foreach($rules as $validate=&gt;$message){ $this-&gt;validator-&gt;addValidation($field, $validate, $message); } } return $this-&gt;doValidate($values, $exit); } protected function doValidate($values = null, $exit = true){ if(!(!isset($_POST) || count($_POST) == 0)){ //some form was submitted if(!$this-&gt;validator-&gt;ValidateForm($values)){ $error = ''; $error_hash = $this-&gt;validator-&gt;GetErrors(); foreach($error_hash as $inpname =&gt; $inp_err) { $error .= $inp_err.PHP_EOL; } return $this-&gt;makeError($error, $exit); } } return true; } protected function makeError($str, $exit = true){ $return = $this-&gt;getErrorPage(nl2br($str)); if($exit) exit($return); return $return; } protected function killPage(){ //Throw a 404 for the page header("HTTP/1.1 404 Not Found"); exit; } } </code></pre>
[]
[ { "body": "<p>Small nitpick,</p>\n\n<pre><code>class_alias('SmallFry\\lib\\MySQL_Interface', 'SmallFry\\lib\\MySQL'); // MySQL class to be deprecated\n</code></pre>\n\n<p>You can use the <code>use</code> statement:</p>\n\n<pre><code>use SmallFry\\lib\\MySQL_Interface as MySQL\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:27:49.903", "Id": "48176", "Score": "4", "body": "class_alias is for more than just the current file" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T17:23:22.023", "Id": "48192", "Score": "0", "body": "Exactly @ChadRetz I did not want to change my code in older files that used an older version of my lib." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:14:49.630", "Id": "30311", "ParentId": "30304", "Score": "-2" } }, { "body": "<p>You have asked for critiques, so here it goes.</p>\n\n<ul>\n<li>A readability remark:\nThe comments for private variables in <code>Bootstrap</code> take too much space yet tell very little to unfamiliar reader. Maybe give more descriptive names to your variables and drop comments or replace them by more details. Also one line per comment. Quoting <a href=\"http://rads.stackoverflow.com/amzn/click/0132350882\" rel=\"nofollow\">Uncle Bob's fantastic book</a>:</li>\n</ul>\n\n<blockquote>\n <p>Explain yourself in code</p>\n</blockquote>\n\n<ul>\n<li><p><code>__construct</code> is generally recommended to be small, yours seems to be doing too much. </p></li>\n<li><p>It is generally considered bad practice to have <code>new Object</code> inside your constructor. This makes it very hard to test and makes your code tightly coupled with dependencies. A better way is to make them explicit dependencies (Dependency Injection):</p>\n\n<pre><code>function __construct(Config $CONFIG, SessionManager $SManager, Template $Template)\n</code></pre></li>\n<li><p>Your function <code>loadController</code> is huge! Quoting Uncle Bob:</p></li>\n</ul>\n\n<blockquote>\n <p>The first rule of functions is that they should be small. The second rule is that they should be smaller than that.</p>\n</blockquote>\n\n<ul>\n<li><p>I can see many hard-coded strings inside your functions, you may want to put them separately in a dedicated config class.</p></li>\n<li><p>Writing style: You are using <code>$app_controller</code> and <code>$modelName</code>. Maybe keep the same convention - either always underscore of camel-case.</p></li>\n<li><p>It is a matter of personal preference, but I like to start private/protected function with underscore, to easily distinguish them from public ones.</p></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T23:47:13.133", "Id": "68522", "Score": "2", "body": "We could really use a PHP guru programmer in our [chatroom](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor). +1" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-03T21:45:50.630", "Id": "68797", "Score": "0", "body": "@syb0rg Thanks, I wish I could call myself PHP guru :) Just read a couple of books." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-04T00:37:02.260", "Id": "68841", "Score": "0", "body": "@DmitriZaitsev that doesn't make you any less welcome in [The 2nd Monitor](http://chat.stackexchange.com/rooms/8595/the-2nd-monitor) ;)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T14:00:03.370", "Id": "70392", "Score": "0", "body": "@lol.upvote Any specific problem you need help with over there?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T17:55:10.823", "Id": "70446", "Score": "0", "body": "@DmitriZaitsev (Neal here) The comments in the Bootstrap class were created by my IDE. Also I use Dependency Injection **throughout** my code, just in that one class I create everything and pass it on to all of the other classes. Also yes I know I am inconsistent in my variable naming (I will _try_ to fix that in the future). Is there anything else that you can add? (I have a feeling you only read the code int he question and not the code in the repository)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-06T19:08:34.170", "Id": "70479", "Score": "0", "body": "Concerning the comments, it is just subjective opinion that they don't help much to a reader. It looks like your IDE is creating some sort of templates to be extended by you rather than left as they are. And yes, I only looked at the code posted. For other parts of code, it is more convenient if you post here (or in another post) whatever parts you are interested in, that way people don't have to go elsewhere to understand the answer." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-01T16:25:23.157", "Id": "40622", "ParentId": "30304", "Score": "7" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T14:02:23.970", "Id": "30304", "Score": "5", "Tags": [ "php", "object-oriented", "template", "library", "framework" ], "Title": "Small PHP framework template library" }
30304
<p>We're trying to design validation classes with a common interface. This would apply to all validators. We would define a validator interface with a <code>validate($input):bool</code> method. Each validator would represent a specific data type (email address, login, etc.); the validate method would implement the appropriate logic.</p> <p>Option 1: Instantiate a validator object (either directly or through a factory) to perform validation</p> <pre><code>class EmailValidator implements ValidatorInterface { public function validate($input) { ... } } // Usage: $var = new EmailValidator(); if ($var-&gt;validate($val)) { ... } </code></pre> <p>Option 2: Validator interface defines a static <code>validate()</code> method implemented by each validator</p> <pre><code>class EmailValidator implements ValidatorInterface { public static function validate($input) { ... } } // Usage: if (EmailValidator::validate($val)) { ... } </code></pre> <p>Which would be the best option to use? Are there better ways to go about this than those laid out above?</p>
[]
[ { "body": "<p>I am not that familiar with static methods in PHP specifically, so my answer is a bit limited in the aspect of what can be done in PHP.</p>\n\n<p>If possible in PHP, I'd say make both ways available.</p>\n\n<p>Obviously, the appeal of the static method is in its ease of use. However, such approach also has its limitations.</p>\n\n<p>For example, let's say you want to make a validator that would check if a validated value is in a certain list. With the static approach, you'd need to make a separate class for each list. But, if you make your class so that you instantiate it, you can make a general validator which would have list management methods (i.e., <code>assignArray</code>, <code>addItem</code>, <code>clearItems</code>, etc), and you could use that one single validator class for all the lists you want.</p>\n\n<p>So, if PHP doesn't allow duality, I'd vote for the non-static approach.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:33:22.263", "Id": "30316", "ParentId": "30305", "Score": "0" } }, { "body": "<p>Don't use static methods. Eventually you will want to be able to apply a group of validators in a single operation i.e. testing for NonBlank then testing for Email. Easy to do with objects, far more challenging with statics.</p>\n\n<p>It's interesting that your Validator is very similar to that used by the popular Symfony\\Validator component. So I think it's safe to say you are on the right track. </p>\n\n<p>Might want to take a look at the component just to get some ideas:</p>\n\n<p><a href=\"https://github.com/symfony/Validator\" rel=\"nofollow\">https://github.com/symfony/Validator</a></p>\n\n<p><a href=\"http://symfony.com/doc/current/book/validation.html\" rel=\"nofollow\">http://symfony.com/doc/current/book/validation.html</a></p>\n\n<p>=================================================================</p>\n\n<p><strong>I don't understand why it would be more challenging with statics.</strong></p>\n\n<p>If you needed multiple constraints then creating instances, storing them in an array and then looping over the array is easier then using statics. </p>\n\n<p>But lets consider a different problem. Suppose you want a UniqueEmailValidator which needs access to the database. It's a bit awkward using statics but:</p>\n\n<pre><code>$validator = new UniqueEmailValidator($db); // Works well\n</code></pre>\n\n<p>And once you start using a dependency injection container you can do:</p>\n\n<pre><code>$validator = $container-&gt;getService('unique_email_validator');\n</code></pre>\n\n<p>Which hides the $db portion.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T01:23:38.627", "Id": "48214", "Score": "1", "body": "I don't understand why it would be more challenging with statics. Since Vedran Sego says the same I guess you are on to something." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T13:26:38.473", "Id": "48269", "Score": "0", "body": "Thank you for elaborating. I was considering making them static for any simple validation, but instantiated for anything more complex (like the unique email validator). I suppose in the name of consistency they should all be instantiated, though." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T20:56:57.200", "Id": "30329", "ParentId": "30305", "Score": "6" } }, { "body": "<p>Why not build a complete validator class that does multiple kind of form validation rather than using validation interface and inheriting from it\nSomething like</p>\n\n<pre><code>&lt;?php\n class Validator{\n //properties\n //functions\n }\n ?&gt;\n</code></pre>\n\n<p>I feel all your method should be static since it aid flexibility.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-06T05:29:33.767", "Id": "391661", "Score": "0", "body": "This is more a comment than an answer." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-09-03T15:06:30.187", "Id": "203029", "ParentId": "30305", "Score": "0" } } ]
{ "AcceptedAnswerId": "30329", "CommentCount": "0", "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2013-08-27T14:02:42.370", "Id": "30305", "Score": "3", "Tags": [ "php", "comparative-review", "validation" ], "Title": "Validator classes" }
30305
<p>I have a factory that loads configuration from an xml file, and uses the configuration to be able to create objects of an appropriate type with appropriate settings. My application does a number of different tasks, and I don't want a broken or missing xml file to interfere with the other tasks the application does.</p> <p>The factory is a Guice-provided dependency, however, if I make the constructor throw an exception, then I will just get a <code>ProvisionException</code>, which could cause unpredictable results or crash the application, neither of which are acceptable.</p> <p>Currently, I have the factory swallow the exception on creation, and then throw it when the <code>make</code> method is called. Alternatively, I have a <code>makeUnchecked</code> method, if you call the <code>ready()</code> method first. Are there any problems with this approach, or is there potentially a better way to do it?</p> <p><a href="http://sscce.org/">SSCCE:</a></p> <pre class="lang-java prettyprint-override"><code>public class FooFactory { private Exception ex = null; @Inject public FooFactory(@FooSettings String filename) { loadSettings(filename); } public void loadSettings(String filename) { try { // stuff this.ex = null; } catch(Exception e) { this.ex = e; } } public Foo make(InputObj input) throws Exception { if(ex != null) throw ex; makeUnchecked(input); } public Foo makeUnchecked(InputObj input) { if (ex != null) throw new IllegalStateException(ex); // factory stuff } public boolean ready() { return ex == null; } } </code></pre>
[]
[ { "body": "<p>Your approach will work, but I would suggest an alternative. \nRemove the <code>makeUnchecked</code> and <code>ready</code> methods. \nDo not have constructor load settings. \nHave a static <code>boolean</code> variable, say, <code>areSettingsLoaded</code> to indicate whether settings have been loaded. Set it to <code>false</code> initially. \nIn the make method add thread-safe code to check the value of <code>areSettingsLoaded</code>. If <code>false</code> call <code>loadsettings</code>. Then set the <code>boolean</code> var to true. \nThis approach will have the following advantages:</p>\n\n<ol>\n<li>The class gets constructed faster. </li>\n<li>The <code>Exception</code> will not be hidden.</li>\n<li><code>Exception</code> handling logic is much simpler.</li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T13:15:19.003", "Id": "48266", "Score": "0", "body": "Would you still have `make` throw a checked exception?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-27T16:55:44.303", "Id": "53393", "Score": "0", "body": "A disadvantage is that it makes testing harder since the static variable acts as a global state which you have to reset before every test." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T10:31:06.373", "Id": "30356", "ParentId": "30307", "Score": "0" } }, { "body": "<blockquote>\n <p>My application does a number of different tasks, and I don't want a broken or missing xml file to interfere with the other tasks the application does.</p>\n</blockquote>\n\n<p>If you don't need the XML file configuration, why do you have it? How can you continue without it?</p>\n\n<p>How you answer this conceptual question has a lot to do with how you implement the code logic using exceptions.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T16:17:49.773", "Id": "30379", "ParentId": "30307", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T14:33:17.810", "Id": "30307", "Score": "5", "Tags": [ "java", "exception-handling", "dependency-injection" ], "Title": "Object can throw exception on construction, but I don't want it to stop everything" }
30307
<p>I have some doubt about how NSString is released in ARC Mode.</p> <p>I would like to know if have something i can do to release a nsstring when i want in arc mode.</p> <p>Take a look at this code:</p> <pre><code>__block NSString *strImage = nil; dispatch_sync(backGround, ^{ // Convert NSData To NSString. strImage = [UIImagePNGRepresentation([UIImage imageWithData:reg.photoData]) base64Encoding]; }); // Prepare Request Operation. NSString * strPost = @"myUrl"; strPost = [strPost stringByAppendingFormat:@"}&amp;image="]; strPost = [strPost stringByAppendingFormat:@"%@",strImage]; //NSLog(@"POST: %@",strPost); // setting up the URL to post to NSString *urlString = @"myURLAPI"; // setting up the request object now NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:urlString]]; [request setHTTPMethod:@"POST"]; /* add some header info now we always need a boundary when we post a file also we need to set the content type You might want to generate a random boundary.. this is just the same as my output from wireshark on a valid html post */ NSString *contentType = [NSString stringWithFormat:@"application/x-www-form-urlencoded"]; [request addValue:contentType forHTTPHeaderField: @"Content-Type"]; /* now lets create the body of the post */ NSMutableData *body = [NSMutableData data]; [body appendData:[NSData dataWithData:[strPost dataUsingEncoding:NSUTF8StringEncoding]]]; // setting the body of the post to the reqeust [request setHTTPBody:body]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc]initWithRequest:request]; //MY DOUBT ABOUT RELEASE THIS STR @autoreleasepool { strImage = nil; } </code></pre> <p>is it correct or have a best way to do it? Thank you</p>
[]
[ { "body": "<p>Also <code>@autoreleasepool</code> does not look are the objects create outside of it scope, just the object used within. Also if using are there is not need for the <code>@autoreleasepool</code> at all, since the scope variables will be released and nilled at the end of the scope.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T21:30:59.467", "Id": "48570", "Score": "0", "body": "so when my function end the str compiler knows that this str need to release? dont i need the autorelease?" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T13:30:41.317", "Id": "30513", "ParentId": "30310", "Score": "1" } } ]
{ "AcceptedAnswerId": "30513", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T14:59:10.780", "Id": "30310", "Score": "1", "Tags": [ "objective-c", "ios" ], "Title": "AutoreleasePool NSString Automatic Reference Counting" }
30310
<p>I'm using an open source program called MElt which lemmatize (give the lemma example:giving-->give) of words. MElt works on Linux and it's programmed in Perl and Python. So far it's working good but it take way too much time to give the results. I looked into the code and located the loop responsible for this:</p> <pre><code>while (&lt;LEFFF&gt;) { chomp; s/ /_/g; # s/(\S)-(\S)/\1_-_\2/g; /^(.*?)\t(.*?)\t(.*?)(\t|$)/ || next; $form = $1; $cats = $2; $lemma = $3; #print "$form \n"; #print "$cats \n"; #print "$lemma \n"; if ($lower_case_lemmas) { $lemma = lc($lemma); } if ($it_mapping) { next if ($form =~ /^.+'$/); next if ($form eq "dato" &amp;&amp; $lemma eq "datare"); # bourrin next if ($form eq "stato" &amp;&amp; $lemma eq "stare"); # bourrin next if ($form eq "stata" &amp;&amp; $lemma eq "stare"); # bourrin next if ($form eq "parti" &amp;&amp; $lemma eq "parto"); # bourrin if ($cats =~ /^(parentf|parento|poncts|ponctw)$/) {$cats = "PUNCT"} if ($cats =~ /^(PRO)$/) {$cats = "PRON"} if ($cats =~ /^(ARTPRE)$/) {$cats = "PREDET"} if ($cats =~ /^(VER|ASP|AUX|CAU)$/) {$cats = "VERB"} if ($cats =~ /^(CON)$/) {$cats = "CONJ"} if ($cats =~ /^(PRE)$/) {$cats = "PREP"} if ($cats =~ /^(DET)$/) {$cats = "ADJ"} if ($cats =~ /^(WH)$/) {$cats = "PRON|CONJ"} next if ($form =~ /^(una|la|le|gli|agli|ai|al|alla|alle|col|dagli|dai|dal|dalla|dalle|degli|dei|del|della|delle|dello|nei|nel|nella|nelle|nello|sul|sulla)$/ &amp;&amp; $cats eq "ART"); next if ($form =~ /^quest[aei]$/ &amp;&amp; $cats eq "ADJ"); next if ($form =~ /^quest[aei]$/ &amp;&amp; $cats eq "PRON"); next if ($form =~ /^quell[aei]$/ &amp;&amp; $cats eq "ADJ"); next if ($form =~ /^quell[aei]$/ &amp;&amp; $cats eq "PRON"); next if ($form =~ /^ad$/ &amp;&amp; $cats eq "PREP"); next if ($form =~ /^[oe]d$/ &amp;&amp; $cats eq "CONJ"); } $qmlemma = quotemeta ($lemma); for $cat (split /\|/, $cats) { if (defined ($cat_form2lemma{$cat}) &amp;&amp; defined ($cat_form2lemma{$cat}{$form}) &amp;&amp; $cat_form2lemma{$cat}{$form} !~ /(^|\|)$qmlemma(\||$)/) { $cat_form2lemma{$cat}{$form} .= "|$lemma"; } else { $cat_form2lemma{$cat}{$form} = "$lemma"; $form_lemma_suffs = "@".$form."###@".$lemma; while ($form_lemma_suffs =~ s/^(.)(.+)###\1(.+)/\2###\3/) { if (length($2) &lt;= 8) { $cat_formsuff_lemmasuff2count{$cat}{$2}{$3}++; if ($multiple_lemmas) { $cat_formsuff_lemmasuff2count{$cat}{$2}{__ALL__}++; } } } } } } </code></pre> <p>The variable <code>LEFFF</code> is a dictionary composed of 490489 lines. So, the loop is comparing the words with all the dictionary lines one by one. This is too much. Any ideas how to optimize this?</p> <p>Here's a preview of how <code>LEFFF</code> is structured:</p> <pre class="lang-none prettyprint-override"><code>touant VPR touer 0 intimiste NC intimiste 1 intimiste ADJ intimiste 0 phonologiques ADJ phonologique 1 condescendirent V condescendre 1 enchaussez VIMP enchausser 1 enchaussez V enchausser 0 riotiez VS rioter 1 riotiez V rioter 0 Eyzin-Pinet NPP Eyzin-Pinet 1 dentaires NC dentaire 0 dentaires ADJ dentaire 1 classe VIMP classer 0 classe VS classer 1 </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T09:14:50.630", "Id": "48494", "Score": "0", "body": "WRT the update: The code you have given us is a very small snippet from the actual code. The two answers just tell how a constant factor can be reduced. This doesn't matter much, because optimizing the algorithmic complexity would be more important. Unfortunately, this would require changes to the data structure you are using, which would require changes throughout the source. WRT the hash table idea: Perl has this as a builtin data type. Indexing the file itself isn't a good idea: we would need to index line offsets to `seek` them. Ugh. You were thinking “database”, which would be better." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T14:21:24.960", "Id": "48532", "Score": "0", "body": "Thank you Amon, I'm implementing the other idea now, I'll probably post another subject somewhere else." } ]
[ { "body": "<p>I would try to get rid of the regular-expressions, because they are quite heavy to compute.</p>\n\n<p>But if you need them, have a look at the answer in this post: <a href=\"https://stackoverflow.com/questions/550258/does-the-o-modifier-for-perl-regular-expressions-still-provide-any-benefit\">precompile regexps once</a></p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:49:59.780", "Id": "48182", "Score": "2", "body": "The `/o` modifier is practically obsolete, because perl is quite good at compiling constant regexes only once. I am more concerned with the style of the regexes – lots of unneccessary captures, and sometimes string equality would be the better test." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:56:16.870", "Id": "48183", "Score": "0", "body": "I meant 'using a regex object' not to use /o. But avoid the regeps would be better." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:31:34.287", "Id": "30315", "ParentId": "30312", "Score": "0" } }, { "body": "<p>Well, this is difficult, especially without being a linguist. However, the code is horrid, and I can fix that.</p>\n\n<hr>\n\n<p><code>s/ /_/g</code> should be <code>tr/ /_/</code>, as single-character transliterations are more efficient than full-fledged regex matches.</p>\n\n<hr>\n\n<pre><code>/^(.*?)\\t(.*?)\\t(.*?)(\\t|$)/ || next;\n$form = $1; $cats = $2; $lemma = $3;\n</code></pre>\n\n<p>should be</p>\n\n<pre><code>my ($form, $cats, $lemma) = split /\\t/, $_, 4 or next;\n</code></pre>\n\n<p>The <code>.*?</code> in the regex is a big no-no. It wants to split the line into three parts at tabs – so let's use <code>split</code>.</p>\n\n<hr>\n\n<p>Certain stuff could be written more readable:</p>\n\n<pre><code> if ($it_mapping) {\n next if $form =~ /.'$/ # optimized from /^.+'$/\n or $form eq \"dato\" &amp;&amp; $lemma eq \"datare\"\n or $form eq \"stato\" &amp;&amp; $lemma eq \"stare\"\n or $form eq \"stata\" &amp;&amp; $lemma eq \"stare\"\n or $form eq \"parti\" &amp;&amp; $lemma eq \"parto\"\n or $cats eq \"ART\" &amp;&amp; $form =~ /^(?:una|la|le|gli|agli|ai|al|alla|alle|col|dagli|dai|dal|dalla|dalle|degli|dei|del|della|delle|dello|nei|nel|nella|nelle|nello|sul|sulla)$/;\n\n # removing capture groups, using eq where appropriate, using postfix if:\n $cats = \"PUNCT\" if $cats =~ /^(?:parentf|parento|poncts|ponctw)$/;\n $cats = \"PRON\" if $cats eq 'PRO';\n $cats = \"PREDET\" if $cats eq 'ARTPRE';\n $cats = \"VERB\" if $cats =~ /^(?:VER|ASP|AUX|CAU)$/;\n $cats = \"CONJ\" if $cats eq 'CON';\n $cats = \"PREP\" if $cats eq 'PRE';\n $cats = \"ADJ\" if $cats eq 'DET';\n $cats = \"PRON|CONJ\" if $cats eq 'WH';\n\n # cheaper test (equality) as early as possible\n next if $cats eq \"PREP\" &amp;&amp; $form eq 'ad'\n or $cats eq \"ADJ\" &amp;&amp; $form =~ /^quest[aei]$/\n or $cats eq \"PRON\" &amp;&amp; $form =~ /^quest[aei]$/\n or $cats eq \"ADJ\" &amp;&amp; $form =~ /^quell[aei]$/\n or $cats eq \"PRON\" &amp;&amp; $form =~ /^quell[aei]$/\n or $cats eq \"CONJ\" &amp;&amp; $form =~ /^[oe]d$/;\n }\n</code></pre>\n\n<p>Note that I did not optimize the gargantuan regex – the <em>trie optimization</em> will transform that into a state machine, which is far more efficient. This regex match was also moved before the <code>$cats</code> normalization in order to bail out as early as possible.</p>\n\n<hr>\n\n<pre><code>$qmlemma = quotemeta ($lemma);\n</code></pre>\n\n<p>should be </p>\n\n<pre><code>my $qmlemma = quotemeta ($lemma);\n</code></pre>\n\n<p>because lexical variables can be more efficient, and it makes it easier to reason about the code.</p>\n\n<hr>\n\n<p>The next part (looping through the <code>$cat</code>s) is very hackish, and could be done more efficient with a different data structure. </p>\n\n<p>(I removed my <code>no autovivification</code> recommendation because that behaviour is needed in the <code>else</code> clause again, and it does not effectively save much).</p>\n\n<p>The regex should be changed to <code>/(?:^|[|])$qmlemma(?:[|]|$)/</code> to avoid unneccessary capturing (and to make it more readable).</p>\n\n<hr>\n\n<p>The else-branch should be changed to</p>\n\n<pre><code>$cat_form2lemma{$cat}{$form} = $lemma; # avoid unneccessary stringification\nmy $form_lemma_suffs = '@' . $form . '###@' . $lemma; # lexical variables!!!\nwhile ($form_lemma_suffs =~ s/^(.)(.+)###\\1(.+)/\\2###\\3/) {\n if (length($2) &lt;= 8) {\n $cat_formsuff_lemmasuff2count{$cat}{$2}{$3}++;\n $cat_formsuff_lemmasuff2count{$cat}{$2}{__ALL__}++ if $multple_lemmas;\n }\n}\n</code></pre>\n\n<p>Most of the changes are meant to improve readability (postfix <code>if</code>, spacing). If I grok that code correctly, then it might be able to change this to</p>\n\n<pre><code>$cat_form2lemma{$cat}{$form} = $lemma; # avoid unneccessary stringification\n\nmy ($form_suff, $lemma_suff) = ($form, $lemma);\nwhile (length($form_suff) and substr($form_suff, 0, 1, '') eq substr($lemma_suff, 0, 1, '')) {\n if (length($form_suff) &lt;= 8) {\n $cat_formsuff_lemmasuff2count{$cat}{$form_suff}{$lemma_suff}++;\n $cat_formsuff_lemmasuff2count{$cat}{$form_suff}{__ALL__}++ if $multiple_lemmas;\n }\n}\n</code></pre>\n\n<p>C-style string manipulation with <code>substr</code> is far more efficient than regexes with captures and backrefs.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T16:01:49.027", "Id": "48184", "Score": "0", "body": "Thank you very much Jamal,\nI'll try to implement all of this (it's probably gonna take a while as I'm more used to C# programming) and I'll keep you posted" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T17:28:48.797", "Id": "48403", "Score": "0", "body": "@Med: Amon, you mean? I didn't answer this question (only made some edits). :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T08:48:23.710", "Id": "48490", "Score": "0", "body": "Oh...My bad yeah yeah I meant Amon ..." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:47:14.790", "Id": "30317", "ParentId": "30312", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:18:14.220", "Id": "30312", "Score": "1", "Tags": [ "performance", "regex", "hash-map", "perl" ], "Title": "Searching for words in a dictionary" }
30312
<p>This program writes out all the files in the current directory level to a text file, outputs an array of sub-directories at the current level, then repeats this process until there are no more sub-directories to search. The code below take 50 seconds to run.</p> <p>I was hoping I could get any pointers on the code in general (I'm very new to C#) and also any suggestions for improving the runtime.</p> <pre><code>using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; namespace ComputerFileOutput { class Program { // Prints a string array of files located in specified path static void filesArray(string path) { string[] array = Directory.GetFiles(path); addFilesToTextFile(array); } //Appends files to .txt document static void addFilesToTextFile(string[] fileArray) { //Append fileArray to current .txt document using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"C:\ComputerFiles.txt", true)) { for (int i = 0; i &lt; fileArray.Length; ++i) { file.WriteLine(fileArray[i]); } } } //Returns a string array of directories in a specified path static string[] getDirectories(string path) { return (Directory.GetDirectories(path)); } static void Main(string[] args) { DateTime t1 = DateTime.Now; string[] startUp = { "------LIST OF ALL COMPUTER FILES------" }; System.IO.File.WriteAllLines(@"C:\ComputerFiles.txt", startUp); //Get files in c directory; append to .txt file filesArray("C:\\"); //Get array of primary directories in C drive string[] directoryArray = getDirectories("C:\\"); //initialize subdirectory search bool moreDirectories = true; //Go through each directory while (moreDirectories == true) { List&lt;string&gt; subDirectories = new List&lt;string&gt;(); foreach(string directoryName in directoryArray) { try { filesArray(directoryName); subDirectories.AddRange(getDirectories(directoryName)); } catch(Exception) { Console.WriteLine("Unathorized to access directory: {0}", directoryName); } } directoryArray = subDirectories.ToArray(); if (directoryArray.Count() == 0) { moreDirectories = false; break; } } // wait for input before exiting DateTime t2 = DateTime.Now; Console.WriteLine("Total seconds = {0}", (t2 - t1).TotalSeconds); Console.WriteLine("Press enter to finish"); Console.ReadLine(); } } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:27:51.857", "Id": "48177", "Score": "0", "body": "what happens to the application when you hit an Exception in your try/catch? does the application stop, or does it skip that one and keep going?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:42:00.807", "Id": "48180", "Score": "2", "body": "When you say \"the code takes 50 seconds to run\" - is that in ALL cases, no matter the depth of recursion required, or just for the hard-coded example case of \"C:\\\\\" ? I wouldn't be too surprised at 50 seconds for detailing your entire c drive." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:43:15.940", "Id": "48181", "Score": "1", "body": "Try capturing all files, THEN writing them out. Or skipping file io entirely -- debug to view the output and see if the time changes. Try some logging to time the variations." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:11:07.887", "Id": "48254", "Score": "0", "body": "I think it's worth pointing out that the whole file enumeration could be done via `Directory.GetFiles(@\"C:\\\", \"*.*\", SearchOption.AllDirectories)`..." } ]
[ { "body": "<p>First of all, you shouldn't hardcode values like your <code>C:\\</code> or <code>C:\\ComputerFiles.txt</code>. If you want to change this, you don't want to edit it at multiple places.</p>\n\n<pre><code>static void filesArray(string path)\n</code></pre>\n\n<p>The usual .Net naming convention for methods is PascalCase (you'll notice that <code>Main</code> has to follow this convention).</p>\n\n<p>Also, <code>filesArray</code> is pretty bad name for this method. It doesn't tell you what the method does (that it prints somethings). On the other hand, it tells you about an implementation detail (it uses an array), which it shouldn't.</p>\n\n<pre><code>static void addFilesToTextFile(string[] fileArray)\n</code></pre>\n\n<p>Whenever you call this method, you open and then close a file. I'm not sure about this, but it could add a measurable overhead, considering that you're going to have huge amount of directories.</p>\n\n<pre><code>return (Directory.GetDirectories(path));\n</code></pre>\n\n<p>The outer parentheses are not necessary here, remove them.</p>\n\n<pre><code>static void Main(string[] args)\n</code></pre>\n\n<p>If you're not going to use command-line arguments, you can safely remove the <code>args</code> parameter.</p>\n\n<pre><code>DateTime t1 = DateTime.Now;\n</code></pre>\n\n<p>To measure runtime of your program accurately, you should usually use <code>Stopwatch</code> instead of <code>DateTime</code>. Though if the time is on the order of 50 s, you don't need millisecond accuracy, so <code>DateTime</code> is probably okay.</p>\n\n<pre><code>while (moreDirectories == true)\n</code></pre>\n\n<p>This whole loop could be simplified if you used <code>Queue&lt;T&gt;</code>. Something like:</p>\n\n<pre><code>//Get array of primary directories in C drive\nvar directories = new Queue&lt;string&gt;(getDirectories(\"C:\\\\\"));\n\n//Go through each directory\nwhile (directories.Count &gt; 0)\n{\n string directoryName = directories.Dequeue();\n\n try\n {\n filesArray(directoryName);\n\n foreach (var subdirectory in getDirectories(directoryName))\n directories.Enqueue(subdirectory);\n }\n catch (Exception)\n {\n Console.WriteLine(\"Unathorized to access directory: {0}\", directoryName);\n }\n}\n</code></pre>\n\n<p>If you don't like that <code>foreach</code>, you could easily create an extension method for it, called something like <code>EnqueueRange()</code>.</p>\n\n<pre><code>catch(Exception)\n</code></pre>\n\n<p>If you're expecting unauthorized access errors, then you should catch <code>UnauthorizedAccessException</code>, nothing else.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T11:52:50.163", "Id": "48251", "Score": "0", "body": "That should probably be `directories.Count` in the loop condition of your `Queue` example." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T16:07:34.507", "Id": "30319", "ParentId": "30313", "Score": "3" } }, { "body": "<p>Due the recursive nature of the file system and the limited deep of directory tree, you can use a recursive function to do the work. The code will be more expresive and there will be less duplications.</p>\n\n<pre><code> private static void Main(string[] args) {\n System.Diagnostics.Stopwatch sw = new System.Diagnostics.Stopwatch();\n sw.Start();\n\n AppendFilesRecursively(\"c:\\\\\");\n\n sw.Stop();\n Console.WriteLine(\"Total seconds = {0}\", sw.Elapsed.TotalSeconds);\n\n\n }\n\n private static void AppendFilesRecursively(string directoryName) {\n string[] directoryArray;\n try {\n filesArray(directoryName);\n directoryArray = getDirectories(directoryName);\n }\n catch (UnauthorizedAccessException) {\n Console.WriteLine(\"Unathorized to access directory: {0}\", directoryName);\n return;\n }\n foreach (var directory in directoryArray) {\n AppendFilesRecursively(directory);\n }\n }\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T20:55:54.237", "Id": "30328", "ParentId": "30313", "Score": "2" } }, { "body": "<p>You probably want to set the folder and file names to be constants somewhere.</p>\n\n<p>I didn't worry to much about performance, besides throwing exceptions it ran pretty fast on my computer.</p>\n\n<p>All I tried to do here is simplify your main loop so that all the initialization, testing for termination, etc. were on one line.</p>\n\n<p>Often flags and break statements are not needed, and the code becomes shorter and cleaner:</p>\n\n<pre><code>List&lt;string&gt; subDirectories = new List&lt;string&gt;();\nfor (string[] directoryArray = getDirectories(\"C:\\\\\"); \n directoryArray.Count() &gt; 0; directoryArray = subDirectories.ToArray())\n{\n foreach (string directoryName in directoryArray)\n {\n processSubFolder(subDirectories, directoryName);\n }\n}\n\n// wait for input before exiting\n</code></pre>\n\n<p>Also I extracted this helper method:</p>\n\n<pre><code>private static void processSubFolder(List&lt;string&gt; subDirectories, string directoryName)\n{\n try\n {\n filesArray(directoryName);\n subDirectories.AddRange(getDirectories(directoryName));\n }\n catch (Exception)\n {\n Console.WriteLine(\"Unathorized to access directory: {0}\", directoryName);\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T21:11:12.150", "Id": "30331", "ParentId": "30313", "Score": "0" } }, { "body": "<p>This looks like a job for <strong>Separation of Concerns</strong>. Split up into four classes - one which can gather all directory names given a root path, one which can gather up files for a given directory path, one which integrates the two, gathering all files for all directories and finally, one which can send those to an output file. Also interfaced for unit testability.</p>\n\n<pre><code>public interface IDirectoryGatherer\n{\n TextWriter Writer\n {\n get;\n }\n\n IEnumerable&lt;string&gt; Directories\n {\n get;\n }\n\n void Gather();\n}\n\npublic sealed class DirectoryGatherer : IDirectoryGatherer\n{\n private readonly string path;\n\n private readonly TextWriter writer;\n\n private readonly List&lt;string&gt; directories = new List&lt;string&gt;();\n\n public DirectoryGatherer(string path, TextWriter writer)\n {\n this.path = path;\n this.writer = writer;\n }\n\n public TextWriter Writer\n {\n get\n {\n return this.writer;\n }\n }\n\n public IEnumerable&lt;string&gt; Directories\n {\n get\n {\n return this.directories;\n }\n }\n\n public void Gather()\n {\n try\n {\n this.directories.AddRange(Directory.GetDirectories(this.path));\n }\n catch (UnauthorizedAccessException)\n {\n this.writer.WriteLine(\"Unauthorized to access directory: {0}\", this.path);\n }\n catch (DirectoryNotFoundException)\n {\n this.writer.WriteLine(\"Directory {0} not found\", this.path);\n }\n\n var gatherers = this.directories.Select(directory =&gt; new DirectoryGatherer(directory, this.writer)).ToList();\n\n for (var i = 0; i &lt; gatherers.Count; i++)\n {\n gatherers[i].Gather();\n this.directories.AddRange(gatherers[i].Directories);\n }\n }\n}\n\npublic interface IFileGatherer\n{\n IEnumerable&lt;string&gt; Files\n {\n get;\n }\n\n void Gather();\n}\n\npublic sealed class FileGatherer : IFileGatherer\n{\n private readonly string path;\n\n private readonly TextWriter writer;\n\n private string[] files;\n\n public FileGatherer(string path, TextWriter writer)\n {\n this.path = path;\n this.writer = writer;\n }\n\n public IEnumerable&lt;string&gt; Files\n {\n get\n {\n return this.files ?? Enumerable.Empty&lt;string&gt;();\n }\n }\n\n public void Gather()\n {\n try\n {\n this.files = Directory.GetFiles(this.path);\n }\n catch (UnauthorizedAccessException)\n {\n this.writer.WriteLine(\"Unauthorized to access directory: {0}\", this.path);\n }\n catch (DirectoryNotFoundException)\n {\n this.writer.WriteLine(\"Directory {0} not found\", this.path);\n }\n }\n}\n\npublic interface IFilesCollection\n{\n IEnumerable&lt;string&gt; Files\n {\n get;\n }\n\n void Gather();\n}\n\npublic sealed class FilesCollection : IFilesCollection\n{\n private readonly IDirectoryGatherer directoryGatherer;\n\n private readonly List&lt;string&gt; files = new List&lt;string&gt;();\n\n public FilesCollection(IDirectoryGatherer directoryGatherer)\n {\n this.directoryGatherer = directoryGatherer;\n }\n\n public IEnumerable&lt;string&gt; Files\n {\n get\n {\n return this.files;\n }\n }\n\n public void Gather()\n {\n this.directoryGatherer.Gather();\n foreach (var fileGatherer in this.directoryGatherer.Directories.Select(directory =&gt; new FileGatherer(directory, this.directoryGatherer.Writer)))\n {\n fileGatherer.Gather();\n this.files.AddRange(fileGatherer.Files);\n }\n }\n}\n\npublic interface IStringsWriter\n{\n void Write();\n}\n\npublic sealed class StringsWriter : IStringsWriter\n{\n private readonly string fileName;\n\n private readonly IEnumerable&lt;string&gt; strings;\n\n public StringsWriter(string fileName, IEnumerable&lt;string&gt; strings)\n {\n this.fileName = fileName;\n this.strings = strings;\n }\n\n public void Write()\n {\n // Append fileArray to current .txt document\n using (var file = new StreamWriter(this.fileName, true))\n {\n foreach (var s in this.strings)\n {\n file.WriteLine(s);\n }\n }\n }\n}\n\ninternal static class Program\n{\n private static void Main()\n {\n var t1 = Stopwatch.StartNew();\n\n File.WriteAllLines(@\"C:\\ComputerFiles.txt\", new[] { \"------LIST OF ALL COMPUTER FILES------\" });\n\n // Get files in c directory; append to .txt file\n // Get array of primary directories in C drive\n IDirectoryGatherer directoryGatherer = new DirectoryGatherer(@\"C:\\\", Console.Out);\n IFilesCollection allFiles = new FilesCollection(directoryGatherer);\n\n allFiles.Gather();\n\n IStringsWriter writer = new StringsWriter(@\"C:\\ComputerFiles.txt\", allFiles.Files);\n\n writer.Write();\n\n // wait for input before exiting\n Console.WriteLine(\"Total seconds = {0}\", t1.Elapsed.TotalSeconds);\n Console.WriteLine(\"Press enter to finish\");\n Console.ReadLine();\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T02:29:07.180", "Id": "30340", "ParentId": "30313", "Score": "1" } }, { "body": "<p>Open console and type:</p>\n\n<pre><code>TREE C:\\\n</code></pre>\n\n<p>To see not only dirs but files:</p>\n\n<pre><code>TREE /F C:\\\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:04:34.167", "Id": "30359", "ParentId": "30313", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T15:21:52.133", "Id": "30313", "Score": "3", "Tags": [ "c#", "search" ], "Title": "Writing out names of files on local C drive to a text document" }
30313
<p>This is an Android app and there is a <code>EditText</code> box, and I need to accept multiple types of inputs one after another in order. This order is predefined. On <code>USER_INP_NAME</code> object <code>newUser</code> is created. After this multiple properties are set with this object. Finally on <code>USER_INP_STATE</code> the object is added to a list. This cycle repeats. </p> <p>I am a "C" programmer, so this is coded in procedure-oriented manner. The switch case is looking ugly for now. Is there a better solution to do this ?</p> <pre><code>userInputs.setOnKeyListener(new OnKeyListener() { @Override public boolean onKey(View v, int keyCode, KeyEvent event) { if (event.getAction() == KeyEvent.ACTION_DOWN) { switch (keyCode) { case KeyEvent.KEYCODE_ENTER: int val = (Integer) userInputs.getTag(); switch (val) { case USER_INP_NAME: newUser = new Users(); newUser.setUsersName(userInputs.getText() .toString()); userInputs.setTag(USER_INP_NUMBER); userInputs.setText(""); userInputs.setHint("User Name"); break; case USER_INP_NUMBER: newUser.setUnitWeight(Integer .parseInt(userInputs.getText().toString())); userInputs.setTag(USER_INP_STATE); userInputs.setText(""); userInputs.setHint("User Number"); break; case USER_INP_STATE: newUser.setShelfLife(Integer .parseInt(userInputs.getText().toString())); userInputs.setTag(USER_INP_NAME); userInputs.setText(""); userInputs.setHint("User State"); uList.add(newUser); adapter.notifyDataSetChanged(); break; default: break; } default: break; } } return false; } }); </code></pre>
[]
[ { "body": "<p>I think I would consider using three controls to achieve this and resetting their visibility on submission.</p>\n\n<p>Reusing whatever you have used to create the userInputs control, rename that to nameInput and create two others weightInput and shelfLifeInput. Importantly when creating the other two controls set their visibility.<br/><br/>\n<strong>In XML:</strong></p>\n\n<pre><code>&lt;TextView\n android:id=\"@+id/weightInput\"\n android:layout_width=\"fill_parent\"\n android:layout_height=\"wrap_content\"\n android:text=\"\"\n android:hint=\"@string/weightHint\"\n android:visibility=\"gone\" /&gt;\n</code></pre>\n\n<p><br/><strong>or programatically:</strong><br/></p>\n\n<pre><code>weightInput.setVisibility(View.GONE);\n</code></pre>\n\n<p>It is import to use View.GONE as opposed to View.HIDDEN as a HIDDEN control still takes up space in the page.</p>\n\n<p>Each of your three inputs can have a handler similar to the one you have created above, but now each handler performs a slightly different function.<br/><br/>\n<strong>Name Input:</strong></p>\n\n<pre><code>userInput.setOnKeyListener(new OnKeyListener() {\n\n @Override\n public boolean onKey(View v, int keyCode, KeyEvent event) {\n if (event.getAction() == KeyEvent.ACTION_DOWN) {\n switch (keyCode) {\n case KeyEvent.KEYCODE_ENTER:\n userInput.setVisibility(View.GONE);\n weightInput.setVisibility(View.VISIBLE);\n break;\n default:\n break;\n }\n }\n return false;\n }\n });\n</code></pre>\n\n<p><strong>Weight Input:</strong></p>\n\n<pre><code>weightInput.setOnKeyListener(new OnKeyListener() {\n\n @Override\n public boolean onKey(View v, int keyCode, KeyEvent event) {\n if (event.getAction() == KeyEvent.ACTION_DOWN) {\n switch (keyCode) {\n case KeyEvent.KEYCODE_ENTER:\n weightInput.setVisibility(View.GONE);\n shelfLifeInput.setVisibility(View.VISIBLE);\n break;\n default:\n break;\n }\n }\n return false;\n }\n });\n</code></pre>\n\n<p><strong>Shelf Life Input:</strong></p>\n\n<pre><code>shelfLifeInput.setOnKeyListener(new OnKeyListener() {\n\n @Override\n public boolean onKey(View v, int keyCode, KeyEvent event) {\n if (event.getAction() == KeyEvent.ACTION_DOWN) {\n switch (keyCode) {\n case KeyEvent.KEYCODE_ENTER:\n //this can probably be locally scoped now.\n //Users is an odd name for what this class appears to be.\n //assume validation will have been added.\n Users newUser = new Users();\n newUser.setUsersName(userInput.getText().toString());\n newUser.setUnitWeight(Integer.parseInt(weightInput.getText().toString()));\n newUser.setShelfLife(Integer.parseInt(shelfLifeInput.getText().toString()));\n uList.add(newUser);\n adapter.notifyDataSetChanged();\n shelfLifeInput.setVisibility(View.GONE);\n userInput.setVisibility(View.VISIBLE);\n\n break;\n default:\n break;\n }\n }\n return false;\n }\n }); \n</code></pre>\n\n<p>You would probably want to break the user creation code out into a separate function so that it is not tightly bound with the view, but for brevity I have followed more closely to your original code. </p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T09:28:41.343", "Id": "30353", "ParentId": "30321", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T17:06:01.063", "Id": "30321", "Score": "1", "Tags": [ "java", "object-oriented", "android" ], "Title": "Getting multiple inputs from single EditText" }
30321
<p>I am calling a C library via P/Invoke. That library needs to be called in sucession with an increasing <code>unsigned int</code>, and returns a pointer. That pointer is then mapped to a managed type, until it returns a <code>NULL</code> pointer. </p> <p>In C, the idiomatic way to write it, is probably <code>for(i=0;;i++)</code>, but what is the most idiomatic way to write it in C#?</p> <p>Currently it is using a <code>do {} while</code> loop, as in my opinion, this is the clearest way to show that this loop will repeat until <code>newPort</code> is <code>null</code>.</p> <pre><code>static IEnumerable&lt;Port&gt; GetPorts () { List&lt;Port&gt; ports = new List&lt;Port&gt;(); uint i = 0; Port newPort; do { // This calls an C library, and maps the returned pointer // to the Port class newPort = GetPortData (i); if (newPort != null){ ports.Add (newPort); } i++; } while(newPort != null); return ports; } </code></pre> <p>On the other hand, the variables <code>i</code> and <code>newPort</code> are only used inside the loop, so using <code>for</code> would be another solution, but it does not clearly show the breaking condition.</p> <pre><code> for (uint i = 0; ; i++) { Port newPort = GetPortData (i); if (newPort == null) { break; } ports.Add (newPort); } </code></pre> <p>Which version should I use?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T21:52:53.373", "Id": "48207", "Score": "1", "body": "BTW, this method might be a good candidate for `yield return`." } ]
[ { "body": "<p>I think the for loop can show the \"breaking condition\" like this:</p>\n\n<pre><code>for (uint i = 0; (newPort = GetPortData(i)) != null; i++) {\n ports.Add (newPort);\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T21:49:29.047", "Id": "48206", "Score": "2", "body": "In my opinion, an expression should be almost always used for its value or for its side effects, but not both." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T21:59:12.617", "Id": "48209", "Score": "0", "body": "I updated the answer. Thanks for your comment!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T22:28:45.597", "Id": "48210", "Score": "1", "body": "Not sure if I'm a fan of calling GetPortData twice. What happens if that method is expensive???" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T19:22:43.977", "Id": "30324", "ParentId": "30322", "Score": "2" } } ]
{ "AcceptedAnswerId": "30324", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T19:00:45.360", "Id": "30322", "Score": "3", "Tags": [ "c#" ], "Title": "Idiomatic loop and break condition" }
30322
<p>This module is dependent upon a utility module I previously posted:</p> <p><a href="https://codereview.stackexchange.com/questions/30189/general-feedback-on-utility-module">General feedback on utility module</a></p> <p>I'm looking for general feedback on how to make this useful to other people. This is a subset of jQuery with some additions, and what I feel are improvements.</p> <p>The code passes jslint and minifies well with closure.</p> <pre><code>/******************************************************************************* **DOM *******************************************************************************/ (function (win, doc) { "use strict"; // p(R)ivate propeties go here var $R = {}, // (P)ublic properties go here $P = function (selector) { return new $R.Constructor(selector); }, // (D)ependencies go here $D; /******************************************************************************/ // GLOBAL MANAGEMENT $D = (function manageGlobal() { $R.g = '$'; if (win[$R.g] &amp;&amp; win[$R.g].molist &amp;&amp; win[$R.g].molist.utility) { win[$R.g].molist.dom = true; } else { throw "dom requires utility module"; } return win[$R.g]; }()); /******************************************************************************/ // DOM RETREIVAL $P.el = function (selector_native) { if (selector_native) { var type = selector_native.match(/^(@|#|\.)([\x20-\x7E]+)$/); if (!type || !type[1] || !type[2]) { return {error: "mal-formed selector"}; } var type1 = type[1]; var type2 = type[2]; if (type1 === '#') { return doc.getElementById(type2); } if (type1 === '.' &amp;&amp; doc.getElementsByClassName) { return doc.getElementsByClassName(type2); } if (type1 === '@') { return doc.getElementsByName(type2); } } }; /******************************************************************************/ // DOM REPORTING $P.aZindex = function () { var z_arr = {}, all_el = document.body.getElementsByTagName("*"), i, len, cur, style, z_index; for (i = 0, len = all_el.length; i &lt; len; i++) { cur = all_el[i]; style = win.getComputedStyle(cur); z_index = style.getPropertyValue("z-index"); if (z_index !== "auto") { z_arr[i] = [cur.id, cur.tagName, cur.className, z_index]; } } return z_arr; }; $P.aDOM = function (node, func) { var arr = [], level = 1; walk(node, func); function walk(node, func) { if (typeof func === 'function') { func(node); } node = node.firstChild; while (node) { if (node.id) { arr.push(node.id); // console.log(node.id); } level++; walk(node, func); node = node.nextSibling; } level--; if (level === 0) { arr.sort(); } } }; /******************************************************************************/ // DOM MANIPULATION $P.removeElement = function (el) { if (el &amp;&amp; el.parentNode) { return el.parentNode.removeChild(el); } return null; }; /* */ $P.insertAfter = function (el, ref) { if (el) { return ref.parentNode.insertBefore(el, ref.nextSibling); } return null; }; $P.isElement = function (obj) { return !!(obj &amp;&amp; obj.nodeType === 1); }; /* */ // update to conform to util style $P.eachChild = function (ref_el, func, con) { if (ref_el) { var iter_el = ref_el.firstChild, result; do { result = func.call(con, iter_el, ref_el); if (result !== undefined) { return result; } iter_el = iter_el.nextSibling; } while (iter_el !== null); } return null; }; $P.HTMLToElement = function (html) { var div = document.createElement('div'); div.innerHTML = html; return div.firstChild; }; $P.getData = function (id) { var data, obj = {}, el = document.getElementById(id); if (el.dataset) { $D.someKey(el.dataset, function (val, key) { obj[key] = val; }); } else { data = $D.filter(el.attributes, function (at) { return (/^data-/).test(at.name); }); $D.someIndex(data, function (val, i) { obj[data[i].name.slice(5)] = val.value; }); } return obj; }; /******************************************************************************/ // MANIPULATE CLASSNAME ATTRIBUTE $R.hasClass = function (el, name) { return new RegExp('(\\s|^)' + name, 'g').test(el.className); }; $R.toggleNS = function (el, ns, prop) { $P.eachString(el.className, function (val) { if (val.match(/toggle_/)) { var names = val.split(/_/); if (names[1] === ns &amp;&amp; names[2] !== prop) { $P.removeClass(el, val); } } }); }; $P.addClass = function (el, name) { if (!$R.hasClass(el, name)) { el.className += (el.className ? ' ' : '') + name; } var temp = name.match(/toggle_(\w+)_(\w+)/); if (temp) { $R.toggleNS(el, temp[1], temp[2]); return; } }; $P.removeClass = function (el, name) { el.className = name ? el.className.replace(new RegExp('(\\s|^)' + name, 'g'), '') : ''; }; /******************************************************************************/ // CONSTRUCTOR $R.Constructor = function (selector) { var type, type1, type2, temp, obj_type; // $D object detected if (selector instanceof $R.Constructor) { return selector; } // window object detected if (selector === win) { this[0] = selector; return this; } // document object detected if (selector === doc) { this[0] = selector; return this; } // element object detected if ($P.isElement(selector)) { this[0] = selector; return this; } // only strings should be left if (selector) { obj_type = $D.getType(selector); } if (obj_type !== 'String') { return this; } // selector is a symbol follwed by asci type = selector.match(/^(@|#|\.)([\x20-\x7E]+)$/); if (!type) { return this; } type1 = type[1]; type2 = type[2]; // id if (type1 === '#') { temp = doc.getElementById(type2); if (!temp) { return this; } this[0] = temp; return this; } // class if (type1 === '.' &amp;&amp; doc.getElementsByClassName) { temp = doc.getElementsByClassName(type2); if (!temp) { return this; } $D.someIndex(temp, function (val, index) { this[index] = val; }, this); return this; } // name if (type1 === '@') { temp = doc.getElementsByName(type2); if (!temp) { return this; } $D.someIndex(temp, function (val, index) { this[index] = val; }, this); return this; } }; $R.proto = $R.Constructor.prototype; /******************************************************************************/ // EFFECTS $R.proto.fade = function (direction, max_time, callback) { var privates = {}, self = this; // initialize privates.elapsed = 0; privates.GRANULARITY = 10; if (privates.timer_id) { win.clearInterval(privates.timer_id); } (function next() { privates.elapsed += privates.GRANULARITY; if (!privates.timer_id) { privates.timer_id = win.setInterval(next, privates.GRANULARITY); } if (direction === 'up') { $D.someKey(self, function (val) { val.style.opacity = privates.elapsed / max_time; }); } else if (direction === 'down') { $D.someKey(self, function (val) { val.style.opacity = (max_time - privates.elapsed) / max_time; }); } if (privates.elapsed &gt;= max_time) { if (callback) { callback(); } win.clearInterval(privates.timer_id); } }()); }; $P.peakOut = function (elem, offset, delay, callback) { var privates = {}; // constants initialization privates.RADIX = 10; privates.GRAN_TIME = 15; privates.GRAN_DIST = 1; privates.UNITS = 'px'; // privates initialization privates.el = elem; privates.start = parseInt($P.getComputedStyle(privates.el).getPropertyValue("top"), privates.RADIX); privates.status = 'down'; privates.end = privates.start + offset; privates.current = privates.start; privates.id = null; (function next() { if ((privates.status === 'down') &amp;&amp; (privates.current &lt; privates.end)) { privates.current += privates.GRAN_DIST; privates.el.style.top = privates.current + privates.UNITS; if (!privates.id) { privates.id = $P.setInterval(next, privates.GRAN_TIME); } } else if ((privates.status === 'down') &amp;&amp; (privates.current === privates.end)) { privates.status = 'up'; $R.resetInterval(privates); $P.setTimeout(next, delay); } else if ((privates.status === 'up') &amp;&amp; (privates.current &gt; privates.start)) { privates.current -= privates.GRAN_DIST; privates.el.style.top = privates.current + privates.UNITS; if (!privates.id) { privates.id = $P.setInterval(next, privates.GRAN_TIME); } } else if ((privates.status === 'up') &amp;&amp; (privates.current === privates.start)) { $R.resetInterval(privates); callback(); } }()); }; $R.resetInterval = function (privates) { $P.clearInterval(privates.id); privates.id = 0; }; $R.expandFont = function (direction, max_time) { var self = this, el_prim = self[0], privates = {}; if (el_prim.timer_id) { return; } el_prim.style.fontSize = $P.getComputedStyle(el_prim, null).getPropertyValue("font-size"); privates.final_size = parseInt(el_prim.style.fontSize, privates.RADIX); privates.GRANULARITY = 10; privates.time_elapsed = 0; (function next() { $D.someKey(self, function (val) { if (direction === 'up') { val.style.fontSize = ((privates.time_elapsed / max_time) * privates.final_size) + 'px'; } else if (direction === 'down') { val.style.fontSize = ((max_time - privates.time_elapsed) / max_time) + 'px'; } }); privates.time_elapsed += privates.GRANULARITY; // completed, do not call next if (el_prim.timer_id_done) { $P.clearTimeout(el_prim.timer_id); el_prim.timer_id = undefined; el_prim.timer_id_done = undefined; // intermediate call to next } else if (privates.time_elapsed &lt; max_time) { el_prim.timer_id = $P.setTimeout(next, privates.GRANULARITY); // normalizing call to guarante (elapsed === max) } else if (privates.time_elapsed &gt;= max_time) { el_prim.timer_id = $P.setTimeout(next, privates.GRANULARITY); el_prim.timer_id_done = true; privates.time_elapsed = max_time; } }()); }; $R.proto.expandFont = function (direction, max_time, big_size) { return $R.expandFont.call(this, direction, max_time, big_size); }; $P.expandFont = (function () { return function (element, direction, max_time, big_size) { var temp = []; temp[0] = element; $R.expandFont.call(temp, direction, max_time, big_size); }; }()); /******************************************************************************/ // EVENTS $R.functionNull = function () { return undefined; }; // createEvent $R.createEvent = function () { if (doc.createEvent) { return function (type) { var event = doc.createEvent("HTMLEvents"); event.initEvent(type, true, false); $D.someKey(this, function (val) { val.dispatchEvent(event); }); }; } if (doc.createEventObject) { return function (type) { var event = doc.createEventObject(); event.eventType = type; $D.someKey(this, function (val) { val.fireEvent('on' + type, event); }); }; } return $R.functionNull; }; $R.proto.createEvent = function (type) { return $R.createEvent.call(this, type); }; $P.createEvent = (function () { return function (element, type) { var temp = []; temp[0] = element; $R.createEvent.call(temp, type); }; }()); // addEvent $R.addEvent = (function () { if (win.addEventListener) { return function (type, callback) { $D.someKey(this, function (val) { val.addEventListener(type, callback); }); }; } if (win.attachEvent) { return function (type, callback) { $D.someKey(this, function (val) { val.attachEvent('on' + type, callback); }); }; } return $R.functionNull; }()); $R.proto.addEvent = function (type, callback) { return $R.addEvent.call(this, type, callback); }; $P.addEvent = (function () { return function (element, type, callback) { var temp = []; temp[0] = element; $R.addEvent.call(temp, type, callback); }; }()); // removeEvent $R.proto.removeEvent = (function () { if (win.removeEventListener) { return function (type, callback) { $D.someKey(this, function (val) { val.removeEventListener(type, callback); }); }; } if (win.detachEvent) { return function (type, callback) { $D.someKey(this, function (val) { val.detachEvent('on' + type, callback); }); }; } return $R.functionNull; }()); $R.proto.removeEvent = function (type, callback) { return $R.removeEvent.call(this, type, callback); }; $P.removeEvent = (function () { return function (element, type, callback) { var temp = []; temp[0] = element; $R.removeEvent.call(temp, type, callback); }; }()); /******************************************************************************/ // AJAX // onreadystatechange,this.readyState === 4 removed $P.ajax = function (config_ajax) { var xhr; // get if (config_ajax.type === 'get') { xhr = new win.XMLHttpRequest(); xhr.open('GET', config_ajax.url, true); xhr.onload = function () { if (this.status === 200) { config_ajax.callback(xhr.responseText); } }; xhr.send(null); } // post if (config_ajax.type === 'post') { xhr = new win.XMLHttpRequest(); xhr.open("POST", config_ajax.url, true); xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); xhr.onload = function () { if (this.status === 200) { config_ajax.callback(xhr.responseText); } }; xhr.send(config_ajax.data); } // post for form_data if (config_ajax.type === 'multi') { xhr = new win.XMLHttpRequest(); xhr.open("POST", config_ajax.url, true); xhr.onload = function () { if (this.status === 200) { config_ajax.callback(xhr.responseText); } }; xhr.send(config_ajax.data); } }; $R.Queue = (function () { var queue = [], publik = {}; function getIndexFromToken(callback) { var hold; $D.someIndex(queue, function (val, index) { if (val.callback === callback) { hold = index; return index; } }); return hold; } function getBlockedProperty(item) { var blocked; if (item) { blocked = item.blocked; } else { blocked = false; } return blocked; } publik.addItem = function (callback) { var temp = {}; temp.blocked = false; temp.callback = callback; temp.response_text = null; queue.push(temp); }; publik.itemCompleted = function (response_text, callback) { var index, item, blocked; index = getIndexFromToken(callback); if (index !== 0) { queue[index].blocked = true; queue[index].response_text = response_text; } else { item = queue.shift(); item.callback(response_text); blocked = getBlockedProperty(queue[0]); while (blocked) { item = queue.shift(); item.callback(item.response_text); blocked = getBlockedProperty(queue[0]); } } }; return publik; }()); $P.serialAjax = function (source, callback) { $R.Queue.addItem(callback); $P.ajax({ type: 'get', url: source, callback: function (response_text) { $R.Queue.itemCompleted(response_text, callback); } }); }; /******************************************************************************/ // WRAPS // timeouts $P.setTimeout = function () { return win.setTimeout.apply(win, arguments); }; $P.clearTimeout = function () { return win.clearTimeout.apply(win, arguments); }; $P.setInterval = function () { return win.setInterval.apply(win, arguments); }; $P.clearInterval = function () { return win.clearInterval.apply(win, arguments); }; // styles $P.getComputedStyle = function () { return win.getComputedStyle.apply(win, arguments); }; // fragments $P.createDocumentFragment = function () { return doc.createDocumentFragment.apply(doc, arguments); }; // elements $P.createElement = function () { return doc.createElement.apply(doc, arguments); }; // oo style $P.FormData = win.FormData; $P.FileReader = win.FileReader; // other style $P.localStorage = win.localStorage; $P.sessionStorage = win.sessionStorage; /******************************************************************************/ // LOG $P.log = function (obj) { var logger, type, temp, completed; // wrap win.console to protect from IE // bind to satisfy Safari if (win.console) { logger = win.console.log.bind(win.console); } else { return; } // validation type = $D.getType(obj); if (!type) { logger("Object did not stringify"); return; } // host objects, event ... if (type === 'Event') { logger('LOG|host|event&gt;'); logger(obj); return; } // library objects if (win.jQuery &amp;&amp; (obj instanceof win.jQuery)) { logger('LOG|library|jquery&gt;'); logger(obj); return; } // language objects $D.someIndex(['Arguments', 'Array', 'Object'], function (val) { if (type === val) { try { temp = JSON.stringify(obj, null, 1); } catch (e) { temp = false; } if (temp) { logger('LOG|language|' + type + '&gt;'); logger(temp); } else { logger('LOG|language|' + type + '&gt;'); logger(obj); } completed = true; } }); if (completed) { return; } $D.someIndex(['Boolean', 'Date', 'Error', 'Function', 'JSON', 'Math', 'Number', 'Null', 'RegExp', 'String', 'Undefined'], function (val) { if (type === val) { logger('LOG|language|' + type + '&gt;'); logger(obj); completed = true; } }); if (completed) { return; } // remaining logger('LOG|not_implemented|&gt;'); logger(obj); return; }; win[$R.g] = $D.extendSafe($P, $D); }(window, window.document)); </code></pre>
[]
[ { "body": "<p>From a once over:</p>\n\n<ul>\n<li>Unfortunate naming\n\n<ul>\n<li><code>win[$R.g].molist.dom</code> &lt;- <code>$R</code> and <code>g</code> and <code>molist</code> are unfortunate</li>\n<li><code>function (ref_el, func, con)</code> &lt;- <code>con</code> ?</li>\n<li><code>$P.HTMLToElement</code> &lt;- I would go for <code>$P.HTMLToBlockElement</code> since you hardcode <code>div</code></li>\n<li><code>win[$R.g] = $D.extendSafe($P, $D);</code> &lt;- No idea what this would do</li>\n</ul></li>\n<li>Regex expressions are hard to parse for many developers, you should document what they do and ideally provide an example match</li>\n<li>I would not simply <code>throw</code> a string, <a href=\"https://stackoverflow.com/a/8987321/7602\">I would throw an error of the right type</a> </li>\n<li>Avoid anonymous functions, your dont want your stacktrace filled with anonymous functions</li>\n<li><p>This is not good because the comment is pointless, I see that you found the windows/document/ object, but why are you doing what you do and why copy paste it ?</p>\n\n<pre><code>// window object detected\n\nif (selector === win) {\n this[0] = selector;\n return this;\n}\n\n// document object detected\n\nif (selector === doc) {\n this[0] = selector;\n return this;\n}\n\n// element object detected\n\nif ($P.isElement(selector)) {\n this[0] = selector;\n return this;\n}\n</code></pre>\n\n<p>Go for something like</p>\n\n<pre><code>//window, document or element object detected\n//enlightened comment as to why I set this[0] and return this \nif (selector === win || selector === doc || $P.isElement(selector)) {\n this[0] = selector;\n return this;\n}\n</code></pre></li>\n<li>Your effects functions need way more commenting on what they do</li>\n<li><code>$P.ajax</code> does not deal with failure at all, you should address that</li>\n<li><code>config_ajax.callback(xhr.responseText);</code> &lt;- Why not return <code>xhr</code> ?</li>\n<li>You are not consistently using lowerCamelCase</li>\n<li><code>// WRAPS</code> &lt;- This part seems completely pointless, why wrap those functions?</li>\n</ul>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-30T18:28:00.117", "Id": "68428", "ParentId": "30327", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T20:42:52.320", "Id": "30327", "Score": "3", "Tags": [ "javascript" ], "Title": "General feedback on DOM module" }
30327
<p>This is my table model code style:</p> <pre><code>public class MyModel extends DefaultTableModel { static Vector data = new Vector(); static Vector column = new Vector(); Connection conn; Statement statement; ResultSet result; public MyModel() { super(data, column); try { conn = DriverManager.getConnection(...); statement = conn.createStatement(); result = statement.executeQuery("Select * from table"); int col = result.getMetaData().getColumnCount(); for (int i = 1; i &lt;= col; i++) { column.add(result.getMetaData().getColumnName(i)); } while (result.next()) { Vector newRow = new Vector(col); for (int i = 1; i &lt;= col; i++) { newRow.add(result.getString(i)); } data.add(newRow); } } catch (SQLException e) { e.printStackTrace(); } } // create methods for remove and add and edit a JTable selected row } //My GUI class that show jtable on own </code></pre> <p>Is this best way?</p> <p>What is this way problems?</p> <p>Any idea to be better?</p>
[]
[ { "body": "<p>This way your software is highly coupled. I can see three big responsibilities in it:</p>\n\n<ul>\n<li>Get data from db</li>\n<li>Format data in \"TableModel way\"</li>\n<li>Create TableModel</li>\n</ul>\n\n<p>Let's create a class to get data. I don't like the idea of let other classes deal with objects from jdbc api, so this class will format data too:</p>\n\n<pre><code>public class TableData {\n\n public TableContent getData() {\n Vector&lt;String&gt; headers = new Vector&lt;String&gt;();\n Vector&lt;Vector&lt;String&gt;&gt; content = new Vector&lt;Vector&lt;String&gt;&gt;();\n\n try {\n Connection conn = DriverManager.getConnection(\"\");\n Statement statement = conn.createStatement();\n ResultSet rs = statement.executeQuery(\"Select * from table\");\n\n headers = buildHeaders(rs);\n content = buildContent(rs);\n\n } catch (SQLException e) {\n e.printStackTrace();\n }\n\n return new TableContent(headers, content);\n }\n\n private Vector&lt;String&gt; buildHeaders(final ResultSet rs) throws SQLException {\n Vector&lt;String&gt; headers = new Vector&lt;String&gt;();\n\n int col = rs.getMetaData().getColumnCount();\n for (int i = 1; i &lt;= col; i++) {\n headers.add(rs.getMetaData().getColumnName(i));\n }\n return headers;\n }\n\n private Vector&lt;Vector&lt;String&gt;&gt; buildContent(final ResultSet rs) throws SQLException {\n Vector&lt;Vector&lt;String&gt;&gt; content = new Vector&lt;Vector&lt;String&gt;&gt;();\n\n while (rs.next()) {\n int col = rs.getMetaData().getColumnCount();\n Vector&lt;String&gt; newRow = new Vector&lt;String&gt;(col);\n\n for (int i = 1; i &lt;= col; i++) {\n newRow.add(rs.getString(i));\n }\n content.add(newRow);\n }\n return content;\n }\n}\n</code></pre>\n\n<p>I've created TableContent just to wrap the result:</p>\n\n<pre><code>public class TableContent {\n\n private final Vector&lt;String&gt; headers;\n private final Vector&lt;Vector&lt;String&gt;&gt; content;\n\n public TableContent(final Vector&lt;String&gt; headers, final Vector&lt;Vector&lt;String&gt;&gt; content) {\n this.headers = headers;\n this.content = content;\n }\n\n public Vector&lt;String&gt; headers() {\n return headers;\n }\n\n public Vector&lt;Vector&lt;String&gt;&gt; content() {\n return content;\n }\n}\n</code></pre>\n\n<p>Now, the TableModel. That way you don't need to extend the class DefaultTableModel, you can simply instantiate one:</p>\n\n<pre><code>TableContent data = new TableData().getData();\nnew DefaultTableModel(data.headers(), data.content());\n</code></pre>\n\n<p>The class TableData still has a problem, the ideal would be to receive the Connection by the constructor, because without it, it's not possible to test the class with unit tests. I didn't wanna make the solution more difficult.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T15:34:29.193", "Id": "48290", "Score": "0", "body": "Thanks Juliano , Great help, I am testing your solution..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T17:40:39.800", "Id": "48306", "Score": "2", "body": "Rather than \"getting\" the data from the `TableData` class, consider `create` methods: `DefaultTableModel dtm = new TableData().createTableContent().createTableModel()`. No accessors necessary, in keeping with the concepts of *information hiding* and *encapsulation*." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T20:31:30.677", "Id": "48793", "Score": "0", "body": "@DaveJarvis Nice, I want to add my optional methods (like add, remove, edit) to my model. before i added them to my extended from `DefaultTableModel` Class, Now how can i define this methods and where should do it?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T01:34:00.627", "Id": "48805", "Score": "0", "body": "@APoliteBoy: I recommend asking another question, rather than asking a question in comments. You'll get more people reading it. :-)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-03T20:25:39.937", "Id": "48868", "Score": "0", "body": "@DaveJarvis Ok.." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T22:30:50.057", "Id": "30335", "ParentId": "30330", "Score": "5" } }, { "body": "<ol>\n<li><p>I'd use a simple <code>List</code> or <code>ArrayList</code> here. <a href=\"https://stackoverflow.com/q/1386275/843804\">Vector is considered obsolete</a>.</p>\n\n<p>(Make sure that accessing is properly synchronized if they're used by multiple threads.)</p></li>\n<li><p><code>printStackTrace()</code> only <code>catch</code> clauses just postpone the errors and usually makes debugging harder. Clients of these class might use these values (or the empty collections) as valid data. You should handle the exception or throw another one with a helpful message. (<em>The Pragmatic Programmer: From Journeyman to Master</em> by <em>Andrew Hunt</em> and <em>David Thomas</em>: <em>Dead Programs Tell No Lies</em>.)</p></li>\n<li><p>Scope of these variables could be smaller:</p>\n\n<blockquote>\n<pre><code>Connection conn;\nStatement statement;\nResultSet result;\n</code></pre>\n</blockquote>\n\n<p>You could declare them inside the constructor. (<em>Effective Java, Second Edition, Item 45: Minimize the scope of local variables</em>)</p></li>\n<li><p>I think creating a local variable for <code>ResultSetMetaData</code> would be a little bit more readable:</p>\n\n<pre><code>ResultSetMetaData metaData = result.getMetaData();\nint col = metaData.getColumnCount();\nfor (int i = 1; i &lt;= col; i++) {\n column.add(metaData.getColumnName(i));\n}\n</code></pre></li>\n<li><p>Don't forget to close your <code>Connection</code>, <code>Statement</code> and <code>ResultSet</code>. See <em>Guideline 1-2: Release resources in all cases</em> in <a href=\"http://www.oracle.com/technetwork/java/seccodeguide-139067.html\" rel=\"nofollow noreferrer\">Secure Coding Guidelines for the Java Programming Language</a></p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-04-13T22:50:46.047", "Id": "47108", "ParentId": "30330", "Score": "3" } } ]
{ "AcceptedAnswerId": "30335", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T21:06:11.357", "Id": "30330", "Score": "5", "Tags": [ "java", "swing", "jdbc" ], "Title": "Table model code style" }
30330
<p>I am implementing an <a href="http://msdn.microsoft.com/en-us/library/System.Collections.IEqualityComparer.aspx" rel="nofollow">IEqualityComparer</a> for Dictionary objects and am looking for input on a couple of different approaches. I define equality in this case to be that both dictionaries contain the same set of KeyValuePair's as defined by equality of the hash value for the respective keys and values.</p> <p>The first generates a hash value by XORing all of the keys and value in both dictionaries and comparing them. The other uses the <a href="http://msdn.microsoft.com/en-us/library/bb359438.aspx" rel="nofollow">HashSet</a> collection and its <a href="http://msdn.microsoft.com/en-us/library/bb336848.aspx" rel="nofollow">SymetricExceptWith</a> method. Are these functionally equivalent and are the pros/cons to either approach or better ways to accomplish this. Both approaches are working for my test cases.</p> <p>GetHashCode approach:</p> <pre><code>class DictionaryComparer&lt;TKey, TValue&gt; : IEqualityComparer&lt;IDictionary&lt;TKey, TValue&gt;&gt; { public DictionaryComparer() { } public bool Equals(IDictionary&lt;TKey, TValue&gt; x, IDictionary&lt;TKey, TValue&gt; y) { // fail fast if count are not equal if (x.Count != y.Count) return false; return GetHashCode(x) == GetHashCode(y); } public int GetHashCode(IDictionary&lt;TKey, TValue&gt; obj) { int hash = 0; foreach (KeyValuePair&lt;TKey, TValue&gt; pair in obj) { int key = pair.Key.GetHashCode(); // key cannot be null int value = pair.Value != null ? pair.Value.GetHashCode() : 0; hash ^= ShiftAndWrap(key, 2) ^ value; } return hash; } private int ShiftAndWrap(int value, int positions) { positions = positions &amp; 0x1F; // Save the existing bit pattern, but interpret it as an unsigned integer. uint number = BitConverter.ToUInt32(BitConverter.GetBytes(value), 0); // Preserve the bits to be discarded. uint wrapped = number &gt;&gt; (32 - positions); // Shift and wrap the discarded bits. return BitConverter.ToInt32(BitConverter.GetBytes((number &lt;&lt; positions) | wrapped), 0); } } </code></pre> <p>HashSet approach:</p> <pre><code>class DictionaryComparer&lt;TKey, TValue&gt; : IEqualityComparer&lt;IDictionary&lt;TKey, TValue&gt;&gt; { public DictionaryComparer() { } public bool Equals(IDictionary&lt;TKey, TValue&gt; x, IDictionary&lt;TKey, TValue&gt; y) { if (x.Count != y.Count) return false; HashSet&lt;KeyValuePair&lt;TKey, TValue&gt;&gt; set = new HashSet&lt;KeyValuePair&lt;TKey, TValue&gt;&gt;(x); set.SymmetricExceptWith(y); return set.Count == 0; } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T21:35:35.837", "Id": "48205", "Score": "3", "body": "I think [Programmers](http://programmers.stackexchange.com/) would be a better fit for this question." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T21:56:26.157", "Id": "48208", "Score": "4", "body": "“as defined by equality of the hash value” No, no, no! You can't compare values just based on their hash codes. You need to compare them based on `Equals()` not on `GetHashCode()`. `GetHashCode()` is for use in hash tables, *nothing else*." } ]
[ { "body": "<p>A 32-bit hash returned by <code>GetHashCode</code> has 2^32 possible values, with a probability distribution dependent on the hashing function. If there are more than 2^32 possible input values then you will get collisions (see <a href=\"http://preshing.com/20110504/hash-collision-probabilities\" rel=\"nofollow noreferrer\">here</a>). And while we like to think collisions are rare, they turn up a lot more frequently than we like to think. It gets worse when people are actively <a href=\"http://arstechnica.com/business/2011/12/huge-portions-of-web-vulnerable-to-hashing-denial-of-service-attack/\" rel=\"nofollow noreferrer\">attacking you through your hashing function</a>.</p>\n\n<p>@svick is correct that you can't use a hash code to compare objects for equality. All you can be certain of (assuming a consistent hash implementation) is that two objects with different hashes are not equal. No other guarantee is given.</p>\n\n<p>Depending on the cost of generating the hashes, you might actually be better off not using them in them in this instance.</p>\n\n<p>The only really guaranteed equality test for a pair of <code>Dictionary</code> instances is to examine their contents.</p>\n\n<p>The simple shortcuts you can implement:</p>\n\n<ul>\n<li>Check if either instance is null (it happens)</li>\n<li>Check if both input <code>Dictionary</code> instances are the same instance</li>\n<li>Check if the counts differ</li>\n</ul>\n\n<p>The other slight speed improvement is to check the keys first. Often checking the keys is a faster operation than checking the values.</p>\n\n<p>Something like:</p>\n\n<pre><code>public bool Equals&lt;TKey, TValue&gt;(IDictionary&lt;TKey, TValue&gt; x, IDictionary&lt;TKey, TValue&gt; y)\n{\n // early-exit checks\n if (null == y)\n return null == x;\n if (null == x)\n return false;\n if (object.ReferenceEquals(x, y))\n return true;\n if (x.Count != y.Count)\n return false;\n\n // check keys are the same\n foreach (TKey k in x.Keys)\n if (!y.ContainsKey(k))\n return false;\n\n // check values are the same\n foreach (TKey k in x.Keys)\n if (!x[k].Equals(y[k])\n return false;\n\n return true;\n}\n</code></pre>\n\n<p>Adding a loop to check for hash inequality <em>might</em> improve the speed. Try it and see.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T01:59:23.410", "Id": "30339", "ParentId": "30332", "Score": "5" } } ]
{ "AcceptedAnswerId": "30339", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T21:13:44.653", "Id": "30332", "Score": "-1", "Tags": [ "c#", ".net", "hash-map" ], "Title": "Proper way to compare two Dictionaries" }
30332
<p>I'm rewriting an old Swing project that I did a few months ago, a fairly simple copy-cat of MS paint. I've been doing a pretty good job of keeping the code maintainable and organized, but I've hit a wall on one class. All I need is some general tips on organization on this one class.</p> <p>The way I have my program set up is that each component of my painting program (buttons for colors, eraser button, <code>JPanel</code> to paint on) is actually a relative (extended from) of another swing component class (for instance <code>PaintPanel</code>, the panel you paint on, extends JPanel, or <code>colorButton</code> is an extension of <code>JButton</code>). This just allows me to keep things encapsulated and organized. </p> <p>So, I needed a <code>JFileMenu</code> for the top of the program in order to save, open files, edit, etc. I created a new Class called <code>PaintMenuBar</code>, extended it from <code>JMenuBar</code>, and started creating the <code>JMenus</code> and <code>JMenuItems</code>. Now, each <code>JMenuItem</code> obviously needs an <code>ActionListener</code>, so I just gave each one a different <code>ActionListener</code>. I'm skeptical about this because I know it can be kind of disorganized looking. </p> <p>Basically, I just want somebody to let me know if this practice is all right, or if there is a better alternative that doesn't involve me making 20 new classes.</p> <p>Here's the entire class: </p> <pre><code>import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.JMenu; import javax.swing.JMenuBar; import javax.swing.JMenuItem; public class PaintMenuBar extends JMenuBar { private static final long serialVersionUID = 1L; JMenu fileMenu; JMenu editMenu; JMenu aboutMenu; public PaintMenuBar() { setUpFileMenu(); setUpEditMenu(); setUpAboutMenu(); } // Set up menu items &amp; such private void setUpFileMenu() { fileMenu = new JMenu("File"); // File menu items JMenuItem newMenuItem = new JMenuItem("New"); newMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); JMenuItem openMenuItem = new JMenuItem("Open"); openMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); JMenuItem saveMenuItem = new JMenuItem("Save"); saveMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); JMenuItem saveAsMenuItem = new JMenuItem("Save As"); saveAsMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); JMenuItem printMenuItem = new JMenuItem("Print"); printMenuItem.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { } }); add(fileMenu); } private void setUpEditMenu() // Create Edit Menu { editMenu = new JMenu("Edit"); } private void setUpAboutMenu() // Create About Menu { aboutMenu = new JMenu("About Paint 2.0"); } } </code></pre> <p>I am aware of some of the junk that is in this class that I still need to clean up, but just try and ignore it.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T14:10:16.043", "Id": "48274", "Score": "2", "body": "You should consider using Swing components, rather than extending Swing components. The only time you should extend a Swing component is when you want to override a method. Your menu bar class looks fine, as long as all the actionPerformed methods are short. If any of your actionPerformed methods gets long, say longer than 10 or 15 lines, you should consider creating a separate ActionListener class." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T17:38:42.107", "Id": "48305", "Score": "1", "body": "Totally agree with Gilbert's comment" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T22:06:34.393", "Id": "48328", "Score": "0", "body": "@GilbertLeBlanc Thanks for the response. If I put up the full code on GitHub or some kind of source-control, would you mind taking a look at it? Your comment has me worried that I've done a few things really wrong." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-22T14:06:20.210", "Id": "73188", "Score": "0", "body": "@GilbertLeBlanc: +1. Could you write it as an aswer?" } ]
[ { "body": "<p>+1 to <em>@Gilbert Le Blanc</em>'s comment. Creating </p>\n\n<p>I'd consider extracting out methods like <code>createOpenMenuItem()</code>, <code>createSaveMenuItem()</code>, <code>createPrintMenuItem()</code> for better readability and higher abstraction:</p>\n\n<pre><code>private JMenuItem createOpenMenuItem() {\n JMenuItem openMenuItem = new JMenuItem(\"Open\");\n openMenuItem.addActionListener(new ActionListener() {\n @Override\n public void actionPerformed(ActionEvent e) {\n\n }\n });\n return openMenuItem;\n}\n</code></pre>\n\n<p>Then the <code>setUpFileMenu</code> would be a lot cleaner:</p>\n\n<pre><code>private void setUpFileMenu() {\n fileMenu = new JMenu(\"File\");\n\n // File menu items\n fileMenu.add(createNewMenuItem());\n fileMenu.add(createOpenMenuItem());\n fileMenu.add(createSaveMenuItem());\n fileMenu.add(createSaveAsMenuItem());\n fileMenu.add(createPrintMenuItem());\n\n add(fileMenu);\n}\n</code></pre>\n\n<p>A maintainer would be helpful, it's easier to get an overview what the method does (without the details) and you can still check them if you are interested in. For example, finding code of save menu is much faster than before.</p>\n\n<blockquote>\n <p>Now, each JMenuItem obviously needs an ActionListener, \n so I just gave each one a different ActionListener. \n I'm skeptical about this because I know it can be kind of disorganized looking. </p>\n</blockquote>\n\n<p>I've found this practice easier to work with than having one <code>ActionListener</code> for multiple components (with a switch-case inside).</p>\n\n<blockquote>\n <p>Basically, I just want somebody to let me know\n if this practice is all right, or if there is a better \n alternative that doesn't involve me making 20 new classes.</p>\n</blockquote>\n\n<p>Having a lot of classes doesn't hurt if they have clear responsibilties.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-02-22T14:24:59.087", "Id": "42504", "ParentId": "30334", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-27T21:28:48.220", "Id": "30334", "Score": "3", "Tags": [ "java", "swing" ], "Title": "Custom component organization system" }
30334
<p>I got about 4 days of assembly knowledge, so I need a review on this <code>strcpy</code> function and if it can be done better (at least I have the feeling).</p> <p>Full code (with the test included):</p> <pre><code>.data s: .asciz "Hello world!" .bss .lcomm destination, 4 .text .globl main main: nop pushl $s pushl $destination call __strcpy addl $8, %esp pushl $destination call puts addl $4, %esp ret .globl __strcpy .type __strcpy, @function __strcpy: movl $0xFFFF, %ecx movl 4(%esp), %edi movl 8(%esp), %esi cpy: cmpl $0, (%esi) je done movsb loop cpy done: ret </code></pre> <p><a href="https://gist.github.com/allanference/6359940" rel="nofollow noreferrer">GitHub</a></p> <p>Parts that I feel can be optimized:</p> <ol> <li><p>Because the <code>done</code> label just executes the <code>ret</code> instruction:</p> <ul> <li><code>cmpl $0, (%esi)</code></li> <li><code>je done</code></li> </ul></li> <li><p>Because the <code>rep</code> instruction-family seems a like better approach:</p> <ul> <li><code>movsb</code></li> <li><code>loop cpy</code></li> </ul></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-12-27T16:41:20.433", "Id": "63524", "Score": "0", "body": "Why not use `loopne` instead of the jump?" } ]
[ { "body": "<p>You can use Bit Twidding Hack to determine if <code>int32</code> or <code>int64</code> has no zero bytes: <a href=\"http://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord\" rel=\"noreferrer\">http://graphics.stanford.edu/~seander/bithacks.html#ZeroInWord</a></p>\n\n<p>If it has not you can copy whole <code>int32</code> or <code>int64</code>. So it will be 4 operations for searching zero byte in 8 bytes (in <code>int64</code> case). It looks like true optimization.</p>\n\n<pre><code>char * strcpy(char * dst, const char * src)\n{\n char * origin = dst;\n\n while (!((((*(uint64_t *)src) - 0x0101010101010101ULL) \n &amp; ~(*(uint64_t *)src) &amp; 0x8080808080808080ULL)))\n {\n *(uint64_t *)dst = *(uint64_t *)src;\n src += 8;\n dst += 8;\n }\n\n while (*dst++ = *src++)\n ;\n\n return origin;\n}\n</code></pre>\n\n<p>Simple <code>strcpy</code> implementation uses 8 compares to zero and 8 byte copyings for each 8 bytes of source string. My implementation uses 4 operation for checking for zeros and 1 operation to copy for 8 bytes. So we have 5ops vs 16ops. Not all ops have same speeds so it is not easy to compare real speedup. We need some benchmarks, is anyone free?</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-02T12:25:30.943", "Id": "48776", "Score": "0", "body": "Sorry for the late reply. This looks good to me, thanks for your effort." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-19T05:07:31.407", "Id": "374716", "Score": "0", "body": "This violates strict aliasing and could create exactly the same kind of problem as the custom `memcpy` that caused the problem in [gcc, strict-aliasing, and horror stories](https://stackoverflow.com/a/2959468)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-19T20:45:45.973", "Id": "374780", "Score": "0", "body": "@PeterCordes don't you think `char *` is allowed to cast to any type without breaking strict aliasing rule? It is an exception to this rule." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-19T20:59:35.210", "Id": "374781", "Score": "0", "body": "It's ok to read a `long` object with a `char*`, but it's not guaranteed to be ok to read a `char` object with a `long*`. You *might* be ok here for strict aliasing, in practice on real compilers, because you'd normally only use `strcpy` on actual string data, not on other objects cast to `char*` the way `memcpy` gets used. But I'm not sure about even that, according to the letter of the law. `char str[16]` is an array object, not a pointer, so accessing `arr[10]` might not count as a `char*` access that's allowed to alias the copying you did with this function." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-19T21:03:26.910", "Id": "374783", "Score": "0", "body": "Apart from strict-aliasing, though, this function has two fatal flaws, one fixable: `uint64_t` has a higher alignment requirement than `char`, so this could easily fault from unaligned access on some CPUs, and even on x86 gcc assumes correct alignment when auto-vectorizing: [Why does unaligned access to mmap'ed memory sometimes segfault on AMD64?](https://stackoverflow.com/q/47510783)." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2018-05-19T21:04:48.200", "Id": "374785", "Score": "0", "body": "The fixable fatal flaw is that you read past the end of the string, which could segfault if the source is `\"hi\"` at the end of a page, if the next page isn't mapped. [Is it safe to read past the end of a buffer within the same page on x86 and x64?](https://stackoverflow.com/q/37800739). In C, even reading outside of the source string object is technically UB though, even if you get the compiler to generate safe asm by getting to an alignment boundary before checking in larger chunks." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T07:23:01.437", "Id": "30348", "ParentId": "30337", "Score": "9" } }, { "body": "<p>Your <code>__strcpy</code> assembler function seems to</p>\n\n<ul>\n<li>copy at most 0xffff bytes</li>\n<li>not to copy the terminating \\0</li>\n</ul>\n\n<p>A normal string copy would copy any number of bytes and would include the \\0.</p>\n\n<p>It is often good to learn from what the compiler gives you from a C function.\nYou can do this with the -S option to <code>gcc</code>. For example this line will\ncompile <code>code.c</code> into assembler file <code>code.s</code></p>\n\n<pre><code>gcc -S -o code.s -O3 -Wall code.c\n</code></pre>\n\n<p>The -O3 sets the optimization level (high).</p>\n\n<p>Also if you omit the length check, you should be able to arrange your loop so that there is only one branch\ninstruction (branches are expensive).</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-24T16:27:53.673", "Id": "36010", "ParentId": "30337", "Score": "3" } }, { "body": "<p>I apologize for my lack of GCC fluency in advance - I have only used MASM and RosAsm for x86, but I will try to translate. This review will be in top-to-bottom order, not in order of importance.</p>\n\n<p>The first thing I would do is evaluate whether you really need to use cdecl calling convention. If you're only calling your function from asm, it makes sense to pass the source and destination in <code>esi</code> and <code>edi</code>, respectively, rather than putting them on the stack and then loading them.</p>\n\n<p>Next, instead of <code>movl %ecx, $0xFFFF</code>, I would do:</p>\n\n<pre><code>xorl %ecx, %ecx\ndecl %ecx\n</code></pre>\n\n<p><code>xor</code>ing a register with itself is such a common idiom that some processors use it as an optimization hint. All it does is set the register to zero, with a smaller opcode &amp; operand. The <code>dec</code> after the <code>xor</code> makes the register all 1 bits no matter how many bits your register actually has. Some day when all of our GPRs are 128 bits, some poor sap that is updating assembly code will thank you for that =D.</p>\n\n<p>Alternatively, you can forget about <code>ecx</code> being a limit altogether. No matter what arbitrary limit you set on the size of the string, it will either (1) not be big enough for someone someday, or (2) be small enough that an access violation (or worse: no access violation) will occur before you actually reach that limit. Either way, that is really only a nominal protection of data integrity.</p>\n\n<p>Now, the string. There seem to be some inconsistencies in how you're treating its terminating null character. You're using <code>cmpl</code> to find four bytes of 0, then using <code>movsb</code> to only copy/advance <code>esi</code> by 1. Normally, strings are only guaranteed to be terminated by a number of null bytes equal to the character size, although in practice there are probably at least 2-3 to get the next datum to be dword-aligned. What that means for you is that your code will fail to detect the end of ~3/4 of normal, null-terminated, ascii strings, and keep copying until it finally causes an access violation.</p>\n\n<p>But that's not all. Notice that you're fetching a dword at <code>esi</code> with the <code>cmpl</code> instruction, and that advancing that pointer by 1 at every iteration will make the pointer not dword-aligned 3/4 of the time. Loading non-aligned data takes two fetches instead of one, so for every 4 bytes of string, your <code>cmpl</code> instruction alone needs 7 fetches from memory. Furthermore, after fetching the data and discarding it with <code>cmpl</code>, you fetch it again with <code>movsb</code>, a total of 11 memory loads per dword of data.</p>\n\n<p>To reduce that number, you should load the data into a register, do your test for the null terminator on that register, then store the data to the destination. I see that someone else has pointed you to the bit-hack that will let you test all 4 bytes of the dword at once, so if you can follow that, do so, but here's a less efficient way that demonstrates my point very clearly:</p>\n\n<pre><code>cpy:\n lodsb ; fetch one byte from [esi++] to al\n test %al, %al ; set the z flag if al is 0\n stosb ; store the byte, even if it's 0, doesn't affect flags\n jnz cpy ; or loopnz if you still want to use a size limit in ecx\n</code></pre>\n\n<p>That will only require 4 fetches per dword, and is perfectly readable (as far as asm goes...). The bit twiddling hack does it with just one.</p>\n\n<p>With regard to your instinct that <code>rep</code> family instructions would be better, I believe you're sadly incorrect. If you learn any other assembly language and try to use strings, you'll certainly appreciate the effort Intel originally put into providing special string instructions, but they haven't really optimized or extended those instructions with the same zeal as one might like. Further, you can't <code>repnz movsb</code>, because <code>movsb</code> doesn't set any flags. If you ever do end up <code>repne scasb</code>, remember to <code>jecxz</code> =D.</p>\n\n<p>This might seem like a long list of complaints, but for having first seen assembly 4 days before writing this, it's remarkable that you can do <em>anything</em> useful. Cheers.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-11-25T00:34:10.433", "Id": "36021", "ParentId": "30337", "Score": "3" } } ]
{ "AcceptedAnswerId": "30348", "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T00:41:49.743", "Id": "30337", "Score": "9", "Tags": [ "strings", "linux", "assembly" ], "Title": "x86 strcpy implementation" }
30337
<p>I would like to share my design of mvc via js.</p> <p>What do you think about it? I tried to not use any mvc framework but i want to get clear structure and a decoupled organisation.</p> <p>Next step for me is evaluating something like require.js to get rid of the ordering within the index file</p> <p>The code:</p> <pre><code>XX.namespace.ContactListController = (function() { var _initListener = function() { $(document).ready(function() { $("#addContact").click(function() { var contactName = $("#contactName").attr('value'); var contact = new XX.namespace.ContactModel(contactName); $.publish("add#contact", contact); }); $("#removeContact").click(function() { var contactName = $("#contactName").attr('value'); var contact = new XX.namespace.ContactModel(contactName); $.publish("remove#contact", contact); }); }); }; var interface = { init: function() { _initListener(); } }; return interface; })(XX.namespace.ContactListModel, XX.namespace.ContactListView); XX.namespace.ContactListModel = (function() { var contactList = []; /** * @private */ var _addContact = function(channel, contact) { contactList.push(contact); }; var _removeContact = function(channel, contact) { var index = contactList.indexOf(contact); contactList.splice(index, 1); }; /** * API */ $(document).ready(function() { $.subscribe("add#contact", _addContact); $.subscribe("remove#contact", _removeContact); }) })(); XX.namespace.ContactModel = function x(name) { this.name = name; }; XX.namespace.ContactListView = (function(){ var uiComponents = { contactList: "#contactList" }; var _addContact = function(channel, contact) { $(uiComponents.contactList).append("&lt;li contact_name='" + contact.name + "'&gt;" + contact.name +"&lt;/li&gt;"); }; var _removeContact = function(channel, contact) { $(uiComponents.contactList+" li[contact_name='" + contact.name+ "']").remove(); }; /** * API */ $(document).ready(function() { $.subscribe("add#contact", _addContact); $.subscribe("remove#contact", _removeContact); }) })(); (function() { XX.namespace.ContactListController.init(); })(); &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;meta charset="utf-8"&gt; &lt;script src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js"&gt; &lt;/script&gt; &lt;script src="js/extlib/tinyPubSub.js"&gt;&lt;/script&gt; &lt;script src="js/src/util/namespace.js"&gt;&lt;/script&gt; &lt;script src="js/src/model/ContactModel.js"&gt;&lt;/script&gt; &lt;script src="js/src/model/ContactListModel.js"&gt;&lt;/script&gt; &lt;script src="js/src/view/ContactListView.js"&gt;&lt;/script&gt; &lt;script src="js/src/controller/ContactListController.js"&gt;&lt;/script&gt; &lt;script src="js/src/application.js"&gt;&lt;/script&gt; &lt;/head&gt; &lt;body&gt; &lt;h2&gt;ContactList1&lt;/h2&gt; &lt;ul id="contactList"&gt; &lt;/ul&gt; &lt;h1&gt;Chat&lt;/h1&gt; &lt;div&gt; &lt;p&gt; &lt;input type="text" id="contactName"/&gt; &lt;input type="button" id="addContact" value="hinzufügen"&gt; &lt;input type="button" id="removeContact" value="entfernen"&gt; &lt;/p&gt; Message: &lt;input id="msg" type="text" /&gt; &lt;textarea id="msgContainer"&gt;&lt;/textarea&gt; &lt;/div&gt; &lt;/body&gt; </code></pre> <p></p>
[]
[ { "body": "<p>Did you post the right code?</p>\n\n<p>What is TC.messenger?</p>\n\n<p>You pass two arguments in</p>\n\n<pre><code>XX.namespace.ContactListController = (function(contactListModel, view) \n</code></pre>\n\n<p>and you save them as members, but never use them.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T06:56:26.883", "Id": "48357", "Score": "0", "body": "Yeah you are right. This i forgot to remove, because i changed from calling the the model and view directly to pubsub mechanism, i changed the code. C.messenger is just the namespace i forgot to mark as XX.namespace, modified my post" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T15:02:58.033", "Id": "30372", "ParentId": "30358", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:02:42.580", "Id": "30358", "Score": "1", "Tags": [ "javascript", "mvc" ], "Title": "Javascript MVC Design Feedback" }
30358
<p>This is my first JavaScript/jQuery project after having been reading and learning for a good few weeks. I am proud I have made something that at least works. However, I'm sure that my code is inefficient, and possibly more complex that it needs to be. I would appreciate any feedback on my JavaScript. What other ways would I go about making this game?</p> <p>As I started making it, I just thought up features and kind of "bolted" them on. So, with some more forethought, I could have been more organised.</p> <p>The game is made for a mobile device, but for now it's browser only. I understand that the game isn't difficult (that's not what I'm aiming for at the moment), it's more the logic of the game, and the practice manipulating the DOM.</p> <p>I want to use more objects in my code. I know how to create and use them, but I don't know how to <em>practically</em> use them.</p> <p>The full game is available <a href="http://jsfiddle.net/e4VjH/" rel="nofollow">here</a>.</p> <pre><code>var images = [ "&lt;img src=\"http://103.imagebam.com/download/CTHPzR99HvxiHwLlnY7ORA/27274/272731499/one.png\" data-brand-name=\"coca cola\"&gt;", "&lt;img src=\"http://107.imagebam.com/download/jlBQih1wkuYKF45fgh7fJg/27274/272731502/two.png\" data-brand-name=\"durex\"&gt;", "&lt;img src=\"http://101.imagebam.com/download/dz31UIrHKVzQy6j9sovh3w/27274/272731500/three.png\" data-brand-name=\"johnson and johnson\"&gt;", "&lt;img src=\"http://107.imagebam.com/download/Q4d8eWgNRSO8RUPaPDLU4Q/27274/272731498/four.png\" data-brand-name=\"nike\"&gt;" ]; var $theimage = $('.the-image'); var $theinputs = $('.the-inputs'); var $button = $('.go'); var $skip = $('.skip'); var $brandName; var $scoreDisplay = $('.score span'); var $attemptsDisplay = $('.attempts span'); var $brandIndexDisplay = $('.brand-index'); var $skipsLefDisplay = $('.skips-left'); var score = 0; var attempts = 3; var userAnswer = ''; var imageCount = 0; var numOfSkips = 3; // Add a new image for a new go function newBrand(i) { $theimage.html(images[i]); } // // Find the number of inputs needed with the brand name, located in the datta attr This is per word (we switched to per letter....) // var numOfInputs = function() { // var $brandLength = $('.the-image img').data('brand-name').split(' ').length; // // Loop through them all and append an input per word in the brand name // for ( var i = 0; i &lt; ($brandLength); i++ ) { // if ( i === 0 ) { // $theinputs.append('&lt;input type=\"text\" placeholder=\"tap me\"&gt;'); // } // else { // $theinputs.append('&lt;input type=\"text\"&gt;'); // } // } // } // Find the number of inputs needed with the brand name, located in the datta attr function numOfInputs() { var $brandName = $('.the-image img').data('brand-name'); var brandLength = $brandName.length; var reg = new RegExp('\\s'); // var space = $brandName.indexOf(' '); // var $numOfSpaces = $brandName.split(' ').length - 1; // var len = $brandLength - $numOfSpaces; for ( var i = 0; i &lt; brandLength; i++ ) { // if ( i === space ) { // $theinputs.append('&lt;br&gt;'); // } if ( $brandName[i].match(reg) ) { $theinputs.append('&lt;br&gt;'); } else { $theinputs.append('&lt;input type=\"text\"&gt;'); } } } // Find the brand name from the data attr to match it to the users answer function findBrandName() { $brandName = $('.the-image img').data('brand-name'); return $brandName; } function addPointToScore() { score += 1; $scoreDisplay.html(score); } function oneLessAttempt() { attempts -= 1; $attemptsDisplay.html(attempts); $attemptsDisplay.toggleClass('animated').toggleClass('pulse'); } function oneLessSkip() { numOfSkips -= 1; $skipsLefDisplay.html(numOfSkips); } // Validation: make the inputs one character only, focus on the next input after character is entered, and allow backspace, delete, tab &amp;&amp; shift... function validate() { $('input').keyup(function(event) { var keyCode = event.keyCode || event.which; var val = $(this).val(); if ( $(this).next().is('br') ) { $(this).next().next().focus(); } else if(val.length === 1) { $(this).next().focus(); } else if (keyCode === 8 || keyCode === 9 || keyCode === 16 || keyCode === 46 || (keyCode === 16 &amp;&amp; keyCode === 9)) { return false; } else { val = val.substring(0, val.length - 1); $(this).val(val); $(this).next().focus() } }); } function getBrandIndex() { $brandIndexDisplay.html(imageCount + 1 + "/" + images.length); } function loadNextBrand() { userAnswer = ''; // Reset user answer imageCount += 1; // Add one to the image array attempts = 3; $attemptsDisplay.html(attempts) newBrand(imageCount); // load in the new brand image $theinputs.empty(); // clear the inputs findBrandName(); // Fetch the brand name from data attr numOfInputs(); // Set the number of inputs validate(); // Rerun the validation func } $(function() { // Initial load, set up the page $theimage.html(images[imageCount]); numOfInputs(); $scoreDisplay.html(score); $attemptsDisplay.html(attempts); $skipsLefDisplay.html(numOfSkips); getBrandIndex(); validate(); // Submit answer $button.click(function() { $brandName = $('.the-image img').data('brand-name').replace(/\s+/g,""); $('.the-inputs input').each(function() { userAnswer += $(this).val(); }); userAnswer = $.trim(userAnswer).toLowerCase().replace(/\s+/g,""); if ( userAnswer === $brandName ) { addPointToScore(); $('.modal').show().addClass('fade'); if (score === 1) { $('.modal-content').html('&lt;h2&gt;Great work!&lt;/h2&gt;&lt;p&gt;You have &lt;span&gt;' + score + ' point&lt;/span&gt;&lt;/p&gt;&lt;button class=\"next\"&gt;On &amp; Up?&lt;/button&gt;'); } else { $('.modal-content').html('&lt;h2&gt;Great work!&lt;/h2&gt;&lt;p&gt;You have &lt;span&gt;' + score + ' points&lt;/span&gt;&lt;/p&gt;&lt;button class=\"next\"&gt;On &amp; Up?&lt;/button&gt;'); } $('.next').click(function() { $('.modal').hide(); }); loadNextBrand(); getBrandIndex(); } else if (images.length - 1 === imageCount) { $('.modal').show().addClass('fade'); $('.modal-content').html('&lt;h2&gt;Bravo, that\'s the end of the game!&lt;/h2&gt;&lt;p&gt;You scored &lt;span&gt;' + score + ' points&lt;/span&gt;&lt;/p&gt;&lt;p&gt;Don\'t forget to screenshot your score!'); } else { oneLessAttempt(); $('.modal').show().addClass('fade'); if (attempts === 1) { $('.modal-content').html('&lt;h2&gt;Ah shoot! Your guess was incorrect...&lt;/h2&gt;&lt;p&gt;You have &lt;span&gt;' + attempts + ' attempt&lt;/span&gt; remaining&lt;/p&gt;&lt;button class=\"cont\"&gt;Try Again&lt;/button&gt;'); } else { $('.modal-content').html('&lt;h2&gt;Ah shoot! Your guess was incorrect...&lt;/h2&gt;&lt;p&gt;You have &lt;span&gt;' + attempts + ' attempts&lt;/span&gt; remaining&lt;/p&gt;&lt;button class=\"cont\"&gt;Try Again&lt;/button&gt;'); } $('.cont').click(function() { $('.modal').hide(); }); if (attempts === 0) { $('.modal').show().addClass('game-over'); $('.modal-content').html('&lt;h2&gt;Bah, it\'s game over!&lt;/h2&gt;&lt;button class=\"restart\"&gt;Start Again?&lt;/button&gt;'); $('.restart').click(function() { location.reload(); }); } $('.the-inputs input').each(function() { $(this).val(''); }); userAnswer = ''; } }); // Click skip $skip.click(function() { $('.modal').show().addClass('fade'); $('.modal-content').html('&lt;h2&gt;Are you sure you want to skip? You will not get any points&lt;/h2&gt;&lt;button class=\"yes\"&gt;Yes&lt;/button&gt;&lt;button class=\"no\"&gt;No&lt;/button&gt;'); $('.yes').click(function() { $('.modal').hide(); loadNextBrand(); getBrandIndex(); oneLessSkip(); if (numOfSkips === 0) { $('.skip').remove(); } }); $('.no').click(function() { $('.modal').hide(); }); if (images.length - 1 === imageCount) { $('.modal').show().addClass('fade'); $('.modal-content').html('&lt;h2&gt;Bravo, that\'s the end of the game!&lt;/h2&gt;&lt;p&gt;You scored &lt;span&gt;' + score + ' points&lt;/span&gt;&lt;/p&gt;&lt;p&gt;Don\'t forget to screenshot your score!&lt;/p&gt;&lt;button class=\"restart\"&gt;Start Again?&lt;/button&gt;'); $('.restart').click(function() { location.reload(); }); } else if (numOfSkips === 0) { console.log('out of skips'); } }); }); </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T13:46:04.363", "Id": "48273", "Score": "0", "body": "Bug report: I notice if I start typing very fast that it will not enter my letters correctly. :)" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T14:35:32.800", "Id": "48278", "Score": "0", "body": "Yes, I know. But I don't know why! Will keep battling..." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T08:22:46.813", "Id": "48362", "Score": "0", "body": "**@mnhg RE: put on hold**\nIf there was an easier way to paste in my JS, I would (like being able to wrap it in tags [code][/code] for example). However, the current 4 or 8 spaces does not work for my code. Half gets put in code blocks, half doesn't. Tell me if I'm missing something here?" } ]
[ { "body": "<p>While browsing the code with a first glance. 2 things come to mind:</p>\n\n<ul>\n<li>This code seems to have no Portability / re-usability</li>\n<li>why jQuery?</li>\n</ul>\n\n<p>There is no encapsulation of the code, this isn't bad since it simply works. But changing the classnames in your html is un-doable since you then also need to change the business logic of your code. To put it in a more professional sentence: your code is Tightly coupled thus rendering it very hard to use in another project.</p>\n\n<p>Next to being Tightly coupled, the entire code is written in the global scope. This doesn't play nice when including other libraries. A very good read on understanding scope and context in javascript: <a href=\"http://ryanmorr.com/understanding-scope-and-context-in-javascript/\">http://ryanmorr.com/understanding-scope-and-context-in-javascript/</a></p>\n\n<p>A part from these jQuery-programmers-mistakes (no pun intended, but most people tend to solve every answer with jQuery without knowing how JS really works) there are some small remaks on the code:</p>\n\n<pre><code>var $theimage = $('.the-image');\nvar $theinputs = $('.the-inputs');\nvar $button = $('.go');\nvar $skip = $('.skip');\nvar $brandName;\nvar $scoreDisplay = $('.score span');\nvar $attemptsDisplay = $('.attempts span');\nvar $brandIndexDisplay = $('.brand-index');\nvar $skipsLefDisplay = $('.skips-left');\n</code></pre>\n\n<p>You just need one element returned here, so use an ID instead of a class. A class '.the-image' is very general and could also be used somewhere else in the code.</p>\n\n<pre><code>var score = 0;\nvar attempts = 3;\nvar userAnswer = '';\nvar imageCount = 0;\nvar numOfSkips = 3;\n</code></pre>\n\n<p>These variables are available EVERYWHERE since they are defined in the global scope. In fact these should actually be encapsulated. (The Module pattern is an easy way to do this).</p>\n\n<p>I noticed you are using <code>&lt;br&gt;</code> to seperate the words. For this you have this strange if ( is('br') part in your code. Drop the <code>&lt;br&gt;</code> and put the words in different <code>&lt;div class=\"word\"&gt;</code> containers. More flexiblity for styling different words, ... (just my 5 cent)</p>\n\n<p>Then, why jQuery?\nThe only thing you are doing is some simple dom selection. Plain Vanilla can do this: <a href=\"https://gist.github.com/liamcurry/2597326\">https://gist.github.com/liamcurry/2597326</a> oh, and have a look here: <a href=\"http://www.doxdesk.com/img/updates/20091116-so-large.gif\">http://www.doxdesk.com/img/updates/20091116-so-large.gif</a></p>\n\n<p>Want to read more about JAvascript? here are some really cool links:</p>\n\n<ul>\n<li><a href=\"http://vanilla-js.com/\">http://vanilla-js.com/</a></li>\n<li><a href=\"http://eloquentjavascript.net/contents.html\">http://eloquentjavascript.net/contents.html</a> (one of my favorites)</li>\n<li><a href=\"http://davidwalsh.name/javascript-objects\">http://davidwalsh.name/javascript-objects</a> (very good articles about scope and patterns)</li>\n<li><a href=\"http://oscargodson.com/posts/what-the-fuck-is-prototypal-inheritance.html\">http://oscargodson.com/posts/what-the-fuck-is-prototypal-inheritance.html</a></li>\n<li><a href=\"http://addyosmani.com/resources/essentialjsdesignpatterns/book/\">http://addyosmani.com/resources/essentialjsdesignpatterns/book/</a></li>\n<li><a href=\"http://blog.bittersweetryan.com/2013/06/a-look-into-how-parameters-are-passed.html\">http://blog.bittersweetryan.com/2013/06/a-look-into-how-parameters-are-passed.html</a></li>\n</ul>\n\n<p>Want to write really good code? Here are some fun articles:</p>\n\n<ul>\n<li><a href=\"http://www.slideshare.net/nzakas/extreme-javascript-compression-with-yui-compressor\">http://www.slideshare.net/nzakas/extreme-javascript-compression-with-yui-compressor</a></li>\n<li><a href=\"http://thc.org/root/phun/unmaintain.html\">http://thc.org/root/phun/unmaintain.html</a></li>\n<li><a href=\"http://javascript.crockford.com/popular.html\">http://javascript.crockford.com/popular.html</a></li>\n</ul>\n\n<p>good luck!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:49:46.030", "Id": "48262", "Score": "0", "body": "I added some links" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:58:36.813", "Id": "48264", "Score": "0", "body": "**Thank you!** This is exactly what I'm looking for, I really appreciate your time." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T13:19:04.820", "Id": "48267", "Score": "1", "body": "I like vanilla-js.com... Amusing" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T13:19:28.817", "Id": "48268", "Score": "0", "body": "If you like the answer, accepting it as the correct one is always welcome :). And your welcome! thats why stackexchange exists" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T13:31:51.700", "Id": "48271", "Score": "0", "body": "Alrighty, sorted." } ], "meta_data": { "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:38:40.013", "Id": "30362", "ParentId": "30360", "Score": "8" } }, { "body": "<p>The keyboard handling needs work, I think.</p>\n\n<p>When a new question is displayed, the first blank should automatically receive focus.</p>\n\n<p>When typing a letter into a blank that already has a character, I would expect the previous character to be overwritten. However, <code>else if(val.length === 1) { $(this).next().focus(); }</code> just moves focus to the next blank.</p>\n\n<p>When typing fast, some characters get lost. I'm not sure how to advise you to fix that problem.</p>\n\n<p>To advance to the next blank, instead of <code>$(this).next().next().focus()</code>, you can do <code>$(this).next('input').focus()</code>.</p>\n\n<p>I would change the \"Go!\" button to an <code>&lt;input type=\"submit\"&gt;</code>, and put the UI inside a <code>&lt;form&gt;</code>. Not only would it make <code>$(this).next('input').focus()</code> work at the end, it would also enable the <kbd>Enter</kbd> key to work.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-30T10:16:16.407", "Id": "68361", "ParentId": "30360", "Score": "1" } } ]
{ "AcceptedAnswerId": "30362", "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:05:15.200", "Id": "30360", "Score": "6", "Tags": [ "javascript", "jquery", "html", "css", "quiz" ], "Title": "\"Guess the Brand\" game" }
30360
<p>I have an SQL Server table from which I want to extract data from one column (<code>DD</code>) and return as multiple columns.</p> <p>The data is in <code>NVARCHAR</code> and looks like:</p> <blockquote> <p><code>;&lt;b&gt;HF&lt;/b&gt;:GN;&lt;b&gt;HM&lt;/b&gt;:GTN;&lt;b&gt;HN&lt;/b&gt;:GN;&lt;b&gt;PN&lt;/b&gt;:AN;&lt;b&gt;PVD&lt;/b&gt;:GO;&lt;b&gt;PVR&lt;/b&gt;:1.1;&lt;b&gt;BN&lt;/b&gt;:AN;&lt;b&gt;BVD&lt;/b&gt;:GO;&lt;b&gt;BV&lt;/b&gt;:2.3;</code></p> </blockquote> <p>There is less to be changed in the way this data is structured.</p> <p>I have to extract all of the data in <code>&lt;b&gt;...&lt;/b&gt;</code> and between <code>:</code> and <code>;</code> and have to return as individual columns. I tried with the following query:</p> <pre><code>SELECT DataID ,SUBSTRING(DD,CHARINDEX(';&lt;b&gt;HF&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;HF&lt;/b&gt;:'),CHARINDEX(';&lt;b&gt;HM&lt;/b&gt;:',DD) - (CHARINDEX(';&lt;b&gt;HF&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;HF&lt;/b&gt;:'))) as HF ,SUBSTRING(DD,CHARINDEX(';&lt;b&gt;HM&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;HM&lt;/b&gt;:'),CHARINDEX(';&lt;b&gt;HN&lt;/b&gt;:',DD) - (CHARINDEX(';&lt;b&gt;HM&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;HM&lt;/b&gt;:'))) as HM ,SUBSTRING(DD,CHARINDEX(';&lt;b&gt;HN&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;HN&lt;/b&gt;:'),CHARINDEX(';&lt;b&gt;PN&lt;/b&gt;:',DD) - (CHARINDEX(';&lt;b&gt;HN&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;HN&lt;/b&gt;:'))) as HN ,SUBSTRING(DD,CHARINDEX(';&lt;b&gt;PN&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;PN&lt;/b&gt;:'),CHARINDEX(';&lt;b&gt;PVD&lt;/b&gt;:',DD) - (CHARINDEX(';&lt;b&gt;PN&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;PN&lt;/b&gt;:'))) as PN ,SUBSTRING(DD,CHARINDEX(';&lt;b&gt;PVD&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;PVD&lt;/b&gt;:'),CHARINDEX(';&lt;b&gt;PVR&lt;/b&gt;:',DD) - (CHARINDEX(';&lt;b&gt;PVD&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;PVD&lt;/b&gt;:'))) as PVD ,SUBSTRING(DD,CHARINDEX(';&lt;b&gt;PVR&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;PVR&lt;/b&gt;:'),CHARINDEX(';&lt;b&gt;BN&lt;/b&gt;:',DD) - (CHARINDEX(';&lt;b&gt;PVR&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;PVR&lt;/b&gt;:'))) as PVR ,SUBSTRING(DD,CHARINDEX(';&lt;b&gt;BN&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;BN&lt;/b&gt;:'),CHARINDEX(';&lt;b&gt;BVD&lt;/b&gt;:',DD) - (CHARINDEX(';&lt;b&gt;BN&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;BN&lt;/b&gt;:'))) as BN ,SUBSTRING(DD,CHARINDEX(';&lt;b&gt;BVD&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;BVD&lt;/b&gt;:'),CHARINDEX(';&lt;b&gt;BVR&lt;/b&gt;:',DD) - (CHARINDEX(';&lt;b&gt;BVD&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;BVD&lt;/b&gt;:'))) as BVD ,SUBSTRING(DD,CHARINDEX(';&lt;b&gt;BVR&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;BVR&lt;/b&gt;:'),LEN(DD) - (CHARINDEX(';&lt;b&gt;BVR&lt;/b&gt;:',DD) + LEN(';&lt;b&gt;BVR&lt;/b&gt;:'))) as BVR FROM DataTable WHERE DD is not null </code></pre> <p>I think I'll have to generate the query at run-time from a list of column names or may have hard-coded query as the structure of the data and the required columns is not likely to change.</p> <p>Given that, is there a better approach to optimize this query? May be by using Regular Expressions or any other approach?</p> <h2>Edit:</h2> <p>Is there a better approach using C# Code-behind? This eventually is being used for an ASP.Net Web Application.</p>
[]
[ { "body": "<p>Basically, sql is not meant to parse text. The database design is the issue here and it probably needs to be modified. Another option is to return the string to the server and do the parsing there and then make another call to sql.</p>\n\n<p>My answer is basically a copy of Andrew White's answer to <a href=\"https://stackoverflow.com/questions/4410452\">this</a> stackoverflow question.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T06:20:11.837", "Id": "48352", "Score": "0", "body": "I understand that SQL/Database is not meant to parse text but I want to avoid unnecessary data processing on the server which could be taken care of at the database end, if possible." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T10:44:29.193", "Id": "48369", "Score": "1", "body": "You should indeed avoid this if possible, but it is either this, or redesigning your schema (the most correct way to go about it), or using some twisted sql coding as you did (which might be a big performance hindrance (?))." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T14:31:56.140", "Id": "30368", "ParentId": "30361", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:06:28.813", "Id": "30361", "Score": "2", "Tags": [ "c#", "asp.net", "sql-server", "etl" ], "Title": "Extract data from one column of SQL Server table" }
30361
<p>I have the following model:</p> <pre><code>namespace Site.Models.Country { public class Country { public string CountryCode { get; set; } public string CountryName { get; set; } public string CountryUrl { get; set; } } } </code></pre> <p>In a separate model folder for a different view and controller, I have a different model like this:</p> <pre><code>namespace Site.Models.Directory { public class DirectoryProfileView { public List&lt;Country&gt; Countries { get; set; } public DirectoryProfileView() { this.Countries = new List&lt;Country&gt;(Country.GetCountryRegions()); } } } </code></pre> <p>Is it correct for me to use the Country model from a different model ? I tried adding using <code>Site.Models.Country</code>;</p> <p>However for the following to work:</p> <pre><code>public List&lt;Country&gt; Countries { get; set; } </code></pre> <p>I need to call by</p> <pre><code>public List&lt;Country.Country&gt; Countries { get; set; } </code></pre> <p>My two questions are:</p> <ol> <li><p>Is this correct? I don't really want to be creating another model exactly like my first Country model.</p></li> <li><p>Also, any feedback on my naming conventions would be appreciated too.</p></li> </ol>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:25:15.277", "Id": "48257", "Score": "1", "body": "I think this is a valid question, but perhaps best suited for migration to the codereview stack exchange site." } ]
[ { "body": "<p>Unless you have several country related classes don't see the point of having a <code>Country</code> namespace.</p>\n\n<p>In case you do have several country related classes, call your namespace different so is not the same as the name of the class. </p>\n\n<p>Without knowing the rest of the classes is hard to suggest a proper name, but just changing <code>Country</code> by <code>CountryModels</code> could do the trick. </p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:28:32.920", "Id": "48258", "Score": "0", "body": "Is this the recommended way of coding the model namespaces and is it common to share models in this manner ? Re the name you mean namespace Site.Models.CountryModels ?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:31:21.073", "Id": "48259", "Score": "0", "body": "Valid solution. But the reason you are having problems is because you a namespace and a class with the same name, and because of that you need to provide a disambiguation to let the compiler know wich one you are referring to." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:32:37.250", "Id": "48260", "Score": "0", "body": "@Tommo1977: I'm no sure what you mean by \"share models\". Models are expected to be related to each other, there is nothing wrong with that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:33:55.083", "Id": "48261", "Score": "0", "body": "@ClaudioRedi OK I understand" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:25:59.533", "Id": "30365", "ParentId": "30364", "Score": "0" } }, { "body": "<ol>\n<li><p>It's ok to do that, classes are there to reuse them.</p></li>\n<li><p>I think the Country part in namespace is redundant and if it is a model that you just use in your view you can name the class CountryViewModel.<br>\nAbout the other class: It's hard to say if there are any other related classes in that namespace or not but it seems reasonable.</p></li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:41:59.310", "Id": "30366", "ParentId": "30364", "Score": "1" } }, { "body": "<p>I think you need to read up a little on namespaces. Both of your namespaces don't make sense unless you will have multiple types of countries and directories.</p>\n\n<p>Your namespace should be if you will have multiple countries</p>\n\n<pre><code>namespace Site.Models.Countries\n</code></pre>\n\n<p>otherwise it should be</p>\n\n<pre><code>namespace Site.Models\n</code></pre>\n\n<p>In regards to naming your view models, I would think on how you will use these models in future. If you are likely to have a page for creating, updating, removing and viewing the country, then you might well have the following view models:</p>\n\n<ul>\n<li>DisplayCountry</li>\n<li>UpdateCountry</li>\n<li>RemoveCountry</li>\n<li>SaveCountry</li>\n</ul>\n\n<p>Some people choose to reuse single country model, but I've seen this cause more trouble than benefit. For example, in the RemoveCountry model I'll have only two properties: </p>\n\n<pre><code>public int Id { get; set; }\npublic string Name { get; set;\n</code></pre>\n\n<p>The first property is purely for data removal purposes - I assume that you'll pass id to your data layer eventually. Second property is mainly for better UX journey. You might use it for notifying user that they are about to remove a country. E.g., in your view you might have</p>\n\n<pre><code>&lt;h2&gt;Warning&lt;/h2&gt;\n&lt;p&gt;Are you sure you want to remove @Model.Name&lt;/p&gt;\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T14:41:59.300", "Id": "30369", "ParentId": "30364", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T12:20:25.257", "Id": "30364", "Score": "3", "Tags": [ "c#" ], "Title": "How to access and share MVC Model?" }
30364
<p>There are my shapes (for example):</p> <pre><code>public abstract class Shape { protected int _id; protected string _description; public abstract string ToXml(); } public sealed class Triangle : Shape { public int TriangleId { get { return _id; } set { _id = value; } } public string TriangleDescription { get { return _description; } set { _description = value; } } public ConsoleColor color { get; set; } public override string ToXml() { // First implementation throw new NotImplementedException(); } } public sealed class Circle : Shape { public int CircleId { get { return _id; } set { _id = value; } } public string CircleDescription { get { return _description; } set { _description = value; } } public int Radius { get; set; } public override string ToXml() { // Second implementation throw new NotImplementedException(); } } public sealed class Square : Shape { public int SquareId { get { return _id; } set { _id = value; } } public string SquareDescription { get { return _description; } set { _description = value; } } public int Edge { get; set; } public override string ToXml() { // Third implementation throw new NotImplementedException(); } } </code></pre> <p>Client have to choose one kind of shape to get xml-view:</p> <pre><code>public enum ShapeType { Triangle, Circle, Square } public class Module { public string GetXml( ShapeType type, int id ) { switch( type ) { case ShapeType.Circle: return DB.GetEntity( id ).ToTypedEntity&lt;Circle&gt;().ToXml(); case ShapeType.Square: return DB.GetEntity( id ).ToTypedEntity&lt;Square&gt;().ToXml(); case ShapeType.Triangle: return DB.GetEntity( id ).ToTypedEntity&lt;Triangle&gt;().ToXml(); } } } </code></pre> <p>As you can see, there are too much the same code parts that are matching enumerations with shape's types. It is not good.</p> <p>How can I avoid it?</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T15:38:24.773", "Id": "48292", "Score": "2", "body": "I don't know C# much, but do you really have to redefine the getters and setters for id and description?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T15:42:41.357", "Id": "48293", "Score": "0", "body": "Also, how does the DB work? Is there a different table for each type? It seems dangerous to have the user ask for both the type and the id since they might be inconsistent. Only asking for the id should be enough (?)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T07:03:06.430", "Id": "48358", "Score": "0", "body": "I came up with this code for example. It is not real code." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T07:46:01.893", "Id": "48360", "Score": "0", "body": "Public methods marked AOP aspects that are checking permissions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T07:50:19.193", "Id": "48361", "Score": "0", "body": "And yes, each type has different table." } ]
[ { "body": "<p>Just expose the class types to the user (which they already appear to be) rather than forcing them to use a gawd-awful enum.</p>\n\n<pre><code>public class Module\n{\n public string GetXml&lt;TShape&gt;( int id ) where TShape : Shape\n { \n return DB.GetEntity( id ).ToTypedEntity&lt;TShape&gt;().ToXml(); \n }\n}\n</code></pre>\n\n<p>The the user can just make a normal call like</p>\n\n<pre><code>new Module().GetXml&lt;Triangle&gt;(34);\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T15:26:18.603", "Id": "48281", "Score": "0", "body": "Might need to add a `where TShape : Shape` onto the end of the method declaration." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T15:20:33.980", "Id": "30374", "ParentId": "30370", "Score": "1" } }, { "body": "<p>I would consider decoupling the Xml serialization from the entity objects. The <a href=\"http://msdn.microsoft.com/en-us/library/182eeyhh%28VS.80%29.aspx\" rel=\"nofollow\">Xml serialization namespace</a> gives you very fine grained control over how an object is represented in Xml plus a lot fo built in functionality that you do not need to reinvent.</p>\n\n<p>The advantages of this decoupling is that your Shape object hierarchy implementations become smaller, you get better on single responsibilty for the shape objects.</p>\n\n<pre><code>public class Module\n{\n public string GetXml&lt;TShape&gt;( int id ) where TShape : Shape\n { \n XmlSerializer ser = new XmlSerializer(typeof(TShape));\n StringBuilder builder = new StringBuilder();\n using(StringWriter sww = new StringWriter(builder))\n using (XmlWriter writer = XmlWriter.Create(sww))\n ser.Serialize(writer, DB.GetEntity( id ).ToTypedEntity&lt;TShape&gt;());\n return builder.ToString(); // Your xml \n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T16:00:38.507", "Id": "30377", "ParentId": "30370", "Score": "0" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T14:47:04.817", "Id": "30370", "Score": "1", "Tags": [ "c#" ], "Title": "How to remove duplicate matching?" }
30370
<p>The code inputs an <code>int</code>, <code>n</code>, which is the number of lines to follow. Then, on each line, the first number goes to array <code>A</code>, the second to <code>B</code>, and the third to <code>C</code>. I then pass these 4 arguments to <code>sub</code> which I have no control over (in an object file where I don't know the implementation). All I know is that it returns an <code>int</code>.</p> <p>What I do then is write <code>n</code>, the three arrays, and the result of <code>sub</code> into an output file. Pretty simple code.</p> <p>This code works as expected, but I just want to see if there are any conventions I should be following (especially C++11) and ideas to consider for efficiency.</p> <pre><code>#include &lt;iostream&gt; #include &lt;fstream&gt; #include &lt;vector&gt; #include &lt;string&gt; #include &lt;sstream&gt; #include &quot;sub.h&quot; int main() { std::ifstream file; file.open(...); if (!file) { std::cerr &lt;&lt; &quot;Error opening file.&quot; &lt;&lt; std::endl; return EXIT_FAILURE; } int n; std::string firstLine; getline(file, firstLine); std::stringstream(firstLine) &gt;&gt; n; int a,b,c; std::vector&lt;int&gt; A1,B1,C1; while (file &gt;&gt; a &gt;&gt; b &gt;&gt; c) { A1.push_back(a); B1.push_back(b); C1.push_back(c); } file.close(); std::ofstream output; output.open(...); output &lt;&lt; n &lt;&lt; &quot;\n&quot;; size_t size = A1.size(); for (size_t i=0; i&lt;size; ++i) { output &lt;&lt; A1[i] &lt;&lt; &quot; &quot; &lt;&lt; B1[i] &lt;&lt; &quot; &quot; &lt;&lt; C1[i] &lt;&lt; std::endl; } //call sub method with pointer to beginning of vectors //I have no control over sub method, its signature is (int, int*, int*, int*) int n1 = sub(n, &amp;A1[0], &amp;B1[0], &amp;C1[0]); //output result and close file output &lt;&lt; n1; output.close(); } </code></pre> <p>Example input:</p> <blockquote> <p>0 1 2 &lt;- This is A[0], B[0], C[0]</p> <p>2 3 4 &lt;- This is A[1], B[1], C[1]</p> <p>4 5 6 &lt;- This is A[2], B[2], C[2]</p> </blockquote> <p>The range-based <code>for</code>-loop would not work in this case. It would, however, if I printed all of A, B, or C on one line.</p>
[]
[ { "body": "<ul>\n<li><p>It's a good idea to order your STL <code>#include</code>s either alphabetically or by groups (see <a href=\"https://codereview.stackexchange.com/questions/30261/code-logicistic-and-cleanliness/30264#30264\">this</a> answer for more details). Header files should also precede STL <code>#include</code>s to avoid dependencies.</p></li>\n<li><p>I'd give your IO files more accurate names (such as <code>inFile</code> and <code>outFile</code>).</p></li>\n<li><p>Include <code>&lt;cstdlib&gt;</code> for <code>EXIT_FAILURE</code>.</p></li>\n<li><p>This is C++ and not C, so use <code>std::size_t</code> instead of <code>size_t</code>.</p></li>\n<li><p>Put the <code>std::vector</code> declarations (<code>A1</code>, <code>B1</code>, <code>C1</code>) on separate lines.</p></li>\n<li><p>You don't have to create another size variable for <code>A1.size()</code> just for a loop.</p>\n\n<p>In that same loop: you're looping through all three arrays at once, but are using one vector's size to do that. That's a bad idea. If they happen to be different sizes, you're going to run into problems.</p></li>\n<li><p>This:</p>\n\n<pre><code>int n1 = sub(n, &amp;A1[0], &amp;B1[0], &amp;C1[0]);\n</code></pre>\n\n<p>is best written as this (with iterators):</p>\n\n<pre><code>int n1 = sub(n, A1.begin(), B1.begin(), C1.begin());\n</code></pre></li>\n</ul>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T15:25:19.197", "Id": "48280", "Score": "0", "body": "Thanks for your comments. The reason I cannot do the range-based for loop is that I need to print in the same order as I input. I'll edit my question with an example." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T15:27:15.730", "Id": "48283", "Score": "0", "body": "Oh, okay. Again, just make sure you're always keeping alert of going out of bounds in any situation." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T15:28:42.053", "Id": "48285", "Score": "0", "body": "Thanks. I originally had `A.at(i)` because it had bounds checking. However, I decided against it due to a suggestion I've seen before about how `operator[]()` is faster than `.at()`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T15:30:19.710", "Id": "48286", "Score": "0", "body": "Right. `at()` is best if you *may* go out of bounds and/or if you need to throw exceptions." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T15:31:27.957", "Id": "48287", "Score": "0", "body": "Anyway, thank you again for all of your comments!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T15:36:08.840", "Id": "48291", "Score": "0", "body": "No problem! Feel free to vote on this once you've earned enough rep. I may still add to this answer if I find anything else." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T15:22:55.887", "Id": "30375", "ParentId": "30371", "Score": "5" } } ]
{ "AcceptedAnswerId": "30375", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T15:01:24.450", "Id": "30371", "Score": "6", "Tags": [ "c++" ], "Title": "Writing input into separate arrays and an output file" }
30371
<p>I'm being forced to use the common anti-pattern of a <code>public interface Constants</code> which many classes in this project implement. Long story short, I need to have a <code>List</code> constant which is pre-populated with values. Normally I would do this like so:</p> <pre><code>public static final List&lt;String&gt; MY_CONSTANT = new ArrayList&lt;String&gt;(); static { MY_CONSTANT.add("foo"); MY_CONSTANT.add("bar"); // ... } </code></pre> <p>Unfortunately, I can't use static initializers in an interface. So after much frustration, I finally have my implementation as follows:</p> <pre><code>public static final List&lt;String&gt; MY_CONSTANT = new ArrayList&lt;String&gt;() { private static final long serialVersionUID = 1898990046107150596L; { add("foo"); add("bar"); // ... } } </code></pre> <p>I hate the fact that I've made an anonymous extension like this and it makes me cringe. Are there any better techniques I can use to accomplish this? Changing the <code>Constants</code> file to a <code>class</code> instead of an <code>interface</code> isn't an option. As I said, I'm just retouching a large, pre-existing code base.</p>
[]
[ { "body": "<p>Not sure I understand your specific case entirely, but couldn't you just use enums for that purpose?</p>\n\n<p>As in...</p>\n\n<p>Simple version... </p>\n\n<pre><code>public enum MyConstants {\n FOO, BAR\n}\n// use method name() to get \"FOO\" or \"BAR\"...\n</code></pre>\n\n<p>Version with actual String values...</p>\n\n<pre><code>public enum MyConstants {\n FOO(\"foo\"), BAR(\"bar\");\n private String value; \n MyConstants(String value) {\n this.value = value;\n }\n public String getValue() {\n return value;\n }\n}\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T18:42:29.493", "Id": "48317", "Score": "0", "body": "Certainly this could work, but I want to *reduce* complexity, not add more. +1" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T16:52:00.523", "Id": "30382", "ParentId": "30380", "Score": "3" } }, { "body": "<p>If you only need constant of <code>java.util.List</code> type you can use static method <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Arrays.html#asList%28T...%29\" rel=\"noreferrer\"><code>java.util.Arrays.asList</code></a>:</p>\n\n<pre><code>import static java.util.Arrays.asList;\n\n...\n\npublic static final List&lt;String&gt; MY_CONSTANT = asList(\"foo\", \"bar\", \"baz\");\n</code></pre>\n\n<p>which creates immutable list instance with passed values.</p>\n\n<p>In cases when more complex object needs to be initialised I like to use static methods which create my constant:</p>\n\n<pre><code>public static final SomeComplexObject constant = createMyConstant();\n\nprivate static SomeComplexObject createMyConstant() {\n SomeComplexObject constant = new SomeComplexObject();\n constant.setProp1(...);\n constant.setProp2(...);\n ...\n return makeItSomehowImmutable(constant);\n}\n</code></pre>\n\n<p>In your case you won't be able to declare <code>private static</code> method inside interface, so the only thing I find reasonable is to create separate utility class with static methods which create constants, declare your method there and reuse it just like with <code>java.util.Arrays.asList</code> method.</p>\n\n<p>Hope this helps...</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T17:27:00.213", "Id": "30385", "ParentId": "30380", "Score": "7" } } ]
{ "AcceptedAnswerId": "30385", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T16:44:11.107", "Id": "30380", "Score": "7", "Tags": [ "java" ], "Title": "Initializing complex constant in Constants interface" }
30380
<p>I've implemented a Ruby version of Conway's Game of Life that functions correctly and passes all my tests. I was hoping to get some advice on how I could clean up the code for readability and efficiency.</p> <p>For anyone who doesn't know the rule to the Game of life, they are as follows:</p> <blockquote> <ul> <li>Any live cell with fewer than two live neighbours dies, as if by needs caused by underpopulation.</li> <li>Any live cell with more than three live neighbours dies, as if by overcrowding.</li> <li>Any live cell with two or three live neighbours lives, unchanged, to the next generation.</li> <li>Any dead cell with exactly three live neighbours becomes a live cell. </li> </ul> </blockquote> <p>(In my implementation, 1 is an alive cell and 0 is a dead cell).</p> <pre><code>class Game_of_life def initialize(hash) @test = nil str = hash[:string] size = hash[:size] @length = nil @board = [] if str != nil str.each_char {|c| @board &lt;&lt; c.to_i} @test = true @length = Math.sqrt(str.length) else (size*size).times do @board &lt;&lt; [0,1].sample end @length = size end end def check_board @board.each_with_index do |organism, index| neighbours = {alive: 0, dead: 0} neighbour_positions = choose_neighbour_set(index) neighbour_positions.each do |position| neighbours[:alive] += 1 if @board[index+position] == 1 neighbours[:dead] += 1 if @board[index+position] == 0 end @board[index] = 0 if organism == 1 &amp;&amp; (neighbours[:alive] &lt; 2 || neighbours[:alive] &gt; 3) @board[index] = 1 if organism == 0 &amp;&amp; neighbours[:alive] == 3 end if @test return @board.join("") else sleep 0.5 puts "\e[H\e[2J" @board.each_slice(@length) {|row| p row } check_board end end def choose_neighbour_set(index) neighbour_set = [-(@length), -(@length - 1), 1, (@length+1), @length, (@length-1), -1, -(@length + 1)] neighbour_set.delete_if{|position| [-(@length + 1), -(@length),-(@length - 1)].include?(position)} if index &lt; @length neighbour_set.delete_if{|position| [(@length-1),@length,(@length+1)].include?(position)} if index &gt; ((@length*(@length-1)) -1) neighbour_set.delete_if{|position| [-(@length + 1),-1,(@length-1)].include?(position)} if index % @length == 0 || index == 0 neighbour_set.delete_if{|position| [(@length+1),1,-(@length - 1)].include?(position)} if (index + 1) % @length == 0 &amp;&amp; index != 0 return neighbour_set end end # Uncomment to watch the game of life unfold! # Game_of_life.new({size: 25}).check_board # &gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt;&gt; Driver code # Test string one arr = "100100111110100011110110001100110010000010111101100010010111110110111100110000011" game = Game_of_life.new({string: arr}) p game.check_board == "110000101000111101110000101111110001100011101101000000000000110111111001101011111" # test string two arr2 = "110111000101110010011000100110100100000101110111001110111011011101110010010110110" game2 = Game_of_life.new({string: arr2}) p game2.check_board == "110011000100110110001010100001010010000100011101001000101001011100010001000111110" # test string three arr3 ='100110010' game3 = Game_of_life.new({string: arr3}) p game3.check_board == "110011011" # test string four arr4 = "0010010111001001" game4 = Game_of_life.new({string: arr4}) p game4.check_board == "0010101110100000" </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T09:38:33.913", "Id": "48365", "Score": "0", "body": "Ruby is the worst language for this problem." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T10:05:02.363", "Id": "48368", "Score": "0", "body": "@Nakilon Wow, that's a doozy. Please explain." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T12:14:38.430", "Id": "48386", "Score": "0", "body": "@MarkThomas, chosing the language for fast processing binary arrays? You really think it needs explanation?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T19:33:16.437", "Id": "48414", "Score": "0", "body": "@Nakilon I think you're making assumptions about the problem. You may be correct, but on the other hand, I've seen implementations in Perl, PHP, JS (none of which are considered particularly speedy languages) as well as Ruby which were perfectly fit for their purpose. Maybe it was just a learning exercise." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-29T07:41:54.883", "Id": "51062", "Score": "0", "body": "James, if @David has answered your question to your satisfaction, you should mark his answer as 'accepted'." } ]
[ { "body": "<ul>\n<li>Ruby convention is to use CamelCase for Classnames (GameOfLife)</li>\n<li>Since \"size\" and \"str\" are mutably exclusive parameters, using a hash parameter here makes the API confusing</li>\n<li>Using flags like \"@test\" to define object behavior is bad style (antipattern)</li>\n<li>Ruby doesn't have tail recursion, so you shouldn't do recursive calls without end conditions</li>\n</ul>\n\n<p>To make this more OOP like and self documenting you can define a base class for the basic initialization:</p>\n\n<pre><code>class GameOfLife\n def initialize(length)\n @length = length # Why not call this \"size\"?\n @board = []\n end\n\n def check_board\n # Implemented as above without the \"if\" statement\n end\n\n def choose_neighbour_set(index)\n # As above\n end\nend\n</code></pre>\n\n<p>Then you can use subclasses for specific implementations</p>\n\n<pre><code>class RandomGameOfLife &lt; GameOfLife\n def initialize(size)\n super(size)\n (size*size).times do\n @board &lt;&lt; [0,1].sample\n end\n end\n\n def iterate_and_output_board\n while true # Iterate till ^C?\n check_board\n sleep 0.5\n puts \"\\e[H\\e[2J\"\n @board.each_slice(@length) {|row| p row }\n end\n end\nend\n\nclass PredefinedGameOfLife &lt; GameOfLife # Or use a better name here\n def initialize(str)\n super(Math.sqrt(str.length))\n str.each_char {|c| @board &lt;&lt; c.to_i}\n end\n\n def check_board\n # This is just an example how to overwrite method behavior\n # Defining another method using \"check_board\" might be better here\n super\n @board.join(\"\")\n end\nend\n</code></pre>\n\n<p>Somebody else might cover the efficiency aspect. I don't want to intermix the aspects here and its better to focus on readability first.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-04T15:10:06.847", "Id": "48939", "Score": "0", "body": "Awesome, thank you very much. This alone helped me organize much more effectively." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-02T17:41:43.880", "Id": "51357", "Score": "0", "body": "\"Ruby doesn't have tail recursion, so you shouldn't do recursive calls without end conditions\" - Doesn't a recursive method need an end condition whether or not the language has tail call optimization?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-10-22T01:31:45.787", "Id": "52866", "Score": "0", "body": "@WayneConrad: Normally yes, hence my question \"Iterate till ^C?\". The end condition here is implicitly given by the signal handling of the process. But even then we don't know the limit of the number of iterations/recursions which might occur, so the loop should be implemented in a way which doesn't leak memory or fills the stack." } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T07:24:05.417", "Id": "30418", "ParentId": "30381", "Score": "3" } } ]
{ "AcceptedAnswerId": "30418", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T16:48:07.793", "Id": "30381", "Score": "3", "Tags": [ "ruby", "game-of-life" ], "Title": "Cleaning up code for Conway's Game of Life" }
30381
<p>I wrote up a simple averages calculator for student grades, based on <a href="http://www.reddit.com/r/dailyprogrammer/comments/1kphtf/081313_challenge_136_easy_student_management/" rel="nofollow">this</a> daily programming challenge.</p> <p>First, the script asks for the file name for the text file containing the student names and grades. It is formatted like so:</p> <pre><code>JON 19 14 15 15 16 JEREMY 15 11 10 15 16 JESSE 19 17 20 19 18 </code></pre> <p>The user is then asked how many assignments there are.</p> <p>While my solution works, it seems awfully verbose. Can you give me tips on "pythonic" ways to simplify the script?</p> <p><strong>grade_avg_generator.py</strong></p> <pre><code>"""Simple student grade manager""" from fileinput import input def import_data(grades_file, assignments): """Split the data into key value pairs.""" student_grades = dict() for line in input(grades_file): this_line = line.split() student_grades[this_line[0]] = [int(item) for item in this_line[1:assignments + 1]] return student_grades def student_means(student_grades): """Generate the average grade for each student and append it.""" for k, v in student_grades.iteritems(): grades = v grades_mean = float(sum(item for item in grades)) / len(grades) v.append(grades_mean) student_grades_mean = student_grades return student_grades_mean def class_mean(student_grades_mean): """Generate the class average.""" class_grades = list() for k, v in student_grades_mean.iteritems(): this_avg = v[-1] class_grades.append(this_avg) class_mean = float(sum(item for item in class_grades)) / len(class_grades) return class_mean def main(): grades_file = raw_input('File name: ') assignments = int(raw_input('How many assignments are there? ')) student_data = import_data(grades_file, assignments) student_data_avg = student_means(student_data) class_avg = class_mean(student_data_avg) print 'class average: %0.2f' % class_avg for k, v in student_data_avg.iteritems(): grades = v[:-1] grades = ' '.join(str(i) for i in grades) avg = str(v[-1]) print 'name: %s | grades: %s | average: %s' % (k, grades, avg) if __name__ == '__main__': main() </code></pre>
[]
[ { "body": "<p>For conciseness in Python, the key is to think in terms of applying functions using <code>map</code> and list comprehensions, rather than thinking procedurally. In this problem, it is very important to define a <a href=\"https://stackoverflow.com/questions/7716331\"><code>mean()</code></a> function. Once you do that, the calculations themselves are one-liners.</p>\n\n<p>The main objection I had to your code was that you mangled the data structure by appending each student's average at the end of his grades. Don't do that — <code>student_means()</code> should just return a fresh <code>dict</code> instead.</p>\n\n<p>I've taken out the non-essential prompt for the number of assignments; you can easily put it back.</p>\n\n<pre><code>\"\"\" Simple student grade manager\"\"\"\n\nfrom fileinput import input\n\ndef mean(list):\n return sum(map(float, list)) / len(list) \\\n if len(list) &gt; 0 else float('nan')\n\ndef import_student_grades(grades_file):\n \"\"\"\n Given a filename, reads data into a dict whose keys are student names\n and whose values are grades (as strings).\n \"\"\"\n line_words = [line.split() for line in input(grades_file)]\n return dict((words[0], words[1:]) for words in line_words)\n\ndef main():\n grades_file = raw_input('File name: ')\n student_grades = import_student_grades(grades_file)\n student_means = dict((k, mean(v)) for k, v in student_grades.iteritems())\n\n print 'class average: %0.2f' % mean(student_means.values())\n for name, grades in student_grades.iteritems():\n print 'name: %(name)s | grades: %(grades)s | average: %(avg)0.2f' % {\n 'name': name,\n 'grades': ' '.join(grades),\n 'avg': student_means[name],\n }\n\nif __name__ == '__main__':\n main()\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T22:34:16.910", "Id": "30404", "ParentId": "30388", "Score": "2" } } ]
{ "AcceptedAnswerId": "30404", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T18:43:26.813", "Id": "30388", "Score": "2", "Tags": [ "python", "csv", "statistics" ], "Title": "Computing average grades for students in a class" }
30388
<p>I haven't understood how I can perform (and so prevent ) a Directory traversal attack thorugh php.</p> <p>Probably isn't necessary, but I ask: my script contains a multiple file upload and download, this is the script to upload:</p> <pre><code>if (isset($setting[5]) &amp;&amp; $setting[5] == 1) { $msid = $DBH-&gt;lastInsertId(); if (isset($_FILES['filename'])) { $count = count($_FILES['filename']['name']); if ($count &gt; 0) { echo '&lt;script&gt;parent.noty({text: "File Upload Started",type:"information",timeout:2000});&lt;/script&gt;'; if (!is_dir('../upload')) { mkdir('../upload'); } $uploadarr = array(); $movedfiles = array(); $query = "INSERT INTO " . $SupportUploadTable . " (`name`,`enc`,`uploader`,`num_id`,`ticket_id`,`message_id`,`upload_date`) VALUES "; for ($i = 0; $i &lt; $count; $i++) { if ($_FILES['filename']['error'][$i] == 0) { if ($_FILES['filename']['size'][$i] &lt;= $maxsize &amp;&amp; $_FILES['filename']['size'][$i] != 0 &amp;&amp; trim( $_FILES['filename']['name'][$i] ) != '' ) { if (count(array_keys($movedfiles, $_FILES['filename']['name'][$i])) == 0) { $encname = uniqid(hash('sha256', $msid . $_FILES['filename']['name'][$i]), true); $target_path = "../upload/" . $encname; if (move_uploaded_file($_FILES['filename']['tmp_name'][$i], $target_path)) { if (CryptFile("../upload/" . $encname)) { $movedfiles[] = $_FILES['filename']['name'][$i]; $uploadarr[] = array($encid, $encname, $_FILES['filename']['name'][$i]); $query .= '("' . $_FILES['filename']['name'][$i] . '","' . $encname . '","' . $_SESSION['id'] . '",' . $tkid . ',"' . $refid . '","' . $msid . '","' . $date . '"),'; echo '&lt;script&gt;parent.noty({text: "' . $_FILES['filename']['name'][$i] . ' has been uploaded",type:"success",timeout:2000});&lt;/script&gt;'; } } } } else { echo '&lt;script&gt;parent.noty({text: "The file ' . $_FILES['filename']['name'][$i] . ' is too big or null. Max file size: ' . ini_get( 'upload_max_filesize' ) . '",type:"error",timeout:9000});&lt;/script&gt;'; } } else { if ($_FILES['filename']['error'][$i] != 4) { echo '&lt;script&gt;parent.noty({text: "File Name:' . $_FILES['filename']['name'][$i] . ' Error Code:' . $_FILES['filename']['error'][$i] . '",type:"error",timeout:9000});&lt;/script&gt;'; } } } if (isset($uploadarr[0])) { $query = substr_replace($query, '', -1); try { $STH = $DBH-&gt;prepare($query); $STH-&gt;execute(); $query = "UPDATE " . $SupportMessagesTable . " SET attachment='1' WHERE id=?"; $STH = $DBH-&gt;prepare($query); $STH-&gt;bindParam(1, $msid, PDO::PARAM_INT); $STH-&gt;execute(); } catch (PDOException $e) { file_put_contents('PDOErrors', $e-&gt;getMessage() . "\n", FILE_APPEND); echo '&lt;script&gt;parent.$(".main").nimbleLoader("hide");parent.noty({text: "An error has occurred, please contact the administrator.",type:"error",timeout:9000});&lt;/script&gt;'; } } echo '&lt;script&gt;parent.noty({text: "File Upload Finished",type:"information",timeout:2000});&lt;/script&gt;'; } } } </code></pre> <p>The download form:</p> <pre><code>&lt;form class="download_form" enctype="multipart/form-data" target="hidden_upload" action="../php/function.php" method="POST"&gt; &lt;input type="hidden" value="fcf5a1b982f5ada8440aa07a6ceaac65b0bccfd1cb9f425da0b3d76d71bfb7b1521e440a7ad805.86327361" name="ticket_id"&gt; &lt;input type="hidden" value="534eabdd15e48e23b570bb3a05a6f5e535952d9e526b39047d9a64fbe50a4789521e440a7fb5d5.01292029" name="file_download"&gt; &lt;input class="btn btn-link download" type="submit" value="key.txt"&gt; &lt;/form&gt; </code></pre> <p>Next I perform a query to retrieve the information and download the file.<br/> Basically I would like to know where the Directory traversal attack could be performed.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T18:48:02.200", "Id": "48318", "Score": "0", "body": "Do you have a page that lists all the files that can be downloaded? That's how a directory traversal attack is done, by following all the links on a page like that." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T18:50:22.817", "Id": "48319", "Score": "0", "body": "No, I have got only a folder with access denied through htaccess and that form to download the files" } ]
[ { "body": "<p>It doesn't appear to be vulnerable to <a href=\"https://www.owasp.org/index.php/Path_Traversal\" rel=\"nofollow\">Path Traversal</a> as you appear to be creating your own <code>$encname</code> variable to store the file rather than directly using the filename from an untrusted source (i.e. the POST request).</p>\n\n<p>Path Traversal usually happens if the user can manipulate a parameter to get to a file they normally can't access.</p>\n\n<p>e.g. if your normal URL is <code>www.example.com/get_file.php?file=readme.txt</code>, the user might be able to change the URL to <code>www.example.com/get_file.php?file=../private.txt</code> in order to read a file in the directory above.</p>\n\n<p>However, I would check your code for <a href=\"https://www.owasp.org/index.php/Cross-site_Scripting_%28XSS%29\" rel=\"nofollow\">XSS</a> and <a href=\"https://www.owasp.org/index.php/SQL_Injection\" rel=\"nofollow\">SQL Injection</a> as it appears to be vulnerable.</p>\n\n<p>For example, the output of <code>$_FILES['filename']['name'][$i]</code> in your code <code>echo '&lt;script&gt;parent.noty({text: \"' . $_FILES['filename']['name'][$i] . ' has been uploaded\",type:\"success\",timeout:2000});&lt;/script&gt;; }</code> should be <a href=\"https://www.owasp.org/index.php/XSS_%28Cross_Site_Scripting%29_Prevention_Cheat_Sheet#RULE_.233_-_JavaScript_Escape_Before_Inserting_Untrusted_Data_into_JavaScript_Data_Values\" rel=\"nofollow\">JS escaped</a>, otherwise it could be possible for an attacker to insert JavaScript into your page by uploading with a spoofed filename containing <code>&lt;script&gt;</code> tags.</p>\n\n<p>Your <code>INSERT</code> query should also use <code>prepare($query);</code> rather than manually building the query with string concatenation. This will stop an attacker changing the query in any way by again using a spoofed filename to break out of the SQL statement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T10:47:03.137", "Id": "48370", "Score": "0", "body": "Thanks! About XSS, is it sufficent to invert single and double quote and use the `htmlentities` php function? About the second point: substitute the name with a ?, insert the name inside an array and `bindParams` the array, is it the correct way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T11:03:07.163", "Id": "48376", "Score": "0", "body": "XSS - no, I would do it properly or there might be some way round it that you haven't thought of (Except for alphanumeric characters, escape all characters less than 256 with the \\xHH format). Yes, that sounds correct to prevent SQL injection." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T11:20:53.853", "Id": "48381", "Score": "0", "body": "I'm sorry, but I'm an Amateur, could you explain it in an easier way?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T11:30:24.873", "Id": "48382", "Score": "1", "body": "http://stackoverflow.com/questions/168214/pass-a-php-string-to-a-javascript-variable-and-escape-newlines - I'm not a PHP man myself so I can't vouch that that will encode everything as described." } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T10:38:38.857", "Id": "30427", "ParentId": "30390", "Score": "1" } } ]
{ "AcceptedAnswerId": "30427", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T18:44:23.280", "Id": "30390", "Score": "1", "Tags": [ "php", "security" ], "Title": "How to perform and prevent a Directory traversal attack" }
30390
<p>I have the following controller function. What I want to do is make this function do less. Most of this code is just random checks on various things that is also done on most of my other controllers. So to prevent from consistently copying and pasting this code THAT IS NOT where the access_level_id is checked in the if statement to be greater than or equal to four. That needs to stay.</p> <pre><code>/** * Content_pages::read() * * @return */ public function read() { // Initializes the user id with the value from the session user id if it exists. If there isn't a value present then the value is set to 0. $user_id = $this-&gt;session-&gt;userdata('user_id'); // Place to dump the user id to verify it is the expected value. // vardump($user_id); // Verifies that the user id is an accepted formed user id. if (($user_id !== FALSE) &amp;&amp; (is_numeric($user_id)) &amp;&amp; (strlen($user_id) &gt;= 5)) { // User data is an object that gathers all of the user data from the users table along with the email address from the login table with use of the user id variable. $user_data = $user = $this-&gt;user-&gt;with_login($user_id); // Place to dump the user data object to verify it is the expected properties and values for the user data object. // vardump($user_data); // Checks to verify that there is data inside of the user data object and that it is not empty. if (!empty($user_data)) { // Set a default for the user avatar. $default_avatar = 'default.jpg'; // Define where the avatars are located on the server. $avatar_directory = 'assets/globals/images/avatars/'; // Check to see if the user's avatar is null. if (!is_null($user_data-&gt;avatar)) { $avatar = $avatar_directory . $user_data-&gt;avatar; // Find out if the user's defined avatar exists on the server avatars directory. if (file_exists(FCPATH . $avatar)) { $user_data-&gt;avatar = base_url() . $avatar_directory . $user_data-&gt;avatar; } else { $user_data-&gt;avatar = base_url() . $avatar_directory . $default_avatar; } } else { $user_data-&gt;avatar = $default_avatar; } // Checks to see if the user has a role id of four and if they do then it shows the admin dashboard and if not then shows the user dashboard. if ($user_data-&gt;access_level_id &gt;= 4) { // Retrieve all the users from the database that handle characters and assign it to the users variable. $themes = $this-&gt;theme-&gt;get_all(); // Place to dump the users array to verify it is the expected value. // vardump($news_categories); // Checks to verify that there is data inside of the users array and that it is not empty. if (!empty($themes)) { $this-&gt;template-&gt;set('themes', $themes); } // Add the breadcrumbs to the view. $this-&gt;breadcrumb-&gt;add_crumb('&lt;li&gt;&lt;a href="' . base_url() . 'wrestling-manager/control-panel" class="glyphicons home"&gt;&lt;i&gt;&lt;/i&gt; Control Panel&lt;/a&gt;&lt;/li&gt;'); $this-&gt;breadcrumb-&gt;add_crumb('&lt;li&gt;&lt;i&gt;&lt;/i&gt; Themes&lt;/li&gt;'); $this-&gt;breadcrumb-&gt;change_link('&lt;li class="divider"&gt;&lt;/li&gt;'); // Sets all the properites for the template view. $this-&gt;template -&gt;set_theme('smashing') -&gt;set_layout('control_panel_view') -&gt;set_partial('header', 'partials/header') -&gt;set_partial('sidebar','partials/sidebar') -&gt;set_partial('footer', 'partials/footer') -&gt;title('Themes') -&gt;set('user_data', $user_data) -&gt;build('themes_view'); } else { // Redirect to custom error page // TODO: Make custom error page. } } else { // Getting redirected here means the user data object is empty. redirect('wrestling-manager/login'); } } else { // Getting redirected here means the user id was not an acceptable value. redirect('wrestling-manager/login'); } } </code></pre> <p><strong>EDIT :</strong> This was done yesterday before I received both answers. Could both people update their answers if possible.</p> <p>Control Panel Controller</p> <pre><code>&lt;?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class Control_panel extends MY_Controller { /** * Control_panel::__construct() * * Load the parent construct and any additional models, helper, libraries available. * * @return void */ public function __construct() { parent::__construct(); } /** * Control_panel::index() * * If user passes then we load the dashboard with the defined template and add the neccessary breadcrumbs and enable the profiler. * * @return void */ public function index() { $this-&gt;template -&gt;title('Wrestling Manager Control Panel'); if ($this-&gt;user_data-&gt;access_level_id &gt;= 4) { $this-&gt;template -&gt;build('admin_dashboard_view'); } else { $this-&gt;template -&gt;build('user_dashboard_view'); } } /** * Control_panel::logout() * * Logs out the current user from their session. * Then we redirect the user to the login page. * * @return void */ public function logout() { $this-&gt;session-&gt;sess_destroy(); redirect('wrestling-manager/login'); } public function show_dashboard() { } } </code></pre> <p>MY_Controller</p> <pre><code>&lt;?php if (!defined('BASEPATH')) exit('No direct script access allowed'); class MY_Controller extends CI_Controller { public $user_data; public function __construct() { parent::__construct(); $this-&gt;load-&gt;helper('flash_helper'); $this-&gt;load-&gt;model('user_model', 'user'); $this-&gt;output-&gt;enable_profiler(TRUE); $this-&gt;_check_auth(); $this-&gt;breadcrumb-&gt;add_crumb('&lt;li&gt;&lt;a href="' . base_url() . 'wrestling-manager/control-panel" class="glyphicons home"&gt;&lt;i&gt;&lt;/i&gt; Control Panel&lt;/a&gt;&lt;/li&gt;'); $this-&gt;breadcrumb-&gt;change_link('&lt;li class="divider"&gt;&lt;/li&gt;'); $this-&gt;template -&gt;set_theme('smashing') -&gt;set_layout('control_panel_view') -&gt;set_partial('header', 'partials/header') -&gt;set_partial('sidebar','partials/sidebar') -&gt;set_partial('footer', 'partials/footer') -&gt;set('user_data', $this-&gt;user_data); } private function _check_auth() { $user_id = $this-&gt;session-&gt;userdata('user_id'); // vardump($user_id); if (($user_id !== FALSE) &amp;&amp; (is_numeric($user_id)) &amp;&amp; (strlen($user_id) &gt;= 5)) { $this-&gt;user_data = $this-&gt;user-&gt;with_login($user_id); // vardump($user_data); if (!empty($this-&gt;user_data)) { $default_avatar = 'default.jpg'; $avatar_directory = 'assets/globals/images/avatars/'; if (!is_null($this-&gt;user_data-&gt;avatar)) { $this-&gt;avatar; $avatar = $avatar_directory . $this-&gt;user_data-&gt;avatar; if (file_exists(FCPATH . $avatar)) { $this-&gt;user_data-&gt;avatar = base_url() . $avatar_directory . $this-&gt;user_data-&gt;avatar; } else { $this-&gt;user_data-&gt;avatar = base_url() . $avatar_directory . $default_avatar; } } else { $this-&gt;user_data-&gt;avatar = $default_avatar; } } else { redirect('wrestling-manager/login'); } } else { redirect('wrestling-manager/login'); } } } </code></pre>
[]
[ { "body": "<p>Here it's a bit more DRY, perhaps someone else can take a crack at trying to get it DRYer:</p>\n\n<pre><code>&lt;?php\n/**\n * Content_pages::read()\n * \n * @return\n */\npublic function read(){\n # Initializes the user id with the value from the session user id if it exists. If there isn't a value present then the value is set to 0.\n $user_id = $this-&gt;session-&gt;userdata('user_id');\n\n\n # User data is an object that gathers all of the user data from the users table along with \n # the email address from the login table with use of the user id variable.\n $user_data = $user = $this-&gt;user-&gt;with_login($user_id);\n\n # Verifies that the user id is an accepted formed user id.\n if (($user_id !== FALSE &amp;&amp; is_numeric($user_id) &amp;&amp; strlen($user_id) &gt;= 5) || (empty($user_data))){\n # Set a default for the user avatar.\n $default_avatar = 'default.jpg';\n\n # Check to see if the user's avatar is null.\n if (!is_null($user_data-&gt;avatar)){\n # Define where the avatars are located on the server.\n $avatar_directory = 'assets/globals/images/avatars/';\n\n # Avatar based on user_data\n $avatar = $avatar_directory . $user_data-&gt;avatar;\n\n # Find out if the user's defined avatar exists on the server avatars directory.\n if (file_exists(FCPATH . $avatar)){\n $user_data-&gt;avatar = base_url() . $avatar_directory . $user_data-&gt;avatar;\n } else {\n $user_data-&gt;avatar = base_url() . $avatar_directory . $default_avatar;\n }\n } else {\n $user_data-&gt;avatar = $default_avatar;\n }\n\n\n # Checks to see if the user has a role id of four and if they do then it shows the admin dashboard and if not then shows the user dashboard.\n if ($user_data-&gt;access_level_id &gt;= 4){\n // Retrieve all the users from the database that handle characters and assign it to the users variable.\n $themes = $this-&gt;theme-&gt;get_all();\n\n # Checks to verify that there is data inside of the users array and that it is not empty.\n if (!empty($themes)){\n $this-&gt;template-&gt;set('themes', $themes);\n }\n\n # Add the breadcrumbs to the view.\n $this-&gt;breadcrumb-&gt;add_crumb('&lt;li&gt;&lt;a href=\"' . base_url() . 'wrestling-manager/control-panel\" class=\"glyphicons home\"&gt;&lt;i&gt;&lt;/i&gt; Control Panel&lt;/a&gt;&lt;/li&gt;');\n $this-&gt;breadcrumb-&gt;add_crumb('&lt;li&gt;&lt;i&gt;&lt;/i&gt; Themes&lt;/li&gt;');\n $this-&gt;breadcrumb-&gt;change_link('&lt;li class=\"divider\"&gt;&lt;/li&gt;');\n\n # Sets all the properites for the template view.\n $this-&gt;template\n -&gt;set_theme('smashing')\n -&gt;set_layout('control_panel_view')\n -&gt;set_partial('header', 'partials/header')\n -&gt;set_partial('sidebar','partials/sidebar')\n -&gt;set_partial('footer', 'partials/footer')\n -&gt;title('Themes')\n -&gt;set('user_data', $user_data)\n -&gt;build('themes_view'); \n } else {\n # Redirect to user dashboard (used to say custom error page here, but above in if statement it says user dash)\n redirect('user/dashboard');\n }\n } else {\n # Redirect since user_id was not an acceptable value OR the user data object is empty.\n redirect('wrestling-manager/login');\n }\n}\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T14:16:02.783", "Id": "30515", "ParentId": "30391", "Score": "0" } }, { "body": "<h1>DRY</h1>\n\n<p>The idea behind DRY is fairly deep:</p>\n\n<blockquote>\n <p>Every piece of knowledge must have a single, unambiguous, authoritative representation within a system.</p>\n</blockquote>\n\n<h1>Avatar</h1>\n\n<p>Developers often miss the idea that assigning a value to an instance variable in multiple places violates the DRY principle. Reading the code top-to-bottom reveals:</p>\n\n<pre><code>$user_data-&gt;avatar = base_url() . $avatar_directory . $user_data-&gt;avatar;\n$user_data-&gt;avatar = base_url() . $avatar_directory . $user_data-&gt;avatar;\n$user_data-&gt;avatar = base_url() . $avatar_directory . $default_avatar;\n$user_data-&gt;avatar = $default_avatar;\n</code></pre>\n\n<p>The <em>knowledge of how the avatar is assigned</em> occurs in multiple places throughout the code, thus breaking the DRY principle. The culprit begins with these lines:</p>\n\n<pre><code>$user_data = $user = $this-&gt;user-&gt;with_login($user_id);\nif (!is_null($user_data-&gt;avatar)){\n</code></pre>\n\n<p>Surely we can rewrite this:</p>\n\n<pre><code>$user = $this-&gt;user-&gt;with_login($user_id);\n\nif( !$user-&gt;has_avatar() ) {\n}\n</code></pre>\n\n<p>Now there is no handle to the user's data. Perfect. This allows how the data is represented to change without affecting the calling code (in this case, the code you've shown). There's something subtle happening here. What does it imply when you can check to see if a user has a valid avatar?</p>\n\n<p>It implies that you should also be able to set the user's avatar! Consider:</p>\n\n<pre><code>$default_avatar = 'default.jpg';\n...\n\n# Define where the avatars are located on the server.\n$avatar_directory = 'assets/globals/images/avatars/';\n\n# Avatar based on user_data\n$avatar = $avatar_directory . $user_data-&gt;avatar;\n\n# Find out if the user's defined avatar exists on the server avatars directory.\nif(file_exists(FCPATH . $avatar)){\n $user_data-&gt;avatar = base_url() . $avatar_directory . $user_data-&gt;avatar;\n} else {\n $user_data-&gt;avatar = base_url() . $avatar_directory . $default_avatar;\n}\n</code></pre>\n\n<p>The above code is not really the responsibility of the controller. It is the responsibility of the \"business object\", in this case the user. All the code above is actually:</p>\n\n<pre><code>$user-&gt;set_default_avatar();\n</code></pre>\n\n<p>Within that method, each line that looks like this:</p>\n\n<pre><code>$user_data-&gt;avatar = ...\n</code></pre>\n\n<p>Would be rewritten as:</p>\n\n<pre><code>$user_data-&gt;set_avatar( ... );\n</code></pre>\n\n<p>This could then be rewritten using an Avatar class. The Avatar class would know about:</p>\n\n<ul>\n<li>Default avatars</li>\n<li>Location of avatars on the server</li>\n</ul>\n\n<p>Consider this tempting code slipped into the controller:</p>\n\n<pre><code>$avatar = new Avatar(); \n$user_data-&gt;set_avatar( $avatar );\n</code></pre>\n\n<p>You wouldn't need the controller to set the avatar, until it changes. The <code>$user_data</code> would have a reference to a default <code>Avatar</code> instance. You could go further with an <code>AvatarFactory</code> that hides knowledge of how the <code>Avatar</code> instance is itself created (does it come from a local JPG image, a web server, or an uploaded file stream -- all should be irrelevant to the controller).</p>\n\n<p>Once the Avatar class exists, at that point all knowledge about Avatars would have a single authoritative representation in the system.</p>\n\n<h1>Roles and Source Comments</h1>\n\n<p>The following line is also missing the point of DRY:</p>\n\n<pre><code>$user_data-&gt;access_level_id &gt;= 4\n</code></pre>\n\n<p>What does 4 mean? What other places in the system will be comparing the \"access_level_id\" to magic numbers?</p>\n\n<p>The code should read more like a sentence:</p>\n\n<pre><code>if( $user-&gt;in_role( $ROLE_ADMIN ) ) {\n ...\n</code></pre>\n\n<p>Source comments should not parrot <em>what</em> the code is doing, but focus on <em>why</em> the code is there:</p>\n\n<pre><code>// Checks to see if the user has a role id of four\n</code></pre>\n\n<p>That comment was apparent from the code. The comment need only state the latter part:</p>\n\n<pre><code>// Show the dashboard based on the user's role.\n</code></pre>\n\n<p>That should give you a clue that the controller, again, is probably doing too much. Once you move the logic for determining the user's role back into the user, you can do magic like:</p>\n\n<pre><code>$user-&gt;show_dashboard();\n</code></pre>\n\n<p>The controller's responsibility is to cause the <code>dashboard</code> to appear. What type of <code>dashboard</code> is shown is not really its concern. The <code>show_dashboard</code> method then might do something like:</p>\n\n<pre><code>if( $user-&gt;in_role( $ROLE_ADMIN ) ) {\n ...\n $this-&gt;show_admin_dashboard();\n}\nelse {\n $this-&gt;show_user_dashboard();\n}\n</code></pre>\n\n<p>The <code>in_role</code> method might look like:</p>\n\n<pre><code>function in_role( $role ) {\n if( $role == $ROLE_ADMIN ) {\n return $this-&gt;get_role() &gt;= 4;\n }\n}\n</code></pre>\n\n<p>Except you'd want to not hard-code the value of <code>4</code>.</p>\n\n<p>Or <code>show_dashboard</code> could resemble:</p>\n\n<pre><code>// Gets the dashboard based on the user's role.\n$dashboard = $this-&gt;get_dashboard();\n$dashboard-&gt;show();\n</code></pre>\n\n<p>Or, to avoid the comment:</p>\n\n<pre><code>$dashboard = $this-&gt;get_dashboard( $this-&gt;get_role() );\n$dashboard-&gt;show();\n</code></pre>\n\n<p>Either way, the underlying implementation can vary without affecting the controller, and that's what is important.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T17:20:24.077", "Id": "48541", "Score": "0", "body": "That is all really awesome. Hopefully I can work on that and try and get something better formed for my controller. Is there anything non avatar related you would change?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T18:24:48.753", "Id": "48547", "Score": "0", "body": "If I worked on it and posted back in an hour would you scan over it again and tell me how the edits look. Only issue is I had placed some of that inside of a MY_Controller yesterday before I was able to update this post." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T18:58:38.383", "Id": "48549", "Score": "0", "body": "I created an Avatar Library on my github account. Thoughts? https://github.com/jeffreydavidson/Avatar" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T19:02:06.863", "Id": "48550", "Score": "0", "body": "Post another question, rather than adding comments here. You'll get more eyes on it." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T19:04:20.420", "Id": "48551", "Score": "0", "body": "Well I want to update my question here with what it pertains still to." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T19:14:56.913", "Id": "48553", "Score": "0", "body": "Your answer is so great but yesterday when I made a MY_Controller and looking at your stuff now I'm a bit confused and trying to piece it together. I updated with my edits." } ], "meta_data": { "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T17:13:33.360", "Id": "30520", "ParentId": "30391", "Score": "2" } } ]
{ "AcceptedAnswerId": "30520", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T19:11:08.263", "Id": "30391", "Score": "3", "Tags": [ "php", "codeigniter" ], "Title": "Helping to Make My Controller Function DRY" }
30391
<p>I'm working with knockout and am trying to stay true the MVVM structure and trying to make the objects have that dependency on each other.</p> <p>Model, ViewModel, Service definitions:</p> <pre><code>var App = window.App || {}; (function(ns, $, ko) { ns.Models = {}; ns.ViewModels = {}; ns.Services = ns.Services || {}; //Service def ns.Services.SearchService = function() { this.SearchByName = function(name, callback) { $.get("/api/SearchByName/" + name, function(d){ callback(d); }); }; }; //Model Def ns.Models.SearchResultModel = function(json) { var self = this; ko.mapping.fromJS(json, {}, self); }; //ViewModel def ns.ViewModels.SearchResultsViewModel = function() { var self = this; self.dataService = new ns.Services.SearchService(); self.SearchResults = ko.observableArray(); self.GetSearchResultsByName = function(name){ self.dataService.SearchByName(name, function(d) { $.each(d, function(i, e) { self.SearchResults.push(new ns.Models.SearchResultModel(e)); }); }); }; }; }(App, jQuery, ko)); </code></pre> <p>And I can currently use it like so:</p> <pre><code>var vm = new App.ViewModels.SearchResultsViewModel(); vm.GetSearchResultsByName("Doe"); ko.applyBindings(vm, document.getElementById("search-results-form")); </code></pre> <p>This is just my starting point and it seems like the <code>ko.applyBindings(...)</code> should be in the <code>ViewModel</code> somewhere.</p> <p>With all that, am I going the right direction for this or am I completely off with it?</p>
[]
[ { "body": "<p>This looks good me, just as it looked good for the SO reviewers.</p>\n\n<p>Some thoughts;</p>\n\n<ul>\n<li>Consider <code>'use strict';</code></li>\n<li>Consider naming your anonymous functions</li>\n<li>It is not clear how <code>SearchResultModel</code> deals with failed calls</li>\n<li><code>var self = this;</code> is only needed for closures, you don't need it in <code>ns.Models.SearchResultModel</code></li>\n</ul>\n\n<p>All in all, pretty solid.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-10-30T20:21:55.530", "Id": "68440", "ParentId": "30392", "Score": "2" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T19:12:03.040", "Id": "30392", "Score": "2", "Tags": [ "javascript", "mvvm", "knockout.js" ], "Title": "Structuring objects for proper MVVM in Knockout" }
30392
<p>I come today with a state machine I'm currently working on.</p> <p>Problem:</p> <blockquote> <p>Given any State that the Character is in, a button press or combination of button presses can modify that state in a different way than how the initial state was entered.</p> </blockquote> <p>I've looked at several different methods of creating a solution, but I feel that my current solution is lacking in its ability to be extendable. Would a Behavior Tree be more suitable for this kind of problem?</p> <pre><code>public class StateManager&lt;T&gt; where T : Engine.Object { //See notes in the Constructor. IState _currentState,_lastState,_nextState,_defaultState; T _objectReference; StateCompletion _onCompletion,_nextOnComplete; public StateManager(T objectRef) { //Creating a "NullState" removes any and all possibilities of a NRE in the event that the next state is considered Null. //It can also be used for error handling or testing deadlock cases. _defaultState = new NullState(); _onCompletion = OnComplete; _nextOnComplete = OnComplete; //This is to store the object that we are currently manipulating with the state machine itself. _objectReference = objectRef; //The various states of the state machine shift and store the various states it passes through. _currentState = _defaultState; _nextState = _defaultState; _lastState = _currentState; //Enter the default "NullState" _currentState.Enter(_objectReference,_lastState,_onCompletion); } //Used for the default NullState private void OnComplete(object isComplete) { Debug.LogWarning("Warning! You are acting on a Null State"); } public void ChangeState&lt;TU&gt;(StateCompletion onComplete) where TU : IState, new() { //Assign next OnComplete Delegate _nextOnComplete = onComplete; //Assign the appropriate state. _nextState = new TU(); if(_lastState != _currentState) //Set previous state if applicable. { _lastState = _currentState; } } public void Execute() { //This is essentially wrapping the inner state machines update loop. _currentState.Execute(); //Check Completion of the current State to catch when the state is finished calculating it's information. if(_currentState.IsComplete()) //States can be { SwitchState(); } } public void CheckModifier(KeyCode key) { //This would pass the keycode into the state and check to see if it could modify its current actions. _currentState.CheckStateModifiers(); //Something about this screams that this is going to lead to loads of repeated codes. } public void PhysicsExecute() { _currentState.PhysicsExcecute(); } private void SwitchState() { //Call the current states OnComplete delegate. _onCompletion(_objectReference); _onCompletion = _nextOnComplete; //Assign the next delegate based on the last state change request. //Begins calculating the next states information in Excecute. _currentState = _nextState; _currentState.Enter(_objectReference,_lastState,_onCompletion); //Set next OnComplete to the Null completion method. _nextState = _defaultState; _nextOnComplete = OnComplete; } } </code></pre>
[]
[ { "body": "<p>I think that you have an issue with general approach you have chosen. <code>StateManager</code> can still be improved tho.</p>\n\n<ol>\n<li><p>Use better and consistent naming. Why <code>_onCompletion</code> but <code>_nextOnComplete</code>? Why <code>_nextState</code>, but <code>_lastState</code> (shouldn't it be \"previous\"?)? Why <code>ChangeState()</code> when it doesnt change the current state, but sets the next state instead (i'm not sure i understand why it changes last state as well)? What <code>IsCompleted()</code> does? Does it actually checks for completion (then the name is fine) or does it retrieves the result of operation (then it could use a better naming)? Looks like it is the latter. It should be a property either way. Minor stuff like that improves code readability by a lot.</p></li>\n<li><p>Delegates are clearly coupled with states, so, if for some reason you can not refactor them into events of IState, you can implemet some aggregator-object:</p>\n\n<pre><code>private class StateInfo\n{\n public IState State { get; set; }\n public StateCompletion OnExecuted { get; set; }\n}\n</code></pre>\n\n<p>and then instead of </p>\n\n<pre><code>_onCompletion = _nextOnComplete;\n_currentState = _nextState;\n</code></pre>\n\n<p>use <code>_currentStateInfo = _nextStateInfo</code>. This will reduce the number of fields and assignments.</p></li>\n<li><p>I dont see an issue with <code>_currentState.CheckStateModifiers();</code>. Repeated code should be dealt with by extracting common logic to the base class (<code>StateBase</code>?).</p></li>\n<li><p>I'm not sure <code>_currentState.Enter</code> (state entering object) makes much sense. Shouldn't object enter state and not vice versa?</p></li>\n</ol>\n\n<p>It's hard to tell more without knowing implementation details and the logic you need to implement.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T20:52:42.883", "Id": "48422", "Score": "0", "body": "ChangeState() does a soft change that will set the next desired state, if another state is set on top of it, that state will be overwritten and the state pushed will take precedence. You are correct about IsComplete() it is waiting for the current state to return true. Once it does it will switch over to the state that is currently in line. I REALLY like your aggregation idea, thank you so much for that tip! The idea was that the states would act on the object and to isolate various physics and collision information in the separate state classes. Is this a bad idea? Thanks again!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T10:44:03.027", "Id": "30428", "ParentId": "30395", "Score": "2" } } ]
{ "AcceptedAnswerId": "30428", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T20:16:20.623", "Id": "30395", "Score": "4", "Tags": [ "c#", "delegates", "state-machine" ], "Title": "State Machine for Character" }
30395
<p>I'm designing a security camera program. Right now, I am just trying to set up the GUI before receiving. I am using Kivy since, in the future, I plan on designing some programs for Android. I really like Python, and I figured I'd start learning Kivy.</p> <p>My question is: am I building the GUI structure correctly?</p> <p>The layout I have planned is for the core container to have a <code>BoxLayout</code> that will hold three containers:</p> <ul> <li>The first container is on the left and will hold buttons to perform various commands.</li> <li>The second container will be in the center and will hold all the video feeds.</li> <li>The third container will be on the right and its purpose is still being considered.</li> </ul> <p></p> <pre><code>import kivy from kivy.config import Config Config.set('graphics', 'fullscreen', 'auto') from kivy.app import App from kivy.uix.label import Label from kivy.uix.button import Button from kivy.uix.boxlayout import BoxLayout from kivy.uix.anchorlayout import AnchorLayout class camMonitor(BoxLayout): def __init__(self, **kwargs): super(camMonitor, self).__init__(**kwargs) self.add_widget(controlInterface()) class controlInterface(BoxLayout): def __init__(self, **kwargs): super(controlInterface, self).__init__(**kwargs) button1 = Button(text='action 1', size =(50,30), size_hint=(None,None)) self.add_widget(button1) class camMonApp(App): def build(self): return camMonitor() if __name__ == '__main__': camMonApp().run() </code></pre> <p>For each container, I have created a separate class. Not every class will be a box layout; that's just what I have it set to at the moment.</p> <p>Should I continue building the GUI the way it is now, or should everything be put into one class?</p>
[]
[ { "body": "<p><strong>tl;dr</strong>: If you are planning on adding more methods to each of these classes, then use them. If not, then don't.</p>\n\n<p>One of the first things you should check when deciding whether to use a class or not, is if the class has two or less methods, <code>__init__</code>, and another function. Since your code doesn't like complete quite yet, I'm making the assumption that there will be more functions added to each of these classes.</p>\n\n<p>Now, I do have a few things about your code that I want to point out. Here's a list of small things you could improve.</p>\n\n<ol>\n<li>Class names should be in <code>PascalCase</code>. Not <code>lowerCasePascalCase</code>.</li>\n<li>There should be two blank lines between each class/function/code block on the top level of your file.</li>\n<li>You have a blank line before each of your class declarations. Preferably, you should either, put a docstring here, or, remove the blank line.</li>\n</ol>\n\n<p>If you want to make sure that your code is PEP8 compliant, you can visit PEP8's page <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow\">here</a>, or use this online PEP8 checker <a href=\"http://pep8online.com/\" rel=\"nofollow\">here</a>. If you want a checker on your local machine, you can just run <code>pip install pep8</code>, and to update, you can run <code>pip install --upgrade pep8</code>.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2015-06-27T14:39:26.903", "Id": "94905", "ParentId": "30396", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T20:53:46.687", "Id": "30396", "Score": "4", "Tags": [ "python", "gui", "user-interface", "layout", "kivy" ], "Title": "GUI layout for a security camera app" }
30396
<p>I've just launched my first project on GitHub. It's a jQuery plugin that helps create a responsive menu. It deals with interactivity (essentially using toggle and some classes), and leaves all the presentation stuff for CSS.</p> <p>Here is the basics for using the plugin:</p> <p><strong>First, create the structure with HTML:</strong></p> <pre><code>&lt;div id="content" class="canvas"&gt; &lt;!-- (...)Here goes the content (...) --&gt; &lt;/div&gt; &lt;!-- A button to toggle our menu --&gt; &lt;a href="#" id="menu-toggle"&gt;Menu&lt;/a&gt; &lt;!-- The menu wrapper --&gt; &lt;div id="menu"&gt; &lt;ul&gt; &lt;li&gt;&lt;a href="#"&gt;sample link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;sample link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;sample link&lt;/a&gt; &lt;!-- The submenu toggle button --&gt; &lt;a href="#" class="submenu-toggle"&gt;Open Submenu&lt;/a&gt; &lt;!-- The submenu wrapper --&gt; &lt;ul class="submenu"&gt; &lt;li&gt;&lt;a href="#"&gt;sample link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;sample link&lt;/a&gt;&lt;/li&gt; &lt;li&gt;&lt;a href="#"&gt;sample link&lt;/a&gt;&lt;/li&gt; &lt;/ul&gt; &lt;/li&gt; &lt;/ul&gt; &lt;/div&gt; </code></pre> <p><strong>Then, call it using jQuery:</strong></p> <pre><code>$('#menu').responsiveMenu($('#menu-toggle')); </code></pre> <p><strong>There are some others options to customize the plugin:</strong></p> <pre><code> $('#menu').responsiveMenu({ trigger: $('#menu-toggle'), activeClass: 'active', submenuTrigger: $('.submenu-toggle'), submenu: $('.submenu'), submenuActiveClass: 'open', breakpoint: 720 moveCanvas: true, canvas: $('.canvas'), }); </code></pre> <p>Where <code>$('#menu')</code> is the main wrapper of the menu, and <code>$('#menu-toggle')</code> is the button to activate the behavior of the plugin.</p> <p><strong>And, finally, the plugin code:</strong></p> <pre><code>;(function ( $, window, document, undefined ) { $.fn.responsiveMenu = function(settings){ var config = { 'trigger': null, 'activeClass': 'active', 'submenuTrigger': $('.sub-toggle'), 'submenu': false, 'submenuActiveClass': 'open', 'breakpoint': 720, 'timeOut': 100, 'moveCanvas': false, 'canvas': null, }; if (settings){$.extend(config, settings);} // declaring plugin variables var mTrigger; var menu = $(this); var active = config.activeClass; var button = config.trigger; var bpoint = config.breakpoint; var submTrigger = config.submenuTrigger; var submenu = config.submenu; var submenuClass = '.' + submenu.prop('class'); var submenuActive = config.submenuActiveClass; var canvasOn = config.moveCanvas; var canvas = config.canvas; var time = config.timeOut; return this.each(function () { if($(window).width() &gt; bpoint){ mTrigger = false; } else { mTrigger = true; } onChange = function(){ clearTimeout(resizeTimer); var resizeTimer = setTimeout(function(){ if($(window).width() &gt; bpoint){ mTrigger = false; menu.removeClass(active); button.removeClass(active); if(canvasOn){ canvas.removeClass(active); } } else { mTrigger = true; } }, time); } $(window).bind('resize',onChange); $(document).ready(onChange); button.click(function(e){ e.preventDefault(); if(mTrigger) { menu.toggleClass(active); button.toggleClass(active); if(canvasOn){ canvas.toggleClass(active); } } }); if(submenu){ // toggle for the submenus submTrigger.click(function(e){ e.preventDefault(); if(mTrigger) { if($(this).hasClass(active)){ submTrigger.removeClass(active); submenu.removeClass(submenuActive); } else { submTrigger.removeClass(active); $(this).addClass(active); submenu.removeClass(submenuActive); $(this).next(submenuClass).addClass(submenuActive); } } }); } }); } })( jQuery, window, document ); </code></pre> <p>If you want to check the repository of the plugin, <a href="http://github.com/diegoliv/responsiveMenu.js">here's the link</a>.</p> <p>In the repository, there is more information about it, such as which option does what in the plugin, etc. <a href="http://diegoliv.github.io/responsiveMenu.js/">There is a simple demo as well</a>.</p> <p>The plugin is in development, so I'm searching for feedback on it. I'm okay with best practices, performance, and possibly any suggestions and contributions as well.</p>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T18:52:54.517", "Id": "49158", "Score": "0", "body": "Nice little plugin you got there! Representando o Brasil na net - show de bola! What happens if I were to have sub-sub-menus? IE: `<ul>\n <li>\n <ul>\n <li>\n <ul>\n <li></li>\n </ul>\n </li>\n </ul>\n </li>\n</ul>`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-06T20:16:02.650", "Id": "49175", "Score": "1", "body": "Valeu, @JonnySooter! Que bom que curtiu!\n\nThanks, I'm glad that you liked! Well, for now I only supported two levels of menus, because this is the use case for most of the times when I need to use it. But I plan to push a update soon that support multiple levels of submenus. I plan too in the next update, to create some methods (like `responsiveMenu.init()` or `responsiveMenu.reset()`) and improve the instantiation (like `var menu = new responsiveMenu({options});`. Keep your eyes on it!" } ]
[ { "body": "<p>Don't be intimidated be the size of the book, I just like to write out and explain in as much detail as possible. Well anyways, I've pretty much re-wrote the whole plugin. I've applied a more object-oriented approach and re-factored the plugin into the <a href=\"http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html\" rel=\"nofollow\">Module Design</a> pattern. It's now much easier to add functionality and debug code. I've also added in some safe guards to properly initiate the plugin as well. At the end of the code, and inside it, I've included a few links for reading and watching materials. I highly recommend you go through them as they can explain the concepts demonstrated here a lot better than I can.</p>\n\n<pre><code>;(function ( $, window, document, undefined ) {\n\n\"use strict\";\n\nvar $window = $(window),\n ResponsiveMenu = { \n //This is your main object, it holds everything about your plugin\n //This way you can easily add methods and functionality to your plugin\n //It also provides an easy way to chain methods\n //It makes it easy to spot bugs because the code is broken down into sections/methods\n\n init: function(options, elem) {\n //In your functions \"this\" refers to the ResponsiveMenu object\n //To call your methods you can do \"this.init()\" or \"this.options\"\n\n this.options = $.extend( {}, this.options, options ); //Basic options extend\n this.elem = $(elem); //Here I cache the element that the plugin was called on $(\"menu\")\n\n if($window.width() &gt; this.options.breakpoint) {\n this.options.mTrigger = false;\n }\n\n this.bindEvents(); //Call my first method\n\n return this; //Maintain chainable\n },\n\n options: { //Options\n trigger: null,\n activeClass: 'active',\n submenuTrigger: $('.sub-toggle'),\n submenu: false,\n submenuActiveClass: 'open',\n breakpoint: 720,\n timeOut: 100,\n moveCanvas: false,\n canvas: null,\n mTrigger: true,\n callback: null\n },\n\n bindEvents: function() {\n //Here I cache the reference to ResponsiveMenu\n //I do this because inside event callback methods, \"this\" refers to the element the event was triggered from\n //Now I can still refer to my main object and keep \"this\" inside the callbacks the same\n var self = this;\n\n this.options.trigger.on('click', function(evt) {\n evt.preventDefault();\n //As you see here I use \"self\" to refer to the main ResponsiveMenu object\n //If I would have used \"this\" I would be referring to the \"trigger\" element\n self.triggerMain(self); //From here we go to the \"triggerMain\" method\n });\n\n if(this.options.submenu){\n this.options.submenuTrigger.on(\"click\", function(evt) { //Same idea from the one above\n evt.preventDefault();\n self.triggerSubMenu(this, self);\n });\n }\n\n //Here I put in a safeguard on your resize event\n //As you probably know, the resize event fires every time there is a resize, even if you're not finished resizing\n //To prevent that I added in a custom event\n $window.on('resize', function() {\n if(this.resizeTO) clearTimeout(this.resizeTO); //Here we see if there's a timeout open, if yes, cancel it\n\n this.resizeTO = setTimeout(function() { //Set a time out so that the event is only triggered once\n $(this).trigger('resizeEnd'); //Trigger the event\n }, self.options.timeOut); //After \"time\"\n });\n\n //I set up the custom event here\n //This will only be called once\n $window.on('resizeEnd', this.onFinalResize(self)); //When this happens, we move down to \"onFinalResize\" method\n },\n\n triggerMain: function(self) {\n //I pass \"self\" here because in here \"this\" still refers to the \"trigger\" element because this has the context of a callback method\n var activeClass = self.options.activeClass;\n\n if(self.options.mTrigger) {\n self.elem.toggleClass(activeClass);\n self.options.trigger.toggleClass(activeClass);\n\n if(self.options.moveCanvas){\n self.options.canvas.toggleClass(activeClass);\n }\n }\n },\n\n triggerSubMenu: function(elem, self) {\n //Here I did things a bit differently to show you different ways to do the same thing\n //As a rule of thumb, if you use a selection more than once, you should cache it\n //So here we cache the clicked element\n //You could use \"this\" instead, but I used \"elem\" so it would be easier to understand\n var $elem = $(elem),\n activeClass = self.options.activeClass,\n subActiveClass = self.options.submenuActiveClass,\n submenu = self.options.submenu;\n\n if(self.options.mTrigger) {\n if($elem.hasClass(activeClass)) {\n $elem.removeClass(activeClass);\n submenu.removeClass(subActiveClass);\n } else {\n $elem.removeClass(activeClass);\n $elem.addClass(activeClass);\n submenu.removeClass(subActiveClass);\n $elem.next('.' + submenu.prop('class')).addClass(subActiveClass);\n }\n }\n },\n\n onFinalResize: function(self) {\n //This is all your code, just that referencing the main object\n if($window.width() &gt; self.options.breakpoint){\n\n var activeClass = self.options.activeClass;\n\n self.options.mTrigger = false;\n self.elem.removeClass(activeClass);\n self.options.trigger.removeClass(activeClass);\n\n if(self.options.moveCanvas) {\n self.options.canvas.removeClass(activeClass);\n }\n\n if (typeof self.options.callback == 'function') {\n self.options.callback.call(this);\n }\n\n } else {\n self.options.mTrigger = true;\n }\n }\n} //ResponsiveMenu\n\n//This section here is Crockford's shim to true prototypal inheritance\n//Read up here: http://javascript.crockford.com/prototypal.html\nif ( typeof Object.create !== 'function' ) {\n Object.create = function (o) {\n function F() {}\n F.prototype = o;\n return new F();\n };\n}\n\n//Here is where your plugin actually gets set up\n$.fn.responsiveMenu = function( options ) { //Add to the namespace\n if (this.length) {\n return this.each(function() {\n var myMenu = Object.create(ResponsiveMenu); //Create the ResponsiveMenu object we made above and save it to \"myMenu\"\n myMenu.init(options, this); //Call the init method, passing in the user's options and the element the plugin wall called on\n $.data(this, 'responsiveMenu', myMenu); //Store the information from our plugin in a safe way - no memory leaks\n });\n }\n};\n})( jQuery, window, document );\n</code></pre>\n\n<p>A really good \"course\" for someone getting started with jQuery is the <strong><a href=\"https://tutsplus.com/course/30-days-to-learn-jquery/\" rel=\"nofollow\">30 Days to Learn jQuery</a></strong> by Jeffery Way. He does a great job with explaining tough concepts and provides an overall lesson on jQuery and plugin development. You have some experience so I'd skip the first few videos and jump right into where you'll start learning.</p>\n\n<p>Anyways, there is no one size fits all when it comes to making plugins. I've simply demonstrated the way I like best. Use this as a learning experience and not as a \"this is how you should do it\". If you have any questions after this or if there's some part that isn't very clear, let me know, and I can elaborate some more.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-10T13:34:49.050", "Id": "49440", "Score": "0", "body": "Awesome! I liked very much this approach of creating an object that holds all the functions of the plugin! I'm currently learning a little of Backbone.js and I see some similarities with it. Also, very interesting reading on Crockford's article about true prototypal inheritance! And I'll be watching for sure this jQuery series!\n\nNow, I see that the plugin is really more extensible and maintainable. I'll be merging your commits later today!" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-09T22:31:10.650", "Id": "31022", "ParentId": "30397", "Score": "2" } } ]
{ "AcceptedAnswerId": "31022", "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T21:02:15.093", "Id": "30397", "Score": "6", "Tags": [ "javascript", "jquery", "plugin" ], "Title": "jQuery plugin that helps create a responsive Menu" }
30397
<p>What might be wrong with this shared pointer? One good point of it might be, that it should handle array types correctly by default (e.g. <code>light_ptr&lt;int[]&gt;(new int[10])</code>.</p> <p><code>std::shared_ptr</code> has the advantage of being more portable. For example, <code>emscripten</code> provides an implementation, but <code>light_ptr</code> won't compile, still, it can be ported to <code>emscripten</code> easily. The native implementation may also be more optimized.</p> <pre><code>#pragma once #ifndef LIGHTPTR_HPP # define LIGHTPTR_HPP #include &lt;cassert&gt; #include &lt;atomic&gt; #include &lt;memory&gt; #include &lt;utility&gt; #include &lt;type_traits&gt; namespace detail { using counter_type = ::std::size_t; using atomic_type = ::std::atomic&lt;counter_type&gt;; template &lt;typename T&gt; using deleter_type = void (*)(T*); template &lt;typename U&gt; struct ref_type { using type = U&amp;; }; template &lt;&gt; struct ref_type&lt;void&gt; { using type = void; }; template &lt;typename T&gt; inline void dec_ref(atomic_type* const counter_ptr, T* const ptr, deleter_type&lt;T&gt; const deleter) { if (counter_ptr &amp;&amp; (counter_type(1) == counter_ptr-&gt;fetch_sub(counter_type(1), ::std::memory_order_relaxed))) { delete counter_ptr; deleter(ptr); } // else do nothing } inline void inc_ref(atomic_type* const counter_ptr) { assert(counter_ptr); counter_ptr-&gt;fetch_add(counter_type(1), ::std::memory_order_relaxed); } } template &lt;typename T&gt; struct light_ptr { template &lt;typename U, typename V&gt; struct deletion_type { using type = V; }; template &lt;typename U, typename V&gt; struct deletion_type&lt;U[], V&gt; { using type = V[]; }; template &lt;typename U, typename V, ::std::size_t N&gt; struct deletion_type&lt;U[N], V&gt; { using type = V[]; }; template &lt;typename U&gt; struct remove_array { using type = U; }; template &lt;typename U&gt; struct remove_array&lt;U[]&gt; { using type = U; }; template &lt;typename U, ::std::size_t N&gt; struct remove_array&lt;U[N]&gt; { using type = U; }; using element_type = typename remove_array&lt;T&gt;::type; using deleter_type = ::detail::deleter_type&lt;element_type&gt;; light_ptr() = default; template &lt;typename U&gt; explicit light_ptr(U* const p, deleter_type const d = default_deleter&lt;U&gt;) { reset(p, d); } ~light_ptr() { ::detail::dec_ref(counter_ptr_, ptr_, deleter_); } light_ptr(light_ptr const&amp; other) { *this = other; } light_ptr(light_ptr&amp;&amp; other) noexcept { *this = ::std::move(other); } light_ptr&amp; operator=(light_ptr const&amp; rhs) { if (*this != rhs) { ::detail::dec_ref(counter_ptr_, ptr_, deleter_); counter_ptr_ = rhs.counter_ptr_; ptr_ = rhs.ptr_; deleter_ = rhs.deleter_; ::detail::inc_ref(counter_ptr_); } // else do nothing return *this; } light_ptr&amp; operator=(light_ptr&amp;&amp; rhs) noexcept { if (*this != rhs) { counter_ptr_ = rhs.counter_ptr_; ptr_ = rhs.ptr_; deleter_ = rhs.deleter_; rhs.counter_ptr_ = nullptr; rhs.ptr_ = nullptr; } // else do nothing return *this; } bool operator&lt;(light_ptr const&amp; rhs) const noexcept { return get() &lt; rhs.get(); } bool operator==(light_ptr const&amp; rhs) const noexcept { return counter_ptr_ == rhs.counter_ptr_; } bool operator!=(light_ptr const&amp; rhs) const noexcept { return !operator==(rhs); } bool operator==(::std::nullptr_t const) const noexcept { return !ptr_; } bool operator!=(::std::nullptr_t const) const noexcept { return ptr_; } explicit operator bool() const noexcept { return ptr_; } typename ::detail::ref_type&lt;T&gt;::type operator*() const noexcept { return *static_cast&lt;T*&gt;(static_cast&lt;void*&gt;(ptr_)); } T* operator-&gt;() const noexcept { return static_cast&lt;T*&gt;(static_cast&lt;void*&gt;(ptr_)); } element_type* get() const noexcept { return ptr_; } void reset() { reset(nullptr); } void reset(::std::nullptr_t const) { ::detail::dec_ref(counter_ptr_, ptr_, deleter_); counter_ptr_ = nullptr; ptr_ = nullptr; } template &lt;typename U&gt; void reset(U* const p, deleter_type const d = default_deleter&lt;U&gt;) { ::detail::dec_ref(counter_ptr_, ptr_, deleter_); counter_ptr_ = new ::detail::atomic_type(::detail::counter_type(1)); ptr_ = p; deleter_ = d; } void swap(light_ptr&amp; other) noexcept { ::std::swap(counter_ptr_, other.counter_ptr_); ::std::swap(ptr_, other.ptr_); ::std::swap(deleter_, other.deleter_); } bool unique() const noexcept { return ::detail::counter_type(1) == use_count(); } ::detail::counter_type use_count() const noexcept { return counter_ptr_ ? counter_ptr_-&gt;load(::std::memory_order_relaxed) : ::detail::counter_type{}; } template &lt;typename U&gt; static void default_deleter(element_type* const p) { ::std::default_delete&lt;typename deletion_type&lt;T, U&gt;::type&gt;()( static_cast&lt;U*&gt;(p)); } private: ::detail::atomic_type* counter_ptr_{}; element_type* ptr_{}; deleter_type deleter_; }; template&lt;class T, class ...Args&gt; inline light_ptr&lt;T&gt; make_light(Args&amp;&amp; ...args) { return light_ptr&lt;T&gt;(new T(::std::forward&lt;Args&gt;(args)...)); } namespace std { template &lt;typename T&gt; struct hash&lt;light_ptr&lt;T&gt; &gt; { size_t operator()(light_ptr&lt;T&gt; const&amp; l) const noexcept { return hash&lt;typename light_ptr&lt;T&gt;::element_type*&gt;(l.get()); } }; } #endif // LIGHTPTR_HPP </code></pre> <p><strong>Usage:</strong></p> <pre><code>#include &lt;iostream&gt; #include &lt;thread&gt; #include &lt;vector&gt; #include "lightptr.hpp" int main() { { light_ptr&lt;int&gt; p(new int); *p = 10; light_ptr&lt;int&gt; s(p); p.reset(new int); std::cout &lt;&lt; s.use_count() &lt;&lt; ": " &lt;&lt; *s &lt;&lt; std::endl; std::vector&lt;light_ptr&lt;float&gt; &gt; v(1000000); for (auto&amp; r: v) { r.reset(new float); *r = 100; } auto a(make_light&lt;char[4]&gt;()); (*a)[2] = 10; a.get()[3] = 10; ::std::thread a_([&amp;p]{light_ptr&lt;int&gt; a(p); std::cout &lt;&lt; p.use_count() &lt;&lt; std::endl;}); ::std::thread b_([&amp;p]{light_ptr&lt;int&gt; a(p); std::cout &lt;&lt; p.use_count() &lt;&lt; std::endl;}); ::std::thread c_([&amp;p]{light_ptr&lt;int&gt; a(p); std::cout &lt;&lt; p.use_count() &lt;&lt; std::endl;}); ::std::thread d_([&amp;p]{light_ptr&lt;int&gt; a(p); std::cout &lt;&lt; p.use_count() &lt;&lt; std::endl;}); ::std::thread e_([&amp;p]{light_ptr&lt;int&gt; a(p); std::cout &lt;&lt; p.use_count() &lt;&lt; std::endl;}); ::std::thread f_([&amp;p]{light_ptr&lt;int&gt; a(p); std::cout &lt;&lt; p.use_count() &lt;&lt; std::endl;}); ::std::thread g_([&amp;p]{light_ptr&lt;int&gt; a(p); std::cout &lt;&lt; p.use_count() &lt;&lt; std::endl;}); ::std::thread h_([&amp;p]{light_ptr&lt;int&gt; a(p); std::cout &lt;&lt; p.use_count() &lt;&lt; std::endl;}); a_.join(); b_.join(); c_.join(); d_.join(); e_.join(); f_.join(); g_.join(); h_.join(); } struct A { ~A() { std::cout &lt;&lt; "deleted" &lt;&lt; std::endl; } }; light_ptr&lt;void&gt; a(new A); light_ptr&lt;A[]&gt; b(new A[1]); return 0; } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T22:33:21.840", "Id": "48435", "Score": "2", "body": "Writing your own shared pointer is a bad idea. It is a lot harder than you think to just get it working correctly. Optimizing is a step on top of that. But making it work should be your priority. PS. The standard one does not use any compiler specific tricks." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T08:13:02.383", "Id": "48482", "Score": "0", "body": "However, I can point out one thing (so far): you're using two different header guards. I'd remove the `#pragma once` while keeping the other." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T08:19:05.783", "Id": "48483", "Score": "0", "body": "@Jamal That's a backup for compilers that don't support the `#pragma once`." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-13T21:31:21.923", "Id": "87380", "Score": "0", "body": "@user1095108: In that case you are stacking them wrong. Put the pragma inside the other header-guard." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-13T21:36:43.880", "Id": "87384", "Score": "0", "body": "@Deduplicator I've read somewhere that `#pragma once` is faster of the two header guards. That's why I put it first, since otherwise I would defeat the purpose why I use both header guards. There seems to be nothing wrong, if one uses both." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-05-13T22:07:20.227", "Id": "87401", "Score": "0", "body": "Both are of equal speed if implemented properly. But the standard `#ifndef`-Guards optimisation heavily depends on the guards actually bracketing *the whole file*, while that's not the case for `#pragma once`. Anyway, if there was a speed difference the same would still hold, please read up on how they work / can be optimised / are optimised." } ]
[ { "body": "<p>The move assignment operator is broken:</p>\n\n<pre><code>light_ptr&amp; operator=(light_ptr&amp;&amp; rhs) noexcept\n</code></pre>\n\n<p>You over write the current members with the values from the rhs, but do not decrement the reference counter before overwriting. It might be easier to swap <code>*this</code> with <code>rhs</code>. </p>\n\n<p>Don't include types that are not being used:</p>\n\n<pre><code> template &lt;typename U, typename V, ::std::size_t N&gt;\n struct deletion_type&lt;U[N], V&gt;\n {\n using type = V[];\n };\n\n template &lt;typename U, ::std::size_t N&gt;\n struct remove_array&lt;U[N]&gt;\n {\n using type = U;\n };\n</code></pre>\n\n<p>Casting to void*. Once this is done the only valid operation is to cast back to the original type. Annything else is undefined.</p>\n\n<pre><code> return static_cast&lt;T*&gt;(static_cast&lt;void*&gt;(ptr_));\n</code></pre>\n\n<p>In this case <code>element_type*</code> is the same as <code>T*</code>. But the code is written in such a way that any changes by a maintainer can easily result in this being not true. Also I don;t actually see the need for a cast.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-12-31T09:17:59.687", "Id": "75330", "ParentId": "30398", "Score": "4" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "6", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T21:16:57.163", "Id": "30398", "Score": "4", "Tags": [ "c++", "c++11", "reinventing-the-wheel", "pointers" ], "Title": "Yet another shared pointer" }
30398
<p>I'm new to programming, and I would like to know if this is the right way to layout code. If anyone has any tips, please share them.</p> <pre><code>import random import time def displayIntro(): print("You are in a land full of dragons. In front of") print("you are two caves. In one cave the dragon is") print("friendly and will give you his treasure. In the") print("other, the dragon is greedy and hungry and will") print("eat you on sight") print() def chooseCave(): cave = "" while cave != "1" and cave != "2": print("Which cave will you choose? (1 or 2)") cave = input() return cave def checkCave(chosenCave): print("You approach the cave...") time.sleep(2) print("It is dark and spooky...") time.sleep(2) print("A large dragon jumps out in front of you. He opens his jaws and...") print() time.sleep(2) friendlyCave = random.randint(1,2) if chosenCave == str(friendlyCave): print("gives you his treasure") else: print("gobbles you down in one bite") playAgain = "yes" while playAgain =="yes" or playAgain == "y": displayIntro() caveNumber = chooseCave() checkCave(caveNumber) print("Would you like to play again? (yes or no)") playAgain = input() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T21:47:50.627", "Id": "48335", "Score": "0", "body": "General rules for code layout in Python are stated in [PEP 8 -- Style Guide for Python Code](http://www.python.org/dev/peps/pep-0008/)." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T04:20:35.520", "Id": "48339", "Score": "3", "body": "This is one of the most suspenseful code examples I've come across. My main bits of advice would be to use a main function instead of the raw script style execution and to store the chosen cave as an int instead of as a string, and then do int comparison instead of string comparison though." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T07:18:18.963", "Id": "487369", "Score": "1", "body": "The code presented seems to be from Al Sweigart's *Invent Your Own Computer Games with Python*, chapter *Dragon Realm*." }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T11:41:13.090", "Id": "487393", "Score": "2", "body": "For anyone in the CV queue, et al.: the code is identical to code on page 57 of [this PDF](https://inventwithpython.com/inventwithpython_3rd.pdf) which supports the claim by greybeard, though there are a couple changes, including string format and capitalization" }, { "ContentLicense": "CC BY-SA 4.0", "CreationDate": "2020-09-01T11:57:49.717", "Id": "487398", "Score": "0", "body": "@SᴀᴍOnᴇᴌᴀ Meant to say page 47 (or 59 if going by the pdf's auto pages)" } ]
[ { "body": "<p>(1) For variable and function names, <code>check_cave</code> (underscore) rather than <code>checkCave</code> (camelcase) are standard in python.</p>\n\n<p>(2) The line <code>def chooseCave</code> needs to be unindented</p>\n\n<p>(3) Your main game loop could probably be neatened up:</p>\n\n<pre><code>while True:\n display_intro()\n check_cave(choose_cave())\n print(\"Would you like to play again? (yes or no)\")\n if input() not in ('yes', 'y'):\n break\n</code></pre>\n\n<p>(4) conventionally you should put the main game loop in a function called <code>main()</code> <a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">and add</a></p>\n\n<pre><code>if __name__ == \"__main__\":\n main()\n</code></pre>\n\n<p>at the end.</p>\n\n<p>(5) More a matter of taste, but I'd find it more elegant to write choose_cave like this:</p>\n\n<pre><code>def choose_cave():\n while True:\n print(\"Which cave will you choose? (1 or 2)\")\n cave = input()\n if cave in ('1', '2'):\n return cave\n</code></pre>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T22:36:24.740", "Id": "30405", "ParentId": "30400", "Score": "13" } }, { "body": "<p>In addition to other answers you can use 'in' to compare for more than one value.</p>\n\n<p>So</p>\n\n<pre><code>while cave != \"1\" and cave != \"2\":\n ...\n</code></pre>\n\n<p>becomes:</p>\n\n<pre><code>while cave not in [\"1\", \"2\"]:\n ...\n</code></pre>\n\n<p>or even:</p>\n\n<pre><code>caves = set(\"12\")\nwhile cave not in caves:\n ...\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-12T07:42:02.773", "Id": "368325", "Score": "0", "body": "a `set` is a more natural container to check presence" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-13T09:19:01.543", "Id": "368546", "Score": "0", "body": "That is true. `while cave not in Set([\"1\", \"2\"]):`" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-13T09:38:49.670", "Id": "368549", "Score": "1", "body": "since python 2.4 there is a `set` [builtin](https://docs.python.org/3/library/stdtypes.html#set-types-set-frozenset), so `{'1', '2'}` or `set('12')` works too" } ], "meta_data": { "CommentCount": "3", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-09-07T22:15:43.527", "Id": "30932", "ParentId": "30400", "Score": "2" } }, { "body": "<h1><code>print</code> and multiline text</h1>\n\n<p>Your <code>displayIntro</code> uses several <code>print</code> calls to output multiline text. You may consider rewriting them like this:</p>\n\n<pre><code>def displayIntro():\n print(\"\"\"\nYou are in a land full of dragons. In front of\nyou are two caves. In one cave the dragon is\nfriendly and will give you his treasure. In the\nother, the dragon is greedy and hungry and will\neat you on sight\"\"\"[1:])\n</code></pre>\n\n<p>This way you can easily apply 80 columns rule for your program output.</p>\n\n<p><code>\"\"\"</code> operator starts (and ends) multiline string. <code>[1:]</code> trims leading newline.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2018-04-13T11:38:42.097", "Id": "191960", "ParentId": "30400", "Score": "6" } } ]
{ "AcceptedAnswerId": "30932", "CommentCount": "5", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-28T21:34:32.180", "Id": "30400", "Score": "9", "Tags": [ "python", "beginner", "game" ], "Title": "Text-based adventure game" }
30400
<p>This first stores a string as input, loops through it to extract all of the numbers into an <code>ArrayList</code>, then prints all of these numbers along with their sum and product.</p> <p>How would I decompose this Java program into multiple methods? </p> <pre><code>public class Assignment1 { public static void main(String[] args){ // Creates scanner for storing input string Scanner numScanner = new Scanner(System.in); String input; System.out.println("Enter a string of numbers to compute their sum and product:"); System.out.println("(Enter '.' to terminate program)"); input = numScanner.nextLine(); // Terminates the program if there is no input if (input.length() == 0){ System.out.println("Invalid input: Not enough characters"); System.exit(-1); } // Terminates the program if the first character is '.' if (input.charAt(0) == '.'){ System.out.println("Thank you for using numberScanner!"); System.exit(-1); } // Defines all of the variables used in the loops int index = 0; int sum = 0; int product = 1; Integer start = null; int end = 0; ArrayList&lt;Integer&gt; numbers = new ArrayList&lt;&gt;(); // Loop that extracts all numbers from the string and computes their sum and product while (index &lt; input.length()){ if (input.charAt(index) &gt;= 'A' &amp;&amp; input.charAt(index) &lt;= 'Z' &amp;&amp; start == null){ index++; }else if (input.charAt(index) &gt;= '1' &amp;&amp; input.charAt(index) &lt;= '9' &amp;&amp; start == null){ start = index; index++; }else if (Character.isDigit(input.charAt(index))){ index++; }else{ end = index; numbers.add(Integer.parseInt(input.substring(start,end))); sum += Integer.parseInt(input.substring(start,end)); product *= Integer.parseInt(input.substring(start,end)); index++; start = null; } } // For the last number, the end is greater than the length of the string // This prints the last number without using the end if (index == input.length()){ numbers.add(Integer.parseInt(input.substring(start))); sum += Integer.parseInt(input.substring(start)); product *= Integer.parseInt(input.substring(start)); index++; } // Prints the Numbers, Sum and Product beside each other System.out.print("Numbers: "); for (Object a : numbers) { System.out.print(a.toString() + " "); } System.out.println("Sum: " + sum + " Product: " + product); } } </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T17:29:10.180", "Id": "48404", "Score": "2", "body": "This seems on-topic to me, as the OP is asking for help refactoring. That seems right up our alley." } ]
[ { "body": "<p>Start by separating your code into input handling, computation, and output. Each of those could have its own method(s).</p>\n\n<p>For the input, you're working too hard. The <code>java.util.Scanner</code> has methods to give you <code>int</code>s.</p>\n\n<p>Think about what the inputs and outputs of each function should be. For example, your input handling function should take an <code>InputStream</code> and return a <code>List</code> of <code>Integer</code>s or an array of <code>int</code>s.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T04:32:00.870", "Id": "30409", "ParentId": "30407", "Score": "1" } }, { "body": "<p>I'm not going to give you a functional solution, but here's roughly what it should look like. </p>\n\n<pre><code>public class Assignment1 {\n public static void main(String[] args){\n String input = gatherInput();\n ArrayList&lt;Integer&gt; numbers = extractIntegers(input);\n\n int sum = sumInts(numbers);\n int product = multiplyInts(numbers);\n\n reportResults(numbers, sum, product);\n}\n</code></pre>\n\n<p>The key thing you need to keep in mind is that a method should do just one thing. I could have combined sumInts and multiplyInts, but they are mostly independent concepts -- so, keep them separate unless there's a performance problem or you need something a bit more abstract (ie you have a list of operations you want to apply to the elements of the list). I would suggest that you consider variations on the above revolving around \"reportResults\"...there are two variations that should be fairly obvious.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T08:24:30.757", "Id": "48363", "Score": "1", "body": "you should honour java code conventions and start method names with lower case letters though." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T06:09:34.113", "Id": "30415", "ParentId": "30407", "Score": "1" } }, { "body": "<p>What @jmoreno has said is pretty much spot on but seeing as this is a java problem remember that the convention is to use lower case letters for method names.</p>\n\n<p>The important things to remember are that each method should be simple, readable, encapsulate a unit of work and be easily testable. Again, following what @jmoreno has said and considering the gatherInput method, you can take the first five lines of code and create a new method that returns your string input. If you are using Eclipse this is very easy, highlight the code and click Alt+Shift+M which will open the 'Extract Method' refactor dialog box.</p>\n\n<p>The loop is the only real place where you have to think a little more as currently it is doing multiple jobs, but if you break out the code that extracts the numbers (extractIntegers(input)) then the rest becomes easy - you should also be able to remove the additional index == input.length() test.</p>\n\n<p>Other considerations:</p>\n\n<ol>\n<li>Have you thought about a for loop instead of a while loop? All of your cases increment the index by 1.</li>\n<li>Do you know how the input string should be formatted, in which case you could use a regular expression to extract the numbers.</li>\n<li>You have used isDigit once, why have you mixed it with the >= &lt;= solution? What about the letters?</li>\n</ol>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T08:36:08.450", "Id": "30420", "ParentId": "30407", "Score": "1" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T03:14:47.130", "Id": "30407", "Score": "2", "Tags": [ "java", "homework" ], "Title": "Extracting numbers from a string into an ArrayList" }
30407
<p>I am trying to write a count sort in Python to beat the built-in <code>timsort</code> in certain situations. Right now it beats the built-in sorted function, but only for very large arrays (1 million integers in length and longer, I haven't tried over 10 million) and only for a range no larger than 10,000. Additionally, the victory is narrow, with count sort only winning by a significant margin in random lists specifically tailored to it.</p> <p>I have read about astounding performance gains that can be gained from vectorizing Python code, but I don't particularly understand how to do it or how it could be used here. I would like to know how I can vectorize this code to speed it up, and any other performance suggestions are welcome.</p> <pre><code>def countsort(unsorted_list): counts = {} for num in unsorted_list: if num in counts: counts[num] += 1 else: counts[num] = 1 sorted_list = [] for num in xrange(min(unsorted_list), max(unsorted_list) + 1): if num in counts: for j in xrange(counts[num]): sorted_list.append(num) return sorted_list </code></pre> <p><a href="https://gist.github.com/anonymous/6373976" rel="nofollow">GitHub</a></p> <p>Additional info:</p> <ul> <li>All that counts is raw speed here, so sacrificing even more space for speed gains is completely fair game.</li> <li>I realize the code is fairly short and clear already, so I don't know how much room there is for improvement in speed.</li> <li>If anyone has a change to the code to make it shorter, as long as it doesn't make it slower, that would be awesome as well.</li> <li>After doing some more precise timing, it is clear that the first for loop takes about 2/3 of the execution time, with the second, constructor, loop taking just 1/3 of the time.</li> </ul>
[]
[ { "body": "<p><code>min()</code> and <code>max()</code> each has to make a pass through your entire <code>unsorted_list</code>. You might do better by keeping track of your extrema while you build your <code>counts</code>, from a cache locality standpoint.</p>\n\n<p>On the other hand, it's possible that Python's (or NumPy's) <code>min()</code> and <code>max()</code> are highly optimized, in which case you should leave it.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T04:50:21.627", "Id": "48342", "Score": "0", "body": "Interesting, use dp to only iterate once for max and min. I'll give it a try." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T04:46:30.730", "Id": "30411", "ParentId": "30408", "Score": "3" } }, { "body": "<p>One way to get a minor speedup is to avoid testing if the value you're adding to the <code>counts</code> dictionary already exists. This code idiom is known as \"easier to ask forgiveness than permission\" and it is faster because it only does the minimum number of lookups on the dictionary.</p>\n\n<pre><code>def countsort(unsorted_list):\n counts = {}\n for num in unsorted_list:\n try:\n counts[num] += 1\n except KeyError:\n counts[num] = 1\n\n sorted_list = []\n for num in range(min(unsorted_list), max(unsorted_list) + 1):\n try:\n for j in xrange(counts[num]):\n sorted_list.append(num)\n except KeyError:\n pass\n\n return sorted_list\n</code></pre>\n\n<p>I had initially though that a <code>collections.Counter</code> instance would be faster still, but for the data I was testing against it was a bit slower. I think this may be because it uses the equivalent of <code>dict.get</code> to do the incrementing, which is slower if most of the use is for values that already exist (<code>d[x] += 1</code> is faster than <code>d[x] = d.get(x,0)+1</code>).</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T05:27:57.463", "Id": "48347", "Score": "0", "body": "try/except is a good catch. I need to update the original post with what I am using now. I tried to update the second block to a pure list comprehension with a filter, but I'm getting lists of lists even though it is faster. I like your try/except solution for it though, and will give it a whirl." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T06:39:28.600", "Id": "48355", "Score": "1", "body": "How about `collections.defaultdict(int)`?" } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T04:49:54.493", "Id": "30412", "ParentId": "30408", "Score": "1" } }, { "body": "<p>I did some benchmarks using the <code>timeit</code> module and this test data:</p>\n\n<pre><code>random.seed(1)\ndata = [random.randint(0,10000) for _ in xrange(1000000)]\n</code></pre>\n\n<p>Original version clocks in at 411 ms, and the builtin <code>sorted</code> at 512 ms.</p>\n\n<p>Using <code>counts = defaultdict(int)</code> that allows unconditional <code>counts[num] += 1</code> takes it to 330 ms.</p>\n\n<p>Using <code>sorted_list.extend(counts[num] * [num])</code> instead of the inner loop improves to 250 ms, or 246 ms when also omitting the second <code>if</code>.</p>\n\n<p>Using <code>min(counts), max(counts)</code> instead of <code>min(unsorted_list), max(unsorted_list)</code> improves further to 197 ms.</p>\n\n<p>Using <code>chain</code> and <code>repeat</code> from <code>itertools</code> to construct the result takes 182 ms (though <code>repeat</code> does not make much difference).</p>\n\n<p>Code looks like this after the changes:</p>\n\n<pre><code>from collections import defaultdict\nfrom itertools import chain, repeat\n\ndef countsort(unsorted_list):\n counts = defaultdict(int)\n for num in unsorted_list:\n counts[num] += 1\n\n return list(\n chain.from_iterable(\n repeat(num, counts[num])\n for num in xrange(min(counts), max(counts) + 1)))\n</code></pre>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T17:18:14.333", "Id": "76521", "Score": "0", "body": "`collections.Counter` was faster than `collections.defaultdict` on my computer (Jython 2.5). Results may vary. Test your environment and your data to see which one gives better performance. As @Blckknght indicated, the performance difference of defaultdict and Counter is dependent on how repetitious your data is. If few data elements are repeated then there is little/no benefit in building `counts`. Countsort is only appropriate for highly repetitious data." } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T07:31:48.037", "Id": "30419", "ParentId": "30408", "Score": "15" } } ]
{ "AcceptedAnswerId": "30419", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T03:41:10.763", "Id": "30408", "Score": "9", "Tags": [ "python", "performance", "sorting" ], "Title": "Beating built-in timsort with own count sort function" }
30408
<p>I put together a Custom Linked List class in hopes of using it for a Talent/Skill Tree for a game. It allows for inserting nodes with <code>NSMutableDictionary</code> for Skills and Requirements along with a <code>nodeID</code> and a Boolean to see if said node is activated or not.</p> <p>I would like some feedback on this and any comments/ideas (all criticism welcome) so I can expand on the idea.</p> <p>The class is located at <a href="https://github.com/D34thStalker/JBListNode" rel="nofollow">Github</a></p> <pre><code>// // JBList.h // // // Created by Julius Btesh on 8/28/13. // // #import &lt;Foundation/Foundation.h&gt; #import "JBListNode.h" @interface JBList : NSObject @property (nonatomic) JBListNode *head; // This always points to the first position of the list @property (nonatomic) JBListNode *tail; // Always points to the last position @property (nonatomic) JBListNode *currTop; @property (nonatomic) JBListNode *currBottom; @property (nonatomic) int count; - (void)pushFront:(NSMutableDictionary *)skills; - (void)pushBack:(NSMutableDictionary *)skills; - (void)pushFront:(NSMutableDictionary *)skills withRequirements:(NSMutableDictionary *)requirements; - (void)pushBack:(NSMutableDictionary *)skills withRequirements:(NSMutableDictionary *)requirements; - (NSMutableDictionary *)popFront; - (NSMutableDictionary *)popBack; - (NSMutableDictionary *)popNode:(NSInteger)node; /* Will not work if you have multiple Skill Dictionaries with the same Keys + Values!!!!! Will find the FIRST nodeID with said Skill!!!!! */ - (NSInteger)findNodeIDForSkills:(NSMutableDictionary *)skills; /* Used for better search precision incase you have multiple Skill Dictionaries but different Requirement Dictionaries!!! But same as above, if there are multiple Skill AND Requirement Dictionaries with the same Keys + Values it will find the FIRST nodeID with said Skill AND Requirement!!! */ - (NSInteger)findNodeIDForSkills:(NSMutableDictionary *)skills andRequirements:(NSMutableDictionary *)requirements; - (void)activateNode:(NSInteger)node; - (void)deactivateNode:(NSInteger)node; - (BOOL)isActivated:(NSInteger)node; - (void)setRequirements:(NSMutableDictionary *)requirements forNode:(NSInteger)node; - (void)editRequirementsAtNode:(NSInteger)node setValue:(id)value forKey:(NSString *)key; - (NSMutableDictionary *)findRequirements:(NSMutableDictionary *)requirements forNode:(NSInteger)node; - (NSMutableDictionary *)findSkillsForNode:(NSInteger)node; - (void)editSkillsAtNode:(NSInteger)node setValue:(id)value forKey:(NSString *)key; - (void)allNodes; @end // // JBList.m // // // Created by Julius Btesh on 8/28/13. // // #import "JBList.h" @implementation JBList { JBListNode *_head; JBListNode *_tail; JBListNode *_currTop; JBListNode *_currBottom; int _count; int nodeID; } - (id)init { if (self = [super init]) { _head = nil; _tail = nil; _count = 0; } return self; } - (void)dealloc { int i = 0; JBListNode *tmp; while (i &lt; _count){ tmp = _head; _head = _head.next; tmp = nil; } } - (void)pushFront:(NSMutableDictionary *)skills { JBListNode *newElement = [[JBListNode alloc] init]; newElement.skills = skills; if ( _count == 0 ){ newElement.next = nil; //Set both the head and tail to NULL newElement.previous = nil; newElement.nodeID = 1; _count = 1; _head = newElement; _tail = newElement; _currTop = newElement; _currBottom = newElement; return; //Since there is only one element, quit } nodeID += 1; JBListNode *tmp = _head; newElement.next = tmp; //The new guys next is currently pointing to the bottom most element newElement.previous = tmp.previous; //Now, whatever the bottom was pointing to (the tail) the new node is pointing to. newElement.nodeID += 1; _currBottom = newElement; //The new node is now the bottom most element tmp.previous = newElement; //Now the former bottom is pointing to the new bottom _head = newElement; //The head is the bottom most element _count += 1; } - (void)pushBack:(NSMutableDictionary *)skills { JBListNode *newElement = [[JBListNode alloc] init]; newElement.skills = skills; if ( _count == 0 ) { newElement.next = nil; newElement.previous = nil; newElement.nodeID = 1; nodeID = 1; _count = 1; _head = newElement; _tail = newElement; _currTop = newElement; _currBottom = newElement; return; //Since there is only one element, quit } nodeID += 1; JBListNode *tmp = _tail; newElement.previous = tmp; // The new node is pointing to the last element added newElement.next = tmp.next; // What ever the current top was pointing to, now the new node is pointing to it newElement.nodeID = nodeID; _currTop = newElement; // Top most element tmp.next = newElement; // Now the former top node is pointing to the new node _tail = newElement; // The tail is the top element _count += 1; } - (void)pushFront:(NSMutableDictionary *)skills withRequirements:(NSMutableDictionary *)requirements { JBListNode *newElement = [[JBListNode alloc] init]; newElement.skills = skills; newElement.requirements = requirements; if ( _count == 0 ){ newElement.next = nil; //Set both the head and tail to NULL newElement.previous = nil; newElement.nodeID = 1; nodeID = 1; _count = 1; _head = newElement; _tail = newElement; _currTop = newElement; _currBottom = newElement; return; //Since there is only one element, quit } nodeID += 1; JBListNode *tmp = _head; newElement.next = tmp; //The new guys next is currently pointing to the bottom most element newElement.previous = tmp.previous; //Now, whatever the bottom was pointing to (the tail) the new node is pointing to. newElement.nodeID = nodeID; _currBottom = newElement; //The new node is now the bottom most element tmp.previous = newElement; //Now the former bottom is pointing to the new bottom _head = newElement; //The head is the bottom most element _count += 1; } - (void)pushBack:(NSMutableDictionary *)skills withRequirements:(NSMutableDictionary *)requirements { JBListNode *newElement = [[JBListNode alloc] init]; newElement.skills = skills; newElement.requirements = requirements; if ( _count == 0 ) { newElement.next = nil; newElement.previous = nil; newElement.nodeID = 1; nodeID = 1; _count = 1; _head = newElement; _tail = newElement; _currTop = newElement; _currBottom = newElement; return; //Since there is only one element, quit } nodeID += 1; JBListNode *tmp = _tail; newElement.previous = tmp; // The new node is pointing to the last element added newElement.next = tmp.next; // What ever the current top was pointing to, now the new node is pointing to it newElement.nodeID = nodeID; _currTop = newElement; // Top most element tmp.next = newElement; // Now the former top node is pointing to the new node _tail = newElement; // The tail is the top element _count += 1; } - (NSMutableDictionary *)popFront { if (_count == 0){//Empty! NSLog(@"Empty!"); return 0; } if (_count - 1 == 0) //If count will equal 0, there is 1 element in the list { NSMutableDictionary *value = _currBottom.skills; //hold the data, so i can delete the bottom _currBottom = nil; //delete the last element _count = 0; _head = nil; //head and tail are pointing to NULL _tail = nil; return value; } NSMutableDictionary *value = _currBottom.skills; JBListNode *tmp = _head; JBListNode *tmp2 = tmp.next; JBListNode *tmp3 = _tail; tmp2.previous = nil; tmp3.next = nil; _head = tmp2; _currBottom = tmp2; tmp = nil; _count -= 1; return value; } - (NSMutableDictionary *)popBack { if (_count == 0){//Empty! NSLog(@"Empty!"); return 0; } if (_count - 1 == 0) //If count will equal 0, there is 1 element in the list { NSMutableDictionary *value = _currTop.skills; //hold the data, so i can delete the tmp _currTop = nil; //delete the last element _count = 0; _head = nil; //head and tail are pointing to NULL _tail = nil; return value; } NSMutableDictionary *value = _currTop.skills; JBListNode *tmp = _tail; JBListNode *tmp2 = tmp.previous; JBListNode *tmp3 = _head; tmp2.next = nil; tmp3.previous = nil; _tail = tmp2; _currTop = tmp2; tmp = nil; _count -= 1; return value; } - (NSMutableDictionary *)popNode:(NSInteger)node { JBListNode *tmp = _head; while (tmp.nodeID != node) { tmp = tmp.next; } if (node == 1) //If count will equal 0, there is 1 element in the list { NSMutableDictionary *value = tmp.skills; //hold the data, so i can delete the tmp _head = tmp.next; _currBottom = tmp.next; _count -= 1; return value; } if (node == nodeID) { NSMutableDictionary *value = tmp.skills; JBListNode *tmp2 = tmp.previous; tmp2.next = nil; _tail = tmp2; _currTop = tmp2; tmp = nil; _count -= 1; return value; } NSMutableDictionary *value = tmp.skills; JBListNode *tmp2 = tmp.previous; JBListNode *tmp3 = tmp.next; tmp2.next = tmp3; tmp3.previous = tmp2; tmp = nil; _count -= 1; return value; } - (NSMutableDictionary *)findSkillsForNode:(NSInteger)node { JBListNode *tmp = _head; while (tmp.nodeID != node) { tmp = tmp.next; } return tmp.skills; } - (void)editSkillsAtNode:(NSInteger)node setValue:(id)value forKey:(NSString *)key { JBListNode *tmp = _head; while (tmp.nodeID != node) { tmp = tmp.next; } [tmp.skills setValue:value forKey:key]; } - (void)activateNode:(NSInteger)node { JBListNode *tmp = _head; while (tmp.nodeID != node) { tmp = tmp.next; } tmp.activated = YES; } - (void)deactivateNode:(NSInteger)node { JBListNode *tmp = _head; while (tmp.nodeID != node) { tmp = tmp.next; } tmp.activated = YES; } - (BOOL)isActivated:(NSInteger)node { JBListNode *tmp = _head; while (tmp.nodeID != node) { tmp = tmp.next; } return tmp.activated; } - (void)setRequirements:(NSMutableDictionary *)requirements forNode:(NSInteger)node { JBListNode *tmp = _head; while (tmp.nodeID != node) { tmp = tmp.next; } tmp.requirements = requirements; } - (void)editRequirementsAtNode:(NSInteger)node setValue:(id)value forKey:(NSString *)key { JBListNode *tmp = _head; while (tmp.nodeID != node) { tmp = tmp.next; } [tmp.requirements setValue:value forKey:key]; } - (NSMutableDictionary *)findRequirements:(NSMutableDictionary *)requirements forNode:(NSInteger)node { JBListNode *tmp = _head; while (tmp.nodeID != node) { tmp = tmp.next; } return tmp.requirements; } - (NSInteger)findNodeIDForSkills:(NSMutableDictionary *)skills { JBListNode *tmp = _head; while (tmp.skills != skills) { tmp = tmp.next; } return tmp.nodeID; } - (NSInteger)findNodeIDForSkills:(NSMutableDictionary *)skills andRequirements:(NSMutableDictionary *)requirements { JBListNode *tmp = _head; while (tmp.skills != skills || tmp.requirements != requirements) { tmp = tmp.next; } return tmp.nodeID; } - (void)allNodes { JBListNode* tmp = _head; while (tmp != nil){ NSLog(@"NodeID: %d", tmp.nodeID); NSLog(@"Skill: %@", tmp.skills); NSLog(@"Requirements: %@", tmp.requirements); NSLog(@"Activated: %d", tmp.activated); tmp = tmp.next; } } @end // // JBListNode.h // // // Created by Julius Btesh on 8/28/13. // // #import &lt;Foundation/Foundation.h&gt; @interface JBListNode : NSObject @property (nonatomic) JBListNode *next; @property (nonatomic) JBListNode *previous; @property (nonatomic) NSInteger nodeID; @property (nonatomic) NSMutableDictionary *skills; @property (nonatomic) NSMutableDictionary *requirements; @property (nonatomic) BOOL activated; @end // // JBListNode.m // // // Created by Julius Btesh on 8/28/13. // // #import "JBListNode.h" @implementation JBListNode { JBListNode *_next; JBListNode *_previous; NSInteger _nodeID; NSMutableDictionary *_skills; NSMutableDictionary *_requirements; BOOL _activated; } - (id)init { if (self = [super init]) { _next = nil; _previous = nil; _activated = NO; } return self; } @end </code></pre>
[]
[ { "body": "<p>First, it should be noted that an <code>NSDictionary</code> can use any object as it's key (as long as it conforms to NSCopying protocol), as such, your <code>setValue:forKey:</code> methods should probably be rewritten to take <code>id</code> as the <code>key</code> argument type, rather than <code>NSString*</code>.</p>\n\n<hr>\n\n<p>Second, while the structure of your binary search tree is important for somethings, the structure is not important to some of your search methods. For example, in <code>findNodeIDForSkills:andRequirements:</code>, all that's important is that the skills and requirements match the arguments and we return the nodeID for the matching node (this can probably also be true for some of the other searches). As such, if we keep a private <code>NSMutableArray</code> that simply holds a reference to all of the nodes, we can use a <code>forin</code> loop to drastically increase the performance of the searches. Forin loops are quite fast.</p>\n\n<hr>\n\n<p>Third, regardless of whether or not you implement my second suggestion, your searches still have a problem in the case that the arguments sent do not match any of the nodes.</p>\n\n<p>In fact, if I'm correct, all of your searches will result in infinite loops if the search criteria cannot be met. They all have this pattern:</p>\n\n<pre><code>while (someCriteria) {\n tmp = tmp.next;\n}\n</code></pre>\n\n<p>When you get to the end of the list, <code>tmp.next</code> will be <code>nil</code>. This assigns <code>nil</code> to <code>tmp</code>, and your criteria will still return true. Because <code>tmp</code> is <code>nil</code>, then <code>tmp.next</code> will still return <code>nil</code>, and at this point your criteria will always be true and the loop will never exit. You need to add something like this:</p>\n\n<pre><code>while (someCriteria) {\n tmp = tmp.next;\n if(!tmp) {\n return nil;\n }\n}\n</code></pre>\n\n<p>Now we're returning some sort of value that indicates nothing was found and users of the class can check whether they got a good value returned or just <code>nil</code>, indicating their search turned up nothing.</p>\n\n<hr>\n\n<p>Fourth, this one is just an Objective-C naming convention note. </p>\n\n<p><code>and</code> is typically reserved to describe an additional action taken place within the method. This isn't what is happening with your <code>findNodeIDForSkills:andRequirements:</code> method, and as such, the <code>and</code> should be taken out:</p>\n\n<pre><code>- (NSInteger)findNodeIDforSkills:(NSMutableDictionary *)skills \n requirements:(NSMutableDictionary *)requirements\n</code></pre>\n\n<p>An example where the <code>and</code> might be more appropriate would look something more like this:</p>\n\n<pre><code>- (NSInteger)findNodeIDforSkills:(NSMutableDictionary*)skills\n andEditRequirements:(id)value\n forKey:(id)key\n</code></pre>\n\n<p>Where we're going to search through the nodes to find a matching skills dictionary, edit the requirements of the dictionary AND return the node ID for the dictionary we just found and edited. We are FINDING and EDITING. Whereas in your current use of the <code>and</code>, you're just finding by two criteria.</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T22:18:56.400", "Id": "76599", "Score": "1", "body": "*NSDictionary can use any object as it's key* that conforms to the `NSCopying` protocol…" } ], "meta_data": { "CommentCount": "1", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2014-03-12T21:47:58.400", "Id": "44206", "ParentId": "30410", "Score": "5" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T04:33:30.977", "Id": "30410", "Score": "2", "Tags": [ "objective-c", "linked-list", "binary-search" ], "Title": "Custom linked list class" }
30410
<p>This changes the application's volume through the Trackbar (1-100, 1% to 100%):</p> <pre><code>public static class NativeMethods { //Winm WindowsSound [DllImport("winmm.dll")] internal static extern int waveOutGetVolume(IntPtr hwo, out uint dwVolume); [DllImport("winmm.dll")] internal static extern int waveOutSetVolume(IntPtr hwo, uint dwVolume); } private void trackBar1_Scroll(object sender, EventArgs e) { uint CurrVol = ushort.MaxValue / 2; NativeMethods.waveOutGetVolume(IntPtr.Zero, out CurrVol); ushort CalcVol = (ushort)(CurrVol &amp; 0x0000ffff); int NewVolume = ((ushort.MaxValue / 100) * trackBar1.Value); uint NewVolumeAllChannels = (((uint)NewVolume &amp; 0x0000ffff) | ((uint)NewVolume &lt;&lt; 16)); NativeMethods.waveOutSetVolume(IntPtr.Zero, NewVolumeAllChannels); label1.Text = Convert.ToString("Volume: " + trackBar1.Value + "%"); } </code></pre> <p>Is it possible to make <code>String.Format</code> use multiple arguments/values?</p> <p>For example:</p> <pre><code> String Status = String.Format("Current Buffer: {0}", waveProvider.BufferedDuration.Milliseconds, TimesBufferClear) + " Clear: " + TimesBufferClear.ToString() + " Ping: " + PingReply + " Buffer: " + SendStream.BufferMilliseconds; </code></pre> <p>There, I would like to use it on everything, as they all work pretty much the same. But if I have to write <code>String.Format</code> every time, it will take up much more space.</p> <p>Is this code okay, or can it be improved?</p>
[]
[ { "body": "<p>There isn't much to review in 6 lines of code. But oh well.</p>\n\n<ol>\n<li>Native methods return error codes, so it is good practice to handle those codes somehow, not just ignore them. For example, if method reports, that there is no sound driver or no sound card or w/e, it makes sense to notify user somehow. Write warning in the status bar of your window or something.</li>\n<li>It is meaningless to initialize <code>CurrVol</code>, since its value will be overriden anyway, wont it? And, if its your real code, you dont have to recieve current volume in order to set it to begin with.</li>\n<li><p><code>Convert.ToString</code> should be refactored to <code>String.Format(\"Volume: {0}%\", trackBar1.Value);</code>. More complex example:</p>\n\n<pre><code>var status = String.Format(\"Current Buffer: {0} Clear: {1} Ping: {2} Buffer: {3}\", waveProvider.BufferedDuration.Milliseconds, TimesBufferClear, PingReply, SendStream.BufferMilliseconds);\n</code></pre></li>\n</ol>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T18:03:35.413", "Id": "48405", "Score": "0", "body": "Yeah i know, but thanks for answering anyway. And How am i supposed to handle the errors? I know ishould handle them, but, i don´t know in what way? True that´s it´s overidden, didn´t think of that. But what do you mean \"if it´s your real code you don´t need...\" . Don´t i need to have the Currvol var?. And nice, looks much better now at the string!" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T04:18:23.583", "Id": "48459", "Score": "0", "body": "@Zerowalker, i dont see you using `Currvol` anywhere in your code (except for calculating `CalcVol` which you dont use either). So i think first three lines can be removed from event handler. As for strings - see my answer." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T04:24:53.590", "Id": "48460", "Score": "0", "body": "@Zerowalker, also, if you are using Visual Studio i recommend you installing ReSharper (at least trial version). It will help you track common mistakes and improve your code style." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T08:28:03.120", "Id": "48485", "Score": "0", "body": "Very true, didn´t notice that, that´s embarrassing, thanks. And nice, perfect, now i understand why it had \"0\" in it. Ah heard of that, will look it up!" } ], "meta_data": { "CommentCount": "4", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T11:00:17.367", "Id": "30430", "ParentId": "30413", "Score": "4" } } ]
{ "AcceptedAnswerId": "30430", "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T05:28:29.297", "Id": "30413", "Score": "4", "Tags": [ "c#", "audio" ], "Title": "TrackBar volume control" }
30413
<p>This is a very simple anagram game that plays only with names of colors.</p> <p>I tried to focus on code design. I also wanted it to support further updates. But, my <code>init</code> seems smelly and you will notice it, especially in the main loop.</p> <p>I was wondering about my naming and commenting/docstrings. I need strong criticism here, without any mercy.</p> <p>This is the module I've created with the only class:</p> <pre><code>class AnagramGame: def __init__(self, words=None, rword=None, inp=None, anagram=None, is_corr_word=False): self._words = None self._rword = rword # Stands for random word self._anagram = anagram self._inp = inp # User input self._is_corr_word = is_corr_word # Stands for correct word bool def get_words(self): return self._words def set_words(self, filename): in_file = open(filename, 'r') self._words = [in_line.rstrip('\n') for in_line in in_file.readlines()] in_file.close() def del_words(self): del self._words words = property(get_words, set_words, del_words) def get_rword(self): return self._rword def set_rword(self, sequence): import random self._rword = random.choice(sequence) def del_rword(self): del self._rword rword = property(get_rword, set_rword, del_rword) def get_anagram(self): return self._anagram def set_anagram(self, sequence): import random self._anagram = ''.join(random.sample(sequence, len(sequence))) def del_anagram(self): del self._anagram anagram = property(get_anagram, set_anagram, del_anagram) def get_is_corr_word(self): return self._is_corr_word def set_is_corr_word(self, boolean): self._is_corr_word = boolean def del_is_corr_word(self): del self._is_corr_word is_corr_word = property(get_is_corr_word, set_is_corr_word, del_is_corr_word) def ask_input(self, prompt=''): self._inp = input(prompt) def check_input(self, prompt_corr, prompt_incorr): if self._inp == self.rword: print(prompt_corr, end='') self._is_corr_word = True return self._is_corr_word else: print(prompt_incorr, end='') self._is_corr_word = False return self._is_corr_word </code></pre> <p>And this is the main program:</p> <pre><code>def main(): import games print("Anagram Mini Game", "\n") while True: Angrm = games.AnagramGame() # Reset all attributes Angrm.words = 'colors.txt' # Load words Angrm.rword = Angrm.words # Extract a word Angrm.anagram = Angrm.rword # Create anagram of the word print("Try build an anagram of this shuffled color name: ", Angrm.anagram) Angrm.ask_input("Give it a try - ") Angrm.check_input("GG beast", "Wrong - ") # Not indent after impact prompts while not Angrm.is_corr_word: Angrm.ask_input() Angrm.check_input("GG beast", "Wrong - ") print("\n\n") # Indent for a new game if __name__ == '__main__': main() </code></pre>
[ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T07:31:17.227", "Id": "48359", "Score": "4", "body": "Instead of shortened variable names (\"rword\"), you would be wise to use full names to improve clarity and do away with unneeded comments. So, use variable names such as \"randomWord\", \"userInput\", \"is_correct_word\"." }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T07:22:41.517", "Id": "48469", "Score": "4", "body": "And in the case of Python, underscores seem to be the recommendation instead of camelCase: tis_but_a_scratch instead of blackKnight" } ]
[ { "body": "<p>In your <code>__init__()</code> function, you have defined <code>words</code> as a parameter but you are assigning <code>None</code> to <code>_words</code></p>\n\n<p>class AnagramGame:</p>\n\n<pre><code>def __init__(self, words=None, rword=None, inp=None,\n anagram=None, is_corr_word=False):\n self._words = None\n # ...\n</code></pre>\n\n<p>You may either remove this parameter or assign the value to <code>_words</code></p>\n\n<hr>\n\n<p>Instead of using an infinite loop <code>while True:</code>, you should have created a <code>bool</code> object. Something like this:</p>\n\n<pre><code>checker = False\nwhile not checker:\n # ...\n</code></pre>\n\n<hr>\n\n<p>I see the purpose of <code>while True:</code> is to make the user play the game endlessly. It would have been great to have an exit criteria too. Else, you could have skipped the infinite loop.</p>\n\n<hr>\n\n<p>You don't have to re-initialize the object and reload the file on each loop run. You may initialize them before the loop, load the files and let the game run on its own.</p>\n\n<p>To reset the values, you may create another function that would only reset the relevant data-members and continue the game further.</p>\n\n<hr>\n\n<p>As you have already mentioned, please have proper comments and doc-strings in the code. It is always better to add them during development. Else mostly they get ignored!</p>\n", "comments": [ { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T08:48:41.220", "Id": "48492", "Score": "0", "body": "I feel its odd to have one single bool for the loop/loops outside of the module. Is it odd?\nCant really get it how to call variable attributes.\n\nI also thought to add some docstrings but what to write on these simple methods, same with commenting.\n\nShould i use property() or the decorator?" }, { "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T11:32:20.627", "Id": "48511", "Score": "0", "body": "I don't think anything will sit outside the module. The bool variable be declared in `main()` and will help you to control the loop exit properly. Docstrings/comments are for general practice. Use properties in this case. You may use decorators where you want something to be accomplished over multiple functions like `@static_method` or something similar." } ], "meta_data": { "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T08:29:33.530", "Id": "30497", "ParentId": "30417", "Score": "4" } }, { "body": "<p>Your long anagram class might be useful for learning about classes, getters and setters, but it isn't actually doing very much. You shouldn't usually be having to access an object's properties that much from outside the object; it should be dealing with the complicated stuff internally. There are a few different options. One would be for Anagram only to deal with making up anagrams and checking them, so that your main game loop would look something like this:</p>\n\n<pre><code> while True:\n game = games.Anagram(file='colors.txt');\n for anagram in game.anagrams:\n print('Try build an anagram of this shuffled color name: ' + anagram.shuffled)\n attempt = input('Give it a try -')\n if attempt == anagram.original:\n print('GG beast', end='')\n else:\n print('Wrong - ', end='')\n</code></pre>\n\n<p>and another would be for all of the game logic to be included in Anagram, so that, for instance, only the following would be left in the main game loop:</p>\n\n<pre><code>game = games.Anagram(file='colors.txt',\n intro='Try build an anagram of this shuffled color name:',\n prompt='Give it a try -',\n right='GG beast',\n wrong='Wrong - ')\nfor turn in game.turns:\n turn.play() \n</code></pre>\n\n<p>What you currently have is messy because it is a mixture of the two. Either way, there's not much call for all that getting and setting.</p>\n\n<p>Also, <code>import</code> statements should usually be at the top of the file.</p>\n", "comments": [], "meta_data": { "CommentCount": "0", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-30T09:19:34.853", "Id": "30499", "ParentId": "30417", "Score": "3" } } ]
{ "AcceptedAnswerId": null, "CommentCount": "2", "ContentLicense": "CC BY-SA 3.0", "CreationDate": "2013-08-29T07:06:51.210", "Id": "30417", "Score": "6", "Tags": [ "python", "game", "python-3.x" ], "Title": "Simple anagram game with names of colors" }
30417