body stringlengths 25 86.7k | comments list | answers list | meta_data dict | question_id stringlengths 1 6 |
|---|---|---|---|---|
<p>I want to have a function that checks to see if a certain resource (deployment, job, cronjob etc) exist in a namespace. Using the Kubernetes Python client, I can create a boolean function (using deployments as a concrete example).</p>
<pre><code>from kubernetes import client, config
def deployment_exists(name, namespace="default"):
config.load_kube_config()
client = client.AppsV1Api()
try:
client.read_namespaced_deployment(name, namespace)
return True
except ApiException as e:
if e.status == 404:
return False
return False
</code></pre>
<p>Is there a way to achieve the same without relying on the <code>ApiException</code> explicitly?</p>
| [] | [
{
"body": "<p>Without knowing more about the <code>kubernetes</code> API that's hard to say, maybe you'd be more lucky on StackOverflow instead.</p>\n\n<p>That said, if there's no explicit function to check, probably not.</p>\n\n<p>Especially the status code 404 sounds like it would probably mean \"not present\", so this doesn't seem overly bad actually.</p>\n\n<hr>\n\n<p>Is it intentional that all other <code>ApiException</code>s also return <code>false</code>? If so, than there's no point to check for the 404. If not, they should be thrown again.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-21T20:27:03.430",
"Id": "226591",
"ParentId": "213355",
"Score": "3"
}
},
{
"body": "<p>You can list all the deployments (in a <a href=\"https://jashandeep-sohik8s-python.readthedocs.io/en/stable/kubernetes.client.apis.html#kubernetes.client.apis.apps_v1beta1_api.AppsV1beta1Api.list_namespaced_deployment\" rel=\"nofollow noreferrer\">namespaced</a> or <a href=\"https://jashandeep-sohik8s-python.readthedocs.io/en/stable/kubernetes.client.apis.html#kubernetes.client.apis.apps_v1beta1_api.AppsV1beta1Api.list_namespaced_deployment\" rel=\"nofollow noreferrer\">non-namespaced</a>) then search for the deployment name in that list:</p>\n<pre><code>import yaml\nimport logging\n \nfrom kubernetes import client, config\n \n \ndef _deployment_exists(namespace, deployment_name):\n config.load_kube_config()\n v1 = client.AppsV1Api()\n resp = v1.list_namespaced_deployment(namespace=namespace)\n for i in resp.items:\n if i.metadata.name == deployment_name:\n return True\n return False\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-06-04T18:53:43.170",
"Id": "262644",
"ParentId": "213355",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T06:10:43.820",
"Id": "213355",
"Score": "8",
"Tags": [
"python",
"error-handling",
"exception"
],
"Title": "See if a specific resource exists in a Kubernetes namespace"
} | 213355 |
<p>I did a <a href="https://en.wikipedia.org/wiki/Goldbach%27s_conjecture" rel="nofollow noreferrer">Goldbach's Conjecture</a> exercise and got it to work. It's pretty slow though and I was wondering how I could optimize it.</p>
<pre><code>number = int(input("Enter your number >> "))
print("\nCalculating...")
if number % 2 == 0: #Only even numbers
primes = primenums(number) #returns all prime numbers <= input number
addend1 = primes[0]
addend2 = primes[0]
while addend1 + addend2 != number:
if primes[-1] == addend2:
addend2 = primes[primes.index(addend1) + 1]
addend1 = primes[primes.index(addend1) + 1]
else:
addend2 = primes[primes.index(addend2) + 1]
</code></pre>
<p>Right now, up to 10,000 the algorithm is pretty fast, but at 100,000 it takes about 3 seconds to finish. Is that just how it is or could I make it faster?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T08:23:14.533",
"Id": "412715",
"Score": "7",
"body": "Have you profiled this? How is `primenums` implemented?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T13:46:29.243",
"Id": "412751",
"Score": "1",
"body": "Profiled? What do you mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T13:47:21.937",
"Id": "412752",
"Score": "1",
"body": "It is a debugging technique that tells you how much time is spent in which part of your code: https://docs.python.org/3/library/debug.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T14:03:48.797",
"Id": "412758",
"Score": "0",
"body": "Sorry for that, I'm a new programmer and didn't know what profiling is!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T17:23:19.287",
"Id": "412806",
"Score": "1",
"body": "The first problem is that you're trying to get speed out of arithmetic in Python; that's a losing proposition. Python has many strengths, and speed of basic arithmetic is not one of them. Running your code in an optimizing Python runtime will help considerably, but if you have heavy-duty computations to perform, picking a language that compiles arithmetic down closer to the metal will help enormously."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T18:10:25.240",
"Id": "412811",
"Score": "7",
"body": "@EricLippert Don't worry about language/compiler/interpreter optimization before you do mathematical/complexity optimization first. Switching languages can only improve performance by a small factor (1-10). Changing the algorithm can give speedups of 1-infinity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T18:11:26.610",
"Id": "412812",
"Score": "0",
"body": "@Vortico: Of course; if there are algorithmic wins here then take them. But if the problem comes down to \"addition and equality is too slow\" then algorithmic wins are no longer going to help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T19:57:11.467",
"Id": "412829",
"Score": "2",
"body": "@Vortico are you seriously lecturing _Eric Lippert_ on performance gains and optimization?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T20:31:17.500",
"Id": "412835",
"Score": "9",
"body": "@MikeTheLiar I know he knows, but someone reading his comment may be misled. It's bad advice to recommend to a programming beginner to change the tool he's learning before even pointing out the issue with his algorithm. It's discouraging, doesn't solve the problem at hand (because maybe his goal is to simply learn Python, and remember this is a *code review* community), and doesn't teach how to think on one's own. It's not \"The first problem\" with his code as he said. It's the 26th or maybe 126th problem he should worry about while playing around with Goldbach's conjecture."
}
] | [
{
"body": "<p>One thing that makes your code slow is your repeated calls to <code>primes.index</code>. Each of these calls needs to linearly scan <code>primes</code> until it finds the value you are looking for, making this <span class=\"math-container\">\\$\\mathcal{O}(n)\\$</span>. This is especially bad in the first <code>if</code> case since you do this twice with exactly the same argument. Instead just keep the index around in addition to the number:</p>\n\n<pre><code>def goldbach_keep_index(number):\n if number % 2 == 1: #Only even numbers\n raise ValueError(\"Goldbach conjecture is only defined for even numbers\")\n primes = primenums(number) #returns all prime numbers <= input number\n i, j = 0, 0\n addend1 = primes[i]\n addend2 = primes[j]\n\n while addend1 + addend2 != number:\n if addend2 == primes[-1]:\n i = j = i + 1\n addend2 = primes[i]\n addend1 = primes[i]\n else:\n j += 1\n addend2 = primes[j]\n return addend1, addend2\n</code></pre>\n\n<p>Note that I made this a function, so you can reuse it.</p>\n\n<p>Your main calling code could look like this:</p>\n\n<pre><code>if __name__ == \"__main__\":\n number = int(input(\"Enter your number >> \"))\n p1, p2 = goldbach_keep_index(number)\n print(f\"{p1} + {p2} = {number}\")\n</code></pre>\n\n<hr>\n\n<p>However, what you are really doing is taking all combinations of prime numbers, without repeating yourself. So just use <a href=\"https://docs.python.org/3/library/itertools.html#itertools.combinations_with_replacement\" rel=\"noreferrer\"><code>itertools.combinations_with_replacement</code></a>:</p>\n\n<pre><code>from itertools import combinations_with_replacement\n\ndef goldbach_combinations(number):\n if number % 2 == 0:\n raise ValueError(\"Goldbach conjecture is only defined for even numbers\")\n primes = primenums(number)\n for addend1, addend2 in combinations_with_replacement(primes, 2):\n if addend1 + addend2 == number:\n return addend1, addend2\n raise Exception(f\"Found a counter-example to the Goldbach conjecture: {number}\")\n</code></pre>\n\n<p>In this case <code>primes</code> does not even need to be a <code>list</code>, it can just be a generator.</p>\n\n<hr>\n\n<p>If you instead make <code>primes</code> a <code>set</code>, you can easily implement the idea suggested by <a href=\"https://codereview.stackexchange.com/users/167190/josiah\">@Josiah</a> in <a href=\"https://codereview.stackexchange.com/a/213359/98493\">their answer</a> by just checking if <code>number - p</code> is in <code>primes</code>:</p>\n\n<pre><code>def goldbach_set(number):\n if number % 2 == 0: #Only even numbers\n raise ValueError(\"Goldbach conjecture is only defined for even numbers\")\n primes = set(primenums(number)) #returns all prime numbers <= input number\n for p in primes:\n k = number - p\n if k in primes:\n return p, k\n raise Exception(f\"Found a counter-example to the Goldbach conjecture: {number}\")\n</code></pre>\n\n<hr>\n\n<p>And now some timing comparisons, where <code>goldbach</code> is your code put into a function:</p>\n\n<pre><code>def goldbach(number):\n if number % 2 == 0: #Only even numbers\n raise ValueError(\"Goldbach conjecture is only defined for even numbers\")\n primes = primenums(number) #returns all prime numbers <= input number\n addend1 = primes[0]\n addend2 = primes[0]\n\n while addend1 + addend2 != number:\n if primes[-1] == addend2:\n addend2 = primes[primes.index(addend1) + 1]\n addend1 = primes[primes.index(addend1) + 1]\n else:\n addend2 = primes[primes.index(addend2) + 1]\n return addend1, addend2\n</code></pre>\n\n<p>And <code>primenums</code> is a simple sieve:</p>\n\n<pre><code>def prime_sieve(limit):\n prime = [True] * limit\n prime[0] = prime[1] = False\n\n for i, is_prime in enumerate(prime):\n if is_prime:\n yield i\n for n in range(i * i, limit, i):\n prime[n] = False\n\ndef primenums(limit):\n return list(prime_sieve(limit))\n</code></pre>\n\n<p><a href=\"https://i.stack.imgur.com/vYS27.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/vYS27.png\" alt=\"enter image description here\"></a></p>\n\n<p>And when pulling the generation of the primes outside of the function (and calculating them up to the largest number in the plot):</p>\n\n<p><a href=\"https://i.stack.imgur.com/OHGFk.png\" rel=\"noreferrer\"><img src=\"https://i.stack.imgur.com/OHGFk.png\" alt=\"enter image description here\"></a></p>\n\n<p>Of course the first three functions are vastly slower than the <code>set</code> because they need to go through more combinations now. However, all functions are then constant time, so the increase in time comes solely from the fact that you have to consider more primes.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T12:06:43.457",
"Id": "412912",
"Score": "0",
"body": "I'm intrigued by the last graph. There is an obvious oscillating pattern where there's a sudden drop in run time even when the size of the input increases. I wonder what's going in there"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T20:35:54.000",
"Id": "412956",
"Score": "1",
"body": "I wondered that. My guess is fixed probe numbers are used, and some happen to have a larger small addend needed to satisfy the conjecture, so they take more loop iterations."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T08:05:27.967",
"Id": "412988",
"Score": "0",
"body": "@Josiah: That is indeed what I did (`x = np.logspace(1, 5, dtype=int); x[x % 2 == 1] += 1`). And while larger numbers indeed tend to have more pairs of prime numbers that sum to them, there is quite a lot of variation: https://en.wikipedia.org/wiki/Goldbach%27s_conjecture#/media/File:Goldbach-1000000.png One might be able to argue that this rise is slightly visible above 10^4 in my plot for the first functions, but since the OP's code took too long I could no go up much higher in numbers..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T08:37:45.443",
"Id": "213358",
"ParentId": "213357",
"Score": "20"
}
},
{
"body": "<p>As suggested by Graipher in the comment, you're probably spending a lot of time generating a list of primes. That would be worth profiling, but I can't speculate as to how it might be improved without at least seeing the code.</p>\n\n<p>There are two things that stand out to me as very clear performance sinks. </p>\n\n<p>The first, and easiest to change, is <code>index</code>. If you call <code>index</code> on a list, python has to check every element in the list one at a time to see whether it's the thing you're after. If you have millions of primes, every one of those index calls is secretly a hidden loop that runs millions of times. \nThe good news is you can resolve this easily enough: just keep another variable which stores where in the list of primes you're up to. Then you don't have to search for your place again every time you go round the loop, because you have a bookmark to it. </p>\n\n<p>Second, and slightly more subtle, is the way that this is looping. You are looking for two numbers that add up to a target. If your target is 100, you might first say \"what if it's 3?\" and then try all primes with 3. Then you say \"what if it's 5?\" and try all the primes with 5. And then you do the same with 7, and so on. This means your trying all the primes with all the primes. </p>\n\n<p>Instead, if you are checking whether the first prime is 3, you know that the second prime has to be 97. So all you have to do is check whether 97 is prime. If so, it's a match, if not, you can move on to checking 5 and 95, and then 7 and 93, and so on. In this way your algorithm checks each prime against one other number instead of each prime against all the others, and should be massively faster. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T14:03:10.577",
"Id": "412757",
"Score": "0",
"body": "Your second suggestion is great indeed. I will implement it that way! Thanks"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T17:10:01.750",
"Id": "412804",
"Score": "0",
"body": "You can make this even more efficient by keeping track of \"near misses\" to your target which eliminate other integers. Suppose you were testing 102. You start by looking for 3 + some prime. 99 isn't a prime, but the nearest prime >= 99 is 101, so if you organize the search carefully, you can remember that you just found a prime pair for 104 = 3 + 99 while looking for a pair for 102, and the next even number you need to test is not 104 but 106 (unless you already found a pair for that as well. of course)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T20:18:12.567",
"Id": "412833",
"Score": "0",
"body": "I would default to using a `set` as in @Graipher's implementation, which is very fast at discovering whether something is present, but does not tell you what the nearest miss was."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T20:25:00.873",
"Id": "412834",
"Score": "0",
"body": "If I had to use a regular `list`, and if the list was sorted, then there is indeed a clever trick available. The idea is that as the small prime being tested grows, the number it needs to be added to shrinks. That means that you can keep two bookmark variables pointing at the list of primes, one at the start and moving forwards, and one at the end and moving backwards. As long as sum is too small, you move the first bookmark along. If the sum is too big, you bring the second bookmark backwards. This avoids having to scan the whole list each time. However, it's quite fiddly to get right."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T08:44:29.410",
"Id": "213359",
"ParentId": "213357",
"Score": "10"
}
},
{
"body": "<p>Let's take n = 1,000,000,000 for example and see what your code does. </p>\n\n<p>It calculates all primes from 1 to 1 billion. That takes a while, but it gives you an array of all primes in sorted order. </p>\n\n<p>It then calculates 2 + 2, 2 + 3, 2 + 5, 2 + 7, 2 + 999,999,xxx to check if one of these numbers equals 1,000,000,000. But obviously when addend1 = 2, addend2 has to be 999,999,998 to add to one billion, so you are checking tens of millions of sums unnecessarily.</p>\n\n<p>It then calculates 3 + 3, 3 + 5, 3 + 7 etc., and again, addend2 would have to be 999,999,997 million. And then again for addend1 = 5, 7, 11 etc. So you are checking a huge number of sums needlessly. </p>\n\n<p>Start with addend1 = first prime, addend2 = last prime in your array. If their sum is too small, replace addend1 with the next prime to make the sum larger by the smallest possible amound. If their sum is too large, replace addend2 with the previous prime. If the sum is right, you have found a solution. And once you reached addend1 > addend2, you know there is no solution. This will be very quick, since usually you don't need to check too many values for addend1. </p>\n\n<p>That makes the search a lot quicker, but doesn't help with the sieve trying to find all the primes. You usually don't need all the primes, only a very small number. In the example with n = 1,000,000,000 you probably find two primes adding up to a billion with addend1 ≤ 1000 and addend2 ≥ 999,999,000. </p>\n\n<p>So here's what you do: To find all primes say in the range 999,999,000 to 1,000,000,000, you need to check if these numbers are divisible by any prime up to the square root of 1,000,000,000 which is a bit less than 32,000. So first you use a sieve to find all numbers up to 32,000. Then you create a sieve that finds all primes from 999,999,000 to 1,000,000,000. You run your search algorithm until it tries to examine primes that are not in this range. This likely doesn't happen, but if it happens, you create another sieve for the numbers 999,998,000 to 999,999,000 and so on. So instead of maybe 50 million primes, you look only for maybe 50 or 100. Again, that makes it a lot faster. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T05:52:22.533",
"Id": "412861",
"Score": "0",
"body": "I didnt learn about sieves yet, gotta look into it"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T07:54:15.617",
"Id": "412869",
"Score": "0",
"body": "It might be worth testing the primality of the larger number as you hit it, rather than sieving a whole range."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T23:57:00.050",
"Id": "213415",
"ParentId": "213357",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T08:17:00.923",
"Id": "213357",
"Score": "11",
"Tags": [
"python",
"performance"
],
"Title": "Goldbach's conjecture algorithm"
} | 213357 |
<p>So this question might be a bit opinion based but I am a bit confused, say i have these two code snippets -</p>
<pre><code>if (eventArgs != null && eventArgs is OnZoomEventArgs)
{
var zoomEventArgs = eventArgs as OnZoomEventArgs;
if (zoomEventArgs.focus != null)
{
var line = zoomEventArgs.focus.GetComponent<AssemblyLine>();
if (line != null)
{
SetLine(line);
} else
{
ResetLine();
}
}
else
{
ResetLine();
}
}
else
{
ResetLine();
}
</code></pre>
<p>and </p>
<pre><code>var zoomEventArgs_ = eventArgs as OnZoomEventArgs;
if(zoomEventArgs_.focus != null)
{
SetLine(zoomEventArgs_.focus.GetComponent<AssemblyLine>());
} else
{
ResetLine();
}
</code></pre>
<p>Which one is better in the sense of readability and in terms of performance maybe.
My question is should I instead check for null reference this many times or should I instead try to not pass a null reference. Is there any other way I can make these code snippets more readable.
I tried to replace </p>
<pre><code>if (line != null)
{
SetLine(line);
} else
{
ResetLine();
}
</code></pre>
<p>with ternaries but I cannot as both SetLine() and ResetLine() have void as return type.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T11:18:26.247",
"Id": "412735",
"Score": "0",
"body": "We need a description of the code and we also need to know that its purpose is. It's off-topic without this information and in its current form it is better suited for [Software Engineering](https://softwareengineering.stackexchange.com/)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T12:03:42.117",
"Id": "412739",
"Score": "0",
"body": "I am sorry, i thought this site would suit, next time i will keep that in mind."
}
] | [
{
"body": "<h2>The problem</h2>\n\n<p>Both examples you show have issues.</p>\n\n<p>Example 1 violates DRY. You have three instances of the same \"failure\" outcome (in this case <code>ResetLine()</code>). Imagine if the failure outcome requires multiple steps. Now imagine you need to change the failure logic. You'd have to make the same change three times, or you'd end up with unexpected behavior.</p>\n\n<p>Example 2 solves the DRY issue, but it actually fails to properly null check. If <code>zoomEventArgs_</code> is null, you're going to run into a null reference exception when you try to access <code>zoomEventArgs_.focus</code>. Note that the <code>as</code> conversion returns <code>null</code> when it cannot convert the object to the chosen type.</p>\n\n<p>There is an easy fix for this:</p>\n\n<pre><code>if(zoomEventArgs_?.focus != null)\n</code></pre>\n\n<p>Note the <code>?.</code> operator. It is the <a href=\"https://www.codeproject.com/Tips/900017/Null-Propagation-Operator-A-New-Feature-of-Csharp\" rel=\"nofollow noreferrer\">null propagation operator</a> that will prevent nullreferences from being thrown (and instead returns <code>null</code>). In other words, your <code>if</code> evaluation will be false if <em>either</em> <code>zoomEventArgs_</code> or <code>zoomEventArgs_.focus</code> is <code>null</code></p>\n\n<hr>\n\n<h2>The solution</h2>\n\n<p>The second example is closer to what you want, but it's not leveraging the best syntax. It can be cleaned up further, without introducing nesting:</p>\n\n<pre><code>if(eventArgs is OnZoomEventArgs zoomEventArgs && zoomEventArgs.focus != null)\n{\n SetLine(zoomEventArgs.focus.GetComponent<AssemblyLine>());\n} else\n{\n ResetLine();\n}\n</code></pre>\n\n<p><code>eventArgs is OnZoomEventArgs zoomEventArgs</code> will cast the object when it can (and return true), and will pass false if it cannot (thus directing you to the <code>else</code>). Notice that you are able to use this casted object immediately in the same evaluation (<code>zoomEventArgs.focus != null</code>).</p>\n\n<p>I also removed the <code>_</code> suffix as it does not conform to any convention I've ever heard of.</p>\n\n<hr>\n\n<h2>Your question</h2>\n\n<blockquote>\n <p>My question is should I instead check for null reference this many times?</p>\n</blockquote>\n\n<p>Should you check for nulls? Of course, it's part of the validation logic. But you should avoid writing individual failure clauses <em>when the failure logic remains the same in all cases</em>.</p>\n\n<blockquote>\n <p>should I instead try to not pass a null reference</p>\n</blockquote>\n\n<p>Never return null unless you intend to deal with it yourself.</p>\n\n<p>When you intentionally throw a null, you are required to handle the potential nulls being returned. This is the honeytrap of developers. It's very easy to \"just return null\" and not write any proper handling, but it simply shifts the problem towards the caller, who now has to deal with nulls.<br>\nDealing with nulls, as trivial as it may seem, requires the caller to know if and when nulls are being returned, and it burdens them with the task of dealing with it.</p>\n\n<p>Avoiding wanton null returning as a good practice is further confirmed by the coming update of C#8, where <a href=\"https://msdn.microsoft.com/en-us/magazine/mt829270.aspx\" rel=\"nofollow noreferrer\">nullable reference types</a> are added specifically to address this \"just return null\" behavior. The name is a bit confusing, what it actually does is that it makes all reference types non-nullable, unless you explictly allow them to be nullable. </p>\n\n<p>This is analogous to how you today can already choose to use <code>int</code> and <code>int?</code>, for example. This behavior is simply going to be extended to reference types.</p>\n\n<blockquote>\n <p>I tried to replace [...] with ternaries but I cannot as both SetLine() and ResetLine() have void as return type.</p>\n</blockquote>\n\n<p>Don't abuse ternaries as \"shorter ifs\". If you want to shorten the line count of your <code>if</code>, simply remove the braces (I'm not opposed to that, but this may clash with some style guides who enforce the use of brackets).</p>\n\n<p>Ternaries should only be used in cases where you are assigning a value and would end up with a needlessly bulky <code>if</code> block for what amounts to a simple assigning of a value.</p>\n\n<p>Note that ternaries do not improve code readability on non-trivially readable code. </p>\n\n<ul>\n<li><code>isActive ? \"active\" : \"inactive\"</code> is readable because it is <strong>simple</strong> (and using an <code>if</code> structure here would be needlessly bulky. </li>\n<li><code>(eventArgs is OnZoomEventArgs zoomEventArgs && zoomEventArgs.focus != null) ? \"passed\" : \"failed\"</code> is considerably less readable because it's no longer a trivially readable piece of logic.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T12:02:37.247",
"Id": "412738",
"Score": "0",
"body": "Thank you for your answer its really helpful."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T11:16:29.400",
"Id": "213368",
"ParentId": "213360",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "213368",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T09:03:37.323",
"Id": "213360",
"Score": "0",
"Tags": [
"c#",
"null"
],
"Title": "Checking For multiple null references"
} | 213360 |
<p>it's hard for me to <a href="https://codereview.stackexchange.com/questions/213301/word-chain-implementation">implement all those features that were suggested</a>, i did so many thing wrong.</p>
<p>can you please review this update on my code, concerning OOP, clean code, and maybe an eye on the algorithm used</p>
<p>What's note-worthy:
the code looks <strong>very more clear</strong> now, single responsibility seems to be corrected, no more brain killer...</p>
<h2>Main class</h2>
<p>skipping the wrapping class, just posting the <code>main</code> method</p>
<pre><code>public static void main( String[] args )
{
WordChainBuilder wordChainBuilder =
new WordChainBuilder("src/main/resources/words.txt");
Collection<String> goldChain = wordChainBuilder.build("gold", "lead");
System.out.println("chain: "+goldChain);
Collection<String> rubyChain = wordChainBuilder.build("ruby", "code");
System.out.println("chain: "+rubyChain);
}
</code></pre>
<h2>WordChainBuilder</h2>
<pre><code>class WordChainBuilder {
private final WordReader wordReader;
WordChainBuilder(String wordListFilename) {
wordReader = new WordReader(wordListFilename);
}
Collection<String> build(String start, String destiny) {
if (start == null || destiny == null || start.length() != destiny.length()) {
throw new IllegalArgumentException();
}
return build(new Node(start), new Node(destiny)).asStrings();
}
NodeList build(Node start, Node destiny) {
List<String> words = wordReader.readAllWordsWithLength(start.getLength());
WordList wordList = new WordList(words);
NodeList currentDepth = new NodeList(start);
while (!currentDepth.isEmpty()) {
NodeList nextDepth = new NodeList();
for (Node node : currentDepth.getNodes()) {
if(node.isDestiny(destiny)){
return buildChain(node);
}
NodeList candidates = findCandidates(node, wordList);
nextDepth.addAll(candidates);
}
wordList.removeAll(nextDepth.asStrings());
currentDepth = nextDepth;
}
return NodeList.emptyList();
}
private NodeList findCandidates(Node node, WordList wordList) {
NodeList derivedNodes = new NodeList();
for (String derivedWord : wordList.getOneLetterDifferenceWords(node.getWord())) {
Node derivedNode = new Node(derivedWord);
derivedNode.setPredecessor(node);
derivedNodes.add(derivedNode);
}
return derivedNodes;
}
private NodeList buildChain(Node node) {
NodeList chain = new NodeList();
while (node.hasPredecssor()){
chain.addFirst(node);
node = node.getPredecessor();
}
chain.addFirst(node);
return chain;
}
}
</code></pre>
<h2>Node</h2>
<pre><code>class Node {
private Node predecessor;
private final String word;
Node(String word) {
if (word == null || word.isEmpty()){
throw new IllegalArgumentException();
}
this.word= word;
}
String getWord() {
return word;
}
void setPredecessor(Node node){
predecessor = node;
}
Node getPredecessor() {
return predecessor;
}
boolean hasPredecssor(){
return predecessor != null;
}
int getLength(){
return word.length();
}
boolean isDestiny(Node destiny) {
return word.equals(destiny.word);
}
@Override
public String toString() {
return word;
}
}
</code></pre>
<p>i'm not sure if i did get the idea of <em>first class collection</em> properly...</p>
<h2>NodeList</h2>
<pre><code>class NodeList extends ArrayList<Node>{
NodeList(Node start) {
super();
add(start);
}
NodeList() {
super();
}
static NodeList emptyList() {
return new NodeList();
}
Collection<String> asStrings(){
return stream().map(Node::getWord).collect(Collectors.toList());
}
void addFirst(Node node){
add(0, node);
}
}
</code></pre>
<p>same thing here, is that a proper implementet of a <em>first class collection</em> ?</p>
<h2>WordList</h2>
<pre><code>class WordList extends ArrayList<String> {
private final List<String> words;
WordList(List<String> words){
this.words = words;
}
List<String> getOneLetterDifferenceWords(String word) {
OneLetterDifference oneWordDifference = new OneLetterDifference(word);
return words.stream().filter(oneWordDifference::test).collect(Collectors.toList());
}
}
</code></pre>
<h2>OneLetterDifference</h2>
<pre><code>class OneLetterDifference implements Predicate<String> {
private final String referenceWord;
OneLetterDifference(String referenceWord){
this.referenceWord = referenceWord;
}
@Override
public boolean test(String word) {
int difference = 0;
for (int i = 0; i < word.length(); i++) {
if (word.charAt(i) != referenceWord.charAt(i)) {
difference = difference + 1;
if (difference > 1){
return false;
}
}
}
return difference == 1;
}
}
</code></pre>
<h2>WordReader</h2>
<pre><code>class WordReader {
private final String filename;
public WordReader(String filename) {
this.filename = filename;
}
List<String> readAllWordsWithLength(int length) {
try (Stream<String> lines = Files.lines(Paths.get(filename), Charset.defaultCharset())) {
return lines.filter(line -> line.length() == length).collect(Collectors.toList());
} catch (IOException e) {
e.printStackTrace();
}
return Collections.emptyList();
}
}
</code></pre>
| [] | [
{
"body": "<h1>Dependency Injection & Responsibility</h1>\n\n<p>Currently your constructor delegates the <code>wordListFilename</code> to the <code>WordReader</code>, which you build there with <code>new</code>. </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public WordChainBuilder(String wordListFilename) {\n wordReader = new WordReader(wordListFilename);\n}\n</code></pre>\n\n<p>The relationship between <code>WordChainBuilder</code> and <code>WordReader</code> is called <a href=\"https://stackoverflow.com/questions/885937/what-is-the-difference-between-association-aggregation-and-composition\">composition</a> in UML.</p>\n\n<p>Imagine you want to write a Unit-Test and a Unit-Test has to be fast and has to test only one unit. A test for <code>WordChainBuilder</code> can't be a Unit-Test because it depends on the file system via <code>WordReader</code> and is therefore not fast.</p>\n\n<p>Imagine <code>WordChainBuilder</code> should now read files from a database. We have to change the constructor.</p>\n\n<p>The definition of Robert C. Martin for responsibilities is \"<em>There should never be more than one reason for a class to change</em>\"</p>\n\n<p>So <code>WordChainBuilder</code> have still more than one responsibility: reading words and build the chain.</p>\n\n<p>The responsibility should only be to build the chain. If you create an interface called <code>WordProvider</code>, you can easily switch from a file reader to a database reader, assume they are of type<code>WordProvider</code>.</p>\n\n<p>Let's change the composition to aggregation:</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public WordChainBuilder(WordProvider provider) {\n this.provider = provider;\n}\n</code></pre>\n\n<p>Now it is possible to write unit-tests, since <code>WordChainBuilder</code> doesn't depend directly on the file-system anymore and we could write a <a href=\"https://en.wikipedia.org/wiki/Mock_object\" rel=\"nofollow noreferrer\">Mock</a> and inject it to <code>WordChainBuilder</code>.</p>\n\n<h1>The <a href=\"https://en.wikipedia.org/wiki/Value_object\" rel=\"nofollow noreferrer\">Value Object</a> <code>Word</code></h1>\n\n<blockquote>\n <p>a value object is a small object that represents a simple entity whose equality is not based on identity: i.e. two value objects are equal when they have the same value</p>\n</blockquote>\n\n<p>In your code base I read often <code>word</code> but it is from type <code>String</code>. Why don't you create a class for it?</p>\n\n<p>The statement <code>start.length() != destiny.length()</code> could be written as <code>start.hasEqualLength(destiny)</code>. The implementation <code>OneLetterDifference</code> of a FunctionalInterface is actually a method that belongs to the class <code>Word</code>, because you compare to Strings that represents a <code>Word</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T05:38:38.113",
"Id": "412982",
"Score": "0",
"body": "wow - i never heard of the value object and i'm very glad you always provide helpful links with your answers - i can learn really much from your answers!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T08:18:19.017",
"Id": "213438",
"ParentId": "213361",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213438",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T09:23:28.257",
"Id": "213361",
"Score": "2",
"Tags": [
"java"
],
"Title": "Word Chain Implementation follow up"
} | 213361 |
<p>I'm writing a system that's responsible for changing <code>Status</code> of Order. There's a specific set of rules that define route of changing <code>Statuses</code>. But, <code>Order</code> and its <code>Products</code> have to satisfy some requirements associated to given <code>Status</code>.</p>
<p>For example, Let's say we have this route of status:</p>
<p>NEW -> ACCEPTED -> CLOSED</p>
<p>Status <code>NEW</code> requires e.g CustomerID to be filled</p>
<p>Status <code>ACCEPTED</code> requires: Customer ID to be filled + some other info</p>
<p>Status <code>CLOSEDD</code> requires: Customer ID, some other info and some other info2</p>
<p>I came with this solution which reduces amount of <code>if</code>s by huge amount, but I think it's kinda over engineered in some parts, <del>especially throwing previous requirements in list constructor
new List>(status_predicates[Statuses.Status_Creating])</del></p>
<p>The method named <code>Predicate</code> is just a helper to minimize amount of syntax.</p>
<p>I just realized that this:</p>
<pre><code>new List<CustomPredicate<Order>>(status_predicates[Statuses.Status_Creating])
</code></pre>
<p>isn't going to work, so implementation changes a little bit (copying-pasting predicates from prev. status), but the concept stays the same.</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Services
{
public class CustomPredicate<T>
{
public Func<T, bool> Predicate { get; set; }
public string Error { get; set; }
public CustomPredicate(Func<T, bool> predicate, string error)
{
Predicate = predicate;
Error = error;
}
}
public class StatusService
{
// dictionary of possible status change route
public static Dictionary<string, List<string>> status_routes = new Dictionary<string, List<string>>
{
{ Statuses.Status_Creating, new List<string> { Statuses.Status_SentNotConfirmed } },
{ Statuses.Status_SentNotConfirmed, new List<string> { Statuses.Status_Accepted, Statuses.Rejected } },
{ Statuses.Status_Accepted, new List<string> { Statuses.InProgress } }
};
// Dictionary of Predicates that have to be satisfied in order to "upgrade" status
// Every predicate list contains requirements of previous
// list of requirements (look at list constructor)
public static Dictionary<string, List<CustomPredicate<Order>>> status_predicates = new Dictionary<string, List<CustomPredicate<Order>>>
{
{
Statuses.Status_Creating,
new List<CustomPredicate<Order>>
{
Predicate(x => x.Products.All(c => !string.IsNullOrWhiteSpace(c.CustomerNote)), "Every product of this order needs to have an customer note field filled."),
Predicate(x => x.Company != null, "You need to pick a company that will provide those products")
}
},
{
// In constructor there's a list of previous predicates
Statuses.Status_SentNotConfirmed,
new List<CustomPredicate<Order>>
{
Predicate(x => x.Products.All(c => !string.IsNullOrWhiteSpace(c.CustomerNote)), "Every product of this order needs to have an customer note field filled."),
Predicate(x => x.Company != null, "You need to pick a company that will provide those products")
Predicate(x => x.Products.All(c => !string.IsNullOrWhiteSpace(c.SomeProperty)), "Someproperty has no value"),
Predicate(x => x.Products.All(c => !string.IsNullOrWhiteSpace(c.SomeProperty2)), "Someproperty2 has no value"),
Predicate(x => !string.IsNullOrWhiteSpace(x.ContactInfo), "Contact info has to be filled"),
}
},
{
// In constructor there's a list of previous predicates
Statuses.InProgress,
new List<CustomPredicate<Order>>
{
Predicate(x => x.Products.All(c => !string.IsNullOrWhiteSpace(c.CustomerNote)), "Every product of this order needs to have an customer note field filled."),
Predicate(x => x.Company != null, "You need to pick a company that will provide those products")
Predicate(x => x.Products.All(c => !string.IsNullOrWhiteSpace(c.SomeProperty)), "Someproperty has no value"),
Predicate(x => x.Products.All(c => !string.IsNullOrWhiteSpace(c.SomeProperty2)), "Someproperty2 has no value"),
Predicate(x => !string.IsNullOrWhiteSpace(x.ContactInfo), "Contact info has to be filled"),
Predicate(x => x.Products.All(c => hasArrived()), "All Products still hasn't arrived yet."),
}
},
};
public static (bool Satisfies, List<string> Errors) CanStatusOfThisOrderBeChanged(Order Order, string targetStatus)
{
if (Order == null || string.IsNullOrEmpty(targetStatus))
{
return (false, new List<string> { "Order or status does not exists" });
}
var errors = new List<string>();
// here's the validator:
foreach (var CustomPredicate in status_predicates[targetStatus])
{
if (!CustomPredicate.Predicate.Invoke(Order))
{
errors.Add(CustomPredicate.Error);
}
}
return (!errors.Any(), errors);
}
public static List<string> GetAvaliableStatusesForThisOrder(Order ord)
{
if (!status_routes.ContainsKey(ord?.Status))
{
throw new Exception("Status does not exists");
}
return status_routes[ord?.Status]; // todo: checking predicates, but that's not the point of this question
}
public static CustomPredicate<Order> Predicate(Func<Order, bool> predicate, string error)
{
return new CustomPredicate<Order>(predicate, error);
}
}
}
</code></pre>
<p>Please do not validate real world / business logic of those bool expression, but just an approach to validate them.</p>
<h1>edit2</h1>
<p>For simplicity let's just use those models</p>
<pre><code>public class Statuses
{
public const string
Status_Creating = "Order is during creation process.",
Status_SentNotConfirmed = "Order is sent to company, but not confirmed yet.",
Status_Accepted = "Order got accepted by company.",
Status_Rejected = "Order got accepted by company.",
Status_InProgress = "Order is in progress.";
}
public class Company
{
public Guid Id { get; } = Guid.NewGuid();
}
public class Order
{
public Guid Id { get; } = Guid.NewGuid();
public Company Company { get; set; }
public List<Product> Products { get; set; } = new List<Product>();
public string ContactInfo { get; set; }
}
public class Product
{
public Guid Id { get; } = Guid.NewGuid();
public string CustomerNote { get; set; }
public string SomeProperty { get; set; }
public string SomeProperty2 { get; set; }
public bool HasArrived()
{
return DateTime.Now >= Arrival;
}
public DateTime Arrival { get; set; }
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T10:40:07.630",
"Id": "412728",
"Score": "0",
"body": "The current question title, which states your concerns about the code, applies to too many questions on this site to be useful. The site standard is for the title to simply state the task accomplished by the code. Please see [ask] for examples, and revise the title accordingly."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T15:29:27.857",
"Id": "412777",
"Score": "0",
"body": "Can you post other types too so that the code compiles without errors?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T01:49:41.963",
"Id": "412853",
"Score": "1",
"body": "Are you open to using 3rd-party libraries? What you're building looks a lot like [FluentValidation](https://fluentvalidation.net) to me--just implement an `AbstractValidator<Order>` for each state transition."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T07:56:21.830",
"Id": "412870",
"Score": "0",
"body": "@t3chb0t Try now"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T08:01:26.933",
"Id": "412873",
"Score": "0",
"body": "@xander Sounds like a good idea"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T08:30:19.517",
"Id": "412875",
"Score": "0",
"body": "It seems to me that you're describing a State Machine for your orders. I've used a framework called [Stateless](https://github.com/dotnet-state-machine/stateless) which I'd recommend for this kind of thing. It might be overkill for you here but you'd need to evaluate that yourself with your full requirements."
}
] | [
{
"body": "<h1>Short answer</h1>\n<p>Yes, it's over-engineered.</p>\n<h1>Long answer</h1>\n<p>You mention that it reduces the number of <code>if</code> statements, but not why this is your goal. In fact, it's pretty clear that reducing the number of <code>if</code> statements isn't <em>inherently</em> a target of clean code, it's something you might want to do to achieve another goal. The possibilities that come to mind are:</p>\n<p><strong>Enhance readibility</strong>: Your design has added a lot of code, including a new class and a helper method, and it's separated the definition of the checks away from where they're actually performed. It's a lot harder to read than if you'd just used in-line ifs.</p>\n<p><strong>Improve testability</strong>: If you have a combinatorial explosion of conditions, it can be useful to be able to inject in a simple condition which always passes or always fails for your unit tests, then test the actual conditions separately. But it doesn't seem like you have that issue, or that your design intends to allow that kind of injection. Really all it means is that you have more complex code, which is now harder to fully test.</p>\n<p>So I think this makes things worse rather than better. If you want to improve readability, there's a fairly common pattern for checking preconditions which looks like:</p>\n<pre><code>private void Foo(int someNumber, string someText)\n{\n CheckPrecondition(someNumber > 0, "Numbers must be positive");\n CheckPrecondition(someText != null, "Text can't be null");\n\n // Rest of the method\n}\n</code></pre>\n<p>This just requires a single helper method. No classes and no <code>Func</code>s. In your case you'd also want to pass the list of errors so that the check method could add its error if there was one. Even that is additional complexity and indirection for a relatively marginal benefit, but I think it's preferable to your version.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T13:22:38.867",
"Id": "412745",
"Score": "0",
"body": "``It's a lot harder to read than if you'd just used in-line ifs.`` I agree, but I thought about it as: ``Ok, so I have e.g 8 different statuses and every of them has at least 5 checks, so I have switch with 8 cases + 8 methods which contain 5+ ifs`` - it's a lot ``CheckPrecondition`` what are overloads of this method? ``No classes and no Funcs`` What's wrong with them?"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T13:04:36.710",
"Id": "213374",
"ParentId": "213364",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T10:22:45.260",
"Id": "213364",
"Score": "5",
"Tags": [
"c#"
],
"Title": "Building a bool expressions validator"
} | 213364 |
<p>I made a GLFW window abstraction, as I find it very useful for me to make such abstractions while learning an API, and It actually pretty much eases my work while coding. </p>
<p>Anyways, share your thoughts. Is the code practice good? Is it bad If I am very explicit in my naming conventions? For example, every method is Window...something. Like DestroyWindow(). Should it be only Destroy();?</p>
<p>Window.h</p>
<pre><code>#pragma once
#include "GLFW\glfw3.h"
enum class WindowMode
{
FULLSCREEN = 0,
WINDOWED = 1
};
struct WindowProps
{
unsigned int WindowWidth;
unsigned int WindowHeight;
const char* WindowTitle;
WindowMode WM;
WindowProps(unsigned int windowWidth = 1280,
unsigned int windowHeight = 720,
const char* windowTitle = "OpenGL",
WindowMode wm = WindowMode::WINDOWED)
: WindowWidth(windowWidth), WindowHeight(windowHeight), WindowTitle(windowTitle), WM(wm)
{
}
};
class Window
{
private:
GLFWwindow* m_Window;
unsigned int m_WindowMinimumWidth;
unsigned int m_WindowMaximumWidth;
unsigned int m_WindowMinimumHeight;
unsigned int m_WindowMaximumHeight;
unsigned int m_MonitorWidth;
unsigned int m_MonitorHeight;
struct WindowData
{
unsigned int WindowWidth;
unsigned int WindowHeight;
const char* WindowTitle;
WindowMode WM;
} m_WindowData;
private:
void InitWindow(const WindowProps& props = WindowProps());
public:
Window(const unsigned int& windowWidth, const unsigned int& windowHeight, const char* windowTitle, WindowMode windowMode);
Window();
void MakeWindowContextCurrent();
void DestroyWindow();
void WindowOnFocus();
void MaximizeWindow();
void MinimizeWindow();
void RestoreWindow();
void CloseWindow();
void SetWindowWidth(const unsigned int& windowWidth);
void SetWindowHeight(const unsigned int& windowHeight);
void SetWindowSizeLimit(const unsigned int& windowMinWidth, const unsigned int& windowMinHeight, const unsigned int& windowMaxWidth, const unsigned int& windowMaxHeight);
void SetWindowTitle(const char* windowTitle);
unsigned int GetMonitorWidth();
unsigned int GetMonitorHeight();
inline unsigned int GetWindowWidth() const { return m_WindowData.WindowWidth; }
inline unsigned int GetWindowHeight() const { return m_WindowData.WindowHeight; }
inline unsigned int GetWindowMinimumWidth() const { return m_WindowMinimumWidth; }
inline unsigned int GetWindowMaximumWidth() const { return m_WindowMaximumWidth; }
inline unsigned int GetWindowMinimumHeight() const { return m_WindowMinimumHeight; }
inline unsigned int GetWindowMaximumHeight() const { return m_WindowMaximumHeight; }
inline const char* GetWindowTitle() const { return m_WindowData.WindowTitle; }
inline GLFWwindow* GetWindowInstance() const { return m_Window; }
};
</code></pre>
<p>Window.cpp</p>
<pre><code>#include "Window.h"
Window::Window(const unsigned int& windowWidth, const unsigned int& windowHeight, const char* windowTitle, WindowMode windowMode)
{
WindowProps windowProperties;
windowProperties.WindowWidth = windowWidth;
windowProperties.WindowHeight = windowHeight;
windowProperties.WindowTitle = windowTitle;
windowProperties.WM = windowMode;
InitWindow(windowProperties);
}
Window::Window()
{
InitWindow();
}
void Window::InitWindow(const WindowProps& windowProperties)
{
m_WindowData.WindowWidth = windowProperties.WindowWidth;
m_WindowData.WindowHeight = windowProperties.WindowHeight;
m_WindowData.WindowTitle = windowProperties.WindowTitle;
m_Window = glfwCreateWindow(
windowProperties.WM == WindowMode::FULLSCREEN ? GetMonitorWidth() : windowProperties.WindowWidth,
windowProperties.WM == WindowMode::FULLSCREEN ? GetMonitorHeight() : windowProperties.WindowHeight,
windowProperties.WindowTitle,
windowProperties.WM == WindowMode::FULLSCREEN ? glfwGetPrimaryMonitor() : nullptr, nullptr
);
}
void Window::MakeWindowContextCurrent()
{
glfwMakeContextCurrent(m_Window);
}
void Window::DestroyWindow()
{
glfwDestroyWindow(m_Window);
}
void Window::WindowOnFocus()
{
glfwFocusWindow(m_Window);
}
void Window::MaximizeWindow()
{
glfwMaximizeWindow(m_Window);
}
void Window::MinimizeWindow()
{
glfwIconifyWindow(m_Window);
}
void Window::RestoreWindow()
{
glfwRestoreWindow(m_Window);
}
void Window::CloseWindow()
{
glfwSetWindowShouldClose(m_Window, GL_TRUE);
}
void Window::SetWindowWidth(const unsigned int& windowWidth)
{
m_WindowData.WindowWidth = windowWidth;
glfwSetWindowSize(m_Window, m_WindowData.WindowWidth, m_WindowData.WindowHeight);
}
void Window::SetWindowHeight(const unsigned int& windowHeight)
{
m_WindowData.WindowHeight = windowHeight;
glfwSetWindowSize(m_Window, m_WindowData.WindowWidth, m_WindowData.WindowHeight);
}
void Window::SetWindowSizeLimit(const unsigned int& windowMinWidth, const unsigned int& windowMinHeight, const unsigned int& windowMaxWidth,
const unsigned int& windowMaxHeight)
{
m_WindowMinimumWidth = windowMinWidth;
m_WindowMinimumHeight = windowMinHeight;
m_WindowMaximumWidth = windowMaxWidth;
m_WindowMaximumHeight = windowMaxHeight;
glfwSetWindowSizeLimits(m_Window, m_WindowMinimumWidth, m_WindowMinimumHeight, m_WindowMaximumWidth, m_WindowMaximumHeight);
}
void Window::SetWindowTitle(const char* windowTitle)
{
m_WindowData.WindowTitle = windowTitle;
glfwSetWindowTitle(m_Window, m_WindowData.WindowTitle);
}
unsigned int Window::GetMonitorWidth()
{
const GLFWvidmode* VidMode = glfwGetVideoMode(glfwGetPrimaryMonitor());
m_MonitorWidth = VidMode->width;
return m_MonitorWidth;
}
unsigned int Window::GetMonitorHeight()
{
const GLFWvidmode* VidMode = glfwGetVideoMode(glfwGetPrimaryMonitor());
m_MonitorHeight = VidMode->height;
return m_MonitorHeight;
}
</code></pre>
<p>Usage Example:</p>
<pre><code>Window myWindow(960, 540, "OpenGL", WindowMode::WINDOWED);
myWindow.MakeWindowContextCurrent();
std::cout << myWindow.GetWindowTitle() << "\n";
std::cout << myWindow.GetWindowWidth() << "\n";
std::cout << myWindow.GetWindowHeight() << "\n";
std::cout << myWindow.GetMonitorWidth() << "\n";
std::cout << myWindow.GetMonitorHeight() << "\n";
myWindow.DestroyWindow();
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T11:07:48.277",
"Id": "412732",
"Score": "1",
"body": "method name specifies the action. Since class name `Window` is already known, having it as substring of member function names e.g. in `InitWindow()`, `MaximizeWindow()` is indeed redundant"
}
] | [
{
"body": "<ul>\n<li><p><code>WindowProps</code> and <code>WindowData</code> are effectively identical. We could just use <code>WindowProps</code> for both.</p></li>\n<li><p>We can query the window width and height from GLFW (with <code>glfwGetWindowSize</code>). We should do this instead of storing the width and height ourselves because:</p>\n\n<ul>\n<li><p>If the window is resized, the width and height stored in the class will be incorrect. To update these values, we'd have to use <code>glfwSetWindowSizeCallback</code>.</p></li>\n<li><p>I suspect that <code>glfwSetWindowSize</code> may not set the window size to the requested values if the window has a size limit (so the values stored in <code>SetWindowWidth</code> and <code>SetWindowHeight</code> may be wrong).</p></li>\n</ul></li>\n<li><p>Similarly, <code>GetMonitorWidth()</code> may return unexpected values if a window is moved to a monitor other than the primary monitor.</p></li>\n<li><p>Note that <code>m_MonitorWidth</code> and <code>m_MonitorHeight</code> are set, and never referred to again. These members could be removed.</p></li>\n<li><p>We should initialize <code>m_Window</code> to <code>nullptr</code> in the constructor(s).</p></li>\n<li><p>The window title should be stored in a <code>std::string</code>. We should not require an externally owned <code>char*</code> to be kept alive for the duration of the <code>Window</code> class lifetime.</p></li>\n<li><p>There is no advantage to passing built-in types by <code>const&</code> (e.g. <code>void SetWindowWidth(const unsigned int& windowWidth);</code>, and others).</p></li>\n<li><p>We should not have a publicly accessible <code>DestroyWindow</code> function. If this is called, it leaves us with an invalid <code>Window</code> object, for which none of the functions (setting size, etc.) make sense or work. We should destroy the window in a class destructor instead.</p></li>\n<li><p>Functions defined inside the body of the class do not need the <code>inline</code> keyword (e.g. <code>inline unsigned int GetWindowWidth() const</code>).</p></li>\n<li><p>As noted by <em>programmer</em> in the comments, the use of <code>Window</code> in the function names is unnecessary.</p></li>\n<li><p>I'd suggest that the default values in <code>WindowProps</code> are unnecessary. Asking the user to supply these every time is not a significant burden. We can do this by <code>delete</code>ing the default constructor:</p>\n\n<pre><code>struct WindowProperties\n{\n unsigned int Width, Height;\n std::string Title;\n WindowMode Mode;\n\n WindowProperties() = delete;\n};\n</code></pre>\n\n<p>We then need only one <code>Window</code> constructor: <code>Window(WindowProperties const& properties);</code> which can be called like so: <code>Window window({ 1024, 768, \"blah\", WindowMode::FULLSCREEN });</code></p></li>\n<li><p>We need to think about copying and moving the <code>Window</code> class. It's probably easiest to prevent both:</p>\n\n<pre><code>Window(Window const&) = delete;\nWindow& operator=(Window const&) = delete;\nWindow(Window&&) = delete;\nWindow& operator=(Window&&) = delete;\n</code></pre>\n\n<p>However, there might be a case for allowing <code>move</code> construction and assignment.</p></li>\n</ul>\n\n<hr>\n\n<p><strong>Comment reply - passing by value:</strong></p>\n\n<p>In C++ all types are value-types. If we want a reference we have to explicitly request it. So if we define a function like this:</p>\n\n<pre><code>void foo(ValueType value);\n</code></pre>\n\n<p>The <code>ValueType</code> is always copied. If <code>ValueType</code> is defined by <code>typedef int ValueType</code>, this is very cheap. If <code>ValueType</code> is a <code>struct ValueType { int[10000]; };</code> it isn't.</p>\n\n<p>Where copying is expensive, we can pass a reference to the object in the outer scope instead:</p>\n\n<pre><code>void foo(const ValueType& value);\n</code></pre>\n\n<p>We can think of this as passing (a safer version of) a pointer to an object somewhere outside the <code>foo</code> function.</p>\n\n<p>For types where copying is cheap (e.g. built-in types like <code>int</code>, <code>unsigned int</code> etc.) this may introduce overhead, and prevents compiler optimizations. So for types like <code>unsigned int</code> it's best to do the copy. So we should have:</p>\n\n<pre><code>void SetWidth(unsigned int width);\nvoid SetHeight(unsigned int height);\nvoid SetSizeLimit(unsigned int minWidth, unsigned int minHeight, unsigned int maxWidth, unsigned int maxHeight);\n</code></pre>\n\n<hr>\n\n<p><strong>Comment reply - destructor:</strong></p>\n\n<p>We should call <code>DestroyWindow</code> from the destructor:</p>\n\n<pre><code>Window::~Window() { DestroyWindow(); }\n</code></pre>\n\n<p>However, <code>DestroyWindow</code> should not be a public function, otherwise we can do this:</p>\n\n<pre><code>myWindow.DestroyWindow();\nmyWindow.SetWidth(480); // crash? error? we shouldn't be able to do this here...\n</code></pre>\n\n<p>Many things in C++ are based on the idea of <a href=\"https://en.cppreference.com/w/cpp/language/raii\" rel=\"nofollow noreferrer\">RAII (resource acquisition is initialization)</a>. This attempts to ensure that the lifetime of a resource (the glfw window in this case) has the same lifetime as the object that \"owns\" it (the <code>Window</code> class). So when the user creates an instance of the <code>Window</code> class, the window is created, and when the user destroys that instance (or it goes out of scope), the window is destroyed.</p>\n\n<pre><code>{\n Window window(...); <--- window resource created\n ... ok to do stuff with window\n} <--- window destructor called automatically at end of scope (window destroyed)\n\n... window doesn't exist any more\n</code></pre>\n\n<hr>\n\n<p><strong>Comment reply - copying:</strong></p>\n\n<p>We need to think about what happens if the user does this:</p>\n\n<pre><code>Window window1(1280, 720, \"title\", WindowMode::WINDOWED);\nWindow window2(window1); // copy construction (create new window by copying an existing one)\nWindow window3 = window1; // also copy construction\n</code></pre>\n\n<p>Or if the user does this:</p>\n\n<pre><code>Window window1(1280, 720, \"title\", WindowMode::WINDOWED);\nWindow window2(920, 53, \"blah\", WindowMode::WINDOWED);\nwindow2 = window3; // copy assignment (assign one existing window to another)\n</code></pre>\n\n<p>These correspond to calling <code>Window</code> member functions with the following signature:</p>\n\n<pre><code>Window(Window const& rhs); // copy construction\nWindow& operator=(Window const& rhs); // copy assignment\n</code></pre>\n\n<p>The compiler may automatically generate these for you.</p>\n\n<p>For a class representing a data structure, we can just copy the data inside the class. For a <code>Window</code> class, we don't really want to have multiple <code>Window</code> objects representing the same glfw window. We could open a new glfw window, copying the settings from the old one. However, it's much easier to just prevent copying altogether by deleting these operators (preventing the compiler from defining them).</p>\n\n<pre><code>Window(Window const&) = delete;\nWindow& operator=(Window const&) = delete;\n</code></pre>\n\n<p>Moving is similar. It allows an object instance to adopt / steal the internal resources from another (which is much quicker than copying them). This is getting a bit long, so I'm not going to go into detail here.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T16:53:19.353",
"Id": "412799",
"Score": "0",
"body": "Thank you very much.\n\nWell I use the inlines when I want to be very explicit, i'm aware of the fact that modern compilers decide which functions should be inlined by themselves. I usually inline my getters if they are one liners\n\nAlso what about the overall structure of the code? Any opinion on it? I just want to know where I am in terms of software design or even just pure code cleanliness.\n\nAnd won't const unsigned int& make it possible to pass either a literal value or a variable? That's what I wanted to achieve."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T17:04:39.773",
"Id": "412802",
"Score": "0",
"body": "And can't I just call the destructor in my Destroy window method?\n\nOh and what do you mean by the last four lines of code? And by copying and moving the window class."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T19:53:02.047",
"Id": "412828",
"Score": "0",
"body": "Edited to add some details."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T12:38:20.777",
"Id": "213372",
"ParentId": "213365",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "213372",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T10:30:06.053",
"Id": "213365",
"Score": "4",
"Tags": [
"c++",
"opengl"
],
"Title": "C++ OpenGL - GLFW Window Abstraction"
} | 213365 |
<p>The task:</p>
<blockquote>
<p>Given an unsigned 8-bit integer, swap its even and odd bits. The 1st
and 2nd bit should be swapped, the 3rd and 4th bit should be swapped,
and so on.</p>
<p>For example, 10101010 should be 01010101. 11100010 should be 11010001.</p>
<p>Bonus: Can you do this in one line?</p>
</blockquote>
<p>My solutions:</p>
<pre><code>// imperative:
function swap8BitInteger(bytes){
let copiedBytes = '';
for(let i = 0; i < bytes.length; i+=2) {
copiedBytes+= `${bytes[i+1]}${bytes[i]}`;
}
return copiedBytes;
}
console.log(swap8BitInteger('11100010'));
// I don't know wether this qualifies as a one-liner
const swap8BitInteger2 = bytes => bytes.split('').reduce((acc, bit, idx) => {acc[idx % 2 === 0 ? idx + 1 : idx - 1] = bit;return acc;}, []).join('');
console.log(swap8BitInteger2('11100010'));
// Not sure wether this is still readable
const swap8BitInteger3 = bytes => bytes.split('').reduce((acc, _, idx) => idx % 2 ? acc : acc + bytes[idx + 1] + bytes[idx], '');
console.log(swap8BitInteger3('11100010'));
</code></pre>
<p>Would be interested to see an even shorter (and/or more readable) solution.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T12:21:22.667",
"Id": "412740",
"Score": "0",
"body": "Are the input and output really supposed to be strings, and not 8-bit integers are the question said?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T12:41:05.043",
"Id": "412741",
"Score": "0",
"body": "JS doesn't have (8 bit) Integer types. It only got numbers, i.e. leading zeros can't be displayed, therefore I took a string representation of an 8 bit Integer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T12:46:36.240",
"Id": "412742",
"Score": "0",
"body": "That is just a display issue, of course a JS Number can easily hold 8 bits"
}
] | [
{
"body": "<h2>OMDG arrays to manipulate bits</h2>\n<p>Bit manipulation is the most basic type of operation a computer can do. These days it can mess with 64 bit in one go. JS number (as signed int 32) is limited to 32 (to keep us in our place)</p>\n<p>BTW JS has 8, 16, 32bit signed and unsigned arrays.</p>\n<p>In JS you can write binary numbers with the <code>0b</code> prefix. Eg <code>0b111</code> is 7</p>\n<p>To swap even odd, you shift all bits to the left <code><< 1</code> (same as * 2) and mask out <code>& 0b10101010</code> the odd bits. The for the even you shift all bits to the right <code>>> 1</code> similar to <code>/2</code>, mask out the even bits <code>& 0b101010101</code> and add or or the result of the previous shift.</p>\n<p>Example show two ways of doing the same thing.</p>\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const swapEvenOdd = char => ((char << 1) & 0b10101010) | ((char >> 1) & 0b1010101);\n\nconst swapEvenOdd2 = char => ((char * 2) & 170) + ((char / 2) & 85);\n\n\nconsole.log(swapEvenOdd(0b01100110).toString(2).padStart(8,\"0\"))\nconsole.log(swapEvenOdd2(0b01100110).toString(2).padStart(8,\"0\"))</code></pre>\r\n</div>\r\n</div>\r\n</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T15:56:06.797",
"Id": "412782",
"Score": "0",
"body": "Im deeply ashamed for not having know this. -.-“"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T15:59:33.937",
"Id": "412784",
"Score": "1",
"body": "@thadeuszlay LOL not to worry, binary maths is a dying art in the world of programming. This not the first time I have seen strings and arrays used to manipulate bits."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T18:02:40.480",
"Id": "412810",
"Score": "0",
"body": "Can you please explain to me each single step and why it is needed? E.g. why is `& 0b10101010` needed and afterwards `|` and then `((char >> 1) & 0b1010101)`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T21:21:27.013",
"Id": "412840",
"Score": "0",
"body": "@thadeuszlay The rundown on bitwise operators https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators The `char & 0b1010` the right side is a mask. It removes any bits that are 0 in the mask from char. eg 4bit `c = 1001` `1001<<1=0010` then `0010&1010=0010` then after or `|` shift right and mask `1001>>1=0100` (if JS had unsigned char (8bit) then would use `>>>` to remove extra top bit) then `0100&0101=0100`. Then the or `0100 | 0010 = 0110` which is the answer"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T11:29:54.227",
"Id": "413127",
"Score": "0",
"body": "Ah, I now understand. Binary math isn't that difficult after all."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T15:52:59.373",
"Id": "213386",
"ParentId": "213370",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "213386",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T12:05:17.090",
"Id": "213370",
"Score": "3",
"Tags": [
"javascript",
"algorithm",
"functional-programming"
],
"Title": "Swap even and odd bits of unsigned 8-bit integer"
} | 213370 |
<p>I want to understand how resnet works also called us <a href="https://medium.com/@14prakash/understanding-and-implementing-architectures-of-resnet-and-resnext-for-state-of-the-art-image-cf51669e1624" rel="nofollow noreferrer">residual networks</a> and I understand it better when I code one myself. I tried to find a simple implementation of resnet in the web but most I found were complicated and all of it used convolutional neural networks especially in python with keras. Because of this I have to code a resnet myself and used the smallest dataset available (that is iris dataset) with dense layers. I am releasing my full code here but I am not fully sure about my resnet implementation. I also included a mlp model to do a comparison study with my resnet implementation. Some where I read that resnet model gives higher accuracy with lesser parameters comparing to a vanilla neural net model. In my implementation also resnet model gave better mean accuracy than the vanilla model.</p>
<p>Please review my code.</p>
<p>used libraries: keras, tensorflow and sckit-learn</p>
<pre><code>"""
A simple toy resnet model and its implementation
Requirements
============
python
keras
tensorflow
sckit-learn
"Added a mlp model also to this code for comparison study with resnet"
"""
from sklearn.model_selection import StratifiedKFold
from sklearn import datasets
from keras.utils import to_categorical
from keras.models import Sequential,Model
from keras.layers import Dense,Input,Add,Activation
import tensorflow as tf
import numpy as np
#Set the seeds
seed=111
tf.set_random_seed(seed)
np.random.seed(seed)
#Load iris dataset
iris = datasets.load_iris()
X = iris.data
y = iris.target
y=to_categorical(y)
input_shape=X.shape[1]
output_shape=y.shape[1]
"""
Training on iris dataset with a vanilla mlp model.
"""
print("Training mlp with cross validation\n")
kfold = StratifiedKFold(n_splits=10, shuffle=True, random_state=seed)
j=False
cvscores = []
for train, test in kfold.split(X, y.argmax(1)):
#mlp model
model = Sequential()
model.add(Dense(4, input_shape=(input_shape,),activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(3,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(3,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(3,activation='relu'))
model.add(Dense(4,activation='relu'))
model.add(Dense(2,activation='relu'))
model.add(Dense(output_shape,activation='softmax'))
model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])
if j==False:
model.summary()
j=True
model.fit(X[train],y[train],batch_size=10,verbose=0,epochs=100)
scores = model.evaluate(X[test], y[test], verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
cvscores.append(scores[1] * 100)
print("Average MLP Score:")
mlp_score=[np.mean(cvscores),np.std(cvscores)]
print("%.2f%% (+/- %.2f%%)" % (mlp_score[0],mlp_score[1] ))
ml=len(model.layers)
mp=model.count_params()
del model
"""
Training on iris dataset with a resnet model.
"""
print("Training resnet with cross validation\n")
def resnet_block(x):
t=x.get_shape().as_list()[1]
i=x
x=Dense(3,activation='relu')(i)
x=Dense(4,activation='relu')(x)
x=Dense(t)(x)
x=Add()([x,i])
x=Activation('relu')(x)
return x
j=False
cvscores = []
for train, test in kfold.split(X, y.argmax(1)):
i=Input(shape=(input_shape,))
x=Dense(2,activation='relu')(i)
x=resnet_block(x)
x=resnet_block(x)
x=resnet_block(x)
o=Dense(output_shape,activation='softmax')(x)
model=Model(i,o)
model.compile(loss='categorical_crossentropy', optimizer='adam',metrics=['accuracy'])
if j==False:
model.summary()
j=True
model.fit(X[train],y[train],batch_size=10,verbose=0,epochs=100)
scores = model.evaluate(X[test], y[test], verbose=0)
print("%s: %.2f%%" % (model.metrics_names[1], scores[1]*100))
cvscores.append(scores[1] * 100)
print("Average Resnet Score:")
resnet_score=[np.mean(cvscores),np.std(cvscores)]
print("%.2f%% (+/- %.2f%%)" % (resnet_score[0],resnet_score[1] ))
rl=len(model.layers)
rp=model.count_params()
print("\n\n")
print("Complete result: \n")
print("MLP")
print('Layers:'+str(ml)+' Parameters'+str(mp))
print('Score: ')
print("%.2f%% (+/- %.2f%%)" % (mlp_score[0],mlp_score[1] ))
print("\nResnet")
print('Layers:'+str(rl)+' Parameters'+str(rp))
print('Score: ')
print("%.2f%% (+/- %.2f%%)" % (resnet_score[0],resnet_score[1] ))
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T12:25:48.053",
"Id": "213371",
"Score": "3",
"Tags": [
"python",
"ai",
"machine-learning",
"neural-network",
"tensorflow"
],
"Title": "A simple toy ResNet model and its implementation"
} | 213371 |
<p>I have written simple input manager which is used for me to detect key press, and fire assigned function. For example I can do something like that:</p>
<pre><code>auto own_pointer = std::make_shared<Player>(*this);
inputControl.addKeyToCheck( sf::Keyboard::H, std::function<void( Player& )>( &Player::sayHello ),own_pointer );
</code></pre>
<p>and in my loop manager, I check input managers, and if H is pressed, then function <code>sayHello</code> will be fired.</p>
<p>I have written moving my player with this input manager.</p>
<pre><code>auto own_pointer = std::make_shared<Player>(*this);
inputControl.addKeyToCheck( sf::Keyboard::A, std::function<void( Player& )>( &Player::moveLeft ),own_pointer );
inputControl.addKeyToCheck( sf::Keyboard::D, std::function<void( Player& )>( &Player::moveRight ), own_pointer );
inputControl.addKeyToCheck( sf::Keyboard::S, std::function<void( Player& )>( &Player::moveDown ), own_pointer );
inputControl.addKeyToCheck( sf::Keyboard::W, std::function<void( Player& )>( &Player::moveTop ), own_pointer );
</code></pre>
<p>where for example <code>moveTop</code> is just</p>
<pre><code>void Player::moveTop()
{
this->getComponent<Velocity>()->y -= speed * mv::constants::mob::DEFAULT_SPEED;
}
</code></pre>
<p>Generally I am so proud of my <code>InputManager</code>, it works everywhere else but there is really bad to use 4 different function to control moving. Have somebody any advice how to deal with that style problem?</p>
<h2>Input manager</h2>
<pre><code> /**
* @brief Class which manage keys' input
*/
template <class T>
class InputManager
{
/* ===Objects=== */
public:
protected:
private:
//when you press KEY you execute FunctionWrapper
std::map < sf::Keyboard::Key, FunctionPointerWrapper_t<T>> keyData;
/* ===Methods=== */
public:
/**
* @brief Checks if keys have been clicked
*/
void update();
/**
* @bried adds key to database
*/
bool addKeyToCheck( sf::Keyboard::Key key, std::function<void( T& )> function, std::shared_ptr<T> object );
/**
* @brief remove key from database
*/
bool eraseKey( sf::Keyboard::Key key );
protected:
private:
};
template <class T>
void InputManager<T>::update()
{
for ( auto&var : keyData )
if ( sf::Keyboard::isKeyPressed( var.first ) )
var.second.function( *var.second.object );
}
template <class T>
bool InputManager<T>::addKeyToCheck( sf::Keyboard::Key key, std::function<void( T& )> function, std::shared_ptr<T> object )
{
keyData.emplace( key, FunctionPointerWrapper_t<T>( function, object ) );
return true;
}
template <class T>
bool InputManager<T>::eraseKey( sf::Keyboard::Key key )
{
keyData.erase( key );
return false;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T13:59:28.450",
"Id": "412754",
"Score": "1",
"body": "I'm not sure this question is a good fit for CodeReview. If you posted the input manager class we could suggest general improvements, some of which might cover what you're asking. However, for a specific question like this you might have better luck on https://gamedev.stackexchange.com/ ."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T14:27:20.200",
"Id": "412761",
"Score": "0",
"body": "this question is only about style, so I think that it is good. Ok, I am going to edit question"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T14:46:02.803",
"Id": "412764",
"Score": "0",
"body": "Can you provide a usage example of how your input manager is invoked and in what manner?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T15:42:34.207",
"Id": "412780",
"Score": "0",
"body": "@Mast it is just invoked by inputManager.update() in main game loop."
}
] | [
{
"body": "<p><code>FunctionPointerWrapper_t</code> seems unnecessary; we can store a <code>std::function<void()></code> in the map directly. To create this function, we can either use <a href=\"https://en.cppreference.com/w/cpp/utility/functional/bind\" rel=\"nofollow noreferrer\"><code>std::bind</code></a>:</p>\n\n<pre><code>auto player = std::make_shared<Player>(*this);\ninputControl.addKeyToCheck( sf::Keyboard::H, std::bind(&Player::sayHello, player) );\n</code></pre>\n\n<p>or a <a href=\"https://en.cppreference.com/w/cpp/language/lambda\" rel=\"nofollow noreferrer\">lambda function</a>:</p>\n\n<pre><code>auto player = std::make_shared<Player>(*this);\ninputControl.addKeyToCheck( sf::Keyboard::H, [=] () { player->sayHello(); } );\n</code></pre>\n\n<p>Note that both of these examples internally create a copy of the <code>shared_ptr</code>.</p>\n\n<hr>\n\n<p>For cutting down on the number of named functions in the player class, we can route the functionality to a single <code>move</code> function, something like:</p>\n\n<pre><code>void Player::move(Vector2f const& speed) { getComponent<Velocity>() += speed * mv::constants::mob::DEFAULT_SPEED; }\n</code></pre>\n\n<p>We can then use <code>std::bind</code>, or lambda functions as above:</p>\n\n<pre><code>inputControl.addKeyToCheck( sf::Keyboard::W, std::bind(&Player::move, player, Vector2f(0.f, -1.f)) );\ninputControl.addKeyToCheck( sf::Keyboard::W, [=] () { player->move(Vector2f(0.f, -1.f)); });\n</code></pre>\n\n<p>Where <code>Vector2f(0.f, -1.f)</code> can be replaced by whatever the actual desired type / value is. (We could also do the multiplication outside of the move function, if it's not common between the functions).</p>\n\n<p>We still need to define 4 functions, but there's less overhead in the <code>Player</code> class.</p>\n\n<p>To simplify it further, we'd probably want to define some sort of axis mapping, so we could do something like:</p>\n\n<pre><code>inputControl.addAxis(Axis(sf::Keyboard::W, sf::Keyboard::S, maxSpeed, minSpeed), [=] (float axisValue) { player->moveVertically(axisValue); });\n</code></pre>\n\n<p>(and perhaps even allow a 2d-axis to be defined mapping 4 keys to one function call) but that might be a fair amount of extra work.</p>\n\n<hr>\n\n<p>General comments:</p>\n\n<ul>\n<li><code>InputManager::addKeyToCheck</code> and <code>InputManager::eraseKey</code> should probably not return a fixed <code>true</code> / <code>false</code> without checking if they actually succeeded.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T16:53:56.590",
"Id": "213391",
"ParentId": "213375",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "213391",
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T13:06:52.497",
"Id": "213375",
"Score": "1",
"Tags": [
"c++",
"sfml"
],
"Title": "Moving character in given direction C++ SFML"
} | 213375 |
<p>This is a class that holds mutex and associated object. On checkout/access the mutex is locked while the stack object lives and a reference to object is obtained. Any suggestions or improvements is welcomed.</p>
<pre><code>#include <mutex>
template<class T>
class MutexProtectedObject {
//this relies on benign use and it is just a helper rather than a foolproof solution - ie. anyone may still save a pointer to obj etc. and access it later
public:
class Access {
public:
Access(std::mutex& m, T& obj) : sl_(m), obj_(obj) {
}
T& obj_;
private:
std::scoped_lock<std::mutex> sl_;//mutex is locked here (by RAII)
};
Access access() {
return Access(mutex, obj);
}
MutexProtectedObject(const MutexProtectedObject&) = delete;
MutexProtectedObject& opreator=(const MutexProtectedObject&) = delete;
private:
std::mutex mutex;
T obj;
};
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T13:35:01.507",
"Id": "412749",
"Score": "2",
"body": "Please make sure the posted code works correctly. I'd also suggest adding usage examples, and unit tests."
}
] | [
{
"body": "<p>There's no way to construct a <code>MutexProtectedObject</code> unless <code>T</code> is default-constructible. I recommend a forwarding constructor, something like (untested):</p>\n\n<pre><code>template<typename... Args>\nMutexProtectedObject(Args&&... args)\n : mutex{},\n obj{std::forward<Args>(args)...}\n{\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T15:20:55.217",
"Id": "213383",
"ParentId": "213376",
"Score": "2"
}
},
{
"body": "<h2>Access</h2>\n\n<p>I don't like the fact that <code>Access</code> gives you a reference to the object directly. This leads to issues with somebody accidentally keeping a reference to the object after the <code>Accesses</code> object is destroyed or accidentally making a copy of the object.</p>\n\n<pre><code>T& myRef = wrapped.access().obj_; // Now I have a reference to the object\n // But the Accesses object is gone.\n\nmyRef.doStuffWithNoLock();\n\n\n// or\n\nT myCopy = wrapped.access().obj_; // I made a copy of the object.\n</code></pre>\n\n<p>How about <code>Access</code> delegating all accesses via operator <code>-></code>? That way you don't leak the object to external code.</p>\n\n<pre><code>class Access\n{\n public:\n T* operator->() {return &obj_;}\n private:\n T& obj_;\n};\n</code></pre>\n\n<p>Now you can use <code>Access</code> like it was a <code>T*</code>:</p>\n\n<pre><code>auto foo = wrapper.access();\nfoo->fun1(args);\nfoo->fun2(args);\n</code></pre>\n\n<h2>Initializer list</h2>\n\n<p>The order of initialization of members is the order of declaration. If you define the order deferently in the initializer list this can be confusing (most compilers will warn you about it).</p>\n\n<pre><code>class Access {\n public:\n Access(std::mutex& m, T& obj)\n : sl_(m) // This is not the order they are\n , obj_(obj) // initialized in. The obj_ will be done first\n {}\n\n T& obj_;\n\n private:\n std::scoped_lock<std::mutex> sl_;//mutex is locked here (by RAII)\n};\n</code></pre>\n\n<p>Best practice is to keep the initializer list in the same order as the declaration order in the class.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T17:00:55.470",
"Id": "412800",
"Score": "0",
"body": "Ah, that's much better than my (removed) suggestion. I couldn't see how to prevent the `T&` outliving the `Access`, but I think you've nailed it. We do still have the ability to retain an `Access` whose `T` has been destroyed; I don't know whether we can do anything about that."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T18:17:54.643",
"Id": "412813",
"Score": "0",
"body": "I sort of arrived at the same conclusion about the member object access on my own after poking a bit around. Thank you."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T16:57:27.893",
"Id": "213393",
"ParentId": "213376",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "213393",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T13:18:52.360",
"Id": "213376",
"Score": "1",
"Tags": [
"c++",
"multithreading",
"c++17",
"raii"
],
"Title": "Mutex Protected Object (scoped object wrapper)"
} | 213376 |
<p>I have written a script that retrieves specific fields of Exif data from thousands of images in a directory (including subdirectories) and saves the info to a csv file:</p>
<pre><code>import os
from PIL import Image
from PIL.ExifTags import TAGS
import csv
from os.path import join
####SET THESE!###
imgpath = 'C:/x/y' #Path to folder of images
csvname = 'EXIF_data.csv' #Name of saved csv
###
def get_exif(fn):
ret = {}
i = Image.open(fn)
info = i._getexif()
for tag, value in info.items():
decoded = TAGS.get(tag, tag)
ret[decoded] = value
return ret
exif_list = []
path_list = []
filename_list = []
DTO_list = []
MN_list = []
for root, dirs, files in os.walk(imgpath, topdown=True):
for name in files:
if name.endswith('.JPG'):
pat = join(root, name)
pat.replace(os.sep,"/")
exif = get_exif(pat)
path_list.append(pat)
filename_list.append(name)
DTO_list.append(exif['DateTimeOriginal'])
MN_list.append(exif['MakerNote'])
zipped = zip(path_list, filename_list, DTO_list, MN_list)
with open(csvname, "w", newline='') as f:
writer = csv.writer(f)
writer.writerow(('Paths','Filenames','DateAndTime','MakerNotes'))
for row in zipped:
writer.writerow(row)
</code></pre>
<p>However, it is quite slow. I've attempted to optimise the script for performance + readabilty by using list and dictionary comprehensions. </p>
<pre><code>import os
from os import walk #Necessary for recursive mode
from PIL import Image #Opens images and retrieves exif
from PIL.ExifTags import TAGS #Convert exif tags from digits to names
import csv #Write to csv
from os.path import join #Join directory and filename for path
####SET THESE!###
imgpath = 'C:/Users/au309263/Documents/imagesorting_testphotos/Finse/FINSE01' #Path to folder of images. The script searches subdirectories as well
csvname = 'PLC_Speedtest2.csv' #Name of saved csv
###
def get_exif(fn): #Defining a function that opens an image, retrieves the exif data, corrects the exif tags from digits to names and puts the data into a dictionary
i = Image.open(fn)
info = i._getexif()
ret = {TAGS.get(tag, tag): value for tag, value in info.items()}
return ret
Paths = [join(root, f).replace(os.sep,"/") for root, dirs, files in walk(imgpath, topdown=True) for f in files if f.endswith('.JPG' or '.jpg')] #Creates list of paths for images
Filenames = [f for root, dirs, files in walk(imgpath, topdown=True) for f in files if f.endswith('.JPG' or '.jpg')] #Creates list of filenames for images
ExifData = list(map(get_exif, Paths)) #Runs the get_exif function on each of the images specified in the Paths list. List converts the map-object to a list.
MakerNotes = [i['MakerNote'] for i in ExifData] #Creates list of MakerNotes from exif data for images
DateAndTime = [i['DateTimeOriginal'] for i in ExifData] #Creates list of Date and Time from exif data for images
zipped = zip(Paths, Filenames, DateAndTime, MakerNotes) #Combines the four lists to be written into a csv.
with open(csvname, "w", newline='') as f: #Writes a csv-file with the exif data
writer = csv.writer(f)
writer.writerow(('Paths','Filenames','DateAndTime','MakerNotes'))
for row in zipped:
writer.writerow(row)
</code></pre>
<p>However, this has not changed the performance. </p>
<p>I've timed regions of the code and found that specifically opening each image and getting the Exif data from each image in the <code>get_exif</code> function is what takes time.
To make the script faster, I am wondering:</p>
<ol>
<li>Is it possible to optimise on the performance of the function?</li>
<li>Is it possible to retrieve Exif data without opening the image?</li>
<li>Is <code>list(map(fn,x))</code> the fastest way of applying the function?</li>
</ol>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T13:36:07.777",
"Id": "213377",
"Score": "3",
"Tags": [
"python",
"performance",
"python-3.x",
"comparative-review",
"image"
],
"Title": "Export EXIF data from thousands of images to CSV"
} | 213377 |
<p>Since my last question (<a href="https://codereview.stackexchange.com/q/213286/192683">BinaryTree<T> written in C#</a>), I have rewritten my code based on the responses. My project can be found on my GitHub repo <a href="https://github.com/TheRealVira/binary-tree/blob/master/BinaryTree/BinaryTree.cs" rel="nofollow noreferrer">here</a>;</p>
<pre><code>using System;
using System.Diagnostics;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
namespace BinaryTree
{
/// <summary>
/// Represents a binary tree <seealso href="https://en.wikipedia.org/wiki/Binary_tree" />.
/// </summary>
/// <typeparam name="T">The type which this tree should contain.</typeparam>
[Serializable]
[DataContract]
public class BinaryTree<T> where T : IComparable<T>
{
[DataMember] private Node _parentNode;
public BinaryTree()
{
Debug.WriteLine("Initializing binary-tree..");
_parentNode = new Node();
}
/// <summary>
/// Adds the specific item inside the binary-tree using binary-tree logic.
/// </summary>
/// <param name="item">The item that will be added.</param>
public void Add(T item)
{
Debug.WriteLine("Adding an item in this binary-tree..");
var currentNode = _parentNode;
while (true)
{
if (currentNode.Item.data == null || currentNode.Item.count.Equals(0))
{
currentNode.Item.data = item;
currentNode.Item.count = 1;
return;
}
var comparisonValue = item.CompareTo(currentNode.Item.data);
if (comparisonValue > 0)
{
if (currentNode.Right == null)
{
currentNode.Right = new Node(item);
return;
}
Debug.WriteLine($"{item} > {currentNode.Item.data} → move to right lower node..");
currentNode = currentNode.Right;
}
else if (comparisonValue.Equals(0))
{
currentNode.Item.count++;
return;
}
else
{
if (currentNode.Left == null)
{
currentNode.Left = new Node(item);
return;
}
Debug.WriteLine($"{item} < {currentNode.Item.data} → move to left lower node..");
currentNode = currentNode.Left;
}
}
}
/// <summary>
/// Removes the specific item inside the binary-tree using binary-tree logic.
/// </summary>
/// <param name="item">The item that will be removed.</param>
/// <param name="fullyRemoval">When set on true will remove said item without any respect towards their count.</param>
public void Remove(T item, bool fullyRemoval = false)
{
Debug.WriteLine("Removing an item in this binary-tree..");
var currentNode = _parentNode;
Node prevNode = default;
while (true)
{
if (currentNode.Item.data == null) return;
var comparisonValue = item.CompareTo(currentNode.Item.data);
if (comparisonValue > 0)
{
if (currentNode.Right == null) return;
(prevNode, currentNode) = (currentNode, currentNode.Right);
}
else if (comparisonValue.Equals(0))
{
if (currentNode.Item.count > 1 && !fullyRemoval)
currentNode.Item.count--;
else
SkipNode(prevNode, currentNode);
return;
}
else
{
if (currentNode.Left == null) return;
(prevNode, currentNode) = (currentNode, currentNode.Left);
}
}
}
private void SkipNode(Node prevNode, Node nodeToSkip)
{
var countOfFurtherNodes = 0;
if (nodeToSkip.Right != null) countOfFurtherNodes++;
if (nodeToSkip.Left != null) countOfFurtherNodes++;
if (prevNode == null)
{
switch (countOfFurtherNodes)
{
case 0:
nodeToSkip.Item = (default(T), 0);
return;
case 1:
nodeToSkip.Item = nodeToSkip.Right?.Item ?? nodeToSkip.Left.Item;
return;
case 2:
var temp = SearchForLeftMostRightNode(nodeToSkip);
Remove(temp.Item.data, true);
temp.Left = nodeToSkip.Left;
temp.Right = nodeToSkip.Right;
nodeToSkip.Item = temp.Item;
return;
}
}
var rightPath = nodeToSkip.Item.data.CompareTo(prevNode.Item.data);
switch (countOfFurtherNodes)
{
case 0 when rightPath > 0:
prevNode.Right = null;
break;
case 0:
prevNode.Left = null;
break;
case 1 when rightPath > 0:
prevNode.Right = nodeToSkip.Right ?? nodeToSkip.Left;
break;
case 1:
prevNode.Left = nodeToSkip.Right ?? nodeToSkip.Left;
break;
case 2 when rightPath > 0:
var temp = SearchForLeftMostRightNode(nodeToSkip);
Remove(temp.Item.data, true);
temp.Left = nodeToSkip.Left;
temp.Right = nodeToSkip.Right;
prevNode.Right = temp;
break;
case 2:
var temp2 = SearchForLeftMostRightNode(nodeToSkip);
Remove(temp2.Item.data, true);
temp2.Left = nodeToSkip.Left;
temp2.Right = nodeToSkip.Right;
prevNode.Left = temp2;
break;
}
}
private Node SearchForLeftMostRightNode(Node node)
{
if (node.Right == null) return node;
node = node.Right;
while (node.Left != null) node = node.Left;
return node;
}
/// <summary>
/// Searches for a specific item inside this binary-tree using binary-tree logic.
/// </summary>
/// <param name="item"></param>
/// <returns>Returns the count of said item if existing - 0 if otherwise.</returns>
public int Contains(T item)
{
Debug.WriteLine("Searching an item in this binary-tree..");
var currentNode = _parentNode;
while (true)
{
if (currentNode.Item.data == null) return 0;
var comparisionValue = item.CompareTo(currentNode.Item.data);
if (comparisionValue > 0)
{
if (currentNode.Right == null) return 0;
Debug.WriteLine($"{item} > {currentNode.Item.data} → search in right lower node..");
currentNode = currentNode.Right;
}
else if (comparisionValue.Equals(0))
{
return currentNode.Item.count;
}
else
{
if (currentNode.Left == null) return 0;
Debug.WriteLine($"{item} < {currentNode.Item.data} → search in left lower node..");
currentNode = currentNode.Left;
}
}
}
/// <summary>
/// Clears everything out of this binary-tree.
/// </summary>
public void Clear()
{
Debug.WriteLine("Clearing this binary-tree..");
_parentNode = new Node();
}
public override bool Equals(object obj)
{
return obj is BinaryTree<T> tree && tree._parentNode.Equals(_parentNode);
}
public void Serialize(string file)
{
using (var writer = new StreamWriter(file))
{
var bf = new BinaryFormatter();
bf.Serialize(writer.BaseStream, this);
}
}
public static BinaryTree<T> Deserialize(string file)
{
using (var reader = new StreamReader(file))
{
var bf = new BinaryFormatter();
return (BinaryTree<T>) bf.Deserialize(reader.BaseStream);
}
}
public override int GetHashCode()
{
return HashCode.Combine(_parentNode);
}
/// <summary>
/// Represents a node of a binary-tree. This may be either a simple node, a parent, or a leaf.
/// </summary>
/// <typeparam name="T">The type which this node should contain.</typeparam>
[Serializable]
[DataContract]
private class Node
{
/// <summary>
/// Saved data and count of data - inside this specific node.
/// </summary>
[DataMember] internal (T data, int count) Item;
/// <summary>
/// Left "lower" arm of current node - this is where everything smaller than this node is getting redirect towards.
/// </summary>
[DataMember] internal Node Left;
/// <summary>
/// Right "lower" arm of current node - this is where everything bigger than this node is getting redirect towards.
/// </summary>
[DataMember] internal Node Right;
internal Node(T item)
{
Item = (item, 1);
}
internal Node()
{
}
public override bool Equals(object obj)
{
return obj is Node node &&
(node.Right?.Equals(Right) ?? Right == null) &&
(node.Item.data?.CompareTo(Item.data).Equals(0) ?? Item.data == null) &&
node.Item.count.Equals(Item.count) &&
(node.Left?.Equals(Left) ?? Left == null);
}
public override int GetHashCode()
{
return HashCode.Combine(Right, Item, Left);
}
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T14:59:14.967",
"Id": "412768",
"Score": "1",
"body": "Do you have any unit tests?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T15:59:30.390",
"Id": "412783",
"Score": "0",
"body": "Yes, you can find those in my repo."
}
] | [
{
"body": "<p>Here's a new unit test which currently fails. Add</p>\n\n<pre><code>using System.Collections.Generic;\nusing System.Linq;\n</code></pre>\n\n<p>and then</p>\n\n<pre><code> [TestMethod]\n public void TestCombinations()\n {\n // Test all sequences of 5 operations drawn from adding and removing four distinct elements.\n for (int i = 0; i < 1 << 15; i++)\n {\n var list = new List<int>();\n var tree = new BinaryTree<int>();\n\n var program = i;\n for (int j = 0; j < 5; j++)\n {\n int instruction = program & 1;\n program >>= 1;\n int value = program & 3;\n program >>= 2;\n\n if (instruction == 0)\n {\n list.Add(value);\n tree.Add(value);\n }\n else\n {\n list.Remove(value);\n tree.Remove(value);\n }\n\n for (value = 0; value < 4; value++)\n {\n Assert.AreEqual(list.Count(elt => elt == value), tree.Contains(value));\n }\n }\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T20:06:36.120",
"Id": "412830",
"Score": "0",
"body": "I have updated my repo - your unit-test has been added and the bug fixed! Thank you very much again for your response."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T16:32:39.427",
"Id": "213389",
"ParentId": "213380",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213389",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T14:26:15.380",
"Id": "213380",
"Score": "2",
"Tags": [
"c#",
".net",
"tree",
".net-core"
],
"Title": "Revision: BinaryTree<T> written in C#"
} | 213380 |
<p>I'm currently trying to teach myself Vue.js and I've just created my first small project: a simple todo list. While writing the component I discovered that you can't access methods from the parent component directly, but I didn't want to put one half of the code in the child component (the <code>deleteToDo</code> method), so I've passed a callback to it. Is this okay in Vue or is there any other preferred way of structuring things like this?</p>
<p><a href="https://jsfiddle.net/8q6vznfa/" rel="nofollow noreferrer">JSFiddle</a></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>Vue.component('todo-item', {
props: ['todo', 'delete_callback'],
template: `<li>
<input type="checkbox" v-model="todo.done">
<input v-model="todo.text" :disabled="todo.done" @change="todoChanged(todo)">
<a @click="delete_callback(todo)">X</a>
</li>`,
methods: {
todoChanged: function (todo) {
if (this.todo.text == '') {
this.delete_callback(todo);
}
}
}
});
var vm = new Vue({
el: '#app',
data: {
show: {
todo: true,
done: false
},
todos: [
{
id: 0,
text: 'Test this stuff',
done: true
},
{
id: 1,
text: 'Learn more Vue',
done: false
},
{
id: 2,
text: 'Buy some tasty food',
done: false
}
]
},
methods: {
addTodo: function (event) {
if (event instanceof KeyboardEvent && event.key != 'Enter') {
return;
}
if (event.target.value != '') {
this.todos.push({
id: this.todos.length,
text: event.target.value,
done: false
});
event.target.value = '';
}
},
deleteToDo: function (todo) {
this.todos.splice(todo.id, 1);
for (let i = 0; i < this.todos.length; i++) {
this.todos[i].id = i;
}
}
}
})</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
box-sizing: border-box;
}
body {
font: 16px "Helvetica Neue", status-bar;
background-color: #444444;
}
#app {
max-width: 400px;
margin: 3rem auto;
padding: 1rem 3rem 3rem 3rem;
background-color: #dddddd;
color: #444444;
}
li {
list-style: none;
}
li > input:disabled {
text-decoration: line-through;
}
li > a, h4 > span {
font-size: 0.7rem;
}
li > a:hover {
cursor: pointer;
color: #222222;
}
#newtodo {
margin-left: 23px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>ToDo</title>
<script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
<link rel="stylesheet" href="test.css">
</head>
<body>
<div id="app">
<h1>ToDo List</h1>
<h4 @click="show.todo = !show.todo">To Do: {{ todos.filter(todo => !todo.done).length }} <span>({{ show.todo ? 'Hide' : 'Show' }})</span></h4>
<ul v-show="show.todo">
<todo-item v-for="todo in todos" v-if="!todo.done" :todo="todo" :key="todo.id" :delete_callback="deleteToDo"></todo-item>
<input id="newtodo" type="text" placeholder="New todo item" @keypress="addTodo" @blur="addTodo"></input>
</ul>
<h4 @click="show.done = !show.done">Done: {{ todos.filter(todo => todo.done).length }} <span>({{ show.done ? 'Hide' : 'Show' }})</span></h4>
<ul v-show="show.done">
<todo-item v-for="todo in todos" v-if="todo.done" :todo="todo" :key="todo.id" :delete_callback="deleteToDo"></todo-item>
</ul>
</div>
<script src="test.js"></script>
</body>
</html></code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T17:46:36.857",
"Id": "412809",
"Score": "0",
"body": "Thanks @SᴀᴍOnᴇᴌᴀ! I didn't know about this feature yet. I've included both the HTML and CSS snippets as well now."
}
] | [
{
"body": "<h2>Your question</h2>\n\n<blockquote>\n <p>so I've passed a callback to it. Is this okay in Vue or is there any other preferred way of structuring things like this?</p>\n</blockquote>\n\n<p>If you haven't already, I would suggest you read the VueJS <a href=\"https://vuejs.org/v2/guide/components.html\" rel=\"nofollow noreferrer\">documentation for <strong>Components</strong></a> - specifically the section <a href=\"https://vuejs.org/v2/guide/components.html#Listening-to-Child-Components-Events\" rel=\"nofollow noreferrer\"><em>Listening to Child Components Events</em></a>. Basically the child component can utilize the built-in <a href=\"https://vuejs.org/v2/api/#vm-emit\" rel=\"nofollow noreferrer\"><code>$emit</code> method</a> to emit an event, which can be handled by the parent using <code>v-on</code>.</p>\n\n<p>BTW the last section of the <a href=\"https://vuejs.org/v2/guide/list.html\" rel=\"nofollow noreferrer\">Documentation page <strong>List rendering</strong></a> has a section <a href=\"https://vuejs.org/v2/guide/list.html#v-for-with-a-Component\" rel=\"nofollow noreferrer\"><em><code>v-for</code> with a Component</em></a> that includes a simple TODO list using <code>$emit</code>. </p>\n\n<hr>\n\n<h3>Other feedback</h3>\n\n<p>You might want to consider using a <em>key</em> that is the index of each item - see the second example of <a href=\"https://vuejs.org/v2/guide/list.html#Mapping-an-Array-to-Elements-with-v-for\" rel=\"nofollow noreferrer\">Mapping an Array to Elements with <code>v-for</code></a> of the documentation:</p>\n\n<pre><code><todo-item v-for=\"(todo, index) in todos\" v-if=\"todo.done\" :todo=\"todo\" :key=\"index\"\n</code></pre>\n\n<p>That way you don't have to re-assign the id values when deleting an item.</p>\n\n<hr>\n\n<p>The Vue object is assigned to a variable <code>vm</code></p>\n\n<pre><code>var vm = new Vue({\n</code></pre>\n\n<p>but it is never used after that. According to <a href=\"https://eslint.org\" rel=\"nofollow noreferrer\">ESLint</a>: \"<em>Such variables take up space in the code and can lead to confusion by readers.</em>\"<sup><a href=\"https://eslint.org/docs/rules/no-unused-vars\" rel=\"nofollow noreferrer\">1</a></sup>.</p>\n\n<hr>\n\n<p>The text input element for the new item has a separate closing tag: </p>\n\n<blockquote>\n<pre><code><input id=\"newtodo\" type=\"text\" placeholder=\"New todo item\" @keypress=\"addTodo\" @blur=\"addTodo\"></input>\n</code></pre>\n</blockquote>\n\n<p>But input elements have no permitted content<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input\" rel=\"nofollow noreferrer\">2</a></sup> <sup><a href=\"https://html.spec.whatwg.org/multipage/input.html#the-input-element\" rel=\"nofollow noreferrer\">3</a></sup> and thus are <a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Empty_element\" rel=\"nofollow noreferrer\">empty elements</a>.</p>\n\n<blockquote>\n <p><em>In HTML, using a closing tag on an empty element is usually invalid. For example, <code><input type=\"text\"></input></code> is invalid HTML.</em><sup><a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Empty_element\" rel=\"nofollow noreferrer\">4</a></sup></p>\n</blockquote>\n\n<p>The jsFiddle syntax highlighting also points this out (I added some colored boxes to point this out):</p>\n\n<p><a href=\"https://i.stack.imgur.com/BV0wN.png\" rel=\"nofollow noreferrer\"><img src=\"https://i.stack.imgur.com/BV0wN.png\" alt=\"jsFiddle syntax highlighting\"></a></p>\n\n<p>Because of this, the closing slash can be added to the end of the start tag:</p>\n\n<pre><code><input id=\"newtodo\" type=\"text\" placeholder=\"New todo item\" @keypress=\"addTodo\" @blur=\"addTodo\" />\n</code></pre>\n\n<p><sup>1</sup><sub><a href=\"https://eslint.org/docs/rules/no-unused-vars\" rel=\"nofollow noreferrer\">https://eslint.org/docs/rules/no-unused-vars</a></sub></p>\n\n<p><sup>2</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input</a></sub></p>\n\n<p><sup>3</sup><sub><a href=\"https://html.spec.whatwg.org/multipage/input.html#the-input-element\" rel=\"nofollow noreferrer\">https://html.spec.whatwg.org/multipage/input.html#the-input-element</a></sub></p>\n\n<p><sup>4</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Glossary/Empty_element\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Glossary/Empty_element</a></sub></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T00:04:06.823",
"Id": "412847",
"Score": "2",
"body": "Thank you very much! This is a great answer :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-21T16:07:08.860",
"Id": "505975",
"Score": "0",
"body": "@SamOnela I'm seeing the mentioned vue todo https://vuejs.org/v2/guide/list.html but it appears there is not method defined that removes a todo item..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-02-22T18:50:47.403",
"Id": "506077",
"Score": "1",
"body": "@RobertRocha - that is true - notice that the remove button is coded as `<button v-on:click=\"$emit(\\'remove\\')\">Remove</button>` so when it is clicked it doesn't call a method on the todo-item component but rather emits an event to the parent. Note that the parent element has `v-on:remove=\"todos.splice(index, 1)\"` on the `<li is=\"todo-item\"` element so it doesn't need a method but one could certainly call a method in either place if it was necessary."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T18:25:01.813",
"Id": "213398",
"ParentId": "213381",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "213398",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T14:30:19.560",
"Id": "213381",
"Score": "5",
"Tags": [
"javascript",
"beginner",
"ecmascript-6",
"to-do-list",
"vue.js"
],
"Title": "Passing a callback to a component in Vue.js"
} | 213381 |
<h2>Context</h2>
<p>I have blocks of if statements that check if a certain cell contains a particular string and to add to the counter of the respective custom property. Originally I was using global variables, but those are zeroed out when excel crashes. I learned of custom document properties and their non-volatility and made the switch. However, adding to the counter is a long, barely readable statement.</p>
<p>With global variables I had a statement like:</p>
<pre><code>If cell = "Heavy Duty" Then numHD = numHD + 4
</code></pre>
<p>But now statements look like:</p>
<pre><code>If cell = "Heavy Duty" Then ThisWorkbook.CustomDocumentProperties("numHD").Value = ThisWorkbook.CustomDocumentProperties("numHD").Value + 4
</code></pre>
<p>It's immensely longer and with 27 other statements doing the same thing for other strings, the code becomes taxing to read.</p>
<h2>What I would like</h2>
<p>Is there a way that I can shorten the custom document property edits to look more in line with what I had before with global variables? I had tried setting up a global variable as a properties type and setting to the property, then just using the variable in the actual sub:</p>
<pre><code>Public numHD As Properties
Set numHD = ThisWorkbook.CustomDocumentProperties("numHD")
Sub count()
If cell = "Heavy Duty" Then numHD = numHD + 4
End Sub
</code></pre>
<p>But Set cannot be used outside of a sub or function apparently. Any advice?</p>
| [] | [
{
"body": "<p>Writing to a document property is a concern in its own right, and thus deserves its own scope. Write a procedure that's responsible only for this!</p>\n\n<pre><code>Public Sub IncrementHeavyDutyCount(ByVal increment As Long)\n With ThisWorkbook.CustomDocumentProperties.Item(\"numHD\")\n .Value = .Value + increment\n End With\nEnd Sub\n</code></pre>\n\n<p>And now you can increment your counter with a simple, self-explanatory procedure call:</p>\n\n<pre><code>If cell = \"Heavy Duty\" Then IncrementHeavyDutyCount 4\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T15:55:07.253",
"Id": "412781",
"Score": "0",
"body": "Can you elaborate on what makes writing to a document property a concern? Maybe I'm misunderstanding something. All of my research, which admittedly was quite some time ago, pointed to this being the best route."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T17:09:51.407",
"Id": "412803",
"Score": "1",
"body": "@LuxClaridge rather hard to explain when all context I have is a single line of code from your project, but as a general rule of thumb, adhering to the *Single Responsibility Principle* means writing small procedures that are responsible for as little as possible - a procedure that does one thing, only has one reason to fail. In this case, \"index out of range\" if there's no `\"numHD\"` custom property in `ThisWorkbook`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T18:50:35.960",
"Id": "412823",
"Score": "2",
"body": "My own approach when wanting to \"save\" application-specific values within a workbook is to create an \"ApplicationData\" worksheet and store all my data there. Quite often, I'll make that worksheet `hidden` (and sometimes `veryhidden`). Data on a worksheet is automatically persistent storage in this respect. So while in the distant past I researched the possibility of using document properties, I've never had the need for them."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T14:06:19.217",
"Id": "412923",
"Score": "0",
"body": "@MathieuGuindon Oh now I understand. Thanks!"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T15:50:33.763",
"Id": "213385",
"ParentId": "213382",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "213385",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T14:51:05.243",
"Id": "213382",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Shortening Custom Document Property additions"
} | 213382 |
<p>I have a DataFrame that has a text column. I am splitting the DataFrame into two parts based on the value in another column. One of those parts is indexed into a gensim similarity model. The other part is then fed into the model to find the indexed text that is most similar. This involves a search function to enumerate over each item in the indexed part. </p>
<p>The goal is to compare each row in df_yes with the sims index (which consists of all rows from df_no. So the function is applied to each row in df_yes and, for each row, find the maximum similarity value and index(ices) of df_no.</p>
<p>With the toy data, it is fast, but with my real data, it is much too slow using <code>apply</code>. Here is the code example:</p>
<pre><code>import pandas as pd
import gensim
import nltk
from nltk.tokenize import word_tokenize
nltk.download('punkt')
d = {'number': [1,2,3,4,5], 'text': ['do you like python', 'do you hate python','do you like apples','who is nelson mandela','i am not interested'], 'answer':['no','yes','no','no','yes']}
df = pd.DataFrame(data=d)
df_yes = df[df['answer']=='yes']
df_no = df[df['answer']=='no']
df_no = df_no.reset_index()
docs = df_no['text'].tolist()
genDocs = [[w.lower() for w in word_tokenize(text)] for text in docs]
dictionary = gensim.corpora.Dictionary(genDocs)
corpus = [dictionary.doc2bow(genDoc) for genDoc in genDocs]
tfidf = gensim.models.TfidfModel(corpus)
sims = gensim.similarities.MatrixSimilarity(tfidf[corpus], num_features=len(dictionary))
def get_search_results(row):
tokenized_row = word_tokenize(row)
query_bag_of_words = dictionary.doc2bow(tokenized_row)
query_tfidf = tfidf[query_bag_of_words]
search_result = sims[query_tfidf]
max_similarity = max(search_result)
index = [i for i, j in enumerate(search_result) if j == max_similarity]
return max_similarity, index
df_yes = df_yes.copy()
df_yes['max_similarity'], df_yes['index'] = zip(*df_yes['text'].apply(get_search_results))
</code></pre>
<p>I have tried converting the operations to dask dataframes to no avail, as well as python multiprocessing. How would I make these functions more efficient? Is it possible to vectorize some/all of the functions? </p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T16:12:35.903",
"Id": "213387",
"Score": "1",
"Tags": [
"python",
"performance",
"python-3.x",
"pandas"
],
"Title": "Optimize Application of Python Gensim Search Functions"
} | 213387 |
<p>The following program displays a menu, and prompts the user to choose an option. Options include to add a book, delete a book, view all books, and to exit the program. (Note that the actual code to implement the database functions will be added later.)</p>
<p>The program files were compiled with no error messages or warnings using the following command line...</p>
<p><code>$gcc -std=c99 -Wall -Wextra -Wpedantic main.c screen.c input.c database.c -o books</code></p>
<p>I would like your feedback on any potential issues, along with any improvements that can be made to the code. </p>
<p>Here are the files:</p>
<p><strong>main.c</strong></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include "struct.h"
#include "screen.h"
#include "input.h"
#include "database.h"
/* display main menu and prompt user to choose menu option */
int main(int argc, char *argv[])
{
if (argc != 1)
{
fprintf(stderr, "Usage: %s\n", argv[0]);
exit(EXIT_FAILURE);
}
/* name of file to store data in */
const char dataFile[] = "database.bin";
/* array of structs containing menu options (number, text, and function) */
menuStruct menuArray[] = {
{ 1, "Add book", addBook },
{ 2, "Delete book", deleteBook },
{ 3, "View all books", viewAllBooks }
};
/* number of menu items */
int menuArrayLength = sizeof(menuArray)/sizeof(menuArray[0]);
int menuChoice;
void(*menuFunction)(const char fname[]);
/* prompt user to choose menu option */
while (1)
{
clearScreen();
displayMainMenu(menuArray, menuArrayLength);
menuChoice = getMenuChoice();
if (menuChoice == (menuArrayLength + 1))
{
clearScreen();
exit(EXIT_SUCCESS);
}
menuFunction = getMenuFunction(menuChoice, menuArray, menuArrayLength);
if (menuFunction != NULL)
{
menuFunction(dataFile);
}
else
{
fprintf(stderr, "\n Invalid entry, press ENTER to continue");
flushInput();
}
}
return 0;
}
</code></pre>
<p><strong>struct.h</strong></p>
<pre><code>#ifndef STRUCT_H
#define STRUCT_H
#define MAXSTRLEN 50 /* max length for string */
/* struct to hold a menu choice (number, text, and function) */
typedef struct menuStruct
{
int menuChoice;
char menuText[MAXSTRLEN];
void (*menuFunction)(const char *fname);
} menuStruct;
/* struct to hold details of a book */
typedef struct bookStruct
{
char id[MAXSTRLEN];
char title[MAXSTRLEN];
char author[MAXSTRLEN];
double price;
} bookStruct;
#endif
</code></pre>
<p><strong>screen.h</strong></p>
<pre><code>#ifndef SCREEN_H
#define SCREEN_H
#include "struct.h"
/* displayMainMenu(): display the main menu using menuArray where each element in the array
is a struct containing a menu choice (number, text, and function), except the exit option */
void displayMainMenu(const menuStruct menuArray[], const int menuArrayLength);
/* displayAddBookHeader(): display the header for adding a book */
void displayAddBookHeader();
/* displayDeleteBookHeader(): display the header for deleting a book */
void displayDeleteBookHeader();
/* displayViewAllBooksHeader(): display the header for viewing all books */
void displayViewAllBooksHeader();
/* clearScreen(): clear the screen */
void clearScreen();
#endif
</code></pre>
<p><strong>screen.c</strong></p>
<pre><code>#include <stdio.h>
#include "screen.h"
void displayMainMenu(const menuStruct menuArray[], const int menuArrayLength)
{
printf(" \n"
"=============================================================================\n"
" Database for Book Collection \n"
" Menu Choices \n"
"=============================================================================\n");
for (int i = 0; i < menuArrayLength; i++)
{
printf("\n %d. %s", menuArray[i].menuChoice, menuArray[i].menuText);
}
printf("\n %d. Exit\n", menuArrayLength + 1); /* exit option for main menu */
}
void displayAddBookHeader()
{
printf(" \n"
"=============================================================================\n"
" Database for Book Collection \n"
" Add Book \n"
"=============================================================================\n");
}
void displayDeleteBookHeader()
{
printf(" \n"
"=============================================================================\n"
" Database for Book Collection \n"
" Delete Book \n"
"=============================================================================\n");
}
void displayViewAllBooksHeader()
{
printf(" \n"
"=============================================================================\n"
" Database for Book Collection \n"
" View All Books \n"
"=============================================================================\n");
}
void clearScreen()
{
printf("\x1b[2J\x1b[1;1H");
}
</code></pre>
<p><strong>input.h</strong></p>
<pre><code>#ifndef INPUT_H
#define INPUT_H
#include "struct.h"
/* getMenuChoice(): prompt user to enter menu choice and return choice */
int getMenuChoice();
/* getMenuFunction(): search each struct within menuArray for option matching menuChoice and return corresponding function */
void(*getMenuFunction(const int menuChoice, const menuStruct menuArray[], const int size))(const char fname[]);
/* flush input from buffer */
void flushInput();
#endif
</code></pre>
<p><strong>input.c</strong></p>
<pre><code>#include <stdio.h>
#include <string.h>
#include "input.h"
#define MAXSTRLEN 50
int getMenuChoice()
{
printf("\n Enter Choice: ");
char userInput[MAXSTRLEN], junk[MAXSTRLEN];
int menuChoice;
fgets(userInput, sizeof(userInput), stdin);
if (strchr(userInput, '\n') == NULL)
{
flushInput();
return 0;
}
if (sscanf(userInput, "%d%[^\n]", &menuChoice, junk) != 1)
{
return 0;
}
return menuChoice;
}
void(*getMenuFunction(const int menuChoice, const menuStruct menuArray[], const int size))(const char fname[])
{
for (int i = 0; i < size; i++)
{
if (menuChoice == menuArray[i].menuChoice)
return menuArray[i].menuFunction;
}
return NULL;
}
void flushInput()
{
int c;
while ((c = getchar()) != '\n' && c != EOF)
{
/* skip it */;
}
}
</code></pre>
<p><strong>database.h</strong></p>
<pre><code>#ifndef DATABASE_H
#define DATABASE_H
void addBook(const char fname[]);
void deleteBook(const char fname[]);
void viewAllBooks(const char fname[]);
#endif
</code></pre>
<p><strong>database.c</strong></p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include "input.h"
#include "database.h"
void addBook(const char fname[])
{
printf("\n Inside addBook(): fname = %s, press ENTER to continue", fname);
flushInput();
}
void deleteBook(const char fname[])
{
printf("\n Inside deleteBook(): fname = %s, press ENTER to continue", fname);
flushInput();
}
void viewAllBooks(const char fname[])
{
printf("\n Inside viewAllBooks(): fname = %s, press ENTER to continue", fname);
flushInput();
}
</code></pre>
| [] | [
{
"body": "<p>Be wary of this:</p>\n\n<blockquote>\n<pre><code>void clearScreen()\n{\n printf(\"\\x1b[2J\\x1b[1;1H\");\n}\n</code></pre>\n</blockquote>\n\n<p>Whilst many terminals support the ANSI command set, not all do, so hard-coding this escape code will limit the program's flexibility.</p>\n\n<p>There are libraries (such as Curses) that help with this, but that's likely overkill for this purpose. The pragmatic approach here is to outsource to the standard command using <code>system()</code> - on POSIX systems, you'll just invoke <code>clear</code>, for example.</p>\n\n<p>That said, I'd advise against clearing screen repeatedly - it makes it much harder for the user to go back and review the actions that have been performed.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T20:10:28.613",
"Id": "412832",
"Score": "0",
"body": "I thought clearing the screen would present things in a more \"clean\" fashion, but I agree with your point. I'll avoid it completely. Toby, thank you very much for your help. Cheers!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-10-17T21:04:38.847",
"Id": "493431",
"Score": "0",
"body": "`system()` is horrible from a performance standpoint, and it's not portable either. I would say it's even less portable than the ANSI sequence. But I fully agree with not clearing the screen to begin with :)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T17:18:20.927",
"Id": "213394",
"ParentId": "213390",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T16:39:16.277",
"Id": "213390",
"Score": "8",
"Tags": [
"c",
"database"
],
"Title": "Maintain non-persistent database for books"
} | 213390 |
<p>While implementing socket.io on my server, I ran into some problems and eventually fixed them. The code below is fired on the connection event of socket.io:</p>
<pre><code>var newarray = []; //a new array
data.map(function(inde) { //data is an array which contains the data of the user's acc_id and some more information,
newarray.push({
enc: inde.fjbngh, //encrypted acc_id
hmac: inde.asdty2 //hmac
})
});
var users = []; // a new array which will contain the decrypted acc_id's
newarray.forEach(function(llol) {
var dec = _SOME_DECRYPTION_FUNCTION_WITH_HMAC;
users.push(dec); // decrypted acc_id stored in the array
})
uniq = [...new Set(users)]; // To get one values out of any unique values as with every user, i'm getting the logged in user's id, so this code whole code is executed once (not in a foreach loop)
var idst = {}; // a new object
idst['socket_id'] = socket.id;
idst['acc_id'] = Number(uniq[0]);
ids.push(idst);// ids is the main global array which contains the socket_id with a unique acc_id.
</code></pre>
<p>The job of the code above is to procure the <code>acc_id</code> of the logged in user and store it in a global array, by which we can know if a user is online or not.</p>
<p>This code fires up on the connection event of socket.io, and the reason why I'm storing <code>acc_id</code> with <code>socket_id</code> is that, whenever a user opens a new tab, web sockets gets 2 unique clients from the same browser but different tabs, so I saved it with an <code>acc_id</code>to avoid multiple clients from the same browser.</p>
<p>The reason for all the filtering is because, it's the connection event and with that, I'm sending all the <code>acc_id</code>(s) of the users, the logged in user needs to chat. I have settled that procedure.</p>
<p>Example of the data array object:</p>
<pre><code>[{ id_of_another_user:'xx', hmac:'xx', id_of_logged_in_user:'xx', hmac:'xx'}]
</code></pre>
<p>On disconnection, the user is removed from the <code>ids</code> array. My question is, does this code perform its job in the most efficient way possible?</p>
<p>I have another doubt that might make this question broad, so I'll ask it later.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T17:42:17.517",
"Id": "213395",
"Score": "1",
"Tags": [
"javascript",
"array",
"node.js",
"socket.io"
],
"Title": "Filtering users in socket.io and seeing who is online"
} | 213395 |
<p>The task:</p>
<blockquote>
<p>Given an integer n and a list of integers l, write a function that
randomly generates a number from 0 to n-1 that isn't in l (uniform).</p>
</blockquote>
<p>Solution 1:</p>
<pre><code>const getRandNotInList = (n , list) => {
const rand = Math.floor(Math.random() * n);
return list.includes(rand) ? getRandNotInList(n, list) : rand;
};
console.log(getRandNotInList(16, [1,2,3,4]));
</code></pre>
<p>Solution 2:</p>
<pre><code>const getRandNotInList2 = (n, list) => {
let rand;
do { rand = Math.floor(Math.random() * n); }
while(list.includes(rand));
return rand;
};
console.log(getRandNotInList2(13, [2,3,4,5,6]));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T18:23:00.383",
"Id": "412815",
"Score": "0",
"body": "what does `l (uniform)` mean? quick google search gave me list of school uniforms."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T18:43:05.653",
"Id": "412818",
"Score": "1",
"body": "Probably uniform random numbers:\nhttps://de.mathworks.com/help/simulink/slref/uniformrandomnumber.html"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T18:43:59.587",
"Id": "412819",
"Score": "0",
"body": "yeah that makes sense. I thought it was the list that was uniform."
}
] | [
{
"body": "<p>When you run Solution 1 with the following parameters:</p>\n\n<pre><code>getRandNotInList(4, [0,1,2,3])\n</code></pre>\n\n<p>you quickly get an error, at least in Google Chrome.</p>\n\n<blockquote>\n <p>Uncaught RangeError: Maximum call stack size exceeded</p>\n</blockquote>\n\n<p>This is because JavaScript engines typically don't implement tail recursion.</p>\n\n<p>Therefore I prefer Solution 2 over Solution 1, which just leads to an endless loop.</p>\n\n<p>(Note to myself: Don't try endless loops in the browser. Google Chrome will just freeze completely.)</p>\n\n<p>Therefore a proper solution should not end in an endless loop. Just check whether <code>list.length >= n</code> and throw an exception in such a case. If the list should ever contain duplicates that's the problem of the caller.</p>\n\n<pre><code>const getRandNotInList3 = (n, list) => {\n if (list.length >= n) throw \"blacklist must not forbid all possible elements\";\n let rand;\n do { rand = Math.floor(Math.random() * n); }\n while(list.includes(rand));\n return rand;\n};\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T01:12:48.080",
"Id": "412849",
"Score": "1",
"body": "How do you know if the list length is greater than n that it contains any values between 0 and n, Eg `getRandNotInList(2, [5,6,7])` would incorrectly throw!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T13:31:26.823",
"Id": "412922",
"Score": "0",
"body": "@Blindman67 Thanks for finding this. I had only thought about duplicate values in the list."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T19:09:31.160",
"Id": "213401",
"ParentId": "213397",
"Score": "1"
}
},
{
"body": "<p>As already mentioned, most JS engines don't do <a href=\"https://en.wikipedia.org/wiki/Tail_recursion\" rel=\"nofollow noreferrer\">TCO</a> so your recursive approach may stack overflow. Often, functional programming in Javascript means using the functional utilities like <code>map</code> and <code>reduce</code> with closures.</p>\n\n<p>So, your second solution is preferable in this regard. Although, I'd clean it up a little to be a regular <code>function</code> definition instead of needlessly using fancy ES6 syntax:</p>\n\n<pre><code>function getRandNotIn(below, excluding) {\n // ...\n}\n</code></pre>\n\n<p>One thing to consider, though, is the performance characteristics of doing <code>while (excluding.includes(num))</code>. If you are only excluding a few numbers, it won't be too expensive (and won't be run many times because on average choosing an excluded number will be rare). But, as <code>excluding.length</code> approaches <code>below</code> the statistical expectation is that there will be more collisions, which means more O(n) traversals. You're probably better off using a <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set\" rel=\"nofollow noreferrer\">Set</a> here. Doing so would then allow you to assert:</p>\n\n<pre><code>if (excluding.length >= below) throw \"can't exclude all numbers\";\n</code></pre>\n\n<p>If <code>excluding</code> wasn't a set, then this assertion would be incorrect because a number could be duplicated. You also probably want to assert this for only numbers in <code>0 <= num < below</code> (as numbers outside that range don't count):</p>\n\n<pre><code>if ((new Set(excluding.values.filter(n => 0 <= n && n < below))).length >= below) throw \"...\";\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T20:38:56.173",
"Id": "213406",
"ParentId": "213397",
"Score": "2"
}
},
{
"body": "<p>The problem is backwards. You would never present a exclusion list for random values, rather you would present a list to randomly pick from.</p>\n<p>Anyways to fit the problem.</p>\n<h1>Two ways this can be done</h1>\n<ol>\n<li>Guessing</li>\n<li>Deterministically</li>\n</ol>\n<h2>Guessing</h2>\n<p>Your method use a random guess, you guess that the number is not in the list. If it is you guess again. This works well when the list contains only a small set of the numbers.</p>\n<p>However when the exclusion list gets larger you need to make more guess to find one that is not in the list. The number of guess grows very fast as your exclusion list gets closer to excluding all.</p>\n<p>This is the worst possible performance at <span class=\"math-container\">\\$O(m^{-(1/n)})\\$</span> it has an Infinity</p>\n<p>The other problem with guessing is that you can not know how long the function is going to run for. This makes it totally unsuitable for many real time applications.</p>\n<h2>Deterministically</h2>\n<p>You can improve the overall performance and have a function that has a known fixed time to get a result.</p>\n<p>However is is much slower when the exclusion list is relatively small.</p>\n<p>The performance is linear at <span class=\"math-container\">\\$O(n)\\$</span></p>\n<p>If the exclusion set does not change between calls it get even less complex at <span class=\"math-container\">\\$O(1)\\$</span> which is the best you can get.</p>\n<h2>Example</h2>\n<p>The <span class=\"math-container\">\\$O(n)\\$</span> solution</p>\n<p>It returns <code>undefined</code> if it can not find a number rather than throw. You should not be solving the calling function problems as the other answers suggest.</p>\n<pre><code>const getRandNotInList = (n, list) => {\n const picks = [];\n const getPickable = () => {\n var i = 0; dir = Math.sign(n);\n list = new Set(list);\n while (i !== n) {\n !list.has(i) && picks.push(i);\n i += dir;\n }\n }\n n = Math.floor(n); \n if (n === 0) { return list.includes(0) ? undefined : 0 }\n getPickable();\n return picks[Math.random() * picks.length | 0]; // (| 0) same as Math.floor \n // (only for positive ints).\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-18T22:33:51.753",
"Id": "439961",
"Score": "0",
"body": "Why do not you just use `if (!list.has(i))` but rather `!list.has(i) &&`? (Or even better rename the variable as `set = new Set(list);` so a `list` does not represent a `Set`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-08-19T05:57:23.943",
"Id": "439983",
"Score": "0",
"body": "@KorayTugay I find minimal evaluation more concise for single line statements that are not suited to ternaries. Why create a second variable, that would mean two references to the same data, one as an array and again as a set. However i did use the wrong type of set and should have used a WeakSet"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T01:08:43.807",
"Id": "213417",
"ParentId": "213397",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "213417",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T18:19:27.527",
"Id": "213397",
"Score": "6",
"Tags": [
"javascript",
"algorithm",
"functional-programming",
"comparative-review",
"random"
],
"Title": "Uniformly generate a number from 0 to n-1 that isn't on a blacklist"
} | 213397 |
<p>Never had any programming course. Am not programmer. Does not plan to be.</p>
<p>If anyone has a lot a time to lose, I feel like I have no clue what I'm doing / that a lot of my code is very badly organized.</p>
<p>It's meant to be a "game". Actualy the game is me coding that.</p>
<p>I'm just looking for a review. Yes it's a lot. I know these kind of shit aren't the main point of these exchange, but I'd like to have an enlighted opinion on how shitty is that stuff I managed to create losing hours of work.</p>
<h2>ThisWorkbook - Where controls are :</h2>
<pre><code>Option Explicit
''START GAME''
Sub initialize()
'UserForm1.Show vbModeless
Call GameEvents.init
End Sub
Private Sub Workbook_Activate()
Application.OnKey "{LEFT}", "ThisWorkbook.OnLeftArrowKeyPress"
Application.OnKey "{RIGHT}", "ThisWorkbook.OnRightArrowKeyPress"
Application.OnKey "{UP}", "ThisWorkbook.OnUpArrowKeyPress"
Application.OnKey "{DOWN}", "ThisWorkbook.OnDownArrowKeyPress"
End Sub
Private Sub Workbook_Deactivate()
Application.OnKey "{LEFT}", ""
Application.OnKey "{RIGHT}", ""
Application.OnKey "{UP}", ""
Application.OnKey "{DOWN}", ""
End Sub
'Inputs
Sub OnLeftArrowKeyPress()
Call GameEvents.Move(Hero, 0, -1)
If Hero.Character_IsInside(Maze.BossRoom) = True Then
MsgBox "You Won"
Call Maze.Generate
End If
End Sub
Sub OnRightArrowKeyPress()
Call GameEvents.Move(Hero, 0, 1)
If Hero.Character_IsInside(Maze.BossRoom) = True Then
MsgBox "You Won"
Call Maze.Generate
End If
End Sub
Sub OnUpArrowKeyPress()
Call GameEvents.Move(Hero, -1, 0)
If Hero.Character_IsInside(Maze.BossRoom) = True Then
MsgBox "You Won"
Call Maze.Generate
End If
End Sub
Sub OnDownArrowKeyPress()
Call GameEvents.Move(Hero, 1, 0)
If Hero.Character_IsInside(Maze.BossRoom) = True Then
MsgBox "You Won"
Call Maze.Generate
End If
End Sub
</code></pre>
<h2>Combat interface (Not finished) :</h2>
<pre><code>Dim Enemy As Character
Dim eIndex As Integer
Public Sub LoadChars(h As Character, e As Character, index As String)
Set Enemy = e
eIndex = index
Me.HeroLabel.Caption = h.TheModel
Me.EnemyLabel.Caption = e.TheModel
Me.ATK1.Caption = h.MyAttack
Me.ATK2.Caption = e.MyAttack
Me.HP1.Caption = h.Myhp
Me.HP2.Caption = e.Myhp
End Sub
Private Sub CommandButton1_Click()
Hero.Character_Myhp = Hero.MyBaseHp - Enemy.MyAttack - 1
Me.HP1.Caption = Hero.Character_Myhp
End Sub
Private Sub UserForm_Click()
End Sub
</code></pre>
<h2>GameEvents module - Module that lead the game, where is stored everything.</h2>
<pre><code>Option Explicit
''ENEMIES''
Private Enemies As New Collection
''DOORS''
Private Doors As New Collection
''LOOPS''
Private lpchar As Character
Private lpdoor As Door
''INITIALIZE GAME''
Public Sub init()
Call Stuff.limpieza(Enemies)
Call Stuff.limpieza(Doors)
Set Maze.BossRoom = Nothing
Call Maze.Generate
Call SetChar(Hero, 110, 110, "@")
Call Move(Hero, 0, 0)
Call SetChar(Enemies(5), Enemies(5).Character_MyPosX, Enemies(5).Character_MyPosY, "S")
Call Move(Enemies(5), 0, 0)
Call SetChar(Enemies(6), Enemies(6).Character_MyPosX, Enemies(6).Character_MyPosY, "G")
Call Move(Enemies(6), 0, 0)
Dim testitem As New Items
Call testitem.rnd
Dim testitem1 As New Items
Call testitem1.rnd
Call Hero.AddItemToInventory(testitem)
Call Hero.AddItemToInventory(testitem1)
End Sub
Public Sub PopulateRoom(WhichRoom As Room)
Dim CurrentEnemy As New Enemy
Call SetChar(CurrentEnemy, WhichRoom.x1 + 2, WhichRoom.y1 + 2, "E")
Enemies.Add CurrentEnemy
Call CurrentEnemy.Character_Display
End Sub
Public Sub AddDoorToRoom(WhichRoom As Room)
Dim CurrentDoor As New Door
Call SetDoor(CurrentDoor, WhichRoom)
Doors.Add CurrentDoor
'Call CurrentDoor.DisplayOpen
Call CurrentDoor.DisplayClosed
End Sub
Sub Move(Who As Character, X As Integer, Y As Integer)
Dim EnemyIndex As Integer
Call Who.DisplayOff
Select Case Cells(Who.MyPosX + X, Who.MyPosY + Y).Value
Case "W"
Cells(Who.MyPosX, Who.MyPosY).Value = Who.TheModel
Case "E", "S", "G"
EnemyIndex = FindEnemyIndex(Who.MyPosX + X, Who.MyPosY + Y)
Call OpenFightMenu(Who, Enemies(EnemyIndex), EnemyIndex)
Case Else
Who.MyPosX = Who.MyPosX + X
Who.MyPosY = Who.MyPosY + Y
Call Who.Display
If Who.MyPosX > 50 Or Who.MyPosY > 50 Then
ActiveWindow.ScrollRow = Who.MyPosX - 60
ActiveWindow.ScrollColumn = Who.MyPosY - 60
End If
End Select
End Sub
Private Sub SetChar(char As Character, Optional X As Integer, Optional Y As Integer, Optional Model As String)
char.MyPosX = X
char.MyPosY = Y
char.TheModel = Model
End Sub
Private Sub SetDoor(TheDoor As Door, TheRoom As Room) ''NEED IMPROVEMENT''
Dim longeur As Integer, largeur As Integer 'longeur = x largeur = y
longeur = TheRoom.y2 - TheRoom.y1: largeur = TheRoom.x3 - TheRoom.x1
Select Case TheRoom.MyDirection
Case 0 'UP
TheDoor.x1 = TheRoom.x3
TheDoor.y1 = TheRoom.y1 + Int(longeur / 2)
TheDoor.x2 = TheRoom.x3 + 1
TheDoor.y2 = TheRoom.y1 + Int(longeur / 2)
Case 1 'RIGHT
TheDoor.x1 = TheRoom.x1 + Int(largeur / 2)
TheDoor.y1 = TheRoom.y3
TheDoor.x2 = TheRoom.x1 + Int(largeur / 2)
TheDoor.y2 = TheRoom.y3 - 1
Case 2 'BOTTOM
TheDoor.x1 = TheRoom.x1
TheDoor.y1 = TheRoom.y1 + Int(longeur / 2)
TheDoor.x2 = TheRoom.x1 - 1
TheDoor.y2 = TheRoom.y1 + Int(longeur / 2)
Case 3 'LEFT
TheDoor.x1 = TheRoom.x1 + Int(largeur / 2)
TheDoor.y1 = TheRoom.y2
TheDoor.x2 = TheRoom.x1 + Int(largeur / 2)
TheDoor.y2 = TheRoom.y2 + 1
End Select
End Sub
''FIND ENEMY INDEX FROM ENEMIES COLLECTION''
Private Function FindEnemyIndex(X As Integer, Y As Integer) As Integer
Dim TheEnemyIndex As Integer
Dim count As Integer
count = 1 ''COLLECTIONS INITIALIZE AT 1''
For Each lpchar In Enemies
If lpchar.MyPosX = X And lpchar.MyPosY = Y Then
TheEnemyIndex = count
Exit For
Else
count = count + 1
End If
Next lpchar
FindEnemyIndex = TheEnemyIndex
End Function
Private Sub OpenFightMenu(h As Character, e As Character, index As Integer)
Call Fight.LoadChars(h, e, index)
Fight.Show vbModeless
End Sub
</code></pre>
<h2>Maze - Where the "dungeon" is generated</h2>
<pre><code>Option Explicit
Option Base 0
Private Rooms As New Collection
Private TmpRooms(3) As Room
Public BossRoom As Room ''BOSSROOM''
Sub Generate()
Application.ScreenUpdating = False
randomize
Sheets(1).UsedRange.ClearContents
Sheets(1).UsedRange.Interior.ColorIndex = 0
''SETUP START ROOM''
Dim i As Integer, counter As Integer: counter = 0 ''counter needs to be relative to maze size to find good lastroom of maze. 1 is nice for 150*150
Dim ValidAttempts() As Room
Dim current As New Room
If BossRoom Is Nothing Then
Call SetRoom(current)
Else
Set current = BossRoom
End If
Call SetTmpRooms(current)
Rooms.Add current
current.Draw
Call current.colored(4)
Do While Rooms.count > 0
ValidAttempts = GetValidAttempts(current)
If ValidAttempts(0) Is Nothing And ValidAttempts(1) Is Nothing And ValidAttempts(2) Is Nothing And ValidAttempts(3) Is Nothing Then
If counter = 1 Then
'call clearroom
Call current.colored(3)
Set BossRoom = current
'GameEvents.populateBossRoom
End If
Set current = Stuff.Pop(Rooms)
counter = counter + 1
Else
Set current = Stuff.GetRnd(ValidAttempts)
current.Draw
Call GameEvents.AddDoorToRoom(current)
Call GameEvents.PopulateRoom(current)
Rooms.Add current
End If
Call SetTmpRooms(current)
Loop
Set current = Nothing
Application.ScreenUpdating = True
End Sub
Private Function GetValidAttempts(CurrentRoom As Room) As Room()
Dim i As Integer, count As Integer
Dim ToTry As New Room
Dim ValidAttempts(3) As Room
count = 0
For i = 0 To 3
Set ToTry = New Room
Call AddRooms(ToTry, CurrentRoom)
Call AddRooms(ToTry, TmpRooms(i))
'ToTry.AmIValid LabyrinthSize
Call ToTry.AmIValid
If ToTry.ValidOrNot = 1 Then
Set ValidAttempts(count) = New Room
Call AddRooms(ValidAttempts(count), ToTry) 'ee
count = count + 1
End If
Next i
GetValidAttempts = ValidAttempts
End Function
''ROOMS''
Private Function SetRoom(theroomyouwanttosett As Room, Optional x1 As Integer = 100, Optional y1 As Integer = 100, Optional x2 As Integer = 100, _
Optional y2 As Integer = 120, Optional x3 As Integer = 120, Optional y3 As Integer = 100, Optional x4 As Integer = 100, Optional y4 As Integer = 100, Optional Directio As Integer = 0)
theroomyouwanttosett.x1 = x1
theroomyouwanttosett.y1 = y1
theroomyouwanttosett.x2 = x2
theroomyouwanttosett.y2 = y2
theroomyouwanttosett.x3 = x3
theroomyouwanttosett.y3 = y3
theroomyouwanttosett.x4 = x4
theroomyouwanttosett.y4 = y4
theroomyouwanttosett.MyDirection = Directio
End Function
Private Function AddRooms(theroomyouwanttoset As Room, addroom As Room)
theroomyouwanttoset.x1 = theroomyouwanttoset.x1 + addroom.x1
theroomyouwanttoset.y1 = theroomyouwanttoset.y1 + addroom.y1
theroomyouwanttoset.x2 = theroomyouwanttoset.x2 + addroom.x2
theroomyouwanttoset.y2 = theroomyouwanttoset.y2 + addroom.y2
theroomyouwanttoset.x3 = theroomyouwanttoset.x3 + addroom.x3
theroomyouwanttoset.y3 = theroomyouwanttoset.y3 + addroom.y3
theroomyouwanttoset.x4 = theroomyouwanttoset.x4 + addroom.x4
theroomyouwanttoset.y4 = theroomyouwanttoset.y4 + addroom.y4
theroomyouwanttoset.MyDirection = addroom.MyDirection
End Function
''RANDOMIZE ROOMS''
Private Sub SetTmpRooms(CurrentRoom As Room)
Dim longeur As Integer, largeur As Integer
If Not IsEmpty(TmpRooms) Then Erase TmpRooms
longeur = Int(20 * rnd + 7) 'Columns
largeur = Int(20 * rnd + 7) ' rows
'up
Set TmpRooms(0) = New Room
Call SetRoom(TmpRooms(0), -largeur, 0, -largeur, 0, CurrentRoom.x1 - CurrentRoom.x3 - 1, 0, CurrentRoom.x1 - CurrentRoom.x3 - 1, 0, 0)
'right
Set TmpRooms(1) = New Room
Call SetRoom(TmpRooms(1), 0, CurrentRoom.y2 - CurrentRoom.y1 + 1, 0, longeur, 0, CurrentRoom.y2 - CurrentRoom.y1 + 1, 0, longeur, 1)
'bot
Set TmpRooms(2) = New Room
Call SetRoom(TmpRooms(2), CurrentRoom.x3 - CurrentRoom.x1 + 1, 0, CurrentRoom.x3 - CurrentRoom.x1 + 1, 0, largeur, 0, largeur, 0, 2)
'left
Set TmpRooms(3) = New Room
Call SetRoom(TmpRooms(3), 0, -longeur, 0, CurrentRoom.y1 - CurrentRoom.y2 - 1, 0, -longeur, 0, CurrentRoom.y1 - CurrentRoom.y2 - 1, 3)
End Sub
</code></pre>
<h2>Stuff module - For stuff</h2>
<pre><code> ''Stuff for second axis randomization on maze''
'If randomnumber > 0.49 Then
' Call SetRoom(TmpRooms(i), -largeur, CurrentRoom.y2 - CurrentRoom.y1 + 1, -largeur, longeur, largeur, CurrentRoom.y2 - CurrentRoom.y1 + 1, largeur, longeur)
'Else
' If largeur > CurrentRoom.x3 - CurrentRoom.x1 Then largeur = 1
' Call SetRoom(TmpRooms(i), largeur, CurrentRoom.y2 - CurrentRoom.y1 + 1, largeur, longeur, -largeur, CurrentRoom.y2 - CurrentRoom.y1 + 1, -largeur, longeur)
'End If
'If randomnumber > 0.49 Then
' Call SetRoom(TmpRooms(i), -largeur, -longeur, -largeur, longeur, CurrentRoom.x1 - CurrentRoom.x3 - 1, -longeur, CurrentRoom.x1 - CurrentRoom.x3 - 1, longeur)
'Else
' If longeur > CurrentRoom.y2 - CurrentRoom.y1 Then longeur = 1
' Call SetRoom(TmpRooms(i), -largeur, longeur, -largeur, longeur, CurrentRoom.x1 - CurrentRoom.x3 - 1, longeur, CurrentRoom.x1 - CurrentRoom.x3 - 1, -longeur)
'End If
''EMPTY COLLECTION''
Sub limpieza(ByRef listilla As Collection)
While listilla.count <> 0
listilla.Remove (listilla.count)
Wend
End Sub
''RANDOM FROM ARRAY''
Function GetRnd(arr)
Dim a
Set a = Nothing
While a Is Nothing
Set a = arr(rnd * UBound(arr))
Wend
Set GetRnd = a
End Function
''STACK''
Function Pop(WhichCollection As Collection) As Variant
With WhichCollection
If .count > 0 Then
Set Pop = .item(.count)
.Remove .count
End If
End With
End Function
Function RandomNameGenerator() As String
'PURPOSE: Create a Randomized String of Characters
'SOURCE: www.TheSpreadsheetGuru.com/the-code-vault
Dim RND1 As Variant
Dim RND2 As Variant
RND1 = Array("Sword", "Axe", "Spear", "Dildo", "Pickaxe", "Stick", "Mace", "Hammer", "Gun", "Sniper", _
"Sextoy", "Strap-On", "Trebuchet", "Catapult", "Balista")
RND2 = Array("Destruction", "Thousand thuth", "Pleasure", "Joy", "Mightiness", "Reckoning", "Fear", "Pain", "Wood", "Iron", _
"Mining", "Agility", "Precision", "Superiority", "Defeat", "Death")
'Randomly Select Characters One-by-One
randomize
RandomNameGenerator = RND1(Int((UBound(RND1) - LBound(RND1) + 1) * rnd + LBound(RND1))) & " " & "Of" & " " & RND2(Int((UBound(RND2) - LBound(RND2) + 1) * rnd + LBound(RND2)))
End Function
</code></pre>
<h2>Characted class module - Used as interface for Enemy class & Hero</h2>
<pre><code>Option Explicit
''POSITIONS''
Public Property Get MyPosX() As Integer
End Property
Public Property Let MyPosX(v As Integer)
End Property
Public Property Get MyPosY() As Integer
End Property
Public Property Let MyPosY(v As Integer)
End Property
''MODEL''
Public Property Get TheModel() As String
End Property
Public Property Let TheModel(v As String)
End Property
''STATS''
Public Property Get MyAttack() As Integer
End Property
Public Property Get Myhp() As Integer
End Property
Public Property Let Myhp(v As Integer)
End Property
''MISC''
Public Sub Display()
End Sub
Public Sub DisplayOff()
End Sub
Public Function IsInside(TheRoom As Room) As Boolean
End Function
</code></pre>
<h2>Door class module - For doors (Not finished at all)</h2>
<pre><code>Option Explicit
Private cell1X As Integer, cell1Y As Integer, cell2X As Integer, cell2Y As Integer ''POSITIONS''
Private IsOpen As Boolean ''OPEN OR CLOSED''
''POSITIONS''
Public Property Get x1() As Integer
x1 = cell1X
End Property
Public Property Get y1() As Integer
y1 = cell1Y
End Property
Public Property Get x2() As Integer
x2 = cell2X
End Property
Public Property Get y2() As Integer
y2 = cell2Y
End Property
Public Property Let x1(newx1 As Integer)
cell1X = newx1
End Property
Public Property Let y1(newy1 As Integer)
cell1Y = newy1
End Property
Public Property Let x2(newx2 As Integer)
cell2X = newx2
End Property
Public Property Let y2(newy2 As Integer)
cell2Y = newy2
End Property
Sub DisplayOpen()
Cells(cell1X, cell1Y).Value = ""
Cells(cell2X, cell2Y).Value = ""
End Sub
Sub DisplayClosed()
Cells(cell1X, cell1Y).Value = "D"
Cells(cell2X, cell2Y).Value = "D"
End Sub
</code></pre>
<h2>Enemy class (not finished) - for enemies</h2>
<pre><code>Implements Character
Option Explicit
Private MyCellX As Integer, MyCellY As Integer 'POSTION
Private hatk As Integer, hdef As Integer, Hhp As Integer 'STATS
Private MyModel As String
''''' CHARACTER INTERFACE ''''
''POSITIONS''
Public Property Get Character_MyPosX() As Integer
Character_MyPosX = MyCellX
End Property
Public Property Let Character_MyPosX(v As Integer)
MyCellX = v
End Property
Public Property Get Character_MyPosY() As Integer
Character_MyPosY = MyCellY
End Property
Public Property Let Character_MyPosY(v As Integer)
MyCellY = v
End Property
''MODEL''
Public Property Get Character_TheModel() As String
Character_TheModel = MyModel
End Property
Public Property Let Character_TheModel(v As String)
MyModel = v
End Property
''STATS''
Public Property Get Character_MyAttack() As Integer
Character_MyAttack = hatk
End Property
Public Property Get Character_Myhp() As Integer
Character_Myhp = Hhp
End Property
Public Property Let Character_Myhp(v As Integer) 'For dmg
Hhp = v
End Property
Sub Character_Display()
Cells(MyCellX, MyCellY).Value = Me.Character_TheModel
End Sub
Sub Character_DisplayOff()
Cells(MyCellX, MyCellY).Value = ""
End Sub
Function Character_IsInside(TheRoom As Room) As Boolean
If Me.Character_MyPosY > TheRoom.y1 And Me.Character_MyPosY < TheRoom.y2 And Me.Character_MyPosX > TheRoom.x1 And Me.Character_MyPosX < TheRoom.x3 Then
Character_IsInside = True
Else
Character_IsInside = False
End If
End Function
</code></pre>
<h2>Hero class - For you, Predeclared ID</h2>
<pre><code>Implements Character
Option Explicit
Private hItems(0 To 9) As Items ''
Private MyCellX As Integer, MyCellY As Integer 'POSTION
Private hatk As Integer, hdef As Integer, Hhp As Integer 'STATS
Private MyModel As String ' you, :)
''POSITIONS''
Public Property Get Character_MyPosX() As Integer
Character_MyPosX = MyCellX
End Property
Public Property Let Character_MyPosX(v As Integer)
MyCellX = v
End Property
Public Property Get Character_MyPosY() As Integer
Character_MyPosY = MyCellY
End Property
Public Property Let Character_MyPosY(v As Integer)
MyCellY = v
End Property
''MODEL''
Public Property Get Character_TheModel() As String
Character_TheModel = MyModel
End Property
Public Property Let Character_TheModel(v As String)
MyModel = v
End Property
''STATS''
Public Property Get Character_MyAttack() As Integer
Character_MyAttack = hatk + GetModifier()(0)
End Property
Public Property Get Character_Myhp() As Integer
Character_Myhp = Hhp + GetModifier()(1)
End Property
Public Property Get MyBaseHp() As Integer
MyBaseHp = Hhp
End Property
Public Property Let Character_Myhp(v As Integer) 'For dmg
Hhp = v
End Property
Public Sub Character_Display()
Cells(MyCellX, MyCellY).Value = Me.Character_TheModel
End Sub
Public Sub Character_DisplayOff()
Cells(MyCellX, MyCellY).Value = ""
End Sub
Public Function Character_IsInside(TheRoom As Room) As Boolean
If Me.Character_MyPosY > TheRoom.y1 And Me.Character_MyPosY < TheRoom.y2 And Me.Character_MyPosX > TheRoom.x1 And Me.Character_MyPosX < TheRoom.x3 Then
Character_IsInside = True
Else
Character_IsInside = False
End If
End Function
Public Sub AddItemToInventory(item As Items)
Static ItemCount As Integer
Set hItems(ItemCount) = item
ItemCount = ItemCount + 1
End Sub
Private Function GetModifier() As Integer()
Dim i As Integer: i = 0
Dim tmparr(0 To 1) As Integer
On Error GoTo err
For i = 0 To UBound(hItems)
On Error Resume Next
tmparr(0) = tmparr(0) + hItems(i).Iatk
tmparr(1) = tmparr(1) + hItems(i).Ihp
Next i
GetModifier = tmparr
Exit Function
err:
GetModifier = Split("0|0", "|")
End Function
</code></pre>
<p>Items class - For items (barely started)</p>
<pre><code>Option Explicit
Dim atk As Integer, HP As Integer
Dim ID As Integer
Dim Name As String
Public Property Get Iatk()
Iatk = atk
End Property
Public Property Get Ihp()
Ihp = HP
End Property
Public Property Get Iname()
Iname = Name
End Property
Public Property Get Iid()
Iid = ID
End Property
Public Sub rnd()
atk = 5
HP = 5
Name = Stuff.RandomNameGenerator
End Sub
</code></pre>
<h2>Rooms class - For maze (X and Y axis are inverted)</h2>
<pre><code>Option Explicit
''store door positions in order to open / close them
Private TLr As Integer, TLc As Integer, TRr As Integer, TRc As Integer, BLr As Integer, BLc As Integer, BRr As Integer, BRc As Integer 'position
Private IsValid As Integer
Private direction As Integer
Private HasBeenRevisited As Boolean
''VALIDITY''
Public Property Get Visited() As Boolean
Visited = HasBeenRevisited
End Property
Public Property Let Visited(Visited2 As Boolean)
HasBeenRevisited = Visited2
End Property
''DIRECTION''
Public Property Get MyDirection() As Integer
MyDirection = direction
End Property
Public Property Let MyDirection(MyDirection2 As Integer)
direction = MyDirection2
End Property
''VALIDITY''
Public Property Get ValidOrNot() As Integer
ValidOrNot = IsValid
End Property
''POSITIONS''
Public Property Get x1() As Integer
x1 = TLr
End Property
Public Property Get y1() As Integer
y1 = TLc
End Property
Public Property Get x2() As Integer
x2 = TRr
End Property
Public Property Get y2() As Integer
y2 = TRc
End Property
Public Property Get x3() As Integer
x3 = BLr
End Property
Public Property Get y3() As Integer
y3 = BLc
End Property
Public Property Get x4() As Integer
x4 = BRr
End Property
Public Property Get y4() As Integer
y4 = BRc
End Property
Public Property Let x1(newx1 As Integer)
TLr = newx1
End Property
Public Property Let y1(newy1 As Integer)
TLc = newy1
End Property
Public Property Let x2(newx2 As Integer)
TRr = newx2
End Property
Public Property Let y2(newy2 As Integer)
TRc = newy2
End Property
Public Property Let x3(newx3 As Integer)
BLr = newx3
End Property
Public Property Let y3(newy3 As Integer)
BLc = newy3
End Property
Public Property Let x4(newx4 As Integer)
BRr = newx4
End Property
Public Property Let y4(newy4 As Integer)
BRc = newy4
End Property
Sub Draw()
Dim i As Integer, j As Integer, longeur As Integer, largeur As Integer 'longeur = x largeur = y
i = 0: j = 0
longeur = TRc - TLc: largeur = BLr - TLr
For i = 0 To longeur
Cells(TLr, TLc + i).Value = "W"
Cells(BLr, BLc + i).Value = "W"
Next i
For j = 1 To largeur - 1
Cells(TLr + j, TLc).Value = "W"
Cells(TRr + j, TRc).Value = "W"
Next j
'call me.flavor
End Sub
Sub Flavor()
End Sub
Sub colored(color As Integer)
Dim longeur As Integer, largeur As Integer, i As Byte, j As Byte
longeur = TRc - TLc: largeur = BLr - TLr
i = 0: j = 0
For i = 1 To longeur - 1
For j = 1 To largeur - 1
Cells(TLr + j, TLc + i).Interior.ColorIndex = color
Next j
Next i
End Sub
Function AmIValid() As Integer 'need add size parameters
Dim i As Integer, j As Integer, longeur As Integer, largeur As Integer 'longeur = x largeur = y
i = 0: j = 0
IsValid = 1
longeur = TRc - TLc: largeur = BLr - TLr
If longeur < 3 Or largeur < 3 Then
IsValid = 2
Else
For i = 0 To longeur
If Cells(TLr, TLc + i).Value = "W" Or Cells(BLr, BLc + i).Value = "W" Or TLr < 100 Or TLc < 100 Or BRr > 150 Or BRc > 150 Then IsValid = 2 'SIZE OF MAZE needs to be passed to inputbox
Next i
For j = 1 To largeur - 1
If Cells(TLr + j, TLc).Value = "W" Or Cells(TRr + j, TRc).Value = "W" Then IsValid = 2
Next j
End If
AmIValid = IsValid
End Function
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T18:49:01.753",
"Id": "412820",
"Score": "7",
"body": "I don't mind spending a lot of time reviewing code - but I'm not going to try to infer the purpose of that code by reading it. Please [edit] 1) your title, so that it summarizes the purpose of the code, and 2) the question body, so that it describes what's what and why it's there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T19:23:47.127",
"Id": "412825",
"Score": "8",
"body": "\"Never had any programming course. Am not programmer. Does not plan to be.\". And yet, you are now writing a program - and a game at that! So, despite your plans, you are now a programmer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T03:23:31.843",
"Id": "412855",
"Score": "2",
"body": "You know, for a non-programmer, I'm thoroughly impressed with the use of classes/objects, the PredeclaredID and `static` locals - these are things many, *many* VBA programmers that have been coding for *years* often don't even bother *trying* to understand or experiment with... thumbs up! I'd recommend further editing this post ([edit]) to add more information/context about what the purpose of everything is - picture yourself presenting your project to someone that's never seen it (which, it kinda is ;-). Side note, I've flagged your post so a moderator can help you get your logins sorted out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T17:08:51.547",
"Id": "413158",
"Score": "1",
"body": "Can you add a description of what your game is supposed to do? It's hard to see where you went wrong if we have no clue what it's supposed to do."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T10:54:46.167",
"Id": "413351",
"Score": "0",
"body": "specific question time (I know you devs like that) : How could I improve my Room.AmIValid Method. \nI found this : https://stackoverflow.com/questions/306316/determine-if-two-rectangles-overlap-each-other\nI'm too retarded to manage a sucessfull implementation and i'm stuck with the two loops that check cells value. HELP !"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T12:55:32.210",
"Id": "413368",
"Score": "0",
"body": "Another question comes to my mind but you are not going to like it. It's not specific.\nHow would I do to add save system ? There must be a smarter way than saving every varaible of the game."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T18:36:55.410",
"Id": "213399",
"Score": "2",
"Tags": [
"object-oriented",
"game",
"vba"
],
"Title": "Feels like I have no clue what I'm doing in my \"project\" - \"GAME\""
} | 213399 |
<p>The task:</p>
<blockquote>
<p>A number is considered perfect if its digits sum up to exactly 10.</p>
<p>Given a positive integer n, return the n-th perfect number.</p>
<p>For example, given 1, you should return 19. Given 2, you should return
28.</p>
</blockquote>
<p>My solution:</p>
<pre><code>const sum = (acc, m) => acc + Number(m);
const getNthPerfectNumber = n => {
let i = 0, x = 0;
while (i !== n) {
x++;
if (x
.toString()
.split('')
.reduce(sum, 0) === 10) { i++; }
}
return x;
};
console.log(getNthPerfectNumber(2));
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T21:32:21.367",
"Id": "412841",
"Score": "1",
"body": "I rolled back your last edit. After getting an answer you are [not allowed to change your code anymore](https://codereview.stackexchange.com/help/someone-answers). This is to ensure that answers do not get invalidated and have to hit a moving target. If you have changed your code you can either post it as an answer (if it would constitute a code review) or ask a new question with your changed code (linking back to this one as reference). Refer to [this post](https://codereview.meta.stackexchange.com/a/1765/120114) for more information"
}
] | [
{
"body": "<p>There's not a lot of code to review here, but what I would say is that the sum function is probably the wrong function to extract. It would make the entire thing more readable if you instead extracted a digitSum function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T20:28:04.843",
"Id": "213405",
"ParentId": "213403",
"Score": "3"
}
},
{
"body": "<p>I'd say one small optimization you could do is start <code>x</code> at 18, since none of the numbers below 19 would have digits that add up to 10. That way there would be quite a few less operations/function calls - this is important to be aware of with functional programming.</p>\n\n<p>Also, if the function gets run multiple times, then it would be beneficial to memorize it- specifically, store results of calls to compute the digit sums for various values (of <code>x</code>) so they can be looked up quicker than re-computing them. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T21:37:18.527",
"Id": "213409",
"ParentId": "213403",
"Score": "3"
}
},
{
"body": "<p>After suggestion by @Magnus Jeffs Tovslid and @Sᴀᴍ Onᴇᴌᴀ:</p>\n\n<pre><code>const memoizedPerfectNumbers = [];\nconst sum = (acc, m) => acc + Number(m);\nconst digitSum = x => x\n .toString()\n .split('')\n .reduce(sum, 0);\nconst getNthPerfectNumber = n => {\n if (memoizedPerfectNumbers[n - 1]) { return memoizedPerfectNumbers[n - 1]; }\n let i = 0, x = 18;\n while (i !== n) {\n x++;\n if (digitSum(x) === 10) { i++; }\n }\n memoizedPerfectNumbers[n - 1] = x;\n return x;\n};\nconsole.log(getNthPerfectNumber(2));\nconsole.log(memoizedPerfectNumbers);\nconsole.log(getNthPerfectNumber(2));\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T17:49:31.417",
"Id": "412947",
"Score": "0",
"body": "I should have worded [my answer](https://codereview.stackexchange.com/a/213409/120114). I was trying to point out that calls to compute the digit sums of values (like `x` in your original code) should be cached"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T07:57:50.510",
"Id": "213437",
"ParentId": "213403",
"Score": "1"
}
},
{
"body": "<blockquote>\n<pre><code> x++;\n</code></pre>\n</blockquote>\n\n<p>This is very inefficient.</p>\n\n<p>The intended approach is probably to write a successor function which takes a \"perfect\"<sup>1</sup> number and gives the next one by manipulating its digits. The optimal approach probably starts by getting a fast calculation for the number of \"perfect\" numbers with <span class=\"math-container\">\\$d\\$</span> digits.</p>\n\n<p>But even if you want to use brute force, there's an easy speed-up by a factor of 10:</p>\n\n<pre><code>let i = 0, prefix = 0;\nwhile (i < n) {\n prefix++;\n lastDigit = 10 - digitSum(prefix);\n if (lastDigit >= 0 && lastDigit <= 9) i++;\n}\n</code></pre>\n\n<hr>\n\n<p><sup>1</sup> The term \"perfect number\" already means something else, and they should have chosen a different name.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T08:32:55.317",
"Id": "213440",
"ParentId": "213403",
"Score": "2"
}
},
{
"body": "<h1>Computers do numbers!</h1>\n\n<p>Compared to manipulating numbers, strings are very slow and use a lot of memory relative to what is being done.</p>\n\n<p>To test if it is a perfect integer</p>\n\n<pre><code>const isPerfectInt = num => {\n var sum = (num | 0) % 10;\n while (num > 0) { sum += (num = num / 10 | 0) % 10 }\n return sum === 10;\n}\n</code></pre>\n\n<h2>Improved cache</h2>\n\n<p>You are caching results in your answer and you only cache what you are looking for. However while you are searching you find all the perfect values below the one you are looking for. This negates most the advantage you get from caching calculations.</p>\n\n<p>If you keep all calculated perfect numbers you can then use that last calculated value as a starting point. That way you will never test the same value twice.</p>\n\n<pre><code>const cache = [0,19]; // set up first value. Saves some messing about\nconst getNthPerfectNumber = n => {\n if (cache[n]) { return cache[n] }\n\n // Start from the last number tested plus one.\n var idx = cache.length - 1, num = cache[idx] + 1;\n while (idx < n) {\n if (isPerfectInt(num)) { cache[++idx] = num }\n num++;\n }\n return num - 1;\n};\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T16:42:36.467",
"Id": "213462",
"ParentId": "213403",
"Score": "7"
}
}
] | {
"AcceptedAnswerId": "213462",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T19:42:54.550",
"Id": "213403",
"Score": "6",
"Tags": [
"javascript",
"algorithm",
"mathematics",
"ecmascript-6"
],
"Title": "Get n-th perfect number"
} | 213403 |
<p>I have started practicing problems in leetcode and I solved the following problem on <a href="https://leetcode.com/problems/plus-one/" rel="nofollow noreferrer">LeetCode</a>.</p>
<p>The challenge is :</p>
<blockquote>
<p>Given a <strong>non-empty</strong> array of digits representing a non-negative integer, plus one to the integer.</p>
<p>The digits are stored such that the most significant digit is at the head of the list, and each element in the array contain a single digit.</p>
<p>You may assume the integer does not contain any leading zero, except the number 0 itself.</p>
</blockquote>
<pre><code> Example 1:
Input: [1,2,3]
Output: [1,2,4]
Explanation: The array represents the integer 123.
Example 2:
Input: [4,3,2,1]
Output: [4,3,2,2]
Explanation: The array represents the integer 4321.
</code></pre>
<p>I am trying to get better at writing good code for my solutions. Please give me your suggestions</p>
<pre><code>class Solution {
public int[] plusOne(int[] a) {
int length = a.length-1;
while(length>=0)
{
a[length]=a[length]+1;
int carry = a[length]/10;
if(carry==1)
{
a[length]=0;
length=length-1;
}
else
break;
}
if(a[0]==0)
{
int [] array = new int[a.length+1];
array[0]=1;
for(int i=1;i<array.length-1;i++)
{
array[i]=0;
}
return array;
}
return a;
}
}
</code></pre>
| [] | [
{
"body": "<p>The way you handle the extra digit for the last carry seems clumsy to me. To my mind, it would be much better to include the extra digit, by creating a new array at the start, then discard the extra digit if it's not needed.</p>\n\n<p>Having that array for the answer, allows you to use it to hold the carry if needed.</p>\n\n<p>When you know the numeric limits to your loop, it is much better to use a <code>for</code> loop rather than a <code>while</code> loop. This keeps the relative information for the loop in one place.</p>\n\n<p>Putting this together it could look like this:</p>\n\n<pre><code>public int[] plusOne(int[] digits) {\n int newLength = digits[0] == 9 ? digits.length + 1 : digits.length;\n int[] answer = new int[newLength];\n int a = newLength - 1;\n answer[a] = 1;\n for (int d = digits.length - 1; d >= 0; --d, --a) {\n answer[a] += digits[d];\n if (answer[a] == 10) {\n answer[a] = 0;\n answer[a-1] = 1;\n }\n }\n return answer[0] > 0 ? answer : Arrays.copyOfRange(answer, 1, newLength); \n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T23:01:20.510",
"Id": "213413",
"ParentId": "213407",
"Score": "1"
}
},
{
"body": "<p>I can't agree with tinstaafl's idea of creating a new array for every input number that starts with a 9. It's not needed in roughly 10% of the possible inputs.</p>\n\n<p>I do however agree that using a for loop is better in this case. Anyone even mildly familiar with for loops can instantly recognise you're looping over each of the digits from right to left which isn't as clear in your while loop.</p>\n\n<p>Instead of breaking the for loop and doing the special case testing afterwards you could also return early instead. With a little bit of rearanging this also simplifies the loop itself slightly.</p>\n\n<p>The final for loop to set the result to all 0's is not needed. Creating a new <code>int[]</code> array will already set them all to 0 for you.</p>\n\n<p>Putting this all together gives us the following implementation:</p>\n\n<pre><code>static int[] plusOne(int[] digits){\n for(int i = digits.length-1; i>=0; i--){\n if(digits[i]<9){\n digits[i]++;\n return digits;\n }\n digits[i]=0; //carry handled by next iteration in for loop\n }\n //didn't return yet so digits were all 9's\n int[] result = new int[digits.length+1];\n result[0] = 1;\n return result;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T08:54:47.963",
"Id": "213503",
"ParentId": "213407",
"Score": "2"
}
},
{
"body": "<h3>Keep it simple</h3>\n\n<p>This condition is used to decide whether an extra digit is needed:</p>\n\n<blockquote>\n<pre><code>if(a[0]==0)\n</code></pre>\n</blockquote>\n\n<p>Why does this work? This works because the only way the first digit is 0,\nif the digit before that was 9 and there was a carry,\nwhich is only possible if the digit before that was 9 and there was a carry,\nand so on.</p>\n\n<p>This is a lot to keep in the head.\nThere is a much simpler way:\ndeclare <code>int carry</code> before the loop,\nand update it within the loop.\nThe code will look more like this:</p>\n\n<pre><code>int carry = 0;\n\nwhile (...) {\n // ...\n}\n\nif (carry == 1) {\n</code></pre>\n\n<p>Isn't that a lot simpler to understand and reason about?</p>\n\n<h3>Pay attention to style</h3>\n\n<p>The computer doesn't care about the writing style, but humans do.</p>\n\n<p>Instead of this:</p>\n\n<blockquote>\n<pre><code>while(length>=0)\n{\n a[length]=a[length]+1;\n int carry = a[length]/10;\n if(carry==1)\n {\n a[length]=0;\n length=length-1;\n }\n else\n break;\n}\n\nif(a[0]==0)\n{\n int [] array = new int[a.length+1];\n array[0]=1;\n for(int i=1;i<array.length-1;i++)\n</code></pre>\n</blockquote>\n\n<p>The preferred writing style in Java is like this:</p>\n\n<pre><code>while (length >= 0) {\n a[length]++;\n int carry = a[length] / 10;\n if (carry == 1) {\n a[length] = 0;\n length--;\n } else {\n break;\n }\n}\n\nif (a[0] == 0) {\n int[] array = new int[a.length + 1];\n array[0] = 1;\n for (int i = 1; i < array.length - 1; i++) {\n</code></pre>\n\n<p>I suggest to follow the above pattern.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T17:00:50.550",
"Id": "213605",
"ParentId": "213407",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "213413",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T20:53:31.253",
"Id": "213407",
"Score": "3",
"Tags": [
"java",
"programming-challenge"
],
"Title": "LeetCode Problem 66 : Plus One"
} | 213407 |
<p>In a recent project my backend architecture consists of</p>
<ul>
<li><code>Repositories</code> (talking to database)</li>
<li><code>Services</code> (handling business logic)</li>
<li><code>Controllers</code> (handling incoming REST calls and providing according responses to the client)</li>
</ul>
<p>I introduced <code>DTO</code> classes for representing the data that is returned by the controllers when a client calls a REST route. Because the services work with <code>Entities</code>, I need to somehow map those to my <code>DTO</code>s. The <code>DTO</code>s contain most of the properties of the according <code>Entity</code>, but can define additional properties as well.</p>
<p>First of all, I have the following <code>Entities</code>:</p>
<p><strong>Image Entity</strong></p>
<pre class="lang-js prettyprint-override"><code>@Entity()
export class Image {
id: number;
name: string;
@ManyToOne(...)
parentFolder: Folder;
@ManyToMany(...)
tags: Tag[];
}
</code></pre>
<p><strong>Tag Entity</strong></p>
<pre class="lang-js prettyprint-override"><code>@Entity()
export class Tag {
id: number;
label: string;
@ManyToMany(...)
images: Image[];
}
</code></pre>
<p>As you can see, there are also some relations (ManyToOne, ManyToMany), so my <code>Entities</code> contain references to other <code>Entities</code>. Same for according <code>DTO</code>s.</p>
<p>Next, you can see my shortened <code>ImageController</code>. In the method <code>findOne</code>, a service is asked to look for an <code>Entity</code> with given id in the database.</p>
<p><strong>Image Controller</strong></p>
<pre class="lang-js prettyprint-override"><code>@Controller('image')
export class ImageController {
constructor(
private readonly imageService: ImageService,
private readonly imageEntityToDtoMapper: ImageEntityToDtoMapper
) { }
@Get(':id')
async findOne(@Param('id') id): Promise<ImageDto> {
const image: Image = await this.imageService.findOne(id);
return this.imageEntityToDtoMapper.map(image);
}
}
</code></pre>
<p>In order to let the controller return a <code>DTO</code>, the result is mapped by an <code>ImageEntityToDtoMapper</code>.</p>
<p><strong>ImageEntityToDtoMapper</strong></p>
<pre class="lang-js prettyprint-override"><code>@Injectable()
export class ImageEntityToDtoMapper {
constructor(
private readonly folderService: FolderService,
private readonly folderEntityToDtoMapper: FolderEntityToDtoMapper,
@Inject(forwardRef(() => TagEntityToDtoMapper))
private readonly tagEntityToDtoMapper: TagEntityToDtoMapper
) { }
async map(entity: Image): Promise<ImageDto> {
if (entity) {
const parentFolderPath = await this.folderService.buildPathByFolderId(entity.parentFolder.id);
const absolutePath = `${parentFolderPath}${path.sep}${entity.name}`;
const dto = new ImageDto();
dto.id = entity.id;
dto.name = entity.name;
dto.absolutePath = absolutePath;
dto.parentFolder = await this.folderEntityToDtoMapper.map(entity.parentFolder);
dto.tags = await this.tagEntityToDtoMapper.mapAll(entity.tags);
return dto;
}
}
}
</code></pre>
<p>And here are my questions, all regarding <code>ImageEntityToDtoMapper</code>:</p>
<ol>
<li><p>Beside simply mapping properties <code>id</code> and <code>name</code> from one class to the other, I'm also "calculating" <code>absolutePath</code>, which is not contained in the original <code>Entity</code>, but only in <code>DTO</code>. Is this mapper class the correct place for that?</p>
<p>Furthermore, for that reason I need to inject the <code>FolderService</code> to the mapper, which seems not quite correct to me...</p>
</li>
<li><p>Because of the Image<code>Entities</code>' relations to <code>Folder</code> and <code>Tag</code>, I need to call their mapper classes from the <code>ImageEntityToDtoMapper</code>. Is this the correct way to do it?</p>
</li>
<li><p>Because I need to inject other <code>Entities</code>' mappers, I have a circular dependency between <code>ImageEntityToDtoMapper</code> and <code>TagEntityToDtoMapper</code>. And in my whole project, I have more cases where multiple mappers depend on each other.</p>
<p>Although the library (<a href="https://docs.nestjs.com/" rel="nofollow noreferrer">NestJS</a>) I'm using offers a way to handle this by using <code>forwardRef</code>, I would like to avoid those circular dependencies. Could you think of any possibility?</p>
</li>
</ol>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-04-06T18:11:34.120",
"Id": "511071",
"Score": "1",
"body": "Did you ever find a solution?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2021-07-21T17:10:47.120",
"Id": "521866",
"Score": "0",
"body": "There is one article which explains these issues much better: \nhttps://nartc.netlify.app/blogs/introduction-to-automapper-typescript/\nCheck if this works for you."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T21:57:55.393",
"Id": "213410",
"Score": "3",
"Tags": [
"typescript",
"dto",
"orm"
],
"Title": "Mapping Entities to DTOs in TypeScript"
} | 213410 |
<p>I'm looking for feedback on some code I've written to work as a transparent proxy. I'm developing a web app that needs information from another web site's API, but that web site has disabled CORS and I cannot get it directly. This was an intentional decision by the web site to encourage development of services that will benefit their larger community.</p>
<p>I've recently seen a lot of articles and posts about how to correctly use <code>HttpClient</code> to avoid a huge number of open sockets and potential performance concerns. After reading those, I've updated my code to look like the following.</p>
<p>Startup.cs</p>
<pre><code> public void ConfigureServices(IServiceCollection services)
{
...
services.AddSingleton<IHttpClientService, HttpClientService>();
services.AddScoped<IProxyService, ProxyService>();
services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
}
</code></pre>
<p><code>HttpClientService</code>'s only purpose is to provide an instance of <code>HttpClient</code> to <code>ProxyService</code>:</p>
<pre><code>public class HttpClientService : IHttpClientService
{
private HttpClient _client;
public HttpClientService()
{
_client = new HttpClient();
}
public HttpClient Client()
{
return _client;
}
}
</code></pre>
<p>I inject <code>HttpClientService</code> into <code>ProxyService</code>:</p>
<pre><code>public class ProxyService : IProxyService
{
private readonly Uri _websiteUri;
private readonly IHttpClientService _http;
public ProxyService(IHttpClientService httpClient)
{
_websiteUri = new Uri("https://www.website.com/api/get-information");
_http = httpClient;
}
public async Task<HttpResponseMessage> GetInformationAsync(string name, string sessionId)
{
var builder = new UriBuilder(_websiteUri);
builder.Port = -1;
var query = HttpUtility.ParseQueryString(builder.Query);
query["name"] = name;
builder.Query = query.ToString();
string url = builder.ToString();
var httpRequestMessage = new HttpRequestMessage
{
Method = HttpMethod.Get,
RequestUri = new Uri(url),
Headers =
{
{ HttpRequestHeader.Cookie.ToString(), "SESSIONID=" + sessionId }
}
};
var response = await _http.Client().SendAsync(httpRequestMessage);
return response;
}
...
}
</code></pre>
<p>My main API calls <code>ProxyService</code> like this:</p>
<pre><code>public class APIController : ControllerBase
{
private readonly IProxyService _proxy;
public APIController(IProxyService proxy)
{
_proxy = proxy;
}
[HttpGet]
public async Task<IActionResult> GetInformation(string name, string sessionId)
{
using (var response = await _proxy.GetInformationAsync(name, sessionId))
{
if (response.IsSuccessStatusCode)
{
var contents = await response.Content.ReadAsStringAsync();
return Ok(contents);
}
else
{
return NotFound();
}
}
}
...
}
</code></pre>
<p>Is this an okay approach? Do I even need to wrap the await <code>_proxy.GetInformationAsync()</code> call in a using block?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-13T22:47:27.960",
"Id": "213412",
"Score": "1",
"Tags": [
"c#",
"asp.net-web-api",
"asp.net-core"
],
"Title": "Transparent proxy using HttpClient"
} | 213412 |
<p>I have a Jupyter notebook that allows a user to type in a phrase and the program will 'guess' which Office character it resembles.</p>
<p>Here is a link to the github <a href="https://github.com/jpf5046/text-analyzer/blob/master/The%20Office%20-%20Text%20Analyzer.ipynb" rel="nofollow noreferrer">repo</a></p>
<p>I have the following littered throughout my code:</p>
<pre><code>the_office_raw_script['polarity'] = the_office_raw_script['line_text'].apply(lambda x: TextBlob(x).sentiment.polarity)
the_office_raw_script['scores'] = the_office_raw_script['line_text'].apply(lambda x: analyser.polarity_scores(x))
</code></pre>
<p>and the following, which is the prediction part:</p>
<pre><code>from sklearn.model_selection import train_test_split
from sklearn.feature_extraction.text import CountVectorizer
from sklearn.feature_extraction.text import TfidfTransformer
from sklearn.naive_bayes import MultinomialNB
X_train, X_test, y_train, y_test = train_test_split(df_upsampled['line_text'], df_upsampled['speaker'], random_state = 0)
count_vect = CountVectorizer()
X_train_counts = count_vect.fit_transform(X_train)
tfidf_transformer = TfidfTransformer()
X_train_tfidf = tfidf_transformer.fit_transform(X_train_counts)
clf = MultinomialNB().fit(X_train_tfidf, y_train)
</code></pre>
<p>I have some examples of output, which is AWESOME! (so happy i got this far)</p>
<pre><code>print(clf.predict(count_vect.transform(["hard working beet farmer"])))
</code></pre>
<p>the above prints <code>dwight</code></p>
<pre><code>print(clf.predict(count_vect.transform(["that's what she said"])))
</code></pre>
<p>the above prints <code>pam</code> which is totally wrong because michael says 'that's what she said' over 15 times throughout the series.</p>
<p><strong>Two Questions</strong></p>
<p>How would I go above making my script into a function, would that be worth it?</p>
<p>How do I somewhat ~hardcode~ some inputs? If someone types in 'that's what she said' or a variation thereof I want it to always print <code>michael</code>?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T00:48:52.003",
"Id": "213416",
"Score": "1",
"Tags": [
"python"
],
"Title": "Python Text Analysis with TextBlob -- Reading lines from The Office TV Show"
} | 213416 |
<p>A modified version of the prime sieve. I actually doubt it could be implemented any faster, but I might be wrong:</p>
<pre class="lang-py prettyprint-override"><code>from math import sqrt
def sieve(n):
"""
* A fast implementation of the prime sieve algorithm. Finds all prime numbers up to a given upper bound.
* Params:
* n: The upper bound.
* Return:
* A list of all prime numbers in [0, n].
* Implementation:
* Implements the sieve of Erasthotenes with a few optimisations for speed.
* We only delete multiples of numbers up to `int(sqrt(n))`. This suffices to find all prime numbers.
* We manipulate a list of boolean values, indexed by the number itself with the values denoting its primality. This is much faster than deleting elements in the list.
"""
if n < 2: return []
prime = [True]*(n + 1) #Initialise the list.
rt = int(sqrt(n))+1
for x in range(2, rt): #We only need to seive multiples of numbers <= to `n`.
if prime[x]:
for c in range(x*x, n + 1, x): prime[c] = False
return [idx for idx, p in enumerate(prime) if p][2:]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T01:37:04.227",
"Id": "412852",
"Score": "0",
"body": "Please always include a language tag with your question. With Python it's also best to include one of [tag:python-3.x] or [tag:python-2.x] if your question is targeting that environment."
}
] | [
{
"body": "<p>Since this is tagged <a href=\"/questions/tagged/beginner\" class=\"post-tag\" title=\"show questions tagged 'beginner'\" rel=\"tag\">beginner</a>, you should know that speed isn't everything. First of all you should care about making your code readable as ultimately that is more important.</p>\n\n<ul>\n<li><p>You should always put new statements on new lines. At first I ignored your first guard statement, due to this. I only caught on that you'd done this when I saw the second from last line was huge.</p></li>\n<li><p>Your comments aren't great. Yes <code>[True]*(n + 1)</code> initializes a list, we can read the code to understand that.</p></li>\n<li><p>Your variable names don't really help reading the code.</p></li>\n</ul>\n\n\n\n<pre><code>def sieve(limit):\n if limit < 2:\n return []\n\n limit += 1 # Preincrement `limit` so `sieve` is inclusive, unlike `range`.\n primes = [True]*limit\n for base in range(2, int(limit**0.5 + 1)):\n if primes[base]:\n for composite in range(base*2, limit, base):\n primes[composite] = False\n return [num for num, is_prime in enumerate(primes) if is_prime][2:]\n</code></pre>\n\n<p>I'd like to point out that your memory usage can be improved. How many <span class=\"math-container\">\\$O(n)\\$</span> lists do you have?</p>\n\n<ol>\n<li><code>primes</code> to perform the sieve.</li>\n<li>Your list comprehension, that gets all the indexes.</li>\n<li>Your duplication of the list comprehension to remove <em>two</em> values.</li>\n</ol>\n\n<p>You can remove the second by returning an iterator. As for the third, you can instead perform an <a href=\"https://docs.python.org/3/library/itertools.html#itertools.islice\" rel=\"nofollow noreferrer\"><code>islice</code></a>, or setting 0 and 1 to false. Yes this is now 10% slower.</p>\n\n<p>However if you change the second for loop to run in C land rather than Python land you net a 40% speed-up from the original.</p>\n\n<pre><code>from math import ceil\n\n\ndef sieve(limit):\n if limit < 2:\n return []\n\n limit += 1 # Preincrement `limit` so sieve is inclusive, unlike `range`.\n primes = [True]*limit\n for base in range(2, int(limit**0.5 + 1)):\n if primes[base]:\n primes[base*2:limit:base] = [False]*(ceil(limit / base) - 2)\n\n primes[0] = primes[1] = False\n return (num for num, is_prime in enumerate(primes) if is_prime)\n</code></pre>\n\n<p>From this changing the last line to use <code>itertools.compress</code> rather than an iterator comprehension reduces time an additional 40% (nearly 70% from the original).</p>\n\n<pre><code>from math import ceil\nfrom itertools import compress\n\n\ndef sieve(limit):\n if limit < 2:\n return []\n\n limit += 1 # Preincrement `limit` so sieve is inclusive, unlike `range`.\n primes = [True]*limit\n for base in range(2, int(limit**0.5 + 1)):\n if primes[base]:\n primes[base*2:limit:base] = [False]*(ceil(limit / base) - 2)\n\n primes[0] = primes[1] = False\n return compress(range(limit), primes)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T07:53:35.130",
"Id": "412868",
"Score": "0",
"body": "Thanks for the suggestions, I am not so sure why you removed `sqrt()` though? Wouldn't it be faster than `n**0.5`? Also, I don't understand what this line of code does: `primes[base*2:limit:base] = [False]*(ceil(limit / base) - 2)`. Could you please explain?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T09:00:00.540",
"Id": "412877",
"Score": "0",
"body": "@TobiAlafin Preference and speed. `timeit(\"sqrt(10000)\", \"from math import sqrt\", number=100000000)` -> 9.42233170700274, `timeit(\"10000 ** 0.5\", number=100000000)` -> 0.8613513769996644. It's called [vectorization](https://stackoverflow.com/q/47755442), in short Python slow, C fast, do everything in C."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T09:43:07.837",
"Id": "412884",
"Score": "0",
"body": "Nice idea with the slice assignment. I thought doing `primes[base*base:limit:base] = [False]*((((limit - base*base) - 1) // base) + 1)` would be even faster, since the slice is a bit smaller, but it seems to be exactly the same speed..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T09:54:31.300",
"Id": "412886",
"Score": "0",
"body": "@Graipher Oh, I guess late last night I didn't notice the difference between `n*n` and `n*2`, oops. That's interesting, wouldn't have thought changing a couple hundred/thousand values at a time would run that quickly. Did you test with larger limits? Mine are at 10000."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T10:48:15.450",
"Id": "412892",
"Score": "0",
"body": "@Peilonrayz: Yes, I tested up to 1E7..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T10:52:26.600",
"Id": "412894",
"Score": "0",
"body": "@Graipher Oh wow :O"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T10:57:51.403",
"Id": "412895",
"Score": "1",
"body": "@Peilonrayz: Here's the plot: https://i.stack.imgur.com/tb2Pe.png"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T11:01:54.200",
"Id": "412897",
"Score": "0",
"body": "@Graipher Wow, that really is negligible. Do you have a GitHub repro for that [timing graph stuff](https://codereview.stackexchange.com/q/165245)?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T11:04:08.873",
"Id": "412898",
"Score": "0",
"body": "@Peilonrayz: No I don't, but that sounds like a good idea. I'll ping you when I have it set up, might take a bit, still gotta work in between SE..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T11:05:24.740",
"Id": "412899",
"Score": "0",
"body": "@Graipher No rush :) Look forward to it"
}
],
"meta_data": {
"CommentCount": "10",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T02:22:51.997",
"Id": "213422",
"ParentId": "213418",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "213422",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T01:28:41.643",
"Id": "213418",
"Score": "2",
"Tags": [
"python",
"performance",
"beginner",
"algorithm",
"sieve-of-eratosthenes"
],
"Title": "Fast Prime Sieve (Python Implementation)"
} | 213418 |
<p>An algorithm for finding prime factors of a number given a list of all primes up to the square root of the number. It's worst case time complexity is <span class="math-container">\$O(n^{1/2})\$</span>, the best case would be <span class="math-container">\$O(\log(n))\$</span>, and I don't know how to calculate average case or amortised worst case. I am aware that this is not strictly optimal, but I think it is easier to understand and implement, than say Pollard's rho algorithm for prime factorisation (I suspect it works better if the number is composite with many prime factors as well). Suggestions for improvements are welcome. </p>
<h2>FastFactorise.py</h2>
<pre><code>def fact(n):
"""
* Function to factorise a given number given a list of prime numbers up to the square root of the number.
* Parameters:
* `n`: The number to be factorised.
* Return:
* `res`: A dict mapping each factor to its power in the prime factorisation of the number.
* Algorithm:
* Step 1: Initialise `res` to an empty dictionary.
* Step 2: If `n` > 1.
* Step 3: Iterate through the prime number list.
* Step 4: If ever the current prime number is > the floor of the square root of `n` + 1 exit the loop.
* Step 5: If the current prime number is a factor of `n`.
* Step 6: Assign 0 to `e`.
* Step 7: While the current prime number is a factor of `n`.
* Step 8: Increment `e`.
* Step 9: Divide `n` by the current prime number.
* [End of Step 7 while loop.]
* Step 10: Map the current prime number to `e` in the result dictionary.
* [End of step 5 if block.]
* Step 11: If `n` is not 1 (after the repeated dividings) map `n` to 1 in the result dictionary.
* Step 12: Return the result dictionary.
* [Exit the function.]
"""
res = {}
if n > 1:
for p in primes:
if p > int(sqrt(n)) + 1: break
if n%p == 0:
e = 0
while n%p == 0:
e += 1
n //= p
res[p] = e
if n != 1: res[n] = 1
return res
</code></pre>
| [] | [
{
"body": "<p><code>sqrt</code> is expensive. You can avoid it by reworking your test condition from:</p>\n\n<pre><code>p > int(sqrt(n)) + 1\n</code></pre>\n\n<p>to:</p>\n\n<pre><code>p*p > n\n</code></pre>\n\n<hr>\n\n<p>You can skip one <code>while n%p == 0</code> iteration by initializing <code>e = 1</code> and unconditionally dividing by <code>p</code> once you’ve found a prime factor:</p>\n\n<pre><code>if n%p == 0:\n e = 1\n n //= p\n while n%p == 0:\n # ...etc...\n</code></pre>\n\n<hr>\n\n<p>Avoid putting “then” statements on the same line as the <code>if</code> statement: place the “then” statement indented on the next line.</p>\n\n<hr>\n\n<p>The algorithm should be a comment, not part of the <code>\"\"\"docstring\"\"\"</code>; callers generally only care about how to use the function, not the implementation details. </p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T07:41:46.553",
"Id": "412866",
"Score": "0",
"body": "I am not to clear on proper docstring documentation. I was under the impression that it was for multiline comments? Your suggestion on phasing out `sqrt()` is apt, thanks (I applied the other fixes as well (I placed the algorithm above the function)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T18:40:43.473",
"Id": "412951",
"Score": "0",
"body": "A triple-quoted string is string that can contain newlines & quotes without needing escapes. If the first statement in a function (or module/class) is a string (including a triple quoted one), it becomes the docstring for that entity. Eg) you can access your `fact()`’s docstring as `fact.__docstring__` and it will return your text, verbatim. More importantly, a user could type `help(fact)` and retrieve the docstring formatted as a help string (some indentation is removed, extra info added). If you packaged the function in a module, `help(mod_name)` gives help for all functions in that module."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T16:51:14.890",
"Id": "413064",
"Score": "0",
"body": "The other way of getting rid of `sqrt` as accuracy is not needed is to do `**0.5`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T18:34:53.377",
"Id": "413076",
"Score": "0",
"body": "@13ros27 `**0.5` is still doing slower, transcendental math, instead of simple multiplication which is not only exact, but is also much faster. (Also, `**0.5` appears to be 8.8% slower than `sqrt` ... on my iPhone)"
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T05:55:36.800",
"Id": "213430",
"ParentId": "213420",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "213430",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T01:53:57.800",
"Id": "213420",
"Score": "3",
"Tags": [
"python",
"performance",
"beginner",
"algorithm",
"primes"
],
"Title": "Fast Factorisation (Python Implementation)"
} | 213420 |
<blockquote>
<h2><a href="https://leetcode.com/problems/binary-tree-level-order-traversal/" rel="nofollow noreferrer">102. Binary Tree Level Order Traversal</a></h2>
<p>Given a binary tree, return the level order traversal of its nodes' values. (ie, from left to right, level by level).</p>
<p><strong>For example:</strong></p>
<p>Given binary tree [3,9,20,null,null,15,7],</p>
<pre><code> 3
/ \
9 20
/ \
15 7
</code></pre>
<p>return its level order traversal as:</p>
<pre><code>[
[3],
[9,20],
[15,7]
]
</code></pre>
</blockquote>
<p>This is my solution in Swift:</p>
<pre><code>func levelOrder(_ root: TreeNode?) -> [[Int]] {
guard let root = root else{
return []
}
let nodes = recursiveVisit(root)
let capacity = nodes.reduce([Int]()) {
if $0.contains($1.0) == false {
return $0 + [$1.0]
}
return $0
}.count
return nodes.reduce([[Int]](repeating: [], count: capacity), {
var tmp = $0
tmp[$1.0].append($1.1)
return tmp
})
}
func recursiveVisit(_ node: TreeNode?) -> [(Int, Int)]{
// [(Int, Int)]
// depth, node.val
guard let node = node else{
return []
}
var nodes = [(Int, Int)]()
nodes.append((0, node.val))
let lhs = recursiveVisit(node.left).map {
return ($0.0 + 1, $0.1)
}
let rhs = recursiveVisit(node.right).map {
return ($0.0 + 1, $0.1)
}
nodes.append(contentsOf: lhs)
nodes.append(contentsOf: rhs)
return nodes
}
</code></pre>
<p>The solution is very intuitive: collect the nodes' value and depth, then reduce to the answer.</p>
<p>It is not as well designed as <a href="https://leetcode.com/problems/binary-tree-level-order-traversal/discuss/33450/Java-solution-with-a-queue-used" rel="nofollow noreferrer">the Java Solution</a>, though.</p>
<p>My question is mainly on the Swift syntax. Is there any other way to do it more lean? Combine the two <code>reduce()</code> calls to one, for example?</p>
| [] | [
{
"body": "<h3>Simplifying your code</h3>\n\n<p>Let's start here:</p>\n\n<blockquote>\n<pre><code>let capacity = nodes.reduce([Int]()) {\n if $0.contains($1.0) == false {\n return $0 + [$1.0]\n }\n return $0\n}.count \n</code></pre>\n</blockquote>\n\n<p>The test </p>\n\n<pre><code>if $0.contains($1.0) == false\n</code></pre>\n\n<p>is shorter (and – in my opinion – better) written as</p>\n\n<pre><code>if !$0.contains($1.0)\n</code></pre>\n\n<p>Each invocation of the closure creates a new array. In such cases it is more efficient to use <code>reduce(into:)</code> with a closure that <em>updates</em> the array:</p>\n\n<pre><code>let capacity = nodes.reduce(into: [Int]()) {\n if !$0.contains($1.0) {\n $0.append($1.0)\n }\n}.count\n</code></pre>\n\n<p>But what this code actually does is to determine the number of distinct levels in the <code>nodes</code> array. That is simpler and more efficiently done with a <em>set:</em></p>\n\n<pre><code>let capacity = Set(nodes.map { $0.0 }).count\n</code></pre>\n\n<p>Here</p>\n\n<blockquote>\n<pre><code>return nodes.reduce([[Int]](repeating: [], count: capacity), {\n var tmp = $0\n tmp[$1.0].append($1.1)\n return tmp\n})\n</code></pre>\n</blockquote>\n\n<p>a new nested array is created with each invocation of the closure. Again, this can be improved with <code>reduce(into:)</code>, so that the first function becomes</p>\n\n<pre><code>func levelOrder(_ root: TreeNode?) -> [[Int]] {\n guard let root = root else {\n return []\n }\n let nodes = recursiveVisit(root)\n let capacity = Set(nodes.map { $0.0 }).count\n return nodes.reduce(into: [[Int]](repeating: [], count: capacity), {\n $0[$1.0].append($1.1)\n })\n}\n</code></pre>\n\n<p>I have only minor suggestions for the second function:</p>\n\n<blockquote>\n<pre><code>var nodes = [(Int, Int)]()\nnodes.append((0, node.val))\n</code></pre>\n</blockquote>\n\n<p>can be combined to </p>\n\n<pre><code>var nodes = [(0, node.val)]\n</code></pre>\n\n<p>The results of the recursive calls can be appended to the <code>nodes</code> array directly:</p>\n\n<pre><code>nodes += recursiveVisit(node.left).map {\n return ($0.0 + 1, $0.1)\n}\nnodes += recursiveVisit(node.right).map {\n return ($0.0 + 1, $0.1)\n}\n</code></pre>\n\n<p>And if you use tuple <em>labels</em> then the code becomes better readable (and almost self-documenting):</p>\n\n<pre><code>func recursiveVisit(_ node: TreeNode?) -> [(level: Int, value: Int)] {\n\n guard let node = node else {\n return []\n }\n var nodes = [(level: 0, value: node.val)]\n nodes += recursiveVisit(node.left).map {\n return (level: $0.level + 1, value: $0.value)\n }\n nodes += recursiveVisit(node.right).map {\n return (level: $0.level + 1, value: $0.value)\n }\n return nodes\n}\n</code></pre>\n\n<p>This can be used in the first function as well. As an alternative, define a custom <code>struct</code> with “level” and “label” members.</p>\n\n<h3>Alternative #1 – A nested function</h3>\n\n<p>It is not necessary to create an array of <code>(level, value)</code> tuples first. You can add a value to the sublist on the current level, or append a new level while traversing the tree recursively. With a <em>nested function</em> you don't even have to pass the array around:</p>\n\n<pre><code>func levelOrder(_ root: TreeNode?) -> [[Int]] {\n var levels: [[Int]] = []\n\n func recursiveVisit(_ node: TreeNode?, level: Int) {\n guard let node = node else {\n return\n }\n if level < levels.count {\n levels[level].append(node.val)\n } else {\n levels.append([node.val])\n }\n recursiveVisit(node.left, level: level + 1)\n recursiveVisit(node.right, level: level + 1)\n }\n\n recursiveVisit(root, level: 0)\n return levels\n}\n</code></pre>\n\n<h3>Alternative #2 – Iteration instead of recursion</h3>\n\n<p>The referenced Java solution solves the task with iteration, and a list containing all nodes on the current level. Of course that can be done in Swift as well. Here is an example of a quite compact implementation:</p>\n\n<pre><code>func levelOrder(_ root: TreeNode?) -> [[Int]] {\n guard let root = root else {\n return []\n }\n\n var wrapList: [[Int]] = []\n var queue = [root] // First level\n\n while !queue.isEmpty {\n // All values of nodes on the current level:\n wrapList.append(queue.map { $0.val })\n // Replace queue by list of all nodes on the next level:\n queue = queue.flatMap { [$0.left, $0.right ] }.compactMap { $0 }\n }\n\n return wrapList\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-20T19:05:46.603",
"Id": "413749",
"Score": "0",
"body": "\"And if you use tuple labels then the code becomes better readable (and almost self-documenting)\" great plus to this - before it was just unreadable for me, with very labels very clear to understand. also the map should not use the short hand parameters to understand it better as a reader"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T13:36:26.963",
"Id": "213453",
"ParentId": "213423",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "213453",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T03:07:05.297",
"Id": "213423",
"Score": "4",
"Tags": [
"programming-challenge",
"tree",
"swift"
],
"Title": "Leetcode 102: Binary tree level-order traversal in Swift"
} | 213423 |
<p>I'm relatively new to .Net/UWP networking and have been trying to make sense of the APIs. I'd like to implement a TCP client that is capable of reading and sending messages independently (there is no protocol and all messages are independent).</p>
<p>Typically (e.g. in a POSIX C++ server), this would be done by spinning up a thread and reading continuously (sleeping periodically if no data) or using asynchronous I/O (epoll, select-poll, etc.)</p>
<p>I've implemented a UWP-compatible client that attempts to use ReadAsync as well as cancellation tokens to shut the client down.</p>
<p>This is a pretty rough cut and I'd like to flesh it out more, especially wrt error handling. Some questions:</p>
<ol>
<li><p>Is looping continuously as I've done in ReadMessages() the recommended/idiomatic way of using these functions?</p></li>
<li><p>Am I using the cancellation tokens appropriately? My intent is to be able to kill a ReadAsync() request when the client object is destructed (or, eventually, when a Disconnect() method is added).</p></li>
<li><p>Where should I be detecting disconnects? try-catch blocks around the ReadAsync methods?</p></li>
</ol>
<p>Lastly, messages (their <code>byte[]</code> buffers, rather), would be output using a fast queue. I've commented that portion out. The intent is to use this as a component in a larger application (e.g., Unity).</p>
<pre><code>namespace Messages
{
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct Header
{
public UInt32 size;
public UInt32 id;
public UInt64 received_timestamp;
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct PingMessage
{
public Header header;
public UInt64 timestamp;
public void Init()
{
header.size = (UInt32)Marshal.SizeOf(typeof(PingMessage));
header.id = 0xdeaddead;
timestamp = (UInt64)System.Diagnostics.Stopwatch.GetTimestamp();
}
}
[StructLayout(LayoutKind.Sequential, Pack = 1)]
public struct PongMessage
{
public Header header;
public UInt64 ping_timestamp;
public void Init()
{
header.size = (UInt32)Marshal.SizeOf(typeof(PongMessage));
header.id = 0xdeadbeef;
}
}
}
public class Client
{
private Windows.Networking.Sockets.StreamSocket m_socket;
private System.Threading.Tasks.Task m_connectionTask;
private Windows.Storage.Streams.DataWriter m_writer;
private System.IO.Stream m_inputStream;
private Windows.Networking.HostName m_hostname;
private string m_port;
private bool m_connected = false;
private System.Threading.CancellationTokenSource m_cancellationSource = new System.Threading.CancellationTokenSource();
private byte[] m_header = new byte[Marshal.SizeOf(typeof(Messages.Header))];
private byte[] m_messageBuffer = null;
//private BlockingRingBuffer<byte[]> m_receiveQueue = new BlockingRingBuffer<byte[]>(1024 * 1024, true);
public static byte[] Serialize<T>(ref T str)
{
int size = Marshal.SizeOf(str);
byte[] arr = new byte[size];
GCHandle h = default(GCHandle);
try
{
h = GCHandle.Alloc(arr, GCHandleType.Pinned);
Marshal.StructureToPtr<T>(str, h.AddrOfPinnedObject(), false);
}
finally
{
if (h.IsAllocated)
{
h.Free();
}
}
return arr;
}
public static T Deserialize<T>(byte[] arr) where T : struct
{
T str = default(T);
GCHandle h = default(GCHandle);
try
{
h = GCHandle.Alloc(arr, GCHandleType.Pinned);
str = (T)Marshal.PtrToStructure(h.AddrOfPinnedObject(), typeof(T));
}
finally
{
if (h.IsAllocated)
{
h.Free();
}
}
return str;
}
public async void Send(byte[] bytes)
{
await m_connectionTask;
if (!m_connected)
{
Console.WriteLine("NOT CONNECTED: dropping message");
return;
}
try
{
m_writer.WriteBytes(bytes);
await m_writer.StoreAsync();
Console.WriteLine("Sent " + bytes.Length + " bytes");
}
catch (Exception exception)
{
// If this is an unknown status it means that the error if fatal and retry will likely fail.
if (Windows.Networking.Sockets.SocketError.GetStatus(exception.HResult) == Windows.Networking.Sockets.SocketErrorStatus.Unknown)
{
throw;
}
Console.WriteLine("Error: Failed to send: " + exception.Message);
}
}
/*
public byte[] GetNextMessage()
{
byte[] buffer;
m_receiveQueue.TryDequeue(out buffer);
return buffer;
}
*/
private async void ReadMessages()
{
//TODO: handle disconnections and exceptions?
while (true)
{
// Read header
await m_inputStream.ReadAsync(m_header, 0, m_header.Length, m_cancellationSource.Token);
if (m_cancellationSource.IsCancellationRequested)
{
return;
}
// Read remainder of message
Messages.Header header = Deserialize<Messages.Header>(m_header);
m_messageBuffer = new byte[header.size];
Buffer.BlockCopy(m_header, 0, m_messageBuffer, 0, m_header.Length);
await m_inputStream.ReadAsync(m_messageBuffer, m_header.Length, (int)header.size - m_header.Length, m_cancellationSource.Token);
if (m_cancellationSource.IsCancellationRequested)
{
return;
}
// Enqueue
//TODO: put on ring buffer
Console.WriteLine("Read message: {0:x}, {1} bytes, thread={2}", header.id, header.size, System.Threading.Thread.CurrentThread.ManagedThreadId);
m_messageBuffer = null;
}
}
public async void Connect(bool blockUntilConnected, Action<bool, Exception> OnConnected = null)
{
m_connectionTask = System.Threading.Tasks.Task.Run(
async () =>
{
Exception e = null;
try
{
await m_socket.ConnectAsync(m_hostname, m_port);
m_writer = new Windows.Storage.Streams.DataWriter(m_socket.OutputStream);
m_inputStream = m_socket.InputStream.AsStreamForRead();
m_connected = true;
Console.WriteLine("Remote Address: " + m_socket.Information.RemoteAddress);
}
catch (Exception exception)
{
Console.WriteLine("Error: Failed to connect: " + exception.Message);
m_connected = false;
e = exception;
}
if (OnConnected != null)
{
OnConnected(m_connected, e);
}
}
);
if (blockUntilConnected)
{
m_connectionTask.Wait();
}
await m_connectionTask;
if (m_connected)
{
ReadMessages();
}
}
public Client(string hostname, int port)
{
m_socket = new Windows.Networking.Sockets.StreamSocket();
m_hostname = new Windows.Networking.HostName(hostname);
m_port = port.ToString();
}
~Client()
{
m_cancellationSource.Cancel();
//m_receiveQueue.StopWaiting(); // queue cannot be reused after this
m_writer.Dispose();
m_socket.Dispose();
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T04:37:20.477",
"Id": "412860",
"Score": "0",
"body": "This is too broad for stackoverflow. You might want to take this to Code Review instead"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T07:15:27.463",
"Id": "412865",
"Score": "0",
"body": "[`ReadAsync`](https://docs.microsoft.com/en-us/dotnet/api/system.io.stream.readasync?view=netframework-4.7.2): \"Returns\n`Task<Int32>`\nA task that represents the asynchronous read operation. The value of the `TResult` parameter contains the total number of bytes read into the buffer. *The result value can be less than the number of bytes requested*\""
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T08:00:32.127",
"Id": "412872",
"Score": "0",
"body": "Good catch, @Damien_The_Unbeliever! Seems I can't edit my post, though, but I've fixed that by checking the task result and repeatedly looping and awaiting."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T23:44:20.430",
"Id": "412964",
"Score": "0",
"body": "I had a quick look. To understand what you are doing there should be more comments. Some of the comments you have are just commented out code, which is usually consider poor form. The Connect method doesn't seem to be called anywhere, so I presume it's the main entry point. I think you need a comment stating what it is meant to do. Some explanation of what is going on in Serialize probably wouldn't go amiss either. I suggest thinking more about a reader who has little or no idea about what you are doing, in writing clear explanations you may help yourself understand the problem better. HTH."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T08:04:44.963",
"Id": "412987",
"Score": "0",
"body": "Thanks, George. This is just a client module. Connect() would be called by whoever is using the Client class. Serialization/Deserialization just converts message structures to byte[] arrays and back for sending and receiving. I've since removed these altogether (messages now serialize themselves). \n\nThe key thing I was hoping to get feedback on is whether the async ReadMessages() makes sense. Once connected, I spin this up and it continuously listens for messages (using background worker threads provided by the OS). The user of client can call GetNextMessage() or Send() independently."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T04:31:27.983",
"Id": "213427",
"Score": "3",
"Tags": [
"c#",
"socket",
"async-await",
"tcp",
"uwp"
],
"Title": "TCP client reading socket asynchronously"
} | 213427 |
<p>I am learning tree on Leetcode. Need to prepare the testing data.</p>
<p>It is easy to convert the array to an organized node, where its elements are integers.</p>
<p>such as <code>[3, 9, 20, 15, 7]</code></p>
<p>Here is my code:</p>
<pre><code>extension Array where Element == Int{
func arrayToTree() -> TreeNode{
var nodes = [TreeNode]()
for num in 0..<self.count{
nodes.append(TreeNode(self[num]))
}
var i = 0
repeat{
nodes[i].left = nodes[2 * i + 1]
if self.count > 2 * i + 2 {
nodes[i].right = nodes[2 * i + 2]
}
i+=1
}while i < (self.count)/2
return nodes.first!
}
}
</code></pre>
<p>When the last level contains some nils , such as <code>[3, 9, 20, nil, nil, 15, 7]</code></p>
<p>Here is the code:</p>
<pre><code>extension Array where Element == Int?{
func arrayToTree() -> TreeNode?{
guard self.count > 0 else{
return nil
}
var nodes = [TreeNode?]()
for num in 0..<self.count{
if let num = self[num]{
nodes.append(TreeNode(num))
}
else{
nodes.append(nil)
}
}
var i = 0
repeat {
nodes[i]?.left = nodes[2 * i + 1]
if self.count > 2 * i + 2 {
nodes[i]?.right = nodes[2 * i + 2]
}
i += 1
} while i < (self.count) / 2
return nodes.first!
}
}
</code></pre>
<p>How can I refactor this?</p>
<p>Such as combine them together using Swift Generic with some Protocol.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T15:32:24.550",
"Id": "413146",
"Score": "0",
"body": "Could you add a link to the leetcode question or the number?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T00:26:31.567",
"Id": "413309",
"Score": "0",
"body": "This is not a question. It's on improving auxiliary code."
}
] | [
{
"body": "<h3>Simplifying <code>func arrayToTree()</code></h3>\n\n<p>This</p>\n\n<blockquote>\n<pre><code> var nodes = [TreeNode?]()\n for num in 0..<self.count{\n if let num = self[num]{\n nodes.append(TreeNode(num))\n }\n else{\n nodes.append(nil)\n }\n }\n</code></pre>\n</blockquote>\n\n<p>creates a new array by <em>mapping</em> each element in <code>self</code> (an optional <code>Int</code>) to a new element (an optional <code>TreeNode</code>). That can be simplified to</p>\n\n<pre><code>let nodes = self.map { $0.map { TreeNode($0) } }\n</code></pre>\n\n<p>where the outer <code>Array.map</code> maps the given array to a new array, and the inner <code>Optional.map</code> maps an optional <code>Int</code> to an optional <code>TreeNode</code>.</p>\n\n<p>The</p>\n\n<blockquote>\n<pre><code> var i = 0\n repeat {\n // ...\n i += 1\n } while i < (self.count) / 2\n</code></pre>\n</blockquote>\n\n<p>loop can be simplified to</p>\n\n<pre><code>for i in 0..<self.count/2 {\n // ...\n}\n</code></pre>\n\n<p>The forced unwrapping </p>\n\n<blockquote>\n<pre><code> return nodes.first!\n</code></pre>\n</blockquote>\n\n<p>cannot crash – the <code>nodes</code> array cannot be empty at this point. I would still suggest to avoid it since later code changes might break the logic. It also makes it easier for future maintainers of the code to verify its correctness. </p>\n\n<p>Actually the preceding code just results in an empty <code>nodes</code> array if the given list is empty. Therefore we can remove the initial <code>guard</code> and replace it by</p>\n\n<pre><code>guard let first = nodes.first else {\n return nil\n}\nreturn first\n</code></pre>\n\n<p>at the end of the method. This can be further shortened to</p>\n\n<pre><code>return nodes.first.flatMap { $0 }\n</code></pre>\n\n<p>Putting it together, the function would look like this:</p>\n\n<pre><code>func arrayToTree() -> TreeNode? {\n\n let nodes = self.map { $0.map { TreeNode($0) } }\n for i in 0..<self.count/2 {\n nodes[i]?.left = nodes[2 * i + 1]\n if self.count > 2 * i + 2 {\n nodes[i]?.right = nodes[2 * i + 2]\n }\n }\n\n return nodes.first.flatMap { $0 }\n}\n</code></pre>\n\n<h3>An alternative implementation</h3>\n\n<p>What you have is a way to create a <code>TreeNode</code>, and that is what <em>initializers</em> methods are for. Therefore I would put the code in a </p>\n\n<pre><code>public convenience init?(values: [Int?])\n</code></pre>\n\n<p>of the <code>TreeNode</code> class instead of an <code>Array</code> extension method. The usage would be</p>\n\n<pre><code>let list = [3, 9, 20, nil, nil, 15, 7]\nif let tree = TreeNode(values: list) {\n // ...\n}\n</code></pre>\n\n<p>And the task calls for a recursive implementation:</p>\n\n<pre><code>public convenience init?(values: [Int?], offset: Int = 0) {\n guard offset < values.count, let value = values[offset] else {\n return nil\n }\n self.init(value)\n self.left = TreeNode(values: values, offset: 2 * offset + 1)\n self.right = TreeNode(values: values, offset: 2 * offset + 2)\n}\n</code></pre>\n\n<h3>Making it generic</h3>\n\n<p>With the above changes it is now easy to replace <code>Int</code> by an arbitrary value type:</p>\n\n<pre><code>public class TreeNode<T> {\n public var val: T\n public var left: TreeNode?\n public var right: TreeNode?\n public init(_ val: T) {\n self.val = val\n self.left = nil\n self.right = nil\n }\n\n public convenience init?(values: [T?], offset: Int = 0) {\n guard offset < values.count, let value = values[offset] else {\n return nil\n }\n self.init(value)\n self.left = TreeNode(values: values, offset: 2 * offset + 1)\n self.right = TreeNode(values: values, offset: 2 * offset + 2)\n }\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T10:39:15.307",
"Id": "213450",
"ParentId": "213429",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "213450",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T05:38:15.847",
"Id": "213429",
"Score": "2",
"Tags": [
"swift",
"generics"
],
"Title": "Swift: arrayToTree() where array contains int and nil"
} | 213429 |
<p>For a homework assignment, I have to create a "TO-DO" list, which will add a list item to the unordered list dynamically using JavaScript. The input element is also added using JavaScript, having to generate a unique id that changes with each site visit. I'm looking for any suggestions that will improve the efficiency of the code.</p>
<p><div class="snippet" data-lang="js" data-hide="false" data-console="false" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>/*
- get user input
- create <li> element
- append that to <ul> list
*/
function Form_Processes() {
this.count = 0;
this.input_id = generate_id();
this.addToList = function() {
var itemToAdd = document.getElementById(this.input_id).value;
if(!(itemToAdd === "")) {
this.count += 1;
var list_tag = document.getElementById('list');
var li_tag = document.createElement('li');
li_tag.id = "li_" + this.count;
var li_text = document.createTextNode("- " + itemToAdd);
li_tag.appendChild(li_text);
list_tag.appendChild(li_tag);
//clear textbox for next input
document.getElementById(this.input_id).value = "";
}
}
this.removeFromList = function() {
var numsOfElements = document.getElementById('list').childElementCount;
if(numsOfElements > 0) {
var itemToRemove = document.getElementById('li_' + this.count);
itemToRemove.outerHTML = "";
this.count -= 1;
} else {
console.log('ERROR: Not Enough Child Elements to remove (script.js:25)');
}
}
function generate_id() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789_";
for (var i = 0; i < 8; i++){
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
}
var f = new Form_Processes();
function execute(x) {
if(x == 1) {
f.addToList()
} else if(x == 2) {
f.removeFromList();
}
}
function load_form() {
var x = document.getElementById('in');
//create input tag
var input_tag = document.createElement('input');
input_tag.type = "text";
input_tag.name = "user_input";
input_tag.id = f.input_id;
input_tag.placeholder = "Enter here...";
x.appendChild(input_tag);
//insert line break
var break_tag = document.createElement('br');
x.appendChild(break_tag);
var button1 = createButton("button", "add_list", 1, "Add To List");
var button2 = createButton("button", "remove_list", 2, "Remove From List");
x.appendChild(button1);
x.appendChild(button2);
}
function createButton(type, name, e, text) {
//create buttons
var button_tag = document.createElement('button');
button_tag.type = type;
button_tag.name = name;
button_tag.onclick = function() { execute(e); }
var button_text = document.createTextNode(text);
button_tag.appendChild(button_text);
return button_tag;
}</code></pre>
<pre class="snippet-code-css lang-css prettyprint-override"><code>* {
font-family: "Times New Roman", Times, serif;
}
body {
background-color: pink;
}
fieldset {
border: none;
}
input[type=text] {
padding: 12px 20px;
border-radius: 5px;
border: 1px solid grey;
font-size: 25px;
margin: 2px;
}
button {
background-color: green;
border: none;
border-radius: 6px; /* rounded corner look */
color: white; /* button text color */
text-align: center;
font-size: 16px;
margin: 1px;
}
ul {
list-style-type: none;
margin: 0;
padding: 0;
}
li {
background-color: grey;
margin: 3px;
font-size: 50px;
border-radius: 5px;
color: white;
padding-left: 15px;
}</code></pre>
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>TO-DO</title>
<script src="script.js"></script>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body onload="load_form()">
<center>
<form action="">
<fieldset id="in">
<!-- content goes below -->
</fieldset>
</form>
<h1>TO-DO</h1>
</center>
<ul id="list">
<!-- items will go below once added -->
</ul>
</body>
</html></code></pre>
</div>
</div>
</p>
| [] | [
{
"body": "<p>I recommend putting the script at the end of the page, just before <code></body></code> The reason is that you'll want to have scripts run when the DOM is ready (i.e. all the elements are present and ready for JS manipulation).</p>\n\n<p><code><center></code> is a deprecated stylistic element. To center an element, set left and right margins to <code>auto</code>. For text, use <code>text-align: center</code>:</p>\n\n<pre><code>.centered-element {\n display: block;\n width: 250px; /* Your desired width */\n margin-left: auto;\n margin-right: auto;\n}\n\n.element-with-centered-text {\n text-align: center;\n}\n</code></pre>\n\n<p>This way, you have separation of concerns. HTML deals with describing the structure, CSS deals with styling your HTML.</p>\n\n<pre><code>* {\n font-family: \"Times New Roman\", Times, serif;\n}\n</code></pre>\n\n<p>This is unnecessary. Applying <code>font-family</code> to <code>body</code> should be enough to apply it to all elements. Font style is inherited by all descendants until an element overrides it (and styles its own descendants).</p>\n\n<pre><code>fieldset {...}\n\ninput[type=text] {...}\n\nbutton {...}\n\nul {..}\n\nli {...}\n</code></pre>\n\n<p>I don't recommend styling elements directly because it breaks expectations. If I add a <code><ul></code> in your app for whatever purpose, I expect it to have bullets. But since your CSS removes them, my list won't have bullets. I'd have to add them back when, by default, they should have had bullets.</p>\n\n<p>Instead, use classes to target app-specific styling and leave element defaults alone. The only time I would style an element directly is if it's part of a globally-applied theme or a normalizer.</p>\n\n<p>As for your JavaScript, you could abstract away your element creation with a function like the following. This way, you don't have to repeat element creation scripts everywhere and you can easily describe dynamic HTML in a nested manner, like HTML.</p>\n\n<pre><code>const e = (name, properties = {}, children = []) => {\n // Create the element\n const element = document.createElement(name)\n\n // Apply properties\n Object.keys(properties).forEach(property => {\n element.setAttribute(property, propertyes[property])\n })\n\n // Append children\n children.forEach(c => {\n if(!c) return\n const node = (typeof c === 'string') ? document.createTextNode(c) : c\n element.appendChild(node)\n })\n\n return element\n}\n\n// Usage\nconst root = e('div', {}, [\n e('p', {}, [\n e('span', {}, [\n 'Hello, World!',\n 'Lorem Ipsum'\n ])\n ])\n])\n\nroot.appendChild(e('span', {}, ['another piece of text']))\n</code></pre>\n\n<p>If the syntax looks familiar, it's because this is the basic premise of how most VDOM libraries work under the hood. They're just nested calls of functions that either return an actual element, or objects that represent elements (which are turned to elements later).</p>\n\n<p>From there, you can describe and build your \"components\" like:</p>\n\n<pre><code>const LoadForm = () => {\n e('div', {}, [\n e('input', { type: 'text', name: 'user_input', placeholder: 'Enter here...' }),\n e('br'),\n e('button', { name: 'add_list' }, ['Add To List']),\n e('button', { name: 'remove_list' }, ['Remove From List']),\n ])\n\ndocument.getElementById('in').appendChild(LoadForm())\n</code></pre>\n\n<p>You can even encapsulate this in a class if you want so that you can also add some helper methods.</p>\n\n<pre><code>class LoadForm {\n onAdd () {\n // Do something on add\n }\n onRemove () {\n // Do something on remove\n }\n render() {\n return (\n e('div', {}, [\n e('input', { type: 'text', name: 'user_input', placeholder: 'Enter here...' }),\n e('br'),\n e('button', { name: 'add_list', onclick: this.onAdd }, [\n 'Add To List'\n ]),\n e('button', { name: 'remove_list', onclick: this.onRemove }, [\n 'Remove From List'\n ]),\n ])\n )\n }\n}\n\ndocument.getElementById('in').appendChild((new LoadForm()).render())\n</code></pre>\n\n<p>Lastly, JavaScript is written in <code>camelCase</code>, not <code>snake_case</code>.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T15:43:06.057",
"Id": "213523",
"ParentId": "213431",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213523",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T06:03:48.260",
"Id": "213431",
"Score": "1",
"Tags": [
"javascript",
"homework",
"dom",
"to-do-list"
],
"Title": "Adding <li> items dynamically to a to-do list"
} | 213431 |
<p>A recent post on StackOverflow about a recursive directory listing which produced an unsorted mixed file/directory list, sparked the stray thought of <em>"What would it take to write a wrapper for the recursive call to produce a sorted listing with directories sorted first?"</em> (this rabbit trail followed...)</p>
<p>In addition to the general code review for any glaring efficiency bottlenecks or obvious mistakes, a specific question would be does it need a check for the number of open file-descriptors, similar to the <code>ftw/nftw</code> parameter <code>nopenfd</code>.</p>
<p>The following example takes the directory path to list as the first argument (defaulting to <code>"."</code> if none given) to provide directory listing sorted ascending with the directories listed first, and optionally a second argument (it doesn't matter what it is) that triggers a descending sort with the directories listed first.</p>
<p>The wrapper function <code>listdir</code> takes the path as its first parameter and a function pointer to the <code>qsort</code> compare function to be used and returns an allocated array of pointers to char with a sentinel <code>NULL</code> marking the end of pointers pointing to an allocated and filled filename. Since the pointer to pointer was declared and initially allocated in the wrapper, calling the actual <code>listdir_read</code> function required just sucking it up and becoming a <em>3-star programmer</em> (if there is a better way to handle this, that would be another point, but it seemed justified here)</p>
<p>The rest is commented and fairly self-explanatory. The <code>qsort</code> compare functions, just iterate past any leading <code>"."</code> or <code>".."</code> and checks whether either of the paths being compared contains a second directory separator while the other does not and sorts the directory before the filename. Otherwise it is just a simple <code>strcmp</code> of the adjacent filenames.</p>
<p>The code:</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <errno.h>
#include <sys/types.h>
#include <unistd.h>
#define INITDSZ 64 /* initial number of pointers to allocate */
#ifndef PATH_MAX /* fallback definition for PATH_MAX */
#define PATH_MAX 4096
#endif
/* file/dir name comparison - ascending (sort dirs first) */
int sort_ascending (const void *a, const void *b) {
const char *pa = *(char * const *)a,
*pb = *(char * const *)b,
*hasdira = NULL,
*hasdirb = NULL;
while (*pa == '.') /* scan past "." and ".." */
pa++;
while (*pb == '.')
pb++;
hasdira = strchr (pa + 1, '/'); /* check for 2nd '/' */
hasdirb = strchr (pb + 1, '/');
if (hasdira && !hasdirb) /* sort dirs before files */
return -1;
else if (!hasdira && hasdirb)
return 1;
return strcmp (*(char * const *)a, *(char * const *)b);
}
/* file/dir name comparison - descending (sort dirs first) */
int sort_descending (const void *a, const void *b) {
const char *pa = *(char * const *)a,
*pb = *(char * const *)b,
*hasdira = NULL,
*hasdirb = NULL;
while (*pa == '.') /* scan past "." and ".." */
pa++;
while (*pb == '.')
pb++;
hasdira = strchr (pa + 1, '/'); /* check for 2nd '/' */
hasdirb = strchr (pb + 1, '/');
if (hasdira && !hasdirb) /* sort dirs before files */
return -1;
else if (!hasdira && hasdirb)
return 1;
return strcmp (*(char * const *)b, *(char * const *)a);
}
/* listdir_read - recursive read of directory storing entires in contents.
* listdir_read recursively loops over directory entries beginning with
* the last directory entry in contents. nptrs is a pointer to the currently
* allocated number of pointers in contents and n is the current used number
* of pointers. storage is allocated for each file/directory and each entry
* added to contents to preserve entries for sorting, and each diretory is
* recursed into to gather subdirectory entries. reallocation occurs as
* needed.
*/
void listdir_read (char ***contents, size_t *nptrs, size_t *n)
{
char *path = (*contents)[*n - 1]; /* pointer to current path */
DIR *dir;
struct dirent *entry;
if (!(dir = opendir(path))) { /* open/validate directory */
perror ("opendir-path not found");
return;
}
while ((entry = readdir(dir))) { /* loop over each entry */
char *name = entry->d_name;
size_t len = strlen (name),
pathlen = strlen (path),
entrylen = pathlen + len + 1; /* +1 for '/' */
if (*n + 1 == *nptrs) { /* realloc, preserving sentinel NULL */
void *tmp = realloc (*contents, 2 * *nptrs * sizeof **contents);
if (!tmp) { /* validate */
perror ("listdir_read() realloc-*contents");
return;
}
*contents = tmp; /* assign new block, zero pointers */
memset (*contents + *nptrs, 0, *nptrs * sizeof **contents);
*nptrs *= 2; /* update number of allocated pointers */
}
if (entry->d_type == DT_DIR) /* if "." or ".." skip */
if (!strcmp(name, ".") || !strcmp(name, ".."))
continue;
(*contents)[*n] = malloc (entrylen + 1); /* allocate storage */
if (!(*contents)[*n]) { /* validate */
perror ("listdir_read() malloc-(*contents)[*n]");
return;
}
sprintf ((*contents)[(*n)++], "%s/%s", path, name); /* fill entry */
if (entry->d_type == DT_DIR) /* if is directory, recurse */
listdir_read (contents, nptrs, n);
}
closedir (dir); /* close directory */
}
/* wrapper for listdir_read, takes path and qsort compare function.
* returns allocated/sorted pointers to entries on success, NULL otherwise.
*/
char **listdir (char *path, int (*cmp)(const void*, const void*))
{
size_t len, n = 0, nptrs = INITDSZ;
char **contents = calloc (nptrs, sizeof *contents); /* allocate nptrs */
if (!contents) { /* validate */
perror ("listdir() calloc-contents");
return NULL;
}
len = strlen (path);
contents[n] = malloc (len + 1); /* allocate storage for 1st entry */
if (!contents[n]) { /* validate */
perror ("listdir() malloc-contents[n]");
return NULL;
}
strcpy (contents[n++], path); /* copy path as first entry */
listdir_read (&contents, &nptrs, &n); /* call listdir_read */
qsort (contents, n, sizeof *contents, cmp); /* sort contents */
return contents;
}
/* read path provided as argv[1] or present working directory by default.
* sort ascending with directories sorted first by default, or descending
* if any agrv[2] provided.
*/
int main (int argc, char **argv) {
char path[PATH_MAX],
**contents = NULL;
if (argc > 1)
strcpy (path, argv[1]);
else
*path = '.', path[1] = 0;
if (argc > 2)
contents = listdir (path, sort_descending);
else
contents = listdir (path, sort_ascending);
if (contents) {
char **p = contents;
while (*p) {
puts (*p);
free (*p++); /* free entries */
}
free (contents); /* free pointers */
}
return 0;
}
</code></pre>
<p><code>valgrind</code> gives the code a clean bill of health on memory handling (though I've only run it against 15 or so subdirectories with ~5500 files). The memory required was approximately 1.8M for that number of files and directories. Execution time seems quite good.</p>
<p>Look things over and let me have the good, the bad and the ugly.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T09:32:07.897",
"Id": "412880",
"Score": "0",
"body": "I needed to define `_DEFAULT_SOURCE` when compiling, otherwise `DT_DIR` is undefined (on GNU/Linux)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T10:02:34.520",
"Id": "412889",
"Score": "0",
"body": "Wow, thanks. I compiled both on OpenSuSE w/gcc 4.8.5 and on Archlinux with gcc 8.2.1 and never got a peep out of the compiler. Ahah! I used `-std=gnu11`, but with `-std=c11` it behaves as you report."
}
] | [
{
"body": "<h1>Possible bug</h1>\n\n<blockquote>\n<pre><code>while (*pa == '.') /* scan past \".\" and \"..\" */\n pa++;\n</code></pre>\n</blockquote>\n\n<p>This also scans past <code>...</code> and <code>....</code>, which are perfectly valid filenames.</p>\n\n<h1>Locale</h1>\n\n<p>This program always sorts using the <code>C</code> locale. We should instead order as the user prefers, by setting locale from environment in <code>main()</code>:</p>\n\n<pre><code>setlocale(LC_ALL, \"\");\n</code></pre>\n\n<p>and then using <code>strcoll</code> rather than <code>strcmp</code> to order strings.</p>\n\n<h1>Directory-first isn't recursive</h1>\n\n<p>I was surprised to get this output:</p>\n\n<pre class=\"lang-none prettyprint-override\"><code>./a/A\n./b/B\n./b/x\n./b/x/X\n./b/y\n./b/y/Y\n./c/C\n.\n./a\n./b\n./c\n</code></pre>\n\n<p>Why is the file <code>b/B</code> shown before directory <code>b/x</code>? I'd expected the directory-first rule to be applied recursively, too.</p>\n\n<h1>Duplication</h1>\n\n<p>The <code>sort_ascending</code> and <code>sort_descending</code> functions are almost identical. I'd be inclined to refactor out the common part:</p>\n\n<pre><code>static int sort_bydir (const char *pa, const char *pb)\n{\n /* scan past \".\" and \"..\" */\n if (*pa == '.') ++pa;\n if (*pa == '.') ++pa;\n\n if (*pb == '.') ++pb;\n if (*pb == '.') ++pb;\n\n const char *hasdira = strchr (pa + 1, '/'); /* check for 2nd '/' */\n const char *hasdirb = strchr (pb + 1, '/');\n\n return (!hasdira && hasdirb) - (hasdira && !hasdirb);\n}\n</code></pre>\n\n<p>Then the two functions are greatly simplified:</p>\n\n<pre><code>/* file/dir name comparison - ascending (sort dirs first) */\nint sort_ascending (const void *a, const void *b) {\n const char *pa = *(char *const *)a;\n const char *pb = *(char *const *)b;\n\n int bydir = sort_bydir(pa, pb);\n return bydir ? bydir : strcoll(pa, pb);\n}\n\n/* file/dir name comparison - descending (sort dirs first) */\nint sort_descending (const void *a, const void *b) {\n const char *pa = *(char *const *)a;\n const char *pb = *(char *const *)b;\n\n int bydir = sort_bydir(pa, pb);\n return bydir ? bydir : strcoll(pb, pa);\n}\n</code></pre>\n\n<h1>Improve the error checking</h1>\n\n<p>If we fail, we <code>perror()</code> but still continue to write incomplete (misleading) results. I think it would be better to emit only the error message in these cases.</p>\n\n<p>Using <code>perror()</code> following memory allocation failure is misleading, as these functions don't set <code>errno</code>.</p>\n\n<p>We forgot to check <code>readdir()</code> for error:</p>\n\n<blockquote>\n <p>If an error occurs, <code>NULL</code> is returned and <code>errno</code> is set appropriately. \n To distinguish end of stream and from an error, set <code>errno</code> to zero\n before calling <code>readdir()</code> and then check the value of <code>errno</code> if <code>NULL</code> is\n returned.</p>\n</blockquote>\n\n<h1>Cope with absence of <code>d_type</code> field</h1>\n\n<p>Not all <code>readdir()</code> implementations provide file type information, and even on systems which do, you can't assume it's populated. The GNU man page says:</p>\n\n<blockquote>\n <p>Only the fields <code>d_name</code> and (as an XSI extension) <code>d_ino</code> are\n specified in POSIX.1. Other than Linux, the <code>d_type</code> field is\n available mainly only on BSD systems. The remaining fields are \n available on many, but not all systems. Under glibc, programs can\n check for the availability of the fields not defined in POSIX.1 by\n testing whether the macros <code>_DIRENT_HAVE_D_NAMLEN</code>,\n <code>_DIRENT_HAVE_D_RECLEN</code>, <code>_DIRENT_HAVE_D_OFF</code>, or\n <code>_DIRENT_HAVE_D_TYPE</code> are defined.</p>\n</blockquote>\n\n<p>It also says:</p>\n\n<blockquote>\n <p>Currently, only some filesystems (among them: Btrfs, ext2, ext3,\n and ext4) have full support for returning the file type in <code>d_type</code>. \n All applications must properly handle a return of <code>DT_UNKNOWN</code>.</p>\n</blockquote>\n\n<p>This means that we must be prepared to fall back to <code>lstat()</code> if <code>_DIRENT_HAVE_D_TYPE</code> is undefined or if <code>entry->d_type == DT_UNKNOWN</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T10:44:07.567",
"Id": "412891",
"Score": "0",
"body": "I think we can probably sort each subdir separately, rather than a single big `qsort()` at the end - I'll come back to this later if I can."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T14:17:13.113",
"Id": "412925",
"Score": "0",
"body": "Toby, great feedback. I like the sort refactor to simplify. The error checking can always be improved, what is there is what I put in it when I was toying with the idea before I even considered posting it here. The absence of the `d_type` field is something I considered, using an atomic call to `open` with `O_DIRECTORY | O_RDONLY` flags, but hadn't implemented it yet. The sort issues is a good point. Currently it sorts the total results at once, bu a sort on a per-directory basis would work for the subs, but presents a pickle when then sorting the parent (files before/after the sorted subs)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T14:24:50.763",
"Id": "412930",
"Score": "0",
"body": "Oh yes, no need to `lstat()`. Perhaps a simpler approach is to `opendir()` everything and handle \"not a directory\" to mean a leaf node? And then add back using `d_type` if available, as an optimisation."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T18:20:30.917",
"Id": "412950",
"Score": "0",
"body": "Yes, I've been playing with the sort and there isn't a clean way to do a sort at the end. So it looks like I'll need to append a `'/'` to the directory before recursing. That will fix the toplevel sort, but it looks like a btree variant will be needed to handle forcing a dirs first sort throughout. For error handling I just changed `listdir_read` from `void` to `int` returning `0` on failure wrapping the recursive call in `if (!listdir_read (contents, nptrs, n)) { closedir (dir); return 0; }` that allows the recursion to unwind after failure. Thanks for your help."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-19T14:54:36.573",
"Id": "413564",
"Score": "0",
"body": "A further point on error checking - we can't assume that directory entries won't change between us reading the entry and following the filename. Murphy's Law says that somebody will be renaming files as we're running!"
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T10:38:22.630",
"Id": "213449",
"ParentId": "213435",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "213449",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T07:08:30.703",
"Id": "213435",
"Score": "2",
"Tags": [
"performance",
"c",
"recursion",
"file-system",
"posix"
],
"Title": "C Recursive Opendir Wrapper to Sort Directories First (ascending/descending)"
} | 213435 |
<p>I am trying to optimize my navigation drawer code. I have tried and followed the BEM naming convention for my CSS although I would like it reviewed with respect to the best practices being followed.
Also, I have used javascript arrow functions for my list in order to avoid repetition of the list item which also needs to be reviewed since I have a nested list where I have used a workaround.</p>
<p>Please find below my code for the navigation drawer list:-</p>
<pre><code>import React from 'react';
import PropTypes from 'prop-types';
import { withStyles, Button } from '@material-ui/core';
import ListSubheader from '@material-ui/core/ListSubheader';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import Collapse from '@material-ui/core/Collapse';
import ExpandLess from '@material-ui/icons/ExpandLess';
import ExpandMore from '@material-ui/icons/ExpandMore';
import MenuIcon from '@material-ui/icons/ArrowForward';
import IconButton from '@material-ui/core/IconButton';
import Divider from '@material-ui/core/Divider';
import Typography from '@material-ui/core/Typography';
import Link from 'next/link';
const fbIcon = '../static/facebook-icon.png';
const twitterIcon = '../static/twitter-icon.png';
const linkedinIcon = '../static/linkedin-icon.png';
const androidIcon = '../static/androidIcon.png';
const iosIcon = '../static/iosIcon.png';
const styles = theme => ({
'list-container': {
width: '100%',
maxWidth: 360,
backgroundColor: '#2ec3d2',
[theme.breakpoints.down('sm')]: {
maxWidth: '15rem',
}
},
'list-container__subheader': {
display: 'flex',
flexDirection: 'column',
backgroundColor: '#2ec3d2'
},
'list-container__nested': {
paddingLeft: theme.spacing.unit * 4
},
'list-container__button': {
color: theme.palette.getContrastText('#fff'),
backgroundColor: '#fff',
marginBottom: 20,
},
'list-container__arrowicon': {
width: 50,
height: 50,
color: '#fff'
},
'list-container__arrow-container': {
display: 'flex',
justifyContent: 'flex-end',
marginTop: 31,
marginBottom: 22,
[theme.breakpoints.down('sm')]: {
marginTop: 11,
marginBottom: 11
}
},
'list-container__row': {
display: 'flex',
flexDirection: 'row',
alignItems: 'flex-end'
},
'list-container__expicon': {
marginLeft: 20,
color: '#fff'
},
'list-container__headertxt': {
fontSize: '14px',
fontFamily: 'Montserrat,sans-serif',
lineHeight: 1,
textAlign: 'left',
color: '#fff',
textTransform: 'uppercase'
},
'social-container': {
display: 'flex',
flexDirection: 'row',
justifyContent: 'space-around',
paddingLeft: 10,
marginTop: 10
},
'social-container__icon': {
width: 30,
height: 30
},
'social-container__psicon': {
width: '145px',
height: '45px',
display: 'flex',
alignItems: 'left',
marginBottom: '5%',
marginTop: '8%',
[theme.breakpoints.down('sm')]: {
marginTop: '10%',
width: '104px',
height: '32px'
},
[theme.breakpoints.down('xs')]: {
marginTop: '10%',
width: '94px',
height: '30px'
}
}
});
const getNavigationLinks = (navigationObj, classes) => Object.keys(navigationObj)
.map(linkName => (
<Link key={linkName} href={navigationObj[linkName]}>
{/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
<ListItem button>
<Typography className={classes['list-container__headertxt']} variant="subtitle2" gutterBottom>
{linkName}
</Typography>
</ListItem>
</Link>
));
const getNestedLinks = (navigationObj, classes) => Object.keys(navigationObj)
.map(linkName => (
<Link key={linkName} href={navigationObj[linkName]}>
{/* eslint-disable-next-line jsx-a11y/anchor-is-valid */}
<ListItem button className={classes['list-container__nested']}>
<Typography className={classes['list-container__headertxt']} variant="subtitle2" gutterBottom>
{linkName}
</Typography>
</ListItem>
</Link>
));
class NavigationList extends React.Component {
state = {
open: false
};
handleClick = () => {
this.setState(state => ({ open: !state.open }));
};
render() {
const { classes } = this.props;
const { open } = this.state;
return (
<div className={classes['list-container']}>
<List
component="nav"
subheader={(
<ListSubheader
className={classes['list-container__subheader']}
component="div"
>
<div className={classes['list-container__arrow-container']}>
<IconButton className={classes['list-container__arrowicon']} aria-label="arrow">
<MenuIcon />
</IconButton>
</div>
<Button
className={classes['list-container__button']}
variant="contained"
size="large"
style={{
color: '#2ec3d2'
}}
>
Download
</Button>
</ListSubheader>
)}
>
{getNavigationLinks(
{
HOME: '/',
'EXISTING CUSTOMER LOGIN': 'https://somelink/',
'ABOUT Us': '/aboutus',
CAREERS: '/careers',
},
classes
)}
<ListItem button onClick={this.handleClick}>
<div className={classes['list-container__row']}>
<Typography className={classes['list-container__headertxt']} variant="subtitle2" gutterBottom>
PRODUCTS
</Typography>
{open ? <ExpandLess className={classes['list-container__expicon']} />
: <ExpandMore className={classes['list-container__expicon']} />}
</div>
</ListItem>
<Collapse in={open} timeout="auto" unmountOnExit>
<List component="div" disablePadding>
{getNestedLinks(
{
'INSTANT CASH': '/',
'SHOP ON AMAZON': 'https://somelink/',
'SHOP AT BIG BAZAAR': '/bigbazaar',
'SCHOOL FEES ': 'https://somelink/'
},
classes
)}
</List>
</Collapse>
{getNavigationLinks(
{
BLOGS: 'https://somelink/',
NEWS: 'https://somelink',
FAQS: '/faqs',
'START YOUR APPLICATION': 'https://somelink/'
},
classes
)}
</List>
<Divider />
<div className={classes['social-container']}>
<img className={classes['social-container__icon']} src={fbIcon} alt="facebook" />
<img className={classes['social-container__icon']} src={twitterIcon} alt="twitter" />
<img className={classes['social-container__icon']} src={linkedinIcon} alt="linkedin" />
</div>
<div className={classes['social-container']}>
<img className={classes['social-container__psicon']} src={androidIcon} alt="android" />
<img className={classes['social-container__psicon']} src={iosIcon} alt="ios" />
</div>
</div>
);
}
}
NavigationList.propTypes = {
classes: PropTypes.object.isRequired
};
export default withStyles(styles)(NavigationList);
</code></pre>
| [] | [
{
"body": "<p>Congratulations on getting a react app to work. That is no small feat. Also nice use of static state and using a function to change state.</p>\n\n<p>I recommend you read \n<a href=\"https://reactjs.org/docs/thinking-in-react.html\" rel=\"nofollow noreferrer\">thinking in react</a>.</p>\n\n<p>Controls are the basic building blocks of a react application. I recommend creating many small controls and composing them into a larger control. You have one monolithic control that is difficult to change and reason about. </p>\n\n<p>Here is your code with some sub-components:</p>\n\n<p><div class=\"snippet\" data-lang=\"js\" data-hide=\"false\" data-console=\"true\" data-babel=\"false\">\r\n<div class=\"snippet-code\">\r\n<pre class=\"snippet-code-js lang-js prettyprint-override\"><code>const HeaderTypeographyRoot = ({ children, classes }) => (\n <Typography\n className={classes[\"list-container__headertxt\"]}\n variant=\"subtitle2\"\n gutterBottom\n >\n {children}\n </Typography>\n);\nconst HeaderTypeography = withStyles(styles)(HeaderTypeographyRoot);\n\nconst mapLinks = (navigationObj, className) => linkName => (\n <Link key={linkName} href={navigationObj[linkName]}>\n <ListItem button className={className}>\n <HeaderTypeography>{linkName}</HeaderTypeography>\n </ListItem>\n </Link>\n);\nconst Links = ({ navigationObj, className }) => {\n const links = Object.keys(navigationObj).map(\n mapLinks(navigationObj, className)\n );\n return <React.Fragment>{links}</React.Fragment>;\n};\n// put in seperate file\nconst SubheaderRoot = ({ classes }) => (\n <ListSubheader\n className={classes[\"list-container__subheader\"]}\n component=\"div\"\n >\n <div className={classes[\"list-container__arrow-container\"]}>\n <IconButton\n className={classes[\"list-container__arrowicon\"]}\n aria-label=\"arrow\"\n />\n </div>\n <Button\n className={classes[\"list-container__button\"]}\n variant=\"contained\"\n size=\"large\"\n style={{\n color: \"#2ec3d2\"\n }}\n >\n Download\n </Button>\n </ListSubheader>\n);\nconst Subheader = withStyles(styles)(SubheaderRoot);\n\nclass ToggleColapse extends React.Component {\n state = {\n open: false\n };\n\n handleClick = () => {\n this.setState(state => ({ open: !state.open }));\n };\n\n render() {\n const { open } = this.state;\n const { children, name } = this.props;\n const icon = open ? \"-\" : \"+\";\n return (\n <React.Fragment>\n <ListItem button onClick={this.handleClick}>\n <HeaderTypeography>{name}</HeaderTypeography>\n {icon}\n </ListItem>\n <Collapse in={open} timeout=\"auto\" unmountOnExit>\n <List component=\"div\" disablePadding>\n {children}\n </List>\n </Collapse>\n </React.Fragment>\n );\n }\n}\n\nclass NavigationList extends React.Component {\n render() {\n const { classes } = this.props;\n return (\n <div className={classes[\"list-container\"]}>\n <List component=\"nav\" subheader={<Subheader />}>\n <Links\n navigationObj={{\n HOME: \"/\",\n \"EXISTING CUSTOMER LOGIN\": \"https://somelink/\",\n \"ABOUT Us\": \"/aboutus\",\n CAREERS: \"/careers\"\n }}\n />\n <ToggleColapse name=\"Products\">\n <Links\n className={classes[\"list-container__nested\"]}\n navigationObj={{\n \"INSTANT CASH\": \"/\",\n \"SHOP ON AMAZON\": \"https://somelink/\",\n \"SHOP AT BIG BAZAAR\": \"/bigbazaar\",\n \"SCHOOL FEES \": \"https://somelink/\"\n }}\n />\n </ToggleColapse>\n <Links\n navigationObj={{\n BLOGS: \"https://somelink/\",\n NEWS: \"https://somelink\",\n FAQS: \"/faqs\",\n \"START YOUR APPLICATION\": \"https://somelink/\"\n }}\n />\n </List>\n </div>\n );\n }\n}\nNavigationList.propTypes = {\n classes: PropTypes.object.isRequired\n};\nexport default withStyles(styles)(NavigationList);</code></pre>\r\n</div>\r\n</div>\r\n</p>\n\n<p><a href=\"https://codesandbox.io/s/48pvr41l39\" rel=\"nofollow noreferrer\"><img src=\"https://codesandbox.io/static/img/play-codesandbox.svg\" alt=\"Edit navigation-drawer-code-review\"></a></p>\n\n<p>Notice a few things:</p>\n\n<p>I make use of the withStyles higher order function so you don't have to pass so many className parameters around.</p>\n\n<p>getNestedLinks and getNaviationLinks are almost the same thing \nI made them into one reusable control (Links). Nested links are the same but are indented. This is done by passing in a className property.</p>\n\n<p>Step 4 in thinking in react is: Identify Where Your State Should Live\nI think it would be better for the is open state to live in the new 'ToggleColapse' control. That way if you wanted a second collapse / nested menu item, you can simply reuse this control. </p>\n\n<p>Next you need to ask, how likely are the links to change, if they are static, favor using static content and don't loop over (getNavigationLinks).</p>\n\n<p>If they are likely to change, separate the values (navigationObj) out of your control. This will make your control easier to understand and if you need to change them, you won't have to hunt through your code.</p>\n\n<p>If you get stuck on this, please ask. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T23:14:28.567",
"Id": "213624",
"ParentId": "213436",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T07:12:21.220",
"Id": "213436",
"Score": "1",
"Tags": [
"beginner",
"css",
"react.js",
"jsx",
"bem"
],
"Title": "CSS and React.js for a basic navigation drawer"
} | 213436 |
<p>Here's my take on the Linear Regression exercise from <a href="https://www.goodreads.com/book/show/80440.Python_Programming" rel="nofollow noreferrer">John Zelle's Python book</a>.</p>
<blockquote>
<p>Open a window, let the user click on as many points as they want. Upon pressing the "Done" button the regression line of those points is drawn.</p>
</blockquote>
<pre><code>from graphics import *
def dots(win):
sumx = 0
sumy = 0
sumx2 = 0
sumxy = 0
count = 0
click = win.getMouse()
clickX = click.getX()
clickY = click.getY()
while (clickX < 31 or clickX > 39 or
clickY < 1 or clickY > 5):
sumx += clickX
sumy += clickY
sumx2 += clickX**2
sumxy += clickX*clickY
count += 1
Point(clickX, clickY).draw(win)
click = win.getMouse()
clickX = click.getX()
clickY = click.getY()
return sumx, sumy, sumx2, sumxy, count
def mean(sum, count):
mean = sum / count
return mean
def calcreg(sumx, sumy, sumx2, sumxy, count):
xleft = 0
xright = 40
m = (sumxy - count * mean(sumx, count) * mean(sumy, count)) / (sumx2 - count * mean(sumx, count)**2)
yleft = mean(sumy, count) + m * (xleft - mean(sumx, count))
yright = mean(sumy, count) + m * (xright - mean(sumx, count))
return Line(Point(xleft, yleft), Point(xright, yright))
def main():
win = GraphWin("Regression Line", 400, 400)
win.setCoords(0, 0, 40, 40)
Text(Point(35, 3), "DONE").draw(win)
Rectangle(Point(31, 1), Point(39 ,5)).draw(win)
sumx, sumy, sumx2, sumxy, count = dots(win)
try:
regline = calcreg(sumx, sumy, sumx2, sumxy, count)
regline.draw(win)
except ZeroDivisionError:
Text(Point(20, 20), "Enter at least 2 points!").draw(win)
win.getMouse()
main()
</code></pre>
<p>Any tips on what I should/could change here?</p>
| [] | [
{
"body": "<h1><code>from <xx> import *</code></h1>\n\n<p>Prevent a <code>*</code> import. You don't know what it will inject in your module namespace. Instead only import the parts you need:</p>\n\n<pre><code>from graphics import GraphWin, Line, Point, Rectangle, Text\n</code></pre>\n\n<p>The google style guide as <a href=\"http://google.github.io/styleguide/pyguide.html#22-imports\" rel=\"nofollow noreferrer\">linked</a> by Mircea also says not to import the classes, but only modules and packages, but that is a matter of style and taste.</p>\n\n<h1>Magic numbers</h1>\n\n<p>There are a lot of magic numbers, scattered in your code. If ever you want to change the location of the button, you will need to adapt that in a few places, and will most likely miss some. To prevent such magic numbers, you can do something like this:</p>\n\n<pre><code>def main():\n coord_max = 40\n win = GraphWin(\"Regression Line\", 10 * coord_max, 10 * coord_max)\n\n win.setCoords(0, 0, coord_max, coord_max)\n\n button_x, button_y = 35, 3\n button_width, button_height = 8, 4\n\n Text(Point(button_x, button_y), \"DONE\").draw(win)\n button = Rectangle(\n Point(button_x - button_width / 2, button_y - button_height / 2),\n Point(button_x + button_width / 2, button_y + button_height / 2),\n )\n button.draw(win)\n</code></pre>\n\n<h1>split functionality</h1>\n\n<p>your <code>dots</code> method does a lot of things now. It:</p>\n\n<ul>\n<li>catches the click</li>\n<li>checks whether it it is the button</li>\n<li>draws the point</li>\n<li>does the summary calculations</li>\n</ul>\n\n<p>Especially the last one should be factored to its own method. The easiest way to do this is let <code>dots</code> just yield the x and y coordinate, and let another method take care of the regression.</p>\n\n<p>Checking whether the click is on the button can also be done simpler. Instead of hardcoding the coordinates, simplest would be to pass in the button object, and ask that one for its bounding coordinates:</p>\n\n<pre><code>def dots(win, button):\n\n while True:\n\n click = win.getMouse()\n x = click.getX()\n y = click.getY()\n if button.p1.x <= x <= button.p2.x and button.p1.y <= y <= button.p2.y:\n break # button press\n Point(x, y).draw(win)\n yield x, y\n</code></pre>\n\n<p>Is to me a lot clearer and easier to understand.</p>\n\n<p>If you don't know that p1 and p2 are bottomleft and topright, you can take that into account by doing:</p>\n\n<pre><code>def dots(win, button):\n while True:\n click = win.getMouse()\n x = click.getX()\n y = click.getY()\n\n x1, x2 = sorted((button.p1.x, button.p2.x))\n y1, y2 = sorted((button.p1.y, button.p2.y))\n if x1 <= x <= x2 and y1 <= y <= y2: # button press\n break\n Point(x, y).draw(win)\n yield x, y\n</code></pre>\n\n<h1>summarize:</h1>\n\n<p>Instead of each summary metric getting its own variable, you can save them in a <code>dict</code> (or a <code>collections.Counter</code> more specifically)</p>\n\n<pre><code>def summarize(points):\n summary = Counter()\n for x, y in points:\n summary[\"x\"] += x\n summary[\"y\"] += y\n summary[\"x2\"] += x ** 2\n summary[\"xy\"] += x * y\n summary[\"count\"] += 1\n summary[\"mean_x\"] = summary[\"x\"] / summary[\"count\"]\n summary[\"mean_y\"] = summary[\"y\"] / summary[\"count\"]\n return summary\n</code></pre>\n\n<h1>regression:</h1>\n\n<p>Then pass this on to a method that calculates the regression line. This needs the maximum <code>x</code> of the screen as an argument:</p>\n\n<pre><code>def regression_line(summary, x_max, x_min=0):\n slope = (\n summary[\"xy\"]\n - summary[\"count\"] * summary[\"mean_x\"] * summary[\"mean_y\"]\n ) / (summary[\"x2\"] - summary[\"count\"] * summary[\"mean_x\"] ** 2)\n\n y_min = summary[\"mean_y\"] + slope * (x_min - summary[\"mean_x\"])\n y_max = summary[\"mean_y\"] + slope * (x_max - summary[\"mean_x\"])\n\n return Line(Point(x_min, y_min), Point(x_max, y_max))\n</code></pre>\n\n<h1>rest of <code>main</code></h1>\n\n<pre><code>points = dots(win, button=button)\nsummary = summarize(points)\ntry:\n regline = regression_line(summary, x_max=coord_max)\nexcept ZeroDivisionError:\n middle_point = Point(coord_max / 2, coord_max / 2)\n Text(middle_point, \"Enter at least 2 points!\").draw(win)\nelse:\n regline.draw(win)\nwin.getMouse()\n</code></pre>\n\n<h1>main guard</h1>\n\n<p>If you put the calling of <code>main()</code> behind <code>if __name__ == \"__main__\":</code>, you can later import this module from somewhere else, and reuse some of the code</p>\n\n<pre><code>if __name__ == \"__main__\":\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T16:23:59.097",
"Id": "412937",
"Score": "0",
"body": "Thanks for this in depth answer! Some things i did the way i did them just because i don't know more advanced methods, for example each metric having its own variable. I just don't know about summaries and dicts yet, it'll probably be further into the book.\n\nAs for the * import: I don't usually do that. In this case the author of the book (who also made the module) said it's supposed to be that way for this module. I once tried \"import graphics\" but that didn't work."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T13:38:55.920",
"Id": "213454",
"ParentId": "213442",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T09:38:50.133",
"Id": "213442",
"Score": "5",
"Tags": [
"python",
"performance",
"programming-challenge",
"statistics",
"gui"
],
"Title": "Linear regression on points specified by the user in a GUI"
} | 213442 |
<p>I invested an hour or so to reimplement the C++ header <code><array></code>. Most stuff is in the namespace <code>my_std</code>, but <code>tuple_size</code>, etc. are not, otherwise they are useless. I aimed for <strong>C++14</strong>. </p>
<p>One caveat: the <code>array<T, N>::swap</code> member function's noexcept specification is too complicated, and I chose not to reimplement the <code>std::is_nothrow_swappable</code> trait which is not available prior to C++17.</p>
<p>I used <a href="https://en.cppreference.com/w/cpp/header/array" rel="nofollow noreferrer">cppreference</a> as a reference. I did not check everything, though, and there may be nonconforming stuff or stuff taken from C++17. Feel free to tell me :)</p>
<p>Here is my code, within 300 lines: (excluding blank lines and comments)</p>
<pre><code>// array.hpp
// C++14 std::array implementation
#ifndef INC_ARRAY_HPP_JCr9Lp1ED0
#define INC_ARRAY_HPP_JCr9Lp1ED0
#include <algorithm>
#include <cstddef>
#include <initializer_list>
#include <iterator>
#include <stdexcept>
#include <tuple>
#include <type_traits>
#include <utility>
namespace my_std {
template <class T, std::size_t N>
struct array {
private:
void error() const
{
throw std::out_of_range{ "array out of range" };
}
public:
using value_type = T;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reference = T&;
using const_reference = const T&;
using pointer = T*;
using const_pointer = const T*;
using iterator = T*;
using const_iterator = const T*;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
constexpr bool empty() const noexcept
{
return N == 0;
}
constexpr size_type size() const noexcept
{
return N;
}
constexpr size_type max_size() const noexcept
{
return N;
}
T& at(std::size_t pos)
{
if (pos >= N)
this->error();
return elems[pos];
}
constexpr const T& at(std::size_t pos) const
{
if (pos >= N)
this->error();
return elems[pos];
}
T& operator[](std::size_t pos)
{
return elems[pos];
}
constexpr const T& operator[](std::size_t pos) const
{
return elems[pos];
}
T& front()
{
return elems[0];
}
constexpr const T& front() const
{
return elems[0];
}
T& back()
{
return elems[N - 1];
}
constexpr const T& back() const
{
return elems[N - 1];
}
T* data() noexcept
{
return elems;
}
constexpr const T* data() const noexcept
{
return elems;
}
T* begin() noexcept
{
return elems;
}
const T* begin() const noexcept
{
return elems;
}
const T* cbegin() const noexcept
{
return elems;
}
T* end() noexcept
{
return begin() + N;
}
const T* end() const noexcept
{
return begin() + N;
}
const T* cend() const noexcept
{
return begin() + N;
}
auto rbegin() noexcept
{
return std::make_reverse_iterator(end());
}
auto rbegin() const noexcept
{
return std::make_reverse_iterator(end());
}
auto crbegin() const noexcept
{
return std::make_reverse_iterator(end());
}
auto rend() noexcept
{
return std::make_reverse_iterator(begin());
}
auto rend() const noexcept
{
return std::make_reverse_iterator(begin());
}
auto crend() const noexcept
{
return std::make_reverse_iterator(begin());
}
void fill(const T& value)
{
std::fill_n(elems, N, value);
}
/*
Note: is_nothrow_swappable_v
is not available prior to C++17.
I am not going to the trouble to
implement it from scratch.
So the noexcept specification of swap
is left unimplemented.
*/
void swap(array& other) /*noexcept(std::is_swappable_v<T>)*/
{
std::swap_ranges(begin(), end(), other.begin());
}
T elems[N];
};
template <class T>
struct array<T, 0> {
private:
void error() const
{
throw std::out_of_range{ "array out of range" };
}
public:
using value_type = T;
using size_type = std::size_t;
using difference_type = std::ptrdiff_t;
using reference = T&;
using const_reference = const T&;
using pointer = T*;
using const_pointer = const T*;
using iterator = T*;
using const_iterator = const T*;
using reverse_iterator = std::reverse_iterator<iterator>;
using const_reverse_iterator = std::reverse_iterator<const_iterator>;
constexpr bool empty() const noexcept { return true; }
constexpr std::size_t size() const noexcept { return 0; }
constexpr std::size_t max_size() const noexcept { return 0; }
T& at(std::size_t pos) { this->error(); }
constexpr const T& at(std::size_t pos) const { this->error(); }
T& operator[](std::size_t pos) { this->error(); }
constexpr const T& operator[](std::size_t pos) const { this->error(); }
T& front() { this->error(); }
constexpr const T& front() const { this->error(); }
T& back() { this->error(); }
constexpr const T& back() const { this->error(); }
T* data() noexcept { return nullptr; }
constexpr const T* data() const noexcept { return nullptr; }
T* begin() noexcept { return nullptr; }
const T* begin() const noexcept { return nullptr; }
const T* cbegin() const noexcept { return nullptr; }
T* end() noexcept { return nullptr; }
const T* end() const noexcept { return nullptr; }
const T* cend() const noexcept { return nullptr; }
T* rbegin() noexcept { return nullptr; }
const T* rbegin() const noexcept { return nullptr; }
const T* crbegin() const noexcept { return nullptr; }
T* rend() noexcept { return nullptr; }
const T* rend() const noexcept { return nullptr; }
const T* crend() const noexcept { return nullptr; }
void fill(const T& value) {}
void swap(array& other) noexcept {}
};
template <class T, std::size_t N>
inline bool operator==(const array<T, N>& lhs,
const array<T, N>& rhs)
{
return std::equal(lhs.begin(), lhs.end(),
rhs.begin(), rhs.end());
}
template <class T, std::size_t N>
inline bool operator!=(const array<T, N>& lhs,
const array<T, N>& rhs)
{
return !(lhs == rhs);
}
template <class T, std::size_t N>
inline bool operator< (const array<T, N>& lhs,
const array<T, N>& rhs)
{
return std::lexicographical_compare(lhs.begin(), lhs.end(),
rhs.begin(), rhs.end());
}
template <class T, std::size_t N>
inline bool operator<=(const array<T, N>& lhs,
const array<T, N>& rhs)
{
return !(rhs < lhs);
}
template <class T, std::size_t N>
inline bool operator> (const array<T, N>& lhs,
const array<T, N>& rhs)
{
return rhs < lhs;
}
template <class T, std::size_t N>
inline bool operator>=(const array<T, N>& lhs,
const array<T, N>& rhs)
{
return !(lhs < rhs);
}
template <std::size_t I, class T, std::size_t N>
constexpr T& get(array<T, N>& a) noexcept
{
return a[I];
}
template <std::size_t I, class T, std::size_t N>
constexpr T&& get(array<T, N>&& a) noexcept
{
return static_cast<T&&>(a[I]);
}
template <std::size_t I, class T, std::size_t N>
constexpr const T& get(const array<T, N>& a) noexcept
{
return a[I];
}
template <class T, std::size_t N>
void swap(array<T, N>& lhs, array<T, N>& rhs)
noexcept(noexcept(lhs.swap(rhs)))
{
return lhs.swap(rhs);
}
}
namespace std {
template <class T, std::size_t N>
class tuple_size<my_std::array<T, N>>
:public std::integral_constant<std::size_t, N> {
};
template <std::size_t I, class T, std::size_t N>
struct tuple_element<I, my_std::array<T, N>> {
using type = T;
};
}
#endif
</code></pre>
<p>The naming for the include guard just contains a random string to avoid name clashes. Generally, I don't like (C++) macros.</p>
| [] | [
{
"body": "<p>If you define all the types why not use them?</p>\n\n<pre><code> const T* begin() const noexcept\n\n // More informative to write:\n\n const_iterator begin() const noexcept\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T23:40:00.947",
"Id": "412963",
"Score": "0",
"body": "Good point! I ought to have used the type aliases I have defined to improve readability instead of littering with “magic types.” I accepted this, but other suggestions are also welcomed ;)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T01:48:05.033",
"Id": "412970",
"Score": "0",
"body": "If you look at my other reviews you will see I usually take code apart piece by piece. But don't see anything else worth commenting on. But it is a very simple bit of code. ;-)"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T21:10:31.387",
"Id": "213478",
"ParentId": "213443",
"Score": "7"
}
},
{
"body": "<p>Another point: instead of</p>\n\n<pre><code>if (pos >= N)\n this->error();\n</code></pre>\n\n<p>it is sufficient to do</p>\n\n<pre><code>if (pos >= N)\n error();\n</code></pre>\n\n<p>since the <code>this-></code> is redundant. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T23:51:23.540",
"Id": "213482",
"ParentId": "213443",
"Score": "1"
}
},
{
"body": "<blockquote>\n <p>One caveat: the <code>array<T, N>::swap</code> member function's <code>noexcept</code> specification is too complicated, and I chose not to reimplement the <code>std::is_nothrow_swappable</code> trait which is not available prior to C++17.</p>\n</blockquote>\n\n<p>If a type trait doesn't exist, write your own. C++11/14 overlooked a lot of library features that didn't require language support when they were added in 17. <code>is_nothrow_swappable</code> is one of those library features (is also 3 simple structs to test).</p>\n\n<blockquote>\n <p>I used cppreference as a reference. I did not check everything, though, and there may be nonconforming stuff or stuff taken from C++17. Feel free to tell me :)</p>\n</blockquote>\n\n<p>You should use the C++14 standard or a draft version close to the final C++14 standard. <a href=\"https://timsong-cpp.github.io/cppwp/n4140/array\" rel=\"nofollow noreferrer\">N4140</a> was the first draft after C++14 was published.</p>\n\n<hr>\n\n<pre><code> void error() const\n {\n throw std::out_of_range{ \"array out of range\" };\n }\n</code></pre>\n\n<p>Your function could be better named here. I'd even consider generalizing it to take any <code>const char*</code> message and make it a free function.</p>\n\n<hr>\n\n<pre><code> constexpr bool empty() const noexcept\n {\n return N == 0;\n }\n</code></pre>\n\n<p>Since you specialize the case where <code>N</code> is <span class=\"math-container\">\\$0\\$</span>, this function will always return false.</p>\n\n<hr>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T03:58:52.523",
"Id": "412973",
"Score": "0",
"body": "Thank you! I was just too lazy to implement the `is_nothrow_swappable`. About `<initializer_list>`: that's required by the standard."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T04:14:49.023",
"Id": "412974",
"Score": "0",
"body": "Are you confusing the *initializer clauses* of an aggregate *initializer list* (`array a = { initializer list }`) with `std::initializer_list`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T04:15:55.037",
"Id": "412975",
"Score": "1",
"body": "I know that `std::initializer_list` is not necessary. But the standard requires that `<array>` includes `<initializer_list>`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T04:16:50.457",
"Id": "412976",
"Score": "1",
"body": "Look: http://eel.is/c++draft/array.syn"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T04:27:39.553",
"Id": "412977",
"Score": "0",
"body": "Gotcha, skipped over the synopsis. Removed from the answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T17:34:23.413",
"Id": "413071",
"Score": "1",
"body": "You can find a list of publicly available versions of the draft standard here: https://stackoverflow.com/a/4653479/14065"
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T03:11:00.477",
"Id": "213487",
"ParentId": "213443",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "213478",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T09:40:01.330",
"Id": "213443",
"Score": "7",
"Tags": [
"c++",
"array",
"reinventing-the-wheel"
],
"Title": "C++14 std::array implementation"
} | 213443 |
<p>I'm trying to implement the game <a href="https://en.wikipedia.org/wiki/Snake_(video_game_genre)" rel="nofollow noreferrer">Snake</a> in Javascript and getting the computer to play it by itself, and want to check whenever the snake loops (repeats the same set of moves twice) so I can kill it.</p>
<p>To do this, the first thing that came to mind is saving the state the entire game at every frame (the state being the position of the snake's head and body segments, as well as the position of the 'pallet' it's looking to eat) in some sort of dictionary, and checking every frame if the new state of the game exists in this dictionary.</p>
<p>I don't quite know what's the best/most efficient/most readable way to implement this is. Here's what I tried so far:</p>
<pre><code>const Snake = {
direction: new Vector2(0, 1), // Up
pallet: Vector2.random(0, 100, 0, 100).floor(),
head: Vector2.random(0, 100, 0, 100).floor(),
body: [], // Array of Vector2's
loopHistory: {}, // Records every state
checkForLoop: function () {
// Current state of the system:
const arr = [this.direction.hash(), this.pallet.hash(), this.head.hash(), ...this.body.map(x => x.hash())];
//True if a loop is found, false if the state is completely new:
let found = true;
let obj = this.loopHistory;
for (let i = 0; i < arr.length; i++) {
if (!obj.hasOwnProperty(arr[i])) {
//This is a part of the state that has never been seen before (new pallet position, new body segment etc.)
found = false;
// Record it for the next time:
obj[arr[i]] = {};
}
obj = obj[arr[i]];
}
return found;
}
}
</code></pre>
<p><code>loopHistory</code> and <code>checkForLoop</code> are the relevant bits. Here's the Vector2 class for reference:</p>
<pre><code> const Vector2 = function (x, y) {
this.x = x;
this.y = y;
};
Vector2.random = function (xmin, xmax, ymin, ymax) {
return new Vector2(
xmin + Math.random() * (xmax - xmin),
ymin + Math.random() * (ymax - ymin)
);
};
Vector2.prototype.hash = function () {
return this.x + 73856093 * this.y;
};
Vector2.prototype.floor = function () {
return new Vector2(Math.floor(this.x), Math.floor(this.y));
};
</code></pre>
<p>The issue with this implementation is it generates a massive ever growing arbitrarily deep object (loopHistory) for every game being run. With each game there could be thousands of states before the snake actually loops to its death, and there could be up to one hundred games running at once. The solution feels inefficient and clumsy and difficult to read/maintain, plus it takes a lot of memory, but that seems inevitable. So I'm looking for the go-to solution for situation like this, if one exists, or just any better implementation.</p>
<p>Please help me kill the snake! Thanks in advance for answers.</p>
<p><strong>Edit:</strong> I forgot to mention that the behavior of the snake is only dependent on the state of the system that we captured earlier (head position, body positions, pallet position) so if it finds itself in the exact same circumstance it will inevitably react the same way and repeat the same moves.</p>
| [] | [
{
"body": "<blockquote>\n <p>So I'm looking for the go-to solution for situation like this, if one exists</p>\n</blockquote>\n\n<p>Big step, small step. Rather than run the snake once, you run it twice in parallel, but the two instances run at different speeds:</p>\n\n<pre><code>snake1 = ...;\nsnake2 = snake1.clone();\nwhile (true) {\n snake1.step();\n snake2.step();\n snake2.step();\n if (snake1.equals(snake2)) {\n // Loop detected\n }\n}\n</code></pre>\n\n<p>If the cycle is of length <span class=\"math-container\">\\$n\\$</span> and you enter the cycle for the first time at <span class=\"math-container\">\\$t_0\\$</span> then this will detect the cycle as long as there's a number <span class=\"math-container\">\\$t \\ge t_0\\$</span> for which <span class=\"math-container\">\\$t \\equiv 2t \\pmod n\\$</span>. But that reduces to <span class=\"math-container\">\\$t \\equiv 0 \\pmod n\\$</span>, so <span class=\"math-container\">\\$t\\$</span> is the first multiple of <span class=\"math-container\">\\$n\\$</span> greater than or equal to <span class=\"math-container\">\\$t_0\\$</span>, and it's guaranteed to find the loop.</p>\n\n<p>Essentially you trade memory saving (no history required) for execution time (it takes <span class=\"math-container\">\\$3t\\$</span> calls to <code>step()</code> rather than <span class=\"math-container\">\\$t_0 + n\\$</span>).</p>\n\n<hr>\n\n<p>That renders rather unnecessary the following observation:</p>\n\n<blockquote>\n<pre><code> const arr = [this.direction.hash(), this.pallet.hash(), this.head.hash(), ...this.body.map(x => x.hash())];\n</code></pre>\n</blockquote>\n\n<p>Most of those don't need to use a <code>Vector2</code> with a hash: there are 4 possibilities for the direction, and the body can be represented by a series of directions. Using arrays of length 4 might be more efficient than object properties.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T10:52:15.753",
"Id": "412893",
"Score": "0",
"body": "Of course, the Tortoise and Hare! Really smart way to approach it. And you're absolutely right, the direction could even be represented by a class with 2 Boolean properties. Thanks!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T10:32:25.950",
"Id": "213448",
"ParentId": "213444",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T09:44:51.510",
"Id": "213444",
"Score": "3",
"Tags": [
"javascript",
"hash-map"
],
"Title": "Hash table with complex variable-length keys"
} | 213444 |
<p>The following is a bash script named <code>wrapper.sh</code>:</p>
<pre><code>#!/bin/bash
data="ZAA:huhu;ZBB:blub;___uname" # actually coming from a Python script
i=1 # counter
while true ; do # loop infinitely
segment=$(echo $data | cut -d ';' -f$i)
if [ -z "$segment" ] ; then # is segment empty?
break
fi
if [[ $segment == ___* ]] ; then # is this a command?
cmd="${segment:3}" # strip command prefix
$cmd "${@:2}" # run *interactive* command
# cat | $cmd "${@:2}" # "OPTIONAL": pass data from stdin ONLY IF THERE IS A PIPE (?)
else
varname=$(echo $segment | cut -d ':' -f1)
vardata=$(echo $segment | cut -d ':' -f2)
export $varname=$vardata # export environment variable
fi
i=$((i + 1)) # increment counter
done
# Just a test
echo $ZAA
echo $ZBB
</code></pre>
<p>The above script has to accomplish the following goals:</p>
<ul>
<li>Pass its own parameters to a Python script, which processes them and returns a <code>data</code> string (intentionally left out of the above example)</li>
<li>Set (export) an arbitrary number of environment variables. Their names and contents are provided in <code>data</code>.</li>
<li>Run a command also provided in <code>data</code> and pass on all but the first argument given to the shell script.</li>
</ul>
<p>Goal the code does not achieve yet: If a pipe is passed to the script (as in <code>some_program | ./wrapper.sh</code>), the pipe is supposed to passed on to the command called by <code>wrapper.sh</code>. The statement <code>cat | $cmd "${@:2}"</code> basically does this, but it hangs if no pipe is passed to <code>wrapper.sh</code>.</p>
<p>Why? Well actually, this thing started as a pure Python script, which was calling the command through <code>subprocess.Popen</code>. But it turned out insanely hard and error-prone to run an <strong>interactive</strong> command like this where an actual human user is supposed to interact with the (running) command. This is something bash is infinitely better at.</p>
<p>Example:</p>
<pre><code>(env) user@box:~> ./wrapper.sh
Linux
huhu
blub
(env) user@box:~> ./wrapper.sh omitted
Linux
huhu
blub
(env) user@box:~> ./wrapper.sh omitted -a
Linux X.X 4.X.XXX #1 SMP XXX 2018 (XXX) x86_64 x86_64 x86_64 GNU/Linux
huhu
blub
</code></pre>
<p>I am not exactly a frequent bash coder, so any ideas on how to improve the above are highly welcome. I might also have overlooked "edge cases" where my script does something strange - I'd love to know.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T17:58:30.993",
"Id": "412949",
"Score": "4",
"body": "I'm not following what you are _really_ trying to accomplish with this seemingly insane system. Perhaps you would be better off including the entire Python-and-Bash system here fore review, so that we can understand the context and suggest a better mechanism entirely."
}
] | [
{
"body": "<ul>\n<li><p>The infinite loop with <code>break</code>, counter, and multiple invocations of <code>cut</code> looks clumsy at best. Consider instead</p>\n\n<pre><code>IFS=\";\"\nfor segment in $data; do\n # your logic here\ndone\n</code></pre></li>\n<li><p>Similarly, <code>cut</code>ting the segment is unnecessary:</p>\n\n<pre><code> IFS=\":\"\n set $segment\n export $1=$2\n IFS=\";\"\n</code></pre>\n\n<p>does the same job.</p></li>\n<li><p>I don't understand the <em>goal not achieved yet</em>. The script has no knowledge where its input coming from. Whoever calls your script is in the position to redirect it at will. Perhaps, close <code>stdin</code> before invoking it?</p></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T04:27:48.047",
"Id": "213492",
"ParentId": "213447",
"Score": "1"
}
},
{
"body": "<h3>Overcomplicated and inefficient parsing</h3>\n\n<p>The parsing of <code>data</code> is both overcomplicated and inefficient:</p>\n\n<ul>\n<li><p>The loop is confusing, because each step has to decide between multiple possible action: split arguments, or run a command, or break. Ideally each step does one kind of thing, that would be very easy to understand</p></li>\n<li><p>As the other review pointed out, invoking <code>cut</code> in a loop is inefficient. In most steps it's invoked multiple times. There are much better ways to split strings than <code>cut</code>.</p></li>\n</ul>\n\n<p>If there are no spaces in <code>data</code> (as in the example), then the loop can be replaced with:</p>\n\n<pre><code>cmd=${data#*;___} # extract the suffix, chopping off the beginning until \";___\"\nvars=${data%%;___*} # extract the prefix, chopping off the end from \";___\"\nvars=(${vars//[:;]/ }) # replace : and ; with space, and convert to an array\n\nfor ((i = 0; i < ${#vars[@]}; i += 2)); do\n export ${vars[i]}=${vars[i+1]}\ndone\n\n\"$cmd\" \"${@:2}\"\n</code></pre>\n\n<p>I think this is easier to understand and efficient.</p>\n\n<h3>Flawed justification to use Bash instead of Python</h3>\n\n<blockquote>\n <p>Why? Well actually, this thing started as a pure Python script, which was calling the command through <code>subprocess.Popen</code>. But it turned out insanely hard and error-prone to run an <strong>interactive</strong> command like this where an actual human user is supposed to interact with the (running) command. This is something bash is infinitely better at.</p>\n</blockquote>\n\n<p>It's not at all clear why Bash is better at whatever \"this\" is.\nIt should not be insanely hard and error-prone to run interactive programs from Python. If you post that Python code (in another question), a reviewer is likely to be able to guide you back to sanity.</p>\n\n<h3>Minor Bash issues</h3>\n\n<p>Don't <code>echo</code> and pipe. Use <em>here strings</em> instead. For example, instead of <code>echo $data | cut -d ';' -f$i</code>, write <code>cut -d ';' -f$i <<< \"$data\"</code>.</p>\n\n<p>Double-quote variables used in command arguments. Instead of <code>echo $data</code>, write <code>echo \"$data\"</code>.</p>\n\n<p>Double-quote variables used as commands. Instead of <code>$cmd \"${@:2}\"</code>, write <code>\"$cmd\" \"${@:2}\"</code>.</p>\n\n<p>Instead of <code>i=$((i + 1))</code>, the arithmetic expression <code>((i++))</code> is probably easier to read, write and understand.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T09:40:41.213",
"Id": "213568",
"ParentId": "213447",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T10:22:58.537",
"Id": "213447",
"Score": "0",
"Tags": [
"bash"
],
"Title": "\"command preprocessing\" with bash - string parsing and handling pipes"
} | 213447 |
<p>The problem is taken from one of recent SO questions: </p>
<p>Finding max sum of matrix elements with following constraints:</p>
<ol>
<li>Exactly one row element has to be included in the sum</li>
<li>If element at (i, j) is selected, then (i + 1, j) is not.</li>
<li>Values in the matrix are nonnegative integers.</li>
</ol>
<p>Below is my working (as far as I can tell) solution. It is based on the following observation: given a solution for a (N x M) matrix (in terms of taken path), the path is either the solution for the matrix without the last row (that is N -1 x M), or there exists at most one better path for the submatrix.<br>
I've aimed to provide code testable at compile time, for that purpose I've also written a lightweight wrapper of <code>std::array</code>, with interface being a subset of e.g. <code>eigen::Matrix</code> classes.</p>
<p>Compiles fine with both gcc and clang (<code>-std=c++17 -Werror -Wall -Wpedantic</code>). </p>
<p>Any thoughts on how to improve it?</p>
<pre><code>#include <array>
/*
* Small access wrapper for an array.
* Underlying storage kept puclic to allow efficient construction as an aggregate
*/
template <typename T, std::size_t rows_, std::size_t cols_>
struct Array2d {
T& operator()(std::size_t row, std::size_t col) {
return storage[index(row, col)];
}
constexpr T const & operator()(std::size_t row, std::size_t col) const {
return storage[index(row, col)];
}
constexpr std::size_t rows() const { return rows_; }
constexpr std::size_t cols() const { return cols_; }
std::array<T, rows_ * cols_> storage;
private:
constexpr std::size_t index (std::size_t row, std::size_t col) const {
return cols_ * row + col;
}
};
template<std::size_t rows, std::size_t cols>
using Problem = Array2d<int, rows, cols>;
namespace MaxSum {
namespace Details {
struct IndexedRowValue {
int val;
std::size_t index;
};
template<std::size_t count>
using TopElements = std::array<IndexedRowValue, count>;
constexpr TopElements<2> sorted_first_two (int v1, int v2) {
auto m1 = IndexedRowValue{v1, 0};
auto m2 = IndexedRowValue{v2, 1};
return v1 >= v2
? TopElements<2>{m1, m2}
: TopElements<2>{m2, m1};
}
constexpr void update_top (TopElements<2> & top_paths, int path_value,
std::size_t col) {
if (path_value > top_paths[0].val) {
top_paths[1] = top_paths[0];
top_paths[0] = IndexedRowValue{path_value, col};
}
else if (path_value > top_paths[1].val)
top_paths[1] = IndexedRowValue{path_value, col};
}
template<typename Matrix>
constexpr TopElements<2> find_top2_in_first_row (Matrix const &input) {
auto result = sorted_first_two(input(0, 0), input(0, 1));
for (auto i = 2u; i < input.cols(); ++i)
update_top(result,input(0, i), i);
return result;
}
constexpr int best_path_value_through_element(TopElements<2> const & top_last_row,
int val,
std::size_t col){
return top_last_row[0].index != col
? top_last_row[0].val + val
: top_last_row[1].val + val;
}
template<typename Matrix>
constexpr TopElements<2> find_best_paths_for_row(TopElements<2> const & top_last_row,
std::size_t row,
Matrix const & input) {
auto path_0 = best_path_value_through_element(top_last_row, input(row, 0), 0u);
auto path_1 = best_path_value_through_element(top_last_row, input(row, 1), 1u);
auto top_paths = sorted_first_two(path_0, path_1);
for (auto i = 2u; i < input.cols(); ++i) {
auto path_i = best_path_value_through_element(top_last_row, input(row, i), i);
update_top(top_paths, path_i, i);
}
return top_paths;
}
template<typename Matrix>
constexpr int solve_non_trivial(Matrix const & input) {
auto top_paths = find_top2_in_first_row(input);
for (auto i = 1u; i < input.rows(); ++i)
top_paths = find_best_paths_for_row(top_paths, i, input);
// key observation: optimal path at row i is either best or second best at i - 1
return top_paths[0].val;
}
} // namespace Details
/*
* Finds max sum of elements of input Matrix, with following constraints:
* Exactly one element from each row can be selected
* If element at (i, j) has been selected, then (i + 1, j) can't be selected
*
* Matrix elements are required to be nonnegative integers.
*/
template<typename Matrix>
constexpr int solve (Matrix const & input) {
int result = 0; // reasonable answer for cases where rows > cols
// special case for 1x1 matrices
if (input.rows() == 1 && input.cols() == 1)
result = input(0, 0);
else if (input.rows() <= input.cols()){
result = Details::solve_non_trivial(input);
}
return result;
}
} // namespace MaxSum
int main() {
constexpr auto trivial = Problem<1u, 1u>{{1}};
static_assert(MaxSum::solve(trivial) == 1);
constexpr auto problem2x2_0 = Problem<2u, 2u>{{1, 0, 0, 1}};
static_assert(MaxSum::solve(problem2x2_0) == 2);
constexpr auto problem2x2_1 = Problem<2u, 2u>{{10, 0, 9, 0}};
static_assert(MaxSum::solve(problem2x2_1) == 10);
constexpr auto problem2x2_2 = Problem<2u, 2u>{{10, 2, 9, 0}};
static_assert(MaxSum::solve(problem2x2_2) == 11);
constexpr auto problem1x5 = Problem<1u, 5u>{{10, 2, 9, 7, 6}};
static_assert(MaxSum::solve(problem1x5) == 10);
constexpr auto problem1x7 = Problem<1u, 7u>{{10, 2, 9, 7, 6, 12, 11}};
static_assert(MaxSum::solve(problem1x7) == 12);
constexpr auto problem3x3 = Problem<3u, 3u>{{1, 2, 3,
5, 6, 4,
3, 2, 4}};
static_assert(MaxSum::solve(problem3x3) == 13);
constexpr auto problem4x4 = Problem<4u, 4u>{{1, 2, 3, 4,
5, 6, 7, 8,
9, 1, 4, 2,
6, 3, 5, 7}};
static_assert(MaxSum::solve(problem4x4) == 27);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T00:53:11.880",
"Id": "412966",
"Score": "1",
"body": "Since you are aiming C++17, you can make the non-`const` `operator[]`s `constexpr` too: `constexpr T& operator()(std::size_t row, std::size_t col) { /*...*/ }`"
}
] | [
{
"body": "<p>Given that the result can be computed as simply as this:</p>\n\n<pre><code>#include <array>\n\ntemplate <std::size_t MN>\nconstexpr int maximum_sum(std::array<int, MN> array, int M, int N, int current_row, int skip) {\n int max = 0;\n for (int x = 0; x < N; ++x) {\n if (x == skip) continue;\n int value = array[current_row * N + x];\n max = std::max(max, current_row + 1 == M ? value : value + maximum_sum(array, M, N, current_row + 1, x));\n }\n return max;\n}\n</code></pre>\n\n<p>I find your code really complicated.</p>\n\n<p>The wrapper looks like a half-measure to me. If you only want a convenient way to handle an array as a 2-dimensional matrix for the task at hand, I'd say that inheritance is more powerful and concise:</p>\n\n<pre><code>template <std::size_t M, std::size_t N>\nstruct Array_2d : public std::array<int, M * N> {\n constexpr int at(std::size_t m, std::size_t n) const { return (*this)[m * N + n]; }\n}\n</code></pre>\n\n<p>Dimensions can then be deduced in the function call: </p>\n\n<pre><code>template <std::size_t M, std::size_t N>\nconstexpr int maximum_sum(Array_2d<M, N> array, std::size_t current_row = 0, std::size_t skip = N) {\n // same as before\n}\n</code></pre>\n\n<p>And if you want a solid, re-usable, <code>constepxr</code> matrix class then write it, but that goes far beyond the functionalities of your wrapper.</p>\n\n<p>Burying types isn't a good thing either: your <code>Problem</code> is fundamentally an <code>array</code>, but there are two \"indirection\" levels before you can ascertain it: an alias, and a composition. Idem for <code>TopElements</code>, which is a simple <code>pair</code> the reader needs some work to recognize under an other alias and a custom class. One good way to look at your program is to understand that you are creating a language: do not create new words when you can use the ones everyone knows.</p>\n\n<p>Your algorithm probably works, but it isn't clearly described (what is a \"matrix, in terms of a taken path\"?), and relies on a long chain of function calls which doesn't make it any easier to understand. Moving away from the simplest algorithm isn't justified unless you can prove it's faster (and that speed matters); but you don't study your algorithm complexity.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T12:10:35.707",
"Id": "413026",
"Score": "0",
"body": "Sorry if the description was unclear: it was \"solution in terms of taken path\" -> \nthat is path maximizing the sum. \nThe observation made allows the algorithm to run in O(M x N) (that is pretty much optimal, \ngiven that each matrix element has to be inpected) time \nwith O(1) auxillary space (again can't do better than that I guess)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T12:35:02.163",
"Id": "413030",
"Score": "0",
"body": "As to inheriting from `std::array` -> this seems wrong, as `std::array` does not have a virtual destructor. And if you decide to go for `private / protected` inheritance then you no longer deal with aggregate type."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T15:13:17.673",
"Id": "413045",
"Score": "0",
"body": "@paler123: that's clearer now, but you should try to go the extra mile and describe your algorithm, not only the observation it's based on. It makes reading the code a lot easier. / As to inheritance, as I said, don't go for half-measures: if you want to write a library-grade matrix class, then go ahead, but your `Array2d` isn't up to the task; if you only want a quick prototype, then by all means, we're consenting adults around there, we won't use base pointers to allocate those arrays on the heap behind your back, so go for what's concise and expressive."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:03:54.833",
"Id": "213508",
"ParentId": "213455",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T13:53:40.480",
"Id": "213455",
"Score": "3",
"Tags": [
"c++",
"dynamic-programming",
"c++17",
"constant-expression"
],
"Title": "Simple DP problem solved in compile time"
} | 213455 |
<p>This filter is basically gradient detection (the variable <code>gradImg</code>) like an edge detection (Sobel or Prewitt filters) and also the direction of that gradient whether vertical or horizontal (<code>dirImg</code>).</p>
<p>I'm trying to optimize it to run faster and I found that this part of the code slow. Would you have any suggestions please? Here's the code you can copy to <a href="http://quick-bench.com/" rel="nofollow noreferrer">http://quick-bench.com/</a>.</p>
<pre><code>#include <math.h>
static void Old_Version(benchmark::State& state) {
// Code inside this loop is measured repeatedly
int rows = 1000, cols = 1000;
unsigned char *smoothImg = new unsigned char[cols*rows];
short *gradImg = new short[cols*rows];
unsigned char* dirImg = new unsigned char[cols*rows];
for (auto _ : state) {
for (int i = 1; i<rows - 1; i++) {
for (int j = 1; j<cols - 1; j++) {
int com1 = smoothImg[(i + 1)*cols + j + 1] - smoothImg[(i - 1)*cols + j - 1];
int com2 = smoothImg[(i - 1)*cols + j + 1] - smoothImg[(i + 1)*cols + j - 1];
int gx=abs(com1+com2+(smoothImg[i*cols + j + 1] - smoothImg[i*cols + j - 1]));
int gy=abs(com1-com2+(smoothImg[(i + 1)*cols + j] - smoothImg[(i - 1)*cols + j]));
int sum = (int)sqrt((double)gx*gx + gy*gy);
int index = i*cols + j;
gradImg[index] = sum;
if (sum >= 20) {
if (gx >= gy) dirImg[index] = 1;//1 vertical
else dirImg[index] = 2;//2 Horizontal
}
}
}
}
}
// Register the function as a benchmark
BENCHMARK(Old_Version);
</code></pre>
<p>My compilation command, using GCC (Ubuntu 8.1.0-5ubuntu1~16.04) 8.1.0:</p>
<p><code>g++ -std=c++1z -fomit-frame-pointer -O4 -ffast-math -mmmx -msse -msse2 -msse3 -DNDEBUG -Wall improve_code.cpp -o improve_code -fopenmp</code></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T14:16:03.960",
"Id": "412924",
"Score": "2",
"body": "Could you add some details about what this filter does?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T14:19:37.797",
"Id": "412926",
"Score": "0",
"body": "Looks like `smoothImg` contents are used uninitialized, which makes for Undefined behaviour. Is this the real code from your project?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T14:21:14.820",
"Id": "412927",
"Score": "0",
"body": "@user673679 I added some information"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T14:22:46.933",
"Id": "412929",
"Score": "0",
"body": "@TobySpeight you're right, but smoothImg in my code is an image .. you can imagine a random values"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T14:48:36.860",
"Id": "412931",
"Score": "1",
"body": "Are SSE/AVX intrinsics within the scope of this question?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T14:50:49.243",
"Id": "412932",
"Score": "0",
"body": "Yes if they are useful in my case.. I don't know if they're already activated! I run my code in with gcc 8.2 on ubuntu 16 (see my edit -2)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T14:58:15.190",
"Id": "412933",
"Score": "0",
"body": "They're enabled but you're not using them yet, just relying on auto-vectorization (which didn't happen and admittedly it's not so simple here)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T17:43:34.910",
"Id": "412946",
"Score": "0",
"body": "`-msse` and the like imply that you're targeting x86 machines at least; what other processors is this to run on?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T10:43:20.223",
"Id": "413000",
"Score": "0",
"body": "@TobySpeight Is going to run on embaded system like the jetson nividia"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:08:18.217",
"Id": "413006",
"Score": "0",
"body": "AIUI, \"Jetson\" is a range of targets, from Cortex-A15 (32-bit ARMv7 with NEON) up to Cortex-A57 (64-bit ARMv8) and included GPGPU. You might find that GPU processing beats CPU code (and for standard filters like these, that libraries such as OpenCV outperform your hand-made code)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:12:11.937",
"Id": "413008",
"Score": "0",
"body": "@TobySpeight The issue is when I want to transfer data from CPU to GPU it is very slow so when I do that many times the whole program becomes slower than if it is all in CPU"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:17:26.783",
"Id": "413010",
"Score": "0",
"body": "Yes, that's always the issue with GPU computing (and why I said \"might\" rather than \"will\"). It depends on whether you already have the data on the GPU."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:22:27.110",
"Id": "413013",
"Score": "0",
"body": "@TobySpeight Yes you're right :)"
}
] | [
{
"body": "<p>Prefer C++ headers (<code><cmath></code> rather than <code><math.h></code>); we'll then use <code>std::abs()</code> and <code>std::sqrt()</code> - or better, <code>std::hypot()</code>.</p>\n\n<p>The <code>std::abs()</code> calls seem premature - we can defer them to within the <code>(sum >= 20)</code> condition.</p>\n\n<p>Prefer to give names to the values used in <code>dirImg</code>. For example:</p>\n\n<pre><code>enum orientation : unsigned char\n{\n None,\n Vertical,\n Horizontal,\n};\n</code></pre>\n\n<p>The indexing in the loop might be easier to read if we just offset from <code>index</code>; it might also be slightly more efficient if the compiler can't reason about the <code>(cols ± 1) * i)</code> for us:</p>\n\n<pre><code> for (std::size_t i = 1; i<rows - 1; i++) {\n for (std::size_t j = 1; j<cols - 1; j++) {\n auto const index = i*cols + j;\n\n // leading and trailing diagonal differences are common\n int com1 = smoothImg[index + cols + 1] - smoothImg[index - cols - 1];\n int com2 = smoothImg[index - cols + 1] - smoothImg[index + cols - 1];\n\n int gx = com1 + com2 + smoothImg[index + 1] - smoothImg[index - 1];\n int gy = com1 - com2 + smoothImg[index + cols] - smoothImg[index - cols];\n\n auto sum = static_cast<short>(std::hypot(gx, gy));\n\n gradImg[index] = sum;\n if (sum >= 20) {\n dirImg[index] = std::abs(gx) >= std::abs(gy) ? Vertical : Horizontal;\n }\n }\n }\n</code></pre>\n\n<p>What's special about the threshold value <code>20</code>? Perhaps that should be a parameter to the function.</p>\n\n<p>Remember to <code>delete[]</code> what you <code>new[]</code> - or better, use standard containers or smart pointers so that we don't need to remember, and so the storage is reclaimed even on a non-local exit (e.g. due to a later <code>std::bad_alloc</code>).</p>\n\n<p>Consider spreading the work across processor cores, e.g. by applying <code>#pragma omp parallel for</code> to the <code>i</code> loop.</p>\n\n<p>Be careful if you use the outputs - we've left a lot of the values uninitialised, especially in <code>dirImg</code>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T17:18:10.467",
"Id": "412939",
"Score": "0",
"body": "Is `hypot` really supposed to be better? A quick [test](http://quick-bench.com/TemEjltKsuTEmHes85K-in25f1k) suggests it's substantially worse"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T17:22:15.913",
"Id": "412940",
"Score": "0",
"body": "Yes, `std::hypot()` is required to be accurate to within 1 ULP, and there are tighter constrains on returning subnormal values. It's also easier to read."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T17:41:15.680",
"Id": "412944",
"Score": "0",
"body": "But it makes the whole thing 2.5 as slow. That doesn't work on a question that asks how to make it faster. Besides, the result is truncated and the input cannot be subnormal (apart from zero but do we really consider that a subnormal?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T17:42:03.143",
"Id": "412945",
"Score": "0",
"body": "@harold - the question wasn't tagged [tag:performance] until after I published this answer."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T10:20:30.223",
"Id": "412996",
"Score": "0",
"body": "haha @TobySpeight always propose hypot function and it is very slow.. other than that thank you"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T10:29:51.747",
"Id": "412997",
"Score": "2",
"body": "It's more correct, but you always have the choice of getting incorrect answers more quickly..."
}
],
"meta_data": {
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T15:26:49.893",
"Id": "213459",
"ParentId": "213456",
"Score": "3"
}
},
{
"body": "<p>For SIMD optimization, I tried doing it with SSE2, as the compilation flags imply SSSE3 is disabled, and SSE3 is not useful here. </p>\n\n<p>It's mostly a transliteration of the scalar code, but there are a few points of interest:</p>\n\n<ul>\n<li>Except the squaring of <code>gx</code> and <code>gy</code> which is done in 32bit, and taking the square root which is done in floating point, most arithmetic is done in 16bit. That shouldn't change the results as everything fits well within the margins.</li>\n<li>16bit is more than 8bit, so basically there is a choice between doing some half-wide loads and stores, or \"doubling\" the code. Often \"doubling\" the code is a little faster because it gets more arithmetic done with the same number of loads and stores, but that didn't pan out this time. So I used the less-common <code>_mm_loadl_epi64</code> and the corresponding store. Note that these notionally take a pointer to <code>__m128i</code>, but they <em>actually</em> just load and store a qword (with no alignment restriction).</li>\n<li><code>_mm_madd_epi16</code> is used for the <code>gx*gx + gy*gy</code> expression, which requires interleaving <code>gx</code> and <code>gy</code>, but is still more convenient than the alternatives.</li>\n<li>There is no good way to conditionally <em>not</em> write a byte somewhere in the middle of a qword store, so for gradients less than 20 I write a zero, which is definitely different than the scalar code (but maybe safer anyway)</li>\n<li>SSE2 has no single instruction to take an absolute value, but SSSE3 does. I didn't use it, but I factored it out so it can easily be updated if SSSE3 support can be assumed someday.</li>\n<li>I paid no particular attention to alignment. The qword loads and stores don't care that much about alignment inherently, but on Core2 it is nevertheless Quite Bad to cross a cache line that way. If Core2 is a serious target, perhaps that aspect can be improved.</li>\n<li>No testing was done other than for performance.</li>\n</ul>\n\n<p>The results on <a href=\"http://quick-bench.com/HqyPJN8LIH2GZ_s0aiVPZlbpEiw\" rel=\"nofollow noreferrer\">quick-bench</a> are OK but not amazing, about an 4x improvement (the final code there is labeled Gradient2). But maybe that's all we can hope for, given that there are square roots to be done. Of course you can still add threading on top of this which should (mostly) stack multiplicatively.</p>\n\n<pre><code>#include <x86intrin.h>\n\n__m128i abs_epi16(__m128i x)\n{\n __m128i m = _mm_srai_epi16(x, 15);\n return _mm_xor_si128(_mm_add_epi16(x, m), m);\n}\n\nvoid Gradient(unsigned char *smoothImg, short *gradImg, unsigned char* dirImg, size_t rows, size_t cols) {\n for (size_t i = 1; i + 1 < rows; i++) {\n size_t j = 1;\n // do blocks of 8 pixels at the time until near the edge\n for (; j + 8 < cols; j += 8) {\n __m128i zero = _mm_setzero_si128();\n // com1\n __m128i img1 = _mm_loadl_epi64((__m128i*)&smoothImg[(i + 1)*cols + j + 1]);\n __m128i img2 = _mm_loadl_epi64((__m128i*)&smoothImg[(i - 1)*cols + j - 1]);\n __m128i img1A = _mm_unpacklo_epi8(img1, zero);\n __m128i img2A = _mm_unpacklo_epi8(img2, zero);\n __m128i com1 = _mm_sub_epi16(img1A, img2A);\n // com2\n __m128i img3 = _mm_loadl_epi64((__m128i*)&smoothImg[(i - 1)*cols + j + 1]);\n __m128i img4 = _mm_loadl_epi64((__m128i*)&smoothImg[(i + 1)*cols + j - 1]);\n __m128i img3A = _mm_unpacklo_epi8(img3, zero);\n __m128i img4A = _mm_unpacklo_epi8(img4, zero);\n __m128i com2 = _mm_sub_epi16(img3A, img4A);\n // gx\n __m128i img5 = _mm_loadl_epi64((__m128i*)&smoothImg[i*cols + j + 1]);\n __m128i img6 = _mm_loadl_epi64((__m128i*)&smoothImg[i*cols + j - 1]);\n __m128i img5A = _mm_unpacklo_epi8(img5, zero);\n __m128i img6A = _mm_unpacklo_epi8(img6, zero);\n __m128i gx = _mm_add_epi16(_mm_add_epi16(com1, com2), _mm_sub_epi16(img5A, img6A));\n // gy\n __m128i img7 = _mm_loadl_epi64((__m128i*)&smoothImg[(i + 1)*cols + j]);\n __m128i img8 = _mm_loadl_epi64((__m128i*)&smoothImg[(i - 1)*cols + j]);\n __m128i img7A = _mm_unpacklo_epi8(img7, zero);\n __m128i img8A = _mm_unpacklo_epi8(img8, zero);\n __m128i gy = _mm_add_epi16(_mm_sub_epi16(com1, com2), _mm_sub_epi16(img7A, img8A));\n // sum\n // gx and gy are interleaved, multiplied by themselves and\n // horizontally added in pairs, creating gx*gx+gy*gy as a dword\n // 32bits is required here to avoid overflow, but also convenient for the next step\n __m128i gxgyL = _mm_unpacklo_epi16(gx, gy);\n __m128i gxgyH = _mm_unpackhi_epi16(gx, gy);\n __m128i lensqL = _mm_madd_epi16(gxgyL, gxgyL);\n __m128i lensqH = _mm_madd_epi16(gxgyH, gxgyH);\n __m128i lenL = _mm_cvttps_epi32(_mm_sqrt_ps(_mm_cvtepi32_ps(lensqL)));\n __m128i lenH = _mm_cvttps_epi32(_mm_sqrt_ps(_mm_cvtepi32_ps(lensqH)));\n __m128i sum = _mm_packs_epi32(lenL, lenH);\n\n // store gradient lengths\n size_t index = i*cols + j;\n _mm_storeu_si128((__m128i*)&gradImg[index], sum);\n\n // classify H/V/low\n __m128i thresholdLow = _mm_set1_epi16(19);\n __m128i markerV = _mm_set1_epi8(1);\n __m128i isSignificant = _mm_cmpgt_epi16(sum, thresholdLow);\n __m128i isHorizontal = _mm_cmplt_epi16(abs_epi16(gx), abs_epi16(gy));\n // if not horizontal, then 1 - 0 = 1\n // if horizontal, then 1 - (-1) = 2\n // if not significant, then make it zero\n __m128i classifier = _mm_and_si128(_mm_sub_epi16(markerV, isHorizontal), isSignificant);\n _mm_storel_epi64((__m128i*)&dirImg[index], _mm_packs_epi16(classifier, classifier));\n }\n for (; j + 1 < cols; j++) {\n int com1 = smoothImg[(i + 1)*cols + j + 1] - smoothImg[(i - 1)*cols + j - 1]; \n int com2 = smoothImg[(i - 1)*cols + j + 1] - smoothImg[(i + 1)*cols + j - 1];\n\n int gx=abs(com1+com2+(smoothImg[i*cols + j + 1] - smoothImg[i*cols + j - 1]));\n int gy=abs(com1-com2+(smoothImg[(i + 1)*cols + j] - smoothImg[(i - 1)*cols + j]));\n\n int sum = (int)sqrt((double)gx*gx + gy*gy);\n\n size_t index = i*cols + j;\n\n gradImg[index] = sum;\n if (sum >= 20) {\n if (gx >= gy) dirImg[index] = 1; //1 vertical\n else dirImg[index] = 2; //2 Horizontal\n }\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:17:33.627",
"Id": "413011",
"Score": "0",
"body": "Thank you for your time.. that's what I'm looking for.. It's faster I just need to test it on real image. I need to learn more about SIMD optimization, it is very useful"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T16:48:11.600",
"Id": "213463",
"ParentId": "213456",
"Score": "4"
}
},
{
"body": "<p>Both Prewitt and Sobel filters are \"separable\".</p>\n\n<p>To calculate the gradients (<code>gx</code> and <code>gy</code>), the original code effectively iterates over and sums a 2d kernel (i.e. <a href=\"https://en.wikipedia.org/wiki/Kernel_(image_processing)#Convolution\" rel=\"nofollow noreferrer\">convolution</a>). For the <a href=\"https://en.wikipedia.org/wiki/Prewitt_operator#Formulation\" rel=\"nofollow noreferrer\">Prewitt</a> and Sobel filters, each gradient kernel can be split into two 1D kernels, <a href=\"http://www.songho.ca/dsp/convolution/convolution2d_separable.html\" rel=\"nofollow noreferrer\">and we can do the calculation of each gradient in two passes</a>. For a <code>k</code> sized filter, this <a href=\"https://dsp.stackexchange.com/questions/36962/why-does-the-separable-filter-reduce-the-cost-of-computing-the-operator\">reduces the work needed at each pixel from <code>k * k</code> to <code>2 * k</code></a>.</p>\n\n<p>This does require some extra memory, but the following is around 4.8x faster.</p>\n\n<pre><code>static void New_Version(benchmark::State& state) {\n\n const int rows = 1000;\n const int cols = 1000;\n const int threshold = 20;\n\n auto to_index = [&] (std::size_t x, std::size_t y)\n {\n return y * cols + x;\n };\n\n unsigned char *smoothImg = new unsigned char[cols*rows];\n short *scratch = new short[cols*rows](); // note: could just use gradImg instead.\n short *gx = new short[cols*rows]();\n short *gy = new short[cols*rows]();\n short *gradImg = new short[cols*rows];\n unsigned char* dirImg = new unsigned char[cols*rows];\n\n const short gxx[3] = { +1, 0, -1 };\n const short gxy[3] = { +1, +1, +1 };\n\n const short gyx[3] = { +1, +1, +1 };\n const short gyy[3] = { +1, 0, -1 };\n\n for (auto _ : state) {\n\n // x gradient: convolve in the x direction first\n for (std::size_t y = 0; y != rows; ++y) // note: need to calculate for the edge pixels too\n for (std::size_t x = 1; x != cols - 1; ++x)\n for (std::size_t o = 0; o != 3; ++o)\n scratch[to_index(x, y)] += smoothImg[to_index(x + o - 1, y)] * gxx[o];\n\n // x gradient: use the results of the first pass and convolve in the y direction\n for (std::size_t y = 1; y != rows - 1; ++y)\n for (std::size_t x = 0; x != cols; ++x)\n for (std::size_t o = 0; o != 3; ++o)\n gx[to_index(x, y)] += scratch[to_index(x, y + o - 1)] * gxy[o];\n\n // y gradient: convolve in the x direction first\n for (std::size_t y = 0; y != rows; ++y)\n for (std::size_t x = 1; x != cols - 1; ++x)\n {\n scratch[to_index(x, y)] = 0;\n for (std::size_t o = 0; o != 3; ++o)\n scratch[to_index(x, y)] += smoothImg[to_index(x + o - 1, y)] * gyx[o];\n }\n\n // y gradient: use the results of the first pass and convolve in the y direction\n for (std::size_t y = 1; y != rows - 1; ++y)\n for (std::size_t x = 0; x != cols; ++x)\n for (std::size_t o = 0; o != 3; ++o)\n gy[to_index(x, y)] += scratch[to_index(x, y + o - 1)] * gyy[o];\n\n // calculate magnitude and direction:\n const unsigned char v = 1;\n const unsigned char h = 2;\n const int t2 = threshold * threshold;\n for (std::size_t i = 0; i != cols * rows; ++i)\n {\n auto const x2 = gx[i] * gx[i];\n auto const y2 = gy[i] * gy[i];\n auto const sqr = x2 + y2;\n dirImg[i] = (sqr >= t2) ? (x2 >= y2) ? v : h : 0;\n gradImg[i] = std::sqrt((double)(sqr));\n }\n }\n}\n// Register the function as a benchmark\nBENCHMARK(New_Version);\n</code></pre>\n\n<p>This could definitely be made neater and more general (e.g. the separable convolution could be abstracted to a separate function taking the image and 2 kernels).</p>\n\n<p>Note that there are also other strategies for dealing with image edges (clamp samples to the edges, mirror, wrap, zero, etc.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T19:15:01.417",
"Id": "213468",
"ParentId": "213456",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "213463",
"CommentCount": "13",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T14:00:16.453",
"Id": "213456",
"Score": "3",
"Tags": [
"c++",
"performance",
"algorithm",
"image"
],
"Title": "Image filter for gradient detection"
} | 213456 |
<p>I had an idea for a <code>__first__</code> special method for a class. It would be run after <code>__new__</code> and before <code>__init__</code> the first time a specific object is instantiated but is not then run if you instantiate the object again. For example, if you run:</p>
<pre><code>class Foo:
def __first__():
print('Inside __first__')
def __init__(self):
print('Inside __init__')
a = Foo()
b = Foo()
</code></pre>
<p>It would return:</p>
<pre><code>Inside __first__
Inside __init__
Inside __init__
</code></pre>
<p>In order to try and create this particular syntax I decided to create a meta class so that you could simply add this syntax to a class of your choice. This was my final code for the meta class and it was the first time I have tried meta class syntax so I was interested in what you thought about my code:</p>
<pre><code>class First(type):
_first = True
def __call__(cls, *args, **kwargs):
if cls._first:
cls._first = False
cls._oldinit = cls.__init__
def init(*args, **kwargs):
cls.__first__()
cls._oldinit(*args, **kwargs)
cls.__init__ = init
cls.__init__.__doc__ = cls._oldinit.__doc__
else:
cls.__init__ = cls._oldinit
return super(First, cls).__call__(*args, **kwargs)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T15:17:13.640",
"Id": "413047",
"Score": "1",
"body": "Would be nice to see this in context rather than an abstract idea - _why_ do you want to do this? Practice with metaclasses, a specific application, etc. ? Should `first` be a class method? Perhaps that's not appropriate but context would be useful here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T15:30:34.317",
"Id": "413052",
"Score": "0",
"body": "@Greedo It is basically just practice of metaclasses but I also thought that this idea could potentially be a useful special method. From the tests I have done I have not specified that `__first__` is a class method but I suppose it could be"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T21:07:48.810",
"Id": "413092",
"Score": "0",
"body": "Have you looked at subclasses? If class D extends B, will B._first interfere with D?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T21:12:51.110",
"Id": "413098",
"Score": "0",
"body": "@AustinHastings Thanks for the suggestion for a way to break it. From what I have seen in the testing I did just now everything works fine with subclasses in that if B has a `__first__` it will be run on the first time of D being run if either B or D has `First` set as its metaclass and then everything else will be normal"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T14:19:27.663",
"Id": "213457",
"Score": "3",
"Tags": [
"python",
"object-oriented",
"python-3.x",
"meta-programming"
],
"Title": "Metaclass to run a __first__ method for the first instantiation of a class"
} | 213457 |
<p>I have a project where, <strong>every time I run it</strong>, I have to: </p>
<ul>
<li>test if some folders exist, and create them if they don't exists.</li>
<li>remove their content if the folders already exist.</li>
</ul>
<p>This is the code that I developed to do this: </p>
<pre><code>import os
import pathlib
def clean_Folders(directory):
folders = ['preprocessed', 'results', 'tmp']
for folder in folders:
if not os.path.exists(os.path.join(directory, folder)):
os.makedirs(os.path.join(directory, folder))
for filepath in pathlib.Path(directory).glob('**/*'):
try:
os.remove(filepath.absolute())
except:
print('something went wrong')
</code></pre>
<p>I had another idea which is creating the folders every time I run my project (without doing the existence test nor caring about what the already contain).<br>
Here is the code: </p>
<pre><code>import os
import shutil
def clean_Folders(directory):
folders = ['preprocessed', 'results', 'tmp']
for folder in folders:
try:
if os.path.exists(os.path.join(directory, folder)):
shutil.rmtree(os.path.join(directory, folder))
os.makedirs(os.path.join(directory, folder))
except:
print('something went wrong')
</code></pre>
<p>Which one of the solutions is more optimized and more professional?<br>
Thank you.</p>
| [] | [
{
"body": "<p>The second one is definitively safer, since in the first one you actually remove everything in all subfolders of <code>directory</code>, not just in the three folders you want to remove.</p>\n\n<p>Some additional comments:</p>\n\n<ul>\n<li>I would save the result of <code>os.path.join(directory, folder)</code> in a variable, you calculate it like three times.</li>\n<li>Have a look at Python's official style-guide, <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP8</a>. It recommends using <code>lower_case</code> both for variables and for function names, so your function should be called <code>clean_folders</code>.</li>\n<li>A bare <code>except</code> is basically never a good idea. And even worse is a bare <code>except</code> with the unhelpful message <code>'something went wrong'</code>. You want to either catch the exception you are looking for and handle it, or let the exception bubble to the top and halt the execution of the program. So, find out what kind of exception you actually want to catch (maybe <code>IOError</code>?). Or at least use <code>except Exception</code>, which excludes exceptions like e.g. the user pressing <kbd>Ctrl</kbd>+<kbd>C</kbd> being caught. </li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T15:37:01.780",
"Id": "412935",
"Score": "0",
"body": "Thank you for the answer and thank you another time for the **very useful** comments!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T15:29:04.783",
"Id": "213460",
"ParentId": "213458",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213460",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T15:04:26.660",
"Id": "213458",
"Score": "1",
"Tags": [
"python",
"performance"
],
"Title": "Creating folders even if already exist or removing removing their content"
} | 213458 |
<p>I am designing a query builder, where the user can just add conditions or groups, and each group can, in turn, have conditions in it. I came up wit the below class design. Can this design be improved?</p>
<pre><code>public enum RuleType
{
Group,
Condition
}
public enum Operator
{
And,
Or
}
public enum ConditonValues
{
GreaterThan = 1,
EqualTo = 2,
LessThan = 3
}
public abstract class RuleParent
{
public Guid Id { get; set; }
public int Order { get; set; }
public RuleType RuleType { get; set; }
}
public class RuleSet : RuleParent
{
public ConditonValues Condition { get; set; }
public string Field { get; set; }
public object Data { get; set; }
}
public class MyGroup : RuleParent
{
public Operator Operator { get; set; }
public List<RuleParent> Rules { get; set; }
public MyGroup()
{
Rules = new List<RuleParent>();
}
}
</code></pre>
<p>Example usage:</p>
<pre><code>var groupM = new MyGroup();
groupM.Rules.AddRange(new List<RuleParent>
{
new RuleSet() { Condition = ConditonValues.EqualTo, Field="name", Data ="reza" , RuleType = RuleType.Condition },
new MyGroup() {
Rules = new List<RuleParent>()
{
new RuleSet() { Condition = ConditonValues.EqualTo, Field="category", Data ="Tools" , RuleType = RuleType.Condition },
new RuleSet() { Condition = ConditonValues.GreaterThan, Field="price", Data ="100" , RuleType = RuleType.Condition }
}
, RuleType = RuleType.Group
}
});
</code></pre>
| [] | [
{
"body": "<p>welcome to code review.</p>\n\n<p>Your organization is clean, I mostly just see a few holes in your logic:</p>\n\n<ul>\n<li><strong>Combining groups</strong> - A group applies the same operator (and, or) to all rules in it. e.g. rule1 AND rule2 AND rule3. However, since groups cannot contain other groups, you cannot combine operations, e.g. rule1 AND (rule2 OR rule3)</li>\n<li><strong>Missing Operator/condition</strong> - you should add NOT to your enum(s) of operators and/or conditions</li>\n<li><strong>Rule Type</strong> - I'm not sure what the purpose of this enum is. If you think that you need it, you could leave it is as, or alternatively make an <code>IRuleParent</code> interface, then make <code>ConditionRuleParent</code> and <code>GroupRuleParent</code> subclasses (this would be the more C#-ish way to model it). By doing it the swcond way, you can declare the type (condition/group) in the class name when you instantiate it, rather than tacking it on as a mandatory argument.</li>\n<li><strong>Clunky syntax</strong> - it's object oriented, but very verbose to use and mentally parse, which leads us to...</li>\n<li><strong><a href=\"https://en.wikipedia.org/wiki/Greenspun's_tenth_rule\" rel=\"nofollow noreferrer\">Greenspun's tenth rule</a></strong> - <em>Any sufficiently complicated C or Fortran program contains an ad-hoc, informally-specified, bug-ridden, slow implementation of half of Common Lisp.</em> (or LINQ in this case). While there are benefits to rolling your own implementation, you are basically recreating a subset of LINQ (the fluent syntax style). If you want something like LINQ, just use LINQ. If you are rolling your own, you might want to spend a little bit of time learning how it works (from a user point of view, at a minimum) and then steal ideas from it as you write your own version. </li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T20:40:05.873",
"Id": "213476",
"ParentId": "213464",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T17:06:20.133",
"Id": "213464",
"Score": "3",
"Tags": [
"c#",
"object-oriented"
],
"Title": "Query builder with OOP design"
} | 213464 |
<p>This is a simple Python script to add <code>@unittest.skipUnless()</code> decorators in a specified format above every function starting with <code>test_</code>. I want to simplify this and try and improve it. It runs extremely quickly and does the job right now, but I'm wondering if this is best practice for modifying Python files. </p>
<p>Do Python developers normally just search for a regex using the IDE's search function, and then modify the search results? Is it a good idea to create a script to modify files if you're going to be repeating a code snippet a lot? How could I improve this code? </p>
<pre><code>import fileinput
import re
import sys
def decorate(file):
'''
Goes through a file and adds @unittest.skipUnless decorators \n
arg file -- the relative path to the file from this root directory, e.g. tests/hardware/test_device
'''
if file is not str:
file = str(file)
pattern = "def test_" # the pattern that defines a test function
template = lambda x: fr'@unittest.skipUnless((not to_test or "{x}" in to_test) and "{x}" not in to_skip, "\n**SKIPPED: {x} test**\n")'
for line in fileinput.input(file, inplace = True):
if pattern in line:
if re.search(fr"{pattern}(\d\d)", line) is not None: # if there are test function numbers (e.g. test_01)
func_name = re.search(r"def test_\d\d_(.*)\(", line).groups()[0]
else: # if there are not test function numbers
func_name = re.search(r"def test_(.*)\(", line).groups()[0]
print(f' {template(func_name)}')
print(line, end="")
print(f"\nThe file {file} has been decorated by unittest.skipUnless decorators")
# get the filepath from the command line, then run decorate() on that file
if len(sys.argv) <= 1:
print("\nERROR: Need one more command line argument (relative path to file)\n")
elif len(sys.argv) > 2:
print("\nERROR: Too many command line arguments, should only be one (relative path to file)\n")
else:
file_in = sys.argv[1]
decorate(file_in)
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T17:19:27.903",
"Id": "213465",
"Score": "1",
"Tags": [
"python",
"python-3.x",
"unit-testing",
"file-system",
"meta-programming"
],
"Title": "Python script to add unittest decorators to source code files"
} | 213465 |
<p>This is my solution to CodingBat problem p150113. My Java knowledge is from 2011 and I'd like to know if this is still the optimal way to approach such a problem. and if my code is clean and understandable.</p>
<blockquote>
<p>We'll say that 2 strings "match" if they are non-empty and their first chars are the same. Loop over and then return the given array of non-empty strings as follows: if a string matches an earlier string in the array, swap the 2 strings in the array. A particular first char can only cause 1 swap, so once a char has caused a swap, its later swaps are disabled. Using a map, this can be solved making just one pass over the array.</p>
</blockquote>
<pre><code>firstSwap(["ab", "ac"]) → ["ac", "ab"]
firstSwap(["ax", "bx", "cx", "cy", "by", "ay", "aaa", "azz"]) → ["ay", "by", "cy", "cx", "bx", "ax", "aaa", "azz"]
firstSwap(["ax", "bx", "ay", "by", "ai", "aj", "bx", "by"]) → ["ay", "by", "ax", "bx", "ai", "aj", "bx", "by"]
public String[] firstSwap(String[] strings) {
HashMap<String,Integer> hashMap = new HashMap<>();
int counter = 0;
int index = 0;
for (String s : strings){
String firstChar = s.substring(0,1);
if(hashMap.containsKey(firstChar)){
// make the switch in the array
if(hashMap.get(firstChar) > -1){
index = hashMap.get(firstChar);
String temp = strings[counter];
strings[counter] = strings[index];
strings[index] = temp;
// make sure it doesn't get swapped again:
hashMap.put(firstChar,-1);
}
} else {
hashMap.put(firstChar,counter);
}
counter = counter + 1;
}
return strings;
}
</code></pre>
| [] | [
{
"body": "<p>Some thoughts:</p>\n\n<p>Use Interfaces when the implementation type does not matter. In your code, the fact that your <code>Map</code> is a <code>HashMap</code> is irrelevant, so prefer the <code>Map</code> interface. </p>\n\n<p><code>-1</code> is a magic number. Use a constant to document what it's doing.</p>\n\n<p>Use whitespace consistently. Just like <code>for</code> statements, <code>if</code> statements should have a blank space between the <code>if</code> and the <code>(</code>. There should also be whitespace before a <code>{</code> and after a <code>,</code> for readability.</p>\n\n<p>Your comments are not contributing enough to offset the visual distraction they provide. </p>\n\n<p>Your map's key is a string of length 1. It should probably be a character. And you definitely shouldn't label it a character in your variable names unless it is one.</p>\n\n<p>Use <code>final</code> on variables which will not be reassigned as a statement of intent.</p>\n\n<p>A <code>for</code> loop would more tightly constrain your indexing variable, which you're confusingly referring to as a <code>counter</code>.</p>\n\n<p>You can use a guard clause to handle the simple case and then <code>continue</code>, rather than having a large nested <code>if</code> statement.</p>\n\n<p>You're looking up <code>firstChar</code> three times. I agree that <code>containsKey</code> is clearer to read than a null check, but there's no reason to duplicate the other call. And you can use another constant to make clear what case you're trying to handle there too.</p>\n\n<p>Note that you're destructively modifying the incoming array. In toy problems that's not a big deal, but if you're writing real code this is a very bad practice. It would be preferable to make a copy of the array and modify that instead.</p>\n\n<p>If you were to apply all these changes, your code might look more like:</p>\n\n<pre><code>private static final Integer ALREADY_SWAPPED = -1;\nprivate static final Integer FIRST_OCCURRENCE = null;\n\npublic String[] firstSwap(final String[] strings) {\n final Map<Character, Integer> map = new HashMap<>();\n final String[] result = Arrays.copyOf(strings, strings.length);\n\n for (int i = 0; i < result.length; i++) {\n final char firstCharacter = result[i].charAt(0);\n final Integer priorIndex = map.get(firstCharacter);\n\n if (priorIndex == FIRST_OCCURRENCE) {\n map.put(firstCharacter, i);\n continue;\n }\n\n if (priorIndex == ALREADY_SWAPPED) {\n continue;\n }\n\n final String temp = result[i];\n result[i] = result[priorIndex];\n result[priorIndex] = temp;\n map.put(firstCharacter, ALREADY_SWAPPED);\n }\n\n return result;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T19:10:47.033",
"Id": "213467",
"ParentId": "213466",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "213467",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T17:45:47.510",
"Id": "213466",
"Score": "3",
"Tags": [
"java"
],
"Title": "Swap Elements in Array if first characters match but only once per first character"
} | 213466 |
<p>This is a Python chat room that I've been working on and it enables to you to chat to other people on the same network through Python.</p>
<h1>Server.py:</h1>
<pre><code>import socket
import sys
s = socket.socket()
host = socket.gethostname()
print(" server will start on host : ", host)
port = 8080
s.bind((host,port))
name = input(str("Please enter your username: "))
print("")
print("Server is waiting for incoming connections")
print("")
s.listen(1)
conn, addr = s.accept()
print("Recieved connection")
print("")
s_name = conn.recv(1024)
s_name = s_name.decode()
print(s_name, "has joined the chat room")
conn.send(name.encode())
while 1:
message = input(str("Please enter your message: "))
conn.send(message.encode())
print("Sent")
print("")
message = conn.recv(1024)
message = message.decode()
print(s_name, ":" ,message)
print("")
</code></pre>
<h1>Client.py:</h1>
<pre><code>import socket
import sys
s = socket.socket()
host = input(str("Please enter the hostname of the server : "))
port = 8080
s.connect((host,port))
name = input(str("Please enter your username : "))
print(" Connected to chat server")
s.send(name.encode())
s_name = s.recv(1024)
s_name = s_name.decode()
print("")
print(s_name, "has joined the chat room ")
while 1:
message = s.recv(1024)
message = message.decode()
print(s_name, ":" ,message)
print("")
message = input(str("Please enter your message: "))
message = message.encode()
s.send(message)
print("Sent")
print("")
</code></pre>
<p>I just wanted suggestions on how I can to improve this chatroom to make it better and faster. All suggestions will be greatly appreciated.</p>
| [] | [
{
"body": "<pre><code>host = input(str(\"Please enter the hostname of the server : \"))\n...\nmessage = input(str(\"Please enter your message: \"))\n</code></pre>\n\n<p>can be changed to simply:</p>\n\n<pre><code>message = input(\"Please enter your message: \")\n...\nhost = input(\"Please enter the hostname of the server : \")\n</code></pre>\n\n<p>since there is no need to cast a string to a string.</p>\n\n<pre><code>while 1:\n</code></pre>\n\n<p>is fine, but is more readable as:</p>\n\n<pre><code>while True:\n</code></pre>\n\n<p>Having print statements like the following:</p>\n\n<pre><code>print(\"\")\n</code></pre>\n\n<p>is redundant. If you want an extra newline after a print statement; Add \"\\n\" to the end of the preceding print statements to remove a function call, and reduce code clutter. E.G:</p>\n\n<pre><code>print(\"Sent\\n\")\n</code></pre>\n\n<p>This is more of a personal preference, but fstring formatting is more readable than the following:</p>\n\n<pre><code>print(s_name, \":\" ,message)\n</code></pre>\n\n<p>should be:</p>\n\n<pre><code>print( f\"{s_name}: {message}\" )\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-20T18:04:14.350",
"Id": "213903",
"ParentId": "213470",
"Score": "2"
}
},
{
"body": "<p>If we send two or more messages from any side at once, another side will receive only a single message at once rather than all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-07-09T07:43:09.877",
"Id": "223790",
"ParentId": "213470",
"Score": "-2"
}
}
] | {
"AcceptedAnswerId": "213903",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T19:39:59.797",
"Id": "213470",
"Score": "6",
"Tags": [
"python",
"python-3.x",
"socket",
"tcp",
"chat"
],
"Title": "Socket chat room in Python"
} | 213470 |
<p>My first program using C. I would appreciate pointers on how to improve the code. I exit just before turns reach 9 and the grid is filled because it causes all sorts of bugs. The computer is random.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Struct with all game state variables.
struct game_data {
int win;
int turn;
int grid[3][3];
}
game= {
0,
1,
{ { 8, 8, 8 },
{ 8, 8, 8 },
{ 8, 8, 8 } }
};
void player_one_move(struct game_data* game)
{
int y_val, x_val;
printf("You are '-1's. Please input co-ordinates in the form 'row column' for the 3x3 grid:\n");
scanf(" %d %d", &y_val, &x_val); //Passes player input to variables x_val and y_val
//Stops illegal moves and places player's position.
if (game->grid[y_val - 1][x_val - 1] == 8) {
game->grid[y_val - 1][x_val - 1] = -1;
printf("\nYour turn:\n\n");
}
else {
player_one_move(game);
}
}
//Player two function.
/*void player_two_move(struct game_data* game)
{
int y_val, x_val;
printf("Please input co-ordinates in the form 'row column' for the 3x3 grid\n");
scanf(" %d %d", &y_val, &x_val);
printf("\nYour turn:\n\n");
game->grid[y_val-1][x_val-1] = 1;
} */
void computer_move(struct game_data* game)
{
int x_val = rand() / (RAND_MAX / 4);
int y_val = rand() / (RAND_MAX / 4);
if (game->grid[y_val][x_val] == 8) {
game->grid[y_val][x_val] = 1;
printf("\nComputer turn:\n\n");
}
else {
computer_move(game);
}
}
void update(struct game_data* game)
{
/*for (int y_val = 0; y_val < 3; y_val++) {
for (int x_val = 0; x_val < 3; x_val++) {
printf("%d ", game->grid[y_val][x_val]);
}
printf("\n");
}
printf("\n");*/
//Displays grid.
printf("%d | %d | %d \n---+---+---\n %d | %d | %d \n---+---+---\n %d | %d | %d \n\n",
game->grid[0][0], game->grid[0][1], game->grid[0][2],
game->grid[1][0], game->grid[1][1], game->grid[1][2],
game->grid[2][0], game->grid[2][1], game->grid[2][2]);
}
void game_event_won(struct game_data* game)
{
int left_diag_sum = 0;
int right_diag_sum = 0;
int col_sum = 0;
int row_sum = 0;
// Counts all columns and rows to find sum
for (int y_val = 0; y_val < 3; y_val++) {
for (int x_val = 0; x_val < 3; x_val++) {
col_sum += game->grid[y_val][x_val];
row_sum += game->grid[x_val][y_val];
if (col_sum == -3 || row_sum == -3) {
game->win = 1;
printf("You have won.\n");
}
if (col_sum == 3 || row_sum == 3) {
game->win = 1;
printf("You have lost.\n");
}
}
}
// Sums diagonals
for (int y_val = 0; y_val < 3; y_val++)
{
left_diag_sum += game->grid[y_val][y_val];
right_diag_sum += game->grid[y_val][2 - y_val];
if (left_diag_sum == -3 || right_diag_sum == -3) {
game->win = 1;
printf("You have won.\n");
}
if (left_diag_sum == 3 || right_diag_sum == 3) {
game->win = 1;
printf("You have lost.\n");
}
}
}
int main(void)
{
//Initialises random number generator.
srand((unsigned)time(0));
while (game.win == 0 && game.turn < 9) {
if (game.turn % 2) {
player_one_move(&game);
game.turn++;
}
else {
//player_two_move(&game); Player two function
computer_move(&game);
game.turn++;
}
update(&game);
game_event_won(&game);
}
return 0;
}
</code></pre>
| [] | [
{
"body": "<p>Before I even looked at your program, I though I'd let the compiler discover any obvious flaws by compiling it with these flags:</p>\n\n<pre><code>gcc -Wall -Wextra -pedantic -O2 noughts-and-crosses.c\n</code></pre>\n\n<p>I expected a few warnings, but there weren't any. This means your code is already free from the worst mistakes. This shows that you have already put some good work into it, and that the code is ready to be inspected by human proofreaders. Very good.</p>\n\n<pre><code>#include <stdio.h>\n#include <stdlib.h>\n#include <time.h>\n</code></pre>\n\n<p>The headers are in alphabetical order. This is good. Since there are only 3 of them I cannot say whether it is coincidence or arranged by your IDE or done by you manually. Anyway, this is how professional programs look. (Except when the headers <em>do need</em> a certain order. Then this order is of course more important than alphabetical.)</p>\n\n<pre><code>// Struct with all game state variables.\n\nstruct game_data {\n int win;\n int turn;\n int grid[3][3];\n}\n</code></pre>\n\n<p>You should remove the empty line between the comment and the beginning of the struct. As it is now, the comment reads like a general remark that applies to all the part below it and not just the struct.</p>\n\n<p>This struct definition is the best place to document which values are valid for the <code>win</code> fields. There are several possible choices:</p>\n\n<ul>\n<li>true, false</li>\n<li>0, 1</li>\n<li>0, 1, 2</li>\n<li>-1, 0, -1</li>\n<li>0, 'o', 'x'</li>\n<li>0, '0', '1'</li>\n<li>0, '1', '2'</li>\n</ul>\n\n<p>It's good style to avoid this possible confusion by commenting the possible values. Especially when you use <code>int</code> as the data type, since that data type is used for almost everything.</p>\n\n<p>For the <code>turn</code> field, I first thought it would mark the player whose turn it is. But that's not what the code says. It's actually the number of turns that have already been played. Therefore I'd expect it to be called <code>turns</code> instead of <code>turn</code>.</p>\n\n<p>The <code>grid</code> field is obvious since it is a 3 by 3 array, which for noughts and crosses can only mean the content of the board. There should be a comment that explains the possible values. Again, there are almost as many possibilities as for the <code>win</code> field.</p>\n\n<pre><code>game= {\n 0,\n 1,\n { { 8, 8, 8 },\n { 8, 8, 8 },\n { 8, 8, 8 } }\n };\n</code></pre>\n\n<p>You surprised me a lot with this part. I first thought about a syntax error, but then I saw that you left out the semicolon after the struct definition. This is unusual since an empty line typically means that the two parts around the empty line are somewhat independent. This is not the case here.</p>\n\n<p>The usual form is to put the semicolon at the end of the struct definition and then repeat the words <code>struct game_data</code>, so that the full variable declaration starts with <code>struct game_data game = {</code>.</p>\n\n<pre><code>void player_one_move(struct game_data* game)\n{\n int y_val, x_val;\n printf(\"You are '-1's. Please input co-ordinates in the form 'row column' for the 3x3 grid:\\n\");\n scanf(\" %d %d\", &y_val, &x_val); //Passes player input to variables x_val and y_val\n\n //Stops illegal moves and places player's position.\n if (game->grid[y_val - 1][x_val - 1] == 8) {\n game->grid[y_val - 1][x_val - 1] = -1;\n printf(\"\\nYour turn:\\n\\n\");\n }\n else {\n player_one_move(game);\n }\n}\n</code></pre>\n\n<p>When the game starts, the empty board is not printed. Therefore there is absolutely no clue that the coordinates are in the range 1..3. It would be far easier if there were some example coordinates written somewhere.</p>\n\n<p>Using 8 for an empty cell is something I don't understand. An 8 does not look like empty at all. A much better choice would be an actual space or at least an underscore or dot.</p>\n\n<p>Also, having -1 for one player and 1 for the other leads to a board layout in which the position of the vertical lines depends on which player plays where. This has nothing to do with the game in reality, where the vertical and horizontal lines are fixed during a game.</p>\n\n<pre><code>void computer_move(struct game_data* game)\n{\n int x_val = rand() / (RAND_MAX / 4);\n int y_val = rand() / (RAND_MAX / 4);\n</code></pre>\n\n<p>This again looks unusual. First, why do you divide by 4 instead of by 3? This gives you random numbers between 0 and 3, therefore it might happen that the computer plays off the board (if the memory right behind the <code>struct game_state</code> just happens to have an 8 stored there).</p>\n\n<p>Second, the usual pattern for generating a random number between 0 and n is to just calculate <code>rand() % n</code>, which in this case is <code>rand() % 3</code>.</p>\n\n<pre><code> if (game->grid[y_val][x_val] == 8) {\n game->grid[y_val][x_val] = 1;\n printf(\"\\nComputer turn:\\n\\n\");\n }\n else {\n computer_move(game);\n }\n}\n\nvoid update(struct game_data* game)\n{\n //Displays grid.\n printf(\"%d | %d | %d \\n---+---+---\\n %d | %d | %d \\n---+---+---\\n %d | %d | %d \\n\\n\",\n game->grid[0][0], game->grid[0][1], game->grid[0][2],\n game->grid[1][0], game->grid[1][1], game->grid[1][2],\n game->grid[2][0], game->grid[2][1], game->grid[2][2]);\n}\n</code></pre>\n\n<p>The above code looks quite nice since it visually tells the reader that it prints the 3x3 board. You could make it even nicer if you'd split the string after each <code>\\n</code>, like this:</p>\n\n<pre><code> printf(\n \"%d | %d | %d \\n\"\n \"---+---+---\\n\"\n \" %d | %d | %d \\n\"\n \"---+---+---\\n\"\n \" %d | %d | %d \\n\"\n \"\\n\",\n game->grid[0][0], game->grid[0][1], game->grid[0][2],\n game->grid[1][0], game->grid[1][1], game->grid[1][2],\n game->grid[2][0], game->grid[2][1], game->grid[2][2]);\n</code></pre>\n\n<p>Now the code looks almost exactly how the board will be printed, which is good.</p>\n\n<pre><code>void game_event_won(struct game_data* game)\n{\n int left_diag_sum = 0;\n int right_diag_sum = 0;\n int col_sum = 0;\n int row_sum = 0;\n\n // Counts all columns and rows to find sum\n for (int y_val = 0; y_val < 3; y_val++) {\n for (int x_val = 0; x_val < 3; x_val++) {\n col_sum += game->grid[y_val][x_val];\n row_sum += game->grid[x_val][y_val];\n if (col_sum == -3 || row_sum == -3) {\n game->win = 1;\n printf(\"You have won.\\n\");\n }\n if (col_sum == 3 || row_sum == 3) {\n game->win = 1;\n printf(\"You have lost.\\n\");\n }\n }\n }\n\n // Sums diagonals\n for (int y_val = 0; y_val < 3; y_val++)\n\n {\n left_diag_sum += game->grid[y_val][y_val];\n right_diag_sum += game->grid[y_val][2 - y_val];\n\n if (left_diag_sum == -3 || right_diag_sum == -3) {\n game->win = 1;\n printf(\"You have won.\\n\");\n }\n if (left_diag_sum == 3 || right_diag_sum == 3) {\n game->win = 1;\n printf(\"You have lost.\\n\");\n }\n }\n}\n</code></pre>\n\n<p>This function is the most important and the most complicated at the same time, which already sounds bad. It is also full of bugs.</p>\n\n<p>For example, it doesn't recognize it when I play at <code>2 1, 2 2, 2 3</code>. That should be a win for me, but it isn't. The reason for this is that you also add each 8 (which means empty) to the sum. Therefore, the only situations in which I can currently win are the horizontal <code>1 1, 1 2, 1 3</code> or the vertical <code>1 1, 2 1, 3 1</code> (but only if the computer and I have also filled the cells at <code>1 2, 1 3, 2 2 and 2 3</code>.</p>\n\n<p>Just counting up to 3 or down to -3 isn't enough. For example, the combination <code>1 3, 2 1, 2 2</code> is not a winning combination, but might be counted as such by your code.</p>\n\n<p>A better approach is to look at each possible combination (3 horizontal, 3 vertical, 2 diagonal) and check for each one separately and independently whether all its cells have the same value and at least one of these cells is not empty.</p>\n\n<p>One time I played against the computer, and to be sure I could not win, I played at <code>1 1, 1 2, 2 1, 2 2</code>. The computer meanwhile got 3 in a row, but nevertheless the game said <code>You have won.</code>, which is wrong.</p>\n\n<p>This function can also print <code>You have won.</code> twice for the same situation (once horizontally or vertically, and once more diagonally). This is another bug.</p>\n\n<pre><code>int main(void)\n{\n //Initialises random number generator.\n srand((unsigned)time(0));\n\n\n while (game.win == 0 && game.turn < 9) {\n if (game.turn % 2) {\n player_one_move(&game);\n game.turn++;\n }\n\n else {\n //player_two_move(&game); Player two function\n computer_move(&game);\n game.turn++;\n }\n update(&game);\n game_event_won(&game);\n }\n\n return 0;\n}\n</code></pre>\n\n<p>There are some more things to how you should structure the code of the game, but the first thing to do is to fix the bugs. After that, you are welcome to post a follow-up question with the fixed code.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T00:56:03.983",
"Id": "213484",
"ParentId": "213479",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213484",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T21:56:49.093",
"Id": "213479",
"Score": "1",
"Tags": [
"beginner",
"c",
"tic-tac-toe"
],
"Title": "Noughts and Crosses"
} | 213479 |
<p>(My code is basically a rewrite of <a href="https://github.com/ababik/Remute" rel="nofollow noreferrer">https://github.com/ababik/Remute</a> so much of the credit goes there)</p>
<p>The idea is to use lambda expression to provide a general <code>With</code> method for immutable objects.</p>
<p>With <code>With</code> you can do:</p>
<pre><code>using With;
public class Employee {
public string EmployeeFirstName { get; }
public string EmployeeLastName { get; }
public Employee(string employeeFirstName, string employeeLastName) {
EmployeeFirstName = employeeFirstName;
EmployeeLastName = employeeLastName;
}
}
public class Department {
public string DepartmentTitle { get; }
public Employee Manager { get; }
public Department() { /* .. */ }
public Department(int manager, string title) { /* .. */ }
public Department(string departmentTitle, Employee manager) {
DepartmentTitle = departmentTitle;
Manager = manager;
}
}
public class Organization {
public string OrganizationName { get; }
public Department DevelopmentDepartment { get; }
public Organization(string organizationName, Department developmentDepartment) {
OrganizationName = organizationName;
DevelopmentDepartment = developmentDepartment;
}
}
var expected = new Organization("Organization", new Department("Development Department", new Employee("John", "Doe")));
var actual = expected.With(x => x.DevelopmentDepartment.Manager.EmployeeFirstName, "Foo");
Console.WriteLine(expected.DevelopmentDepartment.Manager.EmployeeFirstName); // "Doe"
Console.WriteLine(actual.DevelopmentDepartment.Manager.EmployeeFirstName); // "Foo"
Console.WriteLine(Object.ReferenceEquals(expected, actual)); // false
Console.WriteLine(Object.ReferenceEquals(expected.DevelopmentDepartment, actual.DevelopmentDepartment)); // false
Console.WriteLine(Object.ReferenceEquals(expected.DevelopmentDepartment.Manager, actual.DevelopmentDepartment.Manager)); // false
Console.WriteLine(Object.ReferenceEquals(expected.OrganizationName, actual.OrganizationName)); // true
Console.WriteLine(Object.ReferenceEquals(expected.DevelopmentDepartment.DepartmentTitle, expected.DevelopmentDepartment.DepartmentTitle)); // true
var actual1 = expected.With(x => x.DevelopmentDepartment.Manager.EmployeeFirstName, "Foo");
Console.WriteLine(Object.ReferenceEquals(actual, actual1)); // false
</code></pre>
<p><code>With</code> expects any classes in the modified 'path' to have a constructor accepting all properties (with a case insensitive match on property name) and will use that constructor only when necessary to create new objects. There is a lot of caching going on to try an give maximum performance.</p>
<p>The code is quite dense but I still hope to get some inputs on improving it or bug reports !</p>
<pre><code>namespace With {
using ParameterResolver = ValueTuple<PropertyInfo, Func<object, object>>;
internal class WithInternal {
delegate object Activator(params object[] args);
delegate object ResolveInstanceDelegate<T>(T source);
// key: "{sourceType.FullName}|{valueType.FullName}"
// ie: "test.Employee|test.Employee"
// activator: args => new valueType(args[0] as valueCtorParams[0].ParamType, ...) as object
// ie: args => new Employee(args[0] as String, args[1] as String) as Object
// parameterResolvers: [ ValueType(PropertyInfo of sourceTypeProp1, x => (x as sourceType).sourceTypeProp1) as Object), ... ]
// ie: [ ( PropertyInfo of EmployeeFirstName , x => ((x as Employee).EmployeeFirstName) as Object) ),
// ( PropertyInfo of EmployeeLastName , x => ((x as Employee).EmployeeLastName) as Object) ) ]
ImmutableDictionary<string, (Activator activator, ParameterResolver[] parameterResolvers)> ActivationContextCache;
// key: "{sourceType.FullName}|{WithProperty}"
// ie: "test.Organization|DevelopmentDepartment.Manager"
// value: x => WithProperty as Object
// ie: x => x.DevelopmentDepartment.Manager as Object
ImmutableDictionary<string, Delegate> ResolveInstanceExpressionCache;
WithInternal() {
ActivationContextCache = ImmutableDictionary<string, (Activator Activator, ParameterResolver[] ParameterResolvers)>.Empty;
ResolveInstanceExpressionCache = ImmutableDictionary<string, Delegate>.Empty;
}
public readonly static WithInternal Default = new WithInternal();
// Constructs immutable object from any other object.
public TInstance With<TInstance>(object source) {
if (source is null) throw new ArgumentNullException(nameof(source));
return (TInstance)ResolveActivator(source.GetType(), typeof(TInstance), null, source, null);
}
// Contructs immutable object from existing one with changed property specified by lambda expression.
public TInstance With<TInstance, TValue>(TInstance source, Expression<Func<TInstance, TValue>> expression, object target) {
if (source is null) throw new ArgumentNullException(nameof(source));
if (expression is null) throw new ArgumentNullException(nameof(expression));
var sourceParameterExpression = expression.Parameters.Single();
var instanceExpression = expression.Body;
while (instanceExpression != sourceParameterExpression) {
if (!(instanceExpression is MemberExpression memberExpression) || !(memberExpression.Member is PropertyInfo property))
throw new NotSupportedException($"Unable to process expression. Expression: '{instanceExpression}'.");
instanceExpression = memberExpression.Expression;
// create unique cache key, calc same key for x=>x.p and y=>y.p
string key;
try {
var exprStr = instanceExpression.ToString();
key = typeof(TInstance).FullName + '|' + exprStr.Remove(0, exprStr.IndexOf(Type.Delimiter) + 1);
} catch (Exception ex) {
throw new Exception($"Unable to parse expression '{instanceExpression}'.", ex);
}
ResolveInstanceDelegate<TInstance> compiledExpression;
if (ResolveInstanceExpressionCache.TryGetValue(key, out var resolveInstanceDelegate)) {
compiledExpression = (ResolveInstanceDelegate<TInstance>)resolveInstanceDelegate;
} else {
var instanceConvertExpression = Expression.Convert(instanceExpression, typeof(object));
var lambdaExpression = Expression.Lambda<ResolveInstanceDelegate<TInstance>>(instanceConvertExpression, sourceParameterExpression);
compiledExpression = lambdaExpression.Compile();
ResolveInstanceExpressionCache = ResolveInstanceExpressionCache.SetItem(key, compiledExpression);
}
var type = property.DeclaringType;
var instance = compiledExpression.Invoke(source);
target = ResolveActivator(type, type, property, instance, target);
}
return (TInstance)target;
}
object ResolveActivator(Type sourceType, Type valueType, PropertyInfo property, object instance, object target) {
var (activator, parameterResolvers) = GetActivator(sourceType, valueType);
// resolve activator arguments
var arguments = new object[parameterResolvers.Length];
var match = false;
for (var i = 0; i < parameterResolvers.Length; i++) {
var (resolverProperty, resolver) = parameterResolvers[i];
arguments[i] = resolverProperty == property ? target : resolver.Invoke(instance);
if (resolverProperty == property) match = true;
}
if (!match) throw new Exception($"Unable to construct object of type '{property.DeclaringType.Name}'. There is no constructor parameter matching property '{property.Name}'.");
return activator.Invoke(arguments);
}
(Activator activator, ParameterResolver[] parameterResolvers) GetActivator(Type sourceType, Type valueType) {
var key = sourceType.FullName + '|' + valueType.FullName;
if (ActivationContextCache.TryGetValue(key, out var res)) return res;
foreach (var constructor in valueType.GetTypeInfo().DeclaredConstructors) {
var parameters = constructor.GetParameters();
// Get ParameterResolvers
var parameterResolvers = new ParameterResolver[parameters.Length];
{
var properties = sourceType.GetTypeInfo().DeclaredProperties.ToArray();
if (parameters.Length != properties.Length) continue;
var i=0;
foreach (var parameter in parameters) {
var property = properties.Where(x => string.Equals(x.Name, parameter.Name, StringComparison.OrdinalIgnoreCase)).SingleOrDefault();
if (property is null || property.PropertyType != parameter.ParameterType) break;
var parameterExpression = Expression.Parameter(typeof(object));
var parameterConvertExpression = Expression.Convert(parameterExpression, sourceType);
var propertyExpression = Expression.Property(parameterConvertExpression, property);
var propertyConvertExpression = Expression.Convert(propertyExpression, typeof(object));
var lambdaExpression = Expression.Lambda<Func<object, object>>(propertyConvertExpression, parameterExpression);
var compiledExpression = lambdaExpression.Compile();
parameterResolvers[i++] = (property, compiledExpression);
}
if (i < parameters.Length) continue; // this ctor is no good
}
// get target activator
Activator activator;
{
var parameterExpression = Expression.Parameter(typeof(object[]));
var argumentExpressions = new Expression[parameters.Length];
for (var i = 0; i < parameters.Length; i++) {
var arrayExpression = Expression.ArrayIndex(parameterExpression, Expression.Constant(i));
var arrayConvertExpression = Expression.Convert(arrayExpression, parameters[i].ParameterType);
argumentExpressions[i] = arrayConvertExpression;
}
var constructorExpression = Expression.New(constructor, argumentExpressions);
var constructorConvertExpression = Expression.Convert(constructorExpression, typeof(object));
var activatorLambdaExpression = Expression.Lambda<Activator>(constructorConvertExpression, parameterExpression);
activator = activatorLambdaExpression.Compile();
}
res = (activator, parameterResolvers);
ActivationContextCache = ActivationContextCache.SetItem(key, res);
return res;
}
throw new Exception($"Unable to find appropriate Constructor. Type '{sourceType.Name}'.");
}
}
public static class ExtensionMethods {
/// <summary>
/// Contructs immutable object from existing one with changed property specified by lambda expression.
/// </summary>
/// <typeparam name="TInstance">Immutable object type.</typeparam>
/// <typeparam name="TValue">Value to set type.</typeparam>
/// <param name="instance">Original immutable object.</param>
/// <param name="expression">Navigation property specifying what to change.</param>
/// <param name="value">Value to set in the resulting object.</param>
/// <returns></returns>
public static TInstance With<TInstance, TValue>(this TInstance instance, Expression<Func<TInstance, TValue>> expression, TValue value) =>
WithInternal.Default.With(instance, expression, value);
/// <summary>
/// Constructs immutable object from any other object.
/// Helpful cloning immutable object or converting POCO, DTO, anonymous type, dynamic ect.
/// </summary>
/// <typeparam name="TInstance">Immutable object type.</typeparam>
/// <param name="source">Original object.</param>
/// <returns>Configuration to use. Default if not specified.</returns>
public static TInstance With<TInstance>(this object source) =>
WithInternal.Default.With<TInstance>(source);
}
}
</code></pre>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-14T23:05:41.613",
"Id": "213481",
"Score": "1",
"Tags": [
"c#",
"extension-methods",
"immutability",
"expression-trees"
],
"Title": "Extension \"With\" for immutable types"
} | 213481 |
<p>I have written a Windows Forms app that interfaces with a variety of equipment to automate the testing of some gas sensors. The program has four main objects, and sometimes these objects have to call methods or fetch properties from each other; a partial listing of the four relevant classes is below:</p>
<pre><code>// GUI which creates the other class objects and displays their properties
// to the user.
public partial class FormCalibration : Form
{
// Object to represent test equipment.
private Equipment _equipment;
// Object to represent devices under test.
private List<Dut> _duts = new List<Dut>();
// Object to represent tests.
private Test _test;
// When the user clicks a "Start" button, begin testing.
private void buttonStart_Click(object sender, EventArgs e)
{
try
{
// Create object for test equipment.
_equipment = new Equipment(equipmentSettings);
// Initialize the number of DUTs to configure the datalogger for.
_equipment.DutInterface.Channels = new List<bool>(new bool[NumDuts]);
// Create objects for devices under test.
_duts.Clear();
for (uint i = 0; i < NumDuts; i++)
{
Dut dut = new Dut(modelSetting)
{
SetSerialNumber = SetDutSerialNumber,
SetStatus = SetDutStatus,
};
dut.DutInterface = _equipment.DutInterface;
dut.Index = i + 1;
dut.Selected = checkBox.Checked;
dut.Status = DutStatus.Init;
dut.SerialNumber = textBoxSerial.Text;
dut.Message = string.Empty;
_duts.Add(dut);
}
// Create object for the test itself.
_test = new Test(testSetting, _equipment, _duts)
{
Finished = TestFinished,
Update = TestUpdate
};
// Start the test.
_test.Start();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, "Error");
}
}
public void TestFinished()
{
// Reset the form after a test is completed or cancelled
// (omitted for brevity).
}
public void TestUpdate(int percent, string message)
{
// Update the form with the test's status and percent progress.
toolStripProgressBar1.Value = percent;
toolStripStatusLabel1.Text = message;
}
}
public class Test
{
// test equipment object
private Equipment _equipment;
// devices under test
private readonly List<Dut> _duts;
// Report test progress.
public Action<int, string> Update;
// Report test results.
public Action Finished;
public Test(TestSetting settings, Equipment equipment, List<Dut> duts)
{
// Save the reference to the equipment and DUTs objects.
_equipment = equipment;
_duts = duts;
}
public void Start()
{
// Start a new test using a background worker thread
// (omitted for brevity).
}
private void ProgressChanged(object sender, ProgressChangedEventArgs e)
{
// Run action required as test progresses (i.e. update GUI).
Update(e.ProgressPercentage, e.UserState as string);
}
private void RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// If the test was cancelled, update the GUI's status accordingly.
if (e.Cancelled)
{
Update(0, "Test cancelled.");
}
// Run actions required when test is completed (i.e. update GUI).
Finished?.Invoke();
}
// This method handles all the testing of the DUTs. Every time the
// user presses "Start" this is what runs.
private void TestThread(object sender, DoWorkEventArgs e)
{
try
{
// Anything within this do-while structure can be cancelled.
do
{
// Initialize test equipment.
_testThread.ReportProgress(0, "Configuring test equipment...");
_equipment.Open();
if (_testThread.CancellationPending) { break; }
// Initialize DUTs.
_testThread.ReportProgress(0, "Configuring DUT Interface Device...");
foreach (Dut dut in _duts)
{
if (_testThread.CancellationPending) { break; }
dut.Open();
}
// Initialize DUT interface device.
_equipment.DutInterface.Configure();
// Perform test actions (omitted for brevity).
ProcessTest();
} while (false);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ex.GetType().ToString());
}
// Everything between here and the end of the test should be fast
// and highly reliable since it cannot be cancelled.
try
{
// Stop all controllers.
foreach (KeyValuePair<VariableType, IControlDevice> c in _equipment.Controllers)
{
c.Value.SetControlMode(ControlMode.Ambient);
}
// Close DUTs.
foreach (Dut dut in _duts)
{
dut.Close();
}
// Close test equipment.
_testThread.ReportProgress(99, "Closing test equipment...");
_equipment.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message, ex.GetType().ToString());
}
// Update the GUI.
_testThread.ReportProgress(100, "Done.");
MessageBox.Show("Test complete.", "Notice");
// If the operation was cancelled by the user, set the cancel property.
if (_testThread.CancellationPending) { e.Cancel = true; }
}
// This method is a good example of how Equipment and Dut classes are accessed in the Test class.
private void ProcessSamples(double setpoint)
{
// Create an object to hold reference device readings.
Dictionary<VariableType, double> referenceReadings = new Dictionary<VariableType, double>();
// Add reference data to the dictionary.
foreach (VariableType reference in _settings?.References ?? Enumerable.Empty<VariableType>())
{
double value = _equipment.References[reference].Readings[reference];
referenceReadings.Add(reference, value);
}
// Record the data applicable to each DUT.
foreach (Dut dut in _duts)
{
dut.Read(_elapsedTimeStopwatch.Elapsed, setpoint, referenceReadings[VariableType.GasConcentration]);
if (_testThread.CancellationPending) { break; }
}
}
}
// Equipment class doesn't call the other classes, but contains properties
// that represent pieces of equipment, and are accessed by the Test object.
public class Equipment
{
public Dictionary<VariableType, IControlDevice> Controllers;
public Dictionary<VariableType, IReferenceDevice> References;
public IDutInterfaceDevice DutInterface => _datalogger;
public void Open()
{
// Initialize communication to each piece of equipment.
}
public void Read()
{
// Take a reading from each piece of equipment.
}
public void Close()
{
// Terminate communication with each piece of equipment.
}
}
// Dut class doesn't call the other classes, but contains properties that
// represent features of a physical device under test, and are accessed by
// the Test object.
public class Dut
{
// Set DUT status.
public Action<uint, DutStatus> SetStatus;
// Set DUT serial number.
public Action<uint, string> SetSerialNumber;
// Datalogger
public IDutInterfaceDevice DutInterface { get; set; }
// Data collected during a test.
public List<TestResults> Results { get; set; } = new List<TestResults>();
// DUT's fixture position or channel
public uint Index { get; set; }
// true if under test; false if idle
public bool Selected { get; set; }
// DUT status (pass, fail, etc.)
public DutStatus Status { get; set; }
// DUT's unique identification number
public string SerialNumber { get; set; }
// A message to be added to the log
public string Message { get; set; }
public void Open()
{
// If the DUT has been enabled by the user...
if (Selected)
{
// Configure DUT Interface device.
DutInterface.Channels[(int)Index - 1] = Selected;
// Set status to "Found".
Status = DutStatus.Found;
// Update GUI.
SetStatus(Index, Status);
}
}
public void Close()
{
if ((Status == DutStatus.Found) ||
(Status == DutStatus.Fail))
{
// Set status to Pass.
Status = DutStatus.Pass;
// Update GUI.
SetStatus(Index, Status);
// Save test results to csv file.
using (var csv = new CsvWriter(writer))
{
csv.WriteRecords(Results);
}
}
}
public void Read(TimeSpan elapsedTime, double setpoint, double reference)
{
// Only process found or failed DUTs.
if ((Status == DutStatus.Found) ||
(Status == DutStatus.Fail))
{
double reading = 0.0;
reading = DutInterface.Readings[Index];
// Save the result.
Results.Add(new TestResults
{
ElapsedTime = elapsedTime,
Setpoint = setpoint,
Reference = reference,
SensorValue = reading
});
}
}
}
</code></pre>
<p>Instances of the four classes are passed to each other as parameters in the constructors. The <code>Test</code> and <code>Dut</code> classes also have delegates that are assigned to the <code>FormCalibration</code> class in lieu of additional constructor parameters. It all works fine, but I could have chosen to remove the constructor parameters and instead create more delegates. Or remove the delegates in favor of adding more parameters to the constructors.</p>
<p><strong>What strategy would allow these classes to access methods or properties of the other classes and be easiest for a other developers to understand and maintain?</strong></p>
<p>The full project can be found on <a href="https://github.com/SensitTechnologies/TestSuite/tree/master/Sensit.App.Calibration" rel="nofollow noreferrer">GitHub</a>.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T15:03:55.643",
"Id": "445641",
"Score": "0",
"body": "Could you show us how these 4 classes call eachothers methods? I feel a visitor pattern will do the trick here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-17T18:48:40.410",
"Id": "445688",
"Score": "0",
"body": "@dfhwze, I'm at work and would appreciate more time to respond to your request."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-18T21:43:41.457",
"Id": "445864",
"Score": "1",
"body": "I've edited the code listing in an attempt to show some clear examples of how the classes interact. Please let me know if this is not adequate, @dfhwze."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-09-19T04:29:31.363",
"Id": "445890",
"Score": "0",
"body": "Thanks for the effort. It seems reviewable to me now. I'll have a go at it later this week."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T00:12:54.313",
"Id": "213483",
"Score": "3",
"Tags": [
"c#",
"design-patterns"
],
"Title": "Industrial Automation App with tightly integrated classes"
} | 213483 |
<p>Consider the following two Java methods. The first takes a JSON string representing one element, the second representing multiple elements. <code>gson.fromJson()</code> can be called with a <code>Class</code> parameter or a <code>Class[]</code> parameter. The trick is in unifying the method signatures so a caller of <code>creatBean()</code> can call seamlessly with a <code>Class</code> or <code>Class[]</code> parameter. Is there a way these two can be combined?</p>
<pre><code>public <T extends ValidateableBean>T createBean(String json, Class<T> clazz) {
Gson gson = new Gson();
T device = gson.fromJson(json, clazz);
InputValidation inputValidation = new InputValidation();
if (!inputValidation.validate((ValidateableBean) device, "Error during validation")) {
throw new WebApplicationException(Status.BAD_REQUEST);
}
return device;
}
public <T extends ValidateableBean>T[] createBeans(String json, Class<T[]> clazz) {
Gson gson = new Gson();
T[] devices = gson.fromJson(json, clazz);
InputValidation inputValidation = new InputValidation();
for (T device : devices) {
if (!inputValidation.validate((ValidateableBean) device, "Error during validation")) {
throw new WebApplicationException(Status.BAD_REQUEST);
}
}
return devices;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T09:26:50.033",
"Id": "412994",
"Score": "1",
"body": "([Yes and no](https://docs.oracle.com/javase/tutorial/java/javaOO/arguments.html): *Arbitrary Number of Arguments*.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T18:57:26.837",
"Id": "413078",
"Score": "0",
"body": "@greybeard That's an idea. Are you sure there's no better way to overload a construction like this?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T20:55:25.713",
"Id": "413087",
"Score": "0",
"body": "Seeing your question for the first time, I took `Class<T[]> clazz` to be an error and `Class<T>[] clazz` to be intended - foolishly, I think revisiting this. I can't see *varargs* helping here - it just gives a slightly more pleasing syntax for zero to many \"homogeneous\" arguments specified individually. There's more to *creating beans* for one or several elements than `call seamlessly`: you get a variable number of results, too."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T03:04:42.973",
"Id": "213486",
"Score": "0",
"Tags": [
"java",
"json",
"generics",
"template",
"gson"
],
"Title": "Templated JSON parsing methods that work with an element or elements array"
} | 213486 |
<p>Async SelectMany takes an enumeration (length unknown) of tasks, each of which returns another enumeration (length unknown and likely different from one another), and returns results from the second dimension as soon as they are ready. I used the name FoldAsync to make it descriptive, but I'm open to suggestions.</p>
<p>Imagine a task, identified with a number, runs for that many seconds then returns. The 2d array (first # being the time for the first dimension task) of tasks could be </p>
<pre><code>1a : 6 11 16
17 : 33 1b
22 : 3 4 5
</code></pre>
<p>Different ways of nesting <code>Task.WhenAll</code> could result in the main thread iterating through them like so:</p>
<pre><code> Depth first Breadth first
time : task id time : task id
1 : 1a 1 : 1a
7 : 6 17 : 17
12 : 11 22 : 22
17 : 16 23 : 1b
17 : 17 25 : 3
18 : 1b 26 : 4
50 : 33 27 : 5
50 : 22 28 : 6
50 : 3 33 : 11
50 : 4 38 : 16
50 : 5 50 : 33
</code></pre>
<p>Async SelectMany accomplishes:</p>
<pre><code>time : task id
1 : 1a
7 : 6
12 : 11
17 : (16, 17)
17 : (16, 17)
18 : 1b
22 : 22
25 : 3
26 : 4
27 : 5
50 : 33
</code></pre>
<p><code>Task.WhenAny</code> can obtain the same results, but you'd have to maintain a list of both <code>Task<IEnumerable<Task<T>>></code>, and <code>Task<T></code> which you're now casting, and spend <em>O(n^2)</em> iterating through it. It's workable, but I like cool code instead.</p>
<p>The following is my implementation (with 800% too many comments). The /// documentation comments are messy because I couldn't figure out how to display nested generics inside. I tried to manage cancellation and Exceptions in a sane manner. I'm looking for comments, critiques, and hopefully improvements.</p>
<pre><code>using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
using System.Threading.Tasks;
namespace WhereIWork.Utilities.Async
{
/// <summary>
/// A helper class containing the <see cref="FoldAsync{TResult}(IEnumerable{Task{IEnumerable{Task{TResult}}}})"/> extension method that is an async equivalent of <see cref="System.Linq.Enumerable"/>.SelectMany.
/// Also provides an overload taking a <see cref="CancellationToken"/>
/// </summary>
/// <remarks>
/// If the size of your dimensions are known, use <see cref="InterleavingExtensions.Interleaved{TResult}"/> instead.
/// <see cref="FoldAsync{TResult}(IEnumerable{Task{IEnumerable{Task{TResult}}}})"/> blocks, because it cannot know the Count of its results until the all tasks in the first dimension are complete.
/// </remarks>
public static class AsyncEnumerable
{
/// <summary>
/// An asynchronous version of <see cref="System.Linq.Enumerable"/>.SelectMany.
/// Will return results in the order they are completed and not the order from the two-dimensional <see cref="IEnumerable"/>.
/// </summary>
/// <typeparam name="TResult">The type of the expected results.</typeparam>
/// <param name="tasks">The two dimensional <see cref="IEnumerable"/> of <see cref="Task{TResult}"/> that will be folded into one dimension.</param>
/// <returns>An <see cref="IEnumerable{Task}"/> which will block as its results are iterated.</returns>
public static IEnumerable<Task<TResult>> FoldAsync<TResult>(this IEnumerable<Task<IEnumerable<Task<TResult>>>> tasks)
{
return new TaskFolder<TResult>(tasks);
}
/// <summary>
/// An asynchronous version of <see cref="System.Linq.Enumerable"/>.SelectMany.
/// Will return results in the order they are completed and not the order from the two-dimensional <see cref="IEnumerable"/>
/// </summary>
/// <typeparam name="TResult">The type of the expected results.</typeparam>
/// <param name="tasks">The two dimensional <see cref="IEnumerable"/> of <see cref="Task{TResult}"/> that will be folded into one dimension.</param>
/// <param name="token">The cancellation token to be passed into every <see cref="Task"/>&lt;<see cref="IEnumerable"/>&lt;<see cref="Task{TResult}"/>&gt;&gt; and <see cref="Task{TResult}"/>.</param>
/// <returns>An <see cref="IEnumerable{Task}"/> which will block as its results are iterated.</returns>
public static IEnumerable<Task<TResult>> FoldAsync<TResult>(this IEnumerable<Task<IEnumerable<Task<TResult>>>> tasks, CancellationToken token)
{
return new TaskFolder<TResult>(tasks, token);
}
}
/// <summary>
/// Implements <see cref="System.Linq.Enumerable"/>.SelectMany(<see cref="IEnumerable"/>&lt;<see cref="Task"/>&lt;<see cref="IEnumerable"/>&lt;<see cref="Task{TResult}"/>&gt;&gt;&gt;,
/// Func&lt;<see cref="Task"/>&lt;<see cref="IEnumerable"/>&lt;<see cref="Task{TResult}"/>&gt;&gt;,
/// <see cref="IEnumerable"/>&lt;<see cref="Task{TResult}"/>&gt;&gt;)
/// <br/>The advantage of this class is that we process results in the order they are ready, without waiting for tasks that are listed earlier in the initial enumeration.
/// </summary>
/// <remark>
/// The constructors are internal to allow for testing, but this class should not be extended.
/// </remark>
/// <typeparam name="TResult">The common type of the result of all <see cref="Task{TResult}"/> being folded.</typeparam>
// ReSharper disable once InheritdocConsiderUsage
public class TaskFolder<TResult> : IEnumerable<Task<TResult>>, IDisposable
{
/// <summary>
/// The collection to which we will post results as they are ready.
/// The <see cref="IEnumerator{TResult}"/> returned by this class comes from this collection.
/// </summary>
protected readonly BlockingCollection<Task<TResult>> Collection = new BlockingCollection<Task<TResult>>();
protected readonly CancellationToken Token;
/// <summary>
/// The number of active tasks.
/// </summary>
protected int ActiveTasks;
/// <summary>
/// The current state of this <see cref="TaskFolder{TResult}"/>
/// </summary>
protected int CurrentState = InitialState;
protected const int InitialState = 0;
protected const int TasksCompleted = 1;
protected const int EnumerableRequested = 2;
/// <summary>
/// Creates a new TaskFolder and initiates the process of listening for completions.
/// </summary>
/// <param name="twoDimensionalWork">The two dimensional <see cref="IEnumerable"/> of <see cref="Task{TResult}"/> that will be folded into one dimension.</param>
// ReSharper disable once InheritdocConsiderUsage
internal TaskFolder(IEnumerable<Task<IEnumerable<Task<TResult>>>> twoDimensionalWork) : this(twoDimensionalWork, CancellationToken.None)
{
}
/// <summary>
/// Creates a new TaskFolder with a cancellation token, and initiates the process of listening for completions.
/// </summary>
/// <param name="twoDimensionalWork">The two dimensional <see cref="IEnumerable"/> of <see cref="Task{TResult}"/> that will be folded into one dimension.</param>
/// <param name="cancellationToken">The cancellation token to be passed into every <see cref="Task"/>&lt;<see cref="IEnumerable"/>&lt;<see cref="Task{TResult}"/>&gt;&gt; and <see cref="Task{TResult}"/>.</param>
internal TaskFolder(IEnumerable<Task<IEnumerable<Task<TResult>>>> twoDimensionalWork, CancellationToken cancellationToken)
{
// This initial increment represents the need to add the continuation to all first dimension tasks before we complete the BlockingCollection.
Interlocked.Increment(ref ActiveTasks);
cancellationToken.Register(() => AdvanceTaskCompletion(true));
Token = cancellationToken;
foreach (var outerTask in twoDimensionalWork)
{
if (IsCanceled())
{
Console.WriteLine("woah");
return;
}
// Increment first, then any decrementing in OuterContinuation will necessarily not be premature.
Interlocked.Increment(ref ActiveTasks);
// As this is an example of Dynamic Task Parallelism, we do not await the result of ContinueWith
// Because we manage completion using _taskCount, we do not need to track the continuation to guarantee its completion.
// Do not use an overload without the TaskScheduler parameter. http://blog.stephencleary.com/2015/01/a-tour-of-task-part-7-continuations.html
outerTask.ContinueWith(OuterContinuation, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
}
DecrementTaskCounter();
}
/// <summary>
/// Called when a first dimension <see cref="Task"/>&lt;<see cref="IEnumerable"/>&lt;<see cref="Task{TResult}"/>&gt;&gt; is complete.
/// If there was an exception, it will be returned as a <see cref="Task{TResult}"/> in the enumeration.
/// </summary>
/// <remarks>
/// Not async since we have another method of tracking the completion of newly created tasks.
/// </remarks>
/// <param name="task">The first dimension <see cref="Task"/>&lt;<see cref="IEnumerable"/>&lt;<see cref="Task{TResult}"/>&gt;&gt; that has completed.</param>
protected void OuterContinuation(Task<IEnumerable<Task<TResult>>> task)
{
if (IsCanceled())
{
return;
}
// In both the faulted and canceled states, there are no second dimension Task<TResult>, and so we ignore _taskCount.
// If the task has faulted, add an exception to the results.
if (task.IsFaulted)
{
Debug.Assert(task.Exception != null, "If a task if faulted, it should have an exception.");
Debug.Assert(task.Exception.InnerException != null, "It is aggregated, so go 1 deeper");
Collection.Add(Task.FromException<TResult>(task.Exception.InnerException), Token);
DecrementTaskCounter();
return;
}
// If the task was cancelled or threw an exception, add a cancellation to the results. It won't have child tasks to deal with.
if (task.IsCanceled)
{
Collection.Add(Task.FromCanceled<TResult>(Token), Token);
DecrementTaskCounter();
return;
}
// By exclusion, the task has completed and we can safely use the Result without worrying about blocking.
Debug.Assert(task.Status == TaskStatus.RanToCompletion, "The continuation should not be called when the Task is not complete");
try
{
foreach (var innerTask in task.Result)
{
if (IsCanceled())
{
return;
}
// Increment first, then any decrementing in InnerContinuation won't cause _taskCount to go to 0
Interlocked.Increment(ref ActiveTasks);
// As this is an example of Dynamic Task Parallelism, we do not await the result of ContinueWith
// Because we manage completion using _taskCount, we do not need to track the continuation to guarantee its completion.
// Do not use an overload without the TaskScheduler parameter. http://blog.stephencleary.com/2015/01/a-tour-of-task-part-7-continuations.html
innerTask.ContinueWith(InnerContinuation, CancellationToken.None, TaskContinuationOptions.DenyChildAttach, TaskScheduler.Default);
}
}
catch (Exception e)
{
// Any exceptions should be reported to the consumer.
try
{
Collection.Add(Task.FromException<TResult>(e), Token);
}
catch
{
// Ignore, we can't add this exception to the collection, so there's no way to report it to the consumer.
}
}
finally
{
// Decrement at the end, ensuring that all second dimension Task<TResult> have contributed to the counter.
DecrementTaskCounter();
}
}
/// <summary>
/// Called when a result is ready to be added to <see cref="Collection"/> and returned as part of this <see cref="IEnumerable"/>&lt;<see cref="Task{TResult}"/>&gt;
/// </summary>
/// <remarks>
/// Not async since we do not use the result of the <see cref="Task{TResult}"/> and simply return it still wrapped.
/// </remarks>
/// <param name="task">The next result to return to the consumer.</param>
protected void InnerContinuation(Task<TResult> task)
{
if (IsCanceled())
{
return;
}
try
{
Collection.Add(task, Token);
DecrementTaskCounter();
}
catch (OperationCanceledException)
{
// Ignore, we can't add this exception to the collection, so there's no way to report it to the consumer.
}
}
/// <summary>
/// Checks if <see cref="Token"/> has <see cref="CancellationToken.IsCancellationRequested"/> set to true.
/// If so, will call <see cref="AdvanceTaskCompletion"/> to stop processing further results.
/// </summary>
/// <returns>
/// <see cref="Token"/>.IsCancellationRequested
/// </returns>
protected bool IsCanceled()
{
if (!Token.IsCancellationRequested)
{
return false;
}
// Pretend all the tasks are done, no further results will be added.
ActiveTasks = 0;
AdvanceTaskCompletion(true);
return true;
}
/// <summary>
/// Calls <see cref="BlockingCollection{T}.CompleteAdding"/> to tell it we have finished processing <see cref="Task{TResult}"/>.
/// Sets the <see cref="TasksCompleted"/> flag on <see cref="CurrentState"/> to indicate all <see cref="Task{TResult}"/> have been completed.
/// </summary>
protected void AdvanceTaskCompletion(bool fromCancellation = false)
{
// If this has already been run, ignore it.
if ((CurrentState & TasksCompleted) != 0)
{
return;
}
// Completed or Canceled both mean we won't be adding anything new to the collection
// If we're the first to advance to TasksComplete
// ReSharper disable once InvertIf
if (Interlocked.CompareExchange(ref CurrentState, TasksCompleted, InitialState) == InitialState ||
Interlocked.CompareExchange(ref CurrentState, TasksCompleted | EnumerableRequested, EnumerableRequested) == EnumerableRequested)
{
if (fromCancellation)
{
Collection.Add(Task.FromCanceled<TResult>(Token), CancellationToken.None);
}
Collection.CompleteAdding();
}
}
/// <summary>
/// Decrements <see cref="ActiveTasks"/>, and if all the tasks have completed, will advance the internal state.
/// </summary>
protected void DecrementTaskCounter()
{
if (Interlocked.Decrement(ref ActiveTasks) > 0)
{
return;
}
AdvanceTaskCompletion();
}
/// <summary>
/// Returns an <see cref="IEnumerator"/> which will provide <see cref="Task{TResult}"/> in the order they have completed, not the order they were supplied.
/// </summary>
/// <returns>A blocking <see cref="IEnumerator"/>&lt;<see cref="Task{TResult}"/>&gt;.</returns>
// ReSharper disable once InheritdocConsiderUsage
public IEnumerator<Task<TResult>> GetEnumerator()
{
IEnumerable<Task<TResult>> YieldCollectionContents()
{
using (Collection)
{
foreach (var task in Collection.GetConsumingEnumerable())
{
yield return task;
}
}
}
// Allow only one thread to advance into EnumerableRequested
// ReSharper disable once InvertIf
if (Interlocked.CompareExchange(ref CurrentState, EnumerableRequested, InitialState) == InitialState ||
Interlocked.CompareExchange(ref CurrentState, TasksCompleted | EnumerableRequested, TasksCompleted) == TasksCompleted)
{
// GetEnumerator's created IEnumerator will notice the using(collection) and call BlockingCollection.Dispose in it's IEnumerator.Dispose.
// foreach is aware of IEnumerator being IDisposable and will call it.
// https://blogs.msdn.microsoft.com/dancre/2008/03/15/yield-and-usings-your-dispose-may-not-be-called/
return YieldCollectionContents().GetEnumerator();
}
throw new InvalidOperationException("The enumerator has already been fetched. Cannot Enumerate this object twice.");
}
/// <inheritdoc />
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
/// <summary>
/// Dispose of the underlying <see cref="BlockingCollection{T}"/>
/// If <see cref="GetEnumerator"/> has been called, this will do nothing. We rely on the consumer instead.
/// </summary>
// ReSharper disable once InheritdocConsiderUsage
public void Dispose()
{
if ((Interlocked.Exchange(ref CurrentState, EnumerableRequested) & EnumerableRequested) == 0)
{
Collection?.Dispose();
}
}
}
}
</code></pre>
<p>Here is a test case that works</p>
<pre><code>using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using WhereIWork.Utilities.Async;
namespace ConcurrencyTests
{
public class Program
{
private static IEnumerable<Task<IEnumerable<Task<int>>>> TestScenario()
{
return Enumerable.Range(0, 5).Select(async y =>
{
await Task.Delay(y * 100);
return Enumerable.Range(1,5).Select(async z =>
{
await Task.Delay(z * 300);
var value = y*5 + z;
if (value % 7 == 3)
{
throw new Exception("What! " + value);
}
return value;
});
});
}
public static async Task Main()
{
var watch = new Stopwatch();
watch.Start();
foreach (var value in TestScenario().FoldAsync())
{
try
{
var result = await value;
Console.WriteLine(watch.ElapsedMilliseconds + " | " + result);
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
Console.WriteLine(watch.ElapsedMilliseconds);
Console.ReadLine();
}
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T03:29:44.890",
"Id": "412972",
"Score": "0",
"body": "The words Cancellation, cancelled, and cancelling have lost all meaning and are probably spelled a variety of ways with one or two l's. <see cref\"https://en.wikipedia.org/wiki/Semantic_satiation\" />"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T10:33:02.183",
"Id": "412998",
"Score": "2",
"body": "Are you sure this works? I get `The collection has been disposed.` exception when trying to use it. Could you provide some test code?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T15:42:34.467",
"Id": "413053",
"Score": "0",
"body": "I would change your flags enum to not hardcode values, for example, `TaskFetched = 5` should be `TaskFetched = Task | Fetched`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T16:10:32.633",
"Id": "413056",
"Score": "0",
"body": "@t3chb0t Can you please share your test case?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T16:18:36.157",
"Id": "413057",
"Score": "0",
"body": "[This](https://gist.github.com/he-dev/d0a7ff1806eb7b32e98ad35ed1ef7715) is how I tested it in LINQPad - I renamed your method :P."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T16:58:26.550",
"Id": "413067",
"Score": "0",
"body": "I can replicate it without linqpad now. There was a typo/bug hiding it in my test case. I modified the code to fix it. - Fix the bug preventing me from seeing the bug you're talking about - that is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T23:22:06.453",
"Id": "413107",
"Score": "0",
"body": "@t3chb0t I think it's good now... I wrote some unit tests, but won't be adding them here, it's already a huge post."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T03:26:49.820",
"Id": "213489",
"Score": "1",
"Tags": [
"c#",
"asynchronous",
"async-await"
],
"Title": "Async SelectMany implementation"
} | 213489 |
<p>The script parses Bitcoin database (blkXXXXX.dat) files directly from raw binary to txt human readable view. And I think about how to encrease the speed of processing.</p>
<p>Can anyone suggest how to improve the performance? I know that the best way to encrease performance is to write this on C or C++, but what about Python? Also, is this style of programming is good?</p>
<p>Example cut from code (full code avaible <a href="https://github.com/normanvolt/blockchain-parser/blob/3ca052cacd766f7006939c08b4e5b8ee55b6ea7c/blockchain-parser.py" rel="nofollow noreferrer">here</a>):</p>
<pre><code>import os
import hashlib
def reverse(input):
L = len(input)
if (L % 2) != 0:
return None
else:
Res = ''
L = L // 2
for i in range(L):
T = input[i*2] + input[i*2+1]
Res = T + Res
T = ''
return (Res);
f = open('blk01234.dat','rb')
tmpHex = ''
fSize = os.path.getsize(t)
while f.tell() != fSize:
for j in range(4):
b = f.read(1)
b = b.encode('hex').upper()
tmpHex = b + tmpHex
tmpHex = ''
for j in range(4):
b = f.read(1)
b = b.encode('hex').upper()
tmpHex = b + tmpHex
resList.append('Block size = ' + tmpHex)
tmpHex = ''
tmpPos3 = f.tell()
while f.tell() != tmpPos3 + 80:
b = f.read(1)
b = b.encode('hex').upper()
tmpHex = tmpHex + b
tmpHex = tmpHex.decode('hex')
tmpHex = hashlib.new('sha256', tmpHex).digest()
tmpHex = hashlib.new('sha256', tmpHex).digest()
tmpHex = tmpHex.encode('hex')
tmpHex = tmpHex.upper()
tmpHex = reverse(tmpHex)
resList.append('SHA256 hash of the current block hash = ' + tmpHex)
f.seek(tmpPos3,0)
tmpHex = ''
for j in range(4):
b = f.read(1)
b = b.encode('hex').upper()
tmpHex = b + tmpHex
resList.append('Version number = ' + tmpHex)
tmpHex = ''
#.....next part of code
f.close()
f = open('blk01234.txt','w')
for j in resList:
f.write(j + '\n')
f.close()
</code></pre>
| [] | [
{
"body": "<p>Some suggestions:</p>\n\n<ul>\n<li>Every single line should at least be comprehensible on its own. Single letter variables destroy that comprehension, meaning that anyone reading the code needs to read the <em>entire</em> code and mull it over for a while to even understand what it's meant to do. Something like <code>current_byte = file_handle.read(1)</code> is a lot more readable than <code>b = f.read(1)</code>.</li>\n<li>All the top-level code should be in either functions, methods or classes, and the file should have a <code>main</code> function, so that the pieces of this code can be understood and reused.</li>\n<li>Running this through at least one linter such as <code>flake8</code> and <code>pycodestyle</code> will give several tips to produce more pythonic code. For example, <code>return (Res);</code> should be written as <code>return res</code> - no parentheses or semicolon, and <code>snake_case</code> variable names.</li>\n<li>There are several magic values like <code>80</code> and <code>4</code> which are hard to guess the meaning of. They should be pulled out as named variables or constants.</li>\n<li>Instead of closing the file handle explicitly you should use a context manager like <code>with open(…) as file_handle:</code>. This ensures that the file handle will be closed even if there is an exception.</li>\n<li>Rather than checking whether the current position in the file is at the end you should read until reading returns nothing.</li>\n<li>There are assignment operators such as <code>//=</code> which can simplify some of your expressions.</li>\n<li>A helpful exercise for detecting \"hacky\" code is to add <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> to it, and verifying it with <code>mypy</code> using strict settings (like not allowing <code>Any</code>). For example, it looks like the type of <code>b</code> would be <code>Union[byte, str]</code>, which is a code smell - the variable is literally used for two different <em>types of</em> things.</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:17:39.717",
"Id": "413012",
"Score": "0",
"body": "the problem with context manager is that it doesnt play nice with try except finally"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T19:38:29.610",
"Id": "413081",
"Score": "0",
"body": "@PirateApp You'd have to back that assertion up with some hard facts."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T07:14:26.187",
"Id": "213501",
"ParentId": "213494",
"Score": "3"
}
},
{
"body": "<p>You do a lot of manipulation of bytes to construct larger structures, which you then operate on. I'd suggest looking at the standard module <code>struct</code> which can do a lot of this for you in a way that is much easier to grasp.</p>\n\n<p>Also, if you're going to read some bytes and then read them a second time, why not just read them into memory and operate on them twice?</p>\n\n<p>Finally, your output appears to be text. Instead of <code>write()</code> why not use <code>print ()</code>?</p>\n\n<p><strong>Update:</strong></p>\n\n<p>Now that I'm not on a cell phone, let me expand a bit.</p>\n\n<p>First, I'll point you to <a href=\"https://stackoverflow.com/a/1163508/4029014\">this excellent answer</a> to a question on reading 32-bit values on SO. With that as a starting point, here's a function that does the same thing (plus a helper function that gets re-used below):</p>\n\n<pre><code>import struct # Top of file\n\ndef read_buffer(binfile, size):\n \"\"\" Read in size bytes from binfile, or else!\n \"\"\"\n buffer = binfile.read(size)\n\n if buffer is None or len(buffer) != size:\n raise EOFError\n\ndef read_uint32_le(binfile):\n \"\"\" Reads an unsigned 32-bit, little-endian integer value from binfile.\n \"\"\"\n buffer = read_buffer(binfile, 4)\n u32 = struct.unpack('<I', buffer)[0] # unpack always returns tuple\n return u32\n</code></pre>\n\n<p>With this function, I can rewrite some of your code:</p>\n\n<pre><code>while f.tell() != fSize:\n for j in range(4):\n b = f.read(1)\n b = b.encode('hex').upper()\n tmpHex = b + tmpHex\n tmpHex = ''\n for j in range(4):\n b = f.read(1)\n b = b.encode('hex').upper()\n tmpHex = b + tmpHex\n resList.append('Block size = ' + tmpHex)\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>while f.tell() != fSize:\n ignored = read_uint32_le(f)\n blk_size = read_uint32_le(f)\n reslist.append(f\"Block size = {blk_size:08X}\")\n</code></pre>\n\n<p>And the remainder benefits greatly from the fact that there's a <a href=\"https://docs.python.org/3/library/stdtypes.html#bytes.hex\" rel=\"nofollow noreferrer\"><code>bytes.hex()</code></a> method:</p>\n\n<pre><code>tmpHex = ''\ntmpPos3 = f.tell()\nwhile f.tell() != tmpPos3 + 80:\n b = f.read(1)\n b = b.encode('hex').upper()\n tmpHex = tmpHex + b\ntmpHex = tmpHex.decode('hex')\ntmpHex = hashlib.new('sha256', tmpHex).digest()\ntmpHex = hashlib.new('sha256', tmpHex).digest()\ntmpHex = tmpHex.encode('hex')\ntmpHex = tmpHex.upper()\ntmpHex = reverse(tmpHex)\nresList.append('SHA256 hash of the current block hash = ' + tmpHex)\nf.seek(tmpPos3,0)\ntmpHex = ''\nfor j in range(4):\n b = f.read(1)\n b = b.encode('hex').upper()\n tmpHex = b + tmpHex\nresList.append('Version number = ' + tmpHex)\ntmpHex = ''\n</code></pre>\n\n<p>Becomes:</p>\n\n<pre><code>buffer = read_buffer(f, 30)\nhash2 = sha256(sha256(buffer)).hex().upper()\nreslist.append(f\"SHA256 hash of the current block hash = {hash2}\")\nversion = struct.unpack_from('<I', buffer)[0] # returns a tuple\nreslist.append(f\"Version number = {version:08X}\")\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T20:56:15.413",
"Id": "213545",
"ParentId": "213494",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "213545",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T06:04:43.283",
"Id": "213494",
"Score": "4",
"Tags": [
"python",
"performance",
"serialization",
"file-structure",
"cryptocurrency"
],
"Title": "Parsing Bitcoin binary data file with Python"
} | 213494 |
<p>I've created a code that works but takes time to run.</p>
<p>Is there any way of making this code work in a more efficient way?</p>
<p>In short terms I want to:</p>
<ul>
<li><p>make a new copy of sheet 1 and 2</p></li>
<li><p>Select the row with the lowest value in sheet 1</p></li>
<li>Paste this row in sheet 3, and select item-number, rownumber and OP-number from this row</li>
<li><p>Delete copied row in sheet 1</p></li>
<li><p>Select row from sheet 2 with the same item-number, rownumber and that has the LOWEST rownumber</p></li>
<li>Paste this row in sheet 3</li>
<li>Delete copied row in sheet 2</li>
</ul>
<p>Sheet 1 contains 34.000 rows and sheet 2 about 57.000 rows.
This means I'm making a lot of loops in this existing code, and I'm looking for any way to improve this code to work faster.</p>
<p>CODE:</p>
<pre><code>Option Explicit
Sub SpecialCopy()
'~~> 1. Copy sheets to new locations
Dim lr_op As Long, lr_prod As Long, rng_cProd As Range, rng_cOp As Range
'~~> Copy products to new sheet
lr_prod = Sheets("ProdRows_Mo").Cells(Rows.Count, 1).End(xlUp).Row
Set rng_cProd = Sheets("ProdRows_Mo").Range("A27:A" & lr_prod - 27)
rng_cProd.EntireRow.Copy Sheets("ProdRows_Mo_copy").Cells(1, 1).End(xlUp)(1)
'~~> Copy op to new sheet
lr_op = Sheets("OpRows_Mo").Cells(Rows.Count, 1).End(xlUp).Row
Set rng_cOp = Sheets("OpRows_Mo").Range("A27:A" & lr_op - 27)
rng_cOp.EntireRow.Copy Sheets("OpRows_Mo_copy").Cells(1, 1).End(xlUp)(1)
'~~> End 1
'~~> 2. Loop op page for lowest value in "A"
'~~> Count rows in OpRows_copy
Dim rw As Range, rng_fOp As Range, item_mini As Long, item_no As Long, fetch_row As Long, op_no As Long
Dim j As Long, i As Range, vmin As Long, found As Range, item_no_comp As Long, pos_value As Integer, bel_to_op As Long
Do While j < lr_op
With Worksheets("OpRows_Mo_copy")
lr_op = Sheets("OpRows_Mo_copy").Cells(Rows.Count, 1).End(xlUp).Row
Set rng_fOp = Sheets("OpRows_Mo_copy").Range("A1:A" & lr_op)
vmin = Application.WorksheetFunction.Min(rng_fOp)
'MsgBox ("OP " & vmin & "-" & vmin)
Set i = Sheets("OpRows_Mo_copy").Range("A1:A" & lr_op).Find(what:=vmin, LookIn:=xlValues, lookat:=xlWhole)
item_no = .Cells(i.Row, 6).Value
op_no = .Cells(i.Row, 20).Value
fetch_row = i.Row
'Copy the other cells in the row containing the minimum value to the new worksheet.
Sheets("OpRows_Mo_copy").Cells(fetch_row, 1).EntireRow.Copy Sheets("ProdRows_PY").Cells(Rows.Count, 1).End(xlUp).Offset(1)
'Insert pos_value to copied row
If item_no_comp = item_no Then
pos_value = pos_value + 10
Else
pos_value = 10
item_no_comp = item_no
End If
Sheets("ProdRows_PY").Cells(Rows.Count, 5).End(xlUp).Offset(1).Value = pos_value
'Delete the "old" row
Sheets("OpRows_Mo_copy").Rows(fetch_row).Delete
'Set op-no row to
bel_to_op = pos_value
End With
'~~> End 2
'~~> 3. Loop prod page for the lowest value
Dim x As Range, y As Range, c_rows As Integer, row_no As Long, rng_fProd As Range, pos_no As Long, counter As Integer
'~~> Count rows in prodRows_copy
With Worksheets("ProdRows_Mo_copy")
Do
lr_prod = Sheets("ProdRows_Mo_copy").Cells(Rows.Count, 1).End(xlUp).Row
Set rng_fProd = Sheets("ProdRows_Mo_copy").Range("A1:A" & lr_prod)
For Each y In rng_fProd
If item_no = .Cells(y.Row, 7).Value And op_no = .Cells(y.Row, 14).Value Then
If pos_no = 0 Then
row_no = y.Row
pos_no = .Cells(y.Row, 12).Value
ElseIf pos_no > 0 And pos_no > .Cells(y.Row, 12).Value Then
row_no = y.Row
pos_no = .Cells(y.Row, 12).Value
End If
Else
End If
Next y
If pos_no = 0 Then
'endOfProd = True
Exit Do
Else
'Copy the other cells in the row containing the minimum value to the new worksheet.
Sheets("ProdRows_Mo_copy").Cells(row_no, 1).EntireRow.Copy Sheets("ProdRows_PY").Cells(Rows.Count, 1).End(xlUp).Offset(1)
'Insert PY-pos_value to copied row
If item_no_comp = item_no Then
pos_value = pos_value + 10
Else
pos_value = 10
item_no_comp = item_no
End If
Sheets("ProdRows_PY").Cells(Rows.Count, 5).End(xlUp).Offset(1).Value = pos_value
Sheets("ProdRows_PY").Cells(Rows.Count, 5).End(xlUp).Offset(0, -1).Value = bel_to_op
'Delete the "old" row
Sheets("ProdRows_Mo_copy").Rows(row_no).Delete
row_no = 0
pos_no = 0
End If
Loop
End With
lr_op = lr_op - 1
Loop
End Sub
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T19:49:42.427",
"Id": "414625",
"Score": "0",
"body": "The guidelines for how to ask questions on Code Review are a little confusing, but generally speaking, questions should contain more larger picture context of what you use this code for. If you edit your question to follow this convention, you may get more views."
}
] | [
{
"body": "<p>I'm seeing a few things you could do to improve your code. I won't focus just on speed considerations.</p>\n\n<ol>\n<li><p>Explicitly qualify your objects. Don't let Excel make any assumptions about them. Letting Excel make assumptions leads to frustrating, unpredictable, hard to diagnose errors.</p>\n\n<ul>\n<li><strong>Before</strong>: <code>Sheets()</code></li>\n<li><strong>After</strong>: <code>ThisWorkbook.Sheets()</code>.</li>\n</ul></li>\n</ol>\n\n<hr>\n\n<ol start=\"2\">\n<li><p>Use <code>Worksheets()</code> instead of <code>Sheets()</code>, because <code>Sheets()</code> can also refer to <code>ListObjects</code> I believe. This will help you avoid referring to the wrong object.</p>\n\n<ul>\n<li><strong>Before</strong>: <code>.Sheets()</code></li>\n<li><strong>After</strong>: <code>.Worksheets()</code>.</li>\n</ul></li>\n</ol>\n\n<hr>\n\n<ol start=\"3\">\n<li><p>You should use multiple <code>Sub()</code>s to accomplish this purpose. Your existing sub is too long and has too many variables. Using multiple subs will help you more quickly pinpoint errors and ease code reuse.</p>\n\n<ul>\n<li><strong>Before</strong>: Everything in <code>SpecialCopy()</code></li>\n<li><strong>After</strong>: <code>SpecialCopy()</code> broken into multiple pieces, each of which has its own <code>Sub()</code> or <code>Function()</code> with a descriptive name describing what it does. Each <code>Sub()</code> or <code>Function()</code> you create is stored in the same module and you execute those names inside <code>SpecialCopy()</code> to execute those code pieces.</li>\n</ul></li>\n</ol>\n\n<hr>\n\n<ol start=\"4\">\n<li><p>You should use one variable on each line to make your code easier to read. Following the above recommendation to use multiple <code>Sub()</code>s will help you have fewer variables active at a time, decreasing your memory footprint and eliminating the need to put multiple variables on the same line to conserve screen space.</p>\n\n<ul>\n<li><strong>Before</strong>: <code>Dim rw As Range, rng_fOp As Range, item_mini As Long, item_no As Long, fetch_row As Long, op_no As Long</code></li>\n<li><strong>After</strong>: <code>Dim rw As Range</code> as one line with the rest on subsequent lines</li>\n</ul></li>\n</ol>\n\n<hr>\n\n<ol start=\"5\">\n<li><p>If you have worksheets you know ahead of time you want to refer to, give them names in the Project Explorer.</p>\n\n<ul>\n<li><strong>Before</strong>: <code>Sheets(\"ProdRows_Mo\").Range</code></li>\n<li><strong>After</strong>: ProdRows_Mo.Range`</li>\n</ul></li>\n</ol>\n\n<hr>\n\n<ol start=\"6\">\n<li><p>Get rid of <code>.End(xlUp)(1)</code> after <code>.Cells(1,1)</code>. It's not accomplishing anything. </p>\n\n<ul>\n<li><strong>Before</strong>: <code>Sheets(\"OpRows_Mo_copy\").Cells(1, 1).End(xlUp)(1)</code></li>\n<li><strong>After</strong>: <code>Sheets(\"OpRows_Mo_copy\").Cells(1, 1)</code></li>\n</ul></li>\n</ol>\n\n<hr>\n\n<ol start=\"7\">\n<li><p>Indent code inside blocks. After using <code>For</code>, <code>For Each</code>, <code>Do While</code>, <code>With</code>, etc., your next lines shouldn't be spaced with the same left margin.</p>\n\n<ul>\n<li><strong>Before</strong>: <code>Do While j < lr_op</code> / <code>With Worksheets(\"OpRows_Mo_copy\")</code> / <code>lr_op = Sheets(\"OpRows_Mo_copy\").Cells(Rows.Count, 1).End(xlUp).Row</code></li>\n<li><strong>After</strong>: <code>Do While j < lr_op</code> / (indent) <code>With Worksheets(\"OpRows_Mo_copy\")</code> / (2x indent) <code>lr_op = Sheets(\"OpRows_Mo_copy\").Cells(Rows.Count, 1).End(xlUp).Row</code></li>\n</ul></li>\n</ol>\n\n<hr>\n\n<ol start=\"8\">\n<li>Every time you want to cycle through every cell in a range, just read it into an array. Every time you refer to a cell's value on a worksheet via a range object, Excel has to read it from the worksheet, one of the more time-expensive operations it does. Instead, load the range into an array in memory, and you can quickly test every value without having to touch the worksheet. Here, you can use my function:</li>\n</ol>\n\n<hr>\n\n<pre><code>Private Function ConvertRangeToArray(ByVal rngInQuestion As Range) As Variant\n\n Dim arrRangeToArray() As Variant\n With rngInQuestion\n If .Cells.Count = 1 Then\n ReDim arrRangeToArray(1 To 1, 1 To 1)\n arrRangeToArray(1, 1) = .Cells(1, 1).Value\n Else\n arrRangeToArray = .Value\n End If\n End With\n\n ConvertRangeToArray = arrRangeToArray\n\nEnd Function\n</code></pre>\n\n<hr>\n\n<p>This is enough to get you started. Good effort on your code, I look forward to seeing you improve further.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-27T20:47:44.263",
"Id": "214420",
"ParentId": "213495",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T06:18:20.617",
"Id": "213495",
"Score": "1",
"Tags": [
"vba",
"excel"
],
"Title": "Merge info from two sheets info one list"
} | 213495 |
<p>Here is a script that opens about 200 pictures, the first time you open the webpage, loading of the 200 pictures is fast, However if you reopen the page, it takes about 4 minutes to load the same page the second time. Please advise.</p>
<pre><code> session_start();
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Cache-Control: no-store, no-cache, must-revalidate');
header('Cache-Control: post-check=0, pre-check=0', FALSE);
header('Pragma: no-cache');
if(!isset($_SESSION['token']) && (!isset($_SESSION['user']))){
echo "<script language='javascript'>self.close();</script>";
}
require 'db.php';
$upload_id = $_GET['id'];
$client = $_GET['NAME'];
?>
<!DOCTYPE html>
<html>
<head>
<title>Display | <?=$client;?></title>
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="css/w4.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js"></script>
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
</head>
<body>
<?
$myid = $_GET['myd'];
$mydept = $_GET['dept'];
$myrole = $_GET['role'];
?>
<?
//}
// Retrieving Book mark page for this job (upload_id)
$book = ("SELECT * FROM bookmark WHERE user_id = '".$_SESSION['id']."' AND upload_id='".$upload_id."' ");
$bk = mysqli_query($conn, $book) or die ("ERROR bookmark ".mysqli_error($conn));
$bookmark = mysqli_fetch_assoc($bk);
$page = $bookmark['page_book'];
?>
<div class="w3-container">
<center>
</div>
<div class="w3-content w3-display-container">
<?
$s = ("SELECT count(USER_ID) as counter FROM upload_data WHERE UPLOAD_ID='".$upload_id."'");
$r = mysqli_query($conn, $s) or die ("ERROR ".mysqli_error($conn));
$c = mysqli_fetch_assoc($r);
$all = $c['counter'];
$sql = ("SELECT YEAR, FOLDER, USER_ID, FILE_NAME FROM upload_data WHERE UPLOAD_ID='".$upload_id."' ORDER BY USER_ID");
$result = mysqli_query($conn, $sql) or die ("ERROR ".mysqli_error($conn));
while($row = mysqli_fetch_assoc($result)){
$file = $row['FILE_NAME'];
//$all = $row['pages'];
$year = $row['YEAR'];
$folder = $row['FOLDER'];
$id = $row['USER_ID'];
$fileshow = "/unix/upload/$year/$folder/$file";
?>
<div class="w3-display-container myPictures " style="left: -15%; ">
<img src=<? echo $fileshow;?> style="width:130%; height: auto;" data-zoom-image=<? echo $fileshow;?>>
<!--<div class="w3-display-bottomleft w3-large w3-container w3-padding-16 w3-black">
<?echo $id; ?>
</div>-->
</div>
<?
}
?>
<button class="button5" style="position: fixed; width: 100%; left: 20px; top: 140px; height: 40px; width: 100px; border-radius: 2px; background-color: Transparent;" onclick="bookSave(0)">Save</button>&nbsp;
<div id="display" style="position: fixed; width: 100%; left: 30px; top: 372px;" ></div>&nbsp;
<button class="button2" style="position: fixed; width: 100%; left: 20px; top: 505px; height: 40px; width: 100px; border-radius: 2px; background-color: Transparent;;" onclick="plusDivs(-10)">&#10094;&#10094;10-</button>&nbsp;
<font><div id="bookmark" style="position: fixed; width: 100%; left: 20px; top: 190px; height: 60px; width: 100px;"></div></font></center>
<div id="w20" class="clock" style="position: fixed; top: 20px; left: 60%;"></div>
<div class="message" style="position: fixed; top: 20px; left: 50%;"></div>
<button class="button" style="position: fixed; width: 100%; left: 20px; top: 410px; height: 50px; width: 100px; border-radius: 2px;" onclick="plusDivs(-1)">&#10094; 前へ</button>
<button class="button" style="position: fixed; width: 100%; left: 20px; top: 300px; height: 50px; width: 100px; border-radius: 2px;" onclick="plusDivs(1)">次へ &#10095;</button>
<button class="button2" style="position: fixed; width: 100%; left: 20px; top: 215px; height: 40px; width: 100px; border-radius: 2px; background-color: Transparent;" onclick="plusDivs(10)">+10&#10095;&#10095;</button>&nbsp;
</div>
<?$hour = $_GET['t'];?>
<!---------------------------------------- Next | Prev Functions ------------------------------------------------------->
<script>
var slideIndex = 1;
showDivs(slideIndex);
function plusDivs(n) {
showDivs(slideIndex += n);
}
function showDivs(n) {
var i;
var x = document.getElementsByClassName("myPictures");
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("display").innerHTML = this.responseText;
}
};
xhttp.open("POST", "timer5.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("index="+slideIndex+"&name=<?echo $client;?>&upload_id=<?echo $upload_id;?>&total=<?=$all;?>&myid=<?=$myid;?>&dept=<?=$mydept;?>&role=<?=$myrole;?>");
<?if($_SESSION['id']==20000){?>
function clock1(){
var clock;
$(document).ready(function() {
clock = $('.clock').FlipClock({
clockFace: 'MinuteCounter'
});
});
}
var clock;
$(document).ready(function() {
clock = $('.clock').FlipClock(<?=$hour;?>, {
clockFace: 'MinuteCounter',
countdown: true,
callbacks: {
stop: function() {
//$('.message').html('message here');
clock1();
}
}
});
});
<?}?>
}
</script>
<!-- ---------------------------------Save BookMark Functions ---------------------------------------->
<script>
function bookSave(n) {
if(confirm('Save and Close?')){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("bookmark").innerHTML = this.responseText;
}
};
xhttp.open("POST", "booksave.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("index="+slideIndex+"&name=<?echo $client;?>&upload_id=<?echo $upload_id;?>&myid=<?=$myid;?>");
setTimeout("self.close()", 2000 ) // after 5 seconds
}
}
</script>
<!------------------------------------------------------ Call BookMark (PageNumber) when view ------------------------------------------------------------>
<script>
var slideIndex = <?=$page;?>;
showBk(slideIndex);
function bookMark(n) {
showBk(slideIndex += n);
}
function showBk(n) {
var i;
var x = document.getElementsByClassName("myPictures");
if (n > x.length) {slideIndex = 1}
if (n < 1) {slideIndex = x.length}
for (i = 0; i < x.length; i++) {
x[i].style.display = "none";
}
x[slideIndex-1].style.display = "block";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("display").innerHTML = this.responseText;
}
};
xhttp.open("POST", "callbookmark.php", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("index="+slideIndex+"&name=<?echo $client;?>&upload_id=<?echo $upload_id; ?>");
}
</script>
</body>
</html
>
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-19T22:04:29.500",
"Id": "417557",
"Score": "0",
"body": "For reviewers: [this appears to be cross-posted on SO](https://stackoverflow.com/q/54876975/1575353) (originally webmasters SE)"
}
] | [
{
"body": "<p>I'm not sure why the script is slow... One might need to do some debugging to narrow down the timing to individual requests. Because this is the Code Review site, I will provide feedback and offer suggestions below.</p>\n\n<h2>SQL injection</h2>\n\n<p>The code is open to SQL injection, given that the SQL statements are executed with values coming straight from the super global <code>$_GET</code> without any filtering. While it is good that mysqli is used instead of the deprecated mysql library, PDO may be better as it may streamline the execution of statements. But nevertheless, it is recommended that you use bound parameters (e.g. with <a href=\"https://www.php.net/manual/en/mysqli-stmt.bind-param.php\" rel=\"nofollow noreferrer\"><code>bind_param()</code></a>) for the values instead of inserting them straight into the queries.</p>\n\n<h3>Multiple versions of jQuery added</h3>\n\n<p>I see 5 <code><script></code> tags and 4 of them appear to be different versions of jQuery</p>\n\n<blockquote>\n<pre><code><script src=\"https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js\"></script>\n<script src=\"https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.2.1.min.js\"></script>\n<script src=\"https://code.jquery.com/jquery-1.12.4.js\"></script>\n<script src=\"https://code.jquery.com/ui/1.12.1/jquery-ui.js\"></script>\n<script src=\"http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js\"></script>\n</code></pre>\n</blockquote>\n\n<p>You should be able to remove the older versions to reduce loading time/size for users of your page. </p>\n\n<h2>jQuery DOM ready syntax</h2>\n\n<p><code>$(document).ready(function() {</code> can be changed to <code>$(function() {</code> because <a href=\"http://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">the documentation for <code>.ready()</code></a> states:</p>\n\n<blockquote>\n <p>jQuery offers several ways to attach a function that will run when the DOM is ready. All of the following syntaxes are equivalent:</p>\n \n <ul>\n <li><code>$( handler )</code></li>\n <li><code>$( document ).ready( handler )</code></li>\n <li><code>$( \"document\" ).ready( handler )</code></li>\n <li><code>$( \"img\" ).ready( handler )</code></li>\n <li><code>$().ready( handler )</code></li>\n </ul>\n \n <p>As of jQuery 3.0, only the first syntax is recommended; the other syntaxes still work but are deprecated.<sup><a href=\"http://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">1</a></sup></p>\n</blockquote>\n\n<h2>Repeated JS variable</h2>\n\n<p>I see the following line twice:</p>\n\n<blockquote>\n<pre><code>var clock;\n</code></pre>\n</blockquote>\n\n<p>The first one appears to be inside the function <code>clock1</code>, and the second one is outside that function. There isn't much need to re-declare that inside the function.</p>\n\n<h2>JS Selector for clock element</h2>\n\n<p>I see that <code>$('.clock')</code> is used to select the clock element, but there appears to only be one element with that class name:</p>\n\n<blockquote>\n<pre><code> <div id=\"w20\" class=\"clock\" style=\"position: fixed; top: 20px; left: 60%;\"></div>\n</code></pre>\n</blockquote>\n\n<p>You could instead use the id selector for that element: <code>$('#w20;')</code> instead of the class selector... </p>\n\n<h2>code as string passed to setTimeout</h2>\n\n<p>I see this line at the end of the JavaScript function <code>bookSave()</code>:</p>\n\n<blockquote>\n<pre><code> setTimeout(\"self.close()\", 2000 ) // after 5 seconds\n</code></pre>\n</blockquote>\n\n<p>According to <a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout\" rel=\"nofollow noreferrer\">the MDN documentation for <code>setTimeout()</code></a>:</p>\n\n<blockquote>\n <p><strong><code>code</code></strong><br>\n An alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is <strong>not recommended</strong> for the same reasons that make using <a href=\"https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/eval\" rel=\"nofollow noreferrer\"><code>eval()</code></a> a security risk.<sup><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Parameters\" rel=\"nofollow noreferrer\">2</a></sup></p>\n</blockquote>\n\n<p>it would be better to use a function reference, like below:</p>\n\n<pre><code>setTimeout(self.close, 20000 ) //after 5 seconds\n</code></pre>\n\n<p>Notice that the function is not invoked (i.e. the parentheses are not added) when passed as a parameter here, lest it be called when the line is executed.</p>\n\n<p><sup>1</sup><sub><a href=\"http://api.jquery.com/ready/\" rel=\"nofollow noreferrer\">http://api.jquery.com/ready/</a></sub></p>\n\n<p><sup>2</sup><sub><a href=\"https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Parameters\" rel=\"nofollow noreferrer\">https://developer.mozilla.org/en-US/docs/Web/API/WindowOrWorkerGlobalScope/setTimeout#Parameters</a></sub></p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-29T18:59:07.487",
"Id": "216493",
"ParentId": "213496",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T06:31:21.047",
"Id": "213496",
"Score": "1",
"Tags": [
"javascript",
"php",
"jquery",
"cache",
"mysqli"
],
"Title": "When slide show web page is reopen, the web page loading is very slow"
} | 213496 |
<p>This is my take on an image → greyscale converter.</p>
<pre><code>#greyscale.py -- Converts an image file to greyscale
from tkinter.filedialog import askopenfilename, asksaveasfilename
from graphics import *
def displayimage(imagefile):
#Open image to get width and height
image2convert = Image(Point(0, 0), imagefile)
imgwidth = image2convert.getWidth()
imgheight = image2convert.getHeight()
#Set window size to image size and draw image to window
win = GraphWin("Greyscale Converter", imgwidth, imgheight)
image2convert.move(imgwidth/2, imgheight/2)
image2convert.draw(win)
return image2convert, win
def convert(image2convert, win):
width = image2convert.getWidth()
height = image2convert.getHeight()
#For each row of pixels
for pixelx in range(width):
#For each column of pixels
for pixely in range(height):
print("Converted pixel: x:{0} y: {1}".format(pixelx, pixely))
#Get Pixel Colour, calculate greyscale, set Pixel to calculated colour
r, g, b = image2convert.getPixel(pixelx, pixely)
brightness = int(round(0.299 * r + 0.587 * g + 0.114 * b))
image2convert.setPixel(pixelx, pixely, color_rgb(brightness, brightness, brightness))
#See progress for each row
win.update()
return image2convert
def main():
imagefile = askopenfilename(filetypes=[("GIF-Image", ".gif"), ("PPM-Image", ".ppm")])
image2convert, win = displayimage(imagefile)
#convert after click
win.getMouse()
image2convert = convert(image2convert, win)
#save new image
outFile = asksaveasfilename(filetypes=[("GIF-Image", ".gif"), ("PPM-Image", ".ppm")])
newImg = image2convert.save(outFile)
#close file and window after click
win.getMouse()
image2convert.close()
win.close()
main()
</code></pre>
<p>Opinions/Suggestions/Ideas? It is pretty slow, but I don't think that this approach can be much faster.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T08:22:37.870",
"Id": "412990",
"Score": "0",
"body": "Hi Kevin. I'm afraid that Codereview is for suggesting improvements to code that is already working to the best of your knowledge, rather than finding the causes of bugs. It looks to me like you're pretty close though: you have the traceback telling you that it's line 29 that's throwing, and you know the coordinates that cause it to crash because you've printed them out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T08:23:50.423",
"Id": "412991",
"Score": "0",
"body": "If you find and fix the bug, feel free to edit your post with the corrected code so that people can review it."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T10:47:27.763",
"Id": "413001",
"Score": "0",
"body": "I got it to work and edited it :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T12:16:30.920",
"Id": "413027",
"Score": "0",
"body": "Good job. I have requested the question be reopened, and will have a more detailed look later if no-one gets there first."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T13:48:28.427",
"Id": "413035",
"Score": "0",
"body": "In `convert()`, how does `update(win)` work? `win` doesn't seem to be in scope there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T14:50:55.807",
"Id": "413040",
"Score": "0",
"body": "Sorry, seems like i didn't fully update the post to my code. I edited it now."
}
] | [
{
"body": "<p>There are some very good things about this code. </p>\n\n<p>It makes good use of library functionality, which is one of the big strengths of Python. A lot of programmers spend unnecessary amounts of time rewriting things that others have already done, so it's good to see the habit of just using things like <code>askopenfilename</code> as provided. </p>\n\n<p>I also like the use of comments. There are two traps that people fall into with comments: one is not writing any, and the other is writing comments that just say what the code is already saying. A comment like \"Update the window\" before <code>win.update()</code> would be pointless, whereas your comment \"See progress for each row\" explains clearly and concisely what the intention behind that update is. </p>\n\n<p>That said, I am slightly confused by two of your comments. It's almost midnight here and I may be misreading the code, but it looks to me as if the first <code>for</code> loop is going from left to right one column at a time, and the second for loop is going one row at a time. If so, those comments are the wrong way round. It's important to make sure that comments are kept up to date and accurate, or they can mislead the person reading the code (even if it's future you.) </p>\n\n<p>You mention it running quite slowly. Now the general rule is that when something runs slowly, you use a tool called a profiler to work out which bits of the code are taking time. I haven't run one on this code, but in my experience that <code>print</code> line is probably taking a surprising amount of time. We always assume that text is easy for computers, which it kind of is, but if you think about it the computer has to set maybe a couple of thousand pixels to update that text for every one pixel that it's doing the greyscale calculation for. Although it's really useful to have such lines while developing something, it's usually worth taking them out once they have served their purpose. </p>\n\n<p>Finally, I'll rattle through a few python best practices that are generally worth bearing in mind. </p>\n\n<ul>\n<li>Your function <code>displayimage</code> does two jobs. It first loads an image from a file, and then creates a window and puts it on the screen. Now, you have made good use of python's multi-return functionality to let you do that cleanly, but usually best practice is that every function should do one thing and do it well. I would suggest cutting that function in half: one function could take a file name and return an image, and a second function should take an image and set up a window for it.</li>\n<li>Python programmers usually prefer naming things with snake_case for variable names and function names, which means join lowercase words with underscores. That is purely a convention, but sticking to conventions helps to read code more fluently. </li>\n<li>It is generally discouraged to use <code>import *</code>. That is because it is not clear what comes from where. If I want to look at the documentation for, say, <code>Image</code> then I don't know whether to look at the <code>graphics</code> documentation or somewhere else. Even worse, there's a whole bunch of stuff in packages that you're not using, and it can trip you up if you don't realise it's there. For example you could imagine that your <code>graphics</code> module could also have a function called <code>asksaveasfilename</code>. (Ok, probably not that one, but it serves for an example) Then when you call <code>asksaveasfilename</code> you get all sorts of confusion because it could call the wrong one. Even worse, if you update your packages then <code>graphics</code> which didn't have <code>asksaveasfilename</code> before might have it now, and the behaviour of your program changes in entirely unexpected ways. </li>\n</ul>\n\n<p>I hope this is helpful.</p>\n\n<p>Josiah</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-20T06:13:10.070",
"Id": "413640",
"Score": "0",
"body": "You're right about the two comments, i switched them!\n\nAbout the speed, it had the same speed without the printing, it's just the nature of that graphics module. The writer of the book even mentions that's why it's so slow.\n\nSame goes for the import. The writer says to import the module that way, i tried it by just using import graphics but that didn't work. With every other module, i just import the functions I need tho :)\n\nI'll also look into splitting my displayimage function into two functions.\n\nAlso, snake_case is what I'll be using in future programs then!\n\nThank you!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T00:26:02.287",
"Id": "213551",
"ParentId": "213497",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T06:45:36.080",
"Id": "213497",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"image",
"tkinter"
],
"Title": "GIF/PPM to greyscale converter"
} | 213497 |
<p>For an assignment, I am identifying the first quarter of the 2008 recession in the United States. The Excel data I'm using can be downloaded here: <a href="https://github.com/lytemar/Introduction-to-Data-Science-in-Python--University-of-Michigan---Coursera/blob/master/gdplev.xls" rel="nofollow noreferrer">gdplev.xls</a>. How can I improve this pandas code to make it more idiomatic or optimized? </p>
<pre><code>def get_recession_start():
'''Returns the year and quarter of the recession start time as a
string value in a format such as 2005q3'''
GDP_df = pd.read_excel("gdplev.xls",
names=["Quarter", "GDP in 2009 dollars"],
parse_cols = "E,G",
skiprows = 7)
GDP_df = GDP_df.query("Quarter >= '2000q1'")
GDP_df["Growth"] = GDP_df["GDP in 2009 dollars"].pct_change()
GDP_df = GDP_df.reset_index(drop=True)
# recession defined as two consecutive quarters of negative growth
GDP_df["Recession"] = (GDP_df.Growth < 0) & (GDP_df.Growth.shift(-1) < 0)
return GDP_df.iloc[GDP_df["Recession"].idxmax()]["Quarter"]
get_recession_start()
</code></pre>
| [] | [
{
"body": "<p>Your function does too many things: reading Excel file, filtering necessary rows, and calculating the \"recession_start\". My advice is to take the first two out. </p>\n\n<p>Also, supply quarters and GDP as separate objects (<code>pd.Series</code>) to the function instead of the DataFrame. Like this you will remove hardcoded strings from your function, and, what's more important, you will get rid of <code>SettingWithCopyWarning</code> that you should get right now:</p>\n\n<pre><code>df = pd.read_excel('gdplev.xls',\n names=['Quarter', 'GDP in 2009 dollars'],\n usecols='E,G',\n skiprows=7)\nmask = df['Quarter'] >= '2000q1'\nprint(get_recession_start(quarters=df.loc[mask, 'Quarter'],\n gdps=df.loc[mask, 'GDP in 2009 dollars']))\n</code></pre>\n\n<p>Note that I use <code>usecols</code> instead of <code>parse_cols</code> as it is deprecated. Also, I removed <code>df.query</code> in favor of boolean masking and <code>.loc</code>.</p>\n\n<p>Then, the function would look like this:</p>\n\n<pre><code>def get_recession_start(quarters: pd.Series,\n gdps: pd.Series) -> str:\n \"\"\"\n Returns the year and quarter of the recession start time\n as a string value in a format such as 2005q3\n \"\"\"\n growth = gdps.pct_change()\n recession = (growth < 0) & (growth.shift(-1) < 0)\n recession = recession.reset_index(drop=True)\n return quarters.iloc[recession.idxmax()]\n</code></pre>\n\n<p>Here I also used <a href=\"https://www.python.org/dev/peps/pep-0008/#string-quotes\" rel=\"nofollow noreferrer\">triple double quotes</a> for the docstring and <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a>. IMHO, this looks much cleaner. </p>\n\n<p>Probably, it would also make sense to return only the <code>recession.idxmax()</code> index and get corresponding <code>quarters</code> value outside of the function.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T13:01:11.487",
"Id": "213516",
"ParentId": "213500",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "213516",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T07:05:36.150",
"Id": "213500",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"homework",
"pandas"
],
"Title": "Finding recessions in US GDP data using pandas"
} | 213500 |
<p>I'm working with another company in a new application for my company. My job right now is to send on demand to the other company the data that they need, ciphering some of it.</p>
<p>I should point out that the key is not going to be stored in any database.</p>
<p>Here's the code that I wrote, intended to be used in both services.</p>
<pre><code>using System;
using System.IO;
using System.Security.Cryptography;
using System.Text;
namespace RETACrypto
{
public static class CryptoHelper
{
#region Fields
private const int maxIVLength = 16;
private const int maxSaltLength = 32;
private const string password = "lmnKNG6IJVEcsMkaJgnFyZVG0lINDOzv";
#endregion
#region Public Methods
public static string EncryptString(string source)
{
try
{
string result = "";
byte[] resultBytes;
byte[] encriptedSource;
byte[] salt = GetSalt(maxSaltLength);
using (var aes = new AesManaged { Key = GetKey(salt, Encoding.UTF8.GetBytes(password)), Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 })
{
byte[] sourceByteArray = Encoding.UTF8.GetBytes(source);
using (var encryptor = aes.CreateEncryptor(aes.Key, aes.IV))
{
encriptedSource = encryptor.TransformFinalBlock(sourceByteArray, 0, sourceByteArray.Length);
}
resultBytes = new byte[aes.IV.Length + salt.Length + encriptedSource.Length];
Array.Copy(aes.IV, 0, resultBytes, 0, aes.IV.Length);
Array.Copy(encriptedSource, 0, resultBytes, aes.IV.Length, encriptedSource.Length);
Array.Copy(salt, 0, resultBytes, aes.IV.Length + encriptedSource.Length, salt.Length);
}
result = Convert.ToBase64String(resultBytes);
return result;
}
catch (Exception)
{
throw;
}
}
public static string DecryptString(string source)
{
try
{
string result = "";
byte[] sourceByte = Convert.FromBase64String(source);
byte[] resultIV = GetPartOfTheMessage(sourceByte, 0, maxIVLength);
byte[] salt = GetPartOfTheMessage(sourceByte, sourceByte.Length - maxSaltLength, maxSaltLength);
sourceByte = GetPartOfTheMessage(sourceByte, maxIVLength, sourceByte.Length - maxIVLength - maxSaltLength);
byte[] resultByte;
int decryptedByteCount = 0;
using (var aes = new AesManaged { Key = GetKey(salt, Encoding.UTF8.GetBytes(password)), IV = resultIV, Mode = CipherMode.CBC, Padding = PaddingMode.PKCS7 })
{
using (ICryptoTransform AESDecrypt = aes.CreateDecryptor(aes.Key, aes.IV))
{
using (MemoryStream memoryStream = new MemoryStream(sourceByte))
{
using (CryptoStream cs = new CryptoStream(memoryStream, AESDecrypt, CryptoStreamMode.Read))
{
resultByte = new byte[sourceByte.Length];
decryptedByteCount = cs.Read(resultByte, 0, resultByte.Length);
}
}
}
result = Encoding.UTF8.GetString(resultByte);
if (decryptedByteCount < result.Length)
{
result = result.Substring(0, decryptedByteCount);
}
}
return result;
}
catch (Exception)
{
throw;
}
}
#endregion
#region Private Methods
private static byte[] GetSalt(int length)
{
byte[] salt = new byte[length];
using (RNGCryptoServiceProvider random = new RNGCryptoServiceProvider())
{
random.GetNonZeroBytes(salt);
}
return salt;
}
private static byte[] GetKey(byte[] salt, byte[] password)
{
byte[] combine = new byte[salt.Length + password.Length];
byte[] result;
try
{
Array.Copy(salt, combine, salt.Length);
Array.Copy(password, 0, combine, salt.Length, password.Length);
using (SHA256 sha256Hash = SHA256.Create("SHA256"))
{
result = sha256Hash.ComputeHash(combine);
}
}
catch (Exception)
{
throw;
}
return result;
}
private static byte[] GetPartOfTheMessage(byte[] source, int startPoint, int length)
{
byte[] result = new byte[length];
Array.Copy(source, startPoint, result, 0, length);
return result;
}
#endregion
}
}
</code></pre>
<p>Now, my questions:</p>
<ul>
<li>What's the best way of storing <code>maxIVLength</code>, <code>maxSaltLength</code> and;
most importantly, <code>password</code> so there are no magic variables in my
code?</li>
<li>Right now I am storing the IV at the beginning of the message and the
salt at the end. Should I keep it like this or store all at the
beginning or end?</li>
<li>Is my use of <code>RNGCryptoServiceProvider</code> ok or should I make a static
variable so I only construct it once? How do you dispose of it in
that case?</li>
</ul>
<p>There probably are other potential problems or mistakes that I've overlooked, feel free to point them out.</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T10:51:55.193",
"Id": "413002",
"Score": "0",
"body": "Welcome to Code Review! (`problems of mistakes` such as no spelling checker being able to tell *or* should go where `of` stands?)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T10:55:23.027",
"Id": "413003",
"Score": "0",
"body": "@greybeard I guess that's what happens when you use google translate as your main spell checker. Thanks for pointing it out!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T15:46:43.543",
"Id": "413054",
"Score": "0",
"body": "The `try/catch/throw` statements do nothing."
}
] | [
{
"body": "<p>Just to preface this answer: It will be about the crypto-related issues I spotted, not so much about things like code style, idioms, patterns and thelike, because <a href=\"https://crypto.stackexchange.com/users/23623/sejpm\">I know more about that than proper C# style</a>. The points are sorted descending by severity. Oh and I'm already sorry for ignoring your concrete questions...</p>\n\n<hr>\n\n<h2>Rolling your own crypto</h2>\n\n<p>As you may have figured out from this answer barely talking about code quality and being really long, coming up with good cryptographic schemes is <em>hard</em>. Really <em>hard</em>. So as your scenario seems to be \"establish a secure connection with some other party sharing a high-entropy token with me\", I'd suggest you have a look at using <a href=\"https://en.wikipedia.org/wiki/Transport_Layer_Security\" rel=\"nofollow noreferrer\">TLS</a> with one of the <a href=\"https://en.wikipedia.org/wiki/TLS-PSK\" rel=\"nofollow noreferrer\">PSK cipher-suites</a> which takes care of all of the problems mentioned here (and some more).</p>\n\n<p>For example <a href=\"https://www.bouncycastle.org/csharp/\" rel=\"nofollow noreferrer\">BouncyCastle</a> implements these cipher suites.</p>\n\n<h2>Initialization Vector</h2>\n\n<p>Currently the code doesn't set the IV property of the <code>aesManaged</code> class and I couldn't find any documentation saying that a sensible default will be chosen. Thereby I have to assume this will just be a hard-coded value, e.g. all zeroes. This is <em>really</em> bad. This leaks whether two messages share the same prefix for CBC mode!</p>\n\n<p>So if you send <code>AABBCCEF</code> and <code>AABBCDEF</code> an attacker will be able to learn that the messages are equal up to and including <code>AABBC</code> (with 16-byte granularity).</p>\n\n<p>A better approach is to generate this value independently at random for each message. Do not deterministically derive it from the key and / or the message because this will leak whether two messages are equal!</p>\n\n<h2>CBC-Mode</h2>\n\n<p>Currently this code uses the <em>infamous</em> CBC-mode which time and again has lead to attacks in when it was used in TLS. The problem here is that an attacker may modify the message in a malicious way, e.g. to exploit a parser bug or trigger some other reaction without the receiver having a high chance of noticing it before it's too late. The better solution is to use <a href=\"https://blogs.msdn.microsoft.com/shawnfa/2009/03/17/authenticated-symmetric-encryption-in-net/\" rel=\"nofollow noreferrer\"><em>authenticated encryption</em> (like AES-GCM)</a> which will make sure the message is unmodified before handing out the plaintext.</p>\n\n<h2>The <code>password</code></h2>\n\n<p>Currently the <code>password</code> is a magic string, probably intended to be used by both sides. For starters I <em>really</em> hope you didn't intend to use the password posted here in your actual production now that it is forever on the internet.</p>\n\n<p>Next it's usually best-practice to not store credentials (like a password) in a (plain) file or hard-code it into the source, but to put it into an environment variable. This way it can be quickly swapped out and it won't accidently end up in your or a public git repository.</p>\n\n<p>Next it appears that the \"password\" really is just a shared random string already. So why bother with readable characters? Just generate a cryptographically secure 256-bit random value and put its base64 encoded version into an environment variable! This way you can be sure it won't be brute-forced and due to that you can also forego the salt in the key derivation phase and either use it directly or if you also want to use it for other cryptographic applications, use something like HKDF.</p>\n\n<h2>Password-based Key Derivation</h2>\n\n<p>The code uses <code>SHA256(salt||password)</code> as the key. That is a simple salted hash. Assuming the password isn't good this won't protect you from brute-force which will just throw a bunch of GPUs at the problem and arrive at the password at <a href=\"https://medium.com/@iraklis/running-hashcat-v4-0-0-in-amazons-aws-new-p3-16xlarge-instance-e8fab4541e9b\" rel=\"nofollow noreferrer\">a rate of about</a> 8.64TH/USD, that is 8,640,000,000,000 passwords for a single US-Dollar on <a href=\"https://aws.amazon.com/en/ec2/pricing/on-demand/\" rel=\"nofollow noreferrer\">a public cloud service</a>. If the password isn't strong this won't protect you. If it is actually really strong you can forego the salting. If it is in the middle, you should use to a better password-based key derivation, e.g. using <a href=\"https://github.com/P-H-C/phc-winner-argon2\" rel=\"nofollow noreferrer\">Argon2</a>.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T06:25:35.057",
"Id": "413329",
"Score": "0",
"body": "I very much appreciate all your comments and suggestions and will take a look at them ASAP but also I have some clarifications that I probably should have included in the answer:\n_\"Currently the code doesn't set the IV property of the `aesManaged` class\"._\nIn this case I had an `aes.GenerateIV()` line but debugging I realized that the IV also initialized when constructing `AesManaged` so I did some test and thought that line was redundant."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T06:25:48.583",
"Id": "413330",
"Score": "0",
"body": "I had to make two comments because my answer was too long.\n_\"Currently the `password` is a magic string\". \"For starters I really hope you didn't intend to use the password posted here in your actual production\"._\nRight now that `password` is for testing purposes and I'm changing it every week until I find the best way of making and storing passwords for this case."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T19:51:38.220",
"Id": "213538",
"ParentId": "213504",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "213538",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T09:58:49.420",
"Id": "213504",
"Score": "1",
"Tags": [
"c#",
"cryptography",
"aes"
],
"Title": "Encrypt data to be send from service to service"
} | 213504 |
<p>We want to create an application for the analysis of the order history at an online store. Each order is made by a customer and concerns the purchase of one or more items. Orders are stored in <code>OR</code>, an array of integers having 4 columns. The generic line <code>OR[i] = [o, a, q, p]</code> denotes the fact that in the order with code "o" a quantity "q" of the article with code "a" is required, sold at a unit price equal to "p" (for which obviously the total price paid for the item a in the order "o" is equal to "p * q"). An order has as many rows in <code>OR</code> as there are different items contained in the order.</p>
<p>I must write a function "<em>ordine_min(OR)</em>" which returns the order code with the minimum total price. In case of a tie, any of the orders with the minimum total price must be returned.</p>
<pre><code>def ordine_min(OR):
ret = []
for i in range(len(OR)):
if prezzo(OR,i):
ret.append((prezzo(OR, i),i))
return min(ret)
def prezzo(OR, i):
prezzo_tot = 0
for k in range(len(OR)):
if OR[k][0] == i:
prezzo_tot += OR[k][2] * OR[k][3]
return prezzo_tot
</code></pre>
<p>The matrix is here:</p>
<pre><code>OR = [[1,1,2,2],
[1,2,3,2],
[2,1,1,2],
[2,4,1,3],
[3,3,2,1],
[3,4,2,1],
[4,4,1,7],
[4,5,2,1],
[5,1,2,4],
[5,5,1,4],
[6,1,2,1],
[6,2,1,3]]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T10:37:22.393",
"Id": "412999",
"Score": "0",
"body": "take a look at [`pandas`](http://pandas.pydata.org/), which lets you easily handle data with labels"
}
] | [
{
"body": "<ol>\n<li><p>Write code in English</p>\n\n<p>English should be the preferred language to write code in.</p>\n\n<p>It makes it easier for other people (for instance on this site) to understand what the code is doing.</p></li>\n<li><p>Python comes with batteries included</p>\n\n<p>This means whenever possible make use of the modules that are in the standard library, in this case you could make use of the <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>groupby</code> function from the itertools package</a></p>\n\n<p>This function just groups data together with whatever <code>key</code> you supply</p></li>\n<li><p>Use list comprehension when possible</p>\n\n<p>This is not only considered Pythonic, it should also be a bit faster</p></li>\n</ol>\n\n<h1>Revised code</h1>\n\n<pre><code>from itertools import groupby\nimport doctest\n\ndef minimum_order(orders):\n \"\"\"\n This will return *any* order with a minimum total price based on a list of orders\n Where each order consists of [code, _ quauntity, price]\n\n Returns a tuple with (total price, code)\n\n >>> minimum_order([[1,1,2,2],[1,2,3,2]])\n (10, 1)\n \"\"\"\n return min(\n (\n (sum(x[2] * x[3] for x in g), k)\n for k, g in groupby(\n orders, \n lambda x : x[0]\n )\n ), key=lambda x: x[0]\n )\n\nif __name__ == '__main__':\n doctest.testmod()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T20:43:32.720",
"Id": "413086",
"Score": "0",
"body": "0, 2, and 3 are magic numbers. And don't forget `itemgetter`"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T13:10:07.113",
"Id": "213517",
"ParentId": "213506",
"Score": "0"
}
},
{
"body": "<p>Your <code>prezzo()</code> function is very inefficient: for every line, you scan every line in <code>OR</code> to for a matching <code>o</code>, which makes your algorithm O(<em>n</em><sup>2</sup>). To make it worse, you call it from twice from <code>ordine_min()</code>, doubling the work! Ideally, the calculations should be done in one single pass through <code>OR</code>.</p>\n\n<p>Your code is also very hard to read and understand, due to cryptic naming — <code>OR</code>, <code>i</code>, <code>OR[k][2] * OR[k][3]</code>. Using destructuring assignments can help improve readability.</p>\n\n<pre><code>from collections import Counter\n\ndef ordine_min(ordini):\n prezzi_neg = Counter()\n for ordine, articolo, quantità, prezzo in ordini:\n # The Counter can efficiently find the maximum total. We calculate\n # negative prices to trick it into finding the minimum instead.\n prezzi_neg[ordine] -= quantità * prezzo\n for ordine, prezzi_neg in prezzi_neg.most_common(1):\n return -prezzi_neg, ordine\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T09:10:10.387",
"Id": "213645",
"ParentId": "213506",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T10:20:37.830",
"Id": "213506",
"Score": "1",
"Tags": [
"python"
],
"Title": "Find an order with the minimum total price"
} | 213506 |
<p>I've been implementing a MySQL client with the later purpose of automating monthly reports.
At the moment, I've got two distinct use cases: Executing a query and printing the results in files. The results are the data queried and some stats about the execution (start time, end time, duration, ...).</p>
<p>My problem is that I must set up the same context for three different tests. The result (Is the data correctly queried ?), the report (Is the execution well informed ?) and the export (Is the data correctly exported into a csv file ?).</p>
<p>I've tried to set up the context using a fixture but the mocks don't work anymore.
I'm wondering if I'm not facing a code smell. I see two solutions: Mocking the object data and then calling the tested method on this mock (how ?) or structuring my code differently, using a writer class that take an instance of my class as input, which I would easily mock.</p>
<p>I must add that this class has a constructor with a single parameter (the path to a file containing a SQL query) and all other attributes are derived.</p>
<pre><code>import re
from datetime import datetime
from string import Template
from shutil import copyfile
import csv
from os import path
from cursor_provider import CursorProvider
REPORT_TEMPLATE = '''
-- START TIME: {start}
-- END TIME: {end}
-- DURATION: {duration}
-- ROWS COUNT: {count}
-- RESULT FILE: {file}
'''
class Query:
def __init__(self, source, template_vars=None):
self.source = source
self.dir = path.dirname(source)
self.basename = path.basename(source)
self.raw_name, self.ext = path.splitext(self.basename)
self.template_vars = template_vars if template_vars is not None else dict()
self.__interpolated = None
self.__query_str = None
self.__result = None
self.__report = None
self.__export = None
@property
def interpolated(self):
if self.__interpolated is not None:
return self.__interpolated
else:
template = Template(open(self.source).read())
interpolated = template.safe_substitute(**self.template_vars)
unprovided_filtered = re.sub('\n.*\\${\\w+}.*\n', '\n', interpolated)
self.__interpolated = unprovided_filtered
return self.__interpolated
@property
def query_str(self):
if self.__query_str is not None:
return self.__query_str
else:
self.__query_str = ' '.join([
normalize_space(strip_inline_comment(line).strip())
for line in self.interpolated.split('\n')
if not is_comment(line) and not is_blank(line)
])
return self.__query_str
@property
def result(self):
if self.__result is not None:
return self.__result
else:
self.__result = Result(self.query_str)
return self.__result
@property
def report(self):
if self.__report is not None:
return self.__report
else:
prefix = self.result.execution_start.strftime("%Y-%m-%dT%H-%M-%S_")
report_path = path.join(self.dir, prefix + self.basename)
copyfile(self.source, report_path)
with open(report_path, 'a') as executed_file:
executed_file.write(REPORT_TEMPLATE.format(
start=self.result.execution_start.isoformat(),
end=self.result.execution_end.isoformat(),
duration=self.result.duration,
count=len(self.result.rows),
file=path.basename(self.export)
))
self.__report = report_path
return report_path
@property
def export(self):
if self.__export is not None:
return self.__export
elif len(self.result.rows) == 0:
return None
else:
prefix = self.result.execution_start.strftime("%Y-%m-%dT%H-%M-%S_")
export_path = path.join(self.dir, prefix + self.raw_name + '.csv')
with open(export_path, 'w') as export_file:
csv_writer = csv.writer(export_file, quoting=csv.QUOTE_ALL)
csv_writer.writerow(self.result.description)
for row in self.result.rows:
csv_writer.writerow(row)
self.__export = export_path
return export_path
def normalize_space(line):
return re.sub(' +', ' ', line)
def strip_inline_comment(line):
return re.sub('(--|#).*', '', line)
def is_blank(line):
return not line.strip()
def is_comment(line):
return line.strip().startswith('--') or line.strip().startswith('#')
class Result:
def __init__(self, query_str):
cursor = CursorProvider.cursor()
self.execution_start = datetime.now()
cursor.execute(query_str)
self.execution_end = datetime.now()
self.duration = self.execution_end - self.execution_start
self.rows = cursor.fetchall()
self.description = tuple(column[0] for column in cursor.description)
</code></pre>
<p>Here is the code with the same context being constructed three times.</p>
<pre><code>from datetime import datetime, timedelta
import mock
import os.path
import query
def test_query_str():
tested_query = query.Query('tests/assets/sample-query.sql')
assert tested_query.query_str == "SELECT name, title FROM person LEFT JOIN job " \
"ON person.job_id = job.id WHERE title NOT IN ('developer');"
def test_template_query_str():
tested_query = query.Query('tests/assets/sample-template-query.sql',
template_vars=dict(job='developer', disappear='', donotexist=''))
assert tested_query.query_str == "SELECT '{', '$jobs}', name, title FROM person LEFT JOIN job " \
"ON person.job_id = job.id WHERE title IN ('developer') ;"
@mock.patch('query.CursorProvider')
@mock.patch('query.datetime')
def test_result(mock_datetime, mock_cp):
mock_datetime.now.side_effect = (datetime(1992, 3, 4, 11, 0, 5, 654321),
datetime(1992, 3, 4, 11, 0, 5, 987654))
mock_cursor = mock.Mock()
mock_cp.cursor.return_value = mock_cursor
mock_cursor.fetchall.return_value = [
('Adrien Horgnies', 'analyst developer'),
('Constance de Lannoy', 'secretary')
]
mock_cursor.description = (('name',), ('title',))
actual = query.Query('tests/assets/sample-query.sql').result
assert actual.execution_start == datetime(1992, 3, 4, 11, 0, 5, 654321)
assert actual.execution_end == datetime(1992, 3, 4, 11, 0, 5, 987654)
assert actual.duration == timedelta(microseconds=333333)
assert actual.rows == mock_cursor.fetchall.return_value
assert actual.description == ('name', 'title')
@mock.patch('query.CursorProvider')
@mock.patch('query.datetime')
def test_report(mock_datetime, mock_cp, query_path, executed_query_path):
mock_datetime.now.side_effect = (datetime(1992, 3, 4, 11, 0, 5, 654321),
datetime(1992, 3, 4, 11, 0, 5, 987654))
mock_cursor = mock.Mock()
mock_cp.cursor.return_value = mock_cursor
mock_cursor.fetchall.return_value = [
('Adrien Horgnies', 'analyst developer'),
('Constance de Lannoy', 'secretary')
]
mock_cursor.description = (('name',), ('title',))
tested_query = query.Query(query_path)
assert os.path.basename(tested_query.report) == '1992-03-04T11-00-05_query.sql'
assert os.path.isfile(tested_query.report)
assert [line for line in open(tested_query.report)] == [line for line in open(executed_query_path)]
@mock.patch('query.CursorProvider')
@mock.patch('query.datetime')
def test_export(mock_datetime, mock_cp, query_path, executed_export_path):
mock_datetime.now.side_effect = (datetime(1992, 3, 4, 11, 0, 5, 654321),
datetime(1992, 3, 4, 11, 0, 5, 987654))
mock_cursor = mock.Mock()
mock_cp.cursor.return_value = mock_cursor
mock_cursor.fetchall.return_value = [
('Adrien Horgnies', 'analyst developer'),
('Constance de Lannoy', 'secretary')
]
mock_cursor.description = (('name',), ('title',))
tested_query = query.Query(query_path)
assert os.path.basename(tested_query.export) == '1992-03-04T11-00-05_query.csv'
assert os.path.isfile(tested_query.export)
assert [line for line in open(tested_query.export)] == [line for line in open(executed_export_path)]
</code></pre>
<p>In case you need context, <a href="https://github.com/AdrienHorgnies/py-mysql-tracer/tree/6a911e5c3815669d20d474ed306f3841a9d82bcc" rel="nofollow noreferrer">here is the repository</a></p>
<p><strong>My question is, would you test it differently or would you code it differently ? How ?</strong> Does these tests seem sensible to you ?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:48:47.377",
"Id": "413022",
"Score": "0",
"body": "I don't quite understand how codereview works. I receive upvotes but not comments or answers. What does it mean ?"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T10:21:14.477",
"Id": "213507",
"Score": "2",
"Tags": [
"python",
"python-3.x",
"unit-testing"
],
"Title": "setting up mock and fixtures for for multiple pytest unit tests"
} | 213507 |
<p>I read somewhere that you should try to have as few method arguments as possible to make code easier to read, understand and use. I agree with this to a point but I'm not sure how I can make the following method easier. I think all 5 of the arguments are required. </p>
<p>Should I leave it as is? I think, if I was to add some comments, I may remember what this does if I come back to it later but there's a chance I won't know exactly what each argument is for.</p>
<pre><code>public static void RemoveXMLNode(string pathToDocument, string descendant, string element, string elementValue,string newDocumentPath)
{
var xDoc = XDocument.Load(pathToDocument);
xDoc.Descendants(descendant)
.Where(n => (string)n.Element(element) == elementValue)
.Remove();
xDoc.Save(newDocumentPath);
}
</code></pre>
| [] | [
{
"body": "<p>The method has definitely too many arguments and the reason for that is because it does too much. When you look at its name you could think it removes a XML node but under the cover it does three things:</p>\n\n<ul>\n<li>it loads a document</li>\n<li>it then does its job of removing a node</li>\n<li>it then saves the document under new name</li>\n</ul>\n\n<p>If you properly separated these three concerns your APIs would have much simpler signatures.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:32:42.760",
"Id": "413018",
"Score": "0",
"body": "Ok I have edited my post to try and refactor. I think it is an improvement but I still seem to need 4 arguments on my node removal part."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:34:55.997",
"Id": "413019",
"Score": "0",
"body": "@SyntaxError you're on the right track ;-) but unfortunatelly it's not allowed to add the improved version to the question. You can post a self-answer or a follow-up if you want us to take another look at your new code ;-] I had to rollback your edit."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:40:14.243",
"Id": "413021",
"Score": "0",
"body": "Oh ok i didn't know that! Posted an answer instead. Thanks :)"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:24:10.370",
"Id": "213511",
"ParentId": "213509",
"Score": "12"
}
},
{
"body": "<p>I went with the extension method in the end as it produced the least code</p>\n\n<p>Extension method</p>\n\n<pre><code>public static class XDocumentExtensions\n{\n public static void RemoveXMLNode(this XDocument doc, string descendant, string element, string elementValue)\n {\n doc.Descendants(descendant)\n .Where(n => (string)n.Element(element) == elementValue)\n .Remove();\n }\n}\n</code></pre>\n\n<p>Main program</p>\n\n<pre><code>class Program\n{\n static void Main(string[] args)\n {\n XDocument doc = XDocument.Load(@\"C:\\Temp\\Original.xml\");\n doc.RemoveXMLNode(\"Questions\", \"quPage\", \"PAGE60\");\n doc.Save(@\"C:\\Temp\\NewXmlDoc.xml\");\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:51:21.880",
"Id": "413023",
"Score": "0",
"body": "I would add the `ref` keyword to the `XDocument` argument in the `RemoveXMLNode` method, so that you actually pass by reference. As it is, it will create a **copy** of `doc` and remove the node from the copy. The original will stay with the node you are trying to remove."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T12:24:12.250",
"Id": "413028",
"Score": "5",
"body": "@Tom: `XDocument` is a class and thus a reference type. What you are saying only applies to value types."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T18:10:44.950",
"Id": "413075",
"Score": "0",
"body": "While OPs are [encouraged to answer their own questions](https://codereview.stackexchange.com/help/self-answer) bear in mind that [\"_Every answer must make at least one insightful observation about the code in the question. Answers that merely provide an alternate solution with no explanation or justification do not constitute valid Code Review answers and may be deleted._\"](https://codereview.stackexchange.com/help/how-to-answer)..."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:38:36.303",
"Id": "213512",
"ParentId": "213509",
"Score": "0"
}
},
{
"body": "<p>As a follow-up to <strong>t3chb0t</strong>'s and your self-answer, I agree that whilst the original <code>RemoveXMLNode</code> method you have written in your question is technically a one-liner, it is doing a lot.</p>\n\n<p>In response to your self-answer, I have a few pointer:</p>\n\n<ul>\n<li>In your case, I don't think you need a separate <code>LoadXMLDocument</code> method. The line <code>XDocument.load(path)</code> is easy enough to understand.</li>\n<li>Regarding you new <code>RemoveXMLNode</code> method, you have two options:</li>\n</ul>\n\n<p><strong>1. Pass by Reference</strong></p>\n\n<p>In your new method, you are requesting an <code>XDocument</code> argument. Whilst <code>XDocument</code> is a reference type and can be modified through its public methods, you may benefit from using the <code>ref</code> keyword so that you pass the whole object as a reference. This means that any changes to the object you are passing happen on the original object. So to apply this, you would simply change the method arguments to:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> // VVV - Note the 'ref' keyword!\nprivate static void RemoveXMLNode(ref XDocument doc, string descendant, string element, string elementValue)\n</code></pre>\n\n<p>You would then use the method like so:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> // VVV - Note the 'ref' keyword!\nRemoveXMLNode(ref doc, \"Questions\", \"quPage\", \"PAGE60\");\n</code></pre>\n\n<p>You can find more information on the difference between <em>Pass By Reference</em> and <em>Pass By Copy</em> over <a href=\"https://stackoverflow.com/questions/373419/whats-the-difference-between-passing-by-reference-vs-passing-by-value\">here</a>.</p>\n\n<p>There is also some more information on passing Reference Type classes from Jon Skeet's article over <a href=\"http://www.yoda.arachsys.com/csharp/parameters.html\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p>I also wrote some dummy code to try out and demonstrate this behaviour over <a href=\"https://dotnetfiddle.net/JIPz87\" rel=\"nofollow noreferrer\">here</a>.</p>\n\n<p><strong>2. <a href=\"https://docs.microsoft.com/en-us/dotnet/csharp/programming-guide/classes-and-structs/extension-methods\" rel=\"nofollow noreferrer\">Extension Method</a></strong></p>\n\n<p>This simply creates an extension method for your <code>XDocument</code> object. You do so by telling the compiler which of your arguments' object you are extending using the <code>this</code> keyword. When applying, you will actually reduce the number of required parameters by 1, effectively making it shorter.</p>\n\n<p>The only requirement for this option is that your extension method(s) must be in a <strong>non-generic and non-nested static class</strong>.</p>\n\n<p>You would write your method like so:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code> // VVVV - Note the 'this' keyword!\nprivate static void RemoveXMLNode(this XDocument doc, string descendant, string element, string elementValue)\n</code></pre>\n\n<p>Now, you would call this method like so:</p>\n\n<pre class=\"lang-cs prettyprint-override\"><code>// Only three arguments!\ndoc.RemoveXMLNode(\"Questions\", \"quPage\", \"PAGE60\");\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T12:36:24.123",
"Id": "413031",
"Score": "4",
"body": "Regarding #1, you're wrong: because `XDocument` is a reference type, the only thing that gets copied is a reference to the `XDocument` instance, not the instance itself."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T12:57:15.250",
"Id": "413032",
"Score": "0",
"body": "@PieterWitvoet If you're referring to the fact that I mentioned that it's passing a copy, then (on further digging around) I agree and I will modify my answer. If you're referring to the use of `ref`, I don't agree, as it still works."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T13:05:40.937",
"Id": "413033",
"Score": "1",
"body": "Adding `ref` won't break the code, but you'll be passing a reference to a reference around for no good reason. It'll clutter the code, send a confusing signal to other programmers and has a (tiny) performance implication. All for no benefit."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T12:23:50.983",
"Id": "213514",
"ParentId": "213509",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "213511",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:06:32.677",
"Id": "213509",
"Score": "8",
"Tags": [
"c#",
"beginner"
],
"Title": "XML node removal method with 5 arguments"
} | 213509 |
<p>I have <code>invoices</code>, <code>invoices_items</code>, <code>order</code>, <code>order_items</code>. <code>Invoices</code> and <code>Orders</code> tables contain around 1 million records. <code>Invoices_items</code> and <code>Orders_items</code> tables contains more than 2 millions records. Items table contains 200,000 records. Now I want to generate a report based on my filter like customers, item categories and more.</p>
<p>Running on PHP 5.6. MySql 5.7 and Apache2.</p>
<pre><code>SELECT
`si_items`.`item_id`
, SUM(qty) AS `qty`
, IFNULL(SUM(selling_price * (qty)), 0) AS `salestotal`
, GROUP_CONCAT(si.id) AS `siso_id`
, MAX(si.date_transaction) AS `date_transaction`
FROM
`invoice_items` AS `si_items`
LEFT JOIN `invoice` AS `si`
ON si.id = si_items.parent_id
LEFT JOIN `items`
ON si_items.item_id = items.id
WHERE (
DATE_FORMAT(si.date_transaction, '%Y-%m-%d') BETWEEN '2019-01-01'
AND '2019-02-15'
)
AND (si.approved = 1)
AND (si.deleted = 0)
AND (items.deleted = 0)
GROUP BY `item_id`
UNION
SELECT
`so_items`.`item_id`
, SUM(qty) AS `qty`
, IFNULL(SUM(selling_price * (qty)), 0) AS `salestotal`
, GROUP_CONCAT(so.id) AS `soso_id`
, MAX(so.date_transaction) AS `date_transaction`
FROM
`order_items` AS `so_items`
LEFT JOIN `order` AS `so`
ON so.id = so_items.parent_id
LEFT JOIN `items`
ON so_items.item_id = items.id
WHERE (
DATE_FORMAT(so.date_transaction, '%Y-%m-%d') BETWEEN '2019-01-01'
AND '2019-02-15'
)
AND (so.approved = 1)
AND (so.deleted = 0)
AND (items.deleted = 0)
GROUP BY `item_id`
</code></pre>
<p>When I executed this query for 50 days, it took <em>1 minute 20 seconds</em>.</p>
<p>INDEXES are added in tables.</p>
<p>Invoice and Order Tables:</p>
<pre><code>PRIMARY KEY (`id`),
KEY `account_id` (`account_id`),
KEY `approved` (`approved`),
KEY `deleted` (`deleted`),
KEY `finalised` (`finalised`),
KEY `rp_status` (`rp_status`),
KEY `sales_types_id` (`sales_types_id`),
KEY `account_type_id` (`account_type_id`),
KEY `company_id` (`company_id`),
KEY `date_transaction` (`date_transaction`)
</code></pre>
<p>Invoices_items & Order_items</p>
<pre><code>PRIMARY KEY (`id`),
KEY `deleted` (`deleted`),
KEY `item_id` (`item_id`),
KEY `parent_id` (`parent_id`),
KEY `vat_id` (`vat_id`),
KEY `qty` (`qty`),
</code></pre>
<p>Query image:</p>
<p><a href="https://i.stack.imgur.com/3o9Fw.jpg" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/3o9Fw.jpg" alt="enter image description here"></a></p>
<p>I need to increase performance of this query. How should I proceed?</p>
<p><strong>Show Create Tables</strong></p>
<pre><code>CREATE TABLE `invoice` (
`id` char(36) NOT NULL,
`reference` varchar(25) DEFAULT NULL,
`company_id` char(36) DEFAULT NULL,
`branch_id` char(36) DEFAULT NULL,
`account_id` char(36) DEFAULT NULL,
`contact_id` char(36) DEFAULT NULL,
`transaction_type` varchar(10) DEFAULT NULL,
`sales_types_id` int(11) DEFAULT '0',
`quote_validity` int(11) DEFAULT '0',
`delivery_method_id` int(11) DEFAULT '0',
`sales_representative_id` int(11) DEFAULT '0',
`account_type_id` char(36) DEFAULT NULL,
`vat_exempted` tinyint(1) DEFAULT '0',
`description` text,
`finalised` tinyint(1) DEFAULT '0' COMMENT 'Not Yet finalised - status=1; Need Approval - status = 2; Approved - status = 3',
`approved` tinyint(1) DEFAULT '0',
`approved_user_id` int(11) DEFAULT '0',
`default_sales_location_id` char(36) DEFAULT NULL COMMENT '0-Yes; 1-No',
`generate_do` tinyint(1) DEFAULT '1',
`generate_dn` tinyint(4) DEFAULT '1',
`do_status` tinyint(1) DEFAULT '0',
`cn_status` tinyint(1) DEFAULT '0',
`rp_status` tinyint(1) DEFAULT '0',
`dm_status` tinyint(1) DEFAULT '0',
`currency_id` char(36),
`exchange_rate_id` tinyint(1) DEFAULT '0',
`exchange_rate` double DEFAULT '1',
`date_transaction` datetime DEFAULT NULL,
`date_created` datetime DEFAULT NULL,
`date_modified` datetime DEFAULT NULL,
`created_user_id` int(11) DEFAULT '0',
`modified_user_id` int(11) DEFAULT '0',
`deleted` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`),
KEY `account_id` (`account_id`),
KEY `approved` (`approved`),
KEY `branch_id` (`branch_id`),
KEY `cn_status` (`cn_status`),
KEY `created_user_id` (`created_user_id`),
KEY `date_created` (`date_created`),
KEY `deleted` (`deleted`),
KEY `do_status` (`do_status`),
KEY `finalised` (`finalised`),
KEY `reference` (`reference`),
KEY `rp_status` (`rp_status`),
KEY `sales_types_id` (`sales_types_id`),
KEY `account_type_id` (`account_type_id`),
KEY `company_id` (`company_id`),
KEY `date_transaction` (`date_transaction`),
KEY `default_sales_location_id` (`default_sales_location_id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
CREATE TABLE `invoice_items` (
`id` char(36) NOT NULL,
`parent_id` char(36) DEFAULT NULL,
`item_id` char(36) DEFAULT NULL,
`qty` double DEFAULT '0',
`cost_price` double DEFAULT '0',
`list_price` double DEFAULT '0',
`selling_price` double DEFAULT '0',
`unit_price` double DEFAULT '0',
`vat` double DEFAULT '0',
`amount` double DEFAULT '0',
`special_discount` double DEFAULT '0',
`price_change_status` tinyint(1) DEFAULT '0',
`remarks` text,
`vat_id` int(11) DEFAULT '1',
`stock_category_id` tinyint(2) DEFAULT '0' COMMENT '1: Stockable 2: Service',
`is_giftitem` tinyint(1) DEFAULT '0' COMMENT '1: Gift Item 0: NO Gift',
`item_type_status` tinyint(1) DEFAULT '0',
`date_created` datetime DEFAULT NULL,
`date_modified` datetime DEFAULT NULL,
`created_user_id` int(11) DEFAULT '0',
`modified_user_id` int(11) DEFAULT '0',
`deleted` tinyint(1) DEFAULT '0',
PRIMARY KEY (`id`),
KEY `deleted` (`deleted`),
KEY `item_id` (`item_id`),
KEY `parent_id` (`parent_id`),
KEY `stock_category_id` (`stock_category_id`),
KEY `item_type_status` (`item_type_status`),
KEY `vat_id` (`vat_id`),
KEY `amount` (`amount`),
KEY `qty` (`qty`),
KEY `unit_price` (`unit_price`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:27:48.377",
"Id": "413016",
"Score": "0",
"body": "For a question asking to improve the performance of SQL query it would be wise to add the EXPLAIN output. Besides. it would be *extremely wise* to simplify the query taking out insignificant parts leaving only a code that is having the same performance problem."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:37:36.203",
"Id": "413020",
"Score": "0",
"body": "@YourCommonSense. added explain query result"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T12:00:48.680",
"Id": "413024",
"Score": "0",
"body": "I don't get it. Explain says there are only 100000 rows in invoice_items, and you said there are 2 million. Are 95% of them deleted?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T12:07:07.317",
"Id": "413025",
"Score": "0",
"body": "@YourCommonSense, No. Query has been executed for 6 months."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T13:18:28.817",
"Id": "413034",
"Score": "2",
"body": "The current question title, which states your concerns about the code, is too general to be useful here. Please [edit] to the site standard, which is for the title to simply state **the task accomplished by the code**. Please see [How to get the best value out of Code Review: Asking Questions](//codereview.meta.stackexchange.com/q/2436) for guidance on writing good question titles."
}
] | [
{
"body": "<p>I do not see any compound KEY, like <code>(date_transaction, approved, deleted)</code>.\nAlso less indices <em>can</em> improve overall speed - though counter-intuitive.\nMuch this index might not help. In that case reduce the data for the time being.</p>\n\n<p>Experiment with not using parts, i.e. both GROUP_CONCATs: <code>GROUP_CONCAT(si.id) AS siso_id</code> </p>\n\n<p>One could offer a zoom-in on the group IDs, for a single group, done later.</p>\n\n<p>One can also consider paging: here it might do to offer pages per <em>month</em>, reducing the request per page.</p>\n\n<p>Or create an archive table with query results per month.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T12:56:32.893",
"Id": "213515",
"ParentId": "213510",
"Score": "1"
}
},
{
"body": "<p>You use a date format function in the <code>WHERE</code> clause.</p>\n\n<p>This function then means that the query cannot use an index on the date column.</p>\n\n<p>Removing the date format function in the <code>WHERE</code> clause will improve the performance of the query.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-04-11T07:46:45.203",
"Id": "217251",
"ParentId": "213510",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:14:47.183",
"Id": "213510",
"Score": "0",
"Tags": [
"performance",
"sql",
"mysql"
],
"Title": "Improving/ Optimizing Performance Query in MySQL PHP"
} | 213510 |
<p>I have a message coming in and I need to match it against the expected messages. The program will eventually do something as a result of receiving those messages. I am not very experienced at programming, but surely there should be a better way to declare all those messages it can be in like a separate entity and then be able to use it within this HexSearch.cpp file? </p>
<p>I tried to search how to do that but I couldn't find the right words to ask about this using a search engine. There is many more messages than those show here which still need to be declared but this is just a sample, which I don't like to look at already. </p>
<pre><code>#include "HexSearch.h"
void searchFunction(int num, char msg[]) {
static const char readReq[] = { 0x92 };
static const char readResp[] = { 0x00, 0x02, 0x12, 0x34, 0xA1 };
static const char writeReq[] = { 0x0A, 0xE0 };
static const char writeResp[] = { 0x00, 0x02, 0x11, 0x01, 0x98 };
static const char resetReq[] = { 0x00, 0xFF };
static const char resetResp[] = { 0x00, 0x21, 0x23, 0x0E, 0xAE, 0x11, 0x3A };
static const char verReq[] = {0x00, 0xA2};
static const char verResp[] = {0x00, 0x03, 0x82, 0xAA, 0x07, 0x88, 0xA9};
static const char typeReq[] = {0x00, 0x67};
static const char typeResp[] = {0x00, 0x03, 0x00, 0x00, 0xC4, 0x77};
static const char askReq[] = {0x00, 0x55};
static const char askResp[] = {0x00, 0x01, 0xFE, 0xFF};
if (num == 4) {
replyMsg(msg, 2, 3, readReq, readResp, sizeof(readResp) / sizeof(readResp[0]));
}
else if (num == 5) {
replyMsg(msg, 2, 4, writeReq, writeResp, sizeof(writeResp) / sizeof(writeResp[0]));
replyMsg(msg, 2, 4, resetReq, resetResp, sizeof(resetResp) / sizeof(resetResp[0]));
replyMsg(msg, 2, 4, verReq, verResp, sizeof(verResp) / sizeof(verResp[0]));
replyMsg(msg, 2, 4, typeReq, typeResp, sizeof(typeResp) / sizeof(typeResp[0]));
replyMsg(msg, 2, 4, askReq, askResp, sizeof(askResp) / sizeof(askResp[0]));
}
}
void replyMsg(char msg[], int startArr, int endArr, const char* receiv, const char* resps, int respL) {
if (std::equal(msg + startArr, msg + endArr, receiv)) {
for (int x = 0; x < respL; x++) {
serialPC.putc(resps[x]);
}
}
}
</code></pre>
<p>The code works. I am interested in improving it only. <code>num</code> is the total number of bytes of a message. E.g. <code>readReq</code> has one byte of data, but has also got 2 start bytes and 1 end byte so a total of 4. <code>readResp</code> array has the 2 start bytes, 2 data bytes, and one end byte and so it has a total size of 5 bytes. The 2nd byte is the one which specifies the length of a message. <code>msg[]</code> is the message coming in from a serial connection essentially.</p>
<p>As an example, if <code>msg[] = { 0x00, 0x01, 0x92, 0x56 }</code> then <code>num = 4</code> and <code>replyMsg</code> will compare the 3rd byte to see that it matches <code>readReq</code> and so output <code>readResp</code>...</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T15:26:19.093",
"Id": "413050",
"Score": "0",
"body": "Does your code work? It doesn't seem very clear in your post. Not working code is not ready to be reviewed :)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T17:01:01.200",
"Id": "413068",
"Score": "1",
"body": "For a meaningful advice we need to know quite a few details of the protocol. Where `num` is coming from? could byte 2 be used to tell one-byte requests from 2-byte requests? etc."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T08:18:09.160",
"Id": "413340",
"Score": "0",
"body": "@vnp That's correct."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T11:22:40.480",
"Id": "413354",
"Score": "1",
"body": "@vnp is there anything else I can add/edit to take the question off hold status?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T11:23:13.963",
"Id": "413355",
"Score": "0",
"body": "@Snowhawk Hi, is there anything more I can do to take the question off its hold status?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T18:59:13.587",
"Id": "413443",
"Score": "0",
"body": "@TrybGhost Voted to reopen"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T20:54:48.377",
"Id": "427551",
"Score": "0",
"body": "What is at Position 0 and 1?"
}
] | [
{
"body": "<p>Unfortunately your code is incomplete and can't be run in this state. Still I want to recommend some improvements to this snippets.</p>\n\n<p>My first impression from this code is that it looks like plain C, not C++ (besides the use of <code>std::equal</code>). </p>\n\n<p>To pass your <code>Message</code> and compare it you are using plain <code>char</code> arrays.\nWith this approach you have to also pass the size. You shouldn't feel the need for this in C++ any more. Check out containers such as <code>std::array</code> (fixed size) <code>std::vector</code>, <code>std::string</code> or <code>std::string_view</code>.</p>\n\n<p>There's a bug which can make your program truncate the compared values depending on the platform:</p>\n\n<pre><code>static const char readReq[] = { 0x92 };\n</code></pre>\n\n<p>Consider that <code>0x92 = 146(int)</code>.</p>\n\n<p>Not all platforms have <code>char == unsigned char</code>. If you are not lucky it can mean <code>char == signed char</code>. See <a href=\"https://stackoverflow.com/questions/2054939/is-char-signed-or-unsigned-by-default\">https://stackoverflow.com/questions/2054939/is-char-signed-or-unsigned-by-default</a></p>\n\n<p>I found this by accident when I switched your plain C Array:</p>\n\n<pre><code>static const char readReq[] = { 0x92 }; \n</code></pre>\n\n<p>To C++ <code>std::vector</code>:</p>\n\n<pre><code>const std::vector<char> readRequest = { 0x92 };\n</code></pre>\n\n<p>This doesn't event compile. The compiler complains that 0x92 truncates. So I changed it to:</p>\n\n<pre><code>const std::vector<unsigned char> readRequest = { 0x92 };\n</code></pre>\n\n<p>Then I thought probably it is event better to really declare your values as an array of constants. So I changed to <code>std::array</code> like this:</p>\n\n<pre><code>constexpr std::array<unsigned char, 1> readRequest = { 0x92 };\nconstexpr std::array<unsigned char, 5> readResponse = { 0x00, 0x02, 0x12, 0x34, 0xA1 \n</code></pre>\n\n<p>Now it is similar to the old macro defines in C but better because it follows the rules of the language.:</p>\n\n<pre><code>#define readRequest 0x92 \n</code></pre>\n\n<p>With <code>std::array</code> I refactored your code like this:</p>\n\n<pre><code>#include <algorithm>\n#include <array>\n#include <iostream>\n#include <vector>\n\ntemplate<typename MessageBegin, typename MessageEnd, typename ReceiveType, \n typename ResponseType>\nvoid replyMessage(\n const MessageBegin& messageBegin,\n const MessageEnd& messageEnd,\n const ReceiveType& receive,\n const ResponseType& response)\n{\n if (std::equal(messageBegin, messageEnd, receive.begin())) {\n for (const auto& sign : response) {\n std::cout << sign;\n //serialPC.putc(sign);\n }\n }\n}\n\nvoid searchFunction(int number, const std::vector<unsigned char>& message)\n{\n constexpr std::array<unsigned char, 1> readRequest = { 0x92 };\n constexpr std::array<unsigned char, 5> readResponse = { 0x00, 0x02, 0x12, 0x34, 0xA1 };\n\n constexpr std::array<unsigned char, 2> writeRequest = { 0x0A, 0xE0 };\n constexpr std::array<unsigned char, 5> writeResponse = { 0x00, 0x02, 0x11, 0x01, 0x98 };\n\n constexpr std::array<unsigned char, 2> resetRequest = { 0x00, 0xFF };\n constexpr std::array<unsigned char, 7> resetResponse = { 0x00, 0x21, 0x23, 0x0E, 0xAE, 0x11, 0x3A };\n\n constexpr std::array<unsigned char, 2> verReqeust = { 0x00, 0xA2 };\n constexpr std::array<unsigned char, 7> verResponse = { 0x00, 0x03, 0x82, 0xAA, 0x07, 0x88, 0xA9 };\n\n constexpr std::array<unsigned char, 2> typeRequest = { 0x00, 0x67 };\n constexpr std::array<unsigned char, 6> typeResponse = { 0x00, 0x03, 0x00, 0x00, 0xC4, 0x77 };\n\n constexpr std::array<unsigned char, 2> askRequest = { 0x00, 0x55 };\n constexpr std::array<unsigned char, 4> askResponse = { 0x00, 0x01, 0xFE, 0xFF };\n\n if (number == 4) {\n replyMessage(message.begin() + 2, message.begin() + 3, readRequest, readResponse);\n }\n else if (number == 5) {\n replyMessage(message.begin() + 2, message.begin() + 4, writeRequest, writeResponse);\n replyMessage(message.begin() + 2, message.begin() + 4, resetRequest, resetResponse);\n replyMessage(message.begin() + 2, message.begin() + 4, verReqeust, verResponse);\n replyMessage(message.begin() + 2, message.begin() + 4, typeRequest, typeResponse);\n replyMessage(message.begin() + 2, message.begin() + 4, askRequest, askResponse);\n }\n}\n</code></pre>\n\n<p>In this code, other stuff was improved:</p>\n\n<ul>\n<li><p>Cryptic names like <code>msg</code>, <code>resps</code>, <code>respl</code> or <code>replyMsg</code> were renamed. Sure, you can find out what they mean, but it is more stressful to read the code and get the meaning. Make a experiment. Forget the code for 6 months and come back to it. How long does it take you to get its meaning?</p></li>\n<li><p>Functions can now accept Containers, which know their size. Also, we can simply iterate over them.</p></li>\n</ul>\n\n<p>Compare this:</p>\n\n<pre><code>void replyMsg(char msg[], int startArr, int endArr, const char* receiv, const char* resps, int respL) {\n if (std::equal(msg + startArr, msg + endArr, receiv)) {\n for (int x = 0; x < respL; x++) {\n serialPC.putc(resps[x]);\n }\n }\n}\n</code></pre>\n\n<p>with this:</p>\n\n<pre><code>template<typename MessageBegin, typename MessageEnd, typename ReceiveType, \n typename ResponseType>\nvoid replyMessage(\n const MessageBegin& messageBegin,\n const MessageEnd& messageEnd,\n const ReceiveType& receive,\n const ResponseType& response)\n{\n if (std::equal(messageBegin, messageEnd, receive.begin())) {\n for (const auto& sign : response) {\n std::cout << sign;\n //serialPC.putc(sign); // btw what is this???\n }\n }\n}\n</code></pre>\n\n<p>Besides the template, which we had to use because of different array sizes, which is easier to understand?</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T20:25:24.437",
"Id": "221151",
"ParentId": "213513",
"Score": "4"
}
},
{
"body": "<p>Use <a href=\"https://en.cppreference.com/w/cpp/container/span\" rel=\"nofollow noreferrer\"><code>std::span</code></a> (there are free backports if needed), and see most of the boilerplate evaporate:</p>\n\n<pre><code>void replyMsg(std::span<char> msg, std::span<const char> receiv, std::span<const char> resps) {\n if (msg.size() == 3 + receiv.size() && msg.subspan(2, receiv.size()) == receiv)\n for (auto x : resps)\n serialPC.putc(x);\n}\n\nvoid searchFunction(std::span<char> msg) {\n\n static const char readReq[] = { 0x92 };\n static const char readResp[] = { 0x00, 0x02, 0x12, 0x34, 0xA1 };\n\n static const char writeReq[] = { 0x0A, 0xE0 };\n static const char writeResp[] = { 0x00, 0x02, 0x11, 0x01, 0x98 };\n\n static const char resetReq[] = { 0x00, 0xFF };\n static const char resetResp[] = { 0x00, 0x21, 0x23, 0x0E, 0xAE, 0x11, 0x3A };\n\n static const char verReq[] = {0x00, 0xA2};\n static const char verResp[] = {0x00, 0x03, 0x82, 0xAA, 0x07, 0x88, 0xA9};\n\n static const char typeReq[] = {0x00, 0x67};\n static const char typeResp[] = {0x00, 0x03, 0x00, 0x00, 0xC4, 0x77};\n\n static const char askReq[] = {0x00, 0x55};\n static const char askResp[] = {0x00, 0x01, 0xFE, 0xFF};\n\n replyMsg(msg, readReq, readResp);\n replyMsg(msg, writeReq, writeResp);\n replyMsg(msg, resetReq, resetResp);\n replyMsg(msg, verReq, verResp);\n replyMsg(msg, typeReq, typeResp);\n replyMsg(msg, askReq, askResp);\n}\n</code></pre>\n\n<p>A miniscule amount of templating (alternatively use a function-template for <code>bytes</code>), and it's easily condensed even more:</p>\n\n<pre><code>template <char... x>\nstatic constexpr char bytes[] = { x...};\n\nvoid searchFunction(std::span<char> msg) {\n /* read */ replyMsg(msg, bytes<0x92 /* */>, bytes<0x00, 0x02, 0x12, 0x34, 0xA1>);\n /* write */ replyMsg(msg, bytes<0x0A, 0xE0>, bytes<0x00, 0x02, 0x11, 0x01, 0x98>);\n /* reset */ replyMsg(msg, bytes<0x00, 0xFF>, bytes<0x00, 0x21, 0x23, 0x0E, 0xAE, 0x11, 0x3A>);\n /* ver */ replyMsg(msg, bytes<0x00, 0xA2>, bytes<0x00, 0x03, 0x82, 0xAA, 0x07, 0x88, 0xA9>);\n /* type */ replyMsg(msg, bytes<0x00, 0x67>, bytes<0x00, 0x03, 0x00, 0x00, 0xC4, 0x77>);\n /* ask */ replyMsg(msg, bytes<0x00, 0x55>, bytes<0x00, 0x01, 0xFE, 0xFF>);\n}\n</code></pre>\n\n<p>Far less code, and it's far simpler too.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T11:50:41.810",
"Id": "427597",
"Score": "0",
"body": "Theres the gsl header as a support for the c++ core guidelines which contains std::span. Otherwise it will be in C++ 20."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-27T22:07:18.207",
"Id": "221157",
"ParentId": "213513",
"Score": "3"
}
},
{
"body": "<p>Here are some ideas to help you improve your code.</p>\n\n<h2>Use <code>const</code> where practical</h2>\n\n<p>The passed <code>msg</code> parameter is not and probably shouldn't be modified by the code, and so it should be declared as <code>const</code>.</p>\n\n<h2>Use objects</h2>\n\n<p>It seems that fundamentally, what's required here is a list of rules and a way to match them. I'd be inclined to keep things neat and use objects. I'd suggest wrapping things up into a collection of <code>Rule</code> objects.</p>\n\n<h2>Prefer <code>constexpr</code> where practical</h2>\n\n<p>Especially with embedded systems, <code>constexpr</code> can really allow much more compact code when it's used. This is also often useful for desktop applications, but more typically it's for speed rather than space. All of the fixed data structures could be <code>constexpr</code>.</p>\n\n<h2>Consider changing the interface</h2>\n\n<p>Instead of the old C-style length and pointer, it is often useful to declare and use a class for this. For example, one might have a <code>Message</code> class that would return a <code>const char *</code> that points to the data.</p>\n\n<h2>Think about future expansion</h2>\n\n<p>If you only want to be able to send back static messages in response to each requests, the data-oriented approach you have may be fine. However, it may be better to have both a <code>response</code> and some appropriate <code>action</code> instead.</p>\n\n<h2>Provide complete code to reviewers</h2>\n\n<p>This is not so much a change to the code as a change in how you present it to other people. Without the full context of the code and an example of how to use it, it takes more effort for other people to understand your code. This affects not only code reviews, but also maintenance of the code in the future, by you or by others. One good way to address that is by the use of comments. Another good technique is to include test code showing how your code is intended to be used.</p>\n\n<h2>Putting it all together</h2>\n\n<p>Using all of these suggestions, here's one way to do it:</p>\n\n<pre><code>#include <algorithm>\n#include <iostream>\n#include <iomanip>\n#include <string_view>\n\nstruct Message : public std::string_view {\n // I'm assuming that only valid Messages are \n // created. A static_assert could be used here.\n const char *dataptr() const { return begin() + 2; }\n};\n\nvoid doProcess(std::string_view sv, std::string_view name) {\n std::cout << \"Processing \" << name << \" Request: \";\n for (std::size_t i{0}; i < sv.size(); ++i) {\n //serialPC.putc(response[i]);\n std::cout << std::setfill('0') << std::setw(2) << std::hex << (static_cast<unsigned>(sv[i]) & 0xff) << ' ';\n }\n std::cout << '\\n';\n}\n\nvoid processRead(std::string_view sv) {\n doProcess(sv, \"Read\");\n}\n\nvoid processWrite(std::string_view sv) {\n doProcess(sv, \"Write\");\n}\n\nvoid processReset(std::string_view sv) {\n doProcess(sv, \"Reset\");\n}\n\nvoid processVersion(std::string_view sv) {\n doProcess(sv, \"Version\");\n}\n\nvoid processType(std::string_view sv) {\n doProcess(sv, \"Type\");\n}\n\nvoid processAsk(std::string_view sv) {\n doProcess(sv, \"Ask\");\n}\n\nvoid searchFunction(const Message &msg) {\n using namespace std::literals;\n static constexpr struct Rule {\n std::string_view match;\n std::string_view response;\n void (*action)(std::string_view);\n bool isMatch(const Message &msg) const {\n return msg.size() == (match.size() + 3) && std::equal(std::begin(match), std::end(match), msg.dataptr());\n }\n } rules[]{\n { \"\\x92\"sv, \"\\x00\\x02\\x12\\x34\\xA1\"sv, processRead },\n { \"\\x0A\\xE0\"sv, \"\\x00\\x02\\x11\\x01\\x98\"sv, processWrite },\n { \"\\x00\\xFF\"sv, \"\\x00\\x21\\x23\\x0E\\xAE\\x11\\x3A\"sv, processReset },\n { \"\\x00\\xA2\"sv, \"\\x00\\x03\\x82\\xAA\\x07\\x88\\xA9\"sv, processVersion },\n { \"\\x00\\x67\"sv, \"\\x00\\x03\\x00\\x00\\xC4\\x77\"sv, processType },\n { \"\\x00\\x55\"sv, \"\\x00\\x01\\xFE\\xFF\"sv, processAsk },\n };\n for (const auto &rule : rules) {\n if (rule.isMatch(msg)) {\n rule.action(rule.response);\n return;\n }\n }\n}\n\nint main() {\n using namespace std::literals;\n Message msg{\"\\x12\\x34\\x00\\x55\\x88\"sv};\n searchFunction(msg);\n}\n</code></pre>\n\n<p>This assumes a C++17 compiler to be able to use <code>std::string_view</code> objects extensively.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-28T20:17:16.690",
"Id": "221218",
"ParentId": "213513",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T11:51:56.023",
"Id": "213513",
"Score": "4",
"Tags": [
"c++",
"embedded",
"serial-port"
],
"Title": "Function to check if received message matches any of the expected messages"
} | 213513 |
<p>I am traditionally a Java/Backend Developer, and have recently been spending a lot of time dealing with issues that higher tiers of support should be able to handle themselves. To assist them with this, I wrote the following script for them to extract what look like "Log Files" from Kibana, allowing them to do some Analysis before issues get sent down to me. </p>
<p>While this will not be "production" code, it will probably be used as a tool internally, so I would like it to be as complete as possible for use.</p>
<p>Here is the group of scripts:</p>
<p><code>Script:</code></p>
<pre><code># Function defenition, allows us to call this as a CmdLet
function Search-Kibana-Request {
[CmdletBinding()]
# Parameters required by the Kibana Request Search Script
Param (
[Parameter(
Position = 0,
Mandatory = $true,
HelpMessage = "A Request ID that was pulled from a HAR or Chrome Dev Tools"
)]
[Alias("RequestId")]
[String]$REQUEST_ID,
[Parameter(
Position = 1,
Mandatory = $false,
HelpMessage = "Number of days in the past to search within; defaults to 7 days"
)]
[int]$DAYS_TO_SEARCH = 7,
[Parameter(
Position = 2,
Mandatory = $false,
HelpMessage = "Number of results to be returned by the search, default limited to 500"
)]
[int]$SEARCH_RESULT_LIMIT = 500
)
# Set the script variables we will be using
$script:startDateUnixEpoch = ([DateTimeOffset](Get-Date).ToUniversalTime()).ToUnixTimeMilliseconds()
$script:endDateUnixEpoch = ([DateTimeOffset](Get-Date).AddDays($DAYS_TO_SEARCH * -1).ToUniversalTime()).ToUnixTimeMilliseconds()
$script:indexSearchURL = 'https://<KIBANA_HOST>/elasticsearch/us1-wfoadapter-*/_field_stats?level=indices'
$script:queryURL = 'https://<KIBANA_HOST>/elasticsearch/_msearch'
$script:headers = @{'kbn-xsrf' = 'reporting'}
$script:totalIndicies = 0
$script:partitionSize = 5
$script:logText = New-Object System.Collections.Generic.List[System.Object]
# Ensure we are using the right version of TLS for the web requests
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12
# First, get the list of indicies that contain the timeframe we are searching;
# this prevents us from searching all indexes on the server
$body = @{
'fields' = @("@timestamp")
'index_constraints' = @{
'@timestamp' = @{
'max_value' = @{
'gte' = $script:endDateUnixEpoch
'format' = 'epoch_millis'
}
'min_value' = @{
'lte' = $script:startDateUnixEpoch
'format' = 'epoch_millis'
}
}
}
} | ConvertTo-Json -Depth 3 -Compress
$indiciesResponse = (Invoke-RestMethod $script:indexSearchURL -ContentType 'application/json' -Method POST -Body $body -Headers $script:headers)
# With the indicies response, partition the indicies into the correct query size
# for each batch (5), and execute the search query request for each batch
$indiciesToSearch = Get-Member -InputObject $indiciesResponse.indices -MemberType NoteProperty
$partitionedIndicies = $indiciesToSearch | Group-Object -Property { [math]::Floor($script:totalIndicies++ / $script:partitionSize) }
foreach($indexGroup in $partitionedIndicies) {
# Build the part of the query that tells the engine what indicies to search within
$searchGroup = '"' + ($indexGroup.Group.Name -join '","') + '"'
$queryIndexPart = "`"index`":[$($searchGroup)],`"ignore_unavailable`":true"
# Build the part of the query that tells the engine what to search for and how to sort
$querySortPart = "`"size`":$($SEARCH_RESULT_LIMIT),`"sort`":[{`"@timestamp`":{`"order`":`"asc`",`"unmapped_type`":`"boolean`"}}]"
$queryCriteriaPart = "`"query`":{`"bool`":{`"must`":[{`"query_string`":{`"query`":`"message:`\`"$($REQUEST_ID)`\`"`",`"analyze_wildcard`":true}},{`"range`":{`"@timestamp`":{`"gte`":$($script:endDateUnixEpoch),`"lte`":$($script:startDateUnixEpoch),`"format`":`"epoch_millis`"}}}],`"must_not`":[]}}"
# Combine the query parts into a single JSON type object
$queryString = "{$($queryIndexPart)}`r`n{$($querySortPart),$($queryCriteriaPart)}`r`n"
# Execute the query against the indexes that were returned previously
$queryResponse = (Invoke-RestMethod $script:queryURL -ContentType 'application/json' -Method POST -Body $queryString -Headers $script:headers)
# Gather all of the responses that have hits
$queryHits = $queryResponse.responses.hits
if($queryHits.total -ne 0) {
foreach($hit in $queryHits.hits) {
$script:logText.Add($hit._source.message)
}
}
}
# Output the log lines that were returned by the query
Write-Output $script:logText
}
</code></pre>
<p>I have them installing this script for use with the following, which does not seem completely safe.</p>
<p><code>Install:</code></p>
<pre><code># Install the function to the user's profile by appending to the end of the file
$hasUserProfile = Test-Path $Profile -PathType Leaf
if($hasUserProfile -ne $True) {
New-Item -Path $Profile -ItemType File -Force
}
$source = 'U:\Development\EmployeeTemp\<ME>\UsefulScripts\KibanaSearch\KibanaSearchRequest.ps1'
$content = [IO.File]::ReadAllText($source)
Add-Content $Profile "`r`n$($content)`r`n"
# Ensure we tell the user things have been installed
Write-Output "Search-Kibana-Request successfully installed! Press any key to continue..."
$null = $Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown');
Start-Process PowerShell
Stop-Process -Id $PID
</code></pre>
<p>Finally, I have them running the function as follows:</p>
<p><code>Search-Kibana-Request 1234-1234-1234-1234 > log.dbg</code></p>
<p>I know there are issues with the install script, but if anyone can point anything else out, that would be helpful.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T14:22:28.967",
"Id": "213521",
"Score": "1",
"Tags": [
"web-scraping",
"powershell",
"rest"
],
"Title": "Basic Kibana/Elasticsearch Search - Powershell"
} | 213521 |
<p>I want to display on a view the <code>EmployeeHistory</code> view model sorted by <code>elements.assignEffDateNext</code> and I want to instantiate and populate the view model from the controller. The code analysis is saying that the <code>IList<IDMSElementDate> EmployeePositionsOverTime</code> should be read only. I kind of understand why. </p>
<p>This is what I started with. </p>
<pre><code>public class EmployeeHistory
{
public int EmployeeID { get; set; }
public string EmployeeName { get; set; }
public IList<IDMSElementData> EmployeePositionsOverTime { get; set; }
}
public async Task<ActionResult> EmployeeHistory(int? employeeID)
{...//this part retrieves the elements from an api...
Employee emp = db.Employees.Find(employeeID);
string employeeName = emp.EmployeeFullName;
var sortedList = elements.Elements.OrderByDescending(e => e.assignEffDateNext).ToList();
EmployeeHistory empHist = new EmployeeHistory
{
EmployeeID = (int)employeeID,
EmployeeName = employeeName,
EmployeePositionsOverTime = sortedList,
};
return View("EmployeeHistory", empHist);
}
</code></pre>
<p>This is what I have changed it to. I added a constructor and changed the properties to be read-only so the type is immutable now and the analyzer is no longer giving me a warning. I was wondering whether this is better now and whether there is anything else about it that I should change?</p>
<pre><code> public class EmployeeHistory
{
public EmployeeHistory(int employeeID, string employeeName, IList<IDMSElementData> employeePositionsOverTime)
{
EmployeeID = employeeID;
EmployeeName = employeeName;
EmployeePositionsOverTime = employeePositionsOverTime;
}
public int EmployeeID { get; }
public string EmployeeName { get; }
public IList<IDMSElementData> EmployeePositionsOverTime { get; }
}
public async Task<ActionResult> EmployeeHistory(int? employeeID)
{...//this part retrieves the elements from an api...
Employee emp = db.Employees.Find(employeeID);
string employeeName = emp.EmployeeFullName;
var sortedList = elements.Elements.OrderByDescending(e => e.assignEffDateNext).ToList();
EmployeeHistory empHist = new EmployeeHistory((int)employeeID,employeeName,sortedList);
return View("EmployeeHistory", empHist);
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T16:29:19.833",
"Id": "413059",
"Score": "0",
"body": "We cannot answer your question here because it's not about improving the code but about a feature that you are trying to implement and that doesn't seem to work yet."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T16:34:18.727",
"Id": "413060",
"Score": "1",
"body": "What do you mean that it doesn't work yet? Is the problem that I did not include the section of the controller that retrieves the data from the api to populate the elements variable? I left that out because it is not relevant to the question I am asking and it is not a public api. I can run the application with both versions of the code and display the view with the sorted data."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T16:37:27.863",
"Id": "413061",
"Score": "0",
"body": "On the one hand, yes, you have to post complete code, on the other hand this is the feature that you are asking us to implment: _But how do I make it readonly while still being able to populate it from the controller?_ - we do not provide that kind of service here."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T16:40:43.500",
"Id": "413062",
"Score": "0",
"body": "The second set of code is an example of how I made it read only while populating it from the controller. That is the code I was looking to have reviewed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T16:49:48.563",
"Id": "413063",
"Score": "1",
"body": "I think I now understand what your question is so I have edited it a little bit... is this what you mean?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T16:53:12.110",
"Id": "413066",
"Score": "1",
"body": "ok, great ;-) I have one more question.. have you removed any parts from the code that you are asking us to review? This is important on Code Review. If you want to get good and useful feedback you should not change your code before posting. Your API is `async` but I don't see you `await`ing anything there."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T18:48:29.160",
"Id": "413077",
"Score": "1",
"body": "The call to get the data that populates the elements object has the await. I suppose the call to populate the emp object should/could also be asynchronous? I welcome any and all feedback, but wanted to ask primarily about the read only collection."
}
] | [
{
"body": "<p><strong>Nulls:</strong> What happens when someone asks for an EmployeeHistory without passing in an employee ID? It's hard for me to believe that the API for retrieving history will behave well, must less the call to <code>db.Employees.Find()</code>, and certainly not the cast <code>(int)employeeID</code>.</p>\n\n<p>I would recommend either immediately checking this and bailing out (with an ArgumentNullException or an empty view, or whatever you think is best), if you aren't already doing so. Or, you could the signature to <code>EmployeeHistory(int employeeID)</code> - since without an employee ID there is very little you can do.</p>\n\n<hr/>\n\n<p><strong>Names:</strong> You have an EmployeeHistory object, with three properties all named Employee-something. This is a bit redundant. Perhaps just <code>ID</code>, <code>Name</code>, and <code>PositionsOverTime</code>? Or <code>PositionsHeld</code>?</p>\n\n<p>Although that would imply that that <code>EmployeeHistory.ID</code> is the ID <em>of the history</em>... But that raises the question to me, why copy these properties from the Employee object at all? Why not just hold a reference to the actual Employee?</p>\n\n<p>In fact, perhaps it would make more sense to add the history of positions held to the Employee object. That does make more sense: \"This employee has this history\", rather than the other way around.</p>\n\n<p>As a side note, I'll grant that abbreviations like <code>emp</code>, <code>e</code>, and <code>empHist</code> are easy enough to parse in this case. However, my preference would still be for complete words when possible. Remember that code is read far more often than it is written, so if a few extra keystrokes now save a few seconds of parsing later, that's a net win.</p>\n\n<hr/>\n\n<p><strong>Encapsulation:</strong> You may have satisfied the requirement of a read-only collection in the eyes of your code analyzer, but you have not done so in fact. While a consumer of this class would not have the ability to swap out the entire list for one of their own, the <code>IList<T></code> interface is permissive enough that they may as well. <a href=\"https://dotnetfiddle.net/RSrfKo\" rel=\"nofollow noreferrer\">Here's a demo</a>.</p>\n\n<p>If you want to make this history truly read-only, you'll need to avoid handing out a direct reference to the list. <a href=\"https://docs.microsoft.com/en-us/dotnet/api/system.collections.generic.list-1.asreadonly?view=netframework-4.7.2\" rel=\"nofollow noreferrer\"><code>List.AsReadonly()</code></a> is good for this.</p>\n\n<p>Another thing you may want to encapsulate is the <em>order</em> of the list. You have decided* that the history should be sorted with the most recent <code>assignEffDateNext</code> first. If you want to guarantee that histories are always ordered this way, the logic to do so belongs in the history's constructor.</p>\n\n<p>*As a side note, I personally would not sort this list on the back end at all. Suppose a user wants to view the list in chronological order? Or sorted by position title? Javascript is perfectly capable of sorting arrays of the size you're likely to have. This gives your users flexibility while keeping (an admittedly very small) load off the server.</p>\n\n<hr/>\n\n<p><a href=\"https://en.wikipedia.org/wiki/Robustness_principle\" rel=\"nofollow noreferrer\"><strong>Robustness:</strong> <em>\"Be conservative in what you send, be liberal in what you accept.\"</em></a> It's generally nice when functions only ask for what they need. As it stands, an EmployeeHistory cannot be constructed with a Collection of positions - even though just a simple IEnumerable ought to be sufficient. Save yourself future calls to <code>.ToList()</code>, and open up this constructor to be more permissive.</p>\n\n<p>This same principle, in my mind, suggests that you should be as specific as possible about what you're returning. Making positions available as an <code>IReadOnlyList</code> is good, because it allows your users to access positions by index. For the same reason, I would also be more specific about what you're returning from the view. It is an <code>ActionResult</code>, yes... But more specifically it's a <code>ViewResult</code>. This may not have a big impact on your front end, but it could help with testability or refactoring down the line.</p>\n\n<hr/>\n\n<p>Here's how this code might look when you're done:</p>\n\n\n\n<pre class=\"lang-cs prettyprint-override\"><code>public class EmployeeHistory\n{\n public Employee Employee { get; }\n public IReadonlyList<IDMSElementData> PositionsHeld { get; }\n\n public EmployeeHistory(\n Employee employee,\n IEnumerable<IDMSElementData> positions)\n {\n Employee = employee;\n\n PositionsHeld = positions\n .OrderByDescending(position => position.assignEffDateNext)\n .ToList()\n .AsReadOnly();\n }\n}\n\npublic async Task<ViewResult> EmployeeHistory(int employeeID)\n{\n var positions = GetPositionsFromSomeAPICall(employeeID);\n\n var employee = db.Employees.Find(employeeID);\n\n var history = new EmployeeHistory(employee, positions);\n\n return View(\"EmployeeHistory\", history);\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T20:34:26.603",
"Id": "213541",
"ParentId": "213526",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "213541",
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T16:22:34.880",
"Id": "213526",
"Score": "1",
"Tags": [
"c#",
"comparative-review",
"asp.net-mvc",
"asp.net-mvc-5"
],
"Title": "Making EmployeeHistory ViewModel immutable as code analysis suggested"
} | 213526 |
<p>As part of an job interview process, I was tasked to write a solver for a simplified Tetris game using JavaScript. The game board size is 4x4 and there are 4 different pieces given in a .txt file. It is not allowed to rotate the pieces, so they should be placed exactly as they are specified in the file. Following normal Tetris rules, a row is cleared when there are no empty squares on a row. The goal is to have as few pieces on the board as possible after having placed all of them.</p>
<p>On a high level, what my code does is as follows:</p>
<ol>
<li>Parse the input file and create <code>TetrisPiece</code> objects</li>
<li>Create a new <code>Game</code> object that holds the tetris pieces and has a board size of 4x4</li>
<li>Shuffle the tetris pieces and compute their possible locations one at a time. Randomly choose one of the locations, place the piece on the board, and move on to the next piece. This is done by the <code>RandomSolver</code> class</li>
<li>Calculate the score of the solution and compare it to the best score so far. Reset game. Go back to step 3 until score is 0 (the optimal solution) or iterations = 10000</li>
</ol>
<h2>index.js</h2>
<pre><code>const fs = require('fs');
const parseFile = require('./reader');
const Game = require('./game');
const Coordinate = require('./coordinate');
const RandomSolver = require('./RandomSolver');
const inputFile = '../data/tetris_file.txt';
console.log('Parsing input file...');
const tetrisPieces = parseFile(inputFile);
console.log('Done.');
const boardSize = 4;
console.log(`Creating new game with size ${boardSize}`);
const game = new Game(boardSize, tetrisPieces);
const randomSolver = new RandomSolver(game);
randomSolver.run();
</code></pre>
<h2>reader.js</h2>
<pre><code>const fs = require('fs');
const TetrisPiece = require('./tetrisPiece');
const Coordinate = require('./coordinate');
/**
* Parses a file containing tetris piece information. The function reads the
* entire file into memory. For larger files, the file should be consumed line
* by line.
* @param {String} file The file path
* @return {TetrisPiece[]} The tetris pieces in the file
*/
function parseFile(file) {
let data;
try {
data = fs.readFileSync(file, 'utf-8').split('\r\r\n');
}
catch (err) {
throw err;
}
let tetrisPieces = [];
data.forEach(line => {
const tetrisPiece = parseLine(line);
tetrisPieces.push(tetrisPiece);
});
return tetrisPieces;
}
/**
* Parses a line of the input file containing tetric piece information.
* @param {String} line A line in the input file
* @return {TetrisPiece} A tetris piece constructed from input line
*/
function parseLine(line) {
const idCoordinates = line.split(':');
if (idCoordinates.length !== 2) {
throw 'Line contains invalid data';
}
const id = idCoordinates[0];
const rawCoordinates = idCoordinates[1].split(';');
let coordinates = [];
rawCoordinates.forEach(coordinate => {
const xy = coordinate.split(',');
coordinates.push(new Coordinate(xy[0], xy[1]));
});
return new TetrisPiece(id, coordinates);
}
module.exports = parseFile;
</code></pre>
<h2>game.js</h2>
<pre><code>const Coordinate = require('./coordinate');
/**
* Tetris game representation
*/
class Game {
constructor(boardSize, tetrisPieces) {
this.initTetrisBoard(boardSize);
this.tetrisPieces = tetrisPieces;
}
/**
* Initializes game board with given size (square)
* @param {Number} size The length of a side of the square
*/
initTetrisBoard(size) {
this.gameBoard = new Array(size).fill(null).map(item => (new Array(size).fill(null)));
}
/**
* Resets the game state to empty board
*/
reset() {
this.initTetrisBoard(this.getBoardSize());
}
/**
* Places given tetris piece on game board at given position
* @param {TetrisPiece} tetrisPiece The tetris piece to place
* @param {Coordinate} position The game board Coordinate to place the piece at.
* The tetris piece's coordinates are translated with this Coordinate
* @param {Boolean} [visualize=false] Visualize the game board after inserting piece
* @return {Boolean} Whether or not the tetris piece could be placed at given position
*/
placeTetrisPiece(tetrisPiece, position, visualize = false) {
if (!this.isPositionValidForTetrisPiece(tetrisPiece, position)) {
return false;
}
tetrisPiece.coordinates.forEach(localCoord => {
const boardCoord = localCoord.translate(position.x, position.y);
this.gameBoard[boardCoord.y][boardCoord.x] = tetrisPiece.id;
});
if (visualize) {
this.printGameBoard();
}
this.update(visualize);
return true;
}
/**
* Clears all complete rows
* @param {Boolean} [visualize=false] Visualize game board after clearing rows
*/
update(visualize = false) {
let didClearAnyRows = false;
for (let rowIndex = 0; rowIndex < this.gameBoard.length; rowIndex++) {
const row = this.gameBoard[rowIndex];
if (this.isRowComplete(row)) {
this.clearRow(rowIndex);
--rowIndex;
didClearAnyRows = true;
}
}
if (visualize && didClearAnyRows) {
this.printGameBoard();
}
}
/**
* Checks if given tetris piece can be placed at given position
* @param {TetrisPiece} tetrisPiece The tetris piece
* @param {Coordinate} position The tetris piece position
* @return {Boolean}
*/
isPositionValidForTetrisPiece(tetrisPiece, position) {
const boardCoords = tetrisPiece.coordinates.map(
localCoord => localCoord.translate(position.x, position.y));
if (boardCoords.some(boardCoord => this.isOutOfBounds(boardCoord) ||
this.gameBoard[boardCoord.y][boardCoord.x] !== null)) {
return false;
}
return true;
}
/**
* Checks if the tetris piece intersects with any other pieces on the board.
* Ignores coordinates outside the the board bounds
* @param {TetrisPiece} tetrisPiece The tetris piece
* @param {Coordinate} position The tetris piece position
* @return {Boolean} True if piece intersects, false otherwise
*/
checkForCollision(tetrisPiece, position) {
let collision = false;
tetrisPiece.coordinates.forEach(localCoord => {
const boardCoord = localCoord.translate(position.x, position.y);
if (!this.isOutOfBounds(boardCoord)) {
if (this.gameBoard[boardCoord.y][boardCoord.x] !== null) {
collision = true;
}
}
});
return collision;
}
/**
* Checks if given coordinate is outside board bounds
* @param {Coordinate} coord The coordinate
* @return {Boolean} True if outside bounds, false otherwise
*/
isOutOfBounds(coord) {
return coord.x < 0 || coord.y < 0 || coord.x >= this.getBoardSize() || coord.y >= this.getBoardSize();
}
/**
* Checks if tetris piece has any coordinates in spawning area (north of game board).
* @param {TetrisPiece} tetrisPiece The tetris piece
* @param {Coordinate} position The tetris piece position
* @return {Boolean} True if piece has at least one coordinate in spawning area
* but all other coordinates are within bounds, false otherwise
*/
isPartlyInSpawningAreaButInsideBounds(tetrisPiece, position) {
const boardCoords = tetrisPiece.coordinates.map(localCoord => localCoord.translate(position.x, position.y));
if (boardCoords.some(boardCoord => boardCoord.x < 0 || boardCoord.x >= this.getBoardSize() || boardCoord.y < 0)) {
return false;
}
if (boardCoords.some(boardCoord => boardCoord.y >= this.getBoardSize())) {
return true;
}
return false;
}
/**
* Calculates the spawn position for given tetris piece. The spawn position is
* calculated so that it is left-aligned and has at least one coordinate within
* game board bounds.
* @param {TetrisPiece} tetrisPiece The tetris piece
* @return {Coordinate} The spawn position
*/
getSpawnPositionForTetrisPiece(tetrisPiece) {
return new Coordinate(0,
this.getBoardSize() - 1 - Math.min(...tetrisPiece.coordinates.map(coord => coord.y)));
}
/**
* Returns the length of a side on the square game board
* @return {Number} The length of a side on the game board
*/
getBoardSize() {
return this.gameBoard.length;
}
/**
* Checks if the given row is filled by a tetris piece
* @param {Array} row The row to check
* @return {Boolean} True if complete, false otherwise
*/
isRowComplete(row) {
return row.every(val => val !== null);
}
/**
* Clears the given row, shifting all rows on top of it one step down. Inserts
* an empty row on top.
* @param {Number} rowIndex The row index
*/
clearRow(rowIndex) {
const emptyRow = this.createEmptyRow();
this.gameBoard.splice(rowIndex, 1);
this.gameBoard.push(emptyRow);
}
/**
* Creates an empty board row
* @return {Array} Array filled with null, same size as game board
*/
createEmptyRow() {
return new Array(this.getBoardSize()).fill(null);
}
/**
* Returns the number of tetris piece fragments on the board
* @return {Number} The number of fragments
*/
getTotalCost() {
let cost = 0;
this.gameBoard.forEach(row => row.forEach(val => {
if (val !== null) {
cost++;
}
}));
return cost;
}
/**
* Visualizes the current game board state
*/
printGameBoard() {
console.log(' ----');
for (let y = this.gameBoard.length - 1; y >= 0; y--) {
let line = "|";
for (let x = 0; x < this.gameBoard[y].length; x++) {
const val = this.gameBoard[y][x];
line += val === null ? " " : val;
}
line += "|";
console.log(line);
}
console.log(' ----');
}
}
module.exports = Game;
</code></pre>
<h2>randomSolver.js</h2>
<pre><code>/**
* An NPC that tries to find the optimal solution using random decisions
*/
class RandomSolver {
/**
* Initializes solver with a game that is already initialized
* @param {Game} game The intialized game
*/
constructor(game) {
this.game = game;
}
/**
* Attempts to find the best solution and shows the best solution it found
*/
run() {
let bestSolution;
console.log('Finding optimal solution using random decision...');
for (let i = 0; i < 10000; i++) {
const solution = this.randomSolution();
if (solution) {
if (!bestSolution || bestSolution.cost > solution.cost) {
bestSolution = solution;
if (solution.cost === 0) {
break;
}
}
}
this.game.reset();
}
console.log('Optimal solution (in given order):');
console.log(bestSolution);
this.printSolution(bestSolution);
}
/**
* Returns a solution by at each step calculating the possible tetris piece
* positions and choosing one of them randomly
* @return {Object} Undefined if game over, otherwise dict containing each
* tetris piece's ID as key and its position as value. Also contains the total cost
* of the solution with key 'cost'
*/
randomSolution() {
const shuffledPieces = shuffleArray(this.game.tetrisPieces);
let solution = {};
for (let i = 0; i < this.game.tetrisPieces.length; i++) {
const piece = shuffledPieces[i];
const possibleLocationsForPiece = this.getPossiblePositionsForPiece(piece);
// Game over
if (!possibleLocationsForPiece || possibleLocationsForPiece.length === 0) {
return;
}
const randomLocation = possibleLocationsForPiece[Math.floor(Math.random() * possibleLocationsForPiece.length)];
this.game.placeTetrisPiece(piece, randomLocation);
solution[piece.id] = randomLocation;
}
solution['cost'] = this.game.getTotalCost();
return solution;
}
/**
* Visualizes a complete solution
* @param {Object} solution See {@link RandomSolver#randomSolution} for description
*/
async printSolution(solution) {
this.game.reset();
for (const [key, value] of Object.entries(solution)) {
if (key !== 'cost') {
const piece = this.game.tetrisPieces.find(tetrisPiece => tetrisPiece.id === key);
this.game.placeTetrisPiece(piece, value, true);
}
await sleep(1000);
}
this.game.reset();
}
/**
* Returns the valid positions for given tetris piece with current game state
* @param {TetrisPiece} tetrisPiece The tetris piece
* @return {Coordinate[]} The valid positions, empty if none
*/
getPossiblePositionsForPiece(tetrisPiece) {
const spawnPosition = this.game.getSpawnPositionForTetrisPiece(tetrisPiece);
let possibleLocations = [];
possibleLocations = this.explorePossiblePositions(tetrisPiece, spawnPosition, spawnPosition);
return possibleLocations
}
/**
* Recursively calculates all possible positions for given tetris piece at given location
* with current game state
* @param {TetrisPiece} tetrisPiece The tetris piece
* @param {[type]} currentPosition The piece's current (theoretical) position
* @param {[type]} lastPosition The piece's previous position, used to avoid backtracking
* @return {Coordinate[]} The possible positions
*/
explorePossiblePositions(tetrisPiece, currentPosition, lastPosition) {
const southCoordinate = currentPosition.translate(0, -1);
const westCoordinate = currentPosition.translate(-1, 0);
const eastCoordinate = currentPosition.translate(1, 0);
let possibleLocations = [];
if (this.canMoveTo(tetrisPiece, southCoordinate)) {
const exploredPositions = this.explorePossiblePositions(tetrisPiece, southCoordinate, currentPosition);
possibleLocations = addUniqueCoordinates(possibleLocations, exploredPositions);
}
else {
if (this.game.isPositionValidForTetrisPiece(tetrisPiece, currentPosition)) {
possibleLocations = addUniqueCoordinates(possibleLocations, [currentPosition]);
}
}
[westCoordinate, eastCoordinate].forEach(coordinate => {
if (!lastPosition.equals(coordinate)) {
if (this.canMoveTo(tetrisPiece, coordinate)) {
const exploredPositions = this.explorePossiblePositions(tetrisPiece, coordinate, currentPosition);
possibleLocations = addUniqueCoordinates(possibleLocations, exploredPositions);
}
}
});
return possibleLocations;
}
/**
* Calculates if tetris piece can move to given position
* @param {TetrisPiece} tetrisPiece The tetris piece
* @param {Coordinate} position The position
* @return {Boolean} True if possible, false otherwise
*/
canMoveTo(tetrisPiece, position) {
if (this.game.isPositionValidForTetrisPiece(tetrisPiece, position)) {
return true;
}
if (this.game.isPartlyInSpawningAreaButInsideBounds(tetrisPiece, position)) {
if (!this.game.checkForCollision(tetrisPiece, position)) {
return true;
}
}
return false;
}
}
/**
* Adds given coordinates to given array if they do not exist in the array already
* @param {Coordinate[]} arr The array of existing coordinates
* @param {Coordinate[]} coords The coordinates to add if not already present
* @return {Coordinate[]} The new array
*/
function addUniqueCoordinates(arr, coords) {
coords.forEach(coord => {
if (!checkIfCoordinateExistsInArray(arr, coord)) {
arr = [...arr, coord];
}
})
return arr;
}
/**
* Checks if given coordinate exists in array
* @param {Coordinate[]} arr The array of coordinates
* @param {Coordinate} coordToCheck The coordinate to check for
* @return {Boolean} True if exists, false otherwise
*/
function checkIfCoordinateExistsInArray(arr, coordToCheck) {
let exists = false;
arr.forEach(coord => {
if (coord.equals(coordToCheck)) {
exists = true;
}
})
return exists;
}
/** Utility method to shuffle an array */
const shuffleArray = arr => arr
.map(a => [Math.random(), a])
.sort((a, b) => a[0] - b[0])
.map(a => a[1]);
/**
* Utility method to halt execution
* @param {Number} ms Milliseconds to sleepå
*/
function sleep(ms) {
return new Promise(resolve => setTimeout(resolve, ms));
}
module.exports = RandomSolver;
</code></pre>
<h2>coordinate.js</h2>
<pre><code>/**
* A 2D coordinate representation
*/
class Coordinate {
constructor(x, y) {
this.x = parseInt(x);
this.y = parseInt(y);
}
/**
* Translate this coordinate with given x and y offsets
* @param {Number} x Offset along x-axis
* @param {Number} y Offset along y-axis
* @return {Coordinate} The translated Coordinate
*/
translate(x, y) {
return new Coordinate(this.x + parseInt(x), this.y + parseInt(y));
}
/**
* Compare this Coordinate to another Coordinate by value
* @param {Coordinate} coord The Coordinate to compare with
* @return {Boolean}
*/
equals(coord) {
return this.x === coord.x && this.y === coord.y;
}
}
module.exports = Coordinate;
</code></pre>
<h2>tetris_file.txt</h2>
<pre><code>A:0,0;1,0;1,1;2,1
B:0,0;0,1;0,2;1,2
C:0,0;1,0;2,0;1,1
D:0,0;1,0;1,1;1,-1
</code></pre>
<p>Unfortunately I did not pass the assignment, so I asked for feedback on my implementation. According to them, the biggest problem with my code was that the solution was too complex for the task and that the code was hard to read. They also said that my prints were not working and that I overused the <code>let</code>statement.</p>
<p>I am not arguing against the feedback that I got, but what bothers me is even with this feedback, I do not know how I should improve my code. Therefore I am asking for a code review, specifically with readability and architecture in mind. </p>
<p>I am aware that my solution is quite unorthodox for JavaScript; it can probably be seen that I come from a Java background. As such, I would also appreciate any comments on how to make the solution more "JS-like". I should also mention that the algorithm was not important in the task, so it doesn't need to be reviewed.</p>
| [] | [
{
"body": "<h1>Method names and scope</h1>\n\n<p>I think your methods are well named, and are pretty easy to read</p>\n\n<hr>\n\n<h1>Over engineering</h1>\n\n<p>I understand that this was an interview and you probably wanted to show your skill. \nI suspect it ended up being more complex than it needed to be as a result.\nSome of the things you put in would be nice in a large project, but seems over the top for such a small coding challenge.</p>\n\n<p>Signs of over engineering:</p>\n\n<ul>\n<li>A fairly complicated solver. Why not go for a greedy solution obtained by simulating the game. They said the algorithm wasn't important.</li>\n<li>5 separate files</li>\n<li>Error handling on the input. There's also a try-catch there that does nothing.</li>\n<li>A whole class for a simple x,y object. At least you didn't mutate the object, which I liked.</li>\n<li>The game class has too many unnecessary methods. A getter for boardSize - with comments?</li>\n</ul>\n\n<hr>\n\n<h1>Comments</h1>\n\n<p>There are too many irrelevant comments. JSDoc is fine, but you don't need it on every method.</p>\n\n<hr>\n\n<h1>\"Overuse of the let statement\"</h1>\n\n<p>I don't get what they meant by this.</p>\n\n<hr>\n\n<h1>Concerns not separated</h1>\n\n<ul>\n<li>Why is totalCost calculated in the game class, not the solver?</li>\n<li>Why is collision check done in the game class? It should be the solver's job, or maybe a board class.</li>\n</ul>\n\n<p>There are several other methods that seem to bleed from one class to another.</p>\n\n<hr>\n\n<h1>Doing it the js way</h1>\n\n<p>The \"js way\" is obviously not universally agreed upon, but good js code is often very terse.\nWhat makes it terse is that it's dynamically typed, but also that it lends itself to functional programming styles since functions are first class.\nI see that you already make good use of this in your code, but it can be taken even further.</p>\n\n<p>My (obviously subjective) suggestion is to experiment with the following: </p>\n\n<ul>\n<li>Replace all the classes with pure (or close to pure) functions (except for reading input and printing of course). Only comment what's not obvious.\nMany of your methods are half-way there already.</li>\n<li>Put everything in one file. See how far you can go before you feel it getting too crowded.</li>\n<li>Replace the solver with a much simpler greedy solution</li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T20:56:23.963",
"Id": "413088",
"Score": "0",
"body": "I agree with what you said, especially the part about separation of concerns. I was actually thinking about it when I was writing the code but I guess I forgot to refactor. I think my over engineering comes from trying to follow the conventions in \"Clean Code\", where a class/function is supposed to be small and only do one thing. But I suppose for a small coding challenge like this, I should try to keep it brief."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T20:43:11.047",
"Id": "213542",
"ParentId": "213530",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213542",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T18:19:16.667",
"Id": "213530",
"Score": "4",
"Tags": [
"javascript",
"interview-questions",
"tetris"
],
"Title": "A simplified Tetris solver"
} | 213530 |
<p>I'm creating a version of the classic sequential master file update in java. This is used when you sort two files by the same key for updating one file with the other. In this case, I'm pulling in all available note types and then comparing them against note types configured. The goal is to create two collections, the list of configured note types, and the list of available note types, which do not contain the configured ones.</p>
<pre><code>private void setAvailableAndConfiguredNoteTypes(OptionGroupConfiguration optionConfig,
List<Map<String, String>> noteConfig) {
//retrieve the collections and sort by ID
List<ConfigOption> dbConfigured = getConfiguredNoteTypes();
List<ConfigOption> apiAvailable = getAvailableNoteTypes(noteConfig);
ConfigOption.CompareById comparator = new ConfigOption.CompareById();
Collections.sort(dbConfigured, comparator);
Collections.sort(apiAvailable, comparator);
//hold the results
List<ConfigOption> configured = new ArrayList<>();
List<ConfigOption> available = new ArrayList<>();
//process both collections
ListIterator<ConfigOption> configuredIt = dbConfigured.listIterator();
String configuredId = "";
ListIterator<ConfigOption> availableIt = apiAvailable.listIterator();
String availableId = "";
ConfigOption currentAvailable = null;
ConfigOption currentConfigured = null;
while (stillRunning(configuredId, availableId)) {
int cmp = configuredId.compareTo(availableId);
if (cmp == 0) {
//on equal, it goes in configured
if (currentConfigured != null) {
configured.add(currentConfigured);
}
////////////Code Group A
if (configuredIt.hasNext()) {
currentConfigured = configuredIt.next();
configuredId = currentConfigured.getId();
}
else {
currentConfigured = null;
configuredId = EOF;
}
////////////Code Group B
if (availableIt.hasNext()) {
currentAvailable = availableIt.next();
availableId = currentAvailable.getId();
}
else {
currentAvailable = null;
availableId = EOF;
}
}
else if (cmp < 0) {
//someone disabled the configured option, remove it
noteTypesConfiguredRepository.delete(configuredId);
////////////Code Group A
if (configuredIt.hasNext()) {
currentConfigured = configuredIt.next();
configuredId = currentConfigured.getId();
}
else {
currentConfigured = null;
configuredId = EOF;
}
}
else {
//add to available
available.add(currentAvailable);
////////////Code Group B
if (availableIt.hasNext()) {
currentAvailable = availableIt.next();
availableId = currentAvailable.getId();
}
else {
currentAvailable = null;
availableId = EOF;
}
}
}
Collections.sort(available);
optionConfig.setAvailableOptions(available);
Collections.sort(configured);
optionConfig.setConfiguredOptions(configured);
}
private static boolean stillRunning(String configuredId, String availableId) {
boolean result = !(configuredId.equals(EOF) && availableId.equals(EOF));
return result;
}
</code></pre>
<p>Some people on my project are looking at this and thinking it's complicated, but I can't for the life of me figure out how to make it any simpler.</p>
<p>Specifically, if you look at the two sections of 8 lines of code marked code group A and code group B, these are identical sections of 8 lines of code and it REALLY bugs me that I can't figure out a way to use the same 8 lines of code.</p>
<p>Does anyone have any suggestions on how to make this code simpler?</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T19:01:10.943",
"Id": "213532",
"Score": "3",
"Tags": [
"java",
"join"
],
"Title": "Sequential master update"
} | 213532 |
<p>The following is my solution for an inverse mapping with bilinear interpolation on an image. The original image is <code>img</code> and <code>newmatrix</code> is the transformed image. <code>invRot</code> is the inverse transformation matrix. </p>
<p>How can I optimize the nested for loops (or remove them altogether) to give me a better time complexity for large values of row and col?</p>
<pre><code>newmatrix = np.zeros((row, col, 3), np.uint8)
for r in range(row):
for c in range(col):
if offset > 0:
offset = -1 * offset
pt = np.array([r+offset,c,1]) #Adjust the offset.
newpt = np.matmul(invRot, pt) #Reverse map by reverse rotation and pick up color.
#Check the bounds of the inverse pts we got and if they lie in the original image,
#then copy the color from that original pt to the new matrix/image.
if (newpt[0] >= 0 and newpt[0] < (yLen - 1) and newpt[1] >= 0 and newpt[1] < (xLen - 1)):
x = np.asarray(newpt[1])
y = np.asarray(newpt[0])
x0 = np.floor(x).astype(int)
x1 = x0 + 1
y0 = np.floor(y).astype(int)
y1 = y0 + 1
Ia = img[y0, x0]
Ib = img[y1, x0]
Ic = img[y0, x1]
Id = img[y1, x1]
color1 = (x1-x) * (y1-y) * Ia
color2 = (x1-x) * (y-y0) * Ib
color3 = (x-x0) * (y1-y) * Ic
color4 = (x-x0) * (y-y0) * Id
weightedAvgColor = color1 + color2 + color3 + color4
newmatrix[r][c] = weightedAvgColor
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T08:17:41.343",
"Id": "413113",
"Score": "0",
"body": "While I'm normally a huge fan of vectorizing everything, often a really good solution in these situations is to use ``numba`` if at all possible."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T08:24:10.703",
"Id": "413114",
"Score": "0",
"body": "What are ``yLen`` and ``xLen``? And ``row`` and ``col``? Are they just the shape of the input image?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T09:18:21.420",
"Id": "413118",
"Score": "0",
"body": "row and col are the dimensions of the new image square. yLen and xLen are the maximum width and length of the original image."
}
] | [
{
"body": "<p>I'm sure there are ways to vectorize this, but I've learned from past examples that it's often easier to just use <code>numba.jit</code> in these cases (where \"these cases\" means entirely numeric operations with simple loops and no complex python object interactions beyond numpy). You technically ask for a better \"time complexity\", which would require a different algorithm/approach to this problem. That's not so easy to provide, since your current approach fundamentally requires individually processing how each source pixel is represented in each target pixel; that's <code>O(N)</code> or <code>O(H*W)</code> depending on how you want to frame the number of pixels, and I don't see any way around that. This process could be parallelized using a GPU or vectorized code; however, the easiest thing to try first is to make your current code more efficient. If that provides the speedup you require, then you can stop there.</p>\n\n<p>Just naively putting your code through <code>numba.jit</code>, however, doesn't provide any speedup. To figure out why, I used <code>numba.jit(nopython=True)</code>, which errors out when doing anything that numba can't convert into efficient C code. This showed a few minor things to change, such as converting <code>np.floor(x).astype(int)</code> to <code>int(np.floor(x))</code> (which is equivalent, since these are single integers and not arrays). Also, your modification of <code>offset</code> seems like it would only run once and only on the first iteration, if at all, so I moved it outside the loop. Your bounds checking condition can be simplified with a little Python-Fu. And finally, I've modified your variable names to conform to PEP8 style.</p>\n\n<p>The below code produces the same results are your original code, but is able to be efficiently compiled by <code>numba.jit</code>, providing ~20x speedup in my tests.</p>\n\n<pre><code>import numpy as np\nfrom numba import jit\n\n@jit(nopython=True)\ndef numba_func(img, inv_rot, offset, row, col):\n y_len, x_len, _ = img.shape\n\n new_matrix = np.zeros((row, col, 3), np.uint8)\n if offset > 0:\n offset *= -1\n for r in range(row):\n for c in range(col):\n pt = np.array([r + offset, c, 1])\n y, x, _ = inv_rot @ pt #Reverse map by reverse rotation and pick up color.\n\n #Check the bounds of the inverse pts we got and if they lie in the original image,\n #then copy the color from that original pt to the new matrix/image.\n if 0 <= y < (y_len - 1) and 0 <= x < (x_len - 1):\n x0 = int(np.floor(x))\n x1 = x0 + 1\n y0 = int(np.floor(y))\n y1 = y0 + 1\n\n Ia = img[y0, x0]\n Ib = img[y1, x0]\n Ic = img[y0, x1]\n Id = img[y1, x1]\n\n color1 = (x1-x) * (y1-y) * Ia\n color2 = (x1-x) * (y-y0) * Ib\n color3 = (x-x0) * (y1-y) * Ic\n color4 = (x-x0) * (y-y0) * Id\n\n weighted_avg_color = color1 + color2 + color3 + color4\n new_matrix[r, c] = weighted_avg_color\n\n return new_matrix\n</code></pre>\n\n<p>If that's not fast(er) enough, there are other options, but certainly they'll require a more significant re-work of the code. Again, though, due to the nature of the problem, I don't think you'll be able to achieve better \"time complexity\", just faster code; this doesn't seem like the kind of problem with a better algorithmic approach, just better implementations.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T09:27:43.717",
"Id": "413119",
"Score": "0",
"body": "I'll note, I also explored using numba's parallelization feature, and got either no speedup or some slowdown."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T09:24:07.140",
"Id": "213566",
"ParentId": "213533",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213566",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T19:01:27.790",
"Id": "213533",
"Score": "2",
"Tags": [
"python",
"performance",
"image",
"matrix",
"numpy"
],
"Title": "Inverse mapping with bilinear interpolation on an image"
} | 213533 |
<pre><code>class Link:
def __init__(self, value):
self.val = value
self.next = None
def __repr__(self):
return f"{self.val} "
def __str__(self):
return self.__repr__()
# TODO : Implement Non-recursive solutions and string representations in recursive solutions.
class LinkedList:
def __init__(self):
self.head = None
self.tail = None
self.length = 0
def __str__(self):
curr = self.head
linklist = ""
while curr:
linklist += str(curr) + ' '
curr = curr.next
return 'Linklist : ' + linklist
def __len__(self):
curr = self.head
next = self.head
size = 0
while curr and next:
if not next.next:
size += 1
return size
else:
size += 2
curr = curr.next
next = next.next.next
return size
def insert(self, key):
if not self.head:
self.head = Link(key)
self.tail = self.head
else:
node = Link(key)
self.tail.next = node
self.tail = node
self.length += 1
def delete(self, key):
if not self.head:
return False
elif self.head.val == key:
self.head = self.head.next
else:
curr = self.head
prev = None
while curr and curr.val != key:
prev = curr
curr = curr.next
if curr:
prev.next = curr.next
self.length -= 1
return True
return False
def print_reverse(self, node):
if node:
self.print_reverse(node.next)
print(str(node))
def do_reverse(self):
prev = None
curr = self.head
n = None
while curr:
n = curr.next
curr.next = prev
prev = curr
curr = n
self.head = prev
def delete_a_node_pointer(self):
pass
def find_middle_element(self):
curr = self.head
next = self.head
while curr and next:
if not next.next:
return curr.val,
elif next.next and not next.next.next:
return curr.val, curr.next.val
curr = curr.next
next = next.next.next
def hascycle(self):
slow = self.head
fast = self.head
while slow and fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast is slow:
return True
return False
def create_a_cycle(self):
index = 0
curr = self.head
while curr:
if index == 4:
break
curr = curr.next
index += 1
self.tail.next = curr
def find_start_of_the_cycle(self):
slow = self.head
fast = self.head
cycle = False
while slow and fast and fast.next:
slow = slow.next
fast = fast.next.next
if fast is slow:
cycle = True
break
if cycle:
curr = self.head
while curr and fast and curr is not fast:
curr = curr.next
fast = fast.next
return curr
else:
return None
def removeNthFromEnd(self, n):
pass
def test_main():
linklist = LinkedList()
linklist.insert(2)
# linklist.insert(4)
# linklist.insert(3)
# linklist.insert(-3)
#linklist.insert(-92)
print(str(linklist))
# linklist.delete(2)
# linklist.delete(3)
# linklist.delete(4)
# Don't print once the list has a cycle as it will loop for forever
#linklist.create_a_cycle()
# print(str(linklist))
print('HasCycle : ' , linklist.hascycle())
print('Cycle : ', str(linklist.tail), '->', linklist.find_start_of_the_cycle())
print('Middle Element : ', linklist.find_middle_element())
linklist.do_reverse()
print('Reversed', str(linklist))
print('Length LinkedList : ', str(len(linklist)))
if __name__ == '__main__':
test_main()
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T07:41:52.417",
"Id": "413112",
"Score": "0",
"body": "(Please tag [tag:reinventing-the-wheel].)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T12:04:17.383",
"Id": "413129",
"Score": "1",
"body": "@greybeard You can do that yourself too..."
}
] | [
{
"body": "<p>The code presented lacks <a href=\"https://www.python.org/dev/peps/pep-0257/#what-is-a-docstring\" rel=\"nofollow noreferrer\">doc strings</a>.<br>\nThis has consequences: How is anyone supposed to form an opinion on, say, <code>create_a_cycle()</code> (or even <code>removeNthFromEnd()</code>)? </p>\n\n<ul>\n<li>interface<br>\n(I'm preoccupied by exposure to <a href=\"http://simula67.at.ifi.uio.no/Standard-86/chap_11.htm\" rel=\"nofollow noreferrer\">SIMSET</a> at an impressible age <code>link</code> looks <em>almost</em> as good as <code>succ</code>.)<br>\nafter a while, I see test support mixed freely with class interface - don't</li>\n<li>use of a reserved built-in symbol (<code>next</code>) as a variable name - don't<br>\n(In <code>create_a_cycle()</code>, you manage to walk a list with a single reference. You don't even use both in <code>__len__()</code> and <code>find_middle_element()</code>. (In <code>delete(, key)</code>, there is the less readable alternative of using <code>succ.succ</code> (see <code>next</code> avoided).))</li>\n<li><code>__len__()</code>:<br>\nIt <em>looks</em> possible to do source level loop unrolling - but almost never a good idea.<br>\nFirst of all, it impedes readability, <em>especially</em> if not commented properly. </li>\n</ul>\n\n<p>A stripped-down shot at an unrolled <code>__len__()</code> (if not implementing a built-in, there would need to be a docstring…):</p>\n\n<pre><code>def __len__(self):\n # unrolled to follow two links per trip\n curr = self.head\n size = 0\n while curr:\n succ = curr.succ\n if not succ:\n return size + 1\n size += 2\n curr = succ.succ\n return size\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T08:39:09.943",
"Id": "213562",
"ParentId": "213534",
"Score": "1"
}
},
{
"body": "<p>A few things I'd add to @greybeard's answer (though I'll first emphasize: <strong>Add Docstrings</strong>):</p>\n\n<ul>\n<li><p>It's a Linked<em>List</em>, I'd expect to be able to iterate over it. There should be an <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__iter__\" rel=\"nofollow noreferrer\"><code>__iter__</code></a> function here.</p></li>\n<li><p>You rely heavily on knowing what your values are (<code>head</code> and <code>tail</code>), so you should hide them as private variables (<code>_head</code> and <code>_tail</code>) to indicate that external code should not access or modify them.</p></li>\n<li><p>You keep a <code>length</code> attribute, but when <code>__len__</code> is called, you go through the expensive task of re-computing this anyway. If you trust this value, return it; if not, then don't bother keeping it.</p></li>\n<li><p>You have functions to detect and manage cycles in your linked list, but many of your other functions (including <code>__len__</code>) don't check if they're trapped in one. This creates a ripe field for getting code locked in an infinite loop.</p></li>\n<li><p><code>print_reverse</code> relies on recursion, which won't work for lists of more than a few thousand items.</p></li>\n<li><p><code>do_reverse</code> is really vague, but seems to reverse the list; in Python, this is usually defined as <a href=\"https://docs.python.org/3/reference/datamodel.html#object.__reversed__\" rel=\"nofollow noreferrer\"><code>__reversed__</code></a></p></li>\n<li><p><code>delete_a_node_pointer</code>... does nothing, throws no errors, and takes no argument. Delete this, or at least <code>raise NotImplementedError()</code></p></li>\n<li><p><code>create_a_cycle</code> goes to element 4... for no explicable reason. This should be an argument.</p></li>\n<li><p>You support creating a cycle mid-list (that is, tail points to somewhere in the middle of the list), but then elsewhere in your code treat <code>tail.next</code> as properly pointing to <code>head</code> (particularly in <code>insert</code>... and it should be used in <code>delete</code>, that's probably a bug that it's not there). Either keep your linked list as a single ring or support middle-cycles, you can't really do both.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T22:56:15.647",
"Id": "413191",
"Score": "0",
"body": "About creating cycle's mid-list : I needed it that way. Also there's no way to delete the list if it has cycles. The strategy would be to remove the loop and then delete any node."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T17:09:31.900",
"Id": "213607",
"ParentId": "213534",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "213607",
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T19:09:46.043",
"Id": "213534",
"Score": "1",
"Tags": [
"python",
"algorithm",
"linked-list",
"reinventing-the-wheel"
],
"Title": "A LinkedList implementation in Python"
} | 213534 |
<p>The code below is for a coding challenge for a job. I have everything working as they requested, I've reviewed it myself and believe everything is good. I'm just looking to see if anyone see's anything that I may have done in a way that may be considered bad practice, or if there is any obvious improvements that could be made to clean up the code or increase performance. Any feedback is welcome.</p>
<p>Here are the instructions given to me by the company:</p>
<blockquote>
<ol>
<li>Present a menu to the user with 3 options [View Persons, Add Person, Exit]</li>
<li>If the user selects 'View Persons', the application should show a list of persons in the application.</li>
<li>If the user selects 'Add Person', they should be instructed to enter a name. The program should assign a unique id to the new person. </li>
<li>If a person selects 'Exit', the application should close. Otherwise, the application should stay running and/or indicate that the choice was invalid. </li>
<li>Optional: Create a 4th feature where you can search by name and the program indicates whether or not the name is in the system. </li>
<li>Use an in memory list to store person objects.</li>
<li>Use multiple classes and object oriented design to write your program (don't put all of your logic in the Program class).</li>
<li>What we look for:
<ul>
<li>Does the program meet the requirements/instructions and is it stable?</li>
<li>Is the code clean & appropriately commented? </li>
<li>Is there an understandable object oriented design?</li>
</ul></li>
</ol>
</blockquote>
<pre><code>using System;
using System.Collections.Generic;
using System.Linq;
namespace CSECodeSampleConsole
{
public class Program
{
public static void Main(string[] args)
{
Menu menu = new Menu();
menu.MainMenu();
}
}
internal class Person
{
public int Id { get; set; }
public string Name { get; set; }
public static int globalId = 1;
public Person(string name)
{
this.Name = name;
this.Id = globalId;
globalId++;
}
}
internal class Menu
{
List<Person> people = new List<Person>();
public void MainMenu() //Display and Navigate Menu.
{
Console.WriteLine("Please make a selection by entering the corresponding number:");
Console.WriteLine("1.View Persons");
Console.WriteLine("2.Add Person");
Console.WriteLine("3. Search For Person");
Console.WriteLine("4.Exit");
var input = Console.ReadLine();
switch (Convert.ToInt32(input))
{
case 1:
DisplayNames();
break;
case 2:
AddPerson();
break;
case 3:
SearchList();
break;
case 4:
Environment.Exit(0);
break;
default:
Console.WriteLine("Invalid Input\n\n");
MainMenu();
break;
}
return;
}
public void DisplayNames() //Display all names and their Id's in list.
{
if(people.Count == 0)
{
Console.WriteLine("No People To Display Yet.\n\n");
MainMenu();
}
else
{
Console.WriteLine("List of Current People:\n");
foreach (Person person in people)
{
Console.WriteLine(person.Id + " - " + person.Name);
}
Console.WriteLine("\n\n");
MainMenu();
}
return;
}
public void AddPerson() //Add a new person to the list.
{
Console.WriteLine("Please Enter The Person's Name: ");
var result = Console.ReadLine();
Person newPerson = new Person(result);
people.Add(newPerson);
Console.WriteLine(newPerson.Name + " added successfully.\n\n");
MainMenu();
return;
}
public void SearchList() //Find and display search results.
{
Console.WriteLine("Please Enter A Name To Search For: ");
var result = Console.ReadLine();
var searchResults = people.Where(n => n.Name.Contains(result, StringComparison.OrdinalIgnoreCase)).ToList();
if (searchResults.Count == 0)
{
Console.WriteLine("No Results Were Found");
}
else
{
Console.WriteLine("The Following Results Were Found: \n");
foreach (Person person in searchResults)
{
Console.WriteLine(person.Id + " - " + person.Name);
}
}
Console.WriteLine("\n\n");
MainMenu();
}
}
public static class MyExtensionMethods
{
public static bool Contains(this string source, string toCheck, StringComparison comp)
{ //Created this to take away the case sensitivity of the Contains method.
return source != null && toCheck != null && source.IndexOf(toCheck, comp) >= 0;
}
}
}
</code></pre>
| [] | [
{
"body": "<p><strong>Feedack to the code:</strong></p>\n\n<pre><code>this.Id = globalId;\nglobalId++;\n</code></pre>\n\n<p>Could be simplified as</p>\n\n<pre><code>this.Id = globalId++;\n</code></pre>\n\n<hr>\n\n<p><code>globalId</code> should not be public</p>\n\n<hr>\n\n<pre><code>switch (Convert.ToInt32(input)) { ... }\n</code></pre>\n\n<p>That is not a robust way to parse the input. If the user enters a letter, your program crashs!</p>\n\n<hr>\n\n<ul>\n<li><code>MainMenu()</code> can be moved to the end of the MainMenu() method (as recursive call).</li>\n<li><code>return</code> is not needed at the end of a method.</li>\n<li>The <code>Contains</code>-Extension method is not needed because neither the name, nor the search input can be null.</li>\n<li>Use <code>Environment.NewLine</code> or <code>Console.WriteLine</code> instead of \"\\n\".</li>\n</ul>\n\n<hr>\n\n<p><strong>Object oriented design</strong></p>\n\n<p>It is good, that there is a person class for storing information about the person.</p>\n\n<p>However, because the interviewer wishs an \"understandable object oriented design\" I would also try to model the different menu cases as objects.</p>\n\n<p>e.g. </p>\n\n<pre><code>public abstract class MenuEntry\n{\n public MenuEntry(int id, string description)\n {\n this.Id = id;\n this.Description = description;\n }\n\n public int Id { get; }\n public string Description { get; }\n\n public abstract void Execut();\n}\n</code></pre>\n\n<p>That allows to define each menu entry and its logic in a separate class and you get rid of the switch statement.</p>\n\n<p>Further more it is simpler to extend the program with new menu items without touching existign logic ;).</p>\n\n<hr>\n\n<p>Example implementation for <strong>single class entries</strong>:</p>\n\n<pre><code> internal class Person\n {\n public int Id { get; }\n public string Name { get; }\n private static int globalId = 1;\n\n public Person(string name)\n {\n this.Name = name;\n this.Id = globalId++;\n }\n\n }\n\n internal abstract class MenuEntry\n {\n public MenuEntry(int id, string description)\n {\n this.Id = id;\n this.Description = description;\n }\n\n public int Id { get; }\n public string Description { get; }\n\n public abstract void Execut();\n }\n\n internal class DisplayNames : MenuEntry\n {\n private readonly List<Person> persons;\n\n internal DisplayNames(List<Person> persons) : base(1, \"View Persons\")\n {\n this.persons = persons;\n }\n\n public override void Execut()\n {\n if (persons.Count == 0)\n {\n Console.WriteLine(\"No People To Display Yet.\");\n }\n else\n {\n Console.WriteLine(\"List of Current People:\");\n persons.ForEach(p => Console.WriteLine(p.Id + \" - \" + p.Name));\n }\n }\n }\n\n internal class AddPerson : MenuEntry\n {\n private readonly List<Person> persons;\n\n internal AddPerson(List<Person> persons) : base(2, \"Add Person\")\n {\n this.persons = persons;\n }\n\n public override void Execut()\n {\n Console.WriteLine(\"Please Enter The Person's Name: \");\n var result = Console.ReadLine();\n Person newPerson = new Person(result);\n persons.Add(newPerson);\n Console.WriteLine(newPerson.Name + \" added successfully.\");\n }\n }\n\n internal class Exit : MenuEntry\n {\n internal Exit() : base(9, \"Exit\")\n {\n }\n\n public override void Execut()\n {\n Environment.Exit(0);\n }\n }\n\n internal class Menu\n {\n private readonly List<Person> persons = new List<Person>();\n private readonly List<MenuEntry> entries = new List<MenuEntry>();\n\n public Menu()\n {\n this.entries.Add(new DisplayNames(this.persons));\n this.entries.Add(new AddPerson(this.persons));\n // ... other entries\n this.entries.Add(new Exit());\n }\n\n public void Show()\n {\n Console.WriteLine(\"Please make a selection by entering the corresponding number:\");\n this.entries.ForEach(p => Console.WriteLine($\"{p.Id}. {p.Description}\"));\n\n var input = Console.ReadLine();\n\n int entryId = -1;\n MenuEntry entry = null;\n if (int.TryParse(input, out entryId))\n {\n entry = this.entries.FirstOrDefault(e => e.Id == entryId);\n entry?.Execut();\n }\n\n if (entry == null)\n {\n Console.WriteLine(\"Invalid Input.\");\n }\n\n Console.WriteLine();\n Console.WriteLine();\n\n this.Show();\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T19:49:54.887",
"Id": "413082",
"Score": "0",
"body": "The reason I made the extension method was because I couldn't make it be case insensitive without it and that was the cleanest solution I could find. is there a better way to do it?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T20:06:14.457",
"Id": "413084",
"Score": "0",
"body": "You could use `s1.IndexOf(s2, StringComparison.InvariantCultureIgnoreCase) >= 0`. . However, an extension method is also OK if it is used several times."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T20:27:17.850",
"Id": "413085",
"Score": "0",
"body": "I'm a bit confused about how to use the abstract class properly here. I guess we \"inherit\" from the abstract class with child classes like ShowPeople, AddPerson, etc. But I'm not entirely sure how to fill out those child classes."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T07:43:36.320",
"Id": "413203",
"Score": "1",
"body": "@ethancodes: You are absolutly right. Please see my updated answer for an example implementation."
}
],
"meta_data": {
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T19:47:11.890",
"Id": "213537",
"ParentId": "213535",
"Score": "2"
}
},
{
"body": "<p>I am not a C# programmer, but here is some general feedback:</p>\n\n<p>You call <code>menu.MainMenu()</code> but there's no verb! Objects are nouns, methods should be verbs. Maybe name the method <code>DisplayMenu</code> or <code>DispatchUserAction</code> or something that indicates activity is happening? </p>\n\n<p>Your <code>MainMenu</code> method doesn't appear to handle invalid input. What happens if the user hits return? EOF? \"Abcde?\"</p>\n\n<p>The failure mode that I see just calls itself recursively. So can I crash your program by exhausting the stack with a series of 9's as input? Put in a <code>while true</code> loop, or something similar. Maybe loop and call an inner method, for small clear code.</p>\n\n<p>The <code>Person</code> constructor also updates the id counter. Change that so the id is managed separately. Maybe take an optional parameter and force the id counter to be above that value if provided?</p>\n\n<p>You have some awkward code to implement your search. Why is your comparison logic in the Menu class, or some 3rd party class? I think asking if a person's name matches a string is something that the Person class should handle:</p>\n\n<pre><code>foreach (Person guy in people) \n if (guy.isThisYou(target))\n etc.\n</code></pre>\n\n<p>I just noticed you handle all your returns to the main menu by recursion. Don't do that. Return and write a loop in the main menu. </p>\n\n<p>You have a lot of patterns of interacting with the console for input and output. Make those into dedicated helper functions/methods. Examples: printing two newlines to separate \"paragraphs\" could be <code>NewParagraph()</code>; and writing a line then reading a line could be <code>GetInput (String prompt)</code></p>\n\n<p>If possible, separate input and output streams into variables, and read and write against those stream variables. This will make it possible to code some test cases: construct the menu with string streams and compare the output against an expected value for the input.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T20:08:25.510",
"Id": "213539",
"ParentId": "213535",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213537",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T19:13:38.207",
"Id": "213535",
"Score": "4",
"Tags": [
"c#",
"interview-questions",
"console"
],
"Title": "Simple person manager console-app"
} | 213535 |
<p><strong>Purpose</strong></p>
<p>This was designed to be able to seamlessly replace <code>string SAPCustomerID</code> and <code>int CustomerID</code> in parameter lists with <code>CustomerIdentity customer</code> without breaking existing code. This will allow the developer to choose which they can provide and gain access to the other (if needed). Parameters lists being Web API functions or Service functions alike.</p>
<p><strong>Cache</strong></p>
<p>The cache is initialized at the start of the application using <code>CustomerIdentity.SetCache</code> and needs to be thread-safe (assuming <code>ICustomerCache</code> is thread-safe).</p>
<p><strong>Immutable</strong></p>
<p>The class is also designed to be immutable so that I may avoid all of the tedious checks that come along with the two ways to identify a customer (e.g. <code>CustomerID > 0</code> and <code>String.IsNullOrWhiteSpace(SAPCustomerID)</code>).</p>
<p><strong>Consistency</strong></p>
<p>I am considering the removal/adjustment of the <code>CustomerIdentity(int id, string sapCustomerID)</code> constructor. Having it how it is now does open the possibility of a customer missmatch (<code>ID</code> from one customer and <code>SAPCustomerID</code> from another). Haven't decided whether to remove it or use the cache to validate, leaning towards removal since the other constructors should be sufficient.</p>
<p><strong>CustomerIdentity.cs</strong></p>
<pre><code>/// <summary>
/// Identifies a customer via CustomerID or SAPCustomerID.
/// This class can implicitly convert to and from an integer (CustomerID) or a string (SAPCustomerID) looking up the other in the process.
/// </summary>
public class CustomerIdentity
{
#region Customer Cache
private static ICustomerCache CustomerCache;
private static readonly object CacheLock = new object();
/// <summary>
/// Sets the customer cache repository used to get the mappings of SAPCustomerID to CustomerID and vice-versa.
/// </summary>
/// <remarks>Called in Application_Start()</remarks>
public static void SetCustomerCache(ICustomerCache cache)
{
lock (CacheLock)
{
CustomerCache = cache;
}
}
#endregion
public int ID { get; private set; }
public string SAPCustomerID { get; private set; }
/// <summary>
/// Constructs a customer identity using an ID.
/// Looks up SAPCustomerID from the cache loaded at the start of the application.
/// </summary>
/// <exception cref="ArgumentNullException" />
/// <exception cref="ArgumentOutOfRangeException" />
public CustomerIdentity(int id)
{
SetCustomerID(id);
lock (CacheLock)
{
var sapCustomerID = CustomerCache.GetSAPCustomerID(id);
SetSAPCustomerID(sapCustomerID);
}
}
/// <summary>
/// Constructs a customer identity using an SAPCustomerID.
/// Looks up ID from the cache loaded at the start of the application.
/// </summary>
/// <exception cref="ArgumentNullException" />
/// <exception cref="ArgumentOutOfRangeException" />
public CustomerIdentity(string sapCustomerID)
{
SetSAPCustomerID(sapCustomerID);
lock (CacheLock)
{
var id = CustomerCache.GetCustomerID(sapCustomerID);
SetCustomerID(id);
}
}
/// <summary>
/// Constructs a customer identity using both ID and SAPCustomerID.
/// No look ups required for this method of construction.
/// </summary>
/// <exception cref="ArgumentNullException" />
/// <exception cref="ArgumentOutOfRangeException" />
public CustomerIdentity(int id, string sapCustomerID)
{
SetCustomerID(id);
SetSAPCustomerID(sapCustomerID);
}
private void SetCustomerID(int id)
{
if (id <= 0)
{
throw new ArgumentOutOfRangeException($"Parameter '{nameof(id)}' must be a positive integer.");
}
ID = id;
}
private void SetSAPCustomerID(string sapCustomerID)
{
if (String.IsNullOrWhiteSpace(sapCustomerID))
{
throw new ArgumentNullException($"Parameter '{nameof(sapCustomerID)}' cannot be null, empty, or whitespace.");
}
SAPCustomerID = sapCustomerID.Trim().TrimStart('0');
}
/// <summary>
/// Checks if the SAPCustomerID is a route customer.
/// </summary>
/// <remarks>
/// This should be renamed to IsRouteCustomer because only SAPCustomerIDs are allowed here, not routes.
/// </remarks>
public bool IsRouteCustomer()
{
return SAPCustomerID.Length <= 4;
}
#region Implicit Conversion Operators
/// <summary>
/// Implicity converts a customer identity to a string by using its SAPCustomerID as the string.
/// </summary>
public static implicit operator String(CustomerIdentity customer)
{
return customer.SAPCustomerID;
}
/// <summary>
/// Implicity converts a string to a customer identity by passing the string as an SAPCustomerID to the SAPCustomerID constructor.
/// <para/>Note - Invokes CustomerIdentity constructor.
/// </summary>
public static implicit operator CustomerIdentity(String sapCustomerID)
{
return new CustomerIdentity(sapCustomerID);
}
/// <summary>
/// Implicity converts a customer identity to an integer by using its ID as the integer.
/// </summary>
public static implicit operator Int32(CustomerIdentity customer)
{
return customer.ID;
}
/// <summary>
/// Implicity converts an integer to a customer identity by passing the integer as an ID to the ID constructor.
/// <para/>Note - Invokes CustomerIdentity constructor.
/// </summary>
public static implicit operator CustomerIdentity(int id)
{
return new CustomerIdentity(id);
}
#endregion Implicit Conversion Operators
#region Object Function Overrides
/// <summary>
/// To my understanding this is the proper was to override GetHashCode.
/// ID and SAPCustomerID shouldn't be allowed to be their default values, so no need for null checks.
/// </summary>
public override int GetHashCode()
{
return ID.GetHashCode() ^ SAPCustomerID.GetHashCode();
}
/// <summary>
/// Equality should work for CustomerIdentity, String, and Int32.
/// CustomerIdentity will make sure both ID and SAPCustomerID match.
/// String will check that it matches SAPCustomerID only.
/// Int32 will check that it matches ID only.
/// </summary>
public override bool Equals(object obj)
{
if (obj is CustomerIdentity)
{
var customer = obj as CustomerIdentity;
return ID == customer.ID
&& SAPCustomerID == customer.SAPCustomerID;
}
if (obj is int)
{
return ID.Equals((int)obj);
}
if (obj is string)
{
return SAPCustomerID.Equals(obj.ToString());
}
return false;
}
/// <summary>
/// This was overridden to make debugging nicer.
/// </summary>
public override string ToString()
{
return $"{nameof(ID)}: '{ID}' {nameof(SAPCustomerID)}: '{SAPCustomerID}'";
}
#endregion Object Function Overrides
}
</code></pre>
<p><strong>Example Usage</strong></p>
<p>If we have a function to call like this:</p>
<pre><code>public void GetCustomerDeliveries(CustomerIdentity customer, DateTime deliveryDate);
</code></pre>
<p>Then calling it would look like either of the following:</p>
<pre><code>GetCustomerDeliveries(12, DateTime.Today); // CustomerID example
GetCustomerDeliveries("1001234", DateTime.Today); // SAPCustomerID example
</code></pre>
<p><strong>Concerns</strong></p>
<p>I am open to any and all suggestions to improve my code; however, there are a few things I'm particularly concerned with.</p>
<ul>
<li>Is my code readable? If you delete all of the comments, could you still follow what the class does?</li>
<li>Assuming <code>ICustomerCache</code> is thread-safe, is my usage of the cache thread-safe inside <code>CustomerIdentity</code>?</li>
</ul>
| [] | [
{
"body": "<p>I think your code in general is easy to read and understand, so no problem with that. I would maybe change the name <code>SAPCustomerID</code> to just <code>SapId</code> as we know we're dealing with customers from the name of the owner type.</p>\n\n<hr>\n\n<blockquote>\n<pre><code>public override int GetHashCode()\n{\n return ID.GetHashCode() ^ SAPCustomerID.GetHashCode();\n}\n</code></pre>\n</blockquote>\n\n<p>If the <code>ID</code> and/or <code>SAPCustomerID</code> each uniquely defining a Customer then I don't see the necessity for the combination here. Returning one of the hash codes should be sufficient. I assume that a <code>CustomerIdentity</code> is only valid if it contains both ids?</p>\n\n<hr>\n\n<p>Trying this:</p>\n\n<blockquote>\n<pre><code> CustomerIdentity identity1 = (CustomerIdentity)\"12345\";\n CustomerIdentity identity2 = (CustomerIdentity)\"12345\";\n Console.WriteLine(identity1.Equals(identity2)); // true\n Console.WriteLine(identity1 == identity2); // false\n</code></pre>\n</blockquote>\n\n<p><code>Equals()</code> returns <code>true</code> because you carefully implement it to check for equality for each property, and <code>==</code> returns <code>false</code> because it just performs a <code>ReferenceEquals(a, b)</code> by default and because <code>identity1</code> is another instance than <code>identity2</code> (class/reference type).</p>\n\n<p>I would expect both the above statements to return true.</p>\n\n<p>You should implement the <code>==/!=</code> operators using <code>Equals()</code> so they behave equally or find a way to return the same instance of <code>CustomerIdentity</code> when casting from a string or a number.</p>\n\n<hr>\n\n<p>I think, I would define the cache interface as holding and returning objects of type <code>CutstomerIdentity</code> instead of exchanging strings for numbers and vice versa:</p>\n\n<pre><code> public interface ICustomerCache\n {\n CustomerIdentity GetIdentity(string sapId);\n CustomerIdentity GetIdentity(int id);\n }\n</code></pre>\n\n<hr>\n\n<blockquote>\n <p><code>public void GetCustomerDeliveries(CustomerIdentity customer, DateTime deliveryDate);</code></p>\n</blockquote>\n\n<p>Having a <code>Get...()</code> method returning void seems a little odd :-)</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T13:33:30.310",
"Id": "413373",
"Score": "0",
"body": "Oh right, I overload `.Equals` so infrequently I always forget it's different than `==`. `GetCustomerDeliveries` was just a funny mistake of randomly making up an example usage on the fly :P"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T11:57:27.063",
"Id": "213581",
"ParentId": "213536",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "213581",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T19:34:12.190",
"Id": "213536",
"Score": "1",
"Tags": [
"c#"
],
"Title": "CustomerIdentity class to bridge gap between internal and external CustomerIDs"
} | 213536 |
<p>Based on my understanding of Model View Presenter (MVP) I have it generate a diagram. Is this a correct implementation of MVP?</p>
<p>What deficiencies are there in my implementation?</p>
<p>UI</p>
<p><a href="https://i.stack.imgur.com/1wypg.png" rel="noreferrer"><img src="https://i.stack.imgur.com/1wypg.png" alt="enter image description here"></a></p>
<p>Generated diagram</p>
<p><a href="https://i.stack.imgur.com/GT45x.png" rel="noreferrer"><img src="https://i.stack.imgur.com/GT45x.png" alt="enter image description here"></a></p>
<hr>
<p>The code</p>
<pre><code>'LoadingModule class
'@Folder("Model")
Option Explicit
Private Type THelper
PointLoads As Long
DistributedLoads As Long
LeftSupport As BoundaryCondition
RightSupport As BoundaryCondition
SpanCondition As SpanType
End Type
Private this As THelper
Public Property Get PointLoadsCount() As Long
PointLoadsCount = this.PointLoads
End Property
Public Property Let PointLoadsCount(ByVal value As Long)
this.PointLoads = value
End Property
Public Property Get DistributedLoadsCount() As Long
DistributedLoadsCount = this.DistributedLoads
End Property
Public Property Let DistributedLoadsCount(ByVal value As Long)
this.DistributedLoads = value
End Property
Public Property Get LeftBoundaryCondition() As BoundaryCondition
LeftBoundaryCondition = this.LeftSupport
End Property
Public Property Let LeftBoundaryCondition(ByVal value As BoundaryCondition)
this.LeftSupport = value
End Property
Public Property Get RightBoundaryCondition() As BoundaryCondition
RightBoundaryCondition = this.RightSupport
End Property
Public Property Let RightBoundaryCondition(ByVal value As BoundaryCondition)
this.RightSupport = value
End Property
Public Property Get Self() As LoadingModel
Set Self = Me
End Property
Private Sub Class_Initialize()
this.PointLoads = 0
this.DistributedLoads = 0
this.LeftSupport = BoundaryCondition.Fixed
this.RightSupport = BoundaryCondition.Fixed
this.SpanCondition = SpanType.Simple
End Sub
Public Property Get SpanCondition() As SpanType
SpanCondition = this.SpanCondition
End Property
Public Property Let SpanCondition(ByVal value As SpanType)
this.SpanCondition = value
End Property
</code></pre>
<pre><code>'IView Interface
'@Folder("Abstractions")
'@Interface
Option Explicit
Public Function ShowDialog(ByVal viewModel As Object) As Boolean
End Function
</code></pre>
<pre><code>'Userform
'@Folder("UI")
Option Explicit
Implements IView
Private lastPointLoadValue As Long
Private lastDistributedLoadValue As Long
Private Const NumericInputsOnly As String = "Only numeric inputs allowed"
Private Type TView
IsCancelled As Boolean
model As VBAProject.LoadingModel
End Type
Private this As TView
Public Property Get model() As LoadingModel
Set model = this.model
End Property
Public Property Let model(ByVal value As LoadingModel)
Set this.model = value
End Property
Public Property Get IsCancelled() As Boolean
IsCancelled = this.IsCancelled
End Property
Private Sub CancelButton_Click()
OnCancel
End Sub
Private Function IView_ShowDialog(ByVal viewModel As Object) As Boolean
Set this.model = viewModel
SyncUIWithModel
Me.Show
IView_ShowDialog = Not this.IsCancelled
End Function
Private Sub SyncUIWithModel()
Dim spanCounter As Long
For spanCounter = 0 To SpanTypeListBox.ListCount - 1
If (SpanTypeListBox.List(spanCounter) = SpanConditionConverter.ToString(this.model.SpanCondition)) Then
SpanTypeListBox.ListIndex = spanCounter
Exit For
End If
Next
If model.SpanCondition = Cantilever Then
model.LeftBoundaryCondition = Fixed
model.RightBoundaryCondition = Free
End If
Dim leftCounter As Long
For leftCounter = 0 To LeftSupportTypeListBox.ListCount - 1
If (LeftSupportTypeListBox.List(leftCounter) = SupportTypeConverter.ToString(this.model.LeftBoundaryCondition)) Then
LeftSupportTypeListBox.ListIndex = leftCounter
Exit For
End If
Next
Dim rightCounter As Long
For rightCounter = 0 To RightSupportTypeListBox.ListCount - 1
If (RightSupportTypeListBox.List(rightCounter) = SupportTypeConverter.ToString(this.model.RightBoundaryCondition)) Then
RightSupportTypeListBox.ListIndex = rightCounter
Exit For
End If
Next
End Sub
Private Sub OKButton_Click()
Me.Hide
End Sub
Private Sub OnCancel()
this.IsCancelled = True
Me.Hide
End Sub
Private Sub SpanTypeListBox_Click()
If Not this.model Is Nothing Then
this.model.SpanCondition = SpanConditionConverter.ToEnum(SpanTypeListBox.List(SpanTypeListBox.ListIndex))
End If
If this.model.SpanCondition = Cantilever Then
MsgBox "Don't forget to mark the right boundary condition as free."
End If
End Sub
Private Sub UserForm_QueryClose(Cancel As Integer, CloseMode As Integer)
If CloseMode = VbQueryClose.vbFormControlMenu Then
Cancel = True
OnCancel
End If
End Sub
Private Sub LeftSupportTypeListBox_Change()
' viewModel.LeftSupport = SupportTypeConverter.ToEnum(LeftSupportTypeListBox.value)
' ^ Errors out | v workaround
If Not this.model Is Nothing Then
this.model.LeftBoundaryCondition = SupportTypeConverter.ToEnum(LeftSupportTypeListBox.List(LeftSupportTypeListBox.ListIndex))
End If
End Sub
Private Sub RightSupportTypeListBox_Change()
' viewModel.RightSupport = SupportTypeConverter.ToEnum(RightSupportTypeListBox.value)
If Not this.model Is Nothing Then
this.model.RightBoundaryCondition = SupportTypeConverter.ToEnum(RightSupportTypeListBox.List(RightSupportTypeListBox.ListIndex))
End If
End Sub
Private Sub UserForm_Initialize()
LeftSupportTypeListBox.AddItem SupportTypeConverter.ToString(BoundaryCondition.Fixed), 0
LeftSupportTypeListBox.AddItem SupportTypeConverter.ToString(BoundaryCondition.Pinned), 1
LeftSupportTypeListBox.AddItem SupportTypeConverter.ToString(BoundaryCondition.Roller), 2
LeftSupportTypeListBox.AddItem SupportTypeConverter.ToString(BoundaryCondition.Free), 3
LeftSupportTypeListBox.SetFocus
RightSupportTypeListBox.AddItem SupportTypeConverter.ToString(BoundaryCondition.Fixed), 0
RightSupportTypeListBox.AddItem SupportTypeConverter.ToString(BoundaryCondition.Pinned), 1
RightSupportTypeListBox.AddItem SupportTypeConverter.ToString(BoundaryCondition.Roller), 2
RightSupportTypeListBox.AddItem SupportTypeConverter.ToString(BoundaryCondition.Free), 3
SpanTypeListBox.AddItem SpanConditionConverter.ToString(SpanType.Simple), 0
SpanTypeListBox.AddItem SpanConditionConverter.ToString(SpanType.Cantilever), 1
PointLoadsSpinButton.value = 0
PointLoadsTextBox.value = PointLoadsSpinButton.value
DistributedLoadsSpinButton.value = 0
DistributedLoadsTextBox.value = DistributedLoadsSpinButton.value
End Sub
Private Sub PointLoadsSpinButton_Change()
PointLoadsTextBox.value = PointLoadsSpinButton.value
lastPointLoadValue = PointLoadsSpinButton.value
End Sub
Private Sub PointLoadsTextBox_Change()
If PointLoadsTextBox = vbNullString Then
PointLoadsTextBox.value = 0
End If
If Not IsNumeric(PointLoadsTextBox.value) Then
PointLoadsTextBox.value = lastPointLoadValue
MsgBox NumericInputsOnly
Exit Sub
End If
PointLoadsSpinButton.value = PointLoadsTextBox.value
If Not this.model Is Nothing Then
this.model.PointLoadsCount = PointLoadsTextBox.value
End If
End Sub
Private Sub DistributedLoadsSpinButton_Change()
DistributedLoadsTextBox.value = DistributedLoadsSpinButton.value
lastDistributedLoadValue = DistributedLoadsSpinButton.value
End Sub
Private Sub DistributedLoadsTextBox_Change()
If DistributedLoadsTextBox.value = vbNullString Then
DistributedLoadsTextBox.value = 0
End If
If Not IsNumeric(DistributedLoadsTextBox.value) Then
DistributedLoadsTextBox.value = lastDistributedLoadValue
MsgBox NumericInputsOnly
Exit Sub
End If
DistributedLoadsSpinButton.value = DistributedLoadsTextBox.value
If Not this.model Is Nothing Then
this.model.DistributedLoadsCount = CLng(DistributedLoadsTextBox.value)
End If
End Sub
</code></pre>
<pre><code>'Presenter module
Option Explicit
Private ws As Worksheet
Private Const defaultSupportDimension As Long = 10
Private Const defaultSpanWidth As Double = 300
Public Sub CreateLoadingDiagram()
Dim view As IView
Set view = New BasicView
Dim model As LoadingModel
Set model = New LoadingModel
If Not view.ShowDialog(model) Then
Exit Sub
End If
Set ws = ActiveSheet
Dim leftBoundaryConiditionShape As Shape
Dim topLeftCell As Range
Set topLeftCell = ActiveWindow.VisibleRange(7, 2)
Set leftBoundaryConiditionShape = CreateBoundaryConditionShape( _
model.LeftBoundaryCondition, _
topLeftCell.Left, _
topLeftCell.Top)
Dim spanWidth As Double
If (model.SpanCondition = Simple) Then
spanWidth = defaultSpanWidth
Else
spanWidth = defaultSpanWidth / 2
End If
Dim rightBoundaryConditionShape As Shape
Set rightBoundaryConditionShape = CreateBoundaryConditionShape( _
model.RightBoundaryCondition, _
topLeftCell.Left - defaultSupportDimension / 2 + spanWidth, _
topLeftCell.Top)
Dim beamMember As Shape
Set beamMember = ws.Shapes.AddConnector(MsoConnectorType.msoConnectorStraight, _
topLeftCell.Left + defaultSupportDimension / 2, _
topLeftCell.Top, _
topLeftCell.Left + defaultSpanWidth, _
topLeftCell.Top)
Dim distributedLoadHeightOffset As Long
AddDistributedLoads model.DistributedLoadsCount, _
beamMember, _
topLeftCell, _
distributedLoadHeightOffset
'@Ignore UnassignedVariableUsage
AddPointLoads model.PointLoadsCount, beamMember, distributedLoadHeightOffset
Set ws = Nothing
End Sub
Private Function CreateBoundaryConditionShape(ByVal condition As BoundaryCondition, ByVal leftEdge As Double, ByVal topEdge As Double) As Shape
If condition = Free Then
Exit Function
End If
If condition = Fixed Then
Set CreateBoundaryConditionShape = CreateFixedBoundaryConditionShape(leftEdge, topEdge)
Exit Function
End If
Dim shapeType As MsoAutoShapeType
If condition = Pinned Then
shapeType = MsoAutoShapeType.msoShapeIsoscelesTriangle
ElseIf condition = Roller Then
shapeType = MsoAutoShapeType.msoShapeOval
End If
Set CreateBoundaryConditionShape = ws.Shapes.AddShape(shapeType, _
leftEdge, _
topEdge, _
defaultSupportDimension, _
defaultSupportDimension)
End Function
Private Function CreateFixedBoundaryConditionShape(ByVal leftEdge As Double, ByVal topEdge As Double) As Shape
Dim horizon As Shape
Set horizon = ws.Shapes.AddConnector(MsoConnectorType.msoConnectorStraight, _
leftEdge, _
topEdge, _
leftEdge + defaultSupportDimension, _
topEdge)
Dim slanted1 As Shape
Set slanted1 = ws.Shapes.AddConnector(MsoConnectorType.msoConnectorStraight, _
leftEdge, _
topEdge + 0.5 * defaultSupportDimension, _
leftEdge + 0.5 * defaultSupportDimension, _
topEdge)
Dim slanted2 As Shape
Set slanted2 = ws.Shapes.AddConnector(MsoConnectorType.msoConnectorStraight, _
leftEdge, _
topEdge + 1 * defaultSupportDimension, _
leftEdge + 1 * defaultSupportDimension, _
topEdge)
Dim slanted3 As Shape
Set slanted3 = ws.Shapes.AddConnector(MsoConnectorType.msoConnectorStraight, _
leftEdge + 0.5 * defaultSupportDimension, _
topEdge + 1 * defaultSupportDimension, _
leftEdge + 1 * defaultSupportDimension, _
topEdge + 0.5 * defaultSupportDimension)
Set CreateFixedBoundaryConditionShape = ws.Shapes.Range(Array(horizon.Name, slanted1.Name, slanted2.Name, slanted3.Name)).Group
End Function
Private Sub AddDistributedLoads(ByVal nuberOfDistributedLoads As Long, ByVal beamMemberShape As Shape, ByVal topLeftCell As Range, ByRef outDistributedLoadHeightOffset As Long)
Const distributedLoadHeight As Long = 30
Dim counter As Long
For counter = 1 To nuberOfDistributedLoads
outDistributedLoadHeightOffset = counter * distributedLoadHeight
Dim distributedLoad As Shape
Set distributedLoad = ws.Shapes.AddShape(MsoAutoShapeType.msoShapeRectangle, _
topLeftCell.Left + defaultSupportDimension / 2, _
topLeftCell.Top - outDistributedLoadHeightOffset, _
beamMemberShape.Width, _
distributedLoadHeight)
distributedLoad.Fill.Visible = msoFalse
Next
End Sub
Private Sub AddPointLoads(ByVal numberOfPointLoads As Long, ByVal beamMember As Shape, ByVal distributedLoadHeightOffset As Long)
Dim leftDisplacement As Double
leftDisplacement = beamMember.Width / (1 + numberOfPointLoads)
Dim counter As Long
For counter = 1 To numberOfPointLoads
Dim pointLoadInsertion As Double
pointLoadInsertion = beamMember.Left + (leftDisplacement * counter)
Dim pointLoad As Shape
Set pointLoad = ws.Shapes.AddConnector(MsoConnectorType.msoConnectorStraight, _
pointLoadInsertion, _
beamMember.Top - 50 - distributedLoadHeightOffset, _
pointLoadInsertion, _
beamMember.Top - distributedLoadHeightOffset)
pointLoad.Line.EndArrowheadStyle = MsoArrowheadStyle.msoArrowheadTriangle
Next
End Sub
</code></pre>
<p>Converters are used to allow using <code>Enum</code>s instead of strings to maintain consistency and avoid global variables. They have the <code>VB_PredeclaredId</code> attribute set to <code>True</code>.</p>
<pre><code>'@PredeclaredId
'@Folder("Converters")
Option Explicit
Public Enum SpanType
NotSet
Simple
Cantilever
End Enum
Private StringForEnum As Dictionary
Private EnumForString As Dictionary
Private Sub Class_Initialize()
PopulateDictionaries
End Sub
Private Sub PopulateDictionaries()
Set EnumForString = New Dictionary
EnumForString.CompareMode = TextCompare
EnumForString.Add "Simple", SpanType.Simple
EnumForString.Add "Cantilever", SpanType.Cantilever
Set StringForEnum = New Dictionary
EnumForString.CompareMode = TextCompare
Dim key As Variant
For Each key In EnumForString.Keys
StringForEnum.Add EnumForString.Item(key), key
Next
End Sub
Public Function ToEnum(ByVal value As String) As SpanType
If Not EnumForString.Exists(value) Then
ThrowInvalidArgument "ToEnum", value
End If
ToEnum = EnumForString(value)
End Function
Public Function ToString(ByVal value As SpanType) As String
If Not StringForEnum.Exists(value) Then
ThrowInvalidArgument "ToString", CStr(value)
End If
ToString = StringForEnum(value)
End Function
Private Sub ThrowInvalidArgument(ByVal source As String, ByVal value As String)
Err.Raise 5, Information.TypeName(Me) & "." & source, "Invalid input '" & value & "' was supplied."
End Sub
Public Property Get Enums() As Variant
Enums = EnumForString.Items
End Property
Public Property Get Strings() As Variant
Strings = EnumForString.Keys
End Property
</code></pre>
<pre><code>'@PredeclaredId
'@Folder("Converters")
Option Explicit
Public Enum BoundaryCondition
NotSet
Fixed
Pinned
Roller
Free
End Enum
Private StringForEnum As Dictionary
Private EnumForString As Dictionary
Private Sub Class_Initialize()
PopulateDictionaries
End Sub
Private Sub PopulateDictionaries()
Set EnumForString = New Dictionary
EnumForString.CompareMode = TextCompare
EnumForString.Add "Fixed", BoundaryCondition.Fixed
EnumForString.Add "Pinned", BoundaryCondition.Pinned
EnumForString.Add "Roller", BoundaryCondition.Roller
EnumForString.Add "Free", BoundaryCondition.Free
Set StringForEnum = New Dictionary
EnumForString.CompareMode = TextCompare
Dim key As Variant
For Each key In EnumForString.Keys
StringForEnum.Add EnumForString.Item(key), key
Next
End Sub
Public Function ToEnum(ByVal value As String) As BoundaryCondition
If Not EnumForString.Exists(value) Then
ThrowInvalidArgument "ToEnum", value
End If
ToEnum = EnumForString(value)
End Function
Public Function ToString(ByVal value As BoundaryCondition) As String
If Not StringForEnum.Exists(value) Then
ThrowInvalidArgument "ToString", CStr(value)
End If
ToString = StringForEnum(value)
End Function
Private Sub ThrowInvalidArgument(ByVal source As String, ByVal value As String)
Err.Raise 5, Information.TypeName(Me) & "." & source, "Invalid input '" & value & "' was supplied."
End Sub
Public Property Get Enums() As Variant
Enums = EnumForString.Items
End Property
Public Property Get Strings() As Variant
Strings = EnumForString.Keys
End Property
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-22T15:20:27.983",
"Id": "413994",
"Score": "1",
"body": "Very nice implementation. There is very little I would change, and then it would likely be more as personal preferences. For example, I've tended to define a single source for all the `Enum` declarations and converters in a module instead of a persistent class. In that module, I'll often include a central list of custom error codes and descriptions to ensure consistency of numbering across the app. These aren't nits at all, more stylistic differences. Good work."
}
] | [
{
"body": "<p>Amazing work! As PeterT mentioned very little to change in your code, however with that said I did notice some code that keeps repeating itself, not sure if this is intentional.</p>\n<p><strong>Checking if the Model is null</strong></p>\n<p><code>If Not this.model Is Nothing Then</code>, this code appears 6 times through out the UserForm, I believe you can validate if the model is null in your <code>IView_ShowDialog</code> procedure, right before you sync the model with the UI, execution will stop if the <code>viewModel</code> is not set.</p>\n<pre><code>Private Function IView_ShowDialog(ByVal viewModel As Object) As Boolean\nIf viewModel Is Nothing Then Exit Function 'exits if viewModel is null\n\nSet this.model = viewModel\n\nSyncUIWithModel\n\nMe.Show\nIView_ShowDialog = Not this.IsCancelled\nEnd Function\n</code></pre>\n<p><strong>Public Properties</strong></p>\n<p>You are declaring a <code>Public Property Get PointLoadsCount</code> but have a <code>PointLoads</code> private variable under <code>THelper</code>. Why not just use <code>PointLoadsCount</code>, you'll have less naming and less variables to manage, plus it looks cleaner and makes more sense when using <code>this</code> keyword. This is just personal preference, but I do find it easier to manage.</p>\n<pre><code>Private Type THelper\n PointLoadsCount As Long\nEnd Type\n\nPrivate this As THelper\n\nPublic Property Get PointLoadsCount() As Long\n PointLoadsCount = this.PointLoadsCount 'renamed to match Private varaible\nEnd Property\n</code></pre>\n<p>Last note, I believe you can eliminate the following line of code, as you are already setting the model, right before you show the form, additionally this would throw a Runtime Error if executed.</p>\n<pre><code>Public Property Let model(ByVal value As LoadingModel)'should be a Set not Let \n Set this.model = value\nEnd Property\n</code></pre>\n<p>Overall excellent implementation, especially with your <code>Enum</code> converters!</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2020-07-07T03:49:09.653",
"Id": "245111",
"ParentId": "213540",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T20:23:45.177",
"Id": "213540",
"Score": "8",
"Tags": [
"object-oriented",
"vba",
"excel",
"mvp"
],
"Title": "Free body diagram generator using MVP for VBA"
} | 213540 |
<p>This is my first Python script and I would like to hear the opinion of more experienced users, so I can do it right from the beginning instead of trying to correct my mistakes after months (years?) of coding.</p>
<pre><code>#!/usr/bin/env python
import argparse
import csv
import json
import os
import sys
from pprint import pprint
__author__ = 'RASG'
__version__ = '2018.02.15.1843'
# ------------------------------------------------------------------------------
# Argumentos
# ------------------------------------------------------------------------------
arg_parser = argparse.ArgumentParser(
description = 'csv <-> json converter',
epilog = 'Output files: /tmp/rag-*',
formatter_class = lambda prog: argparse.RawTextHelpFormatter(prog, max_help_position=999)
)
arg_parser.add_argument('-v', '--version', action='version', version=__version__)
argslist = [
('-f', '--file', '(default: stdin) Input file', dict(type=argparse.FileType('r'), default=sys.stdin)),
('-ph', '--header', '(default: %(default)s) Print csv header', dict(action='store_true')),
]
for argshort, arglong, desc, options in argslist: arg_parser.add_argument(argshort, arglong, help=desc, **options)
args = arg_parser.parse_args()
# ------------------------------------------------------------------------------
# Funcoes
# ------------------------------------------------------------------------------
def get_file_ext(f):
file_name, file_ext = os.path.splitext(f.name)
return file_ext.lower()
def csv_to_json(csv_file):
csv_reader = csv.DictReader(csv_file)
output_file = open('/tmp/rag-parsed.json', 'wb')
data = []
for row in csv_reader: data.append(row)
json_data = json.dumps(data, indent=4, sort_keys=True)
output_file.write(json_data + '\n')
def json_to_csv(json_file):
json_reader = json.loads(json_file.read())
output_file = open('/tmp/rag-parsed.csv', 'wb')
campos = json_reader[0].keys()
csv_writer = csv.DictWriter(output_file, fieldnames=campos, extrasaction='ignore', lineterminator='\n')
if args.header: csv_writer.writeheader()
for j in json_reader: csv_writer.writerow(j)
# ------------------------------------------------------------------------------
# Executar
# ------------------------------------------------------------------------------
for ext in [get_file_ext(args.file)]:
if ext == '.csv':
csv_to_json(args.file)
break
if ext == '.json':
json_to_csv(args.file)
break
sys.exit('File type not allowed')
</code></pre>
| [] | [
{
"body": "<p>Before any criticism, great job. This is mature-looking code.</p>\n\n<p>Alright, now some criticism ;)</p>\n\n<ul>\n<li><p>Single-line <code>if</code> and <code>for</code> loops are not good style in Python: always break the body out into its own indented block, even if it's only a single line; for example:</p>\n\n<pre><code>for argshort, arglong, desc, options in argslist:\n arg_parser.add_argument(argshort, arglong, help=desc, **options)\n</code></pre></li>\n<li><p>Add <a href=\"https://www.python.org/dev/peps/pep-0257/\" rel=\"nofollow noreferrer\">docstrings</a> to your functions, to document what they do and their inputs/outputs (I prefer the <a href=\"https://sphinxcontrib-napoleon.readthedocs.io/en/latest/example_google.html\" rel=\"nofollow noreferrer\">Google format</a>, but you're free to choose whatever works best for you):</p>\n\n<pre><code>def get_file_ext(f):\n \"\"\"Retrieves the file extension for a given file path\n\n Args:\n f (file): The filepath to get the extension of\n\n Returns:\n str: The lower-case extension of that file path\n \"\"\"\n file_name, file_ext = os.path.splitext(f.name)\n return file_ext.lower()\n</code></pre></li>\n<li><p>There are a couple more built-ins you could use. For example, <code>get_file_ext(f)</code> could be replaced by <code>Path(f.name).suffix</code> (using <a href=\"https://docs.python.org/3/library/pathlib.html\" rel=\"nofollow noreferrer\"><code>pathlib</code></a>, if you're using an up-to-date Python)</p></li>\n<li><p>Unless there's some other good reason, use <code>json.dump(open(...), data, ...)</code> and <code>json.load(open(...))</code> rather than reading/writing the file yourself, like <code>json.loads(open(...).read())</code>. This way, you never need to store the JSON text in memory, it can get saved/read to/from disk lazily by the parser. It's also just cleaner. (Also, you don't need 'wb' mode, just 'w', since JSON is text, not an arbitrary byte stream.)</p></li>\n<li><p>When you do want to manually open a file, it's better practice to use it as a context manager, which will automatically close the file at the proper time:</p>\n\n<pre><code>with open(...) as output_file:\n output_file.write(...)\n</code></pre></li>\n<li><p><a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">Wrap the body of your script in a <code>__main__</code> block</a>:</p>\n\n<pre><code>if __name__ == '__main__':\n for ext in [...]: ...\n</code></pre>\n\n<p>or </p>\n\n<pre><code>def main():\n for ext in [...]: ...\n\nif __name__ == '__main__':\n main()\n</code></pre></li>\n</ul>\n\n<p>That's more the style that's popular and standard in the Python community. You're clearly familiar with good coding, though, and it shows in your style. Good job, and welcome to Python!</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T13:11:07.800",
"Id": "413369",
"Score": "0",
"body": "thank you for the comments, especially about `__main__`. i *do* intend to import the module in a bigger script"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T17:34:06.100",
"Id": "213611",
"ParentId": "213543",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "213611",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T20:49:56.767",
"Id": "213543",
"Score": "3",
"Tags": [
"python",
"beginner",
"json",
"csv"
],
"Title": "CSV/JSON converter"
} | 213543 |
<p>Is the complexity of this code \$O(n^3)$? How can I improve the efficiency and reduce the complexity?</p>
<pre><code>A = [3,2,4,2,4,2,4,5,3]
n= len(A)
def ALG2 (A,i,j): #to check whether all entries between A[i] and A[j] are the same
if i==j:
return True
for k in range (i,j-1):
if A[k] != A[k+1]:
return False
return True
def ALG1(A,n): #find the max length of the arrays that are found in ALG2
l=0
for i in range (0,n-1):
for j in range (i+1,n-1):
if ALG2(A,i,j) and (j-i)>l:
l= j-i
return l
result = ALG1(A,n)
print (result)
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T21:17:52.720",
"Id": "413100",
"Score": "2",
"body": "I'm not sure why this has a down vote :( Could you add a little more description on what this code is doing? If this is a programing challenge including the challenge description and a link would be all that's needed!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T21:38:59.113",
"Id": "413104",
"Score": "0",
"body": "Yes, I believe if you have a loop in a function being called inside of a loop you must also add that as a nested loop."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T21:55:33.943",
"Id": "413105",
"Score": "0",
"body": "Welcome to Code Review! I [changed the title](https://codereview.stackexchange.com/posts/213544/revisions) so that it describes what the code does per [site goals](https://codereview.stackexchange.com/questions/how-to-ask): \"_State what your code does in your title, not your main concerns about it._\". Feel free to [edit] and give it a different title if there is something more appropriate."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T23:01:00.967",
"Id": "413106",
"Score": "0",
"body": "It is not a challenge. It is my assignment actually . It is my first day to use stackexchange. really sorry for causing any inconvenience"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T00:50:55.543",
"Id": "413108",
"Score": "0",
"body": "What is the expected result for `A = [3,2,4,2,4,2,4,5,3]`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T10:48:27.870",
"Id": "413125",
"Score": "0",
"body": "reply to vnp: it will be 1 If A = [2,2,2,2,2,4,3,2,2,2,5] then result will be 5"
}
] | [
{
"body": "<p>Your algorithm is indeed n^3, but you can do it in linear time. <a href=\"https://ideone.com/Ke3q5o\" rel=\"nofollow noreferrer\">https://ideone.com/Ke3q5o</a></p>\n\n<pre><code>A = [3,2,5,4,4,4,4,2,4,4]\n\ndef findLongestContinuousSection(A):\n if len(A) == 0:\n return\n longestStart = 0\n longestStop = 0\n longestLength = 0\n longestVal = 0\n curStart = 0\n curStop = 0\n curLength = 1\n curVal = A[0]\n for k in range(1,len(A)-1):\n if curVal != A[k]: # record cur as longest\n longestVal = curVal\n longestStart = curStart\n longestStop = curStop\n longestLength = curLength\n curStart = k\n curStop = k\n curLength = 1\n curVal = A[k]\n else: # continue to build current streak\n curStop = k\n curLength += 1\n return (longestStart, longestStop, longestLength, longestVal)\n\nprint findLongestContinuousSection(A)\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T11:56:15.737",
"Id": "413128",
"Score": "0",
"body": "I'm confused where the Code Review is. Also this code looks needlessly long."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T12:57:48.460",
"Id": "413138",
"Score": "0",
"body": "I only focused on the complexity."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T17:07:11.403",
"Id": "413156",
"Score": "0",
"body": "so here we return 4 elements in a function. But it cannot be done in python or any programming at all right?"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T11:14:52.057",
"Id": "213577",
"ParentId": "213544",
"Score": "-1"
}
},
{
"body": "<ol>\n<li>You should use better function names <code>ALG1</code> and <code>ALG2</code> don't really say what they're performing.</li>\n<li>You should keep the creation of <code>A</code>, <code>n</code> and <code>result</code> at the bottom of your code.</li>\n<li><p>You should keep your 'main' code in a main guard block:</p>\n\n<pre><code>if __name__ == '__main__':\n A = [3,2,4,2,4,2,4,5,3]\n n= len(A)\n result = ALG1(A,n)\n print(result)\n</code></pre></li>\n<li><p>You should follow <a href=\"https://www.python.org/dev/peps/pep-0008/\" rel=\"nofollow noreferrer\">PEP 8</a>, so that it's easier for others to read your code.</p></li>\n<li><p><code>ALG2</code> can be simplified by slicing the array from <code>i</code> to <code>j</code>, <code>A[i:j]</code>, and then checking if the set has a size of one.</p>\n\n<pre><code>def ALG2(A, i, j):\n return len(set(a[i:j])) == 1\n</code></pre></li>\n<li><p>Your entire code can be drastically simplified by using <a href=\"https://docs.python.org/3/library/itertools.html#itertools.groupby\" rel=\"nofollow noreferrer\"><code>itertools.groupby</code></a>.</p>\n\n<pre><code>import itertools\n\n\ndef ALG1(array):\n sizes = (\n sum(1 for _ in g)\n for _, g in itertools.groupby(array)\n )\n return max(sizes, default=0)\n</code></pre></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T17:05:43.833",
"Id": "413155",
"Score": "0",
"body": "wow so is the itertools installed in python? and what is the itertools really for?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T17:08:08.840",
"Id": "413157",
"Score": "0",
"body": "@WingHoLo Yes it's installed with Python. It's a collection of functions to help with iterators."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T11:41:14.470",
"Id": "213580",
"ParentId": "213544",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "6",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T20:52:19.240",
"Id": "213544",
"Score": "1",
"Tags": [
"python"
],
"Title": "Find maximum length of array where every entries are the same"
} | 213544 |
<p>Made the game much more user-friendly than previous version - has an example grid to demonstrate input, Xs and Os are now used.</p>
<p>Game can now detect draw. </p>
<p>Changed the algorithm to detect winner, it's less buggy overall although there are still some combinations near the end of a game where it incorrectly determines a winner or loser - no idea how to fix this or what causes it. </p>
<p>I would appreciate some tips on how to improve structure of the game and code, and how to avoid mentioned bugs.</p>
<pre><code>#include <stdio.h>
#include <stdlib.h>
#include <time.h>
// Struct with all game state variables.
struct game_data {
int win; // Either 0 or 1.
int turns; // Ranges from 1 to 9(game end).
int turn; // Either 0 or 1 where 0 is human player
char grid[3][3];
};
//Initialising game state variables
struct game_data game = {
0,
1,
0,
{ { ' ', ' ', ' ' },
{ ' ', ' ', ' ' },
{ ' ', ' ', ' ' } }
};
void intro(void){
printf("Welcome to NOUGHTS AND CROSSES\n\n");
printf("The grid you will be playing on is 3x3 and your input will be determined by the co ordinates you put in, in the form 'row column'.\n\n");
printf("For example an input of '1 1' will put a 'Z' on the first row on the first column. Like so:\n\n");
printf(
"+---+---+---+\n"
"| Z | | |\n"
"+---+---+---+\n"
"| | | |\n"
" ---+---+---|\n"
"| | | |\n"
"+---+---+---+\n"
"\n");
}
void player_one_move(struct game_data* game)
{
int y_val, x_val;
printf("You are 'Crosses'. Please input co-ordinates in the form 'row column' for the 3x3 grid:\n");
scanf(" %d %d", &y_val, &x_val);
if (game->grid[y_val - 1][x_val - 1] == ' ') {
game->grid[y_val - 1][x_val - 1] = 'X';
printf("\nYour turn:\n\n");
}
else {
player_one_move(game);
}
}
void computer_move(struct game_data* game)
{
int x_val = rand() % 3;
int y_val = rand() % 3;
if (game->grid[y_val][x_val] == ' ') {
game->grid[y_val][x_val] = 'O';
printf("\nComputer turn:\n\n");
}
else {
computer_move(game);
}
}
void update(struct game_data* game)
{
printf(
"+---+---+---+\n"
"| %c | %c | %c |\n"
"+---+---+---+\n"
"| %c | %c | %c |\n"
"----+---+---|\n"
"| %c | %c | %c |\n"
"+---+---+---+\n"
"\n",
game->grid[0][0], game->grid[0][1], game->grid[0][2],
game->grid[1][0], game->grid[1][1], game->grid[1][2],
game->grid[2][0], game->grid[2][1], game->grid[2][2]);
}
void game_event_won(struct game_data* game)
{
int count;
//BUGGY
/*char current_mark;
if (game->turn == 0) {
current_mark = 'X';}
else{
current_mark = 'O';
}*/
for (int y_val = 0; y_val < 3; y_val++) {
for (int x_val = 0; x_val < 3; x_val++) {
count = 0;
while (game->grid[y_val][x_val] == 'X') {
x_val++;
count++;
//BUGGY
/*if (count == 3 && current_mark == 'X') {
game->win = 1;
printf("You have WON\n");
}
if (count == 3 && current_mark == 'O') {
game->win = 1;
printf("You have LOST\n");
}*/
if (count == 3) {
game->win = 1;
printf("You have WON\n");
}
}
}
}
for (int x_val = 0; x_val < 3; x_val++) {
for (int y_val = 0; y_val < 3; y_val++) {
count = 0;
while (game->grid[y_val][x_val] == 'X') {
y_val++;
count++;
if (count == 3) {
game->win = 1;
printf("You have WON\n");
}
}
}
}
for (int y_val = 0; y_val < 3; y_val++) {
count = 0;
while (game->grid[y_val][y_val] == 'X') {
count++;
y_val++;
if (count == 3) {
game->win = 1;
printf("You have won\n");
}
}
}
for (int y_val = 0; y_val < 3; y_val++) {
count = 0;
while (game->grid[y_val][2 - y_val] == 'X') {
count++;
y_val++;
if (count == 3) {
game->win = 1;
printf("You have won\n");
}
}
}
}
// Repetition of previous function but for 'O's. Less concise but less buggy than previous implementation.
void game_event_lost(struct game_data* game)
{
int count;
for (int y_val = 0; y_val < 3; y_val++) {
for (int x_val = 0; x_val < 3; x_val++) {
count = 0;
while (game->grid[y_val][x_val] == 'O') {
x_val++;
count++;
if (count == 3) {
game->win = 1;
printf("You have LOST\n");
}
}
}
}
for (int x_val = 0; x_val < 3; x_val++) {
for (int y_val = 0; y_val < 3; y_val++) {
count = 0;
while (game->grid[y_val][x_val] == 'O') {
y_val++;
count++;
if (count == 3) {
game->win = 1;
printf("You have LOST\n");
}
}
}
}
for (int y_val = 0; y_val < 3; y_val++) {
count = 0;
while (game->grid[y_val][y_val] == 'O') {
count++;
y_val++;
if (count == 3) {
game->win = 1;
printf("You have LOST\n");
}
}
}
for (int y_val = 0; y_val < 3; y_val++) {
count = 0;
while (game->grid[y_val][2 - y_val] == 'O') {
count++;
y_val++;
if (count == 3) {
game->win = 1;
printf("You have LOST\n");
}
}
}
}
int main(void)
{
srand((unsigned)time(0));
intro();
while (game.win == 0 ) {
if (game.turn == 0) {
player_one_move(&game);
game.turns++;
game.turn = 1;
}
else {
game.turn = 0;
computer_move(&game);
game.turns++;
}
if (game.turns == 9 && game.win == 0){
game.win = 1;
printf("You have drawn\n");
break;
}
update(&game);
game_event_won(&game);
game_event_lost(&game);
}
return 0;
}
</code></pre>
<p>EDIT:</p>
<p>I've changed the game_event_won function. Much simpler and bug free as far I know, even if it's a little uglier. Could probably make it shorter though. </p>
<pre><code> void game_event_won(struct game_data* game)
{
if( ((game->grid[0][0] == game->grid[0][1]) && (game->grid[0][1] == game->grid[0][2]) && (game->grid[0][2] == 'X')) ||
((game->grid[1][0] == game->grid[1][1]) && (game->grid[1][1] == game->grid[1][2]) && (game->grid[1][2] == 'X')) ||
((game->grid[2][0] == game->grid[2][1]) && (game->grid[2][1] == game->grid[2][2]) && (game->grid[2][2] == 'X')) ||
((game->grid[0][0] == game->grid[1][0]) && (game->grid[1][0] == game->grid[2][0]) && (game->grid[2][0] == 'X')) ||
((game->grid[0][1] == game->grid[1][1]) && (game->grid[1][1] == game->grid[2][1]) && (game->grid[2][1] == 'X')) ||
((game->grid[0][2] == game->grid[1][2]) && (game->grid[1][2] == game->grid[2][2]) && (game->grid[2][2] == 'X')) ||
((game->grid[0][0] == game->grid[1][1]) && (game->grid[1][1] == game->grid[2][2]) && (game->grid[2][2] == 'X')) ||
((game->grid[0][2] == game->grid[1][1]) && (game->grid[1][1] == game->grid[2][0]) && (game->grid[2][0] == 'X')) ){
game->win = 1;
printf("You have WON\n");
}
if( ((game->grid[0][0] == game->grid[0][1]) && (game->grid[0][1] == game->grid[0][2]) && (game->grid[0][2] == 'O')) ||
((game->grid[1][0] == game->grid[1][1]) && (game->grid[1][1] == game->grid[1][2]) && (game->grid[1][2] == 'O')) ||
((game->grid[2][0] == game->grid[2][1]) && (game->grid[2][1] == game->grid[2][2]) && (game->grid[2][2] == 'O')) ||
((game->grid[0][0] == game->grid[1][0]) && (game->grid[1][0] == game->grid[2][0]) && (game->grid[2][0] == 'O')) ||
((game->grid[0][1] == game->grid[1][1]) && (game->grid[1][1] == game->grid[2][1]) && (game->grid[2][1] == 'O')) ||
((game->grid[0][2] == game->grid[1][2]) && (game->grid[1][2] == game->grid[2][2]) && (game->grid[2][2] == 'O')) ||
((game->grid[0][0] == game->grid[1][1]) && (game->grid[1][1] == game->grid[2][2]) && (game->grid[2][2] == 'O')) ||
((game->grid[0][2] == game->grid[1][1]) && (game->grid[1][1] == game->grid[2][0]) && (game->grid[2][0] == 'O')) ){
game->win = 1;
printf("You have LOST\n");
}
}
</code></pre>
<p>I've also changed the main loop to fit it, preventing false draws:</p>
<pre><code> int main(void)
{
srand((unsigned)time(0));
intro();
while (game.win == 0 ) {
if (game.turn == 0) {
player_one_move(&game);
game.turns++;
game.turn = 1;
}
else {
game.turn = 0;
computer_move(&game);
game.turns++;
}
update(&game);
game_event_won(&game);
if (game.turns == 10 && game.win == 0){
game.win = 1;
printf("You have DRAWN\n");
break;
}
}
return 0;
}
</code></pre>
| [] | [
{
"body": "<p><strong>Input validation</strong></p>\n\n<p>User input is evil - be it nefarious or just wrong. Spend some effort to validate it.</p>\n\n<pre><code>printf(\"You are 'Crosses'. Please input co-ordinates ...\\n\");\n// scanf(\" %d %d\", &y_val, &x_val);\nif (scanf(\" %d %d\", &y_val, &x_val) != 2) {\n puts(\"Invalid input\");\n exit(EXIT_FAILURE);\n}\nif (y_val < 1 || y_val > 3 || x_val < 1 || x_val > 3) {\n puts(\"Out of range input\");\n exit(EXIT_FAILURE);\n}\n</code></pre>\n\n<p>Better code would selectively allow re-inputting.</p>\n\n<p><strong>Remove <code>//BUGGY</code> comments</strong></p>\n\n<p>Post working code here. For bugs you have trouble solving, consider <a href=\"https://stackoverflow.com/\">Stack overflow</a>.</p>\n\n<p><strong>Use <code>const</code></strong></p>\n\n<p>Functions that do not change their pointed-to data are better coded with <code>const</code>. That allows for clearer function interface, wider application, more compiler time checks and potential better optimization.</p>\n\n<pre><code>// void update(struct game_data* game)\nvoid update(const struct game_data* game)\n</code></pre>\n\n<p><strong>Re-use code</strong></p>\n\n<p>Rather than 8 lines of <code>if( ((game->grid[0][0] == game->grid[0][1]) ...</code> with <code>'X'</code> and then 8 more lines of similar code with <code>'O'</code>, form a helper function.</p>\n\n<pre><code> char three_in_row(const char g[][3]) {\n if(g[0][0] != ' ' && g[0][0] == g[0][1] && g[0][1] == g[0][2]) return g[0][0];\n if(g[1][0] != ' ' && g[1][0] == g[1][1] && g[1][1] == g[1][2]) return g[1][0];\n if(g[2][0] != ' ' && g[2][0] == g[2][1] && g[2][1] == g[2][2]) return g[2][0];\n if(g[0][0] != ' ' && g[0][0] == g[1][0] && g[1][0] == g[2][0]) return g[0][0];\n if(g[0][1] != ' ' && g[0][1] == g[1][1] && g[1][1] == g[2][1]) return g[0][1];\n if(g[0][2] != ' ' && g[0][2] == g[1][2] && g[1][2] == g[2][2]) return g[0][2];\n if(g[0][0] != ' ' && g[0][0] == g[1][1] && g[1][1] == g[2][2]) return g[0][0];\n if(g[0][2] != ' ' && g[0][2] == g[1][1] && g[1][1] == g[2][0]) return g[0][2];\n return ' ';\n }\n\nvoid game_event_won(struct game_data* game) {\n switch (three_in_row(game->grid)) {\n case 'X': game->win = 1; printf(\"You have WON\\n\"); break;\n case 'O': game->win = 1; printf(\"You have LOST\\n\"); break;\n }\n}\n</code></pre>\n\n<p><strong>State assessment</strong></p>\n\n<p>Rather than <code>game_event_won()</code>, consider a function <code>TTT_rate(game)</code> that rates the board from -100 to 100.</p>\n\n<pre><code>0: tie\n100: X won\n-100: O won\n1...99: X winning\n-1...-99: O winning\n</code></pre>\n\n<p><strong>No need for recursion</strong></p>\n\n<p>Use a loop in <code>computer_move(struct game_data* game)</code></p>\n\n<p><strong>Comment and code doe not jibe</strong></p>\n\n<p>Looks like the range is [1...10].</p>\n\n<pre><code>int turns; // Ranges from 1 to 9(game end).\nif (game.turns == 10 && game.win == 0){\n</code></pre>\n\n<p><strong>Format</strong></p>\n\n<p>I'd expect the <code>while</code> block to be indented.</p>\n\n<p>Tip: Use an auto formatter. Manually formatting is unproductive.</p>\n\n<pre><code> while (game.win == 0 ) {\n // if (game.turn == 0) {\n if (game.turn == 0) {\n ...\n</code></pre>\n\n<p><strong>No need for global data</strong></p>\n\n<p>Move <code>struct game_data game</code> from global to inside <code>main()</code>.</p>\n\n<p><strong>Why should user always go first?</strong></p>\n\n<p>Consider allowing user or computer to go first.</p>\n\n<p><strong>Advanced</strong></p>\n\n<p>Call a function for <code>X</code> and <code>O</code> moves. The function pair could be from <code>user_move()</code>, <code>computer_move()</code>, <code>smarter_computer_move1()</code>, <code>smarter_computer_move2()</code>, etc. This would allow 2 to play, computer algorithm 1 vs algorithm 2, user vs various levels of play, etc.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T20:28:26.787",
"Id": "413181",
"Score": "0",
"body": "Would you be able to explain more about the state assessment? What would you judge the rating of the board on?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T20:35:24.460",
"Id": "413184",
"Score": "1",
"body": "@AbdiMo Of course 3-in-a row returns 100,-100. The number of 2 of 3 in a row possibilities that could complete worth 12 each. The number of 1 of 3 in a row possibilities that could complete worth 2 each. The user whose turn it is next rates a point. Or another approach, just rate each square. The key is that this is a _heuristic_ evaluational. You could try 2 different approaches and play them off against each other. Baby [AI](https://en.wikipedia.org/wiki/Artificial_intelligence) steps."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T19:52:13.407",
"Id": "213618",
"ParentId": "213547",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "213618",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T21:29:02.480",
"Id": "213547",
"Score": "3",
"Tags": [
"beginner",
"c",
"game",
"tic-tac-toe"
],
"Title": "Noughts and Crosses Version 2"
} | 213547 |
<p>I am producing a PHP code and I want to implement it in my server to do its function. My question is, are there any vulnerabilities that I should correct?</p>
<p>I tried to establish the session first then I will initiate a SQL connection and I will ask the user to enter his email. Also I added the reset function of his email.</p>
<pre><code><?php
if ($_SESSION['admin'] !== true) {
header('Location: /login.php?');
}
$conn = new mysqli("localhost","admin","password","db");
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$msg = '';
if (isset($_POST['submit'])) {
$email = $_POST['email'];
$sql = "SELECT * FROM users WHERE email = $email;";
$result = @$conn->query($sql);
if ($result->num_rows == 0) {
die("This email: $email is incorrect");
}
$row = $result->fetch_assoc();
$id = $row["id"];
$surename = $row["surename"];
$sql = "SELECT * from users JOIN password_resets ON (password_resets.user_id=users.id) WHERE id=$id;";
$result = @$conn->query($query);
if ($result->num_rows == 0) {
$insert_sql = "INSERT INTO password_resets (user_id, reset_timestamp) VALUES ($id, unix_timestamp());";
if ($conn->query($insert_sql) !== TRUE) {
die("Error: " . $insert_sql . "<br>" . $conn->error);
}
}
$result = $conn->query($query);
$row = $result->fetch_assoc();
$link = "https://".$_SERVER['SERVER_NAME']."/reset.php?id=".$row['id'] ."&timestamp=".$row['reset_timestamp'];
$message = "Hi, $surename,
Here's your password reset link: $link";
$headers = "From: ".$_SESSION['first_name']." ".$_SESSION['last_name']." <".$_SESSION['email'].">";
mail($email,"Your password reset link",$message,$headers);
$msg = "Password reset for $email sent!";
?>
<html>
<head><title>Reset password for a user</title></head>
<body>
<form>
<div class="message"><?=$msg ?></div>
<input type="text" width=80 name="email">
<input type="submit" name="submit" value="Send">
</form>
</body>
</html>
<?php
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T13:32:31.497",
"Id": "413140",
"Score": "0",
"body": "Suppressing errors when you do queries is not a good idea. Establish proper error handling so you are aware of and can fix problems. Don't use something like `$result = @$conn->query($sql);`."
}
] | [
{
"body": "<p>Your code is <em>wide open</em> to <a href=\"https://en.wikipedia.org/wiki/SQL_injection\" rel=\"nofollow noreferrer\">SQL Injection</a> which is the <a href=\"https://www.synopsys.com/blogs/software-security/owasp-top-10-application-security-risks/\" rel=\"nofollow noreferrer\">most dangerous web vulnerability</a>. This occurs when you execute SQL queries with unsanitized user data. By placing the raw <code>$_POST</code> variable directly in your query you are allowing an attacker to inject their own SQL into your query and execute it. They can do anything from stealing data to deleting your database.</p>\n\n<p>To combat this you must use parameterized queries. <a href=\"https://stackoverflow.com/q/60174/250259\">Stack Overflow</a> covers this very well but here's what your code would like if you use <code>mysqli</code> with prepared statements:</p>\n\n<pre><code>$stmt = $dbConnection->prepare('SELECT * FROM users WHERE email = ?');\n$stmt->bind_param('s', $email); // 's' specifies the variable type => 'string'\n\n$stmt->execute();\n\n$result = $stmt->get_result();\n$row = $result->fetch_assoc();\n</code></pre>\n\n<p>You also are wide open to Cross-site scripting (XSS) attacks which is the #7 web vulnerability. This occurs because you take raw <code>$_POST</code> data and output it directly into your HTML. An attacker can place malicious code in this value and attack your users and site once it is rendered by the browser.</p>\n\n<p>When outputting user data, always escape that data. <a href=\"https://stackoverflow.com/q/1996122/250259\">Stack Overflow</a> covers this as well. In PHP you can do this by using <a href=\"http://php.net/manual/en/function.htmlspecialchars.php\" rel=\"nofollow noreferrer\"><code>htmlspecialchars()</code></a>.</p>\n\n<pre><code><?= htmlspecialchars($msg, ENT_QUOTES, 'UTF-8'); ?>\n</code></pre>\n\n<p>You will notice that the one <code>$_POST</code> variable, <code>$_POST['email']</code>, has left your site wide open to attack. Before you even attempt to use it you should validate it indeed is a valid email address. If it is not, you should report an error and not attempt to use it as it obviously is invalid and useless anyway.</p>\n\n<p>PHP offers an easy way to validate an email addresses. <a href=\"http://php.net/manual/en/function.filter-var.php\" rel=\"nofollow noreferrer\"><code>filter_var()</code></a> with the <code>FILTER_VALIDATE_EMAIL</code> flag will validate <a href=\"http://php.net/manual/en/filter.examples.validation.php\" rel=\"nofollow noreferrer\">if an email address is valid</a>. </p>\n\n<pre><code>$email = $_POST['email'];\nif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {\n // email is invalid. report error and abort.\n}\n</code></pre>\n\n<p>On a different note, you start your script off by checking to see if a user is an admin. If they are not you use <code>header()</code> to do a redirect away from that page. That's usually okay but you should follow it with a call to <code>exit()</code> to ensure the script stops executing. If not, the code below may still execute and, combined with other vulnerabilities in the page, leave you open to attack.</p>\n\n<pre><code>if ($_SESSION['admin'] !== true) {\n header('Location: /login.php?');\n exit;\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T23:36:51.143",
"Id": "213550",
"ParentId": "213549",
"Score": "4"
}
},
{
"body": "<p>To be honest, this code could be used as a teaching aid to demonstrate every possible mistake that could be made in a PHP script.</p>\n\n<p>Beside problems already mentioned in the other answer, there is a truckload more. </p>\n\n<h3>A database connection.</h3>\n\n<p>It is not your fault, you are following just a terrible outdated example still shown in the PHP manual. Yet, even such a familiar task must be done properly:</p>\n\n<ul>\n<li>the proper error reporting mode for mysqli must be set</li>\n<li>the proper charset must be set</li>\n<li>the improper error reporting must be wiped from the code. You don't want to show the system error message to every site user.</li>\n</ul>\n\n<p>I even wrote a distinct article, <a href=\"https://phpdelusions.net/mysqli/mysqli_connect\" rel=\"nofollow noreferrer\">how to use mysqli_connect properly</a>, because, to be honest, there is not a single good example on the whole Internet.</p>\n\n<p>Not to mention that you shouldn't write the same database connection script on the every PHP page. Instead, put it in a file, and then only include this file.</p>\n\n<h3>A non-working query</h3>\n\n<p>A query like this <code>$sql = \"SELECT * FROM users WHERE email = $email;\";</code> will never return any result, simply because its syntax is wrong. This is another reason to use prepared statements. </p>\n\n<h3>A flawed error reporting.</h3>\n\n<p>To let you know, @ symbols is a pure evil that will make your life a nightmare on the long run. Errors must be fixed, not swept under the rug! And in order to fix the error you must be aware of its existence. While @ operator will leave you totally ignorant.</p>\n\n<h3>Superfluous queries</h3>\n\n<p>In this code you are running three SELECT queries to the same table. Which is just illogical. Why do you need a <code>$sql = \"SELECT * FROM users WHERE email = $email;\";</code> if on the second line you will run almost identical query? </p>\n\n<p>All you need is to use LEFT JOIN in your second query and it will happily serve for both tasks.</p>\n\n<p>And after inserting into password_resets table you are trying to run the second query again. Which is also superfluous, if you care to define the reset timestamp in the script.</p>\n\n<h3>The code refactored.</h3>\n\n<p>To sum everything up, here is the database interaction part of your code slightly refactored:</p>\n\n<p>db.php:</p>\n\n<pre><code>mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);\ntry {\n $conn = mysqli_connect(\"localhost\",\"admin\",\"password\",\"db\");\n mysqli_set_charset($mysqli, \"utf8mb4\");\n} catch (\\mysqli_sql_exception $e) {\n throw new \\mysqli_sql_exception($e->getMessage(), $e->getCode());\n}\n</code></pre>\n\n<p>password reset script (database interaction part)</p>\n\n<pre><code>require 'db.php';\n$msg = '';\nif (isset($_POST['submit'])) {\n $sql = \"SELECT * from users \n LEFT JOIN password_resets ON (password_resets.user_id=users.id)\n WHERE email=?\";\n $stmt = $conn->prepare($sql);\n $stmt->bind_param(\"s\", $_POST['email']);\n $stmt->execute();\n $row = $stmt->get_result()->fetch_assoc();\n\n if (!$row) {\n $msg = \"This email: $email is incorrect\");\n } else {\n if (!$row['reset_timestamp']) {\n $sql = \"INSERT INTO password_resets (user_id, reset_timestamp) VALUES (?, ?);\";\n $stmt = $conn->prepare($sql);\n $time = time();\n $stmt->bind_param(\"ii\", $row['id'], $time);\n $stmt->execute();\n $row['reset_timestamp'] = $time;\n }\n $link = ... // here goes your email sending business\n }\n}\n</code></pre>\n\n<h3>Overall inconsistency</h3>\n\n<p>There are also other issues, like use of $_SESSION['first_name'] and $_SESSION['last_name']. I was under the impression that a password reset code is called when a user do not remember their password and therefore cannot login. In this case I am wondering why there will be their name in the session.</p>\n\n<p>The same confusion is related to the topmost condition: why access to the password reset page should be restricted for the admin use only? In my understanding it must be available to any site user, or otherwise it will be of no value at all.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T14:30:58.143",
"Id": "213587",
"ParentId": "213549",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-15T23:22:09.180",
"Id": "213549",
"Score": "5",
"Tags": [
"php",
"security",
"authentication",
"email",
"mysqli"
],
"Title": "PHP password-resetting page"
} | 213549 |
<p>In order to learn macros in C I decided to make a generic data structures generator for other projects that I have in C.</p>
<p>The main macros are the following:</p>
<ol>
<li><code>CONTAINER_GENERATE(C, P, PFX, SNAME, FMOD, T) ....</code></li>
<li><code>CONTAINER_GENERATE_SOURCE(C, P, PFX, SNAME, FMOD, T) ....</code></li>
<li><code>CONTAINER_GENERATE_HEADER(C, P, PFX, SNAME, FMOD, T) ....</code></li>
</ol>
<p>Where:</p>
<ul>
<li><strong>C</strong> - The container you want;
<ul>
<li>Currently available are <code>LIST</code>, <code>STACK</code> and <code>QUEUE</code>;</li>
</ul></li>
<li><strong>P</strong> - If you want your data structure's fields visible;
<ul>
<li><code>PRIVATE</code> or <code>PUBLIC</code>. Hides the structure definition in the source file;</li>
<li>Only makes a difference in the macros <code>2</code> and <code>3</code>;</li>
</ul></li>
<li><strong>PFX</strong> - Functions prefix, or namespace;</li>
<li><strong>SNAME</strong> - Structure name (<code>typedef SNAME##_s SNAME;</code>);</li>
<li><strong>FMOD</strong> - Functions modifier;
<ul>
<li>Currently I've been using <code>static</code> with macro <code>1</code>;</li>
</ul></li>
<li><strong>T</strong> - Your data type to be worked with.</li>
</ul>
<p>And here is the source file:</p>
<p><strong>macro_containers.h</strong></p>
<pre><code>#ifndef MACRO_CONTAINERS
#define MACRO_CONTAINERS
#define CONCATH_(C, P) C##_GENERATE_HEADER##_##P
#define CONCATC_(C, P) C##_GENERATE_SOURCE##_##P
#define CONCATH(C, P) CONCATH_(C, P)
#define CONCATC(C, P) CONCATC_(C, P)
#define CONTAINER_GENERATE(C, P, PFX, SNAME, FMOD, T) \
CONTAINER_GENERATE_HEADER(C, P, PFX, SNAME, FMOD, T) \
CONTAINER_GENERATE_SOURCE(C, P, PFX, SNAME, FMOD, T)
#define CONTAINER_GENERATE_HEADER(C, P, PFX, SNAME, FMOD, T) \
CONCATH(C, P) \
(PFX, SNAME, FMOD, T)
#define CONTAINER_GENERATE_SOURCE(C, P, PFX, SNAME, FMOD, T) \
CONCATC(C, P) \
(PFX, SNAME, FMOD, T)
/*****************************************************************************/
/********************************************************************** LIST */
/*****************************************************************************/
/* PRIVATE *******************************************************************/
#define LIST_GENERATE_HEADER_PRIVATE(PFX, SNAME, FMOD, T) \
LIST_GENERATE_HEADER(PFX, SNAME, FMOD, T)
#define LIST_GENERATE_SOURCE_PRIVATE(PFX, SNAME, FMOD, T) \
LIST_GENERATE_STRUCT(PFX, SNAME, FMOD, T) \
LIST_GENERATE_SOURCE(PFX, SNAME, FMOD, T)
/* PUBLIC ********************************************************************/
#define LIST_GENERATE_HEADER_PUBLIC(PFX, SNAME, FMOD, T) \
LIST_GENERATE_STRUCT(PFX, SNAME, FMOD, T) \
LIST_GENERATE_HEADER(PFX, SNAME, FMOD, T)
#define LIST_GENERATE_SOURCE_PUBLIC(PFX, SNAME, FMOD, T) \
LIST_GENERATE_SOURCE(PFX, SNAME, FMOD, T)
/* STRUCT ********************************************************************/
#define LIST_GENERATE_STRUCT(PFX, SNAME, FMOD, T) \
\
struct SNAME##_s \
{ \
T *buffer; \
size_t capacity; \
size_t count; \
};
/* HEADER ********************************************************************/
#define LIST_GENERATE_HEADER(PFX, SNAME, FMOD, T) \
\
typedef struct SNAME##_s SNAME; \
\
FMOD SNAME *PFX##_new(size_t size); \
FMOD void PFX##_free(SNAME *list); \
FMOD bool PFX##_push_front(SNAME *list, T element); \
FMOD bool PFX##_push(SNAME *list, T element, size_t index); \
FMOD bool PFX##_push_back(SNAME *list, T element); \
FMOD bool PFX##_pop_front(SNAME *list); \
FMOD bool PFX##_pop(SNAME *list, size_t index); \
FMOD bool PFX##_pop_back(SNAME *list); \
FMOD bool PFX##_insert_if(SNAME *list, T element, size_t index, bool condition); \
FMOD bool PFX##_remove_if(SNAME *list, size_t index, bool condition); \
FMOD T PFX##_back(SNAME *list); \
FMOD T PFX##_get(SNAME *list, size_t index); \
FMOD T PFX##_front(SNAME *list); \
FMOD bool PFX##_empty(SNAME *list); \
FMOD bool PFX##_full(SNAME *list); \
FMOD size_t PFX##_count(SNAME *list); \
FMOD size_t PFX##_capacity(SNAME *list);
/* SOURCE ********************************************************************/
#define LIST_GENERATE_SOURCE(PFX, SNAME, FMOD, T) \
\
FMOD bool PFX##_grow(SNAME *list); \
\
FMOD SNAME *PFX##_new(size_t size) \
{ \
if (size < 1) \
return NULL; \
\
SNAME *list = malloc(sizeof(SNAME)); \
\
if (!list) \
return NULL; \
\
list->buffer = malloc(sizeof(T) * size); \
\
if (!list->buffer) \
{ \
free(list); \
return NULL; \
} \
\
for (size_t i = 0; i < size; i++) \
{ \
list->buffer[i] = 0; \
} \
\
list->capacity = size; \
list->count = 0; \
\
return list; \
} \
\
FMOD void PFX##_free(SNAME *list) \
{ \
free(list->buffer); \
free(list); \
} \
\
FMOD bool PFX##_push_front(SNAME *list, T element) \
{ \
if (PFX##_full(list)) \
{ \
if (!PFX##_grow(list)) \
return false; \
} \
\
if (!PFX##_empty(list)) \
{ \
for (size_t i = list->count; i > 0; i--) \
{ \
list->buffer[i] = list->buffer[i - 1]; \
} \
} \
\
list->buffer[0] = element; \
\
list->count++; \
\
return true; \
} \
\
FMOD bool PFX##_push(SNAME *list, T element, size_t index) \
{ \
if (index > list->count) \
return false; \
\
if (index == 0) \
{ \
return PFX##_push_front(list, element); \
} \
else if (index == list->count) \
{ \
return PFX##_push_back(list, element); \
} \
\
if (PFX##_full(list)) \
{ \
if (!PFX##_grow(list)) \
return false; \
} \
\
for (size_t i = list->count; i > index; i--) \
{ \
list->buffer[i] = list->buffer[i - 1]; \
} \
\
list->buffer[index] = element; \
\
list->count++; \
\
return true; \
} \
\
FMOD bool PFX##_push_back(SNAME *list, T element) \
{ \
if (PFX##_full(list)) \
{ \
if (!PFX##_grow(list)) \
return false; \
} \
\
list->buffer[list->count++] = element; \
\
return true; \
} \
\
FMOD bool PFX##_pop_front(SNAME *list) \
{ \
if (PFX##_empty(list)) \
return false; \
\
for (size_t i = 0; i < list->count; i++) \
{ \
list->buffer[i] = list->buffer[i + 1]; \
} \
\
list->buffer[--list->count] = 0; \
\
return true; \
} \
\
FMOD bool PFX##_pop(SNAME *list, size_t index) \
{ \
if (PFX##_empty(list)) \
return false; \
\
if (index == 0) \
{ \
return PFX##_pop_front(list); \
} \
else if (index == list->count - 1) \
{ \
return PFX##_pop_back(list); \
} \
\
for (size_t i = index; i < list->count - 1; i++) \
{ \
list->buffer[i] = list->buffer[i + 1]; \
} \
\
list->buffer[--list->count] = 0; \
\
return true; \
} \
\
FMOD bool PFX##_pop_back(SNAME *list) \
{ \
if (PFX##_empty(list)) \
return false; \
\
list->buffer[--list->count] = 0; \
\
return true; \
} \
\
FMOD bool PFX##_insert_if(SNAME *list, T element, size_t index, bool condition) \
{ \
if (condition) \
return PFX##_push(list, element, index); \
\
return false; \
} \
\
FMOD bool PFX##_remove_if(SNAME *list, size_t index, bool condition) \
{ \
if (condition) \
return PFX##_pop(list, index); \
\
return false; \
} \
\
FMOD T PFX##_front(SNAME *list) \
{ \
if (PFX##_empty(list)) \
return 0; \
\
return list->buffer[0]; \
} \
\
FMOD T PFX##_get(SNAME *list, size_t index) \
{ \
if (index >= list->count) \
return 0; \
\
if (PFX##_empty(list)) \
return 0; \
\
return list->buffer[index]; \
} \
\
FMOD T PFX##_back(SNAME *list) \
{ \
if (PFX##_empty(list)) \
return 0; \
\
return list->buffer[list->count - 1]; \
} \
\
FMOD bool PFX##_empty(SNAME *list) \
{ \
return list->count == 0; \
} \
\
FMOD bool PFX##_full(SNAME *list) \
{ \
return list->count >= list->capacity; \
} \
\
FMOD size_t PFX##_count(SNAME *list) \
{ \
return list->count; \
} \
\
FMOD size_t PFX##_capacity(SNAME *list) \
{ \
return list->capacity; \
} \
\
FMOD bool PFX##_grow(SNAME *list) \
{ \
size_t new_capacity = list->capacity * 2; \
\
T *new_buffer = realloc(list->buffer, sizeof(T) * new_capacity); \
\
if (!new_buffer) \
return false; \
\
list->buffer = new_buffer; \
list->capacity = new_capacity; \
\
return true; \
}
/*****************************************************************************/
/********************************************************************* STACK */
/*****************************************************************************/
/* PRIVATE *******************************************************************/
#define STACK_GENERATE_HEADER_PRIVATE(PFX, SNAME, FMOD, T) \
STACK_GENERATE_HEADER(PFX, SNAME, FMOD, T)
#define STACK_GENERATE_SOURCE_PRIVATE(PFX, SNAME, FMOD, T) \
STACK_GENERATE_STRUCT(PFX, SNAME, FMOD, T) \
STACK_GENERATE_SOURCE(PFX, SNAME, FMOD, T)
/* PUBLIC ********************************************************************/
#define STACK_GENERATE_HEADER_PUBLIC(PFX, SNAME, FMOD, T) \
STACK_GENERATE_STRUCT(PFX, SNAME, FMOD, T) \
STACK_GENERATE_HEADER(PFX, SNAME, FMOD, T)
#define STACK_GENERATE_SOURCE_PUBLIC(PFX, SNAME, FMOD, T) \
STACK_GENERATE_SOURCE(PFX, SNAME, FMOD, T)
/* STRUCT ********************************************************************/
#define STACK_GENERATE_STRUCT(PFX, SNAME, FMOD, T) \
\
struct SNAME##_s \
{ \
T *buffer; \
size_t capacity; \
size_t count; \
}; \
\
/* HEADER ********************************************************************/
#define STACK_GENERATE_HEADER(PFX, SNAME, FMOD, T) \
\
typedef struct SNAME##_s SNAME; \
\
FMOD SNAME *PFX##_new(size_t size); \
FMOD void PFX##_free(SNAME *stack); \
FMOD bool PFX##_push(SNAME *stack, T element); \
FMOD bool PFX##_pop(SNAME *stack); \
FMOD T PFX##_top(SNAME *stack); \
FMOD bool PFX##_push_if(SNAME *stack, T element, bool condition); \
FMOD bool PFX##_pop_if(SNAME *stack, bool condition); \
FMOD bool PFX##_empty(SNAME *stack); \
FMOD bool PFX##_full(SNAME *stack); \
FMOD size_t PFX##_count(SNAME *stack); \
FMOD size_t PFX##_capacity(SNAME *stack);
/* SOURCE ********************************************************************/
#define STACK_GENERATE_SOURCE(PFX, SNAME, FMOD, T) \
\
FMOD bool PFX##_grow(SNAME *stack); \
\
FMOD SNAME *PFX##_new(size_t size) \
{ \
if (size < 1) \
return NULL; \
\
SNAME *stack = malloc(sizeof(SNAME)); \
\
if (!stack) \
return NULL; \
\
stack->buffer = malloc(sizeof(T) * size); \
\
if (!stack->buffer) \
{ \
free(stack); \
return NULL; \
} \
\
for (size_t i = 0; i < size; i++) \
{ \
stack->buffer[i] = 0; \
} \
\
stack->capacity = size; \
stack->count = 0; \
\
return stack; \
} \
\
FMOD void PFX##_free(SNAME *stack) \
{ \
free(stack->buffer); \
free(stack); \
} \
\
FMOD bool PFX##_push(SNAME *stack, T element) \
{ \
if (PFX##_full(stack)) \
{ \
if (!PFX##_grow(stack)) \
return false; \
} \
\
stack->buffer[stack->count++] = element; \
\
return true; \
} \
\
FMOD bool PFX##_pop(SNAME *stack) \
{ \
if (PFX##_empty(stack)) \
return false; \
\
stack->buffer[--stack->count] = 0; \
\
return true; \
} \
\
FMOD T PFX##_top(SNAME *stack) \
{ \
if (PFX##_empty(stack)) \
return 0; \
\
return stack->buffer[stack->count - 1]; \
} \
\
FMOD bool PFX##_push_if(SNAME *stack, T element, bool condition) \
{ \
if (condition) \
return PFX##_push(stack, element); \
\
return false; \
} \
\
FMOD bool PFX##_pop_if(SNAME *stack, bool condition) \
{ \
if (condition) \
return PFX##_pop(stack); \
\
return false; \
} \
\
FMOD bool PFX##_empty(SNAME *stack) \
{ \
return stack->count == 0; \
} \
\
FMOD bool PFX##_full(SNAME *stack) \
{ \
return stack->count >= stack->capacity; \
} \
\
FMOD size_t PFX##_count(SNAME *stack) \
{ \
return stack->count; \
} \
\
FMOD size_t PFX##_capacity(SNAME *stack) \
{ \
return stack->capacity; \
} \
\
FMOD bool PFX##_grow(SNAME *stack) \
{ \
size_t new_capacity = stack->capacity * 2; \
\
T *new_buffer = realloc(stack->buffer, sizeof(T) * new_capacity); \
\
if (!new_buffer) \
return false; \
\
stack->buffer = new_buffer; \
stack->capacity = new_capacity; \
\
return true; \
}
/*****************************************************************************/
/********************************************************************* QUEUE */
/*****************************************************************************/
/* PRIVATE *******************************************************************/
#define QUEUE_GENERATE_HEADER_PRIVATE(PFX, SNAME, FMOD, T) \
QUEUE_GENERATE_HEADER(PFX, SNAME, FMOD, T)
#define QUEUE_GENERATE_SOURCE_PRIVATE(PFX, SNAME, FMOD, T) \
QUEUE_GENERATE_STRUCT(PFX, SNAME, FMOD, T) \
QUEUE_GENERATE_SOURCE(PFX, SNAME, FMOD, T)
/* PUBLIC ********************************************************************/
#define QUEUE_GENERATE_HEADER_PUBLIC(PFX, SNAME, FMOD, T) \
QUEUE_GENERATE_STRUCT(PFX, SNAME, FMOD, T) \
QUEUE_GENERATE_HEADER(PFX, SNAME, FMOD, T)
#define QUEUE_GENERATE_SOURCE_PUBLIC(PFX, SNAME, FMOD, T) \
QUEUE_GENERATE_SOURCE(PFX, SNAME, FMOD, T)
/* STRUCT ********************************************************************/
#define QUEUE_GENERATE_STRUCT(PFX, SNAME, FMOD, T) \
\
struct SNAME##_s \
{ \
T *buffer; \
size_t capacity; \
size_t count; \
size_t front; \
size_t rear; \
};
/* HEADER ********************************************************************/
#define QUEUE_GENERATE_HEADER(PFX, SNAME, FMOD, T) \
\
typedef struct SNAME##_s SNAME; \
\
FMOD SNAME *PFX##_new(size_t size); \
FMOD void PFX##_free(SNAME *queue); \
FMOD bool PFX##_enqueue(SNAME *queue, T element); \
FMOD bool PFX##_dequeue(SNAME *queue); \
FMOD T PFX##_peek(SNAME *queue); \
FMOD bool PFX##_enqueue_if(SNAME *queue, T element, bool condition); \
FMOD bool PFX##_dequeue_if(SNAME *queue, bool condition); \
FMOD bool PFX##_empty(SNAME *queue); \
FMOD bool PFX##_full(SNAME *queue); \
FMOD size_t PFX##_count(SNAME *queue); \
FMOD size_t PFX##_capacity(SNAME *queue);
/* SOURCE ********************************************************************/
#define QUEUE_GENERATE_SOURCE(PFX, SNAME, FMOD, T) \
\
FMOD bool PFX##_grow(SNAME *queue); \
\
FMOD SNAME *PFX##_new(size_t size) \
{ \
if (size < 1) \
return NULL; \
\
SNAME *queue = malloc(sizeof(SNAME)); \
\
if (!queue) \
return NULL; \
\
queue->buffer = malloc(sizeof(T) * size); \
\
if (!queue->buffer) \
{ \
free(queue); \
return NULL; \
} \
\
for (size_t i = 0; i < size; i++) \
{ \
queue->buffer[i] = 0; \
} \
\
queue->capacity = size; \
queue->count = 0; \
queue->front = 0; \
queue->rear = 0; \
\
return queue; \
} \
\
FMOD void PFX##_free(SNAME *queue) \
{ \
free(queue->buffer); \
free(queue); \
} \
\
FMOD bool PFX##_enqueue(SNAME *queue, T element) \
{ \
if (PFX##_full(queue)) \
{ \
if (!PFX##_grow(queue)) \
return false; \
} \
\
queue->buffer[queue->rear] = element; \
\
queue->rear = (queue->rear == queue->capacity - 1) ? 0 : queue->rear + 1; \
queue->count++; \
\
return true; \
} \
\
FMOD bool PFX##_dequeue(SNAME *queue) \
{ \
if (PFX##_empty(queue)) \
return false; \
\
queue->buffer[queue->front] = 0; \
\
queue->front = (queue->front == queue->capacity - 1) ? 0 : queue->front + 1; \
queue->count--; \
\
return true; \
} \
\
FMOD T PFX##_peek(SNAME *queue) \
{ \
if (PFX##_empty(queue)) \
return 0; \
\
return queue->buffer[queue->front]; \
} \
\
FMOD bool PFX##_enqueue_if(SNAME *queue, T element, bool condition) \
{ \
if (condition) \
return PFX##_enqueue(queue, element); \
\
return false; \
} \
\
FMOD bool PFX##_dequeue_if(SNAME *queue, bool condition) \
{ \
if (condition) \
return PFX##_dequeue(queue); \
\
return false; \
} \
\
FMOD bool PFX##_empty(SNAME *queue) \
{ \
return queue->count == 0; \
} \
\
FMOD bool PFX##_full(SNAME *queue) \
{ \
return queue->count >= queue->capacity; \
} \
\
FMOD size_t PFX##_count(SNAME *queue) \
{ \
return queue->count; \
} \
\
FMOD size_t PFX##_capacity(SNAME *queue) \
{ \
return queue->capacity; \
} \
\
FMOD bool PFX##_grow(SNAME *queue) \
{ \
\
size_t new_capacity = queue->capacity * 2; \
\
T *new_buffer = malloc(sizeof(T) * new_capacity); \
\
if (!new_buffer) \
return false; \
\
for (size_t i = queue->front, j = 0; j < queue->count; i = (i + 1) % queue->capacity, j++) \
{ \
new_buffer[j] = queue->buffer[i]; \
} \
\
free(queue->buffer); \
\
queue->buffer = new_buffer; \
queue->capacity = new_capacity; \
queue->front = 0; \
queue->rear = queue->count; \
\
return true; \
}
#endif /* MACRO_CONTAINERS */
</code></pre>
<p>Here are some examples:</p>
<ul>
<li>I want a list of type double, and I want to use it only in this file
<ul>
<li>In source file: <code>MACRO_GENERATE(LIST, PUBLIC, dl, dlist, static, double)</code></li>
<li>Note that <code>PUBLIC</code> or <code>PRIVATE</code> makes no difference, but you <strong>must</strong> specify one or the other</li>
<li><code>dlist *list = dl_new(100);</code></li>
</ul></li>
<li>I want a queue called <code>queue_line</code> of type <code>person_t</code> with hidden struct fields
<ul>
<li>In source file: <code>MACRO_GENERATE_SOURCE(QUEUE, PRIVATE, q, queue_line, , person_t)</code></li>
<li>In header file: <code>MACRO_GENERATE_HEADER(QUEUE, PRIVATE, q, queue_line, , person_t)</code></li>
<li>Note here that you can (and should) omit <code>static</code> without a problem</li>
<li><code>queue_line *queue = q_new(120);</code></li>
<li><code>queue->count; // Error</code></li>
<li><code>size_t total_elements = q_count(queue); // OK</code></li>
</ul></li>
<li>I want a stack of type <code>const char *</code> and I want access to its fields
<ul>
<li>In source file: <code>MACRO_GENERATE_SOURCE(STACK, PUBLIC, stk, my_stack, , const char *)</code></li>
<li>In header file: <code>MACRO_GENERATE_HEADER(STACK, PUBLIC, stk, my_stack, , const char *)</code></li>
<li><code>my_stack *stack = stk_new(80);</code></li>
<li><code>for (size_t i = 0; i < stack->count; i++) ... // OK</code></li>
</ul></li>
</ul>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T02:00:29.463",
"Id": "213553",
"Score": "2",
"Tags": [
"c",
"collections",
"macros"
],
"Title": "Simple generic macro-generated containers"
} | 213553 |
<p>I wrote a bash script for backing up my LAMP server. To be honest that's my first experience in bash so I want to ask you for help in its improvement. </p>
<pre><code>#!/bin/bash
date=`(date +%Y%m%d%H%M)`
declare -A users=(
["user1"]="password1"
["user2"]="password2"
)
for user in ${!users[@]}
do
directory=$user
directories=`find /var/www/$directory -maxdepth 1 -mindepth 1 -type d`
for directory in $directories
do
cd $directory
if [ ! -d backups ]
then
mkdir backups
fi
tar --exclude ./backups -czf backups/$date.tar.gz .
password=${users[$user]}
databases=`mysql -u $user -p$password -Bse "SHOW DATABASES;"`
for database in $databases
do
if [ $database = ${directory##*/} ]
then
mysqldump -u $user -p$password $database | gzip > backups/$date.sql.gz
fi
done
chmod 770 backups -R
chown $user:$user backups -R
done
done
</code></pre>
| [] | [
{
"body": "<h3>Use <code>$(...)</code> instead of <code>`...`</code></h3>\n\n<p><code>`...`</code> is archaic, error-prone, and harder to read than <code>$(...)</code>.</p>\n\n<p>For example, instead of <code>date=`(date +%Y%m%d%H%M)`</code>, write <code>date=$(date +%Y%m%d%H%M)</code>.\nNote that the extra <code>(...)</code> around the <code>date</code> command was unnecessary.</p>\n\n<h3>Double-quote variables used in command arguments</h3>\n\n<p>For example instead of <code>for user in ${!users[@]}</code>,\nwrite <code>for user in \"${!users[@]}\"</code>.</p>\n\n<p>This way, if the <code>users</code> array has keys with spaces in it,\nthe program will still work correctly.\nIn the current example none of the keys contain spaces (they are <code>user1</code> and <code>user2</code>),\nso you don't strictly need it,\nbut it's a good habit to build.</p>\n\n<h3>Don't parse the output of find</h3>\n\n<p>This line shows a very bad practice:</p>\n\n<blockquote>\n<pre><code>directories=`find /var/www/$directory -maxdepth 1 -mindepth 1 -type d`\n</code></pre>\n</blockquote>\n\n<p>Let's first correct the form:</p>\n\n<pre><code>directories=$(find \"/var/www/$directory\" -maxdepth 1 -mindepth 1 -type d)\n</code></pre>\n\n<p>The problem here is that if any of the files printed by the command contain a newline character, then it will be impossible to tell complete filenames from partial filenames in <code>$directories</code>. If any of the filenames contain whitespace, then parsing the value of <code>$directories</code> will be complicated.</p>\n\n<p>It's best to avoid parsing the output of <code>find</code> when possible.\nEven if this code works in your example because <em>you know</em> that the filenames will be strictly alphanumeric, it's good to avoid such bad practices if possible.</p>\n\n<p>In this case there's a fairly simple alternative:</p>\n\n<pre><code>for directory in \"/var/www/$directory\"/*/\n</code></pre>\n\n<p>This is basically a simple glob expansion,\nwith the small trick that the trailing <code>/</code> will make it match only directories.</p>\n\n<p>Notice that <code>*/</code> is outside the double-quoted part. This is because <code>*</code> would not be expanded within double-quotes. For the record, this is an equivalent way to write the above:</p>\n\n<pre><code>for directory in /var/www/\"$directory\"/*/\n</code></pre>\n\n<p>Finally, there is a small caveat: this is not exactly equivalent to the <code>find</code> command, because that would also find directories whose name starts with <code>.</code>,\nand the glob expansion won't, by default.\nIf you need to support such filenames, then write <code>shopt -s dotglob</code> before the loop statement. That will enable matching filenames starting with <code>.</code> in glob expansions.</p>\n\n<h3>Avoid changing the working directory (with <code>cd</code>) in scripts</h3>\n\n<p>Changing directories with <code>cd</code> in scripts is error-prone:</p>\n\n<ul>\n<li><p>It may become confusing what is the current working directory, at any point in the script</p></li>\n<li><p>The <code>cd</code> command may fail, for example due to permission issues or filesystem errors. If such failures are not handled (as in the posted script), the program may happily continue executing the rest of the commands, which can have serious consequences. Consider for example what will happen to <code>cd \"$foo\"; rm -fr *</code> if the <code>cd</code> command fails: important stuff could get deleted!</p></li>\n</ul>\n\n<p>In the posted code, instead of this:</p>\n\n<blockquote>\n<pre><code>cd $directory\n\nif [ ! -d backups ]\nthen\n mkdir backups\nfi\n\ntar --exclude ./backups -czf backups/$date.tar.gz .\n</code></pre>\n</blockquote>\n\n<p>You could write without using <code>cd</code> like this:</p>\n\n<pre><code>mkdir -p \"$directory/backups\"\ntar -C \"$directory\" --exclude ./backups -czf \"backups/$date.tar.gz\" .\n</code></pre>\n\n<p>That is, use the <code>-C</code> flag of <code>tar</code> to specify its <em>effective directory</em>,\nand use the correct paths in other commands appropriately.\nKeep in mind that the rest of the commands in the loop body that rely on the path of <code>backups</code> will also need to be adjusted accordingly.\nFor example change <code>gzip > backups/$date.sql.gz</code> to <code>gzip > \"$directory/backups/$date.sql.gz\"</code>.</p>\n\n<p>Notice that I double-quoted the parameters using the <code>$date</code> variable,\nas explained earlier in this posted.\nAnd I replaced a conditional statement by taking advantage of the <code>-p</code> flag of <code>mkdir</code>.</p>\n\n<h3>Don't give permissions willy-nilly</h3>\n\n<p>Using <code>chmod</code> with unnecessarily relaxed permissions is a very bad practice.\nQuestion every permission bit if it's really needed and why.</p>\n\n<p>Let's take a closer look at this:</p>\n\n<blockquote>\n<pre><code>chmod 770 backups -R\nchown $user:$user backups -R\n</code></pre>\n</blockquote>\n\n<p>The <code>chmod</code> gives read-write-execute permission to the user and the group of files and directories under <code>backups</code>, recursively.\nWhy? The loop body creates <code>.gz</code> files under <code>backups</code>.\nThese files don't need to be executable.\nOnly the <code>backups</code> directory needs to be executable, so that the user can access its contents.</p>\n\n<p>It would be better to set an appropriate <code>umask</code> before the loop.\nYou will be able to drop the <code>chmod</code> command,\nbecause the <code>umask</code>, combined with the <code>chown</code> will be enough to ensure correct permissions.</p>\n\n<p>Strictly speaking, the <code>chown</code> is only necessary for the newly created files and directories, instead of a blanket <code>chown -R</code> on the parent directory.\nBut this level of laziness is probably acceptable in a Bash script,\nso until the <code>chown -R</code> becomes a practical concern (for example due to an excessively large number of files in the directory tree), I wouldn't complicate the script with more precise treatment.</p>\n\n<h3>Test your backup solutions</h3>\n\n<p>Can you spot the bug in this code?</p>\n\n<blockquote>\n<pre><code>for database in $databases\ndo\n if [ $database = ${directory##*/} ]\n then\n mysqldump -u $user -p$password $database | gzip > backups/$date.sql.gz\n fi\ndone\n</code></pre>\n</blockquote>\n\n<p>The <code>$database</code> variable is not used in the output filename.\nIf there are multiple databases,\nonly the last one will be saved.\nA few months later, if you try to fix a corrupted database by recovering from backups,\nyou would be in for a terrible surprise,\ndiscovering that some database backups are completely missing.</p>\n\n<p>Be sure to test thoroughly your backup solution, accounting for the most complex supported scenarios.</p>\n\n<p>(And as pointed out multiple times earlier, double-quote variables used in command arguments.)</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T10:41:55.313",
"Id": "213575",
"ParentId": "213555",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213575",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T03:45:18.783",
"Id": "213555",
"Score": "3",
"Tags": [
"beginner",
"mysql",
"bash"
],
"Title": "Bash script to backup a LAMP server"
} | 213555 |
<p>I am trying to solve a question given on <a href="https://codeforces.com/contest/1101/problem/F" rel="nofollow noreferrer">Codeforces</a> involving dynamic programming with 3D arrays. </p>
<blockquote>
<h2><a href="https://codeforces.com/contest/1101/problem/F" rel="nofollow noreferrer">F. Trucks and Cities</a></h2>
<p>There are <span class="math-container">\$n\$</span> cities along the road, which can be represented as a straight line. The <span class="math-container">\$i\$</span>-th city is situated at the distance of <span class="math-container">\$a_i\$</span> kilometers from the origin. All cities are situated in the same direction from the origin. There are <span class="math-container">\$m\$</span> trucks travelling from one city to another.</p>
<p>Each truck can be described by <span class="math-container">\$4\$</span> integers: starting city <span class="math-container">\$s_i\$</span>, finishing city <span class="math-container">\$f_i\$</span>, fuel consumption <span class="math-container">\$c_i\$</span> and number of possible refuelings <span class="math-container">\$r_i\$</span>. The <span class="math-container">\$i\$</span>-th truck will spend <span class="math-container">\$c_i\$</span> litres of fuel per one kilometer.</p>
<p>When a truck arrives in some city, it can be refueled (but refueling is impossible in the middle of nowhere). The <span class="math-container">\$i\$</span>-th truck can be refueled at most <span class="math-container">\$r_i\$</span> times. Each refueling makes truck's gas-tank full. All trucks start with full gas-tank.</p>
<p>All trucks will have gas-tanks of the same size <span class="math-container">\$V\$</span> litres. You should find minimum possible <span class="math-container">\$V\$</span> such that all trucks can reach their destinations without refueling more times than allowed.</p>
<h3>Input</h3>
<p>First line contains two integers <span class="math-container">\$n\$</span> and <span class="math-container">\$m\$</span> (<span class="math-container">\$2 ≤ n
≤ 400\$</span>, <span class="math-container">\$1 ≤ m ≤ 250000\$</span>) — the number of cities and trucks.</p>
<p>The second line contains <span class="math-container">\$n\$</span> integers <span class="math-container">\$a_1,a_2,…,a_n\$</span> (<span class="math-container">\$1 ≤ a_i ≤ 10^9\$</span>, <span class="math-container">\$a_i < a_i + 1\$</span>) — positions of cities in the ascending order.</p>
<p>Next <span class="math-container">\$m\$</span> lines contains <span class="math-container">\$4\$</span> integers each. The <span class="math-container">\$i\$</span>-th line contains integers <span class="math-container">\$s_i, f_i, c_i, r_i\$</span> (<span class="math-container">\$1 ≤ s_i < f_i ≤ n\$</span>, <span class="math-container">\$1 ≤ c_i ≤ 10^9\$</span>, <span class="math-container">\$0 ≤ r_i ≤ n\$</span>) — the description of the <span class="math-container">\$i\$</span>-th truck.</p>
<h3>Output</h3>
<p>Print the only integer — minimum possible size of gas-tanks <span class="math-container">\$V\$</span> such that all trucks can reach their destinations.</p>
<h3>Requirements</h3>
<p>time limit per test — 2 seconds
memory limit per test — 256 megabytes
input — standard input
output — standard output</p>
</blockquote>
<p>Here is my code:</p>
<pre><code>#include<iostream>
#include<vector>
using namespace std;
int mat[403][403][403];
//mat[current_location][final_location][refuel_count_left]
vector<int> city;
int fun(int s,int f, int r){
if(s==f){
return mat[s][f][r] = 0;
}
if(mat[s][f][r]!=0){
return mat[s][f][r];
}
if(s+1==f || r==0){
return mat[s][f][r] = city[f]-city[s];
}
int opt = city[s] + (city[f]-city[s])/(r+1);
int pos = lower_bound(city.begin()+s,city.begin()+f+1,opt) - city.begin();
mat[s][f][r] = max(fun(pos,f,r-1), city[pos] - city[s]);
//cout<<"s=" <<s<<" f="<<f<<" r="<<r<<" mat"<<mat[s][f][r]<<endl;
return mat[s][f][r];
}
int main(){
long long ans=0;
int no_cities,no_vehicle;
cin>>no_cities>>no_vehicle;
city.push_back(0);
for(int i=1;i<=no_cities;++i){
int b;cin>>b;
city.push_back(b);
}
for(int i=0;i<no_vehicle;++i){
int start,finish,costperkm,refuel_count;
cin>>start>>finish>>costperkm>>refuel_count;
long long vol_curr_vehicle = (long long)fun(start,finish,refuel_count)* (long long)costperkm;
//cout<<jj<<" ";
ans = max(ans,vol_curr_vehicle);
}
printf("%lld",ans);
return 0;
}
</code></pre>
<p>I've used a 3D array named <code>mat</code> which stores the different DP states.</p>
<ul>
<li>1st Dimension - index of starting location</li>
<li>2nd Dimension - index of final location to reach</li>
<li>3rd Dimension - No. of refueling left</li>
</ul>
<p>The th element in the <code>city</code> array represents that the th city is situated at the distance of ai kilometers from the origin.</p>
<p>Explanation for the code: </p>
<p>The <code>fun(s,f,r)</code> function takes in 3 arguments representing the current position as s, finish position as <code>f</code> and <code>refuel_count_left</code> as <code>r</code>.</p>
<p>The problem can be understood as dividing the array <code>city</code> into <code>r+1 segments</code> with the starting index as <code>s</code> and ending index as <code>f</code>.</p>
<p>That is, dividing city[s...f] into r+1 segments. This division should be in such a manner that from all segment max(city[ending index of current segment] - city[starting index of current segment]) is minimised.</p>
<p>Inside the function <code>fun(s,f,r)</code> which computes and returns mat[s][f][r], the base cases are when:</p>
<ul>
<li><code>s==f</code> then return 0; because dividing city[s...f] into r+1 segments is just no segment.</li>
<li><code>mat[s][f][r]!=0</code> when mat[s][f][r] has already been computed then return it.</li>
<li><code>s+1==f || r==0</code> then return city[f] - city[s]. which mean that either we have no refuling left then we have to reach the final position from the starting position. Or when we are just before the final position then we just directly reach the final position without refueling.</li>
</ul>
<p>If none of the above match then we have to find the position of a element <code>opt</code> which is equal to <code>city[s] + (city[f]-city[s])/(r+1)</code>. i.e. - There will be one segment present to the left opt(<code>a[s...p]</code>) and r segments to the right of opt (<code>a[p....f]</code>).</p>
<ul>
<li><code>a[s...p]</code> is the first segment out of the r+1 segments and a[p...f] contain the rest r segments out of the r+1 segments.**</li>
<li><code>pos</code> is the first position that I've described.</li>
<li><code>mat[s][f][r]</code> is maximum of <code>fun(pos,f,r-1)</code> and <code>city[pos] - city[s]</code>. where <code>fun(pos,f,r-1)</code> mean that <code>city[s...pos]</code> is the first of the r segments and <code>city[pos...f]</code> are the rest <code>r-1</code> segments and so now we are going to compute for <code>city[pos...f]</code> with <code>r=r-1</code> refuelings left.</li>
</ul>
<p>So, I'm finding the maximum of the difference between the last and first elements of the segments and equating that to <code>mat[s][f][r]</code>.</p>
<p><a href="https://codeforces.com/contest/1101/submission/49959457" rel="nofollow noreferrer">Here</a> is the right answer.</p>
<p>I realized the my code took 1481 ms of time for execution.</p>
<p><strong>What is way that I can use to reduce the time complexity or the time taken by code during execution?</strong></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T20:32:41.843",
"Id": "413183",
"Score": "0",
"body": "Your title is not a good fit for this site. Mind rephrasing it to describe*what the code does* and not what data structure you used or which paradigm. See [help/how-to-ask]."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T06:04:34.817",
"Id": "413200",
"Score": "0",
"body": "I think I've clearly described what the code does. I've used the DP approach which stores the different states in the `mat` 3-D array. What part didn't you understand?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T17:32:11.583",
"Id": "413265",
"Score": "0",
"body": "[How to Ask](https://codereview.stackexchange.com/help/how-to-ask)"
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T04:44:14.247",
"Id": "213557",
"Score": "0",
"Tags": [
"c++",
"performance",
"algorithm",
"dynamic-programming"
],
"Title": "Recursive Dynamic programming with 3D arrays consuming time"
} | 213557 |
<p>I made a simple async networking server and I'd like to get some input on the code, whether things can be done better and whether the code is stable (able to hold more than 1000 connections without lag) for a MMORPG game.</p>
<p>GameNetworkListener.cs:</p>
<pre><code>using System;
using System.Net;
using System.Net.Sockets;
using System.Threading.Tasks;
namespace Rain.Networking.Game
{
public class GameNetworkListener
{
private TcpListener _listener;
public async Task StartListening(int port)
{
_listener = new TcpListener(IPAddress.Any, port);
_listener.Start();
TcpClient lastClient;
while ((lastClient = await _listener.AcceptTcpClientAsync()) != null)
{
Console.WriteLine($"New connection from {lastClient.Client.RemoteEndPoint}");
var gameNetworkClient = new GameNetworkClient(lastClient);
await gameNetworkClient.StartReceiving();
}
}
public void Stop()
{
_listener.Stop();
}
}
}
</code></pre>
<p>GameNetworkClient.cs:</p>
<pre><code>using System;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
namespace Rain.Networking.Game
{
public class GameNetworkClient
{
private readonly TcpClient _client;
private readonly NetworkStream _stream;
public GameNetworkClient(TcpClient client)
{
_client = client;
_stream = client.GetStream();
}
public async Task StartReceiving()
{
while (_client.Connected)
{
var bytes = new byte[512];
var amount = await _stream.ReadAsync(bytes, 0, bytes.Length);
var raw = Encoding.UTF8.GetString(bytes);
if (amount > 0)
{
if (raw.StartsWith("<policy-file-request/>"))
{
await SendData(Encoding.UTF8.GetBytes("<?xml version=\"1.0\"?>\r\n" +
"<!DOCTYPE cross-domain-policy SYSTEM \"/xml/dtds/cross-domain-policy.dtd\">\r\n" +
"<cross-domain-policy>\r\n" +
"<allow-access-from domain=\"*\" to-ports=\"*\" />\r\n" +
"</cross-domain-policy>\x0"));
_client.Dispose();
}
else
{
Console.WriteLine($"Received {raw}");
}
}
else
{
_client.Dispose();
}
}
}
public async Task SendData(byte[] data)
{
await _stream.WriteAsync(data, 0, data.Length);
}
}
}
</code></pre>
<p>Following rules start the server:</p>
<pre><code>_gameNetworkListener = serviceProvider.GetService<GameNetworkListener>();
await _gameNetworkListener.StartListening(30000);
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T18:37:10.683",
"Id": "413173",
"Score": "2",
"body": "Tell us please what else is your server doing besides being one..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T11:04:17.367",
"Id": "413212",
"Score": "0",
"body": "\"and whether the code is stable\" Have you tried? With how many connections?"
}
] | [
{
"body": "<p>I see two major issues when you want to use this code for a MMORPG game.</p>\n\n<h3>Exception Handling</h3>\n\n<p>Make your code robust against connection hick-ups (when connection goes down for a fraction). It's up to be the client to reconnect asap on connection loss (out of scope of your code). The server should dispose client connections on error in order to clean up resources. </p>\n\n<h3>Resource Management</h3>\n\n<p>The server does not care about the number of clients connected, nor does it own the life time scope of these connections.</p>\n\n<p>I would expect the code below to close the connections.</p>\n\n<blockquote>\n<pre><code>public void Stop()\n{\n _listener.Stop();\n // _connectedClients.ForEach(Disconnect); // cleanup resources\n}\n</code></pre>\n</blockquote>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-06-16T12:08:07.660",
"Id": "222398",
"ParentId": "213560",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T07:05:43.250",
"Id": "213560",
"Score": "2",
"Tags": [
"c#",
"game",
"asynchronous",
"networking",
"async-await"
],
"Title": "C# Async/Await networking server"
} | 213560 |
<p>This is an implementation of HttpClient Json Post by Action parameter.</p>
<p><strong>Logic:</strong></p>
<blockquote>
<ul>
<li>It is mainly convenient to pass the url and object (automatically converted to json by Json.Net), and can use Action as a parameter to customize function. </li>
<li>default timeout is 15 sec , if you want to change the time , it could change timeout parameter value.</li>
</ul>
</blockquote>
<p><strong>Code:</strong></p>
<pre><code>using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
public class Program
{
public static void Main(string[] args)
{
Test().Wait();
}
public static async Task Test()
{
//SuccessExecute
await Execute("https://jsonplaceholder.typicode.com/posts", new { value = "ITWeiHan" }); //Result : {"value": "ITWeiHan","id": 101}
//ErrorExecute
await Execute("https://jsonplaceholder.typicode.com/error404", new { value = "ITWeiHan" }); //Result : Error 404
}
public static async Task Execute(string url, object reqeustBody)
{
await HttpClientHelper.PostByJsonContentTypeAsync(url, reqeustBody
, successFunction: responsebody =>
{
//Your Success Logic
Console.WriteLine("Success");
Console.WriteLine(responsebody);
}, errorFunction: httpRequestException =>
{
//Your Error Solution Logic
Console.WriteLine("Error");
Console.WriteLine(httpRequestException.Message);
}
);
}
}
public static class HttpClientHelper
{
public static async Task PostByJsonContentTypeAsync(string url, object reqeustBody, Action<string> successFunction, Action<HttpRequestException> errorFunction, int timeout = 15)
{
var json = JsonConvert.SerializeObject(reqeustBody);
using (var client = new HttpClient() { Timeout = TimeSpan.FromSeconds(timeout) })
using (var request = new HttpRequestMessage(HttpMethod.Post, url))
using (var stringContent = new StringContent(json, Encoding.UTF8, "application/json"))
{
request.Content = stringContent;
try
{
using (var httpResponseMessage = await client.SendAsync(request))
{
HttpResponseMessage response = await client.GetAsync(url);
response.EnsureSuccessStatusCode();
var responseBody = await httpResponseMessage.Content.ReadAsStringAsync();
successFunction(responseBody);
}
}
catch (HttpRequestException e)
{
errorFunction(e);
}
}
}
}
</code></pre>
| [] | [
{
"body": "<p>Great job. Here are some minor notes though.</p>\n\n<p>In newer versions of C# you can leverage <code>async Main</code> in order not to wait for your test method.</p>\n\n<pre><code>public static async Task Main(string[] args)\n{\n await Test();\n}\n</code></pre>\n\n<p>You can speed things up a bit with executing your tests in parallel</p>\n\n<pre><code>public static async Task Test()\n{\n var successExecute = Execute(\"https://jsonplaceholder.typicode.com/posts\", new { value = \"ITWeiHan\" }); //Result : {\"value\": \"ITWeiHan\",\"id\": 101}\n var errorExecute = Execute(\"https://jsonplaceholder.typicode.com/error404\", new { value = \"ITWeiHan\" }); //Result : Error 404\n await Task.WhenAll(successExecute, errorExecute);\n}\n</code></pre>\n\n<p>Also, <code>PostByJsonContentTypeAsync</code> throws couple of more exceptions. Namely <code>InvalidOperationException</code> and <code>ArgumentNullExceptions</code>. Are you intentionally not handling them?</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-11T02:48:48.567",
"Id": "449163",
"Score": "0",
"body": "thanks , yes , i only Focus on HttpRequestException ,user can edit exception class lilke Exception."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-10-10T09:00:41.013",
"Id": "230482",
"ParentId": "213563",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": "230482",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T08:39:55.817",
"Id": "213563",
"Score": "3",
"Tags": [
"c#",
"json",
"async-await",
"rest"
],
"Title": "Mini HttpClient json post by Action parameter"
} | 213563 |
<p>I want to generate all the subarrays from an array of integer as below:</p>
<pre><code>func subarrays(_ arr: [Int]) -> [[Int]]{
var result = [[Int]]()
guard arr.count >= 1 else { return [arr] }
for i in 0..<arr.count {
for res in result {
var resi = res
resi.append(arr[i])
result.append(resi)
}
result.append([ arr[i] ])
}
result.append([])
return result
}
subarrays([1,2]) //{},{1,2},{1},{2}
subarrays([1,2,3]) //{} {1}{2}{3}{1,2}{2,3}{1,3}{1,2,3}
</code></pre>
<p>I have alternative implementations, but really want to know if it is acceptable to use </p>
<pre><code>for res in result
</code></pre>
<p>while adding to the array, or whether this would be seen as unusual practice in any way.</p>
| [] | [
{
"body": "<p>To answer your immediate question: Yes, it is fine to mutate an array while enumerating its elements. The reason is that</p>\n\n<pre><code>for res in result { ... }\n</code></pre>\n\n<p>is equivalent to</p>\n\n<pre><code>var iter = result.makeIterator()\nwhile let res = iter.next() {\n // ...\n}\n</code></pre>\n\n<p>and that arrays are <em>value types</em> in Swift: Mutating <code>result</code> inside the loop creates a new value and does not affect the original array that the iterator is using. See <a href=\"https://stackoverflow.com/q/37997465/1187415\">Remove element from collection during iteration with forEach</a> on Stack Overflow for more details.</p>\n\n<p>There are some possible simplifications. Here</p>\n\n<blockquote>\n<pre><code>var resi = res\nresi.append(arr[i])\nresult.append(resi)\n</code></pre>\n</blockquote>\n\n<p>is is not necessary to declare another array variable, this can be shortened to</p>\n\n<pre><code>result.append(res + [arr[i]])\n</code></pre>\n\n<p>A better name for the <code>res</code> variable might be <code>subarray</code> or <code>subset</code>.</p>\n\n<p>Instead of looping over the array indices</p>\n\n<blockquote>\n<pre><code>for i in 0..<arr.count {\n // ... do something with `arr[i]` ...\n}\n</code></pre>\n</blockquote>\n\n<p>you can enumerate the array (as you already do in the inner loop) </p>\n\n<pre><code>for elem in arr {\n // ... do something with `elem` ...\n}\n</code></pre>\n\n<p>The </p>\n\n<blockquote>\n<pre><code>guard arr.count >= 1 else { return [arr] }\n</code></pre>\n</blockquote>\n\n<p>is not needed. Your algorithm already does “the right thing” for an empty array.</p>\n\n<p>So this is what we have so far:</p>\n\n<pre><code>func subarrays(_ arr: [Int]) -> [[Int]] {\n var result = [[Int]]()\n for elem in arr {\n for subarray in result {\n result.append(subarray + [elem])\n }\n result.append([elem])\n }\n result.append([])\n return result\n}\n</code></pre>\n\n<p>It becomes a bit simpler if <code>result</code> is not initialized with an empty list, but with a list containing the empty subset. Adding the array element itself, and the empty set at the end of the function is no longer necessary:</p>\n\n<pre><code>func subarrays(_ arr: [Int]) -> [[Int]] {\n var result: [[Int]] = [[]]\n for elem in arr {\n for subarray in result {\n result.append(subarray + [elem])\n }\n }\n return result\n}\n</code></pre>\n\n<p>(The subset are returned in a different order now, though.)</p>\n\n<p>The inner loop could be replaced by a <em>map</em> operation:</p>\n\n<pre><code>func subarrays(_ arr: [Int]) -> [[Int]] {\n var result: [[Int]] = [[]]\n for elem in arr {\n result.append(contentsOf: result.map { $0 + [elem] })\n }\n return result\n}\n</code></pre>\n\n<p>or even the entire function body replaced by a single expression:</p>\n\n<pre><code>func subarrays(_ arr: [Int]) -> [[Int]] {\n return arr.reduce(into: [[]], { (result, elem) in\n result.append(contentsOf: result.map { $0 + [elem] })\n })\n}\n</code></pre>\n\n<p>but that is a matter of taste – is not necessarily easier to read.</p>\n\n<p>There is nothing particular with respect to integers in the algorithm, the function can be made generic to take arrays of any element type – or even arbitrary <em>sequences.</em></p>\n\n<p>Finally I would call it <code>subsets(of:)</code>, which is what the function computes:</p>\n\n<pre><code>func subsets<S: Sequence>(of seq: S) -> [[S.Element]] {\n var result: [[S.Element]] = [[]]\n for elem in seq {\n for subset in result {\n result.append(subset + [elem])\n }\n }\n return result\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T14:56:02.253",
"Id": "213593",
"ParentId": "213565",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "213593",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T09:16:50.400",
"Id": "213565",
"Score": "1",
"Tags": [
"swift"
],
"Title": "Generating all subarrays from an array of Integer"
} | 213565 |
<p>I wrote an if statement that checks if an iteratively altered vector "crosses" the up vector (0,1,0) or the down vector (0,-1,0).</p>
<pre><code>if ((lastDiff.x() > 0 && diff.x() < 0 && lastDiff.z() >= 0 && diff.z() <= 0) ||
(lastDiff.x() < 0 && diff.x() > 0 && lastDiff.z() >= 0 && diff.z() <= 0) ||
(lastDiff.x() > 0 && diff.x() < 0 && lastDiff.z() <= 0 && diff.z() >= 0) ||
(lastDiff.x() < 0 && diff.x() > 0 && lastDiff.z() <= 0 && diff.z() >= 0) ||
(lastDiff.z() > 0 && diff.z() < 0 && lastDiff.x() >= 0 && diff.x() <= 0) ||
(lastDiff.z() < 0 && diff.z() > 0 && lastDiff.x() >= 0 && diff.x() <= 0) ||
(lastDiff.z() > 0 && diff.z() < 0 && lastDiff.x() <= 0 && diff.x() >= 0) ||
(lastDiff.z() < 0 && diff.z() > 0 && lastDiff.x() <= 0 && diff.x() >= 0))
</code></pre>
<p>I feel like there is a simpler or better way to implement this if guard but I can't find it. </p>
| [] | [
{
"body": "<p>Code review:</p>\n\n<p>We're checking if the signs of the <code>x</code> and <code>z</code> components have both changed. So we can simplify quite a lot:</p>\n\n<pre><code>auto sign = [] (float f) { return (f > 0.f) ? true : false; }\nauto const& a = lastDiff;\nauto const& b = diff;\n\nif (sign(a.x()) != sign(b.x()) && sign(a.z()) != sign(b.z())) { ... }\n</code></pre>\n\n<p>An alternative:</p>\n\n<p>Set the y coordinate of both vectors to zero. Normalize them. Take the dot product. If the result (which is the cosine of the angle between them) is < 0 they're on opposite sides. If the result is > 0 they're on the same side.</p>\n\n<p>(Make sure to check for zero vectors after that first step).</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T10:38:22.953",
"Id": "413124",
"Score": "1",
"body": "The if statement in the first approach doesn't behave the same way in some cases where one of the vector components is exactly zero."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T20:39:47.483",
"Id": "413187",
"Score": "0",
"body": "@mistertribs is right. This won't work if either x or z stays 0"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T10:02:57.830",
"Id": "213570",
"ParentId": "213567",
"Score": "2"
}
},
{
"body": "<p>You have four groups of repeating conditions:</p>\n\n<pre><code>bool crossX = (lastDiff.x() < 0 && diff.x() > 0) || (lastDiff.x() > 0 && diff.x() < 0);\nbool crossZ = (lastDiff.z() < 0 && diff.z() > 0) || (lastDiff.z() > 0 && diff.z() < 0);\nbool crossTouchX = (lastDiff.x() <= 0 && diff.x() >= 0) || (lastDiff.x() >= 0 && diff.x() <= 0);\nbool crossTouchZ = (lastDiff.z() <= 0 && diff.z() >= 0) || (lastDiff.z() >= 0 && diff.z() <= 0);\n</code></pre>\n\n<p>Using these the original condition can be simplified to:</p>\n\n<pre><code>if ((crossX && crossTouchZ) || (crossZ && crossTouchX))\n{\n // do stuff\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T10:32:57.530",
"Id": "213574",
"ParentId": "213567",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "213574",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T09:34:28.920",
"Id": "213567",
"Score": "3",
"Tags": [
"c++",
"coordinate-system"
],
"Title": "Determine whether a vector intersects the up or down unit vector"
} | 213567 |
<p>I must create a program for information regarding schedules and topics of meetings at work.
The data relating to the meetings are stored in an "M" matrix with 5 columns, in which the generic row [g, m, in, fin, arg] denotes the fact that a meeting has been scheduled for day "g" of month "m", from hours "in" to "fin" hours, on the topic "arg".
Write a function "<em>common_argument(M)</em>" that returns the topic to which more time is dedicated.
I wrote the function and correctly returns the element but is it ok or is it too long?</p>
<pre><code>def common_argument(M):
element = M[0][4]
for i in range(len(M)):
if M[i][4] != element:
if period(M, element) < period(M, M[i][4]):
element = M[i][4]
return element
def period(M,c):
s = 0
for i in range(len(M)):
if c in M[i]:
if M[i][2] != M[i][3]:
if M[i][2] > M[i][3]:
s += M[i][2] - M[i][3]
if M[i][3] > M[i][2]:
s += M[i][3] - M[i][2]
return s
common_argument([[10, 1, 15, 17, 'Vendite'],
[10, 1, 17, 18, 'Progetti'],
[16, 2, 10, 12, 'Vendite'],
[16, 2, 13, 15, 'Progetti'],
[5,3,10, 13, 'Progetti']])
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T09:42:02.970",
"Id": "413209",
"Score": "0",
"body": "This is basically a thinly disguised variant of [your previous question](/q/213506/9357)."
}
] | [
{
"body": "<p>You can keep the nesting small by using <code>continue</code> if the condition is not the right one.</p>\n\n<pre><code>def common_argument(M):\n element = M[0][4]\n for i in range(len(M)):\n if M[i][4] == element:\n continue\n if period(M, element) < period(M, M[i][4]):\n element = M[i][4]\n return element\n\n\n def period(M,c):\n s = 0\n for i in range(len(M)):\n if c not in M[i]:\n continue;\n\n if M[i][2] == M[i][3]:\n continue;\n\n if M[i][2] > M[i][3]:\n s += M[i][2] - M[i][3]\n if M[i][3] > M[i][2]:\n s += M[i][3] - M[i][2]\n return s\n</code></pre>\n\n<p>See the Zen of Python: <a href=\"https://www.python.org/dev/peps/pep-0020/\" rel=\"nofollow noreferrer\">Flat is better than nested.</a></p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T16:13:29.080",
"Id": "413152",
"Score": "2",
"body": "I don't expect everyone else on CodeReview to fully re-write the OP's code, but really? You looked at that mass of code and thought \"Hm, if only he made that one loop less intuitive\"?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T00:21:15.160",
"Id": "413307",
"Score": "1",
"body": "For the record, I can respect \"flat is better than nested,\" but that's not really the point in this case. The point is that his actual logic is redundant and simple, it's just his implementation that's verbose. \"Explicit is better than implicit. Simple is better than complex.\" He should declare what he's doing clearly (e.g. using \"max\" and \"key=duration\") and rely on simpler logic rather than doing everything the hard way (e.g. using \"abs\")"
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T10:55:35.143",
"Id": "213576",
"ParentId": "213573",
"Score": "-2"
}
},
{
"body": "<p>This can be radically simplified (and made much more legible) in a variety of ways.</p>\n\n<p>First off, the you use 5 lines of code to compute the duration of a meeting, including checking in advance if that duration will be 0 (<code>if M[i][2] != M[i][3]</code>). You don't care if the duration is 0 (<code>s += 0</code> leaves <code>s</code> unchanged), and the rest of that logic just ensures that you get a positive difference even if the order of those values is backwards. Technically, the definition of a \"meeting\" that you give doesn't allow those values to be backwards, so it should be safe to simply subtract the start from the end time; however, even if you want to ensure you end up with a positive value, you can just use <code>abs</code> (absolute value):</p>\n\n<pre><code>def period(M,c):\n s = 0\n for i in range(len(M)):\n if c in M[i]:\n s += abs(M[i][3] - M[i][2])\n return s\n</code></pre>\n\n<p>Next, don't iterate over the indices of a list when you can just iterate over the list. Why do you care about <code>i</code>? You don't, you only want the value <code>M[i]</code>, which is much more cheaply and clearly obtained by simply looping on M:</p>\n\n<pre><code>def period(M,c):\n s = 0\n for meeting in M:\n if c in meeting:\n s += abs(meeting[3] - meeting[2])\n return s\n</code></pre>\n\n<p>Also, you check if <code>c in m</code>, but that's not really what you mean: you actually want to know if the topic <code>c</code> is the topic that meeting <code>m</code> is about. While we're at it, let's also unpack exactly what a meeting is expected to be, rather than use arbitrary integer indices into a list:</p>\n\n<pre><code>def period(M,c):\n s = 0\n for _, _, start, fin, topic in M:\n if c == topic:\n s += abs(fin - start)\n return s\n</code></pre>\n\n<p>That's become much more clear now that we've given every value a name (rather than just a number) and been explicit about what we're doing.</p>\n\n<p>Alright, let's tackle the main function now. You iterate over every meeting, and compare it to every other meeting, but this isn't strictly necessary. It also risks doing repeated work (e.g., if you have one REALLY long meeting about 'A' and a thousand tiny ones about 'B', you'll compute the total meeting durations for 'B' a thousand times, and actually do the same with 'A'). Let's first figure out all unique topics, and that way we'll be sure to not re-do any work:</p>\n\n<pre><code>def common_argument(M):\n all_topics = {topic for _, _, _, _, topic in M}\n element = all_topics.pop()\n for other_topic in all_topics:\n if period(M, element) < period(M, other_topic):\n element = other_topic\n return element\n</code></pre>\n\n<p>Well, that still doesn't prevent us from not duplicating work... let's make sure that we only compute the period of each topic once:</p>\n\n<pre><code>def common_argument(M):\n topic_duration = {topic: period(M, topic) for _, _, _, _, topic in M}\n element, element_duration = ... # What to put here?\n for other_topic, other_duration in topic_duration.items():\n if element_duration < other_duration:\n element = other_topic\n return element\n</code></pre>\n\n<p>Alright, we're now only compute each duration once. But the rest of that function is just asking \"What is the max topic, sorted by duration?\" And, in Python, there's a much easier way to ask that:</p>\n\n<pre><code>def common_argument(M):\n topic_duration = {topic: period(M, topic) for _, _, _, _, topic in M}\n return max(topic_duration, key=topic_duration.get)\n</code></pre>\n\n<p>The function <code>topic_duration.get</code> takes a topic and returns its duration, and iterating over <code>topic_duration</code> yields each unique topic once, so this will give us exactly what we want.</p>\n\n<p>The one thing we could still improve is that we're iterating over <code>M</code> once for each topic, yielding a runtime of <code>O(N*T)</code> where <code>N = len(M)</code> and <code>T</code> is the number of unique topics. There's no reason for that, we could easily loop over the array just once. That would look more like the following:</p>\n\n<pre><code>from collections import defaultdict\n\ndef common_argument(M):\n topic_duration = defaultdict(int)\n for _, _, start, fin, topic in M:\n topic_duration[topic] += abs(fin - start)\n\n return max(topic_duration, key=topic_duration.get)\n</code></pre>\n\n<p>And voila, we've collapsed all of the same logic into effectively 4 lines of code, and reduced computational complexity significantly.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T09:41:14.627",
"Id": "413208",
"Score": "1",
"body": "Consider using `collections.Counter` instead of `defaultdict`. That way, you can use `.most_common()` instead of `max()`."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T16:11:14.743",
"Id": "213599",
"ParentId": "213573",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T10:30:41.673",
"Id": "213573",
"Score": "2",
"Tags": [
"python"
],
"Title": "Python program to find the topic with the most meeting time dedicated to it"
} | 213573 |
<p>The task:</p>
<blockquote>
<p>Given a word W and a string S, find all starting indices in S which
are anagrams of W.</p>
<p>For example, given that W is "ab", and S is "abxaba", return 0, 3, and
4.</p>
</blockquote>
<p>My solution:</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> const anagramOccurrencesOf = (w, s) => {
const occurrencesCopy = [];
let sCopy = s.slice(0);
let index = 0;
while (sCopy.length && index !== -1) {
index = sCopy.indexOf(w);
if (index === -1) { break; }
occurrencesCopy.push((occurrencesCopy[occurrencesCopy.length - 1] + index + 1 || 0));
sCopy = sCopy.slice(index + 1);
}
const occurrencesReverse = [];
let sReverse = s.split('').reverse().join('');
index = 0;
while (sReverse.length && index !== -1) {
index = sReverse.indexOf(w);
if (index === -1) { break; }
occurrencesReverse.push( (occurrencesReverse[occurrencesReverse.length - 1] - w.length - index + 1) || s.length - w.length);
sReverse = sReverse.slice(index + 1);
}
return [...occurrencesCopy, ...occurrencesReverse].sort((a,b) => a -b);
};
console.log(anagramOccurrencesOf("ab", "abxaba"));</code></pre>
</div>
</div>
</p>
<p>EDIT: The solution above would find indexes of palindromes. The solution below should find indexes of anagrams:</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>const sortAlphabetically = x => x.toLowerCase().split('').sort().join('')
const getIndexOfAnagramIn = (s, w) => {
const wSorted = sortAlphabetically(w);
const result = []
for (let i = 0; i < s.length + 1 - w.length; i++) {
if (sortAlphabetically(s.slice(i, i + w.length)) === wSorted) {
result.push(i);
}
}
return result;
}
console.log(getIndexOfAnagramIn('abxaba', 'ab'));</code></pre>
</div>
</div>
</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T17:22:37.180",
"Id": "413160",
"Score": "0",
"body": "Notice that anagrams are not only reverses. For a word `abc` there are 6 anagrams."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T18:50:16.567",
"Id": "413174",
"Score": "0",
"body": "Ah, i mistook them with palindromes"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T12:11:43.313",
"Id": "413216",
"Score": "0",
"body": "Shouldn’t the example indices be: `0, 1, 3, 4, 5`?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T13:23:35.217",
"Id": "413218",
"Score": "0",
"body": "Not from what I understood. Why do you think so? @morbusg"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T14:09:11.620",
"Id": "413225",
"Score": "0",
"body": "@thadeuszlay: well, the 4th index confuses me in the example as it is `ba`, but the 1st index would also be when backwards."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T14:18:57.217",
"Id": "413226",
"Score": "0",
"body": "The b refers to the original string, therefore it’s the 4th index @morbusg"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T14:30:26.620",
"Id": "413228",
"Score": "0",
"body": "The word w is permuted but not the string a @morbusg"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T14:52:23.250",
"Id": "413234",
"Score": "0",
"body": "I'm sorry, I'm still a bit confused; a palindrome is a word, phrase, or sequence that reads the same backwards as forwards. `ba` isn't a palindrome, but `abba` would be."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T14:54:10.580",
"Id": "413235",
"Score": "0",
"body": "Ah, are you talking about my first solution? If so, then just ignore my first solution. I misunderstood the term \"anagram\". The solution should be about anagrams not palindromes. @morbusg"
}
] | [
{
"body": "<p>This code looks pretty good. I don't see much I would change. This code makes good use of <code>const</code> and <code>let</code> where appropriate.</p>\n\n<p>The only thing that stands out is that splitting a string into an array can be done with the spread syntax instead of calling <code>split()</code>.</p>\n\n<p>The first instance:</p>\n\n<blockquote>\n<pre><code>let sReverse = s.split('').reverse().join('');\n</code></pre>\n</blockquote>\n\n<p>Could be changed to </p>\n\n<pre><code>let sReverse = [...s].reverse().join('');\n</code></pre>\n\n<p>And the other instance:</p>\n\n<blockquote>\n<pre><code>const sortAlphabetically = x => x.toLowerCase().split('').sort().join('')\n</code></pre>\n</blockquote>\n\n<p>Could be changed to:</p>\n\n<pre><code>const sortAlphabetically = x => [...x.toLowerCase()].sort().join('')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-05-21T21:18:33.197",
"Id": "220676",
"ParentId": "213579",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "220676",
"CommentCount": "9",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T11:25:15.670",
"Id": "213579",
"Score": "1",
"Tags": [
"javascript",
"algorithm",
"strings",
"ecmascript-6",
"iterator"
],
"Title": "Find all starting indices in a string which are anagrams of a word"
} | 213579 |
<p>I have tested this code and it yields the expected outputs, but I want to verify if I have applied insertion sort algorithm correctly or not.</p>
<pre><code> import java.util.*;
public class InsertionSort
{
static void swap(int[] arr, int i, int j)
{
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
static void sorter(int arr[])
{
int hole;
int n = arr.length;
if(n>=2)
{
for(int i = 1; i<n ; i++)
{
hole = i;
inner:
for(int j = i-1; j>=0; j--)
{
if(arr[j]> arr[hole])
{
swap(arr, j, hole);
hole = j;
}
else
break inner;
}
}
}
System.out.println(Arrays.toString(arr));
}
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T09:45:46.413",
"Id": "413130",
"Score": "2",
"body": "Do you want to ascertain correctness or Elegance? Correctness can be found by tests."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T09:46:08.907",
"Id": "413131",
"Score": "0",
"body": "You should follow the Java Naming Conventions: variable names always start with lowercase. `Arr` should be `arr`."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T09:47:46.043",
"Id": "413132",
"Score": "0",
"body": "@MCEmperor Sure, fixing that right now."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T09:48:10.510",
"Id": "413133",
"Score": "0",
"body": "You can check for such answers online https://www.geeksforgeeks.org/insertion-sort/"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T09:48:26.253",
"Id": "413134",
"Score": "0",
"body": "@Sid Correctness, Have I correctly used the concept of insertion sort?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T09:57:51.803",
"Id": "413135",
"Score": "0",
"body": "You can minimize you Code by using sorting method\nhttps://www.geeksforgeeks.org/sorting-algorithms/\nthis can help u out"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T10:04:16.247",
"Id": "413136",
"Score": "1",
"body": "It's correct, but it's far from good code. There is no need for `n` as intermediate variable, `if (n>=2)` is redundant, because it will just loop once in this case. The label `inner` is redundant in this case. And in general, if you ever feel you need to use a label in Java, you should restructure your code. And, finally, printing the result should not be done in the sort method."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T13:54:18.697",
"Id": "413224",
"Score": "0",
"body": "You probably meant `System.err.println()`. Messages, like for example debug statements, should be printed to `System.err`, not `System.out`."
}
] | [
{
"body": "<h3>Labeled loops</h3>\n\n<p>You say </p>\n\n<blockquote>\n<pre><code> break inner;\n</code></pre>\n</blockquote>\n\n<p>But that's not necessary. The <code>inner</code> loop is already the innermost loop. You could just say <code>break;</code>. </p>\n\n<p>And frankly, you could have just said </p>\n\n<pre><code> for (int j = i-1; j >= 0 && arr[j] > arr[hole]; j--)\n</code></pre>\n\n<p>No <code>break</code> or internal <code>if</code> needed. </p>\n\n<p>But that's not the question you really wanted answered. </p>\n\n<h3>Insertion sort?</h3>\n\n<p>It's similar to an <a href=\"https://en.wikipedia.org/wiki/Insertion_sort\" rel=\"nofollow noreferrer\">insertion sort</a>. Your insertion method is a bit odd though. Normally insertion sort would find the insertion point and then move the elements after that. You're bubbling the current value forward. </p>\n\n<p>Consider </p>\n\n<pre><code>int j = i - 1;\nwhile (j >= 0 && numbers[j] < numbers[i]) {\n j--;\n}\n\nint temp = numbers[i];\nfor (int k = i; k > j; k--) {\n numbers[k] = numbers[k - 1];\n}\n\nnumbers[j] = temp;\n</code></pre>\n\n<p>That does about half as many array assignments as your method. </p>\n\n<h3>Naming</h3>\n\n<p>I prefer a descriptive name like <code>numbers</code> to a generic abbreviation like <code>arr</code>. At minimum, it should be <code>array</code>. But I prefer <code>numbers</code>. </p>\n\n<blockquote>\n<pre><code> static void sorter(int arr[])\n</code></pre>\n</blockquote>\n\n<p>As a general rule, we name classes and objects with noun names. Methods get verb names. So </p>\n\n<pre><code> static void sort(int[] numbers) {\n</code></pre>\n\n<p>In Java, we also normally write arrays as <code>int[] name</code> not <code>int name[]</code>. </p>\n\n<p>You could name the class </p>\n\n<pre><code>class InsertionSorter {\n</code></pre>\n\n<p>Although in this case <code>InsertionSort</code> can be used as a noun. </p>\n\n<h3>Wildcard imports</h3>\n\n<pre><code>import java.util.*;\n</code></pre>\n\n<p>The general policy is to import one class at a time, not a wildcard group. That's especially true here, since it's not clear that you are using any <code>java.util</code> classes. </p>\n\n<h3>Mixing logic and display</h3>\n\n<p>It's generally agreed that it is better to return the data and display it separately. Since you are sorting in place, that could just look like </p>\n\n<pre><code>InsertionSort.sort(numbers);\nSystem.out.println(Arrays.toString(numbers));\n</code></pre>\n\n<h3>Declare at initialization</h3>\n\n<p>You have </p>\n\n<blockquote>\n<pre><code> hole = i;\n</code></pre>\n</blockquote>\n\n<p>You could do </p>\n\n<pre><code> int hole = i;\n</code></pre>\n\n<p>It's generally considered best practice to declare variables as late as possible. You don't use <code>hole</code> outside the loop or across iterations, so there's no need to declare it outside the loop. </p>\n\n<h3>Redundant logic</h3>\n\n<blockquote>\n<pre><code> if(n>=2)\n {\n for(int i = 1; i<n ; i++)\n</code></pre>\n</blockquote>\n\n<p>If <code>n</code> is 1 or less then <code>1 < n</code> will be false and it won't enter the loop. </p>\n\n<p>And you don't need <code>n</code>. You can just say <code>numbers.length</code> whenever you need that value. </p>\n\n<h3>Standard methods</h3>\n\n<p>You could also replace these two loops with Java standard methods. </p>\n\n<pre><code> int insertionPoint = Arrays.binarySearch(numbers, 0, i, numbers[i]);\n if (insertionPoint < 0) {\n insertionPoint = -insertionPoint - 1;\n }\n\n int temp = numbers[i];\n System.arraycopy(numbers, insertionPoint, numbers, insertionPoint + 1, i - insertionPoint);\n numbers[insertionPoint] = temp;\n</code></pre>\n\n<p>Of course, it's possible that you were trying to avoid standard methods. After all, <code>Arrays.sort</code> would solve this problem without additional coding. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T23:32:09.980",
"Id": "213626",
"ParentId": "213582",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "8",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T09:42:35.977",
"Id": "213582",
"Score": "0",
"Tags": [
"java",
"sorting"
],
"Title": "Insertion sort algorithm in Java"
} | 213582 |
<p>How can I improve the following code to track when an Azure SQL Database column value was last modified?</p>
<pre><code>IF UPDATE([UserId]) AND EXISTS (SELECT [UserId] FROM inserted EXCEPT SELECT [UserId] FROM deleted)
BEGIN
UPDATE [MyTable] SET [UserIdModified] = SYSUTCDATETIME() FROM [inserted] WHERE [MyTable].[Id] = [inserted].[Id]
END
</code></pre>
<p>Does it make sense (from clarity, readability or performance point-of-view in your opinion) to include the (extra) <code>UPDATE([UserId]</code>) in the beginning of the <code>IF</code> clause, as opposed to only using <code>EXISTS</code>?</p>
<pre><code>IF EXISTS (...)
BEGIN
...
END
</code></pre>
<p><code>UPDATE</code> could clarify things out for a reader (e.g. the script will run only when [<code>UserId</code>] is included) but on the other hand it is redundant (perhaps without real benefits).</p>
<p>I built upon David Coster's answer from <a href="https://stackoverflow.com/questions/651524/most-efficient-method-to-detect-column-change-in-ms-sql-server">here</a>.</p>
<p>Testing things out:</p>
<pre><code>DROP TABLE IF EXISTS [MyTable]
GO
CREATE TABLE [MyTable] ([Id] INT IDENTITY NOT NULL PRIMARY KEY, [UserId] INT, [UserIdModified] DATETIME2)
GO
CREATE TRIGGER [trgMyTableUserIdModified]
ON [MyTable]
AFTER INSERT, UPDATE
AS
BEGIN
IF UPDATE([UserId]) AND EXISTS (SELECT [UserId] FROM inserted EXCEPT SELECT [UserId] FROM deleted)
BEGIN
UPDATE [MyTable] SET [UserIdModified] = SYSUTCDATETIME() FROM [inserted] WHERE [MyTable].[Id] = [inserted].[Id]
END
END
GO
INSERT INTO [MyTable] ([UserId]) VALUES (1)
SELECT * FROM [MyTable]
WAITFOR DELAY '00:00:00.010'
UPDATE [MyTable] SET [UserId] = 2
SELECT *, 'Updated.' [Time should be] FROM [MyTable]
WAITFOR DELAY '00:00:00.010'
UPDATE [MyTable] SET [UserId] = 2
SELECT *, 'Same as above.' [Time should be] FROM [MyTable]
WAITFOR DELAY '00:00:00.010'
UPDATE[MyTable] SET [UserId] = NULL
SELECT *, 'Updated.' [Time should be] FROM [MyTable]
WAITFOR DELAY '00:00:00.010'
UPDATE [MyTable] SET [UserId] = NULL
SELECT *, 'Same as above.' [Time should be] FROM [MyTable]
WAITFOR DELAY '00:00:00.010'
INSERT INTO [MyTable] ([UserId]) VALUES (1)
SELECT *, 'Same as above for 1st element.' [Time should be] FROM [MyTable]
WAITFOR DELAY '00:00:00.010'
UPDATE [MyTable] SET [UserId] = 2 WHERE [Id] = 2
SELECT *, 'Updated only for the 2nd element.' [Test] FROM [MyTable]
</code></pre>
<p>The above test code prints out:</p>
<p><a href="https://i.stack.imgur.com/1dcGj.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/1dcGj.png" alt="enter image description here"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T13:29:04.020",
"Id": "413139",
"Score": "0",
"body": "EXCEPT looks wrong, also I don't think you are following Coster's answer ( which looks sound )."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T14:04:38.103",
"Id": "413142",
"Score": "1",
"body": "@GeorgeBarwood What exactly looks wrong and how it could be improved? Added test code above so it is easy to try things out."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T14:22:25.840",
"Id": "413143",
"Score": "0",
"body": "I take it back, EXCEPT is fine, I didn't spot what you were doing. I think the IF UPDATE([UserId]) is good."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T14:38:07.557",
"Id": "413144",
"Score": "0",
"body": "@GeorgeBarwood Included UPDATE([UserId]) in the original proposal."
}
] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "4",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T13:10:08.737",
"Id": "213583",
"Score": "0",
"Tags": [
"sql",
"sql-server"
],
"Title": "Tracking when a column was last modified using a trigger (in SQL Server)"
} | 213583 |
<p>I wanted to make a very simply Battleship game in Java, any feedback is welcome. </p>
<p>Nevermind the getters / setters. Just assume they are there. </p>
<pre><code>class Game {
Board board = new Board();
void playGame() {
Scanner scanner = new Scanner(System.in);
while (!board.allShipsSank()) {
System.out.println("Enter missile locations, x and y.");
int x = scanner.nextInt();
int y = scanner.nextInt();
board.shoot(x, y);
}
}
}
class Board {
Set<Ship> ships = new HashSet<>();
boolean allShipsSank() {
for (Ship ship : ships)
if (!ship.isSank())
return false;
return true;
}
void shoot(int x, int y) {
for (Ship ship : ships) {
if (ship.shipGeographic.orientation == ShipGeographic.Orientation.HORIZONTAL) {
if (y == ship.shipGeographic.y && ship.shipGeographic.x <= x && x <= ship.shipGeographic.x + ship.len) {
ship.missileAt(x - ship.shipGeographic.x);
return;
}
}
if (ship.shipGeographic.orientation == ShipGeographic.Orientation.VERTICAL) {
if (x == ship.shipGeographic.x && ship.shipGeographic.y <= y && y <= ship.shipGeographic.y + ship.len) {
ship.missileAt(ship.shipGeographic.y + y);
return;
}
}
}
}
}
class ShipGeographic {
enum Orientation {
HORIZONTAL, VERTICAL;
}
int x;
int y;
ShipGeographic.Orientation orientation;
}
class Ship {
// length of the ship
int len;
// Nodes where this ship has been hit
Set<Integer> hit = new HashSet<>();
// Where this Ship is
ShipGeographic shipGeographic;
Ship(int len) {
this.len = len;
}
boolean isSank() {
return hit.size() == len;
}
// For example, if ship is hit at head, parameter is 0
// Missile at same node of ship has no effect
void missileAt(int offsetFromLen) {
if (hit.add(offsetFromLen)) {
System.out.println("boom!");
System.out.println(hit);
}
}
}
</code></pre>
<p>here is how I initialize and run the game:</p>
<pre><code>class App {
public static void main(String[] args) {
Game game = new Game();
// Just some sample data!
{
Ship ship = new Ship(3);
ShipGeographic shipGeographic = new ShipGeographic();
shipGeographic.orientation = ShipGeographic.Orientation.HORIZONTAL;
shipGeographic.x = 1;
shipGeographic.y = 1;
ship.shipGeographic = shipGeographic;
game.board.ships.add(ship);
}
game.playGame();
}
}
</code></pre>
<p>A sample run:</p>
<pre><code>Enter missile locations, x and y.
1
1
boom!
[0]
Enter missile locations, x and y.
5
5
Enter missile locations, x and y.
2
1
boom!
[0, 1]
Enter missile locations, x and y.
3
1
boom!
[0, 1, 2]
Process finished with exit code 0
</code></pre>
| [] | [
{
"body": "<p>Thanks for sharing your code.</p>\n\n<h1>what I like</h1>\n\n<ul>\n<li>you follow the Java Naming conventions</li>\n<li>you resist to solve the problem based on an array</li>\n</ul>\n\n<h1>what I dislike</h1>\n\n<h2>violation of <em>encapsulation / information hiding</em></h2>\n\n<p>You access directly properties of an object and (even worse) their properties too like this:</p>\n\n<blockquote>\n<pre><code>x == ship.shipGeographic.x && ship.shipGeographic.y <= y\n</code></pre>\n</blockquote>\n\n<p>But the code using an object should not know anything about the internal implementation pf this object. The using code should only call (public) methods on on an object. This enables both: polymorphism and improving the internal implementation without affecting the calling code. The getters and setters you mention are <em>not</em> a solution to this problem.</p>\n\n<p>The names for this \"code smells\" is <em>feature envy</em>: the calling code does something what should better be done inside the object by applying the \"tell, don't ask\" principle.</p>\n\n<h2>separation of concerns - intermix of user IO and business logic</h2>\n\n<p>In your code the <code>Board</code> class is responsible for the user IO and also does game logic. This reduces the re-usability of the game logic. I.e.: you have to do a complete rewrite if you want to change the User interface to graphics instead of a command line. You should learn about the Model-View-Controller concept (MVC) and its relatives MCP, MVVC and MVVM.</p>\n\n<h2>unnecessary mutability</h2>\n\n<p>Your ship objects are mutable, this means their properties could be changed at any time during the game. But in practice the properties never change after initialization. Therefore your should pass all the properties as constructor parameters and store them in <code>final</code> declared properties.</p>\n\n<h2>incomplete OO approach.</h2>\n\n<p>IMHO you stopped doing an OO approach half way. </p>\n\n<p>Holding a list of ships which know their positions is a good first step. But you could walked that path further.</p>\n\n<p>E.g. The list of ships could only hold unsunk ones. Then the check for the end of the game would change from a <em>loop</em> to a simple statement: </p>\n\n<pre><code>boolean allShipsSank() {\n return listOfShips.isEmpty(); \n}\n</code></pre>\n\n<p>Next possibility could be the \"ship hit\" logik.</p>\n\n<p>For once the ship should know itself if being hit:</p>\n\n<pre><code>class Ship {\n //...\n boolean isHitBy(int x, int y) {\n // logic here\n }\n //...\n}\n</code></pre>\n\n<p>but instead of doing a calculation here I'd go the \"collection\" approach again. </p>\n\n<p>First we need to introduce another class:</p>\n\n<pre><code>class BordPosition{ // this is a DTO and has no business logik\n final int x;\n final int y;\n BordPosition(int x, int y){\n this.x = x;\n this.y = y;\n }\n // implement equals() and hascode()\n}\n</code></pre>\n\n<p>and we need to enhance the <code>Orientation</code> enum:</p>\n\n<pre><code>enum Orientation {\n HORIZONTAL{\n public BordPosition translate(BordPosition startPoint, int stepsToMove){\n return new BordPosition(startPoint.x+stepsToMove, startPoint.y);\n }\n }, \n VERTICAL{\n public BordPosition translate(BordPosition startPoint, int stepsToMove){\n return new BordPosition(startPoint.x, startPoint.y+stepsToMove);\n }\n };\n abstract public BordPosition translate(BordPosition startPoint, int stepsToMove);\n}\n</code></pre>\n\n<p>then class <code>Ship</code> would change to this</p>\n\n<pre><code>class Ship {\n private final Collection<BordPosition> occupiedFields = new HashSet<>();\n private final Collection<BordPosition> hitFields = new HashSet<>();\n Ship(BordPosition startPoint, Orientation orientation, int size){\n for (int stepsToMove = 0; stepsToMove<size; stepsToMove++) {\n occupiedFields.add(orientation.translate(startPoint,stepsToMove));\n }\n }\n\n boolean isHitBy(BordPosition missleTarget) {\n if(occupiedFields.contains(missleTarget)){\n hitFields.add(missleTarget);\n if (hitFields.size()==occupiedFields.size()){\n // deregister from ship list via Listener pattern\n }\n return true;\n } else {\n return false;\n } \n }\n //...\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T16:02:39.747",
"Id": "413150",
"Score": "0",
"body": "Very useful tips, thank you. I can not tell I agree with all but I think it is ok to disagree sometimes and I guess there is no specific concrete way."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T16:09:30.533",
"Id": "413151",
"Score": "0",
"body": "@KorayTugay \"I can not tell I agree with all but I think it is ok to disagree sometimes\" - yes, there is no \"right or wrong\", only \"more or less useful\". But may you share where you disagree? Maybe I can learn something too?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T13:19:43.670",
"Id": "413370",
"Score": "0",
"body": "Is a ship supposed to know it's location and orientation? If a board consists of Bombable cells and each bombable is connected to either a reference to a Ship or a NOP, depending if the cell is occupied by a vessel or not. Ship would only know it's length, as it's an inherent trait, and you'd add it to the board in either horizontal or vertical orientation and the board would be responsible for knowing which cells the ship occupies, since the cells belong to the board."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-26T10:41:18.867",
"Id": "418386",
"Score": "0",
"body": "@TorbenPutkonen *\"Is a ship supposed to know it's location and orientation?\"* - When doing OOP it is a good approach to look at the real world: In the real world, is it the ship or the ocean knowing position and heading?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T06:22:33.740",
"Id": "418522",
"Score": "0",
"body": "@TimothyTruckle Real world is often way too complicated to be represented as a class hierarchy. In the real world the ship is in water but that water might be moved by currents and wind which affecfts the true heading. Heck, sometimes that body of water might be on a ferris wheel. :) So... there are many ways to skin this cat and whatever way fits here depends on the required fetures."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T07:41:31.117",
"Id": "418532",
"Score": "0",
"body": "@TorbenPutkonen *The real world is way to complex to be used as guideline for our software* - is this what you gonna say?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-27T08:11:07.450",
"Id": "418537",
"Score": "0",
"body": "@TimothyTruckle For this abstraction, yes. Battleshjip game is not a simulation of real life."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T15:59:26.683",
"Id": "213596",
"ParentId": "213584",
"Score": "4"
}
},
{
"body": "<h1>Procedural Programming</h1>\n\n<p>In general it uses data-structures to solve a problem. Data-structures are like lookup tables, in which it is possible to save, modify and read values.</p>\n\n<p>Working with data-structures could look in java like</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>class Stroke { /* ... */}\nclass Color { /* ... */}\n\nclass Rect {\n double width;\n double hight;\n Stroke stroke;\n}\n\nRect rect = new Rect();\nrect.width = 5;\nrect.hight = 14;\nrect.stroke.type = \"dotted\";\nrect.color.value = \"#000\";\nrect.color.opacity= \"0.3\";\n</code></pre>\n\n<p>In the code you provided I found this statemant</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>game.board.ships.add(ship);\n</code></pre>\n</blockquote>\n\n<h1>Object Oriented Programming</h1>\n\n<p>In general it is about sending messages (interact with methods) from one object to an other.</p>\n\n<p>The following two lines of code tries to express <em>\"Hey Game! Please add a ship to the board\"</em>.</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>// in a procedural way\ngame.board.ships.add(ship);\n\n// in an object oriented way\ngame.addToBoard(ship)\n</code></pre>\n\n<p>What I can find in your code base is a hybrid (half object and half data).</p>\n\n<h1>Readability</h1>\n\n<h2>Variables</h2>\n\n<p>Variables are a good way to express what code does.</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>void missileAt(int offsetFromLen)\n</code></pre>\n</blockquote>\n\n<p>What is a <code>len</code>? To answer these question I will look into your class and find the instance variable <code>len</code>.</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>// length of the ship\nint len;\n</code></pre>\n</blockquote>\n\n<p>Now I know it is the <em>length</em> and not a acronym. I thing it is much easier to write the 3 more letters, than to write a comment to explain it.</p>\n\n<h2>Methods</h2>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>if (ship.shipGeographic.orientation == ShipGeographic.Orientation.HORIZONTAL)\n</code></pre>\n</blockquote>\n\n<p>This code be readen easier as</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>if (ship.isInHorizontalPosition())\n</code></pre>\n\n<h1><a href=\"https://refactoring.guru/smells/feature-envy\" rel=\"nofollow noreferrer\">Feature Envy</a></h1>\n\n<blockquote>\n <p>A method accesses the data of another object more than its own data.</p>\n</blockquote>\n\n<p>The method <code>shoot</code> in <code>Board</code> do heavy operations on <code>Ship</code>. This is possible because your \"objects\" don't hide their implementation. </p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>void shoot(int x, int y) {\n for (Ship ship : ships) {\n if (ship.shipGeographic.orientation == ShipGeographic.Orientation.HORIZONTAL) {\n if (y == ship.shipGeographic.y && ship.shipGeographic.x <= x && x <= ship.shipGeographic.x + ship.len) {\n ship.missileAt(x - ship.shipGeographic.x);\n return;\n }\n }\n if (ship.shipGeographic.orientation == ShipGeographic.Orientation.VERTICAL) {\n if (x == ship.shipGeographic.x && ship.shipGeographic.y <= y && y <= ship.shipGeographic.y + ship.len) {\n ship.missileAt(ship.shipGeographic.y + y);\n return;\n }\n }\n }\n}\n</code></pre>\n</blockquote>\n\n<p>Instead of <code>Board</code> the <code>Ship</code> itself should lookup if it gets hit. </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>void shoot(int x, int y) {\n for (Ship ship : ships)\n ship.handleShootTo(x, y);\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-19T13:41:25.900",
"Id": "413541",
"Score": "0",
"body": "A ship can not handle if it is shot or not, a board knows where the ship is. Thanks for the thoughts though, as usual +1."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-19T13:42:23.030",
"Id": "413542",
"Score": "0",
"body": "You can see @Torbens comment in the answer above as well, I actually saw it after I commented to your answer. He seems agree with me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-19T13:44:12.890",
"Id": "413544",
"Score": "1",
"body": "But since the `ship` holds the `shipGeographic` (`ship.shipGeographic`) it knows where it is.. or am I wrong.."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-19T13:45:59.913",
"Id": "413546",
"Score": "1",
"body": "I would add to that that board should not contain algorithms to handle missile hits. Missile hits are part of the rules of the game so they should be in the game engine. How the game engine implements them is another issue (e.g. it can set up object relations so that a hit to board automatically triggers a hit at a certain location of a ship)."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-19T13:49:51.743",
"Id": "413548",
"Score": "0",
"body": "I find that mind games regarding extensions sometimes help. E.g. what if I want to add a nuke that hits at a radius larger than one? Would adding that be easy? If not, the design is flawed."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-19T13:56:30.673",
"Id": "413549",
"Score": "0",
"body": "@Roman I think you are right. I am myself confused as well honestly :) What I had in mind was what Torben is saying, but I guess you are right too. :) I am confused with my own code."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-19T14:05:26.133",
"Id": "413551",
"Score": "0",
"body": "@KorayTugay you can get the best from both worlds: A `Ship` can know its position, while the game engine from @TorbenPutkonen request `Ship`s by their position and interact with them."
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-19T12:46:52.233",
"Id": "213802",
"ParentId": "213584",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T13:21:47.803",
"Id": "213584",
"Score": "3",
"Tags": [
"java",
"object-oriented",
"battleship"
],
"Title": "Battleship Game in Java"
} | 213584 |
<p>I wrote a class that replaces the <code>get</code> and <code>set</code> functions:</p>
<pre><code>template <class T, class U = T, class V = T>
class GetSet
{
public:
template <typename = std::enable_if_t<std::is_same<U, T>::value && std::is_same<V, T>::value>>
inline GetSet() { getf = getNormal; setf = setNormal; };
inline GetSet(U (*getf)(T), T (*setf)(V)) { this->getf = getf; this->setf = setf; };
inline operator U() { return getf(value); };
inline U operator () () { return getf(value); };
inline GetSet<T>& operator = (V v) { value = setf(v); return *this; };
// only for tuples
template <int N>
inline auto get() { static_assert(N < std::tuple_size<T>::value, "Index out of bounds"); return std::get<N>(getf(value)); };
template <int N, class W>
inline GetSet<T>& set(W w) { static_assert(N < std::tuple_size<T>::value, "Index out of bounds"); auto a = getf(value); std::get<N>(a) = w; value = setf(a); return *this; };
private:
inline static T getNormal(T t) { return t; };
inline static T setNormal(T t) { return t; };
U (*getf)(T t);
T (*setf)(V v);
T value;
};
</code></pre>
<p>It can be used like this:</p>
<pre><code>utils::GetSet<std::tuple<int, int>> getSet
(
[](std::tuple<int, int> t)
{
auto[x, y] = t;
return std::tuple(x - 1, y - 1);
},
[](std::tuple<int, int> t)
{
auto[x, y] = t;
return std::tuple(x - 1, y - 1);
}
);
getSet = { 1, 2 };
auto[i, j] = getSet(); // in this example the parentheses are required, because of the auto keyword
getSet.set<0>(8);
auto r = getSet.get<0>();
// r = 6
</code></pre>
<p>Or a very simple example:</p>
<pre><code>utils::GetSet<int> simple;
simple = 1;
int r2 = simple;
</code></pre>
<p>The <code>U</code> and <code>V</code> templates are used in case you want to have <code>get</code>/<code>set</code> functions with different parameters rather than just the standard type that's stored in the class. The main issue I'm aware of is that it's not possible to have a public get and a private set for example.</p>
| [] | [] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T14:07:21.780",
"Id": "213585",
"Score": "3",
"Tags": [
"c++"
],
"Title": "get; set; in C++"
} | 213585 |
<p>I've got the following shell script (let say <code>get_includes.sh</code>):</p>
<pre><code>#!/usr/bin/env bash
includes=($(grep ^#include file.c | grep -o '"[^"]\+"' | tr -d '"'))
echo "0: ${includes[0]}"
echo "1: ${includes[1]}"
</code></pre>
<p>which aims at finding relative include files in source code file.</p>
<p>So for given file like this (<code>file.c</code>):</p>
<pre><code>#include "foo.h"
#include "bar.h"
#include <stdio.h>
int main(void) {
printf("Hello World\n");
return 0;
}
</code></pre>
<p>It'll return the following results which are correct:</p>
<pre><code>$ ./get_includes.sh
0: foo.h
1: bar.h
</code></pre>
<p>The code works as expected, however <code>shellcheck</code> complains about the following issues:</p>
<pre><code>$ shellcheck get_includes.sh
In get_includes.sh line 2:
includes=($(grep ^#include file.c | grep -o '"[^"]\+"' | tr -d '"'))
^-- SC2207: Prefer mapfile or read -a to split command output (or quote to avoid splitting).
For more information:
https://www.shellcheck.net/wiki/SC2207 -- Prefer mapfile or read -a to spli...
https://www.shellcheck.net/wiki/SC2236 -- Use -n instead of ! -z.
</code></pre>
<p>So:</p>
<ul>
<li>I can't quote command substitution, as I expect the command to expand to an array.</li>
<li>I don't want to ignore the warning, I'd like to correct it.</li>
</ul>
<p>I'm using Bash 4.</p>
<p><strong>So, how I can correct the above line to satisfy <code>shellcheck</code>?</strong> If possible, I'd like to keep it in one-liner.</p>
<hr>
<p>I've tried the following approaches which failed:</p>
<pre><code>$ (grep ^#include file.c | grep -o '"[^"]\+"' | read -a myarr; echo $myarr)
(nothing is printed)
$ (grep ^#include file.c | grep -o '"[^"]\+"' | mapfile myarr; echo $myarr)
(nothing is printed)
</code></pre>
| [] | [
{
"body": "<p>After reading more about <a href=\"https://github.com/koalaman/shellcheck/wiki/SC2207\" rel=\"nofollow noreferrer\">SC2207</a>, the proper syntax would be:</p>\n\n<pre><code>mapfile -t includes < <(grep ^#include file.c | grep -o '\"[^\"]\\+\"' | tr -d '\"')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T14:53:38.673",
"Id": "213592",
"ParentId": "213590",
"Score": "0"
}
},
{
"body": "<h3>... so what's going on?</h3>\n\n<blockquote>\n<pre><code>$ (grep ^#include file.c | grep -o '\"[^\"]\\+\"' | read -a myarr; echo $myarr)\n(nothing is printed)\n$ (grep ^#include file.c | grep -o '\"[^\"]\\+\"' | mapfile myarr; echo $myarr)\n(nothing is printed)\n</code></pre>\n</blockquote>\n\n<p>Why doesn't this work? Because <a href=\"https://www.gnu.org/software/bash/manual/html_node/Pipelines.html\" rel=\"nofollow noreferrer\"><em>\"each command in a pipeline is executed in its own subshell\"</em></a>. As the page explains, you could enable the <code>lastpipe</code> option to have the last element of the pipeline run in the current process. (The page doesn't mention that this will only work when you use it in a script, where job control is not active (as mentioned <a href=\"https://www.gnu.org/software/bash/manual/html_node/The-Shopt-Builtin.html#The-Shopt-Builtin\" rel=\"nofollow noreferrer\">here</a>). It won't work in an interactive shell.)</p>\n\n<h3>Keep pipelines as short as possible</h3>\n\n<p>It's good to use the fewest possible processes in pipelines.\nMultiple <code>grep</code> in a pipeline are points to look at with suspicion.\nYou can make the first <code>grep</code> work a little harder,\nusing a stricter pattern, and then you can achieve the same result with 2 processes instead of 3:</p>\n\n<pre><code>grep '^#include .*\"' file.c | cut -d'\"' -f2\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-03-25T08:10:44.637",
"Id": "418210",
"Score": "0",
"body": "What would have worked is `... | { read -a myarr; echo \"$myarr\"; }` but it would have made for quite ugly code."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T16:29:58.900",
"Id": "213601",
"ParentId": "213590",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T14:46:13.380",
"Id": "213590",
"Score": "1",
"Tags": [
"bash",
"shell"
],
"Title": "Bash script to find included files in C code"
} | 213590 |
<p>I just started to practice for competitive programming and just started to solve the most solved problems on SPOJ.</p>
<p>This is what I made for ADDREV: Adding reversed numbers in Java (<a href="https://www.spoj.com/problems/ADDREV/" rel="nofollow noreferrer">https://www.spoj.com/problems/ADDREV/</a>)</p>
<blockquote>
<p>The Antique Comedians of Malidinesia prefer comedies to tragedies. Unfortunately, most of the ancient plays are tragedies. Therefore the dramatic advisor of ACM has decided to transfigure some tragedies into comedies. Obviously, this work is very hard because the basic sense of the play must be kept intact, although all the things change to their opposites. For example the numbers: if any number appears in the tragedy, it must be converted to its reversed form before being accepted into the comedy play.</p>
<p>Reversed number is a number written in arabic numerals but the order of digits is reversed. The first digit becomes last and vice versa. For example, if the main hero had 1245 strawberries in the tragedy, he has 5421 of them now. Note that all the leading zeros are omitted. That means if the number ends with a zero, the zero is lost by reversing (e.g. 1200 gives 21). Also note that the reversed number never has any trailing zeros.</p>
<p>ACM needs to calculate with reversed numbers. Your task is to add two reversed numbers and output their reversed sum. Of course, the result is not unique because any particular number is a reversed form of several numbers (e.g. 21 could be 12, 120 or 1200 before reversing). Thus we must assume that no zeros were lost by reversing (e.g. assume that the original number was 12).</p>
<p><strong>Input</strong></p>
<p>The input consists of N cases (equal to about 10000). The first line of the input contains only positive integer N. Then follow the cases. Each case consists of exactly one line with two positive integers separated by space. These are the reversed numbers you are to add.</p>
<p><strong>Output</strong></p>
<p>For each case, print exactly one line containing only one integer - the reversed sum of two reversed numbers. Omit any leading zeros in the output.</p>
</blockquote>
<pre><code>import java.util.*;
import java.lang.*;
class Main
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner sc = new Scanner(System.in);
sc.nextLine();
while(sc.hasNextInt())
{
printNextNumber(sc);
}
}
public static void printNextNumber(Scanner sc)
{
int a = sc.nextInt();
int b = sc.nextInt();
int reversedA = reverseNumber(a);
int reversedB = reverseNumber(b);
int reversedSum = reverseNumber(reversedA+reversedB);
System.out.println(reversedSum);
}
public static int reverseNumber(int number)
{
return listToNumberMadeOfDigits(numberToListOfDigits(number));
}
public static List<Integer> numberToListOfDigits(int number)
{
List<Integer> list = new ArrayList<>();
while(number>0){
list.add(number%10);
number /= 10;
}
Collections.reverse(list);
return list;
}
public static int listToNumberMadeOfDigits(List<Integer> digits)
{
int number = 0;
for(int i = 0; i < digits.size();i++){
number += Math.pow(10,i)*digits.get(i);
}
return number;
}
}
</code></pre>
<p>How is this code?
What should I avoid in the future?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T17:23:57.567",
"Id": "413161",
"Score": "0",
"body": "It's generally preferable to include the actual problem, rather than a link to the problem, since link rot is a thing. That's why you have the close vote."
}
] | [
{
"body": "<p>You can avoid the call to <code>Collections.reverse</code> by using a structure that allows for efficient additions to the front:</p>\n\n<pre><code>public static List<Integer> numberToListOfDigits2(int number)\n{\n // LLs allow for fast head additions\n LinkedList<Integer> list = new LinkedList<>(); \n\n while(number > 0) {\n list.addFirst(number % 10); // Note the change here\n number /= 10;\n }\n\n return list;\n}\n</code></pre>\n\n<p>This prevents <code>numberToListOfDigit</code> from needing to reiterate the whole list at the end to reverse it. For small lists, the overhead will be minimal, but it's worth thinking about.</p>\n\n<p>I also spaced out your <code>></code> and <code>%</code> calls for readability. You have everything (inconsistently) compacted in your other function as well. I'd change <code>listToNumberMadeOfDigits</code> to something closer to:</p>\n\n<pre><code>public static int listToNumberMadeOfDigits(List<Integer> digits)\n{\n int number = 0;\n\n for(int i = 0; i < digits.size(); i++) {\n number += Math.pow(10, i) * digits.get(i);\n }\n\n return number;\n}\n</code></pre>\n\n<p>I like space. I find it helps readability in nearly every situation.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T16:41:25.410",
"Id": "213602",
"ParentId": "213594",
"Score": "0"
}
},
{
"body": "<p>First, note that this review is of general good coding practices for production code, and not all suggestions will be appropriate for the sphere of \"competitive programming\", in which I have no significant experience.</p>\n\n<p>Some thoughts:</p>\n\n<p>For readability, use whitespace consistently and more frequently. There should be whitespace (0) after control statements (<code>if</code>, <code>while</code>, <code>for</code>), around operators (<code>+</code>, <code>%</code>, ..), and before curly braces (<code>{</code>).</p>\n\n<p>In Java, the convention is that open curly braces go on the same line, not on a newline.</p>\n\n<p>Use <code>final</code> aggressively when variable declarations will not change to reduce cognitive load on readers.</p>\n\n<p><code>AutoCloseable</code> resources such as <code>Scanner</code> should be used in a <code>try-with-resources</code> block to ensure they get closed.</p>\n\n<p><code>a</code> and <code>b</code> are poor choices for variable names because they're meaningless. Variable names should describe the value they hold. You probably don't even need the intermediate variables.</p>\n\n<p>Methods not intended for use outside their class should be <code>private</code>. Always prefer the most restrictive access you can reasonably apply.</p>\n\n<p>In a real application, it would be highly preferable to having the reversed sum pushed back to the <code>main()</code> method to handle printing. This gives you flexibility, rather than pushing your output choice through your code - if you want to change later, it changes in fewer, higher-level places. </p>\n\n<p>It might be nice to use the number of cases they provide you with. </p>\n\n<p>Don't throw <code>Exception</code> ever - throw the most specific checked exception possible. Don't declare thrown checked exceptions if you don't actually throw them.</p>\n\n<p>Your algorithm is much more complex than it needs to be. Lists are extraneous. The problem can be solved with math.</p>\n\n<p>If you were to apply all the changes I suggested, your code might look more like:</p>\n\n<pre><code>import java.util.Scanner;\n\nclass Main {\n\n public static void main(final String[] args) {\n try (final Scanner sc = new Scanner(System.in)) {\n final int numberOfCases = sc.nextInt();\n for (int i = 0; i < numberOfCases; i++) {\n final int firstNumber = sc.nextInt();\n final int secondNumber = sc.nextInt();\n System.out.println(addReversedNumbers(firstNumber, secondNumber));\n }\n }\n }\n\n private static int addReversedNumbers(final int firstNumber, final int secondNumber) {\n return reverseNumber(reverseNumber(firstNumber) + reverseNumber(secondNumber));\n }\n\n private static int reverseNumber(final int number) {\n int numberToReverse = number;\n int reversedNumber = 0;\n\n while (numberToReverse > 0) {\n final int digit = numberToReverse % 10;\n numberToReverse /= 10;\n reversedNumber = 10 * reversedNumber + digit;\n }\n return reversedNumber;\n\n }\n\n}\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T17:22:33.660",
"Id": "213609",
"ParentId": "213594",
"Score": "2"
}
},
{
"body": "<h3>Separate responsibilities cleanly</h3>\n\n<p>Which function's responsibility is it to parse the input?\nIn the posted code this is shared by <code>main</code> and <code>printNextNumber</code>.\n<code>main</code> parses the number of test cases and loops over them,\nand lets <code>printNextNumber</code> parse the individual test cases.</p>\n\n<p>It's confusing when a clear responsibility is split among multiple functions,\neach doing only part of it.\nWhy? These functions share objects and state (<code>scanner</code>),\ntherefore while working on any of these functions,\nyou have to keep in mind what impact the changes may have on the other.\nThis is really too much of a mental burden,\nit would be a lot easier if you could focus your attention on function, without worrying about another.</p>\n\n<p>The parsing of the input would have been better all in <code>main</code>.\nEspecially when I look at a function named <code>printNextNumber</code>,\nI don't expect any parsing to happen there, only printing.</p>\n\n<h3>Adding reversed numbers</h3>\n\n<p>Why are the numbers reversed? What's the point?\nIs the goal really to reverse numbers so you could add them and then reverse the result? Maybe it is, but I doubt it.</p>\n\n<p>Imagine if you had to add arbitrary large integers, so large that they don't fit in <code>int</code>, neither a <code>long</code>, for example <code>12345678901234567890</code> and <code>99999999999999999999999999</code>. How would you go about adding them?\nHow would you do it without a computer, only pen and paper?\nYou would start from the end, and work backwards.</p>\n\n<p>In a program, if the numbers are given reversed as string, and you have to return them in reverse and as string, then it's actually quite convenient for performing the addition digit by digit, appending the added digits to a <code>StringBuilder</code>.\nA solution is possible without reversing digits, and supporting arbitrarily large numbers. I suggest to try that way, as an exercise.\nThat is, implement this function:</p>\n\n<pre><code>private static String addReversedNumbers(String firstNumber, String secondNumber) {\n // TODO\n}\n</code></pre>\n\n<p>Which can be used by <code>main</code> as such:</p>\n\n<pre><code>public static void main(String[] args) {\n try (final Scanner sc = new Scanner(System.in)) {\n final int numberOfCases = sc.nextInt();\n for (int i = 0; i < numberOfCases; i++) {\n final String firstNumber = sc.next();\n final String secondNumber = sc.next();\n System.out.println(addReversedNumbers(firstNumber, secondNumber));\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T13:42:23.770",
"Id": "413221",
"Score": "0",
"body": "Thanks for your input! I have to pay more attention to separation of concerns. The goal was indeed to reverse two numbers, add them and reverse the result."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T13:42:58.533",
"Id": "413222",
"Score": "0",
"body": "I will try that exercice!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T14:58:28.100",
"Id": "413236",
"Score": "0",
"body": "\"The goal was indeed to reverse two numbers, add them and reverse the result.\" -> Well, you already have reversed numbers as inputs, and you're supposed to return reversed number as result. So in fact you don't need to do any reversing at all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T17:17:41.067",
"Id": "413258",
"Score": "0",
"body": "Maybe I'm looking over something but I don't understand. My inputs are numbers that I need to reverse, not reversed numbers."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T17:21:36.327",
"Id": "413261",
"Score": "0",
"body": "@AyoubRossi \"Input - [...] These are the reversed numbers you are to add. [...] Output - [...] print [...] the reversed sum of two reversed numbers.\" -- your inputs are reversed numbers, and the expected output is a reversed number too."
}
],
"meta_data": {
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T06:41:24.780",
"Id": "213641",
"ParentId": "213594",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": "213609",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T15:29:24.107",
"Id": "213594",
"Score": "1",
"Tags": [
"java",
"programming-challenge"
],
"Title": "SPOJ Adding reversed number in Java"
} | 213594 |
<p>This code shows two ways to calculate size of array of any type. I would like to know, which should be preferred? Is there any advantage/disadvantage?</p>
<pre><code>#include <iostream>
// First method
template<typename Arr>
std::size_t array_size_1(const Arr& arr)
{
return sizeof(arr)/sizeof(arr[0]);
}
// Second method
template<typename T, std::size_t sz>
std::size_t array_size_2(const T (&arr)[sz])
{
return sz;
}
int main() {
int arr[] = {1,2,3,4,5};
std::string sarr[] = {"abc", "def", "ghj"};
std::cout << array_size_1(arr) << "\n";
std::cout << array_size_2(sarr) << "\n";
return 0;
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T05:28:36.397",
"Id": "413199",
"Score": "2",
"body": "How about [std::size()](https://en.cppreference.com/w/cpp/iterator/size)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T14:51:19.040",
"Id": "413233",
"Score": "0",
"body": "@MartinYork That's unfortunately C++17."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T16:56:53.017",
"Id": "413256",
"Score": "0",
"body": "@Deduplicator Yea. But it tells you how to do it."
}
] | [
{
"body": "<p>Both suffer (equal amounts) from the problem that when you call them, the compiler has to go instantiate a new function from the template. The code all ends up inlined after optimization, but it <em>does</em> make more work for the compiler than something like</p>\n\n<pre><code>#define NELEM(x) (sizeof(x) / sizeof (x)[0])\n</code></pre>\n\n<p>The benefit of <code>array_size_2</code> is that if you try to call it as</p>\n\n<pre><code>int *p = nullptr;\nstd::vector<int> v;\nsize_t a = array_size_2(p); // ERROR\nsize_t b = array_size_2(v); // ERROR\n</code></pre>\n\n<p>the compiler will reject the call as ill-formed. Whereas if you do the same thing with <code>array_size_1</code> or <code>NELEM</code>, you'll just get for example <code>sizeof(int*) / sizeof(int)</code> or <code>sizeof(vector<int>) / sizeof(int)</code>, which isn't meaningful.</p>\n\n<p>So <code>array_size_2</code> saves you from accidentally writing something meaningless. Especially in cases like</p>\n\n<pre><code>int foo(int a[]) {\n return array_size_1(a); // OOPS!\n}\n</code></pre>\n\n<p>where <code>int a[]</code> is just syntactic sugar for <code>int *a</code> and there's no actual array in existence at all.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T20:37:51.677",
"Id": "413185",
"Score": "1",
"body": "#define-ing NELEM is not best practice in C++ (as tags states C++). `array_size_2` is a good way also to me."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T03:41:33.040",
"Id": "413198",
"Score": "0",
"body": "@fiorentinoing - Can you please explain why NELEM is not a good practice in c++ ?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T09:53:33.283",
"Id": "413210",
"Score": "0",
"body": "my reference is Scott Meyers, Effective C++, Item 2: prefer consts, enums, and inlines to #defines."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T16:24:11.033",
"Id": "213600",
"ParentId": "213595",
"Score": "5"
}
}
] | {
"AcceptedAnswerId": "213600",
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T15:36:04.957",
"Id": "213595",
"Score": "1",
"Tags": [
"c++",
"c++11",
"array",
"template"
],
"Title": "Calculating array size in C++"
} | 213595 |
<p>A method has been written that increments time in minutes that simulates how much time it takes to process item in a supermarket queue and if there is an empty queue, skip it and loops around to find the number of items processed in each interval (each time a minute has passed). I was wondering if there are ways to improve the code I have written??</p>
<pre><code>private Queue[] lines;
private double time; // Time measured in minutes
private static double item_per_min;
private static double time_inc;
private static Random rand = new Random();
static int x = 0;
public static final double lambda = item_per_min * time_inc;
public static double target_Probability = rand.nextDouble();
public static final double target_ProbabilityabilityOfX = Math.pow(lambda, x) * Math.exp(-lambda) / factorial(x); // Poisson
// distribution
public void add_time(double time_inc)
{
for (int i = 0; i < lines.length; i++) // Loops
{
if (lines[i].empty())
{
continue;
}
while (true)
{
time += time_inc;
if (target_ProbabilityabilityOfX > target_Probability)
{
break;
}
x++;
target_Probability -= target_ProbabilityabilityOfX;
}
while (!lines[i].empty() && x > 0)
{
lines[i].decrement();
x--;
}
}
this.display();
}
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T22:45:17.067",
"Id": "413189",
"Score": "0",
"body": "Do you use an IDE for development? Asking because indentation is inconsistent."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T18:05:14.553",
"Id": "413272",
"Score": "0",
"body": "I use eclipse, I think i messed with the indentation and dunno how to return it to normal"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T18:19:46.263",
"Id": "413275",
"Score": "0",
"body": "(Guessing here: you use three spaces per indentation level, and mix tabs and blanks in eclipse. Remedy: convert to blanks before copying to stackexchange.)"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T19:51:31.587",
"Id": "413291",
"Score": "0",
"body": "Stupid question. How would I do that??"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T22:57:07.310",
"Id": "413301",
"Score": "0",
"body": "(Inside Eclipse, I know no better than temporarily changing the language *code style*, marking the text, \"correct indentation\", copy, paste wherever the \"blanked\" version is wanted, and roll back all changes *including Preferences*. A perfunctory doc&web search made me no wiser.)"
}
] | [
{
"body": "<blockquote>\n<pre><code> if (probK <= prob) { // increment k until cumulative probability, prob, reached\n k++;\n prob -= probK;\n } else {\n break;\n }\n</code></pre>\n</blockquote>\n\n<p>With this pattern, it's often better to write </p>\n\n<pre><code> if (probK > prob) {\n break;\n }\n\n k++;\n prob -= probK;\n</code></pre>\n\n<p>This saves some indent and makes it clear what is happening. We check for the end condition and then proceed normally if it was not reached. The other way, it's not obvious what the end condition is, since it is hidden in an <code>else</code>. </p>\n\n<p>But I would actually rewrite the whole loop. </p>\n\n<pre><code> int k = 0;\n for (double probabilityOfK = Math.exp(-lambda);\n probabilityOfK <= targetProbability; \n probabilityOfK *= lambda / k) {\n targetProbability -= probabilityOfK;\n k++;\n }\n</code></pre>\n\n<p>The <code>for</code> loop declaration is on three lines to eliminate side scroll on this site. It might fit on one line in actual code. </p>\n\n<p>I prefer <code>probabilityOfK</code> to <code>probK</code> as being more readable. I prefer <code>targetProbablity</code> to <code>prob</code> as being more descriptive. </p>\n\n<p>I stopped using <code>Math.pow</code> as a rather expensive calculation. It is replaced with a simple multiplication. And you were multiplying anyway, so that's effectively free. </p>\n\n<p>Now it doesn't use a loop forever pattern with a break. It just loops normally until the condition fails. </p>\n\n<p>This works because you never use <code>cumulativeProbability</code> outside the loop, but each value relates to the previous one. </p>\n\n<p>The result may change slightly due to double rounding. It's up to you if that matters. And if it does matter, if the original was better. </p>\n\n<blockquote>\n<pre><code> for (int i = 0; i < lines.length; i++) {\n</code></pre>\n</blockquote>\n\n<p>I would do this with a range-based <code>for</code> loop. Something like </p>\n\n<pre><code> for (Queue<?> line : lines) {\n</code></pre>\n\n<p>Then you could replace all the <code>lines[i]</code> with just <code>line</code>. Replace <code>Queue<?></code> as necessary. </p>\n\n<blockquote>\n<pre><code> while (!lines[i].isEmpty() && k > 0) {\n</code></pre>\n</blockquote>\n\n<p>Consider something like </p>\n\n<pre><code> if (k >= line.size()) {\n line.clear();\n continue;\n }\n\n while (k > 0) {\n</code></pre>\n\n<p>Now you don't have to check if <code>line</code> is empty, as you'll run out of <code>k</code> before you run out of <code>line</code>. </p>\n\n<p>You could move that check into the previous loop. Then if you reach the maximum possible <code>k</code>, you can stop immediately rather than continuing. That might be more efficient. Something like </p>\n\n<pre><code> for (Queue<?> line : lines) {\n if (line.isEmpty()) {\n continue;\n }\n\n updateLine(line);\n }\n</code></pre>\n\n<p>and </p>\n\n<pre><code> public void updateLine(Queue<?> line) {\n int k = 0;\n for (double probabilityOfK = Math.exp(-lambda);\n probabilityOfK <= targetProbability; \n probabilityOfK *= lambda / k) {\n\n targetProbability -= probabilityOfK;\n k++;\n\n if (k >= line.size()) {\n line.clear();\n return;\n }\n }\n\n while (k > 0) {\n line.decrement();\n k--;\n }\n }\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T19:48:19.530",
"Id": "413289",
"Score": "0",
"body": "I have changed the code, based on your suggestions, but don't quite understand the Collections<?> and the if statement you suggested at the bottom. And line is a array of Queue."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T19:53:02.647",
"Id": "213619",
"ParentId": "213597",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T16:04:19.313",
"Id": "213597",
"Score": "2",
"Tags": [
"java",
"random",
"statistics",
"simulation"
],
"Title": "Incrementing time in a discrete-event simulation of a supermarket queue"
} | 213597 |
<p>I have written code for making a Chess Validator, which will validate the moves of a chess game.
There is a <strong>Main</strong> class which is taking the input from the user, about the move.</p>
<h1>Problem Description</h1>
<blockquote>
<p>The board is maintained in the form of a 2D matrix, which contains the pieces as <strong>{color}{type}</strong>. </p>
<p>Eg. <strong>BH : black horse</strong>. </p>
<p>Pieces: </p>
<ul>
<li>K: king, </li>
<li>Q: queen, </li>
<li>P: pawn, </li>
<li>R: rook, </li>
<li>C: bishop, </li>
<li>H: horse </li>
</ul>
<p>A Move is defined as <strong>{color}{type} {src i}{src j} {dest i}{dest j}</strong>
where <span class="math-container">\$i\$</span> denotes row and <span class="math-container">\$j\$</span> gives column.<br>
Eg. <strong><em>BP 12 22</em></strong>,
which move black pawn from <span class="math-container">\$(1,2)\$</span> to <span class="math-container">\$(2,2)\$</span>.</p>
</blockquote>
<h1>The Implementation</h1>
<p><code>Piece</code> is taken as an abstract class, which is being implemented by the different pieces <code>King</code>, <code>Rook</code>, <code>Queen</code>, <code>Bishop</code>, <code>Horse</code>, <code>Pawn</code>. A <code>Piece</code> has a basic validation rule defined as common. All pieces have their own specific move, and a validation specific to the piece type.<br>
<code>Bishop</code> move is still missing in code. </p>
<p>Using <strong>Factory design pattern</strong>, the object of the specific piece is created, and further movements and validations are performed.
Board allows its default, as well as user defined initialization.</p>
<h2>Piece class</h2>
<pre><code>public abstract class Piece {
private char color;
public char getColor() {
return color;
}
public void setColor(char color) {
this.color = color;
}
public abstract boolean validateForPiece(int srcX, int srcY, int destX, int destY);
public void move(int srcX, int srcY, int destX, int destY, String piece) {
Board.CHESS_BOARD[destX][destY]=piece;
Board.CHESS_BOARD[srcX][srcY]="--";
}
public boolean checkMiddlePieces(int srcX, int srcY, int destX, int destY) {
if(srcX==destX && srcY!=destY) {
for(int i=srcY+1;i<destY;i++) {
if(Board.CHESS_BOARD[destX][i]!="--")
return false;
}
}
else if(srcX!=destX && srcY==destY) {
for(int i=srcX+1;i<destX;i++) {
if(Board.CHESS_BOARD[i][destY]!="--")
return false;
}
}
else if(Math.abs(srcX-destX)==Math.abs(srcY-destY)) {
for(int i=srcX+1,j=srcY+1;i<destX && j<destY;i++,j++) {
if(Board.CHESS_BOARD[i][destY]!="--")
return false;
}
}
return true;
}
public boolean validateFirst(int srcX, int srcY, int destX, int destY, String piece) {
char color = piece.charAt(0);
if(srcX>=8 || destX>=8 || srcY>=8 || destY>=8) {
System.out.println("Exception handled");
return false;
}
if(Board.CHESS_BOARD[srcX][srcY].equals("--")) {
System.out.println("Invalid move: No piece in this place");
return false;
}
if(!Board.CHESS_BOARD[srcX][srcY].equals(piece)) {
System.out.println("Invalid move: Different piece at given source");
return false;
}
if(Board.CHESS_BOARD[destX][destY]!="--") {
if(Board.CHESS_BOARD[destX][destY].charAt(0)==color) {
System.out.println("Invalid move: Your color piece at that place");
return false;
}
}
return true;
}
}
</code></pre>
<h2>Pawn class</h2>
<pre><code>public class Pawn extends Piece {
@Override
public boolean validateForPiece(int srcX, int srcY, int destX, int destY) {
if(Board.TOP_WHITE) {
if(this.getColor()=='W' && destX-srcX<0)
return false;
if(this.getColor()=='B' && destX-srcX>0)
return false;
}
else {
if(this.getColor()=='B' && destX-srcX<0)
return false;
if(this.getColor()=='W' && destX-srcX>0)
return false;
}
if(((srcX==1 || srcX==6) && (Math.abs(destX-srcX)==2))
|| ((srcX!=1 || srcX!=6) && (Math.abs(destX-srcX)==1))
&& srcY==destY) {
return true;
}
if(Math.abs(srcY-destY)==1) {
if(Board.CHESS_BOARD[destX][destY]=="--")
return true;
}
if(Math.abs(srcX-destX)==1 && Math.abs(srcY-destY)==1) {
return true;
}
return false;
}
}
</code></pre>
<p>The other classes like <code>Rook</code>, <code>King</code>, <code>Queen</code>, etc are also written in the same format, with different validation logic.</p>
<h2>MoveImpl class</h2>
<pre><code>public class MoveImpl implements Move {
String piece;
int srcX;
int srcY;
int destX;
int destY;
char color;
char pieceType;
private void initializeValues(String inputMove[]) {
piece = inputMove[0];
srcX = Integer.parseInt(""+inputMove[1].charAt(0));
srcY = Integer.parseInt(""+inputMove[1].charAt(1));
destX = Integer.parseInt(""+inputMove[2].charAt(0));
destY = Integer.parseInt(""+inputMove[2].charAt(1));
color = piece.charAt(0);
pieceType = piece.charAt(1);
}
@Override
public void move(String inputMove[]) {
initializeValues(inputMove);
Piece pieceObj = PieceFactory.getPiece(piece);
boolean check1=pieceObj.validateFirst(srcX, srcY, destX, destY, piece);
boolean check2=pieceObj.validateForPiece(srcX, srcY, destX, destY);
if(!check1 || !check2)
System.out.println("Invalid move");
if(check1 && check2)
pieceObj.move(srcX, srcY, destX, destY, piece);
}
}
</code></pre>
<h2>Main class</h2>
<pre><code>public class Main {
public static void main(String[] args) throws IOException {
Move move = new MoveImpl();
System.out.println("Input:");
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String inp = br.readLine();
if(inp.equals("Board")) {
String board[][] = new String[8][8];
for(int i=0;i<8;i++) {
String row = br.readLine();
String rowArr[]=row.split(" ");
if(row.trim()!="")
for(int j=0;j<8;j++) {
board[i][j] = rowArr[j];
}
}
BoardInitializer.initialize(board);
System.out.println();
System.out.println("INITIAL STATE:");
BoardInitializer.displayBoardState();
}
else if(inp.equals("Display")) {
BoardInitializer.initialize();
System.out.println();
System.out.println("INITIAL STATE:");
BoardInitializer.displayBoardState();
}
inp=br.readLine();
if(inp.equals("Moves")){
while(inp!=null && inp.trim()!="") {
if(inp.trim().equals(""))
break;
inp = br.readLine();
if(inp.trim().equals(""))
break;
String inputMove[]=inp.split(" ");
move.move(inputMove);
BoardInitializer.displayBoardState();
}
}
}
}
</code></pre>
<p><strong>Github link:</strong> <a href="https://github.com/yashi320/Chess-Validator/tree/b9a2df847ebb7b1576259175cce0d18411044b48" rel="nofollow noreferrer">https://github.com/yashi320/Chess-Validator</a></p>
<h2>Sample Input and Output:</h2>
<pre><code>Input:
Display
INITIAL STATE:
CURRENT BOARD:
BR BH BC BK BQ BC BH BR
BP BP BP BP BP BP BP BP
-- -- -- -- -- -- -- --
-- -- -- -- -- -- -- --
-- -- -- -- -- -- -- --
-- -- -- -- -- -- -- --
WP WP WP WP WP WP WP WP
WR WH WC WQ WK WC WH WR
Moves
BP 12 32
CURRENT BOARD:
BR BH BC BK BQ BC BH BR
BP BP -- BP BP BP BP BP
-- -- -- -- -- -- -- --
-- -- BP -- -- -- -- --
-- -- -- -- -- -- -- --
-- -- -- -- -- -- -- --
WP WP WP WP WP WP WP WP
WR WH WC WQ WK WC WH WR
BP 32 12
Invalid move
CURRENT BOARD:
BR BH BC BK BQ BC BH BR
BP BP -- BP BP BP BP BP
-- -- -- -- -- -- -- --
-- -- BP -- -- -- -- --
-- -- -- -- -- -- -- --
-- -- -- -- -- -- -- --
WP WP WP WP WP WP WP WP
WR WH WC WQ WK WC WH WR
</code></pre>
<p>Please suggest possible improvements in the design.</p>
| [] | [
{
"body": "<h2>Use Standards</h2>\n\n<p>Use standard notations and representations whenever possible: see <a href=\"https://en.wikipedia.org/wiki/Algebraic_notation_(chess)\" rel=\"noreferrer\">Algebraic Notation</a> for example.</p>\n\n<h2>Avoid Global Variables</h2>\n\n<p><code>Board.CHESS_BOARD</code> is a global variable. <a href=\"http://wiki.c2.com/?GlobalVariablesAreBad\" rel=\"noreferrer\">Global variables are bad</a>. So instead of a global variable, pass the board as an argument to the method. It is very possible that a program may need to consider multiple chessboard states at the same time, so static variables are just unsuitable.</p>\n\n<h2>Test and Fix Bugs</h2>\n\n<p>pawn movement is buggy:</p>\n\n<pre><code>if(((srcX==1 || srcX==6) && (Math.abs(destX-srcX)==2)) \n || ((srcX!=1 || srcX!=6) && (Math.abs(destX-srcX)==1)) \n && srcY==destY) {\n return true;\n}\n</code></pre>\n\n<p>You haven't checked for the emptiness of the destination square, and returned true.\nA pawn can move forward, but cannot attack forward. In order to make the method clearer split it into canAttack and canMove</p>\n\n<p>Buggy as well:</p>\n\n<pre><code>if(Math.abs(srcY-destY)==1) {\n if(Board.CHESS_BOARD[destX][destY]==\"--\")\n return true;\n}\n</code></pre>\n\n<p>Pawns can attack but cannot move diagonally.</p>\n\n<h2>Use Conventional Formatting</h2>\n\n<p>Non-standard formatting looks confusing, weird and unprofessional. When you are new to a language it isn't obvious to you, but when you get used to the language it's obvoius and jarring. Here are a few very common and widely accepted conventions that your code doesn't follow <a href=\"https://www.oracle.com/technetwork/java/javase/documentation/codeconventions-141388.html\" rel=\"noreferrer\">from Sun's Java Code Convention</a></p>\n\n<ul>\n<li><blockquote>\n <p>A keyword followed by a parenthesis should be separated by a space. </p>\n</blockquote></li>\n</ul>\n\n<p><code>if (</code>, <code>while (</code>, <code>for (</code>, <code>try (</code></p>\n\n<ul>\n<li><blockquote>\n <p>All binary operators except . should be separated from their operands by spaces.</p>\n</blockquote></li>\n<li><blockquote>\n <p>The expressions in a for statement should be separated by blank spaces. </p>\n \n <p>Example: <code>for (expr1; expr2; expr3)</code></p>\n</blockquote></li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T08:39:03.627",
"Id": "213702",
"ParentId": "213606",
"Score": "8"
}
},
{
"body": "<p>I would like to add few more points to the previous answers with respect to design.</p>\n\n<p>If you are following the approach that chess board has the information about piece positioning, and piece is just type and have information about its type of movement and whether it can be blocked or not. </p>\n\n<p>Considering this, Piece abstract class should not have attribute 'color'. As board is responsible for knowing at which place which piece is there and what is the actual colour of the piece.</p>\n\n<pre><code>public abstract class Piece {\n private char color; // It can be removed.\n</code></pre>\n\n<p>As the Piece is actually providing a contract about its movement, You should follow approach of interface implementation and can define Piece as an interface with contract method of movement and which can be implemented by type of piece King(K) , Knight(N) , Bishop(B) etc and these classes will be provide the implementation about there movement</p>\n\n<pre><code>public interface Piece{\n //for checking the move is valid or not\n boolean canMove(int srcX, int srcY, int destX, int destY, String[][] board);\n //for checking whether the movement is blocked by any piece in between or not\n //i.e. Knight won't get blocked, But other pieces can get blocked if any piece is in between the path\n boolean isBlocked(int srcX, int srcY, int destX, int destY, String[][] board);\n}\n</code></pre>\n\n<p>Other normal validation like source/ destination is in bound , source has valid piece or not. can be handled as separate validation class which can follow Chain of responsibility design pattern. Implementation i am leaving to you.</p>\n\n<p>Please open a new question with these changes, if you agree with the points; then we can look in depth for the other comments. </p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T10:00:58.637",
"Id": "213709",
"ParentId": "213606",
"Score": "2"
}
},
{
"body": "<p>Thank you for releasing your code! You have some clever solutions and I would like to add few more points to the previous answers.</p>\n\n<h1>Naming</h1>\n\n<h2>Piece</h2>\n\n<p>The class <code>Pawn</code> confuses me, not because it is to complicated, but because of its name. <code>Pawn</code> is used to validate a movement and to do a move of a piece on the board, while the name suggests that it is the piece on the board. So with other words: <em>It is not a piece it is a utility of a piece</em></p>\n\n<p>The abstract class <code>Piece</code> could be renamed to <code>AbstractMovements</code> and <code>Pawn</code> to <code>PawnMovements</code>.</p>\n\n<p>Note the appended <em>s</em> to the names, which indicates that it is a utility class. You can find some in the Java-World like <code>Collections</code>, <code>Objects</code> and so on.</p>\n\n<h2>Move</h2>\n\n<p>Additional the class <code>MoveImpl</code> is not responsible for a move. The moves are done by the implementations of <code>Piece</code> (<code>AbstractMovements</code>). Actual <code>MoveImpl</code> response is to extract the movement information from the users input and delegate it to a <code>Piece</code>. I think it would make sense to rename the abstract class <code>Move</code> to <code>Reader</code> and <code>MoveImpl</code> to <code>ComandLineReader</code>.</p>\n\n<h1><a href=\"http://wiki.c2.com/?PrimitiveObsession\" rel=\"noreferrer\">Primitive Obsession</a></h1>\n\n<blockquote>\n <p>Primitive Obsession is using primitive data types to represent domain ideas. For example, we use a String to represent a message [...]</p>\n</blockquote>\n\n<p>The code-base contains a heavy use of <code>int</code> to represent a <code>Position</code> as a <code>source</code> and <code>destination</code>, <code>String</code> gets abused to represent a <code>Piece</code> and <code>String[][]</code> represents the board.</p>\n\n<h2>Examples</h2>\n\n<p>The method signiture of <code>validateForPiece</code> in <code>Piece</code> could look like </p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public boolean validateForPiece(Position source, Position destination)\n</code></pre>\n\n<p>or the class <code>MoveImpl</code> like</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class MoveImpl implements Move {\n\n Piece piece;\n Position source;\n Position destination;\n\n // ...\n}\n</code></pre>\n\n<p>With the new data-types the if-statements can be clearer. For example</p>\n\n<blockquote>\n <pre class=\"lang-java prettyprint-override\"><code>public boolean checkMiddlePieces(int srcX, int srcY, int destX, int destY) {\n if(srcX==destX && srcY!=destY) { /*..*/ }\n // ..\n}\n</code></pre>\n</blockquote>\n\n<p>could be look like</p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public boolean checkMiddlePieces(Position source, Position destination) {\n if(source.hasSameRowAs(destination) && source.hasNotSameColoumAs(destination)) { /*.. */ }\n // ..\n}\n</code></pre>\n\n<h1>The Main Class</h1>\n\n<p>The <code>main</code> looks like a <em>Factory</em> with super power. It should be possible to move these if-statements into its own class. The main class could interact with with a class called <code>ChessGame</code> or something like that, that knows all your chess logic. </p>\n\n<p>To check if the player enters the correct task at the correct time you could use the <a href=\"https://en.wikipedia.org/wiki/State_pattern\" rel=\"noreferrer\">State Pattern</a>. The <code>InputState</code> makes it possible for example that the user can't enter <em>\"Display\"</em> five times in a row or don't <em>\"Move\"</em> before <em>\"Display\"</em> or <em>\"Board\"</em></p>\n\n<pre class=\"lang-java prettyprint-override\"><code>public class Main {\n private ChessGame chessGame = new ChessGame();\n\n public static void main(String[] args) throws IOException {\n Move move = new MoveImpl();\n System.out.println(\"Input:\");\n BufferedReader br = new BufferedReader(new InputStreamReader(System.in));\n String input = br.readLine();\n\n chessGame.play(input);\n }\n}\n\npublic class ChessGame {\n\n private InputState inputState;\n\n public ChessGame() {\n // user needs to enter first \"Board\" or \"Display\"\n this.inputState = new InformationInputState(this); \n }\n\n void setState(InputState inputState) {\n this.inputState = inputState;\n }\n\n public void play(String input) {\n inputState.execute(input); \n }\n}\n\ninterface InputState {\n void execute(ChessGame, String input);\n}\n\nclass MoveInputState implements InputState {\n\n private ChessGame chessGame;\n\n // constructor\n\n public void execute(String input) {\n if (input.equals(\"Move\")) {\n // ..\n chessGame.setState(new InformationInputState(chessGame))\n }\n }\n}\n\nclass InformationInputState implements InputState {\n\n private ChessGame chessGame;\n\n // constructor\n\n public void execute(String input) {\n if (input.equals(\"Board\")) {\n // ..\n chessGame.setState(new MoveInputState(chessGame))\n } else if (\"Display\") {\n // ..\n chessGame.setState(new MoveInputState(chessGame))\n }\n }\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-20T17:27:31.477",
"Id": "413729",
"Score": "0",
"body": "Here, Pawn is a type of piece only. And the validate method in Pawn is validating rules which should be enforced for Pawn. Similarly, I have code for other pieces as well, which gives different implementation of validation of move for all."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-20T17:33:59.597",
"Id": "413730",
"Score": "0",
"body": "I will encorporate other suggestions in the code, escpecially Position class. Thanks @Roman"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-21T10:08:02.720",
"Id": "413817",
"Score": "0",
"body": "@YashiSrivastava you're welcome! Learn a lot by reading your code :] Keep it up!"
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T13:16:36.120",
"Id": "213726",
"ParentId": "213606",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T17:01:57.143",
"Id": "213606",
"Score": "5",
"Tags": [
"java",
"validation",
"factory-method",
"chess"
],
"Title": "Chess move validator"
} | 213606 |
<p>I am consistently timing out on the mentioned <a href="https://www.codewars.com/kata/n-smallest-elements-in-original-order-performance-edition/train/python" rel="nofollow noreferrer">kata</a>:</p>
<blockquote>
<p>Task
You will be given an array of random integers and a number n. You have to extract n smallest integers out of it preserving the original order.</p>
<h2>Examples</h2>
<pre class="lang-none prettyprint-override"><code>performant_smallest([1, 2, 3, 4, 5], 3) == [1, 2, 3]
performant_smallest([5, 4, 3, 2, 1], 3) == [3, 2, 1]
performant_smallest([1, 2, 3, 4, 1], 3) == [1, 2, 1]
performant_smallest([1, 2, 3, -4, 0], 3) == [1, -4, 0]
performant_smallest([2, 1, 3, 2, 3], 3) == [2, 1, 2]
</code></pre>
<h2>Notes</h2>
<ul>
<li>The number <code>n</code> will always be smaller then the array length </li>
<li>There will be duplicates in the array, and they have to be returned in the order of their each separate appearence<br>
Your solution has to be at least <strong>as fast</strong> as reference, passing the tests in <code>12000+ ms</code> </li>
<li>If you didn't pass a small amount of tests, try submitting again. Otherwise, your solution is not efficient enough. </li>
</ul>
<h2>Test suite</h2>
<pre class="lang-none prettyprint-override"><code>Tests: 1500
Array size: 4500
Numbers range: [-100..100]
Number of elements to return: 50-100% of the array
</code></pre>
<p>Note: you can't use Python 2</p>
</blockquote>
<p>I wrote several different functions for this:</p>
<pre class="lang-python prettyprint-override"><code>from heapq import *
from collections import Counter as count
from copy import copy
def heap_pop(lst, n):
heap, res, i = copy(lst), [0]*n, 0
heapify(heap)
c = count(heappop(heap) for _ in range(n))
for itm in lst:
if c.get(itm, 0) > 0:
res[i] = itm
i += 1
c[itm] -= 1
if i == n: break
return res
def sorting(lst, n):
res, i = [0]*n, 0
c = count(sorted(lst)[:n])
for itm in lst:
if c.get(itm, 0) > 0:
res[i] = itm
i += 1
c[itm] -= 1
if i == n: break
return res
def n_smallest(lst, n):
heap, res, i = copy(lst), [0]*n, 0
heapify(heap)
c = count(nsmallest(n, heap))
for itm in lst:
if c.get(itm, 0) > 0:
res[i] = itm
i += 1
c[itm] -= 1
if i == n: break
return res
def counter_sort(lst, n):
c = count(lst)
d, x, res, sm = sorted(c), {}, [0]*n, 0
for k in d:
z = min(c[k], n-sm)
x[k] = z
sm += z
if sm == n: break
sm = 0
for itm in lst:
if x.get(itm, 0) > 0:
res[sm] = itm
sm += 1
x[itm] -= 1
if sm == n: break
return res
def cs2(lst, n):
c = count(lst)
d, x, res, sm = sorted(c), {}, [0]*n, 0
for k in d:
z = min(c[k], n-sm)
x[k] = z
sm += z
if sm == n: break
sm = 0
for itm in (itm for itm in lst if itm in x):
if x.get(itm, 0) > 0:
res[sm] = itm
sm += 1
x[itm] -= 1
if sm == n: break
return res
def csy(lst, n):
c, sm = [0]*201, 0
for itm in lst: c[itm+100] += 1 #Map each number to num+100.
x, res, sm = {}, [0]*n, 0
for k in range(201):
z = min(c[k], n-sm)
x[k-100] = z
sm += z
if sm == n: break
sm = 0
for itm in lst:
if x.get(itm, 0) > 0:
res[sm] = itm
sm += 1
x[itm] -= 1
if sm == n: break
return res
def csz(lst, n):
c = [0]*201 #Our counter.
for itm in lst: c[itm+100] += 1 #Map each number to num+100.
res, sm = [0]*n, 0
for k in range(201): #Iterate through the numbers in our counter.
sm += c[k]
if sm >= n:
c[k] += n - sm #The sum of `c[:k+1]` should be equal to `n`, and this would give us the count of the `n` smallest elements.
break
sm = 0
for itm in lst: #Iterate through the list to present the elements in their appearance order in the list.
v = itm+100 #The mapping between the list item and its index in our counter.
if v <= k and c[v] > 0: #The item is one of the `n` smallest items.
res[sm] = itm #Place it in its position in the result list.
sm += 1
c[v] -= 1
if sm == n: break
return res
</code></pre>
<p>I benchmarked all of them (<code>lst</code> is 4500 random numbers in [-100, 100], and <code>n</code> in [2250, 4500] with 10000 iterations) to simulate the actual data set. I'm very surprised that none of my counting sort implementations worked considering that it is linear time and there were only two <span class="math-container">\$2 \, O(n)\$</span> iterations in it.</p>
<p><a href="https://i.stack.imgur.com/fbwDh.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/fbwDh.png" alt="enter image description here"></a></p>
<p><code>csz()</code> was the clear best performer, but it only gets to 1068 of the test cases before failing (the same applies to all my counting sort implementations; despite showing massive difference under the benchmark (17.6 - 29.2s) they all reach and terminate at 1068 test cases).</p>
<p><a href="https://i.stack.imgur.com/nJshv.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/nJshv.png" alt="enter image description here"></a></p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T19:29:38.067",
"Id": "413176",
"Score": "0",
"body": "Added new functions I tried. I don't think I *can* do any better."
}
] | [
{
"body": "<p>The Kata was broken—perhaps Codewars server load currently is a lot more than it was 9 months ago when the question was made—but for whatever reason, none of the top 6 solutions could pass within the time constraints imposed on the question. The kata was reworked after someone filed an issue, and now my solution passes. I did write an even more micro optimised version of counting sort which is what I eventually submitted. The only change I made was that since <code>n</code> was 50-100% of the list length it would be faster to find the n smallest elements by counting off the (length - <code>n</code>) largest elements than counting up to <code>n</code>, and since the array had a fixed length for the random tests, we could do that. Here's my final version:</p>\n<h2>My Code</h2>\n<pre><code>count = 0\n\ndef performant_smallest(lst, n):\n global count\n count += 1\n c = [0]*101 #Our counter.\n for itm in lst: c[itm+50] += 1 #Map each number to num+50\n res, sm, stop = [0]*n, 0, (5 - n if count <= 5 else 10000 - n)\n for k in range(100, -1, -1): #Iterate through the numbers in our counter starting backwards to get even better performance, since `n` is large.\n sm += c[k]\n if sm >= stop:\n c[k] = sm - stop #The sum of `c[:k+1]` should be equal to `n`, and this would give us the count of the `n` smallest elements.\n break\n sm = 0\n for itm in lst: #Iterate through the list to present the elements in their appearance order in the list.\n v = itm+50 #The mapping between the list item and its index in our counter.\n if v <= k and c[v] > 0: #The item is one of the `n` smallest items.\n res[sm] = itm #Place it in its position in the result list.\n sm += 1\n c[v] -= 1\n if sm == n: break\n return res\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T02:55:19.197",
"Id": "213684",
"ParentId": "213608",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213684",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T17:18:17.297",
"Id": "213608",
"Score": "5",
"Tags": [
"python",
"beginner",
"python-3.x",
"programming-challenge",
"time-limit-exceeded"
],
"Title": "Codewars: N smallest elements in original order"
} | 213608 |
<p>I have this code for predicting credit card default and it works perfectly, but I am checking here to see if anybody could make it more efficient or compact. It is pretty long though, but please bear with me.</p>
<pre><code># Import necessary libraries.
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
# Extracting data from .csv file.
file = 'C:\\Users\\alhut\\OneDrive\\Desktop\\credit card default project\\creditcard_default.csv'
dataset = pd.read_csv(file, index_col='ID')
dataset.rename(columns=lambda x: x.lower(), inplace=True)
# Preparing the data using dummy features (one-hot encoding). Base values are: other_education, female, not_married.
dataset['grad_school'] = (dataset['education'] == 1).astype('int')
dataset['universty'] = (dataset['education'] == 2).astype('int')
dataset['high_school'] = (dataset['education'] == 3).astype('int')
dataset.drop('education', axis=1, inplace=True) # Drops the education column because all the information is available in the features above.
dataset['male'] = (dataset['sex'] == 1).astype('int')
dataset.drop('sex', axis=1, inplace=True)
dataset['married'] = (dataset['marriage'] == 1).astype('int')
dataset.drop('marriage', axis=1, inplace=True)
# In the case of pay features, <= 0 means the payment was not delayed.
pay_features = ['pay_0','pay_2','pay_3','pay_4','pay_5','pay_6']
for p in pay_features:
dataset.loc[dataset[p]<=0, p] = 0
dataset.rename(columns={'default_payment_next_month':'default'}, inplace=True) # Renames last column for convenience.
# Importing objects from sklearn to help with the predictions.
from sklearn.model_selection import train_test_split
from sklearn.metrics import accuracy_score, precision_score, recall_score, confusion_matrix, precision_recall_curve
from sklearn.preprocessing import RobustScaler
# Scaling and fitting the x and y variables and creating the x and y test and train variables.
target_name = 'default'
X = dataset.drop('default', axis=1)
robust_scaler = RobustScaler()
X = robust_scaler.fit_transform(X)
y = dataset[target_name]
X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.15, random_state=123, stratify=y)
# Creating a confusion matrix.
def CMatrix(CM, labels=['pay','default']):
df = pd.DataFrame(data=CM, index=labels, columns=labels)
df.index.name='TRUE'
df.columns.name='PREDICTION'
df.loc['TOTAL'] = df.sum()
df['Total'] = df.sum(axis=1)
return df
# Preparing a pandas DataFrame to analyze models (evaluation metrics).
metrics = pd.DataFrame(index=['accuracy', 'precision', 'recall'],
columns=['NULL','LogisticReg','ClassTree','NaiveBayes'])
#######################
# The Null Model.
y_pred_test = np.repeat(y_train.value_counts().idxmax(), y_test.size)
metrics.loc['accuracy','NULL'] = accuracy_score(y_pred=y_pred_test, y_true=y_test)
metrics.loc['precision','NULL'] = precision_score(y_pred=y_pred_test, y_true=y_test)
metrics.loc['recall','NULL'] = recall_score(y_pred=y_pred_test, y_true=y_test)
CM = confusion_matrix(y_pred=y_pred_test, y_true=y_test)
CMatrix(CM)
# A. Logistic Regression.
# 1- Import the estimator object (model).
from sklearn.linear_model import LogisticRegression
# 2- Create an instance of the estimator.
logistic_regression = LogisticRegression(n_jobs=-1, random_state=15)
# 3- Use the trainning data to train the estimator.
logistic_regression.fit(X_train, y_train)
# 4- Evaluate the model.
y_pred_test = logistic_regression.predict(X_test)
metrics.loc['accuracy','LogisticReg'] = accuracy_score(y_pred=y_pred_test, y_true=y_test)
metrics.loc['precision','LogisticReg'] = precision_score(y_pred=y_pred_test, y_true=y_test)
metrics.loc['recall','LogisticReg'] = recall_score(y_pred=y_pred_test, y_true=y_test)
# Confusion Matrix.
CM = confusion_matrix(y_pred=y_pred_test, y_true=y_test)
CMatrix(CM)
# B. Classification Trees.
# 1- Import the estimator object (model).
from sklearn.tree import DecisionTreeClassifier
# 2- Create an instance of the estimator.
class_tree = DecisionTreeClassifier(min_samples_split=30, min_samples_leaf=10, random_state=10)
# 3- Use the trainning data to train the estimator.
class_tree.fit(X_train, y_train)
# 4- Evaluate the model.
y_pred_test = class_tree.predict(X_test)
metrics.loc['accuracy','ClassTree'] = accuracy_score(y_pred=y_pred_test, y_true=y_test)
metrics.loc['precision','ClassTree'] = precision_score(y_pred=y_pred_test, y_true=y_test)
metrics.loc['recall','ClassTree'] = recall_score(y_pred=y_pred_test, y_true=y_test)
# Confusion Matrix.
CM = confusion_matrix(y_pred=y_pred_test, y_true=y_test)
CMatrix(CM)
# C. Naive Bayes Classifier
# 1- Import the estimator object (model).
from sklearn.naive_bayes import GaussianNB
# 2- Create an instance of the estimator.
NBC = GaussianNB()
# 3- Use the trainning data to train the estimator.
NBC.fit(X_train, y_train)
# 4- Evaluate the model.
y_pred_test = NBC.predict(X_test)
metrics.loc['accuracy','NaiveBayes'] = accuracy_score(y_pred=y_pred_test, y_true=y_test)
metrics.loc['precision','NaiveBayes'] = precision_score(y_pred=y_pred_test, y_true=y_test)
metrics.loc['recall','NaiveBayes'] = recall_score(y_pred=y_pred_test, y_true=y_test)
# Confusion Matrix.
CM = confusion_matrix(y_pred=y_pred_test, y_true=y_test)
CMatrix(CM)
#######################
# Comparing the models with percentages.
100*metrics
# Comparing the models with a bar graph.
fig, ax = plt.subplots(figsize=(8,5))
metrics.plot(kind='barh', ax=ax)
ax.grid();
# Adjusting the precision and recall values for the logistic regression model and the Naive Bayes Classifier model.
precision_nb, recall_nb, thresholds_nb = precision_recall_curve(y_true=y_test, probas_pred=NBC.predict_proba(X_test)[:,1])
precision_lr, recall_lr, thresholds_lr = precision_recall_curve(y_true=y_test, probas_pred=logistic_regression.predict_proba(X_test)[:,1])
# Plotting the new values for the logistic regression model and the Naive Bayes Classifier model.
fig, ax = plt.subplots(figsize=(8,5))
ax.plot(precision_nb, recall_nb, label='NaiveBayes')
ax.plot(precision_lr, recall_lr, label='LogisticReg')
ax.set_xlabel('Precision')
ax.set_ylabel('Recall')
ax.set_title('Precision-Recall Curve')
ax.hlines(y=0.5, xmin=0, xmax=1, color='r')
ax.legend()
ax.grid();
# Creating a confusion matrix for modified Logistic Regression Classifier.
fig, ax = plt.subplots(figsize=(8,5))
ax.plot(thresholds_lr, precision_lr[1:], label='Precision')
ax.plot(thresholds_lr, recall_lr[1:], label='Recall')
ax.set_xlabel('Classification Threshold')
ax.set_ylabel('Precision, Recall')
ax.set_title('Logistic Regression Classifier: Precision-Recall')
ax.hlines(y=0.6, xmin=0, xmax=1, color='r')
ax.legend()
ax.grid();
# Adjusting the threshold to 0.2.
y_pred_proba = logistic_regression.predict_proba(X_test)[:,1]
y_pred_test = (y_pred_proba >= 0.2).astype('int')
# Confusion Matrix.
CM = confusion_matrix(y_pred=y_pred_test, y_true=y_test)
print('Recall: ', str(100*recall_score(y_pred=y_pred_test, y_true=y_test)) + '%')
print('Precision: ', str(100*precision_score(y_pred=y_pred_test, y_true=y_test)) + '%')
CMatrix(CM)
#######################
# Defining a function to make individual predictions.
def make_ind_prediction(new_data):
data = new_data.values.reshape(1, -1)
data = robust_scaler.transform(data)
prob = logistic_regression.predict_proba(data)[0][1]
if prob >= 0.2:
return 'Will default.'
else:
return 'Will pay.'
# Making individual predictions using given data.
from collections import OrderedDict
new_customer = OrderedDict([('limit_bal', 4000),('age', 50 ),('bill_amt1', 500),
('bill_amt2', 35509 ),('bill_amt3', 689 ),('bill_amt4', 0 ),
('bill_amt5', 0 ),('bill_amt6', 0 ), ('pay_amt1', 0 ),('pay_amt2', 35509 ),
('pay_amt3', 0 ),('pay_amt4', 0 ),('pay_amt5', 0 ), ('pay_amt6', 0 ),
('male', 1 ),('grad_school', 0 ),('university', 1 ), ('high_school', 0 ),
('married', 1 ),('pay_0', -1 ),('pay_2', -1 ),('pay_3', -1 ),
('pay_4', 0),('pay_5', -1), ('pay_6', 0)])
new_customer = pd.Series(new_customer)
make_ind_prediction(new_customer)
</code></pre>
| [] | [
{
"body": "<p>Not going to try a line-by-line analysis, but here are a couple broad suggestions:</p>\n\n<ul>\n<li><p><a href=\"https://stackoverflow.com/questions/419163/what-does-if-name-main-do\">Use a <code>__main__</code> block</a>, and keep the script locked away like that</p></li>\n<li><p>Use functions to compartmentalize logic, and <a href=\"https://dzone.com/articles/is-your-code-dry-or-wet\" rel=\"nofollow noreferrer\">don't repeat yourself</a>. You are clearly aware that your code exists as largely independent blocks of logic (hence your big comment bars), so use functions to name those blocks, then orchestrate how those functions get run to pass data back and forth, making it clear what information is needed where, and making it easier to see what logic is duplicated and what is unique to each part of your task. Rule of thumb: if you're copy-pasting code and just changing variable names (e.g. when you're making plots, computing metrics, etc.), make it a function instead.</p></li>\n<li><p>Put your imports at the top of the file. It's cleaner, and also serves like a header that tells other coders \"here are the kinds of things I'm going to do in this file.\"</p></li>\n</ul>\n\n<p>So your code might look more like:</p>\n\n<pre><code># All your other imports...\nfrom sklearn.naive_bayes import GaussianNB\n\n# ...\n\ndef run_classifier(classifier_type, classifier_kwargs, X_train, y_train, X_test, y_test, metrics):\n # 1- Import the estimator object (model).\n # 2- Create an instance of the estimator.\n classifier = classifier_type(**classifier_kwargs)\n\n # 3- Use the trainning data to train the estimator.\n classifier.fit(X_train, y_train)\n\n # 4- Evaluate the model.\n y_pred_test = classifier.predict(X_test)\n name = classifier_type.__name__\n metrics.loc['accuracy', name] = accuracy_score(y_pred=y_pred_test, y_true=y_test)\n metrics.loc['precision', name] = precision_score(y_pred=y_pred_test, y_true=y_test)\n metrics.loc['recall', name] = recall_score(y_pred=y_pred_test, y_true=y_test)\n\n # Confusion Matrix.\n CM = confusion_matrix(y_pred=y_pred_test, y_true=y_test)\n CMatrix(CM)\n\n return classifier, CM\n\n# ...\n\ndef main():\n # ...\n naive_bayes, nb_cm = run_classifier(NaiveBayes, {}, X_train, y_train, X_test, y_test)\n # etc.\n\n plot_pr_curve(naive_bayes, X_test, Y_test)\n # etc.\n\nif __name__ == '__main__':\n main()\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T08:40:27.850",
"Id": "413207",
"Score": "0",
"body": "Thanks a lot! I fixed up my code a bit based on what you told me, although I didn't see the need to use the main block. Mainly I created a model function and then used it to make the logistic regression, classification tree, and naive bayes models."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T00:18:06.610",
"Id": "413306",
"Score": "0",
"body": "@DeathExploit The reason to use a \"main block\" (by which I mean the ``if __name__ == '__main__'`` block at the bottom) is so that you can keep code from being run if you import this file from other code. For example, if you wanted to interact with these functions or code from an interactive terminal, you don't necessarily want it to train a bunch of classifiers and pop a bunch of plot windows just to be able to use these functions in your terminal. If you don't use that block, it makes the file almost unusable as anything but a standalone script (just like not putting code in functions)."
}
],
"meta_data": {
"CommentCount": "2",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T17:49:43.143",
"Id": "213612",
"ParentId": "213610",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "213612",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T17:28:09.363",
"Id": "213610",
"Score": "0",
"Tags": [
"python",
"finance",
"machine-learning"
],
"Title": "Predicting credit card default"
} | 213610 |
<p>I was solving <a href="https://leetcode.com/problems/hamming-distance/" rel="nofollow noreferrer">this Leetcode challenge about Hamming Distance</a>. Would love feedback on my syntax and code style. Here's the challenge description: </p>
<blockquote>
<p>The Hamming distance between two integers is the number of positions at which the corresponding bits are different.</p>
<p>Given two integers x and y, calculate the Hamming distance.</p>
<p>Note:
0 ≤ x, y < 2<sup>31</sup>.</p>
<p>Example:</p>
<p>Input: x = 1, y = 4</p>
<p>Output: 2</p>
<p>Explanation: </p>
<pre><code>1 (0 0 0 1)
4 (0 1 0 0)
↑ ↑
</code></pre>
<p>The above arrows point to positions where the corresponding bits are<br>
different.</p>
</blockquote>
<p>Here's my solution: </p>
<pre><code> def hammingDistance(x: 'int', y: 'int') -> 'int':
bin_x = bin(x)[2:]
bin_y = bin(y)[2:]
len_x = len(bin_x)
len_y = len(bin_y)
if len_x != len_y:
if len_x > len_y:
zeros = '0' * (len_x - len_y)
bin_y = zeros + bin_y
else:
zeros = '0' * (len_y - len_x)
bin_x = zeros + bin_x
dist = 0
for x,y in zip(bin_x, bin_y):
if x!=y:
dist += 1
return dist
</code></pre>
| [] | [
{
"body": "<p>That's a reasonable approach, but converting to strings early and then doing everything on strings leads to a lot of extra code. Note that this construct in your code, <code>if x!=y</code>, essentially XORs two bits and then does something if the result of that XOR is 1.</p>\n\n<p>Doing that XOR directly on the integers makes the problem simpler, the whole problem of having to pad with zeroes disappears (which about halves the code size already), and the problem is reduced to \"count the ones in binary\". That could still be done with a similar loop, but there is a short-cut:</p>\n\n<pre><code>return bin(x ^ y).count('1')\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T04:39:21.197",
"Id": "213637",
"ParentId": "213615",
"Score": "6"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T19:15:35.573",
"Id": "213615",
"Score": "4",
"Tags": [
"python",
"python-3.x",
"programming-challenge",
"bitwise",
"edit-distance"
],
"Title": "Hamming Distance in Python"
} | 213615 |
<p>I wrote this code to to perform the following:</p>
<ol>
<li>I will remove the "spaces" within the url.</li>
<li>Return welcome message.</li>
<li>Redirect the user to different url.</li>
<li>Compute HMAC for the request.</li>
<li>Return and revoke the user profile picture.</li>
</ol>
<p>Would someone please help me in checking if my code contains any security issues that I should avoid?</p>
<pre><code>import base64
import mimetypes
import os
import hashlib
import hmac
import requests
from django.core.urlresolvers import reverse
from django.http import HttpResponse
from django.shortcuts import redirect, render
from django.views.decorators.csrf import csrf_exempt
def ordenary(s):
return s.strip().replace(' ', '').lower()
def form_of_message(request):
env = {'message': request.GET.get('message', 'hello')}
response = render(request, 'forms/message_form.html', env)
response.set_cookie(key='message_rendered_at', value=time.time())
return response
def proxy(request):
url = request.GET.get('url')
return redirect(url)
def compute_hmac_signature(message, key):
key = bytes(key, 'UTF-8')
message = bytes(message, 'UTF-8')
digest = hmac.new(key, message, hashlib.sha1).hexdigest()
return "sha1={}".format(str(digest))
def user_pic(request):
"""A view that returns the user's avatar image"""
base_path = os.path.join(os.path.dirname(__file__), '../../images/avatars')
filename = request.GET.get('u')
try:
data = open(os.path.join(base_path, filename), 'rb').read()
except IOError:
return render(request, 'templates/avatar.html')
return HttpResponse(data, content_type=mimetypes.guess_type(filename)[0])
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T20:05:38.850",
"Id": "413180",
"Score": "2",
"body": "This looks like a set of functions, but they are never invoked. Do you have a usage example with this?"
}
] | [
{
"body": "<p>Some comments, with security issues <strong>highlighted:</strong></p>\n\n<ul>\n<li>Why would you remove whitespace from URLs? It is perfectly valid for URLs to contain whitespace, unencoded or encoded as <code>+</code> or <code>%20</code>. <strong>If your backend code can't handle whitespace there are much bigger fish to fry.</strong> In general:\n\n<ul>\n<li>Blacklisting is more dangerous than whitelisting, because it's easy to omit some values.</li>\n<li>Whitelisting parts of values (such as characters in a URL) is more dangerous than whitelisting entire values, because clever hackers often find a way to escape the sandboxing attempt by combining parts. For example, depending on how you pass values to your backend, <code>%20</code> in a URL may or may not be replaced with a space character.</li>\n<li>Blanket removal of parts of the input limits your application severely while providing very little security (because of the above). A better solution is to <em>escape</em> the input and <em>test the escaping</em> using previously insecure values. This escaping <em>should</em> be provided by the official libraries (such as SQL or shell escaping).</li>\n<li>An even better solution is to let the library do the escaping for you, for example with parametric SQL queries, because now you don't need to remember to escape every value yourself, only to use parameters rather than string concatenation.</li>\n</ul></li>\n<li>Why would you lowercase the URL? There's no security issue with uppercase characters that I've ever heard of. And again, limiting the URL space like this is a bad trade-off.</li>\n<li><strong><a href=\"https://www.owasp.org/index.php/Top_10_2010-A10-Unvalidated_Redirects_and_Forwards\" rel=\"nofollow noreferrer\">Redirecting to a URL without checking it against a strict whitelist first</a></strong> is a well-known security issue.</li>\n<li>Similarly, <strong>not validating the username parameter is a massive issue</strong> - what if I specify something like <code>u=../../etc/passwd</code>?</li>\n<li><strong>Why would you implement your own HMAC generator?</strong> It's built right into <a href=\"https://docs.python.org/3/library/hmac.html\" rel=\"nofollow noreferrer\">the standard library</a>, even in Python 2.</li>\n<li>What is the purpose of the <code>message_rendered_at</code> cookie?</li>\n<li>Guessing the MIME type indicates that someone could send a JavaScript, PDF or other potentially harmful file as their avatar. If this is shown to other people that could lead to <strong>remote code injection.</strong> This has already happened on many sites with Bitcoin mining scripts. At best you should instead convert all avatars to a single format (PNG is ideal for this) and serve that. If you really need some flexibility then allow a small set of well-known formats and change the file extension when saving it. Then use a <code>dict</code> to map file extension to MIME type.</li>\n<li><code>ordenary</code> is not an English word as far as I know. <code>ordinary</code> would not be a good function name either, because it gives the programmer no idea what it actually does. One thing I've found useful to determine better names for things is to use <a href=\"https://docs.python.org/3/library/typing.html\" rel=\"nofollow noreferrer\">type hints</a> and validate them using <code>mypy</code> with strict settings (not allowing <code>Any</code> type). It takes some getting used to, but doing this properly should tell you exactly what goes into and comes out of any function. A function which takes a <code>Request</code> to <code>/foo</code> and returns a <code>Response</code>, for example, could be a <code>respond_to_foo_request</code>.</li>\n<li>Some of the imports are unused.</li>\n</ul>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T20:12:20.077",
"Id": "213620",
"ParentId": "213617",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T19:46:18.027",
"Id": "213617",
"Score": "1",
"Tags": [
"python",
"django"
],
"Title": "Django functions to sanitize URL, return welcome message, redirect, compute HMAC, and manage profile picture"
} | 213617 |
<p>Explanation : I am adding new elements in the list until the window runs out. Head will have the earliest element and tail will have the most recent element. Once the window is over, every addition requires deletion of the very first element or least used in the list which was temporally inserted a lot earlier than other elements. An access to an existing page in the list brings it to the end of the list signifying most recent use.</p>
<p>List end represents most recent element in the cache.
List head represents earliest of all the elements in the cache.</p>
<p><code>Link.h</code></p>
<pre><code>#ifndef LINKLIST_LINK_H
#define LINKLIST_LINK_H
#include <iosfwd>
class Link{
private:
int value;
Link* next = nullptr;
public:
Link();
explicit Link(int key);
int getValue() const;
void setValue(int value);
Link *getNext() const;
void setNext(Link *next);
friend void operator<<(std::ostream& os, const Link &link);
};
#endif //LINKLIST_LINK_H
</code></pre>
<p><code>Link.cpp</code></p>
<pre><code>#include "Link.h"
#include <iostream>
Link::Link() {
}
Link::Link(int key) {
this->setValue(key);
}
int Link::getValue() const {
return value;
}
void Link::setValue(int value) {
Link::value = value;
}
Link *Link::getNext() const {
return next;
}
void Link::setNext(Link *next) {
Link::next = next;
}
void operator<<(std::ostream& os, const Link &link){
os<<link.getValue()<<" ";
}
</code></pre>
<p><code>LinkList.h</code></p>
<pre><code>#ifndef LINKLIST_LINKLIST_H
#define LINKLIST_LINKLIST_H
#include <vector>
#include "Link.h"
class LinkList{
protected:
Link* head = nullptr;
Link* tail = nullptr;
std::vector<void* >linksAddresses;
public:
virtual ~LinkList();
void insert(int key);
void push_back(int key);
void push_front(int key);
bool deleteKey(int key);
bool findKey(int key);
void insert_sorted(int key);
friend void operator<<(std::ostream& os, const LinkList &linkList);
void getLinksAddresses();
void printReverse() const;
void do_reverse();
Link* delete_at_pos(int n);
};
#endif //LINKLIST_LINKLIST_H
</code></pre>
<p><code>LinkList.cpp</code></p>
<pre><code>#include <iostream>
#include "LinkList.h"
void LinkList::insert(int key) {
push_back(key);
}
void LinkList::push_front(int key) {
Link *newNode = new Link(key);
if (head == nullptr) {
head = newNode;
tail = newNode;
} else {
newNode->setNext(head);
head = newNode;
}
//std::cout << "Inserted " << key <<" address : "<<&newNode << " at front\n";
}
void LinkList::push_back(int key) {
Link *newNode = new Link(key);
if (tail == nullptr) {
head = newNode;
tail = newNode;
} else {
tail->setNext(newNode);
tail = newNode;
}
//std::cout << "Inserted " << key << " at back\n";
}
bool LinkList::deleteKey(int key) {
Link *curr = head;
Link *prev = head;
if (head != nullptr && head->getValue() == key) {
Link *temp = head;
head = head->getNext();
if(head == nullptr)
tail = nullptr;
delete temp;
std::cout << "Deleted " << key << "\n";
return true;
}
while (curr != nullptr && curr->getValue() != key) {
prev = curr;
curr = curr->getNext();
}
if (curr == nullptr) {
std::cout << "To delete Key " << key << " doesn't exist\n";
return false;
} else {
prev->setNext(curr->getNext());
delete curr;
std::cout << "Deleted " << key << "\n";
return true;
}
}
bool LinkList::findKey(int key) {
Link *current = head;
while (current != nullptr && current->getValue() != key)
current = current->getNext();
return current != nullptr;
}
LinkList::~LinkList() {
Link *next;
Link *curr = head;
while (curr != nullptr) {
next = curr->getNext();
delete curr;
curr = next;
}
//std::cout<<"Memory freed\n";
}
void operator<<(std::ostream &os, const LinkList &linkList) {
Link *curr = linkList.head;
os << "List is : ";
while (curr != nullptr) {
os << *curr;
curr = curr->getNext();
}
os << '\n';
}
void LinkList::insert_sorted(int key) {
//TODO
}
void LinkList::getLinksAddresses() {
while (head != nullptr){
linksAddresses.push_back(&head);
std::cout<<&head<<" "<<head->getValue()<<"\n";
head = head->getNext();
}
}
void reverse(Link* head){
if(head!= nullptr){
reverse(head->getNext());
std::cout<<head->getValue()<<" ";
}
}
void LinkList::printReverse() const {
reverse(head);
std::cout<<"\n";
}
void LinkList::do_reverse() {
Link* prev = nullptr;
Link* curr = head;
Link* next = curr->getNext();
while (curr){
}
}
Link* LinkList::delete_at_pos(int n)
{
if(n <=0)
return head;
int count = 1;
Link* curr = head, *prev = nullptr;;
while(curr!=nullptr){
if(count == n)
break;
prev = curr;
curr = curr->getNext();
count++;
}
if(curr!=nullptr){
Link* temp = curr;
if(curr == head){
head = head->getNext();
}else{
prev->setNext(curr->getNext());
}
delete temp;
}
return head;
}
</code></pre>
<p><code>LRU.hpp</code></p>
<pre><code>#ifndef LINKLIST_LRU_HPP
#define LINKLIST_LRU_HPP
#include <iostream>
#include "LinkList.h"
class LRU : public LinkList{
private:
const int MAX = 4;
int max_len = 0;
Link* findPage(int key){
Link *current = LinkList::head;
while (current != nullptr && current->getValue() != key)
current = current->getNext();
return current;
}
public:
void insert(int key) override{
if(MAX > 0) {
Link *page = findPage(key);
if (page != nullptr) {
access(page->getValue());
return;
}
if (max_len >= MAX) {
deleteKey(LinkList::head->getValue());
max_len--;
}
push_back(key);
max_len++;
}
}
bool access(int key){
Link *current = findPage(key);
if(current == nullptr)
return false;
else{
int val = current->getValue();
deleteKey(val);
max_len--;
insert(val);
return true;
}
}
};
#endif //LINKLIST_LRU_HPP
</code></pre>
<p><code>main.cpp</code></p>
<pre><code>#include "LinkList.h"
#include "LRU.hpp"
#include <iostream>
void testingLinkedLRU();
int main() {
testingLinkedLRU();
return 0;
}
void testingLinkedLRU(){
LRU lru;
std::cout<<lru;
lru.insert(1);
std::cout<<lru;
lru.insert(2);
std::cout<<lru;
lru.insert(3);
std::cout<<lru;
lru.insert(4);
std::cout<<lru;
lru.insert(5);
std::cout<<lru;
lru.insert(6);
std::cout<<lru;
lru.access(3);
std::cout<<lru;
lru.insert(-5);
std::cout<<lru;
lru.insert(5);
std::cout<<lru;
lru.insert(50);
std::cout<<lru;
lru.access(5);
std::cout<<lru;
lru.access(1);
std::cout<<lru;
lru.access(-5);
std::cout<<lru;
}
</code></pre>
| [] | [
{
"body": "<ul>\n<li><p>It is misleading that the same field in <code>Link</code> is sometimes referred as <code>key</code> and sometimes as <code>value</code>.</p></li>\n<li><p><code>LRU::insert</code> works too hard.</p>\n\n<ul>\n<li>It calls <code>findPage</code>, followed by <code>access</code>, which in turn calls \n\n<ul>\n<li><code>findPage</code> <em>with the same argument</em>, and</li>\n<li><code>deleteKey</code>, which also traverses the list <em>looking for the same key</em>.</li>\n</ul></li>\n</ul>\n\n<p>Three traversals with the same argument seems excessive. Consider finding the page which <em>links to</em> the victim.</p></li>\n<li><p>A standard implementation of the linked list may exhibits an undesirable behavior. Continuous deletion and creation of nodes will eventually scatter the nodes all over the heap, leading to the poor referential locality, hence plenty of cache misses during traversal. Since your list by definition has a fixed number of entries, try to keep your <code>Link</code>s compactly, say in an array, and reuse them.</p></li>\n<li><p><code>LinkList::push_front</code> shall be streamlined. <code>head = newNode</code> is executed in both branches; take it out of <code>if/else</code>:</p>\n\n<pre><code> newNode->setNext(head);\n if (head == nullptr) {\n tail = newNode;\n }\n head = newNode;\n</code></pre>\n\n<p>Ditto for <code>push_back</code>.</p></li>\n<li><p>I do not endorse trivial getters and setters. There are no invariants to protect, so they just add noise. Making <code>Link::key</code> and <code>Link::next</code> public is just as good.</p></li>\n</ul>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T00:28:42.037",
"Id": "413197",
"Score": "0",
"body": "For the insert method and access method I found some common code between them so I ended up grouping it into a function. I guess I can change the access method to directly take the pointer and bring it to the end/front of the list. This way the access method need not call findPage. Also for optimizations I am gonna substitute the structures for hashtable + doubly linked list where the hash table will have the (key, memory_location) as an entry. this way we can look up and delte in O(1) time. I just wanted to implement a correctly behaving LRU first, irrespective of the time constraints."
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T00:03:37.363",
"Id": "213630",
"ParentId": "213621",
"Score": "5"
}
},
{
"body": "<ol>\n<li><p>One class per file, and each with a dedicated header, is a pretty heavy-handed attempt at getting novices to modularize. As it is often the case, it is also counter-productive in this case.</p>\n</li>\n<li><p><code>Link</code> is an internal implementation-detail of <code>LinkList</code> and derived classes, aside from unfortunately and inadvertently being exposed by <code>.delete_at_pos()</code>.</p>\n<p>Fix that one return, and make the class private.</p>\n</li>\n<li><p>As <code>Link</code> is an implementation-detail, there is no sense in trying and failing miserably to hide its details behind a dozen useless public members. Just expose them directly, the only one which <em>might</em> make sense to keep (though that is debatable) is the constructor.</p>\n</li>\n<li><p>Consider a more descriptive name for <code>LinkList</code>. Maybe <code>ForwardList</code>?</p>\n</li>\n<li><p>I wonder what <code>linksAddresses</code> is for, aside from taking up space.</p>\n</li>\n<li><p>There seems to be a lot of stubbed and half-done code left in <code>LinkList</code>. Other code is quite repetitive.</p>\n</li>\n<li><p>I suggest basing an LRU-cache on a <code>std::vector<T></code> or if the items are heavy, a <code>std::vector<std::unique_ptr<T>></code>. Also, just a single free function treating such a an LRU-cache might be good enough.</p>\n</li>\n<li><p>There is no reason to explicitly mention <code>nullptr</code> all the time for comparisons, this is C++ not Java or C#. Use <code>!</code> for negation as needed.</p>\n</li>\n</ol>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T01:57:46.303",
"Id": "213634",
"ParentId": "213621",
"Score": "4"
}
},
{
"body": "<p>This is a really useful thing to implement! Good choice of projects. Here are some thoughts on how you could improve it:</p>\n<h1>Naming</h1>\n<p>Generally when I think of a linked list I don't think of a list of links. I think of a list of nodes which are linked to each other (via next and/or previous pointers). For that reason, I wouldn't call your class <code>Link</code>, I'd call it <code>Node</code>. The link in your class is the <code>next</code> pointer.</p>\n<p>The distinction between <code>push_back()</code> and <code>insert()</code> is unclear. In the base class there doesn't appear to be a difference as <code>insert()</code> simply calls <code>push_back()</code>. If I make an <code>LRU</code> object and call <code>push_back()</code> what are the consequences? (Or <code>push_front()</code> for that matter?) Perhaps <code>LRU</code> shouldn't make the methods of <code>LinkList</code> public. Also, renaming <code>insert()</code> to <code>add_new_cache_item()</code> would make clear which a caller should be using given a particular use case.</p>\n<p>Related method names should follow the same pattern. You have <code>insert()</code> but then its opposite is called <code>deleteKey()</code>. Presumably that's because <code>delete</code> is a keyword so you couldn't call it that. I'd either rename <code>insert()</code> to <code>insertKey()</code> or rename <code>deleteKey()</code> to simply <code>remove()</code>.</p>\n<h1>Do you need <code>setValue</code>?</h1>\n<p>Is there a reason why you need a <code>setValue()</code> method in <code>Link</code>? It's only called from the constructor. You could simply move the code for it into the constructor and get rid of the public function. (If you added a <code>next</code> parameter to the constructor you could make the class immutable which is helpful for multithreading, though it would involve changing some of the logic of updating the list.)</p>\n<h1>Encapsulation</h1>\n<p>I don't generally like <code>friend</code> functions. People will say that <code>operator<<()</code> is always a <code>friend</code> function. But here you're careful to keep the <code>Link</code> parameter <code>const</code> and it only calls the (also <code>const</code>) <code>getValue()</code> method. There's nothing here that requires it be a <code>friend</code> function, so I say get rid of the <code>friend</code> designation. Just make it a free function in the header.</p>\n<h1>Double-ended Queue</h1>\n<p>What you've created actually has a name other than "linked list". It's often called a <a href=\"https://en.wikipedia.org/wiki/Double-ended_queue\" rel=\"nofollow noreferrer\">double-ended queue</a> or <code>deque</code> for short. They have several useful characteristics such as being O(1) for insertion and deletion at the ends, as you've no doubt discovered. There is a standard container called <code>std::deque</code> that implements this. (Though I realize you tagged this as "reinventing the wheel", which is always good for learning!)</p>\n<h1>Avoid raw pointers</h1>\n<p>I agree with others that you could implement this with a <code>vector</code> or <code>array</code> (or <code>deque</code>) if you wanted to. But whatever you do, you should avoid using raw pointers. They have so many potential pitfalls that they're really not worth it. I recommend using either <code>std::unique_ptr</code> or <code>std::shared_ptr</code> depending on the situation. They help avoid a large class of resource management errors.</p>\n<h1>Symmetry</h1>\n<p>You should strive to make the interface for your classes symmetrical to make them easier to use and understand. By that I mean that if you have an <code>insert()</code> method that does one thing, the <code>remove()</code> or <code>delete()</code> method should do the opposite. In <code>LRU</code> you've overridden <code>insert()</code> to do things like increment the <code>max_len</code> counter. But then in <code>access()</code> you have to manually decrement it after calling <code>deleteKey()</code>. You should also override <code>deleteKey()</code> to call the base class and decrement <code>max_len</code> so that someone updating <code>access()</code> doesn't have to know this fact in the future. They can simply call <code>deleteKey()</code> and not worry about it.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T06:25:55.943",
"Id": "213638",
"ParentId": "213621",
"Score": "2"
}
}
] | {
"AcceptedAnswerId": "213630",
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T20:23:16.353",
"Id": "213621",
"Score": "4",
"Tags": [
"c++",
"linked-list",
"reinventing-the-wheel",
"memory-management"
],
"Title": "LRU implementation in C++ using a LinkedList"
} | 213621 |
<p>I am trying to get better at problem solving, so I am going through challenges on Project Euler.</p>
<h2><a href="http://projecteuler.net/problem=3" rel="nofollow noreferrer">Problem</a>:</h2>
<blockquote>
<p>The prime factors of 13195 are 5, 7, 13 and 29.</p>
<p>What is the largest prime factor of the number 600851475143 ?</p>
</blockquote>
<h2>My solution:</h2>
<p>My approach to this was the following process:</p>
<ul>
<li><p>Get all factors of the number</p>
</li>
<li><p>Identify prime factors by looping from 1 up to each factor. If the factor MOD the numbers going up is equal to 0 and the number is not 1 or the number itself, then it is not a prime. Then another for loop goes through each factor again and checks if it is not in the not primes list, hence making it a prime.</p>
</li>
<li><p>The last item in the primes list gives the biggest prime number</p>
</li>
</ul>
<p>Code:</p>
<pre><code>def get_factors(n):
factors = []
for i in range(1,n+1):
if n % i == 0:
factors.append(i)
return factors
def get_prime_factors(factors):
print(factors)
primes = []
not_primes = [1]
for i in range(len(factors)):
for k in range(1,factors[i]+1):
if factors[i] % k == 0 and factors[i] !=1 and k!=1 and k!=factors[i]:
not_primes.append(factors[i])
for i in factors:
if i not in not_primes:
primes.append(i)
return primes
def biggest_prime(primes):
biggest = primes[-1]
print(biggest)
factors = get_factors(600851475143)
primes = get_prime_factors(factors)
biggest_prime(primes)
</code></pre>
<h2>Problems with my solution:</h2>
<p>It seems like it is too overcomplicated, which is why it can only handle small numbers. The program did not finish executing for the number 600851475143.</p>
<p>What is specifically making my solution so inefficient, is it because I am using too many loops? How can I make it efficient?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T22:49:57.600",
"Id": "413190",
"Score": "0",
"body": "Please give examples of numbers handled and result. Did you try to obtain a run time profile?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T22:57:40.590",
"Id": "413192",
"Score": "0",
"body": "greybeard Well 13195 worked and gave 29. This is my first time using this site, I am not entirely sure what a run time profile is."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T22:58:41.840",
"Id": "413193",
"Score": "0",
"body": "@Newbie101 He wants you to run your code in a profiler to find where to slow spots are. I'm writing a review right now, but always consult a profiler if you're having difficulties finding out why code is slow or taking too much memory."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T23:07:09.407",
"Id": "413194",
"Score": "0",
"body": "Carcigenicate But what if my program does not finish executing, and it's been over 5 minutes..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T23:08:39.013",
"Id": "413195",
"Score": "0",
"body": "@Newbie101 Profilers can handle that. They watch the program as it runs and keep track of how much time is spent in each function."
}
] | [
{
"body": "<p>There's a few things that can be improved.</p>\n\n<p><code>get_factors</code> can be a generator:</p>\n\n<pre><code>def lazy_get_factors(n):\n for i in range(1,n+1):\n if n % i == 0:\n yield i\n</code></pre>\n\n<p>This means all the factors don't need to be entirely found ahead of time. This doesn't have much in the way of gains for you right now since you're relying on the length of the list of factors which means you'd have to realize the entire list anyways, but if you change your algorithm, it may be beneficial. If you substitute this into your code (which isn't necessarily beneficial in the current state), make sure to force the factors into a list first:</p>\n\n<pre><code>factors = list(get_factors(600851475143))\n</code></pre>\n\n<p>Although this defeats the purpose of making it lazy, it's necessary with your current algorithm.</p>\n\n<hr>\n\n<p>The only purpose of <code>not_primes</code> is to maintain \"seen\" membership. Right now, you're using a list to track membership, which is a bad idea since it means <code>in</code> will need to search the <em>entirety</em> of <code>not_primes</code> to see if it contains an element. Use a set here instead:</p>\n\n<pre><code>not_primes = {1} # A set\n. . .\nnot_primes.add(factors[i]) # add instead of append\n</code></pre>\n\n<p>This instantly makes <code>in</code> <em>much</em> faster. The code will no longer slow down as <code>not_primes</code> grows.</p>\n\n<hr>\n\n<p>The bottom bit of <code>get_prime_factors</code> can be written simply as:</p>\n\n<pre><code>return [fact for fact in factors if fact not in not_primes]\n</code></pre>\n\n<p>And then you can get rid of the <code>primes</code> list at the top.</p>\n\n<hr>\n\n<p><code>get_prime_factors</code> is far too big and encompassing too much. It's difficult to look at any single piece of it and easily tell what's going on. You should break the function up into multiple pieces. See my alternate solution below for an example of how much more readable that can make code. </p>\n\n<hr>\n\n<hr>\n\n<p>Here's an entirely different take on it. It uses quite a lot of generators. It's able to find the largest factor nearly instantly. See the comments in the code:</p>\n\n<pre><code>from math import sqrt\n\n# Lazily checks all the possible factors of n, yielding factors as it finds them\n# Ignores 1 as a factor since that's a given\ndef factors_of(n):\n # Sqrt is used here as an optimization\n for fact in range(2, int(sqrt(n) + 2)):\n # Uncomment the below line to see how it only does as much work as needed\n # print(fact)\n\n if n % fact == 0:\n yield fact\n\ndef is_prime(n):\n # This is cheap. It doesn't do any work up front.\n # It's only used here to see if the number has 0 or greater than 0 factors\n factors = factors_of(n)\n\n # An ugly way to check if a generator has any elements\n # WARNING: Consumes the first element if it exists!\n return n == 2 or \\\n not next(factors, None)\n\ndef prime_factors_of(n):\n factors = factors_of(n)\n\n return (fact for fact in factors if is_prime(fact))\n\ndef largest_prime_factor_of(n):\n prime_factors = prime_factors_of(n)\n\n # \"Apply\" the prime factors to max\n # Necessary since max is var-arg\n return max(*prime_factors)\n</code></pre>\n\n<p>See <a href=\"https://stackoverflow.com/a/21525143/3000206\">here</a> for an explanation of the <code>next(factors, None)</code> hack.</p>\n\n<p>Note that not everything here is optimal. The fact that <code>factors_of</code> doesn't return 1 is stupid, but if it did return 1, that would complicate <code>is_prime</code> as then I'd have to check if it contains greater than 1. I tried to keep it simple and brief.</p>\n\n<p>And arguably, <code>prime_factors_of</code> and <code>largest_prime_factor_of</code> don't need the <code>factors</code> and <code>prime_factors</code> variables. The whole of those functions could be on one line. I like having everything spaced out a bit though.</p>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T23:44:55.693",
"Id": "213628",
"ParentId": "213622",
"Score": "0"
}
},
{
"body": "<p>There are <a href=\"/search?q=600851475143+is%3Aquestion\">many questions about Project Euler 3</a> on this site already. The trick is to <a href=\"/a/48185/9357\">pick an algorithm</a> that…</p>\n\n<ul>\n<li>Reduces <code>n</code> whenever you find a factor, so that you don't need to consider factors anywhere near as large as 600851475143</li>\n<li>Only finds prime factors, and never composite factors</li>\n</ul>\n\n\n\n<pre><code>from itertools import chain, count\n\ndef biggest_prime_factor(n):\n for f in chain([2], count(3, 2)):\n while n % f == 0:\n n //= f\n if f >= n ** 0.5:\n return f if n == 1 else n\n\nprint(biggest_prime_factor(600851475143))\n</code></pre>\n",
"comments": [],
"meta_data": {
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T06:39:44.300",
"Id": "213640",
"ParentId": "213622",
"Score": "3"
}
}
] | {
"AcceptedAnswerId": "213628",
"CommentCount": "5",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T22:29:17.790",
"Id": "213622",
"Score": "1",
"Tags": [
"python",
"programming-challenge",
"time-limit-exceeded",
"primes"
],
"Title": "Work out largest prime factor of a number"
} | 213622 |
<p>My goal is to write a GUI application where a user can create a maze and select an algorithm. The passage of the algorithm from a selected start and end point should be visualized.</p>
<p>The following shows only the Breadth-First Search algorithm. During programming, I paid attention to the following things:</p>
<ul>
<li>readable APIs</li>
<li>SOLID-Principles</li>
<li>short and readable methods</li>
</ul>
<p>I am very grateful for a code review that focuses on the above points and things I don't yet have in mind.</p>
<h1>Breadth-First Search Algorithm</h1>
<h2>An Example</h2>
<blockquote>
<pre><code>
// .. build graph ..
BreadthFirstSearch breadthFirstSearch = BreadthFirstSearch.of(graph);
TraversalTable traversalTable = breadthFirstSearch.searchFrom(a);
Path path = traversalTable.to(b);
</code></pre>
</blockquote>
<h2>Breadth-First Search</h2>
<pre class="lang-java prettyprint-override"><code>public class BreadthFirstSearch {
private Graph graph;
private BreadthFirstSearch(Graph graph) {
this.graph = graph;
}
public static BreadthFirstSearch of(Graph graph) {
return new BreadthFirstSearch(graph);
}
public TraversalTable searchFrom(Vertex startVertex) {
Queue<Vertex> queue = new LinkedList<>();
TraversalTable traversalTable = new TraversalTable();
queue.add(startVertex);
traversalTable.add(new Traversal.Builder().withSuccessor(startVertex)
.withPredecessor(new NonVertex())
.withDistance(new Distance(0))
.build());
while (!queue.isEmpty()) {
Vertex currentVertex = queue.poll();
for (Vertex neighbor : graph.neighborsOf(currentVertex)) {
if (traversalTable.containsNot(neighbor)) {
Distance distance = traversalTable.distanceOf(currentVertex);
Traversal traversal = new Traversal.Builder().withSuccessor(neighbor)
.withPredecessor(currentVertex)
.withDistance(distance.increment())
.build();
traversalTable.add(traversal);
queue.add(neighbor);
}
}
}
return traversalTable;
}
}
</code></pre>
<h2>TraversalTable</h2>
<pre class="lang-java prettyprint-override"><code>public class TraversalTable {
private static Traversal.Builder DEFAULT_TRAVERSAL_BUILDER = new Traversal.Builder().withPredecessor(new NonVertex())
.withDistance(Distance.INFINITE);
private final Map<Vertex, Traversal> vertexByPredecessor;
TraversalTable(Map<Vertex, Traversal> vertexByPredecessor) {
this.vertexByPredecessor = vertexByPredecessor;
}
TraversalTable() {
this.vertexByPredecessor = new HashMap<>();
}
public void add(Traversal traversal) {
vertexByPredecessor.put(traversal.getSuccessor(), traversal);
}
public Distance distanceOf(Vertex vertex) {
return traversalOf(vertex).getDistance();
}
public Vertex predecessorOf(Vertex vertex) {
return traversalOf(vertex).getPredecessor();
}
public Path to(Vertex vertex) {
return isNotAccessible(vertex)
? Path.empty()
: to(predecessorOf(vertex), Path.startWith(vertex));
}
private Path to(Vertex vertex, Path path) {
return vertex.isPresent()
? to(predecessorOf(vertex), path.append(vertex))
: path;
}
public boolean isAccessible(Vertex vertex) {
return distanceOf(vertex).isNotInfinite();
}
public boolean isNotAccessible(Vertex vertex) {
return !isAccessible(vertex);
}
public boolean containsNot(Vertex vertex) {
return !contains(vertex);
}
public boolean contains(Vertex vertex) {
return vertexByPredecessor.containsKey(vertex);
}
private Traversal traversalOf(Vertex vertex) {
return vertexByPredecessor
.getOrDefault(vertex, DEFAULT_TRAVERSAL_BUILDER.withSuccessor(vertex).build());
}
@Override
public boolean equals(Object o) { /* ... */ }
@Override
public int hashCode() { /* ... */ }
@Override
public String toString() { /* ... */ }
}
</code></pre>
<h1>Looking for Recommendation</h1>
<h2>Recursion</h2>
<p>In <code>TraversalTable</code> the method <code>to</code> calls a overloaded private method <code>to</code> which builds recursively the <code>Path</code>.
In my opinion it looks cleaner that the previous while loop</p>
<blockquote>
<pre class="lang-java prettyprint-override"><code>public Path to(Vertex vertex) {
if (isAccessible(vertex))
return Path.empty();
Path path = Path.startWith(vertex);
Vertex predecessor = predecessorOf(vertex);
while (predecessor.isPresent()) {
path.append(predecessor);
predecessor = predecessorOf(predecessor);
}
return path;
}
</code></pre>
</blockquote>
<p>However, this method has the advantage of containing all the logic within a method, rather than my current solution where I shared the logic. Do you have a suggestion of legibility and maintainability?</p>
<h2>Level Of Indentation</h2>
<p>The method <code>searchFrom</code> in <code>BreadthFirstSearch</code> has a to high level of Indentation, but I left it that way because the algorithm is so well known. </p>
<blockquote>
<pre class="lang-java prettyprint-override"><code>public TraversalTable searchFrom(Vertex startVertex) {
// 1 lvl
while (!queue.isEmpty()) {
// 2 lvl
for (Vertex neighbor : graph.neighborsOf(currentVertex)) {
// 3 lvl
if (traversalTable.containsNot(neighbor)) {
// 4 lvl
}
}
}
return traversalTable
}
</code></pre>
</blockquote>
<p>If I split the logic into my own methods, I can reduce the level of indentation, but because of the variables that share the lower methods with the root method, they must be delegated, which makes the method's signatures unclear to me..</p>
<pre class="lang-java prettyprint-override"><code>public TraversalTable searchFrom(Vertex startVertex) {
Queue<Vertex> queue = new LinkedList<>();
TraversalTable traversalTable = new TraversalTable();
queue.add(startVertex);
traversalTable.add(new Traversal.Builder().withSuccessor(startVertex)
.withPredecessor(new NonVertex())
.withDistance(new Distance(0))
.build());
while (!queue.isEmpty()) {
Vertex currentVertex = queue.poll();
traversalAllNeighbors(currentVertex, traversalTable, queue);
}
}
private void traversal(Vertex successor, Vertex predecessor, TraversalTable traversalTable) {
Distance distance = traversalTable.distanceOf(currentVertex);
Traversal traversal = new Traversal.Builder().withSuccessor(neighbor)
.withPredecessor(currentVertex)
.withDistance(distance.increment())
.build();
traversalTable.add(traversal);
}
private void traversalAllNeighbors(Vertext vertex, TraversalTable traversalTable, Queue<Vertex> queue) {
for (Vertex neighbor : graph.neighborsOf(vertex)) {
if (traversalTable.containsNot(neighbor)) {
traversal(neighbor, vertex, traversalTable);
queue.add(neighbor);
}
}
}
</code></pre>
<hr>
<p>Additional to these two classes I implemented a <code>Path</code> and <code>Traversal</code> but this does not add any logic to the algorithm.</p>
| [] | [
{
"body": "<pre><code>new Traversal.Builder()\n .withSuccessor(...)\n .withPredecessor(currentVertex)\n .withDistance(distance.increment())\n .build();\n</code></pre>\n\n<p>Having to manually create the Builder instance with new goes against readability as it clutters the caller's code with knowledge of the Builder class. Explicit new operation binds the code to a certain class. I prefer</p>\n\n<pre><code>Traversal.withSuccessor(...)\n .withPredecessor(currentVertex)\n .withDistance(distance.increment())\n .build();\n</code></pre>\n\n<p>...where withSuccessor implicitely creates the Builder instance that corresponds to the meaning of withSuccessor(...). It allows a more readable way for instantiating objects when you have more than one way of instantiation. The Builder is still a public and visible to the caller, but they don't have to import it.</p>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T11:55:35.580",
"Id": "413357",
"Score": "0",
"body": "that was the only thinking i came up with... provide a builder for the initial traversal... `new Traversal.InitalBuilder().withSuccessor(startVertex))\n .build();`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T13:29:23.633",
"Id": "413371",
"Score": "0",
"body": "@MartinFrank, @TorbenPutkonen. What do you think if the `Traversal` class is `private` and you would build up a `Traversal` trough the `TraversalTable` like:\n`traversalTable.addTraversal().withSuccessor(...).withPredecessor(...).withDistance(...).build()`? \n\nThank you for your time!"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T13:38:12.660",
"Id": "413376",
"Score": "0",
"body": "@Roman the builder pattern is *in general* a good option, but it is a bit clumsy for the *initial traversal* since the first traversal does not have a distance nor a predecessor..."
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T13:41:44.283",
"Id": "413377",
"Score": "0",
"body": "@MartinFrank For that I wrote a class `NonVertex` which represents `null` (I know.. I need a better name :P) and the distance would be 0: `...Builder().withSuccessor(...).withPredecessor(new NonVertex()).withDistance(new Distance(0)).build()`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T14:01:34.787",
"Id": "413384",
"Score": "2",
"body": "@Roman since you already know these parameters are null when you create an *initial* traversal you could as well skip them... it's already know the initial traversal does not have a predecessor nor a distance. so use a initialBuilder instead of the default builder"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T14:01:40.797",
"Id": "413385",
"Score": "1",
"body": "@MartinFrank ahhh you mean that this are irrelevant information! I see.. maybe something like `..Builder().onlyWithSuccessor(...);` Yes, I think this could look nice :P"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T14:24:07.790",
"Id": "413390",
"Score": "0",
"body": "@Roman sorry my english really in need of improvement =) thank you for re-writing my point in such an proper way! and thanks for appreciating it"
}
],
"meta_data": {
"CommentCount": "7",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-18T06:38:30.883",
"Id": "213693",
"ParentId": "213623",
"Score": "1"
}
}
] | {
"AcceptedAnswerId": null,
"CommentCount": "0",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T22:43:49.813",
"Id": "213623",
"Score": "4",
"Tags": [
"java",
"algorithm",
"object-oriented",
"comparative-review",
"breadth-first-search"
],
"Title": "Object-Oriented Breadth-First Search Implementation"
} | 213623 |
<p>I'm pretty new to React and I was working on some JSON data. Now I just to understand basic concepts, so I wrote this little component, but in my eyes it's not efficient.</p>
<pre><code>import React from 'react';
import {getJson} from './getJson';
import AddRow from './AddRow';
class TableComponent extends React.Component {
constructor(props) {
super(props)
this.state = {
checked: true,
rows:[],
json: []
}
}
checkboxHandler() {}
componentDidMount() {
this.setState((prevState) => {
return {
json: getJson(),
}
})
}
checkAll = () => {
this.setState({
checked: !this.state.checked
})
this.setState(prevState => {
const json = prevState.json.map(obj => ({
...obj,
items: obj.items.map(item => ({
...item,
value: this.state.checked,
}))
}));
return { json };
});
};
render() {
return (
<div>
<table>
<tbody>
{this.state.json.map((obj, i) => {
return (
<tr key={obj.id}>
{obj.items.map((data, i) => {
return(
<td key={data.id}>
<p>{data.label}</p>
<input
type="checkbox"
checked={data.value}
onChange={this.checkboxHandler}
/>
</td>
)
})}
</tr>
)
})}
</tbody>
</table>
<button onClick={this.checkAll}>check\uncheck</button>
<AddRow actualJson={this.state.json}/>
</div>
)
}
}
export default TableComponent;
</code></pre>
<p>I'm not proud of it because I feel that I'm not respecting the heart of React - use module and components. Is there a way to have cleaner code?</p>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T15:47:05.400",
"Id": "413241",
"Score": "0",
"body": "Welcome to Code Review! (Something's wrong with the first part of your second sentence.) Can you add more of what the code is to accomplish to the title and/or the question?"
}
] | [
{
"body": "<p>There isn't much code to break this down to smaller components but based on the post : </p>\n\n<p><strong><a href=\"https://reactjs.org/docs/state-and-lifecycle.html\" rel=\"nofollow noreferrer\">this.setState()</a> passing an Object or a callback function :</strong></p>\n\n<p>If you want to update the state with a value that's not dependent on the previous one you can do :</p>\n\n<pre><code>this.setState({ key : newValue });\n</code></pre>\n\n<p>If you have to update the <code>state</code> based on the previous one, </p>\n\n<pre><code>this.setState(prevState => ({key: prevState.key + value }));\n</code></pre>\n\n<p>see <a href=\"https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous\" rel=\"nofollow noreferrer\">state updates may be asynchronous</a> for more details.</p>\n\n<p>the reason why i mention this is because in <code>componentDidMount()</code> you're passing a callback function to <code>setState</code> when you don't need the the <code>prevState</code>.</p>\n\n<pre><code>componentDidMount() {\n this.setState({ json: getJson() })\n}\n</code></pre>\n\n<p>In <code>checkAll()</code> you can do one <code>setState()</code> instead of two: </p>\n\n<pre><code>checkAll = () => {\n this.setState(prevState => ({\n checked: !prevState.checked,\n json: prevState.json.map(obj => ({\n ...obj,\n items: obj.items.map(item => ({\n ...item,\n value: prevState.checked,\n }))\n }))\n }));\n};\n</code></pre>\n\n<p><strong>Use <a href=\"https://stackoverflow.com/questions/28889450/when-should-i-use-return-in-es6-arrow-functions\">implicit return </a> in the render method :</strong></p>\n\n<p>the <code>render</code> method can use implict returns inthe <code>.map()</code> and you don't really need the <code>i</code>, it can be refactored to :</p>\n\n<pre><code>render() {\n return (\n <div>\n <table>\n <tbody>\n {this.state.json.map(obj => (\n <tr key={obj.id}>\n {obj.items.map(data => ( \n <td key={data.id}> \n <p>{data.label}</p>\n <input \n type=\"checkbox\" \n checked={data.value}\n onChange={this.checkboxHandler}\n />\n </td>)\n )}\n </tr>)\n )}\n </tbody>\n </table>\n <button onClick={this.checkAll}>check\\uncheck</button>\n <AddRow actualJson={this.state.json}/>\n </div>\n )\n}\n</code></pre>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T22:46:22.203",
"Id": "413299",
"Score": "1",
"body": "thanks for the feedback :) i will study it!"
}
],
"meta_data": {
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T20:14:32.067",
"Id": "213670",
"ParentId": "213625",
"Score": "0"
}
}
] | {
"AcceptedAnswerId": "213670",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T23:17:45.673",
"Id": "213625",
"Score": "1",
"Tags": [
"json",
"react.js",
"jsx"
],
"Title": "React table with JSON"
} | 213625 |
<p>First Code Review request =) I wrote this after making several projects that required a user to pick an option. I wanted to have a set way of forcing that choice in all of my projects. The module also contains a <code>GetNumberChoice()</code> func, but I'll save that for a separate post. </p>
<p>As a relatively green programmer, I'm looking for feedback on the Pythonic-ness, the structure of my functions, and any tips to improve my coding going forward. I really appreciate it!</p>
<pre><code>#!/usr/bin/env python
"""
This is part of a module that contains tools for getting input from a user. At any point while getting input, the user may enter "quit", "exit", or "leave" to quit()
"""
_EXIT_WORDS = ["quit", "exit", "leave"]
def GetStringChoice(prompt, **kwoptions):
"""
Print out the prompt and then return the input as long as it matches one of the options (given as key/value pairs)
Example call:
>>> prompt = "Who is the strongest Avenger?"
>>> input_options = {"t":"Thor", "i":"Iron Man", "c":"Captain America", "h":"The Hulk"}
>>> response = GetStringChoice(prompt, **input_options)
Who is the strongest Avenger?
- 't' for 'Thor'
- 'i' for 'Iron Man'
- 'c' for 'Captain America'
- 'h' for 'The Hulk'
h
>>> response
'h'
Invalid results are rejected:
>>> response = GetStringChoice(prompt, **input_options)
Who is the strongest Avenger?
- 't' for 'Thor'
- 'i' for 'Iron Man'
- 'c' for 'Captain America'
- 'h' for 'The Hulk'
Ant-Man
That wasn't one of the options.
Who is the strongest Avenger?
...
"""
OPTION_TEMPLATE = " - '{0}' for '{1}'" #used to display the kwoptions
MAX_LINE_LEN = 60
PAD = len(OPTION_TEMPLATE) - 6
# "- 6" in PAD removes the characters from the formatting brackets. I'm sure
# there's a better way of doing this... Previously I just hardcoded this to
# be 11 (the number of characters always in OPTION_TEMPLATE) but that seemed
# worse/less understandable
#This adjusts the section before the hyphen to be as wide as the longest key.
space = max(map(len, kwoptions))
while True:
try:
print(_TruncateAtMax(prompt))
for key in kwoptions:
#The _TruncateAtMax call adjusts the section after the hypen to be no longer than 60
# characters, and indents any overflow lines so that they start at the same place
# as the parent line starts.
print(OPTION_TEMPLATE.format(key.ljust(space), \
_TruncateAtMax(kwoptions[key], max_len=MAX_LINE_LEN, spacer=space + PAD)))
user_choice = input("")
if user_choice in kwoptions:
return user_choice
elif user_choice in _EXIT_WORDS:
quit()
print("That wasn't one of the options.",)
except TypeError:
print("\n\n")
raise
except SystemExit:
print("Thanks!")
raise SystemExit #raise the SystemExit exception again to exit the program
def _TruncateAtMax(str, max_len=80, spacer=1):
"""
Truncate a string at max length and continue on the next line. For example:
>>>string = "this is a test of the truncate func"
>>>max_len = 15
>>>_TruncateAtMax(string, max_len)
> this is a test
> of the truncate
> func
"""
if len(str) <= max_len - spacer:
return str
display_str = []
next_line = ""
spacing = "\n" + (" " * spacer)
terms = str.split()
for term in terms:
if len(next_line + term) < max_len:
next_line += term + " "
else:
display_str.append(next_line)
next_line = term + " "
else:
#adds any stragglers (if next_line != "" but also !< max at the end of terms)
display_str.append(next_line)
truncated_str = spacing.join(display_str)
return truncated_str[1:] if truncated_str[0] == "\n" else truncated_str[:]
</code></pre>
| [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T13:29:47.617",
"Id": "413220",
"Score": "1",
"body": "Backslash is redundant inside parentheses. According to [PEP-8](https://pep8.org/#maximum-line-length) it backslashes should be avoided when possible. Also, passing empty string to `input()` is redundant."
}
] | [
{
"body": "<p>The code looks clean and is fairly readable. Good job!</p>\n\n<p>Now here are some things you might want to consider:</p>\n\n<ol>\n<li><p>You use <code>_EXIT_WORDS</code> only to check membership. Instead of a list, use a set:</p>\n\n<pre><code>_EXIT_WORDS = { 'leave', 'stop', 'quit' }\n</code></pre>\n\n<p>Set membership is <em>O(1)</em> whereas list membership is <em>O(n),</em> so it's just a good habit to be in.</p></li>\n<li><p>You spent some time writing the function <code>_TruncateAtMax</code> but python ships with the <a href=\"https://docs.python.org/3.5/library/textwrap.html\" rel=\"nofollow noreferrer\"><code>textwrap</code></a> module that does pretty much what you want. The best code is code you don't have to write yourself...</p></li>\n<li><p>Instead of a long explanatory comment after this line:</p>\n\n<pre><code>PAD = len(OPTION_TEMPLATE) - 6 \n</code></pre>\n\n<p>why not just make it explicit:</p>\n\n<pre><code>PAD = len(OPTION_TEMPLATE) - len('{0}{1}')\n</code></pre>\n\n<p>or use @belkka's excellent suggestion:</p>\n\n<pre><code>PAD = len(OPTION_TEMPLATE.format('', ''))\n</code></pre>\n\n<p>And instead of calling it PAD, which <em>is</em> nicely short, see if you can name it something a bit more clear.</p></li>\n<li><p>Instead of calling <code>key.ljust(space)</code> for each key, try just using the <code>space</code> as a parameter to the format string. You can do something like: <code>'{0:{1}}'.format(str, width)</code></p></li>\n<li><p>Instead of re-computing the strings each time, why not compute the strings outside the loop and print them inside as needed?</p></li>\n<li><p>Instead of raising <code>SystemExit</code> why not just <code>raise</code> again? You do it for <code>TypeError</code>...</p></li>\n</ol>\n",
"comments": [
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T13:23:30.770",
"Id": "413217",
"Score": "2",
"body": "Another way to calculate PAD: `len(OPTION_TEMPLATE.format('', ''))`"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-19T00:06:29.940",
"Id": "413487",
"Score": "0",
"body": "@AustinHastings, first off, thanks for the feedback! Your suggestions make a lot of sense. For #4, what's the benefit of using `.format()` over `.ljust`? Could you explain #5 a little more? What strings should I be computing outside the loop?"
},
{
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-19T04:14:01.613",
"Id": "413491",
"Score": "1",
"body": "@DukeSilver the advantage of `format` is that you're already using it. So instead of calling format, but first calling ljust to pad one of the parameters, you can say, \"format, do this stuff, and make sure the field for this one string is this-many characters wide\" as part of a single operation. The strings to compute outside the loop are the strings you are computing with `format` and `ljust` and everything. Your loop is infinite, but you're just printing the same data over and over again. So compute the data only once."
}
],
"meta_data": {
"CommentCount": "3",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-17T00:04:13.363",
"Id": "213632",
"ParentId": "213627",
"Score": "4"
}
}
] | {
"AcceptedAnswerId": "213632",
"CommentCount": "1",
"ContentLicense": "CC BY-SA 4.0",
"CreationDate": "2019-02-16T23:36:44.713",
"Id": "213627",
"Score": "6",
"Tags": [
"python",
"beginner",
"python-3.x"
],
"Title": "Forcing the user to choose from a set of options (in Python)"
} | 213627 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.