body
stringlengths 25
86.7k
| comments
list | answers
list | meta_data
dict | question_id
stringlengths 1
6
|
|---|---|---|---|---|
<p>I'm working my way through <em>The Java Programming Language, Fourth Edition - The Java Series</em>. This is Exercise 13.3:</p>
<blockquote>
<p>As shown, the delimitedString method assumes only one such string per input string. Write a version that will pull out the delimited strings and retun an array.</p>
</blockquote>
<p>The provided delimitedString method:</p>
<pre><code>public static String delimitedString(String from, char start, char end) {
int startPos = from.indexOf(start);
int endPos = from.lastIndexOf(end);
if (startPos == -1)
return null;
else if (endPos == -1)
return null;
else if (startPos > endPos)
return null;
else
return from.substring(startPos, endPos + 1);
}
</code></pre>
<p>My solution. Note that regular expressions are covered in the next section of the book, so I chose not to use a split for this particular exercise:</p>
<pre><code>public static String[] delimitedStrings(String from, char startDelim, char endDelim) {
int index;
int startPos = 0;
ArrayList<String> list = new ArrayList<String>();
while ((index = from.indexOf(startDelim, startPos)) != -1) {
int endPos;
if ((endPos = from.indexOf(endDelim, index)) != -1) {
list.add(from.substring(index, endPos + 1));
startPos = endPos;
} else {
break;
}
}
return list.toArray(new String[list.size()]);
}
</code></pre>
<p>Supporting tests:</p>
<pre><code>@Test
public void testDelimitedStringsSimple() throws Exception {
String[] strArray = {"<Bonjour!>"};
assertEquals(strArray, StringUtil.delimitedStrings("I say <Bonjour!>", '<', '>'));
}
@Test
public void testDelimitedStringsComplex() throws Exception {
String[] strArray = {"<Bonjour!>","<Bonjour!>","<B<onjour!>", "<Bonjour!>"};
assertEquals(strArray, StringUtil.delimitedStrings("I say <Bonjour!> I say <Bonjour!> and a tricky <B<onjour!> and ><Bonjour!>", '<', '>'));
}
@Test
public void testDelimitedStringsNoStart() throws Exception {
String[] strArray = {};
assertEquals(strArray, StringUtil.delimitedStrings("Bonjour!>", '<', '>'));
}
@Test
public void testDelimitedStringsNoEnd() throws Exception {
String[] strArray = {};
assertEquals(strArray, StringUtil.delimitedStrings("<Bonjour!", '<', '>'));
}
@Test
public void testDelimitedStringsReversed() throws Exception {
String[] strArray = {};
assertEquals(strArray, StringUtil.delimitedStrings(">Bonjour!<", '<', '>'));
}
@Test
public void testDelimitedStringsEmpty() throws Exception {
String[] strArray = {};
assertEquals(strArray, StringUtil.delimitedStrings("", '<', '>'));
}
</code></pre>
|
[] |
[
{
"body": "<p>If I had to put a number on your code it would be a 8 out of 10. You did good here. Since it is so good I am going to be nitpicking a few things. First is your test. You are comparing arrays but using <code>assertEquals</code>. Instead you need to change that to <code>assertArrayEquals</code> (providing you are using JUnit 4.0) The other thing I feel you need to test for is no begin and no end delimiters.</p>\n\n<p>The other nitpicking thing I can find is in your split method. I know that you referred to not using the String.split method, but your method does the same thing. For this exercise there is nothing wrong with giving it the same name seeing as it does the same thing. One thing that annoys me a small amount is the making a while or if statement do more than one thing. Are you assigning or are you comparing? The convention for while and if is to compare only. So move your assignment out of those functions. I'm going to paste your code multiple times and I revise it, so here is where I am sitting now on your code.</p>\n\n<pre><code>public static String[] split(String from, char startDelimiter, char endDelimiter)\n{\n int startPos = 0;\n ArrayList<String> list = new ArrayList<>();\n\n int index = from.indexOf(startDelimiter, startPos);\n\n while (index != -1)\n {\n int endPos = from.indexOf(endDelimiter, index);\n if (endPos != -1)\n {\n list.add(from.substring(index, endPos + 1));\n startPos = endPos;\n }\n else\n {\n break;\n }\n index = from.indexOf(startDelimiter, startPos);\n }\n return list.toArray(new String[list.size()]);\n}\n</code></pre>\n\n<p>Notice that it introduces some duplication with assigning index. Since you have passing tests that means we can refactor a little bit. Now I know you are probably thinking that the reason you put the assignment in the while loop was to remove duplication. Before we address that though lets attack some of your naming. Index. Normally this is a good choice of words to use, but index usually refers to a location in an array. Although a string is an array of characters in this context it is not the exact definition of an index. So I believe a more appropriate name would be <code>startDelimiterLocation</code> , <code>startLocation</code> , or even <code>startLookigFrom</code> this would allow us to make a sentence out of our while and if statments by giving <code>-1</code> a name such as <code>NotFound</code> or since it is a constant <code>NOTFOUND</code>.</p>\n\n<pre><code>public static String[] split(String from, char startDelimiter, char endDelimiter)\n{\n int fromIndex = 0;\n ArrayList<String> list = new ArrayList<>();\n\n int startPosistion = from.indexOf(startDelimiter, fromIndex);\n\n while (startPosistion != NOTFOUND)\n {\n int endPosistion = from.indexOf(endDelimiter, startPosistion);\n if (endPosistion != NOTFOUND)\n {\n list.add(from.substring(startPosistion, endPosistion + 1));\n fromIndex = endPosistion;\n }\n else\n {\n break;\n }\n startPosistion = from.indexOf(startDelimiter, fromIndex);\n }\n return list.toArray(new String[list.size()]);\n}\nprivate static final int NOTFOUND = -1;\n</code></pre>\n\n<p>This gives us the ability to read the code outloud if we wanted (while startPosistion is not not found) (yes i know it's a double negative, but well.. this isn't English. Well that gives me an idea.. Lets make that into an actual sentance, and have it return a boolean.</p>\n\n<pre><code>private static boolean stringHasStringBetweenTwoCharacters(String from, char startDelimiter, char endDelimiter)\n{\n int startPosistion = from.indexOf(startDelimiter);\n if (startPosistion == NOTFOUND) return false;\n\n int endPosistion = from.indexOf(endDelimiter, startPosistion);\n return (startPosistion != NOTFOUND && endPosistion != NOTFOUND);\n}\n</code></pre>\n\n<p>this allows me to rewrite my while method to this. <code>while (stringHasStringBetweenTwoCharacters(from, startDelimiter, endDelimiter))</code> but this makes the tests fail because my method is not looking at where we left off in our string. I removed it on purpose because I wanted this method to only find the first occurrence of a string in between 2 characters. So this means I have to change the logic slightly. Instead of keeping track of where we are in the string, lets just remove up to the endPosistion and leave the rest.</p>\n\n<pre><code>public static String[] split(String from, char startDelimiter, char endDelimiter)\n{\n ArrayList<String> list = new ArrayList<>();\n\n while (stringHasStringBetweenTwoCharacters(from, startDelimiter, endDelimiter))\n {\n int startPosistion = from.indexOf(startDelimiter);\n int endPosistion = from.indexOf(endDelimiter, startPosistion);\n if (endPosistion != NOTFOUND)\n {\n list.add(from.substring(startPosistion, endPosistion + 1));\n from = from.substring(endPosistion + 1);\n }\n else\n {\n break;\n }\n }\n return list.toArray(new String[list.size()]);\n}\nprivate static boolean stringHasStringBetweenTwoCharacters(String from, char startDelimiter, char endDelimiter)\n{\n int startPosistion = from.indexOf(startDelimiter);\n if (startPosistion == NOTFOUND) return false;\n\n int endPosistion = from.indexOf(endDelimiter, startPosistion);\n return (startPosistion != NOTFOUND && endPosistion != NOTFOUND);\n}\nprivate static final int NOTFOUND = -1;\n</code></pre>\n\n<p>so now my tests pass again. Oh but I have duplication again, but no longer in the start position, now it is in the end position. Since I know it is there I can remove the check in my while loop and make a slight adjustment in my duplicate change in index. My final outcome is something like this.</p>\n\n<pre><code>public static String[] split(String from, char startDelimiter, char endDelimiter)\n{\n ArrayList<String> list = new ArrayList<>();\n\n while (stringHasStringBetweenTwoCharacters(from, startDelimiter, endDelimiter))\n {\n int startPosistion = from.indexOf(startDelimiter);\n int endPosistion = from.indexOf(endDelimiter, startPosistion) + 1;\n list.add(from.substring(startPosistion, endPosistion));\n from = from.substring(endPosistion);\n }\n return list.toArray(new String[list.size()]);\n}\nprivate static boolean stringHasStringBetweenTwoCharacters(String from, char startDelimiter, char endDelimiter)\n{\n int startPosistion = from.indexOf(startDelimiter);\n if (startPosistion == NOTFOUND) return false;\n\n int endPosistion = from.indexOf(endDelimiter, startPosistion);\n return (startPosistion != NOTFOUND && endPosistion != NOTFOUND);\n}\nprivate static final int NOTFOUND = -1;\n</code></pre>\n\n<p>Now my methods only do one thing, and it does them well. I moved the logic of how to check to see if my string still contains a token into its own method which leave only the logic of adding my tokens to my arrayList. It may seem a little more verbose, but in my opinion is easier to read</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T20:11:23.897",
"Id": "32934",
"ParentId": "32926",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "32934",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T16:04:56.567",
"Id": "32926",
"Score": "4",
"Tags": [
"java",
"strings"
],
"Title": "Critique of Delimited String Method"
}
|
32926
|
<p>It's not finished yet, but I want to know if the structure and the classes are ok and what can I change. Feel free to say anything.</p>
<p>To be more specific, I want to know what you think about the login function in the <code>Login_Controller</code> class:</p>
<pre><code>public function login() {
if (!empty($_POST['username']) && !empty($_POST['password'])) {
$user = new Users_Model;
$username = $_POST['username'];
$password = $_POST['password'];
if ($iduser = $user->is_registered($username, $password)) {
$_SESSION['user'] = $username;
$_SESSION['iduser'] = $iduser;
if ($_POST['keep']) {
$user->save_cookie($username);
}
header('Location: ' . SITE_ROOT);
exit();
} else {
$error = 'El usuario o el password no son correctos.';
$this->main($error);
}
} else {
$error = 'No ingreso el usuario o el password.';
$this->main($error);
}
}
</code></pre>
<p>And the router as well:</p>
<pre><code>class Router {
static function init($request)
{
$parsed = explode('/', $request);
if ($parsed[0] == 'admin') {
$page = array_shift($parsed).ucfirst(array_shift($parsed));
} else {
$page = array_shift($parsed);
}
if (empty($page)) {
$page = 'index';
}
$action = array_shift($parsed);
if (empty($action)) {
$action = 'main';
}
if (empty($parsed)) {
$arguments = 0;
} else {
$arguments = $parsed;
}
$target = SERVER_ROOT . '/controllers/' . $page . '.php';
if (file_exists($target)) {
include_once $target;
$class = ucfirst($page) . '_Controller';
if (class_exists($class)) {
$controller = new $class;
} else {
die('la clase no existe');
}
} else {
die('la pagina no existe');
}
$controller->$action($arguments);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T10:17:07.147",
"Id": "52898",
"Score": "0",
"body": "I don't think you get the point of MVC :("
}
] |
[
{
"body": "<p>They are ok, but I would still do some things differently.</p>\n\n<ol>\n<li>I would instead throw exceptions.</li>\n<li>Instead of <code>if</code> <code>else</code> within your action, I would use a validator with rules.</li>\n<li>Instead of using <code>$_POST/$_GET directly</code>, I would sanitize them and put it inside a <code>Request</code> class.</li>\n<li>Error messages belongs to the view, so I would set <code>$view->errors[]='message'</code> or something like that.</li>\n<li>Your routing class is not flexible. As a good example, you could take a look at the Silex framework.</li>\n<li><code>Login_Controller</code> should not exist. There might be <code>Account_Controller</code> with <code>login_action</code> or <code>Authenticate_Controller</code> with <code>login_action</code>. </li>\n</ol>\n\n<p>Usually a Controller is a group of actions with to execute specific stuffs. For example, <code>Profile_Controller</code> has view/edit/delete action. Within the controller you check the user roles, if someone can view/edit/delete the profile. In other frameworks, they use \"Access Control List (ACL)\" for this purpose.</p>\n\n<p>Your linked tutorial is just for the basic understanding purpose, so please don't use it. Use a readily existing framework, since you wish to build the app and not the framework itself. You might end with modifying and changing your basic structures and implementing new functions instead of developing the features of your web application.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T02:28:52.087",
"Id": "53006",
"Score": "0",
"body": "Thanks for the answer. Right now I'm taking a look to the Fabien Potencier tutorial for a framework, after that I will take a look to Silex."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T06:23:32.613",
"Id": "53027",
"Score": "0",
"body": "also please note that a Framework is just a delivery detail, it is not really required, with Clean Code Architecture which was introduced by Robert Ceciel Martin (aka. Uncle Bob) youre able to create software and switch the frameworks with less efford"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T10:27:43.560",
"Id": "33057",
"ParentId": "32928",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T16:58:10.747",
"Id": "32928",
"Score": "2",
"Tags": [
"php",
"mvc",
"url-routing",
"framework"
],
"Title": "Basic login with router"
}
|
32928
|
<p>Any way to make this more concise/efficient? </p>
<pre><code>// Write a loop that reverses the elements of an array.
#include <iostream>
#include <iomanip>
const int SIZE = 10;
void reverse(int iArrayRef1 []);
void display(int iArrayRef2 []);
int main()
{
int iArray[SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };
// Display in the original order.
std::cout << "Forwards:\n";
display(iArray);
// Reverse the array.
reverse(iArray);
std::cout << std::endl;
// Display in reversed order.
std::cout << "Backwards:\n";
display(iArray);
return 0;
}
void reverse(int iArrayRef1 [])
{
int temp = 0;
int* indexPtrBeg = iArrayRef1;
int* indexPtrEnd = iArrayRef1 += (SIZE-1);
for (int index = 0; index < (SIZE/2); index++)
{
temp = *indexPtrEnd;
*indexPtrEnd = *indexPtrBeg;
*indexPtrBeg = temp;
indexPtrEnd--;
indexPtrBeg++;
}
}
void display(int iArrayRef2 [])
{
for (int index = 0; index < SIZE; index++)
{
std::cout << std::setw(2) << iArrayRef2[index] << " ";
}
std::cout << std::endl;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T19:38:41.063",
"Id": "52672",
"Score": "0",
"body": "I don't see much wrong. I only wonder why you call the argument ``iArrayRef1`` in ``reverse`` and ``iArrayRef2`` in ``display``. One other minor thing: ``++index`` is slightly faster than ``index++`` since the post-increment operator has to return the pre-incremented value (it first makes a copy, then increments and returns the copy). This also goes for ``indexPtrEnd--`` of course. Modern compilers might optimize the copy away if you don't use it, but it won't hurt to use pre-increment when possible."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T19:50:12.327",
"Id": "52674",
"Score": "0",
"body": "Thank you! In regards to the parameter list, I am still unsure about how to name similar parameters, is there a convention that people generally stick to?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T20:00:40.280",
"Id": "52676",
"Score": "0",
"body": "There's nothing against using the same name in both functions. Personally, all of my function arguments start with 'a' (``void display( int aArray[] )``) to distinguish them from local variables. Also I don't believe hungarian notation (prepending type information to variable names, in your case ``iArray``, where *i* stands for ``int`` I suppose) is very common in C++. In the end though, naming style is personal and you should pick your own and **stick to it**. Inconsistency is the biggest mistake you can make :)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T20:03:59.440",
"Id": "52678",
"Score": "0",
"body": "@thelamb: Yes, normally Hungarian is discouraged. :-) Starting them with `a` isn't best either, but I don't know if it's discouraged as well. You also won't really need to worry about \"local\" naming unless you're dealing with classes (you'll have local *and* member)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T22:35:07.243",
"Id": "52752",
"Score": "0",
"body": "@thelamb: I doubt there is any difference in speed between `++index` and `index++`. With built-in types there will be no difference. And this is also a bad argument to use. The argument you should be using is that the speed is not the same for all types and for user defined types in general it is slower (because of the reason you stated). So for maintenance purposes prefer the prefix version so that if the types change your code is always using the optimum version."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T22:39:21.697",
"Id": "52753",
"Score": "0",
"body": "@thelamb: Use of Hungarian notation has fallen out of favor in most (strongly typed) languages because it does not add information and makes maintenance harder (when you change the types you also need to change the variable names to match). The reason it did not add useful information is mainly historical and because most people do not use it correctly. When used correctly it is a powerful tool. Joel has a famous article on the subject: http://www.joelonsoftware.com/articles/Wrong.html"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T22:42:34.770",
"Id": "52754",
"Score": "0",
"body": "@Jamal: Using `verbs` is the preferred convention for methods (and usually functions). Because the method is an action (hence verb) you are performing on the object."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T22:45:14.267",
"Id": "52756",
"Score": "0",
"body": "@LokiAstari: I see. I do remember someone else telling me that `aObject` isn't preferred, unless that's a bit different here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T22:49:44.567",
"Id": "52759",
"Score": "0",
"body": "If you are just reversing for the print. You shoudl consider using iterators. You can print one way with the normal iterators. Then print in reverse using the reverse iterator on the same container. Thus not requiring you to actually reverse the array."
}
] |
[
{
"body": "<p>For an implementation without the STL, this is pretty good. There's no risky memory-management going on with the raw pointers, and your sorting isn't needlessly slow (compared to bubble sort). I'll base my review on the STL anyway (for future reference), along with some other general tips.</p>\n\n<hr>\n\n<ul>\n<li><p><s><code>SIZE</code> should be of type <a href=\"http://en.cppreference.com/w/cpp/types/size_t\" rel=\"noreferrer\"><code>std::size_t</code></a>. It's preferred to use an unsigned integer type for sizes, plus you'll have a larger range (no negative values are part of it).</s></p></li>\n<li><p>If you have C++11, prefer <a href=\"http://en.cppreference.com/w/cpp/container/array\" rel=\"noreferrer\"><code>std::array</code></a> (or any other STL container) over C-style arrays. This also makes it needless to pass the array size since STL containers already know their own.</p>\n\n<p>Your array initialization, for instance, would look like this:</p>\n\n<pre><code>std::array<int, SIZE> iArray = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\n</code></pre>\n\n<p>If you use the above array or another STL container, the loop counters in <code>reverse()</code> and <code>display()</code> should be of type <a href=\"http://en.cppreference.com/w/cpp/container/array/size\" rel=\"noreferrer\"><code>std::size_type</code></a>. This will ensure:</p>\n\n<ol>\n<li>the supported size type for this container is used</li>\n<li>the loop will be able to access any number of elements</li>\n</ol>\n\n<p>Also, as @thelamb mentioned, pre-increment (<code>++index</code>) is preferred because it will avoid extra copies. This is especially important for user-defined types (such as <code>std::array</code>), while post-increment is still okay with native types (such as <code>int</code>).</p></li>\n<li><p>Prefer <em>iterators</em> to raw pointers in C++:</p>\n\n<pre><code>// with C++11\n\nauto begin = std::begin(container);\nauto end = std::end(container);\n</code></pre>\n\n<p></p>\n\n<pre><code>// without C++11\n\nstd::ContainerType::iterator begin = std::begin(container);\nstd::ContainerType::iterator end = std::end(container);\n</code></pre></li>\n<li><p>You could compare your reverse algorithm to the <a href=\"http://en.cppreference.com/w/cpp/algorithm/reverse\" rel=\"noreferrer\">idiomatic STL method</a> with regards to efficiency (if you were to perform a speed test on them):</p>\n\n<pre><code>std::reverse(container.begin(), container.end());\n</code></pre></li>\n<li><p>I'd avoid the extra newlines in <code>display()</code>. The function's purpose is solely to display the array, plus you'll be forced to have the newline with each call. Two things for this:</p>\n\n<ol>\n<li>add the newlines before and/or after the function call instead</li>\n<li>use <code>\\n</code> instead of <a href=\"http://en.cppreference.com/w/cpp/io/manip/endl\" rel=\"noreferrer\"><code>std::endl</code></a> (the latter <em>also</em> flushes the buffer, which takes longer)</li>\n</ol>\n\n<p>So, instead of this:</p>\n\n<pre><code>std::cout << std::endl;\n\nstd::cout << \"Backwards:\\n\";\ndisplay(iArray);\n</code></pre>\n\n<p>you could have this:</p>\n\n<pre><code>std::cout << \"\\nBackwards:\\n\"; // another '\\n' at the front\ndisplay(iArray);\nstd::cout << \"\\n\"; // newline here instead of in display()\n</code></pre></li>\n</ul>\n\n<hr>\n\n<p>For comparison, here's an idiomatic alternative using <code>template</code>s (any element type is supported). It uses an <a href=\"http://en.cppreference.com/w/cpp/container/vector\" rel=\"noreferrer\"><code>std::vector</code></a> instead of an array, saving you size constraints. It also displays the vector in <a href=\"http://en.cppreference.com/w/cpp/algorithm/copy\" rel=\"noreferrer\">forward</a> and in <a href=\"http://en.cppreference.com/w/cpp/algorithm/reverse_copy\" rel=\"noreferrer\">reverse</a> using an <a href=\"http://en.cppreference.com/w/cpp/iterator/ostream_iterator\" rel=\"noreferrer\">iterator</a>, instead of mutating it for the reverse.</p>\n\n<pre><code>#include <algorithm> // std::copy, std::reverse_copy\n#include <iostream>\n#include <iterator> // std::ostream_iterator\n#include <vector>\n\ntemplate <typename T>\nvoid displayForward(std::vector<T> const& vec)\n{\n std::copy(vec.cbegin(), vec.cend(),\n std::ostream_iterator<T>(std::cout, \" \"));\n}\n\ntemplate <typename T>\nvoid displayReverse(std::vector<T> const& vec)\n{\n std::reverse_copy(vec.cbegin(), vec.cend(),\n std::ostream_iterator<T>(std::cout, \" \"));\n}\n\nint main()\n{\n std::vector<int> vec = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\n\n std::cout << \"Forward:\\n\";\n displayForward(vec);\n\n std::cout << \"\\nBackwards:\\n\";\n displayReverse(vec);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T19:57:37.120",
"Id": "52675",
"Score": "0",
"body": "Thanks Jamal! I am familiar with the STL std::array, in my class however my teacher requested we use the c-style arrays. If given the choice though, would it be better to use a std::array or a std::vector/std::list?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T20:01:54.310",
"Id": "52677",
"Score": "0",
"body": "Oh, okay. I didn't know that. Anyway, that depends on how you will use your data. If you just need something like a C-style array (static, not dynamic), then choose `std::array`. If you need to use a dynamically-allocated array (allowing you to add/remove elements from the back), choose `std::vector`. If you're using a linked list (allowing you to add/remove elements anywhere, albeit possibly slowly), choose `std::list`. Also note that `std::list` specifically implements a doubly linked-list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T20:08:39.063",
"Id": "52679",
"Score": "0",
"body": "As for your implementation with disregard to the STL, I think it's okay. There's not much else you can do with C-style arrays and raw pointers. The code still compiles, displays the correct results, and looks clean. I'll add a few more things here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T21:43:42.633",
"Id": "52680",
"Score": "0",
"body": "Thank you again Jamal. I appreciated the continued guidance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T21:47:55.940",
"Id": "52682",
"Score": "0",
"body": "@ao2130: You're welcome. I think you're doing well overall, at least from an academic perspective (if you weren't, then you would've still been using bubble sort). ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T22:47:17.947",
"Id": "52757",
"Score": "1",
"body": "You can also pass an array by reference. `void func(T (¶m)[Size])`. Useful when used in combination with templates."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T02:58:52.617",
"Id": "52769",
"Score": "1",
"body": "If you're stuck with C-style arrays but can still use the STL and have access to C++11 then you can use std::begin(array) and std::end(array) to use STL algorithms on C-style arrays."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T19:53:05.753",
"Id": "32932",
"ParentId": "32931",
"Score": "12"
}
},
{
"body": "<p>I'll just focus on your <code>reverse()</code> function, assuming that you want to keep the C-style interface rather than the C++-style <code>std::array</code> suggested by @Jamal. (It's an excellent suggestion, but I just want to focus on some basic ideas for this review.)</p>\n\n<p>I would prefer to have the array size passed in explicitly, rather than relying on the <code>SIZE</code> constant. That way, you can pull the <code>SIZE</code> constant into <code>main()</code> rather than having it be global.</p>\n\n<p>In <code>int* indexPtrEnd = iArrayRef1 += (SIZE-1)</code>, the <code>+=</code> is weird. Just <code>+</code> is sufficient; reassigning <code>iArrayRef1</code> as a side-effect is confusing (but luckily harmless).</p>\n\n<p>Since you already have two pointers crawling along the array in opposite directions, there is no need to introduce an <code>index</code> variable. You can just terminate the loop when <code>indexPtrBeg</code> and <code>indexPtrEnd</code> meet or cross each other.</p>\n\n<p>I find your variable names cumbersome. How about <code>array</code>, <code>begin</code>, and <code>end</code>? (In <code>indexPtrBeg</code>, <code>index...</code> is just misleading, and <code>...Ptr...</code> stinks of Hungarian notation.) The <code>temp</code> variable is only used within the loop, so you should declare it inside the loop.</p>\n\n<pre><code>#include <sys/types.h> /* for size_t */\n\nvoid reverse(int array[], size_t size) {\n for (int *begin = array, *end = array + size - 1; begin < end; ++begin, --end) {\n // You could use std::swap() from #include <algorithm>\n // std::swap(*begin, *end);\n int swap = *end;\n *end = *begin;\n *begin = swap;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T01:45:23.453",
"Id": "52686",
"Score": "0",
"body": "+1 good stuff. It's also nice having STL and non/STL reviews to consider. :-) I do have some notes. 1.) It seems that `SIZE` could still be global since it's used in more than one function. 2.) I would argue that the OP's incrementing and decrementing in `reverse()` is more readable. They do work in your example, but they seem to bloat that top line. That may just be me, though."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T01:21:07.877",
"Id": "32939",
"ParentId": "32931",
"Score": "3"
}
},
{
"body": "<p>Don't declare an array with a specific size if you are also going to initialize it:</p>\n\n<blockquote>\n<pre><code>int iArray[SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\n</code></pre>\n</blockquote>\n\n<p>If SIZE is too small them you have an error (that is not reported). If SIZE is too large then the array is silently filled with 0. Both can be an issue. Prefer:</p>\n\n<pre><code>// Let the compiler work out the size from the data you provide.\nint iArray[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };\n</code></pre>\n\n<p>Though it looks like you are passing an array here:</p>\n\n<blockquote>\n<pre><code>void display(int iArrayRef2 [])\n</code></pre>\n</blockquote>\n\n<p>Its not. You are just passing a pointer (arrays decay to pointers). All array context is lost. This is dangerous as some people forget and try and use <code>iArrayRef2</code> as if it was an array. So when you declare a function like this prefer to use pointer syntax. This will remind people that they are dealing with pointers.</p>\n\n<pre><code>void display(int* iArrayRef2)\n</code></pre>\n\n<p>Passing an array as a pointer without a size is a bad idea. You have no idea where it ends. Always pass size information. There are a couple of ways to do this:</p>\n\n<pre><code>void display(int* iArrayRef2, int size) // Standard C way\nvoid display(int* begin, int* end) // Standard C++ 03 way (iterator based)\n\n// Or do it so you can allow real templates\ntemplate<typename I>\nvoid display(I begin, I end)\n\n// Or pass by reference\ntemplate<int size>\nvoid display(int (&iArrayRef2)[size])\n\n// Or pass any of the standard containers.\n</code></pre>\n\n<p>Note if you use the template version above:</p>\n\n<pre><code>display(&iArray[0], &iArray[SIZE]); // prints forward\ndisplay(std::reverse_iterator<int*>(&iArray[SIZE]), std::reverse_iterator<int*>(&iArray[0])); // prints backwards\n</code></pre>\n\n<p>You don't need to re-invent swap</p>\n\n<pre><code> temp = *indexPtrEnd;\n *indexPtrEnd = *indexPtrBeg;\n *indexPtrBeg = temp;\n\n // or\n std::swap(*indexPtrBeg, *indexPtrEnd);\n</code></pre>\n\n<p>If you do encapsulate it in its own function. This will make reading the code easier.</p>\n\n<p>Prefer to use std::reverse rather than your own version (its highly optimized).</p>\n\n<p>There are some useful standard algorithms that can make the code shorter and more readable.</p>\n\n<pre><code>for (int index = 0; index < SIZE; index++)\n{\n std::cout << std::setw(2) << iArrayRef2[index] << \" \";\n}\n\n// or\nstd::cout << std::setw(2);\nstd::copy(&iArrayRef2[0], &iArrayRef2[SIZE], std::ostream_iterator<int>(std::cout, \" \"));\n</code></pre>\n\n<p>Example of passing an array by reference:</p>\n\n<pre><code>template<typename T, int size>\nint size(T (&array)[size])\n{\n return size;\n}\nint main()\n{\n int a[10];\n float b[14];\n std::cout << size(a) << \" \" << size(b) << \"\\n\";\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T23:05:18.073",
"Id": "32984",
"ParentId": "32931",
"Score": "7"
}
},
{
"body": "<p>since this is int reversing, you could avoid the pointers and temp values</p>\n\n<p>(saves memory space, which in this case is not so important but this math trick might help you in the future) </p>\n\n<p>and just use subtraction and adding</p>\n\n<p>for example:</p>\n\n<pre><code>int a= 13;\nint b= 25;\na=a+b;//38\nb=a-b;//38-25 = 13\na=a-b;//38-13 = 25\n</code></pre>\n\n<p>all you have to do is take an array of size x</p>\n\n<p>and you reverse the values of the First(0 index) and last(x-1 index)</p>\n\n<p>then the second (1 index) and one before the last(x-2 index)</p>\n\n<p>and so on</p>\n\n<p>EDIT:</p>\n\n<p>here is my solution using this math trick:</p>\n\n<pre><code>#include <iostream>\n#include <iomanip>\n\nconst int SIZE = 10;\n\nvoid reverse(int array[])\n{\n for (int i = 0; i < SIZE/2; i++)\n {\n array[i]+=array[SIZE-(i+1)];\n array[SIZE-(i+1)]=array[i]-array[SIZE-(i+1)];\n array[i]-=array[SIZE-(i+1)];\n }\n}\n\nvoid display(int iArrayRef2 [])\n{\n for (int index = 0; index < SIZE; index++)\n {\n std::cout << std::setw(2) << iArrayRef2[index] << \" \";\n }\n std::cout << std::endl;\n}\n\nint _tmain(int argc, _TCHAR* argv[])\n{\n int iArray[SIZE] = { 1, 2, 3, 4, 5, 6, 7, 8, 9,10 };\n\n // Display in the original order.\n std::cout << \"Forwards:\\n\";\n display(iArray);\n\n // Reverse the array.\n reverse(iArray);\n\n std::cout << std::endl;\n\n // Display in reversed order.\n std::cout << \"Backwards:\\n\";\n display(iArray);\n\n return 0;\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-20T02:42:56.570",
"Id": "42249",
"ParentId": "32931",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "32932",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T19:28:45.583",
"Id": "32931",
"Score": "4",
"Tags": [
"c++",
"optimization",
"array"
],
"Title": "Reversing the elements of an array"
}
|
32931
|
<p>I frequently have patterns as below, usually not this simple, which require me to first code a working solution for a single test case, and then to refactor the code to make it more concise. See the first incarnation below, then the final code. I'm looking to see what other techniques some use to skip the initial step, other than suddenly being able to see the solution with experience. Or if you would approach the example below in an entirely different fashion.</p>
<p>Initial code:</p>
<pre><code># 4.) A Tic-tac-toe game (see http://en.wikipedia.org/wiki/Tic-tac-toe) can be
# simulated by a computer using a 3 x 3 matrix of strings. Each string has one
# of three possible values, 'X', 'O' or '' (an empty block). Moreover,
# individual move of a player can be simulated with a tuple, containing three
# values: the x-coordinate (0..2), the y-coordinate (0..2) and a string
# containing the mark of the player ('X' or 'O'). Write a procedure
# insertMoves(board, listOfMoves), which has two parameters: a 3 x 3 matrix
# board and a list of players moves as tuples. The procedure then inserts all
# moves in a list to the game board.
def insertMoves(board, list_of_moves):
for move in list_of_moves:
if move[0] == 0:
if move[1] == 0:
(board[0])[0] = move[2]
if move[1] == 1:
(board[1])[0] = move[2]
if move[1] == 2:
(board[2])[0] = move[2]
elif move[0] == 1:
if move[1] == 0:
(board[0])[1] = move[2]
if move[1] == 1:
(board[1])[1] = move[2]
if move[1] == 2:
(board[2])[1] = move[2]
elif move[0] == 2:
if move[1] == 0:
(board[0])[2] = move[2]
if move[1] == 1:
(board[1])[2] = move[2]
if move[1] == 2:
(board[2])[2] = move[2]
return board
row = [''] * 3
board = [row, row[:], row[:]]
moves = [(0, 0, 'A'), (0, 1, 'B'), (0, 2, 'C'), (1, 0, 'D'), (1, 1, 'E'),
(1, 2, 'F'), (2, 0, 'G'), (2, 1, 'H'), (2, 2, 'I')]
final_board = insertMoves(board, moves)
for row in final_board:
print row
</code></pre>
<p>And the final function definition:</p>
<pre><code>def insertMoves(board, list_of_moves):
for move in list_of_moves:
for i in range(0, 3):
if move[0] == i:
for j in range(0, 3):
if move[1] == j:
(board[j])[i] = move[2]
return board
</code></pre>
|
[] |
[
{
"body": "<p>I would write the loop like this:</p>\n\n<pre><code>for i, j, move in list_of_moves:\n assert(0 <= i < 3 and 0 <= j < 3 and move in 'XO')\n board[j][i] = move\n</code></pre>\n\n<p>or maybe:</p>\n\n<pre><code>VALID_MOVES = 'XO'\nfor i, j, move in list_of_moves:\n assert(0 <= j < len(board) and 0 <= i < len(board[j]) and move in VALID_MOVES)\n board[j][i] = move\n</code></pre>\n\n<p>depending on how general I needed the implementation to be.</p>\n\n<p>Something that you might find helpful would be to step through your code in the <a href=\"http://docs.python.org/3/library/pdb.html\" rel=\"nofollow\">Python debugger</a>. Look at each line as it is executed and check that it makes sense. For example:</p>\n\n<pre><code>>>> board = [[''] * 3 for _ in range(3)]\n>>> moves = [(1,1,'X'), (0,0,'O')]\n>>> import pdb\n>>> pdb.run(\"insertMoves(board, moves)\")\n> <string>(1)<module>()\n(Pdb) step\n--Call--\n> cr32933.py(1)insertMoves()\n-> def insertMoves(board, list_of_moves):\n(Pdb) step\n> cr32933.py(2)insertMoves()\n-> for move in list_of_moves:\n(Pdb) step\n> cr32933.py(3)insertMoves()\n-> for i in range(0, 3):\n(Pdb) print move\n(1, 1, 'X')\n(Pdb) step\n> cr32933.py(4)insertMoves()\n-> if move[0] == i:\n(Pdb) print i\n0\n(Pdb) step\n> cr32933.py(3)insertMoves()\n-> for i in range(0, 3):\n(Pdb) step\n> cr32933.py(4)insertMoves()\n-> if move[0] == i:\n(Pdb) print i\n1\n</code></pre>\n\n<p>At about this point (if not earlier) you should be saying to yourself, \"why did I have to go round the loop in order to discover that <code>move[0]</code> has the value 1?\"</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T20:28:25.773",
"Id": "32936",
"ParentId": "32933",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "32936",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T20:06:44.087",
"Id": "32933",
"Score": "0",
"Tags": [
"python"
],
"Title": "Faster track to recognizing patterns in looping through nested sequences"
}
|
32933
|
<p>Please review my code/code quality.</p>
<pre><code>var textarea = document.getElementById("textarea"),
inputFile = document.getElementById("input-file"),
prtHelper = document.getElementById("prt-helper"),
overlay = document.getElementById("overlay"),
help = document.getElementById("help"),
appname = " - notepad",
filename = "untitled.txt",
isModified = false;
if (localStorage.getItem("txt")) { // Load localStorage
textarea.value = localStorage.getItem("txt");
filename = localStorage.getItem("filename");
isModified = true;
}
window.onunload = function() { // Save localStorage
if (isModified) {
localStorage.setItem("txt", textarea.value);
localStorage.setItem("filename", filename);
} else {
localStorage.clear();
}
};
function changeDocTitle() { // Change doc title
document.title = filename + appname;
}
window.onload = changeDocTitle();
textarea.onpaste = textarea.onkeypress = function() { // Note is modified
isModified = true;
};
function cancelSaving() { // Confirm cancel saving
if (isModified && confirm("You have unsaved changes that will be lost.")) {
isModified = false;
return true;
}
}
function New() { // New
if (!isModified || cancelSaving()) {
textarea.value = "";
filename = "untitled.txt";
changeDocTitle();
}
textarea.focus();
}
function Open() { // Open
if (!isModified || cancelSaving()) {
inputFile.click();
}
textarea.focus();
}
function loadFile() { // Load file
var file = inputFile.files[0],
fileReader = new FileReader();
fileReader.onloadend = function(e) {
filename = file.name;
changeDocTitle();
textarea.value = e.target.result;
};
fileReader.readAsText(file);
}
function rename() { // Rename
var newFilename;
do {
newFilename = prompt("Name this note:", filename);
} while (newFilename === "");
if (newFilename) {
filename = (newFilename.lastIndexOf(".txt") == -1) ? newFilename + ".txt" : newFilename;
changeDocTitle();
return true;
}
}
function Save() { // Save
if (rename()) {
var blob = new Blob([textarea.value.replace(/\n/g, "\r\n")], {
type: "text/plain;charset=utf-8"
});
saveAs(blob, filename);
isModified = false;
}
textarea.focus();
}
function Print() { // Print
prtHelper.innerHTML = textarea.value;
window.print();
prtHelper.innerHTML = "";
textarea.focus();
}
function Help() { // Help
help.setAttribute("aria-hidden", "false");
overlay.setAttribute("aria-hidden", "false");
textarea.blur();
document.getElementById("cls-hlp").onclick = overlay.onclick = function() {
closeHelp();
};
}
function closeHelp() { // Close help
help.setAttribute("aria-hidden", "true");
overlay.setAttribute("aria-hidden", "true");
textarea.focus();
}
function bookmark() { // temporarily change doc title
var docTitle = document.title;
document.title = "Notepad5";
setTimeout(function() {
document.title = docTitle;
}, 3);
}
document.onkeydown = function(e) { // Keyboard shortcuts
var key = e.keyCode || e.which;
if (e.ctrlKey) {
if (e.altKey && key == 78) { // Ctrl+Alt+N
e.preventDefault();
New();
}
switch (key) {
case 79: // Ctrl+O
e.preventDefault();
Open();
break;
case 83: // Ctrl+S
e.preventDefault();
Save();
break;
case 80: // Ctrl+P
e.preventDefault();
Print();
break;
case 191: // Ctrl+/
e.preventDefault();
Help();
break;
case 68: //Ctrl+D
bookmark();
break;
default:
break;
}
}
if (key == 27) { // Esc
closeHelp();
}
if (key == 9) { // Tab
e.preventDefault();
var sStart = textarea.selectionStart,
txt = textarea.value;
textarea.value = txt.substring(0, sStart) + "\t" + txt.substring(textarea.selectionEnd);
textarea.selectionEnd = sStart + 1;
}
};
</code></pre>
|
[] |
[
{
"body": "<p>A quick glance,</p>\n\n<p><strong>Code has a lot of global variables</strong></p>\n\n<p>Either namespace it or wrape it so it is in its own scrope and not in window scope.</p>\n\n<p><strong>Attaching Events directly to elements</strong></p>\n\n<p>You should be attaching events with <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/EventTarget.addEventListener\" rel=\"nofollow\">addEventListener</a>. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T12:50:15.323",
"Id": "32997",
"ParentId": "32935",
"Score": "1"
}
},
{
"body": "<p>There could be a lot to improve</p>\n\n<ul>\n<li>As said before, you have a lot of ( too many ) globals</li>\n<li>You should look up MVC ( Model View Controller )\n<ul>\n<li>I would put the title, text and all save/load functions under editor.model</li>\n<li>I would put all routing logic in editor.controller</li>\n<li>I would put a function that takes the title and text from editor.model and shows it into editor.view, plus also the help displaying/hiding logic</li>\n</ul></li>\n<li>In general, try to pass data to functions through parameters, not globals, an example would be fucntion <code>New</code> which should get <code>isModified</code> as a parameter</li>\n<li>function names shoud start with lowercase, <code>open</code> & <code>new</code>, not <code>Open</code> & <code>New</code> etc.</li>\n* \n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T13:58:34.390",
"Id": "33000",
"ParentId": "32935",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T20:20:31.623",
"Id": "32935",
"Score": "2",
"Tags": [
"javascript"
],
"Title": "JavaScript online TextEditor"
}
|
32935
|
<p>Given a sorted array of <em>N</em> elements, I need to find the absolute sum of the differences of all elements.</p>
<p>Given 4 elements (1, 2, 3 and 4):</p>
<blockquote>
<p>|1-2|+|1-3|+|1-4|+|2-3|+|2-4|+|3-4| = 10</p>
</blockquote>
<p>Here is my code in Java:</p>
<pre><code>List<Integer> a = new ArrayList<Integer>(); //just for understanding , the Array List is already filled with numbers
public static int lsum(int N)
{
int sum =0;
for( int i=0;i<N;i++)
{
int w =a.get(i);
for(int j =i;j<N;j++)
{
int z = a.get(j);
sum =sum +(z-w);
}
}
return(sum);
}
</code></pre>
<p>I'm looking for an efficient algorithm rather than the trivial one I am using (O(n<sup>2</sup>) complexity). This is a requirement for a bigger program which requires this function. The input (number of elements) can be as big as 10<sup>5</sup>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T22:08:33.450",
"Id": "52683",
"Score": "0",
"body": "1. What is `min`? 2. Don't you need `abs` somewhere? 3. Do we know anything about the numbers in the array (i.e., their span, distribution,...)? 4. Setting `j=i+1` instead of `j=i` will save you `N` steps."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T22:48:31.370",
"Id": "52684",
"Score": "0",
"body": "@VedranŠego 1. corrected. 2. Consider the list to be sorted in ascending order. 3. k< 10^5 that is all that's given. 4. Thanks for the save, however when the input size is considered the (10^5) does not really help in reducing O(n^2) complexity"
}
] |
[
{
"body": "<p>Let's see this mathematically. I am assuming that <code>a</code> is an ascendingly sorted array. I start with indexes from 1, to get better readability (by avoiding <code>n-1</code> as often as possible).</p>\n\n<p>We want the following sum:</p>\n\n<p>$$\\begin{array}{l@{}l@{}l@{}l}\n\\sum_{i=1}^{n-1} \\sum_{j=i+1}^n (a_j - a_i) = (a_2 - a_1) &+ (a_3 - a_1) &+ (a_4 - a_1) + & \\dots + (a_n - a_1) +\\\\\n &+ (a_3 - a_2) &+ (a_4 - a_2) + & \\dots + (a_n - a_2) +\\\\\n &&+ (a_4 - a_3) + & \\dots + (a_n - a_3) +\\\\\n &&& \\dots\n\\end{array}$$</p>\n\n<p>So, we:</p>\n\n<ol>\n<li>add <code>a1</code> zero times, <code>a2</code> once,... <code>ak</code> k-1 times, and</li>\n<li>subtract <code>a1</code> n-1 times, <code>a2</code> n-2 times,... <code>ak</code> n-k times.</li>\n</ol>\n\n<p>I'd say that your sum is</p>\n\n<p>$$\n\\sum_{k=1}^n (k-1)a_k - \\sum_{k=1}^n (n-k)a_k = \\sum_{k=1}^n (2k-n-1)a_k\n$$</p>\n\n<p>Given your example (1,2,3,4), we get:</p>\n\n<p>$$\n\\sum_{k=1}^4 (2k-4-1)a_k = -3 \\cdot 1 + (-1 \\cdot 2) + 1 \\cdot 3 + 3 \\cdot 4 = -3 - 2 + 3 + 12 = 10.\n$$</p>\n\n<p>This has a linear complexity, which is optimal, because you need to \"visit\" each member of the array at least once (which is linear).</p>\n\n<p>I believe you can write your code by yourself. Just set indexes to go from zero, but be careful about the formula: <code>2k - n - 1</code> becomes <code>2k - n + 1</code> when <code>k</code> starts from zero.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T18:48:03.627",
"Id": "52730",
"Score": "0",
"body": "woah! Thanks a lot. The break up of the formula did the trick."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T21:59:59.633",
"Id": "52748",
"Score": "0",
"body": "What should I say? excellent!"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T23:20:29.130",
"Id": "32938",
"ParentId": "32937",
"Score": "13"
}
},
{
"body": "<p>I would not give you the exact solution to this problem rather I would help you to get an intuition on how to solve this question.</p>\n<p>If we try to generalize count of the number of times a particular number at index <em>i</em> is getting added and the number of times it is being subtracted then for every index <em>i</em> we can use that mathematically derived formula to compute the sum of contributions of every number in the absolute difference in <strong>O(N) time and O(1) extra space</strong>.</p>\n<p>You can refer to this video if you still find difficulties in understanding this concept.</p>\n<p>Video Link:-</p>\n<p><a href=\"https://youtu.be/A4sz4kNDa-8\" rel=\"nofollow noreferrer\">https://youtu.be/A4sz4kNDa-8</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T12:12:28.247",
"Id": "478974",
"Score": "0",
"body": "Thanks for the answer @Vaibhav! And welcome to Stack Exchange. But let's not open ~7 years old threads, unless the question is unanswered or you have something more valuable to add to which is missing. Might I suggest to re-read answering guide. Cheers. :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-06-16T10:12:48.233",
"Id": "243972",
"ParentId": "32937",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "32938",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-19T21:10:22.067",
"Id": "32937",
"Score": "7",
"Tags": [
"java",
"algorithm",
"complexity"
],
"Title": "Simplify function to sum the absolute value of the difference between all pairs of elements of a sorted array"
}
|
32937
|
<p>I have an Access database that I'm converting to SQL Server 2008. One of the queries in the database uses the LAST function. The table has a AutoNumber ID so true order is simple.</p>
<blockquote>
<pre><code>SELECT tbl_unit.unit,
LAST(tbl_unit.date) AS Date,
LAST(tbl_unit.mileage) AS Mileage
FROM tbl_unit
GROUP BY tbl_unit.unit
</code></pre>
</blockquote>
<p>SQL 2008 doesn't have any function like that so I wrote the following:</p>
<pre><code>SELECT Unit, [Date], Mileage
FROM (
SELECT a.id, a.Unit, a.[Date], a.Mileage
FROM tbl_Unit a
INNER JOIN (SELECT MAX(id) MaxID, Unit FROM tbl_Unit
GROUP BY Unit) b ON a.id = b.maxid
) t1
</code></pre>
<p>I'm looking for alternates or better code.<br>
This query returns one record for each "Unit" where the Record is the LAST record entered regardless of the date or mileage values entered. The Table has several thousand entries and this query returns over 100 rows. </p>
<p>The ID is both an auto incrementing number and the primary key. The following data is part of the table.</p>
<blockquote>
<pre><code>ID Unit DATE Mileage
217316 171 2006-01-27 59761
216668 171 2005-12-01 57875
216194 171 2006-01-21 59346
217591 1127 2006-01-30 406692
217467 1127 2006-01-27 406339
217466 1127 2006-01-27 406127
217598 2310 2006-01-29 68372
217505 2310 2006-01-28 68187
217504 2310 2006-01-28 67987
</code></pre>
</blockquote>
<p>The correct output with this set of data is:</p>
<blockquote>
<pre><code>Unit Date Mileage
171 2006-01-27 59761
1127 2006-01-30 406692
2310 2006-01-29 68372
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<p>Have you Tried this?</p>\n\n<pre><code>SELECT Unit, [Date], Mileage\nFROM tbl_unit\nWHERE tbl_unit.id = (SELECT MAX(id) FROM tbl_unit)\n</code></pre>\n\n<p>OR </p>\n\n<pre><code>SELECT Unit, [Date], Mileage\nFROM tbl_unit\nWHERE tbl_unit.Date = (SELECT MAX(Date) FROM tbl_unit)\n</code></pre>\n\n<p>I am not sure exactly what kind of Record set you are looking for, could you give a little more information if this is not useful to you?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T00:16:42.660",
"Id": "52997",
"Score": "0",
"body": "Yep, looked at those. The data is particularly bad and has many lazy entries in it. First one won't work since ID is an AutoNumber. (Only get one record) 2nd won't work since data is frequently bad."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T13:25:19.157",
"Id": "53046",
"Score": "0",
"body": "you should probably work on cleaning up the data first, otherwise you won't really know what is efficient and what is caused by bad data that shouldn't be there in the first place"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T15:41:35.380",
"Id": "53068",
"Score": "0",
"body": "When I rebuild the application I will have appropriate data testing in the input. Cleanup is out of the question. Too much data and too many lazy entries."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T15:59:03.110",
"Id": "53070",
"Score": "0",
"body": "could you elaborate on the bad data? you should be able to work around the bad data while using a query similar to the second query. if that is what you want you should either fix or work around the bad data."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T15:06:46.190",
"Id": "33006",
"ParentId": "32940",
"Score": "1"
}
},
{
"body": "<p>Try this - </p>\n\n<pre><code>;WITH cte AS (\n SELECT a.id, a.Unit, a.[Date], a.Mileage, ROW_NUMBER() OVER (ORDER BY a.id DESC) row_num FROM tbl_Unit a\n)\nSELECT * FROM cte WHERE row_num = 1\n</code></pre>\n\n<p>Check Tech net Document - <a href=\"http://technet.microsoft.com/en-us/library/ms190766%28v=sql.105%29.aspx\" rel=\"nofollow\">CTE</a></p>\n\n<p>Beside these you can also check some code project links, these are helpful.</p>\n\n<p><a href=\"http://www.codeproject.com/Articles/275645/CTE-In-SQL-Server\" rel=\"nofollow\">CTE in SQL Server</a></p>\n\n<p>FOR <code>ROW_NUMBER</code> check <a href=\"http://technet.microsoft.com/en-us/library/ms186734.aspx\" rel=\"nofollow\">documentation</a> you can find examples there which I think you can understand easily.</p>\n\n<p><a href=\"http://www.codeproject.com/Articles/265371/Common-Table-Expressions-CTE-in-SQL-SERVER-2008\" rel=\"nofollow\">CTE in SQL Server 2008</a></p>\n\n<p>You can find details on <code>CTE</code> in these links. It also provides you information on when to use them. When you get familiar with the purpose and the syntax of <code>CTE</code>, you can figure out different use of <code>CTE</code> yourself. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T22:50:52.900",
"Id": "52849",
"Score": "2",
"body": "Can you please explain why you are suggesting it, and what improvements it would make? It makes understanding the answer much easier."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T13:47:24.967",
"Id": "52913",
"Score": "0",
"body": "might want to explain the importance of the `ORDER BY a.id DESC` in this Query as well. I know it is a simple Query but understanding the simple queries is where the advanced stuff becomes easier to understand."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T13:58:12.207",
"Id": "52915",
"Score": "1",
"body": "Code Project links mention about `RANKING` functions too. You can just `Google` them for more information."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-29T18:38:54.120",
"Id": "53601",
"Score": "0",
"body": "Although I prefer this solution, it doesn't work. I have been restricted to SQL 2000 for about 10 years and haven't been able to use CTE like this."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T21:24:24.163",
"Id": "33028",
"ParentId": "32940",
"Score": "2"
}
},
{
"body": "<p>This should do it:</p>\n\n<pre><code>SELECT U1.Unit, U1.[Date], U1.Mileage\nFROM tbl_unit U1\nWHERE U1.id IN (\n SELECT MAX(U2.id) \n FROM tbl_unit U2\n GROUP BY U2.Unit\n);\n</code></pre>\n\n<p>This uses a simple subquery correlated on the <code>tbl_Unit.Unit</code>. This approximates your <code>GROUP BY</code> and <code>LAST()</code> functions in Access by <code>SELECTing</code> the most recent row for each <code>Unit</code>. <code>LAST()</code> in Access returns the most recently added record, and since the <code>id</code> field is an <code>Autonumber</code> (or <code>IDENTITY()</code> in SQL Server) field, <code>MAX(id)</code> will automatically return the most recent row for each unit. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-29T18:40:44.817",
"Id": "53602",
"Score": "0",
"body": "The difference between mine and yours is the sub-query. FYI: I built mine from the inside out which is the reason I left the \"Unit\" in the query."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T01:56:30.447",
"Id": "33209",
"ParentId": "32940",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "33209",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T04:06:47.060",
"Id": "32940",
"Score": "3",
"Tags": [
"sql",
"sql-server",
"ms-access"
],
"Title": "Code conversion from Access to T-SQL"
}
|
32940
|
<p>In some programming languages, copying a variable may be implemented as either a copy by value or a copy by reference. When it is copied by reference, a reference to the data will be assigned, and the underlying data is not copied. Often, object datatypes will be copied by reference by default (for example, in Java), while primitives will be copied by value.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T06:02:53.027",
"Id": "32941",
"Score": "0",
"Tags": null,
"Title": null
}
|
32941
|
A reference is a value that enables a program to indirectly access a particular datum, such as a variable or a record, in the computer's memory or in some other storage device.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T06:02:53.027",
"Id": "32942",
"Score": "0",
"Tags": null,
"Title": null
}
|
32942
|
<p>I have a matrix transpose function that takes arrays with a possibly different number of rows and columns.</p>
<p>How can I improve performance and code quality?</p>
<pre><code>void matrix_transpose(float *matrix, int rows, int columns)
{
int current_row;
int current_column;
float temp;
float buffer[MATRIX_TRANSPOSE_BUFFER_SIZE];
int buffer_position = 0;
if(rows == columns)
{
for(current_row = 0; current_row < rows; ++current_row)
{
for(current_column = current_row; current_column < columns; ++current_column)
{
temp = *(matrix + current_row * columns + current_column);
*(matrix + current_row * columns + current_column) = *(matrix + current_column * columns + current_row);
*(matrix + current_column * columns + current_row) = temp;
}
}
}
else if(rows * columns < MATRIX_TRANSPOSE_BUFFER_SIZE)
{
for(current_column = 0; current_column < columns; ++current_column)
{
for(current_row = 0; current_row < rows; ++current_row)
{
buffer[buffer_position++] = *(matrix + current_row * columns + current_column);
}
}
buffer_position = 0;
while(buffer_position < rows * columns)
{
*matrix++ = buffer[buffer_position++];
}
}
}
</code></pre>
<p>Here's an example call:</p>
<pre><code>float matrix[] = {
1, 2, 3, 4,
5, 6, 7, 8,
9, 10, 11, 12,
13, 14, 15, 16,
17, 18, 19, 20
};
matrix_transpose(matrix, 5, 4);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T19:57:05.683",
"Id": "52735",
"Score": "1",
"body": "Try a [XOR swap](http://en.wikipedia.org/wiki/XOR_swap_algorithm)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T19:59:19.963",
"Id": "52736",
"Score": "0",
"body": "Also, for copying memory, use `memcpy()` as it's usually better optimized than your loop and will make your code more readable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T10:10:06.120",
"Id": "52789",
"Score": "1",
"body": "I was exploring the problem, and discovered that [in-place matrix tranposition](http://en.wikipedia.org/wiki/In-place_matrix_transposition) has been extensively studied."
}
] |
[
{
"body": "<ol>\n<li>The call can apparently fail if the matrix supplied is larger than the internal buffer in the function. Yet there is no indication that this was the case. <code>matrix_transpose</code> should return an error code indicating the result of the operation.</li>\n<li><code>float buffer[MATRIX_TRANSPOSE_BUFFER_SIZE];</code> lives on the stack of the function. The stack is usually limited to a few MB (I think default in Visual Studio is 1MB, on Linux it's typically around 8MB but depends on the setup). Not sure how big the matrices will get but this might get you into trouble. Consider using either a static buffer (not thread safe) or allocate the buffer via <code>malloc</code> on the heap.</li>\n<li>Instead of <code>*(matrix + current_row * columns + current_column)</code> you can also write <code>matrix[current_row * columns + current_column]</code> which is a bit easier on the eyes (imho).</li>\n<li>It is accepted practice that loop counters can be single letter variables. In conjunction with the fact that you operate on a 2 dimensional array you could consider renaming <code>current_row</code> into <code>y</code> and <code>current_column</code> into <code>x</code>. Shortens the code somewhat and doesn't loose much meaning. Using <code>x</code> and <code>y</code> to identify positions in a 2D structure is common practice.</li>\n<li>When you transpose a matrix which is not square then the calling code will not be directly exposed to the fact that <code>rows</code> and <code>columns</code> are now transposed. You should pass <code>rows</code> and <code>columns</code> \"by reference\" (<code>int *</code>) and swap them before you return from the function. Otherwise the calling could needs to do that every time it calls the transpose function and the programmer is bound to forget it at one point.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T09:03:17.887",
"Id": "52692",
"Score": "0",
"body": "Won't calling malloc every time the function runs make it slower?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T09:31:08.503",
"Id": "52693",
"Score": "0",
"body": "I tested calling malloc and free, the total cost for the function went up from just over 640 to over 4000 on the first call and to over 1000 on subsequent calls. Would malloc definitely be considered a better approach?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T10:54:06.263",
"Id": "52694",
"Score": "1",
"body": "Well, if your matrices are always small then keep it on the stack but if you want to make them bigger in the future then you simply can't keep them on the stack. Sure, malloc and free add some overhead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T20:27:58.633",
"Id": "52737",
"Score": "0",
"body": "There's a term we use to describe getting fast results with code that's not quite correct: it's called cheating on a benchmark. Either you fix the bug to handle the general case, or officially recognize the limitation (with a comment on the function and an error code)."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T07:53:58.813",
"Id": "32952",
"ParentId": "32944",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "32952",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T06:06:05.007",
"Id": "32944",
"Score": "2",
"Tags": [
"performance",
"c",
"matrix"
],
"Title": "Matrix transpose function"
}
|
32944
|
A wrapper is an OOP technique where an object encapsulates (wraps) another object, hiding/protecting the object and controlling all access to it.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T06:18:20.473",
"Id": "32946",
"Score": "0",
"Tags": null,
"Title": null
}
|
32946
|
Consider whether your question would be better asked at CrossValidated, a Stack Exchange site for probability, statistics, data analysis, data mining, and machine learning. Code Review questions on statistics should be about implementation and working program review, not about theoretical discussions of statistics or research design.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T06:21:14.970",
"Id": "32948",
"Score": "0",
"Tags": null,
"Title": null
}
|
32948
|
In computing, input/output, or I/O, refers to the communication between an information processing system (such as a computer) and the outside world (possibly a display, an information storage system, or another information processing system).
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T06:29:36.323",
"Id": "32950",
"Score": "0",
"Tags": null,
"Title": null
}
|
32950
|
<p>I have two admin groups - VCS, and VPN. For each group, I need to get the list of all the people in that group, along with their IDs.</p>
<p>What is the best way to do this? Could you please suggest if it is good enough?</p>
<p>Also, should I use a map to store the data instead of creating a new object <code>GetAdminInfo</code>?</p>
<pre><code>public class GetAdminInfo
{
private List<String> persons;
private List<String> personIds;
public List<String> getPersonIds() {
return personIds;
}
public void setPersonIds(List<String> personIds) {
this.personIds = personIds;
}
public List<String> getPersons() {
return persons;
}
public void setPersons(List<String> persons) {
this.persons = persons;
}
}
</code></pre>
<p>This is the method I have written in my DAO class.</p>
<pre><code>public static GetAdminInfo fetchPersonIdInfo(String adminGroup) throws SQLException
{
GetAdminInfo personInfo =null;
Connection connection = null;
PreparedStatement statement = null;
ResultSet rs = null;
List<String> personId = new ArrayList<String>();
List<String> persons = new ArrayList<String>();
try {
connection = createConnection();
statement = connection.prepareStatement("SELECT PERSON_ID,PERSONS FROM ADMIN_INFO WHERE ADMINGROUP = ?");
statement.setString(1, adminGroup);
rs = statement.executeQuery();
if(rs.next())
{
personInfo = new GetAdminInfo();
adminGroup = rs.getString(COLUMN_ADMINGROUP)!=null?rs.getString(COLUMN_ADMINGROUP):"";
personId.add(rs.getString(1));
persons.add(rs.getString(1));
personInfo.setDeviceIds(deviceId);
personInfo.setPersonIds(personId);
}
} finally{
rs.close();
conn.close();
statement.close();
}
return personInfo;
}
</code></pre>
|
[] |
[
{
"body": "<p>Well my first gut reaction is that I don't like what I see. Here is why though and hopefully that will help you understand why I feel this way. First is with the naming convention. GetAdminInfo is a verb. Classes are nouns. This is true in all of mainstream OO languages. Therefore a more appropriate name would be AdministratorInformation. But even that name is misleading because of the contents. Your class has 2 arrays which of type String. Since you are dealing with a database it would be ok to make a class called AdministratorGroup which has 2 properties Name and Id with appropriate Getters and setters. Then your AdministratorInformation class would be renamed to AdministratorGroupCollection and have only 1 Array of type AdministratorGroup. Now after you put this program down for some time and come back to it you will find it easier to remember what these classes do. A name should always indicate its intent. You would be very angry at me if i had a class called CartesianPoint and instantiated it like this <code>CartesianPoint point = new CartesianPoint(\"5Mhz\");</code> You'd be angry because I lied to you. I normally don't do this as I leave it up to you to make changes, but I want to show some sort of code. SO here is what your code would look like after I got my hands on it.</p>\n\n<p><strong>AdministratorInfo</strong></p>\n\n<pre><code>public class AdministratorInfo\n{\n private String ID;\n private String name;\n\n public String getID()\n {\n return ID;\n }\n public String getName()\n {\n return name;\n }\n\n public void setID(String ID)\n {\n this.ID = ID;\n }\n public void setName(String name)\n {\n this.name = name;\n }\n}\n</code></pre>\n\n<p><strong>AdministratorGroupCollection</strong></p>\n\n<pre><code>public class AdministratorGroupCollection\n{\n private List<AdministratorInfo> persons;\n\n public List<AdministratorInfo> getPersons()\n {\n return persons;\n }\n\n public void setPersons(List<AdministratorInfo> newList)\n {\n persons = newList;\n }\n}\n</code></pre>\n\n<p>With this code you will not have to add more and more Lists to your collection class to add or remove properties. You'll only have to change the AdministratorGroup class to adjust those properties.</p>\n\n<p>Last point I want to point out is the confusing basis for your SQL method. By the name of it I get the impression that you are returning a single user and not a collection of users. but your code says that you are returning a collection of users. Don't let your names and methods lie about their intent. If you only intend to return a single user then return a class that is not a collection. If your intent is to get a group or a collection of things then you will return a list. Otherwise you are just making it hard for others (others can mean you in the future) to know how to use your code. Although I would break this method up some more to make it a little bit easier to read it serves its purpose. This is how I interpreted your code, and how I would have fixed it.</p>\n\n<pre><code>public static AdministratorInfo fetchPersonIdInfo(String adminGroup) throws SQLException\n{\n AdministratorInfo personInfo = new AdministratorInfo();\n Connection connection = null;\n PreparedStatement statement = null;\n ResultSet rs = null;\n try\n {\n connection = createConnection();\n statement = connection.prepareStatement(\"SELECT PERSON_ID,PERSONS FROM ADMIN_INFO WHERE ADMINGROUP = ?\");\n statement.setString(1, adminGroup);\n rs = statement.executeQuery();\n if (rs.next())\n {\n //what purpose does it serve to change adminGroup? \n adminGroup = rs.getString(COLUMN_ADMINGROUP) != null ? rs.getString(COLUMN_ADMINGROUP) : \"\";\n personInfo.setID(rs.getString(1));\n personInfo.setName(rs.getString(2));\n personInfo.setDeviceIds(deviceId); //I don't like not knowing what this is\n }\n\n }\n finally\n {\n rs.close();\n connection.close();\n statement.close();\n }\n\n return personInfo;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T21:55:32.387",
"Id": "32980",
"ParentId": "32953",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T08:10:48.347",
"Id": "32953",
"Score": "3",
"Tags": [
"java",
"beginner",
"oracle",
"jdbc"
],
"Title": "Getting list from an Oracle database and storing it in an object"
}
|
32953
|
<pre><code>class MyClass{
static Integer carry = 0;
public static void main(String args[]){
String s1 = "7654729850328997631007285998163550104";
String s2 = "5980139243970186632651869926335829102";
add(s1, s2);
}
public static void add(String a, String b){
ArrayList<String> res = new ArrayList<String>();
StringBuilder myString = null;
int i = a.length() - 1;
int j = b.length() - 1;
while(true){
int i1 = Integer.parseInt(Character.toString(a.charAt(i)));
int i2 = Integer.parseInt(Character.toString(b.charAt(j)));
Integer i3 = i1 + i2 + carry;
if(i3 > 9){
carry = 1;
i3 = i3 - 10;
}else carry = 0;
res.add(i3.toString());
i--;j--;
if(i < 0){
res.add(carry.toString());
break;
}
}
Collections.reverse(res);
for(String r : res){
System.out.print(r);
}
}
}
</code></pre>
<p>This program adds 2 numbers whose length is greater than limit of Long. I think my logic is kind of bulky. Can something be done to improve this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T08:51:30.297",
"Id": "52702",
"Score": "2",
"body": "Use `BigInteger` instead."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T08:54:32.663",
"Id": "52703",
"Score": "0",
"body": "i forgot to remove 'myString' variable since i'm not using it"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T08:55:16.870",
"Id": "52704",
"Score": "0",
"body": "ok thanks for the link, i'll post this code there"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T18:05:08.053",
"Id": "52822",
"Score": "1",
"body": "Just use [BigInteger](http://docs.oracle.com/javase/6/docs/api/java/math/BigInteger.html). :)"
}
] |
[
{
"body": "<p>Loop structure's OK, logic's reasonably good. There is obviously a Java library alternative of <code>BigInteger</code>, but I assume you knew that. Some efficiency issues with excessive toString() and string-ification of what could be character operations.</p>\n\n<p>Here are some tips:</p>\n\n<ol>\n<li>Use <code>int</code> where nulls are not possible, not <code>Integer</code>.</li>\n<li><code>carry</code> is only used locally -- keep it local. Referencing it outside the method can only be erroneous, so it shouldn't be visibly exposed to make that possible..</li>\n<li>Carry calculation from <code>i3</code> is OK here, but could in related algorithms be brittle -- it can't handle a digit-sum > 19 as the maximum carry it can produce is 1.</li>\n<li>If addition completes with a carry of 0, it will output an unnecessary 0 digit.</li>\n<li>If Strings are your inputs, you should probably build a String as the result via a StringBuilder -- not an ArrayList.</li>\n<li><code>myString</code> should be called <code>result</code> or <code>sb</code>, if you're building the result in it.</li>\n<li>Build using StringBuilder in reverse order, and do it by character calculation <code>(char) (i3 + '0')</code> rather than toString() if you want to maximize efficiency.</li>\n<li>Return the result from your function, and do the printing in main() instead. there. That way you have a general-purpose <code>add()</code> function and a fixed-purpose main() method for testing.</li>\n</ol>\n\n<p>Is that complete enough?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T11:15:03.293",
"Id": "52699",
"Score": "0",
"body": "thanks for the suggestion, i got some important pointers :)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T09:18:47.297",
"Id": "32955",
"ParentId": "32954",
"Score": "7"
}
},
{
"body": "<p>This is only a partial refactoring, I have extracted some methods and fixed some problems. For example: if the two numbers have different lenghts, your program throws an exception:</p>\n\n<pre><code>Exception in thread \"main\" java.lang.StringIndexOutOfBoundsException: String index out of range: -1\nat java.lang.String.charAt(Unknown Source)\nat it.test.refactor.MyClass.add(MyClass.java:21)\nat it.test.refactor.MyClass.main(MyClass.java:11)\n</code></pre>\n\n<p>I'll do some more refactoring later :) </p>\n\n<pre><code>package it.test.refactor;\n\nimport java.util.regex.Pattern;\n\npublic class Main {\n\n private static final String DEFAULT1 = \"00033000010\";\n private static final String DEFAULT2 = \"1\";\n\n public static void main(String[] args) {\n if (args.length == 1 || args.length > 2) {\n System.err.println(\"Usage: MyClass integer1 integer2\\n \\n exemple: MyClass 123432 4321234\");\n return;\n }\n if (args.length == 0) {\n System.out.println(\"Warning: using default parameters: \" + DEFAULT1 + \" + \" + DEFAULT2);\n System.out.println(new TextualNumbers().add(DEFAULT1, DEFAULT2));\n } else {\n System.out.println(new TextualNumbers().add(args[0], args[1]));\n }\n }\n}\n\nclass TextualNumbers {\n\n private static Pattern onlyDigits = Pattern.compile(\"\\\\A[0-9]*\\\\z\");\n\n public String add(String firstAddend, String secondAddend) {\n validate(firstAddend);\n validate(secondAddend);\n PartialInputProcessor resultWithCarry = new PartialInputProcessor(0);\n int maxLen = Math.max(firstAddend.length(), secondAddend.length());\n StringBuilder res = new StringBuilder(maxLen + 1);\n for (int charIndex = 0; charIndex < maxLen; charIndex++) {\n int first = parseIntOrGet0(firstAddend, firstAddend.length() - charIndex - 1);\n int second = parseIntOrGet0(secondAddend, secondAddend.length() - charIndex - 1);\n resultWithCarry.processInputs(first, second);\n res.append(resultWithCarry.getPartialResult());\n }\n res.append(String.valueOf(resultWithCarry.getCarry()));\n String response = trimLeadingZeros(res.reverse().toString());\n return response;\n }\n\n private void validate(String addend) {\n if (addend == null) {\n throw new NullPointerException();\n }\n if (addend.length() == 0) {\n throw new IllegalArgumentException(\"[ \" + addend + \" ] is not a positive integer.\");\n }\n\n if (!(onlyDigits.matcher(addend).matches())) {\n throw new IllegalArgumentException(\"[ \" + addend + \" ] is not a positive integer.\");\n }\n }\n\n private int parseIntOrGet0(String intString, int charPosition) {\n if (intString.length() <= charPosition || charPosition < 0) {\n return 0;\n } else {\n return Character.digit(intString.charAt(charPosition), 10);\n }\n }\n\n private String trimLeadingZeros(String a) {\n while (a.startsWith(\"0\")) {\n a = a.substring(1);\n }\n return a;\n }\n\n}\n\n class PartialInputProcessor {\n\n private int carry;\n private String partialResult;\n\n public PartialInputProcessor(int initialCarry) {\n this.carry = 0;\n }\n\n public String getCarry() {\n return String.valueOf(carry);\n }\n\n public String getPartialResult() {\n return partialResult;\n }\n\n public void processInputs(int input1, int input2) {\n int partialSum = input1 + input2 + carry;\n carry = partialSum / 10;\n partialResult = String.valueOf(partialSum % 10);\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T06:01:25.353",
"Id": "52779",
"Score": "0",
"body": "Bugfixes aside, I don't think that this refactoring is better than the original. `sumChar()` uses so many parameters that it should have stayed part of `add()`. Division and modulo operations might be slower than conditional subtraction (needs benchmarking to check). `trimTrailingZeros()` actually trims leading zeros."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T06:02:06.463",
"Id": "52780",
"Score": "0",
"body": "In `parseIntOrGet0()`, why would `intString.length() <= charPosition` ever be true?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T06:04:56.503",
"Id": "52781",
"Score": "1",
"body": "Caution: `Character.digit()` is quite different from `Integer.parseInt()`. The former returns -1 if the character is not a digit, which leads to laughable bugs. The latter throws `NumberFormatException`, which is the preferred behavior."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T08:19:54.127",
"Id": "52787",
"Score": "0",
"body": "Ok, I'll add validation of input parameters; sorry for the wrong method name... Maybe I should code in Italian :D"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T10:46:12.260",
"Id": "32957",
"ParentId": "32954",
"Score": "4"
}
},
{
"body": "<p>Loop structure's OK, logic's reasonably good. There is obviously a Java library alternative of <code>BigInteger</code>, but I assume you knew that. Some efficiency issues with excessive toString() and string-ification of what could be character operations.</p>\n\n<p>Here are some tips:</p>\n\n<ol>\n<li>Use <code>int</code> where nulls are not possible, not <code>Integer</code>.</li>\n<li><code>carry</code> is only used locally -- keep it local. Referencing it outside the method can only be erroneous, so it shouldn't be visibly exposed to make that possible..</li>\n<li>Carry calculation from <code>i3</code> is OK here, but could in related algorithms be brittle -- it can't handle a digit-sum > 19 as the maximum carry it can produce is 1.</li>\n<li>If addition completes with a carry of 0, it will output an unnecessary 0 digit.</li>\n<li>If Strings are your inputs, you should probably build a String as the result via a StringBuilder -- not an ArrayList.</li>\n<li><code>myString</code> should be called <code>result</code> or <code>sb</code>, if you're building the result in it.</li>\n<li>Build using StringBuilder in reverse order, and do it by character calculation <code>(char) (i3 + '0')</code> rather than toString() if you want to maximize efficiency.</li>\n<li>Return the result from your function, and do the printing in main() instead. there. That way you have a general-purpose <code>add()</code> function and a fixed-purpose main() method for testing.</li>\n</ol>\n\n<p>Is that complete enough?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T09:09:37.970",
"Id": "32960",
"ParentId": "32954",
"Score": "0"
}
},
{
"body": "<p>Your code breaks if the input strings are of different lengths.</p>\n\n<p>It is important to note that you don't support negative or non-integer inputs.</p>\n\n<p>I would expect the <code>add()</code> function to return the result as a String: <code>public static String add(String a, String b)</code>. (You probably intended to do that, since you declared <code>myString</code> but never used it.)</p>\n\n<p>Instead of accumulating the result in an <code>ArrayList<String></code>, I would just use the <code>StringBuilder</code>. (<code>StringBuilder</code> is essentially an <code>ArrayList</code> of <code>char</code>. It even has a <code>.reverse()</code> method.)</p>\n\n<p>The <code>carry</code> variable should be local to the <code>add()</code> function; there is no reason why it should be stored in the state of the class. It's confusing, and it makes your code non-thread-safe. (Also, <code>int</code> should be preferred over <code>Integer</code> whenever possible.)</p>\n\n<p><code>MyClass</code> is a pointless name. <code>BigInteger</code> would be a good name, but it would be a bad idea to use the same name as a class in the standard Java library, even if they are in different packages. Name it something similar to <code>BigInteger</code>.</p>\n\n<p>Your variable names could be improved with parallelism. It's hard to remember that <code>i1</code> and <code>i</code> correspond to <code>a</code>, and <code>i2</code> and <code>j</code> correspond to <code>b</code>. Naming the variables <code>digit1</code>, <code>i1</code>, <code>addend1</code> and <code>digit2</code>, <code>i2</code>, <code>addend2</code> would be better.</p>\n\n<p>A <code>while (true) { … }</code> loop with a <code>break</code> inside suggests that the code structure could be improved. I think that a for-loop provides a better structure.</p>\n\n<pre><code>/**\n * Adds two non-negative integers represented as string of digits.\n *\n * @exception NumberFormatException if either argument contains anything other\n * than base-10 digits.\n */\npublic static String add(String addend1, String addend2) {\n StringBuilder buf = new StringBuilder();\n for ( int i1 = addend1.length() - 1, i2 = addend2.length() - 1, carry = 0;\n i1 >= 0 || i2 >= 0 || carry != 0;\n i1--, i2-- ) {\n int digit1 = i1 < 0 ? 0 :\n Integer.parseInt(Character.toString(addend1.charAt(i1)));\n int digit2 = i2 < 0 ? 0 :\n Integer.parseInt(Character.toString(addend2.charAt(i2)));\n\n int digit = digit1 + digit2 + carry;\n if (digit > 9) {\n carry = 1;\n digit -= 10;\n } else {\n carry = 0;\n }\n\n buf.append(digit);\n }\n return buf.reverse().toString();\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T01:26:10.233",
"Id": "52767",
"Score": "0",
"body": "thanks, BTW in the next version of this code(i.e., adding numbers with lengths greater than range of long), instead of 2 numbers i want to add multiple numbers, can u give me some tips/hints how to do that"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T01:28:14.213",
"Id": "52768",
"Score": "3",
"body": "Just call add() multiple times."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T13:41:18.450",
"Id": "53048",
"Score": "0",
"body": "If you really wanted to make an API that supported a single `add()` call, you could use a varargs argument."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T22:58:39.013",
"Id": "32983",
"ParentId": "32954",
"Score": "4"
}
},
{
"body": "<p>This is my version with basic java API's</p>\n\n<pre><code>package geeks.in.action.algo.numtoword;\n\npublic class AddTwoBigNumbers {\n\npublic static void main(String[] args) {\n try {\n System.out.println(\"Addition:\" + addIntegers(\"9999\", \"9999\"));\n System.out.println(\"Addition:\" + addIntegers(\"1233434323432454521\", \"99872343237868642\"));\n System.out.println(\"Addition:\" + addIntegers(\"1233434323432454521\", \"37868642\"));\n System.out.println(\"Addition:\" + addIntegers(\"37868642\", \"1233434323432454521\"));\n } catch (final Exception e) {\n System.out.println(\"Exception : \" + e.getMessage());\n }\n}\n\nprivate static String addIntegers(String number1, String number2) throws Exception {\n validate(number1, number2);\n System.out.println(\"Adding: \" + number1 + \"+\" + number2);\n char[] num1char = number1.toCharArray();\n char[] num2char = number2.toCharArray();\n if (num1char.length > num2char.length) {\n num2char = formatToSameLength(num1char, num2char);\n } else if (num1char.length < num2char.length) {\n num1char = formatToSameLength(num2char, num1char);\n }\n final char[] addition = new char[num1char.length + 1];\n char carrry = '0';\n for (int i = num1char.length - 1; i >= 0; i--) {\n final int sum = Character.getNumericValue(num1char[i]) + Character.getNumericValue(num2char[i]) + Character.getNumericValue(carrry);\n final char[] csum = String.valueOf(sum).toCharArray();\n carrry = '0';\n if (csum.length > 1 && i == 0) {\n addition[i + 1] = csum[1];\n addition[0] = csum[0];\n } else if (csum.length > 1) {\n carrry = csum[0];\n addition[i + 1] = csum[1];\n } else {\n addition[i + 1] = csum[0];\n }\n }\n return String.valueOf(addition);\n}\n\nprivate static void validate(String number1, String number2) throws Exception {\n if (number1.trim().isEmpty() || number2.trim().isEmpty() || !isNumber(number1) || !isNumber(number2)) {\n throw new Exception(\"Number is not present or not a valid number\");\n }\n}\n\nprivate static boolean isNumber(String number) {\n try {\n Integer.parseInt(number);\n return true;\n } catch (final NumberFormatException nfe) {\n }\n return false;\n}\n\nprivate static char[] formatToSameLength(char[] num1char, char[] num2char) {\n final int diff = num1char.length - num2char.length;\n final char[] num = new char[num1char.length];\n for (int i = 0; i < diff; i++) {\n num[i] = '0';\n }\n for (int i = 0; i < num2char.length; i++) {\n num[diff + i] = num2char[i];\n }\n return num;\n}\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-24T12:56:27.987",
"Id": "89182",
"Score": "0",
"body": "Welcome to Code Review! Answering with your own version is correct, but what we like here is the why. Why your solution is better?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-24T12:56:42.867",
"Id": "89183",
"Score": "1",
"body": "This code looks neat, and accurate.... but ... Code Review answers should do more than just 'dump' an alternative solution to a problem. Answers should at least explain why the alternative is better, and what problems the alternative solves that the original code does not. We have [a meta post that covers this](http://meta.codereview.stackexchange.com/questions/1463/short-answers-and-code-only-answers)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-24T12:28:15.517",
"Id": "51612",
"ParentId": "32954",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T08:57:29.193",
"Id": "32954",
"Score": "7",
"Tags": [
"java",
"integer"
],
"Title": "Adding two big integers represented as strings"
}
|
32954
|
<p>I have written code, but I don't like it, it seems very ungeneralized. I want to make it more abstract and universal and independent of type.</p>
<p>I have the task to write programm, which can operate with multi level list. List should be done on array of void pointers. Data structure should be roughly like on the picture: <img src="https://i.stack.imgur.com/sxOmd.png" alt="enter image description here"></p>
<p>I have made this on classes. I have separate class <code>pointerArray</code>, which operates with array of void pointers. But I didn't hit upon the idea how to make generalized class (which doesn't depend of structure type), namely how to do delete function which doesn't depend on structure type. So I have made it template class.</p>
<p>But the main thing, which I don't like is: if I need to add element to the lowest level of list I should step by step cast types to reach lowest level. </p>
<p>For this program maybe it isn't so important, but I have to make same list for more than 5 levels. </p>
<p>So, please, look through, comment and suggest what to change or how to realise this task in another way. Here this sources on <a href="https://github.com/CROSP/VoidArrayList" rel="nofollow noreferrer">github</a>
<strong>WITHOUT USING STANDARD CLASSES</strong> (like <code><vector></code> and so on)
Here is some part of code
pointerArray.h</p>
<pre><code> #ifndef POINTERARRAY_H
#define POINTERARRAY_H
#define DEF_SIZE (10)
#define DELTA (4)
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>
using namespace std;
typedef
int (*TCmpFunc)(void*, string);
template <class T>
class pointerArray {
public:
pointerArray(int initialSize = DEF_SIZE){
this->start = new void* [initialSize]; /* запрашиваем память для нового массива*/
this->initArr(initialSize);
}
void showList();
bool delFromList(int posDel);
int findElList(string key, TCmpFunc cmpF,bool &findOK);
void addToSort(void* pnew, int posAdd);
void replaceSort(int delPos, void* newEl, int inPos);
void clearAll();
bool delAllList(bool delPointers);
void expandDef(int sizeOld, int incSize);
void** getStart() {
return this->start;
};
int getSize() {
return this->size;
};
int getCount() {
return this->count;
}
void* getElem(int posEl) {
return this->start[posEl];
}
~pointerArray() {
this->delAllList(true);
};
protected:
int size;
int count;
void** start;
void initArr(int initSize);
};
template<class T> void pointerArray<T>::initArr(int initSize) {
this->count = 0;
this->size = initSize;
template<class T> void pointerArray<T>::expandDef(int sizeOld, int incSize = DELTA) {
int sizeNew = sizeOld + incSize;
void** arOld = this->start;
this->start = new void* [sizeNew];
for (int i = sizeOld-1; i >= 0; i--) {
this->start[i] = arOld[i];
}
this->size = sizeNew;
delete []arOld;
}
template<class T> int pointerArray<T>::findElList(string key,TCmpFunc cmpF,bool &findOK) {
int posFndEl;
int middl;
int hi, low;
if (this->count == 0) {
posFndEl = 0;
return posFndEl;
}
low = 0;
hi = this->count - 1;
do {
middl = (hi + low) / 2 ;
int resultCompare= cmpF(this->start[middl], key);
if (resultCompare== 0)
{ posFndEl = middl;
findOK = true;
return posFndEl;
}
if (resultCompare == 1)
{
hi = middl - 1;
}
else
{
low = middl + 1;
}
} while (low <= hi);
findOK = false;
posFndEl = low;
return posFndEl;
}
template<class T> void pointerArray<T>::replaceSort(int delPos, void* newEl,int inPos) {
this->delFromList(delPos);
this->addToSort(newEl,inPos);
}
template<class T> void pointerArray<T>::clearAll() {
this->delFromList(0);
}
template<class T> bool pointerArray<T>::delFromList(int posDel) {
int cnt = this->count;
if ((posDel < 0) || (posDel>cnt)) {
return false;
}
delete (T*)(this->start[posDel]);
for (int k = posDel; k < cnt - 1; k++) {
this->start[k] = this->start[k + 1];
}
cnt--;
this->count = cnt;
}
template<class T> bool pointerArray<T>::delAllList(bool delPointers) {
int cnt = this->count;
if ((cnt==0) && (!delPointers)) {
return false;
}
for (int i=0;i<cnt-1;i++) {
delete (T*)(this->start[i]);
}
if (delPointers) {
delete []this->start;
this->start = NULL;
this->size = 0;
}
this->count = 0;
return true;
}
template<class T> void pointerArray<T>::addToSort(void* pnew, int posAdd) {
int cnt = this->count;
int sz = this->size;
if (cnt == sz) {
this->expandDef(this->size);
}
if (posAdd == cnt)
{
this->start[posAdd] = pnew;
} else { // сдвиг элементов в массиве указателей на 1 вправо
for (int k = cnt - 1; k >= posAdd; k--) {
this->start[k + 1] = this->start[k];
}
this->start[posAdd] = pnew;
}
cnt++;
this->count = cnt;
}
#endif // POINTERARRAY_H
</code></pre>
<p>And mainUniv</p>
<pre><code>/*
* File: mainUniv.cpp
* Author: CROSP
*
* Created on October 16, 2013, 8:50 PM
*/
#include "mainUniv.h"
mainUniv::mainUniv() {
this->univPoint = 0;
}
bool mainUniv::addUniv(void* pNew, string name) {
bool success;
this->univPoint->addToSort(pNew,this->univPoint->findElList(name, cmpUniv, success));
}
void* mainUniv::getUniv(string name, bool &findOk) {
int posUniv = (this->univPoint->findElList(name, cmpUniv, findOk));
if (findOk) {
return (this->univPoint->getElem(posUniv));
}
else return 0;
}
void* mainUniv::getFaculty(void* unPoint, string facName,bool &findOk) {
TUniver * tmpUn = (TUniver*)unPoint;
if (tmpUn->subInit) {
int fndPos = tmpUn->sublev->findElList(facName, cmpFact,findOk);
if (findOk) {
return tmpUn->sublev->getElem(fndPos);
}
else {
return 0;
}
}
}
void* mainUniv::getChair(void* unFac, string facName,bool &findOk) {
TFaculty *tmpFac = (TFaculty*)unFac;
if (tmpFac->subInit) {
int fndPos = tmpFac->sublev->findElList(facName, cmpFact,findOk);
if (findOk) {
return tmpFac->sublev->getElem(fndPos);
}
else {
return 0;
}
}
}
bool mainUniv::addFaculty(void* pNew, void *univP, string facName) {
TUniver *tmpUniv = (TUniver*)(univP);
bool findFac = false;
if (!(tmpUniv->subInit)) {
this->initFac(tmpUniv);
}
tmpUniv->sublev->addToSort(pNew, tmpUniv->sublev->findElList(facName, cmpFact, findFac));
return true;
}
bool mainUniv::initFac(void* tmpUn) {
TUniver* tnp =(TUniver*)tmpUn;
tnp->sublev= new pointerArray<TFaculty>();
tnp->subInit = true;
return true;
}
pointerArray<TUniver>* mainUniv::getUnivStart() {
return this->univPoint;
}
bool mainUniv::initChair(void* fac) {
TFaculty* tmpFac = (TFaculty*)(fac);
tmpFac->sublev = new pointerArray<TChair>();
tmpFac->subInit = true;
return true;
}
bool mainUniv::addChair(void* fac,void *pnew,string name) {
TFaculty *tmpFac = (TFaculty*)fac;
bool findOk;
if (!(tmpFac->subInit)) {
this->initChair(tmpFac);
}
tmpFac->sublev->addToSort(pnew,tmpFac->sublev->findElList(name,cmpChr,findOk));
}
void ** mainUniv::createUnivArr(int inSize) {
this->univPoint = new pointerArray<TUniver>(inSize);
return this->univPoint->getStart();
}
void mainUniv::delChair(void *pFac,int delPos) {
TFaculty *tmpF = (TFaculty*)pFac;
tmpF->sublev->delFromList(delPos);
}
bool mainUniv::delFaculty(void *pUniv,string delFac)
{
TUniver* tmpUn = (TUniver*)pUniv;
if (!tmpUn->subInit) {
return false ;
}
bool find;
TFaculty *tmpFac =(TFaculty*)this->getFaculty(pUniv,delFac,find);
if (!find) {
return false;
}
if (tmpFac->subInit) {
this->delAllChairs(tmpFac,true);
}
tmpUn->sublev->delFromList(tmpUn->sublev->findElList(delFac,cmpFact,find));
return true;
}
bool mainUniv::delAllFaculties(void *pUniv,bool delPointers) {
TUniver *tmpUn = (TUniver*)pUniv;
if (tmpUn->subInit) {
int cnt = tmpUn->sublev->getCount();
TFaculty* tmFac;
for (int i=0;i<cnt;i++) {
tmFac =(TFaculty*)(tmpUn->sublev->getElem(i));
if (tmFac->subInit) {
this->delAllChairs(tmFac,true);
}
}
tmpUn->sublev->delAllList(delPointers);
if (delPointers) {
delete tmpUn->sublev;
tmpUn->subInit = false;
}
} else
{return false;}
}
bool mainUniv::delAllChairs(void *pFac,bool delPointers) {
TFaculty *tmpF = (TFaculty*)pFac;
tmpF->sublev->delAllList(delPointers);
if (delPointers) {
delete tmpF->sublev;
tmpF->subInit = false;
}
}
bool mainUniv::delAllUniver(bool delPointers) {
if (!this->univPoint) {
return false;
}
int unCnt = this->univPoint->getCount();
for (int i=0;i<unCnt;i++) {
this->delAllFaculties(this->univPoint->getElem(i),true);
}
this->univPoint->delAllList(delPointers);
if (delPointers){
delete this->univPoint;
}
}
bool mainUniv::delUniv(string name) {
if (!this->univPoint) {
return false;
}
bool fndOk;
int delPos = this->univPoint->findElList(name,cmpUniv,fndOk);
if (fndOk) {
this->delUniv(delPos);
return true;
} else return false;
}
bool mainUniv::delUniv(int delPos) {
TUniver *unDel = (TUniver*)this->univPoint->getElem(delPos);
if(unDel->subInit) {
this->delAllFaculties(unDel,true);
}
this->univPoint->delFromList(delPos);
return true;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T15:54:49.000",
"Id": "52722",
"Score": "1",
"body": "Linking to GitHub is helpful, but by the rules of this site, you must include code to be reviewed in the question itself, or at least the most important parts of the code. Also, if you link to GitHub, you should point to a specific commit, otherwise the reviews here won't make sense after you revise the code there."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T17:04:15.523",
"Id": "52725",
"Score": "0",
"body": "I have only one commit in this represitory , here is link https://github.com/CROSP/VoidArrayList/commit/46ee3995f37ac655da588d6ef9608d22e9e0bd66"
}
] |
[
{
"body": "<p>This looks a lot like <em>c with classes</em> rather than <em>c++</em>. </p>\n\n<ol>\n<li>If you are using void pointers in C++, you are probably doing something wrong. You <code>pointerArray</code> class is templated, but you don't use the templates at all. </li>\n<li>A class name should begin with a capital letter.</li>\n<li>Use a function object (functor) instead of a function pointer. </li>\n<li>You don't have a destructor for <code>pointerArray</code>. If an exception is thrown, you'll probably have a memory leak.</li>\n</ol>\n\n<p>Here's a basic idea of what you may want to do instead:</p>\n\n<pre><code>#define DEF_SIZE 10\n#define DELTA 4\n\ntemplate <typename T>\nstruct SampleCompareFunctor\n{\n bool operator () (const T &lhs, const T &rhs) const {\n return lhs < rhs ;\n }\n};\n\ntemplate <typename T>\nclass Array\n{\npublic:\n Array (const size_t initial_size = DEF_SIZE) ;\n ~Array () ;\n\n void insertValue (const size_t index, const T &val) ;\n T removeValue (const size_t index) ;\n\n // Getters, so you could do Array a ; a [0] ....\n T& operator [] (const size_t index) ;\n const T& operator [] (const size_t index) const ;\n\n template <typename CompareFunctor>\n void sort () ;\n\n//...\n\nprivate:\n T *m_data ;\n};\n\ntemplate <typename T>\nArray <T>::Array (const size_t initial_size) : m_data (new T [initial_size])\n{\n}\n\ntemplate <typename T>\nArray <T>::~Array ()\n{\n delete [] m_data ;\n m_data = nullptr ; // Or NULL if you don't have c++11\n}\n\ntemplate <typename T>\nT& Array <T>::operator [] (const size_t index)\n{\n return m_data [index] ;\n}\n\ntemplate <typename T>\nconst T& Array <T>::operator [] (const size_t index) const\n{\n return m_data [index] ;\n}\n\ntemplate <typename T>\ntemplate <typename CompareFunctor>\nvoid Array <T>::sort ()\n{\n // Implement your sorting function here.\n}\n</code></pre>\n\n<p>This is just a partial review. I haven't looked at the rest yet.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T18:42:20.360",
"Id": "36069",
"ParentId": "32958",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T11:47:37.937",
"Id": "32958",
"Score": "3",
"Tags": [
"c++",
"algorithm"
],
"Title": "Multi level list based on array of void pointers"
}
|
32958
|
<p>Per a <a href="http://www.reddit.com/r/dailyprogrammer/comments/1m1jam/081313_challenge_137_easy_string_transposition/" rel="nofollow">Reddit Daily Programming Challenge</a>, I am performing a matrix transposition on a string using JavaScript.</p>
<p>Example input: 'The quick brown fox jumped over the lazy dog'</p>
<p>Output:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Tqbfjotld
hurouvhao
eioxmeezg
cw pr y
kn e
d
</code></pre>
</blockquote>
<p>While my code works, I wanted to know:</p>
<ol>
<li>From a readability standpoint, would it be better to break the code up into smaller functions?</li>
<li>If there's anything in the code that can be simplified.</li>
</ol>
<pre class="lang-js prettyprint-override"><code>transposeString('The quick brown fox jumped over the lazy dog');
function transposeString(str) {
if (str.indexOf(' ') === -1) {
var map = Array.prototype.map;
var output = map.call(str, function (char) {
return char + '\n';
});
return output.join('');
} else {
var master = [],
longestWord = '';
words = str.split(' ');
words.forEach(function(word) {
if (word.length >= longestWord.length) longestWord = word;
});
longestWord.split('').forEach(function() {
master.push([]);
});
var treatedWords = words.map(function (word) {
if (word.length < longestWord.length) {
var spaces = Array(longestWord.length - word.length + 1).join(' ');
return word = word + spaces;
} else {
return word;
}
});
treatedWords.forEach(function (word) {
var n = 0;
word.split('').forEach(function (char) {
master[n].push(char);
n++;
});
});
master.forEach(function (arr) {
console.log(arr.join(''));
});
return;
}
}
</code></pre>
|
[] |
[
{
"body": "<p><a href=\"http://jsbin.com/ihUnUFU/1/edit?js,console\" rel=\"nofollow\">Here you go, with comments.</a></p>\n\n<p>Obviously, in production I would have only a handful of comments and not the exhaustive ones I put here. However this is the sort of points I might make during a code review.</p>\n\n<p>When I write code I optimize for it for communicating to a human reader what I intend the code to do. In other words - I want it to read like an essay. Therefore, I extract anything detail-heavy into small helper methods at the bottom of the script. The idea is that someone should open my script and the first thing they see should give them a top-level overview of the general flow of logic.</p>\n\n<p>I didn't comment at all on your solution itself, instead just cleaning up the algorithms that were already there.</p>\n\n<pre><code>transposeString('The quick brown fox jumped over the lazy dog');\n\n//Always comment public apis with usage and your intent when writing it.\n\n//Transpose a string of words into a vertical matrix\n//from http://www.reddit.com/r/dailyprogrammer/comments/1m1jam/081313_challenge_137_easy_string_transposition/\nfunction transposeString(str) {\n // the ~ (ones complement) operator makes indexOf work like 'contains'\n // ~(-1) == 0, ~(x != -1) != 0\n // not sure why you need this condition at all however in terms of the problem - seems like everything\n //would just work\n if (!~str.indexOf(' ')) \n //definitely don't have two large branches of conditional logic in the same function, put them \n //in separate well-named functions\n //Also always prefer to return early to get the simple paths out of the way in conditional logic. \n //The whole \"single point of exit\" advice is from back in the day of monolithic functions and gotos all over the place\n return makeVerticalString(str);\n\n //My preference is to use a single var block with everything aligned and commas preceeding\n //the terms. I have good reasons for this but not anything that I care to get into without\n //being super-pedantic. It's ok to have a different style here.\n var words = str.split(' ') //you were misssing var here\n ,longestWord = getLongestWord(words) //give algorithms their own function\n\n //word matrix - I recommend commenting this so that you know it's a matrix and not a flat array\n //also note that it is much cleaner to use a map than a forEach and explicit push\n //When you see array.push() anywhere it can almost always be cleaned up with a map\n ,transposedMatrix = longestWord.split('').map(function() { return [] }) \n\n //give a name to the thing that you're doing here and extract the algorithm to its own function\n //also rename 'treated' to 'padded' to be more explicit\n ,paddedWords = words.map(padWordsShorterThan(longestWord.length));\n ;\n //again, move the actual algorithm to its own labeled function\n paddedWords.forEach(addEachLetterToARow(transposedMatrix));\n\n transposedMatrix.forEach(function (arr) {\n console.log(arr.join(''));\n });\n //no need for return if you're not returning anything\n\n //A line to deliniate private helper functions\n //////////////////////////////////////////////////////////////////////////////////////////////\n function makeVerticalString(str) {\n //You're reducing an array to a single value so really reduce is what you want here\n Array.prototype.reduce.call(str, function(m, c) { return m+c+'\\n'}, '')\n }\n\n function getLongestWord(words) {\n //again going from an array to a single value - we can use reduce here\n return words.reduce(function(longest, thisWord){ return thisWord.length >= longest.length ? thisWord : longest}, '');\n }\n\n //a function that returns a function can be a good tool for controlling scope while keeping things readable\n //note that the inner function still has a name so that it shows up properly in callstack traces (rather than \"anonymous\")\n function padWordsShorterThan(threshold) { return function padWordsShorterThan(word) { \n if (word.length >= threshold)\n return word; \n //no need for else clauses when you return early\n return word + repeatStr(\" \", longestWord.length - word.length + 1);\n }}\n function repeatStr(str, times) {\n //you have a neat little way of implementing a character repeat but its difficult to read - drop it in its own method\n return Array(times).join(str)\n }\n\n\n //Naming anonymous functions not only helps make clear what they're doing\n //but makes them show up named in a debugging callstack rather than \"anonymous\"\n //Rule of thumb - name anonymous functions that are doing significant logic\n function addEachLetterToARow(matrix) { return function addEachLetterToARow(word) {\n var n = 0;\n word.split('').forEach(function addToRow(char) {\n matrix[n].push(char); //note that you have a possible error condition here where matrix[n] does not exist. Do you want to check for that explicitly?\n n+=1; //I agree with Doug Crockford that ++ is wierd and error-prone. += reads much better in my opinion\n });\n } }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T15:43:00.337",
"Id": "32970",
"ParentId": "32963",
"Score": "2"
}
},
{
"body": "<p>I would consider it bad form for your function to <code>console.log()</code> its output instead of returning a value, because it severely harms code reusability.</p>\n\n<p>I don't think that the one-word case deserves special treatment, since it's just a trivial optimization of the general case. Even the empty string doesn't need special handling. A <code>null</code> might deserve a special case, if you decide to handle it.</p>\n\n<p>You omitted the <code>var</code> keyword when defining <code>words</code>.</p>\n\n<p>Instead of appending empty arrays to <code>master</code> using <code>.forEach()</code>, you could define it all at once using <code>.map()</code>:</p>\n\n<pre><code>var master = longestWord.split('').map(function() { return []; });\n</code></pre>\n\n<p>The name <code>treatedWords</code> is insufficiently self-documenting. I suggest <code>paddedWords</code>.</p>\n\n<pre><code>function transposeString(str) {\n if (str == null) return null;\n\n var words = str.split(' ');\n\n var longestWord = '';\n words.forEach(function(word) {\n if (word.length >= longestWord.length) longestWord = word;\n });\n\n var master = longestWord.split('').map(function() { return []; });\n\n var paddedWords = words.map(function (word) {\n if (word.length < longestWord.length) {\n var spaces = Array(longestWord.length - word.length + 1).join(' ');\n return word = word + spaces;\n } else {\n return word;\n }\n });\n\n paddedWords.forEach(function (word) {\n var n = 0;\n word.split('').forEach(function (char) {\n master[n].push(char);\n n++;\n });\n });\n\n return master.map(function (line) {\n return line.join('');\n }).join(\"\\n\");\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T17:50:14.817",
"Id": "32974",
"ParentId": "32963",
"Score": "2"
}
},
{
"body": "<p>Since you asked if the code could be simplified or made more readable, let's explore other programming styles.</p>\n\n<p>(Note: Remarks in my <a href=\"https://codereview.stackexchange.com/a/32974/9357\">first review</a> about handling special cases and the returning a value still apply.)</p>\n\n<hr>\n\n<p>First, I would like to point out that a \"bland\" solution, building the output one character at a time, would actually be slightly shorter than your original:</p>\n\n<pre><code>function transposeString(str) {\n if (str == null) return str;\n\n var words = str.split(' ');\n var out = [];\n for (var c = 0; ; c++) {\n var line = [];\n var done = true;\n for (var w = 0; w < words.length; w++) {\n if (c < words[w].length) {\n done = false;\n line.push(words[w].charAt(c));\n } else {\n line.push(' ');\n }\n }\n if (done) {\n break;\n } else {\n out.push(line.join(''));\n }\n }\n return out.join(\"\\n\");\n}\n</code></pre>\n\n<hr>\n\n<p>Your solution feels a little like functional programming, though not quite. What if you go all the way with functional programming? Your solution was already quite close; you just need to replace <code>.forEach()</code> with <code>.map()</code>. Here's how it could look:</p>\n\n<pre><code>function transposeString(str) {\n if (str == null) return str;\n\n // Wrapper for String.length\n function length(word) { return word.length; };\n\n // range(3) -> [0, 1, 2]\n // http://stackoverflow.com/a/11128802/1157100\n function range(n) {\n return Array(n).join().split(',').map(function(e, i) { return i; });\n };\n\n var words = str.split(' ');\n var maxWordLength = Math.max.apply(null, words.map(length));\n\n // These functions could be anonymous; I've named them for clarity\n return range(maxWordLength).map(function outputLineUsingNthChar(n) {\n return words.map(function nthCharWithSpacePadding(word) {\n return return n < word.length ? word.charAt(n) : ' ';\n }).join('');\n }).join(\"\\n\");\n}\n</code></pre>\n\n<p>That is already shorter, even though JavaScript makes <code>max(words.length)</code> and <code>range()</code> awkward. If you use a library like <a href=\"http://underscorejs.org/\" rel=\"nofollow noreferrer\">Underscore.js</a> to provide support for <a href=\"http://underscorejs.org/#max\" rel=\"nofollow noreferrer\"><code>max()</code></a> and <a href=\"http://underscorejs.org/#range\" rel=\"nofollow noreferrer\"><code>range()</code></a>, it could be very compact. I'd take advantage of that compactness as an opportunity to comment generously.</p>\n\n<pre><code>function transposeString(str) {\n if (str == null) return str;\n\n var words = str.split(' ');\n var maxWordLength = _.max(_.pluck(words, 'length'));\n return _.range(maxWordLength).map(\n // Generate a line of output using the nth character of each word\n function outputLineUsingNthChar(n) {\n return words.map(\n // Extract the nth character of a word, space-padded if needed\n function nthCharWithSpacePadding(word) {\n return n < word.length ? word.charAt(n) : ' ';\n }\n ).join('');\n }\n ).join(\"\\n\");\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T19:06:37.887",
"Id": "32976",
"ParentId": "32963",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "32976",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T12:37:20.940",
"Id": "32963",
"Score": "1",
"Tags": [
"javascript",
"strings",
"matrix"
],
"Title": "Matrix transposition of a string"
}
|
32963
|
<p>I need array to store elements, but I don't want to make memory allocations at runtime. So I reuse elements. Some fields are never changes so as I reuse elements I need to assign those fields just once.</p>
<p>This is what I wrote, only sceleton, need to add "errors test" etc, but enough to demonstrate the idea:</p>
<pre><code>public sealed class ResizeableArray<T> where T : class, new()
{
// made public to use in "foreach", but better to be private
public T[] array;
public int Count { get; private set; }
public ResizeableArray(uint maxLength = 128)
{
if (maxLength <= 0) throw new ArgumentOutOfRangeException("maxLength");
array = new T[maxLength];
for (int i = 0; i < maxLength; i++)
{
array[i] = new T();
}
Count = 0;
}
public T this[int key]
{
get { return array[key]; }
}
public void Clear()
{
Count = 0;
}
public T Add()
{
return array[Count++];
}
public void RemoveRange(int index, int count)
{
var newSize = Count - count;
for (int i = index; i < newSize; i++)
{
array[i] = array[i + count];
}
Count = newSize;
}
public void RemoveAt(int index)
{
throw new NotImplementedException();
}
}
</code></pre>
<p>Usage is simple, for example</p>
<pre><code>var element = array.Add();
// configure, assign only "mutable" fields
element.field1 = value1;
element.field2 = value2;
</code></pre>
<p>What do you think? Is it good class or you can suggest something better?</p>
<p><strong>upd</strong> posting final version I use in production. I think this class can be usefull if you constantly need to reconfigure some array. It's probably will be faster no to allocate new object over and over (but need to measure). Also it's probably less error prone to have always the same instance of the object.</p>
<pre><code>public sealed class ResizeableArray<T> where T : class, new()
{
private T[] array;
public int Count { get; private set; }
public ResizeableArray(uint maxLength = 128)
{
if (maxLength <= 0) throw new ArgumentOutOfRangeException("maxLength");
array = new T[maxLength];
for (int i = 0; i < maxLength; i++)
{
array[i] = new T();
}
MaxLength = maxLength;
Count = 0;
}
public uint MaxLength { get; private set; }
public T this[int key]
{
get { return array[key]; }
}
public void Clear()
{
Count = 0;
}
public T Add()
{
return array[Count++];
}
// sloooow. don't use it
public T InsertAt0()
{
var zeroOrder = array[Count];
for (int i = Count; i > 0; i--)
{
array[i] = array[i - 1];
}
array[0] = zeroOrder;
return zeroOrder;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T13:38:16.317",
"Id": "52709",
"Score": "0",
"body": "Are you sure you really can't afford those allocations? Allocations are extremely cheap in .Net and deallocations can be fairly efficient too."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T13:41:45.223",
"Id": "52710",
"Score": "0",
"body": "Also, could you explain how exactly are you going to use it? Why the support for `foreach`? What's the intended usage of `RemoveRange()`? Why is there `Clear()`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T13:45:11.263",
"Id": "52712",
"Score": "0",
"body": "array contains \"desired orders for trading system\" normally it clears, adds and wait for execution system to process. then again clears adds and process. `Remove*` functions are likely to be removed in future, most common scenario is \"Clear-Add\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T16:34:33.330",
"Id": "52723",
"Score": "0",
"body": "For the record `foreach` works on anything with a `GetEnumerator()` method (meaning that the msdn documentation on this is actually misleading). Here's proof: https://compilify.net/3dy"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T16:37:05.577",
"Id": "52724",
"Score": "1",
"body": "Also, it sounds like what you want is a `List<>` which already exists and is very cheap. Also, you should implement `IEnumerable<T>`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T05:00:44.777",
"Id": "52778",
"Score": "0",
"body": "@GeorgeMauer List doesn't allow to change size and keep elements at the same time. If I delete element from the end of the list it can not be reused later, it just lost."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T13:20:37.753",
"Id": "52851",
"Score": "0",
"body": "Array got a storage limit which you defined, So in the Add function what happens if you call that & count value is same as array's last accessible index?."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T13:43:22.283",
"Id": "52852",
"Score": "0",
"body": "i don't call that way. my question is about idea in general not about \"border tests\" (which I will add later)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T13:45:50.107",
"Id": "52853",
"Score": "0",
"body": "OK, Just curious."
}
] |
[
{
"body": "<blockquote>\n <p>my question is about idea in general</p>\n</blockquote>\n\n<p>It's flawed, in several ways. </p>\n\n<p><strong>Premature Optimization</strong></p>\n\n<p>The code smell I get is that the whole point is avoiding instantiating and then disposing <code>Array</code> elements. Reasons we stay away from optimizing up front</p>\n\n<ul>\n<li>We end up spending too much time on it </li>\n<li>Corrupting our business design for the sake of something that we don't even know is an issue. </li>\n<li>We don't know yet where and how much actual performance is affected. </li>\n<li>We cannot know if our up front optimization is in fact better than what we would have done; it could be worse!</li>\n</ul>\n\n<p><strong>Resizing?</strong></p>\n\n<p>I thought this is what we're trying to avoid. </p>\n\n<p>Where is the \"resizing\"? I assume it will be in <code>Add()</code> and <code>Remove()</code>. If there is no resizing - the size is fixed at instantiation, then the class name is wrong.</p>\n\n<p>The conventional wisdom says resizing <code>Array</code> is less performant than resizing a <code>List</code>. In fact the <code>C#/.NET</code> team went to great lengths to make sure <code>List</code> automatic resizing performs well. Do you have the time and other resources to make your home-spun <code>Array</code> resizing worth not using what the .NET framework already gives you?</p>\n\n<p><strong>Wrong Perspective</strong></p>\n\n<p>I see the client having to write his code in terms of <code>Array</code>s and array elements when it should be in terms of your business objects - <code>TradeOrder</code>, for example.</p>\n\n<p>The structure - the array - should not be the emphasis in your design. If you keep going down this road you are in for ugly maintenance problems over time. </p>\n\n<p><strong>Give the business classes \"collection friendly\" capabilities</strong></p>\n\n<p>I imagine sorting, searching, preventing duplicates, uniqueness, etc. might be important qualities when we make a collection of things. So <code>TradeOrder</code> should implement <code>IEquatable</code> and <code>IComparable</code>.</p>\n\n<p><code>ResizeableArray</code>, or any other <code>TradeOrder</code> user's code, should not be doing this:</p>\n\n<pre><code>if (trade1.stockName == trade2.stockName && trade1.shares == trade2.shares && ...)\n</code></pre>\n\n<p>Client code should be able to do this:</p>\n\n<pre><code>if (trade1.Equals(trade2))\n</code></pre>\n\n<p><strong>Should <code>ResizableArray</code> inherit <code>Array</code>?</strong></p>\n\n<p><code>Array</code> already implements <code>foreach</code>, for example. You'll get all the built-in goodness and it will be exposed at the 'class level' to the client. There's lots of nifty search and sort methods that take advantage of <code>ICompareable</code> implementation.</p>\n\n<blockquote>\n <p>Some fields are never changes so as I reuse elements I need to assign those fields just once</p>\n</blockquote>\n\n<p><strong>Memory Leaks</strong></p>\n\n<p>As <code>ResizableArray</code> gets used it will have empty and occupied elements scattered throughout the <code>Array</code>. You will end up writing code to scan the array for every <code>Add()</code>. Otherwise you'll be adding new elements when there are empty elements available.</p>\n\n<p>It looks like we leave <code>TradeOrder</code> objects in unused array elements. This is the case at instantiation, clearly. Also removing things involves <code>Count</code> but not <code>null</code>ing the reference there. I guarantee you'll be spending lots of extra code and lots of debugging time trying to keep the <code>Count</code> in synch with the actual active objects.</p>\n\n<p><strong>We don't know what an empty element is</strong></p>\n\n<p>The <code>Count</code> is being incremented/decremented but we're leaving objects in place. I'm assuming that at some point we're done with a given object, in which case it should be disposed of. Besides the memory issue, how do we know what <code>array</code> elements are in use and which ones we can over-write?</p>\n\n<blockquote>\n <p>// made public to use in \"foreach\", but better to be private<br/>\n public T[] array;</p>\n</blockquote>\n\n<p>NO. </p>\n\n<p><code>ResizeableArray</code> should implement <code>IEnumerable</code>.</p>\n\n<p>You are forcing client code to be written like this:</p>\n\n<pre><code>foreach (var trade in tradeOrders.array)\n</code></pre>\n\n<p>When they should write:</p>\n\n<pre><code>foreach (var trade in tradeOrders)\n</code></pre>\n\n<p>This is a violation of OO principles. Single Responsibility, Law of Demeter (least knowledge), Encapsulation ... a discussion for another time.</p>\n\n<p>As a practical matter do not force the client to have to know how to manipulate the class properties. <code>ResizableArray</code> should know how to iterate itself. </p>\n\n<p>The client should not tell the <code>ResizeableArray</code> object to resize, or how.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T23:16:22.910",
"Id": "52760",
"Score": "0",
"body": "“The conventional wisdom says resizing `Array` is less performant than resizing a `List`.” That doesn't make much sense. Resizing `List` is implemented as resizing an array. Resizing array manually would be reinventing the wheel, but I don't see any reason why would it be any slower than `List`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T23:18:11.467",
"Id": "52761",
"Score": "0",
"body": "“Should ResizableArray inherit Array?” No, you can't do that. It wouldn't compile."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T00:20:39.600",
"Id": "52764",
"Score": "0",
"body": "Huh. One more reason to not use an Array."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T06:13:53.170",
"Id": "52782",
"Score": "0",
"body": "\"I'm assuming that at some point we're done with a given object, in which case it should be disposed of.\" - no, we never done with object. once object is allocated we never destroy it, only reuse. The main idea - objects allocations at runtime must be avoided as expensive operation. I also tend to avoid using Virtual function and of course OOP. Well c# is not right language for low-latency programming, but i need simple thing - fast array with reusable objects without runtime allocations."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T03:05:11.040",
"Id": "53203",
"Score": "0",
"body": "Beautiful answer! +1"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T17:36:34.557",
"Id": "32973",
"ParentId": "32964",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "32973",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T13:08:38.497",
"Id": "32964",
"Score": "1",
"Tags": [
"c#",
"array"
],
"Title": "array with reusable elements"
}
|
32964
|
<p>I took a JavaScript challenge to finish a task related to logo of "Breaking Bad" where letters in your first name and last name are spotted with elements of periodic table and its respective atomic number. I wrote the below code, any suggestions to improve performance or any best coding practices </p>
<pre><code> function Process() {
var ellist = {
"h": "1",
"he": "2",
"li": "3",
"be": "4",
"b": "5",
"c": "6",
.
.
.
"Lv":"116",
"Uus":"117",
"Uuo":"118"
};
var fname = document.getElementById("firstname");
var lname = document.getElementById("lastname");
var splits = fname.split("");
var value;
for (var i = 0; i < splits.length; i++) {
var onevalue = fname.indexOf(splits[i]);
var singlev = fname.substring(onevalue, onevalue + 1);
var doublev = fname.substring(onevalue, onevalue + 2);
var triplev = fname.substring(onevalue, onevalue + 3);
if (ellist[splits[i]] || ellist[doublev] || ellist[triplev]) {
value = splits[i];
if (ellist[doublev] || ellist[triplev]) {
value = ellist[doublev];
if (ellist[triplev]) {
value = ellist[triplev];
// some code here
}
// some code here
}
// some code here
}
}
</code></pre>
<p>Using the Process() function which contains the logic. The object <em>ellist</em> contains the list of elements of periodic table with its atomic number. First name is taken from textbox on webpage and stored in <em>fname</em> and similarly the last name in <em>lname</em> and in the for loop it contains the code which checks whether the firstname contains the string which matches the elemetns of periodic table. Any suggestions?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T10:46:44.620",
"Id": "52714",
"Score": "1",
"body": "`for (var i = 0; i < splits.length; i++)` -> `for (var i = 0, maxI = splits.length; i < maxI; ++i)`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T10:52:57.657",
"Id": "52715",
"Score": "1",
"body": "Do you have any problems with current performance?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T13:47:11.337",
"Id": "52716",
"Score": "1",
"body": "@Virus721: No, that's irrelevant premature optimization."
}
] |
[
{
"body": "<blockquote>\n <p>Any suggestions?</p>\n</blockquote>\n\n<p>Yes, a few.</p>\n\n<p>First off, split your function into parts (<a href=\"https://en.wikipedia.org/wiki/Single_responsibility_principle\" rel=\"nofollow\">SRP</a>), to separate the view (DOM elements and their values) from the logic (finding element names in strings).</p>\n\n<blockquote>\n<pre><code>var splits = fname.split(\"\");\nfor (var i = 0; i < splits.length; i++) {\n var onevalue = fname.indexOf(splits[i]);\n</code></pre>\n</blockquote>\n\n<p>That doesn't make much sense to me. Don't you expect <code>onevalue == i</code>? If not, you might annotate this explicitly and/or make the comparison. Maybe it's inside the \"some code\"?</p>\n\n<blockquote>\n<pre><code>var doublev = fname.substring(onevalue, onevalue + 2);\nvar triplev = fname.substring(onevalue, onevalue + 3);\n</code></pre>\n</blockquote>\n\n<p>Notice that these will have the same value as <code>singlev</code> in the last [two] iterations of your loop, where the end is outside of the string.</p>\n\n<blockquote>\n<pre><code>if (ellist[splits[i]] || ellist[doublev] || ellist[triplev]) {\n value = splits[i];\n if (ellist[doublev] || ellist[triplev]) {\n value = ellist[doublev];\n if (ellist[triplev]) {\n value = ellist[triplev];\n</code></pre>\n</blockquote>\n\n<p>Ouch. Simplify this to</p>\n\n<pre><code>if (triplev in ellist) {\n value = ellist[triplev];\n} else if (doublev in ellist) {\n value = ellist[doublev];\n} else if (splits[i] in ellist) { // are you sure you don't want `singlev`?\n value = splits[i];\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T14:05:28.600",
"Id": "32967",
"ParentId": "32966",
"Score": "1"
}
},
{
"body": "<p>The function should take <code>firstname</code> and <code>lastname</code> arguments as strings. If you need to retrieve the strings from DOM elements, make a wrapper function. (You actually screwed this up in the code, treating DOM elements as if they were strings.)</p>\n\n<p>This code is unnecessarily verbose:</p>\n\n<pre><code>var singlev = fname.substring(onevalue, onevalue + 1);\nvar doublev = fname.substring(onevalue, onevalue + 2);\nvar triplev = fname.substring(onevalue, onevalue + 3);\nif (ellist[splits[i]] || ellist[doublev] || ellist[triplev]) {\n value = splits[i];\n\n if (ellist[doublev] || ellist[triplev]) {\n value = ellist[doublev];\n\n if (ellist[triplev]) {\n value = ellist[triplev];\n // some code here\n }\n // some code here\n }\n // some code here\n}\n</code></pre>\n\n<p>You could just say</p>\n\n<pre><code>var singlev = fname.charAt(i);\nvar doublev = fname.substring(onevalue, onevalue + 2);\nvar triplev = fname.substring(onevalue, onevalue + 3);\nvalue = ellist[triplev] || ellist[doublev] || ellist[singlev];\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T23:17:58.137",
"Id": "32986",
"ParentId": "32966",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "32967",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-09-30T10:41:53.797",
"Id": "32966",
"Score": "1",
"Tags": [
"javascript",
"performance",
"strings"
],
"Title": "Encoding strings using periodic table abbreviations"
}
|
32966
|
<p>I was receiving <code>405 method not supported</code> errors on <code>get</code> requests to my save controller, so I created a <code>get</code> method which just calls the existing <code>post</code> one as follows:</p>
<pre><code>class Save(webapp2.RequestHandler):
def get(self):
self.post()
def post(self):
#...
</code></pre>
<p>This seems to be working, but is there a more Pythonic way to define both request handlers at once?</p>
|
[] |
[
{
"body": "<p>Yes, you can easily alias one method to another:</p>\n\n<pre><code>class Save(webapp2.RequestHandler):\n\n def post(self):\n #...\n\n get = post\n</code></pre>\n\n<p><strong>But</strong> although I don't know anything about your application, you shouldn't alias GET to POST like this: the two methods have different semantics. GET is a <em>safe method</em> — it must only retrieve data and <em>not</em> update or store it — while POST is an <em>unsafe method</em> — it requests the server to store or update the data in the request. See \"<a href=\"http://en.wikipedia.org/wiki/Hypertext_Transfer_Protocol#Safe_methods\" rel=\"nofollow\">Safe methods</a>\" in Wikipedia.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T13:16:00.043",
"Id": "33066",
"ParentId": "32968",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "33066",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T14:57:42.710",
"Id": "32968",
"Score": "0",
"Tags": [
"python",
"google-app-engine"
],
"Title": "AppEngine get/post on webapp2.RequestHandler"
}
|
32968
|
<p><strong>AccountController Code:</strong></p>
<pre><code>public class AccountController : ApplicationController
{
public AccountController(ITokenHandler tokenStore, IUser user) : base(tokenStore, user){}
public ActionResult LogOn()
{
return View();
}
//
// POST: /Account/LogOn
[HttpPost]
public ActionResult LogOn(string email, string password)
{
dynamic result = user.Login(email, password);
if (result.Authenticated)
{
SetToken(result.User);
return RedirectToAction("Index", "Home");
}
else
{
ViewBag.Message = result.Message;
}
// If we got this far, something failed, redisplay form
return View();
}
//
// GET: /Account/LogOff
public ActionResult LogOff()
{
Response.Cookies["auth"].Value = null;
Response.Cookies["auth"].Expires = DateTime.Today.AddDays(-1);
return RedirectToAction("Index", "Home");
}
//
// GET: /Account/Register
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
public ActionResult Register(string Email, string Password, string ConfirmPassword)
{
var result = user.Register(Email, Password, ConfirmPassword);
if (result.Success)
{
SetToken(result.User);
return RedirectToAction("Index", "Home");
}
else
{
ViewBag.Message = result.Message;
}
return View();
}
private void SetToken(dynamic user)
{
var token = Guid.NewGuid().ToString();
this.user.SetToken(token, user);
TokenStore.SetClientAccess(token);
}
//
// GET: /Account/ChangePassword
[IsAuthorized]
public ActionResult ChangePassword()
{
return View();
}
//
// POST: /Account/ChangePassword
[IsAuthorized]
[HttpPost]
public ActionResult ChangePassword(ChangePasswordModel model)
{
if (ModelState.IsValid)
{
// ChangePassword will throw an exception rather
// than return false in certain failure scenarios.
bool changePasswordSucceeded;
try
{
MembershipUser currentUser = Membership.GetUser(User.Identity.Name, true /* userIsOnline */);
changePasswordSucceeded = currentUser.ChangePassword(model.OldPassword, model.NewPassword);
}
catch (Exception)
{
changePasswordSucceeded = false;
}
if (changePasswordSucceeded)
{
return RedirectToAction("ChangePasswordSuccess");
}
else
{
ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.");
}
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ChangePasswordSuccess
public ActionResult ChangePasswordSuccess()
{
return View();
}
}
</code></pre>
<p><strong>ApplicationController Code:</strong></p>
<pre><code>public class ApplicationController : Controller
{
public ITokenHandler TokenStore;
public IUser user;
public ApplicationController(ITokenHandler tokenStore, IUser user)
{
this.user = user;
TokenStore = tokenStore;
ViewBag.CurrentUser = CurrentUser ?? new { Email = "" };
}
public ApplicationController()
{
TokenStore = new FormsAuthTokenStore();
}
dynamic _currentUser;
public dynamic CurrentUser
{
get
{
var token = TokenStore.GetToken();
if (!String.IsNullOrEmpty(token))
{
_currentUser = user.FindByToken(token);
if (_currentUser == null)
{
//force the current user to be logged out...
TokenStore.RemoveClientAccess();
}
}
//Hip to be null...
return _currentUser;
}
}
public bool IsLoggedIn
{
get
{
return CurrentUser != null;
}
}
}
</code></pre>
<p><strong>TokenStore Code:</strong></p>
<pre><code>public class FormsAuthTokenStore : ITokenHandler
{
public void SetClientAccess(string token)
{
HttpContext.Current.Response.Cookies["auth"].Value = token;
HttpContext.Current.Response.Cookies["auth"].Expires = DateTime.Today.AddDays(60);
HttpContext.Current.Response.Cookies["auth"].HttpOnly = true;
}
public void RemoveClientAccess()
{
Response.Cookies["auth"].Value = null;
Response.Cookies["auth"].Expires = DateTime.Today.AddDays(-1);
}
public string GetToken()
{
var result = "";
if (HttpContext.Current.Request.Cookies["auth"] != null)
{
result = HttpContext.Current.Request.Cookies["auth"].Value;
}
return result;
}
}
</code></pre>
<p><strong>UserModel Code:</strong></p>
<pre><code>public class User : GenericRepository<User>, IUser
{
public int Id { get; set; }
public string Name { get; set; }
public string Email { get; set; }
public string HashedPassword { get; set; }
public DateTime LastLogin { get; set; }
public DateTime CreatedAt { get; set; }
public DateTime UpdatedAt { get; set; }
public string Token { get; set; }
public Boolean IsBanned { get; set; }
public dynamic Register(string email, string password, string confirm)
{
dynamic result = new ExpandoObject();
result.Success = false;
if (email.Length >= 6 && password.Length >= 6 && password.Equals(confirm))
{
try
{
dynamic newUser = new ExpandoObject();
newUser.Email = email;
newUser.HashedPassword = Hash(password);
result.User = Add(newUser);
result.Success = true;
result.Message = "Thanks for signing up!";
}
catch (Exception ex)
{
result.Message = "This email already exists in our system";
}
}
else
{
result.Message = "Please check your email and password - they're invalid";
}
return result;
}
public string Hash(string userPassword)
{
return
BitConverter.ToString(SHA1Managed.Create().ComputeHash(Encoding.Default.GetBytes(userPassword))).Replace
("-", "");
}
public void SetToken(string token, dynamic user)
{
Edit(new {Token = token},Convert.ToInt32(user.ID));
}
public dynamic Login(string email, string password)
{
dynamic result = new ExpandoObject();
object[] queryargs = { email, Hash(password) };
result.UserExists = Exist("User","WHERE Email = @0 AND HashedPassword = @1", queryargs);
result.Authenticated = result.UserExists;
if (!result.Authenticated)
result.Message = "Invalid email or password";
return result;
}
public dynamic FindByToken(string token)
{
object[] queryargs = { token };
return Single("Token = @0", queryargs);
}
}
</code></pre>
<p><strong>IsAuthorized Attribute Code:</strong></p>
<pre><code>public class IsAuthorized : ActionFilterAttribute
{
private string _role { get; set; }
public IsAuthorized(string role)
{
_role = role;
}
public IsAuthorized() { }
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
var controller = (ApplicationController)filterContext.Controller;
if (!controller.IsLoggedIn)
{
filterContext.Result = new RedirectResult("/Account/Logon");
return;
}
if(controller.CurrentUser.IsBanned)
{
filterContext.HttpContext.Response.Write("<h2>Your Accound have been banned :)</h2>");
filterContext.Result = new EmptyResult();
return;
}
if (_role != null)
{
string userRole = controller.CurrentUser.Role;
if (!_role.Equals(userRole))
{
filterContext.HttpContext.Response.Write("Un-Authorized");
filterContext.Result = new EmptyResult();
return;
}
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-01T15:47:36.220",
"Id": "262562",
"Score": "0",
"body": "Why are you doing this? Looks like you could just use the standard MVC auth module as you don't seem to be adding anything extra?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-01T15:48:20.817",
"Id": "262563",
"Score": "0",
"body": "You also seem to be hashing without adding a salt, so it is actually substantially less secure than the standard one..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-09-03T09:29:08.230",
"Id": "262871",
"Score": "0",
"body": "@Milney this was just something i wrote 2 years ago, I was just experimenting with custom authentication but yes i did not go far with it as you mentioned i added nothing extra and yes no salt was added so it's not that secure however i did benefit from that experiment and i learned a lot about authentication and authorization during my research, I also learned how to implement my own thing if it's needed at least i know how to do it and learned what went wrong with my code and what could be generally bad practice so i could avoid in the future and Thanks for contributing :)"
}
] |
[
{
"body": "<p>I'm not much of a web programmer, but I am comfortable with C#. So all of what I have to say is going to be based on styling. As I had posted earlier in a comment to you was to clear out any unused white spaces. It gives the impression that you don't care if there are too many extra white spaces.</p>\n\n<p>The next thing that I want to talk about is your flow of thought. Although you are consistent with how you do it, it is not the most logical. This is your code</p>\n\n<pre><code> [HttpPost]\n public ActionResult LogOn(string email, string password)\n {\n dynamic result = user.Login(email, password);\n if (result.Authenticated)\n {\n SetToken(result.User);\n return RedirectToAction(\"Index\", \"Home\");\n }\n else\n {\n ViewBag.Message = result.Message;\n }\n\n // If we got this far, something failed, redisplay form\n return View();\n }\n</code></pre>\n\n<p>if the result is authenticated you redirect your action. But if authentication was not successful then you don't return anything??? that is how your code is phrased. Obviously next line is where you return a blank View, and you comment that if you get that far that something failed and you want to redisplay the form. You do the exact same bit of code for register. If you find exact duplicate code like that it would be better to pull it out into a method and give it a useful name. I chose this</p>\n\n<pre><code> private ActionResult RedisplayForm(dynamic result)\n {\n ViewBag.Message = result.Message;\n return View();\n }\n</code></pre>\n\n<p>Now for my LogOn and my Register they are a little more to the point and easier to understand with just a cursory glace.</p>\n\n<pre><code> [HttpPost]\n public ActionResult LogOn(string email, string password)\n {\n dynamic result = user.Login(email, password);\n if (result.Authenticated)\n {\n SetToken(result.User);\n return RedirectToAction(\"Index\", \"Home\");\n }\n\n return RedisplayForm(result);\n }\n [HttpPost]\n public ActionResult Register(string Email, string Password, string ConfirmPassword)\n {\n var result = user.Register(Email, Password, ConfirmPassword);\n if (result.Success)\n {\n SetToken(result.User);\n return RedirectToAction(\"Index\", \"Home\");\n }\n\n return RedisplayForm(result);\n }\n</code></pre>\n\n<p>but even here I have some duplicate code. And it looks like it does the same thing as well. If the user is valid (if he's brand new or existing) then we redirect that valid user back to the homepage. ok so make a method called that</p>\n\n<pre><code> private ActionResult RedirectValidUserBackHome(dynamic result)\n {\n SetToken(result.User);\n return RedirectToAction(\"Index\", \"Home\");\n }\n</code></pre>\n\n<p>Now both my methods take on a very nice and easy to read story.</p>\n\n<pre><code> [HttpPost]\n public ActionResult LogOn(string email, string password)\n {\n dynamic result = user.Login(email, password);\n if (result.Authenticated)\n {\n return RedirectValidUserBackHome(result);\n }\n\n return RedisplayForm(result);\n }\n [HttpPost]\n public ActionResult Register(string Email, string Password, string ConfirmPassword)\n {\n var result = user.Register(Email, Password, ConfirmPassword);\n if (result.Success)\n {\n return RedirectValidUserBackHome(result);\n }\n\n return RedisplayForm(result);\n }\n</code></pre>\n\n<p>I don't know enough about ASP to know if i can further pull out the boolean in those, but as it sits right here it is easy enough to read this. The moral of all this is to stay consistent (which you did) but reduce as much duplication as you can without sacrificing readability. Thinking about it now I should have just passed in the required value from result instead of passing in result since it doesn't make sense in that context. So in the end I would end up with this.</p>\n\n<pre><code> [HttpPost]\n public ActionResult LogOn(string email, string password)\n {\n dynamic result = user.Login(email, password);\n if (result.Authenticated)\n {\n return RedirectValidUserBackHome(result.User);\n }\n return DisplayMessageAndRedisplayForm(result.Message);\n }\n\n [HttpPost]\n public ActionResult Register(string Email, string Password, string ConfirmPassword)\n {\n var result = user.Register(Email, Password, ConfirmPassword);\n if (result.Success)\n {\n return RedirectValidUserBackHome(result.User);\n }\n\n return DisplayMessageAndRedisplayForm(result.Message);\n }\n\n private ActionResult RedirectValidUserBackHome(dynamic validUser)\n {\n SetToken(validUser);\n return RedirectToAction(\"Index\", \"Home\");\n }\n private ActionResult DisplayMessageAndRedisplayForm(dynamic message)\n {\n ViewBag.Message = message;\n return View();\n }\n</code></pre>\n\n<p>WOw, this is getting to be a long post, and that is just the first file. I think this principle gives you something to think about.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T21:27:09.930",
"Id": "52740",
"Score": "1",
"body": "Snyder thanks for your help but things doesn't run like that in the world of MVC.\n\nFor example if i do something like: \n\nActionResult DisplayMessageAndRedisplayForm\n\nreturn view(); Here means return a view which got the name of DisplayMessageAndRedisplayForm, that's an entirely different view, which btw does not exist.\n\nso thanks but that won't be useful to me"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T21:32:58.493",
"Id": "52742",
"Score": "0",
"body": "Fair enough, sorry about the misdirection on that one. By all means if it was bad advice down vote"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T21:36:26.233",
"Id": "52743",
"Score": "0",
"body": "No it wasn't, am really sorry i don't mean to be rude or ungrateful but it's just not how things work in MVC, cuz things in MVC works based on naming, if i call a return view in a result action the view is actually the name of the action result."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T21:38:19.447",
"Id": "52744",
"Score": "0",
"body": "Up vote for your point on white spaces thank you so much for your contribution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T21:41:49.660",
"Id": "52745",
"Score": "0",
"body": "Interesting point on the naming. WPF does the same thing for dependency properties. I will stick to my guns about the logical flow of your if/else statements. I feel that your flow could be improved by removing the else statements"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T21:44:09.667",
"Id": "52746",
"Score": "0",
"body": "OK, thanks again and sorry if i sounded rude :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T21:58:24.980",
"Id": "52747",
"Score": "0",
"body": "Nope, never dreamt of it :) We are all in this together."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T21:05:20.850",
"Id": "32978",
"ParentId": "32969",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T15:26:27.653",
"Id": "32969",
"Score": "2",
"Tags": [
"c#",
"mvc",
"security",
"sql-server",
"asp.net-mvc-4"
],
"Title": "Need reviews for an authentication system"
}
|
32969
|
<p>I'm just after some sanity checking of this code:</p>
<pre><code>public struct function defer(required function job, function onSuccess, function onFailure, function onError, function onTerminate){
var threadId = "deferredThread_#createUuid()#";
local[threadId] = "";
try {
cfthread.status = "Running";
thread name=threadId action="run" attributecollection=arguments {
try {
successData.result = job();
cfthread.status = "Completed";
if (structKeyExists(attributes, "onSuccess")){
onSuccess(successData);
}
} catch (any e){
cfthread.status = "Failed";
if (structKeyExists(attributes, "onFailure")){
onFailure(e);
}else{
rethrow;
}
}
}
} catch (any e){
cfthread.status = "Errored";
if (structKeyExists(arguments, "onError")){
onError(e);
}else{
rethrow;
}
}
return {
getStatus = function(){
return cfthread.status;
},
getThreadId = function(){
return threadId;
},
terminate = function(){
if (cfthread.status == "Running"){
thread name=threadId action="terminate";
cfthread.status = "Terminated";
if (isDefined("onTerminate")){
onTerminate();
}
}
}
};
}
</code></pre>
<p>Blog article about it: "<a href="http://cfmlblog.adamcameron.me/2013/10/threads-callbacks-closures-and-pub.html" rel="nofollow">Threads, callbacks, closure and a pub</a>", and <a href="https://github.com/adamcameroncoldfusion/scratch/tree/master/cflib/defer" rel="nofollow">tests and stuff on Github</a>.</p>
<p>Here is a summary of that, copied from the article, and edited for length & situation:</p>
<blockquote>
<p>A week or so ago I encountered a feature proposition for CFML which
was adding closure callback support to the following
functions/operations so they can be processed natively in the
background (non-blocking) and then call back when done:</p>
<p>FileRead FileWrite etc</p>
<p>Basically any operation that can block a network or local resource.
Imagine doing this:</p>
</blockquote>
<pre><code>fileRead( file, function(contents){
// process file here in the background once it is read.
});
</code></pre>
<blockquote>
<p>This is a reasonable idea in general, but I don't think the suggested
approach is very good as it's too focused on specific pain points.</p>
<p>My suggested approach would be more all-encompassing. Why limit this
functionality to a subset of predetermined built-in functions? What
about other built-in operations that might be slow, but otherwise
doesn't need to interact with the rest of the code subsequent to it in
the request? What about custom code that is similar? It makes little
sense to me to "hard-code" this sort of behaviour to specific
operations, to me.</p>
<p>A better solution would be to provide a general mechanism that can be
used by any code to background-thread its execution, and fire
callbacks on completion, failure etc, so as to kick off the next
process, or flag-up that the process has completed.</p>
<p>Then it occurred to me that I thought I could knock a solution out to
this using a single function. Not a very complete solution, but a
solution nevertheless.</p>
</blockquote>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T16:30:30.900",
"Id": "32971",
"Score": "3",
"Tags": [
"multithreading",
"asynchronous",
"error-handling",
"cfml",
"coldfusion-10"
],
"Title": "Quick 'n' dirty job deferment"
}
|
32971
|
<p>This is my first try with Python. I wanted to parse some <code>Log4J</code> so I thought it a good opportunity to write my first Python program.</p>
<p>The format of the logs I deal with are simply like <code>[INFO BLA 08:00:00] Blabla</code>. Most of the time there are single lines like the above; but sometimes, there is a stack trace logged, so a logical "line" is longer than a physical line. Each "logical" line starts with the character <code>[</code>.</p>
<p>So I came up with </p>
<pre><code>#!/usr/bin/env python
import sys
from collections import namedtuple
Logline = namedtuple("Logline", "level timestamp message")
def apply_filter(current_log_line, filtered_lines):
parsed_line = parse_line(current_log_line)
if filter(parsed_line):
filtered_lines.append(parsed_line)
def get_filtered_lines(source):
filtered_lines = []
line_buffer = ""
for line in source:
if line.startswith('[') and line_buffer:
apply_filter(line_buffer, filtered_lines)
line_buffer = ""
line_buffer += line
apply_filter(line_buffer, filtered_lines)
return filtered_lines
def parse_line(log_line):
prefix, message = log_line.split("]", 1)
level, timestamp = parse_prefix(prefix)
return Logline(level, timestamp, message)
def parse_prefix(prefix):
prefix = prefix.strip("[]")
tokens = prefix.split(" ")
level = tokens[0]
timestamp = tokens[-1]
return level, timestamp
def filter(log_line):
return log_line.level == "ERROR" and log_line.timestamp > "07:00:00"
def console_out(lines):
for line in lines:
print("{}{}".format(line.timestamp, line.message.rstrip("\n")))
def main():
if len(sys.argv) != 2:
print("Usage: {0} $logfile".format(sys.argv[0]))
else:
file_name = sys.argv[1]
with open(file_name) as file:
console_out(get_filtered_lines(file))
if __name__ == '__main__':
main()
</code></pre>
<p>Feel free to comment.</p>
<p>One thing, what bugs me is the <code>apply_filter</code> function, which does too many things at once. But I have have no solution for that. </p>
|
[] |
[
{
"body": "<p>Let's see if I understand what's going on with get_filtered_lines() and apply_filter(). First, get_filtered_lines() reads physical lines from the file and strings them together in line_buffer. When we find the beginning of the next logical line ('['), we pass line_buffer off to apply_filter() so the material that has been collected gets processed. Then we empty out line_buffer and start over with the beginning of the logical line just read.</p>\n\n<p>Here's an approach I think is simpler and clearer:</p>\n\n<pre><code>def apply_filter(lbuf):\n parsed = parse_line(lbuf)\n if filter(parsed):\n return [parsed]\n else\n return []\n\ndef get_filtered_lines(source):\n filtered_lines = []\n collected = \"\"\n for line in source:\n if line.startswith('[') and collected:\n filtered_lines.extend(apply_filter(collected))\n collected = \"\"\n collected += line\n filtered_lines.extend(apply_filter(collected))\n return filtered_lines\n</code></pre>\n\n<p>That way, apply_filter doesn't have to be aware of the list being built. It just returns a list of what it finds -- either a line that passes the filter or an empty list. Passing an empty list to extend is a no-op.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-03T14:35:48.800",
"Id": "48865",
"ParentId": "32975",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "48865",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T18:17:30.450",
"Id": "32975",
"Score": "5",
"Tags": [
"python",
"beginner",
"parsing",
"logging"
],
"Title": "Review Simple Logparser"
}
|
32975
|
<p>Here is a program that I've wrote to extract JPEGs from a file. It reads a file that contains the image data and separates it into individual images. </p>
<pre><code>import hashlib
inputfile = 'data.txt'
marker = chr(0xFF)+chr(0xD8)
# Input data
imagedump = file(inputfile, "rb").read()
imagedump = imagedump.split(marker)
count=0
for photo in imagedump:
name = hashlib.sha256(photo).hexdigest()[0:16]+".jpg"
file(name, "wb").write(marker+photo)
count=count+1
print count
</code></pre>
<p>The script names the identified images with their SHA256 digest, and all of the photos that it finds will be dumped into the current directory.</p>
<p>Here's how I test the script to see if it is working correctly:</p>
<ol>
<li>Type <code>cd ~/images/</code></li>
<li>create the folder <code>mkdir test</code></li>
<li>dump some JPEGs into a singe file in the directory <code>cat *.jpg > ./test/data.txt</code></li>
<li><code>cd test</code> and put the script into the current directory</li>
<li>run the script <code>python extract.py</code>, and the JPEGs will be dumped into the current folder</li>
</ol>
<p>How can I improve my script's performance? Are there any problems with its operation? The script does not know when an image ends; just when a new one starts. Could this cause problems?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T07:55:25.200",
"Id": "52785",
"Score": "2",
"body": "Using only 64 bits of SHA256 is a waste. It's not cryptographically sound anyway, so you [might as well use MD5 or SHA1](http://stackoverflow.com/q/2722943/1157100) for slightly faster performance."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T14:16:10.523",
"Id": "52921",
"Score": "1",
"body": "Can you explain more about the background to this problem? Why are the JPEG files simply concatenated together? Why are they not stored in a proper archive format like UStar or ZIP?"
}
] |
[
{
"body": "<p>There <em>is</em> an <a href=\"http://en.wikipedia.org/wiki/JPEG#Syntax_and_structure\" rel=\"nofollow\">End-of-data marker</a> <code>FF D9</code>, but you can't scan for it blindly, because those bytes can also appear within a JPEG image. For example, if the JPEG contains a thumbnail, then <code>FF D9</code> could mark the end of the thumbnail rather than of the whole image. In fact, the <code>FF D8</code> start-of-image marker can also appear within a JPEG image for the same reason. Therefore, your technique is invalid.</p>\n\n<p>To do a proper job, you must look for JPEG markers, most of which are followed by two bytes indicating the payload size, and advance the indicated number of bytes, until you hit the <code>FF D9</code> marker. It might even be faster, since you can advance in chunks rather than scanning every byte sequentially.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T03:20:28.247",
"Id": "32988",
"ParentId": "32981",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-20T22:39:29.227",
"Id": "32981",
"Score": "4",
"Tags": [
"python",
"image"
],
"Title": "JPEG extraction script"
}
|
32981
|
<p>I'm trying to review this block of code to make sure logic is fine. The first version that I commented will create duplicated order 'my college developer' but I fixed it but "really not sure" I want to make sure my fix it exactly same as commented code </p>
<p>the old logic "this code include duplicated"</p>
<pre><code>public void setOrderedProduct(String prodName, int eoq) {
String productCd = getProdCd(prodName);
// Here only one time one product
boolean prodPresent = false;
int indexOfProd = 0;
int sizeOfItems = items.size();
for (int i = 0; i < sizeOfItems; i++) {
PurchaseOrderDTO itemVal = items.get(i);
if (itemVal.getProdcd().equalsIgnoreCase(productCd)) {
prodPresent = true;
indexOfProd = i;
break;
}
}
itemData.setProdname(prodName);
itemData.setQty(eoq);
itemData.setProdcd(productCd);
double costPrice = ProductView.getProductCost(vendorno, productCd);
itemData.setPrice(costPrice);
double extPrice = ProductView.getProductMSRP(vendorno, productCd);
itemData.setExt(extPrice);
if (!prodPresent) {
if (eoq != 0) {
items.add(itemData);
// Now add the details to the database
ProductView.addPurchaseDetails(itemData, vendorno);
}
} else {
if (eoq > 0) {
items.set(indexOfProd, itemData);
ProductView.updatePurchaseDetails(itemData, vendorno);
} else {
items.remove(indexOfProd);
ProductView.removePurchaseDetails(itemData, vendorno);
}
}
if (items.size() > 0)
calculateTotal();
}
</code></pre>
<p>my fixed logic </p>
<pre><code>public void setOrderedProduct(String prodName, int eoq) {
boolean dataPresent = false;
if (orderedProdNameList.contains((Object) prodName)) {
dataPresent = true;
}
if (dataPresent) {
int indexOfProdName = orderedProdNameList.indexOf((Object) prodName);
String productCd = getProdCd(prodName);
// Here only one time one product
PurchaseOrderDTO itemData = new PurchaseOrderDTO();
boolean prodPresent = false;
itemData.setProdname(prodName);
itemData.setQty(eoq);
itemData.setProdcd(productCd);
double costPrice = ProductView.getProductCost(vendorno, productCd);
itemData.setPrice(costPrice);
double extPrice = ProductView.getProductMSRP(vendorno, productCd);
itemData.setExt(extPrice);
// Now add the details to the database
ProductView.addPurchaseDetails(itemData, vendorno);
if (eoq > 0) {
items.set(indexOfProdName, itemData);
ProductView.updatePurchaseDetails(itemData, vendorno);
} else if (eoq == 0) {
for (int i = 0; i < items.size(); i++) {
if (items.get(i).getProdname().equalsIgnoreCase(prodName)) {
items.remove(i);
ProductView.removePurchaseDetails(itemData, vendorno);
}
}
}
} else {
orderedProdNameList.add(prodName);
String productCd = getProdCd(prodName);
// Here only one time one product
PurchaseOrderDTO itemData = new PurchaseOrderDTO();
boolean prodPresent = false;
itemData.setProdname(prodName);
itemData.setQty(eoq);
itemData.setProdcd(productCd);
double costPrice = ProductView.getProductCost(vendorno, productCd);
itemData.setPrice(costPrice);
double extPrice = ProductView.getProductMSRP(vendorno, productCd);
itemData.setExt(extPrice);
items.add(items.size(), itemData);
ProductView.addPurchaseDetails(itemData, vendorno);
}
if (items.size() > 0) {
calculateTotal();
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Not sure if your fixed logic actually works. But I see couple of issues with the code.</p>\n\n<ol>\n<li><p>both if and else block is setting a boolean. But I don't find any use of it in your code. <code>boolean prodPresent = false\n</code></p></li>\n<li><p>How do you get access to <code>items</code> ? is it instance variable ?</p></li>\n<li><p>The if and else block has lot of common code which can be written outside of the condition. </p></li>\n</ol>\n\n<p>Here I am not concerned with your logic but tried to organize the second version of the code which you posted. My intention is to avoid repetitive code in both the if-else block</p>\n\n<pre><code>public void setOrderedProduct(String prodName, int eoq) {\nPurchaseOrderDTO itemData = new PurchaseOrderDTO();\nString productCd = getProdCd(prodName);\n\nitemData.setProdname(prodName);\nitemData.setQty(eoq);\nitemData.setProdcd(productCd);\n\ndouble costPrice = ProductView.getProductCost(vendorno, productCd);\nitemData.setPrice(costPrice);\n\ndouble extPrice = ProductView.getProductMSRP(vendorno, productCd);\nitemData.setExt(extPrice);\n\nif (orderedProdNameList.contains((Object) prodName)) {\n int indexOfProdName = orderedProdNameList.indexOf((Object) prodName);\n\n ProductView.addPurchaseDetails(itemData, vendorno);\n if (eoq > 0) {\n items.set(indexOfProdName, itemData);\n ProductView.updatePurchaseDetails(itemData, vendorno);\n } else if (eoq == 0) {\n for (int i = 0; i < items.size(); i++) {\n if (items.get(i).getProdname().equalsIgnoreCase(prodName)) {\n items.remove(i);\n ProductView.removePurchaseDetails(itemData, vendorno);\n }\n }\n }\n\n} else {\n orderedProdNameList.add(prodName);\n items.add(items.size(), itemData);\n ProductView.addPurchaseDetails(itemData, vendorno);\n}\n if (items.size() > 0) { calculateTotal(); }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T09:02:30.257",
"Id": "33161",
"ParentId": "32987",
"Score": "4"
}
},
{
"body": "<p>Your method is very long. This is code smell - if method is long it maybe do a lot of thinks, but method should do one thing. I suggest you to split method into smaller peaces which defines smaller units of work and are reusable and easy to read. If you put piece of code into method you give name to the code which work as a hint to he programmer what code enclosed in method does. </p>\n\n<p>Also use full name of variables, not some abbreviation like <code>eoq</code>. You write them once (if you are using ide) but read it multiple times so you invest the effor into the writing the proper name.</p>\n\n<p>I did not checked your logic. Your logic should be captured in unit test - if there is no unit test i would hesitate to refactor some code. If there is no unit test dont write them now if you dont have business requirements, but you ca try <a href=\"http://en.wikipedia.org/wiki/Characterization_test\" rel=\"nofollow\">Characterization testing</a> to capture current behavior of the method. Because without any test you cannot be sure if you did not broke something when rewriting the method.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-29T12:30:49.407",
"Id": "33454",
"ParentId": "32987",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "33161",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T03:07:36.540",
"Id": "32987",
"Score": "4",
"Tags": [
"java"
],
"Title": "compare two logic commented one to my logic java"
}
|
32987
|
<p>Below is my implementation of an immutable stack class. The reverse function is trying to return a stack with all elements reversed. Is my implementation good? Maybe the reverse function can be faster?</p>
<pre><code>public class ImStack<T> {
private final T head;
private final ImStack<T> tail;
public ImStack ( T head, ImStack<T> tail)
{
this.head = head;
this.tail = tail;
}
public ImStack<T> pop()
{
return this.tail;
}
public ImStack<T> push( T e)
{
return new ImStack<T>( e, this);
}
public T peek()
{
return this.head;
}
public boolean isEmpty()
{
if ( head == null && tail == null)
return true;
else return false;
}
public int size()
{
if ( isEmpty())
return 0;
else return 1 + tail.size();
}
public ImStack<T> reverse()
{
ImStack<T> resultStack = new ImStack<T> ( null,null);
ImStack<T> tempStack;
tempStack = this;
for ( int i = 0 ; i < this.size(); i++)
{
resultStack = resultStack.push(tempStack.peek());
tempStack = tempStack.pop();
}
return resultStack;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T04:30:17.170",
"Id": "52776",
"Score": "5",
"body": "Stacks typically don't support a `reverse()` operation, since that would violate the last-in, first-out principle, which is the purpose of stacks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T13:30:28.290",
"Id": "52795",
"Score": "0",
"body": "`size()` might overflow the stack, I'd prefer an iterative version."
}
] |
[
{
"body": "<p>Writing an elegant immutable stack is difficult in Java, mainly due to the lack of multiple return values. But your code does look quite fine.</p>\n\n<p>I am comparing your API with <a href=\"http://www.scala-lang.org/api/current/index.html#scala.collection.immutable.Stack\" rel=\"nofollow\">Scala's immutable stack</a>. One interesting bit is that there the signature of <code>push</code> translates to:</p>\n\n<pre><code>public <T2 super T> ImStack<T2> push(T2 e)\n</code></pre>\n\n<p>which looks uncomfortable but makes a lot of sense too: Adding elements to a stack can <em>widen</em> the type but never narrow it down. Keeping the current type is a special case of this.</p>\n\n<p>Your <code>isEmpty</code> method is unfortunately flawed. Assume I have created a stack of one element, like:</p>\n\n<pre><code>Object myObject = null;\nImStack<Object> stack = new ImStack<Object>(myObject, null);\n</code></pre>\n\n<p>Now <code>stack.peek()</code> is correctly <code>null</code>. On an empty stack, this should have created an exception, not returned a null.</p>\n\n<p>One solution to solve this problem is to have <code>isEmpty()</code> <em>always</em> return <code>false</code>. We also create a private subclass¹ of <code>ImStack</code> called <code>ImEmptyStack</code>, where <code>isEmpty()</code> returns <code>true</code>, and <code>peek()</code> throws an exception. In your constructor, you create a new empty stack as tail when that argument would be <code>null</code>:</p>\n\n<pre><code>ImStack(T head, ImStack<? extends T> tail) {\n this.head = head;\n this.tail = tail != null ? tail : new ImEmptyStack<T>();\n}\n</code></pre>\n\n<p><sub>1: Actually, <em>subclassing</em> here leads to problems. The two classes should both be subtypes of a common interface. So basically, the <em>Composite Pattern</em>.</sub></p>\n\n<p>By overriding the <code>size()</code> in the ImEmptyStack, you can simplify that as well:</p>\n\n<pre><code>class ImStack<T> {\n public int size() {\n return 1 + tail.size();\n }\n}\n\nclass ImEmptyStack<T> extends ImStack<T> {\n public int size() {\n return 0;\n }\n}\n</code></pre>\n\n<p>Back to your <code>isEmpty()</code> method, code like this should never happen:</p>\n\n<pre><code>if ( head == null && tail == null)\n return true;\nelse return false;\n</code></pre>\n\n<p>because it is equivalent to <code>return(head == null && tail == null)</code>. Every time you write code like <code>return foo() ? true : false</code>, you know you can simplify that.</p>\n\n<p>I'd like to sketch your <code>reverse()</code> method in a more functional manner, using an accumulator argument:</p>\n\n<pre><code>public ... reverse() {\n return this.reverse(new ImEmptyStack<T>());\n}\n\nprivate ... reverse(ImStack<...> acc) {\n return tail.reverse(acc.push(head));\n}\n\n// Empty stack:\n\nprivate ... reverse(... acc) {\n return acc;\n}\n</code></pre>\n\n<p>This is as efficient as your solution, because your <code>size</code> call also traverses the whole stack recursively. The advantage of my solution is the simplicity. Of course, it is trivial to rewrite this to an iterative solution, because the above sketch is tail recursive:</p>\n\n<pre><code>reverse() {\n ImStack<T> accumulator = new ImEmptyStack();\n ImStack<T> current = this;\n while(!( current instanceof ImEmptyStack<T> )) {\n accumulator = accumulator.push(current.peek());\n current = current.pop();\n }\n return accumulator;\n}\n</code></pre>\n\n<p>Note that <code>.pop()</code> can never return <code>null</code> in my adaption of your code (an empty stack should throw an exception).</p>\n\n<hr>\n\n<p>Something minor that I noticed is your inconsistent spacing around the argument lists of your methods:</p>\n\n<pre><code>ImStack ( T head, ImStack<T> tail) // left outer and inner space\npop() // no space\npush( T e) // left inner space\n</code></pre>\n\n<p>This is no problem in itself, but it would be better to settle for one style.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T14:59:27.530",
"Id": "52806",
"Score": "0",
"body": "@CodesInChaos thanks, fixed :) (in the future, you can also suggest a fix directly by clicking on “edit” under the question, and making the change. If it had been wrong, it can always be reverted.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T15:05:01.717",
"Id": "52807",
"Score": "0",
"body": "I know how to edit, I have a few hundred of them on SO. But in my experience most posters aren't comfortable with that kind of change and prefer a comment."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T08:04:18.910",
"Id": "52883",
"Score": "0",
"body": "It is really a great help to me. Thank you very much :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T06:28:47.467",
"Id": "32994",
"ParentId": "32991",
"Score": "6"
}
}
] |
{
"AcceptedAnswerId": "32994",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T03:55:04.067",
"Id": "32991",
"Score": "6",
"Tags": [
"java",
"stack",
"immutability"
],
"Title": "How is my implementation of an immutable stack?"
}
|
32991
|
<p>I've written a function to parse configuration files. It doesn't handle file opening, but instead takes an array with the file contents and tries to find fields based on an array containing the fields' names. If found, it puts the content into its respective place.</p>
<p>The only rules it has so far are:</p>
<ul>
<li>each field is delimited by a newline <code>'\n'</code></li>
<li>case doesn't matter for the field's name</li>
<li>after a field's name has been found, leading spaces and tabs are irrelevant and discarded</li>
<li>lines containing unrecognized fields are ignored</li>
<li>the character separating the field's name and its respective content must be specified in the field's name</li>
</ul>
<p>Example file:</p>
<blockquote>
<pre><code>FIELD 1: CONTENT 1
FIELD 2: CONTENT 2
FIELD 3: CONTENT 3
FIELD 4: CONTENT 4
FIELD 5: CONTENT 5
</code></pre>
</blockquote>
<p>Here's an example call:</p>
<pre><code>char *configuration = load_file(file_name);
char *field1;
char *field2;
char *field3;
char *field4;
char *field5;
static const char *fields[] = {
"FIELD 1:",
"FIELD 2:",
"FIELD 3:",
"FIELD 4:",
"FIELD 5:",
0
};
char **destinations[] = {
&field1,
&field2,
&field3,
&field4,
&field5,
0
};
//Parse and load fields
parse(destinations, fields, configuration);
</code></pre>
<p>And the function:</p>
<pre><code>//strings allocated must be freed by the caller
static void parse(char ***destinations, const char **fields, const char *source)
{
char buffer[BUFFER_SIZE];
int i, j, buffer_position;
while(*source != '\0')
{
for(i = 0; fields[i] != 0; ++i)
{
//check if first character match, case insensitive
if(*fields[i] == *source || inverse_case(*fields[i]) == *source)
{
//check if subsequent characters match
for(j = 0; fields[i][j] != '\0'; ++j)
{
if(fields[i][j] != source[j] && inverse_case(fields[i][j]) != source[j]) break;
}
//it's not the right field, look for another
if(fields[i][j] != '\0') continue;
//found, update pointer position
source += j;
//skip leading spaces and tabs
while(*source == ' ' || *source == '\t') ++source;
//collect content
for(buffer_position = 0; *source != '\n' && buffer_position < BUFFER_SIZE - 1; ++buffer_position, ++source)
{
buffer[buffer_position] = *source;
}
buffer[buffer_position] = '\0';
//if it's an empty line, nothing to copy
if(buffer_position > 0)
{
//allocate memory for destination and copy
if((*destinations[i] = malloc(buffer_position + 1)) != 0)
{
COPY(*destinations[i], buffer);
}
//if there's an error on malloc(), we just skip the field and notify the user
else
{
printf("Error: malloc(%d)\n", buffer_position + 1);
}
}
//since we found a field that matches, no need to keep looking
//break the for loop, skip the while and process next line
goto next_iteration;
}
}
//no matches for the current line just skip it entirely
while(*++source && *source != '\n');
next_iteration:
++source;
}
}
</code></pre>
<p>My questions:</p>
<ul>
<li>Would it be considered better if the line delimiter was defined by the caller?</li>
<li>By adding the options to not ignore spaces and tabs, and set case sensitivity on/off, would the parameter list be considered too big?</li>
</ul>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T10:16:34.990",
"Id": "52790",
"Score": "0",
"body": "IT would be a better idea to use an existing file format (such as json) and use that. It would be better to read from the stream and match dynamically rather than have to read the whole file into memory. SAX verses DOM model."
}
] |
[
{
"body": "<p>I'll only address C programming issues in this answer, not the algorithm itself.</p>\n\n<p><strong>Program design and programming practice</strong></p>\n\n<ul>\n<li><p>As a rule of thumb, there is never a reason to use more than two levels of indirection in C programming. More levels than that always originates from flawed program design. In your case, you are allocating an array of pointers to char. So it should be <code>char* destinations[]</code>. </p></li>\n<li><p>Because of the above reason, the function should be changed to </p>\n\n<pre><code>static void parse (char **destinations, const char **fields, const char *source)\n</code></pre>\n\n<p>or if you would prefer:</p>\n\n<pre><code>static void parse (char** destinations, \n const char** fields, \n const char* source)\n</code></pre></li>\n<li><p>It is bad practice to allocate memory in a different module than the one doing the allocation. If <code>parse()</code> does memory allocation, then a function located in the same module should handle the cleanup, not the caller. I would advise to create a function called <code>parse_cleanup()</code> or similar, which does this.</p></li>\n<li><p>The function <code>parse</code> is performing a parsing algorithm. The function shouldn't concern itself with anything else but that. Dynamic memory allocation is completely unrelated to the task \"parsing\". Consider splitting the code in two sub-functions: one which handles the algorithm and one for the memory allocation.</p></li>\n<li><p>Your loop control is made needlessly complex. You control the iteration from no less than 5 places: outer while loop, first for loop, continue statement, goto statement. This is spaghetti code and needs to be rewritten from scratch. </p>\n\n<ul>\n<li><p>You don't need nested loops at all. Throughout the iteration, you will have to constantly check for <code>\\0</code>, as any string can end anywhere. You can merge the while and for into a single while. That will also mean that you can remove the goto.</p></li>\n<li><p>Instead of having one big super loop that does a lot of things, consider writing a simple loop that calls upon various functions. Try to avoid <code>break</code> if possible, and always avoid <code>continue</code> and <code>goto</code>, as the latter two are completely superfluous language features that many programmers consider hard to read.</p></li>\n</ul></li>\n<li><p>Consider to add some error handling to the function. Parsers in particular usually have many things that can go wrong. Then it is nice for the caller to have detailed error information.</p></li>\n<li><p>Investigate if you can't use the standard functions <code>isblank()</code>, <code>isspace()</code> and <code>toupper()</code> from ctype.h, rather than your own custom ones.</p></li>\n</ul>\n\n<p><strong>Coding style</strong> \n(these remarks are more subjective and not everyone will agree)</p>\n\n<ul>\n<li><p>Always write statements on a line of their own and always use braces. This makes the code easier to read and prevent bugs during code maintenance. For example:</p>\n\n<pre><code>while(*source == ' ' || *source == '\\t')\n{\n ++source;\n}\n</code></pre></li>\n<li><p>The above is especially important in the case of <code>while(*++source && *source != '\\n');</code>, because there you can't tell whether the programmer intentionally wrote an empty loop, or if they accidentally wrote a <code>;</code> at the end of the line, which is a very common, classic bug. It is far better to write: </p>\n\n<pre><code>while(x)\n{} // this means: \"yes, I did intend this loop to be empty\"\n</code></pre></li>\n<li><p>Never use the ++ operator in the same expression as other operators, it can easily lead to undefined behavior bugs such as the classic <code>i = i + i++;</code> bug. But it is also harder to read. Mixing ++ with other operators is pointless anyhow, since it doesn't affect performance or the final machine code in any way. One example of how to rewrite it:</p>\n\n<pre><code>do\n{\n source++;\n} while (*source != '\\0' && *source != '\\n');\n</code></pre>\n\n<p>(And of course the check for <code>\\0</code> should be explicit like in this example - that is good practice and you do it everywhere else in your code.)</p></li>\n<li><p>Avoid assignment inside conditions. Just as with the ++ operator, it can lead to bugs, and there is never a reason to have assignment inside conditions, it is another 100% superfluous feature of the language.</p>\n\n<p>Most compilers will warn against assignment inside conditions, so it is annoying to have it there. You should <em>not</em> disable such warnings, because they will find the bug <code>x=y</code> where you intended to have <code>x==y</code>.</p>\n\n<p>Furthermore, in the case of <code>if((*destinations[i] = malloc(buffer_position + 1)) != 0)</code>, did you actually intend to set the contents to NULL if allocation fails? It may or may not be better to leave the pointer alone in that case. Your function call documentation must mention which applies. </p></li>\n<li><p>It is good practice to compare against NULL rather than 0 when dealing with pointers, to show the reader that you did intend to compare a pointer and not an integer value.</p></li>\n<li><p>If you heed my advice to never use ++ together with other operators, then the need for either prefix ++ or postfix ++ is gone: they turn completely equivalent. Ask yourself if you are using prefix ++ for a particular reason. Because people who do think they have a reason, tend to either name something based on superstition or something about how compilers were designed in the 80s.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T05:08:57.030",
"Id": "52870",
"Score": "0",
"body": "Thanks for the comprehensive answer. The pointer is set to `NULL` on purpose when `malloc()` fails.\n\nIt's not meant to be a general parser, I guess the function name should be changed. I have a function `load_settings()` that uses this one to fill a structure and another function `close_settings()` that cleans up. I'm checking if the structure is correctly filled on `load_settings()` and notifying the caller from there. Do you mind posting what you consider to be the correct solution for this task so I can understand better your points?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T14:04:33.143",
"Id": "33001",
"ParentId": "32992",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T04:05:32.207",
"Id": "32992",
"Score": "2",
"Tags": [
"c",
"parsing"
],
"Title": "Parsing configuration files"
}
|
32992
|
<p>I am writing a server that serves an <a href="http://www.w3.org/TR/2012/WD-eventsource-20120426/" rel="nofollow">EventSource</a> data-stream using Python's Twisted. Although this is my first time using Twisted, I hope this part of the code is acceptable.</p>
<p>To get the events, the code queries another server. The other server is a <a href="http://en.wikipedia.org/wiki/Programmable_logic_controller" rel="nofollow">PLC</a> that has its own special ASCII-based protocol. It must be continually polled in order to extract the changes in variables that I would like to turn into events. It is here that I am a little uncertain of the best technique, and I have not been able to find any examples of anything similar.</p>
<p>Specifically, my question is: should the ClientFactory keep a reference to the instance of the Protocol that it creates? I am using this instance in my code in order to have access to the protocol, which allows me to query the PLC. </p>
<p><strong>EDIT:</strong> Just to clarify, the PLC can accept only one connection at a time. Thus the code needs to be able to send all queries to the PLC through just the one connection.</p>
<p>Although this approach works, it feels like a bit of a hack to me as the "factory" is really being coerced into something more like a Singleton. Is this how it should be done? Is there a better approach?</p>
<p>To make this more concrete, here is a section of the <code>EventSource</code> code that uses the instance of the protocol:</p>
<pre><code>class EventSource(Resource):
isLeaf = True
def __init__(self):
# Create connection to PLC
self.factory = ASCIIClientFactory()
reactor.connectTCP("192.168.0.91", 10001, self.factory)
def writeEvent(self, request):
if self.factory._instance is None:
return # nothing we can do yet
# Obtain variables from query string
response = {}
if "x" in request.args:
address = request.args["x"][0]
d = self.factory._instance.getRegister( address ) # <--- What do you think?
def onResult(data):
response["x"] = data
request.write("\nevent:\n")
request.write("data: "+json.dumps(response)+"\n")
d.addCallback(onResult)
</code></pre>
<p>And for reference, here is the protocol and its <code>ClientFactory</code>:</p>
<pre><code>class ASCIIClientProtocol(LineReceiver):
class Command:
def __init__(self, string):
self.string = string
self.deferred = Deferred()
def __init__(self):
self._busy = False
self._commands = deque()
self._current = None
def processCommand(self):
if not self._busy:
self._busy = True
self._current = self._commands.popleft()
self.transport.write( self._current.string )
return self._current.deferred
def addCommand(self, commandString):
command = ASCIIClientProtocol.Command( commandString )
self._commands.append( command )
self.processCommand()
return command.deferred
def getRegister(self, address):
return self.addCommand("SR"+str(address)+"*\n")
def getRaw(self, address):
return self.addCommand("SU"+str(address)+"*\n")
def setRegister(self, address, value):
return self.addCommand("SW"+str(address)+" "+str(value)+"*\n")
def dataReceived(self, data):
assert self._current != None
self._current.deferred.callback(data[0:-2]) # Remove the trailing \r\n
self._busy = False
self._current = None
if len(self._commands) != 0:
self.processCommand()
class ASCIIClientFactory(protocol.ClientFactory):
def __init__(self):
self._instance = None
def buildProtocol(self, addr):
self._instance = ASCIIClientProtocol()
return self._instance
def clientConnectionFailed(self, connector, reason):
print "Failed to connect to PLC"
print "reason:", reason
print "Trying again to connect..."
connector.connect()
def clientConnectionLost(self, connector, reason):
print "Connection to PLC has been lost"
print "reason:", reason
print "Trying to reconnect..."
connector.connect()
def startedConnecting(self, connector):
print "Connecting to PLC..."
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T10:59:38.353",
"Id": "32995",
"Score": "1",
"Tags": [
"python",
"client"
],
"Title": "Using a client from within a server in Python's Twisted"
}
|
32995
|
<p>I have ChaplinJS View, with template which varies according to the condition.
I try to avoid switch statements, but I think it's messy at this moment.</p>
<p>What can you advise?</p>
<pre><code>var SiteView = View.extend({
region: 'date',
autoRender: true,
className: 'date-label',
containerMethod: 'append',
initialize: function(params) {
this.type = params.type;
this.types[this.type].call(this);
},
attach: function() {
View.prototype.attach.call(this);
var _this = this;
_this.$el.addClass('active');
},
types: {
day: function() {
var source = "<strong>{{day}},</strong><span> {{dayNum}} {{month}}. {{year}} г.</span>";
var template = Handlebars.compile(source);
this.template = template({
day: moment(Chaplin.mediator.currentDate).format('dd'),
dayNum: moment(Chaplin.mediator.currentDate).format('D'),
month: moment(Chaplin.mediator.currentDate).format('MMM'),
year: moment(Chaplin.mediator.currentDate).format('YYYY')
});
},
week: function() {
var source = "<strong>{{weekStart}} – {{weekEnd}} {{month}}</strong>, <span>{{year}} (н. {{week}})</span>";
var template = Handlebars.compile(source);
this.template = template({
weekStart: moment(new Date()).startOf('week + 1').isoWeekday(1).format('D'),
weekEnd: moment(new Date()).startOf('week + 1').isoWeekday(7).format('D'),
week: moment(Chaplin.mediator.currentDate).format('wo'),
month: moment(Chaplin.mediator.currentDate).format('MMM'),
year: moment(Chaplin.mediator.currentDate).format('YYYY')
});
},
month: function() {
var source = "<strong>{{month}}</strong> <span>{{year}}</span>";
var template = Handlebars.compile(source);
this.template = template({
month: moment(Chaplin.mediator.currentDate).format('MMMM'),
year: moment(Chaplin.mediator.currentDate).format('YYYY')
});
},
year: function() {
var source = "<strong>{{year}}</strong>";
var template = Handlebars.compile(source);
this.template = template({
year: moment(Chaplin.mediator.currentDate).format('YYYY')
});
}
}
});
</code></pre>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T12:33:26.717",
"Id": "32996",
"Score": "2",
"Tags": [
"javascript",
"backbone.js"
],
"Title": "Backbone/ChaplinJS view with various template"
}
|
32996
|
<p>This was just an experiment to see if I could replicate something like C++ function pointers in Java. Basically, the idea was to have an object which represented a method call, and when you call <code>.invoke()</code> on that object, the method would run.</p>
<p>It feels a little sloppy to me, and I feel like there may be some tricks of Reflection and Generics that would make the code more elegant/usable which I haven't thought of or am not aware of. Any tips or tricks?</p>
<pre><code>import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import org.apache.log4j.Level;
import org.apache.log4j.Logger;
import org.jpgohlke.util.logging.LogUtil;
public class MethodPointer<T, R> {
//Logger instance
private static final Logger LOGGER = Logger.getLogger(MethodPointer.class);
//Object fields
private final Method method;
private final Class<R> returnClass;
private ArrayList<Object> args = new ArrayList<Object>();
private T object = null;
//Constructors
public MethodPointer(Method method, Class<R> returnClass) {
this.method = method;
this.returnClass = returnClass;
}
public MethodPointer(Class<T> clazz, T object, String methodName, Class<R> returnClass, Class<?> ... paramClasses) {
Method theMethod = null;
try {
theMethod = clazz.getMethod(methodName, paramClasses);
}
catch(NoSuchMethodException nsme) {
LogUtil.log(LOGGER, Level.ERROR, "Unable to find method " + methodName + " in " + clazz.getSimpleName(), nsme);
throw new IllegalArgumentException("Method signature does not exist in " + clazz.getSimpleName());
}
method = theMethod;
this.object = object;
this.returnClass = returnClass;
}
public MethodPointer(Class<T> clazz, String methodName, Class<R> returnClass, Class<?> ... paramClasses) {
this(clazz, null, methodName, returnClass, paramClasses);
}
//Accessors and mutators
public Method getMethod() {
return method;
}
public Class<R> getReturnClass() {
return returnClass;
}
public Object[] getArguments() {
return args.toArray();
}
public void setArguments(Object ... args) {
this.args = new ArrayList<Object>(Arrays.asList(args));
}
public void setArguments(ArrayList<Object> args) {
this.args = args;
}
public T getObject() {
return object;
}
public void setObject(T object) {
this.object = object;
}
//Invoking the method
public R invoke() throws Exception {
if(Modifier.isStatic(method.getModifiers())) {
object = null;
}
else if(object == null) {
LOGGER.error("An object must be provided to invoke a non-static method upon.");
throw new IllegalArgumentException("An object must be provided to invoke a non-static method upon.");
}
try {
Object returnValue = method.invoke(object, args.toArray());
if(returnClass.isInstance(returnValue)) {
return returnClass.cast(returnValue);
}
else {
LOGGER.error("Unable to return value from method invocation; the object is not an instance of " + returnClass.getSimpleName());
return null;
}
}
catch(Exception e) {
LogUtil.log(LOGGER, Level.ERROR, "Unable to invoke method " + method.getName(), e);
throw e;
}
}
public R invoke(Object ... args) throws Exception {
this.args.addAll(Arrays.asList(args));
return invoke(returnClass);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T13:58:31.780",
"Id": "52798",
"Score": "0",
"body": "I just realized that the type of `args` should be `List<Object>` rather than `ArrayList<Object>`, if I'm adhering strictly to Java convention."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T16:27:04.763",
"Id": "52811",
"Score": "0",
"body": "This could be called a [thunk](http://en.wikipedia.org/wiki/Thunk_\\(functional_programming\\)). However, be aware that the term is [overloaded](http://en.wikipedia.org/wiki/Thunk)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T17:31:36.447",
"Id": "52813",
"Score": "0",
"body": "@200_success Thanks! Learn something new every day."
}
] |
[
{
"body": "<p>It seams like there is a lot of work going on there for just a simple concept. I suspect you don't need all the flexibility and structure that this implementation gives you. Instead, I suggest you use a simple interfaces. Here is the <a href=\"http://docs.guava-libraries.googlecode.com/git/javadoc/com/google/common/base/Function.html\" rel=\"nofollow\"><code>Function</code></a> interfaces that Guava uses:</p>\n\n<pre><code>public interface Function<F,T> {\n T apply(F input);\n boolean equals(Object object);\n}\n</code></pre>\n\n<p>All you have to do is implement <code>apply()</code> and you are done. If it is a one off, then you can just create an anonymous class. If you are calling the same type of function repeatedly in a number of places or you need something slightly different, you can make a concrete class for those cases.</p>\n\n<p>The good news is that Java 8 will make this much easier. The introduction of lambdas and method references makes it much easier to pass code to be called into a function. The <a href=\"http://docs.oracle.com/javase/tutorial/java/javaOO/methodreferences.html\" rel=\"nofollow\">Method Reference</a> page has examples of lambdas and method references.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T15:13:28.653",
"Id": "52808",
"Score": "0",
"body": "Interesting. Thanks. I'll take a look at Guava. I know I didn't *need* all the infrastructure, but I like to make my code as flexible as possible for the client to have easier API usage (like the multiple constructors, etc.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T14:39:52.847",
"Id": "33004",
"ParentId": "32998",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "33004",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T13:51:55.970",
"Id": "32998",
"Score": "3",
"Tags": [
"java",
"generics",
"reflection"
],
"Title": "How can I improve my Java MethodPointer?"
}
|
32998
|
<p><a href="http://requirejs.org/" rel="nofollow">RequireJS</a> is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node.</p>
<p>It uses the <a href="https://github.com/amdjs/amdjs-api/wiki/AMD" rel="nofollow">Asynchronous Module Definition (AMD) API</a> and also supports <a href="http://requirejs.org/docs/plugins.html" rel="nofollow">loader plugins</a>.</p>
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T14:17:31.653",
"Id": "33002",
"Score": "0",
"Tags": null,
"Title": null
}
|
33002
|
RequireJS is a JavaScript file and module loader. It is optimized for in-browser use, but it can be used in other JavaScript environments, like Rhino and Node.
|
[] |
[] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T14:17:31.653",
"Id": "33003",
"Score": "0",
"Tags": null,
"Title": null
}
|
33003
|
<p>I wrote a function that dynamically stores statistical data. I tried to clone the functionality of how I had originally written my solution in Bash. Is there perhaps something I could improve, or do better?</p>
<p><strong>Bash Solution</strong></p>
<pre><code>#!/bin/bash
data_set=()
while IFS= read -r -p 'Enter statistical data (empty line to quit):' input; do
[[ $input ]] || break
data_set+=("$input")
done
</code></pre>
<p><strong>C Solution</strong></p>
<pre><code>double* get_data(int* data_size)
{
double input;
char line[4096];
double* data_set = NULL;
double* new_data = NULL;
int size = 0;
puts("Enter data (end w/empty line): ");
while(fgets(line, sizeof(line), stdin))
{
if(line[0] == '\n') break;
new_data = realloc(data_set, (size+1) * sizeof(double));
if(sscanf(line, "%lf", &input))
{
if(new_data == NULL)
{
free(data_set);
puts("Error (re)allocating memory");
exit(1);
}
data_set = new_data;
data_set[size++] = input;
}
}
*data_size = size;
return data_set;
}
</code></pre>
|
[] |
[
{
"body": "<p>From your bash script, I assume that you expect a proper (no junk) input. In that case, you can just do</p>\n\n<pre><code>while ((c = getchar()) != '\\n') {\n ungetc(c, stdin);\n scanf(\"%lf%*c\", &x);\n printf(\"x = %g\\n\", x);\n}\n</code></pre>\n\n<p>Of course, you'll replace <code>printf</code> with memory (re)allocation.</p>\n\n<p>If you stick to your solution, I think that</p>\n\n<pre><code>if (sscanf(line, \"%lf\", &input))\n{\n new_data = realloc(data_set, (size+1) * sizeof(double));\n ...\n</code></pre>\n\n<p>makes a bit more sense. The way you're doing it now, you (re)allocate the memory even if the input is not a real number. This can lose you all your old data, if <code>realloc</code> has to move the block (so <code>new_data != data_set</code>) in the same step in which <code>input</code> is not a real number.</p>\n\n<p><strong>Edit:</strong> As requested in the comments, I'll elaborate why and how the original code could lose the data. So, I'm talking about this code:</p>\n\n<pre><code>while(fgets(line, sizeof(line), stdin))\n{\n if(line[0] == '\\n') break;\n\n new_data = realloc(data_set, (size+1) * sizeof(double));\n\n if(sscanf(line, \"%lf\", &input))\n {\n if(new_data == NULL)\n {\n free(data_set);\n puts(\"Error (re)allocating memory\");\n exit(1);\n }\n data_set = new_data;\n data_set[size++] = input;\n }\n}\n</code></pre>\n\n<p>There are two things to consider:</p>\n\n<ol>\n<li><p>The sole purpose of the line</p>\n\n<pre><code>if(sscanf(line, \"%lf\", &input))\n</code></pre>\n\n<p>is to make sure that <code>line</code> contains a real number (and to put it in <code>input</code>, as a number). If we were sure that <code>line</code> contains a <code>double</code>, we wouldn't use <code>if</code>.</p></li>\n<li><p>The line</p>\n\n<pre><code>new_data = realloc(data_set, (size+1) * sizeof(double));\n</code></pre>\n\n<p>tries to reallocate the memory pointed to by <code>data_set</code> so that it would fit <code>size+1</code> doubles. However, this may not be possible if the memory right behind the block pointed to by <code>data_set</code> is occupied.</p>\n\n<p>In that case, another memory block of the required size will be allocated, the data will be copied there, and its address will be returned as the return value of <code>realloc</code>, which we save in <code>new_data</code>. The old memory is freed</p></li>\n</ol>\n\n<p>So, what happens if both of these things happen, i.e., if we don't input a number and the occupation of the memory is such that <code>realloc</code> cannot simply expand the occupied memory?</p>\n\n<p>First, we do <code>realloc</code>:</p>\n\n<pre><code>new_data = realloc(data_set, (size+1) * sizeof(double));\n</code></pre>\n\n<p>Now, our memory old memory (the one pointed to by <code>data_set</code>) is freed, a new memory is allocated and pointed to by <code>new_data</code>, and the data is copied to this new memory.</p>\n\n<p>But, since we didn't input the number, this <code>if</code> will have a false condition:</p>\n\n<pre><code>if(sscanf(line, \"%lf\", &input))\n</code></pre>\n\n<p>So, we do not enter this block and, among other things, we don't do</p>\n\n<pre><code>data_set = new_data;\n</code></pre>\n\n<p>Hence, for the next step, our <code>data_set</code> points to some freed memory (where our data <strong>used to be</strong>), while the pointer <code>new_data</code> will be lost, either with the next <code>new_data = realloc(...)</code> command, or when we exit the function. In both cases, our data is unreachable, and any action on <code>data_set</code> will have unpredictable (most probably wrong) results.</p>\n\n<p>It is not very probable that this will happen, but it might, and the solution is simply to reallocate the memory if and only if we're going to work with it. Hence, my suggestion above.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T17:10:59.883",
"Id": "52812",
"Score": "0",
"body": "Hmm, could you explain a little more or demonstrate what you're saying with losing data? The main thing, I want to make sure I've done everything correctly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T17:33:30.463",
"Id": "52815",
"Score": "0",
"body": "I've tried to elaborate it more by editing the answer."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T23:17:27.383",
"Id": "52856",
"Score": "0",
"body": "Appreciate that so much! I understand now."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T15:31:46.117",
"Id": "33007",
"ParentId": "33005",
"Score": "1"
}
},
{
"body": "<p>I find this API to be a poor match for C. You would be better off swapping the return value and the in-out parameter. By returning the number of items read, the return value could also serve as an error indicator (returns -1 on failure; consult <code>errno</code> for the reason). It would also be similar to the way <code>scanf()</code> returns the number of items assigned. That is better than hard-coding the error-handling policy of printing and exiting. (By the way, error messages should go to <code>stderr</code>, not <code>stdout</code>.)</p>\n\n<pre><code>/**\n * Prints the prompt to out, then reads numbers from in. (No prompt\n * if out is NULL). Afterwards, data will point to a newly allocated\n * array of doubles, and the number of elements in the array is returned.\n *\n * On memory allocation failure, returns -1 and errno is set to ENOMEM.\n */\nint get_data(FILE *out, const char *prompt, FILE *in, double **data)\n</code></pre>\n\n<p>By taking additional parameters <code>out</code>, <code>prompt</code>, and <code>in</code>, the function gains a lot more flexibility for nearly no additional work. You can internationalize the prompt or read from a file.</p>\n\n<p>You shouldn't interleave <code>realloc()</code>, <code>sscanf()</code>, and the error checking for <code>realloc()</code>. That is wrong for two reasons:</p>\n\n<ul>\n<li>You allocate space for another element even if <code>sscanf()</code> read junk</li>\n<li>Error checking for a function call should always immediately afterwards</li>\n</ul>\n\n<p>The correct sequence should be <code>sscanf()</code>, <code>realloc()</code>, and the error checking for <code>realloc()</code>.</p>\n\n<hr>\n\n<p>Here is the revised C code:</p>\n\n<pre><code>/* Documentation here */\nint get_data(FILE *out, const char *prompt, FILE *in, double **data) {\n char line[4096];\n int size = 0;\n *data = NULL;\n\n if (out) {\n fputs(prompt, out);\n }\n\n while (fgets(line, sizeof(line), in)) {\n if (line[0] == '\\n') break;\n double input;\n if (!sscanf(line, \"%lf\", &input)) continue;\n\n double *new_data = realloc(*data, (size + 1) * sizeof(double));\n if (!new_data) {\n free(*data);\n return -1;\n /* errno should still be ENOMEM from realloc() */\n }\n *data = new_data;\n (*data)[size++] = input;\n }\n return size;\n}\n</code></pre>\n\n<hr>\n\n<p>One final remark: the Bash version prints the prompt once per line. To replicate that behaviour…</p>\n\n<pre><code>int get_data(FILE *out, const char *prompt, FILE *in, double **data) {\n char line[4096];\n int size = 0;\n *data = NULL;\n\n while ( out && fputs(prompt, out),\n fgets(line, sizeof(line), in) ) {\n if (line[0] == '\\n') break;\n /* etc */\n }\n return size;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T13:17:22.327",
"Id": "53044",
"Score": "0",
"body": "You've definitely opened my head up for some more ideas to add. I really appreciate the detailed answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T08:05:49.983",
"Id": "33054",
"ParentId": "33005",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "33054",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T14:50:30.770",
"Id": "33005",
"Score": "1",
"Tags": [
"c",
"bash",
"io",
"floating-point"
],
"Title": "Floating-Point data input in Bash and C"
}
|
33005
|
<p>I have the following piece of java method code:</p>
<pre><code>@Override
public void applyStates(int timestamp, State[] states) {
// Calculate the time diff between current time and the time stamp of the given states.
int diff = getNetworkTime() - timestamp;
if (diff <= 0) {
Log.e("Ignoring states that seem to come from the future!");
return;
}
if (diff >= DIFF_THRESHOLD) {
Log.w("Ignoring states that are too old. Diff is: " + diff);
return;
}
// Do the real processing here.
}
</code></pre>
<p>I'd like this code to be testable (by unit tests), however since it has a flow that's comprised of multiple return statements, it's not so easy for me to do so.</p>
<p>I'd like to verify for example, that depending on the input, i go into the 2 different validation clauses in the beginning of the method.</p>
<p>Is there a better design than this? how can this method be better structured for testabilty?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T16:24:36.110",
"Id": "52809",
"Score": "4",
"body": "This question appears to be off-topic because the real question is asking “*How can I unit-test side effects and/or specific code paths?*” and is asking for *design help*. There is no substantial material for a *code review* present. This question may be more appropriate for [programmers.stackexchange.com](http://programmers.stackexchange.com/)."
}
] |
[
{
"body": "<p>You've got a Policy abstraction that is asking to be teased out. The Policy provides a method that tests \"is it valid to do this operation now\". In production, the Policy instance checks the time difference to see if it is valid. In test, however, you specify an instance of the policy object that always says no when you want to test that code path.</p>\n\n<p>You've a bit of refactoring to do to make that possible. To make testing easier, you want to inject an instance of policy into the object, so that your test can control which implementation is being used.</p>\n\n<pre><code>@Override\npublic void applyStates(int timestamp, State[] states) {\n if (! this.policy.isValid(timestamp)) {\n return;\n }\n\n // ....\n</code></pre>\n\n<p>So for testing purposes, you might inject a \"policy.isValid always returns false\" object, and then run your tests and verify that none of the states have been applied (whatever that means).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T18:45:39.780",
"Id": "33014",
"ParentId": "33008",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "33014",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T15:49:03.243",
"Id": "33008",
"Score": "1",
"Tags": [
"java",
"unit-testing"
],
"Title": "Proper way of a testable method with multiple return points"
}
|
33008
|
<p>Code review requested to make this code simpler, cleaner, and better. Input array is sorted.</p>
<p>This program finds the greatest number smaller than <code>x</code>. So, in an array <code>[10 20 30 40]</code> and <code>x = 25</code>, the output should be 20.</p>
<pre><code>public class GreatestValueLesserThanEqualToX {
public static Integer findGreatestValueLesserThanOrEqualToX (int[] arr, int x) {
if (arr == null) {
throw new NullPointerException(" The input array is null. ");
}
if (arr.length >= 1) {
return findGreatestValueLesserThanOrEqualToX (arr, x, 0, arr.length - 1);
} else {
return null; // note the difference wrt greatest value lesser than X.
}
}
private static Integer findGreatestValueLesserThanOrEqualToX (int[] arr, int x, int lb, int ub) {
assert arr != null;
final int mid = (lb + ub) / 2;
/**
* Testing boundaries.
*/
// testing lower boundary.
if (mid == 0) {
if (arr[mid] > x) {
return null;
}
// single element array with value lesser than input value.
if (arr.length == 1) {
return arr[0];
}
}
//testing higher boundary.
if (lb == (arr.length - 1) && arr[mid] < x) {
return arr[mid];
}
/**
* Testing equalities and duplicates.
*/
// testing equality and duplicates. eg: consider input like: 1, 2, 2, 5
if (arr[mid] == x || arr[mid + 1] == x) {
return x;
}
/**
* Testing when element is in the range of array elements.
*/
// input x in range of array elements.
if (arr[mid] < x && arr[mid + 1] > x) {
return arr[mid]; // note the difference wrt greatest value lesser than X.
}
if (arr[mid] < x) {
return findGreatestValueLesserThanOrEqualToX (arr, x, mid + 1, ub);
} else {
return findGreatestValueLesserThanOrEqualToX (arr, x, lb, mid);
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>That is not a class: it is a collection of functions. A class has attributes (instance variables) and behaviours (methods that perform operations on the data):</p>\n<blockquote>\n<p>A class is a software element describing an abstract data type and its partial or total implementation. An abstract data type is a set of objects defined by the list of <strong>operations</strong>, or <em>features</em>, applicable to these objects, and the <strong>properties</strong> of these operations.</p>\n<p>~ Bertrand Meyer, <a href=\"http://en.wikipedia.org/wiki/Object-Oriented_Software_Construction\" rel=\"nofollow noreferrer\">Object-Oriented Software Construction</a>, 2nd Edition, p.23.</p>\n</blockquote>\n<p>Consider:</p>\n<pre><code>/**\n * Allows clients to determine the first value that matches\n * a list of values, based on a particular comparator.\n */\npublic class Determinator {\n private int[] list = new int[0];\n private Comparator comparator;\n\n public Determinator( int[] list ) {\n this( list, new LessThanComparator() );\n }\n\n public Determinator( int[] list, Comparator comparator ) {\n setList( list );\n setComparator( comparator );\n }\n\n private void setList( int[] list ) {\n if( list != null ) {\n this.list = list;\n }\n }\n\n private void setComparator( Comparator comparator ) {\n // Same as setList...\n }\n\n /**\n * Finds the first value in the list that has the relationship\n * to x as denoted by the comparator option.\n *\n * @param x The value to compare against the list of values.\n * @throws InvalidParameterException There was no valid value to return.\n */\n public int findValue( int x ) throws InvalidParameterException {\n }\n\n public boolean isWithinBoundary( ... ) {\n }\n\n public boolean isDuplicate( ... ) {\n }\n\n public boolean isInRange( ... ) {\n }\n}\n</code></pre>\n<p>Note:</p>\n<ul>\n<li>All assertions and tests for <code>null</code> values are no longer necessary.</li>\n<li>The interface (i.e., method definitions) for how the class works can be written independently of the methods themselves.</li>\n<li>Using a <a href=\"http://docs.oracle.com/javase/7/docs/api/java/util/Comparator.html\" rel=\"nofollow noreferrer\">Comparator</a> object makes the code more generic, as it can perform any number of comparisons beyond less-than-or-equal-to.</li>\n<li>The logic has been separated into smaller, more manageable methods.</li>\n<li>No <code>null</code> values are returned: an exception is thrown when a suitable value is not found.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T17:33:02.210",
"Id": "52814",
"Score": "0",
"body": "Please explain the downvotes so that we all can learn."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T17:40:36.163",
"Id": "52817",
"Score": "3",
"body": "No idea what the downvote was for, since this is a useful answer. +1. Some critiques, though: 1) if you use `Comparator`, you should explicitly assign the generic type `<T>`; 2) a constructor with *less* arguments should always refer to a constructor with *more* arguments, not the other way around; 3) throwing an `Exception` if no value is found is a bad approach - Exceptions should be used for errors, not for control flow; 4) Saying \"That is not a class\" may be misleading to new Java developers. It *is* a class, just one that only has `static` methods and would be useless to instantiate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T17:43:06.500",
"Id": "52818",
"Score": "0",
"body": "Upon further thought, the Exception throwing might not be that bad, depending on the use of this API and how \"low-level\" you intend it to be. It's a serious design consideration, though."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T18:07:50.287",
"Id": "52823",
"Score": "0",
"body": "Haha, I'd never read the \"Hoare's billion dollar mistake\" quote. Very nice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T18:13:30.670",
"Id": "52824",
"Score": "1",
"body": "1) Agreed. 2) Fixed. 3) Disagree (see Hoare's billion dollar mistake). 4) Disagree; see update."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T18:24:27.420",
"Id": "52825",
"Score": "0",
"body": "To clarify, I disagree that the exception represents a control flow. I *agree* that exceptions should not be used for control flow because that violates the principle of least astonishment. There is nothing astonishing about a documented exception thrown for an *exceptional* scenario. See also: http://stackoverflow.com/a/729404/59087"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T18:54:07.920",
"Id": "52827",
"Score": "0",
"body": "A static function solves this problem just fine. A `Discriminator` class might be a good idea in some circumstances. However, the problem could be generalized in a number of different directions; in the absence of any particular need, I would do The Simplest Thing That Could Possibly Work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T19:32:56.173",
"Id": "52831",
"Score": "0",
"body": "@200_success: If someone requests a code review using an OO language, then the code should leverage object-oriented techniques (as simply as possible). Otherwise, *The Simplest Thing That Could Possibly Work* would be to write it in a non-OO language, and eschew the benefits of object-orientation."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T17:14:45.300",
"Id": "33012",
"ParentId": "33009",
"Score": "1"
}
},
{
"body": "<h1>Interface Design</h1>\n\n<p>The class could be better named. (As @DaveJarvis points out, it's more of a namespace than a class, but I'm OK with a design that is not pure OOP.) I suggest <code>BinarySearcher</code>: it describes what it can do, without repeating the name of the function, and still leaves it open for you to add a <code>findSmallestValueGreaterThanOrEqualToX()</code> function later.</p>\n\n<p>Returning an <code>Integer</code> is weird, especially since the inputs are unboxed <code>int</code>s. I know, you want to be able to return <code>null</code> if no suitable element is found. I have another suggestion: return the <em>index</em> of the element found rather than the element itself; if no suitable element exists then return -1. That behaviour is reminiscent of <code>String.indexOf()</code>, which all Java programmers should be familiar with. Knowing the index, the caller can easily retrieve the element from the array.</p>\n\n<p>We could also shorten the function name a bit. I suggest that the method signature should be</p>\n\n<pre><code>/**\n * Given a sorted array and a limit, finds the rightmost element\n * whose value does not exceed the limit.\n *\n * @param data An array sorted in ascending order\n * @param limit The maximum value to look for\n * @return The index of the last element in data whose value is less\n * than or equal to limit. If no such element exists, returns -1.\n */\npublic static int greatestIndexNotExceeding(int[] data, int limit)\n</code></pre>\n\n<h1>Search Logic</h1>\n\n<p>There is no reason for your helper function to consult <code>arr.length</code>. The helper function's job is to look between indices <code>lb</code> and <code>ub</code>. The caller will vouch for the validity of those bounds. What happens beyond that range is none of the helper function's business.</p>\n\n<p>You have <em>seven</em> cases, which is way too many. You should only need four:</p>\n\n<ul>\n<li>No suitable element</li>\n<li>Found the result</li>\n<li>Consider the upper half of the range</li>\n<li>Consider the lower half of the range</li>\n</ul>\n\n<h1>Null-Handling</h1>\n\n<p>There's no need to <code>throw new NullPointerException()</code> explicitly. The very next line will raise a <code>NullPointerException</code> naturally when it tries to access <code>arr.length</code>. The <code>arr != null</code> assertion is similarly pointless.</p>\n\n<p>When might it be beneficial to check for <code>null</code> explicitly? When a constructor or a setter method accepts an argument and stores it for future use, but does not try to use it immediately. In those cases, it can be hard to track down later how an instance or class variable came to be <code>null</code>.</p>\n\n<hr>\n\n<h1>Proposed Solution</h1>\n\n<pre><code>public class BinarySearcher {\n /**\n * Insert JavaDoc here…\n */\n public static int greatestIndexNotExceeding(int[] data, int limit) {\n if (data.length < 1) {\n return -1;\n }\n return greatestIndexNotExceeding(data, limit, 0, data.length - 1);\n }\n\n private static int greatestIndexNotExceeding(int[] data, int limit, int lb, int ub) {\n final int mid = (lb + ub) / 2;\n\n // Need to go lower but can't\n if (mid == lb && data[mid] > limit) {\n return -1;\n }\n\n // Found a candidate, and can't go higher\n if (data[mid] <= limit && (mid == ub || data[mid + 1] > limit)) {\n return mid;\n }\n\n if (data[mid] <= limit) {\n // Consider upper half\n return greatestIndexNotExceeding(data, limit, mid + 1, ub);\n } else {\n // Consider lower half\n return greatestIndexNotExceeding(data, limit, lb, mid);\n }\n }\n}\n</code></pre>\n\n<p>It should be possible to restructure the code to reduce the number of comparisons between <code>data[mid]</code> and <code>limit</code>, but I think it's more readable this way.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T06:21:39.080",
"Id": "33043",
"ParentId": "33009",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "33043",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T16:44:48.823",
"Id": "33009",
"Score": "6",
"Tags": [
"java",
"algorithm",
"array",
"binary-search",
"mathematics"
],
"Title": "Finding greatest value in array smaller than x"
}
|
33009
|
<p>I have inlined temporary <code>FileOutputStream</code> that I am not able to explicitly close.</p>
<p>Is that a problem?</p>
<pre><code>File raw = new File(uri.getPath());
Bitmap myBitmap = BitmapFactory.decodeFile(uri.getPath());
File compressedPicture = MEUtils.createTemporaryFile(getPackageName());
// see here
myBitmap.compress(Bitmap.CompressFormat.JPEG,
mObjectiveDefinitionForTakingPictureResult.getQuality(),
new FileOutputStream(compressedPicture));
JpegImageMetadata jpegMetadata = (JpegImageMetadata) Sanselan.getMetadata(raw);
TiffImageMetadata exif = jpegMetadata.getExif();
TiffOutputSet outputSet = exif.getOutputSet();
outputSet.setGPSInDegrees(app.locationListener.getLongitude(),
app.locationListener.getLatitude());
File compressedPictureWithMetadata = MEUtils.createTemporaryFile(getPackageName());
// see here
OutputStream compressedPictureWithMetadataOutputStream = new BufferedOutputStream(new FileOutputStream(compressedPictureWithMetadata));
new ExifRewriter().updateExifMetadataLossless(compressedPicture,
compressedPictureWithMetadataOutputStream,
outputSet);
</code></pre>
<h2>EDIT</h2>
<p>It seems that <code>BufferedOutputStream</code> can conveniently wrap a <code>FileOutputStream</code>, directly by inline it in the constructor: <a href="http://developer.android.com/reference/java/io/BufferedOutputStream.html" rel="nofollow">http://developer.android.com/reference/java/io/BufferedOutputStream.html</a></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T17:38:21.383",
"Id": "52816",
"Score": "0",
"body": "in C# I would ask if you have tried a `using` block. but I don't know enough about Java. does it have something similar? that would automatically close the connection when it is finished using it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T17:43:53.580",
"Id": "52819",
"Score": "1",
"body": "@Malachi There's no Java equivalent, sadly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T17:49:08.803",
"Id": "52820",
"Score": "0",
"body": "I guess you would have to Debug the program and see if the Garbage collection grabs that connection and throws it away. it's never really a good idea to leave a connection open. if the garbage collection grabs it when the application is finished with it you should be fine, but if this is a long running application that will call this code many times before the connection gets closed it will cause issues. I would find a way to close the connection or put it into the ExifRewriter(assuming this is something you wrote) Method"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T09:03:45.070",
"Id": "52892",
"Score": "0",
"body": "@mikeTheLiar In Java 7, there's a [try-with-resources](http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html) block. Too bad it's still not as automatic as C++, where the destructor gets called as soon as a variable goes out of scope."
}
] |
[
{
"body": "<p>Yes, you do.</p>\n\n<p>While the garbage collector does close your <code>FileOutputStream</code> (by calling <code>finalize</code>), it is not a good idea to rely on it because it runs unpredictably.</p>\n\n<p>This means that if you do not close your streams explicitly, you may run into a <a href=\"https://stackoverflow.com/questions/17473182/is-there-a-limiltation-of-simultaneous-filestreams\">limit on the number of simultaneously open files</a> or into inability to open a file until you close the previous stream to it (on Windows) or into unpredictable file content if you open several streams to the same file (on Unix).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T18:41:29.423",
"Id": "52826",
"Score": "0",
"body": "The garbage collector only frees the memory occupied bu the object being gc'd. It does not close the file descriptor the OS assigned."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T19:49:51.973",
"Id": "52836",
"Score": "0",
"body": "@bowmore: It depends on the GC. Are you sure Java's does not?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T21:09:50.537",
"Id": "52847",
"Score": "0",
"body": "`FileInputStream`'s `finalize()` will try to close the file, but the garbage collector itself does not attempt to free any resources other than memory."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T22:22:47.883",
"Id": "52848",
"Score": "0",
"body": "@bowmore: but the GC will call `finalize`, right?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T22:54:13.300",
"Id": "52850",
"Score": "0",
"body": "Not guaranteed to. From Effective Java (2nd ed;) : 'It is entirely possible, even likely, that a program terminates without executing\nfinalizers on some objects that are no longer reachable. '"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T22:56:48.210",
"Id": "52854",
"Score": "0",
"body": "@bowmore: that is irrelevant"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T23:07:21.753",
"Id": "52855",
"Score": "0",
"body": "let us [continue this discussion in chat](http://chat.stackexchange.com/rooms/11151/discussion-between-bowmore-and-sds)"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T18:24:00.397",
"Id": "33013",
"ParentId": "33010",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "33013",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T17:01:49.483",
"Id": "33010",
"Score": "5",
"Tags": [
"java",
"android",
"stream"
],
"Title": "Do I need to close my FileOutputStreams?"
}
|
33010
|
<p>I was trying to post this code to a Wikipedia article, but it was soon removed. I then asked about the code in the page's talk section, and some other contributors said that is was "<em>very poor</em>" and that "<em>there are clearly going to be underflows all over the place</em>." What does that mean? What is an "underflow"? </p>
<p>Could you please tell me more about my program's flaws and how it can be improved? Please give me some constructive criticism. <a href="http://en.wikipedia.org/wiki/Talk%3aE_%28mathematical_constant%29#source_code_examples">Here</a> is where I originally posted the code.</p>
<pre><code>#include <stdio.h>
long factorial(int n) {
long result = 1;
for (int i = 1; i <= n; ++i)
result *= i;
return result;
}
int main ()
{
double n=0;
int i;
for (i=0; i<=32; i++) {
n=(1.0/factorial(i))+n;
}
printf("%.32f\n", n);
}
</code></pre>
<p>Here is the result of the program <strong>2.71828182845904553488480814849027</strong></p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T19:34:05.043",
"Id": "52832",
"Score": "2",
"body": "I wouldn't say that the code is poor at all. I would probably mention the inconsistent braces, and you self asign result in your factorial method, and you don't in your main method, but I wouldn't say it was poor because of that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T13:35:41.770",
"Id": "52908",
"Score": "5",
"body": "@RobertSnyder The int-overflow is a critical flaw IMO. printing more digits than `double`'s precision is silly as well."
}
] |
[
{
"body": "<p>If you're to implement something like this, you should first learn about how these things are done. I hope this doesn't sound too harsh. To explain it better, here is my variant of your code, with comparison to what C computes as e using <code>expl(1)</code>:</p>\n\n<pre><code>#include <stdio.h>\n#include <math.h>\n\nint main ()\n{\n long double n = 0, f = 1;\n int i;\n for (i = 28; i >= 1; i--) {\n f *= i; // f = 28*27*...*i = 28! / (i-1)!\n n += f; // n = 28 + 28*27 + ... + 28! / (i-1)!\n } // n = 28! * (1/0! + 1/1! + ... + 1/28!), f = 28!\n n /= f;\n printf(\"%.64llf\\n\", n);\n printf(\"%.64llf\\n\", expl(1));\n printf(\"%llg\\n\", n - expl(1));\n printf(\"%d\\n\", n == expl(1));\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>2.7182818284590452354281681079939403389289509505033493041992187500\n2.7182818284590452354281681079939403389289509505033493041992187500\n0\n1\n</code></pre>\n\n<p>There are two important changes to your code:</p>\n\n<ol>\n<li><p>This code doesn't compute 1, 1*2, 1*2*3,... which is O(n^2), but computes 1*2*3*... in one pass (which is O(n)).</p></li>\n<li><p>It starts from smaller numbers. Let us, for a moment, assume that your factorials are correct (see below). When you compute</p>\n\n<p>1/1 + 1/2 + 1/6 + ... + 1/20!</p>\n\n<p>and try to add it 1/21!, you are adding</p>\n\n<p>1/21! = 1/51090942171709440000 = 2E-20,</p>\n\n<p>to 2.something, which has no effect on the result (double holds about 16 significant digits). This effect is called <a href=\"http://en.wikipedia.org/wiki/Arithmetic_underflow\">underflow</a>.</p>\n\n<p>However, had you started with these numbers, i.e., if you computed 1/32!+1/31!+... they would all have some impact.</p></li>\n</ol>\n\n<p>Notice that 32! needs 118 bits, i.e., 15 bytes. Your long type doesn't hold as much (the standard says <em>at least 32 bits</em>; it's not likely it will hold more than 64). If we add <code>printf(\"%ld\\n\", factorial(i));</code> to your main <code>for</code>-loop, we see the factorials:</p>\n\n<pre><code>1\n2\n6\n24\n120\n720\n5040\n40320\n362880\n3628800\n39916800\n479001600\n6227020800\n87178291200\n1307674368000\n20922789888000\n355687428096000\n6402373705728000\n121645100408832000\n2432902008176640000\n-4249290049419214848\n-1250660718674968576\n8128291617894825984\n-7835185981329244160\n7034535277573963776\n-1569523520172457984\n-5483646897237262336\n-5968160532966932480\n-7055958792655077376\n-8764578968847253504\n4999213071378415616\n-6045878379276664832\n</code></pre>\n\n<p>See the negatives? That's when your (long) integer grew too much and restarted from its lowest possible value. Read about <a href=\"http://en.wikipedia.org/wiki/Arithmetic_overflow\">overflows</a>; it's important to understand them.</p>\n\n<p>By the way, I'm getting the same result (on my computer) even if I replace <code>long</code> with <code>long long</code> (and apply the proper <code>printf</code> format <code>%lld</code>).</p>\n\n<p>Computing this kind of stuff is complex, and takes quite a bit of knowledge about how the numbers are stored in the computer, as well as the numerical mathematics and the mathematical analysis. I don't consider myself an expert, so so there might be more to this problem than what I've wrote. However, my solution seems in accordance to what C computes with its <code>expl</code> function, on my 64bit machine, compiled with gcc 4.7.2 20120921.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T07:45:48.373",
"Id": "52881",
"Score": "1",
"body": "+1 Your putting the division by the common denominator `28!` at the end is probably quite a performance improvement and allows for storing a the approximation as a fraction as well."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T07:56:54.137",
"Id": "52882",
"Score": "3",
"body": "This algorithm is not mentioned in [this similar SO question](http://stackoverflow.com/q/3028282/321973), maybe you want to post it there as well"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T08:39:17.393",
"Id": "52889",
"Score": "0",
"body": "Where did you get that `expl` code from? For comparison, here's GNU libc's [64-bit implementation](http://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/ieee754/dbl-64/e_exp.c;hb=HEAD) (it's nuts!) and [32-bit implementation](http://sourceware.org/git/?p=glibc.git;a=blob;f=sysdeps/ieee754/flt-32/e_expf.c;hb=HEAD) (relatively sane). There are also implementations for other architectures in the `ieee754` directory."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T13:13:12.457",
"Id": "52905",
"Score": "2",
"body": "I didn't get the code. I merely called it, and compared the results (`==` should mean that all that bits of the two `long double` outputs are identical). My GNU libc is version 2.15-59.fc17.x86_64. This was intended as a simple test. True test would involve the estimate of the top bound of the error, but I felt that this would be beyond what was asked here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-08-10T14:00:40.750",
"Id": "183559",
"Score": "0",
"body": "Time complexity does not matter, please use factorials for better readibility."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T19:38:53.910",
"Id": "33018",
"ParentId": "33015",
"Score": "47"
}
},
{
"body": "<p>Your algorithm uses intermediate numbers that are very large and very small, and they are therefore difficult for computers to work with. For example, 32! ≈ 2.6313 × 10<sup>35</sup>, which is well beyond <code>LONG_MAX</code> (which may be as small as 2<sup>31</sup> - 1 ≈ 2 × 10<sup>9</sup>).</p>\n\n<p>Basically, once <em>n</em> is large enough (maybe 13, maybe 21), <code>factorial(n)</code> returns a \"random\" number. Since your <code>result</code> is <code>long</code> instead of <code>unsigned long</code>, most of the overflowed results will be very large positive or very large negative numbers, so their reciprocals will generally average to zero — but there's no guarantee of that.</p>\n\n<p>So, what would be a good algorithm? You want something that avoids using very small or very large intermediate values. This question was posed as Stack Overflow question 3028312; <a href=\"https://stackoverflow.com/a/3028312/1157100\">this answer</a> links to a <a href=\"http://numbers.computation.free.fr/Constants/E/e.ps\" rel=\"nofollow noreferrer\">paper</a> describing many algorithms for computing <em>e</em>. Section 9 of the paper has an efficient algorithm (though it is code-golfed / mysterious):</p>\n\n<blockquote>\n <p>This is a tiny C program from Xavier Gourdon to compute 9000 decimal digits of e on your computer. A program of the same kind exists for π and for some other constants defined by mean of hypergeometric series.</p>\n\n<pre><code>#include <stdio.h>\n#define DIGITS 9000 /* decimal places (not including the '2') */\nint main() {\n int N = DIGITS+9, a[DIGITS+9], x = 0;\n a[0] = 0;\n a[1] = 2;\n for (int n = 2; n < N; ++n) {\n a[n] = 1;\n }\n for ( ; N > 9; --N) {\n for (int n = N - 1; n > 0; --n) {\n a[n] = x % n;\n x = 10 * a[n-1] + x/n;\n }\n printf(\"%d\", x);\n }\n return 0;\n}\n</code></pre>\n \n <p>This program <em>[<a href=\"http://numbers.computation.free.fr/Constants/TinyPrograms/tinycodes.html#tth_sEc2\" rel=\"nofollow noreferrer\">when code-golfed</a>]</em> has 117 characters. It can be changed to compute more digits (change the value of DIGITS) and to be faster (change the constant 10 to another power of 10 and adjust the printf command). A not so obvious question is to find the algorithm used.</p>\n</blockquote>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T20:59:05.760",
"Id": "52844",
"Score": "0",
"body": "It looks like this is an HTML version containing the code in its original form: http://numbers.computation.free.fr/Constants/TinyPrograms/tinycodes.html#tth_sEc2"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T21:07:53.600",
"Id": "52846",
"Score": "2",
"body": "`1+1/n` doesn't seem to make any sense for integers, but it does: it's like `n>1?1:2`, but 2 characters shorter."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T06:24:11.370",
"Id": "52874",
"Score": "1",
"body": "If anyone can further de-golf the code or offer an explanation, please feel free to edit this answer!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T07:37:16.713",
"Id": "52880",
"Score": "0",
"body": "Those two `while`s would probably read better as `for` loops, or at least the inner one: `while (N-- > 9) { for (int n = N; n > 0; n--) { ...`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T08:09:35.983",
"Id": "52885",
"Score": "1",
"body": "I edited in your quote to http://stackoverflow.com/a/3028312/321973, since that link-only answer otherwise were poor following today's SE standards"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T17:40:00.043",
"Id": "52948",
"Score": "0",
"body": "The results of the program are undefined because `a[0]` is not set! Setting it to 0 seems to fix that. `x` is also uninitialised, but changing it doesn't seem to affect the behaviour. I've suggested an edit for these, and also changed the `while` loops to `for` loops for readability."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T17:45:34.570",
"Id": "52949",
"Score": "0",
"body": "Judging from the div/mod by `n` in the inner loop, the program is working in a kind of factorial number system."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T19:40:47.917",
"Id": "33019",
"ParentId": "33015",
"Score": "8"
}
},
{
"body": "<p>Technically the problem is not one of underflow, but of lost significance. Underflow is when the number is too small to be stored in the current format and it is replaced by 0.0. Lose of significance occurs when a (relatively) large number is added to a (relatively) small number. Recall that when fractional numbers are added the \"decimal\" (or binary) point must be lined up. For example in decimal we might add 2.5x10^0 and 2.5x10^-5, which expanded to line up the decimals looks like this...</p>\n\n<pre><code> 2.500000\n+0.000025\n----------\n 2.500025\n</code></pre>\n\n<p>If we perform this calculation with only 4 places of accuracy the answer is simply 2.500 rather than 2.500025, which is what we would expect. The same thing happens with your program but of course you have more digits of accuracy available and of course it occurs in binary, not decimal, but the problem is the same.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T08:18:22.010",
"Id": "52887",
"Score": "1",
"body": "You're right that technically the problem is not underflow. However, lost significance isn't the issue either. As @VedranŠego points out, overflow of the `long` value leads to random wrong numbers being added."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T14:57:00.127",
"Id": "52930",
"Score": "1",
"body": "The question was \"what does underflow mean\"?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T23:49:02.810",
"Id": "52994",
"Score": "0",
"body": "@200_success Underflow (or loss of significance, whatever you want to call it) **is** a problem. Not as big as the overflow in the factorials, but it can contribute to the wrong solution. This is one of the reasons that I have reversed the order of the computation. See my point 2."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T05:33:13.093",
"Id": "33041",
"ParentId": "33015",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "33018",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T18:49:12.790",
"Id": "33015",
"Score": "39",
"Tags": [
"c",
"algorithm",
"mathematics",
"floating-point"
],
"Title": "Why is my C program for calculating Euler's constant of poor quality?"
}
|
33015
|
<p>I recently made a program in Python to open a list of URLs and split the queries into different files. I want to make this code more generic and simple. I am open to suggestions. </p>
<pre><code>def parse_file():
# Open the file for reading
infile = open("URLlist.txt", 'r')
# Read every single line of the file into an array of lines
lines = infile.readlines()
# For every line in the array of lines, do something with that line
for line in lines: # for every line in lines.
print line # print the URL
# parse the URL query string list
# if the URL has a query component print out the the first
# argument(k) and if the URL has multiple arguments, print out
# the other arguments. (v)
for k,v in urlparse.parse_qsl(urlparse.urlparse(line).query):
print k, v
if k == "blog": # if the printed out arguements have blog in it
# write it out to the apropriate file and do this
# to all the others.
with open('blog_file.txt'.format(),'a') as f:
f.write(v)
elif k == 'p':
with open('p_file.txt'.format(),'a') as f:
f.write(v)
elif k == 'attachment_id':
with open('attachment_id_file.txt'.format(),'a') as f:
f.write(v)
elif k == 'lang':
with open('lang_file.txt'.format(),'a') as f:
f.write(v)
elif k == 'portfolio':
with open('portfolio_file.txt'.format(),'a') as f:
f.write(v)
elif k == 'page_id':
with open('page_id_file.txt'.format(),'a') as f:
f.write(v)
elif k == 'comments_popup':
with open('comments_popup_file.txt'.format(),'a') as f:
f.write(v)
elif k == 'iframe':
with open('iframe_file.txt'.format(),'a') as f:
f.write(v)
elif k == 'width':
with open('width_file.txt'.format(),'a') as f:
f.write(v)
elif k == 'height':
with open('height_file.txt'.format(),'a') as f:
f.write(v)
print "--------------------"
infile.close()
f.close()
parse_file()
</code></pre>
|
[] |
[
{
"body": "<h1>Before We Get Started</h1>\n\n<p>It would be good if you could provide some examples of the URLs that you are looking to parse, I did a cursory search and I couldn't coerce a query result from any that I tried with:</p>\n\n<pre><code>urlparse.parse_qsl(urlparse.urlparse(\"some_url\").query\n</code></pre>\n\n<p>In the interest of brevity I'll assume you have some set of URLs that this is working for.</p>\n\n<h1>Code Review</h1>\n\n<p>Step one in making your code more generic will be to remove the hard-coded URL text file from your function body. I would suggest it be a parameter to the <strong>parse_file</strong> function. </p>\n\n<p>Also, You don't need to do this:</p>\n\n<pre><code>lines = infile.readlines()\nfor line in lines:\n</code></pre>\n\n<p><a href=\"http://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects\" rel=\"nofollow\"><strong>.readlines()</strong></a> isn't necessary in how it is being used here and the file can be read without it. You obviously know about the <a href=\"http://docs.python.org/2/reference/compound_stmts.html#with\" rel=\"nofollow\">With Statement</a> and how to use it as a context manager - but you're still opening and closing your URL list file manually!</p>\n\n<pre><code>infile = open(\"URLlist.txt\", 'r')\n...\ninfile.close()\n</code></pre>\n\n<p>Instead, you can alias the opened file in your With Statement and it will be iterable without <strong>.readlines()</strong>:</p>\n\n<pre><code>with open(input_file) as input:\n for line in input:\n</code></pre>\n\n<p>Also, if you find yourself using multiple If/Elif clauses you might consider it time to look into some of Python's more interesting data structures, below I'm using a dictionary. \nYou can replace your predicate:</p>\n\n<pre><code>if k == 'blog':\n</code></pre>\n\n<p>and instead use a key in a dictionary with the value corresponding to the the subsequent procedure. </p>\n\n<pre><code>{'blog' : \"blog_file.txt\"}\n</code></pre>\n\n<h1>Revision</h1>\n\n<p>Below is a possible revision to your code:</p>\n\n<pre><code>import urlparse\ndef parse_file(input_file):\n tags = {'blog' : \"blog_file.txt\",\n 'p' : \"p_file.txt\",\n 'attachment_id' : \"attachment_id_file.txt\",\n 'lang' : \"lang_file.txt\",\n 'portfolio' : \"portfolio_file.txt\",\n 'page_id' : \"page_id_file.txt\",\n 'comments_popup' : \"comments_popup_file.txt\",\n 'iframe' : \"iframe_file.txt\",\n 'width' : \"width_file.txt\",\n 'height' : \"height_file.txt\"}\n with open(input_file) as input:\n for line in input:\n parsed_url = urlparse.parse_qsl(urlparse.urlparse(line).query)\n if len(parsed_url) > 0:\n for key, value in parsed_url:\n if key in tags:\n with open(tags[key], 'a') as output_file:\n output_file.write(value)\n else:\n print key + \" not in tags.\"\n else:\n print(line + \" does not yield query.\")\n</code></pre>\n\n<p>I think this should work as you describe, but without a set of example URLs it's difficult to say for sure. The line:</p>\n\n<pre><code>if len(parsed_url) > 0:\n</code></pre>\n\n<p>is used here because I couldn't coerce <strong>.query</strong> to return anything but an empty list on those URLs I attempted.</p>\n\n<h1>Final Thought</h1>\n\n<p>It might be a good idea to change the functionality for those keys not found in your <em>tags</em> dictionary. You might consider creating a miscellaneous, or catch-all file that unmatched values get written to. That way you don't totally lose work on those unmatched URLs.</p>\n\n<p><em>This is all based on the assumption that you have some domain that your code is currently working for.</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T03:28:54.607",
"Id": "33039",
"ParentId": "33016",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "33039",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T19:17:16.547",
"Id": "33016",
"Score": "2",
"Tags": [
"python",
"parsing",
"generics",
"url",
"file"
],
"Title": "Opening a list of URLs and splitting the queries into different files"
}
|
33016
|
<p>I find myself using this bit of code very often when I am retrieving the results from a Cursor</p>
<pre><code>SearchItem searchItem = new SearchItem();
searchItem.setId(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_ID)));
searchItem.setOrigin(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_ORIGIN)));
searchItem.setDestination(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DESTINATION)));
searchItem.setTimeStamp(cursor.getLong(cursor.getColumnIndex(COLUMN_NAME_TIMESTAMP)));
</code></pre>
<p>Specifically this could be when I am using a <code>CursorAdapter</code> for a <code>ListView</code> and in a DAO object.</p>
<p>What would be a useful design pattern to use in this case?</p>
<p>My first instinct is to have a singleton class which does this. Are there any problems in taking this route?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T02:41:53.167",
"Id": "52833",
"Score": "0",
"body": "I see I was voted down. I am always open to hear why this is a bad question"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T03:46:12.590",
"Id": "52834",
"Score": "0",
"body": "Not sure, but perhaps the voter believed that this type of question leads to discussions of \"equally-right\" answers, which is discouraged by SO (see http://stackoverflow.com/help/dont-ask)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T03:55:01.777",
"Id": "52835",
"Score": "1",
"body": "I didn't realise it was one of those questions. Maybe I should try something and post on codereview"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-22T01:07:33.863",
"Id": "58496",
"Score": "0",
"body": "Is those five lines **exactly** the same when you write them?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T03:09:53.290",
"Id": "58828",
"Score": "0",
"body": "yes exactly the same"
}
] |
[
{
"body": "<p>I am not completely sure if your question is as easy as it sounds (or if I am missing something), but here's my thought on things.</p>\n\n<p>Using a singleton class for this does not make much sense in my opinion. There's no <strong>state</strong> to be stored, and therefore there's no need for an object at all. Instead, it sounds like you could put it in an utility method.</p>\n\n<pre><code>public static SearchItem createSearchItem(Cursor cursor) {\n SearchItem searchItem = new SearchItem();\n searchItem.setId(cursor.getInt(cursor.getColumnIndex(COLUMN_NAME_ID)));\n searchItem.setOrigin(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_ORIGIN)));\n searchItem.setDestination(cursor.getString(cursor.getColumnIndex(COLUMN_NAME_DESTINATION)));\n searchItem.setTimeStamp(cursor.getLong(cursor.getColumnIndex(COLUMN_NAME_TIMESTAMP)));\n return searchItem:\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-25T17:36:05.150",
"Id": "36064",
"ParentId": "33017",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-03T02:28:54.997",
"Id": "33017",
"Score": "0",
"Tags": [
"java",
"android"
],
"Title": "Reusing Code With Database Cursors"
}
|
33017
|
<p>I recently wrote a function that replaces every white space with '%20', just for fun (and sharping my coding skills). The input string is terminated with extra white spaces, with the length that the string should have after encoding takes place. For example:</p>
<pre><code>input = "Not encoded " //2 white spaces in the end
output = "Not%20encoded"
</code></pre>
<p>Although I was able to implement such encoding in-place, I was still not pleased with the result, specially due to the inner loop that shifts the whole string to the right everytime a white space is found. Here is my solution, written in C#:</p>
<pre><code> public string encode(string str)
{
var array = str.ToCharArray();
for (int i = 0; i < array.Length; i++) {
if (array[i] != ' ') continue;
//switch every char >> 2, from the end of the string to i
for (int j = array.Length - 1; j > i; j--) {
array[j] = array[j - 2];
}
array[i++] = '%';
array[i++] = '2';
array[i] = '0';
}
return new String(array);
}
</code></pre>
<p>I'm looking for a solution that operates in O(n), possibly performing a single traversal on the input string. Additional feedback on how to improve performance/readability of my function are always very appreciated :)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T20:58:25.903",
"Id": "52843",
"Score": "0",
"body": "Have you looked at the StringBuilder class? It does away with your 2nd shift-y for loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T21:01:12.753",
"Id": "52845",
"Score": "0",
"body": "I have :) But I was trying to optimize space complexity. That's why I performed the string replacements in-place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T00:29:17.237",
"Id": "52862",
"Score": "0",
"body": "How come the string already has exactly the right amount of trailing spaces? Do you have special code for that? Doesn't that perform more allocations?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T00:39:52.687",
"Id": "52864",
"Score": "0",
"body": "Maybe my question was not clear enough: this is not a \"real world\" application nor a \"real world\" problem. It's just a coding challenge, and the extra trailing spaces is part of the problem specification."
}
] |
[
{
"body": "<p>Your solution:</p>\n\n<ul>\n<li>copies the whole string twice (1. <code>string.ToCharArray()</code> 2. <code>new string()</code>)</li>\n<li>needs <em>n</em> bytes of extra storage (apart from the input and output; <em>n</em> is the size of the output)</li>\n<li>potentially moves the characters in the string a lot (O(<em>n</em><sup>2</sup>))</li>\n<li>requires the input to already have free space for the expansion</li>\n</ul>\n\n<p>Solution using <code>StringBuilder</code>:</p>\n\n<ul>\n<li>copies the whole string twice (1. calls to <code>Append()</code> 2. <code>StringBuilder.ToString()</code>)</li>\n<li>needs about <em>n</em> bytes of extra storage</li>\n<li>doesn't need to move characters at all</li>\n<li>doesn't require the input to be in any special format</li>\n</ul>\n\n<p>Based on this, <code>StringBuilder</code> is clearly the better solution.</p>\n\n<p>But there is even better solution: just use <code>string.Replace()</code>. That's likely going to be quite efficient and it's much shorter than any other of the proposed alternatives.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T00:25:23.200",
"Id": "52861",
"Score": "0",
"body": "@downvoter: it would help if you explained what you think is wrong with my answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T21:15:45.807",
"Id": "33027",
"ParentId": "33020",
"Score": "2"
}
},
{
"body": "<p>As strings are immutable you can't really avoid intermediate store of the data as it's being encoded.</p>\n\n<p>As you already know the length of the final string you can avoid the shuffling:</p>\n\n<pre><code> int spaceCount = 0;\n for (int i = str.Length - 1; str[i] == ' '; i--)\n {\n spaceCount++;\n }\n if (spaceCount == 0) { return str; }\n\n var array = new char[str.Length];\n int idx = 0;\n for (int i = 0; i < str.Length - spaceCount; i++)\n {\n var current = str[i];\n if (current == ' ')\n {\n array[idx++] = '%';\n array[idx++] = '2';\n array[idx++] = '0';\n }\n else \n {\n array[idx++] = current ;\n }\n }\n\n var encoded = new string(array);\n</code></pre>\n\n<p>Space required is 2 * O(n) (array and final string) and time is 2 * O(n) (encoding string into array, building final string)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T00:37:11.900",
"Id": "52863",
"Score": "1",
"body": "Saying that something is 2 * O(n) doesn't make much sense. You can either calculate how man times some specific operations happens (e.g. 2n array accesses) or you can say that it's O(n), but it doesn't make sense to combine the two. That's because 2 * O(n) means exactly the same thing as O(n)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T01:29:01.317",
"Id": "52865",
"Score": "0",
"body": "@svick: While in the theoretical world O(c * n) = c * O(n) = O(n) and c as a constant doesn't matter, in the practical world reducing c can sometimes be a valuable optimization. So I like to state this factor."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T09:35:22.593",
"Id": "52894",
"Score": "0",
"body": "Yes, but the factor you're static doesn't say anything unless you explain it. For example, using your counting, 2 * O(n) could easily be faster than O(n). Constants factors are important, but it's very hard to represent them in a way that makes any sense."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T22:32:31.133",
"Id": "33029",
"ParentId": "33020",
"Score": "1"
}
},
{
"body": "<p>Here's how I would do it (sans assertions/error checks):</p>\n\n<pre><code>private static string Encode(string input)\n{\n var output = new char[input.Length];\n var i = 0;\n var o = 0;\n\n while (o < output.Length)\n {\n if (input[i] != ' ')\n {\n output[o++] = input[i++];\n }\n else\n {\n output[o++] = '%';\n output[o++] = '2';\n output[o++] = '0';\n ++i;\n }\n }\n\n return new string(output);\n}\n</code></pre>\n\n<p>It's <em>O(n)</em> in both time and memory.</p>\n\n<p>Using a <code>StringBuilder</code> doesn't gain you much in this instance, because you know exactly how large your output will be (the same length as your input). It's just a wrapper around a <code>char[]</code> anyway, so you'd end up with slightly slower code without any benefit.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T23:09:29.010",
"Id": "33030",
"ParentId": "33020",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "33029",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T19:51:33.833",
"Id": "33020",
"Score": "2",
"Tags": [
"c#",
"performance",
"strings"
],
"Title": "Function for encoding strings in-place"
}
|
33020
|
<p>I have a <code>select</code> with 3 options and two <code>datepickers</code>, a start and an end date. Based on the option selected, the date end date can either be any future date or limited to a 30 day date range. In the jsFiddle provided below, when Option 1 is selected, the date range is restricted to 30 days. If either Option 2 or Option 3 are selected, the end date can be any future date.</p>
<p>Here is a complete working <a href="http://jsfiddle.net/QcjEt/" rel="nofollow noreferrer"><strong>jsFiddle</strong></a> with the complete code.</p>
<p>I haven't run into any issues with the code below. I'm just wondering if anyone has any suggestions on how I could go about reducing it as it just seems too "bulky".</p>
<pre><code>$('#startDate, #endDate').datepicker({
beforeShow: setDateRange,
dateFormat: "mm/dd/yy",
firstDay: 1,
changeFirstDay: false,
onChange: function() { $(this).valid(); },
onSelect: function() {
if (this.id == 'startDate') {
var date = $('#startDate').datepicker('getDate');
if (date) { date.setDate(date.getDate() + 1); }
$('#endDate').datepicker('option', 'minDate', date);
}
}
});
function setDateRange(input) {
var min = null, dateMin = min, dateMax = null, dayRange = 30;
var opt = $('#select1'), start = $('#startDate'), end = $('#endDate');
if (opt.val() == '1') {
if (input.id == 'startDate') {
if ($('#endDate').datepicker('getDate') != null) {
dateMax = $('#endDate').datepicker('getDate');
dateMin = $('#endDate').datepicker('getDate');
dateMin.setDate(dateMin.getDate() - dayRange);
if (dateMin < min) { dateMin = min; }
}
} else if (input.id == 'endDate') {
dateMin = $('#startDate').datepicker('getDate');
dateMax = new Date(dateMin.getFullYear(),
dateMin.getMonth(), dateMin.getDate() + 30);
if ($('#startDate').datepicker('getDate') != null) {
var rangeMax = new Date(dateMin.getFullYear(),
dateMin.getMonth(), dateMin.getDate() + dayRange);
if (rangeMax < dateMax) { dateMax = rangeMax; }
}
}
} else if (opt.val() != '1') {
if (input.id == 'startDate') {
if ($('#endDate').datepicker('getDate') != null) {
dateMin = null;
}
} else if (input.id == 'endDate') {
dateMin = $('#startDate').datepicker('getDate');
dateMax = null;
if ($('#startDate').datepicker('getDate') != null) { dateMax = null; }
}
}
return {
minDate: dateMin,
maxDate: dateMax
};
}
</code></pre>
<p>I posted this on <a href="https://stackoverflow.com/q/17197868/738262">Stack Overflow</a> a couple months back when I was initially trying to figure out how to get it working. The post goes into a little more detail on the option selections but I have since added on to it some. For example, the code above now includes an <code>onSelect</code> when the <code>datepickers</code> are initialized.</p>
<p>If anyone has any suggestions on how I could go about improving this, please let me know.</p>
|
[] |
[
{
"body": "<p>From a once over;</p>\n\n<ul>\n<li><p>This code does not do what the tin says:</p>\n\n<pre><code>// If selected start date is later than currently selected\n// end date, set end date to start date + 1 day\nvar date = $('#startDate').datepicker('getDate');\nif (date) { date.setDate(date.getDate() + 1); }\n</code></pre>\n\n<p>what this actually does is <em>always</em> set the first possible date to <code>startdate</code> + 1</p></li>\n<li><p>Not sure about this :)</p>\n\n<pre><code><option value=\"2\">Any Future Date</option>\n<option value=\"3\">Any Future Date</option>\n</code></pre></li>\n<li>The continued checks for <code>input.id</code> are a good indication that perhaps you need 2 distinct functions</li>\n<li>The <code>id</code>'s <code>1</code> and <code>2</code> are rather meaningless, they could be meaningful strings, or even better they could be function names that need to be executed.</li>\n<li><p>There a number of non-sensical assignments like here:</p>\n\n<pre><code>dateMax = null;\nif ($('#startDate').datepicker('getDate') != null) { dateMax = null; }\n</code></pre>\n\n<p>if you set <code>dateMax</code> already to <code>null</code>, then why would you set <code>dateMax</code> again to null?</p></li>\n<li>Your code dies when the user tries to select an end date without first selecting first a starting date in 30 days mode with <code>Cannot read property 'getFullYear' of null</code> because you are indeed trying to calculate on an empty field..</li>\n<li>I am not sure why in 30 day mode the start date is impacted by the end date, especially since clearing out the end date opens up the calendar again.</li>\n</ul>\n\n<p>All in all, I would go with something like this:</p>\n\n<pre><code>$('#startDate, #endDate').datepicker({\n beforeShow: setDateRange,\n dateFormat: \"mm/dd/yy\",\n firstDay: 1,\n changeFirstDay: false,\n onChange: function () {\n $(this).valid();\n }\n});\n\nvar dateLogic = {\n\n addDays: function addDays(initialDate, dayCount) {\n var newDate = new Date(initialDate);\n newDate.setDate(newDate.getDate() + dayCount);\n return newDate;\n },\n openWide: {\n minDate: null,\n maxDate: null\n },\n futureDays: {\n startDate: function startDateFutureDays(currentStart, currentEnd) {\n return !currentEnd ? dateLogic.openWide : {\n minDate: null,\n maxDate: dateLogic.addDays(currentEnd, -1)\n }\n },\n endDate: function endDateFutureDays(currentStart) {\n return {\n minDate: currentStart,\n maxDate: null\n }\n }\n },\n thirtyDays: {\n startDate: function startDateThirtyDays(currentStart, currentEnd) {\n return !currentEnd ? dateLogic.openWide : {\n maxDate: currentEnd,\n minDate: dateLogic.addDays(currentEnd, -30)\n };\n },\n endDate: function endDateThirtyDays(currentStart) {\n return !currentStart ? dateLogic.openWide : {\n minDate: currentStart,\n maxDate: dateLogic.addDays(currentStart, 30)\n }\n }\n }\n};\n\nfunction setDateRange(input) {\n\n var opt = $('#select1'),\n startDate = $('#startDate').datepicker('getDate'),\n endDate = $('#endDate').datepicker('getDate');\n\n return dateLogic[opt.val()][input.id](startDate, endDate);\n}\n\n$('#select1').change(function () {\n $('#startDate, #endDate').val('');\n $('#startDate, #endDate').removeAttr('disabled');\n});\n</code></pre>\n\n<p>You can play with this on <a href=\"http://jsfiddle.net/konijn_gmail_com/rc0kr718/\" rel=\"nofollow\">http://jsfiddle.net/konijn_gmail_com/rc0kr718/</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-03T19:54:36.297",
"Id": "118426",
"Score": "0",
"body": "Could not make the snippet work :\\ The insert button seems to do nothing.."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-03T18:31:35.123",
"Id": "64669",
"ParentId": "33022",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "64669",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T20:26:51.703",
"Id": "33022",
"Score": "2",
"Tags": [
"javascript",
"jquery",
"datetime"
],
"Title": "Reduce code handling start and end datepickers"
}
|
33022
|
<p>I have some code to write <code>Error Logs</code> to different places like <code>Console/SignalR Messages/Text File</code>.</p>
<p>The code is as follows:-</p>
<pre><code>public class Logger
{
public void WriteToLog(string message, LogType logType)
{
switch (logType)
{
case LogType.Console:
Console.WriteLine(message);
break;
case LogType.SignalR:
// Code to send message to SignalR Hub
break;
case LogType.File:
// Code to write in .txt file
break;
}
}
}
</code></pre>
<p>Where my <code>LogType</code> is a simple Enum as below:-</p>
<pre><code>public enum LogType
{
Console,
SignalR,
File
}
</code></pre>
<p>But, when I think of Open-Close Principle, I am not getting optimal solution for it.</p>
<p>Edit:</p>
<p>I need to refactor my code as per open close principle. I need to optimize it, so that I don't need to Modify <code>WriteToLog</code> method once any <code>LogType</code> gets added.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T11:32:17.503",
"Id": "52839",
"Score": "1",
"body": "What is the question?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T11:36:51.090",
"Id": "52840",
"Score": "0",
"body": "@Jean-FrançoisCôté:- I need to refactor my code as per open close principle. I need to optimize it, so that I don't need to Modify `WriteToLog` method once any `LogType` gets added."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T12:39:00.930",
"Id": "52841",
"Score": "0",
"body": "I'd say this sounds like a school assignment and you shouldn't shoot yorself in the foot by blindly pasting it here instead of thinking about it yourself and learning something. ;-)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T11:39:54.007",
"Id": "62824",
"Score": "0",
"body": "Look at realisation of this principle in [Log4Net](http://logging.apache.org/log4net/) project. It allow to define appenders in configuration file."
}
] |
[
{
"body": "<p>You should create an interface from which you can make many implementations, e.g. an <code>ILogger</code> interface with <code>Warning</code>, <code>Error</code> methods etc.</p>\n<p>Then you would create an implementation per logging type (one for console, one for SignalR etc). You could then inject the <code>ILogger</code> into any type that requires it (or another approach is to use a static field and resolve the logger through a static log manager type).</p>\n<p>You might also want to consider a library such as <a href=\"http://netcommon.sourceforge.net/\" rel=\"nofollow noreferrer\">Common.Logging</a> which already provides an interface and several implementations already available, e.g. NLog, log4net etc.</p>\n<p>Another consideration is whether you wish to mix business logic and logging code. Other alternatives are an AOP approach (<a href=\"https://www.postsharp.net/\" rel=\"nofollow noreferrer\">PostSharp</a> is one option) or <a href=\"https://docs.microsoft.com/en-us/archive/blogs/agile/embracing-semantic-logging\" rel=\"nofollow noreferrer\">semantic logging</a>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-10-04T11:33:16.443",
"Id": "33024",
"ParentId": "33023",
"Score": "5"
}
},
{
"body": "<p>Create an interface which will implement your logic for Logging:-\nSay:</p>\n\n<pre><code>public interface ILogger {\n void LogMessage(string message);\n }\n</code></pre>\n\n<p>Create a new class for all message type in place of Enum, later stages if any new LogType gets added, respective class can be included without changing your existing Logic:</p>\n\n<pre><code>public class SignalRLogger : ILogger\n {\n public void LogMessage(string message)\n {\n throw new NotImplementedException();//your Implementaion here\n }\n }\n</code></pre>\n\n<p>Now, your implementation would be very similar as below:-</p>\n\n<pre><code>public class Logger\n {\n ILogger _logger;\n\n public Logger(ILogger messageLogger)\n {\n _logger = messageLogger;\n }\n\n public void Log(string message)\n {\n _logger.LogMessage(message);\n }\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T12:02:04.647",
"Id": "33026",
"ParentId": "33023",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "33026",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-04T11:30:54.590",
"Id": "33023",
"Score": "1",
"Tags": [
"c#",
"object-oriented"
],
"Title": "Refactoring based on OPEN CLOSE PRINCIPLE- C#"
}
|
33023
|
<p>I have a some classes and interface</p>
<pre><code>public interface IGeoObject
{
GeoCoordinate GetGeocoordinate();
}
public class User : IGeoObject
{
public GeoCoordinate GetGeocoordinate()
{
//...
return GeoCoordinate;
}
}
public class Venue : IGeoObject
{
public GeoCoordinate GetGeocoordinate()
{
//...
return GeoCoordinate;
}
}
public class Place : IGeoObject
{
public GeoCoordinate GetGeocoordinate()
{
//...
return GeoCoordinate;
}
}
</code></pre>
<p>I have, example variable users with type <code>List<User></code></p>
<p>And I have method with signature </p>
<pre><code>double GetMinDistance(List<IGeoObject> objects, GeoCoordinate position)
</code></pre>
<p>I can't pass users to <code>GetMinDistance</code>, because covariance of generic types not work.</p>
<p>I can create additional list and use method <code>.ConvertAll</code> (or <code>.CasT<T></code>):</p>
<pre><code>List<IGeoObject> list = new List<User>(listUser).ConvertAll(x => (IGeoObject)x);
var dist = GeoTest.GetMinDistance(list, position);
</code></pre>
<p>I'm not sure that this is the most elegant solution. Most embarrassing that the <strong>caller must do this conversion</strong>.</p>
<p>This is similar to my problems in the architecture? There are more elegant solutions?</p>
<p>P.S. Long story, but I really can not give the coordinates of the same species in all classes.</p>
|
[] |
[
{
"body": "<p>You can make <code>GetMinDistance</code> generic:</p>\n\n<pre><code>double GetMinDistance<T>(IList<T> objects, GeoCoordinate position)\n where T: IGeoObject\n{ \n // ...\n}\n</code></pre>\n\n<p>You can use it like this:</p>\n\n<pre><code>List<User> user = ....;\n\nGetMinDistance(user, position);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T23:47:37.473",
"Id": "33032",
"ParentId": "33031",
"Score": "5"
}
},
{
"body": "<p>Covariance works only when it's safe and only on interfaces (and delegates, but that's not relevant here). So, if you wanted to take advantage of it, you would have to declare <code>GetMinDistance()</code> like this:</p>\n\n<pre><code>double GetMinDistance(IEnumerable<IGeoObject> objects, GeoCoordinate position)\n</code></pre>\n\n<p>Instead of <code>IEnumerable</code>, you could use <code>IReadOnlyList</code> if you're on .Net 4.5.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T01:01:12.300",
"Id": "33033",
"ParentId": "33031",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "33033",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-21T23:13:10.720",
"Id": "33031",
"Score": "1",
"Tags": [
"c#",
".net",
"generics"
],
"Title": "Covariance in generic collections"
}
|
33031
|
<p>Following up on <a href="https://codereview.stackexchange.com/questions/32618/listt-implementation-for-vb6-vba">List<T> implementation for VB6/VBA</a>, I'd like some thoughts about the revisited <code>IsTypeSafe</code> function, below.</p>
<p>The previous version pretty much implemented VB.net's <code>Option Strict</code> setting, by only allowing <em>widening</em> numeric type conversions, and preventing implicit conversion between numeric and string data types. This one is more permissive, to a point where I'm torn between ease of use (VB6 isn't .net!) and correctness (it's twisting <code>Option Strict</code> by allowing implicit conversions of <em>in-range</em> values, i.e. a <code>Long</code> with a value of <code>32</code> could be added to a <code>List<Byte></code>... <strong>does that help or hinder usability?</strong>).</p>
<p>Given the following private type where <code>TItem</code> is the type name of <code>T</code> in <code>List<T></code>...</p>
<pre class="lang-vb prettyprint-override"><code>Private Type tList
Encapsulated As Collection
TItem As String
OptionStrict As Boolean
End Type
Private this As tList
</code></pre>
<p>The <code>IsTypeSafe</code> method's behavior depends on the values of <code>this.OptionStrict</code> and <code>this.TItem</code>:</p>
<ul>
<li>When <em>this.OptionStrict = True</em> (the default value; can be modified through a public property), then <code>IsTypeSafe</code> only returns <code>True</code> when the type of <code>value</code> matches exactly with that of <code>this.TItem</code>.</li>
<li>When <em>this.OptionStrict = False</em>, then <code>IsTypeSafe</code> returns <code>True</code> if <code>value</code> can be legally converted to the type specified by <code>this.TItem</code>; if the value <em>can</em> be converted, it <em>is</em> converted, so as to avoid having a <code>List<Integer></code> with <code>Byte</code> values...</li>
<li>When <em>this.TItem = vbNullString</em>, then <code>IsTypeSafe</code> returns <code>True</code> systematically, and then <code>this.TItem</code> becomes the type name of <code>value</code>.</li>
</ul>
<pre class="lang-vb prettyprint-override"><code>Public Function IsTypeSafe(value As Variant) As Boolean
'Determines whether a value can be safely added to the List.
IsTypeSafe = this.TItem = vbNullString Or this.TItem = TypeName(value)
If IsTypeSafe Or this.OptionStrict Then Exit Function
Select Case this.TItem
Case "String":
IsTypeSafe = IsSafeString(value)
If IsTypeSafe Then value = CStr(value)
Case "Boolean"
IsTypeSafe = IsSafeBoolean(value)
If IsTypeSafe Then value = CBool(value)
Case "Byte":
IsTypeSafe = IsSafeByte(value)
If IsTypeSafe Then value = CByte(value)
Case "Date":
IsTypeSafe = IsSafeDate(value)
If IsTypeSafe Then value = CDate(value)
Case "Integer":
IsTypeSafe = IsSafeInteger(value)
If IsTypeSafe Then value = CInt(value)
Case "Long":
IsTypeSafe = IsSafeLong(value)
If IsTypeSafe Then value = CLng(value)
Case "Single"
IsTypeSafe = IsSafeSingle(value)
If IsTypeSafe Then value = CSng(value)
Case "Double":
IsTypeSafe = IsSafeDouble(value)
If IsTypeSafe Then value = CDbl(value)
Case "Currency":
IsTypeSafe = IsSafeCurrency(value)
If IsTypeSafe Then value = CCur(value)
Case Else:
IsTypeSafe = False
End Select
ErrHandler:
'swallow overflow errors:
If Err.Number = 6 Then
Err.Clear
IsTypeSafe = False
End If
End Function
</code></pre>
<p>The method uses a bunch of <code>IsSafe[Type](value As Variant) As Boolean</code> functions that are quite redundant - would there be a clever way to shorten that up?</p>
<pre class="lang-vb prettyprint-override"><code>Private Function IsSafeString(value As Variant) As Boolean
On Error Resume Next
Dim result As String
result = CStr(value) 'assigning value would be an undesirable side-effect here!
IsSafeString = (Err.Number = 0)
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeDate(value As Variant) As Boolean
On Error Resume Next
Dim result As Date
result = CDate(value) 'assigning value would be an undesirable side-effect here!
IsSafeDate = (Err.Number = 0)
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeByte(value As Variant) As Boolean
On Error Resume Next
Dim result As Byte
result = CByte(value) 'assigning value would be an undesirable side-effect here!
IsSafeByte = (Err.Number = 0)
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeBoolean(value As Variant) As Boolean
On Error Resume Next
Dim result As Boolean
result = CBool(value) 'assigning value would be an undesirable side-effect here!
IsSafeBoolean = (Err.Number = 0)
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeCurrency(value As Variant) As Boolean
On Error Resume Next
Dim result As Currency
result = CCur(value) 'assigning value would be an undesirable side-effect here!
IsSafeCurrency = (Err.Number = 0)
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeInteger(value As Variant) As Boolean
On Error Resume Next
Dim result As Integer
result = CInt(value) 'assigning value would be an undesirable side-effect here!
IsSafeInteger = (Err.Number = 0)
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeLong(value As Variant) As Boolean
On Error Resume Next
Dim result As Long
result = CLng(value) 'assigning value would be an undesirable side-effect here!
IsSafeLong = (Err.Number = 0)
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeDouble(value As Variant) As Boolean
On Error Resume Next
Dim result As Double
result = CDbl(value) 'assigning value would be an undesirable side-effect here!
IsSafeDouble = (Err.Number = 0)
Err.Clear
On Error GoTo 0
End Function
Private Function IsSafeSingle(value As Variant) As Boolean
On Error Resume Next
Dim result As Single
result = CSng(value) 'assigning value would be an undesirable side-effect here!
IsSafeSingle = (Err.Number = 0)
Err.Clear
On Error GoTo 0
End Function
</code></pre>
<hr>
<p>This <code>IsTypeSafe</code> function is called by this code:</p>
<blockquote>
<pre class="lang-vb prettyprint-override"><code>Private Function ValidateItemType(value As Variant)
If this.ItemTypeName = vbNullString Then this.ItemTypeName = TypeName(value)
ValidateItemType = IsTypeSafe(value)
End Function
</code></pre>
</blockquote>
<p>Which is called whenever an item is tentatively added to the "type-safe" list:</p>
<blockquote>
<pre class="lang-vb prettyprint-override"><code>Public Sub Add(value As Variant)
'Adds an object to the end of the List.
If Not ValidateItemType(value) Then RaiseErrorUnsafeType "Add()", TypeName(value)
this.Encapsulated.Add value
End Sub
</code></pre>
</blockquote>
<p>This mechanism means the <code>List</code> is a <code>List<Variant></code> until an item is added to it, and then if a <code>Smurf</code> instance is added, the list becomes a <code>List<Smurf></code> and will fail to add anything other than a <code>Smurf</code> object.</p>
<hr>
<p>Here's a little "test" method if you want to see the list in action:</p>
<pre class="lang-vb prettyprint-override"><code>Public Sub TestList()
Dim lst As New List, tmp As List, i As Long
On Error GoTo ErrHandler
lst.Add 1, 2, 3, 4, 8
Debug.Print lst.ToString & " contains " & lst.Count & " items:"
GoSub EnumerateToDebugOutput
lst.OptionStrict = False
Debug.Print "OptionStrict = " & CStr(lst.OptionStrict)
Debug.Print "OptionStrict set to FALSE should not allow overflow values:"
Debug.Print lst.ToString & " can take value 32768? (" & TypeName(32768) & ") : " & lst.IsTypeSafe(32768)
'lst.Add 32768
Debug.Print
Debug.Print "OptionStrict set to FALSE should implicitly convert a value that can be safely converted to the type of the list:"
On Error Resume Next
Debug.Print "Adding value CByte(16)..."
lst.Add CByte(16)
On Error GoTo 0
GoSub EnumerateToDebugOutput
lst.OptionStrict = True
Debug.Print
Debug.Print "OptionStrict = " & CStr(lst.OptionStrict)
Debug.Print "OptionStrict set to TRUE should not allow implicit conversion and throw an error if types mismatch:"
On Error GoTo ErrHandler
Debug.Print "Adding value CByte(32)..."
lst.Add CByte(32)
ErrHandler:
If Err.Number <> 0 Then
Debug.Print "Number: " & Err.Number
Debug.Print "Message: " & Err.Description
Debug.Print "Source: " & Err.Source
Debug.Print "Content:"
GoSub EnumerateToDebugOutput
Resume Next
End If
Exit Sub
EnumerateToDebugOutput:
For i = 1 To lst.Count
Debug.Print lst(i) & " (" & TypeName(lst(i)) & ")"
Next
Debug.Print
Return
End Sub
</code></pre>
<p>...And the generated output:</p>
<pre class="lang-vb prettyprint-override"><code>TestList
List<Integer> contains 5 items:
1 (Integer)
2 (Integer)
3 (Integer)
4 (Integer)
8 (Integer)
OptionStrict = False
OptionStrict set to FALSE should not allow overflow values:
List<Integer> can take value 32768? (Long) : False
OptionStrict set to FALSE should implicitly convert a value that can be safely converted to the type of the list:
Adding value CByte(16)...
1 (Integer)
2 (Integer)
3 (Integer)
4 (Integer)
8 (Integer)
16 (Integer)
OptionStrict = True
OptionStrict set to TRUE should not allow implicit conversion and throw an error if types mismatch:
Adding value CByte(32)...
Number: -2147220503
Message: Type Mismatch. Expected: 'Integer', 'Byte' was supplied.
Source: List<Integer>.ValidateItemType()
Content:
1 (Integer)
2 (Integer)
3 (Integer)
4 (Integer)
8 (Integer)
16 (Integer)
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T13:59:49.873",
"Id": "58118",
"Score": "1",
"body": "reinventing the wheel a bit => the T is very limited though. Instead of all this work you could have used the [vb constants](http://vbadud.blogspot.co.uk/2007/04/get-variable-type.html) for types..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T14:02:30.337",
"Id": "58119",
"Score": "0",
"body": "@mehow Good to see you over here! Feel free to post a review, +100 bounty ends in 4 days :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T14:09:23.520",
"Id": "58121",
"Score": "1",
"body": "not much to review in here except that if you press F2 in VBE and type `vbVarType` you get a list which you could possibly enumerate. That would replace the the select case statement and with a bit of error handling you can easily tell if type is *safe*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T14:19:50.500",
"Id": "58126",
"Score": "0",
"body": "@mehow now you're making me say *if I only knew about these constants before...*"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T15:35:53.037",
"Id": "58139",
"Score": "0",
"body": "@mehow the T can be any type, including any object. That's handled in the first line of the `IsTypeSafe` method - returns true if type names match, the select case is just for edge cases where they don't. I'll see how I can use these constants but I'd love to see an answer that shows it (or I'll have to post my own implementation) :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T15:40:29.020",
"Id": "58141",
"Score": "1",
"body": "post your own:) as a tip consider a collection with enumerated constants-much easier to work with"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T16:58:20.387",
"Id": "58157",
"Score": "0",
"body": "@mehow, his code allows for conversion before returning whether the type is safe or not. I think that is the reason why he would still need the case statement. if trying to input an object of a different type into the list then that might be a different story. but it looks like it will just return false."
}
] |
[
{
"body": "<p>This code looks very clean, </p>\n\n<p>It looks like it handles edge cases well.</p>\n\n<p>I especially like the way that if it converts to the specified data type that it does it and doesn't make you convert explicitly. that is very slick!</p>\n\n<p>I would definitely like to see some code that puts it into play.</p>\n\n<p>Not much to review here, but very good code and good syntax.</p>\n\n<p><strong>Edit</strong></p>\n\n<p>I did find something that I might do differently.</p>\n\n<p>Instead of <code>On Error Resume Next</code> \nI would make it more like a <code>Try Catch</code></p>\n\n<p>Perhaps something like this</p>\n\n<pre><code>Private Function IsSafeDate(value As Variant) As Boolean\n'On Error Resume Next\n On Error GoTo ErrHandler\n\n Dim result As Date\n result = CDate(value) 'assigning value would be an undesirable side-effect here!\n IsSafeDate = True \n Exit Function \n\nErrHandler:\n IsSafeDate = False\nErr.Clear\nEnd Function\n</code></pre>\n\n<p>I think this is a lot clearer as you are not really skating around the errors, and this way you can add an <code>Exit Sub</code> code too if you need it.</p>\n\n<p>I like the <code>Try Catch</code> Method better myself.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T18:29:46.237",
"Id": "57973",
"Score": "1",
"body": "I've added some \"test code\" with generated output :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T17:21:36.613",
"Id": "58161",
"Score": "0",
"body": "@retailcoder is there a way that I can run all that code somewhere nice and simple like so I can play with it a little bit? at work or on a linux machine?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T17:24:18.080",
"Id": "58162",
"Score": "0",
"body": "It should work in VBA - try Excel (Alt+F11) :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-20T17:32:01.150",
"Id": "58166",
"Score": "0",
"body": "You'll have to simulate `this.TItem` if you don't want to copy the whole `List` class from the linked post. That said this linked post has all the code in an easy-copy format in revision 1 (see edit history)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-23T23:14:53.967",
"Id": "58752",
"Score": "2",
"body": "So your answer is essentially that the `IsSafe[Type]` functions are not handling errors in a way that's consistent with the error handling code in the `IsTypeSafe` function (and the rest of the `List` class' code, for that matter) - and you're right! I guess I was just lazy... well sir, you've just earned yourself 100 rep points :)"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-19T18:13:45.370",
"Id": "35707",
"ParentId": "33035",
"Score": "7"
}
},
{
"body": "<p>Just two nitpicks after years. :-)</p>\n\n<p>Regarding the error handling in those <code>IsSafe...</code> procedures:</p>\n\n<p><code>Err.Clear</code> is superfluous there. It is called automatically when a procedure is exited.</p>\n\n<p>The same goes for an enabled error handler, it will be disabled automatically when exiting a procedure, so <code>On Error GoTo 0</code> is not necessary there too.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-09-19T07:27:41.047",
"Id": "176035",
"ParentId": "33035",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "35707",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T02:34:18.370",
"Id": "33035",
"Score": "7",
"Tags": [
"vba",
"type-safety",
"vb6"
],
"Title": "Revisited IsTypeSafe method implementation for \"type-safe\" List"
}
|
33035
|
<p>Okay, here's a challenge at Coderbyte that completely stumped me. I came up with a solution, but I know it is flawed. </p>
<blockquote>
<p>Have the function <code>ArrayAdditionI(arr)</code> take the array of numbers stored in <code>arr</code> and return the string true if any combination of numbers in the array can be added up to equal the largest number in the array, otherwise return the string false. For example: if <code>arr</code> contains [4, 6, 23, 10, 1, 3] the output should return true because 4 + 6 + 10 + 3 = 23. The array will not be empty, will not contain all the same elements, and may contain negative numbers.</p>
</blockquote>
<p>It is easy enough to find the highest value in the array. If the length of the array was fixed, I could probably come up with a way to test various combinations, but I'm not sure how to handle different arrays. I wonder if the solution involves recursion? Or perhaps there is a way to call a function a number of times depending on the size of the array. Anyway, my "solution" is below. I would love to see a real solution, or if anyone wants to give me some hints, I am happy to give it another try.</p>
<pre><code>function ArrayAdditionI(arr) {
var greatest = -100;
var index = -1;
var sum = 0;
for (var i = 0; i<arr.length; i++){
if (arr[i] > greatest){
greatest = arr[i];
index = i;
}
}
arr.splice(i,1)
for (var i = 0; i<arr.length; i++){
sum += arr[i];
if (greatest = sum){
return true;
}else{
return false;
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T03:11:57.193",
"Id": "52868",
"Score": "0",
"body": "Do you require that all remaining numbers add up to the max value or any number of one or more of the remaining numbers add up to the max value? Your question is not quite clear on this topic."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T09:36:30.867",
"Id": "52895",
"Score": "0",
"body": "@jfriend00: *\"if any combination of numbers in the array can be added up to equal the largest number\"* has to mean that any number of remaining numbers can be added, as adding all remaining numbers in different arrangements always gives the same sum. Also, the example shows how four of the five remaining numbers are added."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T21:28:08.387",
"Id": "52979",
"Score": "0",
"body": "@Guffa - I read that, but then their own answer they did not even attempt to look at anything but the total of `all` the numbers. Thus I asked for the OP's comment on that which they did not provide. I never understand why someone posts a question and then disappears - not answering clarifying questions that people might ask."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T23:01:45.820",
"Id": "52987",
"Score": "0",
"body": "@jfriend00: The code is not from Coderbyte, it's from the OP. Coderbyte doesn't provide any code. The code doesn't only look at the total of all numbers, it actually checks the sum after each number is added, so in the special case where numbers at the end should be excluded to get the right sum it would actually work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T23:12:12.313",
"Id": "52988",
"Score": "0",
"body": "@Guffa - The code the OP used doesn't come even close to testing if any combination works. I repeat, it isn't entirely clear what the OP wants and the OP has not responded to the question I posted 19 hrs ago. I will move on. No point in wasting my time when the OP won't answer a simple clarifying question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T01:31:43.317",
"Id": "53002",
"Score": "0",
"body": "@jfriend00: I don't think that the OP saw it neccessary to answer your question, as I answered it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T04:43:30.403",
"Id": "53021",
"Score": "0",
"body": "Yes, I'm sorry. When I saw @Guffa's response, I thought the issue was resolved. My understanding is also that the solution can use all or some of the numbers. My code does not get at the solution very well. As I stated, I was stumped by this one."
}
] |
[
{
"body": "<p>First, let's fix the two bugs in the code.</p>\n\n<p>If the array would contain only numbers below -100, your code would think that -100 was the greatest number, located at index -1. That would make the rest of the code remove the last item of the array instead of the greatest one, and try to sum up the remaining to be -100.</p>\n\n<p>Start with the first item as the greatest instead of -100:</p>\n\n<pre><code>var greatest = arr[0];\nvar index = 0;\n\nfor (var i = 1; i < arr.length; i++){\n if (arr[i] > greatest){\n greatest = arr[i];\n index = i;\n }\n}\n</code></pre>\n\n<p>(That bug would however not change the outcome, as an array of numbers below -100 can't be combined to give the sum -100, and an array of all negative numbers can't form a sum according to the specification.)</p>\n\n<p>The splice is using the variable <code>i</code> instead of <code>index</code>. It should be:</p>\n\n<pre><code>arr.splice(index, 1)\n</code></pre>\n\n<p>Using recursion is a good idea to find a combination. You can make a function that determines if any combination of items from an array can give a specific sum. The function would loop through the items in the array, and call itself to determine if the remaining items could give the sum when the item is subtracted.</p>\n\n<p>Another alternative is to use a bitmask to represent the combinations. If you count from 1 to 2^arr.length-1 you will get all possible combinations. The bitmask 11101 (decimal 29) would give the winning combination [4, 6, 10, 3] from the array [4, 6, 10, 1, 3].</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T13:45:11.697",
"Id": "52912",
"Score": "0",
"body": "This is great! Thanks, I'll work on it again over the next few days and see what I can come up with. If you have any suggestions on simple and concrete introductions to recursion, please pass them along. I have reviewed several sources, but they often present the idea in a mathematical or pseudocode format, which makes it even more impenetrable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T19:56:51.580",
"Id": "52962",
"Score": "0",
"body": "@Nathan: **Re·cur·sion** [n] See recursion. ;) Perhaps a hands-on introduction like this is what you are looking for: http://www.codecademy.com/courses/javascript-lesson-205 A little basic to begin with, but it shows recursion using actual code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-07T22:32:30.347",
"Id": "75694",
"Score": "1",
"body": "@Guffa Off-topic, but if you google \"recursion\", Google will say \"Did you mean 'recursion'?\" ;)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T10:05:48.027",
"Id": "33056",
"ParentId": "33036",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T03:04:29.030",
"Id": "33036",
"Score": "2",
"Tags": [
"javascript",
"array",
"mathematics",
"programming-challenge"
],
"Title": "Testing if numbers in the array can be added up to equal the largest number in the array"
}
|
33036
|
<p>I am currently working on a game and found myself in need of an event handler. I wrote an event handler similar to this one some time ago, but decided to update it using variadic templates (this is my first time using them). I really wanted something with the simple usage that C# events provide. I found some examples that emulate that usage very well, but were a bit more complex than I'd like.</p>
<p>If anyone has any tips for improving this header-only event handling system, or spots any glaring flaws, I would really appreciate it.</p>
<pre><code>#ifndef _EVENT_HANDLER_H_
#define _EVENT_HANDLER_H_
#include <list>
namespace Utilities
{
template <typename... Args>
class Event;
///////////////////////////////////////////////////////////////////////////////////////////
// DelegateContainer
///////////////////////////////////////////////////////////////////////////////////////////
template <typename... Args>
class DelegateContainer
{
friend class Event<Args...>;
protected:
std::list<Event<Args...>*> _subscriptions;
public:
DelegateContainer() { }
DelegateContainer(const DelegateContainer& d)
{ _subscriptions.assign(d._subscriptions.begin(), d._subscriptions.end()); }
DelegateContainer(DelegateContainer&& d)
{
_subscriptions.assign(d._subscriptions.begin(), d._subscriptions.end());
d._subscriptions.clear();
}
~DelegateContainer();
DelegateContainer& operator=(const DelegateContainer& d)
{
_subscriptions.assign(d._subscriptions.begin(), d._subscriptions.end());
return *this;
}//operator=
DelegateContainer& operator=(DelegateContainer&& d)
{
_subscriptions.assign(d._subscriptions.begin(), d._subscriptions.end());
d._subscriptions.clear();
return *this;
}//operator=
virtual bool operator()(Args...) = 0;
};
///////////////////////////////////////////////////////////////////////////////////////////
// Delegate
///////////////////////////////////////////////////////////////////////////////////////////
template <typename T, typename... Args>
class Delegate final : public DelegateContainer<Args...>
{
private:
T* _t;
void (T::*_callback)(Args...);
public:
Delegate() : _t(0),
_callback(0)
{ }
Delegate(T* t, void(T::*callback)(Args...)) : _t(t),
_callback(callback)
{ }
Delegate(const Delegate& d) : _t(d._t),
_callback(d._callback)
{ }
Delegate(Delegate&& d) : _t(d._t),
_callback(d._callback)
{
_subscriptions.assign(d._subscriptions.begin(), d._subscriptions.end());
d._subscriptions.clear();
}
~Delegate() { }
Delegate& operator=(const Delegate& d)
{
_subscriptions.assign(d._subscriptions.begin(), d._subscriptions.end());
_callback = d._callback;
_t = d._t;
return *this;
}//operator=
Delegate& operator=(Delegate&& d)
{
_subscriptions.assign(d._subscriptions.begin(), d._subscriptions.end());
d._subscriptions.clear();
_callback = d._callback;
_t = d._t;
return *this;
}//operator=
public:
bool operator()(Args... args)
{
if (_t && _callback)
{
((*_t).*(_callback))(args...);
return true;
}
return false;
}//operator()
};
///////////////////////////////////////////////////////////////////////////////////////////
// Event
///////////////////////////////////////////////////////////////////////////////////////////
template <typename... Args>
class Event
{
private:
std::list<DelegateContainer<Args...>*> _delegates;
public:
Event() { }
Event(const Event& e)
{ _delegates.assign(e._delegates.begin(), e._delegates.end()); }
Event(Event&& e)
{
_delegates.assign(e._delegates.begin(), e._delegates.end());
e._delegates.clear();
}
~Event()
{
auto itr = _delegates.begin();
while(itr != _delegates.end())
(*itr++)->_subscriptions.remove(this);
}
Event& operator=(const Event& e)
{
_delegates.assign(e._delegates.begin(), e._delegates.end());
return *this;
}//operator=
Event& operator=(Event&& e)
{
_delegates.assign(e._delegates.begin(), e._delegates.end());
e._delegates.clear();
return *this;
}//operator=
Event& operator+=(DelegateContainer<Args...>& d)
{
d._subscriptions.push_back(this);
_delegates.push_back(&d);
return *this;
}//operator+=
Event& operator-=(DelegateContainer<Args...>& d)
{
d._subscriptions.remove(this);
_delegates.remove(&d);
return *this;
}//operator-=
void operator()(Args... args)
{
auto itr = _delegates.begin();
while(itr != _delegates.end())
if ((*itr)->operator()(args...))
itr++;
else
itr = _delegates.erase(itr);
}//operator()
};
///////////////////////////////////////////////////////////////////////////////////////////
// DelegateContainer destructor
///////////////////////////////////////////////////////////////////////////////////////////
template <typename... Args>
DelegateContainer<Args...>::~DelegateContainer()
{
auto itr = _subscriptions.begin();
while(itr != _subscriptions.end())
(*itr++)->operator-=(*this);
}
}//Utilities
#endif // _EVENT_HANDLER_H_
</code></pre>
<p>The <code>DelgateContainer</code> is used as a base for <code>Delegate</code> so the <code>Event</code> can call <code>Delegate</code>s without any knowledge of the object the <code>Delegate</code> belongs to.</p>
<p><code>~DelegateContainer()</code> is defined at the end because it needs to be able to unsubscribe from any <code>Event</code>s it is subscribed to before destruction.</p>
<p>Use case:</p>
<pre><code>#include <iostream>
#include "EventHandler.h"
using namespace Utilities;
class Activator
{
public:
Event<int, char> _myEvent;
Activator() { }
void Update()
{
_myEvent(1, 'A');
std::cout << std::endl;
}//Update
};
class Listener
{
public:
int _i;
Delegate<Listener, int, char> _myDelegate;
Listener(int i) : _i(i)
{
_myDelegate = Delegate<Listener, int, char>(this, &Listener::DelegateMethod);
}
void DelegateMethod(int i, char c)
{
std::cout << ' ' << i * _i << ' ' << c << std::endl;
}//DelegateMethod
};
int main(int argc, char* argv[])
{
Activator activator;
Listener listener0 = Listener(0);
Listener listener1 = Listener(1);
Listener* listener2 = new Listener(2);
activator._myEvent += listener0._myDelegate;
activator._myEvent += listener1._myDelegate;
activator._myEvent += listener2->_myDelegate;
activator.Update();
activator._myEvent -= listener0._myDelegate;
activator.Update();
activator._myEvent += listener0._myDelegate;
activator.Update();
delete listener2;
activator.Update();
return 0;
}
</code></pre>
<p>The use case has the following output:</p>
<blockquote>
<pre><code>0 A
1 A
2 A
1 A
2 A
1 A
2 A
0 A
1 A
0 A
</code></pre>
</blockquote>
|
[] |
[
{
"body": "<p>In no particular order:</p>\n\n<ol>\n<li><p>Normally, you shouldn't define your own copy and move constructors and assignment operators unless you need special processing in them. Which in your case you don't; the implicitly generated ones will do exactly what you need. So just remove them and with them, a potential source of bugs or inefficiencies.</p>\n\n<p>Unfortunately, this doesn't hold if you're also targetting Visual Studio and need efficient moves, because their compiler does not generate implicit move constructors and move assignment operators (even 2013 won't do that :-( ). So if you're targetting VS as well, you'll have to provide them. I will assume you do, and comment on the ones you have.</p>\n\n<p>In constructors, you should prefer initialising to assignment or modification, and you should re-use existing functionality whenever possible. So the copy & move constructors for <code>DelegateContainer</code>, for example, would be better written like this:</p>\n\n<pre><code>DelegateContainer(const DelegateContainer& d)\n : _subscriptions(d._subscriptions)\n{}\n\nDelegateContainer(DelegateContainer&& d)\n : _subscriptions(std::move(d._subscriptions))\n{}\n</code></pre>\n\n<p>The same notes on reuse hold for the assignment operators as well:</p>\n\n<pre><code>DelegateContainer& operator= (const DelegateContainer& d)\n{\n _subscriptions = d._subscriptions;\n return *this;\n}\n\nDelegateContainer& operator= (DelegateContainer&& d)\n{\n _subscriptions = std::move(d._subscriptions);\n return *this;\n}\n</code></pre>\n\n<p>It's doubly important to do proper reuse in derived classes. For example, you've forgotten to copy the subscriptions in <code>Delegate</code>'s copy constructor. So simply do this instead:</p>\n\n<pre><code>Delegate(const Delegate& d)\n : DelegateContainer<Args...>(d)\n , _t(d._t)\n , _callback(d._callback)\n{}\n\nDelegate(Delegate&& d)\n : DelegateContainer<Args...>(std::move(d))\n , _t(std::move(d._t))\n , _callback(std::move(d._callback))\n{}\n\nDelegate& operator= (const Delegate& d)\n{\n DelegateContainer<Args...>::operator= (d);\n _t = d._t;\n _callback = d._callback;\n return *this;\n}\n\nDelegate& operator= (Delegate&& d)\n{\n DelegateContainer<Args...>::operator= (std::move(d));\n _t = std::move(d._t);\n _callback = std::move(d._callback);\n return *this;\n}\n</code></pre>\n\n<p>This analogously applies to copy and move members of <code>Event</code> as well, of course. As an alterantive for basically duplicating the constructor functionality in the assignment operators, you can look at the <a href=\"https://stackoverflow.com/q/3279543/1782465\">copy and swap idiom</a>.</p>\n\n<p>Again, you only have to do this if you're targeting Visual Studio. Otherwise, just remove all of those member functions and the compiler will generate precisely the above code for you.</p>\n\n<p>There is also the question whether you actually need the efficiency of moves. It might turn out it's not such a performance hit (how often are you going to copy delegates?) and the reduced maintenance could offset that, so you could decide to drop the copy and move members altogether and simply accept the sub-optimal performance under VS.</p></li>\n<li><p>Readability of <code>Delegate::operator()</code> could be improved. And you should use forwarding inside, otherwise the call will fail if any callback has a parameter of r-value reference type.</p>\n\n<pre><code>void operator() (Args... args)\n{\n if (_t && _callback)\n {\n (_t->*_callback)(std::forward<Args>(args)...);\n return true;\n }\n return false;\n}\n</code></pre>\n\n<p>The same comments on forwarding apply to <code>Event::operator()</code> as well, of course.</p></li>\n<li><p>The destructor of <code>DelegateContainer</code> has a bug. If someone registers the same delegate twice with the same event, it could happen that <code>Event::operator-=</code> will invalidate both the old value of <code>iter</code> and the new one, which means you'd be dereferencing an invalid iterator in the next iteration.</p>\n\n<p>Generally, it's a bad idea to modify a sequence you're iterating over. Instead, implement the destructor like this:</p>\n\n<pre><code>template <typename... Args>\nDelegateContainer::~DelegateContainer()\n{\n while (!_subscriptions.empty())\n *_subscriptions.front() -= *this;\n}\n</code></pre></li>\n<li><p>I can't see how you handle pointer issues when copying/moving events. When an event is copied, the copy gets the original's list of delegates, but these delegates are not notified of also being registered with the event's copy. Consider this code:</p>\n\n<pre><code>auto* d1 = new Delegate(/*some initialisation*/);\nauto* e1 = new Event;\n\n*e1 += *d1;\n //now d1->_subscriptions is [e1]\n //and e1->_delegates is [d1]\nauto* e2 = new Event(*e1);\n //now d1->_subscriptions is [e1]\n //and e1->_delegates is [d1]\n //and e2->_delegates is [d1]\ndelete d1;\n //Removes d1 from all events in d1->_subscriptions\n //So e1->_delegates is []\n //But e2->_delegates is still [d1]\n(*e2)(); //whoops, dereference-after-free of d1!\n</code></pre>\n\n<p>The same holds for retargetting pointers when you move an event as well, of course.</p></li>\n<li><p>Your include guard macro is illegal. Identifiers which start with an underscore followed by an uppercase letter (as well as those containing two consecutive underscores anywhere) are reserved for the compiler & standard library. You're not allowed to use such identifiers in your code.</p></li>\n<li><p>I understand the usage code is for demonstation only, but you should prefer the mem-initialiser list to assignment even there:</p>\n\n<pre><code> Listener(int i) : _i(i), _myDelegate(this, &Listener::DelegateMethod)\n {}\n</code></pre></li>\n<li><p>You could simplify the entire scenario with a slight shift in design: get rid of <code>Delegate</code>, move its funcitonality into <code>DelegateContainer</code>, and use <code>std::function<void (Args...)></code> instead of an object pointer and pointer-to-member-function. You can the implement <code>operator()</code> directly in <code>DelegateContainer</code>, as it will no longer depend on the type of object actually handling the event. Your use case would then change to something like this:</p>\n\n<pre><code>using namespace std::placeholders;\n\nclass Listener\n{\npublic:\n int _i;\n DelegateContainer<int, char> _myDelegate;\n\n Listener(int i) : _i(i), _myDelegate(std::bind(&Listener::DelegateMethod, this, _1, _2))\n {}\n\n void DelegateMethod(int i, char c)\n {\n std::cout << ' ' << i * _i << ' ' << c << std::endl;\n }//DelegateMethod\n};\n</code></pre>\n\n<p>It would have the advantage of allowing other things than non-const non-volatile member functions as event receivers.</p></li>\n<li><p>You might also look into existing solutions (either to use them or to take inspiration from them), such as <a href=\"http://www.boost.org/doc/libs/1_54_0/doc/html/signals2.html\" rel=\"nofollow noreferrer\">Boost.Signals2</a>.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T10:38:05.730",
"Id": "33126",
"ParentId": "33037",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "33126",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T03:09:41.227",
"Id": "33037",
"Score": "4",
"Tags": [
"c++",
"c++11",
"template",
"event-handling",
"variadic"
],
"Title": "Event handler using variadic templates"
}
|
33037
|
<p>Today I've noticed that the source code for a <a href="http://rosettacode.org/wiki/Four_bit_adder#C" rel="nofollow">Boolean adder</a> is very repetitive, so I wrote a Python script to generate the C source code. The script generates an adder of varying size depending on the length of the added numbers, but the script is very hard to read and understand. How can I improve the readability of my script so that others can understand its operation more easily?</p>
<pre><code>number1 = "98530"
number2 = "84309"
number1 = '{0:b}'.format(int(number1))
number2 = '{0:b}'.format(int(number2))
count = len(number1)
number1 = str(number1)
number2 = str(number2)
print """#include <stdio.h>
typedef char pin_t;
#define IN const pin_t *
#define OUT pin_t *
#define PIN(X) pin_t _##X; pin_t *X = & _##X;
#define V(X) (*(X))
#define NOT(X) (~(X)&1)
#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))
void halfadder(IN a, IN b, OUT s, OUT c)
{
V(s) = XOR(V(a), V(b));
V(c) = V(a) & V(b);
}
void fulladder(IN a, IN b, IN ic, OUT s, OUT oc)
{
PIN(ps); PIN(pc); PIN(tc);
halfadder(/*INPUT*/a, b, /*OUTPUT*/ps, pc);
halfadder(/*INPUT*/ps, ic, /*OUTPUT*/s, tc);
V(oc) = V(tc) | V(pc);
}
"""
print "void fourbitsadder(",
for n in range(0,count):
print "IN "+"a"+str(n)+", ",
print "\n\t\t\t\t\t",
for n in range(0,count):
print "IN "+"b"+str(n)+", ",
print "\n\t\t\t\t\t",
for n in range(0,count):
print "OUT "+"o"+str(n)+", ",
print "\n\t\t\t\t\t",
print "OUT overflow)"
print """
{
\tPIN(zero); V(zero) = 0;
"""
print "\t",
for num in range(0,count):
print "PIN(tc"+str(num)+");",
print "\n\tfulladder(/*INPUT*/a0, b0, zero, /*OUTPUT*/o0, tc0);"
for num in range(1,count-1):
print "\t"+"fulladder(/*INPUT*/"+"a"+str(num)+", "+"b"+str(num)+", "+"tc"+str(num-1)+", "+"/*OUTPUT*/"+"o"+str(num)+", "+"tc"+str(num)+");"
print "\tfulladder(/*INPUT*/a"+str(count-1)+", "+"b"+str(count-1)+", "+"tc"+str(count-2)+", /*OUTPUT*/o"+str(count-1)+", "+ "overflow);"
print "}"
print """
int main()
{
"""
print "\t",
for num in range(0,count):
print "PIN(a"+str(num)+");",
print "\n\t",
for num in range(0,count):
print "PIN(b"+str(num)+");",
print "\n\t",
for num in range(0,count):
print "PIN(s"+str(num)+");",
print "\n\t",
print "\n\tPIN(overflow);"
for num in range(0,count):
print "\t"+"V(a"+str(count-num-1)+") = "+str(number1[num])+"; V(b"+str(count-num-1)+") = "+str(number2[num])+";"
print "\n\tfourbitsadder(",
for num in range(0,count):
print "a"+str(num)+", ",
print "\n\t\t\t\t ",
for num in range(0,count):
print "b"+str(num)+", ",
print "\n\t\t\t\t ",
for num in range(0,count):
print "s"+str(num)+", ",
print "overflow);"
print "\tprintf(\""+count*"%d"+" + "+count*"%d"+" = "+(count+1)*"%d"+"\","
print "\t",
for num in range(0,count):
print "V(a"+str((count-1)-num)+"), ",
print "\n\t",
for num in range(0,count):
print "V(b"+str((count-1)-num)+"), ",
print "\n\t",
print "V(overflow),",
for num in range(0,count-1):
print "V(s"+str((count-1)-num)+"), ",
print "V(s0)",
print ");\n"
#print "V(overflow));"
print "\tprintf(\"\\n\");"
print "\treturn 0;"
print "}"
</code></pre>
<p>Here is the C source code that the program generates:</p>
<pre><code>#include <stdio.h>
typedef char pin_t;
#define IN const pin_t *
#define OUT pin_t *
#define PIN(X) pin_t _##X; pin_t *X = & _##X;
#define V(X) (*(X))
#define NOT(X) (~(X)&1)
#define XOR(X,Y) ((NOT(X)&(Y)) | ((X)&NOT(Y)))
void halfadder(IN a, IN b, OUT s, OUT c)
{
V(s) = XOR(V(a), V(b));
V(c) = V(a) & V(b);
}
void fulladder(IN a, IN b, IN ic, OUT s, OUT oc)
{
PIN(ps); PIN(pc); PIN(tc);
halfadder(/*INPUT*/a, b, /*OUTPUT*/ps, pc);
halfadder(/*INPUT*/ps, ic, /*OUTPUT*/s, tc);
V(oc) = V(tc) | V(pc);
}
void fourbitsadder( IN a0, IN a1, IN a2, IN a3, IN a4, IN a5, IN a6, IN a7, IN a8, IN a9, IN a10, IN a11, IN a12, IN a13, IN a14, IN a15, IN a16,
IN b0, IN b1, IN b2, IN b3, IN b4, IN b5, IN b6, IN b7, IN b8, IN b9, IN b10, IN b11, IN b12, IN b13, IN b14, IN b15, IN b16,
OUT o0, OUT o1, OUT o2, OUT o3, OUT o4, OUT o5, OUT o6, OUT o7, OUT o8, OUT o9, OUT o10, OUT o11, OUT o12, OUT o13, OUT o14, OUT o15, OUT o16,
OUT overflow)
{
PIN(zero); V(zero) = 0;
PIN(tc0); PIN(tc1); PIN(tc2); PIN(tc3); PIN(tc4); PIN(tc5); PIN(tc6); PIN(tc7); PIN(tc8); PIN(tc9); PIN(tc10); PIN(tc11); PIN(tc12); PIN(tc13); PIN(tc14); PIN(tc15); PIN(tc16);
fulladder(/*INPUT*/a0, b0, zero, /*OUTPUT*/o0, tc0);
fulladder(/*INPUT*/a1, b1, tc0, /*OUTPUT*/o1, tc1);
fulladder(/*INPUT*/a2, b2, tc1, /*OUTPUT*/o2, tc2);
fulladder(/*INPUT*/a3, b3, tc2, /*OUTPUT*/o3, tc3);
fulladder(/*INPUT*/a4, b4, tc3, /*OUTPUT*/o4, tc4);
fulladder(/*INPUT*/a5, b5, tc4, /*OUTPUT*/o5, tc5);
fulladder(/*INPUT*/a6, b6, tc5, /*OUTPUT*/o6, tc6);
fulladder(/*INPUT*/a7, b7, tc6, /*OUTPUT*/o7, tc7);
fulladder(/*INPUT*/a8, b8, tc7, /*OUTPUT*/o8, tc8);
fulladder(/*INPUT*/a9, b9, tc8, /*OUTPUT*/o9, tc9);
fulladder(/*INPUT*/a10, b10, tc9, /*OUTPUT*/o10, tc10);
fulladder(/*INPUT*/a11, b11, tc10, /*OUTPUT*/o11, tc11);
fulladder(/*INPUT*/a12, b12, tc11, /*OUTPUT*/o12, tc12);
fulladder(/*INPUT*/a13, b13, tc12, /*OUTPUT*/o13, tc13);
fulladder(/*INPUT*/a14, b14, tc13, /*OUTPUT*/o14, tc14);
fulladder(/*INPUT*/a15, b15, tc14, /*OUTPUT*/o15, tc15);
fulladder(/*INPUT*/a16, b16, tc15, /*OUTPUT*/o16, overflow);
}
int main()
{
PIN(a0); PIN(a1); PIN(a2); PIN(a3); PIN(a4); PIN(a5); PIN(a6); PIN(a7); PIN(a8); PIN(a9); PIN(a10); PIN(a11); PIN(a12); PIN(a13); PIN(a14); PIN(a15); PIN(a16);
PIN(b0); PIN(b1); PIN(b2); PIN(b3); PIN(b4); PIN(b5); PIN(b6); PIN(b7); PIN(b8); PIN(b9); PIN(b10); PIN(b11); PIN(b12); PIN(b13); PIN(b14); PIN(b15); PIN(b16);
PIN(s0); PIN(s1); PIN(s2); PIN(s3); PIN(s4); PIN(s5); PIN(s6); PIN(s7); PIN(s8); PIN(s9); PIN(s10); PIN(s11); PIN(s12); PIN(s13); PIN(s14); PIN(s15); PIN(s16);
PIN(overflow);
V(a16) = 1; V(b16) = 1;
V(a15) = 1; V(b15) = 0;
V(a14) = 0; V(b14) = 1;
V(a13) = 0; V(b13) = 0;
V(a12) = 0; V(b12) = 0;
V(a11) = 0; V(b11) = 1;
V(a10) = 0; V(b10) = 0;
V(a9) = 0; V(b9) = 0;
V(a8) = 0; V(b8) = 1;
V(a7) = 1; V(b7) = 0;
V(a6) = 1; V(b6) = 1;
V(a5) = 1; V(b5) = 0;
V(a4) = 0; V(b4) = 1;
V(a3) = 0; V(b3) = 0;
V(a2) = 0; V(b2) = 1;
V(a1) = 1; V(b1) = 0;
V(a0) = 0; V(b0) = 1;
fourbitsadder( a0, a1, a2, a3, a4, a5, a6, a7, a8, a9, a10, a11, a12, a13, a14, a15, a16,
b0, b1, b2, b3, b4, b5, b6, b7, b8, b9, b10, b11, b12, b13, b14, b15, b16,
s0, s1, s2, s3, s4, s5, s6, s7, s8, s9, s10, s11, s12, s13, s14, s15, s16, overflow);
printf("%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d + %d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d = %d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d%d",
V(a16), V(a15), V(a14), V(a13), V(a12), V(a11), V(a10), V(a9), V(a8), V(a7), V(a6), V(a5), V(a4), V(a3), V(a2), V(a1), V(a0),
V(b16), V(b15), V(b14), V(b13), V(b12), V(b11), V(b10), V(b9), V(b8), V(b7), V(b6), V(b5), V(b4), V(b3), V(b2), V(b1), V(b0),
V(overflow), V(s16), V(s15), V(s14), V(s13), V(s12), V(s11), V(s10), V(s9), V(s8), V(s7), V(s6), V(s5), V(s4), V(s3), V(s2), V(s1), V(s0) );
printf("\n");
return 0;
}
</code></pre>
<p>What type of program did I write? Did I write a type of compiler? It generates code in a lower language.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T09:19:45.553",
"Id": "53134",
"Score": "0",
"body": "This code is not ready for review. I'm sure you know how to do better than this!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T17:02:36.447",
"Id": "53162",
"Score": "0",
"body": "@GarethRees I know that the code is not that readable, that is why I am posting it so that I can get suggestions on how to make it more readable, I don't think I understand what you mean."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T17:09:52.217",
"Id": "53164",
"Score": "0",
"body": "Code Review works best if the author makes the code as good as they possibly can *before* submitting it for review. Otherwise we're wasting our time spotting problems that you could have spotted and fixed for yourself. If you're clever enough to write a Python-to-C code generator, you're clever enough to make your code better than this."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T17:17:37.767",
"Id": "53166",
"Score": "0",
"body": "@GarethRees Now I understand what you mean, i will make those changes, Thanks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-04T03:43:09.103",
"Id": "74886",
"Score": "0",
"body": "Since you are asking for a review of the Python code and not the C code, I am removing that tag from this question."
}
] |
[
{
"body": "<p>The C code may not look pretty in this particular case because it's designed to run fast, but the Python code should look beautiful because it's designed to be clearly readable to someone unfamiliar with it. There are a number of things you can do to achieve this.</p>\n\n<h1>Smaller functions</h1>\n\n<p>Break down your code into functions with descriptive names, so the whole process can be seen in a few lines, rather than a few pages. This also makes it easier to spot other ways to improve your code. Ideally each function should only <a href=\"http://en.wikipedia.org/wiki/Unix_philosophy\" rel=\"nofollow\">do one thing</a>. If you have to scroll to read a function, ask yourself whether it is too long. A short function can be grasped even by someone who is seeing your code for the first time:</p>\n\n<pre><code>def c_code(number1, number2):\n return macros() + tailored_code(number1, number2)\n</code></pre>\n\n<h1>Multilines</h1>\n\n<p>Indent multiline expressions to make it clear they are not unrelated separate lines.</p>\n\n<pre><code>print \"\"\"\n {\n \\tPIN(zero); V(zero) = 0;\n \"\"\"\n</code></pre>\n\n<p>rather than</p>\n\n<pre><code>print \"\"\"\n{\n\\tPIN(zero); V(zero) = 0;\n\"\"\"\n</code></pre>\n\n<p>If you want to make more explicit which whitespace is part of the Python code and which is part of the C code, you can use parentheses to continue over several lines:</p>\n\n<pre><code>print(\"{\\n\"\n \"\\tPIN(zero); V(zero) = 0;\"\n )\n</code></pre>\n\n<p>In this case it may be just as readable to simply use one line:</p>\n\n<pre><code>print \"{\\n\\tPIN(zero); V(zero) = 0;\"\n</code></pre>\n\n<p>Any of these is preferable to multiline expressions without indentation.</p>\n\n<h1>Ease of reuse</h1>\n\n<p>If other people want to use your code in a program of their own, they can only use it to print the C program. If your code was in a function that returned a string, you could still call that function to print the string but other people would also be able to call the function to save the string to file or assign the string to a variable (or even pass it directly to a C compiler). Avoiding using print until the end will make the code much easier to reuse (for yourself and others).</p>\n\n<h1>User input</h1>\n\n<p>It appears that you have fixed the two numbers to be added, even though your Python code is already sufficiently general to take an arbitrary two numbers as arguments. Since you've already written the code to handle arbitrary numbers, go ahead and give the user the chance to provide their own numbers. If you have a function that returns a string containing the full C program, say <code>c_code</code>, then you can include something like the following at the very end of your code:</p>\n\n<pre><code># Handle the case where this program is called from the command line.\nif __name__ == '__main__':\n import sys\n arguments = sys.argv\n if len(arguments) == 3:\n print(c_code(arguments[1], arguments[2])\n else:\n print(input_requirements())\n</code></pre>\n\n<p>You might like to think about allowing the C code to take two numbers as arguments too, but this is just a review of the Python code...</p>\n\n<h1>Is this a compiler?</h1>\n\n<p>In answer to your final question, no I wouldn't describe this as a <a href=\"http://en.wikipedia.org/wiki/Compiler\" rel=\"nofollow\">compiler</a>. It doesn't take source code as input. If it took an arbitrary Python program as input, and output a corresponding C program, then it could be described as a compiler. I would describe your code as <a href=\"http://en.wikipedia.org/wiki/Automatic_programming\" rel=\"nofollow\">automatic programming</a> rather than a compiler.</p>\n\n<h1>Correctness</h1>\n\n<p>I'm mainly reviewing for readability and usability but this question occurred to me:</p>\n\n<p>I notice that you only test the length of the binary string for number1. Does your code still work as intended if number1 < number2? </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T16:26:00.543",
"Id": "76756",
"Score": "2",
"body": "I suggest [`textwrap.dedent()`](http://stackoverflow.com/a/2504454/1157100) as a solution to the multiline indentation problem."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-13T12:27:23.427",
"Id": "44251",
"ParentId": "33038",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T03:13:28.907",
"Id": "33038",
"Score": "7",
"Tags": [
"python",
"mathematics"
],
"Title": "Improving readability of Boolean adder generator?"
}
|
33038
|
<p>I've been working on implementing a doubly linked list from scratch in Java, and if anyone has time, could you critique it?</p>
<pre><code>class Node {
Node prev;
Node next;
int data;
public Node(int d) {
data = d;
prev = null;
next = null;
}
}
class LinkedList {
Node head;
public LinkedList() {
head = null;
}
public void insert(int d) {
if (head == null) {
head = new Node(d);
return;
}
if (head.data > d) {
Node holder = head;
Node newNode = new Node(d);
head = newNode;
head.next = holder;
holder.prev = newNode;
return;
}
Node tmpNode = head;
while (tmpNode.next != null && tmpNode.next.data < d) {
tmpNode = tmpNode.next;
}
Node prevTmp = tmpNode;
Node insertedNode = new Node(d);
if (tmpNode.next != null) {
Node nextTmp = tmpNode.next;
insertedNode.next = nextTmp;
nextTmp.prev = insertedNode;
}
prevTmp.next = insertedNode;
insertedNode.prev = prevTmp;
}
public void delete(int d) {
if (head == null) {
System.out.println("The list is empty.");
return;
}
if (head.data == d) {
head = head.next;
if (head != null) {
head.prev = null;
}
return;
}
Node tmpNode = head;
while (tmpNode != null && tmpNode.data != d) {
tmpNode = tmpNode.next;
}
if (tmpNode == null) {
System.out.println("That node does not exist in the list");
return;
}
if (tmpNode.data == d) {
tmpNode.prev.next = tmpNode.next;
if (tmpNode.next != null) {
tmpNode.next.prev = tmpNode.prev;
}
}
}
public void print() {
Node tmpNode = head;
while (tmpNode != null) {
System.out.print(tmpNode.data + " -> ");
tmpNode = tmpNode.next;
}
System.out.print("null");
}
</code></pre>
|
[] |
[
{
"body": "<ol>\n<li><p>Your are creating something similar to <code>java.util.LinkedList</code>, thus it is best practice to use same or similar method names.</p></li>\n<li><p>Your list is sorted. Whenever you search for an element, change this loop:</p>\n\n<pre><code>while (tmpNode != null && tmpNode.data != d) {\n tmpNode = tmpNode.next;\n}\n\nif (tmpNode == null) {\n System.out.println(\"That node does not exist in the list\");\n return;\n}\n</code></pre>\n\n<p>to this:</p>\n\n<pre><code>while (tmpNode != null && tmpNode.data < d) {\n tmpNode = tmpNode.next;\n}\n\nif (tmpNode == null|| tmpNode.data != d) {\n System.out.println(\"That node does not exist in the list\");\n return;\n}\n</code></pre>\n\n<p>It stops whenever the element can't be found.</p></li>\n<li><p>Instead of <code>System.out.println</code>, use a <code>boolean</code> return value to indicate success.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T12:11:48.360",
"Id": "33063",
"ParentId": "33040",
"Score": "2"
}
},
{
"body": "<p>Can use Generics for Node to provide something for more then just ints.</p>\n\n<pre><code>class Node<T> {\n Node prev;\n Node next;\n T data;\n\n public Node(T data) {\n this.data = data;\n prev = null;\n next = null;\n }\n}\n</code></pre>\n\n<p>then same for your linked list implementation. </p>\n\n<pre><code>class LinkedList<T> {\n Node<T> head;\n\n ...\n\n public void insert(T d) {\n if (head == null) {\n head = new Node<T>(d);\n return;\n }\n\n ...\n</code></pre>\n\n<p>Can make T extends Comparable and use comparable interface to compare if they are less/greater than</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T14:47:56.523",
"Id": "33130",
"ParentId": "33040",
"Score": "4"
}
},
{
"body": "<p>The code should be simplified since this is a basic example and it should be clear and simple. \nYou have two variables that aren't actually needed:</p>\n\n<ul>\n<li><p><code>newNode</code>: when inserting smaller than the first.</p></li>\n<li><p><code>prevTmp</code>: when inserting after while. It can be <code>tmpNode</code>.</p></li>\n</ul>\n\n<p>Just remove them and not bother newcomers with looking why you used those.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-14T22:05:27.260",
"Id": "121487",
"Score": "1",
"body": "I think you should elaborate more on your answer, there isn't much here"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-14T20:46:51.180",
"Id": "66678",
"ParentId": "33040",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T04:44:36.453",
"Id": "33040",
"Score": "4",
"Tags": [
"java",
"linked-list"
],
"Title": "Java Doubly Linked List"
}
|
33040
|
<p>I would like a code review to make this code better, clear, and concise. </p>
<p>The problem it's solving is as follows:</p>
<blockquote>
<p>Given a matrix, print the circumference of each of the items. For example:</p>
<pre><code>1 2 3
4 5 6
7 8 9
</code></pre>
<p>should result in </p>
<pre><code>1 : 2 4 5
2 : 1 4 5 6 3
3 : 2 5 6
etc.
</code></pre>
</blockquote>
<p>Also, am I correct in saying the time complexity is O(n<sup>4</sup>)?</p>
<pre><code>public final class PrintCircumference {
private PrintCircumference() {
}
public static void printCircumference(int[][] m) {
if (m == null) {
throw new NullPointerException("The input matrix cannot be null");
}
int row = m.length;
int col = m[0].length;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
System.out.print(m[i][j] + " --> ");
for (int i1 = Math.max(0, i -1); i1 < Math.min(row, i + 2); i1++) {
for (int j1 = Math.max(0, j -1); j1 < Math.min(col, j + 2); j1++) {
if (i1 != i || j1 != j)
System.out.print(m[i1][j1]);
}
}
System.out.println();
}
}
}
public static void main(String[] args) {
int[][] m = { {1, 2, 3},
{4, 5, 6},
{7, 8, 9}, };
printCircumference(m);
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T09:55:15.083",
"Id": "52896",
"Score": "5",
"body": "Complexity is O(rows * cols). For each matrix element in question, the two innermost for-loops will iterate through at most 8 neighbors (plus itself), regardless of the matrix size. Since 9 is a constant factor, you can ignore it in the complexity estimate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T04:50:07.707",
"Id": "53361",
"Score": "0",
"body": "Actually, the output for 2 is _currently_ `1 3 4 5 6`. Do you want it printed in 'counter-clockwise' order, or the current order is fine?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T08:06:48.217",
"Id": "53371",
"Score": "0",
"body": "@Clockwork-Muse That depends: are you a digital or analog clockwork muse? If digital, then row-major order, else counter-clockwise order."
}
] |
[
{
"body": "<p>If you like to reduce loops in your code, you can do it similar to this one:</p>\n\n<pre><code>static void printDirection(int [][]m, int r1, int r2, int col1, int col2, boolean cond)\n{\n System.out.print( m[r1][col1] + \" \" );\n\n if (cond) System.out.print( m[r2][col2] + \" \" );\n}\n\npublic static void PrintCircumference(int [][] m)\n{\n\n int HEIGHT = m.length;\n int WIDTH = m[0].length;\n\n for (int iRow = 0;iRow < HEIGHT; ++iRow)\n {\n\n boolean isRowNotZero = iRow != 0;\n boolean isRowLessHeight_1 = iRow < HEIGHT - 1;\n int iRowPlusOne = iRow + 1;\n int iRowMinusOne = iRow - 1;\n\n for (int iCol = 0;iCol < WIDTH; ++iCol)\n {\n\n boolean isColNotZero = iCol != 0;\n boolean isColLessWidth_1 = iCol < WIDTH - 1;\n int iColPlusOne = iCol + 1;\n int iColMinusOne = iCol - 1;\n\n System.out.print( m[iRow][iCol] + \" : \" );\n //north\n if (isRowNotZero)\n {\n printDirection(m,\n iRowMinusOne,iRowMinusOne,\n iCol, iColMinusOne,\n isColNotZero);\n }\n //west\n if (isColNotZero)\n {\n printDirection(m,\n iRow,iRowPlusOne,\n iColMinusOne, iColMinusOne,\n isRowLessHeight_1);\n }\n //south\n if (isRowLessHeight_1)\n {\n printDirection(m,\n iRowPlusOne,iRowPlusOne,\n iCol, iColPlusOne,\n isColLessWidth_1);\n }\n //east\n if (isColLessWidth_1)\n {\n printDirection(m,\n iRow,iRowMinusOne,\n iColPlusOne, iColPlusOne,\n isRowNotZero);\n }\n\n System.out.println();\n\n }\n System.out.println( \"-->\" );\n }\n}\n</code></pre>\n\n<p>It checks all neighbors counter-clockwise.</p>\n\n<p>It's working, and tested already :)</p>\n\n<p><strong>Update:</strong> Rework the code to be more optimized.</p>\n\n<p>Profiled <a href=\"http://rextester.com\" rel=\"nofollow\">here</a></p>\n\n<p>Yours:</p>\n\n<blockquote>\n <p>Compilation time: 0.73 sec, absolute running time: 0.13 sec, cpu time: 0.09 sec, memory peak: 14 Mb, absolute service time: 0.87 sec (cached)</p>\n</blockquote>\n\n<p>This one:</p>\n\n<blockquote>\n <p>Compilation time: 0.74 sec, absolute running time: 0.14 sec, cpu time: 0.06 sec, memory peak: 14 Mb, absolute service time: 0.89 sec</p>\n</blockquote>\n\n<p>Although a little bit of difference in performance. Still it's up to you. Just a suggestion :)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T04:50:36.727",
"Id": "53362",
"Score": "2",
"body": "Personally, I'd argue that this is _more_ complex. You have more conditions (and are specifically checking for _directions_), and the way that you're specifically calling out rows/columns there is more prone to error (ie, flubbing a minus for a plus). Also, the counter-clockwise thing is due to an error/type in the output, and does not match current behavior... Also, I didn't catch this before, but your diagonal checks have a redundant condition in them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T06:15:06.303",
"Id": "53364",
"Score": "0",
"body": "@Clockwork-Muse I'm sorry for the wrong term I used. I edited my post. And also, counter-clockwise thing is the sequence w/c they were evaluated, I don't think its an error. It can be rearrange to change the direction."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T06:33:23.043",
"Id": "53365",
"Score": "0",
"body": "... that's even worse, frankly. Your variable names are now too cryptic. Additionally, some of the optimizations you're doing are likely to be performed automatically, transparently, by the compiler/JITter."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T03:42:18.853",
"Id": "33312",
"ParentId": "33042",
"Score": "0"
}
},
{
"body": "<p>Hmm, I think there's two things I'd do:</p>\n\n<ol>\n<li>Put the 'neighbors' loops into their own method. </li>\n<li>Potentially, separating the neighbor collection from the actual printing.</li>\n</ol>\n\n<p>(Please note that I've attempted to format this slightly better for SO's display width)</p>\n\n<pre><code>public final class PrintCircumference {\n\n private PrintCircumference() {\n }\n\n public static void printCircumference(int[][] matrix) {\n\n if (matrix == null) {\n throw new NullPointerException(\"The input matrix cannot be null\");\n }\n\n for (int currentRow = 0, \n rowCount = matrix.length, \n columnCount = matrix[0].length; currentRow < rowCount; currentRow++) {\n for (int currentColumn = 0; currentColumn < columnCount; currentColumn++) {\n System.out.println(matrix[currentRow][currentColumn] \n + \" --> \" \n + collectNeighbors(matrix, rowCount, columnCount, currentRow, currentColumn));\n }\n }\n }\n\n private static String collectNeighbors(int[][] matrix, int rowCount, int columnCount, int originCellRow, int originCellColumn) {\n StringBuilder neighbors = new StringBuilder();\n for (int neighborRow = Math.max(0, originCellRow - 1), \n neighborRowLimit = Math.min(rowCount, originCellRow + 2), \n neighborColumnLimit = Math.min(columnCount, originCellColumn + 2); neighborRow < neighborRowLimit; neighborRow++) {\n for (int neighborColumn = Math.max(0, originCellColumn - 1); neighborColumn < neighborColumnLimit; neighborColumn++) {\n if (neighborRow != originCellRow || neighborColumn != originCellColumn) {\n neighbors.append(matrix[neighborRow][neighborColumn]);\n }\n }\n }\n return neighbors.toString();\n }\n\n public static void main(String[] args) {\n\n int[][] m = { { 1, 2, 3 }, \n { 4, 5, 6 }, \n { 7, 8, 9 }, };\n\n printCircumference(m);\n }\n}\n</code></pre>\n\n<p>I've scoped the variables about as tightly as is possible.<br>\nAlso, the original <code>row</code> and <code>column</code> variables are slightly misnamed - they're the count/limit, whereas most developers are probably expecting them to be the 'current' value. In addition, while <code>i</code> is fine for a single loop, when you're explicitly looping over columns/rows, please name your variables as such. Use new methods to let you 'rename variables in context' (something like what I've done with the <code>currentRow</code> -> <code>originCellRow</code>, etc, here). It's also usually a good idea to put brackets on every loop/condition, in case something more needs to be added at some point in the future.</p>\n\n<p>One word of warning - you're not doing enough error-checking here; fixing that is left as an exercise for the reader (for instance, I was unsure if <em>anything</em> should be printed if the matrix wasn't completely square).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-17T17:23:30.353",
"Id": "57657",
"Score": "0",
"body": "Good, but please resist the urge to assign everything in the for-loop initialization. A for-loop should be _about_ something. For example, in your first loop, the update field is `currentRow++`, so just write `for (int currentRow = 0; currentRow < rowCount; currentRow++)`. Similarly, `for (int neighborRow = Math.max(0, originCellRow - 1); neighborRow < neighborRowLimit; neighborRow++)`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T05:41:16.910",
"Id": "33315",
"ParentId": "33042",
"Score": "1"
}
},
{
"body": "<p>Ok, my solution is overengineered... I took this as an exercise on State pattern. The good thing here is that you can add different behaviours in different regions of the matrix. Here it is:</p>\n\n<pre><code>package it.test.refactor;\n\npublic class MatrixExploring {\n\n public static void main(String[] args) {\n int[][] m = { { 1, 2, 3, 4 }, { 5, 6, 7, 8 }, { 9, 10, 11, 12 } };\n new MatrixCircunference(m).explore();\n }\n}\n\nclass MatrixCircunference {\n\n private int[][] matrix;\n\n private int matrixColumns;\n private int matrixRows;\n private int currentColumn;\n private int currentRow;\n\n private MatrixProcessor NORTHWEST;\n private MatrixProcessor NORTH;\n private MatrixProcessor NORTHEAST;\n private MatrixProcessor CENTER;\n private MatrixProcessor WEST;\n private MatrixProcessor EAST;\n private MatrixProcessor SOUTHWEST;\n private MatrixProcessor SOUTH;\n private MatrixProcessor SOUTHEAST;\n private MatrixProcessor processor;\n\n public MatrixCircunference(int[][] m) {\n if (m == null) {\n throw new NullPointerException(\"The input matrix cannot be null\");\n }\n this.matrix = m;\n currentColumn = 0;\n currentRow = 0;\n matrixRows = m.length;\n matrixColumns = m[0].length;\n\n System.out.println(\"Matrix dimensions: \" + matrixColumns + \" - \" + matrixRows);\n if (matrixRows < 3 || matrixColumns < 3) {\n throw new IllegalArgumentException(\"The input matrix must have at least 3 columns and 3 rows\");\n }\n NORTHWEST = new NorthWest();\n NORTH = new North();\n NORTHEAST = new NorthEast();\n CENTER = new Center();\n WEST = new West();\n EAST = new East();\n SOUTHWEST = new SouthWest();\n SOUTH = new South();\n SOUTHEAST = new SouthEast();\n }\n\n public void explore() {\n processor = NORTHWEST;\n while (processor != null) {\n processor.process();\n processor = processor.nextProcessor();\n }\n }\n\n interface MatrixProcessor {\n\n void process();\n\n MatrixProcessor nextProcessor();\n\n }\n\n class NorthWest implements MatrixProcessor {\n\n public void process() {\n System.out.println(matrix[0][0] + \":\\t\" + matrix[0][1] + \"\\t\" + matrix[1][0] + \"\\t\" + matrix[1][1]);\n }\n\n @Override\n public MatrixProcessor nextProcessor() {\n currentColumn = 1;\n return NORTH;\n }\n\n }\n\n class North implements MatrixProcessor {\n\n @Override\n public void process() {\n System.out.println(matrix[0][currentColumn] + \":\\t\" + matrix[0][currentColumn - 1] + \"\\t\"\n + matrix[0][currentColumn + 1] + \"\\t\" + matrix[1][currentColumn - 1] + \"\\t\"\n + matrix[1][currentColumn] + \"\\t\" + matrix[1][currentColumn + 1] + \"\\t\");\n }\n\n @Override\n public MatrixProcessor nextProcessor() {\n currentColumn++;\n if (matrixColumns > currentColumn + 1) {\n return this;\n }\n return NORTHEAST;\n }\n }\n\n class NorthEast implements MatrixProcessor {\n\n @Override\n public void process() {\n System.out.println(matrix[0][currentColumn] + \":\\t\" + matrix[0][currentColumn - 1] + \"\\t\"\n + matrix[1][currentColumn - 1] + \"\\t\" + matrix[1][currentColumn] + \"\\t\");\n }\n\n @Override\n public MatrixProcessor nextProcessor() {\n currentColumn = 0;\n currentRow = 1;\n return WEST;\n }\n }\n\n class West implements MatrixProcessor {\n\n @Override\n public void process() {\n System.out.println(matrix[currentRow][currentColumn] + \":\\t\" + matrix[currentRow - 1][currentColumn] + \"\\t\"\n + matrix[currentRow - 1][currentColumn + 1] + \"\\t\"\n + matrix[currentRow][currentColumn + 1] + \"\\t\" + matrix[currentRow + 1][currentColumn]\n + \"\\t\" + matrix[currentRow + 1][currentColumn + 1] + \"\\t\");\n }\n\n @Override\n public MatrixProcessor nextProcessor() {\n currentColumn = 1;\n return CENTER;\n }\n }\n\n class Center implements MatrixProcessor {\n\n @Override\n public void process() {\n System.out.println(matrix[currentRow][currentColumn] + \":\\t\" + matrix[currentRow - 1][currentColumn - 1]\n + \"\\t\" + matrix[currentRow - 1][currentColumn] + \"\\t\"\n + matrix[currentRow - 1][currentColumn + 1] + \"\\t\"\n + matrix[currentRow][currentColumn - 1] + \"\\t\" + matrix[currentRow][currentColumn + 1]\n + \"\\t\" + matrix[currentRow + 1][currentColumn - 1] + \"\\t\"\n + matrix[currentRow + 1][currentColumn] + \"\\t\"\n + matrix[currentRow + 1][currentColumn + 1] + \"\\t\");\n }\n\n @Override\n public MatrixProcessor nextProcessor() {\n currentColumn++;\n if (matrixColumns > currentColumn + 1) {\n return this;\n }\n return EAST;\n }\n }\n\n class East implements MatrixProcessor {\n\n @Override\n public void process() {\n System.out.println(matrix[currentRow][currentColumn] + \":\\t\" + matrix[currentRow - 1][currentColumn - 1]\n + \"\\t\" + matrix[currentRow - 1][currentColumn] + \"\\t\"\n + +matrix[currentRow][currentColumn - 1] + \"\\t\" + \"\\t\"\n + matrix[currentRow + 1][currentColumn - 1] + \"\\t\"\n + matrix[currentRow + 1][currentColumn] + \"\\t\");\n }\n\n @Override\n public MatrixProcessor nextProcessor() {\n currentColumn = 0;\n currentRow++;\n if (matrixRows > currentRow + 1) {\n return WEST;\n }\n return SOUTHWEST;\n }\n\n }\n\n class SouthWest implements MatrixProcessor {\n\n @Override\n public void process() {\n System.out.println(matrix[currentRow][currentColumn] + \":\\t\" + matrix[currentRow - 1][currentColumn] + \"\\t\"\n + matrix[currentRow - 1][currentColumn + 1] + \"\\t\"\n + matrix[currentRow][currentColumn + 1] + \"\\t\");\n }\n\n @Override\n public MatrixProcessor nextProcessor() {\n currentColumn = 1;\n return SOUTH;\n }\n }\n\n class South implements MatrixProcessor {\n\n @Override\n public void process() {\n System.out.println(matrix[currentRow][currentColumn] + \":\\t\" + matrix[currentRow - 1][currentColumn - 1]\n + \"\\t\" + matrix[currentRow - 1][currentColumn] + \"\\t\"\n + matrix[currentRow - 1][currentColumn + 1] + \"\\t\"\n + matrix[currentRow][currentColumn - 1] + \"\\t\" + matrix[currentRow][currentColumn + 1]);\n }\n\n @Override\n public MatrixProcessor nextProcessor() {\n currentColumn++;\n if (matrixColumns > currentColumn + 1) {\n return this;\n }\n return SOUTHEAST;\n }\n }\n\n class SouthEast implements MatrixProcessor {\n\n @Override\n public void process() {\n System.out.println(matrix[currentRow][currentColumn] + \":\\t\" + matrix[currentRow - 1][currentColumn - 1]\n + \"\\t\" + matrix[currentRow - 1][currentColumn] + \"\\t\"\n + matrix[currentRow][currentColumn - 1] + \"\\t\");\n }\n\n @Override\n public MatrixProcessor nextProcessor() {\n return null;\n }\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T11:07:36.213",
"Id": "33323",
"ParentId": "33042",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "33315",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T06:00:01.950",
"Id": "33042",
"Score": "3",
"Tags": [
"java",
"algorithm",
"matrix"
],
"Title": "Neighbors of a matrix element"
}
|
33042
|
<p>This is a boggle solver in Java. I would like code reviewers to optimize the code, suggest better coding practices, and help make it cleaner.</p>
<p>I am also unsure of the complexity and would appreciate an explanation of it.</p>
<pre><code>public final class Boggle {
private static final NavigableSet<String> dictionary;
private final Map<Character, List<Character>> graph = new HashMap<Character, List<Character>>();
static {
dictionary = new TreeSet<String>();
try {
FileReader fr = new FileReader("/Users/ameya.patil/Desktop/text.txt");
BufferedReader br = new BufferedReader(fr);
String line;
while ((line = br.readLine()) != null) {
dictionary.add(line.split(":")[0]);
}
} catch (Exception e) {
throw new RuntimeException("Error while reading dictionary");
}
}
private Boggle() {}
public static List<String> boggleSolver(char[][] m) {
if (m == null) {
throw new NullPointerException("The matrix cannot be null");
}
final List<String> validWords = new ArrayList<String>();
for (int i = 0; i < m.length; i++) {
for (int j = 0; j < m[0].length; j++) {
solve(m, i, j, m[i][j] + "", validWords);
}
}
return validWords;
}
private static void solve(char[][] m, int i, int j, String prefix, List<String> validWords) {
assert m != null;
assert validWords != null;
for (int i1 = Math.max(0, i - 1); i1 < Math.min(m.length, i + 2); i1++) {
for (int j1 = Math.max(0, j - 1); j1 < Math.min(m[0].length, j + 2); j1++) {
if (i1 != i || j1 != j) {
String word = prefix+ m[i1][j1];
if (dictionary.contains(word)) {
validWords.add(word);
}
if (dictionary.subSet(word, word + Character.MAX_VALUE).size() > 0) {
solve(m, i1, j1, word, validWords);
}
}
}
}
}
public static void main (String[] args) {
char[][] board = { {'a', 'b', 'c', 'd' },
{'n', 'x', 'p', 'q' },
{'k', 't', 'i', 'w' },
{'e', 'f', 'g', 's' },
};
List<String> list = Boggle.boggleSolver(board);
for (String str : list) {
System.out.println(str);
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T08:22:51.950",
"Id": "52888",
"Score": "3",
"body": "Rule of thumb: If you need to suffix your variable names with numbers, you're doing something wrong."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T16:57:15.010",
"Id": "52943",
"Score": "0",
"body": "not too sure that I understand yoru point. please elaborate."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T19:59:07.380",
"Id": "52963",
"Score": "1",
"body": "@JavaDeveloper: Usually, numbers at the end of a variable name are an indication that you really want an array instead of a bunch of separate variables with numbers at the end. Your i1, j1 doesn't fall into this pattern, but it would be better to use i, j for those and something else for the i, j parameters for solve(). (Maybe x/y, height/width, or horizontal_offset/vertical_offset?)"
}
] |
[
{
"body": "<p>According to the <a href=\"http://www.boggle-game.com/rules-boggle.php\" rel=\"nofollow\">rules</a>, you can only use each tile once per word. You haven't attempted to keep track of tile usage.</p>\n\n<p>Consider storing your dictionary using a <a href=\"http://en.wikipedia.org/wiki/Trie\" rel=\"nofollow\">trie</a>, such as the <a href=\"http://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/trie/PatriciaTrie.html\" rel=\"nofollow\">implementation in Apache Commons</a>. It should provide an efficient <a href=\"http://commons.apache.org/proper/commons-collections/apidocs/org/apache/commons/collections4/trie/PatriciaTrie.html#prefixMap(K)\" rel=\"nofollow\"><code>.prefixMap()</code></a>, which is like your <code>dictionary.subSet()</code>.</p>\n\n<p>You defined <code>graph</code>, but you never use it.</p>\n\n<p>I think that an object-oriented interface would feel natural. Create a new instance of <code>Boggle</code> by passing the <code>char[][]</code> matrix to the constructor.</p>\n\n<p>Method names should be verbs, and shouldn't be redundant with the class name. Therefore, <code>.boggleSolver()</code> should just be <code>.solve()</code>.</p>\n\n<p>The purpose of the loop…</p>\n\n<pre><code>for (int i1 = Math.max(0, i - 1); i1 < Math.min(m.length, i + 2); i1++) {\n for (int j1 = Math.max(0, j - 1); j1 < Math.min(m[0].length, j + 2); j1++) {\n if (i1 != i || j1 != j) {\n // loop body\n }\n }\n}\n</code></pre>\n\n<p>… is to iterate through all the neighbours of tile (<em>i</em>, <em>j</em>). A comment to that effect would be appreciated. Also, I would invert the if-condition to avoid a level of nesting:</p>\n\n<pre><code>// Iterate through the neighbours of tile (i, j)\nfor (int i1 = Math.max(0, i - 1); i1 < Math.min(m.length, i + 2); i1++) {\n for (int j1 = Math.max(0, j - 1); j1 < Math.min(m[0].length, j + 2); j1++) {\n // Skip the tile (i, j) itself\n if (i1 == i && j1 == j) continue;\n\n String word = prefix+ m[i1][j1];\n if (!dictionary.subSet(word, word + Character.MAX_VALUE).isEmpty()) {\n if (dictionary.contains(word)) {\n validWords.add(word);\n }\n solve(m, i1, j1, word, validWords);\n }\n}\n</code></pre>\n\n<p>Note that the <code>dictionary.contains(word)</code> check can be moved inside the <code>!dictionary.subSet(...).isEmpty()</code> check.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T16:59:51.290",
"Id": "52944",
"Score": "0",
"body": "Appreciate all suggestions except the one for using \"Trie\" what benefit would it provide compared to TreeSet ? Instead treeSet provides a constant lookup time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T18:18:13.117",
"Id": "52953",
"Score": "0",
"body": "No, `HashSet` provides O(1) lookup time. `TreeSet` does lookup in O(log n) (where n = number of words), and subset in O(s) (where s = size of subset). A trie does lookup in O(c) (where c = number of characters in word), and subset in O(1). I would say that a trie is the perfectly natural data structure for this problem."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T09:41:06.797",
"Id": "33055",
"ParentId": "33045",
"Score": "5"
}
},
{
"body": "<p><strong>Use a factory</strong></p>\n\n<p>Your static initializer for the dictionary has a couple of different ideas trying to come out of it</p>\n\n<p>1) You have non trivial logic to create the object, which implies the existence of a Factory\n2) Your current method is really several different ideas</p>\n\n<ol>\n<li>read lines from a file</li>\n<li>parse the lines to find words</li>\n<li>add the words to a collection</li>\n<li>use the collection of words to create the dictionary</li>\n</ol>\n\n<p>So it looks to me as though there ought to be Factory.create(Collection) somewhere to build that dictionary object. There might also be Factory.create(File) to allow you to change what the default file is, Factory.create(BufferedReader) because you really don't care where that reader comes from, and so on.</p>\n\n<p><strong>Neighbors</strong></p>\n\n<p>Your double loop is really trying to express the idea that the next letter in a candidate word must come from one of the neighboring tiles. So the code should say that:</p>\n\n<pre><code>for (GridPosition nextGridPosition : findNeighbors(crntGridPosition)) {\n ...\n}\n</code></pre>\n\n<p>Of course, you don't have the GridPosition(x,y) abstraction teased out yet, so you need to find that as well. Using the char[][] array to specify your test configuration is fine (not my choice, but it gets the job done), but you have either a Factory that creates the board from the array, or a Board object that can set the state of its Dice (depending on how you choose to represent a new game).</p>\n\n<p>If you were really modeling Boggle, rather than just a generic word finding exercise, then you would need 16 Die objects that are each capable of representing 6 Faces (as only the top face matters, you don't need to worry about the geometry of the faces), and your factory method might need to recognize invalid configurations. If you are ignoring those concerns, then Tile is probably a better abstraction than Die/Face</p>\n\n<p>@200_success points out that the rules prevent you from using a tile more than once. In other words, your word search has state. You might keep track of which die you have used by pushing and popping them out of a stack, or you might notice that what you really have going is a state machine, where the states track what other states are allowed. So the state machine probably knows which positions you have visited, and where the valid neighbors are.</p>\n\n<p>It's probably easiest if the state is also tracking the values of the tiles, but that concern could be separated.</p>\n\n<p>solve() should be iterating through states, not calling itself recursively. You are \"doing the same thing until the search space is exhausted\", not \"breaking the problem into smaller sub problems\". With only 16 tiles, it doesn't matter much, but thinking clearly about what you are really doing may help make the implementation cleaner.</p>\n\n<pre><code>Stack<State> remainingStates = Stacks.create(Board.initialState());\nwhile(! remainingStates.isEmpty()) {\n State state = remainingStates.pop();\n\n String candidate = state.getWord();\n\n if (! dictionary.subSet(candidate, candidate + Character.MAX_VALUE).isEmpty()) {\n if (dictionary.contains(candidate)) {\n validWords.add(candidate);\n }\n remainingStates.pushAll(state.getNeighbors());\n }\n}\n</code></pre>\n\n<p>Bleah, why should the Board code care how dictionary is implemented? The Board wants to know if candidate is a valid word, and if there are any words that begin with candidate. So tease those two ideas into a Dictionary abstraction</p>\n\n<pre><code> if (! dictionary.hasWordsWithPrefix(candidate) {\n if (dictionary.containsWord(candidate)) {\n validWords.add(candidate);\n }\n remainingStates.pushAll(state.getNeighbors());\n }\n</code></pre>\n\n<p>With that abstraction in place, the Board code is insulated from Dictionary and Dictionary, so you can experiment as you like.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T15:17:50.023",
"Id": "33131",
"ParentId": "33045",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "33055",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T06:47:05.353",
"Id": "33045",
"Score": "4",
"Tags": [
"java",
"algorithm",
"recursion"
],
"Title": "Boggle solver in Java"
}
|
33045
|
<p>so, I am pretty new to this game, and am trying to understand javaScript way better than I currently do. I have this block of code, if it is too long to read, then just skip to my question at the bottom...</p>
<pre><code> function createCSSRule(selectorName, necessaryProperties){
//add class to control all divs
var propertyNameBases, propertyPrefixes, propertyValues, propertySuffixes;
var cssString = selectorName + "{\n";
for (var i9 = 0; i9 < necessaryProperties.length; ++i9){
switch (selectorName){
case "."+options.allPictures:
switch(necessaryProperties[i9]){
case "position":
propertyNameBases = ["position"];
propertyPrefixes = [""],
propertyValues = ["absolute"],
propertySuffixes = [""];
break;
case "height":
propertyNameBases = ["height"];
propertyPrefixes = [""],
propertyValues = ["100%"],
propertySuffixes = [""];
break;
case "width":
propertyNameBases = ["width"];
propertyPrefixes = [""],
propertyValues = ["100%"],
propertySuffixes = [""];
break;
case "background":
propertyNameBases = ["background"];
propertyPrefixes = [""],
propertyValues = ["scroll","#fff","50% 50%","no-repeat","cover"],
propertySuffixes = ["-attachment","-color","-position","-repeat","-size"];
break;
case "transform":
propertyNameBases = ["transform"],
propertyPrefixes = ["", "-moz-", "-webkit-"],
propertyValues = [options.threeDOrigin,options.threeDStyle,"translate3d("+options.translate3dpx+")"],
propertySuffixes = ["-origin","-style",""];
break;
case "transition":
propertyNameBases = ["transition"],
propertyPrefixes = ["", "-webkit-"],
propertyValues = [options.transitionLength + "ms", options.transitionPath, "all"],
propertySuffixes = ["-duration","-timing-function","-property"]; //-delay"];
break;
default:
console.log("missing");
propertyNameBases = null;
propertyPrefixes = null;
propertyValues = null;
propertySuffixes = null;
break;
}
break;
case "."+options.currentPic:
switch(necessaryProperties[i9]){
case "transform":
propertyNameBases = ["transform"],
propertyPrefixes = ["", "-moz-", "-webkit-"],
propertyValues = [options.threeDOrigin,"translate3d(0px, 0px, 0px)"],
propertySuffixes = ["-origin",""];
break;
default:
console.log("missing");
propertyNameBases = null;
propertyPrefixes = null;
propertyValues = null;
propertySuffixes = null;
break;
}
break;
case "."+options.currentPic+"."+options.picAfterCurrent:
switch(necessaryProperties[i9]){
case "transform":
propertyNameBases = ["transform"],
propertyPrefixes = ["", "-moz-", "-webkit-"],
propertyValues = [options.threeDOrigin,"translate3d("+options.negativeTranslate3dpx+")"],
propertySuffixes = ["-origin",""];
break;
default:
console.log("missing");
propertyNameBases = null;
propertyPrefixes = null;
propertyValues = null;
propertySuffixes = null;
break;
}
break;
default:
console.log("wait a second");
break;
}
//name the selector
//iterate through properties
for (i10 = 0; i10 < propertyNameBases.length; i10++){
//iterate through suffixes and value pairs
for (var i11 = 0; i11 < propertyValues.length; i11++){
//iterate through prefixes
if(propertyValues !== false){
for (var i12 = 0; i12 < propertyPrefixes.length; i12++){
cssString = cssString+" "+propertyPrefixes[i12]+propertyNameBases[i10]+propertySuffixes[i11]+": "+propertyValues[i11]+";\n"
}
}
}
}
}
var forAllPictures = ["position","height","width","background","transition","transform"];
var forCurrentPic = ["transform"];
var forpicAfterCurrent = ["transform"];
createCSSRule("."+options.allPictures, forAllPictures);
createCSSRule("."+options.currentPic, forCurrentPic);
createCSSRule("."+options.currentPic+"."+options.picAfterCurrent, forpicAfterCurrent);
</code></pre>
<p>basically, what is going to happen is I am going to pass a string (which is in a combination of variables) to the first parameter, and an array to the second. The first parameter acts as my class name, and the second parameter acts as my array of necessary css properties. I have included the output below so you can get a simple understanding of what I am going for. Each array inside of the if statements is used by the i 's in each for loop to output a string.</p>
<p>Each switch statement sets a specific variable and then 3 for-loops take over concatenating a very long string, which happens to be the css below</p>
<pre><code>.slideShowPics{
position: absolute;
height: 100%;
width: 100%;
background-attachment: scroll;
background-color: #fff;
background-position: 50% 50%;
background-repeat: no-repeat;
background-size: cover;
transition-duration: 5000ms;
-webkit-transition-duration: 5000ms;
transition-timing-function: ease-in;
-webkit-transition-timing-function: ease-in;
transition-property: all;
-webkit-transition-property: all;
transform-origin: 0% 0%;
-moz-transform-origin: 0% 0%;
-webkit-transform-origin: 0% 0%;
transform-style: flat;
-moz-transform-style: flat;
-webkit-transform-style: flat;
transform: translate3d(-640px, 0px, 0px);
-moz-transform: translate3d(-640px, 0px, 0px);
-webkit-transform: translate3d(-640px, 0px, 0px);
}
.currentSlideShowPic{
transform-origin: 0% 0%;
-moz-transform-origin: 0% 0%;
-webkit-transform-origin: 0% 0%;
transform: translate3d(0px, 0px, 0px);
-moz-transform: translate3d(0px, 0px, 0px);
-webkit-transform: translate3d(0px, 0px, 0px);
}
.currentSlideShowPic.movingOut{
transform-origin: 0% 0%;
-moz-transform-origin: 0% 0%;
-webkit-transform-origin: 0% 0%;
transform: translate3d(640px, 0px, 0px);
-moz-transform: translate3d(640px, 0px, 0px);
-webkit-transform: translate3d(640px, 0px, 0px);
}
</code></pre>
<p>I would love for someone to suggest an easier way to do this. </p>
<p>I do not feel like I am using this language correctly. If there is anyone out there who has a better idea than what I am currently using, I would love to hear it. </p>
<p>Like I said, I am still learning. </p>
<p>I feel like I should be able to do this with an object, I just have no idea what I am doing when it comes to objects. If anyone has any articles that are written in clean everyday vernacular, or at least some really good examples, I would appreciate that, otherwise your own examples/explainations would be most appreciated. If, of course, I am able to do this with an object...</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T07:09:41.967",
"Id": "52877",
"Score": "0",
"body": "why do you build the properties strings programmatically, though they will always be the same ? why not just store already built strings and pick the ones you need ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T07:12:14.117",
"Id": "52878",
"Score": "0",
"body": "oh, did not see that some have parameters."
}
] |
[
{
"body": "<p>It seems like you are using JavaScript to programmatically change the CSS of your images.</p>\n\n<p>The better approach would be to create all the CSS classes in a CSS file and then just changing the className to that of your CSS class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T10:02:57.107",
"Id": "52897",
"Score": "1",
"body": "Seconded. The point of CSS is to separate the presentation aspects from the code. Theoretically, the CSS should be under the control of the web designers, not programmers. The code should just set classes on elements to activate the relevant rules."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T14:32:03.167",
"Id": "52927",
"Score": "0",
"body": "in this case, this is exactly what I am doing. I am slowly integrating (almost) total control through the plugin input parameters."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T16:28:57.550",
"Id": "52938",
"Score": "1",
"body": "Are you sure? Do you have one separate file for all of your css classes and another javascript file with your function? It seems to me as if you are using javascript to programmatically create and inline all of the css"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T07:37:41.827",
"Id": "33049",
"ParentId": "33046",
"Score": "6"
}
},
{
"body": "<p>You are setting the same sets of variables in many places of the code, so you can refactor that into an object:</p>\n\n<pre><code>function makeArray(value) {\n return typeof value == \"string\" ? [value] : value;\n}\n\nfunction Property(nameBases, prefixes, values, suffixes) {\n this.nameBases = makeArray(nameBases);\n this.prefixes = makeArray(prefixes);\n this.values = makeArray(values);\n this.suffixes = makeArray(suffixes);\n}\n\nfunction createCSSRule(selectorName, necessaryProperties){\n //add class to control all divs\n var property;\n var cssString = selectorName + \"{\\n\";\n for (var i9 = 0; i9 < necessaryProperties.length; ++i9){\n switch (selectorName){\n case \".\"+options.allPictures:\n switch(necessaryProperties[i9]){\n case \"position\":\n property = new Property(\"position\",\"\",\"absolute\",\"\");\n break;\n case \"height\":\n property = new Property(\"height\",\"\",\"100%\",\"\");\n break;\n case \"width\":\n property = new Property(\"width\",\"\",\"100%\",\"\");\n break;\n case \"background\":\n property = new Property(\"background\",\"\",[\"scroll\",\"#fff\",\"50% 50%\",\"no-repeat\",\"cover\"],[\"-attachment\",\"-color\",\"-position\",\"-repeat\",\"-size\"]);\n break;\n case \"transform\":\n property = new Property(\"transform\",[\"\", \"-moz-\", \"-webkit-\"],[options.threeDOrigin,options.threeDStyle,\"translate3d(\"+options.translate3dpx+\")\"],[\"-origin\",\"-style\",\"\"]);\n break;\n case \"transition\":\n property = new Property(\"transition\",[\"\", \"-webkit-\"],[options.transitionLength + \"ms\", options.transitionPath, \"all\"],[\"-duration\",\"-timing-function\",\"-property\"]; //-delay\"]);\n break;\n default:\n console.log(\"missing\");\n property = new Property(null,null,null,null);\n break;\n }\n break;\n case \".\"+options.currentPic:\n switch(necessaryProperties[i9]){\n case \"transform\":\n property = new Property(\"transform\",[\"\", \"-moz-\", \"-webkit-\"],[options.threeDOrigin,\"translate3d(0px, 0px, 0px)\"],[\"-origin\",\"\"]);\n break;\n default:\n console.log(\"missing\");\n property = new Property(null,null,null,null);\n break;\n }\n break;\n case \".\"+options.currentPic+\".\"+options.picAfterCurrent:\n switch(necessaryProperties[i9]){\n case \"transform\":\n property = new Property(\"transform\",[\"\", \"-moz-\", \"-webkit-\"],[options.threeDOrigin,\"translate3d(\"+options.negativeTranslate3dpx+\")\"],[\"-origin\",\"\"]);\n break;\n default:\n console.log(\"missing\");\n property = new Property(null,null,null,null);\n break;\n }\n break;\n default:\n console.log(\"wait a second\");\n break;\n }\n //name the selector\n //iterate through properties\n for (i10 = 0; i10 < property.NameBases.length; i10++){\n //iterate through suffixes and value pairs\n for (var i11 = 0; i11 < property.Values.length; i11++){\n //iterate through prefixes\n if(property.Values !== false){\n for (var i12 = 0; i12 < property.Prefixes.length; i12++){\n cssString += \" \"+property.Prefixes[i12]+property.NameBases[i10]+property.Suffixes[i11]+\": \"+property.Values[i11]+\";\\n\"\n }\n }\n }\n }\n }\n}\n\ncreateCSSRule(\".\"+options.allPictures, [\"position\",\"height\",\"width\",\"background\",\"transition\",\"transform\"]);\ncreateCSSRule(\".\"+options.currentPic, [\"transform\"]);\ncreateCSSRule(\".\"+options.currentPic+\".\"+options.picAfterCurrent, [\"transform\"]);\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T02:18:56.587",
"Id": "33103",
"ParentId": "33046",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T07:01:17.160",
"Id": "33046",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"css"
],
"Title": "create a really long string with javaScript more efficiently than this"
}
|
33046
|
<p>Just ended up with this approach for wp7 (no tag yet), in case someone would find it useful. Also, improvement considerations are welcome.</p>
<p>It works with </p>
<ul>
<li><code>SimpleLogger.WriteLine("JustLine");</code></li>
<li><code>SimpleLogger.WriteLine(ObjectToBeCastedToString);</code></li>
<li><code>SimpleLogger.WriteLine("Price is {0} {1}", price, currency);</code></li>
</ul>
<pre><code>public class SimpleLogger
{
private static DateTime lastLog;
[Conditional("DEBUG")]
public static void WriteLine(object value)
{
WriteLine((value == null) ? "(null)" : value.ToString());
}
[Conditional("DEBUG")]
public static void WriteLine(string format)
{
WriteLine("{0}", format);
}
[Conditional("DEBUG")]
public static void WriteLine(string format, params object[] values)
{
var formatted = String.Format(null, format, values);
Debug.WriteLine("{0:hh:mm:ss.fff} [{1:hh:mm:ss.fff}] {2}", DateTime.UtcNow, DateTime.UtcNow - lastLog, formatted);
lastLog = DateTime.UtcNow;
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T13:35:45.073",
"Id": "52909",
"Score": "1",
"body": "This site is for requesting reviews of your code, not for publishing it."
}
] |
[
{
"body": "<pre><code>(value == null) ? string.Empty : value.ToString()\n</code></pre>\n\n<p>Consider whether something more descriptive would be suitable for <code>null</code>. Maybe something like <code>\"(null)\"</code>.</p>\n\n<pre><code>public static void WriteLine(string format)\n</code></pre>\n\n<p>The name <code>format</code> is confusing here, because it's not actually format string, it's the value to write. So calling it <code>value</code> (like in the <code>object</code> overload) would make more sense. And maybe you don't need <code>string</code> overload at all.</p>\n\n<pre><code>DateTime.Now.ToUniversalTime()\n</code></pre>\n\n<p>You can write just <code>DateTime.UtcNow</code>. And you should do the same for <code>lastLog</code> too (assuming you keep it, see next item).</p>\n\n<pre><code>DateTime.Now - lastLog\n</code></pre>\n\n<p>I'm not sure what is this for. I don't think the time between two consecutive log entries is that interesting, it just clutters the log. And when it is interesting, you can compute the approximate time difference just by looking at it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T14:01:08.077",
"Id": "52916",
"Score": "0",
"body": "Thanks for review!\n1. What do you mean, \"(null)\" ? \n3. Ok, seems simplier\n4. Yep, deltatime between calls is looking quite nice in the second raw. For example, it shows that reading json with 30 items (like 5-7 fields per item) took 0.3 seconds. I'd never think that it can take that much amount of time, so i'd, probably, didnt even look there. Instead, having second raw as deltatime highlights this issues. Anyway, that's minor change everybody can fit themselves."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T14:06:38.630",
"Id": "52918",
"Score": "1",
"body": "@VitaliiVasylenko Ad 1. I meant that when the value is `null`, the logger would make it clear; something like `value == null ? \"(null)\" : value.ToString()`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T13:46:01.657",
"Id": "33068",
"ParentId": "33050",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "33068",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T07:59:48.247",
"Id": "33050",
"Score": "3",
"Tags": [
"c#",
"logging",
"windows-phone",
"windows-phone-7"
],
"Title": "Simplest WP7 logger"
}
|
33050
|
<p>I use the following code to get the changes between two collections. Objects are "joined" using a primary key. Any tips on performance issues or other optimizations appreciated.</p>
<pre><code>/// <summary>
/// Gets the changes [Deleted, changed, inserted] comparing this collection to another.
/// </summary>
/// <param name="local">The source collection.</param>
/// <param name="remote">The remote collection to comare agains.</param>
/// <param name="keySelector">The primary key selector function</param>
/// <returns></returns>
public static ChangeResult<TSource> CompareTo<TSource, TKey>(this IEnumerable<TSource> local, IEnumerable<TSource> remote, Func<TSource, TKey> keySelector)
{
if (local == null)
throw new ArgumentNullException("local");
if (remote == null)
throw new ArgumentNullException("remote");
if (keySelector == null)
throw new ArgumentNullException("keySelector");
var remoteKeyValues = remote.ToDictionary(keySelector);
var deleted = new List<TSource>();
var changed = new List<TSource>();
var localKeys = new HashSet<TKey>();
foreach (var localItem in local)
{
var localKey = keySelector(localItem);
localKeys.Add(localKey);
/* Check if primary key exists in both local and remote
* and if so check if changed, if not it has been deleted
*/
TSource changeCandidate;
if (remoteKeyValues.TryGetValue(localKey, out changeCandidate))
{
if (!changeCandidate.Equals(localItem))
changed.Add(changeCandidate);
}
else
{
deleted.Add(localItem);
}
}
var inserted = remoteKeyValues
.Where(x => !localKeys.Contains(x.Key))
.Select(x => x.Value)
.ToList();
return new ChangeResult<TSource>(deleted, changed, inserted);
}
/// <summary>
/// Immutable class containing changes
/// </summary>
public class ChangeResult<T>
{
public ChangeResult(IList<T> deleted, IList<T> changed, IList<T> inserted)
{
Deleted = new ReadOnlyCollection<T>(deleted);
Changed = new ReadOnlyCollection<T>(changed);
Inserted = new ReadOnlyCollection<T>(inserted);
}
public IList<T> Deleted { get; private set; }
public IList<T> Changed { get; private set; }
public IList<T> Inserted { get; private set; }
}
</code></pre>
<p>Usage</p>
<pre><code>var changes = Col1.CompareTo(Col2, x => x.UniqueId);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T08:44:34.937",
"Id": "52891",
"Score": "0",
"body": "I'm not posting this as an answer because it doesn't address your actual question of performance but I notice that you are checking if the `local` parameter is null twice and not checking the `remote` parameter at all. Looks like a simple typo/copy and paste."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T18:02:55.010",
"Id": "53077",
"Score": "0",
"body": "How big do you expect `local` and `remote` to be? How many changes, insertions and deletions would you expect?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T19:52:13.883",
"Id": "53085",
"Score": "0",
"body": "@breischl `local` and `remote` will be around 250.000 items, the nr. of changes may vary considerably, but should not be more than around 2%."
}
] |
[
{
"body": "<p>I think it looks like good, clear, general purpose code. I don't see any really significant changes to make, but there might be some minor improvements available.</p>\n\n<p>First, allocating default size collections and letting them grow naturally may not work well for large collections. IIRC they start at 10 elements, and then double each time they top out. But each doubling requires a reallocation and a copy, which can add up when you're adding thousands of items. You should initialize them with the proper size if you know what it is. If you can take a decent guess, even that will help: starting at (for example) 200 elements instead of 10 will save you a lot of allocations. But avoid calling <code>Count()</code> on your input <code>IEnumerable</code> objects since that could cause them to be enumerated an extra time, depending on the underlying implementation.</p>\n\n<p>Second, if you commonly have no insertions in <code>remote</code> and no deletions in <code>local</code>, you could add some code to skip the final enumeration of <code>remoteKeyValue</code>. As you're enumerating <code>local</code>, keep a count of how many items were found in <code>remoteKeyValues</code>. If the number you end up with is equal to <code>remoteKeyValues.Count</code> then you know there are no insertions, because you already matched all the items in that collection.</p>\n\n<p>As always with performance tweaking, profile it before and after any changes.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T21:14:50.690",
"Id": "33139",
"ParentId": "33053",
"Score": "1"
}
},
{
"body": "<p>I would first make <code>ChangeResult<T></code> truly immutable using <code>sealed</code> and <code>readonly</code>. It's unfortunate that we don't have true immutable syntax for automatic properties, but space is cheap, they say:</p>\n\n<pre><code>/// <summary>\n/// Immutable class containing changes\n/// </summary>\npublic sealed class ChangeResult<T> : IChangeResult<T>\n{\n private readonly ReadOnlyCollection<T> deleted;\n\n private readonly ReadOnlyCollection<T> changed;\n\n private readonly ReadOnlyCollection<T> inserted;\n\n public ChangeResult(IList<T> deleted, IList<T> changed, IList<T> inserted)\n {\n this.deleted = new ReadOnlyCollection<T>(deleted);\n this.changed = new ReadOnlyCollection<T>(changed);\n this.inserted = new ReadOnlyCollection<T>(inserted);\n }\n\n public IList<T> Deleted\n {\n get\n {\n return this.deleted;\n }\n }\n\n public IList<T> Changed\n {\n get\n {\n return this.changed;\n }\n }\n\n public IList<T> Inserted\n {\n get\n {\n return this.inserted;\n }\n }\n}\n</code></pre>\n\n<p>and because it's good design to program to interfaces, I extracted one:</p>\n\n<pre><code>public interface IChangeResult<T>\n{\n IList<T> Deleted\n {\n get;\n }\n\n IList<T> Changed\n {\n get;\n }\n\n IList<T> Inserted\n {\n get;\n }\n}\n</code></pre>\n\n<p>Then, in your <code>CompareTo<TSource, TKey>()</code> method, I have it return said interface. Also, I expand the <code>deleted</code> and <code>changed</code> lists to the capacity of the <code>local</code> enumerable (converted to a list locally so an expensive enumerable doesn't get iterated multiple times). This may be overkill in some cases, but in the worst cases, you wind up eliminating potentially expensive list expansion reallocations. A classic speed-vs-space tradeoff. I would then posit that this is actually a great algorithm to go parallel with, as long as you don't care about the order in the three lists:</p>\n\n<pre><code>/// <summary>\n/// Gets the changes [Deleted, changed, inserted] comparing this collection to another.\n/// </summary>\n/// <typeparam name=\"TSource\"></typeparam>\n/// <typeparam name=\"TKey\"></typeparam>\n/// <param name=\"local\">The source collection.</param>\n/// <param name=\"remote\">The remote collection to compare against.</param>\n/// <param name=\"keySelector\">The primary key selector function</param>\n/// <returns></returns>\npublic static IChangeResult<TSource> CompareTo<TSource, TKey>(\n this IEnumerable<TSource> local,\n IEnumerable<TSource> remote,\n Func<TSource, TKey> keySelector)\n{\n if (local == null)\n {\n throw new ArgumentNullException(\"local\");\n }\n\n if (remote == null)\n {\n throw new ArgumentNullException(\"remote\");\n }\n\n if (keySelector == null)\n {\n throw new ArgumentNullException(\"keySelector\");\n }\n\n local = local.ToList();\n\n var remoteKeyValues = remote.ToDictionary(keySelector);\n var deleted = new List<TSource>(local.Count());\n var changed = new List<TSource>(local.Count());\n var localKeys = new HashSet<TKey>();\n\n Parallel.ForEach(\n local,\n localItem =>\n {\n var localKey = keySelector(localItem);\n\n lock (localKeys)\n {\n localKeys.Add(localKey);\n }\n\n /* Check if primary key exists in both local and remote\n * and if so check if changed, if not it has been deleted\n */\n TSource changeCandidate;\n\n if (remoteKeyValues.TryGetValue(localKey, out changeCandidate))\n {\n if (changeCandidate.Equals(localItem))\n {\n return;\n }\n\n lock (changed)\n {\n changed.Add(changeCandidate);\n }\n }\n else\n {\n lock (deleted)\n {\n deleted.Add(localItem);\n }\n }\n });\n\n var inserted = remoteKeyValues\n .AsParallel()\n .Where(x => !localKeys.Contains(x.Key))\n .Select(x => x.Value)\n .ToList();\n\n return new ChangeResult<TSource>(deleted, changed, inserted);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T22:23:32.183",
"Id": "53099",
"Score": "0",
"body": "Shouldn't it be `private readonly ReadOnlyCollection<T> _deleted;`?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T22:30:07.690",
"Id": "53100",
"Score": "0",
"body": "@retailcoder No? Why do you think it should?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T22:34:42.460",
"Id": "53101",
"Score": "0",
"body": "Because it's C# and it's a private field? It would mootinize usage of `this` in the constructor and enhance readability I find."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T01:08:11.380",
"Id": "53105",
"Score": "0",
"body": "Well, we'll have to agree to disagree. Official MS C# coding style guide advises against special prefixes for class member variable names: http://msdn.microsoft.com/en-us/library/ms229012.aspx ."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T01:20:04.870",
"Id": "53106",
"Score": "1",
"body": "Hmm I guess I'm just used to ReSharper-style naming conventions for private fields. Code completion puts them all together that way, and it differenciates private fields from parameters and local variables. At the end of the day it's a matter of personal preference, I'll try real hard to stop twitching when I see `private readonly SomeType field;` ...nice review BTW (got my +1) :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T01:38:45.553",
"Id": "53107",
"Score": "0",
"body": "Thanks :) My ReSharper plus StyleCop for R# does almost the opposite, interestingly."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T07:39:05.157",
"Id": "53127",
"Score": "2",
"body": "Thanks for the tips @JesseC.Slicer. So the only reason you convert `local` to a list is for the ability to set capacity for the lists? If that is done I would send in `local` to the constructor of the `hashset` also and avoid the lock/add in the loop. You are correct in that I don't care about the order and if we are going parallel the use of `ConcurrentBag` instead of lists would probably be a good idea to avoid the need for `lock`. Possibly create my own collection that inherits from `ReadOnlyCollection` but wraps `IProducerConsumerCollection<T>` instead if `IList<T>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T13:28:11.310",
"Id": "53144",
"Score": "0",
"body": "@Magnus I like your thoughts."
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T22:07:53.400",
"Id": "33140",
"ParentId": "33053",
"Score": "4"
}
},
{
"body": "<p>I tried to make a parallelized implementation without full locks (use collections from Concurrency namespace). Also, I've added an optional <code>compareFunc</code> function useful if you want to test object equality without override <code>Equals</code> on <code>TSource</code>.</p>\n\n<p>This is my version:</p>\n\n<pre><code> /// <summary>\n /// Gets the changes [Deleted, changed, inserted] comparing this collection to another.\n /// </summary>\n /// <param name=\"local\">The source collection.</param>\n /// <param name=\"remote\">The remote collection to comare agains.</param>\n /// <param name=\"keySelector\">The primary key selector function</param>\n /// <param name=\"compareFunc\">Optional camparing function between 2 objects of type TSource</param>\n /// <returns>List of changes as Added, Removed and Changed items of type TSource</returns>\n public static ChangeResult<TSource> CompareTo<TSource, TKey>(\n this IEnumerable<TSource> local, IEnumerable<TSource> remote, Func<TSource, TKey> keySelector, Func<TSource, TSource, bool> compareFunc = null)\n {\n if (local == null)\n throw new ArgumentNullException(\"local\");\n if (remote == null)\n throw new ArgumentNullException(\"remote\");\n if (keySelector == null)\n throw new ArgumentNullException(\"keySelector\");\n\n var remoteKeyValues = new ConcurrentDictionary<TKey, TSource>(remote.ToDictionary(keySelector));\n var localKeyValues = new ConcurrentDictionary<TKey, TSource>(local.ToDictionary(keySelector));\n var changed = new ConcurrentBag<Tuple<TSource, TSource>>();\n\n Parallel.ForEach(\n local,\n localItem =>\n {\n var localItemKey = keySelector(localItem);\n\n //1. Check if item is both in local and remote\n if (remoteKeyValues.TryRemove(localItemKey, out var remoteItemValue))\n {\n //1.a item is in both collections -> check if they are different\n var isItemChanged = compareFunc != null ? !compareFunc(localItem, remoteItemValue) :\n !localItem.Equals(remoteItemValue);\n\n if (isItemChanged)\n {\n //1.b are different -> mark a change\n changed.Add(new Tuple<TSource, TSource>(localItem, remoteItemValue));\n }\n\n //1.c remove the item from local list as it's prensent in remote list too\n //this should never return false\n localKeyValues.TryRemove(localItemKey, out var localItemValue);\n }\n\n //2. if item is not in remote list means it has been removed\n });\n\n var deleted = localKeyValues.Values;\n var inserted = remoteKeyValues.Values;\n\n return new ChangeResult<TSource>(deleted, changed, inserted);\n }\n</code></pre>\n\n<p>and ChangeResult class slightly modified:</p>\n\n<pre><code> /// <summary>\n/// Immutable class containing changes\n/// </summary>\npublic sealed class ChangeResult<T>\n{\n public ChangeResult(IEnumerable<T> deleted, IEnumerable<Tuple<T, T>> changed, IEnumerable<T> inserted)\n {\n Deleted = deleted;\n Changed = changed;\n Inserted = inserted;\n }\n\n public IEnumerable<T> Deleted { get; }\n\n public IEnumerable<Tuple<T, T>> Changed { get; }\n\n public IEnumerable<T> Inserted { get; }\n}\n</code></pre>\n\n<p>end this is a test</p>\n\n<pre><code>[TestClass]\npublic class ListUtilsTests\n{\n class User\n {\n public string Key { get; set; }\n\n public string Name { get; set; }\n }\n\n [TestMethod]\n public void ListUtilsCompare()\n {\n var local = new[] { new User() { Key = \"A\", Name = \"John\" }, new User() { Key = \"B\", Name = \"Red\" } };\n var remote = new[] { new User() { Key = \"B\", Name = \"Red (edited)\" }, new User() { Key = \"C\", Name = \"Tizio\" } };\n\n var changes = local.CompareTo(remote, _ => _.Key, (i1, i2) => i1.Name == i2.Name);\n\n Assert.IsNotNull(changes);\n Assert.AreEqual(1, changes.Inserted.Count());\n Assert.AreEqual(\"Tizio\", changes.Inserted.First().Name);\n Assert.AreEqual(1, changes.Deleted.Count());\n Assert.AreEqual(\"John\", changes.Deleted.First().Name);\n Assert.AreEqual(1, changes.Changed.Count());\n Assert.AreEqual(\"Red (edited)\", changes.Changed.First().Item2.Name);\n }\n}\n</code></pre>\n\n<p>Edit: After further investigations, I found that actually going without parallel threads it runs much faster (see <a href=\"https://gist.github.com/adospace/917429d2163a5435f5d19b9f092affce\" rel=\"nofollow noreferrer\">https://gist.github.com/adospace/917429d2163a5435f5d19b9f092affce</a> for a comparison chart).</p>\n\n<p>So just replace the <code>Parallel</code> code above with <code>foreach (var localItem in local)</code></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T11:02:01.270",
"Id": "413834",
"Score": "0",
"body": "Nice, what kind of speed improvement did you get compared to the original implementation?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T14:34:31.523",
"Id": "413856",
"Score": "0",
"body": "I've made a simple benchmark implementation (https://gist.github.com/adospace/917429d2163a5435f5d19b9f092affce). Seems like that your implementation is pretty fast, actually faster of parallelized versions. Using a simple foreach in my code, I found it's a bit faster of your function (about 18% faster): I guess the point here is that lock contention in a parallel implementation degrades performance."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T14:51:21.883",
"Id": "413858",
"Score": "0",
"body": "I guess since there is no cpu intensive operation, this might not be an optimal case for palatalization."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T15:02:58.417",
"Id": "413862",
"Score": "0",
"body": "Yes, I suppose that the parallel version could go better if local items are taken in chunks of many items (say local.Count()/10) so to give more work to each running thread and reduce lock contention."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T10:57:02.333",
"Id": "213948",
"ParentId": "33053",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "33139",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T08:05:34.517",
"Id": "33053",
"Score": "7",
"Tags": [
"c#",
".net"
],
"Title": "Optimization of comparing two collections and get the changes"
}
|
33053
|
<p>I have two active records <code>StudentDemographics</code> and <code>StudentWeeklyReport</code> both having <code>has_many</code> relation like this:</p>
<pre><code>class StudentDemographics < ActiveRecord::Base
has_many :student_weekly_reports, :foreign_key => :student_id
end
</code></pre>
<p>I have to check marks for each student in the last fifth week seminar with the latest one. If the result is <code>true</code>, student should be active, else inactive. I have the following code. Here, I am repeating the loop with each date. <code>@distinct</code> is an array of dates.</p>
<pre><code>def active_learner
safe = []
@active = []
@inactive = []
@distinct = StudentDemographics.select(:date).map(&:date).uniq.sort
@students = StudentDemographics.includes(:student_weekly_reports).select("student_id,date")
@distinct.each_with_index do |date,i|
if i < 4
@count = StudentDemographics.where("date <= ?", date).count
@active[i] = @count
@inactive[i] = 0
else
sum = safe.length
active = inactive = 0
(@students - safe).each do |student|
next if student.date > date
@stu = student.student_weekly_reports.last(5)
if @stu.length > 4
if @stu[4].golden_eggs > @stu[0].golden_eggs
safe << student
active += 1
else
inactive += 1
end
else
safe << student
active += 1
end
end
@active[i] = active + sum
@inactive[i] = inactive
end
end
end
</code></pre>
<p>The performance is not good. It's taking more than 3 secs of time. My MySQL database has 13600 in the <code>StudentWeeklyReports</code> table and 2000 in the <code>StudentDemographics</code> table. Can anyone suggest how I can optimize this?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T06:07:10.533",
"Id": "53025",
"Score": "0",
"body": "`StudentDemographics` has a `date` field, but `StudentWeeklyReport` doesn't? I would have expected the opposite to be true. Perhaps you could provide more context about the whole problem you are trying to solve, and what the motivation is."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T06:21:50.027",
"Id": "53026",
"Score": "0",
"body": "@200_success StudentWeeklyReport also has date field...I have edited my post...In first 4 weeks every one is active...from 5th on wards I have to calculate active students based on the last five weeks data along with that week...if the user marks for 5th week is greater than first week we can consider him as active..."
}
] |
[
{
"body": "<p>I'd suggest a couple of things:</p>\n\n<ol>\n<li><p>the <code>for i in 0...@distinct.length</code> takes your array's length and uses it to construct a range which it turns into an array again. Not necessarily time consuming but unnecessary and hard to read. Ruby gives you <a href=\"http://apidock.com/ruby/Enumerator/each_with_index\" rel=\"nofollow\"><code>each_with_index</code></a> which can do it in a nicer, more concise way.</p></li>\n<li><p><strong>favoring working with IDs</strong> should speed things up because no Active Record objects need to be created and filled and it's quite enough for your calculations. One important tool for that is <a href=\"http://apidock.com/rails/ActiveRecord/Calculations/pluck\" rel=\"nofollow\"><code>pluck</code></a>.</p></li>\n<li><p>I also removed several local variables as you only use them for tallies and that's, again, not really necessary. But no real speedup here, either.</p></li>\n</ol>\n\n<p><strong>TL;DR</strong>: here's the re-factored version with calculations in ruby.</p>\n\n<pre><code>safe_ids = safe.map(&:student_id)\n@distinct.each_with_index do |date, i|\n @active[i] = safe_ids.length\n @inactive[i] = 0\n @student_ids = StudentDemographics.where(\"id not in (?)\", safe_ids).where(\"date <= ?\", date).pluck(\"student_id\")\n @student_ids.each do |student_id|\n @stu = StudentWeeklyReport.where(:student_id => student_id).last(5).pluck(:golden_eggs)\n if @stu.length <= 4 || @stu[4] > @stu[0]\n safe << student_id\n @active[i] += 1\n else\n @inactive[i] += 1\n end\n end\nend\n</code></pre>\n\n<p>You could also try and have the whole <strong>calculation done by the database</strong>, by using <code>group_by</code> and <code>having</code> in a fairly complicated but probably very fast query.</p>\n\n<p>But I'll leave it to the astute reader to figure that one out (mainly since I couldn't manage to get it right in time).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T14:41:17.993",
"Id": "33073",
"ParentId": "33058",
"Score": "1"
}
},
{
"body": "<p>Issing a separate SQL query per record almost always leads to a performance problem. You should be able to formulate this code using just one query, and let the database server do all the work. Stop thinking in terms of Ruby code, and develop a good SQL query that returns three columns (date, active_count, inactive_count).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T09:44:18.217",
"Id": "53039",
"Score": "0",
"body": "Alas, such a query might be impossible in MySQL due to the lack of a `RANK()` function, which would be necessary to work on a pair of seminars four weeks apart. It should be possible in, say, PostgreSQL, which does have such a function."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T23:56:42.457",
"Id": "33099",
"ParentId": "33058",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "33073",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T10:29:40.673",
"Id": "33058",
"Score": "3",
"Tags": [
"performance",
"ruby",
"ruby-on-rails",
"database"
],
"Title": "Getting student demographics report with ActiveRecord"
}
|
33058
|
<p>I'm not a Python developper, but I enjoy programming with it, and for a project I wanted to have generators that I can easily index. Using python's slice model is obviously the way to go, and here's the solution I've come up with.</p>
<pre><code>class _SubscriptableGenerator():
def __init__(self, generator, *args):
self.gen = generator(*args)
def __getitem__(self, key):
try:
if isinstance(key, int):
self.ignore(key)
yield next(self.gen)
else:
step = key.step if key.step else 1
start = key.start if key.start else 0
i = start
self.ignore(start)
while i < key.stop:
yield next(self.gen)
i = i + step
self.ignore(step-1)
except Exception:
self.raiseInvalidSlice(key)
def raiseInvalidSlice(self, key):
raise KeyError("{0} is not a valid key (only int and [x:y:z] slices are implemented.".format(key))
def ignore(self, n):
for i in range(n):
next(self.gen)
</code></pre>
<p>It is not intended to be called by the user of the module, that's internal code. I for example define my generators like so</p>
<pre><code>def _myGen(arg1, arg2):
while 1:
yield something
</code></pre>
<p>and provide them wrapped in my class</p>
<pre><code>def myGen(*args):
return _SubscriptableGenerator(_myGen, *args)
</code></pre>
<p>I'd like to know what a more pythonic solution would be, if there are things to fix, etc. I am not sure about the way to handle exceptions on the key.</p>
|
[] |
[
{
"body": "<p>The most Pythonic solution would be to use <a href=\"http://docs.python.org/3/library/itertools.html#itertools.islice\"><code>itertools.islice</code></a> from the standard library. For example, like this:</p>\n\n<pre><code>from itertools import islice\n\nclass Sliceable(object):\n \"\"\"Sliceable(iterable) is an object that wraps 'iterable' and\n generates items from 'iterable' when subscripted. For example:\n\n >>> from itertools import count, cycle\n >>> s = Sliceable(count())\n >>> list(s[3:10:2])\n [3, 5, 7, 9]\n >>> list(s[3:6])\n [13, 14, 15]\n >>> next(Sliceable(cycle(range(7)))[11])\n 4\n >>> s['string']\n Traceback (most recent call last):\n ...\n KeyError: 'Key must be non-negative integer or slice, not string'\n\n \"\"\"\n def __init__(self, iterable):\n self.iterable = iterable\n\n def __getitem__(self, key):\n if isinstance(key, int) and key >= 0:\n return islice(self.iterable, key, key + 1)\n elif isinstance(key, slice):\n return islice(self.iterable, key.start, key.stop, key.step)\n else:\n raise KeyError(\"Key must be non-negative integer or slice, not {}\"\n .format(key))\n</code></pre>\n\n<p>Note that I've given the class a better name, written a <a href=\"http://docs.python.org/3/tutorial/controlflow.html#documentation-strings\">docstring</a>, and provided some <a href=\"http://docs.python.org/3/library/doctest.html\">doctests</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T15:05:18.240",
"Id": "52933",
"Score": "0",
"body": "Nice, I didn't know about this itertools feature. Thanks !"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T13:18:11.397",
"Id": "33067",
"ParentId": "33060",
"Score": "9"
}
}
] |
{
"AcceptedAnswerId": "33067",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T10:55:48.243",
"Id": "33060",
"Score": "8",
"Tags": [
"python",
"python-3.x",
"generator"
],
"Title": "Subscriptable/Indexable generator"
}
|
33060
|
<p>I am trying to setup an odds calculator for a best of 7 series, given independent odds for each event.</p>
<p>The following code works, but I would like to add recursion to simplify the end.</p>
<pre><code>public class Game
{
public int No { get; set; }
public List<decimal> Odds;
public Game(int no, decimal odd1, decimal odd2)
{
No = no;
Odds = new List<decimal>();
Odds.Add(odd1);
Odds.Add(odd2);
}
}
void Main()
{
var games = new List<Game>();
var homeodd = .6m;
var awayodd = .4m;
var winningOdds = 0m;
//Add 7 games each with a different odd of winning game
games.Add(new Game(1,homeodd,awayodd));
games.Add(new Game(2,homeodd,awayodd));
games.Add(new Game(3,awayodd,homeodd));
games.Add(new Game(4,awayodd,homeodd));
games.Add(new Game(5,awayodd,homeodd));
games.Add(new Game(6,homeodd,awayodd));
games.Add(new Game(7,homeodd,awayodd));
//game one has 2 possible outcomes, 0 = win, 1 = loss =>same for all 7 games
for (int i = 0; i < 2; i++)
{
for (int j = 0; j < 2; j++)
{
for (int k = 0; k < 2; k++)
{
for (int l = 0; l < 2; l++)
{
for (int m = 0; m < 2; m++)
{
for (int n = 0; n < 2; n++)
{
for (int o = 0; o < 2; o++)
{
if ((i+j+k+l+m+n+o)<4) //if we have loss less than 4 games, we have won the series and we want to add the odds of that possibility to the total odds
{
winningOdds += games[0].Odds[i] * games[1].Odds[j] * games[2].Odds[k] * games[3].Odds[l] * games[4].Odds[m] * games[5].Odds[n] * games[6].Odds[o];
}
}
}
}
}
}
}
}
Console.WriteLine(winningOdds);
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T13:09:52.067",
"Id": "52904",
"Score": "2",
"body": "This is messy. You have Game class defined twice and some code directly in the class definition. Write it in a way, so that people don't have to think what you meant."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T13:16:38.973",
"Id": "52906",
"Score": "0",
"body": "good catch, stupid cut and paste screwed me first time"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T13:37:32.313",
"Id": "52910",
"Score": "0",
"body": "can you give some sample input and some expected results? there must be a better way to do this then to use all those `for` statements. what is inside the if statement will only run when all the variables are `=0` . is that intended?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T14:06:29.153",
"Id": "52917",
"Score": "0",
"body": "for (int ii = 0; ii < Math.Pow(2, games.Count()); ii++)\n {\n var result = Convert.ToString(ii, 2);\n result = \"00000000\".Substring(0, 7-result.Length) + result;\n \n var flag = new List<int>();\n \n for (int i2 = 0; i2 < games.Count (); i2++)\n {\n flag.Add(int.Parse(result.Substring(i2,1)));\n }\n \n if (flag.Sum() < 4)\n {\n winningOdds2 += games[0].Odds[flag[0]] * games[1].Odds[flag[1]] * games[2].Odds[flag[2]] * games[3].Odds[flag[3]] * games[4].Odds[flag[4]] * games[5].Odds[flag[5]] * games[6].Odds[flag[6]];\n }\n }"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T14:07:17.690",
"Id": "52919",
"Score": "0",
"body": "All the FOR loops can be replaced with this.... I just need to linq the multiplying line now"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T14:15:11.837",
"Id": "52920",
"Score": "0",
"body": "I don't understand the code. What exactly are you trying to calculate? What does the `if` mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T14:19:22.820",
"Id": "52922",
"Score": "0",
"body": "basically there are 2 possible outcomes for each match, 0 (a win) or 1 (a loss). If your total is 3 or less, you have lost less than 4 matches and have won the series."
}
] |
[
{
"body": "<p>This is a clean as I can make it. The last thing I could do would be to replace the hardcoded 7 by a const to make it a little easier to setup best of 5, best of 3, etc...</p>\n\n<pre><code>using System;\nusing System.Collections.Generic;\nusing System.Linq;\n\nnamespace ConsoleApplication10\n{\n internal class Program\n {\n private static void Main(string[] args)\n {\n var games = new List<Game>();\n\n const decimal homeodd = .6m;\n const decimal awayodd = .4m;\n\n var winningOdds2 = 0m;\n\n games.Add(new Game(1, homeodd));\n games.Add(new Game(2, homeodd));\n games.Add(new Game(3, awayodd));\n games.Add(new Game(4, awayodd));\n games.Add(new Game(5, awayodd));\n games.Add(new Game(6, homeodd));\n games.Add(new Game(7, homeodd));\n\n for (var ii = 0; ii < Math.Pow(2, games.Count()); ii++)\n {\n var result = Convert.ToString(ii, 2);\n result = \"00000000\".Substring(0, 7 - result.Length) + result;\n\n var flag = new List<int>();\n\n for (var i2 = 0; i2 < games.Count(); i2++)\n {\n flag.Add(int.Parse(result.Substring(i2, 1)));\n }\n\n if (flag.Sum() >= 4) continue;\n var product = 1m;\n for (var p = 0; p < 7; p++)\n {\n product = product * games[p].Odds[flag[p]];\n }\n winningOdds2 += product;\n }\n\n Console.WriteLine(winningOdds2);\n Console.ReadLine();\n }\n }\n}\n\npublic class Game\n{\n public int No { get; set; }\n\n public List<decimal> Odds;\n\n public Game(int no, decimal odd1)\n {\n No = no;\n Odds = new List<decimal> {odd1, 1-odd1};\n }\n}\n\n// Define other methods and classes here\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T14:38:57.570",
"Id": "52928",
"Score": "2",
"body": "1. I would be very careful about using `double` as the loop variable. 2. If you want to add zero padding to a string, you can use `PadLeft()`, it's much more readable than your solution. 3. Instead of using digits in a string, I would rather access the bits directly using `%` and `/` or bitwise operators and shifts."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T14:54:03.707",
"Id": "52929",
"Score": "0",
"body": "I dont know how to directly access the bits, quick example please ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T15:01:23.027",
"Id": "52931",
"Score": "0",
"body": "If you're okay with accessing the bits from least significant to most significant (basically, right to left), then it's something like `while (i != 0) { int currentBit = i % 2; ...; i /= 2; }`."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T14:21:03.517",
"Id": "33071",
"ParentId": "33064",
"Score": "0"
}
},
{
"body": "<p>Basically, what you need is a Cartesian product of 7 sequences, each containing a 0 and a 1. <a href=\"https://docs.microsoft.com/en-us/archive/blogs/ericlippert/computing-a-cartesian-product-with-linq\" rel=\"nofollow noreferrer\">Eric Lippert has an interesting article about doing just that using LINQ</a> (note: I think you could make his code more efficient using immutable collections). If you use his method, your code could look something like:</p>\n<pre><code>var product = CartesianProduct(Enumerable.Repeat(new[] { 0, 1 }, games.Count));\n\nforeach (var indexes in product)\n{\n if (indexes.Sum() < 4)\n { \n winningOdds += indexes\n .Select((index, game) => games[game].Odds[index])\n .Aggregate((x, y) => x * y);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-10-22T14:29:40.753",
"Id": "33072",
"ParentId": "33064",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T12:44:34.457",
"Id": "33064",
"Score": "2",
"Tags": [
"c#",
"optimization",
"recursion"
],
"Title": "Optimizing odds calculator"
}
|
33064
|
<p>Just a wrapper around IsolatedStorageSettings.</p>
<p>The only thing i'm not sure about is isoSettings.Save(); Should i call it there? Looking like it works without it, setting [] is enough.</p>
<pre><code>class IsoSettingsManager
{
private static readonly IsolatedStorageSettings isoSettings = IsolatedStorageSettings.ApplicationSettings;
/// <summary>
/// Set a property
/// </summary>
/// <param name="propertyName"></param>
/// <param name="content"></param>
public static void SetProperty(string propertyName, object content)
{
isoSettings[propertyName] = content;
isoSettings.Save();
}
/// <summary>
/// Reads value from IsolatedStorageSettings.
/// WARNING: returns null, if property is not found.
/// </summary>
/// <param name="propertyName"></param>
/// <returns></returns>
public static object GetProperty(string propertyName)
{
if (isoSettings.Contains(propertyName) && isoSettings[propertyName] != null)
return isoSettings[propertyName];
return null;
}
/// <summary>
/// Reads reference from IsolatedStorageSettings.
/// WARNING: returns default(), if property is not found.
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="propertyName"></param>
/// <returns></returns>
public static T GetProperty<T>(string propertyName)
{
if (isoSettings.Contains(propertyName) && isoSettings[propertyName] != null)
return (T) isoSettings[propertyName];
return default(T);
}
/// <summary>
/// Removes property, if already exists
/// </summary>
/// <param name="propertyName"></param>
public static void RemoveProperty(string propertyName)
{
if (isoSettings.Contains(propertyName))
isoSettings.Remove(propertyName);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>When you use your <code>GetProperty</code> method there is no way to find out did you get a real property value or some default value.</p>\n\n<p>It will be more clear if you'll use a standard TryGet pattern here:</p>\n\n<pre><code>public static bool TryGetProperty<T>(string propertyName, out T result)\n{\n if (isoSettings.Contains(propertyName) && isoSettings[propertyName] != null)\n {\n result = (T) isoSettings[propertyName];\n return true; \n }\n\n result = default(T);\n return false;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T07:16:05.183",
"Id": "53121",
"Score": "0",
"body": "The IsolatedStorageSettings supports the TryGetValue method so there is no need to create it manually."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T08:50:43.790",
"Id": "53133",
"Score": "0",
"body": "yep, my bad. So it can be simplified."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T09:46:09.613",
"Id": "33124",
"ParentId": "33074",
"Score": "1"
}
},
{
"body": "<p>There are few things which could be improved. Argument validation, better error handling, duplicate code removal and potentially better API for handling missing value for a given property name. Personally, I am not a big fan of TryGet pattern.</p>\n\n<p>Here's how I would write it:</p>\n\n<pre><code>public static class IsoSettingsManager\n{\n private static readonly IsolatedStorageSettings isoSettings = IsolatedStorageSettings.ApplicationSettings;\n\n // All arguments of public methods must be validated.\n public static void SetProperty(string propertyName, object propertyValue)\n {\n if(string.IsNullOrWhiteSpace(propertyName))\n throw new ArgumentNullException(\"propertyName\");\n\n //I added this check only because in your original GetProperty method\n //you treat 'null' as a missing value for a given property name. \n //In that case, it makes sense to not allow null content to be set\n //as property value.\n\n //You want to carefully think about whether a null content is a valid \n //value or not for your end users and adjust the code accordingly.\n if(propertyValue == null)\n throw new ArgumentNullException(\"propertyValue\");\n\n isoSettings[propertyName] = propertyValue;\n isoSettings.Save();\n }\n\n public static object GetProperty(string propertyName, object alternateValue)\n {\n if(string.IsNullOrWhiteSpace(propertyName))\n throw new ArgumentNullException(\"propertyName\");\n\n //We don't validate alternateValue because user may want to return 'null'\n //as an alternate. \n return isoSettings.Contains(propertyName) ? isoSettings[propertyName] : alternateValue;\n }\n\n //Instead of repeating the code of non generic GetProperty method, we will\n //use it here.\n public static T GetProperty<T>(string propertyName, T alternateValue)\n {\n var propertyValue = GetProperty(propertyName, alternateValue); \n\n //Let's ensure that the property value is of the right type.\n\n //Below logic is strict about type casting. \n //Potentailly, CAST can also invoke conversion and if you want to adapt to \n //that you should use the function outlined in this answer:\n //http://stackoverflow.com/questions/1399273/test-if-convert-changetype-will-work-between-two-types/1399454#1399454\n if(propertyValue.GetType() != typeof(T))\n throw new InvalidOperationException(\"Property value for Property Name \" + propertyName + \" is of type \" + propertyValue.GetType().Name + \" and it can not be casted to type \" + typeof(T).Name);\n\n return (T) propertyValue;\n }\n\n public static T GetProperty<T>(string propertyName)\n {\n return GetProperty<T>(propertyName, default(T));\n }\n\n public static void RemoveProperty(string propertyName)\n {\n if(string.IsNullOrWhiteSpace(propertyName))\n throw new ArgumentNullException(\"propertyName\");\n\n if (isoSettings.Contains(propertyName))\n isoSettings.Remove(propertyName);\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T00:56:36.147",
"Id": "33144",
"ParentId": "33074",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "33124",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T14:45:52.100",
"Id": "33074",
"Score": "1",
"Tags": [
"c#",
"windows-phone",
"windows-phone-7"
],
"Title": "IsoSettingsManager"
}
|
33074
|
<p>I am writing a dice roller winforms application using C# 2012 VS. Dice roller is set up for playing Shadowrun tabletop. I feel that there might be too much code going into the GUI, but I am unsure how it should be formatted. I am also very open to general advice. This is my first program I am trying to construct on my own after graduating. I have never attempted a GUI application before.</p>
<p><a href="https://github.com/andyhoffman12/DiceRoller/" rel="nofollow">GitHub</a></p>
<p>User Control Code:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace DiceRollerWinForms
{
public partial class DiceRollerUserControl : Form
{
private RollDice diceRoll = new RollDice();
private Roll currentRoll = new Roll();
private Int32 rollNumber = 1;
private Int32 currentNumDice = 1;
private Int32 lastNumHit = 0;
private Int32 lastNumDiceRolled = 0;
private string numDiceText = "Number of Dice";
public DiceRollerUserControl()
{
InitializeComponent();
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void aboutToolStripMenuItem_Click(object sender, EventArgs e)
{
}
private void splitContainer1_Panel1_Paint(object sender, PaintEventArgs e)
{
}
private void mainSplitContainer_SplitterMoved(object sender, SplitterEventArgs e)
{
}
private void tableLayoutPanel1_Paint(object sender, PaintEventArgs e)
{
}
private void diceToRollBox_TextChanged(object sender, EventArgs e)
{
if (Int32.TryParse(diceToRollBox.Text, out currentNumDice))
{
currentNumDice = Int32.Parse(diceToRollBox.Text);
}
else
{
currentNumDice = 1;
}
diceToRollBox.Text = currentNumDice.ToString();
}
private void subtractDiceButton_Click(object sender, EventArgs e)
{
if (currentNumDice > 1)
{
currentNumDice--;
}
diceToRollBox.Text = currentNumDice.ToString();
}
private void addDiceButton_Click(object sender, EventArgs e)
{
if (currentNumDice < 100)
{
currentNumDice++;
}
diceToRollBox.Text = currentNumDice.ToString();
}
private void RollDiceButton_Click(object sender, EventArgs e)
{
currentRoll = diceRoll.RollTheDice(currentNumDice, false, false);
ListViewItem i = new ListViewItem(rollNumber.ToString());
i.SubItems.Add(currentRoll.numHits.ToString());
i.SubItems.Add(currentRoll.rawRoll);
i.SubItems.Add(currentRoll.isGlitch.ToString());
i.SubItems.Add(currentRoll.isCritGlitch.ToString());
resultView.Items.Add(i);
rollNumber++;
}
private void RollDiceWithEdgeButton_Click(object sender, EventArgs e)
{
currentRoll = diceRoll.RollTheDice(currentNumDice, false, false);
ListViewItem i = new ListViewItem(rollNumber.ToString());
i.SubItems.Add(currentRoll.numHits.ToString());
i.SubItems.Add(currentRoll.rawRoll);
i.SubItems.Add(currentRoll.isGlitch.ToString());
i.SubItems.Add(currentRoll.isCritGlitch.ToString());
resultView.Items.Add(i);
rollNumber++;
}
private void reRollDiceWithEdgeButton_Click(object sender, EventArgs e)
{
currentRoll = diceRoll.RollTheDice(currentNumDice, false, false);
ListViewItem i = new ListViewItem(rollNumber.ToString());
i.SubItems.Add(currentRoll.numHits.ToString());
i.SubItems.Add(currentRoll.rawRoll);
i.SubItems.Add(currentRoll.isGlitch.ToString());
i.SubItems.Add(currentRoll.isCritGlitch.ToString());
resultView.Items.Add(i);
rollNumber++;
}
private void resultView_SelectedIndexChanged(object sender, EventArgs e)
{
}
}
}
</code></pre>
<p>Other Code:</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security.Cryptography;
namespace DiceRollerWinForms
{
class Roll
{
public string rawRoll { get; set; }
public Int32 numHits {get; set;}
public bool isGlitch {get; set;}
public bool isCritGlitch{get; set;}
public Int32 lastNumDiceRolled { get; set; }
public Int32 lastNumHitsRolled { get; set; }
public bool lastRollWasEdge { get; set; }
internal void FinalRollResults(Int32[] resultsRaw, Int32 numDice)
{
Int32[] rollResults = new Int32[6];
for (Int32 i = 0; i < numDice; i++)
{
switch(resultsRaw[i])
{
case 1:
rollResults[0]++;
break;
case 2:
rollResults[1]++;
break;
case 3:
rollResults[2]++;
break;
case 4:
rollResults[3]++;
break;
case 5:
rollResults[4]++;
break;
case 6:
rollResults[5]++;
break;
}
}
numHits = rollResults[4] + rollResults[5];
//If more than half the dice you rolled show a one, then you’ve got problems. This is called a glitch.
if ((numDice / 2) < rollResults[0])
{
this.isGlitch = true;
if (numHits == 0)
{
this.isCritGlitch = true;
}
}
rawRoll = string.Join(",", resultsRaw);
}
public Roll()
{
//six the number of sides on a dice
rawRoll = ""; //its a magic number
numHits = 0;
isGlitch = false;
isCritGlitch = false;
}
}
class RollDice : Roll
{
private Int32 const_Delay = 0;
private RNGCryptoServiceProvider RNGProvider = new RNGCryptoServiceProvider();
public Roll RollTheDice(Int32 numberOfDiceToRoll, bool edgeRoll, bool reRollEdge)
{
Roll currentRoll = new Roll();
Int32[] results = new Int32[numberOfDiceToRoll];
for (int i = 0; i < numberOfDiceToRoll; i++)
{
System.Threading.Thread.Sleep(const_Delay);
results[i] = RNGDiceRoll(RNGProvider);
}
currentRoll.FinalRollResults(results, numberOfDiceToRoll);
currentRoll.lastNumDiceRolled = numberOfDiceToRoll;
currentRoll.lastNumHitsRolled = currentRoll.numHits;
if (edgeRoll)
{
lastRollWasEdge = true;
}
return currentRoll;
}
private Int32 RNGDiceRoll(RNGCryptoServiceProvider Provider)
{
byte[] arr = new byte[4];
Int32 rand = 0;
do
{
Provider.GetBytes(arr);
rand = BitConverter.ToInt32(arr, 0);
}
while (rand < 1);
Int32 roll = (rand % 6) + 1;
return roll;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>your <code>Do..While</code> threw me for a loop. I saw the <code>While</code> statement and not the <code>Do</code> statement preceding it and wondered where the code was.</p>\n\n<p>you already set the <code>rand</code> variable to something less than <code>1</code> before the loop, so you should just write it</p>\n\n<pre><code>while (rand < 1)\n{\n Provider.GetBytes(arr);\n rand = BitConverter.ToInt32(arr,0);\n}\n</code></pre>\n\n<p>it is more readable and less code to write.</p>\n\n<p>my Instructors didn't like the <code>Do-While</code> loops, they liked it better when we used the <code>While</code> Loops. it is harder to get into an infinite loop with a <code>while</code> loop as opposed to a <code>do-while</code></p>\n\n<p><strong>Difference between <code>Do</code> and <code>While</code></strong></p>\n\n<p>The 2 loops are different. </p>\n\n<p>The <code>Do</code> loop will go through the block then decide whether to go through the loop again based on the <code>while</code> statement. the <code>While</code> loop will test the condition before going through the loop.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T16:28:13.710",
"Id": "52937",
"Score": "1",
"body": "+1 having the loop condition at the beginning of the loop makes it clear what you're getting yourself into."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T16:32:00.503",
"Id": "52939",
"Score": "0",
"body": "the 2 loops are different. the `Do` loop will go through the block then decide whether to go through the loop again based on the `while` statement. the `While` loop will test the condition before going through the loop."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T16:39:31.590",
"Id": "52940",
"Score": "1",
"body": "True, but most loop conditions can be written so as to put it at the top. Makes it more readable imho."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T16:45:54.800",
"Id": "52941",
"Score": "1",
"body": "I agree completely. I have heard some people say that, even though you can code `Do..While` loops that they are still bad coding practice unless you absolutely need them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T17:06:30.343",
"Id": "52945",
"Score": "1",
"body": "Thanks for the heads up. I had to read that again myself.\nI'll get that switched around. Still looking for over all comments on the code. I guess in particular the gui stuff and proper design patterns."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T15:19:06.640",
"Id": "33078",
"ParentId": "33076",
"Score": "4"
}
},
{
"body": "<p>Don't commit an empty event handler without a comment like <code>// todo: implement \"New\" toolbar button click</code> - a comment like this would explain <em>why</em> you have such a handler, and <em>why</em> it's empty. Otherwise you're registering an event without doing anything about it and that's just plain YAGNI.</p>\n\n<p>Your private fields are not following established naming conventions. They should be something like this - also if you're going to be referring to the <code>String</code> class with the C# <code>string</code> alias, you should also be referring to <code>Int32</code> with the C# <code>int</code> alias, for consistency's sake:</p>\n\n<pre><code> private RollDice _diceRoll = new RollDice();\n private Roll _currentRoll = new Roll();\n private int _rollNumber = 1;\n private int _currentNumDice = 1;\n private int _lastNumHit = 0;\n private int _lastNumDiceRolled = 0;\n private string _numDiceText = \"Number of Dice\";\n</code></pre>\n\n<p>Now this one is debatable, but I find explicitly saying what the type of everything is, is an annoyance - use <code>var</code> for implicit typing:</p>\n\n<pre><code> Int32[] rollResults = new Int32[6];\n</code></pre>\n\n<p>Becomes</p>\n\n<pre><code> var rollResults = new int[6];\n</code></pre>\n\n<p>That way if you decide to change that <code>Int32</code> for an <code>Int16</code> or something else, you only have one place to change it. Again, using <code>var</code> whenever possible is only a matter of personal preference... but I prefer that :)</p>\n\n<p>Your class names don't match the file names - <code>RollDice.cs</code> contains class <code>Roll</code> which is sure to cause some trouble at one point or another, not to mention <code>Roll</code> (a <em>verb</em>) is a very bad name to use for a class (a <em>noun</em>).</p>\n\n<p>...and only put 1 class per file, I had to scroll all the way down to find the <code>RollDice</code> class, which is also a non-obvious name, especially when I see another class called <code>DiceRoller</code> where I would expect a <code>Roll()</code> or <code>RollDice()</code> method; I suggest you refactor/rename <code>DiceRoller</code> to <code>DiceRollerApp</code>, since it's your application entry point and that would be clearer that way.</p>\n\n<hr>\n\n<p>That's all I have time to cover for now, I'll edit with more when I have a minute, I think I'll even download your project tonight and see it in action ;)</p>\n\n<hr>\n\n<p><H2>Actual Code Review</H2></p>\n\n<p>Ok so I managed to open up your solution in <strong>VS2012</strong> (read: <strong>not</strong> 2010 as mentioned in both this question and the GitHub repo).</p>\n\n<p>The first, very first thing that strikes me, is this line of code:</p>\n\n<pre><code>Application.Run(new DiceRollerUserControl());\n</code></pre>\n\n<p>Why does it strike me? Because it's a lie - <code>DiceRollerUserControl</code> isn't a <em>user control</em>, it's a <em>form</em>:</p>\n\n<pre><code>public partial class DiceRollerUserControl : Form\n</code></pre>\n\n<p>So the fist thing I'm doing - before I even run the app, is rename this class to <code>DiceRollerMainForm</code>. Second thing I'm doing, build the app. And it's failing with some manifest error - I go to the <em>project properties</em> / \"Signing\" tab and uncheck the \"Sign the ClickOnce manifests\" box, and then it builds. And... another thing strikes me.</p>\n\n<p>You're using a <code>SplitContainer</code>, and your form is resizable. That's good. Now I realize this isn't WPF, but in terms of layout, I'm sure you could do better:</p>\n\n<p><img src=\"https://i.stack.imgur.com/Tiowq.png\" alt=\"broken downsized form\"></p>\n\n<p>The <code>DiceRollerMainForm</code> (the renamed <code>DiceRollerUserControl</code>) is tightly coupled with <code>Dice</code> and <code>Roll</code> classes, because of these lines:</p>\n\n<pre><code> private Dice _diceRoll = new Dice();\n private Roll _currentRoll = new Roll();\n</code></pre>\n\n<p>But I'll leave that aside for now. Moving on to the event handlers:</p>\n\n<pre><code> private void diceToRollBox_TextChanged(object sender, EventArgs e)\n {\n if (int.TryParse(diceToRollBox.Text, out _currentNumDice))\n {\n _currentNumDice = int.Parse(diceToRollBox.Text);\n }\n else\n {\n _currentNumDice = 1;\n }\n diceToRollBox.Text = _currentNumDice.ToString();\n }\n</code></pre>\n\n<p>This is setting the <em>number of dice to be rolled next time we roll the dice</em> - I think setting it to 1 whenever there's a problem with parsing the <code>int</code> value, is a bad decision. Instead, you should give the user some visual cue about the value being invalid, and while the value is invalid the commands that rely on it should be disabled.</p>\n\n<pre><code> private void subtractDiceButton_Click(object sender, EventArgs e)\n {\n if (_currentNumDice > 1)\n {\n _currentNumDice--;\n }\n diceToRollBox.Text = _currentNumDice.ToString();\n }\n\n private void addDiceButton_Click(object sender, EventArgs e)\n {\n if (_currentNumDice < 100)\n {\n _currentNumDice++;\n }\n diceToRollBox.Text = _currentNumDice.ToString();\n }\n</code></pre>\n\n<p>This is the code behind the <kbd>+</kbd> and <kbd>-</kbd> buttons, respectively for adding and removing a dice. Again, you have a piece of logic here that's burried in an event handler, and using magic numbers: this is begging for a <em>minimum</em> and a <em>maximum</em> dice count constant or configuration setting.</p>\n\n<p><strong>Now there's a bug here</strong>: I put a breakpoint on all 3 handlers, and the <em>TextChanged</em> handler is never hit, regardless of what I put in there. So if <code>_currentNumDice</code> is 1 and I enter 10 and then click the <kbd>+</kbd> button, <code>_currentNumDice</code> is 2, not 11. And looking at the original code of <code>InitializeComponents()</code> directly on GitHub, the <code>TextChanged</code> event wasn't registered.</p>\n\n<p>So I register it. And now there's another, more subtle bug: again I put a breakpoint on all 3 handlers, and when I click the <kbd>+</kbd> button, the handler for that button runs and sets the text in the textbox from 1 to 2, which is intended. But since the textbox text has just changed, the <code>TextChanged</code> event fires and the handler for that event runs, hitting a second breakpoint and then the procedure just re-assigns <code>_currentNumDice</code> to the value it was just assigned with.</p>\n\n<p>So we <kbd>Roll</kbd> the dice.</p>\n\n<pre><code> private void RollDiceButton_Click(object sender, EventArgs e)\n {\n _currentRoll = _diceRoll.RollTheDice(_currentNumDice, false, false);\n ListViewItem i = new ListViewItem(_rollNumber.ToString());\n i.SubItems.Add(_currentRoll.numHits.ToString());\n i.SubItems.Add(_currentRoll.rawRoll);\n i.SubItems.Add(_currentRoll.isGlitch.ToString());\n i.SubItems.Add(_currentRoll.isCritGlitch.ToString());\n resultView.Items.Add(i);\n _rollNumber++;\n }\n</code></pre>\n\n<p>First thing that hits me here, is <em>why the heck</em> was <code>_currentRoll</code> initialised with <code>= new Roll()</code> in the first place, if we're going to replace it with the return value from <code>_diceRoll.RollTheDice()</code>? I think <code>_currentRoll</code> should be <code>null</code> until the dice are actually rolled. Actually, I don't think it should even be an instance variable / private field: it's only used for adding <code>SubItems</code> to the <code>ListViewItem</code> that populates the <code>resultView</code>. Variables should be as short-lived as possible, the meaning of <code>_currentRoll</code> has no significance whatsoever after the dice have rolled and the results were added to the <code>resultView</code>, and <code>_rollNumber</code> also only has a significant value within that scope, so a first round of refactor could start with this:</p>\n\n<pre><code> private void RollDiceButton_Click(object sender, EventArgs e)\n {\n var rollIndex = 0;\n var roll = _diceRoll.RollTheDice(_currentNumDice, false, false);\n var item = new ListViewItem(rollIndex.ToString());\n item.SubItems.Add(roll.numHits.ToString());\n item.SubItems.Add(roll.rawRoll);\n item.SubItems.Add(roll.isGlitch.ToString());\n item.SubItems.Add(roll.isCritGlitch.ToString());\n resultView.Items.Add(item);\n rollIndex++;\n }\n</code></pre>\n\n<p>Now <code>numHits</code>, <code>rawRoll</code>, <code>isGlitch</code> and <code>isCritGlitch</code> are absolutely cryptic to me; I have to <em>go to definition</em> of the <code>Roll</code> class in the <code>Dice.cs</code> file (grrr...) and be lucky enough that you have included these comments:</p>\n\n<pre><code> numHits = rollResults[4] + rollResults[5]; //hits are the number of dice that rolld a 5 or 6\n //If more than half the dice you rolled show a one, then you’ve got problems. \n //This is called a glitch.\n</code></pre>\n\n<p>...And now we have a problem: how does <code>rollResults[4]</code> instinctively means a 5 was rolled\"? Let's look at <code>FinalRollResults</code>:</p>\n\n<pre><code> internal void FinalRollResults(int[] resultsRaw, int numDice)\n {\n var rollResults = new int[6];\n\n for (var i = 0; i < numDice; i++)\n {\n //is this legit?\n switch(resultsRaw[i])\n {\n case 1:\n rollResults[0]++;\n break;\n case 2:\n rollResults[1]++;\n break;\n case 3:\n rollResults[2]++;\n break;\n case 4:\n rollResults[3]++;\n break;\n case 5:\n rollResults[4]++;\n break;\n case 6:\n rollResults[5]++;\n break;\n }\n }\n</code></pre>\n\n<p>First off, <code>internal</code> is of no use here, since you have only 1 assembly. Did you mean <code>private</code>? Probably not, since the app doesn't build in that case. I'm making it <code>public</code>. Another thing, <code>FinalRollResults</code> is a very, very bad name for a method - it's a <em>noun</em>, which would be suitable for a class name. But this is a <em>method</em> (verb) and it returns <code>void</code> so the only way to find out what it does, is to read it.</p>\n\n<p>So we're rolling 6-faced dice. What if you wanted to modify your code to also support 8, 12, or 20-faced dice? (I don't know what <em>ShadowRun</em> is, but maybe rules could be configurable?) And who says all dice must have the same number of faces? That makes quite a bunch of hard-coded <code>6</code>'s to fix!</p>\n\n<p>I'll stop here, I think you have enough food for thought as it is!</p>\n\n<p><H2>Key Points</H2></p>\n\n<ul>\n<li><code>TableLayoutPanel</code> doesn't play well with buttons and resizable windows. Actually I've never used it for anything that turned out looking good.. but maybe it's just me.</li>\n<li>This is WinForms, make your form look pretty at a specific size, and don't allow resizing.</li>\n<li>The <kbd>+</kbd> and <kbd>-</kbd> buttons, as well as the textbox, could all be replaced with a <code>NumericUpDown</code> control, which already validates its value so you can't manually enter \"hi there\" for a value: essentially, you're reinventing the wheel here, and your wheel is square.</li>\n<li><strong>Code-behind should only hold <em>presentation logic</em>, and that's exactly what you've got here. Kudos!</strong></li>\n<li>I see a <code>MenuStrip</code> on your design-view form, but none of it at runtime. Not sure why, but I'm sure that menu is intended to be shown... or is it? There's no code for it!</li>\n<li>Three words: naming, naming, and naming:\n\n<ul>\n<li>Class names should be <strong>nouns</strong> that describe <em>what</em> the object is.</li>\n<li>Method names should be <strong>verbs</strong> that describe <em>what</em> the method does.</li>\n<li>Variable names should be <strong>meaningful</strong>. Always.</li>\n</ul></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T17:20:30.553",
"Id": "52946",
"Score": "0",
"body": "Thanks for the Advice. I'll make some changes to it which should show up in github later."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T18:10:09.777",
"Id": "52952",
"Score": "0",
"body": "Also I am curious to know where you get the naming conventions at. I did a brief look on MS's site to see about that but did not see much in the way of _for private ..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T19:11:47.010",
"Id": "52954",
"Score": "0",
"body": "Hmm try downloading the ReSharper demo, it's enforcing them by default. The underscore prefix differenciates private fields from parameters so you can assign `_context = context` in a constructor, for example."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T19:12:38.990",
"Id": "52955",
"Score": "0",
"body": "Just a warning about R#: it's ADDICTIVE! :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T19:30:51.113",
"Id": "52960",
"Score": "0",
"body": "Thanks I'll try it out. I added some spit and polish to the program including renaming it to something more like it is\n\nhttps://github.com/andyhoffman12/ShadowRunDiceRoller"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T15:26:19.303",
"Id": "53066",
"Score": "0",
"body": "Thank you for the review. I'll be making some edits to the code here today and commit them."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-26T01:47:15.300",
"Id": "53277",
"Score": "1",
"body": "AWESOME review. I take issue with saying that TableLayoutPanel is not a good idea. You mentioned WPF and Grid is essentially a TableLayoutPanel, which makes up more than 75% of my user controls in WPF. I've used TableLayoutPanel a few times in a old program I had to fix at work and it scaled my buttons, Labels, and Comboboxes nicely. The program ran on 2 tablets, one with a 9\" screen, and the other with a 5\" screen with very different resolutions. Just my 2 cents, but I like TableLayoutPanel for winforms, I just don't like winforms any more :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-26T01:58:20.190",
"Id": "53278",
"Score": "0",
"body": "Thanks! I guess if you want your buttons, labels and comboboxes to scale it works well (I found it completely broke the OP's layout here), I'm learning WPF right now and I'm [ab]using `StackPanel` and `DockPanel` a lot; I use a `Grid` merely to have a fixed-height section at the top and bottom of my windows... But I'm not even halfway through that brick-like book (Pro WPF) and got a lot to learn still, but I find WPF is *made for* resizable layouts, vs WinForms with its coordinate-based layout is more... fixed-size-friendly. :)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T17:12:11.697",
"Id": "33082",
"ParentId": "33076",
"Score": "11"
}
},
{
"body": "<p>As an addendum to @retailcoder epic answer I offer...</p>\n<h2>Object Oriented Dice</h2>\n<p>Lots of your existing code will simply melt away when we take a more object oriented approach. The key is making classes for the basic things in dice game world and have each class responsible for <em>doing</em> what it is supposed to.</p>\n<h3>Die Class</h3>\n<p>A single Dice, that is.</p>\n<pre><code>public class Die {\n protected int sides = 6;\n protected Random generate = new Random();\n\n public int Roll() { return generate.Next(1,(sides+1)); }\n}\n</code></pre>\n<p><strong>notes</strong></p>\n<ul>\n<li>This is one 6 sided thing. It can be rolled.</li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/system.random%28v=vs.100%29.aspx\" rel=\"noreferrer\">Random class</a> - <a href=\"https://codereview.stackexchange.com/questions/33076/winforms-dice-roller/33151#comment53152_33151\">See OP's concerns on this</a></li>\n</ul>\n<h3>Dice class</h3>\n<p>We have the concept of "rolling dice." OK then let's make some Dice.</p>\n<pre><code>public class Dice {\n List<Die> dice;\n\n public int Count { get { return dice.Count; }\n\n public Dice (params Die[] theDice) { // see notes.\n foreach (Die die in theDice) { dice.Add(die); }\n }\n\n // this is an indexer. see notes.\n public Die this[int i] { get { return dice[i]; } }\n\n public int Roll() {\n int total = 0;\n\n foreach (Die die in dice) { total =+ die.Roll(); }\n\n return total;\n }\n}\n</code></pre>\n<p><strong>notes</strong></p>\n<ul>\n<li>Now rolling a single die is nicely abstracted. The code reads like what it does.</li>\n<li><a href=\"http://msdn.microsoft.com/en-us/library/vstudio/w5zay9db%28v=vs.110%29.aspx\" rel=\"noreferrer\"><code>params</code></a> allows you to have a variable number of parameters. So we can pass in 1, 2, 10 dice if we want</li>\n<li>An indexer is cool. <a href=\"http://msdn.microsoft.com/en-us/library/vstudio/6x16t2tx%28v=vs.110%29.aspx\" rel=\"noreferrer\">Read this.</a></li>\n</ul>\n<h3>DiceGame</h3>\n<p>Just a sketch. This could be a craps, yahtzee, lier's dice...</p>\n<pre><code>public class DiceGame { \n protected Dice dice;\n\n public DiceGame(Dice theDice) { dice = theDice; }\n\n public void Play() { // TBD\n int total = dice.Roll(); rolling all the dice at once\n\n // indexer allows individual Rolls.\n\n int firstDieRoll = dice[0].Roll();\n int secondDieRoll = dice[1].Roll();\n\n // when I don't care how many there are\n for (int i=0; i<dice.Count; i++) {\n dice[i].Roll();\n }\n }\n}\n</code></pre>\n<p><strong>notes</strong></p>\n<ul>\n<li>Everything is in terms of <code>Dice</code>, and that sound logical. <code>DiceGame</code> is nicely abstracted as far as handling dice is concerned.</li>\n<li>The Game deals with <code>Dice</code> only, not individual <code>Die</code>s.</li>\n<li>It does not know how to roll the dice. The dice know, we just tell the dice to do it.</li>\n<li><code>Dice</code>, in turn, does not know how to Roll individual <code>Die</code>s, we just tell the die to roll.</li>\n</ul>\n<h3>Inversion of Control</h3>\n<p>We still need a class to put it all together. But first IOC...</p>\n<p>The knee-jerk way is to instantiate the <code>DiceGame</code>, inside of which we "new-up" some <code>Dice</code>, inside of which we make some <code>Die</code> objects. The better way is to <em>invert</em> this construction hierarchy. Make the smallest bits first, then pass them into the constructor of thing it belongs in and so on...</p>\n<pre><code>public DiceGameBuilder {\n protected Die die1 = new Die();\n protected Die die2 = new Die();\n\n protected Dice dice = new Dice(die1, die2); //params doing it's thing\n\n // DiceGameBuilder actually does not need die1, die2 objects\n // so the constructor call would look like this\n protected Dice dice = new Dice (new Die(), new Die());\n\n protected DiceGame craps = new DiceGame(dice);\n\n craps.Play();\n}\n</code></pre>\n<p>Inversion of Control allows for <em>dependency injection</em>. By inverting the composition of objects we can <em>inject</em> different objects. It limits <em>where</em> we make changes for these different things. This is very powerful when doing unit testing.</p>\n<h3>IOC Makes Change Easier</h3>\n<blockquote>\n<p>So we're rolling 6-faced dice. What if you wanted to modify your code to also support 8, 12, or 20-faced dice? (I don't know what ShadowRun is, but maybe rules could be configurable?) And who says all dice must have the same number of faces? That makes quite a bunch of hard-coded 6's to fix!</p>\n</blockquote>\n<p><strong>Add a new <code>Die</code> constructor</strong></p>\n<pre><code>public Die (int sides = 6) { this.sides = sides; }\n</code></pre>\n<p><strong>Drumroll, please</strong></p>\n<ul>\n<li>Optional constructor parameters :\n<ul>\n<li>Existing calls with no parameters does not need to change</li>\n<li>Be sure to document the default behavior! <a href=\"https://msdn.microsoft.com/library/b2s063f7%28v=vs.100%29.aspx\" rel=\"noreferrer\">XML comments</a> would be just fine.</li>\n</ul>\n</li>\n<li>ONLY the <code>Die</code> class is touched.</li>\n<li>Each <code>Die</code> can have a different number of sides</li>\n<li>Without a <code>Die</code> class this kind of modification would be a nightmare</li>\n<li>I did not made a <code>Die</code> class because I knew I was going to make this change. The <code>Die</code> is a logical, meaningful object in the dice game world - that's why.</li>\n<li><code>Dice</code> needs no modification</li>\n<li><code>DiceGame</code> needs no modification</li>\n<li>The change is very small because only a <code>Die</code> <em>needs to know</em> how many sides it has.</li>\n<li>The classes tend to be small because each class is responsible for <em>doing</em> it's own thing.</li>\n<li>Methods tend to be small - this is a symptom of well designed classes. <code>Dice.Roll()</code> is 3 lines of code!!</li>\n<li>We built all of this <em>business layer</em> code with zero regard for user interface. That's good.</li>\n<li>You should be able to "drive" the dice game without UI.</li>\n<li>The above points means there will be loose coupling with the UI when you write it.</li>\n<li>By building, driving, testing the business layer first (at least some minimally functioning part) the UI will be that much easier and less buggy.</li>\n</ul>\n<hr />\n<h3>Code Maintenance</h3>\n<p><a href=\"https://codereview.stackexchange.com/questions/33076/winforms-dice-roller/33151#comment53279_33151\">This comment</a> about rolling N dice is addressed here.</p>\n<p>The lessons learned</p>\n<ul>\n<li>Method overloading is by far cleaner and clearer.</li>\n<li>Adding a new method is less error prone then modifying an existing one.\n<ul>\n<li>Existing client code calling <code>Roll()</code> is not at risk of breaking.</li>\n</ul>\n</li>\n<li>Good OO design that "separates concerns", that follows the Single Responsibility Principle, makes change so much better in every way.</li>\n<li>The invisible hand of good design is at work here, just like the above example of modifying the <code>Die</code> constructor.</li>\n</ul>\n<p>.</p>\n<pre><code>public class Dice {\n public int Roll() { } // don't need to touch this\n\n public int Roll (int thisMany) {\n if ( this.Count < thisMany ) return 0;\n\n int total = 0;\n \n for (int i = 0; i < thisMany; i++)\n total += dice[i].Roll();\n\n return total;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T04:34:09.250",
"Id": "53115",
"Score": "0",
"body": "Epic answer yourself! +12 if I could!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T14:43:43.583",
"Id": "53152",
"Score": "0",
"body": "I really appreciate your advice on this. I'll be making changes:)\n\n\nI would like to make a huge note that this: \n\nThis is one 6 sided thing. It can be rolled.\nRandom class - use the .NET Framework!\n\n\nis absolute garbage for rolling random numbers in something like dice. go check it out its trash... if you check out my repository i compared that to RNG CRYPTO Service and a mersenne twister and the rng crypto was the only one worthy of rolling dice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T15:33:58.417",
"Id": "53157",
"Score": "0",
"body": "Note that this isn't a *code review* per se, it's really a continuation of my answer, picking up where I left off (I left out any object-oriented approach suggestion on purpose, to leave room for answers like this). One thing about DI: it's also addictive - and when you start having more complex dependencies which have their own dependencies which have their own dependencies, consider looking into an IoC container; take a look at [Ninject](http://www.ninject.org/) for example. The IoC container does all the `new`ing-up for you :)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T17:40:26.400",
"Id": "53167",
"Score": "0",
"body": "+1 Also, since this is in c#, Dice.Roll could be shortened even further with LINQ to `return dice.Sum(d => d.Roll());`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-26T02:03:10.587",
"Id": "53279",
"Score": "1",
"body": "I would suggest renaming Roll() with RollAll(), and adding RollSome(int) method into your Dice class. Since it is a collection, and we use those verbs when playing a dice game it would be good to have that in there. RollSome could be tricky though if you have a game where you roll different side die (such as Risk 2210)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-26T02:33:50.513",
"Id": "53280",
"Score": "0",
"body": "I don't know Risk 2210, but then maybe in that case `RollSome(int)` could have a `RollSome(int count, int sides)` overload, to roll `count` dice with `sides` number of sides, so `RollSome(2, 3)` would roll 2x 3-faced dice (of course that would physically be 6 faces with 1-3 showing up twice), and perhaps throw some `NotSupportedException` if there are no such dice."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-26T06:17:12.683",
"Id": "53291",
"Score": "1",
"body": "`Roll()`, `RollSome(count)`, `RollSome(count, sides)`... whoa! - why not just a `Roll(count)` overload? `Roll()` uses all dice and `Roll(n)` rolls n dice. One way to say \"roll the dice\". consistent, clean. Also, the `RollSome(count,sides)` smells like a game rule misplaced as a confusing dice method. `Die hitCountDice = new Die(4); hitCountDice.Roll()` in a Game class of some kind is far superior to `Dice.RollSome(1,4)`. What in the Wide World of Sports is that supposed to mean?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-26T06:27:34.657",
"Id": "53294",
"Score": "0",
"body": "Make a 3-sided die if needed. Do not make a 6-sided die then hack the `Die` class to shreds trying to force it to act like a 3, 4, 20, etc. sided die. I suppose a 1-sided die is not practical but the ensuing discussion of N-fold space would be fun."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-28T08:55:05.530",
"Id": "53443",
"Score": "0",
"body": "This should not compile. Your `Dice` indexer claims to return a `Die` but it actually calls `Roll()` on a `Die`."
}
],
"meta_data": {
"CommentCount": "9",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T03:26:52.347",
"Id": "33151",
"ParentId": "33076",
"Score": "15"
}
}
] |
{
"AcceptedAnswerId": "33151",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T14:48:18.580",
"Id": "33076",
"Score": "12",
"Tags": [
"c#",
"object-oriented",
"random",
"gui",
"dice"
],
"Title": "WinForms dice roller"
}
|
33076
|
<p>I am getting object of a class AAA from somewhere and I want to add more information in that object. So, I am creating a new class BBB which is derived from AAA. The class BBB has additional field dictionary. I am populating this dictionary in derived class constructor which is taking the Class AAA object and array of item which I want to use as keys of dictionary and values of this dictionary are elements of a field of object of class AAA. I tried to create similar scenario in blow example code:</p>
<pre><code>void Main(){
A obj = new A () ;
obj.prop1 = new int [] {5 ,10, 15} ;
obj.prop2 = "Hello" ;
obj.prop3 = "World" ;
// obj.Dump () ;
B obj2 = new B (new int [] {1,2,3}, obj) ;
// obj2.Dump () ;
}
// Define other methods and classes here
public class A {
public int [] prop1 ;
public string prop2 ;
public string prop3 ;
}
public class B : A {
public Dictionary <int, int> prop4 ;
public B (int [] keys, A a) {
prop4 = new Dictionary <int, int> () ;
if (keys.Length == a.prop1.Length ) {
for (int i = 0 ; i < keys.Length ; i++ ) {
prop4.Add (keys[i], a.prop1[i]) ;
}
// is there a way to obsolete below lines of code???
this.prop1 = a.prop1 ;
this.prop2 = a.prop2 ;
this.prop3 = a.prop3 ;
}
else {
throw new Exception ("something wrong") ;
}
}
}
</code></pre>
<p>In derived class constructor, I am filling the properties manually and I do not want to do it. Is there another way to do it. I have more than 20 properties in my actual class.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T17:30:04.133",
"Id": "52947",
"Score": "0",
"body": "Can you modify `A`? Does the real `A` have a constructor (apart from the parameterless one)."
}
] |
[
{
"body": "<p>Those lines are managing the properties of A, so they belong in A. I've added a protected copy constructor and used constructor chaining to solve your issue:</p>\n\n<pre><code>public class A\n{\n public int [] prop1 ;\n public string prop2 ;\n public string prop3 ;\n\n public A() {}\n\n protected A(A a) //copy constructor\n {\n this.prop1 = a.prop1 ; //review: should this reference be copied, or a new copy made?\n this.prop2 = a.prop2 ;\n this.prop3 = a.prop3 ;\n }\n}\n\npublic class B : A\n{\n public Dictionary <int, int> prop4 ;\n\n public B (int [] keys, A a) : base(a) //constructor chaining\n {\n prop4 = new Dictionary <int, int> () ;\n if (keys.Length == a.prop1.Length )\n {\n for (int i = 0 ; i < keys.Length ; i++ )\n {\n prop4.Add (keys[i], a.prop1[i]) ;\n }\n }\n else\n {\n throw new Exception (\"something wrong\") ;\n } \n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T15:31:15.800",
"Id": "33079",
"ParentId": "33077",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T14:57:39.863",
"Id": "33077",
"Score": "1",
"Tags": [
"c#",
"inheritance"
],
"Title": "Initialization of Extended class without too much overhead?"
}
|
33077
|
<p>Please take a look at this query and try to give me any other ideas that will give the exact same results more efficiently.</p>
<pre><code>SELECT username
FROM users
WHERE username NOT IN (
SELECT DISTINCT username
FROM users, friends
WHERE 'user1' IN (you,friend,username)
AND you IN ('user1',username)
AND friend IN ('user1',username))
AND username <> 'user1'
</code></pre>
<p>Here's a <a href="http://sqlfiddle.com/#!2/65b95/6" rel="nofollow">live demo</a>.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T23:29:17.967",
"Id": "52989",
"Score": "3",
"body": "As with all SQL query optimizations, first run `EXPLAIN SELECT username FROM users WHERE…` and check that the appropriate [indexes](http://use-the-index-luke.com) are in place."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T13:37:13.877",
"Id": "53047",
"Score": "0",
"body": "are you missing entries in the Friends table? should you have more entries that have `you = 'user1'` and `friend = 'user3'` and another for `friend ='user4'`...I am talking about the fiddle now. maybe it is just a subset of the data in the table."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T06:58:44.930",
"Id": "53210",
"Score": "0",
"body": "It would be somewhat easier to work with your query if you prefixed column names with table aliases so that it was clear which column came from which table."
}
] |
[
{
"body": "<p>This query will give you the same results</p>\n\n<pre><code>SELECT username FROM users \nWHERE username NOT IN (SELECT you FROM friends WHERE friend = 'user1') \nAND username NOT IN (SELECT friend FROM friends WHERE you = 'user1')\nAND username <> 'user1'\n</code></pre>\n\n<p>and the <a href=\"http://sqlfiddle.com/#!2/65b95/58\" rel=\"nofollow\">SQLFiddle</a></p>\n\n<p>If you look at the execution plan, it looks like my query grabbed 1 less row throughout the execution and it didn't have to use a temporary or a join buffer. </p>\n\n<p>This Query is more readable than yours, assuming this is what you are trying to do.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T21:59:25.537",
"Id": "33096",
"ParentId": "33080",
"Score": "7"
}
},
{
"body": "<p>Assuming I've got it right and the <code>you</code> and <code>friend</code> columns come from the <code>friends</code> table and <code>username</code> from <code>users</code>, <a href=\"http://sqlfiddle.com/#!2/65b95/68\" rel=\"nofollow noreferrer\" title=\"Demo at SQL Fiddle\">here's another possibility</a> (which could be viewed as a development on <a href=\"https://codereview.stackexchange.com/a/33096/4061\">@Malachi's suggestion</a>):</p>\n\n<pre><code>SELECT username FROM users\nWHERE username NOT IN (\n SELECT CASE you WHEN 'user1' THEN friend ELSE you END\n FROM friends\n WHERE you = 'user1' OR friend = 'user1'\n)\nAND username <> 'user1'\n;\n</code></pre>\n\n<p>Basically, same approach as @Malachi's, except one fewer scan of the <code>friends</code> table, although it may turn out that their solution can use indices more efficiently.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T13:31:20.517",
"Id": "53223",
"Score": "0",
"body": "the Execution plan that was given by SQLFiddle definitely looks more efficient than my answer! Nice use of the Case Statement"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T07:15:46.223",
"Id": "33216",
"ParentId": "33080",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "33216",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T16:26:40.630",
"Id": "33080",
"Score": "5",
"Tags": [
"mysql",
"sql"
],
"Title": "Improve query: find users who are neither friends nor fans of a user"
}
|
33080
|
<p>I am trying to format my code properly. I have already read the programming standards document and I believe that my code follows these rules. I have also used the <kbd>Ctrl</kbd><kbd>Shift</kbd><kbd>F</kbd> keys in Eclipse which should format the code automatically.</p>
<p>Could someone tell me if this looks ok? It would be nice to get some feedback back and to see if it is being created automatically. I already know that the program does work. Any help would be great. If someone knows a better way to format the code, it would be great to hear it as well.</p>
<pre><code>public class UniString {
public static void main(String[] args) {
char[] det = { '\u20ac', '1', '1', '8' };
// char[]det is an array of characters.
for (char a : det) {
/*
* the for loop takes in the char values and prints them off in
* order the "det" array enters into the for loop through "det" ,
* goes into char a and can be written to the console through
* System.out.println(a).
*/
System.out.print(a);
}
System.out.println();
char[] name = { 'j', 'o', 'e' };
// This is another char array.
String nameString = new String(name);
/*
* The char array is made into a String by loading "name" into a String
* class
*/
String changeCase = nameString.toUpperCase();
/*
* The String "nameString" is changed to Upper case letters. The string
* is then stored as "caseChange".
*/
System.out.println(changeCase);
// "caseChange" is printed out.
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Comments rarely go under a piece of code. Move it above it.</p>\n\n<p>Other than that I'd personally also put the opening parenthesis of the \"for\" loop right next to the \"for:</p>\n\n<pre><code>for(char a : det) { }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T17:19:01.367",
"Id": "33083",
"ParentId": "33081",
"Score": "2"
}
},
{
"body": "<p>I disagree with @user1021726: Keeping a space after the <code>for</code> keyword is good — it's a keyword, not a function. It should be kept more like <code>return something</code> than <code>return(something)</code>.</p>\n\n<p>Comments should go above the code that they refer to. Also, in multi-line comments, the asterisks should line up, like in the <a href=\"http://www.oracle.com/technetwork/java/javase/documentation/index-137868.html#writingdoccomments\" rel=\"nofollow\">JavaDoc guide</a>:</p>\n\n<pre><code> /**\n * The for loop takes in the char elements of the \"det\"\n * array and prints them to the console using\n * System.out.print(a). Afterwards, System.out.println()\n * adds a newline. The code below should be equivalent\n * to System.out.println(new String(det)); — though\n * probably slower.\n */\n for (char a : det) {\n System.out.print(a);\n }\n System.out.println();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T20:18:12.260",
"Id": "52968",
"Score": "0",
"body": "I absolutely agree. However, I noticed that you changed the multiline comments `/* ... */` to JavaDoc comments `/** ... */` although the comment refers to code, not a method, field or class. Does this have any special significance?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T22:34:26.560",
"Id": "52986",
"Score": "0",
"body": "No, comments inside a method have absolutely no semantic significance, and are certainly not interpreted as JavaDoc. I just expect them to follow the same formatting conventions. I would be just as happy with multi-line // comments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-28T22:15:15.660",
"Id": "53542",
"Score": "0",
"body": "I always use `//` comments within a method body to allow temporarily commenting out different sections in the method."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T18:41:45.657",
"Id": "33089",
"ParentId": "33081",
"Score": "4"
}
},
{
"body": "<pre><code>// char[]det is an array of characters.\n// This is another char array.\n...\n</code></pre>\n\n<p>These are so obvious things. In my opinion, code should have comments to justify \"why's\" of the code and not \"what's\" of it. </p>\n\n<p>I feel none of the comments in the code are required. Those just make your code look verbose and do not have any meaning what so ever. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-28T21:29:51.450",
"Id": "33417",
"ParentId": "33081",
"Score": "4"
}
},
{
"body": "<p>I'll address some of the naming:</p>\n\n<ul>\n<li><p><code>det</code> is not a very clear name. If it is short for something, spell it out.</p></li>\n<li><p>The name <code>changeCase</code> is a verb, which doesn't make sense for a variable since it doesn't perform an action; it stores something. Since it receives <code>nameString</code> in uppercase, it can be renamed to something like <code>uppercaseNameString</code>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-25T21:48:44.740",
"Id": "63908",
"ParentId": "33081",
"Score": "3"
}
},
{
"body": "<p>I think all the comments should be removed. The point of a comment is to explain why you wrote this code, not what the code does. If anyone reads the code, they will be able to understand what it does without reading the comments. When you write comments, always ask yourself : \"Will this comment help me understand why I wrote this code 5 years ago?\" (Or.. 2 weeks if you have a bad memory like mine), if you can't answer, you probably don't need comments!</p>\n\n<p>The formatting looks perfect in my opinion.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-09-26T12:47:37.633",
"Id": "63942",
"ParentId": "33081",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "33083",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T16:50:18.267",
"Id": "33081",
"Score": "3",
"Tags": [
"java",
"strings",
"formatting"
],
"Title": "Formatting small string use example"
}
|
33081
|
<p>I have a fairly simple app set up with couchrest_model to capture data pulled in from vendors to couchdb for later searching and archiving. Each document has a <code>show</code> (the name of the vendor), a <code>datatype</code> (which is limited to seven or eight unique strings), and a <code>pulled_at</code> timestamp field.</p>
<p>The core method on this model needs to return a Hash where each key is a <code>show</code> and the value is an array of the most recent document for each <code>datatype</code>. Below, I have my (simplified) model code which defines this method. It works, but my code in <code>self.most_recent_by_type_and_show()</code> which loops over the list of <code>_id</code>s and calls <code>get()</code> on each one (thus generating <em>n</em> HTTP requests on each method call) will not scale.</p>
<pre><code>class Snapshot < CouchRest::Model::Base
property :show, String
property :sources, [String]
property :pulled_at, DateTime
property :datatype, String
property :data, [Hash]
design do
view :_most_recent_by_type_and_show, :map => <<-MAP, :reduce => <<-REDUCE
function(doc) {
if (doc.type == "Snapshot") {
emit(doc.show, [doc.datatype, new Date(doc.pulled_at).valueOf()]);
}
}
MAP
function(keys, values, rereduce) {
var maxes = {},
out = [];
if (!rereduce) {
for (var i in keys) {
var show = keys[i][0];
var doc_id = keys[i][1];
var datatype = values[i][0];
var timestamp = values[i][1];
if (typeof maxes[show] == 'undefined') { maxes[show] = {}; }
if (typeof maxes[show][datatype] == 'undefined') { maxes[show][datatype] = [0, null]; }
if (timestamp > maxes[show][datatype][0]) {
maxes[show][datatype] = [timestamp, doc_id];
}
}
}
if (Object.keys(maxes).length == 0) { maxes = values; }
for (var show in maxes) {
for (var datatype in maxes[show]) {
out.push(maxes[show][datatype][1]);
}
}
return out;
}
REDUCE
end
class << self
def most_recent_by_type_and_show opts = {}
options = opts.merge({ reduce: true, })
raw = _most_recent_by_type_and_show(options).group.rows
raw.reduce({}) do |hash, row|
hash[row['key']] = row['value'].map { |id| get id }.sort_by(&:pulled_at).reverse
hash
end
end
end
end
</code></pre>
<p>This feels like I'm overcomplicating the view code, and I'm also not sure that my reduce function is written correctly for <code>rereduce</code>. I initially tried emitting <code>[show, datatype, pulled_at]</code> as the key and the entire <code>doc</code> itself as the value in the map function, but I've read that this is Bad Practice as it will cause the size of my view index to balloon over time. And for some reason, couchrest_model will not allow me to <code>include_docs=true</code> if I'm reducing a view, which seems to be just a limitation of the gem as I can't find anything saying this should be the case in the CouchDB docs.</p>
<p>Would this be better written as a different data structure altogether? Should I maybe be using a <code>_list</code> function? I'm not sure where to go from here.</p>
|
[] |
[
{
"body": "<p>You can use <a href=\"http://ruby-doc.org/gems/docs/s/samlown-couchrest-1.0.0/CouchRest/Database.html#method-i-get_bulk\" rel=\"nofollow\"><code>CouchRest::Database.get_bulk</code></a> API:</p>\n\n<pre><code>hash[row['key']] = database.get_bulk(row['value']).sort_by(&:pulled_at).reverse\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-02-05T16:47:48.587",
"Id": "40979",
"ParentId": "33085",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T18:10:08.747",
"Id": "33085",
"Score": "1",
"Tags": [
"ruby",
"ruby-on-rails",
"couchdb"
],
"Title": "How can I make this CouchDB view code more \"correct\"?"
}
|
33085
|
<p>I'm working on an implementation of <code>MergeSort</code> which sorts a <code>List</code> given as an argument. As follows</p>
<pre><code>public class MergeSort implements Sort {
@Override
public <E extends Comparable<E>> void sort(List<E> list) {
final int length = list.size();
List<E> left = null;
List<E> right = null;
if (length == 1 || length == 0) {
return;
} else {
left = new ArrayList<>(list.subList(0, length/2));
right = new ArrayList<>(list.subList(length/2, length));
sort(left);
sort(right);
}
// can these be improved?
list.clear();
list.addAll(merge(right, left));
}
private <E extends Comparable<E>> List<E> merge(List<E> right, List<E> left) {
List<E> newList = new LinkedList<>();
int rightIndex = 0, leftIndex = 0;
while (rightIndex < right.size() && leftIndex < left.size()) {
E rightElement = right.get(rightIndex);
E leftElement = left.get(leftIndex);
if (rightElement.compareTo(leftElement) > 0) {
newList.add(leftElement);
leftIndex++;
} else {
newList.add(rightElement);
rightIndex++;
}
}
// add remaining
while (leftIndex < left.size()) {
newList.add(left.get(leftIndex));
leftIndex++;
}
while (rightIndex < right.size()) {
newList.add(right.get(rightIndex));
rightIndex++;
}
return newList;
}
}
</code></pre>
<p>I want to do the sorting on the <code>List</code> that's passed as an argument, not return a new <code>List</code>. I feel, however, that calling <code>clear()</code> and <code>addAll()</code> a number of times might slow things down. How can I avoid these calls?</p>
|
[] |
[
{
"body": "<p>You could do</p>\n\n<pre><code>list.clear(); \nmerge(right, left, list);\n</code></pre>\n\n<p>with</p>\n\n<pre><code>private static <E extends Comparable<E>> List<E> merge(List<E> source1, List<E> source2, List<E> destination) {\n // ...\n destination.add(element);\n // ...\n}\n</code></pre>\n\n<p>The <code>merge()</code> function should be declared <code>static</code> to indicate that it doesn't use any instance variables.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T19:19:30.233",
"Id": "52957",
"Score": "0",
"body": "That helps quite a bit. I think I'm hovering over a solution that will perform the sort in-place, instead of adding to new lists all the time."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T19:23:28.607",
"Id": "52958",
"Score": "2",
"body": "[In-place mergesort](http://stackoverflow.com/a/2571104/1157100) is complicated. Better use a different sorting algorithm, then."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T19:25:05.447",
"Id": "52959",
"Score": "0",
"body": "Thank you for the reference. Is there anywhere else I can improve?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T23:39:24.623",
"Id": "52990",
"Score": "0",
"body": "`if (length <= 1) return;`. By returning early, you don't need `else`, which just adds unnecessary indentation."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T23:42:05.417",
"Id": "52991",
"Score": "0",
"body": "You can save two lines by saying `left.get(leftIndex++)` and `right.get(rightIndex++)` during \"add remaining\"."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T23:43:11.487",
"Id": "52992",
"Score": "0",
"body": "You might want to note that `null` elements are not allowed (or add special logic to put all nulls first or last)."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T19:03:35.190",
"Id": "33090",
"ParentId": "33086",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "33090",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T18:27:45.307",
"Id": "33086",
"Score": "1",
"Tags": [
"java",
"sorting",
"mergesort"
],
"Title": "MergeSort implementation with java.util.List passed as argument, not returned"
}
|
33086
|
<p><a href="https://stackoverflow.com/a/17954617/1214743">Answer to Exporting PDF's from SQL Server DB and writing a Map to a Text File</a></p>
<p>this was a Question that I asked in StackOverflow and then answered it when I was finished with the project. </p>
<p>I would like it reviewed so the next time that I get to write something like this I will have better executing code.</p>
<p>here is the post</p>
<p><strong>Answer From Link</strong></p>
<p>I created Variables for the information that I was extracting that I wanted inside the Text File.</p>
<ol>
<li>Filename</li>
<li>Date (From SQL Table for the Original Creation Date)</li>
<li>Case Number (internal Identifier for the 3rd party program to link to)</li>
<li>Description (Taken from the SQL Table to describe the document)</li>
</ol>
<p>Then I put the application to work Writing the Code to PDF one at a time</p>
<pre><code>using (SqlConnection Conn = new SqlConnection(strSQLConn))
{
//open the connection
Conn.Open();
Console.WriteLine("the connection is open");
//Variables needed for looping
DateTime Today = System.DateTime.Now;
DateTime StartDate = Convert.ToDateTime("2008-06-11 00:00:00");
//DateTime StartDate = Today.AddDays(-10);
Console.WriteLine("Converting the Documents from " + StartDate.ToString() + " - TO - " + Today.ToString());
Console.WriteLine("Press Any Key to continue.");
Console.ReadLine();
int RecordCount = 0;
ulong ByteCount = 0;
int i = 1;
foreach (DateTime day in EachDay(StartDate, Today))
{
String strDay = day.ToString();
// Create a SQLCommand to retrieve Data
SqlCommand getRecords = new SqlCommand("spRecapturePDF", Conn);
getRecords.CommandType = CommandType.StoredProcedure;
getRecords.Parameters.Add(new SqlParameter("@OneDay", strDay));
SqlDataReader reader = getRecords.ExecuteReader();
//stuff exporting the binary code to the PDF format
FileStream fs;
BinaryWriter bw;
int buffersize = 100;
byte[] outbyte = new byte[buffersize];
long retval;
long startIndex = 0;
int j = 1;
while (reader.Read())
{
strFileName = reader.GetString(0) + "-" + i + "-" + j;
strDock_no = reader.GetString(0);
dtFiledate = reader.GetDateTime(2);
strDescription = reader.GetString(4);
fs = new FileStream("c:\\FolderName\\" + strFileName + ".pdf", FileMode.OpenOrCreate, FileAccess.Write);
bw = new BinaryWriter(fs);
startIndex = 0;
retval = reader.GetBytes(1,startIndex,outbyte,0,buffersize);
while (retval == buffersize)
{
bw.Write(outbyte);
bw.Flush();
startIndex += buffersize;
retval = reader.GetBytes(1,startIndex,outbyte,0,buffersize);
}
//write the remaining buffer.
bw.Write(outbyte,0,(int)retval);
ByteCount = ByteCount + Convert.ToUInt64(fs.Length);
bw.Flush();
//close the output file
bw.Close();
fs.Close();
//need to write to the Text file here.
TextWriter tw = new StreamWriter(path,true);
tw.WriteLine(strDock_no + "~" + dtFiledate.ToString() + "~" + "c:\\FolderName\\" + strFileName + ".pdf" + "~" + strDescription);
tw.Close();
// increment the J variable for the Next FileName
j++;
RecordCount++;
}
//close the reader and the connection
reader.Close();
i++;
}
Console.WriteLine("Number of Records Processed: " + RecordCount.ToString());
Console.WriteLine("for a Total of : " + ByteCount + " Bytes");
Decimal MByteCount = new Decimal(2);
MByteCount = Convert.ToDecimal(ByteCount) / 1024 / 1024;
Decimal GByteCount = new Decimal(2);
GByteCount = MByteCount / 1024;
Console.WriteLine("Total MBs : " + MByteCount.ToString() + " MB");
Console.WriteLine("Total GBs : " + GByteCount.ToString() + " GB");
Console.WriteLine("Press Enter to Continue ...");
Console.ReadLine();
}
</code></pre>
<p>this Code was enclosed in a <code>foreach</code> statement that went day by day, from a starting date to an end date. inside that <code>foreach</code> statement the Application called a stored procedure that was given the specified day to call the records that were entered that day.</p>
<p>variables <code>i</code> and <code>j</code> were created because I needed to have a unique Filename even if I had the same Case Number. <code>i</code> represented the day (because I went day by day in my select statement) and <code>j</code> represented the record number for that day from the select statement.</p>
<p>the <code>foreach</code> and the while loops were enclosed in a <code>using(conn)</code> so that no matter what the connection would be closed finally.</p>
<p>at the end of the while loop I wrote to the Text File. the Text file was created outside of all the loops so that I could just append the file rather than overwrite it. that code is:</p>
<pre><code>string path = @"c:\\FolderName\\TextFile.txt";
if (!File.Exists(path))
{
TextWriter tw = new StreamWriter(path, false);
tw.WriteLine("Dock_No~Date~FileName(Location)~Description");
tw.Close();
}
</code></pre>
<p>I left out all the <code>Console.Writeline</code> and <code>Console.ReadLine</code> code that wasn't necessary to the functionality I was looking for. I had added some code also that would count the bytes that were written and some code to count the records processed. this is just fun stuff to know, I need to clean up the Fun stuff at the end.</p>
<p>these are the Guts of what it took to accomplish a mass Extract of PDFs from a Blob Field in SQL Server, minus some Connection Mumbo Jumbo</p>
<p><strong>Foreach Day Set up</strong></p>
<p>this is the Code that I used to make the <code>foreach</code> work the way that I wanted it to.</p>
<pre><code>static public IEnumerable<DateTime> EachDay(DateTime Startdate, DateTime EndDate)
{
for (var day = Startdate.Date; day.Date <= EndDate.Date; day = day.AddDays(1))
yield return day;
}
</code></pre>
|
[] |
[
{
"body": "<p>One of the biggest issues I see in the code is the large number of <code>IDisposable</code> objects created not in <code>using</code> statements. I've put in some minor changes (idiomatic variable naming, etc.) below, but the important one is to make sure those resources get deterministically disposed.</p>\n\n<pre><code> using (var conn = new SqlConnection(strSQLConn))\n {\n // open the connection\n conn.Open();\n Console.WriteLine(\"the connection is open\");\n\n // Variables needed for looping\n var today = DateTime.Now;\n var startDate = Convert.ToDateTime(\"2008-06-11 00:00:00\");\n ////var startDate = Today.AddDays(-10);\n\n Console.WriteLine(\"Converting the Documents from \" + startDate + \" - TO - \" + today);\n Console.WriteLine(\"Press Any Key to continue.\");\n Console.ReadLine();\n\n var recordCount = 0;\n ulong byteCount = 0;\n var i = 1;\n\n foreach (var day in EachDay(startDate, today))\n {\n // Create a SQLCommand to retrieve Data\n using (var getRecords = new SqlCommand(\"spRecapturePDF\", conn) { CommandType = CommandType.StoredProcedure })\n {\n getRecords.Parameters.Add(new SqlParameter(\"@OneDay\", day.ToString()));\n using (var reader = getRecords.ExecuteReader())\n {\n // stuff exporting the binary code to the PDF format\n const int BufferSize = 100;\n var buffer = new byte[BufferSize];\n var j = 1;\n\n while (reader.Read())\n {\n strFileName = reader.GetString(0) + \"-\" + i + \"-\" + j;\n strDock_no = reader.GetString(0);\n dtFiledate = reader.GetDateTime(2);\n strDescription = reader.GetString(4);\n using (var fs = new FileStream(\"c:\\\\FolderName\\\\\" + strFileName + \".pdf\", FileMode.OpenOrCreate, FileAccess.Write))\n using (var bw = new BinaryWriter(fs))\n {\n long startIndex = 0;\n var bytesRead = reader.GetBytes(1, startIndex, buffer, 0, BufferSize);\n\n while (bytesRead == BufferSize)\n {\n bw.Write(buffer);\n bw.Flush();\n startIndex += BufferSize;\n bytesRead = reader.GetBytes(1, startIndex, buffer, 0, BufferSize);\n }\n\n // write the remaining buffer.\n bw.Write(buffer, 0, (int)bytesRead);\n byteCount += Convert.ToUInt64(fs.Length);\n }\n\n //need to write to the Text file here.\n using (var tw = new StreamWriter(path, true))\n {\n tw.WriteLine(strDock_no + \"~\" + dtFiledate.ToString() + \"~\" + \"c:\\\\FolderName\\\\\"\n + strFileName + \".pdf\" + \"~\" + strDescription);\n }\n\n // increment the J variable for the Next FileName\n j++;\n recordCount++;\n }\n }\n }\n\n i++;\n }\n\n Console.WriteLine(\"Number of Records Processed: \" + recordCount.ToString());\n Console.WriteLine(\"for a Total of : \" + byteCount + \" Bytes\");\n\n var megabyteCount = Convert.ToDecimal(byteCount) / 1024 / 1024;\n var gigabyteCount = megabyteCount / 1024;\n\n Console.WriteLine(\"Total MBs : \" + megabyteCount + \" MB\");\n Console.WriteLine(\"Total GBs : \" + gigabyteCount + \" GB\");\n Console.WriteLine(\"Press Enter to Continue ...\");\n Console.ReadLine();\n }\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>const string Path = @\"c:\\\\FolderName\\\\TextFile.txt\";\n\nif (File.Exists(Path))\n{\n return;\n}\n\nusing (var tw = new StreamWriter(Path, false))\n{\n tw.WriteLine(\"Dock_No~Date~FileName(Location)~Description\");\n}\n</code></pre>\n\n<p>and</p>\n\n<pre><code>public static IEnumerable<DateTime> EachDay(DateTime startDate, DateTime endDate)\n{\n for (var day = startDate.Date; day.Date <= endDate.Date; day = day.AddDays(1))\n {\n yield return day;\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T20:29:04.920",
"Id": "52970",
"Score": "0",
"body": "is it better practice to use a `var` instead of the actual data type? I assume that makes it easier to maintain, because you can change the data types on the fly?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T21:06:46.113",
"Id": "52971",
"Score": "1",
"body": "Matters not - it's actually quite the subject of programming and stylistic holy wars. I would *not* do it to be able to change data types though - that would cause a lot of downstream confusion. I do it because it's generally easier to type and later understand than `IDictionary<ICustomKeyThingy, IEnumerable<ISomeCustomDataType>>`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T21:13:29.880",
"Id": "52975",
"Score": "0",
"body": "lol. ok. you code was Easier to read than mine as well. I was comparing and kept losing things, but I think that if I read through it rather than comparing it looks a lot cleaner. there was some coding that you did that I didn't know about or was unsure of how to use properly like `using (var getRecords = new SqlCommand(\"spRecapturePDF\", conn) { CommandType = CommandType.StoredProcedure })`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T21:14:13.180",
"Id": "52976",
"Score": "0",
"body": "with the info in the brackets, I like that."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T21:15:30.550",
"Id": "52977",
"Score": "1",
"body": "That's called Object Initializer Syntax. It allows you to assign values to an object's properties as part of a `new MyObject()` initialization."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-13T22:02:49.057",
"Id": "57188",
"Score": "0",
"body": "is it similar in VB?"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T19:58:27.677",
"Id": "33094",
"ParentId": "33087",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "33094",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T18:35:45.670",
"Id": "33087",
"Score": "5",
"Tags": [
"c#",
"sql-server",
"stream"
],
"Title": "Exporting PDF From Database back to PDF Format"
}
|
33087
|
<p>If you input the number 3 from the keyboard, the program will show this:</p>
<pre><code> 0
0 1 0
0 1 2 1 0
0 1 2 3 2 1 0
0 1 2 1 0
0 1 0
0
</code></pre>
<p>Here is my code:</p>
<pre><code>#include <iostream>
using namespace std;
int main()
{
unsigned i,k=0,n;
cout<<"n= "; cin>>n;
while(k<=n)
{
for (i=0;i<=k;i++)
cout<<i;
for (i=k;i>0;i--)
cout<<i-1;
cout<<endl;
k++;
}
k=n;
while (k)
{
k--;
for (i=0;i<=k;i++)
cout<<i;
for (i=k;i>0;i--)
cout<<i-1;
cout<<endl;
}
}
</code></pre>
<p>I have two questions:</p>
<ol>
<li><p>Is there a better/easier/clever way to do this?</p></li>
<li><p>How to deal with spaces? How to show them? (because my code is working but it doesn't show spaces to make this diamond look)</p></li>
</ol>
|
[] |
[
{
"body": "<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice\"><code>using namespace std</code></a> is not preferred, although not that bad for small programs.</p></li>\n<li><p>Each variable should be declared/initialized on separate lines. This improves readability and also makes it easier to add any necessary comments.</p>\n\n<pre><code>unsigned i;\nunsigned k = 0;\nunsigned n;\n</code></pre>\n\n<p>Same with this:</p>\n\n<pre><code>cout << \"n= \";\ncin >> n;\n</code></pre></li>\n<li><p>Prefer <code>\"\\n\"</code> to <a href=\"http://en.cppreference.com/w/cpp/io/manip/endl\" rel=\"nofollow noreferrer\"><code>std::endl</code></a> here (the latter flushes the buffer, which takes longer). It's still okay to use the latter where <em>both</em> flushing and newlining are needed.</p></li>\n<li><p>Always use descriptive names for variables. Single-characters are best for loop counters (such as <code>i</code>). This will vastly improve readability as you won't need comments to describe them.</p></li>\n<li><p>It looks like you could use recursion instead of all these loops. It may take longer (if you input a large number), but it should at least simplify the logic.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T20:00:07.487",
"Id": "52964",
"Score": "0",
"body": "You're absolutely right. Professors from high school where I learn are a little overwhelmed by these practices. I used to work in their way unfortunately. Thank you so much."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T20:02:15.690",
"Id": "52965",
"Score": "0",
"body": "@user2105306: Heck, my *college professors* still use `using namespace std` just because it's used in the books..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T02:46:31.013",
"Id": "53008",
"Score": "1",
"body": "Out of interest: why is `using namespace std` frowned upon?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T02:55:58.630",
"Id": "53010",
"Score": "0",
"body": "@KentBoogaart: That link explains most of it. Personally, I prefer to keep the STL separate from other code, since there's a lot of info in that namespace. Beyond that, it looks like many just dislike `using namespace X` in general. Although it's okay to have it local, I'm used to not using it at all. I was first told about this in my [first question](http://codereview.stackexchange.com/questions/22805/please-critique-my-c-deck-class) here."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T08:45:44.737",
"Id": "53033",
"Score": "1",
"body": "Sorry, didn't notice your link. I find the argument unconvincing, especially for `std`. It's like saying don't do `using System;` in .NET and instead write `System.Bla` or `global::System.Bla` everywhere. If I later update a dependency that also includes, say, a `Tuple<T>` type, then I can disambiguate as necessary at that point."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T18:44:28.443",
"Id": "59500",
"Score": "0",
"body": "The relation between *use recursion* and *don't use `std::endl`* seems a bit strange to me ;) ...I'd say in this case, performance isn't such an important issue."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-28T18:57:20.143",
"Id": "59502",
"Score": "0",
"body": "@Wolf: True, but I was primarily going after some minor aspects since I can't assess the algorithm too well (mainly why I just *mentioned* recursion without giving a relevant example)."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T19:10:56.313",
"Id": "33091",
"ParentId": "33088",
"Score": "10"
}
},
{
"body": "<p>Spacing could be accomplished using <a href=\"http://www.cplusplus.com/reference/iomanip/setw/\" rel=\"nofollow noreferrer\"><code>std::setw()</code></a>.</p>\n\n<p>The diamond-generating code should at least be in its own function — I suggest a function like <code>void diamond(std::ostream &out, int size)</code>. Keep <code>main()</code> simple: just read the size and call <code>diamond(std::cout, n)</code>. Better yet, you could define a <code>Diamond</code> class — see my <a href=\"https://codereview.stackexchange.com/a/31754/9357\">answer</a> to a similar question.</p>\n\n<p>From the linked example, also pick up some ideas about the loop structure and descriptive variable naming. Since this is an exercise and you have quite a bit of work ahead of you, I'll refrain from posting too many details here.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T19:47:31.530",
"Id": "33093",
"ParentId": "33088",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T18:39:04.323",
"Id": "33088",
"Score": "8",
"Tags": [
"c++",
"algorithm",
"formatting"
],
"Title": "Printing a diamond of numbers"
}
|
33088
|
<p>I am pushing an Excel file to the server and then reading it's contents. XLS and XLSX files need to be read differently, but the DLL that I'm using has the EXACT same function calls for both types. If I use a 'dynamic' type, I can save a lot of lines of code and avoid redundancy. However, I've been told many times before to avoid using dynamic if possible. Is this a good place to use it?</p>
<pre><code>dynamic excelFile; // is this a good use of dynamic?
switch (fileExtension)
{
case "xls":
excelFile = new Excel2007();
break;
case "xlsx":
excelFile = new Excel();
break;
default:
results.Message = string.Format("{0} is of an unrecognized format.", uploadFile.FileName);
return RedirectToAction("ImportWizard");
}
excelFile.OpenDatabase(targetPath, new FieldData());
excelFile.CurrentTable = excelFile.Tables[0];
var excelRecords = excelFile.ReadRecords(100);
excelFile.CloseDatabase();
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T01:26:06.630",
"Id": "53001",
"Score": "0",
"body": "Don't they have a common interface or base class?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T15:38:38.460",
"Id": "53067",
"Score": "0",
"body": "Not at this stage (wasn't sure if that was really needed), but if dynamic isn't a good choice here than I can implement that."
}
] |
[
{
"body": "<p>The prevalent answer is: No. (Funny enough, working with Office files seems to be a valid exception to the rule).</p>\n\n<p>The problem is that you don't have type validation anymore, and any issues will reveal themselves at run time.</p>\n\n<p>I'd say, if it's a small thing and it won't be touched or changed by people who might not know how it works, go for it (Even then, make sure you document this).</p>\n\n<p>Otherwise, an Interface approach sounds like a better idea, like ChrisWue's comment said.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T05:36:43.623",
"Id": "33117",
"ParentId": "33097",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "33117",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T23:05:15.853",
"Id": "33097",
"Score": "1",
"Tags": [
"c#",
"asp.net-mvc-4"
],
"Title": "Using 'dynamic' to save lines"
}
|
33097
|
<p>I've created an Ajax login for my website but I feel like I can optimize it, but I'm not sure how and where.</p>
<p>Questions:</p>
<ul>
<li>How can I optimize my code?</li>
<li>Is the code secure? Any ways to break it (injection, etc)?</li>
</ul>
<p>Also, when I attempt to log in, it currently takes about 1 second to process the login (on localhost). Is this long?</p>
<p>Here's my Ajax call:</p>
<pre><code>$(document).ready(function() {
$(document).on("submit", "form", function(event) {
event.preventDefault();
$.ajax({
url: 'assets/php/login_script.php',
type: 'POST',
data: $(this).serialize(),
success: function(data) {
if (data == true) {
window.location.href = "index.php";
} else {
$("input[name=password_field]").focus();
$(".error").html(data);
}
}
});
});
});
</code></pre>
<p>Here's the PHP script:</p>
<pre><code><?php
include_once("access.php");
$cxn = mysqli_connect($host, $user, $pass, $db) or die ("Couldn't connect to the server. Please try again.");
$username = $_POST["username"];
$password = $_POST["password"];
$date = date('Y-m-d h:i:s', time());
$ip_address = get_ip_address();
$expire = time() + 86400 * 365;
$options = array('cost' => 12);
$hash_password = password_hash($password, PASSWORD_BCRYPT, $options);
/* Log the login request. */
$stmt = $cxn->prepare("INSERT INTO login_logs (log_id, username, password, datetime, ip_address) VALUES ('', ?, ?, ?, ?)");
$stmt->bind_param('ssss', $username, $hash_password, $date, $ip_address);
$stmt->execute();
/* Get user information from database. */
$stmt = $cxn->prepare('SELECT * FROM users WHERE username = ?');
$stmt->bind_param('s', $username);
$stmt->execute();
$result = $stmt->get_result();
/* If a result exists, continue. */
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$db_username = $row['username'];
$db_password = $row['password'];
$random_hash = password_hash(time() . $db_username . time(), PASSWORD_BCRYPT, $options);
/* Password matches. */
if (password_verify($password, $db_password)) {
/* Get user's cookie information in database. */
$stmt2 = $cxn->prepare("SELECT * FROM cookies WHERE username = ?");
$stmt2->bind_param('s', $db_username);
$stmt2->execute();
$result2 = $stmt2->get_result();
/* If a result exists, update the cookie. */
if ($result2->num_rows > 0) {
$stmt = $cxn->prepare("UPDATE cookies SET hash = ? WHERE username = ?");
$stmt->bind_param('ss', $random_hash, $db_username);
$stmt->execute();
setcookie("user", $db_username, $expire, "/");
setcookie("hash", $random_hash, $expire, "/");
} else {
$stmt = $cxn->prepare("INSERT INTO cookies (cookie_id, username, hash) VALUES ('', ?, ?)");
$stmt->bind_param('ss', $db_username, $random_hash);
$stmt->execute();
setcookie("user", $db_username, $expire, "/");
setcookie("hash", $random_hash, $expire, "/");
}
echo true;
} else {
echo "Incorrect credentials.";
}
}
} else {
echo "Incorrect credentials.";
}
function get_ip_address() {
$ip_address = '';
if (getenv('HTTP_CLIENT_IP'))
$ip_address = getenv('HTTP_CLIENT_IP');
else if(getenv('HTTP_X_FORWARDED_FOR'))
$ip_address = getenv('HTTP_X_FORWARDED_FOR');
else if(getenv('HTTP_X_FORWARDED'))
$ip_address = getenv('HTTP_X_FORWARDED');
else if(getenv('HTTP_FORWARDED_FOR'))
$ip_address = getenv('HTTP_FORWARDED_FOR');
else if(getenv('HTTP_FORWARDED'))
$ip_address = getenv('HTTP_FORWARDED');
else if(getenv('REMOTE_ADDR'))
$ip_address = getenv('REMOTE_ADDR');
else
$ip_address = 'UNKNOWN';
return $ip_address;
}
?>
</code></pre>
<p>How can I optimize my script to look better, be faster, etc?</p>
|
[] |
[
{
"body": "<p>I've seen quite a few programmers who don't enjoy seeing arrays coming in as arguments into the code (me personally, I'm fine with it as long as there is some sort of documentation that goes with it so you don't forget what the function can and cannot take).</p>\n\n<pre><code>password_hash($password, PASSWORD_BCRYPT, $options);\n</code></pre>\n\n<p>would instead be:</p>\n\n<pre><code>password_hash($password, PASSWORD_BCRYPT, $cost);\n</code></pre>\n\n<p>The above is purely an FYI and not my opinion.</p>\n\n<p>When it comes to accepting username/passwords, you want to be sure you're on a secure location. Based on your current code, if you're only a http:// page (typically port 80) then a malicious bot can potentially sniff the username/password. Easiest way to do this, is run a check against <a href=\"https://stackoverflow.com/questions/5100189/use-php-to-check-if-page-was-accessed-with-ssl\">$_SERVER['HTTPS']</a> but if that fails, you do want to redirect the user to another page or something like that.</p>\n\n<p>You shouldn't have more than one user with the same username, so create a LIMIT 1 at the end of the SQL query, otherwise it'll scan the entire table no matter how many results you get.</p>\n\n<pre><code>$stmt = $cxn->prepare('SELECT * FROM users WHERE username = ? LIMIT 1 ');\n</code></pre>\n\n<p>Same concept for your cookies table lookup:</p>\n\n<pre><code>$stmt2 = $cxn->prepare(\"SELECT * FROM cookies WHERE username = ? LIMIT 1\");\n</code></pre>\n\n<p>Is there a purpose of creating additional variables that are essentially the same values of the initial variables?</p>\n\n<p>e.g.</p>\n\n<pre><code>$username = $_POST['username'];\n</code></pre>\n\n<p>What that ends up doing is you will use up additional memory blocks when it's not really needed to happen. Also, you could lose track of what $username is down the road, and re-initialize it with a different value. Same idea when you're looking at your <code>$row</code> data.</p>\n\n<p>PASSWORD_BCRYPT is not meant to be fast, but it is meant to be secure. You're running it twice, with different values, is there a reason you're doing that for your logs considering you can't reverse the encryption? I'd just run it once and put it against $hash_password</p>\n\n<p>If you're using time() multiple times across the page, that's when you may want to put that against a variable. Even though it's a very quick function, it'll be faster to look it up against a variable that has a fixed number and is stored in a particular memory block, creates a consistent value across the board in case you have to do additional comparisons against each other (compare something about the expiration date or check the value that got inserted into the log table and since that's a salt, might as well have that as a reference etc.).</p>\n\n<p>If the username/password verification feels like it takes a long time, then it is taking a long time, that's the way I see it. If you don't mind how long it takes, you might be ok (as saying 1 second is relative to the actual speed of the script). However, for bottlenecks, you'd have to test pieces of your code to see where is it slowest.</p>\n\n<p>Hope this helps.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T00:34:11.360",
"Id": "33101",
"ParentId": "33098",
"Score": "1"
}
},
{
"body": "<p>Before I begin I just wanted to correct/add to a couple of things from Duniyadnd's post.</p>\n\n<blockquote>\n <p>I've seen quite a few programmers who don't enjoy seeing arrays coming in as arguments</p>\n</blockquote>\n\n<p>Why? This is a rather vague statement that is misleading without context. There is a time and a place for everything. Are you using an indexed array, named keys or position reliant data, instead of/in addition to the argument list? Then yes, that array is most likely bad (APIs with flag arrays might get a pass here). Are you performing some generic repetitive task on a bunch of different elements? Well then, that array is plausible. Does using an array make your code less reusable? There are a number of factors to take into consideration and each situation will have to be evaluated for viability independently. Just saying don't pass arrays as arguments is horribly limiting.</p>\n\n<blockquote>\n <p>Is there a purpose of creating additional variables that are essentially the same values of the initial variables?</p>\n</blockquote>\n\n<p>Yes. Yes there is. This makes code cleaner, thus easier to read. The extra memory blocks this takes up is negligible, especially on today's computers, and is a type of micro optimization that qualifies for premature optimization. PHP may be built on C, but it does not require manual memory management. Additionally, in this instance, creating <code>$username</code> could be setting up to sanitize <code>$_POST[ 'username' ]</code>, which is a crucial step missing from this code (I'll get to this later).</p>\n\n<p>Now that I'm done with the previous answer, I'll move on to the question.</p>\n\n<p><strong>jQuery</strong></p>\n\n<p>In the below snippet <code>document</code> is a jQuery selector. Selectors tell jQuery what to include in the jQuery object. The more specific the selector, the smaller the object; The smaller the object, the easier and faster it is to find what you're looking for. When you tell jQuery you want to search <code>document</code> for a submit event you have to search the whole document. Unless the content on the page is loaded dynamically you don't have to query the whole document. Instead, limit your selector to search for your form. Additionally, querying jQuery for the same selector multiple times forces jQuery to build multiple identical objects. When you are going to be performing multiple tasks on the same jQuery selector you should properly reference it with a variable, or in this case you would have used <code>$( this )</code> as you were already in the <code>$( document ).ready()</code> scope. Finally, jQuery provides a <code>submit()</code> shortcut that does the same thing as <code>on( 'submit' )</code>.</p>\n\n<pre><code>$(document).on(\"submit\", \"form\", function(event) {\n//becomes\n$( '#formID' ).submit( function( event ) {\n</code></pre>\n\n<p>Since we are in the scope of our form now we can reference its action and method attributes to populate our <code>url</code> and <code>type</code> indices. Now if either of these attributes ever change you wont have to update your code to match. Its better to write your code so that you only have to make a change once rather than search for every use.</p>\n\n<pre><code>$this = $( this );\nurl: $this.attr( 'action' ),\ntype: $this.attr( 'method' ),\n</code></pre>\n\n<p>This goes for PHP and jQuery. If you are performing a loose comparison <code>==</code> and not an absolute comparison <code>===</code>, then there is no need to compare to an actual boolean. The following are equivalent.</p>\n\n<pre><code>if( data == true ) {\nif( data ) {\n\nif( data != true ) {\nif( ! data ) {\n</code></pre>\n\n<p><strong>PHP</strong></p>\n\n<p>The <code>*_once()</code> versions of <code>include</code> and <code>require</code> are slightly more demanding on PHP. When its just one include this is trivial, but you should get in the habit writing your code so that there is no circular logic that would make this necessary. That's not to say you shouldn't ever use the <code>*_once()</code> versions, just that they are typically unnecessary. This is dangerously close to violating premature optimization, but figured I'd point it out none-the-less.</p>\n\n<pre><code>include_once(\"access.php\");\n//change to\ninclude 'access.php';//you can add parenthesis if you wish, but they aren't necessary here\n</code></pre>\n\n<p>I noted above that I would be coming back to <code>$username</code>. Well, here it is. You should always sanitize user input, especially before uploading it to your database. There are many different ways to go about this, but for brevity I will use <code>filter_input()</code>.</p>\n\n<pre><code>$username = filter_input( INPUT_POST, 'username', FILTER_SANITIZE_STRING );\n</code></pre>\n\n<p>Get in the habit of returning early. Doing so will reduce your indentation, which in turn increases legibility. This kind of code is a prime example of the arrow anti-pattern. With the arrow anti-pattern you typically have a really large if statement, followed by a small else statement. If you reverse the if logic to match your else logic then you can perform the else block first and return early, thus allowing the rest of the code to continue execution at normal indentation.</p>\n\n<pre><code>if( ! password_verify( $password, $db_password ) ) {\n echo \"Incorrect credentials.\";\n return;//we returned early rest of code is pseudo else statement\n}\n\n//rest of original if statement\n</code></pre>\n\n<p>I don't pretend to be a security expert, but I don't imagine storing even a hashed password client-side is acceptable. What would this even be used for? I'm assuming you're using it as some sort of credentials check. In which case you should really look into using sessions instead.</p>\n\n<pre><code>setcookie(\"hash\", $random_hash, $expire, \"/\");\n//becomes\n$_SESSION[ 'hash' ] = $random_hash;\n//or better yet\n$_SESSION[ 'authenticated' ] = TRUE;\n</code></pre>\n\n<p>There are a number of things wrong with your <code>get_ip_address()</code> function. First and foremost is its repetition. First, you perform a boolean check on the return value of a function. Then, if it returns true, you query the same function again and set the results to a variable. That's two function calls when only one is necessary. Set it first then check it. Then you proceed to do the same thing for numerous other parameters. An array would be useful here. Create an array of all of your flags then loop over them to perform your search. Finally, once found there is no need to continue executing the script, you should return early again.</p>\n\n<pre><code>$flags = array(\n 'HTTP_CLIENT_IP',\n 'HTTP_X_FORWARDED_FOR',\n //etc...\n);\n\nforeach( $flags AS $flag ) {\n $temp = getenv( $flag );\n if( $temp ) {\n return $temp;//you could also use break here if you needed to do something else\n }\n}\n\nreturn 'UNKNOWN';\n</code></pre>\n\n<p>The last issue I saw was with your if statement syntax. PHP is not a braceless syntax language. Like many non-braceless languages, PHP promotes bad coding practices by continuing to allow semi-braceless syntax. For languages like Python, where you don't use braces, this is OK, but PHP inherently requires them, otherwise you wouldn't be limited to one line statements. And what does this save you really? Two bytes? Four or five if you add spacing? This is really a style preference, but it can easily become an issue if a more novice programmer takes over your code and doesn't understand this syntax.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-04T21:52:25.067",
"Id": "60241",
"Score": "0",
"body": "I'm glad you brought up your opinion about my post, but believe it should have been placed as a comment under mine so a discussion could place. I thought the my responses were clear about arguments-considering the context of this specific question. I'm glad you said it is quite vague without context. I do personally disagree that we should create additional variables that are essentially the same as $_POST to keep consistency and also keep track of where that information has come from. This allows the user to set rules for himself that they would never change the value of $_POST."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-05T04:25:39.707",
"Id": "33819",
"ParentId": "33098",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "33819",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-22T23:30:40.680",
"Id": "33098",
"Score": "1",
"Tags": [
"php",
"optimization",
"php5",
"ajax"
],
"Title": "How can I optimize my login script?"
}
|
33098
|
<p>I've made a carousel, which uses a function that is passed a target element, and from this element it adds next, prev, next next, and prev prev classes to its siblings (causing the rotation) - what do they call this, pyramid code?</p>
<p>Looking at this code - it works, but can't stand know that there is probably a better way to write this:</p>
<pre><code> var render = function (cont) {
cont.parent().find('.active').removeClass();
cont.attr('class', 'active');
cont.parent().children().removeClass('next prev next_next prev_prev');
cont.next().attr('class', 'next');
cont.prev().attr('class', 'prev');
cont.next().next().attr('class', 'next_next');
cont.prev().prev().attr('class', 'prev_prev');
};
</code></pre>
|
[] |
[
{
"body": "<p>You can remove the <code>active</code> class along with the other classes, and you can chain the <code>prev</code> and <code>next</code> calls:</p>\n\n<pre><code>var render = function (cont) {\n cont.parent().children().removeClass('active next prev next_next prev_prev');\n cont.addClass('active');\n cont.next().addClass('next').next().addClass('next_next');\n cont.prev().addClass('prev').prev().addClass('prev_prev'); \n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T01:46:39.707",
"Id": "33102",
"ParentId": "33100",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "33102",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T00:12:37.977",
"Id": "33100",
"Score": "1",
"Tags": [
"javascript",
"jquery",
"object-oriented"
],
"Title": "Carousel using a function passed a target element"
}
|
33100
|
<p>New to Go, trying to solve <a href="http://tour.golang.org/#56" rel="nofollow">Tour of Go, Exercise 56</a>, which is about error handling.</p>
<p>Can the following error handling method can be further improved?</p>
<pre><code>package main
import (
"fmt"
"math"
)
type ErrNegativeSqrt float64
func (e ErrNegativeSqrt) Error() string {
return fmt.Sprintf("cannot Sqrt negative number: %f", float64(e))
}
func Sqrt(f float64) (float64, error) {
if f > 0 {
return math.Sqrt(f), nil
} else {
return 0, ErrNegativeSqrt(f)
}
}
func main() {
fmt.Println(Sqrt(2))
fmt.Println(Sqrt(-2))
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-12-08T08:29:35.710",
"Id": "60702",
"Score": "0",
"body": "Minor point, but you don't need to wrap the `return 0, ErrNegativeSqrt(f)` in an else block. The `go vet` tool would complain about this."
}
] |
[
{
"body": "<p>I would name the error <code>ErrSqrtNegative</code> instead of <code>ErrNegativeSqrt</code>.</p>\n\n<p><code>Sqrt(0)</code> should not be an error.</p>\n\n<p>In case of error, I would use <code>math.NaN(), ErrSqrtNegative(f)</code> as the return values.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T05:34:41.370",
"Id": "53022",
"Score": "1",
"body": "Hmm. It looks like the [exercise](http://tour.golang.org/#56) calls for the error to be named `ErrNegativeSqrt`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T05:31:39.967",
"Id": "33116",
"ParentId": "33104",
"Score": "1"
}
},
{
"body": "<p>For example,</p>\n\n<pre><code>package main\n\nimport (\n \"fmt\"\n \"math\"\n)\n\ntype ErrNegativeSqrt float64\n\nfunc (e ErrNegativeSqrt) Error() string {\n return fmt.Sprintf(\"cannot Sqrt negative number: %g\", e)\n}\n\nfunc Sqrt(f float64) (float64, error) {\n if f < 0 {\n return 0, ErrNegativeSqrt(f)\n }\n const delta = 1e-12\n z := f\n for {\n zz := z\n z -= (z*z - f) / (2 * z)\n if math.Abs(z-zz) < delta {\n break\n }\n }\n return z, nil\n}\n\nfunc main() {\n fmt.Println(Sqrt(2))\n fmt.Println(Sqrt(-2))\n}\n</code></pre>\n\n<p>Output:</p>\n\n<pre><code>1.414213562373095 <nil>\n0 cannot Sqrt negative number: -2\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-28T17:26:24.933",
"Id": "67794",
"Score": "0",
"body": "Code-only answers do not constitute a review. Please explain how your changes improve the original code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T13:53:33.257",
"Id": "33230",
"ParentId": "33104",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": "33116",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T03:13:48.930",
"Id": "33104",
"Score": "1",
"Tags": [
"go",
"error-handling"
],
"Title": "A Tour of Go, problem #56 - error handling"
}
|
33104
|
<p>I have a working bloc of code that is a fairly ugly set of for, if and else's. I'm looking to clean it up, but I'm seeking advice on how to do so.</p>
<pre><code>public String getContents() {
if (Blanks.size() > madLibsContent.size()) {
for(int i = 0; i <= Blanks.size() - 1; i++) {
if (i == 0)
contents += Blanks.get(i).getBlankValue() + " " + madLibsContent.get(i) + " ";
else if (i == Blanks.size() - 1)
contents += Blanks.get(i).getBlankValue();
else
contents += Blanks.get(i).getBlankValue() + " " + madLibsContent.get(i) + " ";
}
} else if (Blanks.size() < madLibsContent.size()) {
for(int i = 0; i <= madLibsContent.size() - 1; i++){
if (i == madLibsContent.size() - 1)
contents += madLibsContent.get(i);
else
contents += madLibsContent.get(i) + " " + Blanks.get(i).getBlankValue() + " ";
}
} else {
for(int i = 0; i <= madLibsContent.size() - 1; i++){
if (i == madLibsContent.size() - 1)
contents += madLibsContent.get(i) + " " + Blanks.get(i).getBlankValue();
else
contents += madLibsContent.get(i) + " " + Blanks.get(i).getBlankValue() + " ";
}
}
return contents;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-11T16:18:09.897",
"Id": "53011",
"Score": "2",
"body": "First indent it properly. Then only you can proceed further."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-11T16:23:34.027",
"Id": "53012",
"Score": "0",
"body": "Extracting methods is never a bad idea in such a huge block of code. Start with extracting three methods for the three if conditions and three methods for the three loops. Next would be creating a class for this getContents() thing."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-11T16:40:36.320",
"Id": "53013",
"Score": "0",
"body": "@Dgrin91 The \"also\" may be misleading in that sentence. Just to clarify, it doesn't really belong on [so]."
}
] |
[
{
"body": "<p>Where you have the pattern of: </p>\n\n<pre><code>for(int i = 0; i <= madLibsContent.size() - 1; i++){\n if (i == madLibsContent.size() - 1)\n contents += madLibsContent.get(i) + \" \" + Blanks.get(i).getBlankValue();\n else\n contents += madLibsContent.get(i) + \" \" + Blanks.get(i).getBlankValue() + \" \";\n}\n</code></pre>\n\n<p>Replace it with:</p>\n\n<pre><code>for(int i = 0; i <= madLibsContent.size() - 1; i++){\n contents += madLibsContent.get(i) + \" \" + Blanks.get(i).getBlankValue();\n\n if (i < madLibsContent.size() - 1) \n contents += \" \";\n}\n</code></pre>\n\n<p>Hint: Avoid copying and pasting code.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-11T16:25:57.217",
"Id": "53014",
"Score": "1",
"body": "Yes, and manually typing the exact same line of code does not count as \"avoiding copy and paste!\" :-)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-11T16:22:05.107",
"Id": "33106",
"ParentId": "33105",
"Score": "2"
}
},
{
"body": "<pre><code>public String getContents(){\n if (Blanks.size() > madLibsContent.size()){\n for(int i = 0; i <= Blanks.size() - 1; i++){\n contents += Blanks.get(i).getBlankValue();\n if (i != (Blanks.size() - 1))\n contents += \" \" + madLibsContent.get(i) + \" \";\n }\n }\n else if (Blanks.size() < madLibsContent.size()){\n for(int i = 0; i <= madLibsContent.size() - 1; i++){\n contents += madLibsContent.get(i);\n if (i != (madLibsContent.size() - 1))\n contents += \" \" + Blanks.get(i).getBlankValue() + \" \";\n }\n }\n else{\n for(int i = 0; i <= madLibsContent.size() - 1; i++){\n contents += madLibsContent.get(i) + Blanks.get(i).getBlankValue();\n if (i != (madLibsContent.size() - 1))\n contents += \" \";\n }\n }\n\n return contents;\n}\n</code></pre>\n\n<hr>\n\n<p>First step was clearing out the redundancies: anything that occurs in all if-else statements should be moved outside of them. Then it was just some logic fiddling to get the additional parts added.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-11T16:25:07.093",
"Id": "33107",
"ParentId": "33105",
"Score": "0"
}
},
{
"body": "<p>It looks like you'd get an <code>ArrayIndexOutOfBoundsException</code> because when the one's bigger, you'd still try to access elements at those indices in the other one. The <code>i == Blanks.size()-1</code> should probably be <code>i >= madLibsContent.size()</code> (and similar changes for the other checks).</p>\n\n<p>Assuming this is the case, below is a shorter, hopefully correct, version.</p>\n\n<pre><code>public String getContents()\n{\n int max = Math.max(Blanks.size(), madLibsContent.size());\n for(int i = 0; i < max; i++)\n {\n if (i < Blanks.size())\n {\n contents += Blanks.get(i).getBlankValue();\n if (i < madLibsContent.size())\n contents += \" \";\n }\n if (i < madLibsContent.size())\n contents += madLibsContent.get(i);\n if (i != max-1)\n contents += \" \";\n }\n return contents;\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-11T16:48:31.547",
"Id": "53015",
"Score": "0",
"body": "Much cleaner than mine, but for some reason, I'm getting an error on the last two if statements. The i cannot be resolved for some reason."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-11T17:01:14.843",
"Id": "53016",
"Score": "0",
"body": "@user2871716 The most likely cause is that there's a `}` that shouldn't be there, or there are too few `{`'s. The code as above compiles (as long as I define `contents`, `Blanks` and `madLibsContent` somewhere)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-11T16:30:18.470",
"Id": "33108",
"ParentId": "33105",
"Score": "0"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-11T16:17:35.790",
"Id": "33105",
"Score": "-2",
"Tags": [
"java"
],
"Title": "Cleaning up a nasty looking loop"
}
|
33105
|
<p>I use the Repository/Service design pattern in my projects and I have found something that might be a bit redundant. Am I writing any unnecessary code?</p>
<p>With that in mind, here is my structure:</p>
<pre><code>public class Competition
{
public int Id { get; set; }
[Required] public string UserId { get; set; }
public string UserName { get; set; }
public DateTime DateCreated { get; set; }
public DateTime? DateModified { get; set; }
[Required] public string Name { get; set; }
}
</code></pre>
<p>This is an example POCO class, but as you will see I am using <code>Generics</code> so it can be anything:</p>
<pre><code>internal interface IRepository<TEntity> : IDisposable where TEntity : class
{
IList<TEntity> GetAll();
TEntity Get(int id);
void Save(TEntity model);
void Delete(int id);
}
</code></pre>
<p>My <code>interface</code> implements <code>IDisposable</code> and allows any class object to be set as <code>TEntity</code>:</p>
<pre><code>internal class CompetitionRepository : IRepository<Competition>
{
private readonly string userId;
private readonly CompetitionProvider provider;
public CompetitionRepository(string userId) : this(userId, "DefaultConnection")
{
}
public CompetitionRepository(string userId, string connectionString)
{
this.userId = userId;
this.provider = new CompetitionProvider(connectionString);
}
public IList<Competition> GetAll()
{
return provider.Get(this.userId);
}
public Competition Get(int id)
{
return GetAll().Where(model => model.Id == id).SingleOrDefault();
}
public void Save(Competition model)
{
provider.Save(model);
}
public void Delete(int id)
{
provider.Delete(id);
}
public void Dispose()
{
provider.Dispose();
}
}
</code></pre>
<p>My repository which implements <code>IRepository</code>, specifying <code>Competition</code> as <code>TEntity</code>. This repository queries my database hence the provider.</p>
<p>In this repository, I only do the minimal of what is required to query my database:</p>
<pre><code>public class CompetitionService : IRepository<Competition>
{
private readonly string userId;
private readonly IRepository<Competition> repository;
public CompetitionService(string userId) : this(userId, "DefaultConnection")
{
}
public CompetitionService(string userId, string connectionString)
{
this.userId = userId;
this.repository = new CompetitionRepository(this.userId, connectionString);
}
public IList<Competition> GetAll()
{
return this.repository.GetAll();
}
public Competition Get(int id)
{
return this.repository.Get(id);
}
public void Save(Competition model)
{
if (model.Id > 0)
{
model.UserId = userId;
model.DateCreated = DateTime.UtcNow;
} else
{
model.DateModified = DateTime.UtcNow;
}
this.repository.Save(model);
}
public void Delete(int id)
{
this.repository.Delete(id);
}
public void Dispose()
{
this.repository.Dispose();
}
}
</code></pre>
<p>Now this is my service. For example, you can see the <code>Save</code> method assigns values depending on whether we are creating or updating. A <code>Service</code> class can have anything in there, for example performing an uploads or whatever is not related to data source.</p>
<p>The <code>Repository</code> is there to interact with the data source only and no other code is present. This allows for swapping out the repository with another that queries a different data source.</p>
<p>My problem is that I have noticed that, although the service has code that modifies and corrects the values before they are then saved via the repository, the structure is always very similar to the repository, i.e. it has:</p>
<p><code>GetAll()</code></p>
<p><code>Get()</code></p>
<p><code>Save()</code></p>
<p><code>Delete()</code></p>
<p>I have implemented <code>IRepository<Competition></code> as well. The service may have other public methods, but it doesn't matter because, in my controllers, I would call it like this:</p>
<pre><code>//
// POST: /Competitions/Create
[HttpPost]
public ActionResult Create(Competition model)
{
try
{
using (var service = new CompetitionService(User.Identity.GetUserId()))
{
service.Save(model);
}
return RedirectToAction("Index");
}
catch
{
return View(model);
}
}
</code></pre>
<ol>
<li>Do you think it is good practice or do you think I am over-killing it a bit?</li>
<li>Do you think I should implement <code>IRepository</code> on the service?</li>
<li>In the more extreme case, do you think I should even bother with a service?</li>
</ol>
<p>(NB: I am reluctant to remove the service because sometimes there is a lot of code that needs to go in there that I don't want clogging up my controllers)</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-10T13:03:43.950",
"Id": "53017",
"Score": "0",
"body": "Why ou not use the UnitOfWork pattern as described in the Martin blog http://martinfowler.com/eaaCatalog/unitOfWork.html just remove the save and the delete methods from the Repository interface and do this job in the commit of the unit of work."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T13:52:53.887",
"Id": "53049",
"Score": "1",
"body": "Interfaces shouldn't \"implement\" IDisposable, only the concrete implementation should, otherwise it's a *leaky abstraction*. Mock repos are disposable?"
}
] |
[
{
"body": "<p>You are on the right track. The separation of business logic (services) and data-access logic (repositories) is a good thing, I strongly recommend this. I created a generic repository implementing the <code>IRepository<TEntity></code> interface. It's slightly different than yours, but you get the point (I have a <code>BaseEntity</code> constraint, you can also use <code>class</code> for this):</p>\n\n<pre><code>public class EfRepository<TEntity> : IRepository<TEntity>\n where TEntity : BaseEntity, new()\n{\n private readonly IDbContext _context;\n private IDbSet<TEntity> _entities;\n\n public EfRepository(IDbContext context)\n {\n _context = context;\n }\n\n private IDbSet<TEntity> Entities\n {\n get { return _entities ?? (_entities = _context.Set<TEntity>()); }\n }\n\n public TEntity GetById(object id)\n {\n return Entities.Find(id);\n }\n\n public void Insert(TEntity entity)\n {\n Entities.Add(entity);\n _context.SaveChanges();\n }\n\n public void Update(TEntity entity)\n {\n _context.SaveChanges();\n }\n\n public void Delete(int id)\n {\n // Create a new instance of an entity (BaseEntity) and add the id.\n var entity = new TEntity\n {\n ID = id\n };\n\n // Attach the entity to the context and call the delete method.\n Entities.Attach(entity);\n Delete(entity);\n }\n\n public void Delete(TEntity entity)\n {\n Entities.Remove(entity);\n _context.SaveChanges();\n }\n\n public IList<TEntity> Table\n {\n get { return Entities.ToList(); }\n }\n}\n</code></pre>\n\n<p>This greatly reduces the amount of duplicate code when you would use specific repositories. I use this in my services like:</p>\n\n<pre><code>public class ProductService : IProductService\n{\n private readonly IRepository<Product> _productRepository;\n\n public ProductService(IRepository<Product> productRepository)\n {\n _productRepository = productRepository;\n }\n\n public bool AddProduct(Product product)\n {\n // Validate etc.\n _productRepository.Insert(product);\n\n // return validation result.\n return true;\n }\n}\n</code></pre>\n\n<p>As you may have noticed I use an IoC framework to inject the dependencies.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-10T17:12:11.617",
"Id": "53018",
"Score": "0",
"body": "Yeah, it seems all the answers use dependency injection. I hadn't thought of it properly, I shall adapt this also. Cheers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T02:47:04.147",
"Id": "76186",
"Score": "0",
"body": "What is the IoC framework you are using? Also, how do you go about configuring the EfRepository<TEntity> injection?\nUsing AutoFac, I've done something like:\nbuilder.RegisterAssemblyTypes(typeof(ProjectRepository).Assembly).Where(t => to.Name.EndsWith(\"Repository\")).AsImplementedInterfaces()...\nWho would that transfer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-03-11T08:23:44.610",
"Id": "76211",
"Score": "0",
"body": "@mickyjtwin I'm using [Simple Injector](https://simpleinjector.codeplex.com/) which allows me to do: `container.RegisterOpenGeneric(typeof (IRepository<>), typeof (EfRepository<>));`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-13T22:43:51.293",
"Id": "82512",
"Score": "0",
"body": "@HenkMollema, all you explained seems to make sense, but I've got little problem. My repository implements IDisposable. Advantage of my solution is that repositories operate on simple db operations and I decide when to close db connection. Problem is when I want to use repository in service. I would like to dispose IRepository in the end of each Service Method. I need some way to save Type of IRepository, not concrete instance. I considered using code reflections, but I am afraid of performance and it will look ugly I concerned. Do you know some design pattern or tool to achieve my aim?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T06:20:12.537",
"Id": "82543",
"Score": "0",
"body": "http://pastebin.com/Quhp8Mz7 - here is example of solution I thought of."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T07:27:49.497",
"Id": "82559",
"Score": "0",
"body": "The creation and lifetime of interface implementations (DbRepository<T> for example) should be managed by an [IoC container](http://en.wikipedia.org/wiki/Inversion_of_control). Newing up classes like you do in the constructor is a bad design and causes tight coupling to infrastructure code and frameworks. What are you trying to achieve by saving the concrete type?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T16:12:03.907",
"Id": "82612",
"Score": "0",
"body": "I want only to add multiple using statements. As far as I know, if you dispose object, it becomes unusable and should be instatiated again."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T16:31:20.093",
"Id": "82622",
"Score": "0",
"body": "I found the other question and answer I meant! Look [here](http://stackoverflow.com/questions/12360271/what-happens-to-using-statement-when-i-move-to-dependency-injection). Tell me please, what do you think about that one accepted answer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-14T18:50:20.367",
"Id": "82641",
"Score": "0",
"body": "@pt12lol I think it'll work. But this is not the way to ask questions, please create a new question."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-30T17:53:27.817",
"Id": "90223",
"Score": "0",
"body": "why is the service \"Implementing\" the repository, from my perspective, the service should be using the repositories behaviors, not defining them"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-05-30T21:53:36.650",
"Id": "90272",
"Score": "0",
"body": "@hanzolo how is the service implementing the repository? It's just being injected into the constructor and used in the service methods."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-08T17:07:22.657",
"Id": "119374",
"Score": "0",
"body": "@HenkMollema - i must have been talking about the Op's code, but then i just took a deeper look and see what it's doing.. you're implementation is my preferred layering technique"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-12-03T17:10:09.983",
"Id": "130769",
"Score": "0",
"body": "@HenkMollema How do you split your repository and service interfaces and concrete implementations across projects?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-31T10:15:00.177",
"Id": "154002",
"Score": "0",
"body": "@HenkMollema - with your solution above. Are you using the EF Pocos in your service layer?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-31T10:23:12.790",
"Id": "154005",
"Score": "0",
"body": "@Stokedout basically, yes. Although the entities are (or at least should) not tied completely to EF. You might want to create specific EF entities (DTO's) and map them to their domain models or POCO's."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-03-31T10:25:11.913",
"Id": "154008",
"Score": "0",
"body": "@dav_i sorry for my late reaction. They can be next to each other. Although, the best practice is to have implementation agnostics interfaces in some 'Core' layer and have their implementation in a separate assembly which is injected at runtime."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-10T19:26:50.543",
"Id": "420157",
"Score": "1",
"body": "You are implementing **repository on top of repository**. It only adds extra complexity to your app."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-11-28T16:49:38.207",
"Id": "455584",
"Score": "0",
"body": "As @AlexHerman says, it's repository on top of repository. If you have a repository and a service and they both provide exactly the same public interface, then consumers could use either the service or the repository and it would not matter. It does not make sense. So why implement the same interface twice while calling one a service and one a repo? As long as your service is doing only CRUD, call it repository. If your service is doing smth else as well besides CRUD, put that into (n) another service(s). Separation of concerns."
}
],
"meta_data": {
"CommentCount": "18",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-10T12:50:29.573",
"Id": "33110",
"ParentId": "33109",
"Score": "25"
}
},
{
"body": "<p><strong>First of all:</strong> Why don't you implement your repo as generic? I mean the implementation of generic interface. In your solution, you have to create an <code>IRepository<Entity></code> implementation for each new POCO. That will bloat your code, and you will not get any use of generic interface.</p>\n\n<p>Here is the example of generic repo implementation:</p>\n\n<pre><code>public class Repository<T> : IRepository<T> where T : class, new()\n{\n private IYourContext _context;\n\n public Repository(IYourContext context)\n {\n this._context = context;\n }\n\n public IQueryable<T> All\n {\n get { return _context.Set<T>(); }\n }\n\n public T Find(int id)\n {\n return _context.Set<T>().Find(id);\n }\n\n public void Delete(T entity)\n {\n if (_context.Entry(entity).State == EntityState.Detached)\n _context.Set<T>().Attach(entity);\n _context.Set<T>().Remove(entity);\n }\n\n public void Insert(T entity)\n {\n _context.Set<T>().Add(entity);\n }\n\n public void Update(T entity)\n {\n _context.Set<T>().Attach(entity);\n _context.Entry(entity).State = EntityState.Modified;\n }\n}\n</code></pre>\n\n<p>You can have different methods in your interface and implementation. If that's not the case, then you can use your repo like so:</p>\n\n<pre><code>IRepository<YourPOCO> repo = new Repository<YourPOCO>();\n</code></pre>\n\n<p><strong>Second:</strong> There is a pattern <code>Unit Of Work</code> that is often implemented with Generic Repository pattern. It is a wrapper around repositories that provides a way of sharing one context between all of them.</p>\n\n<p>Here is the example:</p>\n\n<pre><code>public interface IUnitOfWork : IDisposable\n{\n IRepository<Product> ProductRepository { get; }\n // other repositories \n\n void SaveChanges();\n void RollbackChanges();\n}\n</code></pre>\n\n<p>And the implementation:</p>\n\n<pre><code>public class UnitOfWork : IUnitOfWork\n{\n private IRepository<Product> _productRepository;\n private IYourContext _context;\n private bool _disposed = false;\n\n public UnitOfWork(IYourContext context)\n {\n this._context = context;\n }\n\n // Lazy Loading pattern is also often used here\n public IRepository<Product> ProductRepository\n {\n get\n {\n if (this._productRepository == null)\n this._productRepository = new Repository<Product>(_context);\n return _productRepository;\n }\n }\n\n public void SaveChanges()\n {\n _context.SaveChanges();\n }\n\n // implement other functionality\n}\n</code></pre>\n\n<p>With unit of work, when you've made changes in different repositories, you just need to call <code>SaveChanges()</code> method of the <code>UnitOfWork</code> class only once. So, it will be a single transaction.</p>\n\n<p>Also, maybe you've noticed, I use interfaces everywhere, even in the db context implementation. That will help you to unit test your logic in the future if needed. And use <code>Dependency Injection</code>!</p>\n\n<p>For the context:</p>\n\n<pre><code>public interface IYourContext : IDisposable\n{\n DbSet<T> Set<T>() where T : class;\n DbEntityEntry Entry(object entry);\n int SaveChanges();\n}\n\npublic class YourContext : DbContext, IYourContext\n{\n public NorthwindContext(IConnectionFactory connectionFactory) : base(connectionFactory.ConnectionString) { }\n\n public DbSet<Product> Products { get; set; }\n // other DbSets ..\n}\n</code></pre>\n\n<p>And a connection factory (without it you will get an exception in the DI container):</p>\n\n<pre><code>public interface IConnectionFactory\n{\n string ConnectionString { get; }\n}\n\npublic class ConnectionFactory : IConnectionFactory\n{\n public string ConnectionString\n {\n get { return \"YourConStringName\"; }\n }\n}\n</code></pre>\n\n<p><strong>To summarize:</strong> Implement generic repository and unit of work patterns as a DAL (Data Access Layer) and then you can build any service layers with your BL (Business Logic) on top of them.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-10T17:11:14.097",
"Id": "53019",
"Score": "0",
"body": "Great answer, thanks I have marked this as the answer along with the others. I shall have a look at the UnitOfWork pattern as I have not used that before. Cheers"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-08T17:09:16.913",
"Id": "119376",
"Score": "4",
"body": "I've read the unitofwork is taken care of by EF?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2018-04-10T17:19:19.507",
"Id": "368033",
"Score": "0",
"body": "@hanzolo yes, and the repository pattern too. Check this https://softwareengineering.stackexchange.com/a/220126/198700"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-10T12:53:43.323",
"Id": "33111",
"ParentId": "33109",
"Score": "13"
}
},
{
"body": "<p>I sometimes dream that I'm a god but my real-life situation couldn't be further from that.</p>\n\n<p>I am however willing to share my thoughts on your situation.</p>\n\n<p>First of all I would never get rid of your service layer, I am totally in favor of having your controllers as lightweight as possible!</p>\n\n<p>I'm not sure what you are using behind that repository layer, but by the looks of it your respository classes are not doing much besides passing the calls through. Maybe make a generic respository that handles most entities and if you need something more specific create a new respository?</p>\n\n<p>You could also consider using your <code>Provider</code> directly from your service and treat this <em>provider</em> as a repository.</p>\n\n<p>As for the <code>IRepository</code> in the service layer, I must say I'm against it. If you set up your service as a repository then your controller is limited to these CRUD-like methods. This might work out early on if you just have CRUD-like screens but I'm not a big fan of looking at services this way.</p>\n\n<p>In my opinion the service should provide a method for every logical action that you want to do with that entity.</p>\n\n<p><code>Save</code> and <code>Edit</code> can be a part of that, but so would be <code>AddNewAnswerToQuestion</code>, <code>RaiseFlagToQuestion</code>, <code>AddTagToQuestion</code> (for example). I fear that if you limit yourself to CRUD-like methods you will either have to make a lot of <code>if</code> structures in your <code>Save</code> method (if tag has been added, if flag has been set) or your controller will end up doing more and more work (call <code>Save</code> method, then call <code>Mail</code> method because a mail needs to be sent in case of an extra tag).</p>\n\n<p>If you take this a bit more extreme you no longer make a <em>service per entity</em> but a <em>service per action</em>.</p>\n\n<p>At that point you stop calling them <em>services</em> and start calling them <em>commands</em>, and use <a href=\"http://en.wikipedia.org/wiki/Command%E2%80%93query_separation\">CQS (Command-Query Separation)</a> but that choice is up to you :)</p>\n\n<p>So in short, I would make a generic repository, or remove them altogether and make my services more explicit by either making more methods or creating <em>commands</em> instead of <em>services</em>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-10T17:12:32.570",
"Id": "53020",
"Score": "0",
"body": "Nice comment, you said everything I was thinking :) Cheers"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-10T12:57:26.570",
"Id": "33112",
"ParentId": "33109",
"Score": "14"
}
}
] |
{
"AcceptedAnswerId": "33110",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-10T12:38:56.607",
"Id": "33109",
"Score": "51",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Repository/Service Design Pattern"
}
|
33109
|
<p>I've been doing bits and bobs with Python for a few years, but I've never took the time to get feedback on what's pythonic and what's not. In the interest of collaborating more with Python programmers, I'd like to make sure my code follows conventions and idioms that the majority of Pythonistas will recognize.</p>
<p>Please review my Kitchen Timer class for:</p>
<ul>
<li>pythonic idioms and conventions</li>
<li>behavioural correctness (especially around multi-threading and timing precision)</li>
<li>portability</li>
<li>readability</li>
<li>maintainability</li>
<li>efficiency</li>
</ul>
<p>Also, if the purpose of the class is unclear from its API and comments, please offer your suggestions for improvement there too.</p>
<pre><code>from threading import Timer as TTimer
from time import time
from threading import Lock
class NotRunningError(Exception): pass
class AlreadyRunningError(Exception): pass
class KitchenTimer(object):
'''
Loosely models a clockwork kitchen timer with the following differences:
You can start the timer with arbitrary duration (e.g. 1.2 seconds).
The timer calls back a given function when time's up.
Querying the time remaining has 0.1 second accuracy.
'''
running = "running"
stopped = "stopped"
timeup = "timeup"
def __init__(self):
self.__stateLock = Lock()
self.state = self.stopped
self.__timeRemainingLock = Lock()
self.timeRemaining = 0
def start(self, duration=1, whenTimeup=None):
if self.isRunning():
raise AlreadyRunningError
else:
self.state = self.running
self.timeRemaining = duration
self._userWhenTimeup = whenTimeup
self._startTime = self._now()
self._timer = TTimer(duration, self._whenTimeup)
self._timer.start()
def stop(self):
if self.isRunning():
self._timer.cancel()
self.state = self.stopped
self.timeRemaining -= self._elapsedTime()
else:
raise NotRunningError()
def isRunning(self):
return self.state == self.running
def isTimeup(self):
if self.state == self.timeup:
return True
else:
return False
@property
def state(self):
with self.__stateLock:
return self._state
@state.setter
def state(self, state):
with self.__stateLock:
self._state = state
@property
def timeRemaining(self):
with self.__timeRemainingLock:
if self.isRunning():
self._timeRemaining -= self._elapsedTime()
return round(self._timeRemaining, 1)
@timeRemaining.setter
def timeRemaining(self, timeRemaining):
with self.__timeRemainingLock:
self._timeRemaining = timeRemaining
def _whenTimeup(self):
self.state = self.timeup
self.timeRemaining = 0
if callable(self._userWhenTimeup):
self._userWhenTimeup()
def _now(self):
return time()
def _elapsedTime(self):
return self._now() - self._startTime
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T06:31:47.740",
"Id": "53028",
"Score": "0",
"body": "I've just noticed I have two different styles for a predicate. One with explicit True or False, one implicit. Whoops."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T07:03:35.293",
"Id": "53030",
"Score": "0",
"body": "Someone once linked this http://www.python.org/dev/peps/pep-0008/ to me, and I found it very useful when I needed to learn the Python syntax and conventions."
}
] |
[
{
"body": "<h3>1. Bugs</h3>\n\n<ol>\n<li><p>You have two locks, one protecting <code>state</code>, and the other protecting <code>timeRemaining</code>. But these locks operate independently. That means that when you update both of these properties:</p>\n\n<pre><code>self.state = self.timeup\nself.timeRemaining = 0\n</code></pre>\n\n<p>it would be possible for another thread to run in between these two statements and see <code>state == timeup</code> but <code>timeRemaining != 0</code>. You need one lock to protect both properties, so that they are updated atomically. See below for some race conditions that are consequences of this bug.</p></li>\n<li><p>The <code>timeRemaining</code> property updates the <code>_timeRemaining</code> value by subtracting the elapsed time. But this means that if you keep requesting the <code>timeRemaining</code> property, it will keep subtracting the elapsed time, giving you nonsense like this:</p>\n\n<pre><code>>>> t = KitchenTimer()\n>>> t.start(5)\n>>> t.timeRemaining\n3.2\n>>> t.timeRemaining\n0.6\n>>> t.timeRemaining\n-2.6\n>>> t.timeRemaining\n-6.6\n>>> t.timeRemaining\n-11.3\n>>> t.timeRemaining\n0.0\n</code></pre></li>\n<li><p>There's a race condition between the <code>start</code> method and the <code>whenTimeup</code> method. In <code>start</code> you have:</p>\n\n<pre><code>if self.isRunning(): # 1\n raise AlreadyRunningError \nelse:\n self.state = self.running # 2\n self.timeRemaining = duration # 3\n</code></pre>\n\n<p>and in <code>_whenTimeUp</code> you have:</p>\n\n<pre><code>self.state = self.timeup # 4\nself.timeRemaining = 0 # 5\n</code></pre>\n\n<p>A possible order of execution is 4–1–2–3–5 which would set <code>state</code> to <code>running</code> and <code>timeRemaining</code> to 0.</p></li>\n<li><p>There's a race condition between the <code>stop</code> method and the <code>_whenTimeup</code> method. In <code>stop</code> you have:</p>\n\n<pre><code>if self.isRunning(): # 1\n self._timer.cancel() # 2\n self.state = self.stopped # 3\n</code></pre>\n\n<p>and in <code>_whenTimeUp</code> you have:</p>\n\n<pre><code>self.state = self.timeup # 4\n</code></pre>\n\n<p>A possible order of execution is 1–4–2–3 which would leave <code>state</code> as <code>stopped</code> when it ought to be <code>timeup</code>.</p>\n\n<p>(There may well be more race conditions; I haven't looked very hard.)</p></li>\n</ol>\n\n<h3>2. Comments on your code</h3>\n\n<ol>\n<li><p>Why \"Kitchen\" timer? The class doesn't seem to have anything to do with kitchens.</p></li>\n<li><p>There doesn't seem to be any documentation for the methods.</p></li>\n<li><p>Why does the <code>timeRemaining</code> method round the result to one decimal place? There doesn't seem to be any explanation of this. It would be more natural to return the actual time remaining.</p></li>\n<li><p>Why do you rename <code>threading.Timer</code> as <code>TTimer</code>? The name <code>Timer</code> doesn't seem to conflict with anything in your code.</p></li>\n<li><p>The Python style guide (<a href=\"http://www.python.org/dev/peps/pep-0008/\">PEP8</a>) recommends using <code>lowercase_with_underscores</code> for method and property names. You're not obliged to follow this guide, but it will make it easier for you to collaborate with other Python programmers.</p></li>\n<li><p>The intended use of private names in Python is to \"avoid name clashes of names with names defined by subclasses\" but that's not necessary here. So write <code>_state_lock</code> instead of <code>__stateLock</code> and so on.</p></li>\n<li><p>The <code>_now</code> method seems a bit pointless:</p>\n\n<pre><code>def _now(self):\n return time()\n</code></pre>\n\n<p>Why not just call <code>time()</code>?</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T03:33:07.883",
"Id": "53112",
"Score": "0",
"body": "Wow! Thanks @Gareth. This is the best mentoring feedback I've ever received on any code! I'll definitely be using Code Review more often. And I'll update you when I've incorporated your feedback."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T06:03:32.673",
"Id": "53117",
"Score": "0",
"body": "I agree with your race condition examples and I agree that I need to make the internal state of the object change atomically, but before doing that, how can I expose the bug(s) with unit tests?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T08:19:45.790",
"Id": "53129",
"Score": "0",
"body": "Your question about how to make tests that expose race conditions would be a good question for [Programmers Stack Exchange](http://programmers.stackexchange.com/) — but see the answers to [this question](http://programmers.stackexchange.com/q/196105/30159) which are not encouraging."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T01:18:59.433",
"Id": "53350",
"Score": "0",
"body": "I've asked a [question](http://stackoverflow.com/q/19602535/1224758) specific to this context which I think you can help with..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T01:22:12.417",
"Id": "53351",
"Score": "0",
"body": "For reference the updated code can be found [here](https://github.com/doughgle/pomodoro_evolved/blob/master/pomodoro_evolved/kitchen_timer.py)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T01:22:46.733",
"Id": "53352",
"Score": "0",
"body": "To answer your outstanding questions @gareth; 1, The context helps to understand the behaviour. 3, I'm trying to avoid precision related complexity and this precision is good enough for the context. 5, unittest uses CamelCase for it's methods and I find it easier to read."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T10:15:20.340",
"Id": "33125",
"ParentId": "33113",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "33125",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T05:01:01.677",
"Id": "33113",
"Score": "5",
"Tags": [
"python",
"timer"
],
"Title": "Is this kitchen timer code pythonic?"
}
|
33113
|
<p>I have to deploy this code that will list all the directories, sub directories and files in it starting from the root. The code works but I am not sure if this is the correct way to list. It should not fail, though.</p>
<p>Also, in despite not allowing directories with the name <code>.</code> and <code>..</code>, they get printed. Why is that?</p>
<pre><code><?php
# Snippet that lists all the directories,sub directories and files under that directory
# recursive function
function directory_f_lister($root) {
$dir_list = scandir($root);
for($var=0;$var<count($dir_list);$var++) {
if(is_readable($root.$dir_list[$var])) {
if(is_dir($root.$dir_list[$var])) {
if($dir_list[$var] === "." || $dir_list[$var] === "..") continue;
echo "<h3>Name of directory $dir_list[$var]</h3>";
echo "<br />";
$dh = opendir($root.$dir_list[$var]);
while(($name = readdir($dh)) !== false) {
if(is_dir($root.$dir_list[$var].$name)) {
if($dir_list[$var] === "." || $dir_list[$var] === "..") continue;
echo "Name of directory : <strong> $name </strong>";
echo "<br />";
directory_f_lister($root.$dir_list[$var].$name);
}else {
echo $name;
echo "<br/>";
}
}
}
}
}
}
directory_f_lister(DIRECTORY_SEPARATOR);
#end
</code></pre>
|
[] |
[
{
"body": "<p>well <code>.</code> and <code>..</code> are not directories, thats are navigationpoints of directories, . means go inside a root directory, .. means go one folder back, </p>\n\n<p>you might noticed this already in includes like <code>include ../../../foo/bar.php</code> </p>\n\n<p>also instead of scandir and readdir php has classes for this purpose <a href=\"http://www.php.net/manual/en/class.directoryiterator.php\" rel=\"nofollow\">DirectoryIterator</a> or <a href=\"http://www.php.net/manual/en/class.filesystemiterator.php\" rel=\"nofollow\">FileSystemIterator</a> </p>\n\n<p>And if you wish to create reusable methods, dont do output there, instead return an array of folders/files something like</p>\n\n<pre><code>$directories = scanDirectories($rootDirectory); //create output array\nforeach($directories as $directory){\n echo $directory.'<br/>'; \n} \n</code></pre>\n\n<p>this allowes you to modify the output without editing the sourcecode, you could also wrap the output within a function e.g. <code>viewDirectories</code> and reuse it on different places.</p>\n\n<p>here is a small Example </p>\n\n<pre><code> ini_set('html_errors', 'On');\n\nfunction scanDirectory($path) {\n $path = realpath($path);\n\n return new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path), RecursiveIteratorIterator::SELF_FIRST);\n\n}\n\nforeach(scanDirectory('./') as $name=> $object){\n\n echo $name.'<br/>';\n}\n</code></pre>\n\n<p>About your question:</p>\n\n<pre><code>$root.$dir_list[$var].$name //this is your directory name\n</code></pre>\n\n<p>but youre checking if this name is . and ..</p>\n\n<pre><code>$dir_list[$var]\n</code></pre>\n\n<p>so its never becomes true</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T06:33:59.990",
"Id": "33119",
"ParentId": "33114",
"Score": "1"
}
},
{
"body": "<ol>\n<li>If you invert your if condition and continue with next loop entry then you can reduce your level of nesting.</li>\n<li>You will currently miss all files in the first <code>$root</code> (due do the outer <code>is_dir</code> condition).</li>\n<li><p>You should be able move the recursion further to the top. The shorted algorithm for recursively listing directories goes like this (pseudo code):</p>\n\n<pre><code>func list(root)\n print \"Directory: \" + root\n foreach (entry in contentof(root))\n if (entry is directory)\n list(entry)\n else\n print \"File: \" + entry\n</code></pre>\n\n<p>In your code that could look something like this:</p>\n\n<pre><code>function directory_f_lister($root)\n{\n echo \"<h3>Name of directory: $root</h3>\";\n echo \"<br>\";\n for (scandir($root) as $current)\n {\n $currentFullPath = $root.$current;\n if (!is_readable($currentFullPath) || $current == \".\" || $current == \"..\")\n continue;\n if (is_dir($currentFullPath))\n {\n list($currentFullPath);\n }\n else\n {\n echo $current;\n echo \"<br>\";\n }\n }\n }\n</code></pre></li>\n<li>Your approach intermingles the iteration of the structure (filesystem) with the actions of what to do for each item (printing). A better way would be to simply use the <a href=\"http://php.net/manual/en/class.directoryiterator.php\" rel=\"nofollow\">DirectoryIterator</a> to iterate over the filesystem and print each item.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T07:30:12.277",
"Id": "33120",
"ParentId": "33114",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T05:06:10.217",
"Id": "33114",
"Score": "2",
"Tags": [
"php",
"file-system"
],
"Title": "Listing all directories, sub directories and files starting from the root"
}
|
33114
|
<p>After fumbling around with Ruby for a few weeks I've fallen into a coding pattern that I'm comfortable with. When I create a new class and that class has dependencies, I add a method <code>initialize_dependencies</code> that does the job of creating them. That function is then executed from the constructor.</p>
<p>When I write a test for this class, I actually test a subclass where the <code>initialize_dependencies</code> function has been overridden and the dependencies replaced with stubs or mocks. Here is an example of such a test (with most tests and test data removed for brevity):</p>
<pre><code>require "address_kit/entities/street_address"
module AddressKit
module Validation
describe FinnValidationDriver do
# Subject returns hard coded results from finn client.
subject {
Class.new(FinnValidationDriver) {
def initialize_dependencies
@client = Object.new
@client.define_singleton_method(:address_search) { |address_string|
FINN_VALIDATION_DRIVER_TEST_DATA[address_string] or []
}
end
}.new
}
it "considers an address invalid if finn returns no results" do
address = AddressKit::Entities::StreetAddress.new({
street_name: "FOOBAR",
house_number: 123
})
subject.valid?(address).must_equal false
subject.code.must_equal FinnValidationDriver::CODE_NO_RESULTS
end
it "considers an address invalid if finn returns multiple results" do
address = AddressKit::Entities::StreetAddress.new({
street_name: "FORNEBUVEIEN",
house_number: 10
})
subject.valid?(address).must_equal false
subject.code.must_equal FinnValidationDriver::CODE_NOT_SPECIFIC
end
end
end
end
FINN_VALIDATION_DRIVER_TEST_DATA = {
"FORNEBUVEIEN 10" => [
AddressKit::Entities::StreetAddress.new({
street_name: "FORNEBUVEIEN",
house_number: 10,
entrance: "A",
postal_code: 1366,
city: "LYSAKER"
}),
AddressKit::Entities::StreetAddress.new({
street_name: "FORNEBUVEIEN",
house_number: 10,
entrance: "B",
postal_code: 1366,
city: "LYSAKER"
})
],
"TORGET 12, ASKIM" => [
AddressKit::Entities::StreetAddress.new({
street_name: "TORGEIR BJØRNARAAS GATE",
house_number: 12,
postal_code: 1807,
city: "ASKIM"
}),
AddressKit::Entities::StreetAddress.new({
street_name: "TORGET",
house_number: 12,
postal_code: 1830,
city: "ASKIM"
})
]
}
</code></pre>
<p>This class only has one dependency, which is a client for a web service. Here I replace it with a stub returning static data.</p>
<p>I'm <em>fairly</em> new with Ruby so there are probably at least a few issues or potholes with this approach that I'm not seeing. Is there a best practice when it comes to writing classes and tests for them? Am I way off?</p>
|
[] |
[
{
"body": "<p>Ruby lets you override methods on existing objects, so you don't need to derive a new one to override it.</p>\n\n<p>If you change the constructor to take the dependency explicitly as a parameter you don't need your initialize method. see <a href=\"https://stackoverflow.com/questions/2273683/why-are-ioc-containers-unnecessary-with-dynamic-languages/2308494#2308494\">Dependency Injection</a>. Note: If you follow this pattern everywhere you end up with classes either being building blocks or for wiring blocks together. Factories etc. <a href=\"http://david.heinemeierhansson.com/2012/dependency-injection-is-not-a-virtue.html\" rel=\"nofollow noreferrer\">Some people don't like this</a>... so the other option is... </p>\n\n<p>RSpec lets you mock methods on any instance of a specific class...\nsee <a href=\"https://www.relishapp.com/rspec/rspec-mocks/v/2-6/docs/method-stubs/stub-on-any-instance-of-a-class\" rel=\"nofollow noreferrer\">https://www.relishapp.com/rspec/rspec-mocks/v/2-6/docs/method-stubs/stub-on-any-instance-of-a-class</a></p>\n\n<pre><code>describe \"any_instance.stub\" do\n it \"returns the specified value on any instance of the class\" do\n Object.any_instance.stub(:foo).and_return(:return_value)\n\n o = Object.new\n o.foo.should eq(:return_value)\n end\nend\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T23:34:28.387",
"Id": "33143",
"ParentId": "33115",
"Score": "1"
}
},
{
"body": "<p>As Nigel suggested, looking into dependency injection is worthwhile. In the dissenting article <a href=\"http://david.heinemeierhansson.com/2012/dependency-injection-is-not-a-virtue.html\" rel=\"nofollow\">linked</a>, DHH only discusses how DI impacts testing but that's not its only (or even primary) benefit; decoupling is really the goal and testing is often the first indicator of coupling between components. That said, considering DI is much more of an architectural decision, and probably somewhat out of scope here.</p>\n\n<p>I would instead like to expand on Nigel's suggestion to use mocks; i think they will make your spec much more focused and resilient.</p>\n\n<p>A good metric for any spec is the signal to noise ratio; something like:</p>\n\n<pre><code>LOC directly interacting with the object-under-test / LOC in the spec \n</code></pre>\n\n<p>In the spec above, i count 4 or 5 lines that directly test <code>FinnValidationDriver</code>, and a <em>lot</em> of glue code. You probably have more specs than you're showing that reuse the test data, so the ratio is likely higher than i'm seeing, but even so, i'd consider this a code smell.</p>\n\n<h2>Consider this refactored code:</h2>\n\n<pre><code># ...\ndescribe FinnValidationDriver do\n before do\n @driver = FinnValidationDriver.new\n @address = MiniTest::Mock.new\n end\n it \"considers an address invalid if finn returns no results\" do\n @address.expect(:address_string, \"FOOBAR 123\")\n Finn.stub(:address_search, []) do #1\n @driver.valid?(@address).must_equal false\n @driver.code.must_equal FinnValidationDriver::CODE_NO_RESULTS\n end\n end\n it \"considers an address invalid if finn returns multiple results\" do\n @address.expect(:address_string, \"FORNEBUVEIEN 10\")\n Finn.stub(:address_search, ['any', 'two_things']) do #2\n @driver.valid?(@address).must_equal false\n @driver.code.must_equal FinnValidationDriver::CODE_NOT_SPECIFIC\n end\n end\nend\n</code></pre>\n\n<h2>Notes:</h2>\n\n<ol>\n<li>I haven't run any of this code, so no guarantees of correctness :)</li>\n<li>It looks like you're using minitest so i've stuck with <code>MiniTest::Mock</code>, however i don't have much experience with that particular mocking framework. Most frameworks will do the job satisfactorily.</li>\n<li>One thing <code>MiniTest::Mock</code> doesn't seem to provide is the ability to verify that a stubbed method was called (and with the expected params). This may or may not be important to you (line #1)</li>\n<li>I've not bothered to call @address.verify because the interaction between <code>StreetAddress</code> and <code>..Driver</code> isn't the focus of the test.</li>\n<li>I've made an assumption that the <code>..Driver</code> just checks how many addresses were returned by <code>Finn</code>, so line #2 just stubs an array with any two arbitrary items. If <code>Finn</code> does more than check the count, you may have to return a more realistic array.</li>\n</ol>\n\n<h2>Advantages, IMO:</h2>\n\n<ol>\n<li>No need to maintain test data. Over the life of a project, i've found this is a <em>big</em> win: the less you have to maintain, the more resistant the spec is to change.</li>\n<li>Not coupled to the internal data representation of <code>StreetAddress</code>.</li>\n<li>The original spec had intimate knowledge of <code>..Driver's</code> @client instance variable, which is A Bad Thing.</li>\n<li>Much better ratio of LOC directly interacting with <code>..Driver</code> to total LOC.</li>\n</ol>\n\n<h2>A few other thoughts:</h2>\n\n<ul>\n<li><p>Check out <a href=\"http://blog.davidchelimsky.net/blog/2012/05/13/spec-smell-explicit-use-of-subject/\" rel=\"nofollow\">this post</a> by Dave Chelimsky arguing against the <em>explicit</em> use of <code>subject</code> in specs.</p></li>\n<li><p>Based only on the little i see of the <code>..Driver</code> interface, the asymmetry between <code>#valid?(address)</code> and <code>#code()</code> may be a smell. Because it takes an address as a parameter, the <code>valid?</code> method makes <code>FinnValidationDriver</code> appear to be stateless, but the <code>code</code> method depends on the <code>..Driver</code> hanging onto state from the most recent call to <code>valid?</code>. I'm not making a case for the <code>..Driver</code> being either stateful or stateless, just that the signatures of the two methods are incongruous. If the <code>..Driver</code> is meant to be used to validate a single <code>StreetAddress</code> instance, then it should probably require it as a constructor param; if not, then hanging on to state between calls to <code>valid?</code> is a bad idea and all state resulting from validation should be returned by <code>valid?</code>.</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T02:35:02.600",
"Id": "33310",
"ParentId": "33115",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T05:16:35.563",
"Id": "33115",
"Score": "-1",
"Tags": [
"ruby"
],
"Title": "Are there any glaring issues with the way I write and test my Ruby classes?"
}
|
33115
|
<p>Can please someone review and give me suggestions for improving this code? I am very new to JavaScript.</p>
<p>I need to create a method in JavaScript which will take parameters as </p>
<ul>
<li><code>DateRange</code> (possible values as <code>Today</code>/<code>This Week</code>/<code>This Month</code></li>
<li><code>BooleanFullDate</code> (possible values as true/false)</li>
</ul>
<p>Now, when the parameter value is <code>Today</code>, it should return </p>
<pre><code>10/23/2013
10/23/2013
</code></pre>
<p>When <code>This Week</code> and <code>BooleanFullDate</code> are <code>true</code>, it should return </p>
<pre><code>10/20/2013
10/26/2013
</code></pre>
<p>When <code>This Week</code> and <code>BooleanFullDate</code> are <code>false</code>, it should return </p>
<pre><code>10/20/2013
10/23/2013
</code></pre>
<p>When <code>This Month</code> and <code>BooleanFullDate</code> are <code>true</code>, it should return </p>
<pre><code>10/01/2013
10/31/2013
</code></pre>
<p>When <code>This Month</code> and <code>BooleanFullDate</code> are <code>false</code>, it should return </p>
<pre><code>10/01/2013
10/23/2013
</code></pre>
<p>For which I have written my code <a href="http://jsfiddle.net/PSW9T/31/" rel="nofollow noreferrer">here</a>.</p>
<p>Lastly, can someone please suggest improvements for the code? </p>
<p><a href="https://stackoverflow.com/questions/19533894/datetime-in-javascript">original question posted</a></p>
<p>EDIT:- Source code</p>
<pre><code>function GetStartAndEnd(dateRange, bGetFullRange) {
var dateObject = new Date();
var dateobj = new Date()
var month = dateobj.getMonth()+1
var day = dateobj.getDate()
var year = dateobj.getFullYear()
var start = undefined;
var end = undefined;
if (dateRange.toLowerCase() == "today") {
start = month + "/" + day + "/" + year;
end = month + "/" + day + "/" + year;
} else if (dateRange.toLowerCase() == "this week") {
var curr = new Date;
var firstDay = new Date(curr.setDate(curr.getDate() - curr.getDay()));
var lastDay = new Date(curr.setDate(curr.getDate() - curr.getDay() + 6));
var fmonth = firstDay.getMonth()+1;
var fday = firstDay.getDate();
var fyear = firstDay.getFullYear();
start = fmonth + "/" + fday + "/" + fyear;
var lmonth = lastDay.getMonth()+1;
var lday = lastDay.getDate();
var lyear = lastDay.getFullYear();
end = lmonth + "/" + lday + "/" + lyear;
} else if (dateRange.toLowerCase() == "this month" && bGetFullRange) {
var date = new Date(),
y = date.getFullYear(),
m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
var fmonth = firstDay.getMonth()+1;
var fday = firstDay.getDate();
var fyear = firstDay.getFullYear();
start = fmonth + "/" + fday + "/" + fyear;
var lmonth = lastDay.getMonth()+1;
var lday = lastDay.getDate();
var lyear = lastDay.getFullYear();
end = lmonth + "/" + lday + "/" + lyear;
} else if (dateRange.toLowerCase() == "this month" && !bGetFullRange) {
var date = new Date(),
day = date.getDate(),
y = date.getFullYear(),
m = date.getMonth();
var firstDay = new Date(y, m, 1);
var lastDay = new Date(y, m + 1, 0);
var fmonth = firstDay.getMonth()+1;
var fday = firstDay.getDate();
var fyear = firstDay.getFullYear();
start = fmonth + "/" + fday + "/" + fyear;
end = m+1 + "/" + day + "/" + y;
}
console.log({
"start": start,
"end": end
});
return {
"start": start,
"end": end
}
}
GetStartAndEnd("Today");
GetStartAndEnd("this week");
GetStartAndEnd("this month", true);
GetStartAndEnd("this month", false);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T07:34:05.800",
"Id": "53031",
"Score": "1",
"body": "Please include your code for review. External links can easily go away."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T08:41:56.503",
"Id": "53032",
"Score": "0",
"body": "@ChrisWue Sure! I will do it now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T19:53:20.660",
"Id": "53186",
"Score": "0",
"body": "OT: But http://momentjs.com/ might be of some value ;)"
}
] |
[
{
"body": "<p>I see some issues with your code</p>\n\n<ol>\n<li>There's a lot of repetition</li>\n<li>Your return values should be actual <code>Date</code> objects, and perhaps handle the time component too. Formatting the date is outside the function's responsibilities. Who knows how the formatting or use of the start/end dates might change? But what won't change is that the function should return start and end, so stick to that. </li>\n<li>Your arguments are a clue that something's not quite right: The 2nd argument only makes sense if the 1st argument is <code>\"this month\"</code>. Why not respect the 2nd arg for weeks too?</li>\n<li>A style thing, but by convention JS functions are <code>lowerCamelCase</code> unless they're constructors (i.e. classes). So <code>Date</code> is uppercase, as it's a constructor, but your function should be <code>getStartAndEnd</code></li>\n</ol>\n\n<p>To take a page from the ActiveSupport library for Ruby, which has excellent date/time helpers, it might be more beneficial to break everything up into the separate functions (and encapsulate them in an object to avoid polluting the global namespace). </p>\n\n<p>For instance:</p>\n\n<pre><code>var DateHelper = {\n beginningOfDay: function (date) {\n var beginning = new Date(date);\n beginning.setHours(0, 0, 0, 0);\n return beginning;\n },\n\n endOfDay: function (date) {\n var end = new Date(date);\n end.setHours(23, 59, 59, 999);\n return end;\n },\n\n beginningOfWeek: function (date) {\n var beginning = DateHelper.beginningOfDay(date);\n beginning.setDate(date.getDate() - date.getDay());\n return beginning;\n },\n\n endOfWeek: function (date) {\n var end = DateHelper.endOfDay(date);\n end.setDate(date.getDate() - date.getDay() + 6);\n return end;\n },\n\n beginningOfMonth: function (date) {\n var beginning = DateHelper.beginningOfDay(date);\n beginning.setDate(1);\n return beginning;\n },\n\n endOfMonth: function (date) {\n var end = DateHelper.endOfDay(date);\n end.setMonth(date.getMonth() + 1, 0);\n return end;\n }\n\n //... more helper functions?\n}\n</code></pre>\n\n<p>From this, you can build more complex functionality. For instance, your original function could now be written as:</p>\n\n<pre><code>function getStartAndEnd(rangeName, extendToEnd) {\n // At minimum, we'll want the range of the current date\n var range = {\n start: DateHelper.beginningOfDay(new Date),\n end: DateHelper.endOfDay(new Date);\n };\n\n extendToEnd = extendToEnd || false; // default to false\n\n switch(rangeName.toLowerCase()) {\n case \"this week\":\n range.start = DateHelper.beginningOfWeek(range.start);\n if( extendToEnd ) {\n range.end = DateHelper.endOfWeek(range.end);\n }\n break;\n case \"this month\":\n range.start = DateHelper.beginningOfMonth(range.start);\n if( extendToEnd ) {\n range.end = DateHelper.endOfMonth(range.end);\n }\n break;\n default:\n // do nothing\n break;\n }\n return range;\n}\n</code></pre>\n\n<p>That'll give you start/end date objects that you can format however you want (which, of course, would be a job for another tiny function).</p>\n\n<p>But now that everything's broken up into separate, more focussed functions, you can mix and match to suit your needs. I'd avoid calling functions with string arguments that define what you want back. Probably better to simply have a <code>thisWeek()</code> function somewhere, or a <code>thisMonth()</code> function, and leave string interpretation at an even higher level.</p>\n\n<p>Note, by the way, that time and date stuff is always tricky. For instance, all of these functions assume you're talking about the user's local time zone. Depending on your context, that might cause issues. Also, where I live the beginning of a week would be a Monday, not a Sunday. So beware of such things.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T07:20:59.177",
"Id": "53123",
"Score": "0",
"body": "Thanks a lott. +1 for explaining so beautifully. Really appreciate it . Please have a look at [this fiddle](http://jsfiddle.net/Sm5Ge/3/) which I have created as per you code, and let me know if its proper."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T07:29:59.543",
"Id": "53126",
"Score": "0",
"body": "Updated [**Fiddle**](http://jsfiddle.net/Sm5Ge/4/)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T08:42:04.077",
"Id": "53131",
"Score": "0",
"body": "@Idothisallday Well, it certainly looks like it's doing the right thing. Optimally, this is the sort of thing that could be checked with automated tests, but that's a story for another time. But yeah, looks like it's working. Just be sure to remove or otherwise disable the console.log calls in production; no need to spam people's browsers with stuff that's only of interest to you."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T08:45:30.797",
"Id": "53132",
"Score": "0",
"body": "@Idothisallday Just fixed my code by the way. Most of the functions were actually ignoring the argument, and using a new Date instead, which wasn't the idea. Sorry about that."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T20:05:45.680",
"Id": "33137",
"ParentId": "33118",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "33137",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T06:19:35.567",
"Id": "33118",
"Score": "5",
"Tags": [
"javascript",
"datetime"
],
"Title": "Datetime in JavaScript"
}
|
33118
|
<p>I am unsure if the list could store a large number of messages.</p>
<p>There are 50,000 queue messages which I am receiving and assigning to the messages list:</p>
<pre><code> var msgEnumerator = msgQueue.GetMessageEnumerator2();
var messages = new List<System.Messaging.Message>();
while(msgEnumerator.MoveNext(new TimeSpan(0, 0, 1))) {
var msg = msgQueue.ReceiveById(msgEnumerator.Current.Id, new TimeSpan(0, 0, 1));
messages.Add(msg);
}
foreach( var k in messages){
MailMessage mailM = (k.Body as SerializeableMailMessage).GetMailMessage();
try {
SmtpClient sp = new SmtpClient(smtpip, 25);
sp.EnableSsl = false;
sp.Send(mailM);
}
catch (Exception ex){
logger.ErrorException("General error sending email.", ex);
}
}
</code></pre>
<p>Is this the correct way, or is there an alternative? Let me hear your suggestions.</p>
|
[] |
[
{
"body": "<ol>\n<li>You create a lot of <code>TimeSpan</code> objects which is unnecessary. Just create one <code>timeout</code> variable. Especially since it's used in multiple places. This makes changing the timeout later easier. Otherwise you are bound to forget one place.</li>\n<li>Prefer <code>TimeSpan.FromXYZ()</code> methods. They makes it more obvious for what period you create a <code>TimeSpan</code>.</li>\n<li>Consider moving the mail sending code into its own function which just accepts a single message and sends it.</li>\n<li><p>It might make sense to iterate over the message queue directly instead of buffering them all up:</p>\n\n<pre><code>var timeout = TimeSpan.FromSeconds(1);\nvar queueIter = msgQueue.GetMessageEnumerator2();\nwhile (queueIter.MoveNext(timeout))\n{\n using (var message = msgQueue.ReceiveById(queueIter.Current.Id, timeout))\n {\n SendMessage(message);\n }\n}\n</code></pre></li>\n<li>Instead of directly sending the message consider making an event available on the class like <code>MessageReceived</code>. Then other code can subscribe to it and do stuff (like sending it as mail or logging it or saving it somewhere, etc).</li>\n<li>As mentioned in the comment you should wrap all objects you create which are <code>IDisposable</code> into <code>using</code> statements to make sure any allocated resources are cleaned up properly.</li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T18:48:08.500",
"Id": "53082",
"Score": "1",
"body": "In addition, I would note that all the [System.Messaging](http://msdn.microsoft.com/en-us/library/System.Messaging.aspx) objects used above implement IDisposable. Additionally, [System.Net.Mail.MailMessage](http://msdn.microsoft.com/en-us/library/System.Net.Mail.MailMessage.aspx) and [System.Net.Mail.SmtpClient](http://msdn.microsoft.com/en-us/library/system.net.mail.smtpclient.aspx) do as well. You should be wrapping them all in using statements."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T08:21:20.240",
"Id": "33122",
"ParentId": "33121",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "33122",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T07:39:22.203",
"Id": "33121",
"Score": "3",
"Tags": [
"c#"
],
"Title": "Receiving MSMQ messages as a list"
}
|
33121
|
<p>I'm rewriting a god object with long methods into something much more viewable and pretty. </p>
<p>However, I think there is something missing and can be done better. I'm sending examples of one controller and two models in order to get an idea.</p>
<p><strong>Controller: Account.php</strong></p>
<pre><code><?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
/**
*
* handle accounts transformations
*/
class Account extends CI_Controller {
function __construct()
{
parent::__construct();
$this->load->model("outputModel");
$this->load->model("userModel");
$this->load->model('validation');
$this->load->database();
}
/**
* login
*
* @post email
* @post password
* @post device_token optional
* @post device_family optional
*
* @return OutputModel $outputModel auth_token
*/
function index() {
$email = $this->input->post('email');
$password = $this->input->post('password');
if (isset($_POST['device_token']) && isset($_POST['device_family'])) {
$device_token = $this->input->post('device_token');
$device_family = $this->input->post('device_family');
$result = $this->userModel->Login($email,$password,$device_token,$device_family);
} else {
$result = $this->userModel->Login($email,$password);
}
$this->outputModel->process($result);
echo $this->outputModel;
}
/**
* get unread messages and groupchats from (last) dated up to limit
*
* @post string $auth_token
* @post int $limit amount of groupchats requested
* @post int $date_up_to unixtime optional
* @post boolean $order_by_date_desc optional
*
* @return OutputModel $outputModel echo jsoned
*/
function refresh() {
$token = $this->input->post('auth_token');
$data['user_id'] = $this->validation->checkSession($token);
$data['limit'] = $this->input->post('limit');
if (isset($_POST['date_up_to']))
$data['date_up_to'] = $this->input->post('date_up_to');
if (isset($_POST['order_by_date_desc']))
$data['order_by_date_desc'] = $this->input->post('date_up_to');
$result = $this->groupChatModel->getUnread($data);
$this->outputModel->processResult($result);
echo $this->outputModel;
}
function activate($activation_key) {
if (!$this->validation->checkSHA256($activation_key)) {
$this->load->view("activate_unsuccessful.php");
return;
} else {
//continue
}
$this->load->library('email');
$this->load->helper('url');
$this->load->database();
$this->load->helper('string');
# check account exists
$sql = "SELECT * FROM user WHERE activation_key = ?";
$query = $this->db->query($sql, array($activation_key));
if ($query->num_rows() > 0) {
# activate account
$sql = "UPDATE user SET activation_key = 0 WHERE activation_key = ?";
$this->db->query($sql, array($activation_key));
$this->load->view("activate_successful.php");
} else {
$this->load->view("activate_unsuccessful.php");
}
}
/**
* creates account
*
* @post string first_name
* @post string last_name
* @post string phone
* @post string email
* @post string password
*
* @return OutputModel $outputModel auth_token on success or error
*
*/
function create()
{
$this->load->model('userModel');
$first_name = $this->input->post('first_name');
$last_name = $this->input->post('last_name');
$phone = $this->input->post('phone');
$email = $this->input->post('email');
$password = $this->input->post('password');
$result = $this->userModel->CreateAccount($first_name, $last_name, $phone, $email, $password);
$this->outputModel->process($result);
echo $this->outputModel;
}
/**
* changes setting of an account
*
* @post string auth_token
* @post string new_first_name
* @post string new_last_name
* @post string new_phone
* @post string new_password
* @post string old_password
*
*
* @return OutputModel $outputModel auth_token on success or error
*/
function changeSettings() {
$token = $this->input->post('auth_token');
$data['user_id'] = $this->validation->checkSession($token);
$data['new_first_name'] = $this->input->post('new_first_name');
$data['new_last_name'] = $this->input->post('new_last_name');
$data['new_phone'] = $this->input->post('new_phone');
$data['new_password'] = $this->input->post('new_password');
$data['old_password'] = $this->input->post('old_password');
$result = $this->userModel->ChangeSettings($data);
$this->outputModel->process($result);
echo $this->outputModel;
}
}
</code></pre>
<p><strong>Models:</strong></p>
<p><strong>1. <code>UserModel</code></strong></p>
<pre><code><?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class UserModel extends CI_Model {
/**
* @param $email
* @param $password
* @param null $device_token
* @param null $device_family
* @return array
*/
public function Login($email, $password, $device_token = null, $device_family = null )
{
$sql = "SELECT * FROM user WHERE (email = ?) LIMIT 1";
$query = $this->db->query($sql, array(strtolower($email)));
if (!($query->num_rows() > 0)){
$error = #some code error
return array('error' => $error);
} else {
//continue
}
$row = $query->row();
if ($row->password != encrypt($password) {
$error = #some code error
return array('error' => $error);
} else {
//continue
}
# Create a session id and store it in session table with device token and device family
$user_id = $row->id;
$token = hash(func,uniqid());
$expire_date = time() + (24*60*60); //now + 24 hours
$sql = "INSERT INTO auth_tokens (auth_token, user_id, expire_date) VALUES (?, ?, ?)";
$this->db->query($sql, array($token, $user_id, $expire_date));
# Create entry in devicetoken table
if ($device_token && $device_family) {
$this->AddDevice($user_id, $device_token, $device_family);
}
# put session id and user id into response
$response['auth_token'] = $token;
$response['id'] = $user_id;
$response['first_name'] = $row->first_name;
$response['last_name'] = $row->last_name;
return array('result' => $response);
}
/**
* @param $user_id
* @param $device_token
* @param $device_family
* @return void
*/
public function AddDevice($user_id,$device_token,$device_family) {
$sql = "SELECT * FROM devicetoken WHERE device_token = ? AND device_family = ?";
$query = $this->db->query($sql, array($device_token, $device_family ));
if (!$query->num_rows() == 0) {
$sql = "UPDATE devicetoken SET user_id = ?, device_family = ? WHERE device_token = ?";
$this->db->query($sql, array($user_id, $device_family, $device_token));
} else {
$sql = "INSERT INTO api_devicetoken(user_id,device_token,device_family) VALUES (?,?,?)";
$this->db->query($sql, array($user_id,$device_token,$device_family));
}
return;
}
/**
* @param array $data
* @return array
*/
public function ChangeSettings(array $data) {
$this->load->model('validation');
$sql = "SELECT * FROM user WHERE id = ?";
$query = $this->db->query($sql, $data['user_id']);
if ($query->num_rows() == 0) {
return array('error' => #some code error);
}
$row = $query->row();
//check password
if ($row->password!=encrypt($data['old_password'])) {
return array('error' => #some code error);
}
//(process|substitute old) first name
if (array_key_exists('new_first_name',$data)) {
if (!$this->validation->checkName($data['new_first_name'])) {
return array('error' => #some code error);
}
} else {
$data['new_first_name'] = $row->first_name;
}
//(process|substitute old) last name
if (array_key_exists('new_last_name',$data)) {
if (!$this->validation->checkName($data['new_last_name'])) {
return array('error' => #some code error);
}
} else {
$data['new_last_name'] = $row->last_name;
}
//(process|substitute old) phone
if (array_key_exists('new_phone',$data)) {
if (!$this->validation->checkName($data['new_phone'])) {
return array('error' => #some code error);
}
} else {
$data['new_phone'] = $row->phone;
}
//(process|substitute old) new password
if (array_key_exists('new_password',$data)) {
if (!$this->validation->checkPass($data['new_password'])) {
return array('error' => #some code error);
}
} else {
$data['new_password'] = $data['old_password'];
}
$data['new_password'] = encrypt($data['new_password']);
$sql = "UPDATE user SET first_name = ?, last_name = ?, password = ? WHERE id = ?";
$this->db->query($sql, array($data['new_first_name'],$data['new_last_name'],
$data['new_password'],$data['user_id']));
if (!$this->db->affected_rows()) {
return array('error' => #some code error);
}
// update phone
$sql = "UPDATE api_user_data SET value = ?, hash = ? WHERE user_id = ? AND type_id = 3";
$this->db->query($sql, array($data['new_phone'], hash($data['new_phone']), $data['user_id']));
unset($data['new_password']);
unset($data['old_password']);
return array('result' => $data);
}
/**
* @param $first_name
* @param $last_name
* @param $phone
* @param $email
* @param $password
* @return array
*/
public function CreateAccount($first_name, $last_name, $phone, $email, $password) {
$this->load->model('validation');
if (!$this->validation->checkName($first_name))
return array('error' => #some code error);
if (!$this->validation->checkName($last_name))
return array('error' => #some code error);
if (!$this->validation->checkPhone($phone))
return array('error' => #some code error);
if (!$this->validation->checkEmail($email))
return array('error' => #some code error);
if (!$this->validation->checkPass($password))
return array('error' => #some code error);
# Check if email address exists: error = #some code error if yes
# If email exists, but not verified - resend verification is to be used
$sql = "SELECT * FROM user WHERE email = ?";
$query = $this->db->query($sql, array($email));
if ($query->num_rows() > 0)
return array('error' => #some code error); //user already exists
# create activation key
$key = encrypt(uniqid());
# prepare password
$password = encrypt($password);
# store user details with activation key
$sql = "INSERT INTO user (first_name, last_name, password, user_type, activation_key) VALUES (?,?,?,?,?)";
$query = $this->db->query($sql, array($first_name, $last_name, $password, 1, $key)); //1 means type of user
if ($query) {
$user_id = $this->db->insert_id();
$sql = "INSERT INTO user_data(user_id,type_id,value,hash) VALUES (?,?,?,?),(?,?,?,?)";
$this->db->query($sql, array($user_id, 1, $email, hash($email), //1 - main email user data type
$user_id, 3, $phone, hash($phone)));//3 - phone user data type
} else
return array('error' => #some code error); //problem updating database
# send email with activation link
$this->SendActivationEmail($email,$key);
return array('result_object' => array('user_id' => $user_id));
}
/**
* @param $email
* @param $key
* @return void
*/
public function SendActivationEmail($email,$key) {
$this->load->library('email');
$this->load->helper('url');
$activation_url = site_url("/$some_path/$key");
$this->email->from('some adress');
$this->email->to($email);
$this->email->subject('activation');
# if account is activated - $key is 0
if ($key) {
$this->email->message("Click here to activate your account: $activation_url");
} else {
$this->email->message("Account already has been activated.");
}
$this->email->send();
}
}
</code></pre>
<p><strong>2.<code>OutputModel</code></strong></p>
<pre><code><?php
if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class OutputModel extends CI_Model {
private $error = array("error_object"=>array(
"error"=>0)
);
private $result = array();
function __construct() {
// Call the Model constructor
parent::__construct();
}
/**
* @return string jsoned array of $error and $result
*/
function __toString() {
$output=array();
foreach (array($this->error,$this->result) as $value) {
foreach ($value as $subkey=>$subvalue) {
$output[$subkey]=$subvalue;
}
}
$output = json_encode($output, JSON_FORCE_OBJECT);
return $output;
}
/**
* process data into output object
*
* @param array $result "resultObject"
* @return void
*/
function process(array $data) {
if (array_key_exists("result",$data)) {
foreach ($data["result"] as $key=>$value) {
$this->result["result_object"][$key]=$value;
}
}
if (array_key_exists("error",$data)) {
$this->result["error_object"]["error"]=$data['error'];
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p><strong>Disclaimer:</strong> I have never used CodeIgniter, so this will mainly focus on general PHP coding practice.</p>\n\n<p>First of all no comments is better than misleading comments. Take a look at some of the <a href=\"http://www.phpdoc.org/docs/latest/index.html\" rel=\"nofollow\">online resources</a> for doccomments. The <code>@</code> declaration is used for parameters or class information, not internal variables. I've never even seen <code>@post</code> before and don't think it is recognized by any IDE. Besides, this information isn't important to the person using your code. They only need to know what is required, what it returns, if anything, and what it does. Comments for yourself should be done outside of the code so as not to clutter up your source, though if you use self-documenting code comments will be largely unnecessary.</p>\n\n<p>There are better ways to prevent direct script access than checking if a constant is set. Check for a session or user credentials if you must, but the best way is to use an .htaccess file. If done correctly, the .htaccess rules can make it so that no page, other than the index, is directly accessible and all other requests are automatically forwarded back to the index. Admittedly, .htaccess isn't a cureall, AJAX, for instance, is still considered direct access because it is being done client side. This is where a good directory structure, strategic .htaccess files, and a session or credentials check can really shine. Lastly, even if they do somehow access this page directly, they will see nothing as it is a class and no output is directly generated.</p>\n\n<pre><code>if ( ! defined('BASEPATH')) exit('No direct script access allowed');\n</code></pre>\n\n<p>Two more things about the above snippet. Under normal circumstances <code>exit()</code> or <code>die()</code> are very inelegant ways of terminating a script. Its fine here because its a part of the site most people shouldn't see anyway, but its something to keep in mind. Finally, braceless syntax should be avoided. You are saving very little by neglecting your braces while also opening yourself up to potentially troublesome errors later. They take no extra effort to add in and will save you debugging later should you extend this code.</p>\n\n<p>Declare your method access levels. PHP defaults to public, but you should not rely on this.</p>\n\n<pre><code>public function __construct() {\n</code></pre>\n\n<p>I'm not 100% on this, again, I've never used CI, but I believe if a framework provides an interface for calling GET/POST/COOKIES then it should do <code>isset()</code> checks and default values for you as well, otherwise, what's the point. So...</p>\n\n<pre><code>$device_token = $this->input->post('device_token');\n$device_family = $this->input->post('device_family');\nif( $device_token && $device_family ) {//login with token and family\n</code></pre>\n\n<p>However, if your model is built correctly, then the default values for the <code>$device_token</code> and <code>$device_family</code> parameters in the <code>Login()</code> method should be FALSE anyway, so that if/else statement is unnecessary. Declare it once and cover the default functionality in the method.</p>\n\n<pre><code>//defaults for the last two params should be handled in Login()\n$result = $this->userModel->Login($email,$password,$device_token,$device_family);\n</code></pre>\n\n<p>You should remain consistent with your naming schemes. Your class names are capitalized, but the created objects are lowercase camelCase. Most of your methods are lowercase, but <code>Login()</code> is uppercase. You use both camelCase and under_scored variables. Remaining consistent in your naming scheme will help you identify types and write your code without having to continually look up how every new variable is done. I'm currently working on a project like this and I have to say it is the most frustrating thing I've ever done. Please be consistent. You will thank yourself later, and inheriting programmers will thank you.</p>\n\n<p>Using the __toString magic method is a bit confusing. You should use <code>render()</code> or a similarly named method, though the model should not be in charge of the display (more on this in the section entitled MVC).</p>\n\n<pre><code>echo $this->outputModel;\n//should be\n$this->outputModel->render();\n//if models were actually supposed to render that is\n</code></pre>\n\n<p>Else statements are unnecessary if you aren't actually using them. You are actually returning early in all of these <code>else//continue</code> statements, so an else statement isn't even necessary anyway, the remaining code is an assumed else.</p>\n\n<pre><code>if (!$this->validation->checkSHA256($activation_key)) {\n $this->load->view(\"activate_unsuccessful.php\");\n return;//returned, so rest of code is \"else\"\n}// else {\n //continue\n//}\n</code></pre>\n\n<p>I stopped reading at about this point. This is already a lot to go through and there were a lot of repeat offenses. I'll wrap this up with a basic introduction to MVC.</p>\n\n<p><strong>MVC</strong></p>\n\n<p>This is the part that most people tend to struggle with when creating MVC frameworks. It is not the controller's or the model's jobs to display content; That is the view's responsibility. So echoing out the model is doubly wrong. Its wrong because the controller shouldn't echo anything; And its wrong because the model shouldn't have anything to echo. There are many different ways to do MVC, but the underlying principles remain the same. The controller collects potential data its views need from the model. The model stores the data and provides ways of accessing it.</p>\n\n<p>This is a very simplified version of what one of my MVC frameworks looks like (from memory, so sorry its not exact):</p>\n\n<pre><code>$controller = new Controller();//init controller values\n$controller->setModel( 'model' );//set model\n$controller->render( 'view' );//prep page variables and include view\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-06T02:44:52.570",
"Id": "33897",
"ParentId": "33127",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T11:11:19.307",
"Id": "33127",
"Score": "1",
"Tags": [
"php",
"controller",
"codeigniter"
],
"Title": "An account activation class"
}
|
33127
|
<p>I am wondering if I can make these classes a bit more efficient.</p>
<p><strong>Test Results</strong></p>
<p><em>Single Run</em></p>
<ul>
<li>Method 1: 5 Columns - Text Query - 81178 Records = 00:00:00.6390366
secs</li>
<li>Method 2: 5 Columns - Text Query - 81178 Records = 00:00:00.5360307
secs</li>
</ul>
<p><em>10 Run Loop</em></p>
<ul>
<li>Method 1: 5 Columns - Text Query - 81178 Records = 00:00:05.3253045
secs</li>
<li>Method 2: 5 Columns - Text Query - 81178 Records = 00:00:05.0912912
secs</li>
</ul>
<p><em>100 Run Loop</em></p>
<ul>
<li>Method 1: 5 Columns - Text Query - 81178 Records = 00:00:54.1270959
secs</li>
<li>Method 2: 5 Columns - Text Query - 81178 Records = 00:00:53.8710813
secs</li>
</ul>
<p>All 3 attempts for both methods never peak over 25% CPU usage.</p>
<p>As you can see there really is no significant improvement over either method, and method 2 (judging by CPU usage) does not seem to multi-thread.</p>
<p>I am thinking that if I can get rid of my usage of reflection to map the columns to strongly-typed classes that it would make a significant boost to both methods performance, and I am sure that I can make improvements to the asyncronicity of method 2 as well... I just don't know how.</p>
<p><strong>WrapperTest.cs</strong></p>
<pre><code> private static IList<T> Map<T>(DbDataReader dr) where T : new()
{
try
{
// initialize our returnable list
List<T> list = new List<T>();
// fire up the lamda mapping
var converter = new Converter<T>();
// read in each row, and properly map it to our T object
var obj = converter.CreateItemFromRow(dr);
// reutrn it
return list;
}
catch (Exception ex)
{
// Catch an exception if any, an write it out to our logging mechanism, in addition to adding it our returnable message property
_Msg += "Wrapper.Map Exception: " + ex.Message;
ErrorReporting.WriteEm.WriteItem(ex, "o7th.Class.Library.Data.Wrapper.Map", _Msg);
// make sure this method returns a default List
return default(List<T>);
}
}
</code></pre>
<p>This is a continuation of <a href="https://stackoverflow.com/questions/19459583/asyncronous-while-loop">this question</a>.</p>
<p>The code above definitely runs more efficiently now. Is there any way to make it better?</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T14:48:40.687",
"Id": "53057",
"Score": "0",
"body": "you should try to break this up into several questions."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T16:49:35.100",
"Id": "53073",
"Score": "0",
"body": "you can also link to the other questions that you have posted since it is the same application. I think that is reasonable."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T22:06:17.250",
"Id": "53098",
"Score": "1",
"body": "Private fields naming convention is `_field`, not `_Field`... I guess VB is rubbing off on your C#, don't worry, soon your C# will rub off on your VB ;)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T18:29:09.680",
"Id": "53181",
"Score": "2",
"body": "Any reasons you are not using existing ORM like LINQ-to-SQL or Entity Framework?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T23:04:33.603",
"Id": "53194",
"Score": "0",
"body": "I don't think EF is C#-specific (although I never tried with VB), @tia is right, an ORM would make your like much easier. Besides L2S isn't rwally an ORM so you can start with that :) ....as for the naming, no, it doesn't really matter. Just as long as you're consistent through."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T01:43:20.123",
"Id": "53201",
"Score": "0",
"body": "There's also lightweight project like FastMember - https://code.google.com/p/fast-member/, which does exactly what you are doing. For the sake of Code Review, I'll come back to your code on my weekend. I think the performance could be improved by skip using reflection for setting value."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T11:55:42.577",
"Id": "53220",
"Score": "0",
"body": "In every iteration, you use CreateItemFromRow(). Why dont you call that once, and then store the indexes, so you can simply refer the rest of the table by index? That would speed things up significantly."
}
] |
[
{
"body": "<p>Use LINQ expression compilation to generate mapping code at runtime. The concept is to generate a method that does <code>obj.Property1 = dataReader[\"Property1\"]; ...</code> dynamically.</p>\n\n<pre><code>public class Converter<T> where T : new()\n{\n private static ConcurrentDictionary<Type, object> _convertActionMap = new ConcurrentDictionary<Type, object>();\n private Action<IDataReader, T> _convertAction;\n\n private static Action<IDataReader, T> GetMapFunc()\n {\n var exps = new List<Expression>();\n var paramExp = Expression.Parameter(typeof(IDataReader), \"dataReader\");\n var targetExp = Expression.Parameter(typeof(T), \"target\");\n var getPropInfo = typeof(IDataRecord).GetProperty(\"Item\", new[] { typeof(string) });\n foreach (var property in typeof(T).GetProperties())\n {\n var getPropExp = Expression.MakeIndex(paramExp, getPropInfo, new[] { Expression.Constant(property.Name, typeof(string)) });\n var castExp = Expression.TypeAs(getPropExp, property.PropertyType);\n //var bindExp = Expression.Bind(property, castExp);\n var bindExp = Expression.Assign(Expression.Property(targetExp, property), castExp);\n exps.Add(bindExp);\n }\n return Expression.Lambda<Action<IDataReader, T>>(Expression.Block(exps), new[] { paramExp, targetExp }).Compile();\n }\n\n public Converter()\n {\n _convertAction = (Action<IDataReader, T>)_convertActionMap.GetOrAdd(typeof(T), (t) => GetMapFunc());\n }\n\n public T CreateItemFromRow(IDataReader dataReader)\n {\n T result = new T();\n _convertAction(dataReader, result);\n return result;\n }\n}\n</code></pre>\n\n<p>Test method with 80,000 x 100 iteration</p>\n\n<pre><code> static void Main(string[] args)\n{\n var dummyReader = new DummyDataReader();\n var properties = typeof(DummyObject).GetProperties();\n var startDate = DateTime.Now;\n var converter = new Converter<DummyObject>();\n for (int i = 0; i < 80000 * 100; i++)\n {\n //var obj = CreateItemFromRow2<DummyObject>(new DummyDataReader());\n var obj = CreateItemFromRow<DummyObject>(dummyReader, properties);\n //var obj = converter.CreateItemFromRow(dummyReader);\n dummyReader.DummyTail = i;\n }\n\n //var obj = CreateItemFromRow2<DummyObject>(new DummyDataReader());\n Console.WriteLine(\"Time used : \" + (DateTime.Now - startDate).ToString());\n Console.ReadLine();\n}\n</code></pre>\n\n<p>Result:</p>\n\n<pre><code>CreateItemFromRow : 18.5 seconds\nConverter<T> : 7.3 seconds\n</code></pre>\n\n<p>Map function:</p>\n\n<pre><code> private static IList<T> Map<T>(DbDataReader dr) where T : new()\n {\n // initialize our returnable list\n List<T> list = new List<T>();\n // fire up the lamda mapping\n var converter = new Converter<T>();\n\n while (dr.Read()) {\n // read in each row, and properly map it to our T object\n var obj = converter.CreateItemFromRow(dr);\n list.Add(obj);\n }\n\n // reutrn it\n return list;\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T17:37:22.153",
"Id": "53243",
"Score": "0",
"body": "I think I know that `Int32` error, but not sure of the rest. Could you post your class structure? and did you use my `Convert<T>` in your Map<T> method?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T20:38:10.150",
"Id": "53256",
"Score": "0",
"body": "So, I've converted most of your code, and simply added it to my `Wrapper` class. (with some mods), it definately seems to be alot faster now. I am testing while using the same Sproc in my DB, but with differing parameters that return the same number of records. Do you see any way to make what I posted above more efficient? Or do you think that's about it?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T07:33:35.483",
"Id": "53367",
"Score": "0",
"body": "You should still use `Convert<T>` class or adapt it. The point of `Convert<T>` class is to prepare stuff for type `T`, which is cache lookup. Thread-safe cache lookup is relatively costly, and that's why I separated it to `Convert<T>` so the cache lookup was done once for the whole list."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-28T11:50:55.090",
"Id": "53457",
"Score": "0",
"body": "I tried using it like that but came up with errors, that I had posted here as comments, but were never answered for, so I tried it this way. I will attempt your class again"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-28T11:56:05.037",
"Id": "53459",
"Score": "0",
"body": "Once again, I get the error... \"Invalid attempt to read when no data is present.\""
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-28T14:51:43.023",
"Id": "53492",
"Score": "0",
"body": "If you can share your code so please do so. It's quite hard to imagine what's happening without seeing actual code."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-28T14:54:29.063",
"Id": "53493",
"Score": "0",
"body": "i created a new class, pasted your class code into it. Updated question with the new WrapperTest"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-28T16:44:16.500",
"Id": "53505",
"Score": "0",
"body": "You didn't wrap the `CreateItemFromRow` call with `while` loop. You should wrap it with `while (dr.Read()) {`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-28T16:50:30.800",
"Id": "53506",
"Score": "0",
"body": "Please see my edit."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-29T14:05:05.310",
"Id": "53591",
"Score": "0",
"body": "DURRR. What a tool. Thank you for all this, and putting up with me. This is faster. .015secs faster over 10,000 records. Second iteration is over .15secs faster :) Thank you!"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T15:40:10.340",
"Id": "33238",
"ParentId": "33128",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": "33238",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T13:22:48.117",
"Id": "33128",
"Score": "3",
"Tags": [
"c#",
"performance",
"sql",
"sql-server",
"asynchronous"
],
"Title": "DAL mapping efficiency"
}
|
33128
|
<p>This is my first attempt at JavaScript, so I am looking to learn. </p>
<p>I have a website that has jQuery built in and I wanted to leverage that in the following way:</p>
<ol>
<li>I want to get a number variable that precedes a certain text string (<code>*n*/portal.css</code>)</li>
<li>Get the name of the current webpage</li>
<li>Use this number and pageName to help build a URL to a specifically named image file The image will have the same name as the webpage with an "_hd.jpg" appended to it</li>
<li>Check if the image file exists and if it does add this image to a CSS div background otherwise do nothing</li>
</ol>
<pre><code><script>
$(function () {
$(document).foundation();
//get webpage name
var loc = window.location.href
var fileNameIndex = loc.lastIndexOf("/") + 1;
var dotIndex = loc.lastIndexOf('.');
var pageName = loc.substring(fileNameIndex, dotIndex < fileNameIndex ? loc.length : dotIndex);
//get number variable
var head = document.head
var portalCss = head.innerHTML.match(/\/[0-9]+\/portal.css/);
var portalNum = portalCss[0].replace("/", "")
portalNum = portalNum.replace("portal.css", "")
//build url for image
var HeaderImgUrl = '/Portals/' + portalNum + '/Images/' + pageName + '_hd.jpg'
//check if image exists and assign css values to css class RowPageHeader
$.ajax({
url: HeaderImgUrl, //or your url
success: function (data) {
$(".RowPageHeader").css("background-image", "url(" + HeaderImgUrl + ")");
$(".RowPageHeader").css("background-position", "center top");
$(".RowPageHeader").css("background-size", "100% auto");
$(".RowPageHeader").css("background-repeat", "no-repeat");
$(".RowPageHeader").css("overflow", "hidden");
},
})
var FooterImgUrl = '/Portals/' + portalNum + '/Images/footer_bg.jpg'
$.ajax({
url: FooterImgUrl, //or your url
success: function (data) {
$(".RowFooter").css("background-image", "url(" + FooterImgUrl + ")");
$(".RowFooter").css("background-position", "center top");
$(".RowFooter").css("background-size", "2000px auto");
$(".RowFooter").css("background-repeat", "no-repeat");
$(".RowFooter").css("overflow", "hidden");
},
})
})
</script>
</code></pre>
<p><strong>Two questions:</strong></p>
<ol>
<li>How can I improve this code?</li>
<li>I want to move the CSS rules into a CSS class in the pages skin.css file. How can I add a CSS class to the existing one that I am adding the CSS rules to?</li>
</ol>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T02:30:18.823",
"Id": "53110",
"Score": "0",
"body": "Can you give some sample inputs? It's hard to understand the code when you don't know the input."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T15:19:26.443",
"Id": "53154",
"Score": "0",
"body": "sure, the only inputs are the url of the website page (ie www.website.com/MyPage or www.website.com/MyPage.aspx) and the regex search for \"n/portal.css\" where n is an integer that I want to extract. The css classes are hard coded in because they will never change (RowPageHeader and RowFooter). Does this help @JosephtheDreamer?"
}
] |
[
{
"body": "<p>Basically every duplicated object can be made one object. And maybe use a function so you can call it when required.</p>\n\n<p>If you use an <a href=\"http://en.wikipedia.org/wiki/Immediately-invoked_function_expression\" rel=\"nofollow\">IIFE</a> like below, you can put this code in an external *.js file. It will then run asap without stalling other http requests while loading the page. Also pass in the <code>jQuery</code> object as a parameter so you can safely use <code>$</code> instead.</p>\n\n<ol>\n<li><p>The configuration separation allows you to easily change things when needed. They're also grouped and give you a better overview. Compared to the other objects the <code>cfg</code> variable is the \"local global\" so you can use <code>cfg</code> throughout your whole script.</p></li>\n<li><p>The window object groups your functionality or component in one object. Basically one DOM object for a project is ideal imho. Allows you to access <code>window.ComponentName</code> in other files as well.</p></li>\n<li><p>The activation is under your control. For the moment it uses the common DOM ready event and basically just runs the <code>init()</code> function.</p></li>\n</ol>\n\n\n\n<pre><code>// @param ($): jquery version x?\n(function ($) {\n // 1. CONFIGURATION\n var cfg = {\n rowpageheader: '.RowPageHeader',\n rowfooter: '.RowFooter',\n options: {\n header: {\n 'background-position': 'center top',\n 'background-size': '100% auto',\n 'background-repeat': 'no-repeat',\n 'overflow': 'hidden'\n },\n footer: {\n 'background-position': 'center top',\n 'background-size': '2000px auto',\n 'background-repeat': 'no-repeat',\n 'overflow': 'hidden'\n }\n },\n path: {\n portal: 'Portals',\n images: 'Images'\n },\n misc: {\n portalcss: 'portal.css',\n imagequality: '_hd.jpg',\n footerbg: 'footer_bg.jpg'\n }\n };\n\n // 2. DOM OBJECT\n window.Images = {\n init: function () {\n this.cacheItems();\n this.activate();\n },\n\n cacheItems: function () {\n this.rowPageHeader = $(cfg.rowpageheader);\n this.rowFooter = $(cfg.rowfooter);\n },\n\n activate: function () {\n var cfgOptions = cfg.options, \n portalNum = this.getPortalNum(),\n pageName = this.getPageName();\n\n this.updateHeader(portalNum, pageName, cfgOptions.header);\n this.updateFooter(portalNum, cfgOptions.footer);\n },\n\n getPageName: function () {\n var loc = window.location.href,\n fileNameIndex = loc.lastIndexOf('/') + 1,\n dotIndex = loc.lastIndexOf('.');\n\n return loc.substring(fileNameIndex, dotIndex < fileNameIndex ? loc.length : dotIndex);\n },\n\n getPortalNum: function () {\n var head = document.head,\n portalcss = cfg.misc.portalcss,\n regexp = '/\\/[0-9]+\\/' + portalcss + '/',\n portalCss = head.innerHTML.match(regexp),\n portalNum = portalCss[0].replace('/', '');\n\n return portalNum.replace(portalcss, '');\n },\n\n updateHeader: function (portalNum, pageName, options) {\n var proj = this,\n cfgPath = cfg.path,\n headerUrl = [cfgPath.portal, portalNum, cfgPath.images, pageName, cfg.misc.imagequality];\n\n $.ajax({\n url: headerUrl.join('/')\n }).done(function () {\n var opt = $.extend(options, { backgroundImage: 'url(' + headerUrl + ')' });\n proj.rowPageHeader.css(opt);\n });\n },\n\n updateFooter: function (portalNum, options) {\n var proj = this,\n cfgPath = cfg.path,\n footerUrl = [cfgPath.portal, portalNum, cfgPath.images, cfg.misc.footerbg];\n\n $.ajax({\n url: footerUrl.join('/')\n }).done(function () {\n var opt = $.extend(options, { backgroundImage: 'url(' + footerUrl + ')' });\n proj.rowFooter.css(opt);\n });\n }\n };\n\n // 3. DOM READY\n $(function () {\n $(document).foundation();\n Images.init();\n });\n} (jQuery));\n</code></pre>\n\n<p>Haven't checked if this works, but it should ^^</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-26T05:16:46.463",
"Id": "53289",
"Score": "0",
"body": "thats a lot to process for a first time java user. thanks, learned a lot"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-26T00:17:01.713",
"Id": "33270",
"ParentId": "33132",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "33270",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T16:43:57.390",
"Id": "33132",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"css",
"beginner"
],
"Title": "JavaScript and jQuery check for image file and assign CSS"
}
|
33132
|
<p>I am calling a JS file from a bundle directory like so:</p>
<pre><code><script src="{{ asset('bundles/macppages/js/main.js') }}"></script>
</code></pre>
<p>which loads the JS file into the base.index.twig</p>
<p>In that JS file I want to add some custom css via jQuery like this:</p>
<pre><code>function loadBkrndImg(){
var img = new Image();
img.src = "/bundles/macppages/images/bkrnd.0" + currentBkrndImgNum + ".jpg";
$('body').css("background-image","url('" + img.src + "')");
}
</code></pre>
<p>which works, but to the question:</p>
<p>Is this the <em>correct</em> way to do it using the Symfony 2 framework? In Symfony 1, there was a function you could call to pull the web dir. With Sym2, the assets are in the bundle directories, so is there a Symfony2 command for this so it is not so explicit? </p>
|
[] |
[
{
"body": "<p>There might be a better way to retrieve the web directory, I would not know. However, there are other things to ponder upon.</p>\n\n<ul>\n<li>Naming : <code>loadBkrndImg</code> -> <code>loadBackgroundImage</code> looks so much better</li>\n<li>Naming : <code>currentBkrndImgNum</code>, enough said..</li>\n<li>The background image number ought to be a parameter to <code>loadBackgroundImage</code>, not a global</li>\n<li>You are creating an Image() object, assign the <code>src</code> value ( which can trigger the loading of the image ) , and then throw away the image. You could just put the url in a string.</li>\n<li>You could preemptively centralize the retrieval of the asset folder</li>\n</ul>\n\n<p>I would counter-suggest the following : </p>\n\n<pre><code>function getAssetFolder( subfolder )\n{\n var folder = '/bundles/macppages/';\n return subFolder ? ( folder + subfolder + \"/\" ) : folder\n}\n\nfunction loadBackgroundImage( number )\n{\n var url = getAssetFolder( 'images' ) + 'bkrnd.0' + number + '.jpg';\n $('body').css(\"background-image\",\"url('\" + url + \"')\");\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-14T01:03:21.630",
"Id": "39195",
"ParentId": "33134",
"Score": "8"
}
}
] |
{
"AcceptedAnswerId": "39195",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T17:51:40.577",
"Id": "33134",
"Score": "3",
"Tags": [
"javascript",
"jquery",
"image",
"symfony2"
],
"Title": "Linking to an image asset from a JavaScript file in Symfony 2"
}
|
33134
|
<p>I've just wrote a program in C# for counting sort.</p>
<ul>
<li>space complexity is O(N+K)</li>
<li>time complexity is O(N+K)</li>
</ul>
<p>I want reviews on my code and any better ways to implement this.</p>
<pre><code>namespace SortingSelfCoded
{
public static class CountingSorter
{
public static int[] CountingSort(int [] input)
{
// O(1)
int max = input[0];
// O(N)
for (int i = 0; i < input.Length; i++)
{
if (input[i] > max)
{
max = input[i];
}
}
// Space complexity O(N+K)
int[] counts = new int[max + 1];
int[] output = new int[input.Length];
// O(N)
for (int i = 0; i < input.Length; i++)
{
counts[input[i]]++;
}
int j=0;
// O(N+K)
for (int i = 0; i < counts.Length; i++)
{
while (counts[i] > 0)
{
output[j] = i;
j++;
counts[i]--;
}
}
return output;
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>From a practical use point of view:</p>\n\n<ol>\n<li>I'd use <code>input.Max()</code> (LINQ) to obtain the maximum. Less code to write and does the same.</li>\n<li>While it is ok to use single letter variables for loop counter <code>j</code> is not really a loop counter. It's the index of the current element so I would rename <code>j</code> into <code>currentIndex</code>.</li>\n<li><p>Consider changing your last while loop into a for loop. This avoids mutating the state of the <code>count</code> array (saves you a read and write on every iteration):</p>\n\n<pre><code>for (int k = 0; k < count[i]; k++)\n{\n output[currentIndex++] = i;\n}\n</code></pre></li>\n<li><p>Even on a 64 bit system the size of an array is limited to 2GB. So if your largest key is in the vicinity of <code>Int32.Max / 4</code> or larger then you will get an <code>OutOfMemoryException</code>. Depending what else you are doing in your program you will get it much earlier. If you are experimenting around with sorting algorithms then there are <a href=\"http://en.wikipedia.org/wiki/Integer_sorting#Algorithms_for_small_keys\" rel=\"nofollow\">some interesting approaches</a> reducing the key space.</p></li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T20:34:45.497",
"Id": "33138",
"ParentId": "33135",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "33138",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T18:18:28.703",
"Id": "33135",
"Score": "3",
"Tags": [
"c#",
"algorithm",
"sorting"
],
"Title": "Counting sort review"
}
|
33135
|
<p>A few things:</p>
<ol>
<li>I tried to do it with smart pointers because I wanted to learn about them. I'm not sure I made the right choice of type, however (and started to regret it half-way through).</li>
<li>This is for school, so some operations were required. I can't change main.cpp or the general layout.</li>
<li><code>insert()</code> works. However, I'm suspicious it's not working properly. I haven't implemented delete functionality yet.</li>
</ol>
<p>Any comments / suggestions appreciated.</p>
<p>Here's my <a href="https://gist.github.com/bogobogosort/7124239" rel="nofollow">singly linked list</a>.</p>
<p>I've also posted this on <a href="http://www.reddit.com/r/learnprogramming/comments/1p2h8j/c_code_review_school_assignment/" rel="nofollow">Reddit</a>.</p>
<p><strong>List.cpp</strong></p>
<pre><code>#include "List.h"
void List::reverse_print(std::shared_ptr<Link> curr) const {
if (curr) {
reverse_print(curr->next);
std::cout << curr->datum << '\n';
}
}
void List::push_front(int val) {
std::unique_ptr<Link> new_link(new Link(val));
new_link->next = root;
root = std::move(new_link);
}
void List::push_back(int val) {
std::unique_ptr<Link> new_link(new Link(val));
if (!root)
root = std::move(new_link);
else {
std::shared_ptr<Link> curr(root);
while (curr->next) {
curr = curr->next;
}
curr->next = std::move(new_link);
}
}
void List::insert(int val, int loc){
if (loc > length( ) + 1 || loc < 1)
std::cout << "Insertion location is invalid.\n";
else {
if (loc == 1)
push_front(val);
else if (loc == length() + 1)
push_back(val);
else {
int node_count = 1;
std::shared_ptr<Link> ptr(root);
while (node_count < loc - 1) {
ptr = ptr->next;
++node_count;
}
std::shared_ptr<Link> new_link(new Link(val));
ptr->next = new_link;
}
}
}
int List::length() const {
int node_count = 0;
std::shared_ptr<Link> ptr(root);
while (ptr) {
ptr = ptr->next;
++node_count;
}
return node_count;
}
void List::print() const {
std::shared_ptr<Link> temp(root);
if (!temp) {
std::cout << "List is empty.\n";
return;
}
std::cout << "Beginning.\n";
while (temp) {
std::cout << temp->datum << '\n';
temp = temp->next;
}
std::cout << "Ending.\n"
"Length of list : " << length() << " nodes.\n";
}
void List::reverse_print() const {
std::cout << "Ending.\n";
reverse_print(get_first());
std::cout << "Beginning.\n"
"Length of list : " << length() << " nodes.\n";
}
void List::initialize_list() const {
if (this) // not sure what to put here
std::cout << "Empty list exists.\n";
}
std::shared_ptr<List::Link> List::get_first() const {
return root;
}
void List::destroy_list() {
root.reset();
};
bool List::empty( ) const {
return root == nullptr;
}
/*
void delete_link( ){ }
void delete_first( ) { }
void delete_last( ) { }
*/
</code></pre>
<p><strong>List.h</strong></p>
<pre><code>#ifndef LIST_H
#define LIST_H
#include <memory>
#include <iostream>
class List {
struct Link {
int datum;
std::shared_ptr<Link> next;
explicit Link(int val = 0) : datum{ val } {
std::cout << "Link constructor invoked.\n";
}
~Link() {
std::cout << "Link destructor invoked.\n";
}
};
std::shared_ptr<Link> root;
void reverse_print(std::shared_ptr<Link>) const;
public:
explicit List() : root{ nullptr } {
std::cout << "List constructor invoked.\n";
}
~List() {
std::cout << "List destructor invoked.\n";
}
void push_front(int);
void push_back(int);
void insert(int, int);
int length() const;
void print() const;
void reverse_print() const;
void initialize_list() const;
std::shared_ptr<Link> get_first( ) const;
void destroy_list( );
bool empty( ) const;
//void delete_first( );
//void delete_last( );
//bool delete_link(int val);
};
#endif
</code></pre>
<p><strong>Main.cpp</strong></p>
<pre><code>#include "Menu.h"
#include "List.h"
int main() {
Menu menu;
std::unique_ptr<List>list(new List());
do {
menu.display();
menu.query_user();
menu.process_command(list);
} while (menu.cont());
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T21:21:15.103",
"Id": "53094",
"Score": "0",
"body": "Spotted 1 Bug and about 5 comments."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-17T18:19:40.463",
"Id": "122202",
"Score": "1",
"body": "If the list is big enough, the stack will overflow on container destruction."
}
] |
[
{
"body": "<p>Some comments to the things you have implemented so far:</p>\n\n<ol>\n<li><code>reverse_print</code>: Printing the list in reverse order recursively is an academically interesting solution but if your list is sufficiently long then your stack will explode. Use a <code>std::stack</code> to temporarily store the elements and then print that.</li>\n<li><code>push_back</code>: Currently this is O(n) because you iterate the entire list to find the last element. If you store a <code>tail</code> pointer which points to the last element in the list in addition to <code>root</code> then you can avoid that and this operation becomes O(1).</li>\n<li><code>length()</code>: Keep a length property in the class which you increment/decrement when a node got added/removed. Again reduces an O(n) operation to O(1).</li>\n<li><code>insert()</code>:\n<ol>\n<li>While it's commendable for the (application) user experience to have 1 based indices, as a programer who might use this it will be confusing. Indices into containers like arrays and vectors are 0 based in C++ land. Deviating from the standard is bad because it is unexpected.</li>\n<li>Insert is broken. You will lose all items after the insert position (<code>new_link->next</code> points to nothing and <code>ptr->next</code> now points to <code>new_link</code> -> all elements starting from the old <code>ptr->next</code> are now lost)</li>\n</ol></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T17:43:44.480",
"Id": "53168",
"Score": "0",
"body": "This is exactly what I was looking for. Thanks for taking the time to look at it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T09:11:04.020",
"Id": "33162",
"ParentId": "33136",
"Score": "5"
}
},
{
"body": "<p>Everything @ChrisWue said.</p>\n<p>Also:</p>\n<p>Design.<br />\nUsing <code>sharded_ptr<></code> does have affects on meaning (especially when copying). And I don't think you handle that correctly. Also You are building a container like structure. Usually memory management is done either by container (for groups of values) or by smart pointer (for single values). These are complementary types of memory management and intermixing them adds redundancy. You are already writing code to manage memory why add another layer on top (you can but it usually more efficient to do it manually).</p>\n<p>So personally I would have not gone with smart pointers here (because you are building a container).</p>\n<p>But the problem:</p>\n<pre><code> List a;\n // Do stuff with a\n\n List b(a); // Make a copy of `a`\n</code></pre>\n<p>This is not doing what you expect.<br />\nWith your code both list share the underlying list of nodes. If I modify one of these objects then the other one is modified in parallel. This may be deliberate and feature but it <code>violates the principle of least surprise</code> and thus should be clearly documented if delibrate.</p>\n<p>Note I: Same applies to assignment operator.<br />\nNote II: The compiler automatically generates the copy constructor and assignment operator.</p>\n<p>I will assume the above was a mistake. Basically I believe you are using the wrong smart pointer. The list of nodes contained by the list is solely owned by the container and there is no shared ownership. A more appropriate smart pointer would have <code>std::unique_ptr<></code>. If you would have used this the compiler would have complained when you tried to build as the default copy constructor would have not worked.</p>\n<p>The reason for using a smart pointer to control memory management is that it can get quite convoluted in normal code. But because your code hides the link object internally the number of use cases is limited (nobody can abuse your object just you). So this makes memory management simpler and you can quite easily implement it yourself (but std::unique_ptr is a perfectly valid alternative in this case).</p>\n<p>Note 3: Implement the Copy constructor. Implement assignment in terms of copy construction by using the <code>Copy and Swap</code> idiom.</p>\n<h2>Edit: Based on question comment</h2>\n<p>Adding an element to a list that uses std::unique_ptr</p>\n<pre><code>struct Node\n{\n std::unique_ptr<Node> next;\n};\n\nvoid insert(std::unique_ptr<Node>& after, std::unique_ptr<Node>& newNode)\n{\n /*\n * after: A node in the chain.\n * newNode: A new node (with next NULL) that needs to be added to the chain.\n *\n * This function adds `newNode` to the chain.\n * Post condition: after->next = newNode\n * newNode->next = after(before call)->next;\n */\n std::swap(after->next, newNode->next); // newNode->next now points to the rest of the chain.\n std::swap(after->next, newNode); // newNode added to chain.\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-29T05:10:40.933",
"Id": "53562",
"Score": "0",
"body": "Thanks for looking at my code. I've given it some thought and revamped the code quite a bit, however I'm not sure how to acomplish `insert_front` or `insert` at any location other than back with `unique_ptr`s. Any ideas? Here is my new [push_back](https://gist.github.com/bogo-sort/7209459) function"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T16:23:52.007",
"Id": "33241",
"ParentId": "33136",
"Score": "3"
}
},
{
"body": "<p>I wanted to offer a different angle, so definitely see the other answers. I'm mostly nitpicking:</p>\n\n<ol>\n<li>Organize your code top-down. Show the header for the cpp file, and probably main before either. Why? So that by the time we see the guts of the code, we have a sense for what you want to do.</li>\n<li>Don't omit parameter names in the header file - they help self-document your API.</li>\n<li>Prefer <code>std::make_shared</code> to the <code>std::shared_ptr</code> constructor, always. Use auto to make this easy. When C++14 rolls around, use <code>std::make_unique</code> instead of the <code>std::unique_ptr</code> constructors for the same reasons.</li>\n<li>Be consistent about using curly-brace initialization.</li>\n<li>Use using statements in the cpp file. Recall that you can do <code>using std::cout;</code> to just pull in that one symbol, rather than the entire standard library. This also documents your specific dependencies on headers nicely at the top.</li>\n<li>Pass <code>std::shared_ptr</code>'s by const-reference to avoid copying them when you don't need to.</li>\n<li>(Super nitpicking) Curly-brace your one line statements (ifs). It's a maintenance hazard if you don't. I've seen too many very competent programmers introduce silly bugs by doing this and mixing up their indentation. On the scale of importance maintainability >> linecount.</li>\n<li>It's not at all clear why in main your List is stored inside a <code>std::unique_ptr</code>. If this is meant to disable copy operations, you're doing so via the wrong avenue, as a user who doesn't know better won't put it in a <code>std::unique_ptr</code>. Instead, actually go ahead and explicitly disable copy operations, since they would yield surprising semantics.</li>\n<li>Prefer the name <code>clear</code> to <code>destroy_list</code>. It is more idiomatic (in that it matches the behavior and nomenclature of the standard library). <code>size</code> is also more idiomatic than <code>length</code> in C++.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-01-01T20:12:48.663",
"Id": "38400",
"ParentId": "33136",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": "33162",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T19:43:00.767",
"Id": "33136",
"Score": "6",
"Tags": [
"c++",
"c++11",
"homework",
"linked-list",
"smart-pointers"
],
"Title": "Singly linked-list with smart pointers"
}
|
33136
|
<p>Usually, <code>AsyncTask</code>s are meant to be one-shot, i.e. you start it, it fetches some data, displays the result and dies. However, I'm now using a long-running <code>AsyncTask</code> to load images as the need arises. So far it's working great, but I'd just like to know if this is good practice & if there's any threading detail that I missed. Here's my slimmed down implementation:</p>
<pre><code>public class ImageLoader extends AsyncTask<Void, Object, Void> {
private final List<String> pendingURLs = new Vector<String>();
private Thread backgroundThread;
@Override
protected Void doInBackground(Void... params) {
this.backgroundThread = Thread.currentThread();
while (!backgroundThread.isInterrupted()) {
String url = null;
synchronized(this) {
if (pendingURLs.size() > 0) {
url = pendingURLs.remove(0);
}
}
if (url != null) {
// fetch image...
publishProgress(url, fetchedBitmap); // in onProgressUpdate I call a listener that can be implemented by any Fragment or other component
}
try {
synchronized(this) {
if (pendingURLs.size() == 0) {
wait();
}
}
} catch (InterruptedException e) {
break;
}
}
}
public syncrhonized void addUrl(String url) {
pendingURLs.add(url);
notify();
}
public Thread getBackgroundThread() {
return backgroundThread;
}
}
</code></pre>
<p>Then, in my <code>Fragment#onCreate()</code> I create a new instance and execute it like this:</p>
<pre><code>mLoader = new ImageLoader();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
mLoader.executeOnExecutor(AsyncTask.THREAD_POOL_EXECUTOR);
} else {
mLoader.execute();
}
</code></pre>
<p>Finally, in my <code>Fragment#onDestroy()</code> I do:</p>
<pre><code>if (mLoader != null && mLoader.getBackgroundThread() != null) {
mLoader.getBackgroundThread().interrupt(); // this will cause it to break out of the while loop and finish the thread
}
</code></pre>
|
[] |
[
{
"body": "<p>For starters, you should replace your Vector with an ArrayBlockingQueue . Then you can drop the wait and the null check. Can also then remove synchronization on the add method since its handled by the data structure.</p>\n\n<pre><code>private final BlockingQueue<String> pendingURLs = new ArrayBlockingQueue<String>(64);\nprotected void doInBackground(Void... params) {\n this.backgroundThread = Thread.currentThread();\n while (!backgroundThread.isInterrupted()) {\n String url = pendingURLs.take();\n // fetch image...\n publishProgress(url, fetchedBitmap); // in onProgressUpdate I call a listener that can be implemented by any Fragment or other component\n }\n\npublic void addUrl(String url) {\n pendingURLs.put(url);\n}\n</code></pre>\n\n<p>You should probably replace it with just a new thread instead of using asynctask at all.</p>\n\n<pre><code>public class ImageLoader implements Runnable {\n private final BlockingQueue<String> pendingURLs = new ArrayBlockingQueue<String>();\n\n public void run() {\n while (true) {\n String url = pendingURLs.take(); \n // fetch image...\n publishProgress(url, fetchedBitmap); // in onProgressUpdate I call a listener that can be implemented by any Fragment or other component\n }\n }\n\n public void addUrl(String url) {\n pendingURLs.put(url);\n }\n}\n</code></pre>\n\n<p>Then you can create it in your initialization somewhere, ie</p>\n\n<pre><code> ImageLoader loader = new ImageLoader();\n new Thread(loader, \"BackgroundLoader\").start();\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-28T11:38:56.383",
"Id": "53455",
"Score": "0",
"body": "+1 Nice improvement to use the blocking queue. However, I wouldn't stray from `AsyncTask` since it handles calling `onProgressUpdate` on the UI thread whenever I call `publishProgress` from the background thread."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-07-16T10:09:22.923",
"Id": "102053",
"Score": "0",
"body": "which one is better,\nAndroid loader or AsyncTask ????"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T17:08:05.803",
"Id": "33187",
"ParentId": "33141",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T22:15:24.780",
"Id": "33141",
"Score": "1",
"Tags": [
"java",
"multithreading",
"android"
],
"Title": "Background image loader AsyncTask"
}
|
33141
|
<p>Is this code an adequate implementation of the producer/consumer pattern?</p>
<p>In computer science, the producer/consumer pattern is a classic example of multithreaded synchronisation. The problem describes some threads called consumers and some threads called producers sharing a common fixed-size queue.</p>
<p>In the above code, the queue is called <code>_myQueue</code> and it's size is 1000.</p>
<p>Each producer job is to generate some item, put it in the queue by calling <code>AddItem()</code>, and start again.
The consumers job is to remove items from the queue by calling <code>RemoveItem()</code></p>
<p>The problem is to make sure no producer tries to add items to the queue when it's full (i.e. containing 1000 items) and no consumer tries to remove items from the queue when it's empty.</p>
<p>Also, we'd like to avoid situation where consumers or producers end up waiting for no reason (deadlocks).</p>
<pre><code>private int _count = 1000;
private Queue<string> _myQueue = new Queue<string>();
private static object _door = new object();
public void AddItem(string someItem)
{
lock (_door)
{
while (_myQueue.Count == _count)
{
Monitor.Wait(_door);
}
_myQueue.Enqueue(someItem);
Monitor.Pulse(_door);
}
}
public string RemoveItem()
{
string item = null;
lock (_door)
{
while (_myQueue.Count == 0)
{
Monitor.Wait(_door);
}
item = _myQueue.Dequeue();
Monitor.Pulse(_door);
}
return item;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T00:20:07.890",
"Id": "53102",
"Score": "4",
"body": "Why would you write your own instead of using `BlockingCollection`? Also, does it seem to work for you?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T22:53:14.450",
"Id": "53191",
"Score": "0",
"body": "@svick I'm aware of the existence of this class in .NET 4 but this is more of a personal challenge than a real world problem. My implementation seems to work but I wanted to make sure I didn't overlook something."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-10-24T15:56:03.703",
"Id": "123728",
"Score": "0",
"body": "@svick : One reason to avoid using BlockingCollection, is simply if you can't use .NET 4 features, either because you are forced in a production environment without it, or because your development environment doesn't support that (e.g. Unity 3D)."
}
] |
[
{
"body": "<p>Answering whether or not this implementation is correct would require to know what the specification of the problem is. Now assuming the spec is:</p>\n\n<blockquote>\n <p>Create a queue to which multiple threads can add items and multiple threads can remove item. The queue will hold no more than 1000 string references and blocks writers when the queue is full and readers when the queue is empty.</p>\n</blockquote>\n\n<p>then I'd say yes your implementation will achieve that.</p>\n\n<p>Some remarks:</p>\n\n<ol>\n<li>As mentioned by @svick you should seriously consider using <a href=\"http://msdn.microsoft.com/en-us/library/dd287116.aspx\" rel=\"nofollow\"><code>BlockingCollection</code></a> which was added in .NET 4.0. </li>\n<li>You can increase the practical usefulness immediately by doing two simple things\n<ol>\n<li>Make your class generic. This way you can create a blocking queue for any type not just <code>string</code>.</li>\n<li>Let the user pass in the capacity.</li>\n</ol></li>\n<li><p>Some future speculation in case you are stuck with .NET 3.5 or earlier and want to stick with your implementation: If you are ever tempted to implement <code>IEnumerable<T></code> (to show the content in a UI for example) on your class then remember that the following implementation is broken (I have seen this more often than I'd like):</p>\n\n<pre><code>public IEnumerator<T> GetEnumerator()\n{\n lock (_door)\n {\n return _myQueue.GetEnumerator();\n }\n}\n</code></pre>\n\n<p>The correct way would be to make a local copy of the queue (inside the lock) and return the enumerator to that. The other option is to iterate over the queue inside the lock and yield the items which effectively locks the queue for the entire duration of the enumeration. However this is probably a bad idea since a caller which is not aware of this can easily lock out all access to the queue for a long period of time.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T23:04:00.970",
"Id": "53193",
"Score": "0",
"body": "Sorry if I wasn't clear enough. I edited my question. The spec you assumed is correct. I want to make sure as well my implementation doesn't result in a deadlock. This is more of a personal challenge than a real world problem, hence not using `BlockingCollection` or Generics. +1 for the GetEnumerator() tip!"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T17:33:06.503",
"Id": "53242",
"Score": "1",
"body": "Peeking in the source of `BlockingCollection`, it offers an both an enumerator which makes a copy and a consuming enumerable which modifies the collection as it is enumerated."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T08:31:37.787",
"Id": "33160",
"ParentId": "33142",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-23T23:01:46.520",
"Id": "33142",
"Score": "5",
"Tags": [
"c#",
"multithreading"
],
"Title": "Producer/Consumer in C#"
}
|
33142
|
<p>I have this Book program that contains 2 classes: <code>Book</code> and <code>Library</code>. I have the Book class done, but need some help on the Library class. Please help me check my code. I can provide the Book class if you need it.</p>
<p>Instruction here:</p>
<blockquote>
<p>Fields: A single private ArrayList of Book field is all that is
necessary. This will hold all the Book objects in the library.</p>
<p>Methods: <code>public Library(ArrayList other)</code></p>
<p>Throws a NullPointerException if other is null. Otherwise, the
Library’s Book ArrayList should take on all the books in other.</p>
<p><code>public Library( )</code> Creates an empty ArrayList of books.</p>
<p><code>public boolean add(Book book)</code></p>
<p>First checks for null or empty Strings and calls the appropriate
exception. Otherwise it adds the Book argument to the end of the
library ArrayList. Notice it returns a boolean (whether or not the add
operation succeeded) See the add method of ArrayList:</p>
<p><code>public ArrayList findTitles(String title)</code></p>
<p>Generates an ArrayList of all books which have titles that match
(exactly) with the passed argument and returns this list to the
calling program. The String compareTo method is useful here.</p>
<p><code>public void sort( )</code></p>
<p>Sorts the library’s book ArrayList in ascending order according to the
title field (sort these titles just as they are, i.e. don’t worry
about articles such as The or A, etc.). As illustrated in the
textbook, p. 666 (Don’t let this number concern you :) ), you will use
the Collections sort.</p>
<p><code>public String toString( )</code></p>
<p>returns a properly formatted String representation of all the books in
the library (Title followed by authors).</p>
</blockquote>
<pre><code> import java.util.ArrayList;
</code></pre>
<p>import java.util.Collections;</p>
<pre><code>public class Library {
private ArrayList<Book> allBook = new ArrayList<Book>();
public Library(ArrayList<Book> other) {
if (other == null) {
throw new NullPointerException("null pointer");
} else
this.allBook = other;
}
public Library() {
this.allBook = new ArrayList<Book>();
}
public boolean add(Book book) {
if (book != null && !book.equals("")) {
throw new IllegalArgumentException("Can't be empty");
}
allBook.add(book);
return true;
}
public ArrayList<Book> findTitles(String title) {
for(Book b: allBook) {
if(title.compareTo(b.getTitle())== 0) {
return allBook;
}
}
return null;
}
public void sort() {
Collections.sort(allBook);
}
public String toString() {
return Library.this.toString();
}
}
public class Book implements Comparable<Book> {
private String bookTitle;
private ArrayList<String> bookAuthor;
public Book(String title, ArrayList<String> authors) {
if(title == null && authors == null) {
throw new IllegalArgumentException("Can't be null");
}
if(title.isEmpty() && authors.isEmpty()) {
throw new IllegalArgumentException("Can't be empty");
}
bookTitle = title;
bookAuthor = authors;
}
public String getTitle() {
return bookTitle;
}
public ArrayList<String> getAuthors( ) {
return bookAuthor;
}
public String toString( ) {
return bookTitle + bookAuthor;
}
public int compareTo(Book other){
return bookTitle.compareTo(other.bookTitle);
}
public boolean equals(Object o) {
if(!(o instanceof Book)) {
return false;
}
Book b = (Book) o;
return b.bookTitle.equals(bookTitle)
&& b.bookAuthor.equals(bookAuthor);
}
}
</code></pre>
|
[] |
[
{
"body": "<p>Your default constructor Library() initializes the allBook member variable twice, with the same value in each case. Probably not what you had in mind. The immediate fix is to remove the (re) assignment in the default constructor.</p>\n\n<p>Now you have two different constructors that do the right thing two different ways. To save yourself maintenance headaches, you'd normally prefer to have one code path that does \"everything\", so it would be good to combine the two. There are two different ways of doing that, depending on the requirements....</p>\n\n<p>Consider this test.</p>\n\n<pre><code>ArrayList source = new ArrayList();\nsource.add(book1);\nsource.add(book2);\nsource.add(book3);\n\nLibrary library = new Library(source);\nlibrary.add(book4);\n</code></pre>\n\n<p>At this point, the library should contain four books. But how many books should the source array contain?</p>\n\n<p>If the answer is four, the the library is supposed to be modifying the array it was passed. In that case, the easy answer to the constructor problem is to have the default constructor call the other, like so:</p>\n\n<pre><code>Library () {\n this(new ArrayList<Book>);\n}\n</code></pre>\n\n<p>On the other hand, if the source array should still contain three books, then the Library should contain a copy of the ArrayList, rather than holding onto the original. If that's your requirement, then the good answer is to go the other way around - initialize the allBook member where you declare it, but use copy semantics when you are passed the ArrayList</p>\n\n<pre><code>ArrayList<Book> allBook = new ArrayList<Book> ();\n\nLibrary () {}\n\nLibrary (ArrayList<Book> books) {\n allBook.addAll(books);\n}\n</code></pre>\n\n<p>Your code in this version of the puzzle is very confused about Books, titles, and Strings. Your requirements said </p>\n\n<pre><code>public ArrayList findTitles(String title)\n</code></pre>\n\n<p>but the signature in your class is</p>\n\n<pre><code>public ArrayList<Book> findTitles(Book title)\n</code></pre>\n\n<p>The code in a number of places suggests that, once upon a time, you thought all books were just Strings, and then you changed your mind. Your compiler should be telling you that you aren't being consistent.</p>\n\n<p>The requirements for findTitles says that you should be returning an ArrayList of books with matching titles. That means you probably need to be creating a new ArrayList, and then add()ing the matching Books to it. The code you've written returns all of the books, but takes extra time to compare at the books first. You probably don't want to call Book.compareTo (although you can implement the solution correctly that way), but instead Book.getTitle().equals(otherBook.getTitle())</p>\n\n<p>There are better answers than for loops for visiting all of the elements in an ArrayList. See Iterable. Since you've written Book.toString() already, you can start Library.toString() by building a big String out of all of the Book.toString()s.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T02:41:25.153",
"Id": "33149",
"ParentId": "33148",
"Score": "6"
}
},
{
"body": "<p>I have never written a line of java code, but I'll give it a shot:</p>\n\n<pre><code>public Library(ArrayList<Book> other) {\n if (other == null) {\n throw new NullPointerException(\"null pointer\");\n } else\n allBook = other;\n}\n</code></pre>\n\n<p>The <code>else</code> here is redundant after the guard clause, this method could be written like this:</p>\n\n<pre><code>public Library(ArrayList<Book> other) {\n if (other == null) {\n throw new NullPointerException(\"null pointer\");\n }\n allBook = other;\n}\n</code></pre>\n\n<hr>\n\n<p><code>Library.toString()</code> (spoiler):</p>\n\n<blockquote class=\"spoiler\">\n <p> Simply iterate <em>allBook</em> and call the <em>toString</em> method on each book.</p>\n</blockquote>\n\n<p>The <em>Book</em> class' <em>toString</em> method could do a little more than just concatenating <code>bookTitle+bookAuthor</code>. Maybe something like <code>\"Title: \" + bookTitle + \" | Author: \" + bookAuthor</code> would look much better.</p>\n\n<hr>\n\n<p>In <code>Book.equals()</code>, I think the method should actually throw an exception if <code>o</code> isn't a <code>book</code>, but again I'm not very used to duck-typed code so maybe not... but then if an object has a <code>bookTitle</code> and a <code>bookAuthor</code> property then why shouldn't it be treated as if it were a <code>Book</code>? It looks like a duck, quacks like a duck, walks like a duck, ...it's a duck! (or maybe I'm mixing up java with javascript here) -- point is, if <code>Book.equals()</code> handles the case where <code>o</code> isn't a <code>Book</code>, then I don't see why <code>Book.compareTo()</code> shouldn't do the same... or vice-versa!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T10:32:47.287",
"Id": "53135",
"Score": "0",
"body": "I got everything else, But still not sure how the toString method in Library works."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T12:41:22.490",
"Id": "53142",
"Score": "0",
"body": "In C# I'd use a `StringBuilder` and `builder.Append(thisBook.ToString());` on each iteration, and then I'd `return builder.ToString()`."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T02:42:23.027",
"Id": "33150",
"ParentId": "33148",
"Score": "4"
}
},
{
"body": "<p>Just a quick note (as far as I see nobody has mentioned yet):</p>\n\n<p><code>ArrayList<...></code> reference types should be simply <code>List<...></code>. See: <em>Effective Java, 2nd edition</em>, <em>Item 52: Refer to objects by their interfaces</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T05:24:53.510",
"Id": "33153",
"ParentId": "33148",
"Score": "3"
}
},
{
"body": "<p>I agree with everything said by @VoidOfUnreason and @RetailCoder, and won't bother repeating them. I'll just note that there are many careless bugs.</p>\n\n<p>In <strong><code>Library.add()</code></strong>, your if-condition is wrong. Also, the problem specifies that it should return a boolean indicating whether the operation succeeded. That's open to interpretation: what constitutes a failure? Running out of memory? Not likely; the customary action in that case would be to helplessly let the <code>OutOfMemoryException</code> propagate. What if you try to add the same book to the library twice? That's a reasonable failure mode. What if you add a second copy of a book that is already in the library? That should succeed, I would think.</p>\n\n<p>In <strong><code>Library.findTitles()</code></strong>, your for-loop is wrong. A common idiom in languages with zero-based arrays is…</p>\n\n<pre><code>for (int i = 0; i < n; i++) { ... }\n</code></pre>\n\n<p>In any case, modern Java code would typically say instead…</p>\n\n<pre><code>for (Book b : allBook) { ... }\n</code></pre>\n\n<p>The specification says that <code>.findTitles()</code> should return a list of matching books — so where's your new list?</p>\n\n<p>A hint for <strong><code>Library.toString()</code></strong>: you want to build a long string, so use a <code>StringBuilder</code> object. For each book in the library, you'll want to appends its string representation to the result.</p>\n\n<p>In the <strong><code>Book()</code></strong> constructor, your validation probably doesn't behave the way you intended.</p>\n\n<p>In <strong><code>Book.toString()</code></strong>, just slapping <code>bookTitle</code> and <code>bookAuthor</code> together is unlikely to yield a satisfactory result.</p>\n\n<p>Since you overrode <code>Book.equals()</code>, you should also implement <strong><code>Book.hashCode()</code></strong> to be consistent. Otherwise, you would not be able to store <code>Book</code>s in a <code>HashMap</code> or <code>Hashtable</code>.</p>\n\n<p>I would rename your instance variables <strong><code>allBook</code></strong> and <strong><code>bookAuthor</code></strong> using their plurals. The code will read more smoothly, and logic mistakes will be less likely.</p>\n\n<hr>\n\n<p>You really ought to have some test cases. Usually, that would be accomplished using <a href=\"http://junit.org/\" rel=\"nofollow\"><code>JUnit</code></a>, but for a beginner, making a <code>public static void main(String[] args)</code> would work fine. Implementing the tests would be a good exercise for you, and would help to uncover many bugs.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T07:02:41.000",
"Id": "53119",
"Score": "0",
"body": "thank you, i end up using the for each method,I think I got the problem figured out. Now im working on the test class which is public static void main(String[] args)."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T06:15:36.387",
"Id": "33156",
"ParentId": "33148",
"Score": "3"
}
},
{
"body": "<p><strong>1</strong>) I know it is not your fault, but I strongly disagree with the specification</p>\n\n<blockquote>\n <p>Methods: public Library(ArrayList other)</p>\n \n <p>Throws a NullPointerException if other is null. Otherwise, the Library’s Book ArrayList should take on all the books in other.</p>\n</blockquote>\n\n<p>I do not like the fact of <em>killing objects in the constructor</em>. The job of a constructor is: to initialize the object in a sane state - not killing it for <em>user's faults</em>. There are two ways to prevent this:</p>\n\n<p>1) Use a <code>factory</code> or a <code>builder</code> method, which refuse to initialize the Library with <code>null</code></p>\n\n<p>2) Gracefully ignore the attempt to initialize with <code>null</code> and initialize with an empty <code>ArrayList</code></p>\n\n<p><strong>Besides</strong>: Throwing a <code>NullPointerException</code> in the constructor leads to ugly code, since you have to wrap the construction in an unnecessary <code>try</code>-<code>catch</code>-block. Don't do this - please!</p>\n\n<p><strong>2)</strong> Naming\nYou could improve your naming a little bit:\n* <code>allBooks</code> should be renamed to <em>just</em> <code>books</code>, since the <code>ArrayList</code> contains <em>all</em> books. <code>allBooks</code> is a <em>tautology</em>.</p>\n\n<ul>\n<li><code>add</code> could be renamed to <code>addBook</code> - of course you could object, that this is a <em>tautology</em> too; since every IDE shows you, which type is expected. But not everyone uses an IDE. From this I would prefer <code>addBook</code></li>\n</ul>\n\n<p><strong>3)</strong> Actual Code </p>\n\n<blockquote>\n <p>First checks for null or empty Strings and calls the appropriate exception. Otherwise it adds the Book argument to the end of the library ArrayList. Notice it returns a boolean (whether or not the add operation succeeded) See the add method of ArrayList:</p>\n</blockquote>\n\n<p>Again: These are <strong>very poor</strong> specifications!\nWhy on earth do you have to return a <code>boolean</code> to signal, that there was <em>no</em> error, when the previous sentence clearly states, you have to throw an <code>Exception</code> if anything goes wrong? And more: <em>Who cares for a <code>boolean</code> return-value</em>? The <em>only</em> thing, which would make <em>any</em> sense, would be returning some kind of <em>id</em> in a <em>persistence-context</em> or for heavens sake the <em>total</em> number of books, but <strong>not a boolean</strong>.</p>\n\n<p>I am unhappy with that implementation. Of course, your <code>Book</code> has a <code>toString()</code>-Method and you are checking if the book is <em>literaly</em> a <em>blank</em> book. But doing it this way:</p>\n\n<pre><code>public boolean add(Book book) {\n if (book != null && !book.equals(\"\")) {\n throw new IllegalArgumentException(\"Can't be empty\");\n }\n allBook.add(book);\n return true;\n}\n</code></pre>\n\n<p>It reads <em>wrong</em>: »Check, whether the book is an empty string!« That doesn't make any sense at all. And honestly: At first, I didn't get it, unless I saw, the <code>toString()</code>. </p>\n\n<p>A better way of expressing this would be, adding a method to <code>Book</code>:</p>\n\n<pre><code>public boolean isBlank(){\n return bookAuthor.isEmpty() && bookTitle.isEmpty();\n}\n</code></pre>\n\n<p>And the check becomes more <code>readable</code> and makes <em>sense</em></p>\n\n<pre><code>public boolean addBook(Book book) {\n if (book == null || book.isBlank()){\n throw new IllegalArgumentException(\"Can't be empty\");\n }\n allBook.add(book);\n return true;\n}\n</code></pre>\n\n<p>»If the book is <code>null</code> <em>or</em> the book is <em>blank</em> throw an <code>IllegalArgumentException</code>«\nBtw. Why did you you use the <em>negative</em> from: <code>!a && !b</code> instead of just <code>a || b</code>?</p>\n\n<blockquote>\n <p>Generates an ArrayList of all books which have titles that match (exactly) with the passed argument and returns this list to the calling program. The String compareTo method is useful here.</p>\n</blockquote>\n\n<p>Here the specification is <em>clear</em>, but your implementation is <em>wrong</em>:</p>\n\n<pre><code>public ArrayList<Book> findTitles(String title) {\n for(Book b: allBook) {\n if(title.compareTo(b.getTitle())== 0) {\n return allBook;\n }\n }\n return null;\n}\n</code></pre>\n\n<p>You iterate over all books in the library, and if <em>one</em> book matches, you return the <em>whole</em> library. That's not, what you intended. And more <strong>Do not return <code>null</code></strong>! Please, never ever! That doesn't make any sense and leads to <em>excessive use</em> of <a href=\"http://c2.com/cgi/wiki?GuardClause\" rel=\"nofollow\">Guard Clauses</a> against <code>null</code>. It is a clear <strong>antipattern</strong>. In Java8 there is a <em>nicer</em> solution if you want to <em>hide</em> <code>null</code> in an <a href=\"http://www.oracle.com/technetwork/articles/java/java8-optional-2175753.html\" rel=\"nofollow\">optional</a>.</p>\n\n<p>Say, your teacher asks you to look for a specific book on the shelf and you do <em>simply nothing</em> - what does that mean to your teacher? A) you are <em>deaf</em> or b) you are <em>dumb</em> or c) you are <em>neither</em>, but <em>there is no book</em>. If someone asks you for a list of books, when there is <em>none</em>, simply return an <em>empty</em> list, and say politely: »Sorry, the list is empty, because there was no such book«.</p>\n\n<pre><code>public ArrayList<Book> findTitles(String title) {\n ArrayList<Book> result=new ArrayList<>();\n for(Book b: allBook) {\n if(title.compareTo(b.getTitle())== 0) {\n result.add(b);\n }\n }\n return result;\n}\n</code></pre>\n\n<p>This would be the <em>polite</em> way to answer the question.</p>\n\n<blockquote>\n <p>Sorts the library’s book ArrayList in ascending order according to the title field (sort these titles just as they are, i.e. don’t worry about articles such as The or A, etc.). As illustrated in the textbook, p. 666 (Don’t let this number concern you :) ), you will use the Collections sort.</p>\n</blockquote>\n\n<p>Sorry, the specification makes me <em>cry</em>.</p>\n\n<p>How does this make sense in any way? Imagine someone going to a library, with a wizards hat on and a big staff: »Sort you, I, as your master, command you!«.</p>\n\n<pre><code>public void sort() {\n Collections.sort(allBook);\n}\n</code></pre>\n\n<p>Of course, the implementation is <em>according to the specification</em> correct.\nBut that doesn't make really sense. I would prefer two alternatives:</p>\n\n<ul>\n<li><p>If it is crucial, that your library is sorted in some way, you could choose to <em>always</em> have a <em>sorted collection</em> of books</p></li>\n<li><p>otherwise, I would <em>generate</em> a sorted List <em>on the fly</em>\nThe implementation depends on the <em>usage</em>.</p></li>\n</ul>\n\n<p>And what is <em>that</em>?</p>\n\n<pre><code>public String toString() {\n return Library.this.toString();\n}\n</code></pre>\n\n<p>The specification was for once <em>clear</em> at this point:</p>\n\n<blockquote>\n <p>returns a properly formatted String representation of all the books in the library (Title followed by authors).</p>\n</blockquote>\n\n<pre><code>public String toString() {\n StringBuilder sb=new StringBuilder();\n for(Book b:books) sb.append(b.toString());\n return sb.toString();\n}\n</code></pre>\n\n<p>That should do the trick.</p>\n\n<p>Let's talk about <code>Book</code>:</p>\n\n<pre><code>public Book(String title, ArrayList<String> authors) {\n if (title == null && authors == null) {\n throw new IllegalArgumentException(\"Can't be null\");\n }\n if (title.isEmpty() && authors.isEmpty()) {\n throw new IllegalArgumentException(\"Can't be empty\");\n }\n bookTitle = title;\n bookAuthor = authors;\n}\n</code></pre>\n\n<p>The same as above: Don't throw exceptions in a constructor!\n<strong>Additionally</strong>: If you do not allow <em>blank</em> books, why check for blank books in the <code>Library</code>? Are you afraid of <em>malicious subclasses</em> of books, which allow blank books?</p>\n\n<pre><code>public int compareTo(Book other) {\n return bookTitle.compareTo(other.bookTitle);\n}\n</code></pre>\n\n<p>Why only compare the title? There are at least two books called<a href=\"http://www.amazon.co.uk/s/ref=nb_sb_noss_2/280-4444867-5052023?url=search-alias%3Dstripbooks&field-keywords=french%20kitchen&sprefix=french%20kit%2Cstripbooks\" rel=\"nofollow\">French Kitchen</a>, but they are not the same, since the authors differ.</p>\n\n<pre><code>public ArrayList<String> getAuthors() {\n return bookAuthor;\n}\n</code></pre>\n\n<p>This is <em>naughty</em> and could bite you:</p>\n\n<pre><code>public static void main(String[] args) {\n ArrayList<String> authors=new ArrayList<>();\n authors.add(\"1\");\n authors.add(\"2\");\n authors.add(\"3\");\n authors.add(\"4\");\n Book b=new Book(\"test\", authors);\n ArrayList<String> list1=b.getAuthors();\n list1.add(\"5\");\n ArrayList<String> list2=b.getAuthors();\n for(String s:list2){\n System.out.println(s);\n }\n}\n</code></pre>\n\n<p>You are <strong>leaking</strong> the <em>reference</em> of your <em>internal</em> authors.</p>\n\n<pre><code>public List<String> getAuthors() {\n List<String> result=new ArrayList<>();\n for(String a:bookAuthor) result.add(a);\n return result;\n}\n</code></pre>\n\n<p>This is what you want.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-05-14T07:20:32.683",
"Id": "90713",
"ParentId": "33148",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T01:45:31.167",
"Id": "33148",
"Score": "5",
"Tags": [
"java",
"array",
"homework"
],
"Title": "Book program with arrayList"
}
|
33148
|
<p>I've written a method in c# that allows me to do create a dictionary from a passed in object and N lambda expressions that reference that objects properties and methods. It's working the way I want it and seems to perform well, but I'm looking for criticism and seeking to improve the code.</p>
<p>Here's an example usage:</p>
<pre><code>class Person
{
public string Name { get; set; }
public int Age { get; set; }
public Dictionary<string, object> MakeDictionary()
{
return DictionaryThing.Data(this, x => x.Name, x => x.Age);
/* example return dictionary:
Name: "Ronnie"
Age: 29
*/
}
}
</code></pre>
<p>And here's the code for DictionaryThing:</p>
<pre><code>static class DictionaryThing
{
static ConcurrentDictionary<string, Delegate> expCache = new ConcurrentDictionary<string, Delegate>();
public static Dictionary<string, object> Data<T>(T obj, params Expression<Func<T, dynamic>>[] expressions)
{
var dict = new Dictionary<string, object>();
foreach (var exp in expressions)
{
string name = null;
var body = exp.Body;
var unaryExp = body as UnaryExpression;
if (unaryExp != null)
body = unaryExp.Operand;
var memberExp = body as MemberExpression;
if (memberExp != null)
name = memberExp.Member.Name;
var methodCallExp = body as MethodCallExpression;
if (methodCallExp != null)
name = methodCallExp.Method.Name;
if (name == null)
throw new InvalidExpressionException(
string.Format("The expression '{0}' is invalid. You must supply an expression that references a property or a function of the type '{1}'.",
exp.Body, typeof(T)));
var key = typeof(T).FullName + "." + name;
var func = (Func<T, dynamic>)expCache.GetOrAdd(key, k => ((LambdaExpression)exp).Compile());
dict[name] = func(obj);
}
return dict;
}
}
</code></pre>
<p>My concerns are:</p>
<ul>
<li>Is there a better way to work with the expressions that are passed in. </li>
<li>Can the expressions parameter be better constrained by a more appropriate type?</li>
<li>Is there a better way to derive the cache key?</li>
</ul>
|
[] |
[
{
"body": "<p>Ronnie,</p>\n<p>You have a good starting point for the problem you are trying to solve.</p>\n<p>To answer your concerns:</p>\n<ol>\n<li><p>Is there a better way to work with the expressions that are passed in.</p>\n<p>I think what you have done is fine. You are using Expression to let user specify methods/properties in type safe way. The only thing I would change is to use <code>Expression<Func<T, object>>[]</code> instead of <code>Expression<Func<T, dynamic>>[]</code> as dynamic will invoke the compiler at run time.</p>\n</li>\n<li><p>Can the expressions parameter be better constrained by a more appropriate type?</p>\n<p>I don't think you can specify additional constraints at compile time but you can definitely add code to validate the expression at runtime.</p>\n</li>\n<li><p>Is there a better way to derive the cache key?</p>\n<p>I think your cache key is fine. If you want to be more conservative, you can include Type.AssemblyQualifiedName. I would worry about it only if I was releasing to general public and not if I am using this class as part of a team.</p>\n</li>\n</ol>\n<p>With that said, here's the full re-factored code along with my notes. I hope it helps.</p>\n<pre><code>void Main()\n{\n var ronnie = new Person();\n ronnie.Name = "Ronnie";\n ronnie.Address = "Greensboro, NC";\n \n var dictionary = ObjectToDictionaryConverter.GetDictionary(ronnie, x => x.Name, x => x.Address);\n \n // In following example, we are trying to pass in an expression which is not valid for our object.\n // Running this code will throw an appropriate exception like\n // Expression value(UserQuery+<>c__DisplayClass0).anotherDictionary.Keys is invalid. \n // Expression Property/Member Type System.Collections.Generic.Dictionary`2[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089],[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]\n //, expecting Type: UserQuery+Person\n \n //var anotherDictionary = new Dictionary<string, string>();\n //var dictionary = ObjectToDictionaryConverter.GetDictionary(ronnie, x => anotherDictionary.Keys); \n\n //I don't think you can enforce this constraint at compile time (I am not sure about it, I would love to be proved wrong.)\n \n Console.WriteLine(dictionary["Name"]); //Prints Ronnie\n Console.WriteLine(dictionary["Address"]); //Prints Greensboro, NC\n \n}\n\npublic class Person\n{\n public string Name { get; set; }\n \n public string Address { get; set; }\n}\n\n// Why would you name a class like 'DictionaryThing'? It doesn't explain anything about what the class does. \n// Let's give it a more descriptive 'ObjectToDictionaryConverter' name. You may prefer some other name but \n// make sure that you put same thought in to naming your class as the code which goes inside the class.\n\n// Next, the original code was doing two things\n// 1. Inspecting the expression to derive a key\n// 2. Create the dictionary from the input object (while also catching the expression details)\n\n// Following SRP, let's separate it out in two classes so that each class is responsible for doing one thing.\n// This also means that you can use the Expression inspection code somewhere else if you choose to.\npublic static class ObjectToDictionaryConverter \n{\n //Always spell out the variable name in its full. (expCache -> expressionCache)\n static ConcurrentDictionary<string, Delegate> expressionCache = new ConcurrentDictionary<string, Delegate>();\n\n public static Dictionary<string, object> GetDictionary<T>(T obj, params Expression<Func<T, object>>[] expressions)\n {\n //Always validate your arguments. \n if(ReferenceEquals(obj, null))\n throw new ArgumentNullException("obj");\n \n if(expressions.Length == 0)\n throw new ArgumentException("You must specify at least one expression.");\n \n foreach (var expression in expressions)\n {\n if(expression == null)\n throw new ArgumentException("You can not specify NULL expression.");\n }\n \n var result = new Dictionary<string, object>();\n \n foreach (var expression in expressions)\n {\n //The purpose of ExpressionDetail is to inspect our expression \n var expressionDetail = ExpressionDetail.Create(expression);\n\n //A lambda expression can be a valid expression referring to a property or function.\n //But for our need, we will need to compile this expression to a delegate and run on object of Type T, let's make\n //sure that expression refers to the correct type.\n \n //IMPORTANT: We should not put this check in ExpressionDetail class. It is not\n //the responsibility of ExpressionDetail to enforce this type constraint. \n //This type constraint is only needed for ObjectToDictionaryConverter class. \n if(expressionDetail.DeclaringType != typeof(T))\n throw new InvalidExpressionException("Expression " + expression.Body + " is invalid. Expression Property/Member Type " + expressionDetail.DeclaringType.FullName + ", expecting Type: " + typeof(T).FullName); \n \n //expressionDetail has properties like 'Name', 'FullName', 'Delegate' \n var func = (Func<T, object>) expressionCache.GetOrAdd(expressionDetail.FullName, expressionDetail.Delegate); \n \n result[expressionDetail.Name] = func(obj);\n }\n\n return result;\n }\n}\n\npublic class ExpressionDetail\n{\n private ExpressionDetail()\n {\n \n }\n \n public MemberInfo MemberInfo { get; private set; }\n \n public LambdaExpression Expression { get; private set; }\n \n //By figuring out MemberInfo from the Expression, \n //we can now have all these read-only properties to get expression detail.\n public string Name { get { return MemberInfo.Name; } }\n \n public Type DeclaringType { get { return MemberInfo.DeclaringType; } }\n \n public string FullName { get { return DeclaringType.FullName + "." + Name; } }\n \n //Depending on performance requirement, you may want to use Lazy<T> to calculate this value\n //only once. \n public Delegate Delegate { get { return Expression.Compile(); } }\n\n //We are expecting a lambda expression which should either point to a method or a property access.\n //To get body, we have to handle the case of expression being UnaryExpression\n //To learn more: http://stackoverflow.com/questions/3567857/why-are-some-object-properties-unaryexpression-and-others-memberexpression\n private static Expression GetBody(LambdaExpression expression)\n {\n //We don't validate arguments here only because it's a private method.\n \n var unaryExpression = expression.Body as UnaryExpression;\n return unaryExpression != null ? unaryExpression.Operand : expression.Body;\n }\n \n //In your original method, you returned the name.\n //However, it could be even more useful to get the MemberInfo and store it.\n //Now we will have access to Name as well as the Type in which the property/method is declared.\n\n // There are lots of edge cases here. \n // Refer to: http://stackoverflow.com/questions/671968/retrieving-property-name-from-lambda-expression and update this method to handle the edge cases that you care about.\n private static MemberInfo GetMemberInfo(Expression expression)\n {\n //We don't validate arguments here only because it's a private method.\n \n var memberExpression = expression as MemberExpression;\n \n if(memberExpression != null)\n return memberExpression.Member;\n \n var methodCallExpression = expression as MethodCallExpression;\n \n if(methodCallExpression != null)\n return methodCallExpression.Method;\n \n return null;\n }\n \n public static ExpressionDetail Create(LambdaExpression expression)\n {\n if(expression == null)\n throw new ArgumentNullException("expression");\n \n var body = GetBody(expression);\n \n var memberInfo = GetMemberInfo(body);\n \n if (memberInfo == null)\n throw new InvalidExpressionException(\n string.Format("The expression '{0}' is invalid. You must supply an expression that references a property or a function.",\n expression.Body));\n \n return new ExpressionDetail { MemberInfo = memberInfo, Expression = expression};\n }\n\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T16:30:11.840",
"Id": "53161",
"Score": "0",
"body": "Even `AssemblyQualifiedName` is not 100 % safe. You can create two distinct dynamic assemblies with the same name. (But this will be even rarer than `FullName` collision and I agree with you that that one should be already pretty rare, especially if you control the code that uses this method.)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T17:07:00.517",
"Id": "53163",
"Score": "0",
"body": "@svick Agreed. It looks like you are a regular here, any comments on my code? Any other improvement ideas?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T17:16:53.870",
"Id": "53165",
"Score": "0",
"body": "Your code seems reasonable to me. One note: it's annoying when I have to scroll horizontally, especially when reading comments. (This wouldn't be a problem for your code normally, but it is when you post it to SE, which shows code in a narrow window.)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T16:11:52.237",
"Id": "33184",
"ParentId": "33152",
"Score": "5"
}
},
{
"body": "<ol>\n<li><p>I think <code>DictionaryThing</code> is a really bad name for a class, you should think about a better name. And <code>Data()</code> is not a great name either. <code>DictionaryThing.Data</code> doesn't really tell you what it does.</p></li>\n<li><p>I don't see any reason to use <code>dynamic</code> in your code. Using <code>object</code> instead would work just as well and it would be less confusing, because writing <code>dynamic</code> implies that you're actually doing something dynamically.</p></li>\n<li><p>You could create a separate cache for each <code>T</code>. With that, you wouldn't need to compute key from the type name and you also wouldn't need the cast.</p>\n\n<p>To do this, you could create a nested static generic type, that would hold the cache. Something like:</p>\n\n<pre><code>static class DictionaryThing \n{\n private static CacheHolder<T>\n {\n public static ConcurrentDictionary<string, Func<T, object>> expressionCache = …;\n }\n\n …\n}\n</code></pre></li>\n<li><p>You don't check that the <code>UnaryException</code> is actually <code>Convert</code>. I can't think of a sensible situation where it would be anything else, but I would check it anyway, just to be on the safe side.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T16:19:48.820",
"Id": "53159",
"Score": "0",
"body": "+1 Great idea of using separate Cache for each T. It avoids possible collision."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T16:13:14.630",
"Id": "33185",
"ParentId": "33152",
"Score": "3"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T03:30:06.517",
"Id": "33152",
"Score": "7",
"Tags": [
"c#",
"functional-programming",
"reflection"
],
"Title": "Function that builds dictionary based on lambda params"
}
|
33152
|
<blockquote>
<p><strong>Maze puzzle</strong></p>
<p>A 1 in input matrix means "allowed"; 0 means "blocked". Given such a matrix, find the route from the 1st quadrant to the last (n-1, n-1).</p>
</blockquote>
<p>I would like to get some feedback to optimize and make this code cleaner. Also let me know if O(n!) is the complexity, where n is the dimension of the maze.</p>
<pre><code>final class Coordinate {
private final int x;
private final int y;
public Coordinate(int x, int y) {
this.x = x;
this.y = y;
}
public int getX() {
return x;
}
public int getY() {
return y;
}
}
public class Maze {
private final int[][] maze;
public Maze(int[][] maze) {
if (maze == null) {
throw new NullPointerException("The input maze cannot be null");
}
if (maze.length == 0) {
throw new IllegalArgumentException("The size of maze should be greater than 0");
}
this.maze = maze;
}
public List<Coordinate> solve() {
return getMazePath(0, 0, new Stack<Coordinate>());
}
private List<Coordinate> getMazePath(int row, int col, Stack<Coordinate> stack) {
assert stack != null;
stack.add(new Coordinate(row, col));
if ((row == maze.length - 1) && (col == maze[0].length - 1)) {
Coordinate[] coordinateArray = stack.toArray(new Coordinate[stack.size()]);
return Arrays.asList(coordinateArray);
}
for (int j = col; j < maze[row].length; j++) {
if ((j + 1) < maze[row].length && maze[row][j + 1] == 1) {
return getMazePath(row, j + 1, stack);
}
if ((row + 1) < maze.length && maze[row + 1][col] == 1) {
return getMazePath(row + 1, col, stack);
}
}
return Collections.emptyList();
}
public static void main(String[] args) {
int[][] m = { {1, 0, 0},
{1, 1, 0},
{0, 1, 1} };
Maze maze = new Maze(m);
for (Coordinate coord : maze.solve()) {
System.out.println(coord.getX() + " : " + coord.getY());
}
}
}
</code></pre>
|
[] |
[
{
"body": "<p>First of all I don't think the time complexity is <code>O(n!)</code>. You are doing DFS(unknowingly). So the time complexity would be <a href=\"https://stackoverflow.com/questions/10118580/time-complexity\">O(n + m)</a> and AFAIK you can't solve maze problem less than that unless you are using BFS. But nevertheless it will not make any difference.</p>\n\n<p>Now your code has some bug, I think you didn't consider that way and it's ok if you are a beginner like me. Try to change the maze matrix to </p>\n\n<pre><code>int[][] m = {{1, 1, 1},\n {1, 0, 1},\n {1, 1, 0}, \n {0, 1, 1}};\n</code></pre>\n\n<p>and you will get the <a href=\"http://ideone.com/cwlZI6\" rel=\"nofollow noreferrer\">picture</a>. Maze can be solved but still it's not printing anything.\nSo what is the solution? <strong>BACK-TRACK</strong>.</p>\n\n<p>Moreover you are only taking account of possibilities of going <em>right</em> and <em>down</em>, why not <em>up</em> and <em>left</em>?</p>\n\n<p>You have hard-coded that the start point will be always (0,0) and end point will be (N-1, N-1)... yeah your puzzle says that but this will not be same for every puzzle right? So think of a general solving technique...</p>\n\n<p><strong>SPOILER ALERT</strong></p>\n\n<blockquote class=\"spoiler\">\n <p> <a href=\"http://www.cs.bu.edu/teaching/alg/maze/\" rel=\"nofollow noreferrer\">Web resource</a><br>\n<br>\n <a href=\"http://pastebin.com/SNeQB8JN\" rel=\"nofollow noreferrer\">My solution</a></p>\n</blockquote>\n\n<h2>Code Cleaning Tips</h2>\n\n<ol>\n<li><code>getMazePath</code> method can be cleaned. In 1st <code>if</code> you are checking if you have reached the goal or not. Now move the checking condition to another method and return <code>true</code> if you have reached the goal.</li>\n<li>In for loop(no need of this if you are using recursion) you are checking if <em>you are in the maze</em> and <em>path exists or not</em>... see how you are repeating yourself for every condition... think of a general solution.</li>\n<li>No need for maintaining a <code>Stack</code>, since you are not using any of Stack's method but only <code>add</code>, which you can also use with a <code>List</code>.</li>\n<li>Override <code>toString</code> method in <code>Coordinate</code> class. And get rid of long <code>S.o.p</code> s.</li>\n</ol>\n\n<p>Good Luck!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T09:46:36.880",
"Id": "33164",
"ParentId": "33155",
"Score": "1"
}
},
{
"body": "<p>Your logic is just not correct, with the for-loop. Consider the following maze:</p>\n\n<pre><code>1000001\n0000001\n0000001\n0000001\n</code></pre>\n\n<p>Your code will find a \"solution\" by jumping to the upper-right, then taking a path down to the finish.</p>\n\n<p>Fix that, and the issues raised by @tintinmj, and then we might be able to analyze the complexity. Until then, it would be a meaningless discussion.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T10:14:25.707",
"Id": "33165",
"ParentId": "33155",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "33164",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T05:43:11.980",
"Id": "33155",
"Score": "2",
"Tags": [
"java",
"algorithm",
"recursion",
"matrix",
"pathfinding"
],
"Title": "Finding a route in maze matrix"
}
|
33155
|
<pre><code>try {
var isSupported = !! new Blob();
} catch (e) {
document.body.innerHTML = "<h1>Sorry your browser isn\'t supported :(</h1>";
}
var textarea = document.getElementById("textarea"),
inputFile = document.getElementById("input-file"),
appname = "notepad",
untitled = "untitled.txt",
isModified = false,
filename;
window.onload = function() {
if (localStorage.getItem("txt")) { // Load localStorage
newNote(localStorage.getItem("txt"), localStorage.getItem("name"));
} else {
newNote();
}
};
window.onunload = function() {
if (isModified) { // Save localStorage
localStorage.setItem("txt", textarea.value);
localStorage.setItem("name", filename);
} else {
localStorage.clear();
}
};
textarea.addEventListener("input", function() {
isModified = true;
});
function changeDocTitle(newFilename) { // Change doc title
filename = newFilename;
document.title = filename + " - " + appname;
}
function dontSave() { // Confirm dont save
if (confirm("You have unsaved changes that will be lost.")) {
isModified = false;
return true;
}
}
function newNote(txt, name) { // New
if (!isModified || dontSave()) {
textarea.value = txt || "";
changeDocTitle(name || untitled);
if (textarea.value) {
isModified = true;
}
}
textarea.focus();
}
function openNote() { // Open
if (!isModified || dontSave()) {
inputFile.click();
}
textarea.focus();
}
inputFile.addEventListener("change", function() { // Load file
var file = inputFile.files[0],
reader = new FileReader();
reader.onload = function() {
newNote(reader.result, file.name);
};
reader.readAsText(file);
});
function rename() { // Rename
var newFilename = prompt("Name this note:", filename);
if (newFilename !== null) {
if (newFilename === "") {
changeDocTitle(untitled);
} else {
changeDocTitle(newFilename.lastIndexOf(".txt") == -1 ? newFilename + ".txt" : newFilename);
}
return true;
}
}
function saveNote() { // Save
if (rename()) {
var blob = new Blob([textarea.value.replace(/\n/g, "\r\n")], {
type: "text/plain;charset=utf-8"
});
saveAs(blob, filename);
isModified = false;
}
textarea.focus();
}
function getStats() { // Stats
var txt = textarea.value,
txtStats = {};
txtStats.chars = txt.length;
txtStats.words = txt.split(/\S+/g).length - 1;
txtStats.lines = txt.replace(/[^\n]/g, "").length + 1;
return txtStats.lines + " lines, " + txtStats.words + " words, " + txtStats.chars + " chars";
}
document.addEventListener("keydown", function(e) { // Shortcuts
var key = e.keyCode || e.which;
if (e.altKey && e.shiftKey && key == 78) { // Alt+Shift+N
e.preventDefault();
newNote();
}
if (e.ctrlKey) { // Ctrl+
switch (key) {
case 79: // O
e.preventDefault();
openNote();
break;
case 83: // S
e.preventDefault();
saveNote();
break;
case 75: // K
e.preventDefault();
alert(getStats());
break;
case 191: // /
e.preventDefault();
alert("Help note for " + appname + " will be added soon!");
break;
}
}
if (key == 9) { // Tab
e.preventDefault();
var sStart = textarea.selectionStart,
txt = textarea.value;
textarea.value = txt.substring(0, sStart) + "\t" + txt.substring(textarea.selectionEnd);
textarea.selectionEnd = sStart + 1;
}
});
</code></pre>
|
[] |
[
{
"body": "<p>From a once over:</p>\n\n<ul>\n<li>You do not need the <code>\\</code> in <code>\"<h1>Sorry your browser isn\\'t supported :(</h1>\"</code> because your string is surrounded with double quotes</li>\n<li>I would check immediately whether <code>textarea</code> and <code>inputFile</code> found something and give a proper error message when those elements are missing in the HTML</li>\n<li>You are doing both proper event handling with <code>textarea.addEventListener</code> and old skool event handling with <code>window.onload</code>, stick to proper event handling</li>\n<li><code>\"txt\"</code> and <code>\"name\"</code> are the keys to interact with localStorage, these should be named constants</li>\n<li>Personally, I would try also to store the cursor position when storing the text in localStorage, this would look nice</li>\n<li><code>dontSave() { // Confirm dont save</code> -> perhaps the function should be named differently ;)</li>\n<li><code>saveAs</code> is missing ?</li>\n</ul>\n\n<p>All in all a promising start for a cool editor. It helped me to build a jsbin for this : <a href=\"http://jsbin.com/jetuh/1/edit\" rel=\"nofollow\">http://jsbin.com/jetuh/1/edit</a></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2014-04-15T19:36:52.890",
"Id": "47281",
"ParentId": "33157",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T06:50:51.910",
"Id": "33157",
"Score": "-1",
"Tags": [
"javascript",
"html5"
],
"Title": "Text editing web app"
}
|
33157
|
<p>I have created a program that allows the user to view/add/delete employees and also view employee payslip, either weekly employee or monthly employee, which is all done in the console.</p>
<p>My programme runs fine and does as asked, but I feel it is not OOP. Can anyone suggest any changes to make it more OO?</p>
<p>Please see the 5 classes below that I use.</p>
<pre><code>package payslips;
import java.util.*;
import payslips.Employee;
import payslips.Payslip;
public class MainProgramme
{
public static String name;
public static String street;
public static String town;
public static String postcode;
public static int payrollNo;
public static char taxcode;
public static String type;
static Scanner sc = new Scanner(System.in);
static Scanner sd = new Scanner(System.in);
static int tempvar;
static int temppayrollNo;
static ArrayList<Employee> list = new ArrayList<Employee>();
static String names[] = { "John Hepburn", "David Jones", "Louise White",
"Harry Martin", "Christine Robertson" };
static String streets[] = { "50 Granton Road", "121 Lochend Park",
"100 Govan Avenue", "51 Gorgie Road", "1 Leith Street" };
static String towns[] = { "Edinburgh", "Edinburgh", "Glasgow", "Edinburgh",
"Edinburgh" };
static String postcodes[] = { "EH6 7UT", "EH1 1BA", "G15 5GG", "EH5 2PR",
"EH4 4ST" };
static int payrollNos[] = { 10001, 10002, 10003, 10004, 10005 };
static char taxcodes[] = { 'C', 'B', 'C', 'C', 'B' };
static String types[] = { "Monthly", "Weekly", "Monthly", "Monthly","Weekly" };
public static void main(String[] args)
{
for (int i = 0; i < 5; i++) {
name = names[i];
street = streets[i];
town = towns[i];
postcode = postcodes[i];
payrollNo = payrollNos[i];
taxcode = taxcodes[i];
type = types[i];
Employee e = new Employee(name, street, town, postcode, payrollNo,taxcode, type);
list.add(e);
}
// statements and prompts within the console for the user to follow
System.out.println("Welcome to your Payroll System");
System.out.println();
System.out.println("Please enter your choice below from the following options");
System.out.println();
System.out.println("View all current weekly employees = 1 ");
System.out.println("View all current monthly employees = 2 ");
System.out.println("Delete an employee = 3 ");
System.out.println("Add an employee = 4 ");
System.out.println("Print an employee payslip = 5");
System.out.println("To exit the system = 0 ");
// allows user to enter number of choice and this reflects which statement is ran in userChoice method
tempvar = sc.nextInt();
// runs the userChoice method
userChoice();
}
// method to determine what statement runs according to which choice user makes
public static void userChoice()
{
Employee tempEmployee = new Employee();
boolean foundEmployee = false;
// if user enters 1 it prints out the employee list.
if (tempvar == 1)
{
Weekly.printWeekly();
}
else if (tempvar == 2)
{
Monthly.printMonthly();
}
else if (tempvar == 3)
{
printEmployeelist();
System.out.println("");
System.out.println("Above are a list of all employees.");
System.out.println("Please enter the payroll number of the employee you wish to delete from the system");
temppayrollNo = sc.nextInt();
// while loop to search on payroll number, deletes the employee if correct, error message if not
if (list.isEmpty() == false)
{
int a = 0;
while (a < list.size())
{
tempEmployee = list.get(a);
if (tempEmployee.payrollNo == temppayrollNo)
{
foundEmployee = true;
break;
}
a++;
}
if (foundEmployee == true)
{
System.out.println("You have deleted : "+ tempEmployee.getName());
System.out.println();
list.remove(tempEmployee);
printEmployeelist();
}
else
{
System.out.println("The payroll number you have entered is incorrect");
}
}
}
else if (tempvar == 4) // allows the user to add an employee to the employee list, entering details using scanner
{
// initialises variables for entering title
String tempstring1;
int stringlength;
int whitespace;
String tempstring2;
String tempstring3;
// initialises variables for entering title
String tempstring4;
int stringlength2;
int whitespace2;
String tempstring5;
String tempstring6;
String tempstring7;
System.out.println("You have chosen to add an employee to the system");
System.out.println();
// block of code that builds string together to get employee name
System.out.println("Please enter the name of the new employee: ");
tempstring1 = sd.nextLine(); // takes in string using scanner
stringlength = tempstring1.length(); // saves length of string
if (tempstring1.contains(" ")) // if statement to see if the string contains a space
{
whitespace = tempstring1.indexOf(" "); // finds the whitespace
tempstring2 = tempstring1.substring((0), (whitespace));// creates string from start of input to whitespace
tempstring3 = tempstring1.substring((whitespace) + 1,(stringlength));// creates string from whitespace plus one and adds on rest of the string
tempEmployee.setName(tempstring2 + " " + tempstring3); // combines tempstring1 and tempstring2 together to complete full string
}
else // else statement that just enters the string if it is just one word
{
tempEmployee.setName(tempstring1);
}
// block of code that repeats same process as above to get street name
System.out.println("Please enter the address of the employee: ");
tempstring4 = sd.nextLine();
stringlength2 = tempstring4.length();
if (tempstring4.contains(" ")) {
whitespace2 = tempstring4.indexOf(" ");
tempstring5 = tempstring4.substring((0), (whitespace2));
tempstring6 = tempstring4.substring((whitespace2) + 1,(stringlength2));
tempEmployee.setStreet(tempstring5 + " " + tempstring6);
}
else
{
tempEmployee.setStreet(tempstring4);
}
System.out.println("Please enter the town: ");
tempEmployee.setTown(sd.nextLine());// takes in town using scanner
System.out.println("Please enter the postcode: ");
tempstring7 = sd.nextLine(); //post code using scanner
if (tempstring7.length() > 5 && tempstring7.length() < 9) // sets the length of string
{
tempEmployee.setPostcode(tempstring7);
}
else
{
tempEmployee.setPostcode("You have not entered a valid UK postcode");
}
tempEmployee.setPayrollNo(payrollNo + 1); // sets payroll number to next in sequence
System.out.println("Please enter your Tax code (A, B or C): ");
tempEmployee.setTaxcode(sd.next().charAt(0));// takes in tax code using scanner
System.out.println("Please enter Employee Type (Weekly or Monthly): ");
tempEmployee.setType(sd.next()); //takes in type of employee
list.add(tempEmployee);// creates temp employee and adds to list
printEmployeelist();// prints employee list to view
}
else if (tempvar == 5)
{
Payslip.Payslips(); //runs payslip method from payslip class
}
else if (tempvar == 0) // if user hits 0 it allows them to exit the programme
{
System.out.println("You have exited the system");
System.exit(0);
}
else // if any other choice entered they will be met with this message
{
System.out.println("You have entered the wrong choice");
}
}
// method to create the book list using a for loop
public static void printEmployeelist() {
for (int i = 0; i < list.size(); i++)
System.out.println(list.get(i));
}
}
</code></pre>
<hr>
<pre><code>package payslips;
import java.util.Scanner;
public class Payslip extends MainProgramme
{
static int tempSalary;
static double tempHours;
static Scanner ss = new Scanner(System.in);
public static void Payslips()
{
{
Employee tempEmployee = new Employee();
boolean foundEmployee = false;
{
System.out.println("Please enter the employee payroll number to view payslip");
temppayrollNo = sc.nextInt();
if (list.isEmpty() == false)
{
int a = 0;
while (a < list.size())
{
tempEmployee = list.get(a);
if (tempEmployee.payrollNo == temppayrollNo)
{
foundEmployee = true;
break;
}
a++;
}
if (foundEmployee == true)
{
tempEmployee.getType();
if (tempEmployee.type == "Weekly")
{
System.out.println("Please enter hours worked this week: ");
tempHours = ss.nextDouble();
System.out.println();
System.out.println("PAYSLIP");
System.out.println("Week No:"+ (int) (Math.random() * 52));
System.out.println("Name: "+ tempEmployee.getName());
System.out.println("Payroll No: "+ tempEmployee.getPayrollNo());
System.out.println("Address: "+ tempEmployee.getStreet() + ", "+ tempEmployee.getTown() + ", "+ tempEmployee.getPostcode());
System.out.println("Tax Code: "+ tempEmployee.getTaxcode());
System.out.println("Weekly Pay: £"+ (tempHours * 8.50));
}
else
{
System.out.println("Please Enter Salary (£): ");
tempSalary = ss.nextInt();
System.out.println();
System.out.println("PAYSLIP");
System.out.println("Month No:"+ (int) (Math.random() * 12));
System.out.println("Name: "+ tempEmployee.getName());
System.out.println("Payroll No: "+ tempEmployee.getPayrollNo());
System.out.println("Address: "+ tempEmployee.getStreet() + ", "+ tempEmployee.getTown() + ", "+ tempEmployee.getPostcode());
System.out.println("Tax Code: "+ tempEmployee.getTaxcode());
System.out.println("Salary : £" + tempSalary + " Monthly Pay: £"+ (tempSalary / 12));
}
}
else
{
System.out.println("The payroll number you have entered is incorrect");
}
}
}
}
}
}
</code></pre>
<hr>
<pre><code>package payslips;
import payslips.MainProgramme;
public class Employee extends MainProgramme
{
public Employee()
{
}
//initialises variables
public String name;
public String street;
public String town;
public String postcode;
public int payrollNo;
public char taxcode;
public String type;
public Employee(String name, String street, String town, String postcode, int payrollNo, char taxcode, String type)
{
//sets constructors
this.name = name;
this.street = street;
this.town = town;
this.postcode = postcode;
this.payrollNo = payrollNo;
this.taxcode = taxcode;
this.type = type;
}
//sets the getters and setters
public String getName()
{
return name;
}
public void setName(String name)
{
this.name = name;
}
public String getStreet()
{
return street;
}
public void setStreet(String street)
{
this.street = street;
}
public String getTown()
{
return town;
}
public void setTown(String town)
{
this.town = town;
}
public String getPostcode()
{
return postcode;
}
public void setPostcode(String postcode)
{
this.postcode = postcode;
}
public int getPayrollNo()
{
return payrollNo;
}
public void setPayrollNo(int payrollNo)
{
this.payrollNo = payrollNo;
}
public char getTaxcode()
{
return taxcode;
}
public void setTaxcode(char taxcode)
{
this.taxcode = taxcode;
}
public String getType()
{
return type;
}
public void setType(String type)
{
this.type = type;
}
//when printing employee list method it sets the input to display as below
public String toString()
{
return "Name: " + this.name + " / " + "Street: " + this.street + " / "
+ "Town: " + this.town + " / " + "Postcode: " + this.postcode + " / " + "Payroll Number: " + this.payrollNo
+ " / " + "Tax Code: " + this.taxcode + " / " + "Type: " + this.type;
}
}
</code></pre>
<hr>
<pre><code>package payslips;
public class Monthly extends MainProgramme
{
public static void printMonthly()
{
for (int i = 0; i < list.size(); i++)
if (types[i] == "Monthly")
{
System.out.println(list.get(i));
}
}
}
</code></pre>
<hr>
<pre><code>package payslips;
public class Weekly extends MainProgramme
{
public static void printWeekly()
{
for (int i = 0; i < list.size(); i++)
if (types[i] == "Weekly")
{
System.out.println(list.get(i));
}
}
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T10:57:07.543",
"Id": "53136",
"Score": "2",
"body": "As a start: You have the hierarchy reversed. Normally the main application depends on the Objects...in your case the objects depend on the main application. Every Object *should* be able to stand on their own."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T11:31:55.600",
"Id": "53138",
"Score": "0",
"body": "@Bobby what is the best way to start going about changing this?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T12:41:31.320",
"Id": "53143",
"Score": "1",
"body": "Start by zero, maybe even with a diagram showing what you need and what not. Design the classes `Employee`/`Payslip` as completely independent, which only interact via functions with the outside world (no calling of System.out too!). Also another rule of thumb: If you need to suffix your variables with numbers because the name is duplicate, you're doing something wrong. Also sorry, but this would need a complete rewrite so I won't do a review here. Maybe you should buy yourself a good book like \"Effective Java\", that would clear a lot up and would explain you the basics better then I could."
}
] |
[
{
"body": "<p>Before we talk about making this program object-oriented, we have more basic issues to cover.</p>\n\n<h1>Basic (Java) Programming</h1>\n\n<h2>Scoping</h2>\n\n<p>Each variable has a <em>scope</em> where it is visible. In Java, variables have <em>block scope</em>, that is, their visibility begins with their declaration and ends with the closing brace <code>}</code> for the current block.</p>\n\n<pre><code>int x = 0; // declaration of \"x\"\nif (x < 4) { // we enter a block\n int y = 2; // declaration of \"y\"\n ...\n} // the scope of \"y\" ends here\n// x is still visible here\n</code></pre>\n\n<p>So when we need temp variables, we can declare them in the inner scope where they are needed. The fewer variables in an outer scope we have, the easier a program is to understand.</p>\n\n<p>You should avoid variables that are public, static, or in outer scopes, because these are in a sense <em>global</em> variables. There are often better ways to access your data, e.g. through variables in tight scope, or through getter methods.</p>\n\n<h2>Variable naming</h2>\n\n<p>A variable name should make it obvious what this variable does. For example, you have two variables <code>sc</code> and <code>sd</code>. These are bot scanners around the <code>System.in</code> stream. You never explain what their difference is. Good variable names don't tell use <em>what</em> their content is (we can already see the type at the variable declaration), but rather what its <em>purpose</em> is. E.g. <code>input</code> might be better than <code>sc</code>. What is <code>list</code>? Yes, I can see that it's a <code>List</code>, thankyou very much. Oh, it's a collection of all employess? → <code>employees</code>.</p>\n\n<p>A few lines later, you have <code>tempstring1</code> through <code>tempstring7</code>. It is <em>impossible</em> to know from these names what they are supposed to do. It seems <code>tempstring1</code> should be <code>name</code> and <code>tempstring4</code> should be <code>address</code>, but it is difficult to understand the relevant code because it is obscured with these unintelligible variable names.</p>\n\n<p>Use better names! They cost you nothing, and make code much easier to read. And above all, avoid single-letter names.</p>\n\n<h2>No Magic Numbers, and Bad Assumptions</h2>\n\n<p>A magic number is a number that occurs in the source code without explanation why this specific number is needed here. Numbers like <code>0</code> or <code>1</code> are often obvious, but anything else should be explained.</p>\n\n<p>The problem is that these numbers often contain assumptions about your data that can be invalidated without you realizing it. When the data changes, and your program isn't updated accordingly, then you get bugs that are difficult to track down. For example, in your `main you have this loop:</p>\n\n<pre><code>for (int i = 0; i < 5; i++) ...\n</code></pre>\n\n<p>The number <code>5</code> is a magic number here. Where does it come from? Ah, of course it's from your arrays like <code>names</code>. Using <code>names.length</code> here would already be much better.</p>\n\n<p>If you make certain assumptions you can also test them for validity with <em>asserts</em>. An assert is an expression that expresses a state which you as a programmer know to be true, but you want to make sure. Here, an assertion that all of your input arrays have the same length seems like a good idea:</p>\n\n<pre><code>assert names.length == streets.length;\nassert names.length == ...;\n...\n</code></pre>\n\n<h2>Putting a Few Pieces Together</h2>\n\n<p>We can now <em>refactor</em> your loop there to use better variable scoping etc:</p>\n\n<pre><code>assert names.length == streets.length;\nassert names.length == ...;\n...\n\nfor (int i = 0; i < names.length; i++) {\n // declare these vars in this scope only – not needed on the outside\n String name = names[i];\n String street = streets[i];\n String town = towns[i];\n String postcode = postcodes[i];\n int payrollNo = payrollNos[i];\n char taxcode = taxcodes[i];\n String type = types[i];\n\n Employee employee = new Employee(name, street, town, postcode, payrollNo, taxcode, type);\n employees.add(employee);\n}\n</code></pre>\n\n<p>Wow, is that a lot code for so little. Instead of spreading your data of one employee across several arrays and then later building it, you might as well construct them directly:</p>\n\n<pre><code>static ArrayList<Employee> employees = new ArrayList<Employee>();\n\n// this is called a static initializer block\n// it runs before `main` is executed\nstatic {\n employees.add(new Employee(\"John Hepburn\", \"50 Granton Road\", \"Edinburgh\", \"EH6 7UT\", 10001, 'C', \"Monthly\"));\n employees.add(new Employee(\"David Jones\", \"121 Lochend Park\", \"Edinburgh\", \"EH1 1BA\", 10002, 'B', \"Weekly\"));\n ...\n}\n</code></pre>\n\n<p>Hey, that is not only shorter, this is easier to read as well</p>\n\n<h2>Foreach-loops</h2>\n\n<p>When iterating over each element of a Java collection, using <code>.get(...)</code> calls feels natural at first, but there is something better. Assume code like this:</p>\n\n<pre><code>int temppayrollNo = ...;\nboolean foundEmployee = false;\nint a = 0;\nwhile (a < list.size()) {\n tempEmployee = list.get(a);\n if (tempEmployee.payrollNo == temppayrollNo) {\n foundEmployee = true;\n break;\n }\n a++;\n}\n</code></pre>\n\n<p>First of all, this is a normal for-loop which you just expanded to the more low-level <code>while</code>. Below I also clear up variable names:</p>\n\n<pre><code>int wantedPayrollNo = ...;\nEmployee foundEmployee = null;\nfor (int i = 0; i < employees.size(); i++) {\n Employee employee = employees.get(a);\n if (employee.payrollNo == wantedPayrollNo) {\n foundEmployee = employee;\n break;\n }\n}\n\nif (foundEmployee != null) ...\n</code></pre>\n\n<p>We can use a for-each loop for any collection that implements the <code>Iterable</code> interface, which any <code>List</code> does. Therefore:</p>\n\n<pre><code>int wantedPayrollNo = ...;\nEmployee foundEmployee = null;\nfor (Employee employee : employees) {\n if (employee.payrollNo == wantedPayrollNo) {\n foundEmployee = employee;\n break;\n }\n}\n\n...\n</code></pre>\n\n<p>This abstracts over actually accessing each element, and is more general. Use modern Java features like this to make your code easier.</p>\n\n<h2>Choosing a good data structure</h2>\n\n<p>Above, we iterated through all <code>employees</code> and stopped when we found the correct one. For that, we were comparing a certain index (here: the payroll number) for equality. There are data structures that can do this much more efficiently. In Java, these implement the <code>Map</code> interface. To index the employees by their payroll number, we do something like:</p>\n\n<pre><code>// do this once, on startup\nMap<Integer, Employee> employeesByPayrollNo = new HashMap<Integer, Employee>();\nfor (Employee employee : employees) {\n employeesByPayrollNo.put(employee.payrollNo, employee);\n}\n</code></pre>\n\n<p>Then, we can just look up an entry like <code>Employee foundEmployee = employeesByPayrollNo.get(wantedPayrollNo)</code>.</p>\n\n<h2>Don't repeat yourself</h2>\n\n<p>Parts of your code have massive repetition, for example when print out an report about your employee. Many of the lines are independent from the payment frequency. You could also have written:</p>\n\n<pre><code>boolean isWeekly = tempEmployee.type == \"Weekly\";\ndouble pay = 0;\ndouble hourlyPay = 8.50;\n\nif (isWeekly) {\n System.out.println(\"Please enter hours worked this week: \");\n pay = hourlyPay * ss.nextDouble();\n}\nelse {\n System.out.println(\"Please Enter Salary (£): \");\n pay = ss.nextInt();\n}\n\nSystem.out.println();\nSystem.out.println(\"PAYSLIP\");\nif (isWeekly) System.out.println(\"Week No:\" + (int) (Math.random() * 52));\nelse System.out.println(\"Month No:\" + (int) (Math.random() * 12));\nSystem.out.println(\"Name: \"+ tempEmployee.getName());\nSystem.out.println(\"Payroll No: \"+ tempEmployee.getPayrollNo());\nSystem.out.println(\"Address: \"+ tempEmployee.getStreet() + \", \"+ tempEmployee.getTown() + \", \"+ tempEmployee.getPostcode());\nSystem.out.println(\"Tax Code: \"+ tempEmployee.getTaxcode());\nif (isWeekly) System.out.println(\"Weekly Pay: £\"+ pay);\nelse System.out.println(\"Salary : £\" + pay + \" Monthly Pay: £\" + (pay / 12));\n}\n</code></pre>\n\n<p>Of course, such functionality shouldn't be <em>hardcoded</em> into your program, but you should rather be using a templating system where you only do <code>template.render(isWeekly, pay)</code> or something.</p>\n\n<h1>Aspects not covered</h1>\n\n<ul>\n<li>Redundant code (all this substringing nonsense when parsing a name)</li>\n<li>Single-Responsibility principle (Address should be its own class)</li>\n<li>Enums instead of strings to ensure correctness at compile time (what happens if the type of an employee is <code>\"weekly\"</code> or <code>Wekly</code>? That shouldn't be possible)</li>\n<li>When (not) to use inheritance</li>\n<li>Early returns to avoid deeply nested <code>if</code>s</li>\n<li>Finding abstractions and refactoring into helper methods</li>\n<li>Abstracting away from text-based interfaces: <code>System.out.println(...)</code> should be a very rare occurrence.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T13:32:00.757",
"Id": "53145",
"Score": "0",
"body": "thank you for such a detailed response, a lot seems very very useful. Hopefully I can go away and use this. Really hoping I can get the OOP sorted as i seem to just run everything through the main rather than use my classes correctly, any wee tips on how to move my code into the right classes?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T13:46:45.740",
"Id": "53146",
"Score": "0",
"body": "@Kieran OOP is no end in itself. It is an useful abstraction mechanism, along with “procedural programming” (abstracting stuff into helper functions). Start with cleaning up your code, then read a respected Java book, which will teach you the basics of object orientation. While OOP is in no way complicated, you have more urgent things to learn before that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T13:10:31.023",
"Id": "33173",
"ParentId": "33167",
"Score": "12"
}
},
{
"body": "<p>There is much to be gained by refactoring this code into an object-oriented style. However, before we proceed, I would like to point out that it's not good procedural-style code to begin with.</p>\n\n<p>You've marked every class as <code>… extends MainProgramme</code>, which is nonsense. You wouldn't say that an employee <em>is</em> a main programme, so you shouldn't say that in your code either. Your employee code resides in the <code>payslips</code> package. Having <code>package payslips;</code> at the top of each file is all you need.</p>\n\n<p>In <code>MainProgramme</code>, you are using class variables in many places where a local variable should be used. Remember, using a class variable is just about as bad as a global variable (well, slightly better than a global in the sense that it is in a namespace). In fact, if you want good code, <strong>get rid of all <code>static</code> variables and functions</strong> in your code unless you know exactly what the justification is.</p>\n\n<hr>\n\n<p>Well, let's think about what kinds of objects there ought to be in this system. Obviously, there an <code>Employee</code> class. (Your existing <code>Employee</code> class is perfectly fine, except that its instance variables should all be <code>private</code>.) Employees belong on a payroll, so there should be a <code>Payroll</code> class. (You could also call it a <code>Company</code> instead.)</p>\n\n<pre><code>import java.util.*;\n\npublic class Payroll implements Iterable<Employee> {\n private List<Employee> employees;\n private int maxPayrollNo = Integer.MIN_VALUE;\n\n public Payroll(Employee[] employees) {\n // LinkedList supports .remove(), but ArrayList doesn't\n this.employees = new LinkedList<Employee>(Arrays.asList(employees));\n for (Employee e : employees) {\n if (e.getPayrollNo() > this.maxPayrollNo) {\n this.maxPayrollNo = e.getPayrollNo();\n }\n }\n }\n\n @Override\n public Iterator<Employee> iterator() {\n return this.employees.iterator();\n }\n\n public void add(Employee e) {\n this.employees.add(e);\n }\n\n public int nextPayrollNo() {\n return ++this.maxPayrollNo;\n }\n\n @Override\n public String toString() {\n StringBuilder s = new StringBuilder();\n for (Employee e : this) {\n s.append(e).append('\\n');\n }\n return s.toString();\n }\n}\n</code></pre>\n\n<p>Three things to note in the code above.</p>\n\n<ol>\n<li><p>This is the logical place to put the <code>.nextPayrollNo()</code> method, and it demonstrates that a bare <code>List</code> is insufficient to model the payroll. </p></li>\n<li><p>The way in which the collection of employees is stored is hidden from everything else. I've chosen to use a <code>LinkedList</code> now, but in the future it may change to a <code>HashSet</code> or something, and the interface could remain the same. You could also implement a <code>.findByPayrollNo(int)</code> and a <code>.remove(Employee)</code> method as well, but I've chosen not to bother.</p></li>\n<li><p>Your <code>MainProgramme.printEmployeeList()</code> was just a stray chunk of code without a home. I've moved it here, where it logically belongs, so you can call <code>payroll.toString()</code>.</p></li>\n</ol>\n\n<hr>\n\n<p>What may not be so obvious is that the main programme itself could benefit from object-oriented reorganization. Your <code>.userChoice()</code> function could be slightly better written as a giant <code>switch</code> block. A giant <code>switch</code> block, in turn, is an antipattern, or Bad Code Smell, in object-oriented programming, <a href=\"https://stackoverflow.com/a/126455/1157100\">the remedy for which is polymorphism</a>.</p>\n\n<p>What does that mean, in this example? Your <code>switch</code> decides which action to perform. Therefore, you want to define different kinds of \"Action\" objects. Specifically, what these actions all have in common is that they operate on a <code>Payroll</code>, so let's call these actions <code>PayrollAction</code>s.</p>\n\n<pre><code>public interface PayrollAction {\n /**\n * The name of the action.\n */\n String toString();\n\n /**\n * Code to perform the action.\n */\n void perform(Payroll p);\n}\n</code></pre>\n\n<hr>\n\n<p>Let's skip ahead a bit. Where do I want to go with this? My goal is to simplify <code>MainProgramme</code> to this:</p>\n\n<pre><code>import java.util.Scanner;\n\npublic class MainProgramme\n{\n private static Employee[] EMPLOYEES = {\n new Employee(\"John Hepburn\", \"50 Granton Road\", \"Edinburgh\", \"EH6 7UT\", 10001, 'C', \"Monthly\"),\n new Employee(\"David Jones\", \"121 Lochend Park\", \"Edinburgh\", \"EH1 1BA\", 10002, 'B', \"Weekly\"),\n new Employee(\"Louise White\", \"100 Govan Avenue\", \"Glasgow\", \"G15 5GG\", 10003, 'C', \"Monthly\"),\n new Employee(\"Harry Martin\", \"51 Gorgie Road\", \"Edinburgh\", \"EH5 2PR\", 10004, 'C', \"Monthly\"),\n new Employee(\"Christine Robertson\", \"1 Leith Street\", \"Edinburgh\", \"EH4 4ST\", 10005, 'B', \"Weekly\"),\n };\n\n private static PayrollAction[] ACTIONS = {\n new Exit(),\n new FilteredPrint(EmployeeTypeFilter.WEEKLY),\n new FilteredPrint(EmployeeTypeFilter.MONTHLY),\n new EmployeeDelete(),\n new EmployeeAdd(),\n new PayslipPrint(),\n };\n\n public static void main(String[] args)\n {\n Payroll payroll = new Payroll(EMPLOYEES);\n\n // Main menu\n System.out.println(\"Welcome to your Payroll System\");\n System.out.println();\n System.out.println(\"Please enter your choice below from the following options\");\n System.out.println();\n\n // List the actions, with \"Exit = 0\" last\n for (int i = 1; i < ACTIONS.length; i++) {\n System.out.format(\"%s = %d\\n\", ACTIONS[i], i);\n }\n System.out.format(\"%s = %d\\n\", ACTIONS[0], 0);\n\n // User to enter number of choice\n Scanner sc = new Scanner(System.in);\n\n PayrollAction action;\n try {\n action = ACTIONS[sc.nextInt()];\n } catch (ArrayIndexOutOfBoundsException noSuchAction) {\n System.out.println(\"You have entered the wrong choice\");\n return;\n }\n action.perform(payroll);\n }\n}\n</code></pre>\n\n<p>Much better, isn't it? Please take a long break now and see if you can reorganize the code to make it work. I'll include some spoilers below.</p>\n\n<hr>\n\n<p>We need a general way to select which employee(s) to operate on. We can accomplish that using \"filter\" objects.</p>\n\n<pre><code>public interface EmployeeFilter {\n boolean accepts(Employee e);\n}\n</code></pre>\n\n<p>Specifically, we need to support your weekly and monthly employee filters. We can create those two filters as singletons. (Singletons <em>are</em> are justified use of <code>static</code> members.)</p>\n\n<pre><code>public class EmployeeTypeFilter implements EmployeeFilter {\n private final String employeeType;\n\n private EmployeeTypeFilter(String employeeType) {\n this.employeeType = employeeType;\n }\n\n public static EmployeeTypeFilter MONTHLY = new EmployeeTypeFilter(\"Monthly\"),\n WEEKLY = new EmployeeTypeFilter(\"Weekly\");\n\n @Override\n public boolean accepts(Employee e) {\n return this.employeeType.equals(e.getType());\n }\n\n @Override\n public String toString() {\n return this.employeeType.toLowerCase() + \" employees\";\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T22:30:56.163",
"Id": "33199",
"ParentId": "33167",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T10:41:23.327",
"Id": "33167",
"Score": "4",
"Tags": [
"java",
"object-oriented"
],
"Title": "Managing employee information"
}
|
33167
|
<p>My function takes the values of the profit (function declared as <code>fieldProfit</code>) and the field score (function declared as <code>fieldScore</code>). If both are above 10, then you earn a badge, hence, <code>innerbadge = 1</code>.</p>
<p>But, there's also another condition that must be met: the field or (x, y) coordinates have to fall in the area depicted as the shaded in box that has a hole in the middle. Here's the image:</p>
<p><img src="https://i.stack.imgur.com/vEjbC.png" alt="enter image description here"></p>
<p>I've written the code for it, and I just wanted to make sure that my logic/syntax is correct.</p>
<pre><code> int badgeInnerCircle(int x, int y) {
double fprofit, fscore;
int innerbadge;
if ((x >= 1 && x <= 20) && (y >= 1 && y <= 20)) {
if (((x == 7 || x == 8) && (y >= 7 && y <= 14)) || ((x == 13 || x == 14)
&& (y >= 7 && y <= 14)) || ((x >= 7 && x <= 14) && (y == 7 || y == 8))
|| ((x >= 7 && x <= 14) && (y == 13 || y == 14))) {
fprofit = fieldProfit(x, y);
fscore = fieldScore(x, y);
if (fprofit >= 10 && fscore >= 10) {
innerbadge = 1;
}
else {
innerbadge = 0;
}
}
}
else {
innerbadge = -1;
}
return innerbadge;
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T12:12:30.593",
"Id": "53141",
"Score": "0",
"body": "Needs documentation!"
}
] |
[
{
"body": "<p>I think we can all agree that that code is hard to read. Rather than treating the dark shaded zone as the union of four rectangles, you would be better off treating it as a square with the centre excluded.</p>\n\n<p>I've used a macro to reduce the verbosity.</p>\n\n<p>In your code, when (<em>x</em>, <em>y</em>) falls in either of the white zones, you return an uninitialized value for <code>innerbadge</code>. In those cases, the behaviour is undefined.</p>\n\n<pre><code>#define XY_IN_SQUARE(min, max) (((min) <= x && x <= (max)) && \\\n ((min) <= y && y <= (max)))\n\nint badgeInnerCircle(int x, int y) {\n if (XY_IN_SQUARE(9, 12)) { /* In innermost white zone */\n return /* what? */;\n } else if (XY_IN_SQUARE(7, 14)) { /* In dark grey zone */\n double fprofit = fieldProfit(x, y);\n double fscore = fieldScore(x, y);\n\n /* The following value will be either 1 or 0 */\n return fprofit >= 10 && fscore >= 10;\n } else if (XY_IN_SQUARE(2, 19)) { /* In outer white zone */\n return /* what? */;\n } else if (XY_IN_SQUARE(1, 20)) { /* On yellow border */\n return /* what? */;\n } else { /* Outside yellow border */\n return -1;\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T11:43:49.967",
"Id": "33169",
"ParentId": "33168",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T10:45:40.500",
"Id": "33168",
"Score": "0",
"Tags": [
"c"
],
"Title": "Calculating profit and score, if coordinates fall in a certain region of a field"
}
|
33168
|
<p>For a Project Euler problem, I made a Ruby roman numeral converter:</p>
<pre><code>def romanize(num)
digits = {
1000 => "M",
900 => "CM", 500 => "D", 400 => "CD", 100 => "C",
90 => "XC", 50 => "L", 40 => "XL", 10 => "X",
9 => "IX", 5 => "V", 4 => "IV", 1 => "I"
}
digits.reduce("") do |acc, digit|
key, numeral = digit
occurances, num = num.divmod(key)
acc + (numeral * occurances)
end
end
</code></pre>
<p>This works great, but I'm not sure it's good Ruby. Specifically, I'm wondering if the body of the <code>reduce</code> block could be shortened, and if it could made more clear.</p>
<p>For example, I don't think its that obvious that <code>num</code> is being modified in the middle of the <code>reduce</code> block.</p>
<p>Also, I know I can monkey patch this into the <code>Fixnum</code> class, but that's not what I'm looking for.</p>
<p><strong>Update #1</strong></p>
<p>@Tokland's answer taught me some new things. His answer works well, and is pretty clever.</p>
<p>If I take just two of his concepts and apply them to mine, the <code>digits.reduce("") ...</code> block can be simplified to:</p>
<pre><code>digits.map do |key, numeral|
occurances, num = num.divmod(key)
numeral * occurances
end.join
</code></pre>
<p>This needs one less line because it deconstructs the digit key/value in the block arguments. Also, it creates an array which is joined into a string at the end. For big numbers (around 100-trillion), this is much quicker.</p>
<p>The only problem I still see is that it's modifying the <code>num</code> variable, which is essentially global state to the block.</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T06:49:13.977",
"Id": "53209",
"Score": "1",
"body": "In this case: `|(key, numeral)|` -> `|key, numeral|`"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T10:25:47.773",
"Id": "53216",
"Score": "0",
"body": "@tokland Good catch. I've corrected it in the question."
}
] |
[
{
"body": "<p>Some notes:</p>\n\n<ul>\n<li>Use 2 spaces for indentation, not 4.</li>\n<li><code>key, numeral = digit</code>: You can unpack block arguments: <code>do |acc, (key, numeral)|</code>.</li>\n<li><code>Concat</code>ing strings is costly, better build an array and finally join it.</li>\n<li>You are using <code>inject</code>, which is great because it'a functional abstraction, but you are modifying <code>num</code> on each iteration, so it ends up being a weird mixture of functional and imperative style. I know it's a bit cumbersome, but conceptually it's better to keep also <code>num</code> in the accumulator.</li>\n</ul>\n\n<p>I'd write:</p>\n\n<pre><code>digits.reduce(:output => [], :num => num) do |state, (key, numeral)|\n ocurrences, remainder = state[:num].divmod(key)\n {:output => state[:output] << (numeral * ocurrences), :num => remainder} \nend[:output].join\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T01:09:12.227",
"Id": "53198",
"Score": "0",
"body": "There's some good stuff I learned in this answer (such as unpacking arguments. Constructing an array with `reduce`/`inject` feels wrong, though, doesn't it? Even though that's what I did in mine, it seems like there should be a good `map` solution."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T01:10:59.423",
"Id": "53199",
"Score": "0",
"body": "Also, I benchmarked constructing an array and then joining it versus string concatenation. For trivial examples, there's almost no difference. For a number in the 100-trillions, though, joining was much quicker (0.4s vs 2.5s)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T01:17:13.380",
"Id": "53200",
"Score": "0",
"body": "Finally, while it is cumbersome, it's also very clever to use the accumulator to pass state from one iteration to the next. Avoids modifying anything external to the block. Maybe it's just me, though, but it seems like it's not obvious what's going on here at first glance. I'd be worried about doing something like this on a real project, because someone else might struggle to figure it out... and I might struggle to figure it out 6 months from now."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T06:47:25.967",
"Id": "53208",
"Score": "0",
"body": "@ahuth: Indeed for a programmer not familiary with functional style this may be hard to grasp at first. I don't think you can do it with `map` because there is state in the computation. In functional languages you'd probably write it with a recursive function (but it would be completely equivalent, a fold is a recursive abstraction). Instead of `state` you'd have the two arguments (`output`/`num`). I've used a hash instead of an array pair to try to make it more clear."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T00:49:11.860",
"Id": "53348",
"Score": "0",
"body": "`digits.reduce([[], num]) do |(output, current), (key, numeral)|` ? Looks better than hash."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T08:32:04.103",
"Id": "53374",
"Score": "0",
"body": "@VictorMoroz: yes, that's more compact. I usually use an array not a hash, in fact."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T12:50:17.510",
"Id": "33172",
"ParentId": "33170",
"Score": "3"
}
},
{
"body": "<p>Rather than looping through <code>digits</code>, you could break down <code>num</code> in a loop, like this:</p>\n\n<pre><code>@digits = {\n 1000 => \"M\",\n 900 => \"CM\", 500 => \"D\", 400 => \"CD\", 100 => \"C\",\n 90 => \"XC\", 50 => \"L\", 40 => \"XL\", 10 => \"X\",\n 9 => \"IX\", 5 => \"V\", 4 => \"IV\", 1 => \"I\"\n}\n\ndef romanize(num)\n @digits.keys.each_with_object('') do |key, str|\n nbr, num = num.divmod(key)\n str << @digits[key]*nbr\n end\nend\n\nromanize(888) # => \"DCCCLXXXVIII\" \nromanize(999) # => \"CMXCIX\"\n</code></pre>\n\n<p>Note that</p>\n\n<pre><code>str << @digits[key]*nbr\n</code></pre>\n\n<p>leaves <code>str</code> unchanged if <code>nbr = 0</code>.</p>\n\n<p>You could also do this using recursion:</p>\n\n<pre><code> def romanize(num, str='')\n return str if num == 0\n key = @digits.keys.find { |k| k <= num }\n str << @digits[key]\n romanize(num-key, str)\nend\n\nromanize(888) # => \"DCCCLXXXVIII\" \nromanize(999) # => \"CMXCIX\"\n</code></pre>\n\n<p>Note both of these methods require Ruby 1.9+. Since 1.9, hash pairs have been kept in the order in which they were added. For Ruby 1.8x you would need to replace <code>@digits</code> with an array of key-value pairs or order its keys in an array <code>keys</code> and for each key <code>key</code> in <code>keys</code>, extract its value with <code>@digits[key]</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-05T15:01:01.570",
"Id": "54277",
"Score": "0",
"body": "Thanks for the recursive solution. If I'm not mistaken, this is tail-call optimized, too?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-08T05:49:06.700",
"Id": "54696",
"Score": "0",
"body": "Sorry, but I can't help you with that. In fact, this is the first time I've heard that term. I looked it up and get the general idea, but best for someone else to answer that."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-27T06:36:38.887",
"Id": "33316",
"ParentId": "33170",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "33172",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T12:25:35.430",
"Id": "33170",
"Score": "4",
"Tags": [
"ruby",
"project-euler",
"converting",
"roman-numerals"
],
"Title": "Roman numeral converter in Ruby"
}
|
33170
|
<p>This might be a loaded question, but here goes. I have some code that is very similar between all the methods. I am trying to find a way to accomplish all methods with a generic method/function. I'm not sure if I should be using delegates, and if so how to implement in this specific situation, or if there is a much more simple way to make a generic method. </p>
<p>Below I have copied the code I am trying to make generic. All methods take this basic syntax: (Parameters) ConcurrentQueue(pPeople), With that collection, the first part gets the count of the records. Each method iterates over a different part of the collection (or collection in the collection). </p>
<p>Thanks for any help or nudges in the right direction! If you have an idea that would help, it would be great if you could give an example related to this code (or very similar).</p>
<p>Code: I have copied three methods that give that show similar code (there are many more).</p>
<pre><code> private void UpdatepPeopleAddressIDs(ConcurrentQueue<pPeople> people)
{
//Get Count of records that need an ID from uMaxIDs
int updateCount = 0; object lockObject = new object();
Parallel.ForEach<pPeople>(people, person =>
{
person.myPeopleAddressList.ForEach(address =>
{
if (address.ID == 0)
{
lock (lockObject)
{
updateCount++;
}
}
});
});
}
private void UpdatepPeopleContactNumbersIDs(ConcurrentQueue<pPeople> people)
{
//Get Count of records that need an ID from uMaxIDs
int updateCount = 0; object lockObject = new object();
Parallel.ForEach<pPeople>(people, person =>
{
person.myPeopleContactsList.ForEach(contact =>
{
if (contact.ID == 0)
{
lock (lockObject)
{
updateCount++;
}
}
});
});
}
private void UpdatepPeopleEmailIDs(ConcurrentQueue<pPeople> people)
{
//Get Count of records that need an ID from uMaxIDs
int updateCount = 0; object lockObject = new object();
Parallel.ForEach<pPeople>(people, person =>
{
person.myPeopleEmailsList.ForEach(emails =>
{
if (emails.ID == 0)
{
lock (lockObject)
{
updateCount++;
}
}
});
});
}
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T13:37:51.733",
"Id": "53147",
"Score": "4",
"body": "Observation: you are sharing a lock between all objects in that operation. Frankly, you might as well do it in series rather than parallel. An `Interlocked.Increment` might be a viable option. But again: since this is just a trivial test and increment, I can't see the purpose of parallelism here"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T13:39:45.077",
"Id": "53148",
"Score": "0",
"body": "Observation2: Use Interlocked.Increment(ref this.counter); instead of full lock blocks."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T13:40:35.150",
"Id": "53149",
"Score": "1",
"body": "Do the address, contact and email class share a base class or interface? This would be easy if the ID property on those classes where defined in an interface..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T14:39:41.057",
"Id": "53151",
"Score": "0",
"body": "Agree with @MarcGravell. The code inside Parallel.ForEach is doing so little, you are better off not using Parallel.ForEach. ConcurrentQueue can change while you are enumerating over it (you get a copy) and the updateCount may or may not reflect the latest queue status. Finally, the most important thing: running these functions is USELESS. They update a local variable 'updateCount' and does nothing with it."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T15:04:53.770",
"Id": "53153",
"Score": "0",
"body": "I simplified the methods dramatically. Stuff is done with updateCount, I just have left that out of my code since it is not relevant to this current question. I didn't want to paste hundreds of lines of code when all I need help on was one specific part of it. I do agree that parallel.foreach is fairly useless, I originally had more happening in that loop, but have changed as I have gone on. I realize some of the coding doesn't necessarily make sense since you can't see the whole solution, but it also isn't needed for this example."
}
] |
[
{
"body": "<p>Here is an example of an update people function and a call to it.</p>\n\n<p>I make no claim to your code being correct, I'm just refactoring to the generic case given the code you posted.</p>\n\n<pre><code> private void UpdatePeople(ConcurrentQueue<pPeople> people, Action<pPeople> actOn)\n {\n //Get Count of records that need an ID from uMaxIDs\n int updateCount = 0; object lockObject = new object();\n Parallel.ForEach<pPeople>(people, person => actOn(person));\n }\n\n\n private void UpdatepPeopleEmailIDs(ConcurrentQueue<pPeople> people)\n {\n UpdatePeople(people, person =>\n {\n person.myPeopleEmailsList.ForEach(emails =>\n {\n if (emails.ID == 0)\n {\n lock (lockObject)\n {\n updateCount++;\n }\n }\n });\n });\n }\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T13:41:08.503",
"Id": "33175",
"ParentId": "33174",
"Score": "0"
}
},
{
"body": "<p>This is fairly easy to achieve. You need to make use of callback, which can perform the functionality specific to the method, which your generic method then uses. Something like this:</p>\n\n<pre><code>private void UpdatepPeople<T>(ConcurrentQueue<pPeople> people,\n Func<PersonClass, List<T>> listProvider,\n Func<T, bool> updateRequiredTest)\n{\n var updateCount = 0; \n var lockObject = new object();\n\n Parallel.ForEach<pPeople>(people, person =>\n {\n listProvider(person).ForEach(item =>\n {\n if (updateRequiredTest(item))\n {\n lock (lockObject)\n {\n updateCount++;\n }\n }\n });\n });\n}\n\nprivate void UpdatepPeopleContactNumbersIDs(ConcurrentQueue<pPeople> people)\n{\n UpdatepPeople<ContactType>(people,\n person => person.myPeopleContactsList,\n contact => contact.ID == 0);\n}\n\nprivate void UpdatepPeopleEmailIDs(ConcurrentQueue<pPeople> people)\n{\n UpdatepPeople<EmailType>(people,\n person => person.myPeopleEmailsList,\n contact => emails.ID == 0);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T13:53:23.140",
"Id": "33176",
"ParentId": "33174",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "33176",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T13:35:18.227",
"Id": "33174",
"Score": "2",
"Tags": [
"c#",
"delegates"
],
"Title": "Refactoring Into Generic Methods"
}
|
33174
|
<p>I have the following code and am wondering if this can be further optimized and also beautified (in order to be more readable) :</p>
<pre><code>if( ( subType = entry.getSubType() ) ==null
||
!(subType.equals("typeA") || subType.equals("typeB"))
||
( version>=5 && (subType.equals("typeA") || subType.equals("typeB")) )
||
( version>=4 && subType.equals("typeA") )
)
arrayData.add(entry);
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-26T13:30:44.557",
"Id": "242113",
"Score": "0",
"body": "@jamal please inform as to which of the criteria were used in order to decide that the question is off-topic? I'm quite eager and curious. That is the specific section of code I wanted reviewed and it's quite explanatory what they do. You cannot expect someone to upload their whole project or classes to code review in order to be \"concrete\". Declaring this is not a concrete section of code for review is completely subjective based on the help center rules. Or do we need to upload a full application? I could package that in public static main for you if that makes it concrete :D..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-26T13:48:49.600",
"Id": "242116",
"Score": "2",
"body": "This isn't even a complete function. We don't do stub code, as explained in the close header. We don't have enough context to see what you want. Why we don't deal in questions without context can be read [here](http://meta.codereview.stackexchange.com/a/1710/52915)."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-05-26T21:28:20.193",
"Id": "242182",
"Score": "0",
"body": "Actually, it's pretty clear, considering the generality of the question as well as the naming and sample size. If you have actual code, even something partial that works on its own, then you're welcome to post that."
}
] |
[
{
"body": "<p>I don't really do Java. But this looks like infrequently executed code that you should be optimizing for readability vs. trying to minimize the number of comparisons.</p>\n\n<p>Imagine being in the position of someone maintaining the code after a directive like <em>\"we've decided not to support versions prior to 4.\"</em> Is it completely clear which part they can delete?</p>\n\n<p>So how do you convey the intention of this code (essentially, a version-sensitive decision on whether or not to add an entry to arrayData based on a type?) You want to distinguish between versions prior to 4, version 4, and version 5 and above. Imagine breaking it down so each branch is clearly separated:</p>\n\n<pre><code>boolean shouldAdd = false;\n\nWhateverType subType = entry.getSubType();\nboolean isTypeA = (subType == null) ? false : subType.equals(\"typeA\");\nboolean isTypeB = (subType == null) ? false : subType.equals(\"typeB\");\n\nif (!isTypeA && !isTypeB)\n shouldAdd = true;\n\nif (version >= 4) { \n if (isTypeA)\n shouldAdd = true;\n}\n\nif (version >= 5) {\n if (isTypeB)\n shouldAdd = true;\n}\n\nif (shouldAdd)\n arrayData.add(entry);\n</code></pre>\n\n<p>This approach tips toward being verbose just to float the idea of leaning away from thinking you have to collapse everything into a single <code>if</code> statement. You can have complex per-version logic that sets a variable, and that variable can trigger the ultimate decision. (In this case your per-version logic is pretty simple, so it's overkill.)</p>\n\n<p>If you cache the result of the type check in a boolean, it will be cheap and avoids potential mistyping of the string constant. <em>(And if you're referring to these frequently, you should probably create a global constant... it's easy to miss and get <code>\"tpyeA\"</code> and have no compiler checking to catch the mistake!)</em></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T15:51:18.120",
"Id": "33182",
"ParentId": "33177",
"Score": "3"
}
},
{
"body": "<p>@HostileFork is completely right. From a code review perspective, your code should be optimized for readability.</p>\n\n<p>It could be a little more <a href=\"http://en.wikipedia.org/wiki/Don%27t_repeat_yourself\" rel=\"nofollow\">DRY</a>.</p>\n\n<pre><code>WhateverType subType = entry.getSubType();\nboolean isTypeA = (subType == null) ? false : subType.equals(\"typeA\");\nboolean isTypeB = (subType == null) ? false : subType.equals(\"typeB\");\n\n//What should be added ? \nif ( ( !isTypeA && !isTypeB ) // Anything other than A and B should be \n ||( version >= 4 && isTypeA ) // Type A for version 4 and over should be\n ||( version >= 5 && isTypeB )) // Type B for version 5 and over should be\n arrayData.add(entry);\n</code></pre>\n\n<p>Note that this code is 9 lines as well, but readable.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T16:13:03.737",
"Id": "53158",
"Score": "1",
"body": "+1 for saying I'm right. :-) I wanted to introduce a variable just to show that the per-version logic could be more complex and not force one into a single `if` statement, but I've expanded and made that more explicit..."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T19:11:47.560",
"Id": "53183",
"Score": "3",
"body": "`\"typeA\".equals(subType)` will allow you to skip the null checks, assuming `subType` is a string and not a different class with a special `equals`"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T16:04:02.177",
"Id": "33183",
"ParentId": "33177",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": "33183",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T14:11:53.463",
"Id": "33177",
"Score": "-1",
"Tags": [
"java"
],
"Title": "Optimize/Beautify Boolean Statement in Specific Code"
}
|
33177
|
<p>I'm using Munkres library from <a href="https://github.com/bmc/munkres/" rel="nofollow">https://github.com/bmc/munkres/</a> to calculate maximum profit (reversed problem).</p>
<p>What do you think about this coding style?</p>
<pre><code>def get_no_of_vowels(str):
return sum(str.lower().count(c) for c in "aeiuoy")
def get_no_of_consonants(str):
return sum(str.lower().count(c) for c in "bcdfghjklmnpqrstvwxz")
def count_letters(str):
return sum(c.isalpha() for c in str)
def compute_ss(name, item):
if not count_letters(item)%2:
ss = get_no_of_vowels(name)*1.5
else:
ss = get_no_of_consonants(name)
if gcd(count_letters(name), count_letters(item)) > 1:
ss*=1.5
return ss
if __name__ == "__main__":
with open(sys.argv[1]) as f:
for line in f:
names = line.strip().split(';')[0].split(',')
items = line.strip().split(';')[1].split(',')
dic = collections.defaultdict(list)
profit_matrix = []
for name in names:
row = []
for item in items:
row.append(compute_ss(name, item))
profit_matrix.append(row)
m = Munkres()
cost_matrix = make_cost_matrix(profit_matrix, lambda x: 1e10 - x)
indexes = m.compute(cost_matrix)
total = 0
for row, column in indexes:
value = profit_matrix[row][column]
# print '(%.2f, %.2f) -> %.2f' % (row, column, value)
total += value
print "%.2f"%total
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T16:22:48.877",
"Id": "53160",
"Score": "0",
"body": "It seems to be missing the necessary `import` statements."
}
] |
[
{
"body": "<p>I just want to point out two sources of inefficiency:</p>\n\n<p>1) The counting functions, e.g.:</p>\n\n<pre><code>def get_no_of_vowels(str):\n return sum(str.lower().count(c) for c in \"aeiuoy\")\n</code></pre>\n\n<p>This will loop over <code>str</code> 6 times, which is 5 more times than is necessary. A more efficient approach is:</p>\n\n<pre><code>def get_no_of_vowels(str):\n return sum(1 for s in str if s.lower() in \"aeiouy\" else 0)\n</code></pre>\n\n<p>We are creating a generator that will convert each character into a 1 or a 0, and then just sum them. That way, we just do one iteration. Also, \"y\" is not a vowel.</p>\n\n<p>2) Your line-splitting code here:</p>\n\n<pre><code> names = line.strip().split(';')[0].split(',')\n items = line.strip().split(';')[1].split(',')\n</code></pre>\n\n<p>You are splitting line twice. That's extra work. Prefer:</p>\n\n<pre><code>names, items = line.strip().split(';')\nnames = names.split(',')\nitems = items.split(',')\n</code></pre>\n\n<p>Hope that helps.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-28T19:35:40.710",
"Id": "53531",
"Score": "1",
"body": "Your version of `get_no_of_vowels` raises a `SyntaxError` for me. You need `sum(1 if s.lower() in \"aeiouy\" else 0 for s in str)`. (But: Python uses [Iverson's convention](http://drj11.wordpress.com/2007/05/25/iversons-convention-or-what-is-the-value-of-x-y/), so you can actually write `sum(s.lower() in 'aeiouy' for s in str)`.)"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-26T22:01:48.463",
"Id": "33305",
"ParentId": "33180",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T15:33:07.267",
"Id": "33180",
"Score": "1",
"Tags": [
"python"
],
"Title": "Munkres algorithm in Python: calculating maximum profit"
}
|
33180
|
<p>I have been looking for an algorithm for splitting a file into smaller pieces, which satisfy the following requirements:</p>
<ul>
<li>The first line in the original file is a header, this header must be carried over to the resulting files</li>
<li>The ability to specify the approximate size to split off, for example, I want to split a file to blocks of about 200,000 characters in size. </li>
<li>File must be splitted at line boundaries</li>
</ul>
<p>More info:</p>
<ol>
<li>This is part of my web service: the user uploads a CSV file, the web service will see this CSV is a chunk of data--it does not know of any file, just the contents.</li>
<li>The web service then breaks the chunk of data up into several smaller pieces, each will the header (first line of the chunk). It then schedules a task for each piece of data. I don't want to process the whole chunk of data since it might take a few minutes to process all of it. I want to process them in smaller size. This is why I need to split my data.</li>
<li>The final code will not deal with open file for reading nor writing. I only do that to test out the code.</li>
<li>The task to process smaller pieces of data will deal with CSV via <code>csv.DictReader</code>. It does not make sense to use the <code>csv</code> module to break up the original chunk of data into pieces. I have done some timing and my algorithm achieves better performance as opposed to reading/writing line-by-line just to break data into pieces.</li>
</ol>
<p>Here is an example:</p>
<p>If my original file is:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Header
line1
line2
line3
line4
</code></pre>
</blockquote>
<p>If I want my approximate block size of 8 characters, then the above will be splitted as followed:</p>
<p>File1:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Header
line1
line2
</code></pre>
</blockquote>
<p>File2:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Header
line3
line4
</code></pre>
</blockquote>
<p>In the example above, if I start counting from the beginning of <em>line1</em> (yes, I want to exclude the header from the counting), then the first file should be:</p>
<blockquote>
<pre class="lang-none prettyprint-override"><code>Header
line1
li
</code></pre>
</blockquote>
<p>But, since I want the splitting done at line boundary, I included the rest of line2 in <em>File1</em>. </p>
<p>Here is what I have so far. I am looking to turn this code segment into a procedure, but more importantly, I want the code to speed up a bit. Currently, it takes about 1 second to finish. In the final solution, In addition, I am going to do the following:</p>
<ul>
<li>Change the procedure to return a generator, which returns blocks of data. I don't really need to write them into files. I think I know how to do this, but any comment or suggestion is welcome.</li>
<li>Since my data is in Unicode (Vietnamese text), I have to deal with <code>.encode()</code>, <code>.decode()</code>. Any hint to speed this up would be great.</li>
</ul>
<pre class="lang-python prettyprint-override"><code>with open('data.csv') as f:
buf = f.read().decode('utf-8')
header, chunk = buf.split('\n', 1)
block_size = 200000
block_start = 0
counter = 0
while True:
counter += 1
filename = 'part_%03d.txt' % counter
block_end = chunk.find('\n', block_start + block_size)
print filename, block_start, block_end
with open(filename, 'w') as f:
f.write(header + '\n')
if block_end == -1:
f.write(chunk[block_start:].encode('utf-8'))
else:
f.write(chunk[block_start:block_end].encode('utf-8'))
f.write('\n')
block_start = block_end + 1
if block_end == -1: break
</code></pre>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T19:44:44.570",
"Id": "53185",
"Score": "0",
"body": "But » it takes about 1 second to finish« I wouldn't call it that slow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T19:54:20.030",
"Id": "53187",
"Score": "0",
"body": "I agreed, but in context of a web app, a second might be slow."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T20:04:01.950",
"Id": "53188",
"Score": "0",
"body": "On the other hand, there is not much going on in your programm. I think it would be hard to optimize more for performance, though some refactoring for \"clean\" code would be nice ;) My guess is, that the the I/O-Part is the real bottleneck. Have you done any python profiling yet for hot-spots?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-02-25T07:33:33.907",
"Id": "295879",
"Score": "0",
"body": "Thank you so much for this code! It worked like magic for me after searching in lots of places.\nHowever, rather than setting the chunk size, I want to split into multiple files based on a column value.\nWhen I tried doing it in other ways, the header(which is in row 0) would not appear in the resulting files. I want to see the header in all the files generated like yours.\nCan you help me out by telling how can I divide into chunks based on a column?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2017-03-06T17:37:27.723",
"Id": "297348",
"Score": "0",
"body": "@Nymeria123 Please post a new question (instead of commenting) and put a link back to this one. That way, you will get help quicker."
}
] |
[
{
"body": "<h3>1. Comments on your code</h3>\n\n<ol>\n<li><p>There's no documentation. What does your program do and how should it be used?</p></li>\n<li><p>Your program is not split up into functions. This makes it hard to test it from the interactive interpreter.</p></li>\n<li><p>The name <code>data.csv</code> seems arbitrary. Surely this should be an argument to the program? Similarly for <code>'part_%03d.txt'</code> and <code>block_size = 200000</code>.</p></li>\n<li><p>You read the whole of the input file into memory and then use <code>.decode</code>, <code>.split</code> and so on. It would be more efficient to read and write one line at a time, thus using no more memory than is needed to store the longest line in the input.</p></li>\n<li><p>In Python, a file object is also an <em>iterator</em> that yields the lines of the file. It's often simplest to process the lines in a file using <code>for line in file:</code> loop or <code>line = next(file)</code>.</p></li>\n<li><p>When you have an infinite loop incrementing a counter, like this:</p>\n\n<pre><code>counter = 0\nwhile True:\n counter += 1\n</code></pre>\n\n<p>consider using <a href=\"http://docs.python.org/3/library/itertools.html#itertools.count\"><code>itertools.count</code></a>, like this:</p>\n\n<pre><code>for counter in itertools.count(1):\n</code></pre>\n\n<p>(But you'll see below that it's actually more convenient here to use <a href=\"http://docs.python.org/3/library/functions.html#enumerate\"><code>enumerate</code></a>.)</p></li>\n<li><p>Since your data is encoded in UTF-8, and only character you actually look for in the input is the newline character (<code>\\n</code>), there is no need for you to decode the input or encode the output: you could work with <a href=\"http://docs.python.org/3/library/stdtypes.html#bytes\">bytes</a> throughout. (But if you insist on decoding the input and encoding the output, then you should pass the <code>encoding='utf-8'</code> keyword argument to <a href=\"http://docs.python.org/3/library/functions.html#open\"><code>open</code></a>.)</p></li>\n</ol>\n\n<h3>2. Revised code</h3>\n\n<p>Here's how I'd implement your program. The only tricky aspect to it is that I have two different loops that iterate over the same iterator <code>f</code> (the first one using <a href=\"http://docs.python.org/3/library/functions.html#enumerate\"><code>enumerate</code></a>, the second one using <a href=\"http://docs.python.org/3/library/itertools.html#itertools.count\"><code>itertools.chain</code></a>). This works because the iterator state is stored in the object <code>f</code>, so the two loops can independently fetch lines from the iterator and the lines still come out in the right order.</p>\n\n<pre><code>from itertools import chain\n\ndef split_file(filename, pattern, size):\n \"\"\"Split a file into multiple output files.\n\n The first line read from 'filename' is a header line that is copied to\n every output file. The remaining lines are split into blocks of at\n least 'size' characters and written to output files whose names\n are pattern.format(1), pattern.format(2), and so on. The last\n output file may be short.\n\n \"\"\"\n with open(filename, 'rb') as f:\n header = next(f)\n for index, line in enumerate(f, start=1):\n with open(pattern.format(index), 'wb') as out:\n out.write(header)\n n = 0\n for line in chain([line], f):\n out.write(line)\n n += len(line)\n if n >= size:\n break\n\nif __name__ == '__main__':\n split_file('data.csv', 'part_{0:03d}.txt', 200000)\n</code></pre>\n\n<h3>3. Generating the output blocks instead</h3>\n\n<p>Do you really want to process a CSV file in chunks? I can't imagine why you would want to do that. Surely either you have to process the whole file at once, or else you can process it one line at a time?</p>\n\n<p>Processing a file one line at a time is easy:</p>\n\n<pre><code>with open(filename, encoding='utf-8') as f:\n header = next(f)\n for line in f:\n # process line\n</code></pre>\n\n<p>But given that this is apparently a CSV file, why not use Python's built-in <a href=\"http://docs.python.org/3/library/csv.html\"><code>csv</code></a> module to do whatever you need to do? Like this:</p>\n\n<pre><code>import csv\nwith open(filename, encoding='utf-8', newline='') as f:\n reader = csv.reader(f)\n header = next(reader)\n for row in reader:\n # row[0] is the first field in this row, and so on.\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-05-10T17:51:16.073",
"Id": "373414",
"Score": "0",
"body": "I think there is an error in this code upgrade. `n += len(line)` should be `n += 1`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-05-10T18:09:07.357",
"Id": "373418",
"Score": "0",
"body": "@metersk: `size` is in characters rather than lines."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2018-05-10T18:12:27.160",
"Id": "373419",
"Score": "0",
"body": "Ah! Maybe I should read the OP next time ! Regardless, this was very helpful for splitting on lines with my tiny change. Thanks!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T20:29:32.143",
"Id": "33197",
"ParentId": "33193",
"Score": "10"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T19:03:05.127",
"Id": "33193",
"Score": "7",
"Tags": [
"python",
"performance",
"file",
"csv",
"utf-8"
],
"Title": "Splitting a CSV file with headers"
}
|
33193
|
<p><strong>Problem</strong>: Make a slider, located at the bottom of the page. The slider should be dynamically loaded only when a div (<code>#slider</code>) becomes visible on the screen. Images do not have to load all at once. Load the first two images, then load the third when we switched to the second, and so on.</p>
<p>I would like other users to look look at my code and tell me what I'm doing wrong and what could be done better (if you can - in more detail).</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>$(function () {
var countImg = 5,
indexImg = 1,
indexImgLoad = 2,
pathImg = '/img/slider/',
formatImg = 'jpg',
controlFlag = 1,
elWrap = $('#slider'),
el = elWrap.find('img');
function create () {
Img = new Image();
Img.src= pathImg+indexImg+'.'+formatImg;
$(Img).appendTo($("#slides"));
$('<span class="next"></span><span class="prev"></span>').appendTo($("#slider"));
navigation();
check();
}
function change () {
el.fadeOut(500);
el.filter(':nth-child('+indexImg+')').fadeIn(500);
}
function newimg() {
nextImg = new Image();
nextImg.src= pathImg+indexImgLoad+'.'+formatImg;
$(nextImg).appendTo($("#slides"));
}
function check() {
if (controlFlag && indexImgLoad <= countImg) {
newimg();
}
if (controlFlag){
el = elWrap.find('img');
}
if (el.length == countImg){
controlFlag = 0;
}
}
function navigation(){
$('span.next').click(function() {
indexImg++;
indexImgLoad++;
if(indexImg > countImg) {
indexImg = 1;
}
check();
change();
});
$('span.prev').click(function() {
indexImg--;
if(indexImg < 1) {
indexImg = countImg;
}
indexImgLoad++;
check();
change ();
});
}
var loadSlider = 1;
window.onscroll = function() {
var pageY = window.pageYOffset || document.documentElement.scrollTop,
heightScreen = window.innerHeight + pageY;
sliderTopY = $("#slides").offset().top;
if ((heightScreen > (sliderTopY - sliderTopY * 0.05)) && loadSlider) {
loadSlider = 0;
create();
}
}
});</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>.slider_wrap {
margin: 0px auto 0;
width: 735px;
height: 200px;
position: relative;
overflow: hidden;
}
.slider_wrap img {
width: 645px;
height: auto;
display: none;
position: absolute;
top: 0;
left: 45px;
}
.slider_wrap img:first-child {
display: block;
}
.slider_wrap span {
width: 45px;
height: 200px;
display: block;
position: absolute;
cursor: pointer;
background: url(/img/rotator_buttons.png) no-repeat;
opacity: 0.7;
}
.slider_wrap span.next {
right: 0;
background-position: -45px 0;
}
.slider_wrap span.next:hover, span.prev:hover {
opacity: 1.0;
}
.slider_wrap span.prev {
background-position: 0 0;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div style="height:1800px;">div: height = 1800px</div>
<div id="slider" class="slider_wrap">
<div id="slides">
</div>
</div></code></pre>
</div>
</div>
</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T23:26:55.737",
"Id": "53195",
"Score": "0",
"body": "(quote)The slider should be dynamically loaded only when an `unicorn` becomes visible on the screen.(/quote)"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T06:27:14.873",
"Id": "53207",
"Score": "0",
"body": "Sorry :) There was: div id=slider"
}
] |
[
{
"body": "<p>Few things:</p>\n\n<ol>\n<li>You can create a plugin out of it (create divs <code>#slider</code> and <code>#slides</code> - don't use id, but just reference - and add class slider_wrap in code)</li>\n<li>You don't put var before <code>nextImg = new Image();</code></li>\n<li><p>Instead of new Image you can use jQuery:</p>\n\n<p><code>$('<img/>').attr('src', path).appendTo($(\"#slides\"));</code></p></li>\n<li><p>Instead of <code>$('span.next')</code> use <code>elWrap.find('span.next')</code> because it will not work if span.next is somewhere in the html.</p></li>\n<li>Is always better ot use jQuery not native function because they may be different from browser to browser. So use <code>$(window).scroll(function() { })</code> <code>$(window).innerHeight()</code> and <code>$(window).scrollTop();</code> </li>\n<li>Inside newimg you call <code>$(\"#slides\")</code> you can call that before a function and store it's value in variable.</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T20:23:04.217",
"Id": "33196",
"ParentId": "33194",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "33196",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T19:37:18.550",
"Id": "33194",
"Score": "1",
"Tags": [
"javascript",
"beginner",
"jquery"
],
"Title": "Dynamically loaded slider"
}
|
33194
|
<p>This is a working stack implementation using a linked list. I'm just curious to know if this is a good way of doing it. Any suggestions are welcome. Can we keep track of the number of elements in the stack using a <code>count</code> variable as used in the code?</p>
<pre><code>#include <cstdlib>
#include<iostream>
using namespace std;
class node
{
public:
int data;
node* next;
};
class StackusingList
{
public:
StackusingList(int max)
{
top = NULL;
maxnum = max;
count=0;
}
void push(int element)
{
if(count == maxnum)
cout<<"stack is full";
else
{
node *newTop = new node;
if(top == NULL)
{
newTop->data = element;
newTop->next = NULL;
top = newTop;
count++;
}
else
{
newTop->data = element;
newTop->next = top;
top = newTop;
count++;
}
}
}
void pop()
{
if(top == NULL)
cout<< "nothing to pop";
else
{
node * old = top;
top = top->next;
count--;
delete(old);
}
}
void print()
{
node *temp;
temp = top;
while(temp!=NULL)
{
cout<<temp->data<<",";
temp=temp->next;
}
}
private:
node *top;
int count; //head
int maxnum;
int stackData;
};
int main(int argc, char** argv) {
StackusingList *sl = new StackusingList(5);
sl->push(1);
sl->push(2);
sl->push(3);
sl->push(4);
sl->push(5);
sl->push(6);
sl->pop();
cout<<"new stack\n";
sl->print();
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<ul>\n<li><p>At some point, I'd recommend using <code>template</code> here. This will allow you to store any date type, not just <code>int</code>s, in your structure.</p></li>\n<li><p>It'd be better to define <code>node</code> as a <code>struct</code> inside <code>StackusingList</code> as <code>private</code>. In your current implementation, <code>node</code>'s fields are <em>not</em> hidden because they are all made <code>public</code>.</p>\n\n<pre><code>class LinkedList\n{\nprivate:\n struct Node\n {\n };\n\npublic:\n\n};\n</code></pre></li>\n<li><p>Prefer <a href=\"https://en.cppreference.com/w/cpp/language/nullptr\" rel=\"nofollow noreferrer\"><code>nullptr</code></a> to <code>NULL</code> if you're using C++11.</p></li>\n<li><p><code>StackusingList()</code> should be an <a href=\"https://en.cppreference.com/w/cpp/language/initializer_list\" rel=\"nofollow noreferrer\">initializer list</a>:</p>\n\n<pre><code>StackusingList(int max) : top(NULL), maxnum(max), count(0) {}\n</code></pre></li>\n<li><p><code>count</code> should be of type <a href=\"http://en.cppreference.com/w/cpp/types/size_t\" rel=\"nofollow noreferrer\"><code>std::size_t</code></a>.</p></li>\n<li><p>In both <code>push()</code> and <code>pop()</code>, you'll need to <code>return</code> if the stack is full or empty respectively. Otherwise, the function will continue to execute, defeating the purpose of the check.</p></li>\n<li><p><code>print()</code>:</p>\n\n<pre><code>// no data members are being modified,\n// so make this const\nvoid print() const\n{\n // could just be initialized\n // the asterisk is commonly\n // put next to the type in C++\n node* temp = top;\n\n while (temp)\n {\n cout << temp-> data << \",\";\n temp = temp->next;\n }\n}\n</code></pre></li>\n<li><p><strong>Watch out:</strong></p>\n\n<pre><code>StackusingList *sl = new StackusingList(5);\n</code></pre>\n\n<p>You do not call <code>delete</code> with this <code>new</code>, thereby causing a <strong>memory leak</strong>! <em>Always call</em> <code>delete</code> <em>properly with every</em> <code>new</code>.</p>\n\n<p>At the end of <code>main()</code> before the <code>return</code>:</p>\n\n<pre><code>delete s1;\n</code></pre>\n\n<p>Beyond that, you really don't need to use <code>new</code> here. It's only necessary with the nodes, which you're already doing. It's best to just avoid manual allocation/deallocation as much as possible.</p></li>\n<li><p><code>stackData</code> isn't used anywhere (and doesn't have a clear meaning), so just remove it.</p></li>\n<li><p>You're missing a few useful <code>public</code> member functions:</p>\n\n<pre><code>std::size_t size() const { return count; } // put into header\n</code></pre>\n\n<p></p>\n\n<pre><code>bool empty() const { return count == 0; } // put into header\n</code></pre>\n\n<p></p>\n\n<pre><code>template <typename T>\nT StackusingList<T>::top() const { return top->data; }\n</code></pre></li>\n<li><p><strong>There is no destructor!</strong> You're allocating <code>new</code> nodes, so you have to define the destructor to properly <code>delete</code> them:</p>\n\n<pre><code>StackusingList::~StackusingList()\n{\n node* current = top;\n\n while (current)\n {\n node* next = current->next;\n delete current;\n current = next;\n }\n\n top = NULL;\n}\n</code></pre>\n\n<p>With the destructor defined, you'll need to satisfy <a href=\"https://stackoverflow.com/questions/4172722/what-is-the-rule-of-three\">The Rule of Three</a>. This is also important because the default copy constructor and assignment operator will perform a <em>shallow</em> copy of <code>top</code>. This means that the pointer <em>itself</em> will be copied instead of just the <em>data</em> at that pointer. This will cause problems if you try to copy list objects or initialize new ones with existing ones.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-16T19:24:29.363",
"Id": "197908",
"Score": "0",
"body": "@Jamal quick question why you hide the node in the private class ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2015-10-16T20:42:02.977",
"Id": "197936",
"Score": "0",
"body": "@Lamour: It's because it shouldn't be exposed to the public interface."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2013-10-24T21:12:39.280",
"Id": "33198",
"ParentId": "33195",
"Score": "10"
}
},
{
"body": "<blockquote>\n <p>I'm just curious to know if this is a good way of doing it?</p>\n</blockquote>\n\n<p>No.</p>\n\n<blockquote>\n <p>Any suggestions are welcome.</p>\n</blockquote>\n\n<p>Hold On.</p>\n\n<blockquote>\n <p>Can we keep track of the number of elements in the stack using a count variable as used in the code?</p>\n</blockquote>\n\n<p>Yep.</p>\n\n<p>Basically your memory management is broken.<br>\nWhen you push elements on you create them with <code>new</code> and when you pop elements off you delete them. But what happens when the stack object goes out of scope? Anything still left in the stack is now leaked.</p>\n\n<p>Also the use of a maximum count in the constructor suggests that you should be allocating a single piece of storage once on construction to store all the values. The point of using a linked list is to allow the list to grow dynamically. It would be a better idea to just create a storage area and keep track of how full it is (if you are allowed to use std::vector in your assignment this does all the hard work for you).</p>\n\n<p>From this:</p>\n\n<pre><code>int main(int argc, char** argv) { \n StackusingList *sl = new StackusingList(5);\n</code></pre>\n\n<p>One assumes you have a Java background.<br>\nIf you don't need your object to live beyond the time span of the function then you don't need use new. What you need is just create a local object.</p>\n\n<pre><code>int main(int argc, char** argv) { \n StackusingList sl(5);\n</code></pre>\n\n<p>This variable is created locally. It is destroyed when the function terminates. If you had written it correctly the destructor would then clean up any internal memory it had allocated.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-26T19:00:28.453",
"Id": "33298",
"ParentId": "33195",
"Score": "4"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T19:59:24.810",
"Id": "33195",
"Score": "14",
"Tags": [
"c++",
"linked-list",
"stack"
],
"Title": "Stack implementation using linked list"
}
|
33195
|
<p>I've written some XSLT where I want to assign values to some variables.</p>
<p>Depending on whether or not a condition is met, I want the variable to be populated with a computed value and I want it to have a default value otherwise.</p>
<p>I've written the following code that appears to work, but I think that there may be a better way.</p>
<pre><code><xsl:variable name='HasValue' select='count($Catalog/lookup) &gt; 0' />
<xsl:variable name='Product' >
<xsl:choose><xsl:when test='$HasValue'>
<xsl:value-of select='$Catalog/lookup/Product' />
</xsl:when><xsl:otherwise>UNK</xsl:otherwise></xsl:choose>
</xsl:variable>
<xsl:variable name='Area' >
<xsl:choose><xsl:when test='$HasValue'>
<xsl:value-of select='$Catalog/lookup/Area' />
</xsl:when><xsl:otherwise>UNK</xsl:otherwise></xsl:choose>
</xsl:variable>
</code></pre>
<p>Yes, my XSLT processor uses XSLT 2.0</p>
|
[] |
[
{
"body": "<p>IMHO your code is fine. The \"problem\" with XSLT variables is that they are NOT variables but more resemble constants: once set they cannot be changed anymore. Also, their scope is restricted to anything that follows their definition until the closing tag. In particular they are NOT visible in any ancestor tag. The combination of both results in the type of constructs that you have used above.</p>\n\n<p>What is most disturbing is the fact that you usually have to repeat the testing of the criterion again and again if several variables depend on the same criterion. Again there's nothing generic that you can do about this, but of course, you can always at least create another variable holding the result of the test and then use that several times.</p>\n\n<p>Depending on the context of your XSLT I would suggest two alternatives which may or may not be more elegant:</p>\n\n<p>a) works in XSLT 1.0 and 2.0: If you just define the variables to be used as parameters to a template-call consider writing the template-call twice once in the <code>when</code> as once in the <code>otherwise</code> portion. This way you will end up with just one <code><choose></code>.</p>\n\n<p>b) Works only well in XSLT 2.0 (or a little awkward in XSLT with node-set extensions): move the check of the criterion and the selection of the definition values into a template and return the \"set\" of values to the assigned in a node-set. In a way you can regard this node-set as a record whose attributes have been set according to the criterion. See example below.</p>\n\n<pre><code><?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<xsl:stylesheet \n version=\"1.0\"\n xmlns:xsl=\"http://www.w3.org/1999/XSL/Transform\">\n <xsl:output method=\"xml\" version=\"1.0\" encoding=\"UTF-8\" indent=\"yes\" />\n\n <xsl:template name=\"get_values\">\n <xsl:param name=\"catalog\"/>\n\n <xsl:choose>\n\n <xsl:when test=\"count($catalog/lookup) &gt; 0\">\n <PRODUCT VALUE=\"{$catalog/lookup/Product}\"/>\n <AREA VALUE=\"{$catalog/lookup/Area}\"/>\n </xsl:when>\n\n <xsl:otherwise>\n <PRODUCT VALUE=\"UNK\"/>\n <AREA VALUE=\"UNK\"/> \n </xsl:otherwise>\n\n </xsl:choose>\n\n </xsl:template>\n\n <xsl:template match=\"/\">\n\n <xsl:variable name=\"Catalog\" select=\".\"/>\n\n <xsl:variable name=\"my_config\">\n <xsl:call-template name=\"get_values\">\n <xsl:with-param name=\"catalog\" select=\"$Catalog\"/>\n </xsl:call-template>\n </xsl:variable>\n\n <xsl:message>\n The value of PRODUCT is <xsl:value-of select=\"$my_config/PRODUCT/@VALUE\"/> \n and the value of AREA is <xsl:value-of select=\"$my_config/AREA/@VALUE\"/> \n </xsl:message>\n\n </xsl:template>\n\n</xsl:stylesheet>\n</code></pre>\n\n<p>This solution is definitely not shorter than yours but it resembles more other standard programming languages. The record type approach may come in especially handy if you have a lot of templates requiring the attributes in the record.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-01T16:18:28.250",
"Id": "53921",
"Score": "0",
"body": "Would `<xsl:apply-templates select=\"$my_config\" />` work? If so, then `<xsl:message>` can be simplified."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-02T01:38:40.660",
"Id": "53950",
"Score": "0",
"body": "Yes, you can pass `$my_config` to `apply-templates`. My code above is just supposed to show that the dynamically built XML tree works just as though it were coming from the input file. So, basically there's no difference."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-01T01:50:24.433",
"Id": "33631",
"ParentId": "33200",
"Score": "4"
}
},
{
"body": "<p>Since you're using XSLT 2.0, you can use an <code>if</code> statement and drop the <code>xsl:choose</code> entirely. This will be more efficient because the processor won't need to create a new tree. It is also much less code...</p>\n\n<pre><code><xsl:variable name=\"HasValue\" select=\"count($Catalog/lookup) &gt; 0\" />\n<xsl:variable name=\"Product\" select=\"if ($HasValue) then $Catalog/lookup/Product else 'UNK'\"/>\n<xsl:variable name=\"Area\" select=\"if ($HasValue) then $Catalog/lookup/Area else 'UNK'\"/>\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-05T23:26:51.930",
"Id": "215288",
"Score": "0",
"body": "Welcome to Code Review! Good job on your first answer."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2016-01-05T23:20:41.477",
"Id": "115952",
"ParentId": "33200",
"Score": "2"
}
}
] |
{
"AcceptedAnswerId": "33631",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-24T22:39:49.590",
"Id": "33200",
"Score": "3",
"Tags": [
"xml",
"xslt"
],
"Title": "Conditional assignment in XSLT?"
}
|
33200
|
<p>I have created a Job Scheduler, and i want some review, new ideas for it.</p>
<p><strong>Scheduler.cs</strong></p>
<pre><code>public abstract class Scheduler
{
#region Fields && Properties
private readonly List<Job> _jobs = new List<Job>();
private readonly Random _rand = new Random();
private Job _currentlyExecutingJob;
private Thread _workingThread;
public bool? Parallel { get; private set; }
public DateTimeOffset NextExecutionTime { get; private set; }
public string ID { get; set; }
public abstract Task JobTrigger(Job job);
public abstract void UnobservedException(Exception exception, Job job);
#endregion
#region Ctor
protected Scheduler(bool parallel) { Parallel = parallel; }
#endregion
#region Methods
public void Start()
{
if (!Equals(_workingThread, null)) return;
_workingThread = new Thread(ReviewJobs);
_workingThread.Start();
}
public void Stop()
{
if (Equals(_workingThread, null)) return;
_workingThread.Abort();
_workingThread = null;
}
private void ReviewJobs()
{
while (!Equals(_workingThread, null)) {
IEnumerable<Job> jobsToExecute = from job in _jobs
where job.NextExecutionTime <= DateTimeOffset.Now
orderby job.Priority
select job;
if (!jobsToExecute.Any()) {
Thread.Sleep(100);
continue;
}
try {
foreach (Job job in jobsToExecute) {
Job o = _currentlyExecutingJob = job;
if (Parallel != null && (bool)Parallel) {
JobTrigger(o);
} else {
JobTrigger(o).Wait();
}
if (!o.Repeat)
_jobs.Remove(o);
else if (o.Interval != null)
o.NextExecutionTime = DateTimeOffset.Now.Add((TimeSpan)(o.RandomizeExecution
? TimeSpan.FromSeconds(_rand.Next((int)((TimeSpan)o.Interval).TotalSeconds, ((int)((TimeSpan)o.Interval).TotalSeconds + 30)))
: o.Interval));
}
} catch (Exception exception) {
UnobservedException(exception, _currentlyExecutingJob);
} finally {
NextExecutionTime = (from job in _jobs
where job.NextExecutionTime <= DateTimeOffset.Now
orderby job.Priority
select job.NextExecutionTime).FirstOrDefault();
}
}
}
#endregion
#region Helper Methods
public Job GetJob(string id) { return _jobs.Find(job => job.ID == id); }
public Job GetJob(Job job) { return _jobs.Find(x => x == job); }
public Job GetJob<T>(Job<T> job) { return _jobs.Find(x => x == job); }
public IEnumerable<Job> GetAllJobs() { return _jobs; }
public void RemoveJob(string id)
{
Job existingJob = GetJob(id);
if (null != existingJob)
{
_jobs.Remove(existingJob);
}
}
public void RemoveJob(Job job)
{
Job existingJob = GetJob(job);
if (null != existingJob)
{
_jobs.Remove(existingJob);
}
}
public void RemoveAllJobs() { _jobs.RemoveRange(0, _jobs.Count); }
#endregion
}
</code></pre>
<p><strong>Job.cs</strong></p>
<pre><code>public class Job
{
public string ID { get; set; }
public TimeSpan Interval { get; private set; }
public DateTimeOffset NextExecutionTime { get; set; }
public int Priority { get; set; }
public bool Repeat { get; private set; }
public bool RandomizeExecution { get; set; }
public object Data { get; set; }
#region Fluent
public Job RunOnceAt(DateTimeOffset executionTime)
{
NextExecutionTime = executionTime;
Repeat = false;
return this;
}
public Job RepeatFrom(DateTimeOffset executionTime, TimeSpan interval)
{
NextExecutionTime = executionTime;
Interval = interval;
Repeat = true;
return this;
}
#endregion
}
</code></pre>
<p><strong>Usage</strong>:</p>
<pre><code>public class SchedulerUsage : Scheduler
{
public SchedulerUsage(bool parallel) : base(parallel) {
}
public override async Task JobTrigger(Job job)
{
switch (job.ID) {
//Handle Jobs
}
}
public override void UnobservedException(Exception exception, Job job)
{
//Handle Exceptions
}
/// <summary>
/// Example of adding job
/// </summary>
public void ExampleUsage()
{
Job job = new Job
{
ID = "ID",
Data = "ATTACH SOME DATA"
}.RunOnceAt(DateTimeOffset.Now.AddSeconds(7));
//Add the job... [HERE IS WHAT I WANT TO ACHIVE]
/*await*/base.AddJob(job);
//Start the scheduler...
base.Start();
}
}
</code></pre>
<p>Also Please i want to know how could i use Async/Await to wait for a job to finish executing ?. [VERY IMPORTANT]</p>
|
[
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T11:47:56.813",
"Id": "53217",
"Score": "0",
"body": "“I want to know how could i use Async/Await to wait for a job to finish executing?” This is not the right place to ask that, this site is for reviews of your code only."
}
] |
[
{
"body": "<ol>\n<li>Using <code>Equals(object, null)</code> to test whether an object is null is rather unusual. I can't see any reason in your case why it would be preferred over <code>object == null</code>.</li>\n<li>Why is <code>Parallel</code> a nullable bool? I can't see any code which relies of the tri-state nature. If you insist on keeping it then a more concise way of checking it for true is <code>if (Parallel == true)</code> which will only evaluate to true if it is not null and true.</li>\n<li><code>Parallel</code> is not a good name for a boolean flag. <code>RunJobsInParallel</code> is a bit longer but makes it much more clear what the flag is doing.</li>\n<li><a href=\"https://stackoverflow.com/questions/1559255/whats-wrong-with-using-thread-abort\">Calling <code>Abort()</code> to terminate a thread is nasty</a>. Use a flag which the main scheduler methods checks at convenient points in order to exit early. Use <code>Join</code> with a timeout to wait for the worker thread.</li>\n<li><code>_jobs</code> is not thread safe. You iterate over it in <code>ReviewJobs</code> on the worker thread and you have public remove methods which could be called from a different thread to remove jobs from the list. This is waiting for an exception to happen (\"collection was modified during enumeration\").</li>\n<li>Actually upon reading your code more carefully: <code>jobsToExecute</code> is an <code>IEnumerable</code> and because it's built by a LINQ statement this means you \"only\" have a set of nested enumerators which iterate over the original <code>_jobs</code> collection when you do your <code>foreach</code>. This means your code should fail when you call <code>_jobs.Remove()</code> inside that loop. <code>jobsToExecute</code> needs to be built with <code>ToList()</code> or <code>ToArray()</code> to create a independent copy.</li>\n<li><p>If you want to wait for specific jobs to finish then you can put a <code>ManualResetEvent</code> on the <code>Job</code> class. This should be set by whoever executes the job once it is finished. Expose a <code>WaitAsync()</code> method on the <code>Job</code> class to wait on the event. Something along these lines:</p>\n\n<pre><code>public class Job\n{\n ...\n private ManualResetEventSlim _JobDone = new ManualResetEventSlim(false);\n\n public void ProcessingStarted()\n {\n _JobDone.Reset();\n }\n\n public void ProcessingDone()\n {\n _JobDone.Set();\n }\n\n public async Task WaitAsync()\n {\n await Task.Run(() => _JobDone.WaitOne());\n }\n}\n</code></pre>\n\n<p><code>JobTrigger</code> should do something along these lines:</p>\n\n<pre><code>job.ProcessingStarted();\n... // process job\njob.ProcessingDone();\n</code></pre>\n\n<p>Then something can wait on the job. As mentioned by svick the above code might not scale well if you have many jobs to wait on. Try StackOverflow if you need help solving this specific problem.</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T03:31:01.500",
"Id": "53204",
"Score": "0",
"body": "Sorry can you specify the 6 point in code, also will this enable me to use Async/Await ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T07:32:00.473",
"Id": "53211",
"Score": "0",
"body": "@RuneS: Expanded the answer"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T11:52:42.437",
"Id": "53218",
"Score": "0",
"body": "There is a reason why the error you mentioned in #6 doesn't happen: `orderby` doesn't stream its results; once you request the first item, it will iterate the whole source collection. But I wouldn't rely on this and I agree with the suggestion to use `ToList()`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T11:55:33.940",
"Id": "53219",
"Score": "1",
"body": "Also, your implementation of #7 is not very good. You're wasting a thread waiting for `_JobDone` for no good reason. A better solution would be to use `TaskCompletionSource`."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T15:45:31.430",
"Id": "53231",
"Score": "0",
"body": "@svick : can you illustrate this particular point in code ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T16:08:38.557",
"Id": "53233",
"Score": "0",
"body": "@ChrisWue : i can't understand the point of WaitAsync method you came up with... can you please be more clear ?"
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T16:09:16.557",
"Id": "53234",
"Score": "0",
"body": "Also if you look at topic above (the usage part) you will see how i want the await feature to be implemented."
},
{
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T18:10:53.317",
"Id": "53245",
"Score": "0",
"body": "For #4, the recommended means of stopping asynchronous execution is done through [CancellationToken](http://msdn.microsoft.com/en-us/library/system.threading.cancellationtoken.aspx) and [CancellationTokenSource](http://msdn.microsoft.com/en-us/library/system.threading.cancellationtokensource.aspx). In fact, Task.Run even has an [overload](http://msdn.microsoft.com/en-us/library/hh160373.aspx) which takes in a token :)"
}
],
"meta_data": {
"CommentCount": "8",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T02:56:22.650",
"Id": "33211",
"ParentId": "33207",
"Score": "5"
}
}
] |
{
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T01:06:12.167",
"Id": "33207",
"Score": "1",
"Tags": [
"c#"
],
"Title": "Job Scheduler Implementation"
}
|
33207
|
<p>This is a program that I wrote to add two numbers together that are too large for the C language to store. It stores the numbers as strings instead and processes one digit at a time. But I suspect that the program could be done in fewer steps. In what ways can I reduce the size of my program? Where am I taking more steps than necessary?</p>
<pre><code>#include <stdio.h>
#include <string.h>
int main()
{
char *a = "1490438498359508";
char *b = "1575390843059845";
char *sum = "";
char str[15] = "";
char src[512];
int carry = 0;
int alength = strlen(a);
int blength = strlen(b);
int n;
int i;
int c, d;
for (n=1; n<blength+1; n++) {
int c=0, d=0;
i = 0;
c = a[alength-n]-48;
d = b[blength-n]-48;
i = c+d;
if (carry == 1) {
i=i+1;
}
if (i > 9) {
i = i-10;
carry=1;
} else {
carry=0;
}
int aInt = i;
char str[15] = "";
sprintf(str, "%d", aInt);
strcat(src, str);
}
int nlength = strlen(src);
int x;
for (x=0; x<nlength+1; x++) {
printf("%c", src[nlength-x]);
}
printf("\n");
return 0;
}
</code></pre>
|
[] |
[
{
"body": "<p>1) It seems that you assumed length of <code>a</code> and <code>b</code> are the same. But if <code>a</code> has a bigger length than <code>b</code> you don't process all digits! Your loop should go over maximum of lengths of <code>a</code> and <code>b</code> and whenever one operand has no digit any more, use 0.</p>\n\n<p>2) You can write these lines</p>\n\n<pre><code>i = c+d;\nif (carry == 1) {\n i=i+1;\n}\n</code></pre>\n\n<p>like this:</p>\n\n<pre><code>i = c + d + carry\n</code></pre>\n\n<p>use arithmetic operations when branches are not necessary.</p>\n\n<p>3) The result of addition has always at most one digit more than the bigger operand. So you can allocate a string once and avoid concatenation in each iteration (just put the result digit in its right place).</p>\n\n<p>4) You can reduce number of iterations by using the fact that you can add in higher bases! This way instead of a string, use an integer array and treat the\noperands, say in base 10000. Now each digit in this base is a 4 digit number in base 10. Everything will be the same, except for setting the value of carry.\nWith base 10^4, you reduced number of iteration to one-forth. You can go further till where integer range supports safely (10^8).</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T02:41:04.480",
"Id": "33210",
"ParentId": "33208",
"Score": "2"
}
},
{
"body": "<h3>Big Picture</h3>\n\n<ul>\n<li><strong>Function:</strong> This code ought to be packaged into a function, not just in <code>main()</code>. I propose <code>char *add(const char *a, const char *b)</code>.</li>\n<li><strong>Bug:</strong> You assume that <code>a</code> and <code>b</code> are the same length. If that turns out not to be the case, then you'll either ignore the most significant digits of <code>a</code> (wrong answer) or access the bytes preceding the beginning of <code>a</code> (garbage answer or crash).</li>\n<li><strong>Carrying:</strong> You ignore the carry bit at the end of the loop.</li>\n<li><strong>Buffers:</strong> You allocated 15-byte and 512-byte buffers. Why those lengths? You should assume that an attacker will try to overflow your buffers with ridiculously long input, regardless of how large you make your fixed-size buffers.</li>\n</ul>\n\n<h3>Variables</h3>\n\n<ul>\n<li><p><strong>Unused and redeclared variables:</strong> Compiling with warnings turned on (I used <code>clang -Wall -o add add.c</code>…</p>\n\n<blockquote>\n<pre><code>add.c:8:11: warning: unused variable 'sum' [-Wunused-variable]\n char *sum = \"\";\n ^\nadd.c:9:10: warning: unused variable 'str' [-Wunused-variable]\n char str[15] = \"\";\n ^\nadd.c:16:9: warning: unused variable 'c' [-Wunused-variable]\n int c, d;\n ^\nadd.c:16:12: warning: unused variable 'd' [-Wunused-variable]\n int c, d;\n ^\n4 warnings generated.\n</code></pre>\n</blockquote>\n\n<p>Redeclaring <code>str</code>, <code>c</code>, and <code>d</code> is pretty sloppy. Fortunately it didn't cause a bug. You want to avoid a giant block of declarations, and declare the variables as close as possible to the point of use.</p></li>\n</ul>\n\n<h3>Mechanics</h3>\n\n<ul>\n<li><strong>Magic numbers:</strong> What's <code>48</code>? For clarity, write <code>'0'</code> instead.</li>\n<li><strong>int → char:</strong> Calling <code>sprintf()</code> seems like overkill — why not use the inverse technique and add <code>'0'</code>? If you wanted to use <code>sprintf()</code>, though, you could do without <code>aInt</code> (just use <code>i</code>) and <code>str</code> and <code>strcat()</code> (just <code>sprintf()</code> to the end of <code>src</code>).</li>\n<li><strong>Initialization:</strong> In the loop, there's no need to set <code>c</code>, <code>d</code>, and <code>i</code> to 0, when you're going to assign the useful values right away anyway. (The harm is just to the verbosity of your code. The compiler can optimize these assignments away for you.)</li>\n<li><strong>Avoid conditionals:</strong> In the loop, if if-else are unnecessary.</li>\n</ul>\n\n<p>Cleaning up the loop using the remarks above…</p>\n\n<pre><code>char *srcEnd = src;\nfor (int n = 1; n <= blength; n++) {\n int c = a[alength - n] - '0',\n d = b[blength - n] - '0';\n int i = c + d + carry;\n carry = i / 10;\n i = i % 10;\n\n *srcEnd++ = (char)(i + '0');\n}\nif (carry) {\n *srcEnd++ = (char)(carry + '0');\n}\n*srcEnd = '\\0';\n</code></pre>\n\n<p>There's more work necessary to fix the same-length assumption, but I'll leave that as an exercise.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-11-21T09:19:01.020",
"Id": "35819",
"ParentId": "33208",
"Score": "1"
}
}
] |
{
"AcceptedAnswerId": "35819",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 3.0",
"CreationDate": "2013-10-25T01:36:56.497",
"Id": "33208",
"Score": "1",
"Tags": [
"c",
"mathematics"
],
"Title": "Reducing steps for long addition program"
}
|
33208
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.